tempest.games 0.2.45 → 0.2.47

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,74 +1,74 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var vH=Object.create;var{getPrototypeOf:xH,defineProperty:FY,getOwnPropertyNames:fH}=Object;var hH=Object.prototype.hasOwnProperty;var dE=(Y,Z,X)=>{X=Y!=null?vH(xH(Y)):{};let _=Z||!Y||!Y.__esModule?FY(X,"default",{value:Y,enumerable:!0}):X;for(let G of fH(Y))if(!hH.call(_,G))FY(_,G,{get:()=>Y[G],enumerable:!0});return _};var cE=(Y,Z)=>()=>(Z||Y((Z={exports:{}}).exports,Z),Z.exports);var kH=(Y,Z)=>{for(var X in Z)FY(Y,X,{get:Z[X],enumerable:!0,configurable:!0,set:(_)=>Z[X]=()=>_})};var lE=(Y,Z)=>()=>(Y&&(Z=Y(Y=0)),Z);var oE=import.meta.require;import yE,{join as gE,normalize as pE,resolve as g3}from"path";var E2=(Y)=>Array.isArray(Y)?Y:[Y],OX=(Y,Z)=>{let X=[[],[]];for(let _ of Y)if(Z(_))X[0].push(_);else X[1].push(_);return X},p8=Array,n1=(Y,Z)=>Y.includes(Z),VX=(Y,Z=0)=>[...new Array(Y)].map((X,_)=>_+Z),Z0=(Y,Z,X)=>{if(Y===void 0)return Z===void 0?[]:Array.isArray(Z)?Z:[Z];if(X?.prepend)if(Array.isArray(Z))Y.unshift(...Z);else Y.unshift(Z);else if(Array.isArray(Z))Y.push(...Z);else Y.push(Z);return Y},s1=(Y,Z)=>{if(Z===void 0||Z===null)return Y??[];if(Y===void 0||Y===null)return E2(Z);return Y.concat(Z)},DX=(...Y)=>Y.reduce(s1,[]),d1=(Y,Z,X)=>{if(Y===void 0)return Array.isArray(Z)?Z:[Z];let _=X?.isEqual??((G,$)=>G===$);for(let G of E2(Z))if(!Y.some(($)=>_($,G)))Y.push(G);return Y},LX=(Y,Z)=>Y.reduce((X,_)=>{let G=_[Z];return X[G]=Z0(X[G],_),X},{}),t1=(Y,Z,X)=>Y.length===Z.length&&Y.every(X?.isEqual?(_,G)=>X.isEqual(_,Z[G]):(_,G)=>_===Z[G]);var J1=(Y,Z)=>y0(Y)===Z,y0=(Y)=>{let Z=typeof Y;return Z==="object"?Y===null?"null":"object":Z==="function"?"object":Z},Q1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},MX={...Q1,function:"a function"};class AX extends Error{}var _0=(Y)=>j2(Y,AX),j2=(Y,Z=Error)=>{throw new Z(Y)};class j4 extends Error{name="ParseError"}var R=(Y)=>j2(Y,j4),v1=(Y)=>` ${Y}`;var o=(Y,Z)=>{let X={},_=Array.isArray(Y),G=!1;for(let[$,W]of Object.entries(Y).entries()){let H=_?Z($,W[1]):Z(...W,$);G||=typeof H[0]==="number";let Q=Array.isArray(H[0])||H.length===0?H:[H];for(let[J,U]of Q)if(typeof J==="object")X[J.group]=Z0(X[J.group],U);else X[J]=U}return G?Object.values(X):X};var EY=Object.entries;var g0=(Y,Z)=>(Y in Z),n2=(Y,Z)=>(Z in Y);class OY{constructor(Y){Object.assign(this,Y)}}var wX=class{};class S4 extends wX{}var bH=(Y,Z)=>{let X={},_={},G;for(G in Y)if(G in Z)X[G]=Y[G];else _[G]=Y[G];return[X,_]};var RX=(Y,Z)=>bH(Y,Z)[1],c1=(Y)=>Object.keys(Y).length===0,S2=(Y)=>[...Object.entries(Y),...Object.getOwnPropertySymbols(Y).map((Z)=>[Z,Y[Z]])],NX=(Y,Z)=>Object.defineProperties(Y,Object.getOwnPropertyDescriptors(Z)),IX=(Y)=>{let Z=Object.keys(Y).sort(),X={};for(let _=0;_<Z.length;_++)X[Z[_]]=Y[Z[_]];return X};var L1=v1("represents an uninitialized value"),TX=(Y)=>Object.values(Y).filter((Z)=>{if(typeof Z==="number")return!0;return typeof Y[Z]!=="number"});var VY={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},DY=globalThis.File??Blob,LY={ArrayBuffer,Blob,File:DY,FormData,Headers,Request,Response,URL},yH={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},P2={...VY,...LY,...yH,String,Number,Boolean},P4=(Y)=>{let Z=Object.getPrototypeOf(Y);while(Z?.constructor&&(!g0(Z.constructor.name,P2)||!(Y instanceof P2[Z.constructor.name])))Z=Object.getPrototypeOf(Z);let X=Z?.constructor?.name;if(X===void 0||X==="Object")return;return X},v4=(Y)=>typeof Y==="object"&&Y!==null?P4(Y)??"object":y0(Y);var F0=Array.isArray,gH={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"},pH={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"},mH={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"},KX={...gH,...pH,...mH},x4=(Y)=>{let Z=Object(Y).name??null;return Z&&g0(Z,P2)&&P2[Z]===Y?Z:null};var MY=(Y,Z)=>{let X=Y.prototype;while(X!==null){if(X===Z.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var BX=(Y)=>CX(Y,new Map),CX=(Y,Z)=>{if(typeof Y!=="object"||Y===null)return Y;if(Z?.has(Y))return Z.get(Y);let X=x4(Y.constructor);if(X==="Date")return new Date(Y.getTime());if(X&&X!=="Array")return Y;let _=Array.isArray(Y)?Y.slice():Object.create(Object.getPrototypeOf(Y)),G=Object.getOwnPropertyDescriptors(Y);if(Z){Z.set(Y,_);for(let $ in G){let W=G[$];if("get"in W||"set"in W)continue;W.value=CX(W.value,Z)}}return Object.defineProperties(_,G),_};var uH=(Y)=>{let Z=L1;return()=>Z===L1?Z=Y():Z},O2=(Y)=>typeof Y==="function"&&Y.length===0;var qX=class extends Function{constructor(...Y){let Z=Y.slice(0,-1),X=Y.at(-1);try{super(...Z,X)}catch(_){return _0(`Encountered an unexpected error while compiling your definition:
3
+ var xH=Object.create;var{getPrototypeOf:fH,defineProperty:EY,getOwnPropertyNames:hH}=Object;var kH=Object.prototype.hasOwnProperty;var cE=(Y,Z,X)=>{X=Y!=null?xH(fH(Y)):{};let _=Z||!Y||!Y.__esModule?EY(X,"default",{value:Y,enumerable:!0}):X;for(let G of hH(Y))if(!kH.call(_,G))EY(_,G,{get:()=>Y[G],enumerable:!0});return _};var lE=(Y,Z)=>()=>(Z||Y((Z={exports:{}}).exports,Z),Z.exports);var bH=(Y,Z)=>{for(var X in Z)EY(Y,X,{get:Z[X],enumerable:!0,configurable:!0,set:(_)=>Z[X]=()=>_})};var oE=(Y,Z)=>()=>(Y&&(Z=Y(Y=0)),Z);var iE=import.meta.require;import gE,{join as pE,normalize as mE,resolve as p3}from"path";var E2=(Y)=>Array.isArray(Y)?Y:[Y],OX=(Y,Z)=>{let X=[[],[]];for(let _ of Y)if(Z(_))X[0].push(_);else X[1].push(_);return X},g8=Array,n1=(Y,Z)=>Y.includes(Z),DX=(Y,Z=0)=>[...new Array(Y)].map((X,_)=>_+Z),Z0=(Y,Z,X)=>{if(Y===void 0)return Z===void 0?[]:Array.isArray(Z)?Z:[Z];if(X?.prepend)if(Array.isArray(Z))Y.unshift(...Z);else Y.unshift(Z);else if(Array.isArray(Z))Y.push(...Z);else Y.push(Z);return Y},s1=(Y,Z)=>{if(Z===void 0||Z===null)return Y??[];if(Y===void 0||Y===null)return E2(Z);return Y.concat(Z)},LX=(...Y)=>Y.reduce(s1,[]),d1=(Y,Z,X)=>{if(Y===void 0)return Array.isArray(Z)?Z:[Z];let _=X?.isEqual??((G,$)=>G===$);for(let G of E2(Z))if(!Y.some(($)=>_($,G)))Y.push(G);return Y},MX=(Y,Z)=>Y.reduce((X,_)=>{let G=_[Z];return X[G]=Z0(X[G],_),X},{}),t1=(Y,Z,X)=>Y.length===Z.length&&Y.every(X?.isEqual?(_,G)=>X.isEqual(_,Z[G]):(_,G)=>_===Z[G]);var H1=(Y,Z)=>y0(Y)===Z,y0=(Y)=>{let Z=typeof Y;return Z==="object"?Y===null?"null":"object":Z==="function"?"object":Z},J1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},AX={...J1,function:"a function"};class wX extends Error{}var _0=(Y)=>q2(Y,wX),q2=(Y,Z=Error)=>{throw new Z(Y)};class C4 extends Error{name="ParseError"}var A=(Y)=>q2(Y,C4),v1=(Y)=>` ${Y}`;var i=(Y,Z)=>{let X={},_=Array.isArray(Y),G=!1;for(let[$,W]of Object.entries(Y).entries()){let H=_?Z($,W[1]):Z(...W,$);G||=typeof H[0]==="number";let Q=Array.isArray(H[0])||H.length===0?H:[H];for(let[J,z]of Q)if(typeof J==="object")X[J.group]=Z0(X[J.group],z);else X[J]=z}return G?Object.values(X):X};var VY=Object.entries;var g0=(Y,Z)=>(Y in Z),r2=(Y,Z)=>(Z in Y);class OY{constructor(Y){Object.assign(this,Y)}}var RX=class{};class q4 extends RX{}var yH=(Y,Z)=>{let X={},_={},G;for(G in Y)if(G in Z)X[G]=Y[G];else _[G]=Y[G];return[X,_]};var NX=(Y,Z)=>yH(Y,Z)[1],c1=(Y)=>Object.keys(Y).length===0,j2=(Y)=>[...Object.entries(Y),...Object.getOwnPropertySymbols(Y).map((Z)=>[Z,Y[Z]])],IX=(Y,Z)=>Object.defineProperties(Y,Object.getOwnPropertyDescriptors(Z)),KX=(Y)=>{let Z=Object.keys(Y).sort(),X={};for(let _=0;_<Z.length;_++)X[Z[_]]=Y[Z[_]];return X};var L1=v1("represents an uninitialized value"),TX=(Y)=>Object.values(Y).filter((Z)=>{if(typeof Z==="number")return!0;return typeof Y[Z]!=="number"});var DY={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},LY=globalThis.File??Blob,MY={ArrayBuffer,Blob,File:LY,FormData,Headers,Request,Response,URL},gH={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},S2={...DY,...MY,...gH,String,Number,Boolean},j4=(Y)=>{let Z=Object.getPrototypeOf(Y);while(Z?.constructor&&(!g0(Z.constructor.name,S2)||!(Y instanceof S2[Z.constructor.name])))Z=Object.getPrototypeOf(Z);let X=Z?.constructor?.name;if(X===void 0||X==="Object")return;return X},S4=(Y)=>typeof Y==="object"&&Y!==null?j4(Y)??"object":y0(Y);var F0=Array.isArray,pH={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"},mH={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"},uH={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"},BX={...pH,...mH,...uH},P4=(Y)=>{let Z=Object(Y).name??null;return Z&&g0(Z,S2)&&S2[Z]===Y?Z:null};var AY=(Y,Z)=>{let X=Y.prototype;while(X!==null){if(X===Z.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var CX=(Y)=>qX(Y,new Map),qX=(Y,Z)=>{if(typeof Y!=="object"||Y===null)return Y;if(Z?.has(Y))return Z.get(Y);let X=P4(Y.constructor);if(X==="Date")return new Date(Y.getTime());if(X&&X!=="Array")return Y;let _=Array.isArray(Y)?Y.slice():Object.create(Object.getPrototypeOf(Y)),G=Object.getOwnPropertyDescriptors(Y);if(Z){Z.set(Y,_);for(let $ in G){let W=G[$];if("get"in W||"set"in W)continue;W.value=qX(W.value,Z)}}return Object.defineProperties(_,G),_};var dH=(Y)=>{let Z=L1;return()=>Z===L1?Z=Y():Z},V2=(Y)=>typeof Y==="function"&&Y.length===0;var jX=class extends Function{constructor(...Y){let Z=Y.slice(0,-1),X=Y.at(-1);try{super(...Z,X)}catch(_){return _0(`Encountered an unexpected error while compiling your definition:
4
4
  Message: ${_}
5
5
  Source: (${Y.slice(0,-1)}) => {
6
6
  ${Y.at(-1)}
7
- }`)}}};class x1{constructor(Y,...[Z]){return Object.assign(Object.setPrototypeOf(Y.bind(Z?.bind??this),this.constructor.prototype),Z?.attach)}}var jX=uH(()=>{try{return new Function("return false")()}catch{return!0}});var EO=v1("brand");var SX=v1("arkInferred");var DO=v1("args");class s0{constructor(){}}var dH=()=>{try{return((new Error().stack?.split(`
8
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},cH=globalThis.process?.env??{},PX={fileName:dH,env:cH};var vX=(Y)=>Y[0].toUpperCase()+Y.slice(1);var AY=(Y)=>new RegExp(lH(Y),typeof Y==="string"?"":Y.flags);var lH=(Y)=>{return`^(?:${typeof Y==="string"?Y:Y.source})$`};var a1={negativeLookahead:(Y)=>`(?!${Y})`,nonCapturingGroup:(Y)=>`(?:${Y})`},f4="\\",V2={" ":1,"\n":1,"\t":1};var oH=/^-0\.?0*$/.source,fX=/[1-9]\d*/.source,iH=/\.\d+/.source,rH=/\.\d*[1-9]/.source,hX=(Y)=>AY(a1.negativeLookahead(oH)+a1.nonCapturingGroup("-?"+a1.nonCapturingGroup(a1.nonCapturingGroup("0|"+fX)+a1.nonCapturingGroup(Y.decimalPattern)+"?")+(Y.allowDecimalOnly?"|"+Y.decimalPattern:"")+"?")),xX=hX({decimalPattern:rH,allowDecimalOnly:!1}),nH=xX.test.bind(xX),m8=hX({decimalPattern:iH,allowDecimalOnly:!0}),IO=m8.test.bind(m8),sH=/^-?\d*\.?\d*$/,tH=(Y)=>Y.length!==0&&sH.test(Y),h4=AY(a1.negativeLookahead("^-0$")+"-?"+a1.nonCapturingGroup(a1.nonCapturingGroup("0|"+fX))),aH=h4.test.bind(h4),wY=/^-?\d+$/,eH=wY.test.bind(wY),kX={number:"a number",bigint:"a bigint",integer:"an integer"},bX=(Y,Z)=>`'${Y}' was parsed as ${kX[Z]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,YJ=(Y,Z)=>Z==="number"?nH(Y):aH(Y),ZJ=(Y,Z)=>Z==="number"?Number(Y):Number.parseInt(Y),XJ=(Y,Z)=>Z==="number"?tH(Y):eH(Y),yX=(Y,Z)=>RY(Y,"number",Z),gX=(Y,Z)=>RY(Y,"number",{...Z,strict:!0}),pX=(Y,Z)=>RY(Y,"integer",Z),RY=(Y,Z,X)=>{let _=ZJ(Y,Z);if(!Number.isNaN(_)){if(XJ(Y,Z)){if(X?.strict)return YJ(Y,Z)?_:R(bX(Y,Z));return _}}return X?.errorOnFail?R(X?.errorOnFail===!0?`Failed to parse ${kX[Z]} from '${Y}'`:X?.errorOnFail):void 0},mX=(Y)=>{if(Y[Y.length-1]!=="n")return;let Z=Y.slice(0,-1),X;try{X=BigInt(Z)}catch{return}if(h4.test(Z))return X;if(wY.test(Z))return R(bX(Y,"bigint"))};var _J="0.46.0",GJ={version:_J,filename:PX.fileName(),FileConstructor:DY},v2=GJ,uX=new Map,NY=Object.create(null),k4=(Y)=>{let Z=uX.get(Y);if(Z)return Z;let X=$J(Y);if(NY[X])X=`${X}${NY[X]++}`;else NY[X]=1;return v2[X]=Y,uX.set(Y,X),X},D2=(Y)=>/^[$A-Z_a-z][\w$]*$/.test(Y),$J=(Y)=>{switch(typeof Y){case"object":{if(Y===null)break;let Z=P4(Y)??"object";return Z[0].toLowerCase()+Z.slice(1)}case"function":return D2(Y.name)?Y.name:"fn";case"symbol":return Y.description&&D2(Y.description)?Y.description:"symbol"}return _0(`Unexpected attempt to register serializable value of type ${y0(Y)}`)};var b4=(Y)=>typeof Y==="string"?JSON.stringify(Y):typeof Y==="bigint"?`${Y}n`:`${Y}`;var dX=(Y,Z={})=>y4(Y,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...Z},[]);var i=(Y,Z)=>{switch(y0(Y)){case"object":let X=Y,_=X.constructor.name;return _==="Object"||_==="Array"?Z?.quoteKeys===!1?u8(X,Z?.indent??0,""):JSON.stringify(y4(X,s2,[]),null,Z?.indent):u8(X,Z?.indent??0,"");case"symbol":return s2.onSymbol(Y);default:return b4(Y)}},u8=(Y,Z,X)=>{if(typeof Y==="function")return s2.onFunction(Y);if(typeof Y!=="object"||Y===null)return b4(Y);let _=X+" ".repeat(Z);if(Array.isArray(Y)){if(Y.length===0)return"[]";let $=Y.map((W)=>u8(W,Z,_)).join(`,
7
+ }`)}}};class x1{constructor(Y,...[Z]){return Object.assign(Object.setPrototypeOf(Y.bind(Z?.bind??this),this.constructor.prototype),Z?.attach)}}var SX=dH(()=>{try{return new Function("return false")()}catch{return!0}});var VV=v1("brand");var PX=v1("arkInferred");var LV=v1("args");class n0{constructor(){}}var cH=()=>{try{return((new Error().stack?.split(`
8
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},lH=globalThis.process?.env??{},vX={fileName:cH,env:lH};var xX=(Y)=>Y[0].toUpperCase()+Y.slice(1);var wY=(Y)=>new RegExp(oH(Y),typeof Y==="string"?"":Y.flags);var oH=(Y)=>{return`^(?:${typeof Y==="string"?Y:Y.source})$`};var a1={negativeLookahead:(Y)=>`(?!${Y})`,nonCapturingGroup:(Y)=>`(?:${Y})`},v4="\\",O2={" ":1,"\n":1,"\t":1};var iH=/^-0\.?0*$/.source,hX=/[1-9]\d*/.source,rH=/\.\d+/.source,nH=/\.\d*[1-9]/.source,kX=(Y)=>wY(a1.negativeLookahead(iH)+a1.nonCapturingGroup("-?"+a1.nonCapturingGroup(a1.nonCapturingGroup("0|"+hX)+a1.nonCapturingGroup(Y.decimalPattern)+"?")+(Y.allowDecimalOnly?"|"+Y.decimalPattern:"")+"?")),fX=kX({decimalPattern:nH,allowDecimalOnly:!1}),sH=fX.test.bind(fX),p8=kX({decimalPattern:rH,allowDecimalOnly:!0}),KV=p8.test.bind(p8),tH=/^-?\d*\.?\d*$/,aH=(Y)=>Y.length!==0&&tH.test(Y),x4=wY(a1.negativeLookahead("^-0$")+"-?"+a1.nonCapturingGroup(a1.nonCapturingGroup("0|"+hX))),eH=x4.test.bind(x4),RY=/^-?\d+$/,YJ=RY.test.bind(RY),bX={number:"a number",bigint:"a bigint",integer:"an integer"},yX=(Y,Z)=>`'${Y}' was parsed as ${bX[Z]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,ZJ=(Y,Z)=>Z==="number"?sH(Y):eH(Y),XJ=(Y,Z)=>Z==="number"?Number(Y):Number.parseInt(Y),_J=(Y,Z)=>Z==="number"?aH(Y):YJ(Y),gX=(Y,Z)=>NY(Y,"number",Z),pX=(Y,Z)=>NY(Y,"number",{...Z,strict:!0}),mX=(Y,Z)=>NY(Y,"integer",Z),NY=(Y,Z,X)=>{let _=XJ(Y,Z);if(!Number.isNaN(_)){if(_J(Y,Z)){if(X?.strict)return ZJ(Y,Z)?_:A(yX(Y,Z));return _}}return X?.errorOnFail?A(X?.errorOnFail===!0?`Failed to parse ${bX[Z]} from '${Y}'`:X?.errorOnFail):void 0},uX=(Y)=>{if(Y[Y.length-1]!=="n")return;let Z=Y.slice(0,-1),X;try{X=BigInt(Z)}catch{return}if(x4.test(Z))return X;if(RY.test(Z))return A(yX(Y,"bigint"))};var GJ="0.46.0",$J={version:GJ,filename:vX.fileName(),FileConstructor:LY},P2=$J,dX=new Map,IY=Object.create(null),f4=(Y)=>{let Z=dX.get(Y);if(Z)return Z;let X=WJ(Y);if(IY[X])X=`${X}${IY[X]++}`;else IY[X]=1;return P2[X]=Y,dX.set(Y,X),X},D2=(Y)=>/^[$A-Z_a-z][\w$]*$/.test(Y),WJ=(Y)=>{switch(typeof Y){case"object":{if(Y===null)break;let Z=j4(Y)??"object";return Z[0].toLowerCase()+Z.slice(1)}case"function":return D2(Y.name)?Y.name:"fn";case"symbol":return Y.description&&D2(Y.description)?Y.description:"symbol"}return _0(`Unexpected attempt to register serializable value of type ${y0(Y)}`)};var h4=(Y)=>typeof Y==="string"?JSON.stringify(Y):typeof Y==="bigint"?`${Y}n`:`${Y}`;var cX=(Y,Z={})=>k4(Y,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...Z},[]);var r=(Y,Z)=>{switch(y0(Y)){case"object":let X=Y,_=X.constructor.name;return _==="Object"||_==="Array"?Z?.quoteKeys===!1?m8(X,Z?.indent??0,""):JSON.stringify(k4(X,n2,[]),null,Z?.indent):m8(X,Z?.indent??0,"");case"symbol":return n2.onSymbol(Y);default:return h4(Y)}},m8=(Y,Z,X)=>{if(typeof Y==="function")return n2.onFunction(Y);if(typeof Y!=="object"||Y===null)return h4(Y);let _=X+" ".repeat(Z);if(Array.isArray(Y)){if(Y.length===0)return"[]";let $=Y.map((W)=>m8(W,Z,_)).join(`,
9
9
  `+_);return Z?`[
10
10
  ${_}${$}
11
- ${X}]`:`[${$}]`}let G=Y.constructor.name;if(G==="Object"){let $=S2(Y).map(([W,H])=>{let Q=typeof W==="symbol"?s2.onSymbol(W):D2(W)?W:JSON.stringify(W),J=u8(H,Z,_);return`${_}${Q}: ${J}`});if($.length===0)return"{}";return Z?`{
11
+ ${X}]`:`[${$}]`}let G=Y.constructor.name;if(G==="Object"){let $=j2(Y).map(([W,H])=>{let Q=typeof W==="symbol"?n2.onSymbol(W):D2(W)?W:JSON.stringify(W),J=m8(H,Z,_);return`${_}${Q}: ${J}`});if($.length===0)return"{}";return Z?`{
12
12
  ${$.join(`,
13
13
  `)}
14
- ${X}}`:`{${$.join(", ")}}`}if(Y instanceof Date)return x2(Y);if("expression"in Y&&typeof Y.expression==="string")return Y.expression;return G},s2={onCycle:()=>"(cycle)",onSymbol:(Y)=>`Symbol(${k4(Y)})`,onFunction:(Y)=>`Function(${k4(Y)})`},y4=(Y,Z,X)=>{switch(y0(Y)){case"object":{let _=Y;if("toJSON"in _&&typeof _.toJSON==="function")return _.toJSON();if(typeof _==="function")return s2.onFunction(_);if(X.includes(_))return"(cycle)";let G=[...X,_];if(Array.isArray(_))return _.map((W)=>y4(W,Z,G));if(_ instanceof Date)return _.toDateString();let $={};for(let W in _)$[W]=y4(_[W],Z,G);for(let W of Object.getOwnPropertySymbols(_))$[Z.onSymbol?.(W)??W.toString()]=y4(_[W],Z,G);return $}case"symbol":return s2.onSymbol(Y);case"bigint":return Z.onBigInt?.(Y)??`${Y}n`;case"undefined":return Z.onUndefined??"undefined";case"string":return Y.replaceAll("\\","\\\\");default:return Y}},x2=(Y)=>{let Z=Y.getFullYear(),X=Y.getMonth(),_=Y.getDate(),G=Y.getHours(),$=Y.getMinutes(),W=Y.getSeconds(),H=Y.getMilliseconds();if(X===0&&_===1&&G===0&&$===0&&W===0&&H===0)return`${Z}`;let Q=`${WJ[X]} ${_}, ${Z}`;if(G===0&&$===0&&W===0&&H===0)return Q;let J=Y.toLocaleTimeString(),U=J.endsWith(" AM")||J.endsWith(" PM")?J.slice(-3):"";if(U)J=J.slice(0,-U.length);if(H)J+=`.${JJ(H,3)}`;else if(HJ.test(J))J=J.slice(0,-3);return`${J+U}, ${Q}`},WJ=["January","February","March","April","May","June","July","August","September","October","November","December"],HJ=/:\d\d:00$/,JJ=(Y,Z)=>String(Y).padStart(Z,"0");var cX=(Y,Z,...[X])=>{let _=X?.stringifySymbol??i,G=Y;switch(typeof Z){case"string":G=D2(Z)?Y===""?Z:`${Y}.${Z}`:`${Y}[${JSON.stringify(Z)}]`;break;case"number":G=`${Y}[${Z}]`;break;case"symbol":G=`${Y}[${_(Z)}]`;break;default:if(X?.stringifyNonKey)G=`${Y}[${X.stringifyNonKey(Z)}]`;else R(`${i(Z)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return G},e1=(Y,...Z)=>Y.reduce((X,_)=>cX(X,_,...Z),"");class g4 extends p8{cache={};constructor(...Y){super();this.push(...Y)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let Y=0;Y<this.length;Y++)this.cache.json.push(typeof this[Y]==="symbol"?i(this[Y]):this[Y]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=e1(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Y="",Z=[Y];for(let X of this)Y=cX(Y,X),Z.push(Y);return this.cache.stringifyAncestors=Z}}class IY{chars;i;def;constructor(Y){this.def=Y,this.chars=[...Y],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(Y){let Z="";while(this.lookahead){if(Y(this,Z))if(Z[Z.length-1]===f4)Z=Z.slice(0,-1);else break;Z+=this.shift()}return Z}shiftUntilLookahead(Y){return typeof Y==="string"?this.shiftUntil((Z)=>Z.lookahead===Y):this.shiftUntil((Z)=>(Z.lookahead in Y))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in V2))}jumpToIndex(Y){this.i=Y<0?this.length+Y:Y}jumpForward(Y){this.i+=Y}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(Y,Z){return this.chars.slice(Y,Z).join("")}lookaheadIs(Y){return this.lookahead===Y}lookaheadIsIn(Y){return this.lookahead in Y}}var rO=v1("implementedTraits");var TY="$ark",QJ=2;while(TY in globalThis)TY=`$ark${QJ++}`;var lX=TY;globalThis[lX]=v2;var N=v2,UJ=(Y)=>`${lX}.${Y}`,B0=(Y)=>UJ(k4(Y));class d8 extends S4{argNames;body="";constructor(...Y){super();this.argNames=Y;for(let Z of Y){if(Z in this)throw new Error(`Arg name '${Z}' would overwrite an existing property on FunctionBody`);this[Z]=Z}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(Y,Z=!1){return KY(Y,Z)}index(Y,Z=!1){return oX(`${Y}`,Z)}line(Y){return this.body+=`${" ".repeat(this.indentation)}${Y}
14
+ ${X}}`:`{${$.join(", ")}}`}if(Y instanceof Date)return v2(Y);if("expression"in Y&&typeof Y.expression==="string")return Y.expression;return G},n2={onCycle:()=>"(cycle)",onSymbol:(Y)=>`Symbol(${f4(Y)})`,onFunction:(Y)=>`Function(${f4(Y)})`},k4=(Y,Z,X)=>{switch(y0(Y)){case"object":{let _=Y;if("toJSON"in _&&typeof _.toJSON==="function")return _.toJSON();if(typeof _==="function")return n2.onFunction(_);if(X.includes(_))return"(cycle)";let G=[...X,_];if(Array.isArray(_))return _.map((W)=>k4(W,Z,G));if(_ instanceof Date)return _.toDateString();let $={};for(let W in _)$[W]=k4(_[W],Z,G);for(let W of Object.getOwnPropertySymbols(_))$[Z.onSymbol?.(W)??W.toString()]=k4(_[W],Z,G);return $}case"symbol":return n2.onSymbol(Y);case"bigint":return Z.onBigInt?.(Y)??`${Y}n`;case"undefined":return Z.onUndefined??"undefined";case"string":return Y.replaceAll("\\","\\\\");default:return Y}},v2=(Y)=>{let Z=Y.getFullYear(),X=Y.getMonth(),_=Y.getDate(),G=Y.getHours(),$=Y.getMinutes(),W=Y.getSeconds(),H=Y.getMilliseconds();if(X===0&&_===1&&G===0&&$===0&&W===0&&H===0)return`${Z}`;let Q=`${HJ[X]} ${_}, ${Z}`;if(G===0&&$===0&&W===0&&H===0)return Q;let J=Y.toLocaleTimeString(),z=J.endsWith(" AM")||J.endsWith(" PM")?J.slice(-3):"";if(z)J=J.slice(0,-z.length);if(H)J+=`.${QJ(H,3)}`;else if(JJ.test(J))J=J.slice(0,-3);return`${J+z}, ${Q}`},HJ=["January","February","March","April","May","June","July","August","September","October","November","December"],JJ=/:\d\d:00$/,QJ=(Y,Z)=>String(Y).padStart(Z,"0");var lX=(Y,Z,...[X])=>{let _=X?.stringifySymbol??r,G=Y;switch(typeof Z){case"string":G=D2(Z)?Y===""?Z:`${Y}.${Z}`:`${Y}[${JSON.stringify(Z)}]`;break;case"number":G=`${Y}[${Z}]`;break;case"symbol":G=`${Y}[${_(Z)}]`;break;default:if(X?.stringifyNonKey)G=`${Y}[${X.stringifyNonKey(Z)}]`;else A(`${r(Z)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return G},e1=(Y,...Z)=>Y.reduce((X,_)=>lX(X,_,...Z),"");class b4 extends g8{cache={};constructor(...Y){super();this.push(...Y)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let Y=0;Y<this.length;Y++)this.cache.json.push(typeof this[Y]==="symbol"?r(this[Y]):this[Y]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=e1(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Y="",Z=[Y];for(let X of this)Y=lX(Y,X),Z.push(Y);return this.cache.stringifyAncestors=Z}}class KY{chars;i;def;constructor(Y){this.def=Y,this.chars=[...Y],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(Y){let Z="";while(this.lookahead){if(Y(this,Z))if(Z[Z.length-1]===v4)Z=Z.slice(0,-1);else break;Z+=this.shift()}return Z}shiftUntilLookahead(Y){return typeof Y==="string"?this.shiftUntil((Z)=>Z.lookahead===Y):this.shiftUntil((Z)=>(Z.lookahead in Y))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in O2))}jumpToIndex(Y){this.i=Y<0?this.length+Y:Y}jumpForward(Y){this.i+=Y}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(Y,Z){return this.chars.slice(Y,Z).join("")}lookaheadIs(Y){return this.lookahead===Y}lookaheadIsIn(Y){return this.lookahead in Y}}var nV=v1("implementedTraits");var TY="$ark",zJ=2;while(TY in globalThis)TY=`$ark${zJ++}`;var oX=TY;globalThis[oX]=P2;var I=P2,UJ=(Y)=>`${oX}.${Y}`,B0=(Y)=>UJ(f4(Y));class u8 extends q4{argNames;body="";constructor(...Y){super();this.argNames=Y;for(let Z of Y){if(Z in this)throw new Error(`Arg name '${Z}' would overwrite an existing property on FunctionBody`);this[Z]=Z}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(Y,Z=!1){return BY(Y,Z)}index(Y,Z=!1){return iX(`${Y}`,Z)}line(Y){return this.body+=`${" ".repeat(this.indentation)}${Y}
15
15
  `,this}const(Y,Z){return this.line(`const ${Y} = ${Z}`),this}let(Y,Z){return this.line(`let ${Y} = ${Z}`)}set(Y,Z){return this.line(`${Y} = ${Z}`)}if(Y,Z){return this.block(`if (${Y})`,Z)}elseIf(Y,Z){return this.block(`else if (${Y})`,Z)}else(Y){return this.block("else",Y)}for(Y,Z,X=0){return this.block(`for (let i = ${X}; ${Y}; i++)`,Z)}forIn(Y,Z){return this.block(`for (const k in ${Y})`,Z)}block(Y,Z,X=""){return this.line(`${Y} {`),this.indent(),Z(this),this.dedent(),this.line(`}${X}`)}return(Y=""){return this.line(`return ${Y}`)}write(Y="anonymous",Z=0){return`${Y}(${this.argNames.join(", ")}) { ${Z?this.body.split(`
16
16
  `).map((X)=>" ".repeat(Z)+`${X}`).join(`
17
- `):this.body} }`}compile(){return new qX(...this.argNames,this.body)}}var Y2=(Y)=>J1(Y,"object")||typeof Y==="symbol"?B0(Y):b4(Y),KY=(Y,Z=!1)=>{if(typeof Y==="string"&&D2(Y))return`${Z?"?":""}.${Y}`;return oX(zJ(Y),Z)},zJ=(Y)=>typeof Y==="symbol"?B0(Y):JSON.stringify(Y),oX=(Y,Z=!1)=>`${Z?"?.":""}[${Y}]`;class p4 extends d8{traversalKind;optimistic;constructor(Y){super("data","ctx");this.traversalKind=Y.kind,this.optimistic=Y.optimistic===!0}invoke(Y,Z){let X=Z?.arg??this.data,_=typeof Y==="string"?!0:this.requiresContextFor(Y),G=typeof Y==="string"?Y:Y.id;if(_)return`${this.referenceToId(G,Z)}(${X}, ${this.ctx})`;return`${this.referenceToId(G,Z)}(${X})`}referenceToId(Y,Z){let X=Z?.kind??this.traversalKind,_=`this.${Y}${X}`;return Z?.bind?`${_}.bind(${Z?.bind})`:_}requiresContextFor(Y){return this.traversalKind==="Apply"||Y.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(Y,Z,X){let _=this.requiresContextFor(X);if(_)this.line(`${this.ctx}.path.push(${Y})`);if(this.check(X,{arg:Z}),_)this.line(`${this.ctx}.path.pop()`);return this}check(Y,Z){return this.traversalKind==="Allows"?this.if(`!${this.invoke(Y,Z)}`,()=>this.return(!1)):this.line(this.invoke(Y,Z))}}var c8=(Y)=>o(Y,(Z,X)=>[Z,F0(X)?[...X]:X]),X1=v1("arkKind"),y=(Y,Z)=>Y?.[X1]===Z,D0=(Y)=>y(Y,"root")||y(Y,"constraint");var iX=["unit","proto","domain"],t2=["required","optional","index","sequence"],BY=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],l8=[...BY,...t2,"structure","predicate"],a2=["alias","union","morph","unit","intersection","proto","domain"],FJ=[...a2,...l8],o8=o(l8,(Y,Z)=>[Z,1]),rX=o([...t2,"undeclared"],(Y,Z)=>[Z,1]),nX=o(FJ,(Y,Z)=>[Z,Y]),e2=(Y)=>typeof Y==="string"&&(Y in nX);var Y4=(Y)=>nX[Y],i8=(Y)=>a2.slice(Y4(Y)+1),PV=[...i8("union"),"alias"],vV=[...i8("morph"),"alias"],I1=(Y)=>{if(typeof Y==="string"||typeof Y==="boolean"||Y===null)return Y;if(typeof Y==="number"){if(Number.isNaN(Y))return"NaN";if(Y===Number.POSITIVE_INFINITY)return"Infinity";if(Y===Number.NEGATIVE_INFINITY)return"-Infinity";return Y}return Y2(Y)},L2=(Y)=>{let Z="{ ";for(let[X,_]of Object.entries(Y))Z+=`${X}: ${Y2(_)}, `;return Z+" }"},r=(Y)=>{let Z=Y;if(Z.hasAssociatedError)Z.defaults.expected??=(X)=>("description"in X)?X.description:Z.defaults.description(X),Z.defaults.actual??=(X)=>i(X),Z.defaults.problem??=(X)=>`must be ${X.expected}${X.actual?` (was ${X.actual})`:""}`,Z.defaults.message??=(X)=>{if(X.path.length===0)return X.problem;let _=`${X.propString} ${X.problem}`;if(_[0]==="[")return`value at ${_}`;return _};return Z};class sX extends Error{name="ToJsonSchemaError";code;context;constructor(Y,Z){super(i(Z,{quoteKeys:!1,indent:4}));this.code=Y,this.context=Z}hasCode(Y){return this.code===Y}}var EJ={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Y)=>R0.throw("arrayObject",Y),arrayPostfix:(Y)=>R0.throw("arrayPostfix",Y),defaultValue:(Y)=>R0.throw("defaultValue",Y),domain:(Y)=>R0.throw("domain",Y),morph:(Y)=>R0.throw("morph",Y),patternIntersection:(Y)=>R0.throw("patternIntersection",Y),predicate:(Y)=>R0.throw("predicate",Y),proto:(Y)=>R0.throw("proto",Y),symbolKey:(Y)=>R0.throw("symbolKey",Y),unit:(Y)=>R0.throw("unit",Y),date:(Y)=>R0.throw("date",Y)}},R0={Error:sX,throw:(...Y)=>{throw new R0.Error(...Y)},throwInternalOperandError:(Y,Z)=>_0(`Unexpected JSON Schema input for ${Y}: ${i(Z)}`),defaultConfig:EJ};N.config??={};var m4=(Y,Z)=>{if(!Z)return Y;let X={...Y},_;for(_ in Z){let G={...Y.keywords};if(_==="keywords"){for(let $ in Z[_]){let W=Z.keywords[$];if(W===void 0)continue;G[$]=typeof W==="string"?{description:W}:W}X.keywords=G}else if(_==="toJsonSchema")X[_]=CY(Y.toJsonSchema,Z.toJsonSchema);else if(e2(_))X[_]={...Y[_],...Z[_]};else X[_]=Z[_]}return X},CY=(Y,Z)=>{if(!Y)return Z??{};if(!Z)return Y;let X={...Y},_;for(_ in Z)if(_==="fallback")X.fallback=OJ(Y.fallback,Z.fallback);else X[_]=Z[_];return X},OJ=(Y,Z)=>{Y=tX(Y),Z=tX(Z);let X={},_;for(_ in R0.defaultConfig.fallback)X[_]=Z[_]??Z.default??Y[_]??Y.default??R0.defaultConfig.fallback[_];return X},tX=(Y)=>typeof Y==="function"?{default:Y}:Y??{};class M2 extends S4{[X1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Y,relativePath:Z,...X},_){super();this.input=X,this.ctx=_,NX(this,X);let G=_.data;if(X.code==="union")X.errors=X.errors.flatMap((W)=>{let H=W.hasCode("union")?W.errors:[W];if(!Y&&!Z)return H;return H.map((Q)=>Q.transform((J)=>({...J,path:DX(Y,J.path,Z)})))});this.nodeConfig=_.config[this.code];let $=[...X.path??_.path];if(Z)$.push(...Z);if(Y)$.unshift(...Y);this.path=new g4(...$),this.data="data"in X?X.data:G}transform(Y){return new M2(Y({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(Y){return this.code===Y}get propString(){return e1(this.path)}get expected(){if(this.input.expected)return this.input.expected;let Y=this.meta?.expected??this.nodeConfig.expected;return typeof Y==="function"?Y(this.input):Y}get actual(){if(this.input.actual)return this.input.actual;let Y=this.meta?.actual??this.nodeConfig.actual;return typeof Y==="function"?Y(this.data):Y}get problem(){if(this.input.problem)return this.input.problem;let Y=this.meta?.problem??this.nodeConfig.problem;return typeof Y==="function"?Y(this):Y}get message(){if(this.input.message)return this.input.message;let Y=this.meta?.message??this.nodeConfig.message;return typeof Y==="function"?Y(this):Y}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class U1 extends p8{[X1]="errors";ctx;constructor(Y){super();this.ctx=Y}byPath=Object.create(null);get flatByPath(){return o(this.byPath,(Y,Z)=>[Y,Z.flat])}get flatProblemsByPath(){return o(this.byPath,(Y,Z)=>[Y,Z.flat.map((X)=>X.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new qY(this)}add(Y){if(this.includes(Y))return;this._add(Y)}transform(Y){let Z=new U1(this.ctx);for(let X of this)Z.add(Y(X));return Z}merge(Y){for(let Z of Y){if(this.includes(Z))continue;this._add(new M2({...Z,path:[...this.ctx.path,...Z.path]},this.ctx))}}affectsPath(Y){if(this.length===0)return!1;return Y.stringifyAncestors().some((Z)=>(Z in this.byPath))||Y.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((Y)=>Y.toJSON())]}toString(){return this.join(`
18
- `)}_add(Y){let Z=this.byPath[Y.propString];if(Z){if(Z.hasCode("union")&&Z.errors.length===0)return;let X=Y.hasCode("union")&&Y.errors.length===0?Y:new M2({code:"intersection",errors:Z.hasCode("intersection")?[...Z.errors,Y]:[Z,Y]},this.ctx),_=this.indexOf(Z);this.mutable[_===-1?this.length:_]=X,this.byPath[Y.propString]=X,this.addAncestorPaths(Y)}else this.byPath[Y.propString]=Y,this.addAncestorPaths(Y),this.mutable.push(Y);this.count++}addAncestorPaths(Y){for(let Z of Y.path.stringifyAncestors())this.byAncestorPath[Z]=Z0(this.byAncestorPath[Z],Y)}}class qY extends Error{name="TraversalError";constructor(Y){if(Y.length===1)super(Y.summary);else super(`
19
- `+Y.map((Z)=>` \u2022 ${VJ(Z)}`).join(`
20
- `));Object.defineProperty(this,"arkErrors",{value:Y,enumerable:!1})}}var VJ=(Y)=>Y.toString().split(`
17
+ `):this.body} }`}compile(){return new jX(...this.argNames,this.body)}}var Y2=(Y)=>H1(Y,"object")||typeof Y==="symbol"?B0(Y):h4(Y),BY=(Y,Z=!1)=>{if(typeof Y==="string"&&D2(Y))return`${Z?"?":""}.${Y}`;return iX(FJ(Y),Z)},FJ=(Y)=>typeof Y==="symbol"?B0(Y):JSON.stringify(Y),iX=(Y,Z=!1)=>`${Z?"?.":""}[${Y}]`;class y4 extends u8{traversalKind;optimistic;constructor(Y){super("data","ctx");this.traversalKind=Y.kind,this.optimistic=Y.optimistic===!0}invoke(Y,Z){let X=Z?.arg??this.data,_=typeof Y==="string"?!0:this.requiresContextFor(Y),G=typeof Y==="string"?Y:Y.id;if(_)return`${this.referenceToId(G,Z)}(${X}, ${this.ctx})`;return`${this.referenceToId(G,Z)}(${X})`}referenceToId(Y,Z){let X=Z?.kind??this.traversalKind,_=`this.${Y}${X}`;return Z?.bind?`${_}.bind(${Z?.bind})`:_}requiresContextFor(Y){return this.traversalKind==="Apply"||Y.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(Y,Z,X){let _=this.requiresContextFor(X);if(_)this.line(`${this.ctx}.path.push(${Y})`);if(this.check(X,{arg:Z}),_)this.line(`${this.ctx}.path.pop()`);return this}check(Y,Z){return this.traversalKind==="Allows"?this.if(`!${this.invoke(Y,Z)}`,()=>this.return(!1)):this.line(this.invoke(Y,Z))}}var d8=(Y)=>i(Y,(Z,X)=>[Z,F0(X)?[...X]:X]),Y1=v1("arkKind"),y=(Y,Z)=>Y?.[Y1]===Z,L0=(Y)=>y(Y,"root")||y(Y,"constraint");var rX=["unit","proto","domain"],s2=["required","optional","index","sequence"],CY=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],c8=[...CY,...s2,"structure","predicate"],t2=["alias","union","morph","unit","intersection","proto","domain"],EJ=[...t2,...c8],l8=i(c8,(Y,Z)=>[Z,1]),nX=i([...s2,"undeclared"],(Y,Z)=>[Z,1]),sX=i(EJ,(Y,Z)=>[Z,Y]),a2=(Y)=>typeof Y==="string"&&(Y in sX);var e2=(Y)=>sX[Y],o8=(Y)=>t2.slice(e2(Y)+1),vO=[...o8("union"),"alias"],xO=[...o8("morph"),"alias"],R1=(Y)=>{if(typeof Y==="string"||typeof Y==="boolean"||Y===null)return Y;if(typeof Y==="number"){if(Number.isNaN(Y))return"NaN";if(Y===Number.POSITIVE_INFINITY)return"Infinity";if(Y===Number.NEGATIVE_INFINITY)return"-Infinity";return Y}return Y2(Y)},L2=(Y)=>{let Z="{ ";for(let[X,_]of Object.entries(Y))Z+=`${X}: ${Y2(_)}, `;return Z+" }"},n=(Y)=>{let Z=Y;if(Z.hasAssociatedError)Z.defaults.expected??=(X)=>("description"in X)?X.description:Z.defaults.description(X),Z.defaults.actual??=(X)=>r(X),Z.defaults.problem??=(X)=>`must be ${X.expected}${X.actual?` (was ${X.actual})`:""}`,Z.defaults.message??=(X)=>{if(X.path.length===0)return X.problem;let _=`${X.propString} ${X.problem}`;if(_[0]==="[")return`value at ${_}`;return _};return Z};class tX extends Error{name="ToJsonSchemaError";code;context;constructor(Y,Z){super(r(Z,{quoteKeys:!1,indent:4}));this.code=Y,this.context=Z}hasCode(Y){return this.code===Y}}var VJ={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Y)=>N0.throw("arrayObject",Y),arrayPostfix:(Y)=>N0.throw("arrayPostfix",Y),defaultValue:(Y)=>N0.throw("defaultValue",Y),domain:(Y)=>N0.throw("domain",Y),morph:(Y)=>N0.throw("morph",Y),patternIntersection:(Y)=>N0.throw("patternIntersection",Y),predicate:(Y)=>N0.throw("predicate",Y),proto:(Y)=>N0.throw("proto",Y),symbolKey:(Y)=>N0.throw("symbolKey",Y),unit:(Y)=>N0.throw("unit",Y),date:(Y)=>N0.throw("date",Y)}},N0={Error:tX,throw:(...Y)=>{throw new N0.Error(...Y)},throwInternalOperandError:(Y,Z)=>_0(`Unexpected JSON Schema input for ${Y}: ${r(Z)}`),defaultConfig:VJ};I.config??={};var g4=(Y,Z)=>{if(!Z)return Y;let X={...Y},_;for(_ in Z){let G={...Y.keywords};if(_==="keywords"){for(let $ in Z[_]){let W=Z.keywords[$];if(W===void 0)continue;G[$]=typeof W==="string"?{description:W}:W}X.keywords=G}else if(_==="toJsonSchema")X[_]=qY(Y.toJsonSchema,Z.toJsonSchema);else if(a2(_))X[_]={...Y[_],...Z[_]};else X[_]=Z[_]}return X},qY=(Y,Z)=>{if(!Y)return Z??{};if(!Z)return Y;let X={...Y},_;for(_ in Z)if(_==="fallback")X.fallback=OJ(Y.fallback,Z.fallback);else X[_]=Z[_];return X},OJ=(Y,Z)=>{Y=aX(Y),Z=aX(Z);let X={},_;for(_ in N0.defaultConfig.fallback)X[_]=Z[_]??Z.default??Y[_]??Y.default??N0.defaultConfig.fallback[_];return X},aX=(Y)=>typeof Y==="function"?{default:Y}:Y??{};class M2 extends q4{[Y1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Y,relativePath:Z,...X},_){super();this.input=X,this.ctx=_,IX(this,X);let G=_.data;if(X.code==="union")X.errors=X.errors.flatMap((W)=>{let H=W.hasCode("union")?W.errors:[W];if(!Y&&!Z)return H;return H.map((Q)=>Q.transform((J)=>({...J,path:LX(Y,J.path,Z)})))});this.nodeConfig=_.config[this.code];let $=[...X.path??_.path];if(Z)$.push(...Z);if(Y)$.unshift(...Y);this.path=new b4(...$),this.data="data"in X?X.data:G}transform(Y){return new M2(Y({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(Y){return this.code===Y}get propString(){return e1(this.path)}get expected(){if(this.input.expected)return this.input.expected;let Y=this.meta?.expected??this.nodeConfig.expected;return typeof Y==="function"?Y(this.input):Y}get actual(){if(this.input.actual)return this.input.actual;let Y=this.meta?.actual??this.nodeConfig.actual;return typeof Y==="function"?Y(this.data):Y}get problem(){if(this.input.problem)return this.input.problem;let Y=this.meta?.problem??this.nodeConfig.problem;return typeof Y==="function"?Y(this):Y}get message(){if(this.input.message)return this.input.message;let Y=this.meta?.message??this.nodeConfig.message;return typeof Y==="function"?Y(this):Y}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 Q1 extends g8{[Y1]="errors";ctx;constructor(Y){super();this.ctx=Y}byPath=Object.create(null);get flatByPath(){return i(this.byPath,(Y,Z)=>[Y,Z.flat])}get flatProblemsByPath(){return i(this.byPath,(Y,Z)=>[Y,Z.flat.map((X)=>X.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new jY(this)}add(Y){if(this.includes(Y))return;this._add(Y)}transform(Y){let Z=new Q1(this.ctx);for(let X of this)Z.add(Y(X));return Z}merge(Y){for(let Z of Y){if(this.includes(Z))continue;this._add(new M2({...Z,path:[...this.ctx.path,...Z.path]},this.ctx))}}affectsPath(Y){if(this.length===0)return!1;return Y.stringifyAncestors().some((Z)=>(Z in this.byPath))||Y.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((Y)=>Y.toJSON())]}toString(){return this.join(`
18
+ `)}_add(Y){let Z=this.byPath[Y.propString];if(Z){if(Z.hasCode("union")&&Z.errors.length===0)return;let X=Y.hasCode("union")&&Y.errors.length===0?Y:new M2({code:"intersection",errors:Z.hasCode("intersection")?[...Z.errors,Y]:[Z,Y]},this.ctx),_=this.indexOf(Z);this.mutable[_===-1?this.length:_]=X,this.byPath[Y.propString]=X,this.addAncestorPaths(Y)}else this.byPath[Y.propString]=Y,this.addAncestorPaths(Y),this.mutable.push(Y);this.count++}addAncestorPaths(Y){for(let Z of Y.path.stringifyAncestors())this.byAncestorPath[Z]=Z0(this.byAncestorPath[Z],Y)}}class jY extends Error{name="TraversalError";constructor(Y){if(Y.length===1)super(Y.summary);else super(`
19
+ `+Y.map((Z)=>` \u2022 ${DJ(Z)}`).join(`
20
+ `));Object.defineProperty(this,"arkErrors",{value:Y,enumerable:!1})}}var DJ=(Y)=>Y.toString().split(`
21
21
  `).join(`
22
- `);class f1{path=[];errors=new U1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Y,Z){this.root=Y,this.config=Z}get data(){let Y=this.root;for(let Z of this.path)Y=Y?.[Z];return Y}get propString(){return e1(this.path)}reject(Y){return this.error(Y),!1}mustBe(Y){return this.error(Y),!1}error(Y){let Z=typeof Y==="object"?Y.code?Y:{...Y,code:"predicate"}:{code:"predicate",expected:Y};return this.errorFromContext(Z)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(Y){let Z={path:new g4(...this.path),morphs:Y};if(this.currentBranch)this.currentBranch.queuedMorphs.push(Z);else this.queuedMorphs.push(Z)}finalize(Y){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 Y?Y(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(Y){return this.errorFromContext(Y)}errorFromContext(Y){let Z=new M2(Y,this);if(this.currentBranch)this.currentBranch.error=Z;else this.errors.add(Z);return Z}applyQueuedMorphs(){while(this.queuedMorphs.length){let Y=this.queuedMorphs;this.queuedMorphs=[];for(let{path:Z,morphs:X}of Y){if(this.errors.affectsPath(Z))continue;this.applyMorphsAtPath(Z,X)}}}applyMorphsAtPath(Y,Z){let X=Y.at(-1),_;if(X!==void 0){_=this.root;for(let G=0;G<Y.length-1;G++)_=_[Y[G]]}this.path=[...Y];for(let G of Z){let $=D0(G),W=G(_===void 0?this.root:_[X],this);if(W instanceof M2){this.errors.add(W);break}if(W instanceof U1){if(!$)this.errors.merge(W);break}if(_===void 0)this.root=W;else _[X]=W;this.applyQueuedMorphs()}}}var z1=(Y,Z,X)=>{if(!X)return Z();X.path.push(Y);let _=Z();return X.path.pop(),_};class d4 extends x1{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Y,Z){super((_,G,$=this.onFail)=>{if(G)return this.traverseApply(_,G),G.hasError()?G.errors:G.data;return this.rootApply(_,$)},{attach:Y});this.attachments=Y,this.$=Z,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((_,G)=>AJ(_,G.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let _=0;_<this.children.length;_++){if(this.includesTransform||=this.children[_].includesTransform,this.includesContextualPredicate||=this.children[_].includesContextualPredicate,this.isCyclic||=this.children[_].isCyclic,!X){let G=this.children[_].flatRefs;for(let $=0;$<G.length;$++){let W=G[$];if(!this.flatRefs.some((H)=>eX(H,W))){this.flatRefs.push(W);for(let H of W.node.branches)if(H.hasKind("morph")||H.hasKind("intersection")&&H.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:W.path,propString:W.propString,node:H})}}}Object.assign(this.referencesById,this.children[_].referencesById)}this.flatRefs.sort((_,G)=>_.path.length>G.path.length?1:_.path.length<G.path.length?-1:_.propString>G.propString?1:_.propString<G.propString?-1:_.node.expression<G.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((_)=>_.length===1||_.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((_)=>_.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(_)=>this.traverseAllows(_,new f1(_,this.$.resolvedConfig)):(_)=>this.traverseAllows(_)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Z,X)=>{if(this.allows(Z))return Z;let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"contextual":return(Z,X)=>{let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Y=this.$.resolvedConfig.clone;return(Z,X)=>{if(this.allows(Z))return this.contextFreeMorph(Y&&(typeof Z==="object"&&Z!==null||typeof Z==="function")?Y(Z):Z);let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,_0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=MJ(this.metaJson);cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=Y4(this.kind);precompilation;assert=(Y,Z)=>this(Y,Z,(X)=>X.throw());traverse(Y,Z){return this(Y,Z,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(Y){if(!this.includesTransform)return this;let Z={};for(let[X,_]of this.innerEntries){let G=this.impl.keys[X];if(G.reduceIo)G.reduceIo(Y,Z,_);else if(G.child){let $=_;Z[X]=F0($)?$.map((W)=>W[Y]):$[Y]}else Z[X]=_}return this.$.node(this.kind,Z)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Y){let Z=D0(Y)?Y:this.$.parseDefinition(Y);return this.innerHash===Z.innerHash}ifEquals(Y){return this.equals(Y)?this:void 0}hasKind(Y){return this.kind===Y}assertHasKind(Y){if(this.kind!==Y)j2(`${this.kind} node was not of asserted kind ${Y}`);return this}hasKindIn(...Y){return Y.includes(this.kind)}assertHasKindIn(...Y){if(!n1(Y,this.kind))j2(`${this.kind} node was not one of asserted kinds ${Y}`);return this}isBasis(){return n1(iX,this.kind)}isConstraint(){return n1(l8,this.kind)}isStructural(){return n1(t2,this.kind)}isRefinement(){return n1(BY,this.kind)}isRoot(){return n1(a2,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Y){return this.hasKind("unit")&&this.allows(Y)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Y){let Z=u4.normalize(Y);return this._select(Z)}_select(Y){let Z=u4.applyBoundary[Y.boundary??"references"](this);if(Y.kind)Z=Z.filter((X)=>X.kind===Y.kind);if(Y.where)Z=Z.filter(Y.where);return u4.applyMethod[Y.method??"filter"](Z,this,Y)}transform(Y,Z){return this._transform(Y,this._createTransformContext(Z))}_createTransformContext(Y){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Y?.prereduced??!1},undeclaredKeyHandling:void 0,...Y}}_transform(Y,Z){let X=Z.bindScope??this.$;if(Z.seen[this.id])return this.$.lazilyResolve(Z.seen[this.id]);if(Z.shouldTransform?.(this,Z)===!1)return this;let _;if(Z.seen[this.id]=()=>_,this.hasKind("structure")&&this.undeclared!==Z.undeclaredKeyHandling)Z={...Z,undeclaredKeyHandling:this.undeclared};let G=o(this.inner,(J,U)=>{if(!this.impl.keys[J].child)return[J,U];let F=U;if(!F0(F)){let D=F._transform(Y,Z);return D?[J,D]:[]}if(F.length===0)return[J,U];let V=F.flatMap((D)=>{return D._transform(Y,Z)??[]});return V.length?[J,V]:[]});delete Z.seen[this.id];let $=Object.assign(G,{meta:this.meta}),W=Z.selected&&!Z.selected.includes(this)?$:Y(this.kind,$,Z);if(W===null)return null;if(D0(W))return _=W;let H=Object.keys(W);if((H.length===0||H.length===1&&H[0]==="meta")&&!c1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in W))return Z.undeclaredKeyHandling?{...W,value:N.intrinsic.unknown}:null;if(this.kind==="morph")W.in??=N.intrinsic.unknown;return _=X.node(this.kind,W,Z.parseOptions)}configureReferences(Y,Z="references"){let X=u4.normalize(Z),_=typeof Y==="string"?(H,Q)=>({...Q,meta:{...Q.meta,description:Y}}):typeof Y==="function"?(H,Q)=>({...Q,meta:Y(Q.meta)}):(H,Q)=>({...Q,meta:{...Q.meta,...Y}});if(X.boundary==="self")return this.$.node(this.kind,_(this.kind,{...this.inner,meta:this.meta}));let G=this._select(X),$=G&&E2(G),W=X.boundary==="child"?(H,Q)=>Q.root.children.includes(H):X.boundary==="shallow"?(H)=>H.kind!=="structure":()=>!0;return this.$.finalize(this.transform(_,{shouldTransform:W,selected:$}))}}var u4={applyBoundary:{self:(Y)=>[Y],child:(Y)=>[...Y.children],shallow:(Y)=>[...Y.shallowReferences],references:(Y)=>[...Y.references]},applyMethod:{filter:(Y)=>Y,assertFilter:(Y,Z,X)=>{if(Y.length===0)j2(aX(Z,X));return Y},find:(Y)=>Y[0],assertFind:(Y,Z,X)=>{if(Y.length===0)j2(aX(Z,X));return Y[0]}},normalize:(Y)=>typeof Y==="function"?{boundary:"references",method:"filter",where:Y}:typeof Y==="string"?g0(Y,u4.applyBoundary)?{method:"filter",boundary:Y}:{boundary:"references",method:"filter",kind:Y}:{boundary:"references",method:"filter",...Y}},aX=(Y,Z)=>`${Y} had no references matching ${i(Z)}.`,DJ=(Y)=>e1(Y,{stringifyNonKey:(Z)=>Z.expression}),LJ=/"(\$ark\.[^"]+)"/g,MJ=(Y)=>JSON.stringify(Y).replaceAll(LJ,"$1"),h1=(Y,Z)=>({path:Y,node:Z,propString:DJ(Y)}),eX=(Y,Z)=>Y.propString===Z.propString&&Y.node.equals(Z.node),jY=(Y,Z)=>d1(Y,Z,{isEqual:eX}),AJ=(Y,Z)=>d1(Y,Z,{isEqual:(X,_)=>X.equals(_)});class P extends Array{static init(Y,Z,X,_){return new P({kind:Y,l:Z,r:X,path:_?.path??[],optional:_?.optional??!1})}add(Y,Z,X,_){return this.push({kind:Y,l:Z,r:X,path:_?.path??[],optional:_?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Y,l:Z,r:X}=this[0],_=e1(Y);return PY(`Intersection${_&&` at ${_}`} of ${Y_(Z,X)}`)}return`The following intersections result in unsatisfiable types:
23
- \u2022 ${this.map(({path:Y,l:Z,r:X})=>`${Y}: ${Y_(Z,X)}`).join(`
24
- \u2022 `)}`}throw(){return R(this.describeReasons())}invert(){let Y=this.map((Z)=>({...Z,l:Z.r,r:Z.l}));if(!(Y instanceof P))return new P(...Y);return Y}withPrefixKey(Y,Z){return this.map((X)=>({...X,path:[Y,...X.path],optional:X.optional||Z==="optional"}))}toNeverIfDisjoint(){return N.intrinsic.never}}var Y_=(Y,Z)=>`${SY(Y)} and ${SY(Z)}`,SY=(Y)=>D0(Y)?Y.expression:F0(Y)?Y.map(SY).join(" | ")||"never":String(Y),PY=(Y)=>`${Y} results in an unsatisfiable type`;var Z4={},F1=(Y,Z,X)=>L0(Y,Z,{$:X,invert:!1,pipe:!1}),c4=(Y,Z,X)=>L0(Y,Z,{$:X,invert:!1,pipe:!0}),L0=(Y,Z,X)=>{let _=X.pipe?"|>":"&",G=`${Y.hash}${_}${Z.hash}`;if(Z4[G]!==void 0)return Z4[G];if(!X.pipe){let H=`${Z.hash}${_}${Y.hash}`;if(Z4[H]!==void 0){let Q=Z4[H],J=Q instanceof P?Q.invert():Q;return Z4[G]=J,J}}let $=!X.pipe||!Y.includesTransform&&!Z.includesTransform;if($&&Y.equals(Z))return Y;let W=$?vY(Y,Z,X):Y.hasKindIn(...a2)?wJ(Y,Z,X):vY(Y,Z,X);if(D0(W)){if(Y.equals(W))W=Y;else if(Z.equals(W))W=Z}return Z4[G]=W,W},vY=(Y,Z,X)=>{let _=Y.precedence<Z.precedence?Y.kind:Z.kind,G=Y.impl.intersections[Z.kind]??Z.impl.intersections[Y.kind];if(G===void 0)return null;else if(_===Y.kind)return G(Y,Z,X);else{let $=G(Z,Y,{...X,invert:!X.invert});if($ instanceof P)$=$.invert();return $}},wJ=(Y,Z,X)=>Y.includesTransform||Z.includesTransform?X.invert?Z_(Z,Y,X):Z_(Y,Z,X):vY(Y,Z,X),Z_=(Y,Z,X)=>Y.distribute((_)=>RJ(_,Z,X),(_)=>{let G=_.filter(D0);if(G.length===0)return P.init("union",Y.branches,Z.branches);if(G.length<Y.branches.length||!Y.branches.every((H,Q)=>H.in.equals(G[Q].in)))return X.$.parseSchema(G);let $;if(G.length===1){let H=G[0];if(!$)return H;return X.$.node("morph",{...H.inner,in:H.in.configure($,"self")})}let W={branches:G};if($)W.meta=$;return X.$.parseSchema(W)}),RJ=(Y,Z,X)=>{if(Y.hasKind("morph")){let G=[...Y.morphs];if(Y.lastMorphIfNode){let $=L0(Y.lastMorphIfNode,Z,X);if($ instanceof P)return $;G[G.length-1]=$}else G.push(Z);return X.$.node("morph",{morphs:G,in:Y.inner.in})}if(Z.hasKind("morph")){let G=L0(Y,Z.in,X);if(G instanceof P)return G;return X.$.node("morph",{morphs:[Z],in:G})}return X.$.node("morph",{morphs:[Z],in:Y})};class T1 extends d4{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,X1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Y){return F1(this,Y,this.$)}}class Z2 extends T1{traverseApply=(Y,Z)=>{if(!this.traverseAllows(Y,Z))Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.traversalKind==="Allows")Y.return(this.compiledCondition);else Y.if(this.compiledNegation,()=>Y.line(`${Y.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return L2(this.errorContext)}}var t0=(Y)=>(Z,X)=>{if(F0(Z)){if(Z.length===0)return;let G=Z.map(($)=>X.$.node(Y,$));if(Y==="predicate")return G;return G.sort(($,W)=>$.hash<W.hash?-1:1)}let _=X.$.node(Y,Z);return _.hasOpenIntersection()?[_]:_},X4=(Y)=>{let Z=Y.r.shift();if(!Z){let _=Y.l.length===0&&Y.kind==="structure"?N.intrinsic.unknown.internal:Y.ctx.$.node(Y.kind,Object.assign(Y.baseInner,NJ(Y.l)),{prereduced:!0});for(let G of Y.roots){if(_ instanceof P)return _;_=L0(G,_,Y.ctx)}return _}let X=!1;for(let _=0;_<Y.l.length;_++){let G=L0(Y.l[_],Z,Y.ctx);if(G===null)continue;if(G instanceof P)return G;if(!X){if(G.isRoot())return Y.roots.push(G),Y.l.splice(_),X4(Y);Y.l[_]=G,X=!0}else if(!Y.l.includes(G))return _0(`Unexpectedly encountered multiple distinct intersection results for refinement ${G}`)}if(!X)Y.l.push(Z);if(Y.kind==="intersection"){if(Z.impliedSiblings)for(let _ of Z.impliedSiblings)d1(Y.r,_)}return X4(Y)},_4=(Y)=>{return Object.entries(Y).flatMap(([X,_])=>(X in o8)?_:[]).sort((X,_)=>X.precedence<_.precedence?-1:X.precedence>_.precedence?1:X.kind==="predicate"&&_.kind==="predicate"?0:X.hash<_.hash?-1:1)},NJ=(Y)=>{let Z={};for(let X of Y)if(X.hasOpenIntersection())Z[X.kind]=Z0(Z[X.kind],X);else{if(Z[X.kind])return _0(`Unexpected intersection of closed refinements of kind ${X.kind}`);Z[X.kind]=X}return Z},X_=(...Y)=>R(__(...Y)),__=(Y,Z,X)=>{let _=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Z).defaultShortDescription;return`${vX(Y)} operand must be ${Z.description} (was ${_})`};var G_=(Y,Z,X)=>new A2(Y,Z,X,X,null);class r8 extends x1{}class A2 extends x1{[X1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Y,Z,X,_,G){super((...$)=>{let W=o(this.names,(H,Q)=>{let J=this.arg$.parse($[H]);if(!J.extends(this.constraints[H]))R(IJ(Q,this.constraints[H].expression,J.expression));return[Q,J]});if(this.defIsLazy()){let H=this.bodyDef(W);return this.$.parse(H)}return this.$.parse(Z,{args:W})});this.paramDefs=Y,this.bodyDef=Z,this.$=X,this.arg$=_,this.hkt=G,this.description=G?new G().description??`a generic type for ${G.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof r8}cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get json(){return this.cacheGetter("json",{params:this.params.map((Y)=>Y[1].isUnknown()?Y[0]:[Y[0],Y[1].json]),body:dX(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Y)=>typeof Y==="string"?[Y,N.intrinsic.unknown]:[Y[0],this.$.parse(Y[1])]))}get names(){return this.cacheGetter("names",this.params.map((Y)=>Y[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Y)=>Y[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var IJ=(Y,Z,X)=>`${Y} must be assignable to ${Z} (was ${X})`;var TJ=r({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Y)=>typeof Y==="function"?{predicate:Y}:Y,defaults:{description:(Y)=>`valid according to ${Y.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class $_ extends T1{serializedPredicate=B0(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=L2(this.errorContext);traverseApply=(Y,Z)=>{if(!this.predicate(Y,Z.external)&&!Z.hasError())Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.traversalKind==="Allows"){Y.return(this.compiledCondition);return}Y.if(`${this.compiledNegation} && !ctx.hasError()`,()=>Y.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Y,Z){return Z.fallback.predicate({code:"predicate",base:Y,predicate:this.predicate})}}var xY={implementation:TJ,Node:$_};var KJ=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Y)=>Number.isInteger(Y)?Y:R(BJ(Y))}},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,hasAssociatedError:!0,defaults:{description:(Y)=>Y.rule===1?"an integer":Y.rule===2?"even":`a multiple of ${Y.rule}`},intersections:{divisor:(Y,Z,X)=>X.$.node("divisor",{rule:Math.abs(Y.rule*Z.rule/CJ(Y.rule,Z.rule))})},obviatesBasisDescription:!0});class W_ extends Z2{traverseAllows=(Y)=>Y%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=N.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Y){if(Y.type="integer",this.rule===1)return Y;return Y.multipleOf=this.rule,Y}}var fY={implementation:KJ,Node:W_};var BJ=(Y)=>`divisor must be an integer (was ${Y})`,CJ=(Y,Z)=>{let X,_=Y,G=Z;while(G!==0)X=G,G=_%G,_=X;return _};class M1 extends Z2{boundOperandKind=PJ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=vJ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${qJ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?xJ(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Y){return(this.limitKind==="upper"?this.numericLimit<Y.numericLimit:this.numericLimit>Y.numericLimit)||this.numericLimit===Y.numericLimit&&this.exclusive===!0&&!Y.exclusive}overlapsRange(Y){if(this.isStricterThan(Y))return!1;if(this.numericLimit===Y.numericLimit&&(this.exclusive||Y.exclusive))return!1;return!0}overlapIsUnit(Y){return this.numericLimit===Y.numericLimit&&!this.exclusive&&!Y.exclusive}}var qJ={"<":">=","<=":">",">":"<=",">=":"<"},jJ={min:"max",minLength:"maxLength",after:"before"},n8={parse:(Y)=>Y||void 0},s8=(Y)=>(Z)=>{if(typeof Z==="number")return{rule:Z};let{exclusive:X,..._}=Z;return X?{..._,rule:Y==="minLength"?_.rule+1:_.rule-1}:_},t8=(Y)=>(Z)=>{if(typeof Z==="number"||typeof Z==="string"||Z instanceof Date)return{rule:Z};let{exclusive:X,..._}=Z;if(!X)return _;let G=typeof _.rule==="number"?_.rule:typeof _.rule==="string"?new Date(_.rule).valueOf():_.rule.valueOf();return X?{..._,rule:Y==="after"?G+1:G-1}:_},a8=(Y)=>typeof Y==="string"||typeof Y==="number"?new Date(Y):Y,SJ=(Y,Z)=>`${Y} bound must be a positive integer (was ${Z})`,G4=(Y)=>(Z)=>{if(!Number.isInteger(Z)||Z<0)R(SJ(Y,Z));return Z},PJ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},vJ=(Y,Z)=>`${g0(Y,jJ)?">":"<"}${Z?"":"="}`,xJ=(Y)=>typeof Y==="string"?Y:new Date(Y).toLocaleString(),H_=(Y)=>`Bounded expression ${Y} must be exactly one of number, string, Array, or Date`;var fJ=r({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a8,serialize:(Y)=>Y.toISOString()}},normalize:t8("after"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or later`,actual:x2},intersections:{after:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class J_ extends M1{impliedBasis=N.intrinsic.Date.internal;collapsibleLimitString=x2(this.rule);traverseAllows=(Y)=>Y>=this.rule;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,after:this.rule})}}var hY={implementation:fJ,Node:J_};var hJ=r({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a8,serialize:(Y)=>Y.toISOString()}},normalize:t8("before"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or earlier`,actual:x2},intersections:{before:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,after:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("unit",{unit:Y.rule}):null:P.init("range",Y,Z)}});class Q_ extends M1{collapsibleLimitString=x2(this.rule);traverseAllows=(Y)=>Y<=this.rule;impliedBasis=N.intrinsic.Date.internal;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,before:this.rule})}}var kY={implementation:hJ,Node:Q_};var kJ=r({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:G4("exactLength")}},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,hasAssociatedError:!0,defaults:{description:(Y)=>`exactly length ${Y.rule}`,actual:(Y)=>`${Y.length}`},intersections:{exactLength:(Y,Z,X)=>P.init("unit",X.$.node("unit",{unit:Y.rule}),X.$.node("unit",{unit:Z.rule}),{path:["length"]}),minLength:(Y,Z)=>Y.rule>=Z.rule?Y:P.init("range",Y,Z),maxLength:(Y,Z)=>Y.rule<=Z.rule?Y:P.init("range",Y,Z)}});class U_ extends Z2{traverseAllows=(Y)=>Y.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=N.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y.maxLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y.maxItems=this.rule,Y;default:return R0.throwInternalOperandError("exactLength",Y)}}}var bY={implementation:kJ,Node:U_};var bJ=r({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:n8},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,defaults:{description:(Y)=>{if(Y.rule===0)return Y.exclusive?"negative":"non-positive";return`${Y.exclusive?"less than":"at most"} ${Y.rule}`}},intersections:{max:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,min:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("unit",{unit:Y.rule}):null:P.init("range",Y,Z)},obviatesBasisDescription:!0});class z_ extends M1{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(Y)=>Y<this.rule:(Y)=>Y<=this.rule;reduceJsonSchema(Y){if(this.exclusive)Y.exclusiveMaximum=this.rule;else Y.maximum=this.rule;return Y}}var yY={implementation:bJ,Node:z_};var yJ=r({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:G4("maxLength")}},reduce:(Y,Z)=>Y.rule===0?Z.node("exactLength",Y):void 0,normalize:s8("maxLength"),defaults:{description:(Y)=>`at most length ${Y.rule}`,actual:(Y)=>`${Y.length}`},intersections:{maxLength:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,minLength:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("exactLength",{rule:Y.rule}):null:P.init("range",Y,Z)}});class F_ extends M1{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length<=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.maxLength=this.rule,Y;case"array":return Y.maxItems=this.rule,Y;default:return R0.throwInternalOperandError("maxLength",Y)}}}var gY={implementation:yJ,Node:F_};var gJ=r({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:n8},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,defaults:{description:(Y)=>{if(Y.rule===0)return Y.exclusive?"positive":"non-negative";return`${Y.exclusive?"more than":"at least"} ${Y.rule}`}},intersections:{min:(Y,Z)=>Y.isStricterThan(Z)?Y:Z},obviatesBasisDescription:!0});class E_ extends M1{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(Y)=>Y>this.rule:(Y)=>Y>=this.rule;reduceJsonSchema(Y){if(this.exclusive)Y.exclusiveMinimum=this.rule;else Y.minimum=this.rule;return Y}}var pY={implementation:gJ,Node:E_};var pJ=r({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:G4("minLength")}},reduce:(Y)=>Y.rule===0?N.intrinsic.unknown:void 0,normalize:s8("minLength"),defaults:{description:(Y)=>Y.rule===1?"non-empty":`at least length ${Y.rule}`,actual:(Y)=>Y.length===0?"":`${Y.length}`},intersections:{minLength:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class O_ extends M1{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length>=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y;default:return R0.throwInternalOperandError("minLength",Y)}}}var mY={implementation:pJ,Node:O_};var V_={min:pY.implementation,max:yY.implementation,minLength:mY.implementation,maxLength:gY.implementation,exactLength:bY.implementation,after:hY.implementation,before:kY.implementation},D_={min:pY.Node,max:yY.Node,minLength:mY.Node,maxLength:gY.Node,exactLength:bY.Node,after:hY.Node,before:kY.Node};var mJ=r({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Y)=>typeof Y==="string"?{rule:Y}:Y instanceof RegExp?Y.flags?{rule:Y.source,flags:Y.flags}:{rule:Y.source}:Y,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Y)=>`matched by ${Y.rule}`},intersections:{pattern:()=>null}});class L_ extends Z2{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=N.intrinsic.string.internal;reduceJsonSchema(Y,Z){if(Y.pattern)return Z.fallback.patternIntersection({code:"patternIntersection",base:Y,pattern:this.rule});return Y.pattern=this.rule,Y}}var uY={implementation:mJ,Node:L_};var l4=(Y,Z)=>{let X=uJ(Y);if(Z&&!Z.includes(X))return R(`Root of kind ${X} should be one of ${Z}`);return X},uJ=(Y)=>{if(y(Y,"root"))return Y.kind;if(typeof Y==="string")return Y[0]==="$"?"alias":(Y in Q1)?"domain":"proto";if(typeof Y==="function")return"proto";if(typeof Y!=="object"||Y===null)return R(M_(Y));if("morphs"in Y)return"morph";if("branches"in Y||F0(Y))return"union";if("unit"in Y)return"unit";if("reference"in Y)return"alias";let Z=Object.keys(Y);if(Z.length===0||Z.some((X)=>(X in o8)))return"intersection";if("proto"in Y)return"proto";if("domain"in Y)return"domain";return R(M_(Y))},M_=(Y)=>`${i(Y)} is not a valid type schema`,A_={},dJ=(Y)=>F0(Y)?Y.map((Z)=>Z.collapsibleJson):Y.collapsibleJson,_1={};N.nodesByRegisteredId=_1;var dY=(Y)=>{return A_[Y]??=0,`${Y}${++A_[Y]}`},cY=(Y)=>{let Z=$4[Y.kind],X=Z.applyConfig?.(Y.def,Y.$.resolvedConfig)??Y.def,_={},{meta:G,...$}=X,W=G===void 0?{}:typeof G==="string"?{description:G}:G,H=EY($).sort(([J],[U])=>e2(J)?e2(U)?Y4(J)-Y4(U):1:e2(U)?-1:J<U?-1:1).filter(([J,U])=>{if(J.startsWith("meta.")){let F=J.slice(5);return W[F]=U,!1}return!0});for(let J of H){let U=J[0],F=Z.keys[U];if(!F)return R(`Key ${U} is not valid on ${Y.kind} schema`);let V=F.parse?F.parse(J[1],Y):J[1];if(V!==L1&&(V!==void 0||F.preserveUndefined))_[U]=V}if(Z.reduce&&!Y.prereduced){let J=Z.reduce(_,Y.$);if(J){if(J instanceof P)return J.throw();return cJ(J,W)}}return lY({id:Y.id,kind:Y.kind,inner:_,meta:W,$:Y.$})},lY=({id:Y,kind:Z,inner:X,meta:_,$:G,ignoreCache:$})=>{let W=$4[Z],H=EY(X),Q=[],J={};for(let[v,k]of H){let m=W.keys[v],T=m.serialize??(m.child?dJ:I1);if(J[v]=T(k),m.child===!0){let I=k;if(F0(I))Q.push(...I);else Q.push(I)}else if(typeof m.child==="function")Q.push(...m.child(k))}if(W.finalizeInnerJson)J=W.finalizeInnerJson(J);let U={...J},F={};if(!c1(_))F=o(_,(v,k)=>[v,v==="examples"?k:I1(k)]),U.meta=e8(F,"description",!0);J=e8(J,W.collapsibleKey,!1);let V=JSON.stringify({kind:Z,...J});U=e8(U,W.collapsibleKey,!1);let D=e8(U,W.collapsibleKey,!0),A=JSON.stringify({kind:Z,...U});if(G.nodesByHash[A]&&!$)return G.nodesByHash[A];let w={id:Y,kind:Z,impl:W,inner:X,innerEntries:H,innerJson:J,innerHash:V,meta:_,metaJson:F,json:U,hash:A,collapsibleJson:D,children:Q};if(Z!=="intersection"){for(let v in X)if(v!=="in"&&v!=="out")w[v]=X[v]}let f=new R_[Z](w,G);return G.nodesByHash[A]=f},w_=(Y,Z)=>{if(Y.id===Z)return Y;if(D0(_1[Z]))_0(`Unexpected attempt to overwrite node id ${Z}`);return lY({id:Z,kind:Y.kind,inner:Y.inner,meta:Y.meta,$:Y.$,ignoreCache:!0})},cJ=(Y,Z,X)=>{if(X&&D0(_1[X]))_0(`Unexpected attempt to overwrite node id ${X}`);return lY({id:X??dY(Z.alias??Y.kind),kind:Y.kind,inner:Y.inner,meta:Z,$:Y.$})},e8=(Y,Z,X)=>{let _=Object.keys(Y);if(_.length===1&&_[0]===Z){let G=Y[Z];if(X)return G;if(J1(G,"object")&&(Object.keys(G).length===1||Array.isArray(G)))return G}return Y};var o4=(Y,Z,X)=>{if(Y.key!==Z.key)return null;let _=Y.key,G=L0(Y.value,Z.value,X),$=Y.required||Z.required?"required":"optional";if(G instanceof P)if($==="optional")G=N.intrinsic.never.internal;else return G.withPrefixKey(Y.key,Y.required&&Z.required?"required":"optional");if($==="required")return X.$.node("required",{key:_,value:G});let W=Y.hasDefault()?Z.hasDefault()?Y.default===Z.default?Y.default:R(oY(Y.default,Z.default)):Y.default:Z.hasDefault()?Z.default:L1;return X.$.node("optional",{key:_,value:G,default:W})};class i4 extends T1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=N.intrinsic.object.internal;serializedKey=Y2(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=Z0(this.value.flatRefs.map((Y)=>h1([this.key,...Y.path],Y.node)),h1([this.key],this.value));_transform(Y,Z){Z.path.push(this.key);let X=super._transform(Y,Z);return Z.path.pop(),X}hasDefault(){return"default"in this.inner}traverseAllows=(Y,Z)=>{if(this.key in Y)return z1(this.key,()=>this.value.traverseAllows(Y[this.key],Z),Z);return this.optional};traverseApply=(Y,Z)=>{if(this.key in Y)z1(this.key,()=>this.value.traverseApply(Y[this.key],Z),Z);else if(this.hasKind("required"))Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.if(`${this.serializedKey} in data`,()=>Y.traverseKey(this.serializedKey,`data${Y.prop(this.key)}`,this.value)),this.hasKind("required"))Y.else(()=>Y.traversalKind==="Apply"?Y.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Y.return(!1));if(Y.traversalKind==="Allows")Y.return(!0)}}var oY=(Y,Z)=>`Invalid intersection of default values ${i(Y)} & ${i(Z)}`;var lJ=r({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},default:{preserveUndefined:!0}},normalize:(Y)=>Y,reduce:(Y,Z)=>{if(Z.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Y.value.allows(void 0))return Z.node("optional",{...Y,value:Y.value.or(d.undefined)},{prereduced:!0})}},defaults:{description:(Y)=>`${Y.compiledKey}?: ${Y.value.description}`},intersections:{optional:o4}});class N_ extends i4{constructor(...Y){super(...Y);if("default"in this.inner)n4(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:Y,...Z}=this.inner;return this.cacheGetter("outProp",this.$.node("required",Z,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${i(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=iJ(this);defaultValueMorphRef=this.defaultValueMorph&&B0(this.defaultValueMorph)}var r4={implementation:lJ,Node:N_},oJ={},iJ=(Y)=>{if(!Y.hasDefault())return;let Z=`{${Y.compiledKey}: ${Y.value.id} = ${I1(Y.default)}}`;return oJ[Z]??=iY(Y.key,Y.value,Y.default)},iY=(Y,Z,X)=>{if(typeof X==="function")return Z.includesTransform?(G,$)=>{return z1(Y,()=>Z(G[Y]=X(),$),$),G}:(G)=>{return G[Y]=X(),G};let _=Z.includesTransform?Z.assert(X):X;return J1(_,"object")?(G,$)=>{return z1(Y,()=>Z(G[Y]=X,$),$),G}:(G)=>{return G[Y]=_,G}},n4=(Y,Z,X)=>{let _=O2(Z);if(J1(Z,"object")&&!_)R(rJ(X));let G=Y.in(_?Z():Z);if(G instanceof U1){if(X===null)R(`Default ${G.summary}`);let $=G.transform((W)=>W.transform((H)=>({...H,prefixPath:[X]})));R(`Default for ${$.summary}`)}return Z},rJ=(Y)=>{return`Non-primitive default ${Y===null?"":typeof Y==="number"?`for value at [${Y}] `:`for ${Y2(Y)} `}must be specified as a function like () => ({my: 'object'})`};class K1 extends d4{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,X1,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Y)=>{let Z=this(Y);if(Z instanceof U1)return Z;return{value:Z}}}}as(){return this}brand(Y){if(Y==="")return R(nJ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Y,Z){let X=this.branches.map(Y);return Z?.(X)??X}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Y={}){let Z=CY(this.$.resolvedConfig.toJsonSchema,Y);Z.useRefs||=this.isCyclic;let X=typeof Z.dialect==="string"?{$schema:Z.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse(Z)),Z.useRefs)X.$defs=o(this.references,(_,G)=>G.isRoot()&&!G.alwaysExpandJsonSchema?[G.id,G.toResolvedJsonSchema(Z)]:[]);return X}toJsonSchemaRecurse(Y){if(Y.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(Y)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Y){let Z=this.innerToJsonSchema(Y);return Object.assign(Z,this.metaJson)}intersect(Y){let Z=this.$.parseDefinition(Y),X=this.rawIntersect(Z);if(X instanceof P)return X;return this.$.finalize(X)}rawIntersect(Y){return F1(this,Y,this.$)}toNeverIfDisjoint(){return this}and(Y){let Z=this.intersect(Y);return Z instanceof P?Z.throw():Z}rawAnd(Y){let Z=this.rawIntersect(Y);return Z instanceof P?Z.throw():Z}or(Y){let Z=this.$.parseDefinition(Y);return this.$.finalize(this.rawOr(Z))}rawOr(Y){let Z=[...this.branches,...Y.branches];return this.$.node("union",Z)}map(Y){return this.$.schema(this.applyStructuralOperation("map",[Y]))}pick(...Y){return this.$.schema(this.applyStructuralOperation("pick",Y))}omit(...Y){return this.$.schema(this.applyStructuralOperation("omit",Y))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Y=this.applyStructuralOperation("keyof",[]).reduce((Z,X)=>Z.intersect(X).toNeverIfDisjoint(),N.intrinsic.unknown.internal);if(Y.branches.length===0)R(PY(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Y)}get props(){if(this.branches.length!==1)return R(sJ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(Z.distribute((X)=>this.applyStructuralOperation("merge",[I_(X)??R(T_("merge",X.expression))])))}applyStructuralOperation(Y,Z){return this.distribute((X)=>{if(X.equals(N.intrinsic.object)&&Y!=="merge")return X;let _=I_(X);if(!_)R(T_(Y,X.expression));if(Y==="keyof")return _.keyof();if(Y==="get")return _.get(...Z);if(Y==="props")return _.props;let G=Y==="required"?"require":Y==="partial"?"optionalize":Y;return this.$.node("intersection",{...X.inner,structure:_[G](...Z)})})}get(...Y){if(Y[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Y))}extract(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>X.extends(Z)))}exclude(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>!X.extends(Z)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Y){return!(this.intersect(Y)instanceof P)}extends(Y){let Z=this.intersect(Y);return!(Z instanceof P)&&this.equals(Z)}ifExtends(Y){return this.extends(Y)?this:void 0}subsumes(Y){return this.$.parseDefinition(Y).extends(this)}configure(Y,Z="shallow"){return this.configureReferences(Y,Z)}describe(Y,Z="shallow"){return this.configure({description:Y},Z)}optional(){return[this,"?"]}default(Y){return n4(this,Y,null),[this,"=",Y]}from(Y){return this.assert(Y)}_pipe(...Y){let Z=Y.reduce((X,_)=>X.rawPipeOnce(_),this);return this.$.finalize(Z)}tryPipe(...Y){let Z=Y.reduce((X,_)=>X.rawPipeOnce(y(_,"root")?_:(G,$)=>{try{return _(G,$)}catch(W){return $.error({code:"predicate",predicate:_,actual:`aborted due to error:
22
+ `);class f1{path=[];errors=new Q1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Y,Z){this.root=Y,this.config=Z}get data(){let Y=this.root;for(let Z of this.path)Y=Y?.[Z];return Y}get propString(){return e1(this.path)}reject(Y){return this.error(Y),!1}mustBe(Y){return this.error(Y),!1}error(Y){let Z=typeof Y==="object"?Y.code?Y:{...Y,code:"predicate"}:{code:"predicate",expected:Y};return this.errorFromContext(Z)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(Y){let Z={path:new b4(...this.path),morphs:Y};if(this.currentBranch)this.currentBranch.queuedMorphs.push(Z);else this.queuedMorphs.push(Z)}finalize(Y){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 Y?Y(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(Y){return this.errorFromContext(Y)}errorFromContext(Y){let Z=new M2(Y,this);if(this.currentBranch)this.currentBranch.error=Z;else this.errors.add(Z);return Z}applyQueuedMorphs(){while(this.queuedMorphs.length){let Y=this.queuedMorphs;this.queuedMorphs=[];for(let{path:Z,morphs:X}of Y){if(this.errors.affectsPath(Z))continue;this.applyMorphsAtPath(Z,X)}}}applyMorphsAtPath(Y,Z){let X=Y.at(-1),_;if(X!==void 0){_=this.root;for(let G=0;G<Y.length-1;G++)_=_[Y[G]]}this.path=[...Y];for(let G of Z){let $=L0(G),W=G(_===void 0?this.root:_[X],this);if(W instanceof M2){this.errors.add(W);break}if(W instanceof Q1){if(!$)this.errors.merge(W);break}if(_===void 0)this.root=W;else _[X]=W;this.applyQueuedMorphs()}}}var z1=(Y,Z,X)=>{if(!X)return Z();X.path.push(Y);let _=Z();return X.path.pop(),_};class m4 extends x1{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Y,Z){super((_,G,$=this.onFail)=>{if(G)return this.traverseApply(_,G),G.hasError()?G.errors:G.data;return this.rootApply(_,$)},{attach:Y});this.attachments=Y,this.$=Z,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((_,G)=>wJ(_,G.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let _=0;_<this.children.length;_++){if(this.includesTransform||=this.children[_].includesTransform,this.includesContextualPredicate||=this.children[_].includesContextualPredicate,this.isCyclic||=this.children[_].isCyclic,!X){let G=this.children[_].flatRefs;for(let $=0;$<G.length;$++){let W=G[$];if(!this.flatRefs.some((H)=>Y_(H,W))){this.flatRefs.push(W);for(let H of W.node.branches)if(H.hasKind("morph")||H.hasKind("intersection")&&H.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:W.path,propString:W.propString,node:H})}}}Object.assign(this.referencesById,this.children[_].referencesById)}this.flatRefs.sort((_,G)=>_.path.length>G.path.length?1:_.path.length<G.path.length?-1:_.propString>G.propString?1:_.propString<G.propString?-1:_.node.expression<G.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((_)=>_.length===1||_.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((_)=>_.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(_)=>this.traverseAllows(_,new f1(_,this.$.resolvedConfig)):(_)=>this.traverseAllows(_)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Z,X)=>{if(this.allows(Z))return Z;let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"contextual":return(Z,X)=>{let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Y=this.$.resolvedConfig.clone;return(Z,X)=>{if(this.allows(Z))return this.contextFreeMorph(Y&&(typeof Z==="object"&&Z!==null||typeof Z==="function")?Y(Z):Z);let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,_0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=AJ(this.metaJson);cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=e2(this.kind);precompilation;assert=(Y,Z)=>this(Y,Z,(X)=>X.throw());traverse(Y,Z){return this(Y,Z,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(Y){if(!this.includesTransform)return this;let Z={};for(let[X,_]of this.innerEntries){let G=this.impl.keys[X];if(G.reduceIo)G.reduceIo(Y,Z,_);else if(G.child){let $=_;Z[X]=F0($)?$.map((W)=>W[Y]):$[Y]}else Z[X]=_}return this.$.node(this.kind,Z)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Y){let Z=L0(Y)?Y:this.$.parseDefinition(Y);return this.innerHash===Z.innerHash}ifEquals(Y){return this.equals(Y)?this:void 0}hasKind(Y){return this.kind===Y}assertHasKind(Y){if(this.kind!==Y)q2(`${this.kind} node was not of asserted kind ${Y}`);return this}hasKindIn(...Y){return Y.includes(this.kind)}assertHasKindIn(...Y){if(!n1(Y,this.kind))q2(`${this.kind} node was not one of asserted kinds ${Y}`);return this}isBasis(){return n1(rX,this.kind)}isConstraint(){return n1(c8,this.kind)}isStructural(){return n1(s2,this.kind)}isRefinement(){return n1(CY,this.kind)}isRoot(){return n1(t2,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Y){return this.hasKind("unit")&&this.allows(Y)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Y){let Z=p4.normalize(Y);return this._select(Z)}_select(Y){let Z=p4.applyBoundary[Y.boundary??"references"](this);if(Y.kind)Z=Z.filter((X)=>X.kind===Y.kind);if(Y.where)Z=Z.filter(Y.where);return p4.applyMethod[Y.method??"filter"](Z,this,Y)}transform(Y,Z){return this._transform(Y,this._createTransformContext(Z))}_createTransformContext(Y){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Y?.prereduced??!1},undeclaredKeyHandling:void 0,...Y}}_transform(Y,Z){let X=Z.bindScope??this.$;if(Z.seen[this.id])return this.$.lazilyResolve(Z.seen[this.id]);if(Z.shouldTransform?.(this,Z)===!1)return this;let _;if(Z.seen[this.id]=()=>_,this.hasKind("structure")&&this.undeclared!==Z.undeclaredKeyHandling)Z={...Z,undeclaredKeyHandling:this.undeclared};let G=i(this.inner,(J,z)=>{if(!this.impl.keys[J].child)return[J,z];let E=z;if(!F0(E)){let D=E._transform(Y,Z);return D?[J,D]:[]}if(E.length===0)return[J,z];let V=E.flatMap((D)=>{return D._transform(Y,Z)??[]});return V.length?[J,V]:[]});delete Z.seen[this.id];let $=Object.assign(G,{meta:this.meta}),W=Z.selected&&!Z.selected.includes(this)?$:Y(this.kind,$,Z);if(W===null)return null;if(L0(W))return _=W;let H=Object.keys(W);if((H.length===0||H.length===1&&H[0]==="meta")&&!c1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in W))return Z.undeclaredKeyHandling?{...W,value:I.intrinsic.unknown}:null;if(this.kind==="morph")W.in??=I.intrinsic.unknown;return _=X.node(this.kind,W,Z.parseOptions)}configureReferences(Y,Z="references"){let X=p4.normalize(Z),_=typeof Y==="string"?(H,Q)=>({...Q,meta:{...Q.meta,description:Y}}):typeof Y==="function"?(H,Q)=>({...Q,meta:Y(Q.meta)}):(H,Q)=>({...Q,meta:{...Q.meta,...Y}});if(X.boundary==="self")return this.$.node(this.kind,_(this.kind,{...this.inner,meta:this.meta}));let G=this._select(X),$=G&&E2(G),W=X.boundary==="child"?(H,Q)=>Q.root.children.includes(H):X.boundary==="shallow"?(H)=>H.kind!=="structure":()=>!0;return this.$.finalize(this.transform(_,{shouldTransform:W,selected:$}))}}var p4={applyBoundary:{self:(Y)=>[Y],child:(Y)=>[...Y.children],shallow:(Y)=>[...Y.shallowReferences],references:(Y)=>[...Y.references]},applyMethod:{filter:(Y)=>Y,assertFilter:(Y,Z,X)=>{if(Y.length===0)q2(eX(Z,X));return Y},find:(Y)=>Y[0],assertFind:(Y,Z,X)=>{if(Y.length===0)q2(eX(Z,X));return Y[0]}},normalize:(Y)=>typeof Y==="function"?{boundary:"references",method:"filter",where:Y}:typeof Y==="string"?g0(Y,p4.applyBoundary)?{method:"filter",boundary:Y}:{boundary:"references",method:"filter",kind:Y}:{boundary:"references",method:"filter",...Y}},eX=(Y,Z)=>`${Y} had no references matching ${r(Z)}.`,LJ=(Y)=>e1(Y,{stringifyNonKey:(Z)=>Z.expression}),MJ=/"(\$ark\.[^"]+)"/g,AJ=(Y)=>JSON.stringify(Y).replaceAll(MJ,"$1"),h1=(Y,Z)=>({path:Y,node:Z,propString:LJ(Y)}),Y_=(Y,Z)=>Y.propString===Z.propString&&Y.node.equals(Z.node),SY=(Y,Z)=>d1(Y,Z,{isEqual:Y_}),wJ=(Y,Z)=>d1(Y,Z,{isEqual:(X,_)=>X.equals(_)});class P extends Array{static init(Y,Z,X,_){return new P({kind:Y,l:Z,r:X,path:_?.path??[],optional:_?.optional??!1})}add(Y,Z,X,_){return this.push({kind:Y,l:Z,r:X,path:_?.path??[],optional:_?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Y,l:Z,r:X}=this[0],_=e1(Y);return vY(`Intersection${_&&` at ${_}`} of ${Z_(Z,X)}`)}return`The following intersections result in unsatisfiable types:
23
+ \u2022 ${this.map(({path:Y,l:Z,r:X})=>`${Y}: ${Z_(Z,X)}`).join(`
24
+ \u2022 `)}`}throw(){return A(this.describeReasons())}invert(){let Y=this.map((Z)=>({...Z,l:Z.r,r:Z.l}));if(!(Y instanceof P))return new P(...Y);return Y}withPrefixKey(Y,Z){return this.map((X)=>({...X,path:[Y,...X.path],optional:X.optional||Z==="optional"}))}toNeverIfDisjoint(){return I.intrinsic.never}}var Z_=(Y,Z)=>`${PY(Y)} and ${PY(Z)}`,PY=(Y)=>L0(Y)?Y.expression:F0(Y)?Y.map(PY).join(" | ")||"never":String(Y),vY=(Y)=>`${Y} results in an unsatisfiable type`;var Y4={},U1=(Y,Z,X)=>M0(Y,Z,{$:X,invert:!1,pipe:!1}),u4=(Y,Z,X)=>M0(Y,Z,{$:X,invert:!1,pipe:!0}),M0=(Y,Z,X)=>{let _=X.pipe?"|>":"&",G=`${Y.hash}${_}${Z.hash}`;if(Y4[G]!==void 0)return Y4[G];if(!X.pipe){let H=`${Z.hash}${_}${Y.hash}`;if(Y4[H]!==void 0){let Q=Y4[H],J=Q instanceof P?Q.invert():Q;return Y4[G]=J,J}}let $=!X.pipe||!Y.includesTransform&&!Z.includesTransform;if($&&Y.equals(Z))return Y;let W=$?xY(Y,Z,X):Y.hasKindIn(...t2)?RJ(Y,Z,X):xY(Y,Z,X);if(L0(W)){if(Y.equals(W))W=Y;else if(Z.equals(W))W=Z}return Y4[G]=W,W},xY=(Y,Z,X)=>{let _=Y.precedence<Z.precedence?Y.kind:Z.kind,G=Y.impl.intersections[Z.kind]??Z.impl.intersections[Y.kind];if(G===void 0)return null;else if(_===Y.kind)return G(Y,Z,X);else{let $=G(Z,Y,{...X,invert:!X.invert});if($ instanceof P)$=$.invert();return $}},RJ=(Y,Z,X)=>Y.includesTransform||Z.includesTransform?X.invert?X_(Z,Y,X):X_(Y,Z,X):xY(Y,Z,X),X_=(Y,Z,X)=>Y.distribute((_)=>NJ(_,Z,X),(_)=>{let G=_.filter(L0);if(G.length===0)return P.init("union",Y.branches,Z.branches);if(G.length<Y.branches.length||!Y.branches.every((H,Q)=>H.in.equals(G[Q].in)))return X.$.parseSchema(G);let $;if(G.length===1){let H=G[0];if(!$)return H;return X.$.node("morph",{...H.inner,in:H.in.configure($,"self")})}let W={branches:G};if($)W.meta=$;return X.$.parseSchema(W)}),NJ=(Y,Z,X)=>{if(Y.hasKind("morph")){let G=[...Y.morphs];if(Y.lastMorphIfNode){let $=M0(Y.lastMorphIfNode,Z,X);if($ instanceof P)return $;G[G.length-1]=$}else G.push(Z);return X.$.node("morph",{morphs:G,in:Y.inner.in})}if(Z.hasKind("morph")){let G=M0(Y,Z.in,X);if(G instanceof P)return G;return X.$.node("morph",{morphs:[Z],in:G})}return X.$.node("morph",{morphs:[Z],in:Y})};class N1 extends m4{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,Y1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Y){return U1(this,Y,this.$)}}class Z2 extends N1{traverseApply=(Y,Z)=>{if(!this.traverseAllows(Y,Z))Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.traversalKind==="Allows")Y.return(this.compiledCondition);else Y.if(this.compiledNegation,()=>Y.line(`${Y.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return L2(this.errorContext)}}var s0=(Y)=>(Z,X)=>{if(F0(Z)){if(Z.length===0)return;let G=Z.map(($)=>X.$.node(Y,$));if(Y==="predicate")return G;return G.sort(($,W)=>$.hash<W.hash?-1:1)}let _=X.$.node(Y,Z);return _.hasOpenIntersection()?[_]:_},Z4=(Y)=>{let Z=Y.r.shift();if(!Z){let _=Y.l.length===0&&Y.kind==="structure"?I.intrinsic.unknown.internal:Y.ctx.$.node(Y.kind,Object.assign(Y.baseInner,IJ(Y.l)),{prereduced:!0});for(let G of Y.roots){if(_ instanceof P)return _;_=M0(G,_,Y.ctx)}return _}let X=!1;for(let _=0;_<Y.l.length;_++){let G=M0(Y.l[_],Z,Y.ctx);if(G===null)continue;if(G instanceof P)return G;if(!X){if(G.isRoot())return Y.roots.push(G),Y.l.splice(_),Z4(Y);Y.l[_]=G,X=!0}else if(!Y.l.includes(G))return _0(`Unexpectedly encountered multiple distinct intersection results for refinement ${G}`)}if(!X)Y.l.push(Z);if(Y.kind==="intersection"){if(Z.impliedSiblings)for(let _ of Z.impliedSiblings)d1(Y.r,_)}return Z4(Y)},X4=(Y)=>{return Object.entries(Y).flatMap(([X,_])=>(X in l8)?_:[]).sort((X,_)=>X.precedence<_.precedence?-1:X.precedence>_.precedence?1:X.kind==="predicate"&&_.kind==="predicate"?0:X.hash<_.hash?-1:1)},IJ=(Y)=>{let Z={};for(let X of Y)if(X.hasOpenIntersection())Z[X.kind]=Z0(Z[X.kind],X);else{if(Z[X.kind])return _0(`Unexpected intersection of closed refinements of kind ${X.kind}`);Z[X.kind]=X}return Z},__=(...Y)=>A(G_(...Y)),G_=(Y,Z,X)=>{let _=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Z).defaultShortDescription;return`${xX(Y)} operand must be ${Z.description} (was ${_})`};var $_=(Y,Z,X)=>new A2(Y,Z,X,X,null);class i8 extends x1{}class A2 extends x1{[Y1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Y,Z,X,_,G){super((...$)=>{let W=i(this.names,(H,Q)=>{let J=this.arg$.parse($[H]);if(!J.extends(this.constraints[H]))A(KJ(Q,this.constraints[H].expression,J.expression));return[Q,J]});if(this.defIsLazy()){let H=this.bodyDef(W);return this.$.parse(H)}return this.$.parse(Z,{args:W})});this.paramDefs=Y,this.bodyDef=Z,this.$=X,this.arg$=_,this.hkt=G,this.description=G?new G().description??`a generic type for ${G.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof i8}cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get json(){return this.cacheGetter("json",{params:this.params.map((Y)=>Y[1].isUnknown()?Y[0]:[Y[0],Y[1].json]),body:cX(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Y)=>typeof Y==="string"?[Y,I.intrinsic.unknown]:[Y[0],this.$.parse(Y[1])]))}get names(){return this.cacheGetter("names",this.params.map((Y)=>Y[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Y)=>Y[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var KJ=(Y,Z,X)=>`${Y} must be assignable to ${Z} (was ${X})`;var TJ=n({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Y)=>typeof Y==="function"?{predicate:Y}:Y,defaults:{description:(Y)=>`valid according to ${Y.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class W_ extends N1{serializedPredicate=B0(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=L2(this.errorContext);traverseApply=(Y,Z)=>{if(!this.predicate(Y,Z.external)&&!Z.hasError())Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.traversalKind==="Allows"){Y.return(this.compiledCondition);return}Y.if(`${this.compiledNegation} && !ctx.hasError()`,()=>Y.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Y,Z){return Z.fallback.predicate({code:"predicate",base:Y,predicate:this.predicate})}}var fY={implementation:TJ,Node:W_};var BJ=n({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Y)=>Number.isInteger(Y)?Y:A(CJ(Y))}},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,hasAssociatedError:!0,defaults:{description:(Y)=>Y.rule===1?"an integer":Y.rule===2?"even":`a multiple of ${Y.rule}`},intersections:{divisor:(Y,Z,X)=>X.$.node("divisor",{rule:Math.abs(Y.rule*Z.rule/qJ(Y.rule,Z.rule))})},obviatesBasisDescription:!0});class H_ extends Z2{traverseAllows=(Y)=>Y%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=I.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Y){if(Y.type="integer",this.rule===1)return Y;return Y.multipleOf=this.rule,Y}}var hY={implementation:BJ,Node:H_};var CJ=(Y)=>`divisor must be an integer (was ${Y})`,qJ=(Y,Z)=>{let X,_=Y,G=Z;while(G!==0)X=G,G=_%G,_=X;return _};class M1 extends Z2{boundOperandKind=vJ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=xJ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${jJ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?fJ(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Y){return(this.limitKind==="upper"?this.numericLimit<Y.numericLimit:this.numericLimit>Y.numericLimit)||this.numericLimit===Y.numericLimit&&this.exclusive===!0&&!Y.exclusive}overlapsRange(Y){if(this.isStricterThan(Y))return!1;if(this.numericLimit===Y.numericLimit&&(this.exclusive||Y.exclusive))return!1;return!0}overlapIsUnit(Y){return this.numericLimit===Y.numericLimit&&!this.exclusive&&!Y.exclusive}}var jJ={"<":">=","<=":">",">":"<=",">=":"<"},SJ={min:"max",minLength:"maxLength",after:"before"},r8={parse:(Y)=>Y||void 0},n8=(Y)=>(Z)=>{if(typeof Z==="number")return{rule:Z};let{exclusive:X,..._}=Z;return X?{..._,rule:Y==="minLength"?_.rule+1:_.rule-1}:_},s8=(Y)=>(Z)=>{if(typeof Z==="number"||typeof Z==="string"||Z instanceof Date)return{rule:Z};let{exclusive:X,..._}=Z;if(!X)return _;let G=typeof _.rule==="number"?_.rule:typeof _.rule==="string"?new Date(_.rule).valueOf():_.rule.valueOf();return X?{..._,rule:Y==="after"?G+1:G-1}:_},t8=(Y)=>typeof Y==="string"||typeof Y==="number"?new Date(Y):Y,PJ=(Y,Z)=>`${Y} bound must be a positive integer (was ${Z})`,_4=(Y)=>(Z)=>{if(!Number.isInteger(Z)||Z<0)A(PJ(Y,Z));return Z},vJ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},xJ=(Y,Z)=>`${g0(Y,SJ)?">":"<"}${Z?"":"="}`,fJ=(Y)=>typeof Y==="string"?Y:new Date(Y).toLocaleString(),J_=(Y)=>`Bounded expression ${Y} must be exactly one of number, string, Array, or Date`;var hJ=n({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t8,serialize:(Y)=>Y.toISOString()}},normalize:s8("after"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or later`,actual:v2},intersections:{after:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class Q_ extends M1{impliedBasis=I.intrinsic.Date.internal;collapsibleLimitString=v2(this.rule);traverseAllows=(Y)=>Y>=this.rule;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,after:this.rule})}}var kY={implementation:hJ,Node:Q_};var kJ=n({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t8,serialize:(Y)=>Y.toISOString()}},normalize:s8("before"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or earlier`,actual:v2},intersections:{before:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,after:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("unit",{unit:Y.rule}):null:P.init("range",Y,Z)}});class z_ extends M1{collapsibleLimitString=v2(this.rule);traverseAllows=(Y)=>Y<=this.rule;impliedBasis=I.intrinsic.Date.internal;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,before:this.rule})}}var bY={implementation:kJ,Node:z_};var bJ=n({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:_4("exactLength")}},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,hasAssociatedError:!0,defaults:{description:(Y)=>`exactly length ${Y.rule}`,actual:(Y)=>`${Y.length}`},intersections:{exactLength:(Y,Z,X)=>P.init("unit",X.$.node("unit",{unit:Y.rule}),X.$.node("unit",{unit:Z.rule}),{path:["length"]}),minLength:(Y,Z)=>Y.rule>=Z.rule?Y:P.init("range",Y,Z),maxLength:(Y,Z)=>Y.rule<=Z.rule?Y:P.init("range",Y,Z)}});class U_ extends Z2{traverseAllows=(Y)=>Y.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=I.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y.maxLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y.maxItems=this.rule,Y;default:return N0.throwInternalOperandError("exactLength",Y)}}}var yY={implementation:bJ,Node:U_};var yJ=n({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r8},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,defaults:{description:(Y)=>{if(Y.rule===0)return Y.exclusive?"negative":"non-positive";return`${Y.exclusive?"less than":"at most"} ${Y.rule}`}},intersections:{max:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,min:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("unit",{unit:Y.rule}):null:P.init("range",Y,Z)},obviatesBasisDescription:!0});class F_ extends M1{impliedBasis=I.intrinsic.number.internal;traverseAllows=this.exclusive?(Y)=>Y<this.rule:(Y)=>Y<=this.rule;reduceJsonSchema(Y){if(this.exclusive)Y.exclusiveMaximum=this.rule;else Y.maximum=this.rule;return Y}}var gY={implementation:yJ,Node:F_};var gJ=n({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_4("maxLength")}},reduce:(Y,Z)=>Y.rule===0?Z.node("exactLength",Y):void 0,normalize:n8("maxLength"),defaults:{description:(Y)=>`at most length ${Y.rule}`,actual:(Y)=>`${Y.length}`},intersections:{maxLength:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,minLength:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("exactLength",{rule:Y.rule}):null:P.init("range",Y,Z)}});class E_ extends M1{impliedBasis=I.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length<=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.maxLength=this.rule,Y;case"array":return Y.maxItems=this.rule,Y;default:return N0.throwInternalOperandError("maxLength",Y)}}}var pY={implementation:gJ,Node:E_};var pJ=n({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r8},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,defaults:{description:(Y)=>{if(Y.rule===0)return Y.exclusive?"positive":"non-negative";return`${Y.exclusive?"more than":"at least"} ${Y.rule}`}},intersections:{min:(Y,Z)=>Y.isStricterThan(Z)?Y:Z},obviatesBasisDescription:!0});class V_ extends M1{impliedBasis=I.intrinsic.number.internal;traverseAllows=this.exclusive?(Y)=>Y>this.rule:(Y)=>Y>=this.rule;reduceJsonSchema(Y){if(this.exclusive)Y.exclusiveMinimum=this.rule;else Y.minimum=this.rule;return Y}}var mY={implementation:pJ,Node:V_};var mJ=n({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_4("minLength")}},reduce:(Y)=>Y.rule===0?I.intrinsic.unknown:void 0,normalize:n8("minLength"),defaults:{description:(Y)=>Y.rule===1?"non-empty":`at least length ${Y.rule}`,actual:(Y)=>Y.length===0?"":`${Y.length}`},intersections:{minLength:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class O_ extends M1{impliedBasis=I.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length>=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y;default:return N0.throwInternalOperandError("minLength",Y)}}}var uY={implementation:mJ,Node:O_};var D_={min:mY.implementation,max:gY.implementation,minLength:uY.implementation,maxLength:pY.implementation,exactLength:yY.implementation,after:kY.implementation,before:bY.implementation},L_={min:mY.Node,max:gY.Node,minLength:uY.Node,maxLength:pY.Node,exactLength:yY.Node,after:kY.Node,before:bY.Node};var uJ=n({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Y)=>typeof Y==="string"?{rule:Y}:Y instanceof RegExp?Y.flags?{rule:Y.source,flags:Y.flags}:{rule:Y.source}:Y,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Y)=>`matched by ${Y.rule}`},intersections:{pattern:()=>null}});class M_ extends Z2{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=I.intrinsic.string.internal;reduceJsonSchema(Y,Z){if(Y.pattern)return Z.fallback.patternIntersection({code:"patternIntersection",base:Y,pattern:this.rule});return Y.pattern=this.rule,Y}}var dY={implementation:uJ,Node:M_};var d4=(Y,Z)=>{let X=dJ(Y);if(Z&&!Z.includes(X))return A(`Root of kind ${X} should be one of ${Z}`);return X},dJ=(Y)=>{if(y(Y,"root"))return Y.kind;if(typeof Y==="string")return Y[0]==="$"?"alias":(Y in J1)?"domain":"proto";if(typeof Y==="function")return"proto";if(typeof Y!=="object"||Y===null)return A(A_(Y));if("morphs"in Y)return"morph";if("branches"in Y||F0(Y))return"union";if("unit"in Y)return"unit";if("reference"in Y)return"alias";let Z=Object.keys(Y);if(Z.length===0||Z.some((X)=>(X in l8)))return"intersection";if("proto"in Y)return"proto";if("domain"in Y)return"domain";return A(A_(Y))},A_=(Y)=>`${r(Y)} is not a valid type schema`,w_={},cJ=(Y)=>F0(Y)?Y.map((Z)=>Z.collapsibleJson):Y.collapsibleJson,Z1={};I.nodesByRegisteredId=Z1;var cY=(Y)=>{return w_[Y]??=0,`${Y}${++w_[Y]}`},lY=(Y)=>{let Z=G4[Y.kind],X=Z.applyConfig?.(Y.def,Y.$.resolvedConfig)??Y.def,_={},{meta:G,...$}=X,W=G===void 0?{}:typeof G==="string"?{description:G}:G,H=VY($).sort(([J],[z])=>a2(J)?a2(z)?e2(J)-e2(z):1:a2(z)?-1:J<z?-1:1).filter(([J,z])=>{if(J.startsWith("meta.")){let E=J.slice(5);return W[E]=z,!1}return!0});for(let J of H){let z=J[0],E=Z.keys[z];if(!E)return A(`Key ${z} is not valid on ${Y.kind} schema`);let V=E.parse?E.parse(J[1],Y):J[1];if(V!==L1&&(V!==void 0||E.preserveUndefined))_[z]=V}if(Z.reduce&&!Y.prereduced){let J=Z.reduce(_,Y.$);if(J){if(J instanceof P)return J.throw();return lJ(J,W)}}return oY({id:Y.id,kind:Y.kind,inner:_,meta:W,$:Y.$})},oY=({id:Y,kind:Z,inner:X,meta:_,$:G,ignoreCache:$})=>{let W=G4[Z],H=VY(X),Q=[],J={};for(let[v,k]of H){let m=W.keys[v],T=m.serialize??(m.child?cJ:R1);if(J[v]=T(k),m.child===!0){let K=k;if(F0(K))Q.push(...K);else Q.push(K)}else if(typeof m.child==="function")Q.push(...m.child(k))}if(W.finalizeInnerJson)J=W.finalizeInnerJson(J);let z={...J},E={};if(!c1(_))E=i(_,(v,k)=>[v,v==="examples"?k:R1(k)]),z.meta=a8(E,"description",!0);J=a8(J,W.collapsibleKey,!1);let V=JSON.stringify({kind:Z,...J});z=a8(z,W.collapsibleKey,!1);let D=a8(z,W.collapsibleKey,!0),R=JSON.stringify({kind:Z,...z});if(G.nodesByHash[R]&&!$)return G.nodesByHash[R];let w={id:Y,kind:Z,impl:W,inner:X,innerEntries:H,innerJson:J,innerHash:V,meta:_,metaJson:E,json:z,hash:R,collapsibleJson:D,children:Q};if(Z!=="intersection"){for(let v in X)if(v!=="in"&&v!=="out")w[v]=X[v]}let f=new N_[Z](w,G);return G.nodesByHash[R]=f},R_=(Y,Z)=>{if(Y.id===Z)return Y;if(L0(Z1[Z]))_0(`Unexpected attempt to overwrite node id ${Z}`);return oY({id:Z,kind:Y.kind,inner:Y.inner,meta:Y.meta,$:Y.$,ignoreCache:!0})},lJ=(Y,Z,X)=>{if(X&&L0(Z1[X]))_0(`Unexpected attempt to overwrite node id ${X}`);return oY({id:X??cY(Z.alias??Y.kind),kind:Y.kind,inner:Y.inner,meta:Z,$:Y.$})},a8=(Y,Z,X)=>{let _=Object.keys(Y);if(_.length===1&&_[0]===Z){let G=Y[Z];if(X)return G;if(H1(G,"object")&&(Object.keys(G).length===1||Array.isArray(G)))return G}return Y};var c4=(Y,Z,X)=>{if(Y.key!==Z.key)return null;let _=Y.key,G=M0(Y.value,Z.value,X),$=Y.required||Z.required?"required":"optional";if(G instanceof P)if($==="optional")G=I.intrinsic.never.internal;else return G.withPrefixKey(Y.key,Y.required&&Z.required?"required":"optional");if($==="required")return X.$.node("required",{key:_,value:G});let W=Y.hasDefault()?Z.hasDefault()?Y.default===Z.default?Y.default:A(iY(Y.default,Z.default)):Y.default:Z.hasDefault()?Z.default:L1;return X.$.node("optional",{key:_,value:G,default:W})};class l4 extends N1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=I.intrinsic.object.internal;serializedKey=Y2(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=Z0(this.value.flatRefs.map((Y)=>h1([this.key,...Y.path],Y.node)),h1([this.key],this.value));_transform(Y,Z){Z.path.push(this.key);let X=super._transform(Y,Z);return Z.path.pop(),X}hasDefault(){return"default"in this.inner}traverseAllows=(Y,Z)=>{if(this.key in Y)return z1(this.key,()=>this.value.traverseAllows(Y[this.key],Z),Z);return this.optional};traverseApply=(Y,Z)=>{if(this.key in Y)z1(this.key,()=>this.value.traverseApply(Y[this.key],Z),Z);else if(this.hasKind("required"))Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.if(`${this.serializedKey} in data`,()=>Y.traverseKey(this.serializedKey,`data${Y.prop(this.key)}`,this.value)),this.hasKind("required"))Y.else(()=>Y.traversalKind==="Apply"?Y.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Y.return(!1));if(Y.traversalKind==="Allows")Y.return(!0)}}var iY=(Y,Z)=>`Invalid intersection of default values ${r(Y)} & ${r(Z)}`;var oJ=n({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},default:{preserveUndefined:!0}},normalize:(Y)=>Y,reduce:(Y,Z)=>{if(Z.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Y.value.allows(void 0))return Z.node("optional",{...Y,value:Y.value.or(d.undefined)},{prereduced:!0})}},defaults:{description:(Y)=>`${Y.compiledKey}?: ${Y.value.description}`},intersections:{optional:c4}});class I_ extends l4{constructor(...Y){super(...Y);if("default"in this.inner)i4(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:Y,...Z}=this.inner;return this.cacheGetter("outProp",this.$.node("required",Z,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${r(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=rJ(this);defaultValueMorphRef=this.defaultValueMorph&&B0(this.defaultValueMorph)}var o4={implementation:oJ,Node:I_},iJ={},rJ=(Y)=>{if(!Y.hasDefault())return;let Z=`{${Y.compiledKey}: ${Y.value.id} = ${R1(Y.default)}}`;return iJ[Z]??=rY(Y.key,Y.value,Y.default)},rY=(Y,Z,X)=>{if(typeof X==="function")return Z.includesTransform?(G,$)=>{return z1(Y,()=>Z(G[Y]=X(),$),$),G}:(G)=>{return G[Y]=X(),G};let _=Z.includesTransform?Z.assert(X):X;return H1(_,"object")?(G,$)=>{return z1(Y,()=>Z(G[Y]=X,$),$),G}:(G)=>{return G[Y]=_,G}},i4=(Y,Z,X)=>{let _=V2(Z);if(H1(Z,"object")&&!_)A(nJ(X));let G=Y.in(_?Z():Z);if(G instanceof Q1){if(X===null)A(`Default ${G.summary}`);let $=G.transform((W)=>W.transform((H)=>({...H,prefixPath:[X]})));A(`Default for ${$.summary}`)}return Z},nJ=(Y)=>{return`Non-primitive default ${Y===null?"":typeof Y==="number"?`for value at [${Y}] `:`for ${Y2(Y)} `}must be specified as a function like () => ({my: 'object'})`};class I1 extends m4{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,Y1,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Y)=>{let Z=this(Y);if(Z instanceof Q1)return Z;return{value:Z}}}}as(){return this}brand(Y){if(Y==="")return A(sJ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Y,Z){let X=this.branches.map(Y);return Z?.(X)??X}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Y={}){let Z=qY(this.$.resolvedConfig.toJsonSchema,Y);Z.useRefs||=this.isCyclic;let X=typeof Z.dialect==="string"?{$schema:Z.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse(Z)),Z.useRefs)X.$defs=i(this.references,(_,G)=>G.isRoot()&&!G.alwaysExpandJsonSchema?[G.id,G.toResolvedJsonSchema(Z)]:[]);return X}toJsonSchemaRecurse(Y){if(Y.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(Y)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Y){let Z=this.innerToJsonSchema(Y);return Object.assign(Z,this.metaJson)}intersect(Y){let Z=this.$.parseDefinition(Y),X=this.rawIntersect(Z);if(X instanceof P)return X;return this.$.finalize(X)}rawIntersect(Y){return U1(this,Y,this.$)}toNeverIfDisjoint(){return this}and(Y){let Z=this.intersect(Y);return Z instanceof P?Z.throw():Z}rawAnd(Y){let Z=this.rawIntersect(Y);return Z instanceof P?Z.throw():Z}or(Y){let Z=this.$.parseDefinition(Y);return this.$.finalize(this.rawOr(Z))}rawOr(Y){let Z=[...this.branches,...Y.branches];return this.$.node("union",Z)}map(Y){return this.$.schema(this.applyStructuralOperation("map",[Y]))}pick(...Y){return this.$.schema(this.applyStructuralOperation("pick",Y))}omit(...Y){return this.$.schema(this.applyStructuralOperation("omit",Y))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Y=this.applyStructuralOperation("keyof",[]).reduce((Z,X)=>Z.intersect(X).toNeverIfDisjoint(),I.intrinsic.unknown.internal);if(Y.branches.length===0)A(vY(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Y)}get props(){if(this.branches.length!==1)return A(tJ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(Z.distribute((X)=>this.applyStructuralOperation("merge",[K_(X)??A(T_("merge",X.expression))])))}applyStructuralOperation(Y,Z){return this.distribute((X)=>{if(X.equals(I.intrinsic.object)&&Y!=="merge")return X;let _=K_(X);if(!_)A(T_(Y,X.expression));if(Y==="keyof")return _.keyof();if(Y==="get")return _.get(...Z);if(Y==="props")return _.props;let G=Y==="required"?"require":Y==="partial"?"optionalize":Y;return this.$.node("intersection",{...X.inner,structure:_[G](...Z)})})}get(...Y){if(Y[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Y))}extract(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>X.extends(Z)))}exclude(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>!X.extends(Z)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Y){return!(this.intersect(Y)instanceof P)}extends(Y){let Z=this.intersect(Y);return!(Z instanceof P)&&this.equals(Z)}ifExtends(Y){return this.extends(Y)?this:void 0}subsumes(Y){return this.$.parseDefinition(Y).extends(this)}configure(Y,Z="shallow"){return this.configureReferences(Y,Z)}describe(Y,Z="shallow"){return this.configure({description:Y},Z)}optional(){return[this,"?"]}default(Y){return i4(this,Y,null),[this,"=",Y]}from(Y){return this.assert(Y)}_pipe(...Y){let Z=Y.reduce((X,_)=>X.rawPipeOnce(_),this);return this.$.finalize(Z)}tryPipe(...Y){let Z=Y.reduce((X,_)=>X.rawPipeOnce(y(_,"root")?_:(G,$)=>{try{return _(G,$)}catch(W){return $.error({code:"predicate",predicate:_,actual:`aborted due to error:
25
25
  ${W}
26
- `})}}),this);return this.$.finalize(Z)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Y){return this.$.finalize(this.toNode(this.$.parseDefinition(Y)))}toNode(Y){let Z=c4(this,Y,this.$);if(Z instanceof P)return Z.throw();return Z}rawPipeOnce(Y){if(y(Y,"root"))return this.toNode(Y);return this.distribute((Z)=>Z.hasKind("morph")?this.$.node("morph",{in:Z.inner.in,morphs:[...Z.morphs,Y]}):this.$.node("morph",{in:Z,morphs:[Y]}),this.$.parseSchema)}narrow(Y){return this.constrainOut("predicate",Y)}constrain(Y,Z){return this._constrain("root",Y,Z)}constrainIn(Y,Z){return this._constrain("in",Y,Z)}constrainOut(Y,Z){return this._constrain("out",Y,Z)}_constrain(Y,Z,X){let _=this.$.node(Z,X);if(_.isRoot())return _.isUnknown()?this:_0(`Unexpected constraint node ${_}`);let G=Y==="root"?this:this[Y];if(G.hasKind("morph")||_.impliedBasis&&!G.extends(_.impliedBasis))return X_(Z,_.impliedBasis,this);let $=this.$.node("intersection",{[_.kind]:_}),W=Y==="out"?c4(this,$,this.$):F1(this,$,this.$);if(W instanceof P)W.throw();return this.$.finalize(W)}onUndeclaredKey(Y){let Z=typeof Y==="string"?Y:Y.rule,X=typeof Y==="string"?!1:Y.deep;return this.$.finalize(this.transform((_,G)=>_==="structure"?Z==="ignore"?RX(G,{undeclared:1}):{...G,undeclared:Z}:G,X?void 0:{shouldTransform:(_)=>!n1(t2,_.kind)}))}hasEqualMorphs(Y){if(!this.includesTransform&&!Y.includesTransform)return!0;if(!t1(this.shallowMorphs,Y.shallowMorphs))return!1;if(!t1(this.flatMorphs,Y.flatMorphs,{isEqual:(Z,X)=>Z.propString===X.propString&&(Z.node.hasKind("morph")&&X.node.hasKind("morph")?Z.node.hasEqualMorphs(X.node):Z.node.hasKind("intersection")&&X.node.hasKind("intersection")?Z.node.structure?.structuralMorphRef===X.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(Y){return this.onUndeclaredKey({rule:Y,deep:!0})}filter(Y){return this.constrainIn("predicate",Y)}divisibleBy(Y){return this.constrain("divisor",Y)}matching(Y){return this.constrain("pattern",Y)}atLeast(Y){return this.constrain("min",Y)}atMost(Y){return this.constrain("max",Y)}moreThan(Y){return this.constrain("min",W4(Y))}lessThan(Y){return this.constrain("max",W4(Y))}atLeastLength(Y){return this.constrain("minLength",Y)}atMostLength(Y){return this.constrain("maxLength",Y)}moreThanLength(Y){return this.constrain("minLength",W4(Y))}lessThanLength(Y){return this.constrain("maxLength",W4(Y))}exactlyLength(Y){return this.constrain("exactLength",Y)}atOrAfter(Y){return this.constrain("after",Y)}atOrBefore(Y){return this.constrain("before",Y)}laterThan(Y){return this.constrain("after",W4(Y))}earlierThan(Y){return this.constrain("before",W4(Y))}}var nJ="Expected a non-empty brand name after #",W4=(Y)=>typeof Y==="object"&&!(Y instanceof Date)?{...Y,exclusive:!0}:{rule:Y,exclusive:!0},s4=(Y,Z)=>y(Z,"root")?y(Y,"root")?Y.extends(Z):Z.allows(Y):y(Y,"root")?Y.hasUnit(Z):Z===Y,I_=(Y)=>{if(Y.hasKind("morph"))return null;if(Y.hasKind("intersection"))return Y.inner.structure??(Y.basis?.domain==="object"?Y.$.bindReference(N.intrinsic.emptyStructure):null);if(Y.isBasis()&&Y.domain==="object")return Y.$.bindReference(N.intrinsic.emptyStructure);return null},sJ=(Y)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
- ${Y}`,T_=(Y,Z)=>`${Y} operand must be an object (was ${Z})`;var l1=(Y,Z)=>o(i8(Y),(X,_)=>[_,Z]);var tJ=(Y)=>typeof Y==="string"?{reference:Y}:Y,K_=(Y)=>Y instanceof P?N.intrinsic.never.internal:Y,aJ=r({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Y)=>Y.startsWith("$")?Y:`$ark.${Y}`},resolve:{}},normalize:tJ,defaults:{description:(Y)=>Y.reference},intersections:{alias:(Y,Z,X)=>X.$.lazilyResolve(()=>K_(L0(Y.resolution,Z.resolution,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.reference}`),...l1("alias",(Y,Z,X)=>{if(Z.isUnknown())return Y;if(Z.isNever())return Z;if(Z.isBasis()&&!Z.overlaps(N.intrinsic.object))return P.init("assignability",N.intrinsic.object,Z);return X.$.lazilyResolve(()=>K_(L0(Y.resolution,Z,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.id}`)})}});class B_ extends K1{expression=this.reference;structure=void 0;get resolution(){let Y=this._resolve();return _1[this.id]=Y}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let Y=this.reference,Z=_1[Y],X=[];while(y(Z,"context")){if(X.includes(Z.id))return R(eJ(Z.id,X));X.push(Z.id),Z=_1[Z.id]}if(!y(Z,"root"))return _0(`Unexpected resolution for reference ${this.reference}
26
+ `})}}),this);return this.$.finalize(Z)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Y){return this.$.finalize(this.toNode(this.$.parseDefinition(Y)))}toNode(Y){let Z=u4(this,Y,this.$);if(Z instanceof P)return Z.throw();return Z}rawPipeOnce(Y){if(y(Y,"root"))return this.toNode(Y);return this.distribute((Z)=>Z.hasKind("morph")?this.$.node("morph",{in:Z.inner.in,morphs:[...Z.morphs,Y]}):this.$.node("morph",{in:Z,morphs:[Y]}),this.$.parseSchema)}narrow(Y){return this.constrainOut("predicate",Y)}constrain(Y,Z){return this._constrain("root",Y,Z)}constrainIn(Y,Z){return this._constrain("in",Y,Z)}constrainOut(Y,Z){return this._constrain("out",Y,Z)}_constrain(Y,Z,X){let _=this.$.node(Z,X);if(_.isRoot())return _.isUnknown()?this:_0(`Unexpected constraint node ${_}`);let G=Y==="root"?this:this[Y];if(G.hasKind("morph")||_.impliedBasis&&!G.extends(_.impliedBasis))return __(Z,_.impliedBasis,this);let $=this.$.node("intersection",{[_.kind]:_}),W=Y==="out"?u4(this,$,this.$):U1(this,$,this.$);if(W instanceof P)W.throw();return this.$.finalize(W)}onUndeclaredKey(Y){let Z=typeof Y==="string"?Y:Y.rule,X=typeof Y==="string"?!1:Y.deep;return this.$.finalize(this.transform((_,G)=>_==="structure"?Z==="ignore"?NX(G,{undeclared:1}):{...G,undeclared:Z}:G,X?void 0:{shouldTransform:(_)=>!n1(s2,_.kind)}))}hasEqualMorphs(Y){if(!this.includesTransform&&!Y.includesTransform)return!0;if(!t1(this.shallowMorphs,Y.shallowMorphs))return!1;if(!t1(this.flatMorphs,Y.flatMorphs,{isEqual:(Z,X)=>Z.propString===X.propString&&(Z.node.hasKind("morph")&&X.node.hasKind("morph")?Z.node.hasEqualMorphs(X.node):Z.node.hasKind("intersection")&&X.node.hasKind("intersection")?Z.node.structure?.structuralMorphRef===X.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(Y){return this.onUndeclaredKey({rule:Y,deep:!0})}filter(Y){return this.constrainIn("predicate",Y)}divisibleBy(Y){return this.constrain("divisor",Y)}matching(Y){return this.constrain("pattern",Y)}atLeast(Y){return this.constrain("min",Y)}atMost(Y){return this.constrain("max",Y)}moreThan(Y){return this.constrain("min",$4(Y))}lessThan(Y){return this.constrain("max",$4(Y))}atLeastLength(Y){return this.constrain("minLength",Y)}atMostLength(Y){return this.constrain("maxLength",Y)}moreThanLength(Y){return this.constrain("minLength",$4(Y))}lessThanLength(Y){return this.constrain("maxLength",$4(Y))}exactlyLength(Y){return this.constrain("exactLength",Y)}atOrAfter(Y){return this.constrain("after",Y)}atOrBefore(Y){return this.constrain("before",Y)}laterThan(Y){return this.constrain("after",$4(Y))}earlierThan(Y){return this.constrain("before",$4(Y))}}var sJ="Expected a non-empty brand name after #",$4=(Y)=>typeof Y==="object"&&!(Y instanceof Date)?{...Y,exclusive:!0}:{rule:Y,exclusive:!0},r4=(Y,Z)=>y(Z,"root")?y(Y,"root")?Y.extends(Z):Z.allows(Y):y(Y,"root")?Y.hasUnit(Z):Z===Y,K_=(Y)=>{if(Y.hasKind("morph"))return null;if(Y.hasKind("intersection"))return Y.inner.structure??(Y.basis?.domain==="object"?Y.$.bindReference(I.intrinsic.emptyStructure):null);if(Y.isBasis()&&Y.domain==="object")return Y.$.bindReference(I.intrinsic.emptyStructure);return null},tJ=(Y)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
+ ${Y}`,T_=(Y,Z)=>`${Y} operand must be an object (was ${Z})`;var l1=(Y,Z)=>i(o8(Y),(X,_)=>[_,Z]);var aJ=(Y)=>typeof Y==="string"?{reference:Y}:Y,B_=(Y)=>Y instanceof P?I.intrinsic.never.internal:Y,eJ=n({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Y)=>Y.startsWith("$")?Y:`$ark.${Y}`},resolve:{}},normalize:aJ,defaults:{description:(Y)=>Y.reference},intersections:{alias:(Y,Z,X)=>X.$.lazilyResolve(()=>B_(M0(Y.resolution,Z.resolution,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.reference}`),...l1("alias",(Y,Z,X)=>{if(Z.isUnknown())return Y;if(Z.isNever())return Z;if(Z.isBasis()&&!Z.overlaps(I.intrinsic.object))return P.init("assignability",I.intrinsic.object,Z);return X.$.lazilyResolve(()=>B_(M0(Y.resolution,Z,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.id}`)})}});class C_ extends I1{expression=this.reference;structure=void 0;get resolution(){let Y=this._resolve();return Z1[this.id]=Y}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let Y=this.reference,Z=Z1[Y],X=[];while(y(Z,"context")){if(X.includes(Z.id))return A(YQ(Z.id,X));X.push(Z.id),Z=Z1[Z.id]}if(!y(Z,"root"))return _0(`Unexpected resolution for reference ${this.reference}
28
28
  Seen: [${X.join("->")}]
29
- Resolution: ${i(Z)}`);return Z}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Y=this.reference.slice(1),Z=this.$.resolutions[Y];if(typeof Z==="string")return Z;if(y(Z,"root"))return Z.id;return _0(`Unexpected resolution for reference ${this.reference}: ${i(Z)}`)}get defaultShortDescription(){return Q1.object}innerToJsonSchema(Y){return this.resolution.toJsonSchemaRecurse(Y)}traverseAllows=(Y,Z)=>{let X=Z.seen[this.reference];if(X?.includes(Y))return!0;return Z.seen[this.reference]=Z0(X,Y),this.resolution.traverseAllows(Y,Z)};traverseApply=(Y,Z)=>{let X=Z.seen[this.reference];if(X?.includes(Y))return;Z.seen[this.reference]=Z0(X,Y),this.resolution.traverseApply(Y,Z)};compile(Y){let Z=this.resolutionId;Y.if(`ctx.seen.${Z} && ctx.seen.${Z}.includes(data)`,()=>Y.return(!0)),Y.if(`!ctx.seen.${Z}`,()=>Y.line(`ctx.seen.${Z} = []`)),Y.line(`ctx.seen.${Z}.push(data)`),Y.return(Y.invoke(Z))}}var eJ=(Y,Z)=>`Alias '${Y}' has a shallow resolution cycle: ${[...Z,Y].join("->")}`,t4={implementation:aJ,Node:B_};class f2 extends K1{traverseApply=(Y,Z)=>{if(!this.traverseAllows(Y,Z))Z.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return L2(this.errorContext)}compile(Y){if(Y.traversalKind==="Allows")Y.return(this.compiledCondition);else Y.if(this.compiledNegation,()=>Y.line(`${Y.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var YQ=r({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Y)=>typeof Y==="string"?{domain:Y}:n2(Y,"numberAllowsNaN")&&Y.domain!=="number"?R(Y6.writeBadAllowNanMessage(Y.domain)):Y,applyConfig:(Y,Z)=>Y.numberAllowsNaN===void 0&&Y.domain==="number"&&Z.numberAllowsNaN?{...Y,numberAllowsNaN:!0}:Y,defaults:{description:(Y)=>Q1[Y.domain],actual:(Y)=>Number.isNaN(Y)?"NaN":Q1[y0(Y)]},intersections:{domain:(Y,Z)=>Y.domain==="number"&&Z.domain==="number"?Y.numberAllowsNaN?Z:Y:P.init("domain",Y,Z)}});class C_ extends f2{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Y)=>typeof Y==="number"&&!Number.isNaN(Y):(Y)=>y0(Y)===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 Q1[this.domain]}innerToJsonSchema(Y){if(this.domain==="bigint"||this.domain==="symbol")return Y.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var Y6={implementation:YQ,Node:C_,writeBadAllowNanMessage:(Y)=>`numberAllowsNaN may only be specified with domain "number" (was ${Y})`};var ZQ=r({kind:"intersection",hasAssociatedError:!0,normalize:(Y)=>{if(D0(Y))return Y;let{structure:Z,...X}=Y,_=!!Z,G=Z??{},$=o(X,(W,H)=>{if(g0(W,rX)){if(_)R(`Flattened structure key ${W} cannot be specified alongside a root 'structure' key.`);return G[W]=H,[]}return[W,H]});if(y(G,"constraint")||!c1(G))$.structure=G;return $},finalizeInnerJson:({structure:Y,...Z})=>J1(Y,"object")?{...Y,...Z}:Z,keys:{domain:{child:!0,parse:(Y,Z)=>Z.$.node("domain",Y)},proto:{child:!0,parse:(Y,Z)=>Z.$.node("proto",Y)},structure:{child:!0,parse:(Y,Z)=>Z.$.node("structure",Y),serialize:(Y)=>{if(!Y.sequence?.minLength)return Y.collapsibleJson;let{sequence:Z,...X}=Y.collapsibleJson,{minVariadicLength:_,...G}=Z,$=G.variadic&&Object.keys(G).length===1?G.variadic:G;return{...X,sequence:$}}},divisor:{child:!0,parse:t0("divisor")},max:{child:!0,parse:t0("max")},min:{child:!0,parse:t0("min")},maxLength:{child:!0,parse:t0("maxLength")},minLength:{child:!0,parse:t0("minLength")},exactLength:{child:!0,parse:t0("exactLength")},before:{child:!0,parse:t0("before")},after:{child:!0,parse:t0("after")},pattern:{child:!0,parse:t0("pattern")},predicate:{child:!0,parse:t0("predicate")}},reduce:(Y,Z)=>q_({},Y,{$:Z,invert:!1,pipe:!1}),defaults:{description:(Y)=>{if(Y.children.length===0)return"unknown";if(Y.structure)return Y.structure.description;let Z=[];if(Y.basis&&!Y.refinements.some((X)=>X.impl.obviatesBasisDescription))Z.push(Y.basis.description);if(Y.refinements.length){let X=Y.refinements.toSorted((_,G)=>_.kind==="min"&&G.kind==="max"?-1:0).map((_)=>_.description);Z.push(...X)}if(Y.inner.predicate)Z.push(...Y.inner.predicate.map((X)=>X.description));return Z.join(" and ")},expected:(Y)=>` \u25E6 ${Y.errors.map((Z)=>Z.expected).join(`
29
+ Resolution: ${r(Z)}`);return Z}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Y=this.reference.slice(1),Z=this.$.resolutions[Y];if(typeof Z==="string")return Z;if(y(Z,"root"))return Z.id;return _0(`Unexpected resolution for reference ${this.reference}: ${r(Z)}`)}get defaultShortDescription(){return J1.object}innerToJsonSchema(Y){return this.resolution.toJsonSchemaRecurse(Y)}traverseAllows=(Y,Z)=>{let X=Z.seen[this.reference];if(X?.includes(Y))return!0;return Z.seen[this.reference]=Z0(X,Y),this.resolution.traverseAllows(Y,Z)};traverseApply=(Y,Z)=>{let X=Z.seen[this.reference];if(X?.includes(Y))return;Z.seen[this.reference]=Z0(X,Y),this.resolution.traverseApply(Y,Z)};compile(Y){let Z=this.resolutionId;Y.if(`ctx.seen.${Z} && ctx.seen.${Z}.includes(data)`,()=>Y.return(!0)),Y.if(`!ctx.seen.${Z}`,()=>Y.line(`ctx.seen.${Z} = []`)),Y.line(`ctx.seen.${Z}.push(data)`),Y.return(Y.invoke(Z))}}var YQ=(Y,Z)=>`Alias '${Y}' has a shallow resolution cycle: ${[...Z,Y].join("->")}`,n4={implementation:eJ,Node:C_};class x2 extends I1{traverseApply=(Y,Z)=>{if(!this.traverseAllows(Y,Z))Z.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return L2(this.errorContext)}compile(Y){if(Y.traversalKind==="Allows")Y.return(this.compiledCondition);else Y.if(this.compiledNegation,()=>Y.line(`${Y.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var ZQ=n({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Y)=>typeof Y==="string"?{domain:Y}:r2(Y,"numberAllowsNaN")&&Y.domain!=="number"?A(e8.writeBadAllowNanMessage(Y.domain)):Y,applyConfig:(Y,Z)=>Y.numberAllowsNaN===void 0&&Y.domain==="number"&&Z.numberAllowsNaN?{...Y,numberAllowsNaN:!0}:Y,defaults:{description:(Y)=>J1[Y.domain],actual:(Y)=>Number.isNaN(Y)?"NaN":J1[y0(Y)]},intersections:{domain:(Y,Z)=>Y.domain==="number"&&Z.domain==="number"?Y.numberAllowsNaN?Z:Y:P.init("domain",Y,Z)}});class q_ extends x2{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Y)=>typeof Y==="number"&&!Number.isNaN(Y):(Y)=>y0(Y)===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 J1[this.domain]}innerToJsonSchema(Y){if(this.domain==="bigint"||this.domain==="symbol")return Y.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var e8={implementation:ZQ,Node:q_,writeBadAllowNanMessage:(Y)=>`numberAllowsNaN may only be specified with domain "number" (was ${Y})`};var XQ=n({kind:"intersection",hasAssociatedError:!0,normalize:(Y)=>{if(L0(Y))return Y;let{structure:Z,...X}=Y,_=!!Z,G=Z??{},$=i(X,(W,H)=>{if(g0(W,nX)){if(_)A(`Flattened structure key ${W} cannot be specified alongside a root 'structure' key.`);return G[W]=H,[]}return[W,H]});if(y(G,"constraint")||!c1(G))$.structure=G;return $},finalizeInnerJson:({structure:Y,...Z})=>H1(Y,"object")?{...Y,...Z}:Z,keys:{domain:{child:!0,parse:(Y,Z)=>Z.$.node("domain",Y)},proto:{child:!0,parse:(Y,Z)=>Z.$.node("proto",Y)},structure:{child:!0,parse:(Y,Z)=>Z.$.node("structure",Y),serialize:(Y)=>{if(!Y.sequence?.minLength)return Y.collapsibleJson;let{sequence:Z,...X}=Y.collapsibleJson,{minVariadicLength:_,...G}=Z,$=G.variadic&&Object.keys(G).length===1?G.variadic:G;return{...X,sequence:$}}},divisor:{child:!0,parse:s0("divisor")},max:{child:!0,parse:s0("max")},min:{child:!0,parse:s0("min")},maxLength:{child:!0,parse:s0("maxLength")},minLength:{child:!0,parse:s0("minLength")},exactLength:{child:!0,parse:s0("exactLength")},before:{child:!0,parse:s0("before")},after:{child:!0,parse:s0("after")},pattern:{child:!0,parse:s0("pattern")},predicate:{child:!0,parse:s0("predicate")}},reduce:(Y,Z)=>j_({},Y,{$:Z,invert:!1,pipe:!1}),defaults:{description:(Y)=>{if(Y.children.length===0)return"unknown";if(Y.structure)return Y.structure.description;let Z=[];if(Y.basis&&!Y.refinements.some((X)=>X.impl.obviatesBasisDescription))Z.push(Y.basis.description);if(Y.refinements.length){let X=Y.refinements.toSorted((_,G)=>_.kind==="min"&&G.kind==="max"?-1:0).map((_)=>_.description);Z.push(...X)}if(Y.inner.predicate)Z.push(...Y.inner.predicate.map((X)=>X.description));return Z.join(" and ")},expected:(Y)=>` \u25E6 ${Y.errors.map((Z)=>Z.expected).join(`
30
30
  \u25E6 `)}`,problem:(Y)=>`(${Y.actual}) must be...
31
- ${Y.expected}`},intersections:{intersection:(Y,Z,X)=>q_(Y.inner,Z.inner,X),...l1("intersection",(Y,Z,X)=>{if(Y.children.length===0)return Z;let{domain:_,proto:G,...$}=Y.inner,W=G??_,H=W?L0(W,Z,X):Z;return H instanceof P?H:Y?.basis?.equals(H)?Y:Y.$.node("intersection",{...$,[H.kind]:H},{prereduced:!0})})}});class j_ extends K1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((Y)=>Y.isRefinement());structure=this.inner.structure;expression=XQ(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(Y){return this.children.reduce((Z,X)=>X.isBasis()?X.toJsonSchemaRecurse(Y):X.reduceJsonSchema(Z,Y),{})}traverseAllows=(Y,Z)=>this.children.every((X)=>X.traverseAllows(Y,Z));traverseApply=(Y,Z)=>{let X=Z.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.refinements.length){for(let _=0;_<this.refinements.length-1;_++)if(this.refinements[_].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>X)return;if(this.refinements.at(-1).traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.structure){if(this.structure.traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.inner.predicate){for(let _=0;_<this.inner.predicate.length-1;_++)if(this.inner.predicate[_].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>X)return;this.inner.predicate.at(-1).traverseApply(Y,Z)}};compile(Y){if(Y.traversalKind==="Allows"){for(let Z of this.children)Y.check(Z);Y.return(!0);return}if(Y.initializeErrorCount(),this.basis){if(Y.check(this.basis),this.children.length>1)Y.returnIfFail()}if(this.refinements.length){for(let Z=0;Z<this.refinements.length-1;Z++)Y.check(this.refinements[Z]),Y.returnIfFailFast();if(Y.check(this.refinements.at(-1)),this.structure||this.inner.predicate)Y.returnIfFail()}if(this.structure){if(Y.check(this.structure),this.inner.predicate)Y.returnIfFail()}if(this.inner.predicate){for(let Z=0;Z<this.inner.predicate.length-1;Z++)Y.check(this.inner.predicate[Z]),Y.returnIfFail();Y.check(this.inner.predicate.at(-1))}}}var rY={implementation:ZQ,Node:j_},XQ=(Y)=>{let Z=Y.structure?.expression||`${Y.basis&&!Y.refinements.some((X)=>X.impl.obviatesBasisExpression)?Y.basis.nestableExpression+" ":""}${Y.refinements.map((X)=>X.expression).join(" & ")}`||"unknown";if(Z==="Array == 0")Z="[]";return Z},q_=(Y,Z,X)=>{let _={},G=Y.proto??Y.domain,$=Z.proto??Z.domain,W=G?$?L0(G,$,X):G:$;if(W instanceof P)return W;if(W)_[W.kind]=W;return X4({kind:"intersection",baseInner:_,l:_4(Y),r:_4(Z),roots:[],ctx:X})};var _Q=r({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},morphs:{parse:E2,serialize:(Y)=>Y.map((Z)=>y(Z,"root")?Z.json:B0(Z))},declaredIn:{child:!1,serialize:(Y)=>Y.json},declaredOut:{child:!1,serialize:(Y)=>Y.json}},normalize:(Y)=>Y,defaults:{description:(Y)=>`a morph from ${Y.in.description} to ${Y.out?.description??"unknown"}`},intersections:{morph:(Y,Z,X)=>{if(!Y.hasEqualMorphs(Z))return R(GQ(Y.expression,Z.expression));let _=L0(Y.in,Z.in,X);if(_ instanceof P)return _;let G={morphs:Y.morphs};if(Y.declaredIn||Z.declaredIn){let $=L0(Y.in,Z.in,X);if($ instanceof P)return $.throw();else G.declaredIn=$}if(Y.declaredOut||Z.declaredOut){let $=L0(Y.out,Z.out,X);if($ instanceof P)return $.throw();else G.declaredOut=$}return _.distribute(($)=>X.$.node("morph",{...G,in:$}),X.$.parseSchema)},...l1("morph",(Y,Z,X)=>{let _=Y.inner.in?L0(Y.inner.in,Z,X):Z;return _ instanceof P?_:_.equals(Y.inner.in)?Y:X.$.node("morph",{...Y.inner,in:_})})}});class S_ extends K1{serializedMorphs=this.morphs.map(B0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=y(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??N.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??N.intrinsic.unknown.internal}declareIn(Y){return this.$.node("morph",{...this.inner,declaredIn:Y})}declareOut(Y){return this.$.node("morph",{...this.inner,declaredOut:Y})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(Y){return Y.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(Y),out:this.introspectableOut?.toJsonSchemaRecurse(Y)??null})}compile(Y){if(Y.traversalKind==="Allows"){if(!this.introspectableIn)return;Y.return(Y.invoke(this.introspectableIn));return}if(this.introspectableIn)Y.line(Y.invoke(this.introspectableIn));Y.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(Y,Z)=>!this.introspectableIn||this.introspectableIn.traverseAllows(Y,Z);traverseApply=(Y,Z)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(Y,Z);Z.queueMorphs(this.morphs)};hasEqualMorphs(Y){return t1(this.morphs,Y.morphs,{isEqual:(Z,X)=>Z===X||y(Z,"root")&&y(X,"root")&&Z.equals(X)})}}var nY={implementation:_Q,Node:S_},GQ=(Y,Z)=>`The intersection of distinct morphs at a single path is indeterminate:
31
+ ${Y.expected}`},intersections:{intersection:(Y,Z,X)=>j_(Y.inner,Z.inner,X),...l1("intersection",(Y,Z,X)=>{if(Y.children.length===0)return Z;let{domain:_,proto:G,...$}=Y.inner,W=G??_,H=W?M0(W,Z,X):Z;return H instanceof P?H:Y?.basis?.equals(H)?Y:Y.$.node("intersection",{...$,[H.kind]:H},{prereduced:!0})})}});class S_ extends I1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((Y)=>Y.isRefinement());structure=this.inner.structure;expression=_Q(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(Y){return this.children.reduce((Z,X)=>X.isBasis()?X.toJsonSchemaRecurse(Y):X.reduceJsonSchema(Z,Y),{})}traverseAllows=(Y,Z)=>this.children.every((X)=>X.traverseAllows(Y,Z));traverseApply=(Y,Z)=>{let X=Z.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.refinements.length){for(let _=0;_<this.refinements.length-1;_++)if(this.refinements[_].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>X)return;if(this.refinements.at(-1).traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.structure){if(this.structure.traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.inner.predicate){for(let _=0;_<this.inner.predicate.length-1;_++)if(this.inner.predicate[_].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>X)return;this.inner.predicate.at(-1).traverseApply(Y,Z)}};compile(Y){if(Y.traversalKind==="Allows"){for(let Z of this.children)Y.check(Z);Y.return(!0);return}if(Y.initializeErrorCount(),this.basis){if(Y.check(this.basis),this.children.length>1)Y.returnIfFail()}if(this.refinements.length){for(let Z=0;Z<this.refinements.length-1;Z++)Y.check(this.refinements[Z]),Y.returnIfFailFast();if(Y.check(this.refinements.at(-1)),this.structure||this.inner.predicate)Y.returnIfFail()}if(this.structure){if(Y.check(this.structure),this.inner.predicate)Y.returnIfFail()}if(this.inner.predicate){for(let Z=0;Z<this.inner.predicate.length-1;Z++)Y.check(this.inner.predicate[Z]),Y.returnIfFail();Y.check(this.inner.predicate.at(-1))}}}var nY={implementation:XQ,Node:S_},_Q=(Y)=>{let Z=Y.structure?.expression||`${Y.basis&&!Y.refinements.some((X)=>X.impl.obviatesBasisExpression)?Y.basis.nestableExpression+" ":""}${Y.refinements.map((X)=>X.expression).join(" & ")}`||"unknown";if(Z==="Array == 0")Z="[]";return Z},j_=(Y,Z,X)=>{let _={},G=Y.proto??Y.domain,$=Z.proto??Z.domain,W=G?$?M0(G,$,X):G:$;if(W instanceof P)return W;if(W)_[W.kind]=W;return Z4({kind:"intersection",baseInner:_,l:X4(Y),r:X4(Z),roots:[],ctx:X})};var GQ=n({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},morphs:{parse:E2,serialize:(Y)=>Y.map((Z)=>y(Z,"root")?Z.json:B0(Z))},declaredIn:{child:!1,serialize:(Y)=>Y.json},declaredOut:{child:!1,serialize:(Y)=>Y.json}},normalize:(Y)=>Y,defaults:{description:(Y)=>`a morph from ${Y.in.description} to ${Y.out?.description??"unknown"}`},intersections:{morph:(Y,Z,X)=>{if(!Y.hasEqualMorphs(Z))return A($Q(Y.expression,Z.expression));let _=M0(Y.in,Z.in,X);if(_ instanceof P)return _;let G={morphs:Y.morphs};if(Y.declaredIn||Z.declaredIn){let $=M0(Y.in,Z.in,X);if($ instanceof P)return $.throw();else G.declaredIn=$}if(Y.declaredOut||Z.declaredOut){let $=M0(Y.out,Z.out,X);if($ instanceof P)return $.throw();else G.declaredOut=$}return _.distribute(($)=>X.$.node("morph",{...G,in:$}),X.$.parseSchema)},...l1("morph",(Y,Z,X)=>{let _=Y.inner.in?M0(Y.inner.in,Z,X):Z;return _ instanceof P?_:_.equals(Y.inner.in)?Y:X.$.node("morph",{...Y.inner,in:_})})}});class P_ extends I1{serializedMorphs=this.morphs.map(B0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=y(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??I.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??I.intrinsic.unknown.internal}declareIn(Y){return this.$.node("morph",{...this.inner,declaredIn:Y})}declareOut(Y){return this.$.node("morph",{...this.inner,declaredOut:Y})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(Y){return Y.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(Y),out:this.introspectableOut?.toJsonSchemaRecurse(Y)??null})}compile(Y){if(Y.traversalKind==="Allows"){if(!this.introspectableIn)return;Y.return(Y.invoke(this.introspectableIn));return}if(this.introspectableIn)Y.line(Y.invoke(this.introspectableIn));Y.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(Y,Z)=>!this.introspectableIn||this.introspectableIn.traverseAllows(Y,Z);traverseApply=(Y,Z)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(Y,Z);Z.queueMorphs(this.morphs)};hasEqualMorphs(Y){return t1(this.morphs,Y.morphs,{isEqual:(Z,X)=>Z===X||y(Z,"root")&&y(X,"root")&&Z.equals(X)})}}var sY={implementation:GQ,Node:P_},$Q=(Y,Z)=>`The intersection of distinct morphs at a single path is indeterminate:
32
32
  Left: ${Y}
33
- Right: ${Z}`;var $Q=r({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Y)=>x4(Y)??I1(Y)},dateAllowsInvalid:{}},normalize:(Y)=>{let Z=typeof Y==="string"?{proto:P2[Y]}:typeof Y==="function"?D0(Y)?Y:{proto:Y}:typeof Y.proto==="string"?{...Y,proto:P2[Y.proto]}:Y;if(typeof Z.proto!=="function")R(a4.writeInvalidSchemaMessage(Z.proto));if(n2(Z,"dateAllowsInvalid")&&Z.proto!==Date)R(a4.writeBadInvalidDateMessage(Z.proto));return Z},applyConfig:(Y,Z)=>{if(Y.dateAllowsInvalid===void 0&&Y.proto===Date&&Z.dateAllowsInvalid)return{...Y,dateAllowsInvalid:!0};return Y},defaults:{description:(Y)=>Y.builtinName?KX[Y.builtinName]:`an instance of ${Y.proto.name}`,actual:(Y)=>Y instanceof Date&&Y.toString()==="Invalid Date"?"an invalid Date":v4(Y)},intersections:{proto:(Y,Z)=>Y.proto===Date&&Z.proto===Date?Y.dateAllowsInvalid?Z:Y:MY(Y.proto,Z.proto)?Y:MY(Z.proto,Y.proto)?Z:P.init("proto",Y,Z),domain:(Y,Z)=>Z.domain==="object"?Y:P.init("domain",N.intrinsic.object.internal,Z)}});class P_ extends f2{builtinName=x4(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(Y)=>Y instanceof Date&&Y.toString()!=="Invalid Date":(Y)=>Y instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(Y){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return Y.fallback.date?.({code:"date",base:{}})??Y.fallback.proto({code:"proto",base:{},proto:this.proto});default:return Y.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 a4={implementation:$Q,Node:P_,writeBadInvalidDateMessage:(Y)=>`dateAllowsInvalid may only be specified with constructor Date (was ${Y.name})`,writeInvalidSchemaMessage:(Y)=>`instanceOf operand must be a function (was ${y0(Y)})`};var WQ=r({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Y,Z)=>{let X=[];for(let _ of Y){let G=y(_,"root")?_.branches:Z.$.parseSchema(_).branches;for(let $ of G)if($.hasKind("morph")){let W=X.findIndex((H)=>H.hasKind("morph")&&H.hasEqualMorphs($));if(W===-1)X.push($);else{let H=X[W];X[W]=Z.$.node("morph",{...H.inner,in:H.in.rawOr($.in)})}}else X.push($)}if(!Z.def.ordered)X.sort((_,G)=>_.hash<G.hash?-1:1);return X}}},normalize:(Y)=>F0(Y)?{branches:Y}:Y,reduce:(Y,Z)=>{let X=DQ(Y);if(X.length===1)return X[0];if(X.length===Y.branches.length)return;return Z.node("union",{...Y,branches:X},{prereduced:!0})},defaults:{description:(Y)=>Y.distribute((Z)=>Z.description,H4),expected:(Y)=>{let Z=LX(Y.errors,"propString"),X=Object.entries(Z).map(([_,G])=>{let $=[];for(let Q of G)d1($,Q.expected);let W=H4($),H=G.every((Q)=>Q.actual===G[0].actual)?G[0].actual:i(G[0].data);return`${_&&`${_} `}must be ${W}${H&&` (was ${H})`}`});return H4(X)},problem:(Y)=>Y.expected,message:(Y)=>Y.problem},intersections:{union:(Y,Z,X)=>{if(Y.isNever!==Z.isNever)return P.init("presence",Y,Z);let _;if(Y.ordered){if(Z.ordered)R(MQ(Y.expression,Z.expression));if(_=sY(Z.branches,Y.branches,X),_ instanceof P)_.invert()}else _=sY(Y.branches,Z.branches,X);if(_ instanceof P)return _;return X.$.parseSchema(Y.ordered||Z.ordered?{branches:_,ordered:!0}:{branches:_})},...l1("union",(Y,Z,X)=>{let _=sY(Y.branches,[Z],X);if(_ instanceof P)return _;if(_.length===1)return _[0];return X.$.parseSchema(Y.ordered?{branches:_,ordered:!0}:{branches:_})})}});class f_ extends K1{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let Y=[],Z=-1;for(let X of this.branches){if(X.hasKind("unit")&&X.domain==="boolean"){if(Z===-1)Z=Y.length,Y.push(X);else Y[Z]=N.intrinsic.boolean;continue}Y.push(X)}return Y}unitBranches=this.branches.filter((Y)=>Y.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?EQ(this.discriminant):null;expression=this.distribute((Y)=>Y.nestableExpression,VQ);createBranchedOptimisticRootApply(){return(Y,Z)=>{let X=this.traverseOptimistic(Y);if(X!==L1)return X;let _=new f1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)}}get shallowMorphs(){return this.branches.reduce((Y,Z)=>d1(Y,Z.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Y)=>Y.defaultShortDescription,H4)}innerToJsonSchema(Y){if(this.branchGroups.length===1&&this.branchGroups[0].equals(N.intrinsic.boolean))return{type:"boolean"};let Z=this.branchGroups.map((X)=>X.toJsonSchemaRecurse(Y));if(Z.every((X)=>Object.keys(X).length===1&&n2(X,"const")))return{enum:Z.map((X)=>X.const)};return{anyOf:Z}}traverseAllows=(Y,Z)=>this.branches.some((X)=>X.traverseAllows(Y,Z));traverseApply=(Y,Z)=>{let X=[];for(let _=0;_<this.branches.length;_++){if(Z.pushBranch(),this.branches[_].traverseApply(Y,Z),!Z.hasError()){if(this.branches[_].includesTransform)return Z.queuedMorphs.push(...Z.popBranch().queuedMorphs);return Z.popBranch()}X.push(Z.popBranch().error)}Z.errorFromNodeContext({code:"union",errors:X,meta:this.meta})};traverseOptimistic=(Y)=>{for(let Z=0;Z<this.branches.length;Z++){let X=this.branches[Z];if(X.traverseAllows(Y)){if(X.contextFreeMorph)return X.contextFreeMorph(Y);return Y}}return L1};compile(Y){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(Y);let Z=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")Z=`typeof ${Z} === "object" ? ${Z} === null ? "null" : "object" : typeof ${Z} === "function" ? "object" : typeof ${Z}`;let X=this.discriminant.cases,_=Object.keys(X),{optimistic:G}=Y;if(Y.optimistic=!1,Y.block(`switch(${Z})`,()=>{for(let J in X){let U=X[J],F=J==="default"?J:`case ${J}`;Y.line(`${F}: return ${U===!0?G?Y.data:U:G?`${Y.invoke(U)} ? ${U.contextFreeMorph?`${B0(U.contextFreeMorph)}(${Y.data})`:Y.data} : "${L1}"`:Y.invoke(U)}`)}return Y}),Y.traversalKind==="Allows"){Y.return(G?`"${L1}"`:!1);return}let $=H4(this.discriminant.kind==="domain"?_.map((J)=>{let U=J.slice(1,-1);return U==="function"?Q1.object:Q1[U]}):_),W=this.discriminant.path.map((J)=>typeof J==="symbol"?B0(J):JSON.stringify(J)),H=JSON.stringify($),Q=this.discriminant.kind==="domain"?`${zQ}[${Z}]`:`${FQ}(${Z})`;Y.line(`ctx.errorFromNodeContext({
33
+ Right: ${Z}`;var WQ=n({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Y)=>P4(Y)??R1(Y)},dateAllowsInvalid:{}},normalize:(Y)=>{let Z=typeof Y==="string"?{proto:S2[Y]}:typeof Y==="function"?L0(Y)?Y:{proto:Y}:typeof Y.proto==="string"?{...Y,proto:S2[Y.proto]}:Y;if(typeof Z.proto!=="function")A(s4.writeInvalidSchemaMessage(Z.proto));if(r2(Z,"dateAllowsInvalid")&&Z.proto!==Date)A(s4.writeBadInvalidDateMessage(Z.proto));return Z},applyConfig:(Y,Z)=>{if(Y.dateAllowsInvalid===void 0&&Y.proto===Date&&Z.dateAllowsInvalid)return{...Y,dateAllowsInvalid:!0};return Y},defaults:{description:(Y)=>Y.builtinName?BX[Y.builtinName]:`an instance of ${Y.proto.name}`,actual:(Y)=>Y instanceof Date&&Y.toString()==="Invalid Date"?"an invalid Date":S4(Y)},intersections:{proto:(Y,Z)=>Y.proto===Date&&Z.proto===Date?Y.dateAllowsInvalid?Z:Y:AY(Y.proto,Z.proto)?Y:AY(Z.proto,Y.proto)?Z:P.init("proto",Y,Z),domain:(Y,Z)=>Z.domain==="object"?Y:P.init("domain",I.intrinsic.object.internal,Z)}});class v_ extends x2{builtinName=P4(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(Y)=>Y instanceof Date&&Y.toString()!=="Invalid Date":(Y)=>Y instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(Y){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return Y.fallback.date?.({code:"date",base:{}})??Y.fallback.proto({code:"proto",base:{},proto:this.proto});default:return Y.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 s4={implementation:WQ,Node:v_,writeBadInvalidDateMessage:(Y)=>`dateAllowsInvalid may only be specified with constructor Date (was ${Y.name})`,writeInvalidSchemaMessage:(Y)=>`instanceOf operand must be a function (was ${y0(Y)})`};var HQ=n({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Y,Z)=>{let X=[];for(let _ of Y){let G=y(_,"root")?_.branches:Z.$.parseSchema(_).branches;for(let $ of G)if($.hasKind("morph")){let W=X.findIndex((H)=>H.hasKind("morph")&&H.hasEqualMorphs($));if(W===-1)X.push($);else{let H=X[W];X[W]=Z.$.node("morph",{...H.inner,in:H.in.rawOr($.in)})}}else X.push($)}if(!Z.def.ordered)X.sort((_,G)=>_.hash<G.hash?-1:1);return X}}},normalize:(Y)=>F0(Y)?{branches:Y}:Y,reduce:(Y,Z)=>{let X=LQ(Y);if(X.length===1)return X[0];if(X.length===Y.branches.length)return;return Z.node("union",{...Y,branches:X},{prereduced:!0})},defaults:{description:(Y)=>Y.distribute((Z)=>Z.description,W4),expected:(Y)=>{let Z=MX(Y.errors,"propString"),X=Object.entries(Z).map(([_,G])=>{let $=[];for(let Q of G)d1($,Q.expected);let W=W4($),H=G.every((Q)=>Q.actual===G[0].actual)?G[0].actual:r(G[0].data);return`${_&&`${_} `}must be ${W}${H&&` (was ${H})`}`});return W4(X)},problem:(Y)=>Y.expected,message:(Y)=>Y.problem},intersections:{union:(Y,Z,X)=>{if(Y.isNever!==Z.isNever)return P.init("presence",Y,Z);let _;if(Y.ordered){if(Z.ordered)A(AQ(Y.expression,Z.expression));if(_=tY(Z.branches,Y.branches,X),_ instanceof P)_.invert()}else _=tY(Y.branches,Z.branches,X);if(_ instanceof P)return _;return X.$.parseSchema(Y.ordered||Z.ordered?{branches:_,ordered:!0}:{branches:_})},...l1("union",(Y,Z,X)=>{let _=tY(Y.branches,[Z],X);if(_ instanceof P)return _;if(_.length===1)return _[0];return X.$.parseSchema(Y.ordered?{branches:_,ordered:!0}:{branches:_})})}});class h_ extends I1{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let Y=[],Z=-1;for(let X of this.branches){if(X.hasKind("unit")&&X.domain==="boolean"){if(Z===-1)Z=Y.length,Y.push(X);else Y[Z]=I.intrinsic.boolean;continue}Y.push(X)}return Y}unitBranches=this.branches.filter((Y)=>Y.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?VQ(this.discriminant):null;expression=this.distribute((Y)=>Y.nestableExpression,DQ);createBranchedOptimisticRootApply(){return(Y,Z)=>{let X=this.traverseOptimistic(Y);if(X!==L1)return X;let _=new f1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)}}get shallowMorphs(){return this.branches.reduce((Y,Z)=>d1(Y,Z.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Y)=>Y.defaultShortDescription,W4)}innerToJsonSchema(Y){if(this.branchGroups.length===1&&this.branchGroups[0].equals(I.intrinsic.boolean))return{type:"boolean"};let Z=this.branchGroups.map((X)=>X.toJsonSchemaRecurse(Y));if(Z.every((X)=>Object.keys(X).length===1&&r2(X,"const")))return{enum:Z.map((X)=>X.const)};return{anyOf:Z}}traverseAllows=(Y,Z)=>this.branches.some((X)=>X.traverseAllows(Y,Z));traverseApply=(Y,Z)=>{let X=[];for(let _=0;_<this.branches.length;_++){if(Z.pushBranch(),this.branches[_].traverseApply(Y,Z),!Z.hasError()){if(this.branches[_].includesTransform)return Z.queuedMorphs.push(...Z.popBranch().queuedMorphs);return Z.popBranch()}X.push(Z.popBranch().error)}Z.errorFromNodeContext({code:"union",errors:X,meta:this.meta})};traverseOptimistic=(Y)=>{for(let Z=0;Z<this.branches.length;Z++){let X=this.branches[Z];if(X.traverseAllows(Y)){if(X.contextFreeMorph)return X.contextFreeMorph(Y);return Y}}return L1};compile(Y){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(Y);let Z=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")Z=`typeof ${Z} === "object" ? ${Z} === null ? "null" : "object" : typeof ${Z} === "function" ? "object" : typeof ${Z}`;let X=this.discriminant.cases,_=Object.keys(X),{optimistic:G}=Y;if(Y.optimistic=!1,Y.block(`switch(${Z})`,()=>{for(let J in X){let z=X[J],E=J==="default"?J:`case ${J}`;Y.line(`${E}: return ${z===!0?G?Y.data:z:G?`${Y.invoke(z)} ? ${z.contextFreeMorph?`${B0(z.contextFreeMorph)}(${Y.data})`:Y.data} : "${L1}"`:Y.invoke(z)}`)}return Y}),Y.traversalKind==="Allows"){Y.return(G?`"${L1}"`:!1);return}let $=W4(this.discriminant.kind==="domain"?_.map((J)=>{let z=J.slice(1,-1);return z==="function"?J1.object:J1[z]}):_),W=this.discriminant.path.map((J)=>typeof J==="symbol"?B0(J):JSON.stringify(J)),H=JSON.stringify($),Q=this.discriminant.kind==="domain"?`${FQ}[${Z}]`:`${EQ}(${Z})`;Y.line(`ctx.errorFromNodeContext({
34
34
  code: "predicate",
35
35
  expected: ${H},
36
36
  actual: ${Q},
37
37
  relativePath: [${W}],
38
38
  meta: ${this.compiledMeta}
39
- })`)}compileIndiscriminable(Y){if(Y.traversalKind==="Apply"){Y.const("errors","[]");for(let Z of this.branches)Y.line("ctx.pushBranch()").line(Y.invoke(Z)).if("!ctx.hasError()",()=>Y.return(Z.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Y.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:Z}=Y;Y.optimistic=!1;for(let X of this.branches)Y.if(`${Y.invoke(X)}`,()=>Y.return(Z?X.contextFreeMorph?`${B0(X.contextFreeMorph)}(${Y.data})`:Y.data:!0));Y.return(Z?`"${L1}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let G=o(this.unitBranches,($,W)=>[`${W.in.serializedValue}`,W.hasKind("morph")?W:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:G}}let Y=[];for(let G=0;G<this.branches.length-1;G++){let $=this.branches[G];for(let W=G+1;W<this.branches.length;W++){let H=this.branches[W],Q=F1($.in,H.in,$.$);if(!(Q instanceof P))continue;for(let J of Q){if(!J.kind||J.optional)continue;let U,F;if(J.kind==="domain"){let{l:D,r:A}=J;U=`"${typeof D==="string"?D:D.domain}"`,F=`"${typeof A==="string"?A:A.domain}"`}else if(J.kind==="unit")U=J.l.serializedValue,F=J.r.serializedValue;else continue;let V=Y.find((D)=>t1(D.path,J.path)&&D.kind===J.kind);if(!V)Y.push({kind:J.kind,cases:{[U]:{branchIndices:[G],condition:J.l},[F]:{branchIndices:[W],condition:J.r}},path:J.path});else{if(V.cases[U])V.cases[U].branchIndices=d1(V.cases[U].branchIndices,G);else V.cases[U]??={branchIndices:[G],condition:J.l};if(V.cases[F])V.cases[F].branchIndices=d1(V.cases[F].branchIndices,W);else V.cases[F]??={branchIndices:[W],condition:J.r}}}}}let Z=this.ordered?QQ(Y,this.branches):Y;if(!Z.length)return null;let X=HQ(Z,this),_={};for(let G in X.best.cases){let $=JQ(X,G);if($===null){_[G]=!0;continue}if($.length===this.branches.length)return null;if(this.ordered)$.sort((Q,J)=>Q.originalIndex-J.originalIndex);let W=$.map((Q)=>Q.branch),H=W.length===1?W[0]:this.$.node("union",this.ordered?{branches:W,ordered:!0}:W);Object.assign(this.referencesById,H.referencesById),_[G]=H}if(X.defaultEntries.length){let G=X.defaultEntries.map(($)=>$.branch);_.default=this.$.node("union",this.ordered?{branches:G,ordered:!0}:G,{prereduced:!0}),Object.assign(this.referencesById,_.default.referencesById)}return Object.assign(X.location,{cases:_})}}var HQ=(Y,Z)=>{let X=Y.sort(($,W)=>Object.keys(W.cases).length-Object.keys($.cases).length)[0],_={kind:X.kind,path:X.path,optionallyChainedPropString:h_(X.path)},G=Z.branches.map(($,W)=>({originalIndex:W,branch:$}));return{best:X,location:_,defaultEntries:G,node:Z}},JQ=(Y,Z)=>{let X=Y.best.cases[Z],_=UQ(X.condition,Y.location.path,Y.node.$),G=[],$=[];for(let W=0;W<Y.defaultEntries.length;W++){let H=Y.defaultEntries[W];if(X.branchIndices.includes(H.originalIndex)){let Q=v_(Y.node.branches[H.originalIndex],Y.location);if(Q===null)G=null;else G?.push({originalIndex:H.originalIndex,branch:Q})}else if(H.branch.hasKind("alias")&&_.hasKind("domain")&&_.domain==="object")G?.push(H);else{if(H.branch.in.overlaps(_)){let Q=v_(H.branch,Y.location);G?.push({originalIndex:H.originalIndex,branch:Q})}$.push(H)}}return Y.defaultEntries=$,G},QQ=(Y,Z)=>{return Y.filter((_)=>{let G=Object.values(_.cases).map(($)=>$.branchIndices);for(let $=0;$<G.length-1;$++){let W=G[$];for(let H=$+1;H<G.length;H++){let Q=G[H];for(let J of W)for(let U of Q)if(J>U){if(Z[J].overlaps(Z[U]))return!1}}}return!0})},UQ=(Y,Z,X)=>{let _=Y==="undefined"?X.node("unit",{unit:void 0}):Y==="null"?X.node("unit",{unit:null}):Y==="boolean"?X.units([!0,!1]):Y;for(let G=Z.length-1;G>=0;G--){let $=Z[G];_=X.node("intersection",typeof $==="number"?{proto:"Array",sequence:[...VX($).map((W)=>({})),_]}:{domain:"object",required:[{key:$,value:_}]})}return _},h_=(Y)=>Y.reduce((Z,X)=>Z+KY(X,!0),"data"),zQ=B0(MX),FQ=B0(i),tY={implementation:WQ,Node:f_},EQ=(Y)=>({kind:Y.kind,path:Y.path.map((Z)=>typeof Z==="string"?Z:Y2(Z)),cases:o(Y.cases,(Z,X)=>[Z,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),OQ={delimiter:" | ",finalDelimiter:" | "},VQ=(Y)=>H4(Y,OQ),H4=(Y,Z)=>{let X=Z?.delimiter??", ",_=Z?.finalDelimiter??" or ";if(Y.length===0)return"never";if(Y.length===1)return Y[0];if(Y.length===2&&Y[0]==="false"&&Y[1]==="true"||Y[0]==="true"&&Y[1]==="false")return"boolean";let G={},$=Y.filter((H)=>G[H]?!1:G[H]=!0),W=$.pop();return`${$.join(X)}${$.length?_:""}${W}`},sY=(Y,Z,X)=>{let _=Z.map(()=>[]);for(let $=0;$<Y.length;$++){let W={};for(let H=0;H<Z.length;H++){if(_[H]===null)continue;if(Y[$].equals(Z[H])){_[H]=null,W={};break}let Q=L0(Y[$],Z[H],X);if(Q instanceof P)continue;if(Q.equals(Y[$])){_[H].push(Y[$]),W={};break}if(Q.equals(Z[H]))_[H]=null;else W[H]=Q}for(let H in W)_[H][$]=W[H]}let G=_.flatMap(($,W)=>$?.flatMap((H)=>H.branches)??Z[W]);return G.length===0?P.init("union",Y,Z):G},DQ=({branches:Y,ordered:Z})=>{if(Y.length<2)return Y;let X=Y.map(()=>!0);for(let _=0;_<Y.length;_++)for(let G=_+1;G<Y.length&&X[_]&&X[G];G++){if(Y[_].equals(Y[G])){X[G]=!1;continue}let $=F1(Y[_].in,Y[G].in,Y[0].$);if($ instanceof P)continue;if(!Z)LQ(Y[_],Y[G]);if($.equals(Y[_].in))X[_]=!!Z;else if($.equals(Y[G].in))X[G]=!1}return Y.filter((_,G)=>X[G])},LQ=(Y,Z)=>{if(!Y.includesTransform&&!Z.includesTransform)return;if(!t1(Y.shallowMorphs,Z.shallowMorphs))R(x_(Y.expression,Z.expression));if(!t1(Y.flatMorphs,Z.flatMorphs,{isEqual:(X,_)=>X.propString===_.propString&&(X.node.hasKind("morph")&&_.node.hasKind("morph")?X.node.hasEqualMorphs(_.node):X.node.hasKind("intersection")&&_.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===_.node.structure?.structuralMorphRef:!1)}))R(x_(Y.expression,Z.expression))},v_=(Y,Z)=>Y.transform((X,_)=>{if(X==="domain"||X==="unit")return null;return _},{shouldTransform:(X,_)=>{let G=h_(_.path);if(!Z.optionallyChainedPropString.startsWith(G))return!1;if(X.hasKind("domain")&&X.domain==="object")return!0;if((X.hasKind("domain")||Z.kind==="unit")&&G===Z.optionallyChainedPropString)return!0;return X.children.length!==0&&X.kind!=="index"}}),x_=(Y,Z)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
39
+ })`)}compileIndiscriminable(Y){if(Y.traversalKind==="Apply"){Y.const("errors","[]");for(let Z of this.branches)Y.line("ctx.pushBranch()").line(Y.invoke(Z)).if("!ctx.hasError()",()=>Y.return(Z.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Y.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:Z}=Y;Y.optimistic=!1;for(let X of this.branches)Y.if(`${Y.invoke(X)}`,()=>Y.return(Z?X.contextFreeMorph?`${B0(X.contextFreeMorph)}(${Y.data})`:Y.data:!0));Y.return(Z?`"${L1}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let G=i(this.unitBranches,($,W)=>[`${W.in.serializedValue}`,W.hasKind("morph")?W:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:G}}let Y=[];for(let G=0;G<this.branches.length-1;G++){let $=this.branches[G];for(let W=G+1;W<this.branches.length;W++){let H=this.branches[W],Q=U1($.in,H.in,$.$);if(!(Q instanceof P))continue;for(let J of Q){if(!J.kind||J.optional)continue;let z,E;if(J.kind==="domain"){let{l:D,r:R}=J;z=`"${typeof D==="string"?D:D.domain}"`,E=`"${typeof R==="string"?R:R.domain}"`}else if(J.kind==="unit")z=J.l.serializedValue,E=J.r.serializedValue;else continue;let V=Y.find((D)=>t1(D.path,J.path)&&D.kind===J.kind);if(!V)Y.push({kind:J.kind,cases:{[z]:{branchIndices:[G],condition:J.l},[E]:{branchIndices:[W],condition:J.r}},path:J.path});else{if(V.cases[z])V.cases[z].branchIndices=d1(V.cases[z].branchIndices,G);else V.cases[z]??={branchIndices:[G],condition:J.l};if(V.cases[E])V.cases[E].branchIndices=d1(V.cases[E].branchIndices,W);else V.cases[E]??={branchIndices:[W],condition:J.r}}}}}let Z=this.ordered?zQ(Y,this.branches):Y;if(!Z.length)return null;let X=JQ(Z,this),_={};for(let G in X.best.cases){let $=QQ(X,G);if($===null){_[G]=!0;continue}if($.length===this.branches.length)return null;if(this.ordered)$.sort((Q,J)=>Q.originalIndex-J.originalIndex);let W=$.map((Q)=>Q.branch),H=W.length===1?W[0]:this.$.node("union",this.ordered?{branches:W,ordered:!0}:W);Object.assign(this.referencesById,H.referencesById),_[G]=H}if(X.defaultEntries.length){let G=X.defaultEntries.map(($)=>$.branch);_.default=this.$.node("union",this.ordered?{branches:G,ordered:!0}:G,{prereduced:!0}),Object.assign(this.referencesById,_.default.referencesById)}return Object.assign(X.location,{cases:_})}}var JQ=(Y,Z)=>{let X=Y.sort(($,W)=>Object.keys(W.cases).length-Object.keys($.cases).length)[0],_={kind:X.kind,path:X.path,optionallyChainedPropString:k_(X.path)},G=Z.branches.map(($,W)=>({originalIndex:W,branch:$}));return{best:X,location:_,defaultEntries:G,node:Z}},QQ=(Y,Z)=>{let X=Y.best.cases[Z],_=UQ(X.condition,Y.location.path,Y.node.$),G=[],$=[];for(let W=0;W<Y.defaultEntries.length;W++){let H=Y.defaultEntries[W];if(X.branchIndices.includes(H.originalIndex)){let Q=x_(Y.node.branches[H.originalIndex],Y.location);if(Q===null)G=null;else G?.push({originalIndex:H.originalIndex,branch:Q})}else if(H.branch.hasKind("alias")&&_.hasKind("domain")&&_.domain==="object")G?.push(H);else{if(H.branch.in.overlaps(_)){let Q=x_(H.branch,Y.location);G?.push({originalIndex:H.originalIndex,branch:Q})}$.push(H)}}return Y.defaultEntries=$,G},zQ=(Y,Z)=>{return Y.filter((_)=>{let G=Object.values(_.cases).map(($)=>$.branchIndices);for(let $=0;$<G.length-1;$++){let W=G[$];for(let H=$+1;H<G.length;H++){let Q=G[H];for(let J of W)for(let z of Q)if(J>z){if(Z[J].overlaps(Z[z]))return!1}}}return!0})},UQ=(Y,Z,X)=>{let _=Y==="undefined"?X.node("unit",{unit:void 0}):Y==="null"?X.node("unit",{unit:null}):Y==="boolean"?X.units([!0,!1]):Y;for(let G=Z.length-1;G>=0;G--){let $=Z[G];_=X.node("intersection",typeof $==="number"?{proto:"Array",sequence:[...DX($).map((W)=>({})),_]}:{domain:"object",required:[{key:$,value:_}]})}return _},k_=(Y)=>Y.reduce((Z,X)=>Z+BY(X,!0),"data"),FQ=B0(AX),EQ=B0(r),aY={implementation:HQ,Node:h_},VQ=(Y)=>({kind:Y.kind,path:Y.path.map((Z)=>typeof Z==="string"?Z:Y2(Z)),cases:i(Y.cases,(Z,X)=>[Z,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),OQ={delimiter:" | ",finalDelimiter:" | "},DQ=(Y)=>W4(Y,OQ),W4=(Y,Z)=>{let X=Z?.delimiter??", ",_=Z?.finalDelimiter??" or ";if(Y.length===0)return"never";if(Y.length===1)return Y[0];if(Y.length===2&&Y[0]==="false"&&Y[1]==="true"||Y[0]==="true"&&Y[1]==="false")return"boolean";let G={},$=Y.filter((H)=>G[H]?!1:G[H]=!0),W=$.pop();return`${$.join(X)}${$.length?_:""}${W}`},tY=(Y,Z,X)=>{let _=Z.map(()=>[]);for(let $=0;$<Y.length;$++){let W={};for(let H=0;H<Z.length;H++){if(_[H]===null)continue;if(Y[$].equals(Z[H])){_[H]=null,W={};break}let Q=M0(Y[$],Z[H],X);if(Q instanceof P)continue;if(Q.equals(Y[$])){_[H].push(Y[$]),W={};break}if(Q.equals(Z[H]))_[H]=null;else W[H]=Q}for(let H in W)_[H][$]=W[H]}let G=_.flatMap(($,W)=>$?.flatMap((H)=>H.branches)??Z[W]);return G.length===0?P.init("union",Y,Z):G},LQ=({branches:Y,ordered:Z})=>{if(Y.length<2)return Y;let X=Y.map(()=>!0);for(let _=0;_<Y.length;_++)for(let G=_+1;G<Y.length&&X[_]&&X[G];G++){if(Y[_].equals(Y[G])){X[G]=!1;continue}let $=U1(Y[_].in,Y[G].in,Y[0].$);if($ instanceof P)continue;if(!Z)MQ(Y[_],Y[G]);if($.equals(Y[_].in))X[_]=!!Z;else if($.equals(Y[G].in))X[G]=!1}return Y.filter((_,G)=>X[G])},MQ=(Y,Z)=>{if(!Y.includesTransform&&!Z.includesTransform)return;if(!t1(Y.shallowMorphs,Z.shallowMorphs))A(f_(Y.expression,Z.expression));if(!t1(Y.flatMorphs,Z.flatMorphs,{isEqual:(X,_)=>X.propString===_.propString&&(X.node.hasKind("morph")&&_.node.hasKind("morph")?X.node.hasEqualMorphs(_.node):X.node.hasKind("intersection")&&_.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===_.node.structure?.structuralMorphRef:!1)}))A(f_(Y.expression,Z.expression))},x_=(Y,Z)=>Y.transform((X,_)=>{if(X==="domain"||X==="unit")return null;return _},{shouldTransform:(X,_)=>{let G=k_(_.path);if(!Z.optionallyChainedPropString.startsWith(G))return!1;if(X.hasKind("domain")&&X.domain==="object")return!0;if((X.hasKind("domain")||Z.kind==="unit")&&G===Z.optionallyChainedPropString)return!0;return X.children.length!==0&&X.kind!=="index"}}),f_=(Y,Z)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
40
40
  Left: ${Y}
41
- Right: ${Z}`,MQ=(Y,Z)=>`The intersection of two ordered unions is indeterminate:
41
+ Right: ${Z}`,AQ=(Y,Z)=>`The intersection of two ordered unions is indeterminate:
42
42
  Left: ${Y}
43
- Right: ${Z}`;var AQ=r({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Y)=>Y instanceof Date?Y.toISOString():I1(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>i(Y.unit),problem:({expected:Y,actual:Z})=>`${Y===Z?`must be reference equal to ${Y} (serialized to the same value)`:`must be ${Y} (was ${Z})`}`},intersections:{unit:(Y,Z)=>P.init("unit",Y,Z),...l1("unit",(Y,Z)=>{if(Z.allows(Y.unit))return Y;let X=Z.hasKind("intersection")?Z.basis:Z;if(X){let _=X.hasKind("domain")?X:N.intrinsic.object;if(Y.domain!==_.domain){let G=Y.domain==="undefined"||Y.domain==="null"||Y.domain==="boolean"?Y.domain:N.intrinsic[Y.domain];return P.init("domain",G,_)}}return P.init("assignability",Y,Z.hasKind("intersection")?Z.children.find((_)=>!_.allows(Y.unit)):Z)})}});class b_ extends f2{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=k_(this.unit,this.serializedValue);compiledNegation=k_(this.unit,this.serializedValue,"negated");expression=i(this.unit);domain=y0(this.unit);get defaultShortDescription(){return this.domain==="object"?Q1.object:this.description}innerToJsonSchema(Y){return this.unit===null?{type:"null"}:N.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Y.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Y)=>Y instanceof Date&&Y.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Y)=>Number.isNaN(Y):(Y)=>Y===this.unit}var aY={implementation:AQ,Node:b_},k_=(Y,Z,X)=>{if(Y instanceof Date){let _=`data instanceof Date && data.toISOString() === ${Z}`;return X?`!(${_})`:_}if(Number.isNaN(Y))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${Z}`};var wQ=r({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Y,Z)=>{let X=Z.$.parseSchema(Y);if(!X.extends(N.intrinsic.key))return R(NQ(X.expression));let _=X.branches.filter((G)=>G.hasKind("unit"));if(_.length)return R(RQ(_.map((G)=>i(G.unit))));return X}},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>`[${Y.signature.expression}]: ${Y.value.description}`},intersections:{index:(Y,Z,X)=>{if(Y.signature.equals(Z.signature)){let _=L0(Y.value,Z.value,X),G=_ instanceof P?N.intrinsic.never.internal:_;return X.$.node("index",{signature:Y.signature,value:G})}if(Y.signature.extends(Z.signature)&&Y.value.subsumes(Z.value))return Z;if(Z.signature.extends(Y.signature)&&Z.value.subsumes(Y.value))return Y;return null}}});class y_ extends T1{impliedBasis=N.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=Z0(this.value.flatRefs.map((Y)=>h1([this.signature,...Y.path],Y.node)),h1([this.signature],this.value));traverseAllows=(Y,Z)=>S2(Y).every((X)=>{if(this.signature.traverseAllows(X[0],Z))return z1(X[0],()=>this.value.traverseAllows(X[1],Z),Z);return!0});traverseApply=(Y,Z)=>{for(let X of S2(Y))if(this.signature.traverseAllows(X[0],Z))z1(X[0],()=>this.value.traverseApply(X[1],Z),Z)};_transform(Y,Z){Z.path.push(this.signature);let X=super._transform(Y,Z);return Z.path.pop(),X}compile(){}}var eY={implementation:wQ,Node:y_},RQ=(Y)=>`Index keys ${Y.join(", ")} should be specified as named props.`,NQ=(Y)=>`Indexed key definition '${Y}' must be a string or symbol`;var IQ=r({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>`${Y.compiledKey}: ${Y.value.description}`,expected:(Y)=>Y.missingValueDescription,actual:()=>"missing"},intersections:{required:o4,optional:o4}});class g_ extends i4{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=L2(this.errorContext)}var YZ={implementation:IQ,Node:g_};var TQ=r({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},optionals:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},defaultables:{child:(Y)=>Y.map((Z)=>Z[0]),parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>{let _=Z.$.parseSchema(X[0]);return n4(_,X[1],null),[_,X[1]]})},serialize:(Y)=>Y.map((Z)=>[Z[0].collapsibleJson,I1(Z[1])])},variadic:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y,Z)},minVariadicLength:{parse:(Y)=>Y===0?void 0:Y},postfix:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}}},normalize:(Y)=>{if(typeof Y==="string")return{variadic:Y};if("variadic"in Y||"prefix"in Y||"defaultables"in Y||"optionals"in Y||"postfix"in Y||"minVariadicLength"in Y){if(Y.postfix?.length){if(!Y.variadic)return R(qQ);if(Y.optionals?.length||Y.defaultables?.length)return R(XZ)}if(Y.minVariadicLength&&!Y.variadic)return R("minVariadicLength may not be specified without a variadic element");return Y}return{variadic:Y}},reduce:(Y,Z)=>{let X=Y.minVariadicLength??0,_=Y.prefix?.slice()??[],G=Y.defaultables?.slice()??[],$=Y.optionals?.slice()??[],W=Y.postfix?.slice()??[];if(Y.variadic){while($.at(-1)?.equals(Y.variadic))$.pop();if($.length===0&&G.length===0)while(_.at(-1)?.equals(Y.variadic))_.pop(),X++;while(W[0]?.equals(Y.variadic))W.shift(),X++}else if($.length===0&&G.length===0)_.push(...W.splice(0));if(X!==Y.minVariadicLength||Y.prefix&&Y.prefix.length!==_.length)return Z.node("sequence",{...Y,prefix:_,defaultables:G,optionals:$,postfix:W,minVariadicLength:X},{prereduced:!0})},defaults:{description:(Y)=>{if(Y.isVariadicOnly)return`${Y.variadic.nestableExpression}[]`;return`[${Y.tuple.map((X)=>X.kind==="defaultables"?`${X.node.nestableExpression} = ${i(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(Y,Z,X)=>{let _=e4({l:Y.tuple,r:Z.tuple,disjoint:new P,result:[],fixedVariants:[],ctx:X}),G=_.disjoint.length===0?[_,..._.fixedVariants]:_.fixedVariants;return G.length===0?_.disjoint:G.length===1?X.$.node("sequence",p_(G[0].result)):X.$.node("union",G.map(($)=>({proto:Array,sequence:p_($.result)})))}}});class m_ extends T1{impliedBasis=N.intrinsic.Array.internal;tuple=CQ(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((Y)=>{if(Y.kind==="defaultables"||Y.kind==="optionals")return this.defaultablesAndOptionals.push(Y.node),!0;return Y.kind==="prefix"});variadicOrPostfix=s1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return jY(this.flatRefs,this.prevariadic.flatMap((Y,Z)=>Z0(Y.node.flatRefs.map((X)=>h1([`${Z}`,...X.path],X.node)),h1([`${Z}`],Y.node)))),jY(this.flatRefs,this.variadicOrPostfix.flatMap((Y)=>Z0(Y.flatRefs.map((Z)=>h1([N.intrinsic.nonNegativeIntegerString.internal,...Z.path],Z.node)),h1([N.intrinsic.nonNegativeIntegerString.internal],Y)))),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=BQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?B0(this.defaultValueMorphs):void 0;elementAtIndex(Y,Z){if(Z<this.prevariadic.length)return this.tuple[Z];let X=Y.length-this.postfixLength;if(Z>=X)return{kind:"postfix",node:this.postfix[Z-X]};return{kind:"variadic",node:this.variadic??_0(`Unexpected attempt to access index ${Z} on ${this}`)}}traverseAllows=(Y,Z)=>{for(let X=0;X<Y.length;X++)if(!this.elementAtIndex(Y,X).node.traverseAllows(Y[X],Z))return!1;return!0};traverseApply=(Y,Z)=>{let X=0;for(;X<Y.length;X++)z1(X,()=>this.elementAtIndex(Y,X).node.traverseApply(Y[X],Z),Z)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Y){if(this.prefix)for(let[Z,X]of this.prefix.entries())Y.traverseKey(`${Z}`,`data[${Z}]`,X);for(let[Z,X]of this.defaultablesAndOptionals.entries()){let _=`${Z+this.prefixLength}`;Y.if(`${_} >= ${Y.data}.length`,()=>Y.traversalKind==="Allows"?Y.return(!0):Y.return()),Y.traverseKey(_,`data[${_}]`,X)}if(this.variadic){if(this.postfix)Y.const("firstPostfixIndex",`${Y.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Y.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Y.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Z,X]of this.postfix.entries()){let _=`firstPostfixIndex + ${Z}`;Y.traverseKey(_,`data[${_}]`,X)}}if(Y.traversalKind==="Allows")Y.return(!0)}_transform(Y,Z){Z.path.push(N.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(Y,Z);return Z.path.pop(),X}expression=this.description;reduceJsonSchema(Y,Z){if(this.prevariadic.length)Y.prefixItems=this.prevariadic.map((X)=>{let _=X.node.toJsonSchemaRecurse(Z);if(X.kind==="defaultables"){let G=typeof X.default==="function"?X.default():X.default;_.default=N.intrinsic.jsonData.allows(G)?G:Z.fallback.defaultValue({code:"defaultValue",base:_,value:G})}return _});if(this.minLength)Y.minItems=this.minLength;if(this.variadic){let X=Object.assign(Y,{items:this.variadic.toJsonSchemaRecurse(Z)});if(this.maxLength)X.maxItems=this.maxLength;if(this.postfix){let _=this.postfix.map((G)=>G.toJsonSchemaRecurse(Z));Y=Z.fallback.arrayPostfix({code:"arrayPostfix",base:X,elements:_})}}else Y.items=!1,delete Y.maxItems;return Y}}var KQ={},BQ=(Y)=>{if(!Y.defaultables)return[];let Z=[],X="[",_=Y.prefixLength+Y.defaultablesLength-1;for(let G=Y.prefixLength;G<=_;G++){let[$,W]=Y.defaultables[G-Y.prefixLength];Z.push(iY(G,$,W)),X+=`${G}: ${$.id} = ${I1(W)}, `}return X+="]",KQ[X]??=Z},ZZ={implementation:TQ,Node:m_},CQ=(Y)=>{let Z=[];if(Y.prefix)for(let X of Y.prefix)Z.push({kind:"prefix",node:X});if(Y.defaultables)for(let[X,_]of Y.defaultables)Z.push({kind:"defaultables",node:X,default:_});if(Y.optionals)for(let X of Y.optionals)Z.push({kind:"optionals",node:X});if(Y.variadic)Z.push({kind:"variadic",node:Y.variadic});if(Y.postfix)for(let X of Y.postfix)Z.push({kind:"postfix",node:X});return Z},p_=(Y)=>Y.reduce((Z,X)=>{if(X.kind==="variadic")Z.variadic=X.node;else if(X.kind==="defaultables")Z.defaultables=Z0(Z.defaultables,[[X.node,X.default]]);else Z[X.kind]=Z0(Z[X.kind],X.node);return Z},{}),XZ="A postfix required element cannot follow an optional or defaultable element",qQ="A postfix element requires a variadic element",e4=(Y)=>{let[Z,...X]=Y.l,[_,...G]=Y.r;if(!Z||!_)return Y;let $=X.at(-1)?.kind==="postfix",W=G.at(-1)?.kind==="postfix",H=Z.kind==="prefix"||_.kind==="prefix"?"prefix":Z.kind==="postfix"||_.kind==="postfix"?"postfix":Z.kind==="variadic"&&_.kind==="variadic"?"variadic":$||W?"prefix":Z.kind==="defaultables"||_.kind==="defaultables"?"defaultables":"optionals";if(Z.kind==="prefix"&&_.kind==="variadic"&&W){let F=e4({...Y,fixedVariants:[],r:G.map((V)=>({...V,kind:"prefix"}))});if(F.disjoint.length===0)Y.fixedVariants.push(F)}else if(_.kind==="prefix"&&Z.kind==="variadic"&&$){let F=e4({...Y,fixedVariants:[],l:X.map((V)=>({...V,kind:"prefix"}))});if(F.disjoint.length===0)Y.fixedVariants.push(F)}let Q=L0(Z.node,_.node,Y.ctx);if(Q instanceof P)if(H==="prefix"||H==="postfix")Y.disjoint.push(...Q.withPrefixKey(H==="prefix"?Y.result.length:`-${X.length+1}`,"required")),Y.result=[...Y.result,{kind:H,node:N.intrinsic.never.internal}];else if(H==="optionals"||H==="defaultables")return Y;else return e4({...Y,fixedVariants:[],l:X.map((F)=>({...F,kind:"prefix"})),r:X.map((F)=>({...F,kind:"prefix"}))});else if(H==="defaultables"){if(Z.kind==="defaultables"&&_.kind==="defaultables"&&Z.default!==_.default)R(oY(Z.default,_.default));Y.result=[...Y.result,{kind:H,node:Q,default:Z.kind==="defaultables"?Z.default:_.kind==="defaultables"?_.default:_0(`Unexpected defaultable intersection from ${Z.kind} and ${_.kind} elements.`)}]}else Y.result=[...Y.result,{kind:H,node:Q}];let J=Y.l.length,U=Y.r.length;if(Z.kind!=="variadic"||J>=U&&(_.kind==="variadic"||U===1))Y.l=X;if(_.kind!=="variadic"||U>=J&&(Z.kind==="variadic"||J===1))Y.r=G;return e4(Y)};var c_=(Y)=>(Z)=>{if(Z.props.length||Z.index){let X=Z.index?.map((G)=>G[Y])??[];for(let G of Z.props)X.push(G[Y]);if(Z.undeclared)X.push(`+ (undeclared): ${Z.undeclared}`);let _=`{ ${X.join(", ")} }`;return Z.sequence?`${_} & ${Z.sequence.description}`:_}return Z.sequence?.description??"{}"},jQ=c_("description"),SQ=c_("expression"),u_=(Y,Z,X)=>{let _=Y.required?"required":"optional";if(!Z.signature.allows(Y.key))return null;let G=F1(Y.value,Z.value,X);if(G instanceof P)return _==="optional"?X.node("optional",{key:Y.key,value:N.intrinsic.never.internal}):G.withPrefixKey(Y.key,Y.kind);return null},PQ=r({kind:"structure",hasAssociatedError:!1,normalize:(Y)=>Y,applyConfig:(Y,Z)=>{if(!Y.undeclared&&Z.onUndeclaredKey!=="ignore")return{...Y,undeclared:Z.onUndeclaredKey};return Y},keys:{required:{child:!0,parse:t0("required"),reduceIo:(Y,Z,X)=>{Z.required=Z0(Z.required,X.map((_)=>_[Y]));return}},optional:{child:!0,parse:t0("optional"),reduceIo:(Y,Z,X)=>{if(Y==="in"){Z.optional=X.map((_)=>_.in);return}for(let _ of X)Z[_.outProp.kind]=Z0(Z[_.outProp.kind],_.outProp.out)}},index:{child:!0,parse:t0("index")},sequence:{child:!0,parse:t0("sequence")},undeclared:{parse:(Y)=>Y==="ignore"?void 0:Y,reduceIo:(Y,Z,X)=>{if(X!=="delete")return;if(Y==="in")delete Z.undeclared;else Z.undeclared="reject"}}},defaults:{description:jQ},intersections:{structure:(Y,Z,X)=>{let _={...Y.inner},G={...Z.inner},$=new P;if(Y.undeclared){let Q=Y.keyof();for(let J of Z.requiredKeys)if(!Q.allows(J))$.add("presence",N.intrinsic.never.internal,Z.propsByKey[J].value,{path:[J]});if(G.optional)G.optional=G.optional.filter((J)=>Q.allows(J.key));if(G.index)G.index=G.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let U=F1(Q,J.signature,X.$);if(U instanceof P)return[];let F=Z6(U,J.value,X.$);if(F.required)G.required=s1(G.required,F.required);if(F.optional)G.optional=s1(G.optional,F.optional);return F.index??[]})}if(Z.undeclared){let Q=Z.keyof();for(let J of Y.requiredKeys)if(!Q.allows(J))$.add("presence",Y.propsByKey[J].value,N.intrinsic.never.internal,{path:[J]});if(_.optional)_.optional=_.optional.filter((J)=>Q.allows(J.key));if(_.index)_.index=_.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let U=F1(Q,J.signature,X.$);if(U instanceof P)return[];let F=Z6(U,J.value,X.$);if(F.required)_.required=s1(_.required,F.required);if(F.optional)_.optional=s1(_.optional,F.optional);return F.index??[]})}let W={};if(Y.undeclared||Z.undeclared)W.undeclared=Y.undeclared==="reject"||Z.undeclared==="reject"?"reject":"delete";let H=X4({kind:"structure",baseInner:W,l:_4(_),r:_4(G),roots:[],ctx:X});if(H instanceof P)$.push(...H);if($.length)return $;return H}},reduce:(Y,Z)=>{if(Y.index){if(!(Y.required||Y.optional))return;let X=!1,_=Y.required??[],G=Y.optional??[],$=[...G];for(let W of Y.index){for(let H of _){let Q=u_(H,W,Z);if(Q instanceof P)return Q}for(let[H,Q]of G.entries()){let J=u_(Q,W,Z);if(J instanceof P)return J;if(J===null)continue;$[H]=J,X=!0}}if(X)return Z.node("structure",{...Y,optional:$},{prereduced:!0})}}});class l_ extends T1{impliedBasis=N.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Y)=>Y.impliedSiblings??[]);props=s1(this.required,this.optional);propsByKey=o(this.props,(Y,Z)=>[Z.key,Z]);propsByKeyReference=B0(this.propsByKey);expression=SQ(this);requiredKeys=this.required?.map((Y)=>Y.key)??[];optionalKeys=this.optional?.map((Y)=>Y.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Y=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Z}of this.index)Y=Y.concat(Z.branches);return this._keyof=this.$.node("union",Y)}map(Y){return this.$.node("structure",this.props.flatMap(Y).reduce((Z,X)=>{let _=this.propsByKey[X.key];if(D0(X)){if(X.kind!=="required"&&X.kind!=="optional")return R(`Map result must have kind "required" or "optional" (was ${X.kind})`);return Z[X.kind]=Z0(Z[X.kind],X),Z}let G=X.kind??_?.kind??"required",$=o(X,(W,H)=>(W in r4.implementation.keys)?[W,H]:[]);return Z[G]=Z0(Z[G],this.$.node(G,$)),Z},{}))}assertHasKeys(Y){let Z=Y.filter((X)=>!s4(X,this.keyof()));if(Z.length)return R(d_(this.expression,Z))}get(Y,...Z){let X,_=!1,G=hQ(Y);if((typeof G==="string"||typeof G==="symbol")&&this.propsByKey[G])X=this.propsByKey[G].value,_=this.propsByKey[G].required;if(this.index){for(let W of this.index)if(s4(G,W.signature))X=X?.and(W.value)??W.value}if(this.sequence&&s4(G,N.intrinsic.nonNegativeIntegerString))if(y(G,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let W=Number.parseInt(G);if(W<this.sequence.prevariadic.length){let H=this.sequence.prevariadic[W].node;X=X?.and(H)??H,_||=W<this.sequence.prefixLength}else if(this.sequence.variadic){let H=this.$.node("union",this.sequence.variadicOrPostfix);X=X?.and(H)??H}}if(!X){if(this.sequence?.variadic&&y(G,"root")&&G.extends(N.intrinsic.number))return R(kQ(G.expression,this.sequence.expression));return R(d_(this.expression,[G]))}let $=X.get(...Z);return _?$:$.or(N.intrinsic.undefined)}pick(...Y){return this.assertHasKeys(Y),this.$.node("structure",this.filterKeys("pick",Y))}omit(...Y){return this.assertHasKeys(Y),this.$.node("structure",this.filterKeys("omit",Y))}optionalize(){let{required:Y,...Z}=this.inner;return this.$.node("structure",{...Z,optional:this.props.map((X)=>X.hasKind("required")?this.$.node("optional",X.inner):X)})}require(){let{optional:Y,...Z}=this.inner;return this.$.node("structure",{...Z,required:this.props.map((X)=>X.hasKind("optional")?{key:X.key,value:X.value}:X)})}merge(Y){let Z=this.filterKeys("omit",[Y.keyof()]);if(Y.required)Z.required=Z0(Z.required,Y.required);if(Y.optional)Z.optional=Z0(Z.optional,Y.optional);if(Y.index)Z.index=Z0(Z.index,Y.index);if(Y.sequence)Z.sequence=Y.sequence;if(Y.undeclared)Z.undeclared=Y.undeclared;else delete Z.undeclared;return this.$.node("structure",Z)}filterKeys(Y,Z){let X=c8(this.inner),_=(G)=>{let $=Z.some((W)=>s4(G,W));return Y==="pick"?$:!$};if(X.required)X.required=X.required.filter((G)=>_(G.key));if(X.optional)X.optional=X.optional.filter((G)=>_(G.key));if(X.index)X.index=X.index.filter((G)=>_(G.signature));return X}traverseAllows=(Y,Z)=>this._traverse("Allows",Y,Z);traverseApply=(Y,Z)=>this._traverse("Apply",Y,Z);_traverse=(Y,Z,X)=>{let _=X?.currentErrorCount??0;for(let G=0;G<this.props.length;G++)if(Y==="Allows"){if(!this.props[G].traverseAllows(Z,X))return!1}else if(this.props[G].traverseApply(Z,X),X.failFast&&X.currentErrorCount>_)return!1;if(this.sequence){if(Y==="Allows"){if(!this.sequence.traverseAllows(Z,X))return!1}else if(this.sequence.traverseApply(Z,X),X.failFast&&X.currentErrorCount>_)return!1}if(this.index||this.undeclared==="reject"){let G=Object.keys(Z);G.push(...Object.getOwnPropertySymbols(Z));for(let $=0;$<G.length;$++){let W=G[$];if(this.index){for(let H of this.index)if(H.signature.traverseAllows(W,X)){if(Y==="Allows"){if(!z1(W,()=>H.value.traverseAllows(Z[W],X),X))return!1}else if(z1(W,()=>H.value.traverseApply(Z[W],X),X),X.failFast&&X.currentErrorCount>_)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(W)){if(Y==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[W],meta:this.meta}),X.failFast)return!1}}}if(this.structuralMorph&&X&&!X.hasError())X.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Y)=>Y.hasDefault())??[])}declaresKey=(Y)=>(Y in this.propsByKey)||this.index?.some((Z)=>Z.signature.allows(Y))||this.sequence!==void 0&&N.intrinsic.nonNegativeIntegerString.allows(Y);_compileDeclaresKey(Y){let Z=[];if(this.props.length)Z.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let X of this.index)Z.push(Y.invoke(X.signature,{kind:"Allows",arg:"k"}));if(this.sequence)Z.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return Z.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",xQ(this))}structuralMorphRef=this.structuralMorph&&B0(this.structuralMorph);compile(Y){if(Y.traversalKind==="Apply")Y.initializeErrorCount();for(let Z of this.props)if(Y.check(Z),Y.traversalKind==="Apply")Y.returnIfFailFast();if(this.sequence){if(Y.check(this.sequence),Y.traversalKind==="Apply")Y.returnIfFailFast()}if(this.index||this.undeclared==="reject")Y.const("keys","Object.keys(data)"),Y.line("keys.push(...Object.getOwnPropertySymbols(data))"),Y.for("i < keys.length",()=>this.compileExhaustiveEntry(Y));if(Y.traversalKind==="Allows")return Y.return(!0);if(this.structuralMorphRef)Y.if("ctx && !ctx.hasError()",()=>{return Y.line("ctx.queueMorphs(["),fQ(Y,this),Y.line("])")})}compileExhaustiveEntry(Y){if(Y.const("k","keys[i]"),this.index)for(let Z of this.index)Y.if(`${Y.invoke(Z.signature,{arg:"k",kind:"Allows"})}`,()=>Y.traverseKey("k","data[k]",Z.value));if(this.undeclared==="reject")Y.if(`!(${this._compileDeclaresKey(Y)})`,()=>{if(Y.traversalKind==="Allows")return Y.return(!1);return Y.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Y.return())});return Y}reduceJsonSchema(Y,Z){switch(Y.type){case"object":return this.reduceObjectJsonSchema(Y,Z);case"array":let X=this.sequence?.reduceJsonSchema(Y,Z)??Y;if(this.props.length||this.index)return Z.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},Z)});return X;default:return R0.throwInternalOperandError("structure",Y)}}reduceObjectJsonSchema(Y,Z){if(this.props.length){Y.properties={};for(let X of this.props){let _=X.value.toJsonSchemaRecurse(Z);if(typeof X.key==="symbol"){Z.fallback.symbolKey({code:"symbolKey",base:Y,key:X.key,value:_,optional:X.optional});continue}if(X.hasDefault()){let G=typeof X.default==="function"?X.default():X.default;_.default=N.intrinsic.jsonData.allows(G)?G:Z.fallback.defaultValue({code:"defaultValue",base:_,value:G})}Y.properties[X.key]=_}if(this.requiredKeys.length&&Y.properties)Y.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in Y.properties))}if(this.index)for(let X of this.index){let _=X.value.toJsonSchemaRecurse(Z);if(X.signature.equals(N.intrinsic.string)){Y.additionalProperties=_;continue}for(let G of X.signature.branches){if(!G.extends(N.intrinsic.string)){Y=Z.fallback.symbolKey({code:"symbolKey",base:Y,key:null,value:_,optional:!1});continue}let $={type:"string"};if(G.hasKind("morph"))$=Z.fallback.morph({code:"morph",base:G.in.toJsonSchemaRecurse(Z),out:G.out.toJsonSchemaRecurse(Z)});if(!G.hasKind("intersection"))return _0(`Unexpected index branch kind ${G.kind}.`);let{pattern:W}=G.inner;if(W){let H=Object.assign($,{pattern:W[0].rule});for(let Q=1;Q<W.length;Q++)$=Z.fallback.patternIntersection({code:"patternIntersection",base:H,pattern:W[Q].rule});Y.patternProperties??={},Y.patternProperties[H.pattern]=_}}}if(this.undeclared&&!Y.additionalProperties)Y.additionalProperties=!1;return Y}}var _Z={},vQ=(Y)=>{let Z="";for(let X=0;X<Y.defaultable.length;X++)Z+=Y.defaultable[X].defaultValueMorphRef;if(Y.sequence?.defaultValueMorphsReference)Z+=Y.sequence?.defaultValueMorphsReference;if(Y.undeclared==="delete"){if(Z+="delete !(",Y.required)for(let X of Y.required)Z+=X.compiledKey+" | ";if(Y.optional)for(let X of Y.optional)Z+=X.compiledKey+" | ";if(Y.index)for(let X of Y.index)Z+=X.signature.id+" | ";if(Y.sequence)if(Y.sequence.maxLength===null)Z+=d.nonNegativeIntegerString.id;else for(let X=0;X<Y.sequence.tuple.length;X++)Z+=X+" | ";Z+=")"}return Z},xQ=(Y)=>{let Z=vQ(Y);if(!Z)return;if(_Z[Z])return _Z[Z];let X=(_,G)=>{for(let $=0;$<Y.defaultable.length;$++)if(!(Y.defaultable[$].key in _))Y.defaultable[$].defaultValueMorph(_,G);if(Y.sequence?.defaultables)for(let $=_.length-Y.sequence.prefixLength;$<Y.sequence.defaultables.length;$++)Y.sequence.defaultValueMorphs[$](_,G);if(Y.undeclared==="delete"){for(let $ in _)if(!Y.declaresKey($))delete _[$]}return _};return _Z[Z]=X},fQ=(Y,Z)=>{let _=`(data${Z.defaultable.some((G)=>G.defaultValueMorph.length===2)||Z.sequence?.defaultValueMorphs.some((G)=>G.length===2)?", ctx":""})`;return Y.block(`${_} => `,(G)=>{for(let $=0;$<Z.defaultable.length;$++){let{serializedKey:W,defaultValueMorphRef:H}=Z.defaultable[$];G.if(`!(${W} in data)`,(Q)=>Q.line(`${H}${_}`))}if(Z.sequence?.defaultables)G.for(`i < ${Z.sequence.defaultables.length}`,($)=>$.set("data[i]",5),`data.length - ${Z.sequence.prefixLength}`);if(Z.undeclared==="delete")G.forIn("data",($)=>$.if(`!(${Z._compileDeclaresKey($)})`,(W)=>W.line("delete data[k]")));return G.return("data")})},GZ={implementation:PQ,Node:l_},hQ=(Y)=>{if(y(Y,"root")&&Y.hasKind("unit"))Y=Y.unit;if(typeof Y==="number")Y=`${Y}`;return Y},kQ=(Y,Z)=>`${Y} is not allowed as an array index on ${Z}. Use the 'nonNegativeIntegerString' keyword instead.`,Z6=(Y,Z,X)=>{let[_,G]=OX(Y.branches,(W)=>W.hasKind("unit"));if(!_.length)return{index:X.node("index",{signature:Y,value:Z})};let $={};for(let W of _){let H=X.node("required",{key:W.unit,value:Z});$[H.kind]=Z0($[H.kind],H)}if(G.length)$.index=X.node("index",{signature:G,value:Z});return $},bQ=(Y)=>y(Y,"root")?Y.expression:i(Y),d_=(Y,Z)=>`Key${Z.length===1?"":"s"} ${Z.map(bQ).join(", ")} ${Z.length===1?"does":"do"} not exist on ${Y}`;var $4={...V_,alias:t4.implementation,domain:Y6.implementation,unit:aY.implementation,proto:a4.implementation,union:tY.implementation,morph:nY.implementation,intersection:rY.implementation,divisor:fY.implementation,pattern:uY.implementation,predicate:xY.implementation,required:YZ.implementation,optional:r4.implementation,index:eY.implementation,sequence:ZZ.implementation,structure:GZ.implementation};N.defaultConfig=IX(Object.assign(o($4,(Y,Z)=>[Y,Z.defaults]),{jitless:jX(),clone:BX,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:R0.defaultConfig}));N.resolvedConfig=m4(N.defaultConfig,N.config);var R_={...D_,alias:t4.Node,domain:Y6.Node,unit:aY.Node,proto:a4.Node,union:tY.Node,morph:nY.Node,intersection:rY.Node,divisor:fY.Node,pattern:uY.Node,predicate:xY.Node,required:YZ.Node,optional:r4.Node,index:eY.Node,sequence:ZZ.Node,structure:GZ.Node};class J4 extends OY{get[X1](){return"module"}}var $Z=(Y,Z)=>new J4(o(Y,(X,_)=>[X,y(_,"module")?$Z(_,Z):Z.bindReference(_)]));var yQ=(Y)=>F0(Y)?Y:("branches"in Y)&&F0(Y.branches)?Y.branches:void 0,gQ=(Y,Z)=>R(`Node of kind ${Z} is not valid as a ${Y} definition`),o_=(Y)=>`#${Y} duplicates public alias ${Y}`,WZ={};N.ambient??={};var i_,n_="function $",pQ=(Y)=>s_(Y,t_(Y)),s_=(Y,Z)=>{let X=Z.write(n_,4),_=Z.compile()();for(let G of Y){if(G.precompilation)continue;if(G.traverseAllows=_[`${G.id}Allows`].bind(_),G.isRoot()&&!G.allowsRequiresContext)G.allows=G.traverseAllows;if(G.traverseApply=_[`${G.id}Apply`].bind(_),_[`${G.id}Optimistic`])G.traverseOptimistic=_[`${G.id}Optimistic`].bind(_);G.precompilation=X}},t_=(Y)=>new d8().return(Y.reduce((Z,X)=>{let _=new p4({kind:"Allows"}).indent();X.compile(_);let G=_.write(`${X.id}Allows`),$=new p4({kind:"Apply"}).indent();X.compile($);let W=$.write(`${X.id}Apply`),H=`${Z}${G},
43
+ Right: ${Z}`;var wQ=n({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Y)=>Y instanceof Date?Y.toISOString():R1(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>r(Y.unit),problem:({expected:Y,actual:Z})=>`${Y===Z?`must be reference equal to ${Y} (serialized to the same value)`:`must be ${Y} (was ${Z})`}`},intersections:{unit:(Y,Z)=>P.init("unit",Y,Z),...l1("unit",(Y,Z)=>{if(Z.allows(Y.unit))return Y;let X=Z.hasKind("intersection")?Z.basis:Z;if(X){let _=X.hasKind("domain")?X:I.intrinsic.object;if(Y.domain!==_.domain){let G=Y.domain==="undefined"||Y.domain==="null"||Y.domain==="boolean"?Y.domain:I.intrinsic[Y.domain];return P.init("domain",G,_)}}return P.init("assignability",Y,Z.hasKind("intersection")?Z.children.find((_)=>!_.allows(Y.unit)):Z)})}});class y_ extends x2{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=b_(this.unit,this.serializedValue);compiledNegation=b_(this.unit,this.serializedValue,"negated");expression=r(this.unit);domain=y0(this.unit);get defaultShortDescription(){return this.domain==="object"?J1.object:this.description}innerToJsonSchema(Y){return this.unit===null?{type:"null"}:I.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Y.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Y)=>Y instanceof Date&&Y.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Y)=>Number.isNaN(Y):(Y)=>Y===this.unit}var eY={implementation:wQ,Node:y_},b_=(Y,Z,X)=>{if(Y instanceof Date){let _=`data instanceof Date && data.toISOString() === ${Z}`;return X?`!(${_})`:_}if(Number.isNaN(Y))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${Z}`};var RQ=n({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Y,Z)=>{let X=Z.$.parseSchema(Y);if(!X.extends(I.intrinsic.key))return A(IQ(X.expression));let _=X.branches.filter((G)=>G.hasKind("unit"));if(_.length)return A(NQ(_.map((G)=>r(G.unit))));return X}},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>`[${Y.signature.expression}]: ${Y.value.description}`},intersections:{index:(Y,Z,X)=>{if(Y.signature.equals(Z.signature)){let _=M0(Y.value,Z.value,X),G=_ instanceof P?I.intrinsic.never.internal:_;return X.$.node("index",{signature:Y.signature,value:G})}if(Y.signature.extends(Z.signature)&&Y.value.subsumes(Z.value))return Z;if(Z.signature.extends(Y.signature)&&Z.value.subsumes(Y.value))return Y;return null}}});class g_ extends N1{impliedBasis=I.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=Z0(this.value.flatRefs.map((Y)=>h1([this.signature,...Y.path],Y.node)),h1([this.signature],this.value));traverseAllows=(Y,Z)=>j2(Y).every((X)=>{if(this.signature.traverseAllows(X[0],Z))return z1(X[0],()=>this.value.traverseAllows(X[1],Z),Z);return!0});traverseApply=(Y,Z)=>{for(let X of j2(Y))if(this.signature.traverseAllows(X[0],Z))z1(X[0],()=>this.value.traverseApply(X[1],Z),Z)};_transform(Y,Z){Z.path.push(this.signature);let X=super._transform(Y,Z);return Z.path.pop(),X}compile(){}}var YZ={implementation:RQ,Node:g_},NQ=(Y)=>`Index keys ${Y.join(", ")} should be specified as named props.`,IQ=(Y)=>`Indexed key definition '${Y}' must be a string or symbol`;var KQ=n({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>`${Y.compiledKey}: ${Y.value.description}`,expected:(Y)=>Y.missingValueDescription,actual:()=>"missing"},intersections:{required:c4,optional:c4}});class p_ extends l4{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=L2(this.errorContext)}var ZZ={implementation:KQ,Node:p_};var TQ=n({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},optionals:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},defaultables:{child:(Y)=>Y.map((Z)=>Z[0]),parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>{let _=Z.$.parseSchema(X[0]);return i4(_,X[1],null),[_,X[1]]})},serialize:(Y)=>Y.map((Z)=>[Z[0].collapsibleJson,R1(Z[1])])},variadic:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y,Z)},minVariadicLength:{parse:(Y)=>Y===0?void 0:Y},postfix:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}}},normalize:(Y)=>{if(typeof Y==="string")return{variadic:Y};if("variadic"in Y||"prefix"in Y||"defaultables"in Y||"optionals"in Y||"postfix"in Y||"minVariadicLength"in Y){if(Y.postfix?.length){if(!Y.variadic)return A(jQ);if(Y.optionals?.length||Y.defaultables?.length)return A(_Z)}if(Y.minVariadicLength&&!Y.variadic)return A("minVariadicLength may not be specified without a variadic element");return Y}return{variadic:Y}},reduce:(Y,Z)=>{let X=Y.minVariadicLength??0,_=Y.prefix?.slice()??[],G=Y.defaultables?.slice()??[],$=Y.optionals?.slice()??[],W=Y.postfix?.slice()??[];if(Y.variadic){while($.at(-1)?.equals(Y.variadic))$.pop();if($.length===0&&G.length===0)while(_.at(-1)?.equals(Y.variadic))_.pop(),X++;while(W[0]?.equals(Y.variadic))W.shift(),X++}else if($.length===0&&G.length===0)_.push(...W.splice(0));if(X!==Y.minVariadicLength||Y.prefix&&Y.prefix.length!==_.length)return Z.node("sequence",{...Y,prefix:_,defaultables:G,optionals:$,postfix:W,minVariadicLength:X},{prereduced:!0})},defaults:{description:(Y)=>{if(Y.isVariadicOnly)return`${Y.variadic.nestableExpression}[]`;return`[${Y.tuple.map((X)=>X.kind==="defaultables"?`${X.node.nestableExpression} = ${r(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(Y,Z,X)=>{let _=t4({l:Y.tuple,r:Z.tuple,disjoint:new P,result:[],fixedVariants:[],ctx:X}),G=_.disjoint.length===0?[_,..._.fixedVariants]:_.fixedVariants;return G.length===0?_.disjoint:G.length===1?X.$.node("sequence",m_(G[0].result)):X.$.node("union",G.map(($)=>({proto:Array,sequence:m_($.result)})))}}});class u_ extends N1{impliedBasis=I.intrinsic.Array.internal;tuple=qQ(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((Y)=>{if(Y.kind==="defaultables"||Y.kind==="optionals")return this.defaultablesAndOptionals.push(Y.node),!0;return Y.kind==="prefix"});variadicOrPostfix=s1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return SY(this.flatRefs,this.prevariadic.flatMap((Y,Z)=>Z0(Y.node.flatRefs.map((X)=>h1([`${Z}`,...X.path],X.node)),h1([`${Z}`],Y.node)))),SY(this.flatRefs,this.variadicOrPostfix.flatMap((Y)=>Z0(Y.flatRefs.map((Z)=>h1([I.intrinsic.nonNegativeIntegerString.internal,...Z.path],Z.node)),h1([I.intrinsic.nonNegativeIntegerString.internal],Y)))),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=CQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?B0(this.defaultValueMorphs):void 0;elementAtIndex(Y,Z){if(Z<this.prevariadic.length)return this.tuple[Z];let X=Y.length-this.postfixLength;if(Z>=X)return{kind:"postfix",node:this.postfix[Z-X]};return{kind:"variadic",node:this.variadic??_0(`Unexpected attempt to access index ${Z} on ${this}`)}}traverseAllows=(Y,Z)=>{for(let X=0;X<Y.length;X++)if(!this.elementAtIndex(Y,X).node.traverseAllows(Y[X],Z))return!1;return!0};traverseApply=(Y,Z)=>{let X=0;for(;X<Y.length;X++)z1(X,()=>this.elementAtIndex(Y,X).node.traverseApply(Y[X],Z),Z)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Y){if(this.prefix)for(let[Z,X]of this.prefix.entries())Y.traverseKey(`${Z}`,`data[${Z}]`,X);for(let[Z,X]of this.defaultablesAndOptionals.entries()){let _=`${Z+this.prefixLength}`;Y.if(`${_} >= ${Y.data}.length`,()=>Y.traversalKind==="Allows"?Y.return(!0):Y.return()),Y.traverseKey(_,`data[${_}]`,X)}if(this.variadic){if(this.postfix)Y.const("firstPostfixIndex",`${Y.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Y.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Y.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Z,X]of this.postfix.entries()){let _=`firstPostfixIndex + ${Z}`;Y.traverseKey(_,`data[${_}]`,X)}}if(Y.traversalKind==="Allows")Y.return(!0)}_transform(Y,Z){Z.path.push(I.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(Y,Z);return Z.path.pop(),X}expression=this.description;reduceJsonSchema(Y,Z){if(this.prevariadic.length)Y.prefixItems=this.prevariadic.map((X)=>{let _=X.node.toJsonSchemaRecurse(Z);if(X.kind==="defaultables"){let G=typeof X.default==="function"?X.default():X.default;_.default=I.intrinsic.jsonData.allows(G)?G:Z.fallback.defaultValue({code:"defaultValue",base:_,value:G})}return _});if(this.minLength)Y.minItems=this.minLength;if(this.variadic){let X=Object.assign(Y,{items:this.variadic.toJsonSchemaRecurse(Z)});if(this.maxLength)X.maxItems=this.maxLength;if(this.postfix){let _=this.postfix.map((G)=>G.toJsonSchemaRecurse(Z));Y=Z.fallback.arrayPostfix({code:"arrayPostfix",base:X,elements:_})}}else Y.items=!1,delete Y.maxItems;return Y}}var BQ={},CQ=(Y)=>{if(!Y.defaultables)return[];let Z=[],X="[",_=Y.prefixLength+Y.defaultablesLength-1;for(let G=Y.prefixLength;G<=_;G++){let[$,W]=Y.defaultables[G-Y.prefixLength];Z.push(rY(G,$,W)),X+=`${G}: ${$.id} = ${R1(W)}, `}return X+="]",BQ[X]??=Z},XZ={implementation:TQ,Node:u_},qQ=(Y)=>{let Z=[];if(Y.prefix)for(let X of Y.prefix)Z.push({kind:"prefix",node:X});if(Y.defaultables)for(let[X,_]of Y.defaultables)Z.push({kind:"defaultables",node:X,default:_});if(Y.optionals)for(let X of Y.optionals)Z.push({kind:"optionals",node:X});if(Y.variadic)Z.push({kind:"variadic",node:Y.variadic});if(Y.postfix)for(let X of Y.postfix)Z.push({kind:"postfix",node:X});return Z},m_=(Y)=>Y.reduce((Z,X)=>{if(X.kind==="variadic")Z.variadic=X.node;else if(X.kind==="defaultables")Z.defaultables=Z0(Z.defaultables,[[X.node,X.default]]);else Z[X.kind]=Z0(Z[X.kind],X.node);return Z},{}),_Z="A postfix required element cannot follow an optional or defaultable element",jQ="A postfix element requires a variadic element",t4=(Y)=>{let[Z,...X]=Y.l,[_,...G]=Y.r;if(!Z||!_)return Y;let $=X.at(-1)?.kind==="postfix",W=G.at(-1)?.kind==="postfix",H=Z.kind==="prefix"||_.kind==="prefix"?"prefix":Z.kind==="postfix"||_.kind==="postfix"?"postfix":Z.kind==="variadic"&&_.kind==="variadic"?"variadic":$||W?"prefix":Z.kind==="defaultables"||_.kind==="defaultables"?"defaultables":"optionals";if(Z.kind==="prefix"&&_.kind==="variadic"&&W){let E=t4({...Y,fixedVariants:[],r:G.map((V)=>({...V,kind:"prefix"}))});if(E.disjoint.length===0)Y.fixedVariants.push(E)}else if(_.kind==="prefix"&&Z.kind==="variadic"&&$){let E=t4({...Y,fixedVariants:[],l:X.map((V)=>({...V,kind:"prefix"}))});if(E.disjoint.length===0)Y.fixedVariants.push(E)}let Q=M0(Z.node,_.node,Y.ctx);if(Q instanceof P)if(H==="prefix"||H==="postfix")Y.disjoint.push(...Q.withPrefixKey(H==="prefix"?Y.result.length:`-${X.length+1}`,"required")),Y.result=[...Y.result,{kind:H,node:I.intrinsic.never.internal}];else if(H==="optionals"||H==="defaultables")return Y;else return t4({...Y,fixedVariants:[],l:X.map((E)=>({...E,kind:"prefix"})),r:X.map((E)=>({...E,kind:"prefix"}))});else if(H==="defaultables"){if(Z.kind==="defaultables"&&_.kind==="defaultables"&&Z.default!==_.default)A(iY(Z.default,_.default));Y.result=[...Y.result,{kind:H,node:Q,default:Z.kind==="defaultables"?Z.default:_.kind==="defaultables"?_.default:_0(`Unexpected defaultable intersection from ${Z.kind} and ${_.kind} elements.`)}]}else Y.result=[...Y.result,{kind:H,node:Q}];let J=Y.l.length,z=Y.r.length;if(Z.kind!=="variadic"||J>=z&&(_.kind==="variadic"||z===1))Y.l=X;if(_.kind!=="variadic"||z>=J&&(Z.kind==="variadic"||J===1))Y.r=G;return t4(Y)};var l_=(Y)=>(Z)=>{if(Z.props.length||Z.index){let X=Z.index?.map((G)=>G[Y])??[];for(let G of Z.props)X.push(G[Y]);if(Z.undeclared)X.push(`+ (undeclared): ${Z.undeclared}`);let _=`{ ${X.join(", ")} }`;return Z.sequence?`${_} & ${Z.sequence.description}`:_}return Z.sequence?.description??"{}"},SQ=l_("description"),PQ=l_("expression"),d_=(Y,Z,X)=>{let _=Y.required?"required":"optional";if(!Z.signature.allows(Y.key))return null;let G=U1(Y.value,Z.value,X);if(G instanceof P)return _==="optional"?X.node("optional",{key:Y.key,value:I.intrinsic.never.internal}):G.withPrefixKey(Y.key,Y.kind);return null},vQ=n({kind:"structure",hasAssociatedError:!1,normalize:(Y)=>Y,applyConfig:(Y,Z)=>{if(!Y.undeclared&&Z.onUndeclaredKey!=="ignore")return{...Y,undeclared:Z.onUndeclaredKey};return Y},keys:{required:{child:!0,parse:s0("required"),reduceIo:(Y,Z,X)=>{Z.required=Z0(Z.required,X.map((_)=>_[Y]));return}},optional:{child:!0,parse:s0("optional"),reduceIo:(Y,Z,X)=>{if(Y==="in"){Z.optional=X.map((_)=>_.in);return}for(let _ of X)Z[_.outProp.kind]=Z0(Z[_.outProp.kind],_.outProp.out)}},index:{child:!0,parse:s0("index")},sequence:{child:!0,parse:s0("sequence")},undeclared:{parse:(Y)=>Y==="ignore"?void 0:Y,reduceIo:(Y,Z,X)=>{if(X!=="delete")return;if(Y==="in")delete Z.undeclared;else Z.undeclared="reject"}}},defaults:{description:SQ},intersections:{structure:(Y,Z,X)=>{let _={...Y.inner},G={...Z.inner},$=new P;if(Y.undeclared){let Q=Y.keyof();for(let J of Z.requiredKeys)if(!Q.allows(J))$.add("presence",I.intrinsic.never.internal,Z.propsByKey[J].value,{path:[J]});if(G.optional)G.optional=G.optional.filter((J)=>Q.allows(J.key));if(G.index)G.index=G.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let z=U1(Q,J.signature,X.$);if(z instanceof P)return[];let E=Y6(z,J.value,X.$);if(E.required)G.required=s1(G.required,E.required);if(E.optional)G.optional=s1(G.optional,E.optional);return E.index??[]})}if(Z.undeclared){let Q=Z.keyof();for(let J of Y.requiredKeys)if(!Q.allows(J))$.add("presence",Y.propsByKey[J].value,I.intrinsic.never.internal,{path:[J]});if(_.optional)_.optional=_.optional.filter((J)=>Q.allows(J.key));if(_.index)_.index=_.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let z=U1(Q,J.signature,X.$);if(z instanceof P)return[];let E=Y6(z,J.value,X.$);if(E.required)_.required=s1(_.required,E.required);if(E.optional)_.optional=s1(_.optional,E.optional);return E.index??[]})}let W={};if(Y.undeclared||Z.undeclared)W.undeclared=Y.undeclared==="reject"||Z.undeclared==="reject"?"reject":"delete";let H=Z4({kind:"structure",baseInner:W,l:X4(_),r:X4(G),roots:[],ctx:X});if(H instanceof P)$.push(...H);if($.length)return $;return H}},reduce:(Y,Z)=>{if(Y.index){if(!(Y.required||Y.optional))return;let X=!1,_=Y.required??[],G=Y.optional??[],$=[...G];for(let W of Y.index){for(let H of _){let Q=d_(H,W,Z);if(Q instanceof P)return Q}for(let[H,Q]of G.entries()){let J=d_(Q,W,Z);if(J instanceof P)return J;if(J===null)continue;$[H]=J,X=!0}}if(X)return Z.node("structure",{...Y,optional:$},{prereduced:!0})}}});class o_ extends N1{impliedBasis=I.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Y)=>Y.impliedSiblings??[]);props=s1(this.required,this.optional);propsByKey=i(this.props,(Y,Z)=>[Z.key,Z]);propsByKeyReference=B0(this.propsByKey);expression=PQ(this);requiredKeys=this.required?.map((Y)=>Y.key)??[];optionalKeys=this.optional?.map((Y)=>Y.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Y=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Z}of this.index)Y=Y.concat(Z.branches);return this._keyof=this.$.node("union",Y)}map(Y){return this.$.node("structure",this.props.flatMap(Y).reduce((Z,X)=>{let _=this.propsByKey[X.key];if(L0(X)){if(X.kind!=="required"&&X.kind!=="optional")return A(`Map result must have kind "required" or "optional" (was ${X.kind})`);return Z[X.kind]=Z0(Z[X.kind],X),Z}let G=X.kind??_?.kind??"required",$=i(X,(W,H)=>(W in o4.implementation.keys)?[W,H]:[]);return Z[G]=Z0(Z[G],this.$.node(G,$)),Z},{}))}assertHasKeys(Y){let Z=Y.filter((X)=>!r4(X,this.keyof()));if(Z.length)return A(c_(this.expression,Z))}get(Y,...Z){let X,_=!1,G=kQ(Y);if((typeof G==="string"||typeof G==="symbol")&&this.propsByKey[G])X=this.propsByKey[G].value,_=this.propsByKey[G].required;if(this.index){for(let W of this.index)if(r4(G,W.signature))X=X?.and(W.value)??W.value}if(this.sequence&&r4(G,I.intrinsic.nonNegativeIntegerString))if(y(G,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let W=Number.parseInt(G);if(W<this.sequence.prevariadic.length){let H=this.sequence.prevariadic[W].node;X=X?.and(H)??H,_||=W<this.sequence.prefixLength}else if(this.sequence.variadic){let H=this.$.node("union",this.sequence.variadicOrPostfix);X=X?.and(H)??H}}if(!X){if(this.sequence?.variadic&&y(G,"root")&&G.extends(I.intrinsic.number))return A(bQ(G.expression,this.sequence.expression));return A(c_(this.expression,[G]))}let $=X.get(...Z);return _?$:$.or(I.intrinsic.undefined)}pick(...Y){return this.assertHasKeys(Y),this.$.node("structure",this.filterKeys("pick",Y))}omit(...Y){return this.assertHasKeys(Y),this.$.node("structure",this.filterKeys("omit",Y))}optionalize(){let{required:Y,...Z}=this.inner;return this.$.node("structure",{...Z,optional:this.props.map((X)=>X.hasKind("required")?this.$.node("optional",X.inner):X)})}require(){let{optional:Y,...Z}=this.inner;return this.$.node("structure",{...Z,required:this.props.map((X)=>X.hasKind("optional")?{key:X.key,value:X.value}:X)})}merge(Y){let Z=this.filterKeys("omit",[Y.keyof()]);if(Y.required)Z.required=Z0(Z.required,Y.required);if(Y.optional)Z.optional=Z0(Z.optional,Y.optional);if(Y.index)Z.index=Z0(Z.index,Y.index);if(Y.sequence)Z.sequence=Y.sequence;if(Y.undeclared)Z.undeclared=Y.undeclared;else delete Z.undeclared;return this.$.node("structure",Z)}filterKeys(Y,Z){let X=d8(this.inner),_=(G)=>{let $=Z.some((W)=>r4(G,W));return Y==="pick"?$:!$};if(X.required)X.required=X.required.filter((G)=>_(G.key));if(X.optional)X.optional=X.optional.filter((G)=>_(G.key));if(X.index)X.index=X.index.filter((G)=>_(G.signature));return X}traverseAllows=(Y,Z)=>this._traverse("Allows",Y,Z);traverseApply=(Y,Z)=>this._traverse("Apply",Y,Z);_traverse=(Y,Z,X)=>{let _=X?.currentErrorCount??0;for(let G=0;G<this.props.length;G++)if(Y==="Allows"){if(!this.props[G].traverseAllows(Z,X))return!1}else if(this.props[G].traverseApply(Z,X),X.failFast&&X.currentErrorCount>_)return!1;if(this.sequence){if(Y==="Allows"){if(!this.sequence.traverseAllows(Z,X))return!1}else if(this.sequence.traverseApply(Z,X),X.failFast&&X.currentErrorCount>_)return!1}if(this.index||this.undeclared==="reject"){let G=Object.keys(Z);G.push(...Object.getOwnPropertySymbols(Z));for(let $=0;$<G.length;$++){let W=G[$];if(this.index){for(let H of this.index)if(H.signature.traverseAllows(W,X)){if(Y==="Allows"){if(!z1(W,()=>H.value.traverseAllows(Z[W],X),X))return!1}else if(z1(W,()=>H.value.traverseApply(Z[W],X),X),X.failFast&&X.currentErrorCount>_)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(W)){if(Y==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[W],meta:this.meta}),X.failFast)return!1}}}if(this.structuralMorph&&X&&!X.hasError())X.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Y)=>Y.hasDefault())??[])}declaresKey=(Y)=>(Y in this.propsByKey)||this.index?.some((Z)=>Z.signature.allows(Y))||this.sequence!==void 0&&I.intrinsic.nonNegativeIntegerString.allows(Y);_compileDeclaresKey(Y){let Z=[];if(this.props.length)Z.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let X of this.index)Z.push(Y.invoke(X.signature,{kind:"Allows",arg:"k"}));if(this.sequence)Z.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return Z.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",fQ(this))}structuralMorphRef=this.structuralMorph&&B0(this.structuralMorph);compile(Y){if(Y.traversalKind==="Apply")Y.initializeErrorCount();for(let Z of this.props)if(Y.check(Z),Y.traversalKind==="Apply")Y.returnIfFailFast();if(this.sequence){if(Y.check(this.sequence),Y.traversalKind==="Apply")Y.returnIfFailFast()}if(this.index||this.undeclared==="reject")Y.const("keys","Object.keys(data)"),Y.line("keys.push(...Object.getOwnPropertySymbols(data))"),Y.for("i < keys.length",()=>this.compileExhaustiveEntry(Y));if(Y.traversalKind==="Allows")return Y.return(!0);if(this.structuralMorphRef)Y.if("ctx && !ctx.hasError()",()=>{return Y.line("ctx.queueMorphs(["),hQ(Y,this),Y.line("])")})}compileExhaustiveEntry(Y){if(Y.const("k","keys[i]"),this.index)for(let Z of this.index)Y.if(`${Y.invoke(Z.signature,{arg:"k",kind:"Allows"})}`,()=>Y.traverseKey("k","data[k]",Z.value));if(this.undeclared==="reject")Y.if(`!(${this._compileDeclaresKey(Y)})`,()=>{if(Y.traversalKind==="Allows")return Y.return(!1);return Y.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Y.return())});return Y}reduceJsonSchema(Y,Z){switch(Y.type){case"object":return this.reduceObjectJsonSchema(Y,Z);case"array":let X=this.sequence?.reduceJsonSchema(Y,Z)??Y;if(this.props.length||this.index)return Z.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},Z)});return X;default:return N0.throwInternalOperandError("structure",Y)}}reduceObjectJsonSchema(Y,Z){if(this.props.length){Y.properties={};for(let X of this.props){let _=X.value.toJsonSchemaRecurse(Z);if(typeof X.key==="symbol"){Z.fallback.symbolKey({code:"symbolKey",base:Y,key:X.key,value:_,optional:X.optional});continue}if(X.hasDefault()){let G=typeof X.default==="function"?X.default():X.default;_.default=I.intrinsic.jsonData.allows(G)?G:Z.fallback.defaultValue({code:"defaultValue",base:_,value:G})}Y.properties[X.key]=_}if(this.requiredKeys.length&&Y.properties)Y.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in Y.properties))}if(this.index)for(let X of this.index){let _=X.value.toJsonSchemaRecurse(Z);if(X.signature.equals(I.intrinsic.string)){Y.additionalProperties=_;continue}for(let G of X.signature.branches){if(!G.extends(I.intrinsic.string)){Y=Z.fallback.symbolKey({code:"symbolKey",base:Y,key:null,value:_,optional:!1});continue}let $={type:"string"};if(G.hasKind("morph"))$=Z.fallback.morph({code:"morph",base:G.in.toJsonSchemaRecurse(Z),out:G.out.toJsonSchemaRecurse(Z)});if(!G.hasKind("intersection"))return _0(`Unexpected index branch kind ${G.kind}.`);let{pattern:W}=G.inner;if(W){let H=Object.assign($,{pattern:W[0].rule});for(let Q=1;Q<W.length;Q++)$=Z.fallback.patternIntersection({code:"patternIntersection",base:H,pattern:W[Q].rule});Y.patternProperties??={},Y.patternProperties[H.pattern]=_}}}if(this.undeclared&&!Y.additionalProperties)Y.additionalProperties=!1;return Y}}var GZ={},xQ=(Y)=>{let Z="";for(let X=0;X<Y.defaultable.length;X++)Z+=Y.defaultable[X].defaultValueMorphRef;if(Y.sequence?.defaultValueMorphsReference)Z+=Y.sequence?.defaultValueMorphsReference;if(Y.undeclared==="delete"){if(Z+="delete !(",Y.required)for(let X of Y.required)Z+=X.compiledKey+" | ";if(Y.optional)for(let X of Y.optional)Z+=X.compiledKey+" | ";if(Y.index)for(let X of Y.index)Z+=X.signature.id+" | ";if(Y.sequence)if(Y.sequence.maxLength===null)Z+=d.nonNegativeIntegerString.id;else for(let X=0;X<Y.sequence.tuple.length;X++)Z+=X+" | ";Z+=")"}return Z},fQ=(Y)=>{let Z=xQ(Y);if(!Z)return;if(GZ[Z])return GZ[Z];let X=(_,G)=>{for(let $=0;$<Y.defaultable.length;$++)if(!(Y.defaultable[$].key in _))Y.defaultable[$].defaultValueMorph(_,G);if(Y.sequence?.defaultables)for(let $=_.length-Y.sequence.prefixLength;$<Y.sequence.defaultables.length;$++)Y.sequence.defaultValueMorphs[$](_,G);if(Y.undeclared==="delete"){for(let $ in _)if(!Y.declaresKey($))delete _[$]}return _};return GZ[Z]=X},hQ=(Y,Z)=>{let _=`(data${Z.defaultable.some((G)=>G.defaultValueMorph.length===2)||Z.sequence?.defaultValueMorphs.some((G)=>G.length===2)?", ctx":""})`;return Y.block(`${_} => `,(G)=>{for(let $=0;$<Z.defaultable.length;$++){let{serializedKey:W,defaultValueMorphRef:H}=Z.defaultable[$];G.if(`!(${W} in data)`,(Q)=>Q.line(`${H}${_}`))}if(Z.sequence?.defaultables)G.for(`i < ${Z.sequence.defaultables.length}`,($)=>$.set("data[i]",5),`data.length - ${Z.sequence.prefixLength}`);if(Z.undeclared==="delete")G.forIn("data",($)=>$.if(`!(${Z._compileDeclaresKey($)})`,(W)=>W.line("delete data[k]")));return G.return("data")})},$Z={implementation:vQ,Node:o_},kQ=(Y)=>{if(y(Y,"root")&&Y.hasKind("unit"))Y=Y.unit;if(typeof Y==="number")Y=`${Y}`;return Y},bQ=(Y,Z)=>`${Y} is not allowed as an array index on ${Z}. Use the 'nonNegativeIntegerString' keyword instead.`,Y6=(Y,Z,X)=>{let[_,G]=OX(Y.branches,(W)=>W.hasKind("unit"));if(!_.length)return{index:X.node("index",{signature:Y,value:Z})};let $={};for(let W of _){let H=X.node("required",{key:W.unit,value:Z});$[H.kind]=Z0($[H.kind],H)}if(G.length)$.index=X.node("index",{signature:G,value:Z});return $},yQ=(Y)=>y(Y,"root")?Y.expression:r(Y),c_=(Y,Z)=>`Key${Z.length===1?"":"s"} ${Z.map(yQ).join(", ")} ${Z.length===1?"does":"do"} not exist on ${Y}`;var G4={...D_,alias:n4.implementation,domain:e8.implementation,unit:eY.implementation,proto:s4.implementation,union:aY.implementation,morph:sY.implementation,intersection:nY.implementation,divisor:hY.implementation,pattern:dY.implementation,predicate:fY.implementation,required:ZZ.implementation,optional:o4.implementation,index:YZ.implementation,sequence:XZ.implementation,structure:$Z.implementation};I.defaultConfig=KX(Object.assign(i(G4,(Y,Z)=>[Y,Z.defaults]),{jitless:SX(),clone:CX,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:N0.defaultConfig}));I.resolvedConfig=g4(I.defaultConfig,I.config);var N_={...L_,alias:n4.Node,domain:e8.Node,unit:eY.Node,proto:s4.Node,union:aY.Node,morph:sY.Node,intersection:nY.Node,divisor:hY.Node,pattern:dY.Node,predicate:fY.Node,required:ZZ.Node,optional:o4.Node,index:YZ.Node,sequence:XZ.Node,structure:$Z.Node};class H4 extends OY{get[Y1](){return"module"}}var WZ=(Y,Z)=>new H4(i(Y,(X,_)=>[X,y(_,"module")?WZ(_,Z):Z.bindReference(_)]));var gQ=(Y)=>F0(Y)?Y:("branches"in Y)&&F0(Y.branches)?Y.branches:void 0,pQ=(Y,Z)=>A(`Node of kind ${Z} is not valid as a ${Y} definition`),i_=(Y)=>`#${Y} duplicates public alias ${Y}`,HZ={};I.ambient??={};var r_,s_="function $",mQ=(Y)=>t_(Y,a_(Y)),t_=(Y,Z)=>{let X=Z.write(s_,4),_=Z.compile()();for(let G of Y){if(G.precompilation)continue;if(G.traverseAllows=_[`${G.id}Allows`].bind(_),G.isRoot()&&!G.allowsRequiresContext)G.allows=G.traverseAllows;if(G.traverseApply=_[`${G.id}Apply`].bind(_),_[`${G.id}Optimistic`])G.traverseOptimistic=_[`${G.id}Optimistic`].bind(_);G.precompilation=X}},a_=(Y)=>new u8().return(Y.reduce((Z,X)=>{let _=new y4({kind:"Allows"}).indent();X.compile(_);let G=_.write(`${X.id}Allows`),$=new y4({kind:"Apply"}).indent();X.compile($);let W=$.write(`${X.id}Apply`),H=`${Z}${G},
44
44
  ${W},
45
- `;if(!X.hasKind("union"))return H;let Q=new p4({kind:"Allows",optimistic:!0}).indent();X.compile(Q);let J=Q.write(`${X.id}Optimistic`);return`${H}${J},
45
+ `;if(!X.hasKind("union"))return H;let Q=new y4({kind:"Allows",optimistic:!0}).indent();X.compile(Q);let J=Q.write(`${X.id}Optimistic`);return`${H}${J},
46
46
  `},`{
47
- `)+"}");class X6{config;resolvedConfig;name;get[X1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Y,Z){if(this.config=m4(N.config,Z),this.resolvedConfig=m4(N.resolvedConfig,Z),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(WZ).length}`,this.name in WZ)R(`A Scope already named ${this.name} already exists`);WZ[this.name]=this;let X=Object.entries(Y).map((_)=>this.preparseOwnAliasEntry(..._));for(let[_,G]of X){let $=_;if(_[0]==="#"){if($=_.slice(1),$ in this.aliases)R(o_($));this.aliases[$]=G}else{if($ in this.aliases)R(o_(_));this.aliases[$]=G,this.exportedNames.push($)}if(!y(G,"module")&&!y(G,"generic")&&!O2(G)){let W=this.preparseOwnDefinitionFormat(G,{alias:$});this.resolutions[$]=y(W,"root")?this.bindReference(W):this.createParseContext(W).id}}i_??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[i_.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=N.intrinsic?o(N.intrinsic,(_,G)=>_.startsWith("json")?[]:[_,this.bindReference(G)]):{}}cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Y){return Y}generic=(...Y)=>{let Z=this;return(X,_)=>new A2(Y,_?new r8(X):X,Z,Z,_??null)};units=(Y,Z)=>{let X=[];for(let G of Y)if(!X.includes(G))X.push(G);let _=X.map((G)=>this.node("unit",{unit:G},Z));return this.node("union",_,{...Z,prereduced:!0})};lazyResolutions=[];lazilyResolve(Y,Z){let X=this.node("alias",{reference:Z??"synthetic",resolve:Y},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(Y,Z)=>this.finalize(this.parseSchema(Y,Z));parseSchema=(Y,Z)=>this.node(l4(Y),Y,Z);preparseNode(Y,Z,X){let _=typeof Y==="string"?Y:l4(Z,Y);if(D0(Z)&&Z.kind===_)return Z;if(_==="alias"&&!X?.prereduced){let{reference:W}=t4.implementation.normalize(Z,this);if(W.startsWith("$")){let H=this.resolveRoot(W.slice(1));Z=H,_=H.kind}}else if(_==="union"&&J1(Z,"object")){let W=yQ(Z);if(W?.length===1)Z=W[0],_=l4(Z)}if(D0(Z)&&Z.kind===_)return Z;let $=$4[_].normalize?.(Z,this)??Z;if(D0($))return $.kind===_?$:gQ(_,$.kind);return{...X,$:this,kind:_,def:$,prefix:X.alias??_}}bindReference(Y){let Z;if(D0(Y))Z=Y.$===this?Y:new Y.constructor(Y.attachments,this);else Z=Y.$===this?Y:new A2(Y.params,Y.bodyDef,Y.$,this,Y.hkt);if(!this.resolved)Object.assign(this.referencesById,Z.referencesById);return Z}resolveRoot(Y){return this.maybeResolveRoot(Y)??R(QZ(Y))}maybeResolveRoot(Y){let Z=this.maybeResolve(Y);if(y(Z,"generic"))return;return Z}maybeResolveSubalias(Y){return HZ(this.aliases,Y)??HZ(this.ambient,Y)}get ambient(){return N.ambient}maybeResolve(Y){let Z=this.resolutions[Y];if(Z){if(typeof Z!=="string")return this.bindReference(Z);let _=_1[Z];if(y(_,"root"))return this.resolutions[Y]=_;if(y(_,"context")){if(_.phase==="resolving")return this.node("alias",{reference:`$${Y}`},{prereduced:!0});if(_.phase==="resolved")return _0(`Unexpected resolved context for was uncached by its scope: ${i(_)}`);_.phase="resolving";let G=this.bindReference(this.parseOwnDefinitionFormat(_.def,_));return _.phase="resolved",_1[G.id]=G,_1[_.id]=G,this.resolutions[Y]=G}return _0(`Unexpected nodesById entry for ${Z}: ${i(_)}`)}let X=this.aliases[Y]??this.ambient?.[Y];if(!X)return this.maybeResolveSubalias(Y);if(X=this.normalizeRootScopeValue(X),y(X,"generic"))return this.resolutions[Y]=this.bindReference(X);if(y(X,"module")){if(!X.root)R(YG(Y));return this.resolutions[Y]=this.bindReference(X.root)}return this.resolutions[Y]=this.parse(X,{alias:Y})}createParseContext(Y){let Z=Y.id??dY(Y.prefix);return _1[Z]=Object.assign(Y,{[X1]:"context",$:this,id:Z,phase:"unresolved"})}traversal(Y){return new f1(Y,this.resolvedConfig)}import(...Y){return new J4(o(this.export(...Y),(Z,X)=>[`#${Z}`,X]))}precompilation;_exportedResolutions;_exports;export(...Y){if(!this._exports){this._exports={};for(let X of this.exportedNames){let _=this.aliases[X];this._exports[X]=y(_,"module")?$Z(_,this):r_(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=e_(this,this._exports),this._json=a_(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=t_(this.references);this.precompilation=X.write(n_,4),s_(this.references,X)}this.resolved=!0}let Z=Y.length?Y:this.exportedNames;return new J4(o(Z,(X,_)=>[_,this._exports[_]]))}resolve(Y){return this.export()[Y]}node=(Y,Z,X={})=>{let _=this.preparseNode(Y,Z,X);if(D0(_))return this.bindReference(_);let G=this.createParseContext(_),$=cY(G),W=this.bindReference($);return _1[G.id]=W};parse=(Y,Z={})=>this.finalize(this.parseDefinition(Y,Z));parseDefinition(Y,Z={}){if(y(Y,"root"))return this.bindReference(Y);let X=this.preparseOwnDefinitionFormat(Y,Z);if(y(X,"root"))return this.bindReference(X);let _=this.createParseContext(X);_1[_.id]=_;let G=this.bindReference(this.parseOwnDefinitionFormat(Y,_));if(G.isCyclic)G=w_(G,_.id);return _1[_.id]=G,G}finalize(Y){if(r_(Y),!Y.precompilation&&!this.resolvedConfig.jitless)pQ(Y.references);return Y}}class JZ extends X6{parseOwnDefinitionFormat(Y,Z){return cY(Z)}preparseOwnDefinitionFormat(Y,Z){return this.preparseNode(l4(Y),Y,Z)}preparseOwnAliasEntry(Y,Z){return[Y,Z]}normalizeRootScopeValue(Y){return Y}}var r_=(Y)=>{let Z=Y.references.filter((X)=>X.hasKind("alias"));for(let X of Z){Object.assign(X.referencesById,X.resolution.referencesById);for(let _ of Y.references)if(X.id in _.referencesById)Object.assign(_.referencesById,X.referencesById)}return Y},a_=(Y)=>o(Y,(Z,X)=>[Z,y(X,"root")||y(X,"generic")?X.json:y(X,"module")?a_(X):_0(`Unexpected resolution ${i(X)}`)]),HZ=(Y,Z)=>{let X=Z.indexOf(".");if(X===-1)return;let _=Z.slice(0,X),G=Y[_];if(G===void 0)return;if(!y(G,"module"))return R(mQ(_));let $=Z.slice(X+1),W=G[$];if(W===void 0)return HZ(G,$);if(y(W,"root")||y(W,"generic"))return W;if(y(W,"module"))return W.root??R(YG(Z));_0(`Unexpected resolution for alias '${Z}': ${i(W)}`)},_6=(Y,Z)=>new JZ(Y,Z),Y8=new JZ({});var e_=(Y,Z)=>{let X={};for(let _ in Z){let G=Z[_];if(y(G,"module")){let $=e_(Y,G),W=o($,(H,Q)=>[`${_}.${H}`,Q]);Object.assign(X,W)}else if(y(G,"root")||y(G,"generic"))X[_]=G;else _0(`Unexpected scope resolution ${i(G)}`)}return X},QZ=(Y)=>`'${Y}' is unresolvable`,mQ=(Y)=>`'${Y}' must reference a module to be accessed using dot syntax`,YG=(Y)=>`Reference to submodule '${Y}' must specify an alias`;Y8.export();var{schema:H0,node:Q4,defineSchema:bw,generic:B1}=Y8;var UZ="^(?:0|[1-9]\\d*)$",uQ=new RegExp(UZ),pw=B0(uQ);var ZG=_6({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();N.intrinsic={...ZG};var XG=_6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:UZ}},{prereducedAliases:!0}).export();Object.assign(N.intrinsic,XG);var dQ=_6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),d={...ZG,...XG,...dQ,emptyStructure:Q4("structure",{},{prereduced:!0})};N.intrinsic={...d};var GG=(Y)=>typeof Y==="string"&&Y[0]==="d"&&(Y[1]==="'"||Y[1]==='"')&&Y.at(-1)===Y[1],_G=(Y)=>Y.toString()!=="Invalid Date",$G=(Y)=>Y.slice(2,-1),zZ=(Y)=>`'${Y}' could not be parsed by the Date constructor`,WG=(Y,Z)=>cQ(Y,Z),cQ=(Y,Z)=>{let X=new Date(Y);if(_G(X))return X;let _=yX(Y);if(_!==void 0){let G=new Date(_);if(_G(G))return G}return Z?R(Z===!0?zZ(Y):Z):void 0};var FZ=(Y,Z)=>{let X=Y.scanner.shiftUntil(lQ[JG[Z]]);if(Y.scanner.lookahead==="")return Y.error(iQ(X,Z));if(Y.scanner.shift(),Z==="/"){try{new RegExp(X)}catch(_){R(String(_))}Y.root=Y.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(g0(Z,EZ))Y.root=Y.ctx.$.node("unit",{unit:X});else{let _=WG(X,zZ(X));Y.root=Y.ctx.$.node("unit",{meta:X,unit:_})}},EZ={"'":1,'"':1},HG={"/":1,"'":1,'"':1},JG={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},lQ={"'":(Y)=>Y.lookahead==="'",'"':(Y)=>Y.lookahead==='"',"/":(Y)=>Y.lookahead==="/"},oQ={'"':"double-quote","'":"single-quote","/":"forward slash"},iQ=(Y,Z)=>`${Z}${Y} requires a closing ${oQ[JG[Z]]}`;var QG=(Y)=>`Private type references should not include '#'. Use '${Y}' instead.`,G6="Optional definitions like 'string?' are only valid as properties in an object or tuple",$6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var UG={">":!0,">=":!0},zG={"<":!0,"<=":!0};var U4={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},FG=(Y)=>`Unmatched )${Y===""?"":` before ${Y}`}`,W6=(Y)=>`Missing ${Y}`,EG=(Y,Z)=>`Left bounds are only valid when paired with right bounds (try ...${Z}${Y})`,H6=(Y)=>`Left-bounded expressions must specify their limits using < or <= (was ${Y})`,OG=(Y,Z,X,_)=>`An expression may have at most one left bound (parsed ${Y}${U4[Z]}, ${X}${U4[_]})`;var VG=(Y,Z,X)=>DG(Y,Z,X,[]),DG=(Y,Z,X,_)=>{let G=X.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Z.params.length)return X.error(OZ(Y,Z.names,_.map(($)=>$.expression)));return _}if(G.finalizer===",")return DG(Y,Z,X,_);return G.error(W6(">"))},OZ=(Y,Z,X)=>`${Y}<${Z.join(", ")}> requires exactly ${Z.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var VZ=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator();if(Z==="keyof")Y.addPrefix("keyof");else Y.root=nQ(Y,Z)},rQ=(Y,Z,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(OZ(Y,Z.names,[]));let G=VG(Y,Z,X);return Z(...G)},nQ=(Y,Z)=>sQ(Y,Z)??tQ(Y,Z)??Y.error(Z===""?Y.scanner.lookahead==="#"?QG(Y.shiftedByOne().scanner.shiftUntilNextTerminator()):DZ(Y):QZ(Z)),sQ=(Y,Z)=>{if(Y.ctx.args?.[Z]){let _=Y.ctx.args[Z];if(typeof _!=="string")return _;return Y.ctx.$.node("alias",{reference:_},{prereduced:!0})}let X=Y.ctx.$.maybeResolve(Z);if(y(X,"root"))return X;if(X===void 0)return;if(y(X,"generic"))return rQ(Z,X,Y);return R(`Unexpected resolution ${i(X)}`)},tQ=(Y,Z)=>{let X=gX(Z);if(X!==void 0)return Y.ctx.$.node("unit",{unit:X});let _=mX(Z);if(_!==void 0)return Y.ctx.$.node("unit",{unit:_})},DZ=(Y)=>{let Z=Y.previousOperator();return Z?LZ(Z,Y.scanner.unscanned):aQ(Y.scanner.unscanned)},LZ=(Y,Z="")=>`Token '${Y}' requires a right operand${Z?` before '${Z}'`:""}`,aQ=(Y)=>`Expected an expression${Y?` before '${Y}'`:""}`;var MZ=(Y)=>Y.scanner.lookahead===""?Y.error(DZ(Y)):Y.scanner.lookahead==="("?Y.shiftedByOne().reduceGroupOpen():Y.scanner.lookaheadIsIn(HG)?FZ(Y,Y.scanner.shift()):Y.scanner.lookaheadIsIn(V2)?MZ(Y.shiftedByOne()):Y.scanner.lookahead==="d"?Y.scanner.nextLookahead in EZ?FZ(Y,`${Y.scanner.shift()}${Y.scanner.shift()}`):VZ(Y):VZ(Y);class X2 extends IY{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in X2.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...V2};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(Y,Z)=>Y===">"?Z[0]==="="?Z[1]==="=":Z.trimStart()===""||g0(Z.trimStart()[0],X2.terminatingChars):Y==="="?Z[0]!=="=":Y===","||Y==="?"}var MG=(Y,Z)=>{let X=eQ(Y,Z);if(Y.root.hasKind("unit")){if(typeof Y.root.unit==="number"){Y.reduceLeftBound(Y.root.unit,X),Y.unsetRoot();return}if(Y.root.unit instanceof Date){let _=`d'${Y.root.description??Y.root.unit.toISOString()}'`;Y.unsetRoot(),Y.reduceLeftBound(_,X);return}}return ZU(Y,X)},AG={"<":1,">":1,"=":1},eQ=(Y,Z)=>Y.scanner.lookaheadIs("=")?`${Z}${Y.scanner.shift()}`:Z;var LG=(Y,Z,X,_)=>{if(X.extends(N.intrinsic.number)){if(typeof Z!=="number")return R(AZ(Y,Z,_));return Y==="=="?["min","max"]:Y[0]===">"?["min"]:["max"]}if(X.extends(N.intrinsic.lengthBoundable)){if(typeof Z!=="number")return R(AZ(Y,Z,_));return Y==="=="?["exactLength"]:Y[0]===">"?["minLength"]:["maxLength"]}if(X.extends(N.intrinsic.Date))return Y==="=="?["after","before"]:Y[0]===">"?["after"]:["before"];return R(H_(X.expression))},YU=(Y)=>({rule:GG(Y.limit)?$G(Y.limit):Y.limit,exclusive:Y.comparator.length===1}),ZU=(Y,Z)=>{let X=Y.unsetRoot(),_=Y.scanner.location;Y.parseOperand();let G=Y.unsetRoot(),$=Y.scanner.sliceChars(_,Y.scanner.location);if(Y.root=X,!G.hasKind("unit")||typeof G.unit!=="number"&&!(G.unit instanceof Date))return Y.error(AZ(Z,$,"right"));let W=G.unit,H=Z.length===1,Q=LG(Z,typeof W==="number"?W:$,X,"right");for(let U of Q)Y.constrainRoot(U,Z==="=="?{rule:W}:{rule:W,exclusive:H});if(!Y.branches.leftBound)return;if(!g0(Z,zG))return Y.error(H6(Z));let J=LG(Y.branches.leftBound.comparator,Y.branches.leftBound.limit,X,"left");Y.constrainRoot(J[0],YU(Y.branches.leftBound)),Y.branches.leftBound=null},AZ=(Y,Z,X)=>`Comparator ${X==="left"?U4[Y]:Y} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Z})`;var wG=(Y)=>{Y.scanner.shiftUntilNonWhitespace();let Z=Y.scanner.shiftUntilNextTerminator();Y.root=Y.root.brand(Z)};var NG=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator(),X=pX(Z,{errorOnFail:RG(Z)});if(X===0)Y.error(RG(0));Y.root=Y.root.constrain("divisor",X)},RG=(Y)=>`% operator must be followed by a non-zero integer literal (was ${Y})`;var wZ=(Y)=>{let Z=Y.scanner.shift();return Z===""?Y.finalize(""):Z==="["?Y.scanner.shift()==="]"?Y.setRoot(Y.root.array()):Y.error(XU):Z==="|"?Y.scanner.lookahead===">"?Y.shiftedByOne().pushRootToBranch("|>"):Y.pushRootToBranch(Z):Z==="&"?Y.pushRootToBranch(Z):Z===")"?Y.finalizeGroup():X2.lookaheadIsFinalizing(Z,Y.scanner.unscanned)?Y.finalize(Z):g0(Z,AG)?MG(Y,Z):Z==="%"?NG(Y):Z==="#"?wG(Y):(Z in V2)?wZ(Y):Y.error(J6(Z))},J6=(Y,Z="")=>`'${Y}' is not allowed here${Z&&` (should be ${Z})`}`,XU="Missing expected ']'";var IG=(Y)=>{let Z=Y.unsetRoot();Y.parseOperand();let X=Y.unsetRoot();if(!X.hasKind("unit"))return Y.error(_U(X.expression));let _=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Z,"=",_]},_U=(Y)=>`Default value '${Y}' must a literal value`;var RZ=(Y,Z)=>{let X=Z.$.maybeResolveRoot(Y);if(X)return X;if(Y.endsWith("[]")){let $=Z.$.maybeResolveRoot(Y.slice(0,-2));if($)return $.array()}let _=new z4(new X2(Y),Z),G=GU(_);if(_.finalizer===">")R(J6(">"));return G},GU=(Y)=>{Y.parseOperand();let Z=Z8(Y).root;if(!Z)return _0(`Root was unexpectedly unset after parsing string '${Y.scanner.scanned}'`);if(Y.finalizer==="=")Z=IG(Y);else if(Y.finalizer==="?")Z=[Z,"?"];if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.lookahead)R(J6(Y.scanner.lookahead));return Z},Z8=(Y)=>{while(Y.finalizer===void 0)$U(Y);return Y},$U=(Y)=>Y.hasRoot()?Y.parseOperator():Y.parseOperand();class z4{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Y,Z){this.scanner=Y,this.ctx=Z}error(Y){return R(Y)}hasRoot(){return this.root!==void 0}setRoot(Y){this.root=Y}unsetRoot(){let Y=this.root;return this.root=void 0,Y}constrainRoot(...Y){this.root=this.root.constrain(Y[0],Y[1])}finalize(Y){if(this.groups.length)return this.error(W6(")"));this.finalizeBranches(),this.finalizer=Y}reduceLeftBound(Y,Z){let X=U4[Z];if(!g0(X,UG))return this.error(H6(Z));if(this.branches.leftBound)return this.error(OG(this.branches.leftBound.limit,this.branches.leftBound.comparator,Y,X));this.branches.leftBound={comparator:X,limit:Y}}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 Y=this.groups.pop();if(!Y)return this.error(FG(this.scanner.unscanned));this.branches=Y}addPrefix(Y){this.branches.prefixes.push(Y)}applyPrefixes(){while(this.branches.prefixes.length){let Y=this.branches.prefixes.pop();this.root=Y==="keyof"?this.root.keyof():_0(`Unexpected prefix '${Y}'`)}}pushRootToBranch(Y){this.assertRangeUnset(),this.applyPrefixes();let Z=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(Z)??Z,Y==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Y==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return Z8(new z4(this.scanner,this.ctx))}parseOperator(){return wZ(this)}parseOperand(){return MZ(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(EG(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 WU="An empty string is not a valid generic parameter name",Q6=(Y,Z,X)=>{Y.shiftUntilNonWhitespace();let _=Y.shiftUntilNextTerminator();if(_===""){if(Y.lookahead===""&&Z.length)return Z;return R(WU)}return Y.shiftUntilNonWhitespace(),HU(Y,_,Z,X)},TG="extends ",HU=(Y,Z,X,_)=>{if(Y.shiftUntilNonWhitespace(),Y.unscanned.startsWith(TG))Y.jumpForward(TG.length);else{if(Y.lookahead===",")Y.shift();return X.push(Z),Q6(Y,X,_)}let G=Z8(new z4(Y,_));return X.push([Z,G.root]),Q6(Y,X,_)};class NZ extends x1{$;constructor(Y){super((...Z)=>new X8(Y)(...Z),{bind:Y});this.$=Y}in(Y){return new X8(this.$,Y===void 0?void 0:this.$.parse(Y))}at(Y,Z){return new X8(this.$).at(Y,Z)}case(Y,Z){return new X8(this.$).case(Y,Z)}}class X8 extends x1{$;in;key;branches=[];constructor(Y,Z){super((X)=>this.caseEntries(Object.entries(X).map(([_,G])=>_==="default"?[_,G]:[this.$.parse(_),G])));this.$=Y,this.in=Z}at(Y,Z){if(this.key)R(QU);if(this.branches.length)R(JU);return this.key=Y,Z?this.match(Z):this}case(Y,Z){return this.caseEntry(this.$.parse(Y),Z)}caseEntry(Y,Z){let _=(this.key?this.$.parse({[this.key]:Y}):Y).pipe(Z);return this.branches.push(_),this}match(Y){return this(Y)}strings(Y){return this.caseEntries(Object.entries(Y).map(([Z,X])=>Z==="default"?[Z,X]:[this.$.node("unit",{unit:Z}),X]))}caseEntries(Y){for(let Z=0;Z<Y.length;Z++){let[X,_]=Y[Z];if(X==="default"){if(Z!==Y.length-1)R("default may only be specified as the last key of a switch definition");return this.default(_)}if(typeof _!=="function")return R(`Value for case "${X}" must be a function (was ${y0(_)})`);this.caseEntry(X,_)}return this}default(Y){if(typeof Y==="function")this.case(d.unknown,Y);let Z={branches:this.branches,ordered:!0};if(Y==="never"||Y==="assert")Z.meta={onFail:KG};let X=this.$.node("union",Z);if(!this.in)return this.$.finalize(X);let _=this.in.pipe(X);if(Y==="never"||Y==="assert")_=_.configureReferences({onFail:KG},"self");return this.$.finalize(_)}}var KG=(Y)=>Y.throw(),JU="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",QU="At most one key matcher may be specified per expression";var U6=(Y,Z)=>{if(F0(Y)){if(Y[1]==="=")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"=",Y[2]];if(Y[1]==="?")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"?"]}return z6(Y,Z)},BG="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",CG="Only required keys may specify default values, e.g. { value: 'number = 0' }";var qG=(Y,Z)=>{let X,_={},G=S2(Y);for(let[W,H]of G){let Q=FU(W);if(Q.kind==="spread"){if(!c1(_))return R(zU);let D=Z.$.parseOwnDefinitionFormat(H,Z);if(D.equals(d.object))continue;if(!D.hasKind("intersection")||!D.basis?.equals(d.object))return R(EU(D.expression));X=D.structure;continue}if(Q.kind==="undeclared"){if(H!=="reject"&&H!=="delete"&&H!=="ignore")R(UU(H));_.undeclared=H;continue}let J=U6(H,Z),U=Q;if(Q.kind==="required"){if(!F0(J))IZ(_,"required",{key:Q.normalized,value:J},Z);else IZ(_,"optional",J[1]==="="?{key:Q.normalized,value:J[0],default:J[2]}:{key:Q.normalized,value:J[0]},Z);continue}if(F0(J)){if(J[1]==="?")R(BG);if(J[1]==="=")R(CG)}if(Q.kind==="optional"){IZ(_,"optional",{key:Q.normalized,value:J},Z);continue}let F=Z.$.parseOwnDefinitionFormat(U.normalized,Z),V=Z6(F,J,Z.$);if(V.index)_.index=Z0(_.index,V.index);if(V.required)_.required=Z0(_.required,V.required)}let $=Z.$.node("structure",_);return Z.$.parseSchema({domain:"object",structure:X?.merge($)??$})},IZ=(Y,Z,X,_)=>{Y[Z]=Z0(Y[Z],_.$.node(Z,X))},UU=(Y)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${i(Y)})`,zU="Spread operator may only be used as the first key in an object",FU=(Y)=>typeof Y==="symbol"?{kind:"required",normalized:Y}:Y.at(-1)==="?"?Y.at(-2)===f4?{kind:"required",normalized:`${Y.slice(0,-2)}?`}:{kind:"optional",normalized:Y.slice(0,-1)}:Y[0]==="["&&Y.at(-1)==="]"?{kind:"index",normalized:Y.slice(1,-1)}:Y[0]===f4&&Y[1]==="["&&Y.at(-1)==="]"?{kind:"required",normalized:Y.slice(1)}:Y==="..."?{kind:"spread"}:Y==="+"?{kind:"undeclared"}:{kind:"required",normalized:Y==="\\..."?"...":Y==="\\+"?"+":Y},EU=(Y)=>`Spread operand must resolve to an object literal type (was ${Y})`;var SG=(Y,Z)=>IU(Y)?fG[Y[0]](Y,Z):RU(Y)?xG[Y[1]](Y,Z):null,OU=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[1],Z).keyof(),TZ=(Y,Z)=>{if(Y[2]===void 0)return R(LZ(Y[1],""));let X=Z.$.parseOwnDefinitionFormat(Y[0],Z),_=Z.$.parseOwnDefinitionFormat(Y[2],Z);if(Y[1]==="|")return Z.$.node("union",{branches:[X,_]});let G=Y[1]==="&"?F1(X,_,Z.$):c4(X,_,Z.$);if(G instanceof P)return G.throw();return G},VU=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).array(),DU=(Y,Z)=>{if(typeof Y[2]!=="function")return R(PG("=>",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).pipe(Y[2])},PG=(Y,Z)=>`${Y===":"?"Narrow":"Morph"} expression requires a function following '${Y}' (was ${typeof Z})`,LU=(Y,Z)=>{if(typeof Y[2]!=="function")return R(PG(":",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).constrain("predicate",Y[2])},MU=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).configureReferences(Y[2],"shallow"),vG=(Y)=>Y,AU=vG({"[]":VU,"?":()=>R(G6)}),wU=vG({"|":TZ,"&":TZ,":":LU,"=>":DU,"|>":TZ,"@":MU,"=":()=>R($6)}),xG={...AU,...wU},RU=(Y)=>xG[Y[1]]!==void 0,NU=(Y)=>Y,fG=NU({keyof:OU,instanceof:(Y,Z)=>{if(typeof Y[1]!=="function")return R(jG(v4(Y[1])));let X=Y.slice(1).map((_)=>typeof _==="function"?Z.$.node("proto",{proto:_}):R(jG(v4(_))));return X.length===1?X[0]:Z.$.node("union",{branches:X})},"===":(Y,Z)=>Z.$.units(Y.slice(1))}),IU=(Y)=>fG[Y[0]]!==void 0,jG=(Y)=>`Expected a constructor following 'instanceof' operator (was ${Y})`;var bG=(Y,Z)=>{let X=[{}],_=0;while(_<Y.length){let G=!1;if(Y[_]==="..."&&_<Y.length-1)G=!0,_++;let $=U6(Y[_],Z),[W,H,Q]=!F0($)?[$]:$;if(_++,G){if(!W.extends(N.intrinsic.Array))return R(BU(W.expression));X=X.flatMap((J)=>W.distribute((U)=>KU(c8(J),U)))}else X=X.map((J)=>{if(H==="?")return yG(J,W);if(H==="=")return TU(J,W,Q);return KZ(J,W)})}return Z.$.parseSchema(X.map((G)=>c1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},KZ=(Y,Z)=>{if(Y.defaultables||Y.optionals)return R(Y.variadic?XZ:CU);if(Y.variadic)Y.postfix=Z0(Y.postfix,Z);else Y.prefix=Z0(Y.prefix,Z);return Y},yG=(Y,Z)=>{if(Y.variadic)return R(gG);return Y.optionals=Z0(Y.optionals,Z),Y},TU=(Y,Z,X)=>{if(Y.variadic)return R(gG);if(Y.optionals)return R(qU);return Y.defaultables=Z0(Y.defaultables,[[Z,X]]),Y},hG=(Y,Z)=>{if(Y.postfix)R(kG);if(Y.variadic){if(!Y.variadic.equals(Z))R(kG)}else Y.variadic=Z.internal;return Y},KU=(Y,Z)=>{let X=Z.select({method:"find",kind:"sequence"});if(!X)return hG(Y,N.intrinsic.unknown);if(X.prefix)for(let _ of X.prefix)KZ(Y,_);if(X.optionals)for(let _ of X.optionals)yG(Y,_);if(X.variadic)hG(Y,X.variadic);if(X.postfix)for(let _ of X.postfix)KZ(Y,_);return Y},BU=(Y)=>`Spread element must be an array (was ${Y})`,kG="A tuple may have at most one variadic element",CU="A required element may not follow an optional element",gG="An optional element may not follow a variadic element";var qU="A defaultable element may not follow an optional element without a default";var jU={},z6=(Y,Z)=>{if(typeof Y==="string"){if(Z.args&&Object.keys(Z.args).some((_)=>Y.includes(_)))return RZ(Y,Z);let X=jU[Z.$.name]??={};return X[Y]??=RZ(Y,Z)}return J1(Y,"object")?SU(Y,Z):R(BZ(y0(Y)))},SU=(Y,Z)=>{let X=P4(Y);switch(X){case void 0:if(y(Y,"root"))return Y;return qG(Y,Z);case"Array":return PU(Y,Z);case"RegExp":return Z.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0});case"Function":{let _=O2(Y)?Y():Y;if(y(_,"root"))return _;return R(BZ("Function"))}default:return R(BZ(X??i(Y)))}},PU=(Y,Z)=>SG(Y,Z)??bG(Y,Z),BZ=(Y)=>`Type definitions must be strings or objects (was ${Y})`;class CZ extends x1{constructor(Y){let Z=Object.assign({errors:U1,hkt:s0,$:Y,raw:Y.parse,module:Y.constructor.module,scope:Y.constructor.scope,define:Y.define,match:Y.match,generic:Y.generic,schema:Y.schema,keywords:Y.ambient,unit:Y.unit,enumerated:Y.enumerated,instanceOf:Y.instanceOf,valueOf:Y.valueOf,or:Y.or,and:Y.and,merge:Y.merge,pipe:Y.pipe},Y.ambientAttachments);super((...X)=>{if(X.length===1)return Y.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0].at(-1)===">"){let _=X[0].slice(1,-1),G=Y.parseGenericParams(_,{});return new A2(G,X[1],Y,Y,null)}return Y.parse(X)},{bind:Y,attach:Z})}}var F4=N;class F6 extends X6{get ambientAttachments(){if(!F4.typeAttachments)return;return this.cacheGetter("ambientAttachments",o(F4.typeAttachments,(Y,Z)=>[Y,this.bindReference(Z)]))}preparseOwnAliasEntry(Y,Z){let X=Y.indexOf("<");if(X===-1){if(y(Z,"module")||y(Z,"generic"))return[Y,Z];let $=this.name==="ark"?Y:Y==="root"?this.name:`${this.name}.${Y}`,W=this.resolvedConfig.keywords?.[$];if(W)Z=[Z,"@",W];return[Y,Z]}if(Y.at(-1)!==">")R("'>' must be the last character of a generic declaration in a scope");let _=Y.slice(0,X),G=Y.slice(X+1,-1);return[_,()=>{let $=this.parseGenericParams(G,{alias:_});return G_($,Z,this)}]}parseGenericParams(Y,Z){return Q6(new X2(Y),[],this.createParseContext({...Z,def:Y,prefix:"generic"}))}normalizeRootScopeValue(Y){if(O2(Y)&&!y(Y,"generic"))return Y();return Y}preparseOwnDefinitionFormat(Y,Z){return{...Z,def:Y,prefix:Z.alias??"type"}}parseOwnDefinitionFormat(Y,Z){if(!(Z.alias&&(Z.alias in this.aliases))&&!Z.args)Z.args={this:Z.id};let _=z6(Y,Z);if(F0(_)){if(_[1]==="=")return R($6);if(_[1]==="?")return R(G6)}return _}unit=(Y)=>this.units([Y]);valueOf=(Y)=>this.units(TX(Y));enumerated=(...Y)=>this.units(Y);instanceOf=(Y)=>this.node("proto",{proto:Y},{prereduced:!0});or=(...Y)=>this.schema(Y.map((Z)=>this.parse(Z)));and=(...Y)=>Y.reduce((Z,X)=>Z.and(this.parse(X)),this.intrinsic.unknown);merge=(...Y)=>Y.reduce((Z,X)=>Z.merge(this.parse(X)),this.intrinsic.object);pipe=(...Y)=>this.intrinsic.unknown.pipe(...Y);match=new NZ(this);declare=()=>({type:this.type});define(Y){return Y}type=new CZ(this);static scope=(Y,Z={})=>new F6(Y,Z);static module=(Y,Z={})=>this.scope(Y,Z).export()}var qZ=Object.assign(F6.scope,{define:(Y)=>Y}),Y0=F6;class pG extends s0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var vU=B1(["base",d.object],["props",d.object])((Y)=>Y.base.merge(Y.props),pG),mG=Y0.module({Key:d.key,Merge:vU});class uG extends s0{}var xU=B1("element")((Y)=>{let Z=Y.element.exclude(d.Array),X=Z.array();return Z.rawOr(X).pipe(E2).distribute((_)=>_.assertHasKind("morph").declareOut(X),H0)},uG),dG=Y0.module({root:d.Array,readonly:"root",index:d.nonNegativeIntegerString,liftFrom:xU},{name:"Array"});var jZ=H0(["string",v2.FileConstructor]),fU=jZ.rawOr(jZ.array()),cG=H0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:fU}}),lG=Y0.module({root:["instanceof",FormData],value:jZ,parsed:cG,parse:H0({in:FormData,morphs:(Y)=>{let Z={};for(let[X,_]of Y)if(X in Z){let G=Z[X];if(typeof G==="string"||G instanceof v2.FileConstructor)Z[X]=[G,_];else G.push(_)}else Z[X]=_;return Z},declaredOut:cG})},{name:"FormData"});var oG=Y0.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 hU={Boolean:1,Number:1,String:1},iG=Y0.module({...o({...VY,...LY},(Y,Z)=>(Y in hU)?[]:[Y,["instanceof",Z]]),Array:dG,TypedArray:oG,FormData:lG});var kU=H0({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"}),bU=H0({domain:"number",divisor:1}),E6=Y0.module({root:d.number,integer:bU,epoch:kU,safe:H0({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 N0=(Y,Z,X)=>{let _={domain:"string",pattern:{rule:Y.source,flags:Y.flags,meta:Z}};if(X)_.meta={format:X};return Q4("intersection",_)},rG=N0(h4,"a well-formed integer string"),W9=Y0.module({root:rG,parse:H0({in:rG,morphs:(Y,Z)=>{let X=Number.parseInt(Y);return Number.isSafeInteger(X)?X:Z.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:d.integer})},{name:"string.integer"}),yU=N0(/^[\dA-Fa-f]+$/,"hex characters only"),gU=Y0.module({root:N0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:N0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),nG=N0(/^[A-Z].*$/,"capitalized"),pU=Y0.module({root:H0({in:"string",morphs:(Y)=>Y.charAt(0).toUpperCase()+Y.slice(1),declaredOut:nG}),preformatted:nG},{name:"string.capitalize"}),mU=(Y)=>{let Z=Y.replaceAll(/[ -]+/g,""),X=0,_,G,$=!1;for(let W=Z.length-1;W>=0;W--){if(_=Z.substring(W,W+1),G=Number.parseInt(_,10),$)G*=2,X+=G>=10?G%10+1:G;else X+=G;$=!$}return!!(X%10===0?Z:!1)},uU=/^(?: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}))$/,dU=H0({domain:"string",pattern:{meta:"a credit card number",rule:uU.source},predicate:{meta:"a credit card number",predicate:mU}});var cU=/^([+-]?\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 lU=(Y)=>!Number.isNaN(new Date(Y).valueOf()),sG=H0({domain:"string",predicate:{meta:"a parsable date",predicate:lU}}).assertHasKind("intersection"),tG=W9.root.internal.narrow((Y,Z)=>{let X=Number.parseInt(Y),_=E6.epoch(X);if(_ instanceof U1)return Z.errors.merge(_),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),oU=Y0.module({root:tG,parse:H0({in:tG,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.epoch"}),aG=N0(cU,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),iU=Y0.module({root:aG,parse:H0({in:aG,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.iso"}),rU=Y0.module({root:sG,parse:H0({declaredIn:sG,in:"string",morphs:(Y,Z)=>{let X=new Date(Y);if(Number.isNaN(X.valueOf()))return Z.error("a parsable date");return X},declaredOut:d.Date}),iso:iU,epoch:oU},{name:"string.date"}),nU=N0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),eG="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",w2=`(${eG}[.]){3}${eG}`,sU=new RegExp(`^${w2}$`),x0="(?:[0-9a-fA-F]{1,4})",tU=new RegExp(`^((?:${x0}:){7}(?:${x0}|:)|(?:${x0}:){6}(?:${w2}|:${x0}|:)|(?:${x0}:){5}(?::${w2}|(:${x0}){1,2}|:)|(?:${x0}:){4}(?:(:${x0}){0,1}:${w2}|(:${x0}){1,3}|:)|(?:${x0}:){3}(?:(:${x0}){0,2}:${w2}|(:${x0}){1,4}|:)|(?:${x0}:){2}(?:(:${x0}){0,3}:${w2}|(:${x0}){1,5}|:)|(?:${x0}:){1}(?:(:${x0}){0,4}:${w2}|(:${x0}){1,6}|:)|(?::((?::${x0}){0,5}:${w2}|(?::${x0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),aU=Y0.module({root:["v4 | v6","@","an IP address"],v4:N0(sU,"an IPv4 address","ipv4"),v6:N0(tU,"an IPv6 address","ipv6")},{name:"string.ip"}),E4="a JSON string",H9=(Y)=>{if(!(Y instanceof SyntaxError))throw Y;return`must be ${E4} (${Y})`},eU=H0({meta:E4,domain:"string",predicate:{meta:E4,predicate:(Y,Z)=>{try{return JSON.parse(Y),!0}catch(X){return Z.reject({code:"predicate",expected:E4,problem:H9(X)})}}}}),Yz=(Y,Z)=>{if(Y.length===0)return Z.error({code:"predicate",expected:E4,actual:"empty"});try{return JSON.parse(Y)}catch(X){return Z.error({code:"predicate",expected:E4,problem:H9(X)})}},Zz=Y0.module({root:eU,parse:H0({meta:"safe JSON string parser",in:"string",morphs:Yz,declaredOut:d.jsonObject})},{name:"string.json"}),Y9=N0(/^[a-z]*$/,"only lowercase letters"),Xz=Y0.module({root:H0({in:"string",morphs:(Y)=>Y.toLowerCase(),declaredOut:Y9}),preformatted:Y9},{name:"string.lower"}),J9=["NFC","NFD","NFKC","NFKD"],_8=o(J9,(Y,Z)=>[Z,H0({domain:"string",predicate:(X)=>X.normalize(Z)===X,meta:`${Z}-normalized unicode`})]),O6=o(J9,(Y,Z)=>[Z,H0({in:"string",morphs:(X)=>X.normalize(Z),declaredOut:_8[Z]})]),_z=Y0.module({root:O6.NFC,preformatted:_8.NFC},{name:"string.normalize.NFC"}),Gz=Y0.module({root:O6.NFD,preformatted:_8.NFD},{name:"string.normalize.NFD"}),$z=Y0.module({root:O6.NFKC,preformatted:_8.NFKC},{name:"string.normalize.NFKC"}),Wz=Y0.module({root:O6.NFKD,preformatted:_8.NFKD},{name:"string.normalize.NFKD"}),Hz=Y0.module({root:"NFC",NFC:_z,NFD:Gz,NFKC:$z,NFKD:Wz},{name:"string.normalize"}),Z9=N0(m8,"a well-formed numeric string"),Jz=Y0.module({root:Z9,parse:H0({in:Z9,morphs:(Y)=>Number.parseFloat(Y),declaredOut:d.number})},{name:"string.numeric"}),X9="a regex pattern",Qz=H0({domain:"string",predicate:{meta:X9,predicate:(Y,Z)=>{try{return new RegExp(Y),!0}catch(X){return Z.reject({code:"predicate",expected:X9,problem:String(X)})}}},meta:{format:"regex"}}),Uz=/^(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-]+)*))?$/,zz=N0(Uz,"a semantic version (see https://semver.org/)"),_9=N0(/^\S.*\S$|^\S?$/,"trimmed"),Fz=Y0.module({root:H0({in:"string",morphs:(Y)=>Y.trim(),declaredOut:_9}),preformatted:_9},{name:"string.trim"}),G9=N0(/^[A-Z]*$/,"only uppercase letters"),Ez=Y0.module({root:H0({in:"string",morphs:(Y)=>Y.toUpperCase(),declaredOut:G9}),preformatted:G9},{name:"string.upper"}),Oz=(Y)=>{if(URL.canParse)return URL.canParse(Y);try{return new URL(Y),!0}catch{return!1}},$9=H0({domain:"string",predicate:{meta:"a URL string",predicate:Oz},meta:{format:"uri"}}),Vz=Y0.module({root:$9,parse:H0({declaredIn:$9,in:"string",morphs:(Y,Z)=>{try{return new URL(Y)}catch{return Z.error("a URL string")}},declaredOut:H0(URL)})},{name:"string.url"}),Dz=Y0.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:N0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:N0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:N0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:N0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:N0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:N0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:N0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:N0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),Q9=Y0.module({root:d.string,alpha:N0(/^[A-Za-z]*$/,"only letters"),alphanumeric:N0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:yU,base64:gU,capitalize:pU,creditCard:dU,date:rU,digits:N0(/^\d*$/,"only digits 0-9"),email:nU,integer:W9,ip:aU,json:Zz,lower:Xz,normalize:Hz,numeric:Jz,regex:Qz,semver:zz,trim:Fz,upper:Ez,url:Vz,uuid:Dz},{name:"string"});var U9=Y0.module({bigint:d.bigint,boolean:d.boolean,false:d.false,never:d.never,null:d.null,number:d.number,object:d.object,string:d.string,symbol:d.symbol,true:d.true,unknown:d.unknown,undefined:d.undefined}),z9=Y0.module({root:d.unknown,any:d.unknown},{name:"unknown"}),Lz=Y0.module({root:d.jsonObject,stringify:Q4("morph",{in:d.jsonObject,morphs:(Y)=>JSON.stringify(Y),declaredOut:d.string})},{name:"object.json"}),F9=Y0.module({root:d.object,json:Lz},{name:"object"});class E9 extends s0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var Mz=B1(["K",d.key],"V")((Y)=>({domain:"object",index:{signature:Y.K,value:Y.V}}),E9);class O9 extends s0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var Az=B1(["T",d.object],["K",d.key])((Y)=>Y.T.pick(Y.K),O9);class V9 extends s0{description='omit a set of properties from an object like `Omit(User, "age")`'}var wz=B1(["T",d.object],["K",d.key])((Y)=>Y.T.omit(Y.K),V9);class D9 extends s0{description="make all named properties of an object optional like `Partial(User)`"}var Rz=B1(["T",d.object])((Y)=>Y.T.partial(),D9);class L9 extends s0{description="make all named properties of an object required like `Required(User)`"}var Nz=B1(["T",d.object])((Y)=>Y.T.required(),L9);class M9 extends s0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var Iz=B1("T","U")((Y)=>Y.T.exclude(Y.U),M9);class A9 extends s0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var Tz=B1("T","U")((Y)=>Y.T.extract(Y.U),A9),w9=Y0.module({Exclude:Iz,Extract:Tz,Omit:wz,Partial:Rz,Pick:Az,Record:Mz,Required:Nz});var R2=qZ({...U9,...w9,...iG,...mG,string:Q9,number:E6,object:F9,unknown:z9},{prereducedAliases:!0,name:"ark"}),p0=R2.export();Object.assign(F4.ambient,p0);F4.typeAttachments={string:p0.string.root,number:p0.number.root,bigint:p0.bigint,boolean:p0.boolean,symbol:p0.symbol,undefined:p0.undefined,null:p0.null,object:p0.object.root,unknown:p0.unknown.root,false:p0.false,true:p0.true,never:p0.never,arrayIndex:p0.Array.index,Key:p0.Key,Record:p0.Record,Array:p0.Array.root,Date:p0.Date};var E1=Object.assign(R2.type,F4.typeAttachments),Kz=R2.match,Bz=R2.generic,JT=R2.schema,Cz=R2.define,qz=R2.declare;function G1(Y){return JSON.parse(Y)}var Q0=(Y)=>JSON.stringify(Y),TT=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function O4(Y){return M6(o0.STORE,Y,void 0)}function G8(Y){return L4(o0.STORE,Y)}function PZ(...Y){if(Y.length===2)return A1(o0.STORE,...Y);return A1(o0.STORE,...Y)}function V6(Y,Z){return j9(o0.STORE,Y,Z)}function R9(Y){return P9(Y,o0.STORE)}var _2={atom_family:"atom family",atom:"atom",continuity:"continuity",key:"key",mutable_atom_family:"atom family [m]",mutable_atom:"atom [m]",readonly_held_selector_family:"selector family [h]",readonly_held_selector:"selector [h]",readonly_pure_selector_family:"selector family",readonly_pure_selector:"selector",state:"state",timeline:"timeline",transaction:"transaction",unknown:"unknown",writable_held_selector_family:"selector family [wh]",writable_held_selector:"selector [wh]",writable_pure_selector_family:"selector family [w]",writable_pure_selector:"selector [w]"};var SZ=(Y)=>(Z,X,_,G,...$)=>{console[Y](`${Z} ${_2[X]} \`${_}\` ${G}`,...$)},jz={error:SZ("error"),info:SZ("info"),warn:SZ("warn")},N9=class{logLevel;filter;logger;constructor(Y,Z,X=jz){this.logLevel=Y,this.filter=Z,this.logger=X}error=(...Y)=>{if(this.logLevel!==null){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.error(...Y);else if(Z)this.logger.error(...Z)}};info=(...Y)=>{if(this.logLevel==="info"){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.info(...Y);else if(Z)this.logger.info(...Z)}};warn=(...Y)=>{if(this.logLevel!=="error"&&this.logLevel!==null){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.warn(...Y);else if(Z)this.logger.warn(...Z)}}};var Sz=class{store;constructor(Y=o0.STORE){this.store=Y,K9("root",Y)}allocate(Y,Z,X){return V4(this.store,Y,Z,X)}fuse(Y,Z,X){return B9(this.store,Y,Z,X)}deallocate(Y){D4(this.store,Y)}claim(Y,Z,X){return W8(this.store,Y,Z,X)}},I9=class{store;realm;constructor(Y=o0.STORE){this.store=Y,this.realm=new Sz(Y)}allocate(Y,Z,X){V4(this.store,Y,Z,X)}deallocate(Y){D4(this.store,Y)}claim(Y,Z,X){W8(this.store,Y,Z,X)}};function D6(Y){return fZ(o0.STORE,Y)}function $8(Y){return xZ(o0.STORE,Y)}var G2=class Y extends Set{mode="record";subject=new W0;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(Z,X=0){super(Z);if(Z instanceof Y)this.parent=Z,this.cacheUpdateNumber=Z.cacheUpdateNumber;if(X)this.cacheLimit=X,this.cache=new Array(X),this.subscribe("auto cache",(_)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=_})}READONLY_VIEW=this;toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(Z){let X=new Y(Z.members,Z.cacheLimit);return X.cache=Z.cache,X.cacheIdx=Z.cacheIdx,X.cacheUpdateNumber=Z.cacheUpdateNumber,X}add(Z){let X=super.add(Z);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${Q0(Z)}`);return X}clear(){let Z=this.mode==="record"?[...this]:null;if(super.clear(),Z)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(Z)}`)}delete(Z){let X=super.delete(Z);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${Q0(Z)}`);return X}parent=null;child=null;transactionUpdates=null;transaction(Z){this.mode="transaction",this.transactionUpdates=[],this.child=new Y(this);let X=this.child._subscribe("transaction",(_)=>{this.transactionUpdates?.push(_)});try{if(Z(this.child)){for(let G of this.transactionUpdates)this.doStep(G);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(_){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",_),_}finally{X(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(Z,X){return this.subject.subscribe(Z,X)}subscribe(Z,X){return this.subject.subscribe(Z,(_)=>{X(`${this.cacheUpdateNumber}=${_}`)})}emit(Z){this.subject.next(Z)}doStep(Z){let X=Z.indexOf(":"),_=Z.substring(0,X),G=Z.substring(X+1);switch(_){case"add":this.add(JSON.parse(G));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(G));break;case"tx":for(let $ of G.split(";"))this.doStep($)}}getUpdateNumber(Z){let X=Z.indexOf("=");return Number(Z.substring(0,X))}do(Z){let X=Z.indexOf("="),_=Number(Z.substring(0,X)),G=_-this.cacheUpdateNumber;if(G>0){if(G===1){this.mode="playback";let W=Z.substring(X+1);return this.doStep(W),this.mode="record",this.cacheUpdateNumber=_,null}return this.cacheUpdateNumber+1}if(Math.abs(G)<this.cacheLimit){let W=this.cacheIdx+G;if(this.cache[W]===Z)return null;this.mode="playback";let Q=!1;while(!Q){this.cacheIdx%=this.cacheLimit;let U=this.cache[this.cacheIdx];if(this.cacheIdx--,!U)return"OUT_OF_RANGE";this.undo(U),Q=this.cacheIdx===W-1}let J=Z.substring(X+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=_,null}return"OUT_OF_RANGE"}undoStep(Z){let X=Z.indexOf(":"),_=Z.substring(0,X),G=Z.substring(X+1);switch(_){case"add":this.delete(JSON.parse(G));break;case"del":this.add(JSON.parse(G));break;case"clear":{let $=JSON.parse(G);for(let W of $)this.add(W);break}case"tx":{let $=G.split(";");for(let W=$.length-1;W>=0;W--)this.undoStep($[W])}}}undo(Z){let X=Z.indexOf("=");if(Number(Z.substring(0,X))===this.cacheUpdateNumber){this.mode="playback";let G=Z.substring(X+1);return this.undoStep(G),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}};function T9(Y=Math.random){return Y().toString(36).slice(2)}function t(Y){while(Y.child!==null)Y=Y.child;return Y}var vz=class Y{_buffer;_index=0;constructor(Z){let X;if(typeof Z==="number")X=Z;else X=Z.length;this._buffer=Array.from({length:X})}get buffer(){return this._buffer}get index(){return this._index}add(Z){this._buffer[this._index]=Z,this._index=(this._index+1)%this._buffer.length}copy(){let Z=new Y([...this._buffer]);return Z._index=this._index,Z}};function b1(Y){let Z={key:Y.key,type:Y.type};if("family"in Y)Z.family=Y.family;return Z}var xz=Symbol("counterfeit"),fz={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"};function v9(Y,Z,X){let _=Q0(Z),G=`${Y.key}(${_})`,$=fz[Y.type],W={key:G,type:$,family:{key:Y.key,subKey:_}};if(X)W.counterfeit=!0;return W}var k1=class extends Map{deleted=new Set;changed=new Set;source;constructor(Y){super();this.source=Y}get(Y){if(super.has(Y))return super.get(Y);if(!this.deleted.has(Y)&&this.source.has(Y))return this.source.get(Y);return}set(Y,Z){if(this.deleted.delete(Y),this.source.has(Y))this.changed.add(Y);return super.set(Y,Z)}hasOwn(Y){return super.has(Y)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){if(this.source.has(Y))this.deleted.add(Y),this.changed.delete(Y);return super.delete(Y)}clear(){this.deleted=new Set(this.source.keys()),this.changed.clear(),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let[Y,Z]of this.source)if(!this.deleted.has(Y)&&!this.changed.has(Y))yield[Y,Z]}*entries(){yield*this[Symbol.iterator]()}*keys(){yield*super.keys();for(let Y of this.source.keys())if(!this.deleted.has(Y)&&!this.changed.has(Y))yield Y}*values(){for(let[,Y]of this[Symbol.iterator]())yield Y}forEach(Y){for(let[Z,X]of this[Symbol.iterator]())Y(X,Z,this)}get size(){return super.size+this.source.size-this.changed.size-this.deleted.size}},b9=class extends Set{deleted=new Set;source;constructor(Y){super();this.source=Y}add(Y){if(this.source.has(Y))return this.deleted.delete(Y),this;return super.add(Y)}hasOwn(Y){return super.has(Y)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){if(this.source.has(Y))return this.deleted.add(Y),!0;return super.delete(Y)}clear(){this.deleted=new Set(this.source),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let Y of this.source)if(!this.deleted.has(Y))yield Y}*iterateOwn(){yield*super[Symbol.iterator]()}get size(){return super.size+this.source.size-this.deleted.size}},hz=class extends Map{deleted=new Set;source;constructor(Y){super();this.source=Y}get(Y){if(super.has(Y))return super.get(Y);if(!this.deleted.has(Y)&&this.source.has(Y)){let X=this.source.get(Y),_=new b9(X);return super.set(Y,_),_}return}set(Y,Z){return this.deleted.delete(Y),super.set(Y,Z)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){return this.deleted.add(Y),super.delete(Y)}},$2=class Y{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(Z,X)=>`${Z}:${X}`;warn;getRelatedKeys(Z){return this.relations.get(Z)}addRelation(Z,X){let _=this.relations.get(Z),G=this.relations.get(X);if(_)_.add(X);else _=new Set([X]),this.relations.set(Z,_);if(G)G.add(Z);else G=new Set([Z]),this.relations.set(X,G)}deleteRelation(Z,X){let _=this.relations.get(Z);if(_){if(_.delete(X),_.size===0)this.relations.delete(Z);let G=this.relations.get(X);if(G){if(G.delete(Z),G.size===0)this.relations.delete(X)}}}replaceRelationsUnsafely(Z,X){this.relations.set(Z,new Set(X));for(let _ of X){let G=new Set().add(Z);this.relations.set(_,G)}}replaceRelationsSafely(Z,X){let _=this.relations.get(Z),G=this.isAType?.(Z)?Z:void 0,$=G===void 0?Z:void 0;if(_)for(let W of _){G??=W,$??=W;let H=this.relations.get(W);if(H){if(H.size===1)this.relations.delete(W);else H.delete(Z);this.contents.delete(this.makeContentKey(G,$))}}this.relations.set(Z,new Set(X));for(let W of X){let H=this.relations.get(W);if(H)H.add(Z);else H=new Set().add(Z),this.relations.set(W,H)}}getContentInternal(Z){return this.contents.get(Z)}setContent(Z,X){this.contents.set(Z,X)}deleteContent(Z){this.contents.delete(Z)}constructor(Z,X){if(this.a=Z.between[0],this.b=Z.between[1],this.cardinality=Z.cardinality,this.isAType=X?.isAType??null,this.isBType=X?.isBType??null,this.isContent=X?.isContent??null,X?.makeContentKey)this.makeContentKey=X.makeContentKey;if(!X?.externalStore){let _=X?.source;if(_===void 0)this.relations=new Map(Z.relations?.map(([G,$])=>[G,new Set($)])),this.contents=new Map(Z.contents);if(_)this.relations=new hz(_.relations),this.contents=new k1(_.contents)}if(X?.externalStore){let _=X.externalStore;if(this.has=(G,$)=>_.has(G,$),this.addRelation=(G,$)=>{_.addRelation(G,$)},this.deleteRelation=(G,$)=>{_.deleteRelation(G,$)},this.replaceRelationsSafely=(G,$)=>{_.replaceRelationsSafely(G,$)},this.replaceRelationsUnsafely=(G,$)=>{_.replaceRelationsUnsafely(G,$)},this.getRelatedKeys=(G)=>_.getRelatedKeys(G),_.getContent)this.getContentInternal=(G)=>{return _.getContent(G)},this.setContent=(G,$)=>{_.setContent(G,$)},this.deleteContent=(G)=>{_.deleteContent(G)};for(let[G,$]of Z.relations??[]){let W=this.isAType?.(G)?G:void 0,H=W===void 0?G:void 0;for(let Q of $)W??=Q,H??=Q,this.addRelation(W,H)}for(let[G,$]of Z.contents??[])this.setContent(G,$)}if(X?.warn)this.warn=X.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([Z,X])=>[Z,[...X]]),contents:[...this.contents.entries()]}}set(...Z){let X,_,G;switch(Z.length){case 1:{let $=Z[0];X=$[this.a],_=$[this.b],G=void 0;break}case 2:{let $=Z[0];if(typeof $==="string")[X,_]=Z;else X=$[this.a],_=$[this.b],G=Z[1];break}default:X=Z[0],_=Z[1],G=Z[2];break}switch(this.cardinality){case"1:1":{let $=this.getRelatedKey(X);if($&&$!==_)this.delete(X,$)}case"1:n":{let $=this.getRelatedKey(_);if($&&$!==X)this.delete($,_)}break;case"n:n":}if(G){let $=this.makeContentKey(X,_);this.setContent($,G)}return this.addRelation(X,_),this}delete(Z,X){X=typeof X==="string"?X:Z[this.b];let _=typeof Z==="string"?Z:Z[this.a];if(_===void 0&&typeof X==="string"){let G=this.getRelatedKeys(X);if(G)for(let $ of G)this.delete($,X)}else if(typeof _==="string"&&X===void 0){let G=this.getRelatedKeys(_);if(G)for(let $ of G)this.delete(_,$)}else if(typeof _==="string"&&typeof X==="string"){this.deleteRelation(_,X);let G=this.makeContentKey(_,X);this.deleteContent(G)}return this}getRelatedKey(Z){let X=this.getRelatedKeys(Z);if(X){if(X.size>1)this.warn?.(`${X.size} related keys were found for key "${Z}": (${[...X].map((G)=>`"${G}"`).join(", ")}). Only one related key was expected.`);let _;for(let G of X){_=G;break}return _}}replaceRelations(Z,X,_){let G=!Array.isArray(X),$=G?Object.keys(X):X;if(_?.reckless)this.replaceRelationsUnsafely(Z,$);else this.replaceRelationsSafely(Z,$);if(G)for(let W of $){let H=this.makeContentKey(Z,W),Q=X[W];this.setContent(H,Q)}return this}getContent(Z,X){let _=this.makeContentKey(Z,X);return this.getContentInternal(_)}getRelationEntries(Z){let X=Z[this.a],_=Z[this.b];if(X!==void 0&&_===void 0){let G=this.getRelatedKeys(X);if(G)return[...G].map(($)=>{return[$,this.getContent(X,$)]})}if(X===void 0&&_!==void 0){let G=this.getRelatedKeys(_);if(G)return[...G].map(($)=>{return[$,this.getContent($,_)]})}return[]}has(Z,X){if(X)return this.getRelatedKeys(Z)?.has(X)??!1;return this.relations.has(Z)}overlay(){let Z={source:this,makeContentKey:this.makeContentKey};if(this.isAType)Z.isAType=this.isAType;if(this.isBType)Z.isBType=this.isBType;if(this.isContent)Z.isContent=this.isContent;if(this.warn)Z.warn=this.warn;return new Y({between:[this.a,this.b],cardinality:this.cardinality},Z)}incorporate(Z){let{relations:X,contents:_}=Z;for(let[G,$]of X)if($ instanceof b9){let{source:W}=$;for(let H of $.iterateOwn())W.add(H)}else this.relations.set(G,$);for(let G of X.deleted)this.relations.delete(G);for(let[G,$]of _)this.contents.set(G,$);for(let G of _.deleted)this.contents.delete(G)}},W0=class{Subscriber;subscribers=new Map;subscribe(Y,Z){return this.subscribers.set(Y,Z),()=>{this.unsubscribe(Y)}}unsubscribe(Y){this.subscribers.delete(Y)}next(Y){let Z=this.subscribers.values();for(let X of Z)X(Y)}},kz=class extends W0{state;constructor(Y){super();this.state=Y}next(Y){this.state=Y,super.next(Y)}},bz=(Y,Z)=>{let X=t(Y);if(X.operation.open)return X.operation.prev.get(Z.key);return X.valueMap.get(Z.key)};function y9(Y,Z,X,_){let G=Y.disposalTraces.buffer.find(($)=>$?.key===Q0(_));switch(Y.logger.error("\u274C",Z.type,Z.key,"gets a fallback value because key",_,"is not allocated",G?`This key was previously disposed:
48
- ${G.trace}`:"(no previous disposal trace found)"),X.type){case"mutable_atom_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=new X.class;return Y.defaults.set(X.key,$),$}case"atom_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=X.default,W=$(_);return Y.defaults.set(X.key,W),W}case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=X.default(_);return Y.defaults.set(X.key,$),$}}}var bZ=class extends Promise{fate;resolve;reject;done=!1;constructor(Y){let Z,X;super((_,G)=>{Z=_,X=G});this.resolve=Z,this.reject=X,this.use(Y instanceof Promise?Y:new Promise(Y))}pass(Y,Z){if(Y===this.fate)this.resolve(Z),this.done=!0}fail(Y,Z){if(Y===this.fate)this.reject(Z),this.done=!0}use(Y){if(this===Y)return;if(Y instanceof Promise){let Z=Y;this.fate=Z,Z.then((X)=>{this.pass(Z,X)},(X)=>{this.fail(Z,X)})}else this.resolve(Y),this.fate=void 0}};function N2(Y){return"epoch"in Y.transactionMeta}function a0(Y){return"phase"in Y.transactionMeta}function g9(Y,Z){if(Y.operation.open){let X=performance.now();return Y.logger.info("\uD83D\uDEAB",Z.type,Z.key,`deferring setState at T-${X} until setState for "${Y.operation.token.key}" is done`),X}return Y.operation={open:!0,done:new Set,prev:new Map,timestamp:Date.now(),token:Z},Y.logger.info("\u2B55",Z.type,Z.key,`operation start in store "${Y.config.name}"${a0(Y)?` ${Y.transactionMeta.phase} "${Y.transactionMeta.update.token.key}"`:""}`),Y}function p9(Y){if(Y.operation.open)Y.logger.info("\uD83D\uDD34",Y.operation.token.type,Y.operation.token.key,`operation done in store "${Y.config.name}"`);Y.operation={open:!1},Y.on.operationClose.next(Y.operation)}var m9=(Y,Z)=>{if(!Y.operation.open)return Y.logger.error("\uD83D\uDC1E","unknown",Z,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return Y.operation.done.has(Z)},R6=(Y,Z)=>{if(!Y.operation.open){Y.logger.error("\uD83D\uDC1E","unknown",Z,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}Y.operation.done.add(Z)};function mZ(Y,Z){let X=t(Y),{key:_,type:G}=Z,$=X.selectorAtoms.getRelatedKeys(_);if(X.logger.info("\uD83E\uDDF9",G,_,$?`evicting ${$.size} states downstream:`:"no downstream states",$??"to evict"),$){if(X.operation.open)X.logger.info("\uD83E\uDDF9",G,_,`[ ${[...X.operation.done].join(", ")} ] already done`);for(let W of $){if(m9(X,W))continue;d9(X,W),R6(X,W)}}}function u9(Y,Z){let X=t(Y),_=X.selectorGraph.getRelationEntries({upstreamSelectorKey:Z}).filter(([G,{source:$}])=>$===Z);for(let[G]of _){if(m9(X,G))continue;d9(X,G),R6(X,G),u9(Y,G)}}function W2(Y,Z,X){let{key:_,subject:G,type:$}=Z,W=Y.valueMap.get(_);if(W instanceof bZ&&!W.done){let H=W;if(X instanceof Promise)return H.use(X),H;return Y.valueMap.set(_,X),X}if(X instanceof Promise){let H=new bZ(X);return Y.valueMap.set(_,H),H.then(function Q(J){if(Y.valueMap.get(_)===H){switch(g9(Y,Z),W2(Y,Z,J),$){case"atom":case"mutable_atom":mZ(Y,Z);break;case"readonly_pure_selector":case"writable_pure_selector":u9(Y,_);break}p9(Y),G.next({newValue:J,oldValue:H})}}).catch((Q)=>{Y.logger.error("\uD83D\uDCA5","state",_,"rejected:",Q)}),H}return Y.logger.info("\uD83D\uDCDD",Z.type,Z.key,"writing to cache",X),Y.valueMap.set(_,X),X}function yz(Y,Z,X){Y.logger.info("\uD83D\uDCD6",Z.type,Z.key,"reading cached value");let _=Y.valueMap.get(Z.key);if(X==="mut"&&Z.type==="mutable_atom"&&a0(Y)){let $=Z,{parent:W}=Y;if(Y.valueMap.hasOwn($.key))return _;let H=W.valueMap.get($.key);Y.logger.info("\uD83D\uDCC3","atom",$.key,"copying");let Q=H.toJSON(),J=$.class.fromJSON(Q);Y.valueMap.set($.key,J),new sZ($,W),_=J}return _}function d9(Y,Z){let X=Y.valueMap.get(Z);if(X instanceof bZ){let _=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if(_)_.getFrom(Y);return}if(Y.operation.open)Y.operation.prev.set(Z,X);Y.valueMap.delete(Z),Y.logger.info("\uD83D\uDDD1","state",Z,"evicted")}var gz=/^\[object (?:Async|Generator|AsyncGenerator)?Function\]$/;function Q8(Y){let Z=Object.prototype.toString.call(Y);return gz.test(Z)}function b2(Y,Z,X){if(Y.valueMap.has(Z.key))return yz(Y,Z,X);Y.logger.info("\u2754",Z.type,Z.key,"value not found in cache");let{key:_}=Z;switch(Z.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return Y.logger.info("\uD83E\uDDEE",Z.type,_,"computing value"),Z.getFrom(Y);case"atom":{let G;if(Q8(Z.default))G=Z.default(),Y.logger.info("\u2728",Z.type,_,"computed default",G);else G=Z.default,Y.logger.info("\u2728",Z.type,_,"using static default",G);return W2(Y,Z,G)}case"mutable_atom":{let G=new Z.class;return Y.logger.info("\u2728",Z.type,_,"created new instance",G),W2(Y,Z,G)}}}function uZ(Y,Z){return S0(Y,{key:Z.family.key,type:`${Z.type}_family`})}var U8=Symbol("MUST_CREATE");function z8(Y,Z,X,_){let G=Q0(X),$=Y.molecules.get(G);if(!$&&Y.config.lifespan==="immortal")return Y.logger.warn("\uD83D\uDCA3","key",G,"was used to mint a counterfeit token for",Z.type,`"${Z.key}"`),v9(Z,X,xz);let H;if(_===U8){if(Y.logger.info("\uD83D\uDC6A",Z.type,Z.key,"adds member",typeof X==="string"?`\`${X}\``:X),H=Z(X),$)Y.moleculeData.set(G,Z.key)}else H=v9(Z,X);return H}var pz=(Y)=>{let Z=t(Y);if(!a0(Z)){Y.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}Y.logger.info("\uD83E\uDE82","transaction",Z.transactionMeta.update.token.key,"Aborting transaction"),Z.parent.child=null},c9=class extends Error{constructor(Y,Z){super(`${_2[Y.type]} ${Q0(Y.key)} not found in store "${Z.config.name}".`)}};function vZ(Y,Z,X){return(..._)=>{let G=S0(Y,Z);if(G)return G.run(_,X);throw new c9(Z,Y)}}function yZ(Y,Z){if(Q8(Y))return Y(Z);return Y}var gZ=(Y,Z,X)=>{let _=b2(Y,Z,"mut"),G=yZ(X,_);return Y.logger.info("\u2B50","atom",Z.key,"setting value",G),G=W2(Y,Z,G),R6(Y,Z.key),mZ(Y,Z),{oldValue:_,newValue:G}};function x9(Y,Z){switch(Z.type){case"mutable_atom":return gZ(Y,Z,new Z.class);case"atom":{let X=Z.default;if(Q8(X))X=X();return gZ(Y,Z,X)}}}function mz(Y,Z){let X;switch(Z.type){case"atom":case"mutable_atom":X=x9(Y,Z);break;case"writable_pure_selector":case"writable_held_selector":{let _=Z.getFrom(Y),G=w6(Y,Z.key);for(let W of G.values()){let H=x9(Y,W);r9(Y,Z,H,!1)}let $=Z.getFrom(Y);X={oldValue:_,newValue:$}}break}return X}function w1(Y,...Z){dZ(Y,pZ,...Z)}var A6=Symbol("RESET");function L6(Y,...Z){let X,_,G;if(Z.length===1)X=Z[0],w1(Y,X,A6);else _=Z[0],G=Z[1],w1(Y,_,G,A6)}function uz(Y,Z,X){let _,G,$,{type:W,key:H}=Z;switch(Z.type){case"writable_pure_selector":_=b2(Y,Z,"mut"),G=yZ(X,_),G=W2(Y,Z,G);break;case"writable_held_selector":$=Z.const,yZ(X,$),_=$,G=$}return Y.logger.info("\u2B50",W,H,"setting to",G),R6(Y,H),Z.setSelf(G),{oldValue:_,newValue:G}}var dz=(Y,Z,X)=>{let _;switch(Z.type){case"atom":case"mutable_atom":_=gZ(Y,Z,X);break;case"writable_pure_selector":case"writable_held_selector":_=uz(Y,Z,X);break}return _};function cz(Y,Z,X){let{token:_,update:{newValue:G,oldValue:$}}=Z;w1(Y,_,X==="newValue"?G:$)}function lz(Y){let{stack:Z}=Y;if(Z)return`
47
+ `)+"}");class Z6{config;resolvedConfig;name;get[Y1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Y,Z){if(this.config=g4(I.config,Z),this.resolvedConfig=g4(I.resolvedConfig,Z),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(HZ).length}`,this.name in HZ)A(`A Scope already named ${this.name} already exists`);HZ[this.name]=this;let X=Object.entries(Y).map((_)=>this.preparseOwnAliasEntry(..._));for(let[_,G]of X){let $=_;if(_[0]==="#"){if($=_.slice(1),$ in this.aliases)A(i_($));this.aliases[$]=G}else{if($ in this.aliases)A(i_(_));this.aliases[$]=G,this.exportedNames.push($)}if(!y(G,"module")&&!y(G,"generic")&&!V2(G)){let W=this.preparseOwnDefinitionFormat(G,{alias:$});this.resolutions[$]=y(W,"root")?this.bindReference(W):this.createParseContext(W).id}}r_??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[r_.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=I.intrinsic?i(I.intrinsic,(_,G)=>_.startsWith("json")?[]:[_,this.bindReference(G)]):{}}cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Y){return Y}generic=(...Y)=>{let Z=this;return(X,_)=>new A2(Y,_?new i8(X):X,Z,Z,_??null)};units=(Y,Z)=>{let X=[];for(let G of Y)if(!X.includes(G))X.push(G);let _=X.map((G)=>this.node("unit",{unit:G},Z));return this.node("union",_,{...Z,prereduced:!0})};lazyResolutions=[];lazilyResolve(Y,Z){let X=this.node("alias",{reference:Z??"synthetic",resolve:Y},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(Y,Z)=>this.finalize(this.parseSchema(Y,Z));parseSchema=(Y,Z)=>this.node(d4(Y),Y,Z);preparseNode(Y,Z,X){let _=typeof Y==="string"?Y:d4(Z,Y);if(L0(Z)&&Z.kind===_)return Z;if(_==="alias"&&!X?.prereduced){let{reference:W}=n4.implementation.normalize(Z,this);if(W.startsWith("$")){let H=this.resolveRoot(W.slice(1));Z=H,_=H.kind}}else if(_==="union"&&H1(Z,"object")){let W=gQ(Z);if(W?.length===1)Z=W[0],_=d4(Z)}if(L0(Z)&&Z.kind===_)return Z;let $=G4[_].normalize?.(Z,this)??Z;if(L0($))return $.kind===_?$:pQ(_,$.kind);return{...X,$:this,kind:_,def:$,prefix:X.alias??_}}bindReference(Y){let Z;if(L0(Y))Z=Y.$===this?Y:new Y.constructor(Y.attachments,this);else Z=Y.$===this?Y:new A2(Y.params,Y.bodyDef,Y.$,this,Y.hkt);if(!this.resolved)Object.assign(this.referencesById,Z.referencesById);return Z}resolveRoot(Y){return this.maybeResolveRoot(Y)??A(zZ(Y))}maybeResolveRoot(Y){let Z=this.maybeResolve(Y);if(y(Z,"generic"))return;return Z}maybeResolveSubalias(Y){return JZ(this.aliases,Y)??JZ(this.ambient,Y)}get ambient(){return I.ambient}maybeResolve(Y){let Z=this.resolutions[Y];if(Z){if(typeof Z!=="string")return this.bindReference(Z);let _=Z1[Z];if(y(_,"root"))return this.resolutions[Y]=_;if(y(_,"context")){if(_.phase==="resolving")return this.node("alias",{reference:`$${Y}`},{prereduced:!0});if(_.phase==="resolved")return _0(`Unexpected resolved context for was uncached by its scope: ${r(_)}`);_.phase="resolving";let G=this.bindReference(this.parseOwnDefinitionFormat(_.def,_));return _.phase="resolved",Z1[G.id]=G,Z1[_.id]=G,this.resolutions[Y]=G}return _0(`Unexpected nodesById entry for ${Z}: ${r(_)}`)}let X=this.aliases[Y]??this.ambient?.[Y];if(!X)return this.maybeResolveSubalias(Y);if(X=this.normalizeRootScopeValue(X),y(X,"generic"))return this.resolutions[Y]=this.bindReference(X);if(y(X,"module")){if(!X.root)A(ZG(Y));return this.resolutions[Y]=this.bindReference(X.root)}return this.resolutions[Y]=this.parse(X,{alias:Y})}createParseContext(Y){let Z=Y.id??cY(Y.prefix);return Z1[Z]=Object.assign(Y,{[Y1]:"context",$:this,id:Z,phase:"unresolved"})}traversal(Y){return new f1(Y,this.resolvedConfig)}import(...Y){return new H4(i(this.export(...Y),(Z,X)=>[`#${Z}`,X]))}precompilation;_exportedResolutions;_exports;export(...Y){if(!this._exports){this._exports={};for(let X of this.exportedNames){let _=this.aliases[X];this._exports[X]=y(_,"module")?WZ(_,this):n_(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=YG(this,this._exports),this._json=e_(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=a_(this.references);this.precompilation=X.write(s_,4),t_(this.references,X)}this.resolved=!0}let Z=Y.length?Y:this.exportedNames;return new H4(i(Z,(X,_)=>[_,this._exports[_]]))}resolve(Y){return this.export()[Y]}node=(Y,Z,X={})=>{let _=this.preparseNode(Y,Z,X);if(L0(_))return this.bindReference(_);let G=this.createParseContext(_),$=lY(G),W=this.bindReference($);return Z1[G.id]=W};parse=(Y,Z={})=>this.finalize(this.parseDefinition(Y,Z));parseDefinition(Y,Z={}){if(y(Y,"root"))return this.bindReference(Y);let X=this.preparseOwnDefinitionFormat(Y,Z);if(y(X,"root"))return this.bindReference(X);let _=this.createParseContext(X);Z1[_.id]=_;let G=this.bindReference(this.parseOwnDefinitionFormat(Y,_));if(G.isCyclic)G=R_(G,_.id);return Z1[_.id]=G,G}finalize(Y){if(n_(Y),!Y.precompilation&&!this.resolvedConfig.jitless)mQ(Y.references);return Y}}class QZ extends Z6{parseOwnDefinitionFormat(Y,Z){return lY(Z)}preparseOwnDefinitionFormat(Y,Z){return this.preparseNode(d4(Y),Y,Z)}preparseOwnAliasEntry(Y,Z){return[Y,Z]}normalizeRootScopeValue(Y){return Y}}var n_=(Y)=>{let Z=Y.references.filter((X)=>X.hasKind("alias"));for(let X of Z){Object.assign(X.referencesById,X.resolution.referencesById);for(let _ of Y.references)if(X.id in _.referencesById)Object.assign(_.referencesById,X.referencesById)}return Y},e_=(Y)=>i(Y,(Z,X)=>[Z,y(X,"root")||y(X,"generic")?X.json:y(X,"module")?e_(X):_0(`Unexpected resolution ${r(X)}`)]),JZ=(Y,Z)=>{let X=Z.indexOf(".");if(X===-1)return;let _=Z.slice(0,X),G=Y[_];if(G===void 0)return;if(!y(G,"module"))return A(uQ(_));let $=Z.slice(X+1),W=G[$];if(W===void 0)return JZ(G,$);if(y(W,"root")||y(W,"generic"))return W;if(y(W,"module"))return W.root??A(ZG(Z));_0(`Unexpected resolution for alias '${Z}': ${r(W)}`)},X6=(Y,Z)=>new QZ(Y,Z),a4=new QZ({});var YG=(Y,Z)=>{let X={};for(let _ in Z){let G=Z[_];if(y(G,"module")){let $=YG(Y,G),W=i($,(H,Q)=>[`${_}.${H}`,Q]);Object.assign(X,W)}else if(y(G,"root")||y(G,"generic"))X[_]=G;else _0(`Unexpected scope resolution ${r(G)}`)}return X},zZ=(Y)=>`'${Y}' is unresolvable`,uQ=(Y)=>`'${Y}' must reference a module to be accessed using dot syntax`,ZG=(Y)=>`Reference to submodule '${Y}' must specify an alias`;a4.export();var{schema:H0,node:J4,defineSchema:yw,generic:K1}=a4;var UZ="^(?:0|[1-9]\\d*)$",dQ=new RegExp(UZ),mw=B0(dQ);var XG=X6({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();I.intrinsic={...XG};var _G=X6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:UZ}},{prereducedAliases:!0}).export();Object.assign(I.intrinsic,_G);var cQ=X6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),d={...XG,..._G,...cQ,emptyStructure:J4("structure",{},{prereduced:!0})};I.intrinsic={...d};var $G=(Y)=>typeof Y==="string"&&Y[0]==="d"&&(Y[1]==="'"||Y[1]==='"')&&Y.at(-1)===Y[1],GG=(Y)=>Y.toString()!=="Invalid Date",WG=(Y)=>Y.slice(2,-1),FZ=(Y)=>`'${Y}' could not be parsed by the Date constructor`,HG=(Y,Z)=>lQ(Y,Z),lQ=(Y,Z)=>{let X=new Date(Y);if(GG(X))return X;let _=gX(Y);if(_!==void 0){let G=new Date(_);if(GG(G))return G}return Z?A(Z===!0?FZ(Y):Z):void 0};var EZ=(Y,Z)=>{let X=Y.scanner.shiftUntil(oQ[QG[Z]]);if(Y.scanner.lookahead==="")return Y.error(rQ(X,Z));if(Y.scanner.shift(),Z==="/"){try{new RegExp(X)}catch(_){A(String(_))}Y.root=Y.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(g0(Z,VZ))Y.root=Y.ctx.$.node("unit",{unit:X});else{let _=HG(X,FZ(X));Y.root=Y.ctx.$.node("unit",{meta:X,unit:_})}},VZ={"'":1,'"':1},JG={"/":1,"'":1,'"':1},QG={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},oQ={"'":(Y)=>Y.lookahead==="'",'"':(Y)=>Y.lookahead==='"',"/":(Y)=>Y.lookahead==="/"},iQ={'"':"double-quote","'":"single-quote","/":"forward slash"},rQ=(Y,Z)=>`${Z}${Y} requires a closing ${iQ[QG[Z]]}`;var zG=(Y)=>`Private type references should not include '#'. Use '${Y}' instead.`,_6="Optional definitions like 'string?' are only valid as properties in an object or tuple",G6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var UG={">":!0,">=":!0},FG={"<":!0,"<=":!0};var Q4={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},EG=(Y)=>`Unmatched )${Y===""?"":` before ${Y}`}`,$6=(Y)=>`Missing ${Y}`,VG=(Y,Z)=>`Left bounds are only valid when paired with right bounds (try ...${Z}${Y})`,W6=(Y)=>`Left-bounded expressions must specify their limits using < or <= (was ${Y})`,OG=(Y,Z,X,_)=>`An expression may have at most one left bound (parsed ${Y}${Q4[Z]}, ${X}${Q4[_]})`;var DG=(Y,Z,X)=>LG(Y,Z,X,[]),LG=(Y,Z,X,_)=>{let G=X.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Z.params.length)return X.error(OZ(Y,Z.names,_.map(($)=>$.expression)));return _}if(G.finalizer===",")return LG(Y,Z,X,_);return G.error($6(">"))},OZ=(Y,Z,X)=>`${Y}<${Z.join(", ")}> requires exactly ${Z.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var DZ=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator();if(Z==="keyof")Y.addPrefix("keyof");else Y.root=sQ(Y,Z)},nQ=(Y,Z,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(OZ(Y,Z.names,[]));let G=DG(Y,Z,X);return Z(...G)},sQ=(Y,Z)=>tQ(Y,Z)??aQ(Y,Z)??Y.error(Z===""?Y.scanner.lookahead==="#"?zG(Y.shiftedByOne().scanner.shiftUntilNextTerminator()):LZ(Y):zZ(Z)),tQ=(Y,Z)=>{if(Y.ctx.args?.[Z]){let _=Y.ctx.args[Z];if(typeof _!=="string")return _;return Y.ctx.$.node("alias",{reference:_},{prereduced:!0})}let X=Y.ctx.$.maybeResolve(Z);if(y(X,"root"))return X;if(X===void 0)return;if(y(X,"generic"))return nQ(Z,X,Y);return A(`Unexpected resolution ${r(X)}`)},aQ=(Y,Z)=>{let X=pX(Z);if(X!==void 0)return Y.ctx.$.node("unit",{unit:X});let _=uX(Z);if(_!==void 0)return Y.ctx.$.node("unit",{unit:_})},LZ=(Y)=>{let Z=Y.previousOperator();return Z?MZ(Z,Y.scanner.unscanned):eQ(Y.scanner.unscanned)},MZ=(Y,Z="")=>`Token '${Y}' requires a right operand${Z?` before '${Z}'`:""}`,eQ=(Y)=>`Expected an expression${Y?` before '${Y}'`:""}`;var AZ=(Y)=>Y.scanner.lookahead===""?Y.error(LZ(Y)):Y.scanner.lookahead==="("?Y.shiftedByOne().reduceGroupOpen():Y.scanner.lookaheadIsIn(JG)?EZ(Y,Y.scanner.shift()):Y.scanner.lookaheadIsIn(O2)?AZ(Y.shiftedByOne()):Y.scanner.lookahead==="d"?Y.scanner.nextLookahead in VZ?EZ(Y,`${Y.scanner.shift()}${Y.scanner.shift()}`):DZ(Y):DZ(Y);class X2 extends KY{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in X2.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...O2};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(Y,Z)=>Y===">"?Z[0]==="="?Z[1]==="=":Z.trimStart()===""||g0(Z.trimStart()[0],X2.terminatingChars):Y==="="?Z[0]!=="=":Y===","||Y==="?"}var AG=(Y,Z)=>{let X=Yz(Y,Z);if(Y.root.hasKind("unit")){if(typeof Y.root.unit==="number"){Y.reduceLeftBound(Y.root.unit,X),Y.unsetRoot();return}if(Y.root.unit instanceof Date){let _=`d'${Y.root.description??Y.root.unit.toISOString()}'`;Y.unsetRoot(),Y.reduceLeftBound(_,X);return}}return Xz(Y,X)},wG={"<":1,">":1,"=":1},Yz=(Y,Z)=>Y.scanner.lookaheadIs("=")?`${Z}${Y.scanner.shift()}`:Z;var MG=(Y,Z,X,_)=>{if(X.extends(I.intrinsic.number)){if(typeof Z!=="number")return A(wZ(Y,Z,_));return Y==="=="?["min","max"]:Y[0]===">"?["min"]:["max"]}if(X.extends(I.intrinsic.lengthBoundable)){if(typeof Z!=="number")return A(wZ(Y,Z,_));return Y==="=="?["exactLength"]:Y[0]===">"?["minLength"]:["maxLength"]}if(X.extends(I.intrinsic.Date))return Y==="=="?["after","before"]:Y[0]===">"?["after"]:["before"];return A(J_(X.expression))},Zz=(Y)=>({rule:$G(Y.limit)?WG(Y.limit):Y.limit,exclusive:Y.comparator.length===1}),Xz=(Y,Z)=>{let X=Y.unsetRoot(),_=Y.scanner.location;Y.parseOperand();let G=Y.unsetRoot(),$=Y.scanner.sliceChars(_,Y.scanner.location);if(Y.root=X,!G.hasKind("unit")||typeof G.unit!=="number"&&!(G.unit instanceof Date))return Y.error(wZ(Z,$,"right"));let W=G.unit,H=Z.length===1,Q=MG(Z,typeof W==="number"?W:$,X,"right");for(let z of Q)Y.constrainRoot(z,Z==="=="?{rule:W}:{rule:W,exclusive:H});if(!Y.branches.leftBound)return;if(!g0(Z,FG))return Y.error(W6(Z));let J=MG(Y.branches.leftBound.comparator,Y.branches.leftBound.limit,X,"left");Y.constrainRoot(J[0],Zz(Y.branches.leftBound)),Y.branches.leftBound=null},wZ=(Y,Z,X)=>`Comparator ${X==="left"?Q4[Y]:Y} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Z})`;var RG=(Y)=>{Y.scanner.shiftUntilNonWhitespace();let Z=Y.scanner.shiftUntilNextTerminator();Y.root=Y.root.brand(Z)};var IG=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator(),X=mX(Z,{errorOnFail:NG(Z)});if(X===0)Y.error(NG(0));Y.root=Y.root.constrain("divisor",X)},NG=(Y)=>`% operator must be followed by a non-zero integer literal (was ${Y})`;var RZ=(Y)=>{let Z=Y.scanner.shift();return Z===""?Y.finalize(""):Z==="["?Y.scanner.shift()==="]"?Y.setRoot(Y.root.array()):Y.error(_z):Z==="|"?Y.scanner.lookahead===">"?Y.shiftedByOne().pushRootToBranch("|>"):Y.pushRootToBranch(Z):Z==="&"?Y.pushRootToBranch(Z):Z===")"?Y.finalizeGroup():X2.lookaheadIsFinalizing(Z,Y.scanner.unscanned)?Y.finalize(Z):g0(Z,wG)?AG(Y,Z):Z==="%"?IG(Y):Z==="#"?RG(Y):(Z in O2)?RZ(Y):Y.error(H6(Z))},H6=(Y,Z="")=>`'${Y}' is not allowed here${Z&&` (should be ${Z})`}`,_z="Missing expected ']'";var KG=(Y)=>{let Z=Y.unsetRoot();Y.parseOperand();let X=Y.unsetRoot();if(!X.hasKind("unit"))return Y.error(Gz(X.expression));let _=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Z,"=",_]},Gz=(Y)=>`Default value '${Y}' must a literal value`;var NZ=(Y,Z)=>{let X=Z.$.maybeResolveRoot(Y);if(X)return X;if(Y.endsWith("[]")){let $=Z.$.maybeResolveRoot(Y.slice(0,-2));if($)return $.array()}let _=new z4(new X2(Y),Z),G=$z(_);if(_.finalizer===">")A(H6(">"));return G},$z=(Y)=>{Y.parseOperand();let Z=e4(Y).root;if(!Z)return _0(`Root was unexpectedly unset after parsing string '${Y.scanner.scanned}'`);if(Y.finalizer==="=")Z=KG(Y);else if(Y.finalizer==="?")Z=[Z,"?"];if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.lookahead)A(H6(Y.scanner.lookahead));return Z},e4=(Y)=>{while(Y.finalizer===void 0)Wz(Y);return Y},Wz=(Y)=>Y.hasRoot()?Y.parseOperator():Y.parseOperand();class z4{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Y,Z){this.scanner=Y,this.ctx=Z}error(Y){return A(Y)}hasRoot(){return this.root!==void 0}setRoot(Y){this.root=Y}unsetRoot(){let Y=this.root;return this.root=void 0,Y}constrainRoot(...Y){this.root=this.root.constrain(Y[0],Y[1])}finalize(Y){if(this.groups.length)return this.error($6(")"));this.finalizeBranches(),this.finalizer=Y}reduceLeftBound(Y,Z){let X=Q4[Z];if(!g0(X,UG))return this.error(W6(Z));if(this.branches.leftBound)return this.error(OG(this.branches.leftBound.limit,this.branches.leftBound.comparator,Y,X));this.branches.leftBound={comparator:X,limit:Y}}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 Y=this.groups.pop();if(!Y)return this.error(EG(this.scanner.unscanned));this.branches=Y}addPrefix(Y){this.branches.prefixes.push(Y)}applyPrefixes(){while(this.branches.prefixes.length){let Y=this.branches.prefixes.pop();this.root=Y==="keyof"?this.root.keyof():_0(`Unexpected prefix '${Y}'`)}}pushRootToBranch(Y){this.assertRangeUnset(),this.applyPrefixes();let Z=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(Z)??Z,Y==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Y==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return e4(new z4(this.scanner,this.ctx))}parseOperator(){return RZ(this)}parseOperand(){return AZ(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(VG(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 Hz="An empty string is not a valid generic parameter name",J6=(Y,Z,X)=>{Y.shiftUntilNonWhitespace();let _=Y.shiftUntilNextTerminator();if(_===""){if(Y.lookahead===""&&Z.length)return Z;return A(Hz)}return Y.shiftUntilNonWhitespace(),Jz(Y,_,Z,X)},TG="extends ",Jz=(Y,Z,X,_)=>{if(Y.shiftUntilNonWhitespace(),Y.unscanned.startsWith(TG))Y.jumpForward(TG.length);else{if(Y.lookahead===",")Y.shift();return X.push(Z),J6(Y,X,_)}let G=e4(new z4(Y,_));return X.push([Z,G.root]),J6(Y,X,_)};class IZ extends x1{$;constructor(Y){super((...Z)=>new Y8(Y)(...Z),{bind:Y});this.$=Y}in(Y){return new Y8(this.$,Y===void 0?void 0:this.$.parse(Y))}at(Y,Z){return new Y8(this.$).at(Y,Z)}case(Y,Z){return new Y8(this.$).case(Y,Z)}}class Y8 extends x1{$;in;key;branches=[];constructor(Y,Z){super((X)=>this.caseEntries(Object.entries(X).map(([_,G])=>_==="default"?[_,G]:[this.$.parse(_),G])));this.$=Y,this.in=Z}at(Y,Z){if(this.key)A(zz);if(this.branches.length)A(Qz);return this.key=Y,Z?this.match(Z):this}case(Y,Z){return this.caseEntry(this.$.parse(Y),Z)}caseEntry(Y,Z){let _=(this.key?this.$.parse({[this.key]:Y}):Y).pipe(Z);return this.branches.push(_),this}match(Y){return this(Y)}strings(Y){return this.caseEntries(Object.entries(Y).map(([Z,X])=>Z==="default"?[Z,X]:[this.$.node("unit",{unit:Z}),X]))}caseEntries(Y){for(let Z=0;Z<Y.length;Z++){let[X,_]=Y[Z];if(X==="default"){if(Z!==Y.length-1)A("default may only be specified as the last key of a switch definition");return this.default(_)}if(typeof _!=="function")return A(`Value for case "${X}" must be a function (was ${y0(_)})`);this.caseEntry(X,_)}return this}default(Y){if(typeof Y==="function")this.case(d.unknown,Y);let Z={branches:this.branches,ordered:!0};if(Y==="never"||Y==="assert")Z.meta={onFail:BG};let X=this.$.node("union",Z);if(!this.in)return this.$.finalize(X);let _=this.in.pipe(X);if(Y==="never"||Y==="assert")_=_.configureReferences({onFail:BG},"self");return this.$.finalize(_)}}var BG=(Y)=>Y.throw(),Qz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",zz="At most one key matcher may be specified per expression";var Q6=(Y,Z)=>{if(F0(Y)){if(Y[1]==="=")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"=",Y[2]];if(Y[1]==="?")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"?"]}return z6(Y,Z)},CG="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",qG="Only required keys may specify default values, e.g. { value: 'number = 0' }";var jG=(Y,Z)=>{let X,_={},G=j2(Y);for(let[W,H]of G){let Q=Ez(W);if(Q.kind==="spread"){if(!c1(_))return A(Fz);let D=Z.$.parseOwnDefinitionFormat(H,Z);if(D.equals(d.object))continue;if(!D.hasKind("intersection")||!D.basis?.equals(d.object))return A(Vz(D.expression));X=D.structure;continue}if(Q.kind==="undeclared"){if(H!=="reject"&&H!=="delete"&&H!=="ignore")A(Uz(H));_.undeclared=H;continue}let J=Q6(H,Z),z=Q;if(Q.kind==="required"){if(!F0(J))KZ(_,"required",{key:Q.normalized,value:J},Z);else KZ(_,"optional",J[1]==="="?{key:Q.normalized,value:J[0],default:J[2]}:{key:Q.normalized,value:J[0]},Z);continue}if(F0(J)){if(J[1]==="?")A(CG);if(J[1]==="=")A(qG)}if(Q.kind==="optional"){KZ(_,"optional",{key:Q.normalized,value:J},Z);continue}let E=Z.$.parseOwnDefinitionFormat(z.normalized,Z),V=Y6(E,J,Z.$);if(V.index)_.index=Z0(_.index,V.index);if(V.required)_.required=Z0(_.required,V.required)}let $=Z.$.node("structure",_);return Z.$.parseSchema({domain:"object",structure:X?.merge($)??$})},KZ=(Y,Z,X,_)=>{Y[Z]=Z0(Y[Z],_.$.node(Z,X))},Uz=(Y)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${r(Y)})`,Fz="Spread operator may only be used as the first key in an object",Ez=(Y)=>typeof Y==="symbol"?{kind:"required",normalized:Y}:Y.at(-1)==="?"?Y.at(-2)===v4?{kind:"required",normalized:`${Y.slice(0,-2)}?`}:{kind:"optional",normalized:Y.slice(0,-1)}:Y[0]==="["&&Y.at(-1)==="]"?{kind:"index",normalized:Y.slice(1,-1)}:Y[0]===v4&&Y[1]==="["&&Y.at(-1)==="]"?{kind:"required",normalized:Y.slice(1)}:Y==="..."?{kind:"spread"}:Y==="+"?{kind:"undeclared"}:{kind:"required",normalized:Y==="\\..."?"...":Y==="\\+"?"+":Y},Vz=(Y)=>`Spread operand must resolve to an object literal type (was ${Y})`;var PG=(Y,Z)=>Kz(Y)?hG[Y[0]](Y,Z):Nz(Y)?fG[Y[1]](Y,Z):null,Oz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[1],Z).keyof(),TZ=(Y,Z)=>{if(Y[2]===void 0)return A(MZ(Y[1],""));let X=Z.$.parseOwnDefinitionFormat(Y[0],Z),_=Z.$.parseOwnDefinitionFormat(Y[2],Z);if(Y[1]==="|")return Z.$.node("union",{branches:[X,_]});let G=Y[1]==="&"?U1(X,_,Z.$):u4(X,_,Z.$);if(G instanceof P)return G.throw();return G},Dz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).array(),Lz=(Y,Z)=>{if(typeof Y[2]!=="function")return A(vG("=>",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).pipe(Y[2])},vG=(Y,Z)=>`${Y===":"?"Narrow":"Morph"} expression requires a function following '${Y}' (was ${typeof Z})`,Mz=(Y,Z)=>{if(typeof Y[2]!=="function")return A(vG(":",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).constrain("predicate",Y[2])},Az=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).configureReferences(Y[2],"shallow"),xG=(Y)=>Y,wz=xG({"[]":Dz,"?":()=>A(_6)}),Rz=xG({"|":TZ,"&":TZ,":":Mz,"=>":Lz,"|>":TZ,"@":Az,"=":()=>A(G6)}),fG={...wz,...Rz},Nz=(Y)=>fG[Y[1]]!==void 0,Iz=(Y)=>Y,hG=Iz({keyof:Oz,instanceof:(Y,Z)=>{if(typeof Y[1]!=="function")return A(SG(S4(Y[1])));let X=Y.slice(1).map((_)=>typeof _==="function"?Z.$.node("proto",{proto:_}):A(SG(S4(_))));return X.length===1?X[0]:Z.$.node("union",{branches:X})},"===":(Y,Z)=>Z.$.units(Y.slice(1))}),Kz=(Y)=>hG[Y[0]]!==void 0,SG=(Y)=>`Expected a constructor following 'instanceof' operator (was ${Y})`;var yG=(Y,Z)=>{let X=[{}],_=0;while(_<Y.length){let G=!1;if(Y[_]==="..."&&_<Y.length-1)G=!0,_++;let $=Q6(Y[_],Z),[W,H,Q]=!F0($)?[$]:$;if(_++,G){if(!W.extends(I.intrinsic.Array))return A(Cz(W.expression));X=X.flatMap((J)=>W.distribute((z)=>Bz(d8(J),z)))}else X=X.map((J)=>{if(H==="?")return gG(J,W);if(H==="=")return Tz(J,W,Q);return BZ(J,W)})}return Z.$.parseSchema(X.map((G)=>c1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},BZ=(Y,Z)=>{if(Y.defaultables||Y.optionals)return A(Y.variadic?_Z:qz);if(Y.variadic)Y.postfix=Z0(Y.postfix,Z);else Y.prefix=Z0(Y.prefix,Z);return Y},gG=(Y,Z)=>{if(Y.variadic)return A(pG);return Y.optionals=Z0(Y.optionals,Z),Y},Tz=(Y,Z,X)=>{if(Y.variadic)return A(pG);if(Y.optionals)return A(jz);return Y.defaultables=Z0(Y.defaultables,[[Z,X]]),Y},kG=(Y,Z)=>{if(Y.postfix)A(bG);if(Y.variadic){if(!Y.variadic.equals(Z))A(bG)}else Y.variadic=Z.internal;return Y},Bz=(Y,Z)=>{let X=Z.select({method:"find",kind:"sequence"});if(!X)return kG(Y,I.intrinsic.unknown);if(X.prefix)for(let _ of X.prefix)BZ(Y,_);if(X.optionals)for(let _ of X.optionals)gG(Y,_);if(X.variadic)kG(Y,X.variadic);if(X.postfix)for(let _ of X.postfix)BZ(Y,_);return Y},Cz=(Y)=>`Spread element must be an array (was ${Y})`,bG="A tuple may have at most one variadic element",qz="A required element may not follow an optional element",pG="An optional element may not follow a variadic element";var jz="A defaultable element may not follow an optional element without a default";var Sz={},z6=(Y,Z)=>{if(typeof Y==="string"){if(Z.args&&Object.keys(Z.args).some((_)=>Y.includes(_)))return NZ(Y,Z);let X=Sz[Z.$.name]??={};return X[Y]??=NZ(Y,Z)}return H1(Y,"object")?Pz(Y,Z):A(CZ(y0(Y)))},Pz=(Y,Z)=>{let X=j4(Y);switch(X){case void 0:if(y(Y,"root"))return Y;return jG(Y,Z);case"Array":return vz(Y,Z);case"RegExp":return Z.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0});case"Function":{let _=V2(Y)?Y():Y;if(y(_,"root"))return _;return A(CZ("Function"))}default:return A(CZ(X??r(Y)))}},vz=(Y,Z)=>PG(Y,Z)??yG(Y,Z),CZ=(Y)=>`Type definitions must be strings or objects (was ${Y})`;class qZ extends x1{constructor(Y){let Z=Object.assign({errors:Q1,hkt:n0,$:Y,raw:Y.parse,module:Y.constructor.module,scope:Y.constructor.scope,define:Y.define,match:Y.match,generic:Y.generic,schema:Y.schema,keywords:Y.ambient,unit:Y.unit,enumerated:Y.enumerated,instanceOf:Y.instanceOf,valueOf:Y.valueOf,or:Y.or,and:Y.and,merge:Y.merge,pipe:Y.pipe},Y.ambientAttachments);super((...X)=>{if(X.length===1)return Y.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0].at(-1)===">"){let _=X[0].slice(1,-1),G=Y.parseGenericParams(_,{});return new A2(G,X[1],Y,Y,null)}return Y.parse(X)},{bind:Y,attach:Z})}}var U4=I;class U6 extends Z6{get ambientAttachments(){if(!U4.typeAttachments)return;return this.cacheGetter("ambientAttachments",i(U4.typeAttachments,(Y,Z)=>[Y,this.bindReference(Z)]))}preparseOwnAliasEntry(Y,Z){let X=Y.indexOf("<");if(X===-1){if(y(Z,"module")||y(Z,"generic"))return[Y,Z];let $=this.name==="ark"?Y:Y==="root"?this.name:`${this.name}.${Y}`,W=this.resolvedConfig.keywords?.[$];if(W)Z=[Z,"@",W];return[Y,Z]}if(Y.at(-1)!==">")A("'>' must be the last character of a generic declaration in a scope");let _=Y.slice(0,X),G=Y.slice(X+1,-1);return[_,()=>{let $=this.parseGenericParams(G,{alias:_});return $_($,Z,this)}]}parseGenericParams(Y,Z){return J6(new X2(Y),[],this.createParseContext({...Z,def:Y,prefix:"generic"}))}normalizeRootScopeValue(Y){if(V2(Y)&&!y(Y,"generic"))return Y();return Y}preparseOwnDefinitionFormat(Y,Z){return{...Z,def:Y,prefix:Z.alias??"type"}}parseOwnDefinitionFormat(Y,Z){if(!(Z.alias&&(Z.alias in this.aliases))&&!Z.args)Z.args={this:Z.id};let _=z6(Y,Z);if(F0(_)){if(_[1]==="=")return A(G6);if(_[1]==="?")return A(_6)}return _}unit=(Y)=>this.units([Y]);valueOf=(Y)=>this.units(TX(Y));enumerated=(...Y)=>this.units(Y);instanceOf=(Y)=>this.node("proto",{proto:Y},{prereduced:!0});or=(...Y)=>this.schema(Y.map((Z)=>this.parse(Z)));and=(...Y)=>Y.reduce((Z,X)=>Z.and(this.parse(X)),this.intrinsic.unknown);merge=(...Y)=>Y.reduce((Z,X)=>Z.merge(this.parse(X)),this.intrinsic.object);pipe=(...Y)=>this.intrinsic.unknown.pipe(...Y);match=new IZ(this);declare=()=>({type:this.type});define(Y){return Y}type=new qZ(this);static scope=(Y,Z={})=>new U6(Y,Z);static module=(Y,Z={})=>this.scope(Y,Z).export()}var jZ=Object.assign(U6.scope,{define:(Y)=>Y}),e=U6;class mG extends n0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var xz=K1(["base",d.object],["props",d.object])((Y)=>Y.base.merge(Y.props),mG),uG=e.module({Key:d.key,Merge:xz});class dG extends n0{}var fz=K1("element")((Y)=>{let Z=Y.element.exclude(d.Array),X=Z.array();return Z.rawOr(X).pipe(E2).distribute((_)=>_.assertHasKind("morph").declareOut(X),H0)},dG),cG=e.module({root:d.Array,readonly:"root",index:d.nonNegativeIntegerString,liftFrom:fz},{name:"Array"});var SZ=H0(["string",P2.FileConstructor]),hz=SZ.rawOr(SZ.array()),lG=H0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:hz}}),oG=e.module({root:["instanceof",FormData],value:SZ,parsed:lG,parse:H0({in:FormData,morphs:(Y)=>{let Z={};for(let[X,_]of Y)if(X in Z){let G=Z[X];if(typeof G==="string"||G instanceof P2.FileConstructor)Z[X]=[G,_];else G.push(_)}else Z[X]=_;return Z},declaredOut:lG})},{name:"FormData"});var iG=e.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 kz={Boolean:1,Number:1,String:1},rG=e.module({...i({...DY,...MY},(Y,Z)=>(Y in kz)?[]:[Y,["instanceof",Z]]),Array:cG,TypedArray:iG,FormData:oG});var bz=H0({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"}),yz=H0({domain:"number",divisor:1}),F6=e.module({root:d.number,integer:yz,epoch:bz,safe:H0({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 I0=(Y,Z,X)=>{let _={domain:"string",pattern:{rule:Y.source,flags:Y.flags,meta:Z}};if(X)_.meta={format:X};return J4("intersection",_)},nG=I0(x4,"a well-formed integer string"),H9=e.module({root:nG,parse:H0({in:nG,morphs:(Y,Z)=>{let X=Number.parseInt(Y);return Number.isSafeInteger(X)?X:Z.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:d.integer})},{name:"string.integer"}),gz=I0(/^[\dA-Fa-f]+$/,"hex characters only"),pz=e.module({root:I0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:I0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),sG=I0(/^[A-Z].*$/,"capitalized"),mz=e.module({root:H0({in:"string",morphs:(Y)=>Y.charAt(0).toUpperCase()+Y.slice(1),declaredOut:sG}),preformatted:sG},{name:"string.capitalize"}),uz=(Y)=>{let Z=Y.replaceAll(/[ -]+/g,""),X=0,_,G,$=!1;for(let W=Z.length-1;W>=0;W--){if(_=Z.substring(W,W+1),G=Number.parseInt(_,10),$)G*=2,X+=G>=10?G%10+1:G;else X+=G;$=!$}return!!(X%10===0?Z:!1)},dz=/^(?: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}))$/,cz=H0({domain:"string",pattern:{meta:"a credit card number",rule:dz.source},predicate:{meta:"a credit card number",predicate:uz}});var lz=/^([+-]?\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 oz=(Y)=>!Number.isNaN(new Date(Y).valueOf()),tG=H0({domain:"string",predicate:{meta:"a parsable date",predicate:oz}}).assertHasKind("intersection"),aG=H9.root.internal.narrow((Y,Z)=>{let X=Number.parseInt(Y),_=F6.epoch(X);if(_ instanceof Q1)return Z.errors.merge(_),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),iz=e.module({root:aG,parse:H0({in:aG,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.epoch"}),eG=I0(lz,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),rz=e.module({root:eG,parse:H0({in:eG,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.iso"}),nz=e.module({root:tG,parse:H0({declaredIn:tG,in:"string",morphs:(Y,Z)=>{let X=new Date(Y);if(Number.isNaN(X.valueOf()))return Z.error("a parsable date");return X},declaredOut:d.Date}),iso:rz,epoch:iz},{name:"string.date"}),sz=I0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),Y9="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",w2=`(${Y9}[.]){3}${Y9}`,tz=new RegExp(`^${w2}$`),x0="(?:[0-9a-fA-F]{1,4})",az=new RegExp(`^((?:${x0}:){7}(?:${x0}|:)|(?:${x0}:){6}(?:${w2}|:${x0}|:)|(?:${x0}:){5}(?::${w2}|(:${x0}){1,2}|:)|(?:${x0}:){4}(?:(:${x0}){0,1}:${w2}|(:${x0}){1,3}|:)|(?:${x0}:){3}(?:(:${x0}){0,2}:${w2}|(:${x0}){1,4}|:)|(?:${x0}:){2}(?:(:${x0}){0,3}:${w2}|(:${x0}){1,5}|:)|(?:${x0}:){1}(?:(:${x0}){0,4}:${w2}|(:${x0}){1,6}|:)|(?::((?::${x0}){0,5}:${w2}|(?::${x0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),ez=e.module({root:["v4 | v6","@","an IP address"],v4:I0(tz,"an IPv4 address","ipv4"),v6:I0(az,"an IPv6 address","ipv6")},{name:"string.ip"}),F4="a JSON string",J9=(Y)=>{if(!(Y instanceof SyntaxError))throw Y;return`must be ${F4} (${Y})`},YU=H0({meta:F4,domain:"string",predicate:{meta:F4,predicate:(Y,Z)=>{try{return JSON.parse(Y),!0}catch(X){return Z.reject({code:"predicate",expected:F4,problem:J9(X)})}}}}),ZU=(Y,Z)=>{if(Y.length===0)return Z.error({code:"predicate",expected:F4,actual:"empty"});try{return JSON.parse(Y)}catch(X){return Z.error({code:"predicate",expected:F4,problem:J9(X)})}},XU=e.module({root:YU,parse:H0({meta:"safe JSON string parser",in:"string",morphs:ZU,declaredOut:d.jsonObject})},{name:"string.json"}),Z9=I0(/^[a-z]*$/,"only lowercase letters"),_U=e.module({root:H0({in:"string",morphs:(Y)=>Y.toLowerCase(),declaredOut:Z9}),preformatted:Z9},{name:"string.lower"}),Q9=["NFC","NFD","NFKC","NFKD"],Z8=i(Q9,(Y,Z)=>[Z,H0({domain:"string",predicate:(X)=>X.normalize(Z)===X,meta:`${Z}-normalized unicode`})]),E6=i(Q9,(Y,Z)=>[Z,H0({in:"string",morphs:(X)=>X.normalize(Z),declaredOut:Z8[Z]})]),GU=e.module({root:E6.NFC,preformatted:Z8.NFC},{name:"string.normalize.NFC"}),$U=e.module({root:E6.NFD,preformatted:Z8.NFD},{name:"string.normalize.NFD"}),WU=e.module({root:E6.NFKC,preformatted:Z8.NFKC},{name:"string.normalize.NFKC"}),HU=e.module({root:E6.NFKD,preformatted:Z8.NFKD},{name:"string.normalize.NFKD"}),JU=e.module({root:"NFC",NFC:GU,NFD:$U,NFKC:WU,NFKD:HU},{name:"string.normalize"}),X9=I0(p8,"a well-formed numeric string"),QU=e.module({root:X9,parse:H0({in:X9,morphs:(Y)=>Number.parseFloat(Y),declaredOut:d.number})},{name:"string.numeric"}),_9="a regex pattern",zU=H0({domain:"string",predicate:{meta:_9,predicate:(Y,Z)=>{try{return new RegExp(Y),!0}catch(X){return Z.reject({code:"predicate",expected:_9,problem:String(X)})}}},meta:{format:"regex"}}),UU=/^(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-]+)*))?$/,FU=I0(UU,"a semantic version (see https://semver.org/)"),G9=I0(/^\S.*\S$|^\S?$/,"trimmed"),EU=e.module({root:H0({in:"string",morphs:(Y)=>Y.trim(),declaredOut:G9}),preformatted:G9},{name:"string.trim"}),$9=I0(/^[A-Z]*$/,"only uppercase letters"),VU=e.module({root:H0({in:"string",morphs:(Y)=>Y.toUpperCase(),declaredOut:$9}),preformatted:$9},{name:"string.upper"}),OU=(Y)=>{if(URL.canParse)return URL.canParse(Y);try{return new URL(Y),!0}catch{return!1}},W9=H0({domain:"string",predicate:{meta:"a URL string",predicate:OU},meta:{format:"uri"}}),DU=e.module({root:W9,parse:H0({declaredIn:W9,in:"string",morphs:(Y,Z)=>{try{return new URL(Y)}catch{return Z.error("a URL string")}},declaredOut:H0(URL)})},{name:"string.url"}),LU=e.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:I0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:I0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:I0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:I0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:I0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:I0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:I0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:I0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),z9=e.module({root:d.string,alpha:I0(/^[A-Za-z]*$/,"only letters"),alphanumeric:I0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:gz,base64:pz,capitalize:mz,creditCard:cz,date:nz,digits:I0(/^\d*$/,"only digits 0-9"),email:sz,integer:H9,ip:ez,json:XU,lower:_U,normalize:JU,numeric:QU,regex:zU,semver:FU,trim:EU,upper:VU,url:DU,uuid:LU},{name:"string"});var U9=e.module({bigint:d.bigint,boolean:d.boolean,false:d.false,never:d.never,null:d.null,number:d.number,object:d.object,string:d.string,symbol:d.symbol,true:d.true,unknown:d.unknown,undefined:d.undefined}),F9=e.module({root:d.unknown,any:d.unknown},{name:"unknown"}),MU=e.module({root:d.jsonObject,stringify:J4("morph",{in:d.jsonObject,morphs:(Y)=>JSON.stringify(Y),declaredOut:d.string})},{name:"object.json"}),E9=e.module({root:d.object,json:MU},{name:"object"});class V9 extends n0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var AU=K1(["K",d.key],"V")((Y)=>({domain:"object",index:{signature:Y.K,value:Y.V}}),V9);class O9 extends n0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var wU=K1(["T",d.object],["K",d.key])((Y)=>Y.T.pick(Y.K),O9);class D9 extends n0{description='omit a set of properties from an object like `Omit(User, "age")`'}var RU=K1(["T",d.object],["K",d.key])((Y)=>Y.T.omit(Y.K),D9);class L9 extends n0{description="make all named properties of an object optional like `Partial(User)`"}var NU=K1(["T",d.object])((Y)=>Y.T.partial(),L9);class M9 extends n0{description="make all named properties of an object required like `Required(User)`"}var IU=K1(["T",d.object])((Y)=>Y.T.required(),M9);class A9 extends n0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var KU=K1("T","U")((Y)=>Y.T.exclude(Y.U),A9);class w9 extends n0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var TU=K1("T","U")((Y)=>Y.T.extract(Y.U),w9),R9=e.module({Exclude:KU,Extract:TU,Omit:RU,Partial:NU,Pick:wU,Record:AU,Required:IU});var R2=jZ({...U9,...R9,...rG,...uG,string:z9,number:F6,object:E9,unknown:F9},{prereducedAliases:!0,name:"ark"}),p0=R2.export();Object.assign(U4.ambient,p0);U4.typeAttachments={string:p0.string.root,number:p0.number.root,bigint:p0.bigint,boolean:p0.boolean,symbol:p0.symbol,undefined:p0.undefined,null:p0.null,object:p0.object.root,unknown:p0.unknown.root,false:p0.false,true:p0.true,never:p0.never,arrayIndex:p0.Array.index,Key:p0.Key,Record:p0.Record,Array:p0.Array.root,Date:p0.Date};var F1=Object.assign(R2.type,U4.typeAttachments),BU=R2.match,CU=R2.generic,QK=R2.schema,qU=R2.define,jU=R2.declare;function X1(Y){return JSON.parse(Y)}var Q0=(Y)=>JSON.stringify(Y),TK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function E4(Y){return A6(_1.STORE,Y,void 0)}function X8(Y){return V4(_1.STORE,Y)}function vZ(...Y){return B1(_1.STORE,...Y)}function V6(Y,Z){return S9(_1.STORE,Y,Z)}function N9(Y){return v9(Y,_1.STORE)}var _2={atom_family:"atom family",atom:"atom",continuity:"continuity",key:"key",mutable_atom_family:"atom family [m]",mutable_atom:"atom [m]",readonly_held_selector_family:"selector family [h]",readonly_held_selector:"selector [h]",readonly_pure_selector_family:"selector family",readonly_pure_selector:"selector",state:"state",timeline:"timeline",transaction:"transaction",unknown:"unknown",writable_held_selector_family:"selector family [wh]",writable_held_selector:"selector [wh]",writable_pure_selector_family:"selector family [w]",writable_pure_selector:"selector [w]"};var PZ=(Y)=>(Z,X,_,G,...$)=>{console[Y](`${Z} ${_2[X]} \`${_}\` ${G}`,...$)},SU={error:PZ("error"),info:PZ("info"),warn:PZ("warn")},I9=class{logLevel;filter;logger;constructor(Y,Z,X=SU){this.logLevel=Y,this.filter=Z,this.logger=X}error=(...Y)=>{if(this.logLevel!==null){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.error(...Y);else if(Z)this.logger.error(...Z)}};info=(...Y)=>{if(this.logLevel==="info"){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.info(...Y);else if(Z)this.logger.info(...Z)}};warn=(...Y)=>{if(this.logLevel!=="error"&&this.logLevel!==null){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.warn(...Y);else if(Z)this.logger.warn(...Z)}}};var K9=class{store;deallocateTX;claimTX;constructor(Y=_1.STORE){this.store=Y,this.deallocateTX=B9(Y),this.claimTX=C9(Y),T9("root",Y)}allocate(Y,Z,X){M6(this.store,Y,Z,X)}deallocate(Y){D6(this.store,this.deallocateTX,xZ())(Y)}claim(Y,Z,X){G8(this.store,Y,Z,X)}};function O6(Y){return fZ(_1.STORE,Y)}function _8(Y){return $8(_1.STORE,Y)}var G2=class Y extends Set{mode="record";subject=new W0;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(Z,X=0){super(Z);if(Z instanceof Y)this.parent=Z,this.cacheUpdateNumber=Z.cacheUpdateNumber;if(X)this.cacheLimit=X,this.cache=new Array(X),this.subscribe("auto cache",(_)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=_})}READONLY_VIEW=this;toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(Z){let X=new Y(Z.members,Z.cacheLimit);return X.cache=Z.cache,X.cacheIdx=Z.cacheIdx,X.cacheUpdateNumber=Z.cacheUpdateNumber,X}add(Z){let X=super.add(Z);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${Q0(Z)}`);return X}clear(){let Z=this.mode==="record"?[...this]:null;if(super.clear(),Z)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(Z)}`)}delete(Z){let X=super.delete(Z);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${Q0(Z)}`);return X}parent=null;child=null;transactionUpdates=null;transaction(Z){this.mode="transaction",this.transactionUpdates=[],this.child=new Y(this);let X=this.child._subscribe("transaction",(_)=>{this.transactionUpdates?.push(_)});try{if(Z(this.child)){for(let G of this.transactionUpdates)this.doStep(G);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(_){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",_),_}finally{X(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(Z,X){return this.subject.subscribe(Z,X)}subscribe(Z,X){return this.subject.subscribe(Z,(_)=>{X(`${this.cacheUpdateNumber}=${_}`)})}emit(Z){this.subject.next(Z)}doStep(Z){let X=Z.indexOf(":"),_=Z.substring(0,X),G=Z.substring(X+1);switch(_){case"add":this.add(JSON.parse(G));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(G));break;case"tx":for(let $ of G.split(";"))this.doStep($)}}getUpdateNumber(Z){let X=Z.indexOf("=");return Number(Z.substring(0,X))}do(Z){let X=Z.indexOf("="),_=Number(Z.substring(0,X)),G=_-this.cacheUpdateNumber;if(G>0){if(G===1){this.mode="playback";let W=Z.substring(X+1);return this.doStep(W),this.mode="record",this.cacheUpdateNumber=_,null}return this.cacheUpdateNumber+1}if(Math.abs(G)<this.cacheLimit){let W=this.cacheIdx+G;if(this.cache[W]===Z)return null;this.mode="playback";let Q=!1;while(!Q){this.cacheIdx%=this.cacheLimit;let z=this.cache[this.cacheIdx];if(this.cacheIdx--,!z)return"OUT_OF_RANGE";this.undo(z),Q=this.cacheIdx===W-1}let J=Z.substring(X+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=_,null}return"OUT_OF_RANGE"}undoStep(Z){let X=Z.indexOf(":"),_=Z.substring(0,X),G=Z.substring(X+1);switch(_){case"add":this.delete(JSON.parse(G));break;case"del":this.add(JSON.parse(G));break;case"clear":{let $=JSON.parse(G);for(let W of $)this.add(W);break}case"tx":{let $=G.split(";");for(let W=$.length-1;W>=0;W--)this.undoStep($[W])}}}undo(Z){let X=Z.indexOf("=");if(Number(Z.substring(0,X))===this.cacheUpdateNumber){this.mode="playback";let G=Z.substring(X+1);return this.undoStep(G),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}};function xZ(Y=Math.random){return Y().toString(36).slice(2)}function Y0(Y){while(Y.child!==null)Y=Y.child;return Y}function vU(Y){while(Y.parent!==null)Y=Y.parent;return Y}var xU=class Y{_buffer;_index=0;constructor(Z){let X;if(typeof Z==="number")X=Z;else X=Z.length;this._buffer=Array.from({length:X})}get buffer(){return this._buffer}get index(){return this._index}add(Z){this._buffer[this._index]=Z,this._index=(this._index+1)%this._buffer.length}copy(){let Z=new Y([...this._buffer]);return Z._index=this._index,Z}};function b1(Y){let Z={key:Y.key,type:Y.type};if("family"in Y)Z.family=Y.family;return Z}var fU=Symbol("counterfeit"),hU={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"};function x9(Y,Z,X){let _=Q0(Z),G=`${Y.key}(${_})`,$=hU[Y.type],W={key:G,type:$,family:{key:Y.key,subKey:_}};if(X)W.counterfeit=!0;return W}var k1=class extends Map{deleted=new Set;changed=new Set;source;constructor(Y){super();this.source=Y}get(Y){if(super.has(Y))return super.get(Y);if(!this.deleted.has(Y)&&this.source.has(Y))return this.source.get(Y);return}set(Y,Z){if(this.deleted.delete(Y),this.source.has(Y))this.changed.add(Y);return super.set(Y,Z)}hasOwn(Y){return super.has(Y)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){if(this.source.has(Y))this.deleted.add(Y),this.changed.delete(Y);return super.delete(Y)}clear(){this.deleted=new Set(this.source.keys()),this.changed.clear(),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let[Y,Z]of this.source)if(!this.deleted.has(Y)&&!this.changed.has(Y))yield[Y,Z]}*entries(){yield*this[Symbol.iterator]()}*keys(){yield*super.keys();for(let Y of this.source.keys())if(!this.deleted.has(Y)&&!this.changed.has(Y))yield Y}*values(){for(let[,Y]of this[Symbol.iterator]())yield Y}forEach(Y){for(let[Z,X]of this[Symbol.iterator]())Y(X,Z,this)}get size(){return super.size+this.source.size-this.changed.size-this.deleted.size}},y9=class extends Set{deleted=new Set;source;constructor(Y){super();this.source=Y}add(Y){if(this.source.has(Y))return this.deleted.delete(Y),this;return super.add(Y)}hasOwn(Y){return super.has(Y)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){if(this.source.has(Y))return this.deleted.add(Y),!0;return super.delete(Y)}clear(){this.deleted=new Set(this.source),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let Y of this.source)if(!this.deleted.has(Y))yield Y}*iterateOwn(){yield*super[Symbol.iterator]()}get size(){return super.size+this.source.size-this.deleted.size}},kU=class extends Map{deleted=new Set;source;constructor(Y){super();this.source=Y}get(Y){if(super.has(Y))return super.get(Y);if(!this.deleted.has(Y)&&this.source.has(Y)){let X=this.source.get(Y),_=new y9(X);return super.set(Y,_),_}return}set(Y,Z){return this.deleted.delete(Y),super.set(Y,Z)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){return this.deleted.add(Y),super.delete(Y)}},$2=class Y{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(Z,X)=>`${Z}:${X}`;warn;getRelatedKeys(Z){return this.relations.get(Z)}addRelation(Z,X){let _=this.relations.get(Z),G=this.relations.get(X);if(_)_.add(X);else _=new Set([X]),this.relations.set(Z,_);if(G)G.add(Z);else G=new Set([Z]),this.relations.set(X,G)}deleteRelation(Z,X){let _=this.relations.get(Z);if(_){if(_.delete(X),_.size===0)this.relations.delete(Z);let G=this.relations.get(X);if(G){if(G.delete(Z),G.size===0)this.relations.delete(X)}}}replaceRelationsUnsafely(Z,X){this.relations.set(Z,new Set(X));for(let _ of X){let G=new Set().add(Z);this.relations.set(_,G)}}replaceRelationsSafely(Z,X){let _=this.relations.get(Z),G=this.isAType?.(Z)?Z:void 0,$=G===void 0?Z:void 0;if(_)for(let W of _){G??=W,$??=W;let H=this.relations.get(W);if(H){if(H.size===1)this.relations.delete(W);else H.delete(Z);this.contents.delete(this.makeContentKey(G,$))}}this.relations.set(Z,new Set(X));for(let W of X){let H=this.relations.get(W);if(H)H.add(Z);else H=new Set().add(Z),this.relations.set(W,H)}}getContentInternal(Z){return this.contents.get(Z)}setContent(Z,X){this.contents.set(Z,X)}deleteContent(Z){this.contents.delete(Z)}constructor(Z,X){if(this.a=Z.between[0],this.b=Z.between[1],this.cardinality=Z.cardinality,this.isAType=X?.isAType??null,this.isBType=X?.isBType??null,this.isContent=X?.isContent??null,X?.makeContentKey)this.makeContentKey=X.makeContentKey;if(!X?.externalStore){let _=X?.source;if(_===void 0)this.relations=new Map(Z.relations?.map(([G,$])=>[G,new Set($)])),this.contents=new Map(Z.contents);if(_)this.relations=new kU(_.relations),this.contents=new k1(_.contents)}if(X?.externalStore){let _=X.externalStore;if(this.has=(G,$)=>_.has(G,$),this.addRelation=(G,$)=>{_.addRelation(G,$)},this.deleteRelation=(G,$)=>{_.deleteRelation(G,$)},this.replaceRelationsSafely=(G,$)=>{_.replaceRelationsSafely(G,$)},this.replaceRelationsUnsafely=(G,$)=>{_.replaceRelationsUnsafely(G,$)},this.getRelatedKeys=(G)=>_.getRelatedKeys(G),_.getContent)this.getContentInternal=(G)=>{return _.getContent(G)},this.setContent=(G,$)=>{_.setContent(G,$)},this.deleteContent=(G)=>{_.deleteContent(G)};for(let[G,$]of Z.relations??[]){let W=this.isAType?.(G)?G:void 0,H=W===void 0?G:void 0;for(let Q of $)W??=Q,H??=Q,this.addRelation(W,H)}for(let[G,$]of Z.contents??[])this.setContent(G,$)}if(X?.warn)this.warn=X.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([Z,X])=>[Z,[...X]]),contents:[...this.contents.entries()]}}set(...Z){let X,_,G;switch(Z.length){case 1:{let $=Z[0];X=$[this.a],_=$[this.b],G=void 0;break}case 2:{let $=Z[0];if(typeof $==="string")[X,_]=Z;else X=$[this.a],_=$[this.b],G=Z[1];break}default:X=Z[0],_=Z[1],G=Z[2];break}switch(this.cardinality){case"1:1":{let $=this.getRelatedKey(X);if($&&$!==_)this.delete(X,$)}case"1:n":{let $=this.getRelatedKey(_);if($&&$!==X)this.delete($,_)}break;case"n:n":}if(G){let $=this.makeContentKey(X,_);this.setContent($,G)}return this.addRelation(X,_),this}delete(Z,X){X=typeof X==="string"?X:Z[this.b];let _=typeof Z==="string"?Z:Z[this.a];if(_===void 0&&typeof X==="string"){let G=this.getRelatedKeys(X);if(G)for(let $ of G)this.delete($,X)}else if(typeof _==="string"&&X===void 0){let G=this.getRelatedKeys(_);if(G)for(let $ of G)this.delete(_,$)}else if(typeof _==="string"&&typeof X==="string"){this.deleteRelation(_,X);let G=this.makeContentKey(_,X);this.deleteContent(G)}return this}getRelatedKey(Z){let X=this.getRelatedKeys(Z);if(X){if(X.size>1)this.warn?.(`${X.size} related keys were found for key "${Z}": (${[...X].map((G)=>`"${G}"`).join(", ")}). Only one related key was expected.`);let _;for(let G of X){_=G;break}return _}}replaceRelations(Z,X,_){let G=!Array.isArray(X),$=G?Object.keys(X):X;if(_?.reckless)this.replaceRelationsUnsafely(Z,$);else this.replaceRelationsSafely(Z,$);if(G)for(let W of $){let H=this.makeContentKey(Z,W),Q=X[W];this.setContent(H,Q)}return this}getContent(Z,X){let _=this.makeContentKey(Z,X);return this.getContentInternal(_)}getRelationEntries(Z){let X=Z[this.a],_=Z[this.b];if(X!==void 0&&_===void 0){let G=this.getRelatedKeys(X);if(G)return[...G].map(($)=>{return[$,this.getContent(X,$)]})}if(X===void 0&&_!==void 0){let G=this.getRelatedKeys(_);if(G)return[...G].map(($)=>{return[$,this.getContent($,_)]})}return[]}has(Z,X){if(X)return this.getRelatedKeys(Z)?.has(X)??!1;return this.relations.has(Z)}overlay(){let Z={source:this,makeContentKey:this.makeContentKey};if(this.isAType)Z.isAType=this.isAType;if(this.isBType)Z.isBType=this.isBType;if(this.isContent)Z.isContent=this.isContent;if(this.warn)Z.warn=this.warn;return new Y({between:[this.a,this.b],cardinality:this.cardinality},Z)}incorporate(Z){let{relations:X,contents:_}=Z;for(let[G,$]of X)if($ instanceof y9){let{source:W}=$;for(let H of $.iterateOwn())W.add(H)}else this.relations.set(G,$);for(let G of X.deleted)this.relations.delete(G);for(let[G,$]of _)this.contents.set(G,$);for(let G of _.deleted)this.contents.delete(G)}},W0=class{Subscriber;subscribers=new Map;subscribe(Y,Z){return this.subscribers.set(Y,Z),()=>{this.unsubscribe(Y)}}unsubscribe(Y){this.subscribers.delete(Y)}next(Y){let Z=this.subscribers.values();for(let X of Z)X(Y)}},bU=class extends W0{state;constructor(Y){super();this.state=Y}next(Y){this.state=Y,super.next(Y)}},yU=(Y,Z)=>{let X=Y0(Y);if(X.operation.open)return X.operation.prev.get(Z.key);return X.valueMap.get(Z.key)};function g9(Y,Z,X,_){let G=Y.disposalTraces.buffer.find(($)=>$?.key===Q0(_));switch(Y.logger.error("\u274C",Z.type,Z.key,"gets a fallback value because key",_,"is not allocated",G?`This key was previously disposed:
48
+ ${G.trace}`:"(no previous disposal trace found)"),X.type){case"mutable_atom_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=new X.class;return Y.defaults.set(X.key,$),$}case"atom_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=X.default,W=$(_);return Y.defaults.set(X.key,W),W}case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=X.default(_);return Y.defaults.set(X.key,$),$}}}var bZ=class extends Promise{fate;resolve;reject;done=!1;constructor(Y){let Z,X;super((_,G)=>{Z=_,X=G});this.resolve=Z,this.reject=X,this.use(Y instanceof Promise?Y:new Promise(Y))}pass(Y,Z){if(Y===this.fate)this.resolve(Z),this.done=!0}fail(Y,Z){if(Y===this.fate)this.reject(Z),this.done=!0}use(Y){if(this===Y)return;if(Y instanceof Promise){let Z=Y;this.fate=Z,Z.then((X)=>{this.pass(Z,X)},(X)=>{this.fail(Z,X)})}else this.resolve(Y),this.fate=void 0}};function O4(Y){return"epoch"in Y.transactionMeta}function E1(Y){return"phase"in Y.transactionMeta}function p9(Y,Z){if(Y.operation.open){let X=performance.now();return Y.logger.info("\uD83D\uDEAB",Z.type,Z.key,`deferring setState at T-${X} until setState for "${Y.operation.token.key}" is done`),X}return Y.operation={open:!0,done:new Set,prev:new Map,timestamp:Date.now(),token:Z,subEvents:[]},Y.logger.info("\u2B55",Z.type,Z.key,`operation start in store "${Y.config.name}"${E1(Y)?` ${Y.transactionMeta.phase} "${Y.transactionMeta.update.token.key}"`:""}`),Y}function m9(Y){if(Y.operation.open)Y.logger.info("\uD83D\uDD34",Y.operation.token.type,Y.operation.token.key,`operation done in store "${Y.config.name}"`);Y.operation={open:!1},Y.on.operationClose.next(Y.operation)}var u9=(Y,Z)=>{if(!Y.operation.open)return Y.logger.error("\uD83D\uDC1E","unknown",Z,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return Y.operation.done.has(Z)},R6=(Y,Z)=>{if(!Y.operation.open){Y.logger.error("\uD83D\uDC1E","unknown",Z,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}Y.operation.done.add(Z)};function uZ(Y,Z){let X=Y0(Y),{key:_,type:G}=Z,$=X.selectorAtoms.getRelatedKeys(_);if(X.logger.info("\uD83E\uDDF9",G,_,$?`evicting ${$.size} states downstream:`:"no downstream states",$??"to evict"),$){if(X.operation.open)X.logger.info("\uD83E\uDDF9",G,_,`[ ${[...X.operation.done].join(", ")} ] already done`);for(let W of $){if(u9(X,W))continue;c9(X,W),R6(X,W)}}}function d9(Y,Z){let X=Y0(Y),_=X.selectorGraph.getRelationEntries({upstreamSelectorKey:Z}).filter(([G,{source:$}])=>$===Z);for(let[G]of _){if(u9(X,G))continue;c9(X,G),R6(X,G),d9(Y,G)}}function W2(Y,Z,X){let{key:_,subject:G,type:$}=Z,W=Y.valueMap.get(_);if(W instanceof bZ&&!W.done){let H=W;if(X instanceof Promise)return H.use(X),H;return Y.valueMap.set(_,X),X}if(X instanceof Promise){let H=new bZ(X);return Y.valueMap.set(_,H),H.then(function Q(J){if(Y.valueMap.get(_)===H){switch(p9(Y,Z),W2(Y,Z,J),$){case"atom":case"mutable_atom":uZ(Y,Z);break;case"readonly_pure_selector":case"writable_pure_selector":d9(Y,_);break}m9(Y),G.next({newValue:J,oldValue:H})}}).catch((Q)=>{Y.logger.error("\uD83D\uDCA5","state",_,"rejected:",Q)}),H}return Y.logger.info("\uD83D\uDCDD",Z.type,Z.key,"writing to cache",X),Y.valueMap.set(_,X),X}function gU(Y,Z,X){Y.logger.info("\uD83D\uDCD6",Z.type,Z.key,"reading cached value");let _=Y.valueMap.get(Z.key);if(X==="mut"&&Z.type==="mutable_atom"&&E1(Y)){let $=Z,{parent:W}=Y;if(Y.valueMap.hasOwn($.key))return _;let H=W.valueMap.get($.key);Y.logger.info("\uD83D\uDCC3","atom",$.key,"copying");let Q=H.toJSON(),J=$.class.fromJSON(Q);Y.valueMap.set($.key,J),new tZ($,W),_=J}return _}function c9(Y,Z){let X=Y.valueMap.get(Z);if(X instanceof bZ){let _=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if(_)_.getFrom(Y);return}if(Y.operation.open)Y.operation.prev.set(Z,X);Y.valueMap.delete(Z),Y.logger.info("\uD83D\uDDD1","state",Z,"evicted")}var pU=/^\[object (?:Async|Generator|AsyncGenerator)?Function\]$/;function J8(Y){let Z=Object.prototype.toString.call(Y);return pU.test(Z)}function k2(Y,Z,X){if(Y.valueMap.has(Z.key))return gU(Y,Z,X);Y.logger.info("\u2754",Z.type,Z.key,"value not found in cache");let{key:_}=Z;switch(Z.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return Y.logger.info("\uD83E\uDDEE",Z.type,_,"computing value"),Z.getFrom(Y);case"atom":{let G;if(J8(Z.default))G=Z.default(),Y.logger.info("\u2728",Z.type,_,"computed default",G);else G=Z.default,Y.logger.info("\u2728",Z.type,_,"using static default",G);return W2(Y,Z,G)}case"mutable_atom":{let G=new Z.class;return Y.logger.info("\u2728",Z.type,_,"created new instance",G),W2(Y,Z,G)}}}function dZ(Y,Z){return S0(Y,{key:Z.family.key,type:`${Z.type}_family`})}var Q8=Symbol("MUST_CREATE");function z8(Y,Z,X,_){let G=Q0(X),$=Y.molecules.get(G);if(!$&&Y.config.lifespan==="immortal")return Y.logger.warn("\uD83D\uDCA3","key",G,"was used to mint a counterfeit token for",Z.type,`"${Z.key}"`),x9(Z,X,fU);let H;if(_===Q8){if(Y.logger.info("\uD83D\uDC6A",Z.type,Z.key,"adds member",typeof X==="string"?`\`${X}\``:X),H=Z(X),$)Y.moleculeData.set(G,Z.key)}else H=x9(Z,X);return H}var mU=(Y)=>{Y.logger.info("\uD83E\uDE82","transaction",Y.transactionMeta.update.token.key,"Aborting transaction"),Y.parent.child=null};function D6(Y,Z,X){return(..._)=>{return S0(Y,Z).run(_,X)}}function yZ(Y,Z){if(J8(Y))return Y(Z);return Y}var gZ=(Y,Z,X)=>{let _=k2(Y,Z,"mut"),G=yZ(X,_);return Y.logger.info("\u2B50","atom",Z.key,"setting value",G),G=W2(Y,Z,G),R6(Y,Z.key),uZ(Y,Z),{oldValue:_,newValue:G}};function f9(Y,Z){switch(Z.type){case"mutable_atom":return gZ(Y,Z,new Z.class);case"atom":{let X=Z.default;if(J8(X))X=X();return gZ(Y,Z,X)}}}function uU(Y,Z){let X;switch(Z.type){case"atom":case"mutable_atom":X=f9(Y,Z);break;case"writable_pure_selector":case"writable_held_selector":{let _=Z.getFrom(Y),G=w6(Y,Z.key);for(let W of G.values()){let H=f9(Y,W);r9(Y,Z,H,!1)}let $=Z.getFrom(Y);X={oldValue:_,newValue:$}}break}return X}function T1(Y,...Z){cZ(Y,mZ,...Z)}var pZ=Symbol("RESET");function L6(Y,...Z){let X=[...Z,pZ];T1(Y,...X)}function dU(Y,Z,X){let _,G,$,{type:W,key:H}=Z;switch(Z.type){case"writable_pure_selector":_=k2(Y,Z,"mut"),G=yZ(X,_),G=W2(Y,Z,G);break;case"writable_held_selector":$=Z.const,yZ(X,$),_=$,G=$}return Y.logger.info("\u2B50",W,H,"setting to",G),R6(Y,H),Z.setSelf(G),{oldValue:_,newValue:G}}var cU=(Y,Z,X)=>{let _;switch(Z.type){case"atom":case"mutable_atom":_=gZ(Y,Z,X);break;case"writable_pure_selector":case"writable_held_selector":_=dU(Y,Z,X);break}return _};function lU(Y,Z,X){let{token:_,update:{newValue:G,oldValue:$}}=Z;T1(Y,_,X==="newValue"?G:$)}function oU(Y){let{stack:Z}=Y;if(Z)return`
49
49
  `+Z.split(`
50
50
  `)?.slice(1)?.join(`
51
- `);return""}function K9(Y,Z=o0.STORE){let X={key:Y,stringKey:Q0(Y),dependsOn:"any"};return Z.molecules.set(Q0(Y),X),Y}function V4(Y,Z,X,_="any"){let G=Z,$=Q0(X),W=[],H=t(Y);if(Array.isArray(G))for(let U of G){let F=Q0(U);if(H.molecules.get(F))Y.moleculeGraph.set(F,$,{source:F});else W.push(F)}else{let U=Q0(G);if(H.molecules.get(U))Y.moleculeGraph.set(U,$,{source:U});else W.push(U)}if(W.length===0)H.molecules.set($,{key:X,stringKey:$,dependsOn:_});let Q={type:"molecule_creation",key:X,provenance:G,timestamp:Date.now()};if(a0(H)&&H.transactionMeta.phase==="building")H.transactionMeta.update.subEvents.push(Q);else H.on.moleculeCreation.next(Q);for(let U of W){let F=Y.disposalTraces.buffer.find((V)=>V?.key===U);Y.logger.error("\u274C","key",X,"allocation failed:",`Could not allocate to ${U} in store "${Y.config.name}".`,F?`
52
- ${U} was most recently disposed
53
- ${F.trace}`:`No previous disposal trace for ${U} was found.`)}return X}function B9(Y,Z,X,_){let G=`T$--${Z}==${X}++${_}`;return V4(Y,[X,_],G,"all"),G}function D4(Y,Z){let X=Q0(Z),_=Y.molecules.get(X);if(!_){let D=Y.disposalTraces.buffer.find((A)=>A?.key===X);Y.logger.error("\u274C","key",Z,"deallocation failed:",`Could not find allocation for ${X} in store "${Y.config.name}".`,D?`
51
+ `);return""}function T9(Y,Z=_1.STORE){let X={key:Y,stringKey:Q0(Y),dependsOn:"any"};return Z.molecules.set(Q0(Y),X),Y}function M6(Y,Z,X,_="any"){let G=Z,$=Q0(X),W=[],H=Y0(Y);if(Array.isArray(G))for(let z of G){let E=Q0(z);if(H.molecules.get(E))Y.moleculeGraph.set(E,$,{source:E});else W.push(E)}else{let z=Q0(G);if(H.molecules.get(z))Y.moleculeGraph.set(z,$,{source:z});else W.push(z)}if(W.length===0)H.molecules.set($,{key:X,stringKey:$,dependsOn:_});let Q={type:"molecule_creation",key:X,provenance:G,timestamp:Date.now()};if(E1(H)&&H.transactionMeta.phase==="building")H.transactionMeta.update.subEvents.push(Q);else H.on.moleculeCreation.next(Q);for(let z of W){let E=Y.disposalTraces.buffer.find((V)=>V?.key===z);Y.logger.error("\u274C","key",X,"allocation failed:",`Could not allocate to ${z} in store "${Y.config.name}".`,E?`
52
+ ${z} was most recently disposed
53
+ ${E.trace}`:`No previous disposal trace for ${z} was found.`)}return X}function B9(Y){return $8(Y,{key:"[Internal] deallocate",do:(Z,X)=>{N6(Y0(Y),X)}})}function N6(Y,Z){let X=Q0(Z),_=Y.molecules.get(X);if(!_){let V=Y.disposalTraces.buffer.find((D)=>D?.key===X);Y.logger.error("\u274C","key",Z,"deallocation failed:",`Could not find allocation for ${X} in store "${Y.config.name}".`,V?`
54
54
  This state was most recently deallocated
55
- ${D.trace}`:`No previous disposal trace for ${X} was found.`);return}let G=Y.moleculeJoins.getRelatedKeys(_.key);if(G)for(let D of G){let A=Y.joins.get(D);if(A)A.relations.delete(_.key),A.molecules.delete(_.stringKey)}Y.moleculeJoins.delete(_.stringKey);let $=[],W=[],H={type:"molecule_disposal",key:_.key,values:W,provenance:$,timestamp:Date.now()},Q=t(Y);Q.molecules.delete(X);let J=a0(Q)&&Q.transactionMeta.phase==="building";if(J)Q.transactionMeta.update.subEvents.push(H);let U=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:_.stringKey});if(U)for(let[D,{source:A}]of U)if(A===_.stringKey){let w=G1(D);D4(Y,w)}else $.push(A);let F=Q.moleculeData.getRelatedKeys(_.stringKey);if(F)for(let D of F){let A=Q.families.get(D),w=q0(Y,A,_.key),f=A1(Y,w);W.push([A.key,f]),H8(Y,w)}if(Q.moleculeGraph.delete(_.stringKey),Q.moleculeJoins.delete(_.stringKey),Q.moleculeData.delete(_.stringKey),!J)Q.on.moleculeDisposal.next(H);Q.molecules.delete(_.stringKey);let V=lz(new Error);Y.disposalTraces.add({key:X,trace:V})}function W8(Y,Z,X,_){let G=Q0(X),$=t(Y),W=$.molecules.get(G);if(!W){let V=Y.disposalTraces.buffer.find((D)=>D?.key===G);return Y.logger.error("\u274C","key",G,"claim failed:",`Could not allocate to ${G} in store "${Y.config.name}".`,V?`
55
+ ${V.trace}`:`No previous disposal trace for ${X} was found.`);return}let G=Y.moleculeJoins.getRelatedKeys(X);if(G)for(let V of G){let D=Y.joins.get(V);if(D)D.relations.delete(Z)}Y.moleculeJoins.delete(X);let $=[],W=[],H=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:X});if(H)for(let[V,{source:D}]of H)if(D===X){let R=X1(V);N6(Y,R)}else $.push(D);let Q=Y.moleculeData.getRelatedKeys(_.stringKey);if(Q)for(let V of Q){let D=Y.families.get(V),R=B1(Y,D,Z);W.push([D.key,R]),W8(Y,D,Z)}let J={type:"molecule_disposal",key:_.key,values:W,provenance:$,timestamp:Date.now()};Y.molecules.delete(X);let z=E1(Y)&&Y.transactionMeta.phase==="building";if(z)Y.transactionMeta.update.subEvents.push(J);if(Y.moleculeGraph.delete(_.stringKey),Y.moleculeJoins.delete(_.stringKey),Y.moleculeData.delete(_.stringKey),!z)Y.on.moleculeDisposal.next(J);Y.molecules.delete(_.stringKey);let E=oU(new Error);Y.disposalTraces.add({key:X,trace:E})}function C9(Y){return $8(Y,{key:"[Internal] claim",do:(Z,X,_,G)=>{G8(Y,X,_,G)}})}function G8(Y,Z,X,_){let G=Q0(X),$=Y0(Y),W=$.molecules.get(G);if(!W){let V=Y.disposalTraces.buffer.find((D)=>D?.key===G);return Y.logger.error("\u274C","key",G,"claim failed:",`Could not allocate to ${G} in store "${Y.config.name}".`,V?`
56
56
  ${G} was most recently disposed
57
57
  ${V.trace}`:`No previous disposal trace for ${G} was found.`),X}let H=Q0(Z),Q=$.molecules.get(H);if(!Q){let V=Y.disposalTraces.buffer.find((D)=>D?.key===H);return Y.logger.error("\u274C","key",X,"claim failed:",`Could not allocate to ${H} in store "${Y.config.name}".`,V?`
58
58
  ${H} was most recently disposed
59
- ${V.trace}`:`No previous disposal trace for ${H} was found.`),X}let J=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:W.stringKey}).filter(([,{source:V}])=>V!==G).map(([V])=>G1(V));if(_)$.moleculeGraph.delete(G);$.moleculeGraph.set({upstreamMoleculeKey:Q.stringKey,downstreamMoleculeKey:W.stringKey},{source:Q.stringKey});let U={type:"molecule_transfer",key:W.key,exclusive:Boolean(_),from:J,to:[Q.key],timestamp:Date.now()};if(a0($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.subEvents.push(U);return X}function oz(Y,Z,X){switch(X){case"newValue":l9(Y,Z);break;case"oldValue":H8(Y,Z.token);break}}function iz(Y,Z,X){switch(X){case"newValue":H8(Y,Z.token);break;case"oldValue":if(l9(Y,Z),Z.subType==="atom")Y.valueMap.set(Z.token.key,Z.value);break}}function l9(Y,Z){let{token:X}=Z;if(Z.subType==="writable"&&Z.value)w1(Y,X,Z.value);else A1(Y,X)}function rz(Y,Z,X){switch(X){case"newValue":V4(Y,Z.provenance,Z.key);break;case"oldValue":D4(Y,Z.key);break}}function nz(Y,Z,X){switch(X){case"newValue":D4(Y,Z.key);break;case"oldValue":{let _=Z.provenance.map(G1);V4(Y,_,Z.key);for(let[G,$]of Z.values){let W=Y.families.get(G);if(W){A1(Y,W,Z.key);let H=`${G}(${Q0(Z.key)})`;Y.valueMap.set(H,$)}}}break}}function sz(Y,Z,X){switch(X){case"newValue":for(let _ of Z.to)W8(Y,_,Z.key,Z.exclusive?"exclusive":void 0);break;case"oldValue":{let _="exclusive";for(let G of Z.from)W8(Y,G,Z.key,_),_=void 0}break}}function o9(Y,Z,X){let _=X==="newValue"?Z.subEvents:[...Z.subEvents].reverse();for(let G of _)switch(G.type){case"atom_update":cz(Y,G,X);break;case"state_creation":oz(Y,G,X);break;case"state_disposal":iz(Y,G,X);break;case"molecule_creation":rz(Y,G,X);break;case"molecule_disposal":nz(Y,G,X);break;case"molecule_transfer":sz(Y,G,X);break;case"transaction_outcome":o9(Y,G,X);break}}function i9(Y,Z){return Y.transactionMeta.actionContinuities.getRelatedKey(Z)}function tz(Y,Z){return Y.transactionMeta.epoch.get(Z)}function az(Y,Z){if(!N2(Y))return;let _=i9(Y,Z);if(_===void 0)return;return tz(Y,_)}function ez(Y,Z,X){if(!N2(Y))return;let G=i9(Y,Z);if(G!==void 0)Y.transactionMeta.epoch.set(G,X)}function YF(Y,Z){let X=t(Y),{parent:_}=X;if(_===null||!a0(X)||X.transactionMeta?.phase!=="building"){Y.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}X.transactionMeta.phase="applying",X.transactionMeta.update.output=Z,_.child=null,_.on.transactionApplying.next(X.transactionMeta);let{subEvents:G}=X.transactionMeta.update;if(Y.logger.info("\uD83D\uDEC4","transaction",X.transactionMeta.update.token.key,`Applying transaction with ${G.length} updates:`,G),o9(_,X.transactionMeta.update,"newValue"),N2(_))ez(_,X.transactionMeta.update.token.key,X.transactionMeta.update.epoch),S0(Y,{key:X.transactionMeta.update.token.key,type:"transaction"})?.subject.next(X.transactionMeta.update),Y.logger.info("\uD83D\uDEEC","transaction",X.transactionMeta.update.token.key,"Finished applying transaction.");else if(a0(_))_.transactionMeta.update.subEvents.push(X.transactionMeta.update);_.on.transactionApplying.next(null)}function ZF(Y){return{store:Y}}var XF=(Y,Z,X,_)=>{let G=t(Y),$={parent:G,child:null,on:G.on,loggers:G.loggers,logger:G.logger,config:G.config,atoms:new k1(G.atoms),atomsThatAreDefault:new Set(G.atomsThatAreDefault),families:new k1(G.families),joins:new k1(G.joins),operation:{open:!1},readonlySelectors:new k1(G.readonlySelectors),timelines:new k1(G.timelines),timelineTopics:G.timelineTopics.overlay(),trackers:new Map,transactions:new k1(G.transactions),selectorAtoms:G.selectorAtoms.overlay(),selectorGraph:G.selectorGraph.overlay(),writableSelectors:new k1(G.writableSelectors),valueMap:new k1(G.valueMap),defaults:G.defaults,disposalTraces:Y.disposalTraces.copy(),molecules:new k1(G.molecules),moleculeGraph:G.moleculeGraph.overlay(),moleculeData:G.moleculeData.overlay(),moleculeJoins:G.moleculeJoins.overlay(),miscResources:new k1(G.miscResources)},W=az(Y,Z.key),H={phase:"building",update:{type:"transaction_outcome",token:Z,id:_,epoch:W===void 0?NaN:W+1,timestamp:Date.now(),subEvents:[],params:X,output:void 0},toolkit:{get:(...J)=>A1(Q,...J),set:(...J)=>{w1(Q,...J)},reset:(...J)=>{L6(Q,...J)},run:(J,U=T9())=>vZ(Q,J,U),find:(...J)=>q0(Y,...J),json:(J)=>y2(Q,J),dispose:(...J)=>{H8(Q,...J)},env:()=>ZF(Q)}},Q=Object.assign($,{transactionMeta:H});return G.child=Q,Y.logger.info("\uD83D\uDEEB","transaction",Z.key,"Building transaction with params:",X),Q};function xZ(Y,Z){let{key:X}=Z,_=Y.transactions.has(X),G={key:X,type:"transaction",run:(H,Q)=>{let J=b1(G),U=XF(Y,J,H,Q);try{let F=t(Y),{toolkit:V}=U.transactionMeta,D=Z.do(V,...H);return YF(F,D),D}catch(F){throw pz($),Y.logger.warn("\uD83D\uDCA5","transaction",X,"caught:",F),F}},install:(H)=>xZ(H,Z),subject:new W0},$=t(Y);$.transactions.set(X,G);let W=b1(G);if(!_)Y.on.transactionCreation.next(W);return W}function r9(Y,Z,{oldValue:X,newValue:_},G,$){let W=b1(Z);if(G&&$){Z.subject.next({newValue:_});let F={type:"state_creation",subType:"writable",token:W,timestamp:Date.now(),value:_};$.subject.next(F);let D=t(Y);if(W.family){if(N2(D))switch(W.type){case"atom":case"mutable_atom":Y.on.atomCreation.next(W);break;case"writable_pure_selector":case"writable_held_selector":Y.on.selectorCreation.next(W);break}else if(a0(D)&&D.on.transactionApplying.state===null)D.transactionMeta.update.subEvents.push(F)}return}let{key:H,subject:Q,type:J}=Z,U={oldValue:kZ(X)?X.READONLY_VIEW:X,newValue:kZ(_)?_.READONLY_VIEW:_};if(N2(Y)){switch(J){case"mutable_atom":Y.logger.info("\uD83D\uDCE2",J,H,"is now (",_,") subscribers:",Q.subscribers);break;case"atom":case"writable_pure_selector":case"writable_held_selector":Y.logger.info("\uD83D\uDCE2",J,H,"went (",X,"->",_,") subscribers:",Q.subscribers)}Q.next(U)}if(a0(Y)&&(J==="mutable_atom"||J==="atom")){if(Y.on.transactionApplying.state===null){if(kZ(_))return;let{timestamp:F}=Y.operation,V={type:"atom_update",token:W,timestamp:F,update:U};Y.transactionMeta.update.subEvents.push(V),Y.logger.info("\uD83D\uDCC1","atom",H,"stowed (",X,"->",_,")");return}if(zF(Z,"tracker:signal")){let F=H.slice(1),V=Y.atoms.get(F);if(b2(Y,V,"mut").do(U.newValue)===null===!0)mZ(Y,V)}}}var pZ=Symbol("OWN_OP"),_F=Symbol("JOIN_OP");function dZ(Y,Z,...X){let _,G,$,W,H,Q;if(X.length===2){if($=X[0],Q=X[1],"family"in $)if(W=uZ(Y,$),H=G1($.family.subKey),_=F8(Y,W,H),!_)$=G=z8(Y,W,H,U8);else $=_}else if(W=S0(Y,X[0]),H=X[1],Q=X[2],_=F8(Y,W,H),!_)$=G=z8(Y,W,H,U8);else $=_;let J=Q===A6?"reset":"set",U;if(Z===pZ){let A=g9(Y,$);if(typeof A==="number"){let f=A,v=Y.on.operationClose.subscribe(`waiting to ${J} "${$.key}" at T-${f}`,function k(){v(),Y.logger.info("\uD83D\uDFE2",$.type,$.key,"resuming deferred",J,`from T-${f}`),dZ(Y,Z,$,Q)});return}U=A}else U=Y;if("counterfeit"in $&&"family"in $){let A=$.family.subKey,w=Y.disposalTraces.buffer.find((f)=>f?.key===A);Y.logger.error("\u274C",$.type,$.key,"could not be",J,"because key",A,"is not allocated.",w?`this key was previously disposed:${w.trace}`:"(no previous disposal trace found)");return}let F=S0(U,$),V;if(Q===A6)V=mz(U,F);else V=dz(U,F,Q);let D=Boolean(G);if(r9(U,F,V,D,W),Z===pZ)p9(U)}var n9=(Y,Z)=>t(Y).atoms.has(Z),GF=(Y,Z)=>t(Y).writableSelectors.has(Z),$F=(Y,Z)=>t(Y).readonlySelectors.has(Z),WF=(Y,Z)=>n9(Y,Z)||GF(Y,Z)||$F(Y,Z);function f9(Y,Z){return t(Y).selectorGraph.getRelationEntries({downstreamSelectorKey:Z}).filter(([_,{source:G}])=>G!==Z).map(([_,{source:G}])=>G).filter((_)=>WF(Y,_))}function w6(Y,Z,X=new Set){let _=f9(Y,Z),G=new Map;while(_.length>0){let $=_.pop();if(X.has($))continue;if(X.add($),n9(Y,$)){let W=Y.atoms.get($);G.set(W.key,W)}else _.push(...f9(Y,$))}return G}function HF(Y,Z,X,_,G){let $=t(Y),{type:W,key:H}=_;if(W==="atom"||W==="mutable_atom")$.selectorAtoms.set({selectorKey:X,atomKey:H}),Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atom "${H}"`);else{let Q=w6(Y,H,G);Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atoms: [ ${[...Q.values()].map((J)=>`"${J.key}"`).join(", ")} ]`);for(let{key:J}of Q.values())$.selectorAtoms=$.selectorAtoms.set({selectorKey:X,atomKey:J})}G.add(H)}function N6(Y,Z,X,_){return{get:(...G)=>{let $=t(Y),{token:W,family:H,subKey:Q}=nZ(Y,...G),J;if("counterfeit"in W&&H&&Q)J=y9(Y,W,H,Q);else{let U=S0(Y,W);J=b2(Y,U)}return Y.logger.info("\uD83D\uDD0C",Z,X,`registers dependency ( "${W.key}" =`,J,")"),$.selectorGraph.set({upstreamSelectorKey:W.key,downstreamSelectorKey:X},{source:W.key}),HF(Y,Z,X,W,_),J},set:(...G)=>{let $=t(Y);dZ($,_F,...G)},find:(...G)=>q0(Y,...G),json:(G)=>y2(Y,G)}}function cZ(Y,Z,X){let _=t(Y),G=new W0,$=new Set,{key:W,const:H}=Z,Q="readonly_held_selector";Y.logger.info("\uD83D\uDD28","readonly_held_selector",W,"is being created");let{get:J,find:U,json:F}=N6(_,"readonly_held_selector",W,$),D={...Z,type:"readonly_held_selector",subject:G,getFrom:(w)=>{let f=w.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[v,{source:k}]of f)if(k!==W)w.selectorGraph.delete(v,W);return w.selectorAtoms.delete(W),Z.get({get:J,find:U,json:F},H),W2(w,D,H),Y.logger.info("\u2728","readonly_held_selector",W,"=",H),$.clear(),H},install:(w)=>cZ(w,Z,X)};if(X)D.family=X;_.readonlySelectors.set(W,D);let A={key:W,type:"readonly_held_selector"};if(X)A.family=X;return A}function lZ(Y,Z,X){let _=t(Y),G=new W0,$=new Set,W=Z.key,H="readonly_pure_selector";Y.logger.info("\uD83D\uDD28","readonly_pure_selector",W,"is being created");let{get:Q,find:J,json:U}=N6(_,"readonly_pure_selector",W,$),V={...Z,type:"readonly_pure_selector",subject:G,getFrom:()=>{let A=t(Y),w=A.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[k,{source:m}]of w)if(m!==W)A.selectorGraph.delete(k,W);A.selectorAtoms.delete(W);let f=Z.get({get:Q,find:J,json:U}),v=W2(A,V,f);return Y.logger.info("\u2728","readonly_pure_selector",W,"=",v),$.clear(),v},install:(A)=>lZ(A,Z,X)};if(X)V.family=X;_.readonlySelectors.set(W,V);let D={key:W,type:"readonly_pure_selector"};if(X)D.family=X;return D}function oZ(Y,Z,X){let _=t(Y),G=new W0,$=new Set,{key:W,const:H}=Z,Q="writable_held_selector";Y.logger.info("\uD83D\uDD28","writable_held_selector",W,"is being created");let J=N6(_,"writable_held_selector",W,$),{find:U,get:F,json:V}=J,D={find:U,get:F,json:V},f={...Z,type:"writable_held_selector",subject:G,getFrom:(k)=>{let m=k.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[T,{source:I}]of m)if(I!==W)k.selectorGraph.delete(T,W);return k.selectorAtoms.delete(W),Z.get(D,H),W2(k,f,H),Y.logger.info("\u2728","writable_held_selector",W,"=",H),$.clear(),H},setSelf:()=>{Z.set(J,H)},install:(k)=>oZ(k,Z,X)};if(X)f.family=X;_.writableSelectors.set(W,f);let v={key:W,type:"writable_held_selector"};if(X)v.family=X;return v}function iZ(Y,Z,X){let _=t(Y),G=new W0,$=new Set,W=Z.key,H="writable_pure_selector";Y.logger.info("\uD83D\uDD28","writable_pure_selector",W,"is being created");let Q=N6(_,"writable_pure_selector",W,$),{find:J,get:U,json:F}=Q,V={find:J,get:U,json:F},w={...Z,type:"writable_pure_selector",subject:G,getFrom:(v)=>{let k=v.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[I,{source:q}]of k)if(q!==W)v.selectorGraph.delete(I,W);v.selectorAtoms.delete(W);let m=Z.get(V),T=W2(v,w,m);return Y.logger.info("\u2728","writable_pure_selector",W,"=",T),$.clear(),T},setSelf:(v)=>{Z.set(Q,v)},install:(v)=>iZ(v,Z,X)};if(X)w.family=X;_.writableSelectors.set(W,w);let f={key:W,type:"writable_pure_selector"};if(X)f.family=X;return f}function C9(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X){let $=oZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}if(_){let $=cZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}if(X){let $=iZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}let G=lZ(Y,Z,void 0);return Y.on.selectorCreation.next(G),G}function JF(Y,Z){let X=t(Y),{key:_,type:G,family:$}=Z;if(!$)Y.logger.error("\u274C",G,_,"Standalone selectors cannot be disposed.");else{if(X.molecules.get($.subKey))X.moleculeData.delete($.subKey,$.key);let H;switch(Z.type){case"writable_held_selector":X.writableSelectors.delete(_),H={key:$.key,type:"writable_held_selector_family"},S0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"writable_pure_selector":X.writableSelectors.delete(_),H={key:$.key,type:"writable_pure_selector_family"},S0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"readonly_held_selector":X.readonlySelectors.delete(_),H={key:$.key,type:"readonly_held_selector_family"},S0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"readonly_pure_selector":X.readonlySelectors.delete(_),H={key:$.key,type:"readonly_pure_selector_family"},S0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break}if(X.valueMap.delete(_),X.selectorAtoms.delete(_),X.selectorGraph.delete(_),X.moleculeData.delete($.key,$.subKey),Y.logger.info("\uD83D\uDD25",Z.type,_,"deleted"),a0(X)&&X.transactionMeta.phase==="building")X.transactionMeta.update.subEvents.push({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});else Y.on.selectorDisposal.next(Z)}}function k2(Y,Z,X){let _=Z.key,G="readonly_pure_selector_family",$={key:_,type:"readonly_pure_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","readonly_pure_selector_family",_,`Overwriting an existing ${_2[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new W0,J=Object.assign((U)=>{let F=Q0(U),V={key:_,subKey:F},D=`${_}(${F})`,A=t(Y);return lZ(A,{key:D,get:Z.get(U)},V)},$,{internalRoles:X,subject:H,install:(U)=>k2(U,Z),default:(U)=>{return Z.get(U)({get:(...V)=>A1(Y,...V),find:(...V)=>q0(Y,...V),json:(V)=>y2(Y,V)})}});return Y.families.set(_,J),$}function L4(Y,Z,X){let _={key:Z.key,type:"atom_family"},G=Y.families.get(Z.key);if(G)Y.logger.error("\u2757","atom_family",Z.key,`Overwriting an existing ${_2[G.type]} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new W0,H=Object.assign((Q)=>{let J=Q0(Q),U={key:Z.key,subKey:J},F=`${Z.key}(${J})`,V=t(Y),D=Z.default,A={key:F,default:Q8(D)?()=>D(Q):D};if(Z.effects)A.effects=Z.effects(Q);return h2(V,A,U)},_,{default:Z.default,subject:$,install:(Q)=>L4(Q,Z),internalRoles:X});if(Y.families.set(Z.key,H),Q8(Z.default)===!1)Y.defaults.set(Z.key,Z.default);return _}function s9(Y,Z,X){let _=Z.key,G="readonly_held_selector_family",$={key:_,type:"readonly_held_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","readonly_held_selector_family",_,`Overwriting an existing ${_2[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new W0,J=Object.assign((U)=>{let F=Q0(U),V={key:_,subKey:F},D=`${_}(${F})`,A=t(Y);return cZ(A,{key:D,const:Z.const(U),get:Z.get(U)},V)},$,{internalRoles:X,subject:H,install:(U)=>s9(U,Z),default:Z.const});return Y.families.set(_,J),$}function t9(Y,Z,X){let _=Z.key,G="writable_held_selector_family",$={key:_,type:"writable_held_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","writable_held_selector_family",_,`Overwriting an existing ${_2[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new W0,J=Object.assign((U)=>{let F=Q0(U),V={key:_,subKey:F},D=`${_}(${F})`,A=t(Y);return oZ(A,{key:D,const:Z.const(U),get:Z.get(U),set:Z.set(U)},V)},$,{internalRoles:X,subject:H,install:(U)=>t9(U,Z),default:Z.const});return Y.families.set(_,J),$}function rZ(Y,Z,X){let _=Z.key,G="writable_pure_selector_family",$={key:_,type:"writable_pure_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","writable_pure_selector_family",_,`Overwriting an existing ${_2[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new W0,J=Object.assign((U)=>{let F=Q0(U),V={key:_,subKey:F},D=`${_}(${F})`,A=t(Y);return iZ(A,{key:D,get:Z.get(U),set:Z.set(U)},V)},$,{internalRoles:X,subject:H,install:(U)=>rZ(U,Z),default:(U)=>{return Z.get(U)({get:(...V)=>A1(Y,...V),find:(...V)=>q0(Y,...V),json:(V)=>y2(Y,V)})}});return Y.families.set(_,J),$}function fZ(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X)return t9(Y,Z,void 0);if(_)return s9(Y,Z,void 0);if(X)return rZ(Y,Z);return k2(Y,Z)}function F8(Y,Z,X){let _=Q0(X),G=`${Z.key}(${_})`,$=t(Y),W;switch(Z.type){case"atom_family":case"mutable_atom_family":W=$.atoms.get(G);break;case"writable_held_selector_family":case"writable_pure_selector_family":W=$.writableSelectors.get(G);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":W=$.readonlySelectors.get(G);break}if(W)return b1(W);return W}function q0(Y,Z,X){let _=S0(Y,Z),G=F8(Y,Z,X);if(G)return G;return z8(Y,_,X)}function H8(Y,...Z){let X;if(Z.length===1)X=Z[0];else{let _=Z[0],G=Z[1];X=q0(Y,_,G)}try{S0(Y,X)}catch(_){Y.logger.error("\u274C",X.type,X.key,`could not be disposed because it was not found in the store "${Y.config.name}".`);return}switch(X.type){case"atom":case"mutable_atom":a9(Y,X);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":JF(Y,X);break}}function nZ(Y,...Z){let X,_,G,$,W;if(Z.length===1){if(W=Z[0],"family"in W){let J=uZ(Y,W);if(G=S0(Y,J),$=G1(W.family.subKey),X=F8(Y,J,$),"counterfeit"in W)return{token:W,family:G,subKey:$,isNew:!1};if(!X)_=z8(Y,J,$,U8),W=_;else W=X}}else if(G=S0(Y,Z[0]),$=Z[1],X=F8(Y,G,$),!X)_=z8(Y,G,$,U8),W=_;else W=X;let H="counterfeit"in W;if(Boolean(_)&&H===!1&&G){let J={type:"state_creation",subType:"readable",token:W,timestamp:Date.now()};G.subject.next(J);let F=t(Y);if(W.family){if(N2(F))switch(W.type){case"atom":case"mutable_atom":Y.on.atomCreation.next(W);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":Y.on.selectorCreation.next(W);break}else if(a0(F)&&F.on.transactionApplying.state===null)F.transactionMeta.update.subEvents.push(J)}}return{token:W,family:G,subKey:$,isNew:Boolean(_)}}function A1(Y,...Z){let{token:X,family:_,subKey:G}=nZ(Y,...Z);if("counterfeit"in X&&_&&G)return y9(Y,X,_,G);let $=S0(Y,X);return b2(Y,$)}var h9=(Y,Z,X)=>{return X.subject.subscribe(`${Z.type}:${Z.key}`,(_)=>{Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"root",X.key,"went",_.oldValue,"->",_.newValue);let G=bz(Y,Z),$=b2(Y,Z);Y.logger.info("\u2728",Z.type,Z.key,"went",G,"->",$),Z.subject.next({newValue:$,oldValue:G})})};function E8(Y,Z,X,_){function G(F){if(Y.operation.open){let V=Y.on.operationClose.subscribe(`state subscription ${X}`,()=>{V(),_(F)})}else _(F)}nZ(Y,Z);let $=S0(Y,Z);Y.logger.info("\uD83D\uDC40",$.type,$.key,`Adding subscription "${X}"`);let W=$.type==="writable_pure_selector"||$.type==="readonly_pure_selector",H=new Map,Q=G;if(W){b2(Y,$);for(let[F,V]of w6(Y,$.key))H.set(F,h9(Y,$,V));Q=function F(V){let D=w6(Y,$.key);for(let[A,w]of H)if(D.get(A))D.delete(A);else w(),H.delete(A);for(let[A,w]of D)H.set(A,h9(Y,$,w));G(V)}}let J=$.subject.subscribe(X,Q);return()=>{Y.logger.info("\uD83D\uDE48",$.type,$.key,`Removing subscription "${X}"`),J();for(let F of H.values())F()}}function S0(Y,Z){let X,_=Y;while(_!==null){switch(Z.type){case"atom":case"mutable_atom":X=_.atoms.get(Z.key);break;case"writable_pure_selector":case"writable_held_selector":X=_.writableSelectors.get(Z.key);break;case"readonly_pure_selector":case"readonly_held_selector":X=_.readonlySelectors.get(Z.key);break;case"atom_family":case"mutable_atom_family":case"writable_pure_selector_family":case"readonly_pure_selector_family":case"writable_held_selector_family":case"readonly_held_selector_family":X=_.families.get(Z.key);break;case"timeline":X=_.timelines.get(Z.key);break;case"transaction":X=_.transactions.get(Z.key);break}if(X)return X;_=_.child}throw new c9(Z,Y)}var QF=(Y,Z,X,_)=>{let G=S0(Y,Z);Y.logger.info("\uD83D\uDC40","timeline",Z.key,`Adding subscription "${X}"`);let $=G.subject.subscribe(X,_);return()=>{Y.logger.info("\uD83D\uDE48","timeline",Z.key,`Removing subscription "${X}" from timeline`),$()}};var sZ=class{initializeSignalAtom(Y,Z){let X=`*${Y.key}`;Z.atoms.delete(X),Z.valueMap.delete(X);let _=Y.family?{key:`*${Y.family.key}`,subKey:Y.family.subKey}:void 0,G=h2(Z,{key:X,default:null},_,["tracker:signal"]);if(Z.parent?.valueMap.has(X)){let $=Z.parent.valueMap.get(X);Z.valueMap.set(X,$)}return G}unsubscribeFromInnerValue;unsubscribeFromState;captureSignalsFromCore(Y,Z,X){let _=Y.key,G=X.config.name,$=a0(X)?X.transactionMeta.update.token.key:"main",W=`tracker:${G}:${$}:${_}`,H=(J)=>{w1(X,Z,J)},Q=A1(X,Y);this.unsubscribeFromInnerValue=Q.subscribe(W,H),this.unsubscribeFromState=E8(X,Y,W,function J(U){if(U.newValue!==U.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=U.newValue.subscribe(W,H)}.bind(this))}supplySignalsToCore(Y,Z,X){let _=`tracker:${X.config.name}:${a0(X)?X.transactionMeta.update.token.key:"main"}:${Y.key}`;E8(X,Z,_,function G({newValue:$,oldValue:W}){let H=X.timelineTopics.getRelatedKey(Z.key);if(H&&X.timelines.get(H)?.timeTraveling){let F=QF(X,{key:H,type:"timeline"},_,function V(D){F(),w1(X,Y,(A)=>{if(D==="redo"&&$)A.do($);else if(D==="undo"&&W)A.undo(W);return A})});return}let Q=A1(X,Y),J=Q.getUpdateNumber($),U=J-Q.cacheUpdateNumber;if($&&U===1)w1(X,Y,(F)=>(F.do($),F));else{let F=Q.cacheUpdateNumber+1;X.logger.info("\u274C","mutable_atom",Y.key,"could not be updated. Expected update number",F,"but got",J)}})}mutableAtomToken;latestSignalToken;[Symbol.dispose];constructor(Y,Z){let X=t(Z),_=this.initializeSignalAtom(Y,X);this.mutableAtomToken=Y,this.latestSignalToken=_,this.captureSignalsFromCore(Y,_,X),this.supplySignalsToCore(Y,_,X),X.trackers.set(Y.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(Y.key)}}};function M6(Y,Z,X){Y.logger.info("\uD83D\uDD28","atom",Z.key,`creating in store "${Y.config.name}"`);let _=t(Y),{key:G}=Z,$=_.atoms.get(G),W="mutable_atom";if($&&$.type===W)return Y.logger.error("\u274C",W,G,"Tried to create atom, but it already exists in the store."),b1($);let H=new W0,Q={...Z,type:W,install:(U)=>{return U.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${U.config.name}"`),M6(U,Z,X)},subject:H};if(X)Q.family=X;_.atoms.set(Q.key,Q);let J=b1(Q);if(Z.effects){let U=0,F=[];for(let V of Z.effects){let D=V({resetSelf:()=>{L6(Y,J)},setSelf:(A)=>{w1(Y,J,A)},onSet:(A)=>E8(Y,J,`effect[${U}]`,A)});if(D)F.push(D);++U}Q.cleanup=()=>{for(let V of F)V()}}if(new sZ(J,Y),!X)C9(Y,{key:`${G}:JSON`,get:({get:U})=>U(J).toJSON(),set:({set:U},F)=>{U(J,Z.class.fromJSON(F))}});return Y.on.atomCreation.next(J),J}var UF=class{trackers=new Map;latestSignalAtoms;mutableAtoms;constructor(Y,Z){let X=L4(Z,{key:`*${Y.key}`,default:null},["mutable","updates"]);this.latestSignalAtoms=S0(Z,X),this.mutableAtoms=Y;let _=(G)=>{let{type:$,token:W}=G;if(W.family){let H=G1(W.family.subKey);switch($){case"state_creation":this.trackers.set(H,new sZ(W,Z));break;case"state_disposal":{let Q=this.trackers.get(H);if(Q)Q[Symbol.dispose](),this.trackers.delete(H)}}}};this.mutableAtoms.subject.subscribe(`store=${Z.config.name}::tracker-atom-family`,_)}};function hZ(Y,Z,X){let _={key:Z.key,type:"mutable_atom_family"},G=Y.families.get(Z.key);if(G)Y.logger.error("\u2757","mutable_atom_family",Z.key,`Overwriting an existing ${_2[G.type]} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new W0,H=Object.assign((Q)=>{let J=Q0(Q),U={key:Z.key,subKey:J},F=`${Z.key}(${J})`,V=t(Y),D={key:F,class:Z.class};if(Z.effects)D.effects=Z.effects(Q);return M6(V,D,U)},_,{class:Z.class,subject:$,install:(Q)=>hZ(Q,Z),internalRoles:X});return Y.families.set(Z.key,H),rZ(Y,{key:`${Z.key}:JSON`,get:(Q)=>({get:J})=>J(_,Q).toJSON(),set:(Q)=>({set:J},U)=>{J(_,Q,Z.class.fromJSON(U))}},["mutable","json"]),new UF(H,Y),_}var k9=(Y,Z)=>{let X=t(Z),_=`${Y.key}:JSON`;return X.families.get(_)},y2=(Y,Z)=>{if(Z.family){let _=t(Y),$={key:`${Z.family.key}:JSON`,type:"writable_pure_selector_family"},W=S0(_,$),H=G1(Z.family.subKey);return q0(Y,W,H)}return{type:"writable_pure_selector",key:`${Z.key}:JSON`}};var tZ=(Y)=>{let X={type:"atom",key:`*${Y.key}`};if(Y.family)X.family={key:`*${Y.family.key}`,subKey:Y.family.subKey};return X};function kZ(Y){return typeof Y==="object"&&Y!==null&&"do"in Y&&"undo"in Y&&"subscribe"in Y&&"cacheUpdateNumber"in Y&&"getUpdateNumber"in Y&&"READONLY_VIEW"in Y&&"toJSON"in Y}var q9=class{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new $2({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new $2({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new $2({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new $2({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new vz(100);molecules=new Map;moleculeJoins=new $2({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeGraph=new $2({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeData=new $2({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});miscResources=new Map;on={atomCreation:new W0,atomDisposal:new W0,selectorCreation:new W0,selectorDisposal:new W0,timelineCreation:new W0,transactionCreation:new W0,transactionApplying:new kz(null),operationClose:new W0,moleculeCreation:new W0,moleculeDisposal:new W0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new N9("warn",(Y,Z,X)=>!M4(X))];logger={error:(...Y)=>{for(let Z of this.loggers)Z.error(...Y)},info:(...Y)=>{for(let Z of this.loggers)Z.info(...Y)},warn:(...Y)=>{for(let Z of this.loggers)Z.warn(...Y)}};constructor(Y,Z=null){if(this.config={...Z?.config,...Y},Z!==null){if(this.operation={...Z?.operation},N2(Z))this.transactionMeta={epoch:new Map(Z?.transactionMeta.epoch),actionContinuities:new $2(Z?.transactionMeta.actionContinuities.toJSON())};for(let[,_]of Z.families){if(_.internalRoles?.includes("mutable")||_.internalRoles?.includes("join"))continue;_.install(this)}let X=new Set;for(let[,_]of Z.atoms){if(X.has(_.key))continue;if(_.install(this),_.type==="mutable_atom"){let G=y2(Z,_),$=tZ(_);X.add(G.key),X.add($.key)}}for(let[,_]of Z.readonlySelectors)_.install(this);for(let[,_]of Z.writableSelectors){if(X.has(_.key))continue;_.install(this)}for(let[,_]of Z.transactions)_.install(this);for(let[,_]of Z.timelines)_.install(this)}}},o0={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new q9({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function h2(Y,Z,X,_){let{key:$}=Z;Y.logger.info("\uD83D\uDD28","atom",$,"is being created");let W=t(Y),H=W.atoms.get($);if(H&&H.type==="atom")return Y.logger.error("\u274C","atom",$,"Tried to create atom, but it already exists in the store."),b1(H);let Q=new W0,J={...Z,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",$,`installing in store "${F.config.name}"`),h2(F,Z,X)},subject:Q};if(X)J.family=X;if(_)J.internalRoles=_;W.atoms.set($,J);let U=b1(J);if(Z.effects){let F=0,V=[];for(let D of Z.effects){let A=D({resetSelf:()=>{L6(Y,U)},setSelf:(w)=>{w1(Y,U,w)},onSet:(w)=>E8(Y,U,`effect[${F}]`,w)});if(A)V.push(A);++F}J.cleanup=()=>{for(let D of V)D()}}return Y.on.atomCreation.next(U),U}function a9(Y,Z){let X=t(Y),{key:_,family:G}=Z,$=S0(X,Z);if(!G)Y.logger.error("\u274C","atom",_,"Standalone atoms cannot be disposed.");else{$.cleanup?.();let W=Y.valueMap.get($.key),H=uZ(Y,Z),J=S0(Y,H).subject,U={type:"state_disposal",subType:"atom",token:Z,value:W,timestamp:Date.now()};J.next(U);let F=a0(X);if(X.atoms.delete(_),X.valueMap.delete(_),X.selectorAtoms.delete(_),X.atomsThatAreDefault.delete(_),X.moleculeData.delete(G.key,G.subKey),Y.timelineTopics.delete(_),Z.type==="mutable_atom"){let V=tZ(Z);a9(Y,V),Y.trackers.delete(_)}if(Y.logger.info("\uD83D\uDD25","atom",_,"deleted"),F&&X.transactionMeta.phase==="building"){let V=X.transactionMeta.update.subEvents.at(-1);if(!(V?.type==="molecule_disposal"&&V.values.some(([w])=>w===$.family?.key)))X.transactionMeta.update.subEvents.push(U)}else Y.on.atomDisposal.next(Z)}}function zF(Y,Z){if("internalRoles"in Y===!1)return!1;return Y.internalRoles.includes(Z)}function T0(Y){return Y[0].toUpperCase()+Y.slice(1)}var e9=class{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(Y,Z){let X=this.toolkit;this.toolkit=Y,Z(this),this.toolkit=X}store;realm;[Symbol.dispose](){}constructor(Y,Z,X=o0.STORE){this.store=X,this.realm=new I9(X),this.options=Y,this.defaultContent=Z,this.store.miscResources.set(`join:${Y.key}`,this),this.realm.allocate("root",Y.key),this.toolkit={get:(...T)=>A1(X,...T),set:(...T)=>{w1(X,...T)},find:(...T)=>q0(X,...T),json:(T)=>y2(X,T)};let _=Y.between[0],G=Y.between[1],$=hZ(X,{key:`${Y.key}/relatedKeys`,class:G2},["join","relations"]);this.core={relatedKeysAtoms:$};let W=({get:T},I)=>T($,I),H=({set:T},I,q)=>{if(!this.store.molecules.has(Q0(I)))this.realm.allocate(Y.key,I);T($,I,(C)=>C.add(q)),T($,q,(C)=>C.add(I))},Q=({set:T},I,q)=>{T($,I,(C)=>{return C.delete(q),C}),T($,q,(C)=>{return C.delete(I),C})},J=(T,I,q)=>{let{find:C,get:g,set:n}=T,K=C($,I),a=g(K);for(let p of a){if(q.includes(p))continue;n($,p,(z0)=>{return z0.delete(I),z0})}n(K,(p)=>{return p.transaction((e)=>{e.clear();for(let z0 of q){let h0=W(T,z0),H1=h0.has(I);if(this.relations.cardinality==="1:n"){let r1=[];for(let B of h0){if(B===I)continue;let u=W(T,B);if(u.delete(z0),u.size===0)r1.push(B)}if(!H1&&h0.size>0)h0.clear();for(let B of r1){let u=[z0,B].sort(),G0=`"${u[0]}:${u[1]}"`;this.molecules.delete(G0)}}if(!H1)h0.add(I);e.add(z0)}return!0}),p})},U=(T,I,q)=>{let{set:C}=T;C($,I,(g)=>{return g.transaction((n)=>{for(let K of q)n.add(K);return!0}),g});for(let g of q)C($,g,(n)=>{return n.add(I),n});return!0},F=(T,I,q)=>{let C=W(T,I);return q?C.has(q):C.size>0},V={getRelatedKeys:(T)=>W(this.toolkit,T),addRelation:(T,I)=>{this.store.moleculeJoins.set(T,Y.key),this.store.moleculeJoins.set(I,Y.key),H(this.toolkit,T,I)},deleteRelation:(T,I)=>{Q(this.toolkit,T,I)},replaceRelationsSafely:(T,I)=>{J(this.toolkit,T,I)},replaceRelationsUnsafely:(T,I)=>{U(this.toolkit,T,I)},has:(T,I)=>F(this.toolkit,T,I)},D,A;if(Z){A=L4(X,{key:`${Y.key}/content`,default:Z},["join","content"]);let T=({get:C},g)=>C(A,g),I=({set:C},g,n)=>{C(A,g,n)};D=Object.assign(V,{getContent:(C)=>{return T(this.toolkit,C)},setContent:(C,g)=>{I(this.toolkit,C,g)},deleteContent:(C)=>{this.realm.deallocate(C)}})}else D=V;let w=new $2(Y,{externalStore:D,isAType:Y.isAType,isBType:Y.isBType,makeContentKey:(...T)=>{let[I,q]=T,C=T.sort(),g=`${C[0]}:${C[1]}`,n=X.molecules.get(Q0(I)),K=X.molecules.get(Q0(q));if(!n)this.realm.allocate(Y.key,I);if(!K)this.realm.allocate(Y.key,q);return this.realm.allocate(I,g,"all"),this.realm.claim(q,g),this.store.moleculeJoins.set(g,Y.key),g}}),f=()=>k2(X,{key:`${Y.key}/singleRelatedKey`,get:(T)=>({get:I})=>{let q=I($,T);for(let C of q)return C;return null}},["join","keys"]),v=()=>{return k2(X,{key:`${Y.key}/multipleRelatedKeys`,get:(T)=>({get:I})=>{let q=k9($,X);return I(q,T).members}},["join","keys"])},k=()=>k2(X,{key:`${Y.key}/singleRelatedEntry`,get:(T)=>({get:I})=>{let q=I($,T);for(let C of q){let g=w.isAType?.(T)?T:void 0,n=g===void 0?T:void 0;g??=C,n??=C;let K=w.makeContentKey(g,n),a=I(A,K);return[C,a]}return null}},["join","entries"]),m=()=>k2(X,{key:`${Y.key}/multipleRelatedEntries`,get:(T)=>({get:I})=>{let q=k9($,X);return I(q,T).members.map((g)=>{let n=w.isAType?.(T)?T:void 0,K=n===void 0?T:void 0;n??=g,K??=g;let a=w.makeContentKey(n,K),p=I(A,a);return[g,p]})}},["join","entries"]);switch(Y.cardinality){case"1:1":{let T=f(),I=`${_}KeyOf${T0(G)}`,q=`${G}KeyOf${T0(_)}`,C={[I]:T,[q]:T},g;if(Z){let n=k(),K=`${_}EntryOf${T0(G)}`,a=`${G}EntryOf${T0(_)}`,p={[K]:n,[a]:n};g=Object.assign(C,p)}else g=C;this.relations=w,this.states=g;break}case"1:n":{let T=f(),I=v(),q=`${_}KeyOf${T0(G)}`,C=`${G}KeysOf${T0(_)}`,g={[q]:T,[C]:I},n;if(Z){let K=k(),a=m(),p=`${_}EntryOf${T0(G)}`,e=`${G}EntriesOf${T0(_)}`,z0={[p]:K,[e]:a};n=Object.assign(g,z0)}else n=g;this.relations=w,this.states=n;break}case"n:n":{let T=v(),I=`${_}KeysOf${T0(G)}`,q=`${G}KeysOf${T0(_)}`,C={[I]:T,[q]:T},g;if(Z){let n=m(),K=`${_}EntriesOf${T0(G)}`,a=`${G}EntriesOf${T0(_)}`,p={[K]:n,[a]:n};g=Object.assign(C,p)}else g=C;this.relations=w,this.states=g}}}};function j9(Y,Z,X){return Y.joins.set(Z.key,new e9(Z,X,Y)),{key:Z.key,type:"join",a:Z.between[0],b:Z.between[1],cardinality:Z.cardinality}}function aZ(Y,Z){let X=Z.joins.get(Y.key);if(X===void 0){let G=o0.STORE.joins.get(Y.key);if(G===void 0)throw new Error(`Join "${Y.key}" not found in store "${Z.config.name}"`);X=new e9(G.options,G.defaultContent,Z),Z.joins.set(Y.key,X)}return X}function J8(Y,Z,X){let _=aZ(Y,X),G=t(X);if(a0(G)){let{toolkit:$}=G.transactionMeta;_.transact($,({relations:W})=>{Z(W)})}else Z(_.relations)}function S9(Y,Z,X){let _=aZ(Y,X),G;switch(Y.cardinality){case"1:1":{let $=`${Y.a}KeyOf${T0(Y.b)}`,W=`${Y.b}KeyOf${T0(Y.a)}`;G={get[$](){let Q=_.states[$];return q0(X,Q,Z)},get[W](){let Q=_.states[W];return q0(X,Q,Z)}};let H=`${Y.a}EntryOf${T0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntryOf${T0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return q0(X,J,Z)},get[Q](){let J=_.states[Q];return q0(X,J,Z)}})}break}case"1:n":{let $=`${Y.a}KeyOf${T0(Y.b)}`,W=`${Y.b}KeysOf${T0(Y.a)}`;G={get[$](){let Q=_.states[$];return q0(X,Q,Z)},get[W](){let Q=_.states[W];return q0(X,Q,Z)}};let H=`${Y.a}EntryOf${T0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntriesOf${T0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return q0(X,J,Z)},get[Q](){let J=_.states[Q];return q0(X,J,Z)}})}break}case"n:n":{let $=`${Y.a}KeysOf${T0(Y.b)}`,W=`${Y.b}KeysOf${T0(Y.a)}`;G={get[$](){let Q=_.states[$];return q0(X,Q,Z)},get[W](){let Q=_.states[W];return q0(X,Q,Z)}};let H=`${Y.a}EntriesOf${T0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntriesOf${T0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return q0(X,J,Z)},get[Q](){let J=_.states[Q];return q0(X,J,Z)}})}}}return G}function P9(Y,Z){return aZ(Y,Z).core.relatedKeysAtoms}function M4(Y){return Y.startsWith("\uD83D\uDD0D ")}var FF=(Y)=>{return h2(Y,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Z=new Map;for(let[X,_]of Y.atoms){if(M4(X))continue;let G=b1(_);if(_.family){let $=Z.get(_.family.key);if(!$||!("familyMembers"in $))$={key:_.family.key,familyMembers:new Map},Z.set(_.family.key,$);$.familyMembers.set(_.family.subKey,G)}else Z.set(X,G)}return Z},effects:[({setSelf:Z})=>{Y.on.atomCreation.subscribe("introspection",(X)=>{if(M4(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W===void 0||!("familyMembers"in W))W={key:G,familyMembers:new Map},_.set(G,W);W.familyMembers.set($,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.atomDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)_.delete(G)}}return new Map(_)})})}]},void 0)},EF=(Y)=>{return h2(Y,{key:"\uD83D\uDD0D Selector Token Index",default:()=>{let Z=new Map;for(let X of[Y.readonlySelectors,Y.writableSelectors])for(let[_,G]of X){if(M4(_))continue;let $=b1(G);if(G.family){let W=Z.get(G.family.key);if(!W||!("familyMembers"in W))W={key:G.family.key,familyMembers:new Map},Z.set(G.family.key,W);W.familyMembers.set(G.family.subKey,$)}else Z.set(_,$)}return Z},effects:[({setSelf:Z})=>{Y.on.selectorCreation.subscribe("introspection",(X)=>{if(M4(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W===void 0||!("familyMembers"in W))W={key:G,familyMembers:new Map},_.set(G,W);W.familyMembers.set($,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.selectorDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)_.delete(G)}}else _.delete(X.key);return new Map(_)})})}]},void 0)};var eZ=class{supported;constructor(Y){this.supported=Y}refine(Y){for(let[Z,X]of Object.entries(this.supported))try{if(X(Y)===!0&&X!==Boolean)return{type:Z,data:Y}}catch(_){try{if(Y instanceof X)return{type:Z,data:Y}}catch(G){}}return null}},Z7=new eZ({number:(Y)=>typeof Y==="number",string:(Y)=>typeof Y==="string",boolean:(Y)=>typeof Y==="boolean",null:(Y)=>Y===null});function X7(Y){if(!Y)return!1;return Object.getPrototypeOf(Y)===Object.prototype}var _7=new eZ({object:X7,array:(Y)=>Array.isArray(Y)}),OF=new eZ({...Z7.supported,..._7.supported}),I6=(Y)=>{if(Y===void 0)return"undefined";let Z=OF.refine(Y);if(Z)return Z.type;return Object.getPrototypeOf(Y).constructor.name};var YK=class Y{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Z=o0.STORE){this.store=Z,this.atomIndex=FF(this.store),this.selectorIndex=EF(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(Z=Y.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let X=PZ(this.atomIndex),_=PZ(this.selectorIndex),G=[...X.values()].filter((Q)=>("familyMembers"in Q)),$=[..._.values()].filter((Q)=>("familyMembers"in Q)),W=performance.now(),H=[];if(Z.atomFamilies)for(let Q of G){let J=Q.familyMembers.values();for(let U of J){let V=this.statesCreatedAt.get(U.key)??this.auditorCreatedAt,D=W-V;H.push([U,D])}}if(Z.selectorFamilies)for(let Q of $){let J=Q.familyMembers.values();for(let U of J){let V=this.statesCreatedAt.get(U.key)??this.auditorCreatedAt,D=W-V;H.push([U,D])}}return H}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},Y7=(Y,Z)=>{let X=(_,G)=>{let W=((Q,J)=>{let U=Z(Q,J);if(U)return U;return null})(_,G);if(W?.jobComplete??W?.pathComplete)return W;let H=Array.isArray(G)?G.map((Q,J)=>[J,Q]):X7(G)?Object.entries(G):[];for(let[Q,J]of H){let U=X([..._,Q],J);if(U?.jobComplete)return U}return{}};X([],Y)};function VF(Y,Z){return{summary:`${Y<Z?"+":"-"}${Math.abs(Y-Z)} (${Y} \u2192 ${Z})`}}function DF(Y,Z){return{summary:`${Y.length<Z.length?"+":"-"}${Math.abs(Y.length-Z.length)} ("${Y}" \u2192 "${Z}")`}}function LF(Y,Z){return{summary:`${Y} \u2192 ${Z}`}}function G7(Y,Z,X){let _="",G=[],$=[],W=[];return Y7(Y,(H,Q)=>{let J;for(J of H){let U=Z[J];if(U===void 0)$.push([J,JSON.stringify(Q)]);else{let F=X(Q,U);if(F.summary!=="No Change")W.push([J,F])}}}),Y7(Z,(H,Q)=>{let J;for(J of H)if(Y[J]===void 0)G.push([J,JSON.stringify(Q)])}),_=`\uFF5E${W.length} \uFF0B${G.length} \uFF0D${$.length}`,{summary:_,added:G,removed:$,changed:W}}function MF(Y,Z,X){return G7(Y,Z,X)}var AF=class{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(Y,Z,X){this.leafRefinery=Y,this.treeRefinery=Z,this.leafDiffers={},this.treeDiffers={};for(let _ of Object.keys(Y.supported)){let G=X[_];this.leafDiffers[_]=G}for(let _ of Object.keys(Z.supported)){let G=X[_];this.treeDiffers[_]=G}}diff(Y,Z){if(Y===Z)return{summary:"No Change"};let X=this.leafRefinery.refine(Y)??this.treeRefinery.refine(Y),_=this.leafRefinery.refine(Z)??this.treeRefinery.refine(Z);if(X!==null&&_!==null){if(X.type===_.type){if(X.type in this.leafDiffers)return this.leafDiffers[X.type](X.data,_.data);if(X.type in this.treeDiffers)return this.treeDiffers[X.type](X.data,_.data,(H,Q)=>this.diff(H,Q))}}let G=I6(Y),$=I6(Z);if(G===$)return{summary:`${G} \u2192 ${$}`};return{summary:`Type change: ${G} \u2192 ${$}`}}},ZK=new AF(Z7,_7,{number:VF,string:DF,boolean:LF,null:()=>({summary:"No Change"}),object:G7,array:MF});var wF=class extends Map{set(Y,Z){if(this.has(Y))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:Y,value:Z}),this;return super.set(Y,Z)}clear(){throw new Error("Cannot clear an InvariantMap")}},HK=class Y{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Z){this.key=Z}static existing=new wF;static create(Z,X){let _=new Y(Z),{type:G,globals:$,actions:W,perspectives:H}=X(_),Q={type:G,key:Z,globals:$,actions:W,perspectives:H};return Y.existing.set(Z,Q),Q}add(...Z){switch(Z[0].type){case"atom":case"mutable_atom":this.globals.push(...Z);break;case"transaction":this.actions.push(...Z);break;case"atom_family":case"mutable_atom_family":{let[_,G]=Z;this.perspectives.push({type:"realtime_perspective",resourceAtoms:_,viewAtoms:G})}break}return this}};var JK=O4({key:"usersInRoomIndex",class:G2}),Y5=O4({key:"roomIndex",class:G2}),RF={enteredAtEpoch:0},O8=V6({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(Y)=>typeof Y==="string",isBType:(Y)=>typeof Y==="string"},RF),QK=D6({key:"usersInMyRoomView",get:(Y)=>({find:Z})=>{let X=R9(O8);return[Z(X,Y)]}});import{spawn as NF}from"child_process";var Z5=class{listeners;globalListeners;handleEvent(Y,...Z){for(let _ of this.globalListeners)_(Y,...Z);let X=this.listeners.get(Y);if(X)for(let _ of X)_(...Z)}id="no_id_retrieved";emit;constructor(Y){this.emit=Y,this.listeners=new Map,this.globalListeners=new Set}on(Y,Z){let X=this.listeners.get(Y);if(X)X.add(Z);else this.listeners.set(Y,new Set([Z]));return this}onAny(Y){return this.globalListeners.add(Y),this}off(Y,Z){let X=this.listeners.get(Y);if(X)if(Z)X.delete(Z);else this.listeners.delete(Y);return this}offAny(Y){return this.globalListeners.delete(Y),this}},IF=class extends Z5{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(Y){if(Array.isArray(Y)){let[Z,...X]=Y;switch(Z){case"i":this.logger.info(...X);break;case"w":this.logger.warn(...X);break;case"e":this.logger.error(...X);break;default:return}}}constructor(Y,Z,X){super((_,...G)=>{let $=JSON.stringify([_,...G])+"\x03",W=(H)=>{if(H.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",W)};return this.process.stdin.once("error",W),this.process.stdin.write($),this});if(this.process=Y,this.key=Z,this.logger=X??{info:(..._)=>{console.info(this.id,this.key,..._)},warn:(..._)=>{console.warn(this.id,this.key,..._)},error:(..._)=>{console.error(this.id,this.key,..._)}},this.process.stdout.on("data",(_)=>{let G=_.toString();if(G==="ALIVE")return;this.unprocessedEvents.push(...G.split("\x03"));let $=this.unprocessedEvents.shift();this.incompleteData+=$??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let W=G1(this.incompleteData);this.handleEvent(...W);while(this.unprocessedEvents.length>0){let H=this.unprocessedEvents.shift();if(H){if(this.unprocessedEvents.length===0)this.incompleteData=H;W=G1(H),this.handleEvent(...W)}}this.incompleteData=""}catch(W){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(W)}}),this.process.stderr.on("data",(_)=>{let G=_.toString();this.unprocessedLogs.push(...G.split("\x03"));let $=this.unprocessedLogs.shift();this.incompleteLog+=$??"";try{let W=G1(this.incompleteLog);this.handleLog(W);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)W=G1(this.incompleteLog),this.handleLog(W)}catch(W){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(W),console.error("\u274C\u274C\u274C\uFE0F")}}),Y.pid)this.id=Y.pid.toString()}},TF=class extends Z5{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(Y){super((...Z)=>{return this.out.next(Z),this});this.id=Y,this.in=new W0,this.out=new W0,this.in.subscribe("socket",(Z)=>{this.handleEvent(...Z)})}dispose(){for(let Y of this.disposalFunctions)Y()}},$7=class extends Z5{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...Y){this.process.stderr.write(Q0(Y.map((Z)=>Z instanceof G2?`{ ${Z.toJSON().members.join(" | ")} }`:Z))+"\x03")}logger={info:(...Y)=>{this.log("i",...Y)},warn:(...Y)=>{this.log("w",...Y)},error:(...Y)=>{this.log("e",...Y)}};constructor(){super((Y,...Z)=>{let X=JSON.stringify([Y,...Z]);return this.process.stdout.write(X+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(Y)=>{let Z=Y.toString();this.unprocessedEvents.push(...Z.split("\x03"));let X=this.unprocessedEvents.shift();this.incompleteData+=X??"";try{let _=G1(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",_),this.handleEvent(..._);while(this.unprocessedEvents.length>0){let G=this.unprocessedEvents.shift();if(G){if(this.unprocessedEvents.length===0)this.incompleteData=G;let $=G1(G);this.handleEvent(...$)}}this.incompleteData=""}catch(_){if(_ instanceof Error)this.logger.error("\u2757",_.message,_.cause,_.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(Y)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${Y}`)}),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",(Y)=>{this.logger.info("\uD83D\uDC64","user",Y,"joined");let Z=new TF(`user:${Y}`);this.relays.set(Y,Z),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let X of this.relayServices){let _=X(Z);if(_)Z.disposalFunctions.push(_)}this.on(`user:${Y}`,(...X)=>{Z.in.next(X)}),Z.out.subscribe("socket",(X)=>{this.emit(...X)})}),this.on("user-leaves",(Y)=>{let Z=this.relays.get(Y);if(this.off(`relay:${Y}`),Z)Z.dispose(),this.relays.delete(Y)}),process.stdout.write("ALIVE")}relay(Y){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(Y)}},W7=G8({key:"roomArguments",default:["echo",["Hello World!"]]}),KF=D6({key:"room",get:(Y)=>async({get:Z,find:X})=>{let _=X(W7,Y),G=Z(_),[$,W]=G,H=await new Promise((Q)=>{let J=NF($,W,{env:process.env}),U=(F)=>{if(F.toString()==="ALIVE")J.stdout.off("data",U),Q(J)};J.stdout.on("data",U)});return new IF(H,Y)}}),AK=$8({key:"createRoom",do:({get:Y,set:Z,find:X},_,G,$)=>{let W=$?[G,$]:[G],H=X(W7,_);Z(H,W),Z(Y5,(U)=>U.add(_));let Q=X(KF,_);return Y(Q)}}),wK=$8({key:"joinRoom",do:(Y,Z,X,_)=>{let G={enteredAtEpoch:_};return J8(O8,($)=>{$.set({room:Z,user:X},G)},Y.env().store),G}}),RK=$8({key:"leaveRoom",do:(Y,Z,X)=>{J8(O8,(_)=>{_.delete({room:Z,user:X})},Y.env().store)}}),NK=$8({key:"destroyRoom",do:(Y,Z)=>{J8(O8,(X)=>{X.delete({room:Z})},Y.env().store),Y.set(Y5,(X)=>(X.delete(Z),X))}});var IK=G8({key:"redactor",default:{occlude:(Y)=>Y}}),TK=G8({key:"unacknowledgedUpdates",default:()=>[]}),KK=G8({key:"sockets",default:null}),BK=O4({key:"socketsIndex",class:G2}),CK=O4({key:"usersIndex",class:G2}),qK=V6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(Y)=>Y.startsWith("user::"),isBType:(Y)=>Y.startsWith("socket::")});var{file:y3,serve:mE}=globalThis.Bun;import{readFileSync as Q7}from"fs";import{createServer as jF}from"http";import{createServer as SF}from"https";import{resolve as _5}from"path";function H7(Y,Z){if(Y instanceof Promise)throw new Error(Z)}function BF(Y,Z){let X={},_=[];for(let G in Y){let $=Y[G]["~standard"].validate(Z[G]);if(H7($,`Validation must be synchronous, but ${G} returned a Promise.`),$.issues){_.push(...$.issues.map((W)=>({...W,message:W.message,path:[G,...W.path??[]]})));continue}X[G]=$.value}if(_.length)return{issues:_};return{value:X}}function X5(Y){let Z=Y.runtimeEnvStrict??Y.runtimeEnv??process.env;if(Y.emptyStringAsUndefined??!1){for(let[k,m]of Object.entries(Z))if(m==="")delete Z[k]}if(!!Y.skipValidation)return Z;let G=typeof Y.client==="object"?Y.client:{},$=typeof Y.server==="object"?Y.server:{},W=typeof Y.shared==="object"?Y.shared:{},H=Y.isServer??(typeof window==="undefined"||("Deno"in window)),Q=H?{...$,...W,...G}:{...G,...W},J=Y.createFinalSchema?.(Q,H)["~standard"].validate(Z)??BF(Q,Z);H7(J,"Validation must be synchronous");let U=Y.onValidationError??((k)=>{throw console.error("\u274C Invalid environment variables:",k),new Error("Invalid environment variables")}),F=Y.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(J.issues)return U(J.issues);let V=(k)=>{if(!Y.clientPrefix)return!0;return!k.startsWith(Y.clientPrefix)&&!(k in W)},D=(k)=>{return H||!V(k)},A=(k)=>{return k==="__esModule"||k==="$$typeof"},w=(Y.extends??[]).reduce((k,m)=>{return Object.assign(k,m)},{}),f=Object.assign(w,J.value);return new Proxy(f,{get(k,m){if(typeof m!=="string")return;if(A(m))return;if(!D(m))return F(m);return Reflect.get(k,m)}})}var CF="__vite_start_time"in globalThis,qF=typeof window!=="undefined",gK="vitest"in globalThis,H2=E1("string"),J7=E1('"true" | "false" | undefined'),y1=X5({isServer:!CF&&!qF,server:{CI:E1("string | undefined").pipe(Boolean),POSTGRES_USER:H2,POSTGRES_PASSWORD:H2,POSTGRES_DATABASE:H2,POSTGRES_HOST:H2,POSTGRES_PORT:H2.pipe((Y)=>Number.parseInt(Y,10)),BACKEND_PORT:H2.pipe((Y)=>Number.parseInt(Y,10)),RUN_WORKERS_FROM_SOURCE:J7.pipe((Y)=>Y==="true"),FRONTEND_PORT:H2.pipe((Y)=>Number.parseInt(Y,10)),FRONTEND_ORIGINS:H2.pipe.try((Y)=>JSON.parse(Y),E1("string[]")),API_KEY_OPENAI:E1("string | undefined"),API_KEY_RESEND:E1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:H2,VITE_DEV_FRONTEND_HOST:E1("string | undefined"),VITE_DEV_HTTPS:J7.pipe((Y)=>Y==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var U7=_5(import.meta.dirname,"../dev"),T6=y1.VITE_DEV_HTTPS?{cert:Q7(_5(U7,"./cert.pem"),"utf-8"),key:Q7(_5(U7,"./key.pem"),"utf-8")}:void 0;function oK(Y){if(T6)return SF(T6,Y);return jF({},Y)}import fE from"path";var E=Symbol.for("drizzle:entityKind");function M(Y,Z){if(!Y||typeof Y!=="object")return!1;if(Y instanceof Z)return!0;if(!Object.prototype.hasOwnProperty.call(Z,E))throw new Error(`Class "${Z.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let X=Object.getPrototypeOf(Y).constructor;if(X)while(X){if(E in X&&X[E]===Z[E])return!0;X=Object.getPrototypeOf(X)}return!1}class E0{constructor(Y,Z){this.table=Y,this.config=Z,this.name=Z.name,this.keyAsName=Z.keyAsName,this.notNull=Z.notNull,this.default=Z.default,this.defaultFn=Z.defaultFn,this.onUpdateFn=Z.onUpdateFn,this.hasDefault=Z.hasDefault,this.primary=Z.primaryKey,this.isUnique=Z.isUnique,this.uniqueName=Z.uniqueName,this.uniqueType=Z.uniqueType,this.dataType=Z.dataType,this.columnType=Z.columnType,this.generated=Z.generated,this.generatedIdentity=Z.generatedIdentity}static[E]="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(Y){return Y}mapToDriverValue(Y){return Y}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class G5{static[E]="ColumnBuilder";config;constructor(Y,Z,X){this.config={name:Y,keyAsName:Y==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:Z,columnType:X,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(Y){return this.config.default=Y,this.config.hasDefault=!0,this}$defaultFn(Y){return this.config.defaultFn=Y,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(Y){return this.config.onUpdateFn=Y,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(Y){if(this.config.name!=="")return;this.config.name=Y}}var g1=Symbol.for("drizzle:Name");class $5{static[E]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(Y,Z){if(this.reference=()=>{let{name:X,columns:_,foreignColumns:G}=Y();return{name:X,columns:_,foreignTable:G[0].table,foreignColumns:G}},Z)this._onUpdate=Z.onUpdate,this._onDelete=Z.onDelete}onUpdate(Y){return this._onUpdate=Y===void 0?"no action":Y,this}onDelete(Y){return this._onDelete=Y===void 0?"no action":Y,this}build(Y){return new z7(Y,this)}}class z7{constructor(Y,Z){this.table=Y,this.reference=Z.reference,this.onUpdate=Z._onUpdate,this.onDelete=Z._onDelete}static[E]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:Y,columns:Z,foreignColumns:X}=this.reference(),_=Z.map((W)=>W.name),G=X.map((W)=>W.name),$=[this.table[g1],..._,X[0].table[g1],...G];return Y??`${$.join("_")}_fk`}}function K6(Y,...Z){return Y(...Z)}function F7(Y,Z){return`${Y[g1]}_${Z.join("_")}_unique`}function E7(Y,Z,X){for(let _=Z;_<Y.length;_++){let G=Y[_];if(G==="\\"){_++;continue}if(G==='"')return[Y.slice(Z,_).replace(/\\/g,""),_+1];if(X)continue;if(G===","||G==="}")return[Y.slice(Z,_).replace(/\\/g,""),_]}return[Y.slice(Z).replace(/\\/g,""),Y.length]}function O7(Y,Z=0){let X=[],_=Z,G=!1;while(_<Y.length){let $=Y[_];if($===","){if(G||_===Z)X.push("");G=!0,_++;continue}if(G=!1,$==="\\"){_+=2;continue}if($==='"'){let[Q,J]=E7(Y,_+1,!0);X.push(Q),_=J;continue}if($==="}")return[X,_+1];if($==="{"){let[Q,J]=O7(Y,_+1);X.push(Q),_=J;continue}let[W,H]=E7(Y,_,!1);X.push(W),_=H}return[X,_]}function V7(Y){let[Z]=O7(Y,1);return Z}function W5(Y){return`{${Y.map((Z)=>{if(Array.isArray(Z))return W5(Z);if(typeof Z==="string")return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Z}`}).join(",")}}`}class b extends G5{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(Y){return new L7(this.config.name,this,Y)}references(Y,Z={}){return this.foreignKeyConfigs.push({ref:Y,actions:Z}),this}unique(Y,Z){return this.config.isUnique=!0,this.config.uniqueName=Y,this.config.uniqueType=Z?.nulls,this}generatedAlwaysAs(Y){return this.config.generated={as:Y,type:"always",mode:"stored"},this}buildForeignKeys(Y,Z){return this.foreignKeyConfigs.map(({ref:X,actions:_})=>{return K6((G,$)=>{let W=new $5(()=>{let H=G();return{columns:[Y],foreignColumns:[H]}});if($.onUpdate)W.onUpdate($.onUpdate);if($.onDelete)W.onDelete($.onDelete);return W.build(Z)},X,_)})}buildExtraConfigColumn(Y){return new D7(Y,this.config)}}class j extends E0{constructor(Y,Z){if(!Z.uniqueName)Z.uniqueName=F7(Y,[Z.name]);super(Y,Z);this.table=Y}static[E]="PgColumn"}class D7 extends j{static[E]="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(Y){return this.indexConfig.opClass=Y,this}}class V8{static[E]="IndexedColumn";constructor(Y,Z,X,_){this.name=Y,this.keyAsName=Z,this.type=X,this.indexConfig=_}name;keyAsName;type;indexConfig}class L7 extends b{static[E]="PgArrayBuilder";constructor(Y,Z,X){super(Y,"array","PgArray");this.config.baseBuilder=Z,this.config.size=X}build(Y){let Z=this.config.baseBuilder.build(Y);return new H5(Y,this.config,Z)}}class H5 extends j{constructor(Y,Z,X,_){super(Y,Z);this.baseColumn=X,this.range=_,this.size=Z.size}size;static[E]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(Y){if(typeof Y==="string")Y=V7(Y);return Y.map((Z)=>this.baseColumn.mapFromDriverValue(Z))}mapToDriverValue(Y,Z=!1){let X=Y.map((_)=>_===null?null:M(this.baseColumn,H5)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Z)return X;return W5(X)}}class M7 extends b{static[E]="PgEnumObjectColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumObjectColumn");this.config.enum=Z}build(Y){return new A7(Y,this.config)}}class A7 extends j{static[E]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}var B6=Symbol.for("drizzle:isPgEnum");function w7(Y){return!!Y&&typeof Y==="function"&&B6 in Y&&Y[B6]===!0}class R7 extends b{static[E]="PgEnumColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumColumn");this.config.enum=Z}build(Y){return new N7(Y,this.config)}}class N7 extends j{static[E]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}function D8(Y,Z){return Array.isArray(Z)?PF(Y,[...Z],void 0):vF(Y,Z,void 0)}function PF(Y,Z,X){let _=Object.assign((G)=>new R7(G??"",_),{enumName:Y,enumValues:Z,schema:X,[B6]:!0});return _}function vF(Y,Z,X){let _=Object.assign((G)=>new M7(G??"",_),{enumName:Y,enumValues:Object.values(Z),schema:X,[B6]:!0});return _}class P0{static[E]="Subquery";constructor(Y,Z,X,_=!1,G=[]){this._={brand:"Subquery",sql:Y,selectedFields:Z,alias:X,isWith:_,usedTables:G}}}class L8 extends P0{static[E]="WithSubquery"}var I7="0.44.5";var J5,Q5,O0={startActiveSpan(Y,Z){if(!J5)return Z();if(!Q5)Q5=J5.trace.getTracer("drizzle-orm",I7);return K6((X,_)=>_.startActiveSpan(Y,(G)=>{try{return Z(G)}catch($){throw G.setStatus({code:X.SpanStatusCode.ERROR,message:$ instanceof Error?$.message:"Unknown error"}),$}finally{G.end()}}),J5,Q5)}};var M0=Symbol.for("drizzle:ViewBaseConfig");var g2=Symbol.for("drizzle:Schema"),C6=Symbol.for("drizzle:Columns"),T7=Symbol.for("drizzle:ExtraConfigColumns"),U5=Symbol.for("drizzle:OriginalName"),z5=Symbol.for("drizzle:BaseName"),M8=Symbol.for("drizzle:IsAlias"),K7=Symbol.for("drizzle:ExtraConfigBuilder"),xF=Symbol.for("drizzle:IsDrizzleTable");class S{static[E]="Table";static Symbol={Name:g1,Schema:g2,OriginalName:U5,Columns:C6,ExtraConfigColumns:T7,BaseName:z5,IsAlias:M8,ExtraConfigBuilder:K7};[g1];[U5];[g2];[C6];[T7];[z5];[M8]=!1;[xF]=!0;[K7]=void 0;constructor(Y,Z,X){this[g1]=this[U5]=Y,this[g2]=Z,this[z5]=X}}function d0(Y){return Y[g1]}function p2(Y){return`${Y[g2]??"public"}.${Y[g1]}`}function F5(Y){return Y!==null&&Y!==void 0&&typeof Y.getSQL==="function"}function fF(Y){let Z={sql:"",params:[]};for(let X of Y)if(Z.sql+=X.sql,Z.params.push(...X.params),X.typings?.length){if(!Z.typings)Z.typings=[];Z.typings.push(...X.typings)}return Z}class m0{static[E]="StringChunk";value;constructor(Y){this.value=Array.isArray(Y)?Y:[Y]}getSQL(){return new h([this])}}class h{constructor(Y){this.queryChunks=Y;for(let Z of Y)if(M(Z,S)){let X=Z[S.Symbol.Schema];this.usedTables.push(X===void 0?Z[S.Symbol.Name]:X+"."+Z[S.Symbol.Name])}}static[E]="SQL";decoder=C7;shouldInlineParams=!1;usedTables=[];append(Y){return this.queryChunks.push(...Y.queryChunks),this}toQuery(Y){return O0.startActiveSpan("drizzle.buildSQL",(Z)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,Y);return Z?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams(Y,Z){let X=Object.assign({},Z,{inlineParams:Z.inlineParams||this.shouldInlineParams,paramStartIndex:Z.paramStartIndex||{value:0}}),{casing:_,escapeName:G,escapeParam:$,prepareTyping:W,inlineParams:H,paramStartIndex:Q}=X;return fF(Y.map((J)=>{if(M(J,m0))return{sql:J.value.join(""),params:[]};if(M(J,q6))return{sql:G(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let U=[new m0("(")];for(let[F,V]of J.entries())if(U.push(V),F<J.length-1)U.push(new m0(", "));return U.push(new m0(")")),this.buildQueryFromSourceParams(U,X)}if(M(J,h))return this.buildQueryFromSourceParams(J.queryChunks,{...X,inlineParams:H||J.shouldInlineParams});if(M(J,S)){let U=J[S.Symbol.Schema],F=J[S.Symbol.Name];return{sql:U===void 0||J[M8]?G(F):G(U)+"."+G(F),params:[]}}if(M(J,E0)){let U=_.getColumnCasing(J);if(Z.invokeSource==="indexes")return{sql:G(U),params:[]};let F=J.table[S.Symbol.Schema];return{sql:J.table[M8]||F===void 0?G(J.table[S.Symbol.Name])+"."+G(U):G(F)+"."+G(J.table[S.Symbol.Name])+"."+G(U),params:[]}}if(M(J,O1)){let U=J[M0].schema,F=J[M0].name;return{sql:U===void 0||J[M0].isAlias?G(F):G(U)+"."+G(F),params:[]}}if(M(J,R1)){if(M(J.value,I2))return{sql:$(Q.value++,J),params:[J],typings:["none"]};let U=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(M(U,h))return this.buildQueryFromSourceParams([U],X);if(H)return{sql:this.mapInlineParam(U,X),params:[]};let F=["none"];if(W)F=[W(J.encoder)];return{sql:$(Q.value++,U),params:[U],typings:F}}if(M(J,I2))return{sql:$(Q.value++,J),params:[J],typings:["none"]};if(M(J,h.Aliased)&&J.fieldAlias!==void 0)return{sql:G(J.fieldAlias),params:[]};if(M(J,P0)){if(J._.isWith)return{sql:G(J._.alias),params:[]};return this.buildQueryFromSourceParams([new m0("("),J._.sql,new m0(") "),new q6(J._.alias)],X)}if(w7(J)){if(J.schema)return{sql:G(J.schema)+"."+G(J.enumName),params:[]};return{sql:G(J.enumName),params:[]}}if(F5(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],X);return this.buildQueryFromSourceParams([new m0("("),J.getSQL(),new m0(")")],X)}if(H)return{sql:this.mapInlineParam(J,X),params:[]};return{sql:$(Q.value++,J),params:[J],typings:["none"]}}))}mapInlineParam(Y,{escapeString:Z}){if(Y===null)return"null";if(typeof Y==="number"||typeof Y==="boolean")return Y.toString();if(typeof Y==="string")return Z(Y);if(typeof Y==="object"){let X=Y.toString();if(X==="[object Object]")return Z(JSON.stringify(Y));return Z(X)}throw new Error("Unexpected param value: "+Y)}getSQL(){return this}as(Y){if(Y===void 0)return this;return new h.Aliased(this,Y)}mapWith(Y){return this.decoder=typeof Y==="function"?{mapFromDriverValue:Y}:Y,this}inlineParams(){return this.shouldInlineParams=!0,this}if(Y){return Y?this:void 0}}class q6{constructor(Y){this.value=Y}static[E]="Name";brand;getSQL(){return new h([this])}}function B7(Y){return typeof Y==="object"&&Y!==null&&"mapToDriverValue"in Y&&typeof Y.mapToDriverValue==="function"}var C7={mapFromDriverValue:(Y)=>Y},q7={mapToDriverValue:(Y)=>Y},hB={...C7,...q7};class R1{constructor(Y,Z=q7){this.value=Y,this.encoder=Z}static[E]="Param";brand;getSQL(){return new h([this])}}function O(Y,...Z){let X=[];if(Z.length>0||Y.length>0&&Y[0]!=="")X.push(new m0(Y[0]));for(let[_,G]of Z.entries())X.push(G,new m0(Y[_+1]));return new h(X)}((Y)=>{function Z(){return new h([])}Y.empty=Z;function X(Q){return new h(Q)}Y.fromList=X;function _(Q){return new h([new m0(Q)])}Y.raw=_;function G(Q,J){let U=[];for(let[F,V]of Q.entries()){if(F>0&&J!==void 0)U.push(J);U.push(V)}return new h(U)}Y.join=G;function $(Q){return new q6(Q)}Y.identifier=$;function W(Q){return new I2(Q)}Y.placeholder=W;function H(Q,J){return new R1(Q,J)}Y.param=H})(O||(O={}));((Y)=>{class Z{constructor(X,_){this.sql=X,this.fieldAlias=_}static[E]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Z(this.sql,this.fieldAlias)}}Y.Aliased=Z})(h||(h={}));class I2{constructor(Y){this.name=Y}static[E]="Placeholder";getSQL(){return new h([this])}}function E5(Y,Z){return Y.map((X)=>{if(M(X,I2)){if(!(X.name in Z))throw new Error(`No value for placeholder "${X.name}" was provided`);return Z[X.name]}if(M(X,R1)&&M(X.value,I2)){if(!(X.value.name in Z))throw new Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue(Z[X.value.name])}return X})}var hF=Symbol.for("drizzle:IsDrizzleView");class O1{static[E]="View";[M0];[hF]=!0;constructor({name:Y,schema:Z,selectedFields:X,query:_}){this[M0]={name:Y,originalName:Y,schema:Z,selectedFields:X,query:_,isExisting:!_,isAlias:!1}}getSQL(){return new h([this])}}E0.prototype.getSQL=function(){return new h([this])};S.prototype.getSQL=function(){return new h([this])};P0.prototype.getSQL=function(){return new h([this])};class A4{constructor(Y){this.table=Y}static[E]="ColumnAliasProxyHandler";get(Y,Z){if(Z==="table")return this.table;return Y[Z]}}class A8{constructor(Y,Z){this.alias=Y,this.replaceOriginalName=Z}static[E]="TableAliasProxyHandler";get(Y,Z){if(Z===S.Symbol.IsAlias)return!0;if(Z===S.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Z===S.Symbol.OriginalName)return this.alias;if(Z===M0)return{...Y[M0],name:this.alias,isAlias:!0};if(Z===S.Symbol.Columns){let _=Y[S.Symbol.Columns];if(!_)return _;let G={};return Object.keys(_).map(($)=>{G[$]=new Proxy(_[$],new A4(new Proxy(Y,this)))}),G}let X=Y[Z];if(M(X,E0))return new Proxy(X,new A4(new Proxy(Y,this)));return X}}function j6(Y,Z){return new Proxy(Y,new A8(Z,!1))}function o1(Y,Z){return new Proxy(Y,new A4(new Proxy(Y.table,new A8(Z,!1))))}function O5(Y,Z){return new h.Aliased(w8(Y.sql,Z),Y.fieldAlias)}function w8(Y,Z){return O.join(Y.queryChunks.map((X)=>{if(M(X,E0))return o1(X,Z);if(M(X,h))return w8(X,Z);if(M(X,h.Aliased))return O5(X,Z);return X}))}class S6 extends Error{static[E]="DrizzleError";constructor({message:Y,cause:Z}){super(Y);this.name="DrizzleError",this.cause=Z}}class J2 extends Error{constructor(Y,Z,X){super(`Failed query: ${Y}
60
- params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrace(this,J2),X)this.cause=X}}class V5 extends S6{static[E]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class j7{static[E]="ConsoleLogWriter";write(Y){console.log(Y)}}class D5{static[E]="DefaultLogger";writer;constructor(Y){this.writer=Y?.writer??new j7}logQuery(Y,Z){let X=Z.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),_=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${Y}${_}`)}}class L5{static[E]="NoopLogger";logQuery(){}}class $1{static[E]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(Y){return this.then(void 0,Y)}finally(Y){return this.then((Z)=>{return Y?.(),Z},(Z)=>{throw Y?.(),Z})}then(Y,Z){return this.execute().then(Y,Z)}}function S7(Y,Z,X){let _={},G=Y.reduce(($,{path:W,field:H},Q)=>{let J;if(M(H,E0))J=H;else if(M(H,h))J=H.decoder;else J=H.sql.decoder;let U=$;for(let[F,V]of W.entries())if(F<W.length-1){if(!(V in U))U[V]={};U=U[V]}else{let D=Z[Q],A=U[V]=D===null?null:J.mapFromDriverValue(D);if(X&&M(H,E0)&&W.length===2){let w=W[0];if(!(w in _))_[w]=A===null?d0(H.table):!1;else if(typeof _[w]==="string"&&_[w]!==d0(H.table))_[w]=!1}}return $},{});if(X&&Object.keys(_).length>0){for(let[$,W]of Object.entries(_))if(typeof W==="string"&&!X[W])G[$]=null}return G}function C1(Y,Z){return Object.entries(Y).reduce((X,[_,G])=>{if(typeof _!=="string")return X;let $=Z?[...Z,_]:[_];if(M(G,E0)||M(G,h)||M(G,h.Aliased))X.push({path:$,field:G});else if(M(G,S))X.push(...C1(G[S.Symbol.Columns],$));else X.push(...C1(G,$));return X},[])}function R8(Y,Z){let X=Object.keys(Y),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let[G,$]of X.entries())if($!==_[G])return!1;return!0}function P6(Y,Z){let X=Object.entries(Z).filter(([,_])=>_!==void 0).map(([_,G])=>{if(M(G,h)||M(G,E0))return[_,G];else return[_,new R1(G,Y[S.Symbol.Columns][_])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function P7(Y,Z){for(let X of Z)for(let _ of Object.getOwnPropertyNames(X.prototype)){if(_==="constructor")continue;Object.defineProperty(Y.prototype,_,Object.getOwnPropertyDescriptor(X.prototype,_)||Object.create(null))}}function v7(Y){return Y[S.Symbol.Columns]}function Q2(Y){return M(Y,P0)?Y._.alias:M(Y,O1)?Y[M0].name:M(Y,h)?void 0:Y[S.Symbol.IsAlias]?Y[S.Symbol.Name]:Y[S.Symbol.BaseName]}function X0(Y,Z){return{name:typeof Y==="string"&&Y.length>0?Y:"",config:typeof Y==="object"?Y:Z}}function x7(Y){if(typeof Y!=="object"||Y===null)return!1;if(Y.constructor.name!=="Object")return!1;if("logger"in Y){let Z=typeof Y.logger;if(Z!=="boolean"&&(Z!=="object"||typeof Y.logger.logQuery!=="function")&&Z!=="undefined")return!1;return!0}if("schema"in Y){let Z=typeof Y.schema;if(Z!=="object"&&Z!=="undefined")return!1;return!0}if("casing"in Y){let Z=typeof Y.casing;if(Z!=="string"&&Z!=="undefined")return!1;return!0}if("mode"in Y){if(Y.mode!=="default"||Y.mode!=="planetscale"||Y.mode!==void 0)return!1;return!0}if("connection"in Y){let Z=typeof Y.connection;if(Z!=="string"&&Z!=="object"&&Z!=="undefined")return!1;return!0}if("client"in Y){let Z=typeof Y.client;if(Z!=="object"&&Z!=="function"&&Z!=="undefined")return!1;return!0}if(Object.keys(Y).length===0)return!0;return!1}class T2 extends b{static[E]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(Y){if(Y){let{name:Z,...X}=Y;this.config.generatedIdentity={type:"always",sequenceName:Z,sequenceOptions:X}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(Y){if(Y){let{name:Z,...X}=Y;this.config.generatedIdentity={type:"byDefault",sequenceName:Z,sequenceOptions:X}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class f7 extends T2{static[E]="PgBigInt53Builder";constructor(Y){super(Y,"number","PgBigInt53")}build(Y){return new h7(Y,this.config)}}class h7 extends j{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class k7 extends T2{static[E]="PgBigInt64Builder";constructor(Y){super(Y,"bigint","PgBigInt64")}build(Y){return new b7(Y,this.config)}}class b7 extends j{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(Y){return BigInt(Y)}}function y7(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new f7(X);return new k7(X)}class g7 extends b{static[E]="PgBigSerial53Builder";constructor(Y){super(Y,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new p7(Y,this.config)}}class p7 extends j{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class m7 extends b{static[E]="PgBigSerial64Builder";constructor(Y){super(Y,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(Y){return new u7(Y,this.config)}}class u7 extends j{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(Y){return BigInt(Y)}}function d7(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new g7(X);return new m7(X)}class c7 extends b{static[E]="PgBooleanBuilder";constructor(Y){super(Y,"boolean","PgBoolean")}build(Y){return new l7(Y,this.config)}}class l7 extends j{static[E]="PgBoolean";getSQLType(){return"boolean"}}function N8(Y){return new c7(Y??"")}class o7 extends b{static[E]="PgCharBuilder";constructor(Y,Z){super(Y,"string","PgChar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new i7(Y,this.config)}}class i7 extends j{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function r7(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new o7(X,_)}class n7 extends b{static[E]="PgCidrBuilder";constructor(Y){super(Y,"string","PgCidr")}build(Y){return new s7(Y,this.config)}}class s7 extends j{static[E]="PgCidr";getSQLType(){return"cidr"}}function t7(Y){return new n7(Y??"")}class a7 extends b{static[E]="PgCustomColumnBuilder";constructor(Y,Z,X){super(Y,"custom","PgCustomColumn");this.config.fieldConfig=Z,this.config.customTypeParams=X}build(Y){return new e7(Y,this.config)}}class e7 extends j{static[E]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(Y,Z){super(Y,Z);this.sqlName=Z.customTypeParams.dataType(Z.fieldConfig),this.mapTo=Z.customTypeParams.toDriver,this.mapFrom=Z.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(Y){return typeof this.mapFrom==="function"?this.mapFrom(Y):Y}mapToDriverValue(Y){return typeof this.mapTo==="function"?this.mapTo(Y):Y}}function Y$(Y){return(Z,X)=>{let{name:_,config:G}=X0(Z,X);return new a7(_,G,Y)}}class U2 extends b{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(O`now()`)}}class Z$ extends U2{static[E]="PgDateBuilder";constructor(Y){super(Y,"date","PgDate")}build(Y){return new v6(Y,this.config)}}class v6 extends j{static[E]="PgDate";getSQLType(){return"date"}mapFromDriverValue(Y){return new Date(Y)}mapToDriverValue(Y){return Y.toISOString()}}class X$ extends U2{static[E]="PgDateStringBuilder";constructor(Y){super(Y,"string","PgDateString")}build(Y){return new x6(Y,this.config)}}class x6 extends j{static[E]="PgDateString";getSQLType(){return"date"}}function _$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="date")return new Z$(X);return new X$(X)}class G$ extends b{static[E]="PgDoublePrecisionBuilder";constructor(Y){super(Y,"number","PgDoublePrecision")}build(Y){return new $$(Y,this.config)}}class $$ extends j{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function W$(Y){return new G$(Y??"")}class H$ extends b{static[E]="PgInetBuilder";constructor(Y){super(Y,"string","PgInet")}build(Y){return new J$(Y,this.config)}}class J$ extends j{static[E]="PgInet";getSQLType(){return"inet"}}function Q$(Y){return new H$(Y??"")}class U$ extends T2{static[E]="PgIntegerBuilder";constructor(Y){super(Y,"number","PgInteger")}build(Y){return new z$(Y,this.config)}}class z$ extends j{static[E]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseInt(Y);return Y}}function I8(Y){return new U$(Y??"")}class F$ extends b{static[E]="PgIntervalBuilder";constructor(Y,Z){super(Y,"string","PgInterval");this.config.intervalConfig=Z}build(Y){return new E$(Y,this.config)}}class E$ extends j{static[E]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let Y=this.fields?` ${this.fields}`:"",Z=this.precision?`(${this.precision})`:"";return`interval${Y}${Z}`}}function O$(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new F$(X,_)}class V$ extends b{static[E]="PgJsonBuilder";constructor(Y){super(Y,"json","PgJson")}build(Y){return new f6(Y,this.config)}}class f6 extends j{static[E]="PgJson";constructor(Y,Z){super(Y,Z)}getSQLType(){return"json"}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}}function D$(Y){return new V$(Y??"")}class L$ extends b{static[E]="PgJsonbBuilder";constructor(Y){super(Y,"json","PgJsonb")}build(Y){return new h6(Y,this.config)}}class h6 extends j{static[E]="PgJsonb";constructor(Y,Z){super(Y,Z)}getSQLType(){return"jsonb"}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}}function M$(Y){return new L$(Y??"")}class A$ extends b{static[E]="PgLineBuilder";constructor(Y){super(Y,"array","PgLine")}build(Y){return new w$(Y,this.config)}}class w$ extends j{static[E]="PgLine";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,_]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X),Number.parseFloat(_)]}mapToDriverValue(Y){return`{${Y[0]},${Y[1]},${Y[2]}}`}}class R$ extends b{static[E]="PgLineABCBuilder";constructor(Y){super(Y,"json","PgLineABC")}build(Y){return new N$(Y,this.config)}}class N$ extends j{static[E]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,_]=Y.slice(1,-1).split(",");return{a:Number.parseFloat(Z),b:Number.parseFloat(X),c:Number.parseFloat(_)}}mapToDriverValue(Y){return`{${Y.a},${Y.b},${Y.c}}`}}function I$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new A$(X);return new R$(X)}class T$ extends b{static[E]="PgMacaddrBuilder";constructor(Y){super(Y,"string","PgMacaddr")}build(Y){return new K$(Y,this.config)}}class K$ extends j{static[E]="PgMacaddr";getSQLType(){return"macaddr"}}function B$(Y){return new T$(Y??"")}class C$ extends b{static[E]="PgMacaddr8Builder";constructor(Y){super(Y,"string","PgMacaddr8")}build(Y){return new q$(Y,this.config)}}class q$ extends j{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}}function j$(Y){return new C$(Y??"")}class S$ extends b{static[E]="PgNumericBuilder";constructor(Y,Z,X){super(Y,"string","PgNumeric");this.config.precision=Z,this.config.scale=X}build(Y){return new k6(Y,this.config)}}class k6 extends j{static[E]="PgNumeric";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.scale}mapFromDriverValue(Y){if(typeof Y==="string")return Y;return String(Y)}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 P$ extends b{static[E]="PgNumericNumberBuilder";constructor(Y,Z,X){super(Y,"number","PgNumericNumber");this.config.precision=Z,this.config.scale=X}build(Y){return new v$(Y,this.config)}}class v$ extends j{static[E]="PgNumericNumber";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.scale}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}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 x$ extends b{static[E]="PgNumericBigIntBuilder";constructor(Y,Z,X){super(Y,"bigint","PgNumericBigInt");this.config.precision=Z,this.config.scale=X}build(Y){return new f$(Y,this.config)}}class f$ extends j{static[E]="PgNumericBigInt";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.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 h$(Y,Z){let{name:X,config:_}=X0(Y,Z),G=_?.mode;return G==="number"?new P$(X,_?.precision,_?.scale):G==="bigint"?new x$(X,_?.precision,_?.scale):new S$(X,_?.precision,_?.scale)}class k$ extends b{static[E]="PgPointTupleBuilder";constructor(Y){super(Y,"array","PgPointTuple")}build(Y){return new b$(Y,this.config)}}class b$ extends j{static[E]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(Y){if(typeof Y==="string"){let[Z,X]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X)]}return[Y.x,Y.y]}mapToDriverValue(Y){return`(${Y[0]},${Y[1]})`}}class y$ extends b{static[E]="PgPointObjectBuilder";constructor(Y){super(Y,"json","PgPointObject")}build(Y){return new g$(Y,this.config)}}class g$ extends j{static[E]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(Y){if(typeof Y==="string"){let[Z,X]=Y.slice(1,-1).split(",");return{x:Number.parseFloat(Z),y:Number.parseFloat(X)}}return Y}mapToDriverValue(Y){return`(${Y.x},${Y.y})`}}function p$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new k$(X);return new y$(X)}function kF(Y){let Z=[];for(let X=0;X<Y.length;X+=2)Z.push(Number.parseInt(Y.slice(X,X+2),16));return new Uint8Array(Z)}function m$(Y,Z){let X=new ArrayBuffer(8),_=new DataView(X);for(let G=0;G<8;G++)_.setUint8(G,Y[Z+G]);return _.getFloat64(0,!0)}function M5(Y){let Z=kF(Y),X=0,_=Z[X];X+=1;let G=new DataView(Z.buffer),$=G.getUint32(X,_===1);X+=4;let W;if($&536870912)W=G.getUint32(X,_===1),X+=4;if(($&65535)===1){let H=m$(Z,X);X+=8;let Q=m$(Z,X);return X+=8,[H,Q]}throw new Error("Unsupported geometry type")}class u$ extends b{static[E]="PgGeometryBuilder";constructor(Y){super(Y,"array","PgGeometry")}build(Y){return new d$(Y,this.config)}}class d$ extends j{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){return M5(Y)}mapToDriverValue(Y){return`point(${Y[0]} ${Y[1]})`}}class c$ extends b{static[E]="PgGeometryObjectBuilder";constructor(Y){super(Y,"json","PgGeometryObject")}build(Y){return new l$(Y,this.config)}}class l$ extends j{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){let Z=M5(Y);return{x:Z[0],y:Z[1]}}mapToDriverValue(Y){return`point(${Y.x} ${Y.y})`}}function o$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new u$(X);return new c$(X)}class i$ extends b{static[E]="PgRealBuilder";constructor(Y,Z){super(Y,"number","PgReal");this.config.length=Z}build(Y){return new r$(Y,this.config)}}class r$ extends j{static[E]="PgReal";constructor(Y,Z){super(Y,Z)}getSQLType(){return"real"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function n$(Y){return new i$(Y??"")}class s$ extends b{static[E]="PgSerialBuilder";constructor(Y){super(Y,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new t$(Y,this.config)}}class t$ extends j{static[E]="PgSerial";getSQLType(){return"serial"}}function a$(Y){return new s$(Y??"")}class e$ extends T2{static[E]="PgSmallIntBuilder";constructor(Y){super(Y,"number","PgSmallInt")}build(Y){return new YW(Y,this.config)}}class YW extends j{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number(Y);return Y}}function ZW(Y){return new e$(Y??"")}class XW extends b{static[E]="PgSmallSerialBuilder";constructor(Y){super(Y,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new _W(Y,this.config)}}class _W extends j{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}}function GW(Y){return new XW(Y??"")}class $W extends b{static[E]="PgTextBuilder";constructor(Y,Z){super(Y,"string","PgText");this.config.enumValues=Z.enum}build(Y){return new WW(Y,this.config)}}class WW extends j{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function HW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new $W(X,_)}class JW extends U2{constructor(Y,Z,X){super(Y,"string","PgTime");this.withTimezone=Z,this.precision=X,this.config.withTimezone=Z,this.config.precision=X}static[E]="PgTimeBuilder";build(Y){return new b6(Y,this.config)}}class b6 extends j{static[E]="PgTime";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function QW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new JW(X,_.withTimezone??!1,_.precision)}class UW extends U2{static[E]="PgTimestampBuilder";constructor(Y,Z,X){super(Y,"date","PgTimestamp");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new y6(Y,this.config)}}class y6 extends j{static[E]="PgTimestamp";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(Y)=>{return new Date(this.withTimezone?Y:Y+"+0000")};mapToDriverValue=(Y)=>{return Y.toISOString()}}class zW extends U2{static[E]="PgTimestampStringBuilder";constructor(Y,Z,X){super(Y,"string","PgTimestampString");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new g6(Y,this.config)}}class g6 extends j{static[E]="PgTimestampString";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function FW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="string")return new zW(X,_.withTimezone??!1,_.precision);return new UW(X,_?.withTimezone??!1,_?.precision)}class EW extends b{static[E]="PgUUIDBuilder";constructor(Y){super(Y,"string","PgUUID")}defaultRandom(){return this.default(O`gen_random_uuid()`)}build(Y){return new p6(Y,this.config)}}class p6 extends j{static[E]="PgUUID";getSQLType(){return"uuid"}}function q1(Y){return new EW(Y??"")}class OW extends b{static[E]="PgVarcharBuilder";constructor(Y,Z){super(Y,"string","PgVarchar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new VW(Y,this.config)}}class VW extends j{static[E]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function e0(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new OW(X,_)}class DW extends b{static[E]="PgBinaryVectorBuilder";constructor(Y,Z){super(Y,"string","PgBinaryVector");this.config.dimensions=Z.dimensions}build(Y){return new LW(Y,this.config)}}class LW extends j{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function MW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new DW(X,_)}class AW extends b{static[E]="PgHalfVectorBuilder";constructor(Y,Z){super(Y,"array","PgHalfVector");this.config.dimensions=Z.dimensions}build(Y){return new wW(Y,this.config)}}class wW extends j{static[E]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){return Y.slice(1,-1).split(",").map((Z)=>Number.parseFloat(Z))}}function RW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new AW(X,_)}class NW extends b{static[E]="PgSparseVectorBuilder";constructor(Y,Z){super(Y,"string","PgSparseVector");this.config.dimensions=Z.dimensions}build(Y){return new IW(Y,this.config)}}class IW extends j{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function TW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new NW(X,_)}class KW extends b{static[E]="PgVectorBuilder";constructor(Y,Z){super(Y,"array","PgVector");this.config.dimensions=Z.dimensions}build(Y){return new BW(Y,this.config)}}class BW extends j{static[E]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){return Y.slice(1,-1).split(",").map((Z)=>Number.parseFloat(Z))}}function CW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new KW(X,_)}function qW(){return{bigint:y7,bigserial:d7,boolean:N8,char:r7,cidr:t7,customType:Y$,date:_$,doublePrecision:W$,inet:Q$,integer:I8,interval:O$,json:D$,jsonb:M$,line:I$,macaddr:B$,macaddr8:j$,numeric:h$,point:p$,geometry:o$,real:n$,serial:a$,smallint:ZW,smallserial:GW,text:HW,time:QW,timestamp:FW,uuid:q1,varchar:e0,bit:MW,halfvec:RW,sparsevec:TW,vector:CW}}var A5=Symbol.for("drizzle:PgInlineForeignKeys"),jW=Symbol.for("drizzle:EnableRLS");class u0 extends S{static[E]="PgTable";static Symbol=Object.assign({},S.Symbol,{InlineForeignKeys:A5,EnableRLS:jW});[A5]=[];[jW]=!1;[S.Symbol.ExtraConfigBuilder]=void 0;[S.Symbol.ExtraConfigColumns]={}}function bF(Y,Z,X,_,G=Y){let $=new u0(Y,_,G),W=typeof Z==="function"?Z(qW()):Z,H=Object.fromEntries(Object.entries(W).map(([U,F])=>{let V=F;V.setName(U);let D=V.build($);return $[A5].push(...V.buildForeignKeys(D,$)),[U,D]})),Q=Object.fromEntries(Object.entries(W).map(([U,F])=>{let V=F;V.setName(U);let D=V.buildExtraConfigColumn($);return[U,D]})),J=Object.assign($,H);if(J[S.Symbol.Columns]=H,J[S.Symbol.ExtraConfigColumns]=Q,X)J[u0.Symbol.ExtraConfigBuilder]=X;return Object.assign(J,{enableRLS:()=>{return J[u0.Symbol.EnableRLS]=!0,J}})}var K2=(Y,Z,X)=>{return bF(Y,Z,X,void 0)};function SW(...Y){if(Y[0].columns)return new T8(Y[0].columns,Y[0].name);return new T8(Y)}class T8{static[E]="PgPrimaryKeyBuilder";columns;name;constructor(Y,Z){this.columns=Y,this.name=Z}build(Y){return new PW(Y,this.columns,this.name)}}class PW{constructor(Y,Z,X){this.table=Y,this.columns=Z,this.name=X}static[E]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[u0.Symbol.Name]}_${this.columns.map((Y)=>Y.name).join("_")}_pk`}}function V1(Y,Z){if(B7(Z)&&!F5(Y)&&!M(Y,R1)&&!M(Y,I2)&&!M(Y,E0)&&!M(Y,S)&&!M(Y,O1))return new R1(Y,Z);return Y}var m6=(Y,Z)=>{return O`${Y} = ${V1(Z,Y)}`},vW=(Y,Z)=>{return O`${Y} <> ${V1(Z,Y)}`};function K8(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new h(Z);return new h([new m0("("),O.join(Z,new m0(" and ")),new m0(")")])}function xW(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new h(Z);return new h([new m0("("),O.join(Z,new m0(" or ")),new m0(")")])}function fW(Y){return O`not ${Y}`}var hW=(Y,Z)=>{return O`${Y} > ${V1(Z,Y)}`},kW=(Y,Z)=>{return O`${Y} >= ${V1(Z,Y)}`},bW=(Y,Z)=>{return O`${Y} < ${V1(Z,Y)}`},yW=(Y,Z)=>{return O`${Y} <= ${V1(Z,Y)}`};function gW(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return O`false`;return O`${Y} in ${Z.map((X)=>V1(X,Y))}`}return O`${Y} in ${V1(Z,Y)}`}function pW(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return O`true`;return O`${Y} not in ${Z.map((X)=>V1(X,Y))}`}return O`${Y} not in ${V1(Z,Y)}`}function mW(Y){return O`${Y} is null`}function uW(Y){return O`${Y} is not null`}function dW(Y){return O`exists ${Y}`}function cW(Y){return O`not exists ${Y}`}function lW(Y,Z,X){return O`${Y} between ${V1(Z,Y)} and ${V1(X,Y)}`}function oW(Y,Z,X){return O`${Y} not between ${V1(Z,Y)} and ${V1(X,Y)}`}function iW(Y,Z){return O`${Y} like ${Z}`}function rW(Y,Z){return O`${Y} not like ${Z}`}function nW(Y,Z){return O`${Y} ilike ${Z}`}function sW(Y,Z){return O`${Y} not ilike ${Z}`}function tW(Y){return O`${Y} asc`}function aW(Y){return O`${Y} desc`}class w5{constructor(Y,Z,X){this.sourceTable=Y,this.referencedTable=Z,this.relationName=X,this.referencedTableName=Z[S.Symbol.Name]}static[E]="Relation";referencedTableName;fieldName}class eW{constructor(Y,Z){this.table=Y,this.config=Z}static[E]="Relations"}class B2 extends w5{constructor(Y,Z,X,_){super(Y,Z,X?.relationName);this.config=X,this.isNullable=_}static[E]="One";withFieldName(Y){let Z=new B2(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Z.fieldName=Y,Z}}class B8 extends w5{constructor(Y,Z,X){super(Y,Z,X?.relationName);this.config=X}static[E]="Many";withFieldName(Y){let Z=new B8(this.sourceTable,this.referencedTable,this.config);return Z.fieldName=Y,Z}}function Y3(){return{and:K8,between:lW,eq:m6,exists:dW,gt:hW,gte:kW,ilike:nW,inArray:gW,isNull:mW,isNotNull:uW,like:iW,lt:bW,lte:yW,ne:vW,not:fW,notBetween:oW,notExists:cW,notLike:rW,notIlike:sW,notInArray:pW,or:xW,sql:O}}function Z3(){return{sql:O,asc:tW,desc:aW}}function X3(Y,Z){if(Object.keys(Y).length===1&&"default"in Y&&!M(Y.default,S))Y=Y.default;let X={},_={},G={};for(let[$,W]of Object.entries(Y))if(M(W,S)){let H=p2(W),Q=_[H];X[H]=$,G[$]={tsName:$,dbName:W[S.Symbol.Name],schema:W[S.Symbol.Schema],columns:W[S.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let U of Object.values(W[S.Symbol.Columns]))if(U.primary)G[$].primaryKey.push(U);let J=W[S.Symbol.ExtraConfigBuilder]?.(W[S.Symbol.ExtraConfigColumns]);if(J){for(let U of Object.values(J))if(M(U,T8))G[$].primaryKey.push(...U.columns)}}else if(M(W,eW)){let H=p2(W.table),Q=X[H],J=W.config(Z(W.table)),U;for(let[F,V]of Object.entries(J))if(Q){let D=G[Q];if(D.relations[F]=V,U)D.primaryKey.push(...U)}else{if(!(H in _))_[H]={relations:{},primaryKey:U};_[H].relations[F]=V}}return{tables:G,tableNamesMap:X}}function yF(Y){return function Z(X,_){return new B2(Y,X,_,_?.fields.reduce((G,$)=>G&&$.notNull,!0)??!1)}}function gF(Y){return function Z(X,_){return new B8(Y,X,_)}}function _3(Y,Z,X){if(M(X,B2)&&X.config)return{fields:X.config.fields,references:X.config.references};let _=Z[p2(X.referencedTable)];if(!_)throw new Error(`Table "${X.referencedTable[S.Symbol.Name]}" not found in schema`);let G=Y[_];if(!G)throw new Error(`Table "${_}" not found in schema`);let $=X.sourceTable,W=Z[p2($)];if(!W)throw new Error(`Table "${$[S.Symbol.Name]}" not found in schema`);let H=[];for(let Q of Object.values(G.relations))if(X.relationName&&X!==Q&&Q.relationName===X.relationName||!X.relationName&&Q.referencedTable===X.sourceTable)H.push(Q);if(H.length>1)throw X.relationName?new Error(`There are multiple relations with name "${X.relationName}" in table "${_}"`):new Error(`There are multiple relations between "${_}" and "${X.sourceTable[S.Symbol.Name]}". Please specify relation name`);if(H[0]&&M(H[0],B2)&&H[0].config)return{fields:H[0].config.references,references:H[0].config.fields};throw new Error(`There is not enough information to infer relation "${W}.${X.fieldName}"`)}function G3(Y){return{one:yF(Y),many:gF(Y)}}function u6(Y,Z,X,_,G=($)=>$){let $={};for(let[W,H]of _.entries())if(H.isJson){let Q=Z.relations[H.tsKey],J=X[W],U=typeof J==="string"?JSON.parse(J):J;$[H.tsKey]=M(Q,B2)?U&&u6(Y,Y[H.relationTableTsKey],U,H.selection,G):U.map((F)=>u6(Y,Y[H.relationTableTsKey],F,H.selection,G))}else{let Q=G(X[W]),J=H.field,U;if(M(J,E0))U=J;else if(M(J,h))U=J.decoder;else U=J.sql.decoder;$[H.tsKey]=Q===null?null:U.mapFromDriverValue(Q)}return $}import QE from"os";import UE from"fs";var d6=new Map,R5=new Map,N5=Symbol("OriginError"),w4={};class j1 extends Promise{constructor(Y,Z,X,_,G={}){let $,W;super((H,Q)=>{$=H,W=Q});this.tagged=Array.isArray(Y.raw),this.strings=Y,this.args=Z,this.handler=X,this.canceller=_,this.options=G,this.state=null,this.statement=null,this.resolve=(H)=>(this.active=!1,$(H)),this.reject=(H)=>(this.active=!1,W(H)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[N5]=this.handler.debug?new Error:this.tagged&&pF(this.strings)}get origin(){return(this.handler.debug?this[N5].stack:this.tagged&&R5.has(this.strings)?R5.get(this.strings):R5.set(this.strings,this[N5].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(Y=1,Z){if(this.options.simple=!1,typeof Y==="function")Z=Y,Y=1;if(this.cursorRows=Y,typeof Z==="function")return this.cursorFn=Z,this;let X;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};X&&X();let _=new Promise((G,$)=>{this.cursorFn=(W)=>{return G({value:W,done:!1}),new Promise((H)=>X=H)},this.resolve=()=>(this.active=!1,G({done:!0})),this.reject=(W)=>(this.active=!1,$(W))});return this.execute(),_},return(){return X&&X(w4),{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(Y){return this.forEachFn=Y,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 pF(Y){if(d6.has(Y))return d6.get(Y);let Z=Error.stackTraceLimit;return Error.stackTraceLimit=4,d6.set(Y,new Error),Error.stackTraceLimit=Z,d6.get(Y)}class R4 extends Error{constructor(Y){super(Y.message);this.name=this.constructor.name,Object.assign(this,Y)}}var f0={connection:$3,postgres:W3,generic:H3,notSupported:J3};function $3(Y,Z,X){let{host:_,port:G}=X||Z,$=Object.assign(new Error("write "+Y+" "+(Z.path||_+":"+G)),{code:Y,errno:Y,address:Z.path||_},Z.path?{}:{port:G});return Error.captureStackTrace($,$3),$}function W3(Y){let Z=new R4(Y);return Error.captureStackTrace(Z,W3),Z}function H3(Y,Z){let X=Object.assign(new Error(Y+": "+Z),{code:Y});return Error.captureStackTrace(X,H3),X}function J3(Y){let Z=Object.assign(new Error(Y+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:Y});return Error.captureStackTrace(Z,J3),Z}var mF={string:{to:25,from:null,serialize:(Y)=>""+Y},number:{to:0,from:[21,23,26,700,701],serialize:(Y)=>""+Y,parse:(Y)=>+Y},json:{to:114,from:[114,3802],serialize:(Y)=>JSON.stringify(Y),parse:(Y)=>JSON.parse(Y)},boolean:{to:16,from:16,serialize:(Y)=>Y===!0?"t":"f",parse:(Y)=>Y==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(Y)=>(Y instanceof Date?Y:new Date(Y)).toISOString(),parse:(Y)=>new Date(Y)},bytea:{to:17,from:17,serialize:(Y)=>"\\x"+Buffer.from(Y).toString("hex"),parse:(Y)=>Buffer.from(Y.slice(2),"hex")}};class o6{then(){I5()}catch(){I5()}finally(){I5()}}class S8 extends o6{constructor(Y){super();this.value=n6(Y)}}class i1 extends o6{constructor(Y,Z,X){super();this.value=Y,this.type=Z,this.array=X}}class i6 extends o6{constructor(Y,Z){super();this.first=Y,this.rest=Z}build(Y,Z,X,_){let G=uF.map(([$,W])=>({fn:W,i:Y.search($)})).sort(($,W)=>$.i-W.i).pop();return G.i===-1?q5(this.first,_):G.fn(this.first,this.rest,Z,X,_)}}function r6(Y,Z,X,_){let G=Y instanceof i1?Y.value:Y;if(G===void 0){if(Y instanceof i1?Y.value=_.transform.undefined:G=Y=_.transform.undefined,G===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(Y instanceof i1?(Z.push(Y.value),Y.array?Y.array[Y.type||l6(Y.value)]||Y.type||F3(Y.value):Y.type):(Z.push(Y),l6(Y)))}var U3=O3(mF);function B5(Y,Z,X,_,G,$){for(let W=1;W<Y.strings.length;W++)Z+=C5(Z,X,_,G,$)+Y.strings[W],X=Y.args[W];return Z}function C5(Y,Z,X,_,G){return Z instanceof i6?Z.build(Y,X,_,G):Z instanceof j1?K5(Z,X,_,G):Z instanceof S8?Z.value:Z&&Z[0]instanceof j1?Z.reduce(($,W)=>$+" "+K5(W,X,_,G),""):r6(Z,X,_,G)}function K5(Y,Z,X,_){return Y.fragment=!0,B5(Y,Y.strings[0],Y.args[0],Z,X,_)}function z3(Y,Z,X,_,G){return Y.map(($)=>"("+_.map((W)=>C5("values",$[W],Z,X,G)).join(",")+")").join(",")}function Q3(Y,Z,X,_,G){let $=Array.isArray(Y[0]),W=Z.length?Z.flat():Object.keys($?Y[0]:Y);return z3($?Y:[Y],X,_,W,G)}function c6(Y,Z,X,_,G){if(typeof Y==="string"&&(Y=[Y].concat(Z)),Array.isArray(Y))return q5(Y,G);let $;return(Z.length?Z.flat():Object.keys(Y)).map((H)=>{return $=Y[H],($ instanceof j1?K5($,X,_,G):$ instanceof S8?$.value:r6($,X,_,G))+" as "+n6(G.transform.column.to?G.transform.column.to(H):H)}).join(",")}var uF=Object.entries({values:Q3,in:(...Y)=>{let Z=Q3(...Y);return Z==="()"?"(null)":Z},select:c6,as:c6,returning:c6,"\\(":c6,update(Y,Z,X,_,G){return(Z.length?Z.flat():Object.keys(Y)).map(($)=>n6(G.transform.column.to?G.transform.column.to($):$)+"="+C5("values",Y[$],X,_,G))},insert(Y,Z,X,_,G){let $=Z.length?Z.flat():Object.keys(Array.isArray(Y)?Y[0]:Y);return"("+q5($,G)+")values"+z3(Array.isArray(Y)?Y:[Y],X,_,$,G)}}).map(([Y,Z])=>[new RegExp("((?:^|[\\s(])"+Y+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Z]);function I5(){throw f0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:dF,parsers:cF}=U3;function F3(Y){if(Array.isArray(Y))return F3(Y[0]);return typeof Y==="string"?1009:0}var E3=function(Y){let Z=O3(Y||{});return{serializers:Object.assign({},dF,Z.serializers),parsers:Object.assign({},cF,Z.parsers)}};function O3(Y){return Object.keys(Y).reduce((Z,X)=>{if(Y[X].from&&[].concat(Y[X].from).forEach((_)=>Z.parsers[_]=Y[X].parse),Y[X].serialize)Z.serializers[Y[X].to]=Y[X].serialize,Y[X].from&&[].concat(Y[X].from).forEach((_)=>Z.serializers[_]=Y[X].serialize);return Z},{parsers:{},serializers:{}})}function q5(Y,{transform:{column:Z}}){return Y.map((X)=>n6(Z.to?Z.to(X):X)).join(",")}var n6=function Y(Z){return'"'+Z.replace(/"/g,'""').replace(/\./g,'"."')+'"'},l6=function Y(Z){return Z instanceof i1?Z.type:Z instanceof Date?1184:Z instanceof Uint8Array?17:Z===!0||Z===!1?16:typeof Z==="bigint"?20:Array.isArray(Z)?Y(Z[0]):0},lF=/\\/g,oF=/"/g;function iF(Y){return Y.replace(lF,"\\\\").replace(oF,"\\\"")}var V3=function Y(Z,X,_,G){if(Array.isArray(Z)===!1)return Z;if(!Z.length)return"{}";let $=Z[0],W=G===1020?";":",";if(Array.isArray($)&&!$.type)return"{"+Z.map((H)=>Y(H,X,_,G)).join(W)+"}";return"{"+Z.map((H)=>{if(H===void 0){if(H=_.transform.undefined,H===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return H===null?"null":'"'+iF(X?X(H.type?H.value:H):""+H)+'"'}).join(W)+"}"},T5={i:0,char:null,str:"",quoted:!1,last:0},D3=function Y(Z,X,_){return T5.i=T5.last=0,L3(T5,Z,X,_)};function L3(Y,Z,X,_){let G=[],$=_===1020?";":",";for(;Y.i<Z.length;Y.i++){if(Y.char=Z[Y.i],Y.quoted)if(Y.char==="\\")Y.str+=Z[++Y.i];else if(Y.char==='"')G.push(X?X(Y.str):Y.str),Y.str="",Y.quoted=Z[Y.i+1]==='"',Y.last=Y.i+2;else Y.str+=Y.char;else if(Y.char==='"')Y.quoted=!0;else if(Y.char==="{")Y.last=++Y.i,G.push(L3(Y,Z,X,_));else if(Y.char==="}"){Y.quoted=!1,Y.last<Y.i&&G.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;break}else if(Y.char===$&&Y.p!=="}"&&Y.p!=='"')G.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;Y.p=Y.char}return Y.last<Y.i&&G.push(X?X(Z.slice(Y.last,Y.i+1)):Z.slice(Y.last,Y.i+1)),G}var m2=(Y)=>{let Z=Y[0];for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},u2=(Y)=>{let Z=Y[0].toUpperCase();for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},d2=(Y)=>Y.replace(/_/g,"-"),C8=(Y)=>Y.replace(/([A-Z])/g,"_$1").toLowerCase(),q8=(Y)=>(Y.slice(0,1)+Y.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),j8=(Y)=>Y.replace(/-/g,"_");function j5(Y){return function Z(X,_){return typeof X==="object"&&X!==null&&(_.type===114||_.type===3802)?Array.isArray(X)?X.map((G)=>Z(G,_)):Object.entries(X).reduce((G,[$,W])=>Object.assign(G,{[Y($)]:Z(W,_)}),{}):X}}m2.column={from:m2};m2.value={from:j5(m2)};C8.column={to:C8};var S5={...m2};S5.column.to=C8;u2.column={from:u2};u2.value={from:j5(u2)};q8.column={to:q8};var P5={...u2};P5.column.to=q8;d2.column={from:d2};d2.value={from:j5(d2)};j8.column={to:j8};var v5={...d2};v5.column.to=j8;import M3 from"net";import tF from"tls";import P8 from"crypto";import x5 from"stream";import{performance as A3}from"perf_hooks";class c2 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 N1=rF;function rF(Y=[]){let Z=Y.slice(),X=0;return{get length(){return Z.length-X},remove:(_)=>{let G=Z.indexOf(_);return G===-1?null:(Z.splice(G,1),_)},push:(_)=>(Z.push(_),_),shift:()=>{let _=Z[X++];if(X===Z.length)X=0,Z=[];else Z[X-1]=void 0;return _}}}var Y1=Buffer.allocUnsafe(256),nF="BCcDdEFfHPpQSX".split("").reduce((Y,Z)=>{let X=Z.charCodeAt(0);return Y[Z]=()=>{return Y1[0]=X,U0.i=5,U0},Y},{}),U0=Object.assign(sF,nF,{N:String.fromCharCode(0),i:0,inc(Y){return U0.i+=Y,U0},str(Y){let Z=Buffer.byteLength(Y);return s6(Z),U0.i+=Y1.write(Y,U0.i,Z,"utf8"),U0},i16(Y){return s6(2),Y1.writeUInt16BE(Y,U0.i),U0.i+=2,U0},i32(Y,Z){if(Z||Z===0)return Y1.writeUInt32BE(Y,Z),U0;return s6(4),Y1.writeUInt32BE(Y,U0.i),U0.i+=4,U0},z(Y){return s6(Y),Y1.fill(0,U0.i,U0.i+Y),U0.i+=Y,U0},raw(Y){return Y1=Buffer.concat([Y1.subarray(0,U0.i),Y]),U0.i=Y1.length,U0},end(Y=1){Y1.writeUInt32BE(U0.i-Y,Y);let Z=Y1.subarray(0,U0.i);return U0.i=0,Y1=Buffer.allocUnsafe(256),Z}}),c=U0;function s6(Y){if(Y1.length-U0.i<Y){let Z=Y1,X=Z.length;Y1=Buffer.allocUnsafe(X+(X>>1)+Y),Z.copy(Y1)}}function sF(){return U0.i=0,U0}var k5=N3,aF=1,C2=c().S().end(),w3=c().H().end(),eF=c().i32(8).i32(80877103).end(8),YE=Buffer.concat([c().E().str(c.N).i32(0).end(),C2]),ZE=c().D().str("S").str(c.N).end(),N4=()=>{},XE=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),_E={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 N3(Y,Z={},{onopen:X=N4,onend:_=N4,onclose:G=N4}={}){let{ssl:$,max:W,user:H,host:Q,port:J,database:U,parsers:F,transform:V,onnotice:D,onnotify:A,onparameter:w,max_pipeline:f,keep_alive:v,backoff:k,target_session_attrs:m}=Y,T=N1(),I=aF++,q={pid:null,secret:null},C=h5(UY,Y.idle_timeout),g=h5(UY,Y.max_lifetime),n=h5(l3,Y.connect_timeout),K=null,a,p=new c2,e=Buffer.alloc(0),z0=Y.fetch_types,h0={},H1={},r1=Math.random().toString(36).slice(2),B=1,u=0,G0=0,I0=0,k0=0,s=0,J0=0,v0=0,K0=null,A0=null,i0=!1,V0=null,S1=null,c0=null,z2=null,b0=null,w0=null,P1=null,m1=null,x=null,B4=null,r0={queue:Z.closed,idleTimer:C,connect(z){c0=z,QX()},terminate:q4,execute:C4,cancel:m3,end:UY,count:0,id:I};return Z.closed&&Z.closed.push(r0),r0;async function p3(){let z;try{z=Y.socket?await Promise.resolve(Y.socket(Y)):new M3.Socket}catch(L){r2(L);return}return z.on("error",r2),z.on("close",UX),z.on("drain",HX),z}async function m3({pid:z,secret:L},l,$0){try{a=c().i32(16).i32(80877102).i32(z).i32(L).end(16),await JX(),K.once("error",$0),K.once("close",l)}catch(C0){$0(C0)}}function C4(z){if(i0)return g8(z,f0.connection("CONNECTION_DESTROYED",Y));if(z.cancelled)return;try{return z.state=q,x?T.push(z):(x=z,x.active=!0),c3(z),l0(u3(z))&&!z.describeFirst&&!z.cursorFn&&T.length<f&&(!z.options.onexecute||z.options.onexecute(r0))}catch(L){return T.length===0&&l0(C2),u1(L),!0}}function u3(z){if(z.parameters.length>=65534)throw f0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return z.options.simple?c().Q().str(z.statement.string+c.N).end():z.describeFirst?Buffer.concat([GX(z),w3]):z.prepare?z.prepared?y8(z):Buffer.concat([GX(z),y8(z)]):d3(z)}function GX(z){return Buffer.concat([FX(z.statement.string,z.parameters,z.statement.types,z.statement.name),jH("S",z.statement.name)])}function y8(z){return Buffer.concat([qH(z.parameters,z.statement.types,z.statement.name,z.cursorName),z.cursorFn?EX("",z.cursorRows):YE])}function d3(z){return Buffer.concat([FX(z.statement.string,z.parameters,z.statement.types),ZE,y8(z)])}function c3(z){let L=[],l=[],$0=B5(z,z.strings[0],z.args[0],L,l,Y);!z.tagged&&z.args.forEach((C0)=>r6(C0,L,l,Y)),z.prepare=Y.prepare&&("prepare"in z.options?z.options.prepare:!0),z.string=$0,z.signature=z.prepare&&l+$0,z.onlyDescribe&&delete H1[z.signature],z.parameters=z.parameters||L,z.prepared=z.prepare&&z.signature in H1,z.describeFirst=z.onlyDescribe||L.length&&!z.prepared,z.statement=z.prepared?H1[z.signature]:{string:$0,types:l,name:z.prepare?r1+B++:""},typeof Y.debug==="function"&&Y.debug(I,$0,L,l)}function l0(z,L){if(w0=w0?Buffer.concat([w0,z]):Buffer.from(z),L||w0.length>=1024)return $X(L);return A0===null&&(A0=setImmediate($X)),!0}function $X(z){let L=K.write(w0,z);return A0!==null&&clearImmediate(A0),w0=A0=null,L}function l3(){u1(f0.connection("CONNECT_TIMEOUT",Y,K)),K.destroy()}async function WX(){if(l0(eF),!await new Promise((L)=>K.once("data",(l)=>L(l[0]===83)))&&$==="prefer")return i2();K.removeAllListeners(),K=tF.connect({socket:K,servername:M3.isIP(K.host)?void 0:K.host,...$==="require"||$==="allow"||$==="prefer"?{rejectUnauthorized:!1}:$==="verify-full"?{}:typeof $==="object"?$:{}}),K.on("secureConnect",i2),K.on("error",r2),K.on("close",UX),K.on("drain",HX)}function HX(){!x&&X(r0)}function QY(z){if(V0){if(V0.push(z),G0-=z.length,G0>0)return}e=V0?Buffer.concat(V0,s-G0):e.length===0?z:Buffer.concat([e,z],e.length+z.length);while(e.length>4){if(s=e.readUInt32BE(1),s>=e.length){G0=s-e.length,V0=[e];break}try{o3(e.subarray(0,s+1))}catch(L){x&&(x.cursorFn||x.describeFirst)&&l0(C2),u1(L)}e=e.subarray(s+1),G0=0,V0=null}}async function JX(){if(i0=!1,h0={},K||(K=await p3()),!K)return;if(n.start(),Y.socket)return $?WX():i2();if(K.on("connect",$?WX:i2),Y.path)return K.connect(Y.path);K.ssl=$,K.connect(J[I0],Q[I0]),K.host=Q[I0],K.port=J[I0],I0=(I0+1)%J.length}function QX(){setTimeout(JX,u?u+J0-A3.now():0)}function i2(){try{H1={},z0=Y.fetch_types,r1=Math.random().toString(36).slice(2),B=1,g.start(),K.on("data",QY),v&&K.setKeepAlive&&K.setKeepAlive(!0,1000*v);let z=PH();l0(z)}catch(z){r2(z)}}function r2(z){if(r0.queue===Z.connecting&&Y.host[k0+1])return;u1(z);while(T.length)g8(T.shift(),z)}function u1(z){b0&&(b0.destroy(z),b0=null),x&&g8(x,z),c0&&(g8(c0,z),c0=null)}function g8(z,L){if(z.reserve)return z.reject(L);if(!L||typeof L!=="object")L=new Error(L);"query"in L||"parameters"in L||Object.defineProperties(L,{stack:{value:L.stack+z.origin.replace(/.*\n/,`
61
- `),enumerable:Y.debug},query:{value:z.string,enumerable:Y.debug},parameters:{value:z.parameters,enumerable:Y.debug},args:{value:z.args,enumerable:Y.debug},types:{value:z.statement&&z.statement.types,enumerable:Y.debug}}),z.reject(L)}function UY(){return z2||(!r0.reserved&&_(r0),!r0.reserved&&!c0&&!x&&T.length===0?(q4(),new Promise((z)=>K&&K.readyState!=="closed"?K.once("close",z):z())):z2=new Promise((z)=>P1=z))}function q4(){if(i0=!0,b0||x||c0||T.length)r2(f0.connection("CONNECTION_DESTROYED",Y));if(clearImmediate(A0),K)K.removeListener("data",QY),K.removeListener("connect",i2),K.readyState==="open"&&K.end(c().X().end());P1&&(P1(),z2=P1=null)}async function UX(z){if(e=Buffer.alloc(0),G0=0,V0=null,clearImmediate(A0),K.removeListener("data",QY),K.removeListener("connect",i2),C.cancel(),g.cancel(),n.cancel(),K.removeAllListeners(),K=null,c0)return QX();!z&&(x||T.length)&&r2(f0.connection("CONNECTION_CLOSED",Y,K)),u=A3.now(),z&&Y.shared.retries++,J0=(typeof k==="function"?k(Y.shared.retries):k)*1000,G(r0,f0.connection("CONNECTION_CLOSED",Y,K))}function o3(z,L=z[0]){(L===68?i3:L===100?wH:L===65?OH:L===83?r3:L===90?n3:L===67?s3:L===50?zX:L===49?t3:L===116?a3:L===84?e3:L===82?YH:L===110?WH:L===75?HH:L===69?FH:L===115?VH:L===51?DH:L===71?LH:L===78?NH:L===72?MH:L===99?RH:L===73?IH:L===86?TH:L===118?KH:L===87?AH:BH)(z)}function i3(z){let L=7,l,$0,C0,n0=x.isRaw?new Array(x.statement.columns.length):{};for(let Z1=0;Z1<x.statement.columns.length;Z1++)$0=x.statement.columns[Z1],l=z.readInt32BE(L),L+=4,C0=l===-1?null:x.isRaw===!0?z.subarray(L,L+=l):$0.parser===void 0?z.toString("utf8",L,L+=l):$0.parser.array===!0?$0.parser(z.toString("utf8",L+1,L+=l)):$0.parser(z.toString("utf8",L,L+=l)),x.isRaw?n0[Z1]=x.isRaw===!0?C0:V.value.from?V.value.from(C0,$0):C0:n0[$0.name]=V.value.from?V.value.from(C0,$0):C0;x.forEachFn?x.forEachFn(V.row.from?V.row.from(n0):n0,p):p[v0++]=V.row.from?V.row.from(n0):n0}function r3(z){let[L,l]=z.toString("utf8",5,z.length-1).split(c.N);if(h0[L]=l,Y.parameters[L]!==l)Y.parameters[L]=l,w&&w(L,l)}function n3(z){if(x&&x.options.simple&&x.resolve(S1||p),x=S1=null,p=new c2,n.cancel(),c0){if(m){if(!h0.in_hot_standby||!h0.default_transaction_read_only)return zH();else if(UH(m,h0))return q4()}if(z0)return c0.reserve&&(c0=null),JH();c0&&!c0.reserve&&C4(c0),Y.shared.retries=k0=0,c0=null;return}while(T.length&&(x=T.shift())&&(x.active=!0,x.cancelled))N3(Y).cancel(x.state,x.cancelled.resolve,x.cancelled.reject);if(x)return;r0.reserved?!r0.reserved.release&&z[5]===73?z2?q4():(r0.reserved=null,X(r0)):r0.reserved():z2?q4():X(r0)}function s3(z){v0=0;for(let L=z.length-1;L>0;L--){if(z[L]===32&&z[L+1]<58&&p.count===null)p.count=+z.toString("utf8",L+1,z.length-1);if(z[L-1]>=65){p.command=z.toString("utf8",5,L),p.state=q;break}}if(B4&&(B4(),B4=null),p.command==="BEGIN"&&W!==1&&!r0.reserved)return u1(f0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(x.options.simple)return zX();if(x.cursorFn)p.count&&x.cursorFn(p),l0(C2);x.resolve(p)}function t3(){x.parsing=!1}function zX(){!p.statement&&(p.statement=x.statement),p.columns=x.statement.columns}function a3(z){let L=z.readUInt16BE(5);for(let l=0;l<L;++l)!x.statement.types[l]&&(x.statement.types[l]=z.readUInt32BE(7+l*4));x.prepare&&(H1[x.signature]=x.statement),x.describeFirst&&!x.onlyDescribe&&(l0(y8(x)),x.describeFirst=!1)}function e3(z){if(p.command)S1=S1||[p],S1.push(p=new c2),p.count=null,x.statement.columns=null;let L=z.readUInt16BE(5),l=7,$0;x.statement.columns=Array(L);for(let C0=0;C0<L;++C0){$0=l;while(z[l++]!==0);let n0=z.readUInt32BE(l),Z1=z.readUInt16BE(l+4),F2=z.readUInt32BE(l+6);x.statement.columns[C0]={name:V.column.from?V.column.from(z.toString("utf8",$0,l-1)):z.toString("utf8",$0,l-1),parser:F[F2],table:n0,number:Z1,type:F2},l+=18}if(p.statement=x.statement,x.onlyDescribe)return x.resolve(x.statement),l0(C2)}async function YH(z,L=z.readUInt32BE(5)){(L===3?ZH:L===5?XH:L===10?_H:L===11?GH:L===12?$H:L!==0?CH:N4)(z,L)}async function ZH(){let z=await zY();l0(c().p().str(z).z(1).end())}async function XH(z){let L="md5"+await R3(Buffer.concat([Buffer.from(await R3(await zY()+H)),z.subarray(9)]));l0(c().p().str(L).z(1).end())}async function _H(){m1=(await P8.randomBytes(18)).toString("base64"),c().p().str("SCRAM-SHA-256"+c.N);let z=c.i;l0(c.inc(4).str("n,,n=*,r="+m1).i32(c.i-z-4,z).end())}async function GH(z){let L=z.toString("utf8",9).split(",").reduce((Z1,F2)=>(Z1[F2[0]]=F2.slice(2),Z1),{}),l=await P8.pbkdf2Sync(await zY(),Buffer.from(L.s,"base64"),parseInt(L.i),32,"sha256"),$0=await t6(l,"Client Key"),C0="n=*,r="+m1+",r="+L.r+",s="+L.s+",i="+L.i+",c=biws,r="+L.r;K0=(await t6(await t6(l,"Server Key"),C0)).toString("base64");let n0="c=biws,r="+L.r+",p="+$E($0,Buffer.from(await t6(await GE($0),C0))).toString("base64");l0(c().p().str(n0).end())}function $H(z){if(z.toString("utf8",9).split(c.N,1)[0].slice(2)===K0)return;u1(f0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),K.destroy()}function zY(){return Promise.resolve(typeof Y.pass==="function"?Y.pass():Y.pass)}function WH(){if(p.statement=x.statement,p.statement.columns=[],x.onlyDescribe)return x.resolve(x.statement),l0(C2)}function HH(z){q.pid=z.readUInt32BE(5),q.secret=z.readUInt32BE(9)}async function JH(){z0=!1,(await new j1([`
59
+ ${V.trace}`:`No previous disposal trace for ${H} was found.`),X}let J=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:W.stringKey}).filter(([,{source:V}])=>V!==G).map(([V])=>X1(V));if(_)$.moleculeGraph.delete(G);$.moleculeGraph.set({upstreamMoleculeKey:Q.stringKey,downstreamMoleculeKey:W.stringKey},{source:Q.stringKey});let z={type:"molecule_transfer",key:W.key,exclusive:Boolean(_),from:J,to:[Q.key],timestamp:Date.now()};if(E1($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.subEvents.push(z);return X}function iU(Y,Z,X){switch(X){case"newValue":l9(Y,Z);break;case"oldValue":W8(Y,Z.token);break}}function rU(Y,Z,X){switch(X){case"newValue":W8(Y,Z.token);break;case"oldValue":if(l9(Y,Z),Z.subType==="atom")Y.valueMap.set(Z.token.key,Z.value);break}}function l9(Y,Z){let{token:X}=Z;if(Z.subType==="writable"&&Z.value)T1(Y,X,Z.value);else B1(Y,X)}function nU(Y,Z,X){switch(X){case"newValue":M6(Y,Z.provenance,Z.key);break;case"oldValue":N6(Y,Z.key);break}}function sU(Y,Z,X){switch(X){case"newValue":N6(Y,Z.key);break;case"oldValue":{let _=Z.provenance.map(X1);M6(Y,_,Z.key);for(let[G,$]of Z.values){let W=Y.families.get(G);if(W){B1(Y,W,Z.key);let H=`${G}(${Q0(Z.key)})`;Y.valueMap.set(H,$)}}}break}}function tU(Y,Z,X){switch(X){case"newValue":for(let _ of Z.to)G8(Y,_,Z.key,Z.exclusive?"exclusive":void 0);break;case"oldValue":{let _="exclusive";for(let G of Z.from)G8(Y,G,Z.key,_),_=void 0}break}}function o9(Y,Z,X){let _=X==="newValue"?Z.subEvents:[...Z.subEvents].reverse();for(let G of _)switch(G.type){case"atom_update":lU(Y,G,X);break;case"state_creation":iU(Y,G,X);break;case"state_disposal":rU(Y,G,X);break;case"molecule_creation":nU(Y,G,X);break;case"molecule_disposal":sU(Y,G,X);break;case"molecule_transfer":tU(Y,G,X);break;case"transaction_outcome":o9(Y,G,X);break}}function i9(Y,Z){return Y.transactionMeta.actionContinuities.getRelatedKey(Z)}function aU(Y,Z){return Y.transactionMeta.epoch.get(Z)}function eU(Y,Z){let X=i9(Y,Z);if(X===void 0)return;return aU(Y,X)}function YF(Y,Z,X){let _=i9(Y,Z);if(_!==void 0)Y.transactionMeta.epoch.set(_,X)}function ZF(Y,Z){let X=Y0(Y),{parent:_}=X;X.transactionMeta.phase="applying",X.transactionMeta.update.output=Z,_.child=null,_.on.transactionApplying.next(X.transactionMeta);let{subEvents:G}=X.transactionMeta.update;if(Y.logger.info("\uD83D\uDEC4","transaction",X.transactionMeta.update.token.key,`applying ${G.length} subEvents:`,G),o9(_,X.transactionMeta.update,"newValue"),O4(_))YF(_,X.transactionMeta.update.token.key,X.transactionMeta.update.epoch),S0(Y,{key:X.transactionMeta.update.token.key,type:"transaction"})?.subject.next(X.transactionMeta.update),Y.logger.info("\uD83D\uDEEC","transaction",X.transactionMeta.update.token.key,"applied");else if(E1(_))_.transactionMeta.update.subEvents.push(X.transactionMeta.update);_.on.transactionApplying.next(null)}function XF(Y){return{store:Y}}var _F=(Y,Z,X,_)=>{let G=Y0(Y),$={parent:G,child:null,on:G.on,loggers:G.loggers,logger:G.logger,config:G.config,atoms:new k1(G.atoms),atomsThatAreDefault:new Set(G.atomsThatAreDefault),families:new k1(G.families),joins:new k1(G.joins),operation:{open:!1},readonlySelectors:new k1(G.readonlySelectors),timelines:new k1(G.timelines),timelineTopics:G.timelineTopics.overlay(),trackers:new Map,transactions:new k1(G.transactions),selectorAtoms:G.selectorAtoms.overlay(),selectorGraph:G.selectorGraph.overlay(),writableSelectors:new k1(G.writableSelectors),valueMap:new k1(G.valueMap),defaults:G.defaults,disposalTraces:Y.disposalTraces.copy(),molecules:new k1(G.molecules),moleculeGraph:G.moleculeGraph.overlay(),moleculeData:G.moleculeData.overlay(),moleculeJoins:G.moleculeJoins.overlay(),miscResources:new k1(G.miscResources)},W=eU(Y,Z.key),H={phase:"building",update:{type:"transaction_outcome",token:Z,id:_,epoch:W===void 0?NaN:W+1,timestamp:Date.now(),subEvents:[],params:X,output:void 0},toolkit:{get:(...J)=>B1(Q,...J),set:(...J)=>{T1(Q,...J)},reset:(...J)=>{L6(Q,...J)},run:(J,z=xZ())=>D6(Q,J,z),find:(...J)=>j0(Y,...J),json:(J)=>b2(Q,J),dispose:(...J)=>{W8(Q,...J)},env:()=>XF(Q)}},Q=Object.assign($,{transactionMeta:H});return G.child=Q,Y.logger.info("\uD83D\uDEEB","transaction",Z.key,"building with params:",X),Q};function $8(Y,Z){let{key:X}=Z,_=Y.transactions.has(X),G={key:X,type:"transaction",run:(H,Q)=>{let J=b1(G),z=_F(Y,J,H,Q);try{let{toolkit:E}=z.transactionMeta,V=Z.do(E,...H);return ZF(z,V),V}catch(E){throw mU(z),Y.logger.warn("\uD83D\uDCA5","transaction",X,"caught:",E),E}},install:(H)=>$8(H,Z),subject:new W0};Y0(Y).transactions.set(X,G);let W=b1(G);if(!_)Y.on.transactionCreation.next(W);return W}function r9(Y,Z,{oldValue:X,newValue:_},G,$){let W=b1(Z);if(G&&$){Z.subject.next({newValue:_});let E={checkpoint:!0,type:"state_creation",subType:"writable",token:W,timestamp:Date.now(),value:_};Y.operation.subEvents.push(E),$.subject.next(E);let D=Y0(Y);if(W.family){if(O4(D))switch(W.type){case"atom":case"mutable_atom":Y.on.atomCreation.next(W);break;case"writable_pure_selector":case"writable_held_selector":Y.on.selectorCreation.next(W);break}else if(E1(D)&&D.on.transactionApplying.state===null)D.transactionMeta.update.subEvents.push(E)}return}let{key:H,subject:Q,type:J}=Z,z={oldValue:kZ(X)?X.READONLY_VIEW:X,newValue:kZ(_)?_.READONLY_VIEW:_};if(O4(Y)){switch(J){case"mutable_atom":Y.logger.info("\uD83D\uDCE2",J,H,"is now (",_,") subscribers:",Q.subscribers.keys());break;case"atom":case"writable_pure_selector":case"writable_held_selector":Y.logger.info("\uD83D\uDCE2",J,H,"went (",X,"->",_,") subscribers:",Q.subscribers.keys())}Q.next(z)}if(E1(Y)&&(J==="mutable_atom"||J==="atom")){if(Y.on.transactionApplying.state===null){if(kZ(_))return;let{timestamp:E}=Y.operation,V={type:"atom_update",token:W,timestamp:E,update:z};Y.transactionMeta.update.subEvents.push(V),Y.logger.info("\uD83D\uDCC1","atom",H,"stowed (",X,"->",_,")");return}if(e9(Z,"tracker:signal")){let E=H.slice(1),V=Y.atoms.get(E);if(k2(Y,V,"mut").do(z.newValue)===null===!0)uZ(Y,V)}}}var mZ=Symbol("OWN_OP"),GF=Symbol("JOIN_OP");function cZ(Y,Z,...X){let _,G,$,W,H,Q;if(X.length===2){if($=X[0],Q=X[1],"family"in $)if(W=dZ(Y,$),H=X1($.family.subKey),_=U8(Y,W,H),!_)$=G=z8(Y,W,H,Q8);else $=_}else if(W=S0(Y,X[0]),H=X[1],Q=X[2],_=U8(Y,W,H),!_)$=G=z8(Y,W,H,Q8);else $=_;let J=Q===pZ?"reset":"set",z;if(Z===mZ){let R=p9(Y,$);if(typeof R==="number"){let f=R,v=Y.on.operationClose.subscribe(`waiting to ${J} "${$.key}" at T-${f}`,function k(){v(),Y.logger.info("\uD83D\uDFE2",$.type,$.key,"resuming deferred",J,`from T-${f}`),cZ(Y,Z,$,Q)});return}z=R}else z=Y;if("counterfeit"in $&&"family"in $){let R=$.family.subKey,w=Y.disposalTraces.buffer.find((f)=>f?.key===R);Y.logger.error("\u274C",$.type,$.key,"could not be",J,"because key",R,"is not allocated.",w?`this key was previously disposed:${w.trace}`:"(no previous disposal trace found)");return}let E=S0(z,$),V;if(Q===pZ)V=uU(z,E);else V=cU(z,E,Q);let D=Boolean(G);if(r9(z,E,V,D,W),Z===mZ)m9(z)}var n9=(Y,Z)=>Y0(Y).atoms.has(Z),$F=(Y,Z)=>Y0(Y).writableSelectors.has(Z),WF=(Y,Z)=>Y0(Y).readonlySelectors.has(Z),HF=(Y,Z)=>n9(Y,Z)||$F(Y,Z)||WF(Y,Z);function h9(Y,Z){return Y0(Y).selectorGraph.getRelationEntries({downstreamSelectorKey:Z}).filter(([_,{source:G}])=>G!==Z).map(([_,{source:G}])=>G).filter((_)=>HF(Y,_))}function w6(Y,Z,X=new Set){let _=h9(Y,Z),G=new Map;while(_.length>0){let $=_.pop();if(X.has($))continue;if(X.add($),n9(Y,$)){let W=Y.atoms.get($);G.set(W.key,W)}else _.push(...h9(Y,$))}return G}function JF(Y,Z,X,_,G){let $=Y0(Y),{type:W,key:H}=_;if(W==="atom"||W==="mutable_atom")$.selectorAtoms.set({selectorKey:X,atomKey:H}),Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atom "${H}"`);else{let Q=w6(Y,H,G);Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atoms: [ ${[...Q.values()].map((J)=>`"${J.key}"`).join(", ")} ]`);for(let{key:J}of Q.values())$.selectorAtoms=$.selectorAtoms.set({selectorKey:X,atomKey:J})}G.add(H)}function I6(Y,Z,X,_){return{get:(...G)=>{let $=Y0(Y),{token:W,family:H,subKey:Q}=sZ(Y,...G),J;if("counterfeit"in W&&H&&Q)J=g9(Y,W,H,Q);else{let z=S0(Y,W);J=k2(Y,z)}return Y.logger.info("\uD83D\uDD0C",Z,X,`registers dependency ( "${W.key}" =`,J,")"),$.selectorGraph.set({upstreamSelectorKey:W.key,downstreamSelectorKey:X},{source:W.key}),JF(Y,Z,X,W,_),J},set:(...G)=>{let $=Y0(Y);cZ($,GF,...G)},find:(...G)=>j0(Y,...G),json:(G)=>b2(Y,G)}}function lZ(Y,Z,X){let _=Y0(Y),G=new W0,$=new Set,{key:W,const:H}=Z,Q="readonly_held_selector";Y.logger.info("\uD83D\uDD28","readonly_held_selector",W,"is being created");let{get:J,find:z,json:E}=I6(_,"readonly_held_selector",W,$),D={...Z,type:"readonly_held_selector",subject:G,getFrom:(w)=>{let f=w.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[v,{source:k}]of f)if(k!==W)w.selectorGraph.delete(v,W);return w.selectorAtoms.delete(W),Z.get({get:J,find:z,json:E},H),W2(w,D,H),Y.logger.info("\u2728","readonly_held_selector",W,"=",H),$.clear(),H},install:(w)=>lZ(w,Z,X)};if(X)D.family=X;_.readonlySelectors.set(W,D);let R={key:W,type:"readonly_held_selector"};if(X)R.family=X;return R}function oZ(Y,Z,X){let _=Y0(Y),G=new W0,$=new Set,W=Z.key,H="readonly_pure_selector";Y.logger.info("\uD83D\uDD28","readonly_pure_selector",W,"is being created");let{get:Q,find:J,json:z}=I6(_,"readonly_pure_selector",W,$),V={...Z,type:"readonly_pure_selector",subject:G,getFrom:()=>{let R=Y0(Y),w=R.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[k,{source:m}]of w)if(m!==W)R.selectorGraph.delete(k,W);R.selectorAtoms.delete(W);let f=Z.get({get:Q,find:J,json:z}),v=W2(R,V,f);return Y.logger.info("\u2728","readonly_pure_selector",W,"=",v),$.clear(),v},install:(R)=>oZ(R,Z,X)};if(X)V.family=X;_.readonlySelectors.set(W,V);let D={key:W,type:"readonly_pure_selector"};if(X)D.family=X;return D}function iZ(Y,Z,X){let _=Y0(Y),G=new W0,$=new Set,{key:W,const:H}=Z,Q="writable_held_selector";Y.logger.info("\uD83D\uDD28","writable_held_selector",W,"is being created");let J=I6(_,"writable_held_selector",W,$),{find:z,get:E,json:V}=J,D={find:z,get:E,json:V},f={...Z,type:"writable_held_selector",subject:G,getFrom:(k)=>{let m=k.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[T,{source:K}]of m)if(K!==W)k.selectorGraph.delete(T,W);return k.selectorAtoms.delete(W),Z.get(D,H),W2(k,f,H),Y.logger.info("\u2728","writable_held_selector",W,"=",H),$.clear(),H},setSelf:()=>{Z.set(J,H)},install:(k)=>iZ(k,Z,X)};if(X)f.family=X;_.writableSelectors.set(W,f);let v={key:W,type:"writable_held_selector"};if(X)v.family=X;return v}function rZ(Y,Z,X){let _=Y0(Y),G=new W0,$=new Set,W=Z.key,H="writable_pure_selector";Y.logger.info("\uD83D\uDD28","writable_pure_selector",W,"is being created");let Q=I6(_,"writable_pure_selector",W,$),{find:J,get:z,json:E}=Q,V={find:J,get:z,json:E},w={...Z,type:"writable_pure_selector",subject:G,getFrom:(v)=>{let k=v.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[K,{source:C}]of k)if(C!==W)v.selectorGraph.delete(K,W);v.selectorAtoms.delete(W);let m=Z.get(V),T=W2(v,w,m);return Y.logger.info("\u2728","writable_pure_selector",W,"=",T),$.clear(),T},setSelf:(v)=>{Z.set(Q,v)},install:(v)=>rZ(v,Z,X)};if(X)w.family=X;_.writableSelectors.set(W,w);let f={key:W,type:"writable_pure_selector"};if(X)f.family=X;return f}function q9(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X){let $=iZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}if(_){let $=lZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}if(X){let $=rZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}let G=oZ(Y,Z,void 0);return Y.on.selectorCreation.next(G),G}function QF(Y,Z){let X=Y0(Y),{key:_,type:G,family:$}=Z;if(!$)Y.logger.error("\u274C",G,_,"Standalone selectors cannot be disposed.");else{if(X.molecules.get($.subKey))X.moleculeData.delete($.subKey,$.key);let H;switch(Z.type){case"writable_held_selector":X.writableSelectors.delete(_),H={key:$.key,type:"writable_held_selector_family"},S0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"writable_pure_selector":X.writableSelectors.delete(_),H={key:$.key,type:"writable_pure_selector_family"},S0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"readonly_held_selector":X.readonlySelectors.delete(_),H={key:$.key,type:"readonly_held_selector_family"},S0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"readonly_pure_selector":X.readonlySelectors.delete(_),H={key:$.key,type:"readonly_pure_selector_family"},S0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break}if(X.valueMap.delete(_),X.selectorAtoms.delete(_),X.selectorGraph.delete(_),X.moleculeData.delete($.key,$.subKey),Y.logger.info("\uD83D\uDD25",Z.type,_,"deleted"),E1(X)&&X.transactionMeta.phase==="building")X.transactionMeta.update.subEvents.push({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});else Y.on.selectorDisposal.next(Z)}}function h2(Y,Z,X){let _=Z.key,G="readonly_pure_selector_family",$={key:_,type:"readonly_pure_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","readonly_pure_selector_family",_,`Overwriting an existing ${_2[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new W0,J=Object.assign((z)=>{let E=Q0(z),V={key:_,subKey:E},D=`${_}(${E})`,R=Y0(Y);return oZ(R,{key:D,get:Z.get(z)},V)},$,{internalRoles:X,subject:H,install:(z)=>h2(z,Z),default:(z)=>{return Z.get(z)({get:(...V)=>B1(Y,...V),find:(...V)=>j0(Y,...V),json:(V)=>b2(Y,V)})}});return Y.families.set(_,J),$}function V4(Y,Z,X){let _={key:Z.key,type:"atom_family"},G=Y.families.get(Z.key);if(G)Y.logger.error("\u2757","atom_family",Z.key,`Overwriting an existing ${_2[G.type]} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new W0,H=Object.assign((Q)=>{let J=Q0(Q),z={key:Z.key,subKey:J},E=`${Z.key}(${J})`,V=Y0(Y),D=Z.default,R={key:E,default:J8(D)?()=>D(Q):D};if(Z.effects)R.effects=Z.effects(Q);return f2(V,R,z)},_,{default:Z.default,subject:$,install:(Q)=>V4(Q,Z),internalRoles:X});if(Y.families.set(Z.key,H),J8(Z.default)===!1)Y.defaults.set(Z.key,Z.default);return _}function s9(Y,Z,X){let _=Z.key,G="readonly_held_selector_family",$={key:_,type:"readonly_held_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","readonly_held_selector_family",_,`Overwriting an existing ${_2[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new W0,J=Object.assign((z)=>{let E=Q0(z),V={key:_,subKey:E},D=`${_}(${E})`,R=Y0(Y);return lZ(R,{key:D,const:Z.const(z),get:Z.get(z)},V)},$,{internalRoles:X,subject:H,install:(z)=>s9(z,Z),default:Z.const});return Y.families.set(_,J),$}function t9(Y,Z,X){let _=Z.key,G="writable_held_selector_family",$={key:_,type:"writable_held_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","writable_held_selector_family",_,`Overwriting an existing ${_2[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new W0,J=Object.assign((z)=>{let E=Q0(z),V={key:_,subKey:E},D=`${_}(${E})`,R=Y0(Y);return iZ(R,{key:D,const:Z.const(z),get:Z.get(z),set:Z.set(z)},V)},$,{internalRoles:X,subject:H,install:(z)=>t9(z,Z),default:Z.const});return Y.families.set(_,J),$}function nZ(Y,Z,X){let _=Z.key,G="writable_pure_selector_family",$={key:_,type:"writable_pure_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","writable_pure_selector_family",_,`Overwriting an existing ${_2[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new W0,J=Object.assign((z)=>{let E=Q0(z),V={key:_,subKey:E},D=`${_}(${E})`,R=Y0(Y);return rZ(R,{key:D,get:Z.get(z),set:Z.set(z)},V)},$,{internalRoles:X,subject:H,install:(z)=>nZ(z,Z),default:(z)=>{return Z.get(z)({get:(...V)=>B1(Y,...V),find:(...V)=>j0(Y,...V),json:(V)=>b2(Y,V)})}});return Y.families.set(_,J),$}function fZ(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X)return t9(Y,Z,void 0);if(_)return s9(Y,Z,void 0);if(X)return nZ(Y,Z);return h2(Y,Z)}function U8(Y,Z,X){let _=Q0(X),G=`${Z.key}(${_})`,$=Y0(Y),W;switch(Z.type){case"atom_family":case"mutable_atom_family":W=$.atoms.get(G);break;case"writable_held_selector_family":case"writable_pure_selector_family":W=$.writableSelectors.get(G);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":W=$.readonlySelectors.get(G);break}if(W)return b1(W);return W}function j0(Y,Z,X){let _=S0(Y,Z),G=U8(Y,Z,X);if(G)return G;return z8(Y,_,X)}function W8(Y,...Z){let X;if(Z.length===1)X=Z[0];else{let _=Z[0],G=Z[1];X=j0(Y,_,G)}try{S0(Y,X)}catch(_){Y.logger.error("\u274C",X.type,X.key,`could not be disposed because it was not found in the store "${Y.config.name}".`);return}switch(X.type){case"atom":case"mutable_atom":a9(Y,X);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":QF(Y,X);break}}function sZ(Y,...Z){let X,_,G,$,W;if(Z.length===1){if(W=Z[0],"family"in W){let J=dZ(Y,W);if(G=S0(Y,J),$=X1(W.family.subKey),X=U8(Y,J,$),"counterfeit"in W)return{token:W,family:G,subKey:$,isNew:!1};if(!X)_=z8(Y,J,$,Q8),W=_;else W=X}}else if(G=S0(Y,Z[0]),$=Z[1],X=U8(Y,G,$),!X)_=z8(Y,G,$,Q8),W=_;else W=X;let H="counterfeit"in W;if(Boolean(_)&&H===!1&&G){let J;switch(W.type){case"readonly_pure_selector":case"readonly_held_selector":J="readable";break;case"atom":case"mutable_atom":case"writable_pure_selector":case"writable_held_selector":J="writable";break}let z={type:"state_creation",subType:J,token:W,timestamp:Date.now()};G.subject.next(z);let V=Y0(Y);if(W.family){if(O4(V))switch(W.type){case"atom":case"mutable_atom":Y.on.atomCreation.next(W);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":Y.on.selectorCreation.next(W);break}else if(E1(V)&&V.on.transactionApplying.state===null)V.transactionMeta.update.subEvents.push(z)}}return{token:W,family:G,subKey:$,isNew:Boolean(_)}}function B1(Y,...Z){let{token:X,family:_,subKey:G}=sZ(Y,...Z);if("counterfeit"in X&&_&&G)return g9(Y,X,_,G);let $=S0(Y,X);return k2(Y,$)}var k9=(Y,Z,X)=>{return X.subject.subscribe(`${Z.type}:${Z.key}`,(_)=>{Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"root",X.key,"went",_.oldValue,"->",_.newValue);let G=yU(Y,Z),$=k2(Y,Z);Y.logger.info("\u2728",Z.type,Z.key,"went",G,"->",$),Z.subject.next({newValue:$,oldValue:G})})};function F8(Y,Z,X,_){function G(E){if(Y.operation.open){let V=Y.on.operationClose.subscribe(`state subscription ${X}`,()=>{V(),_(E)})}else _(E)}sZ(Y,Z);let $=S0(Y,Z);Y.logger.info("\uD83D\uDC40",$.type,$.key,`Adding subscription "${X}"`);let W=$.type==="writable_pure_selector"||$.type==="readonly_pure_selector",H=new Map,Q=G;if(W){k2(Y,$);for(let[E,V]of w6(Y,$.key))H.set(E,k9(Y,$,V));Q=function E(V){let D=w6(Y,$.key);for(let[R,w]of H)if(D.get(R))D.delete(R);else w(),H.delete(R);for(let[R,w]of D)H.set(R,k9(Y,$,w));G(V)}}let J=$.subject.subscribe(X,Q);return()=>{Y.logger.info("\uD83D\uDE48",$.type,$.key,`Removing subscription "${X}"`),J();for(let E of H.values())E()}}function S0(Y,Z){let X,_=Y;while(_!==null){switch(Z.type){case"atom":case"mutable_atom":X=_.atoms.get(Z.key);break;case"writable_pure_selector":case"writable_held_selector":X=_.writableSelectors.get(Z.key);break;case"readonly_pure_selector":case"readonly_held_selector":X=_.readonlySelectors.get(Z.key);break;case"atom_family":case"mutable_atom_family":case"writable_pure_selector_family":case"readonly_pure_selector_family":case"writable_held_selector_family":case"readonly_held_selector_family":X=_.families.get(Z.key);break;case"timeline":X=_.timelines.get(Z.key);break;case"transaction":X=_.transactions.get(Z.key);break}if(X)return X;_=_.child}throw new FF(Z,Y)}var zF=(Y,Z,X,_)=>{let G=S0(Y,Z);Y.logger.info("\uD83D\uDC40","timeline",Z.key,`Adding subscription "${X}"`);let $=G.subject.subscribe(X,_);return()=>{Y.logger.info("\uD83D\uDE48","timeline",Z.key,`Removing subscription "${X}" from timeline`),$()}};var tZ=class{initializeSignalAtom(Y,Z){let X=`*${Y.key}`;Z.atoms.delete(X),Z.valueMap.delete(X);let _=Y.family?{key:`*${Y.family.key}`,subKey:Y.family.subKey}:void 0,G=f2(Z,{key:X,default:null},_,["tracker:signal"]);if(Z.parent?.valueMap.has(X)){let $=Z.parent.valueMap.get(X);Z.valueMap.set(X,$)}return G}unsubscribeFromInnerValue;unsubscribeFromState;captureSignalsFromCore(Y,Z,X){let _=Y.key,G=X.config.name,$=E1(X)?X.transactionMeta.update.token.key:"main",W=`tracker:${G}:${$}:${_}`,H=(J)=>{T1(X,Z,J)},Q=B1(X,Y);this.unsubscribeFromInnerValue=Q.subscribe(W,H),this.unsubscribeFromState=F8(X,Y,W,function J(z){if(z.newValue!==z.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=z.newValue.subscribe(W,H)}.bind(this))}supplySignalsToCore(Y,Z,X){let _=`tracker:${X.config.name}:${E1(X)?X.transactionMeta.update.token.key:"main"}:${Y.key}`;F8(X,Z,_,function G({newValue:$,oldValue:W}){let H=X.timelineTopics.getRelatedKey(Z.key);if(H&&X.timelines.get(H)?.timeTraveling){let E=zF(X,{key:H,type:"timeline"},_,function V(D){E(),T1(X,Y,(R)=>{if(D==="redo"&&$)R.do($);else if(D==="undo"&&W)R.undo(W);return R})});return}let Q=B1(X,Y),J=Q.getUpdateNumber($),z=J-Q.cacheUpdateNumber;if($&&z===1)T1(X,Y,(E)=>(E.do($),E));else{let E=Q.cacheUpdateNumber+1;X.logger.info("\u274C","mutable_atom",Y.key,"could not be updated. Expected update number",E,"but got",J)}})}mutableAtomToken;latestSignalToken;[Symbol.dispose];constructor(Y,Z){let X=Y0(Z),_=this.initializeSignalAtom(Y,X);this.mutableAtomToken=Y,this.latestSignalToken=_,this.captureSignalsFromCore(Y,_,X),this.supplySignalsToCore(Y,_,X),X.trackers.set(Y.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(Y.key)}}};function A6(Y,Z,X){Y.logger.info("\uD83D\uDD28","atom",Z.key,`creating in store "${Y.config.name}"`);let _=Y0(Y),{key:G}=Z,$=_.atoms.get(G),W="mutable_atom";if($&&$.type===W)return Y.logger.error("\u274C",W,G,"Tried to create atom, but it already exists in the store."),b1($);let H=new W0,Q={...Z,type:W,install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${z.config.name}"`),A6(z,Z,X)},subject:H};if(X)Q.family=X;_.atoms.set(Q.key,Q);let J=b1(Q);if(Z.effects){let z=0,E=[];for(let V of Z.effects){let D=V({resetSelf:()=>{L6(Y,J)},setSelf:(R)=>{T1(Y,J,R)},onSet:(R)=>F8(Y,J,`effect[${z}]`,R)});if(D)E.push(D);++z}Q.cleanup=()=>{for(let V of E)V()}}if(new tZ(J,Y),!X)q9(Y,{key:`${G}:JSON`,get:({get:z})=>z(J).toJSON(),set:({set:z},E)=>{z(J,Z.class.fromJSON(E))}});return Y.on.atomCreation.next(J),J}var UF=class{trackers=new Map;latestSignalAtoms;mutableAtoms;constructor(Y,Z){let X=V4(Z,{key:`*${Y.key}`,default:null},["mutable","updates"]);this.latestSignalAtoms=S0(Z,X),this.mutableAtoms=Y;let _=(G)=>{let{type:$,token:W}=G;if(W.family){let H=X1(W.family.subKey);switch($){case"state_creation":this.trackers.set(H,new tZ(W,Z));break;case"state_disposal":{let Q=this.trackers.get(H);if(Q)Q[Symbol.dispose](),this.trackers.delete(H)}}}};this.mutableAtoms.subject.subscribe(`store=${Z.config.name}::tracker-atom-family`,_)}};function hZ(Y,Z,X){let _={key:Z.key,type:"mutable_atom_family"},G=Y.families.get(Z.key);if(G)Y.logger.error("\u2757","mutable_atom_family",Z.key,`Overwriting an existing ${_2[G.type]} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new W0,H=Object.assign((Q)=>{let J=Q0(Q),z={key:Z.key,subKey:J},E=`${Z.key}(${J})`,V=Y0(Y),D={key:E,class:Z.class};if(Z.effects)D.effects=Z.effects(Q);return A6(V,D,z)},_,{class:Z.class,subject:$,install:(Q)=>hZ(Q,Z),internalRoles:X});return Y.families.set(Z.key,H),nZ(Y,{key:`${Z.key}:JSON`,get:(Q)=>({get:J})=>J(_,Q).toJSON(),set:(Q)=>({set:J},z)=>{J(_,Q,Z.class.fromJSON(z))}},["mutable","json"]),new UF(H,Y),_}var b9=(Y,Z)=>{let X=Y0(Z),_=`${Y.key}:JSON`;return X.families.get(_)},b2=(Y,Z)=>{if(Z.family){let _=Y0(Y),$={key:`${Z.family.key}:JSON`,type:"writable_pure_selector_family"},W=S0(_,$),H=X1(Z.family.subKey);return j0(Y,W,H)}return{type:"writable_pure_selector",key:`${Z.key}:JSON`}};var aZ=(Y)=>{let X={type:"atom",key:`*${Y.key}`};if(Y.family)X.family={key:`*${Y.family.key}`,subKey:Y.family.subKey};return X};function kZ(Y){return typeof Y==="object"&&Y!==null&&"do"in Y&&"undo"in Y&&"subscribe"in Y&&"cacheUpdateNumber"in Y&&"getUpdateNumber"in Y&&"READONLY_VIEW"in Y&&"toJSON"in Y}var j9=class{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new $2({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new $2({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new $2({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new $2({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new xU(100);molecules=new Map;moleculeJoins=new $2({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeGraph=new $2({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeData=new $2({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});miscResources=new Map;on={atomCreation:new W0,atomDisposal:new W0,selectorCreation:new W0,selectorDisposal:new W0,timelineCreation:new W0,transactionCreation:new W0,transactionApplying:new bU(null),operationClose:new W0,moleculeCreation:new W0,moleculeDisposal:new W0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new I9("warn",(Y,Z,X)=>!D4(X))];logger={error:(...Y)=>{for(let Z of this.loggers)Z.error(...Y)},info:(...Y)=>{for(let Z of this.loggers)Z.info(...Y)},warn:(...Y)=>{for(let Z of this.loggers)Z.warn(...Y)}};constructor(Y,Z=null){if(this.config={...Z?.config,...Y},Z!==null){if(this.operation={...Z?.operation},O4(Z))this.transactionMeta={epoch:new Map(Z?.transactionMeta.epoch),actionContinuities:new $2(Z?.transactionMeta.actionContinuities.toJSON())};for(let[,_]of Z.families){if(_.internalRoles?.includes("mutable")||_.internalRoles?.includes("join"))continue;_.install(this)}let X=new Set;for(let[,_]of Z.atoms){if(X.has(_.key))continue;if(_.install(this),_.type==="mutable_atom"){let G=b2(Z,_),$=aZ(_);X.add(G.key),X.add($.key)}}for(let[,_]of Z.readonlySelectors)_.install(this);for(let[,_]of Z.writableSelectors){if(X.has(_.key))continue;_.install(this)}for(let[,_]of Z.transactions)_.install(this);for(let[,_]of Z.timelines)_.install(this)}}},_1={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new j9({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function f2(Y,Z,X,_){let{key:$}=Z;Y.logger.info("\uD83D\uDD28","atom",$,"is being created");let W=Y0(Y),H=W.atoms.get($);if(H&&H.type==="atom")return Y.logger.error("\u274C","atom",$,"Tried to create atom, but it already exists in the store."),b1(H);let Q=new W0,J={...Z,type:"atom",install:(E)=>{return E.logger.info("\uD83D\uDEE0\uFE0F","atom",$,`installing in store "${E.config.name}"`),f2(E,Z,X)},subject:Q};if(X)J.family=X;if(_)J.internalRoles=_;W.atoms.set($,J);let z=b1(J);if(Z.effects){let E=0,V=[];for(let D of Z.effects){let R=D({resetSelf:()=>{L6(Y,z)},setSelf:(w)=>{T1(Y,z,w)},onSet:(w)=>F8(Y,z,`effect[${E}]`,w)});if(R)V.push(R);++E}J.cleanup=()=>{for(let D of V)D()}}return Y.on.atomCreation.next(z),z}function a9(Y,Z){let X=Y0(Y),{key:_,family:G}=Z,$=S0(X,Z);if(!G)Y.logger.error("\u274C","atom",_,"Standalone atoms cannot be disposed.");else{$.cleanup?.();let W=Y.valueMap.get($.key),H=dZ(Y,Z),J=S0(Y,H).subject,z={type:"state_disposal",subType:"atom",token:Z,value:W,timestamp:Date.now()};J.next(z);let E=E1(X);if(X.atoms.delete(_),X.valueMap.delete(_),X.selectorAtoms.delete(_),X.atomsThatAreDefault.delete(_),X.moleculeData.delete(G.key,G.subKey),Y.timelineTopics.delete(_),Z.type==="mutable_atom"){let V=aZ(Z);a9(Y,V),Y.trackers.delete(_)}if(Y.logger.info("\uD83D\uDD25","atom",_,"deleted"),E&&X.transactionMeta.phase==="building"){let V=X.transactionMeta.update.subEvents.at(-1),R=V?.type==="molecule_disposal"&&V.values.some(([f])=>f===$.family?.key),w=e9($,"tracker:signal");if(!R&&!w)X.transactionMeta.update.subEvents.push(z)}else Y.on.atomDisposal.next(Z)}}function e9(Y,Z){if("internalRoles"in Y===!1)return!1;return Y.internalRoles.includes(Z)}function K0(Y){return Y[0].toUpperCase()+Y.slice(1)}var Y7=class{toolkit;options;defaultContent;relations;states;core;transact(Y,Z){let X=this.toolkit;this.toolkit=Y,Z(this),this.toolkit=X}store;realm;[Symbol.dispose](){}constructor(Y,Z,X=_1.STORE){this.store=X,this.realm=new K9(X),this.options=Y,this.defaultContent=Z,this.store.miscResources.set(`join:${Y.key}`,this),this.realm.allocate("root",Y.key),this.toolkit={get:(...T)=>B1(X,...T),set:(...T)=>{T1(X,...T)},find:(...T)=>j0(X,...T),json:(T)=>b2(X,T)};let _=Y.between[0],G=Y.between[1],$=hZ(X,{key:`${Y.key}/relatedKeys`,class:G2},["join","relations"]);this.core={relatedKeysAtoms:$};let W=({get:T},K)=>T($,K),H=({set:T},K,C)=>{if(!this.store.molecules.has(Q0(K)))this.realm.allocate(Y.key,K);T($,K,(q)=>q.add(C)),T($,C,(q)=>q.add(K))},Q=({set:T},K,C)=>{T($,K,(N)=>{return N.delete(C),N}),T($,C,(N)=>{return N.delete(K),N});let[q,g]=[K,C].sort(),o=`${q}:${g}`;this.store.moleculeJoins.delete(o)},J=(T,K,C)=>{let{find:q,get:g,set:o}=T,N=q($,K),s=g(N);for(let p of s){if(C.includes(p))continue;o($,p,(U0)=>{return U0.delete(K),U0})}o(N,(p)=>{return p.transaction((a)=>{a.clear();for(let U0 of C){let h0=W(T,U0),W1=h0.has(K);if(this.relations.cardinality==="1:n"){let r1=[];for(let B of h0){if(B===K)continue;let u=W(T,B);if(u.delete(U0),u.size===0)r1.push(B)}if(!W1&&h0.size>0)h0.clear();for(let B of r1){let[u,G0]=[U0,B].sort(),O0=`${u}:${G0}`;X.moleculeJoins.delete(O0)}}if(!W1)h0.add(K);a.add(U0)}return!0}),p})},z=(T,K,C)=>{let{set:q}=T;q($,K,(g)=>{return g.transaction((o)=>{for(let N of C)o.add(N);return!0}),g});for(let g of C)q($,g,(o)=>{return o.add(K),o});return!0},E=(T,K,C)=>{let q=W(T,K);return C?q.has(C):q.size>0},V={getRelatedKeys:(T)=>W(this.toolkit,T),addRelation:(T,K)=>{this.store.moleculeJoins.set(`"${T}"`,Y.key),this.store.moleculeJoins.set(`"${K}"`,Y.key),H(this.toolkit,T,K)},deleteRelation:(T,K)=>{Q(this.toolkit,T,K)},replaceRelationsSafely:(T,K)=>{J(this.toolkit,T,K)},replaceRelationsUnsafely:(T,K)=>{z(this.toolkit,T,K)},has:(T,K)=>E(this.toolkit,T,K)},D,R;if(Z){R=V4(X,{key:`${Y.key}/content`,default:Z},["join","content"]);let T=({get:q},g)=>q(R,g),K=({set:q},g,o)=>{q(R,g,o)};D=Object.assign(V,{getContent:(q)=>{return T(this.toolkit,q)},setContent:(q,g)=>{K(this.toolkit,q,g)},deleteContent:(q)=>{}})}else D=V;let w=new $2(Y,{externalStore:D,isAType:Y.isAType,isBType:Y.isBType,makeContentKey:(...T)=>{let[K,C]=T,[q,g]=T.sort(),o=`${q}:${g}`,N=X.molecules.get(Q0(K)),s=X.molecules.get(Q0(C));if(!N)this.realm.allocate(Y.key,K);if(!s)this.realm.allocate(Y.key,C);return this.realm.allocate(K,o,"all"),this.realm.claim(C,o),this.store.moleculeJoins.set(o,Y.key),o}}),f=()=>h2(X,{key:`${Y.key}/singleRelatedKey`,get:(T)=>({get:K})=>{let C=K($,T);for(let q of C)return q;return null}},["join","keys"]),v=()=>{return h2(X,{key:`${Y.key}/multipleRelatedKeys`,get:(T)=>({get:K})=>{let C=b9($,X);return K(C,T).members}},["join","keys"])},k=()=>h2(X,{key:`${Y.key}/singleRelatedEntry`,get:(T)=>({get:K})=>{let C=K($,T);for(let q of C){let g=w.isAType?.(T)?T:void 0,o=g===void 0?T:void 0;g??=q,o??=q;let N=w.makeContentKey(g,o),s=K(R,N);return[q,s]}return null}},["join","entries"]),m=()=>h2(X,{key:`${Y.key}/multipleRelatedEntries`,get:(T)=>({get:K})=>{let C=b9($,X);return K(C,T).members.map((g)=>{let o=w.isAType?.(T)?T:void 0,N=o===void 0?T:void 0;o??=g,N??=g;let s=w.makeContentKey(o,N),p=K(R,s);return[g,p]})}},["join","entries"]);switch(Y.cardinality){case"1:1":{let T=f(),K=`${_}KeyOf${K0(G)}`,C=`${G}KeyOf${K0(_)}`,q={[K]:T,[C]:T},g;if(Z){let o=k(),N=`${_}EntryOf${K0(G)}`,s=`${G}EntryOf${K0(_)}`,p={[N]:o,[s]:o};g=Object.assign(q,p)}else g=q;this.relations=w,this.states=g;break}case"1:n":{let T=f(),K=v(),C=`${_}KeyOf${K0(G)}`,q=`${G}KeysOf${K0(_)}`,g={[C]:T,[q]:K},o;if(Z){let N=k(),s=m(),p=`${_}EntryOf${K0(G)}`,a=`${G}EntriesOf${K0(_)}`,U0={[p]:N,[a]:s};o=Object.assign(g,U0)}else o=g;this.relations=w,this.states=o;break}case"n:n":{let T=v(),K=`${_}KeysOf${K0(G)}`,C=`${G}KeysOf${K0(_)}`,q={[K]:T,[C]:T},g;if(Z){let o=m(),N=`${_}EntriesOf${K0(G)}`,s=`${G}EntriesOf${K0(_)}`,p={[N]:o,[s]:o};g=Object.assign(q,p)}else g=q;this.relations=w,this.states=g}}}};function S9(Y,Z,X){return Y.joins.set(Z.key,new Y7(Z,X,Y)),{key:Z.key,type:"join",a:Z.between[0],b:Z.between[1],cardinality:Z.cardinality}}function eZ(Y,Z){let X=Z.joins.get(Y.key);if(X===void 0){let G=_1.STORE.joins.get(Y.key);if(G===void 0)throw new Error(`Join "${Y.key}" not found in store "${Z.config.name}"`);let $=vU(Z);X=new Y7(G.options,G.defaultContent,$),Z.joins.set(Y.key,X)}return X}function H8(Y,Z,X){let _=eZ(Y,X),G=Y0(X);if(E1(G)){let{toolkit:$}=G.transactionMeta;_.transact($,({relations:W})=>{Z(W)})}else Z(_.relations)}function P9(Y,Z,X){let _=eZ(Y,X),G;switch(Y.cardinality){case"1:1":{let $=`${Y.a}KeyOf${K0(Y.b)}`,W=`${Y.b}KeyOf${K0(Y.a)}`;G={get[$](){let Q=_.states[$];return j0(X,Q,Z)},get[W](){let Q=_.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntryOf${K0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntryOf${K0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return j0(X,J,Z)},get[Q](){let J=_.states[Q];return j0(X,J,Z)}})}break}case"1:n":{let $=`${Y.a}KeyOf${K0(Y.b)}`,W=`${Y.b}KeysOf${K0(Y.a)}`;G={get[$](){let Q=_.states[$];return j0(X,Q,Z)},get[W](){let Q=_.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntryOf${K0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntriesOf${K0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return j0(X,J,Z)},get[Q](){let J=_.states[Q];return j0(X,J,Z)}})}break}case"n:n":{let $=`${Y.a}KeysOf${K0(Y.b)}`,W=`${Y.b}KeysOf${K0(Y.a)}`;G={get[$](){let Q=_.states[$];return j0(X,Q,Z)},get[W](){let Q=_.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntriesOf${K0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntriesOf${K0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return j0(X,J,Z)},get[Q](){let J=_.states[Q];return j0(X,J,Z)}})}}}return G}function v9(Y,Z){return eZ(Y,Z).core.relatedKeysAtoms}var FF=class extends Error{constructor(Y,Z){super(`${_2[Y.type]} ${Q0(Y.key)} not found in store "${Z.config.name}".`)}};function D4(Y){return Y.startsWith("\uD83D\uDD0D ")}var EF=(Y)=>{return f2(Y,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Z=new Map;for(let[X,_]of Y.atoms){if(D4(X))continue;let G=b1(_);if(_.family){let $=Z.get(_.family.key);if(!$||!("familyMembers"in $))$={key:_.family.key,familyMembers:new Map},Z.set(_.family.key,$);$.familyMembers.set(_.family.subKey,G)}else Z.set(X,G)}return Z},effects:[({setSelf:Z})=>{Y.on.atomCreation.subscribe("introspection",(X)=>{if(D4(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W===void 0||!("familyMembers"in W))W={key:G,familyMembers:new Map},_.set(G,W);W.familyMembers.set($,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.atomDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)_.delete(G)}}return new Map(_)})})}]},void 0)},VF=(Y)=>{return f2(Y,{key:"\uD83D\uDD0D Selector Token Index",default:()=>{let Z=new Map;for(let X of[Y.readonlySelectors,Y.writableSelectors])for(let[_,G]of X){if(D4(_))continue;let $=b1(G);if(G.family){let W=Z.get(G.family.key);if(!W||!("familyMembers"in W))W={key:G.family.key,familyMembers:new Map},Z.set(G.family.key,W);W.familyMembers.set(G.family.subKey,$)}else Z.set(_,$)}return Z},effects:[({setSelf:Z})=>{Y.on.selectorCreation.subscribe("introspection",(X)=>{if(D4(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W===void 0||!("familyMembers"in W))W={key:G,familyMembers:new Map},_.set(G,W);W.familyMembers.set($,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.selectorDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)_.delete(G)}}else _.delete(X.key);return new Map(_)})})}]},void 0)};var Y5=class{supported;constructor(Y){this.supported=Y}refine(Y){for(let[Z,X]of Object.entries(this.supported))try{if(X(Y)===!0&&X!==Boolean)return{type:Z,data:Y}}catch(_){try{if(Y instanceof X)return{type:Z,data:Y}}catch(G){}}return null}},X7=new Y5({number:(Y)=>typeof Y==="number",string:(Y)=>typeof Y==="string",boolean:(Y)=>typeof Y==="boolean",null:(Y)=>Y===null});function _7(Y){if(!Y)return!1;return Object.getPrototypeOf(Y)===Object.prototype}var G7=new Y5({object:_7,array:(Y)=>Array.isArray(Y)}),OF=new Y5({...X7.supported,...G7.supported}),K6=(Y)=>{if(Y===void 0)return"undefined";let Z=OF.refine(Y);if(Z)return Z.type;return Object.getPrototypeOf(Y).constructor.name};var ZT=class Y{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Z=_1.STORE){this.store=Z,this.atomIndex=EF(this.store),this.selectorIndex=VF(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(Z=Y.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let X=vZ(this.atomIndex),_=vZ(this.selectorIndex),G=[...X.values()].filter((Q)=>("familyMembers"in Q)),$=[..._.values()].filter((Q)=>("familyMembers"in Q)),W=performance.now(),H=[];if(Z.atomFamilies)for(let Q of G){let J=Q.familyMembers.values();for(let z of J){let V=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,D=W-V;H.push([z,D])}}if(Z.selectorFamilies)for(let Q of $){let J=Q.familyMembers.values();for(let z of J){let V=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,D=W-V;H.push([z,D])}}return H}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},Z7=(Y,Z)=>{let X=(_,G)=>{let W=((Q,J)=>{let z=Z(Q,J);if(z)return z;return null})(_,G);if(W?.jobComplete??W?.pathComplete)return W;let H=Array.isArray(G)?G.map((Q,J)=>[J,Q]):_7(G)?Object.entries(G):[];for(let[Q,J]of H){let z=X([..._,Q],J);if(z?.jobComplete)return z}return{}};X([],Y)};function DF(Y,Z){return{summary:`${Y<Z?"+":"-"}${Math.abs(Y-Z)} (${Y} \u2192 ${Z})`}}function LF(Y,Z){return{summary:`${Y.length<Z.length?"+":"-"}${Math.abs(Y.length-Z.length)} ("${Y}" \u2192 "${Z}")`}}function MF(Y,Z){return{summary:`${Y} \u2192 ${Z}`}}function $7(Y,Z,X){let _="",G=[],$=[],W=[];return Z7(Y,(H,Q)=>{let J;for(J of H){let z=Z[J];if(z===void 0)$.push([J,JSON.stringify(Q)]);else{let E=X(Q,z);if(E.summary!=="No Change")W.push([J,E])}}}),Z7(Z,(H,Q)=>{let J;for(J of H)if(Y[J]===void 0)G.push([J,JSON.stringify(Q)])}),_=`\uFF5E${W.length} \uFF0B${G.length} \uFF0D${$.length}`,{summary:_,added:G,removed:$,changed:W}}function AF(Y,Z,X){return $7(Y,Z,X)}var wF=class{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(Y,Z,X){this.leafRefinery=Y,this.treeRefinery=Z,this.leafDiffers={},this.treeDiffers={};for(let _ of Object.keys(Y.supported)){let G=X[_];this.leafDiffers[_]=G}for(let _ of Object.keys(Z.supported)){let G=X[_];this.treeDiffers[_]=G}}diff(Y,Z){if(Y===Z)return{summary:"No Change"};let X=this.leafRefinery.refine(Y)??this.treeRefinery.refine(Y),_=this.leafRefinery.refine(Z)??this.treeRefinery.refine(Z);if(X!==null&&_!==null){if(X.type===_.type){if(X.type in this.leafDiffers)return this.leafDiffers[X.type](X.data,_.data);if(X.type in this.treeDiffers)return this.treeDiffers[X.type](X.data,_.data,(H,Q)=>this.diff(H,Q))}}let G=K6(Y),$=K6(Z);if(G===$)return{summary:`${G} \u2192 ${$}`};return{summary:`Type change: ${G} \u2192 ${$}`}}},XT=new wF(X7,G7,{number:DF,string:LF,boolean:MF,null:()=>({summary:"No Change"}),object:$7,array:AF});var RF=class extends Map{set(Y,Z){if(this.has(Y))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:Y,value:Z}),this;return super.set(Y,Z)}clear(){throw new Error("Cannot clear an InvariantMap")}},JT=class Y{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Z){this.key=Z}static existing=new RF;static create(Z,X){let _=new Y(Z),{type:G,globals:$,actions:W,perspectives:H}=X(_),Q={type:G,key:Z,globals:$,actions:W,perspectives:H};return Y.existing.set(Z,Q),Q}add(...Z){switch(Z[0].type){case"atom":case"mutable_atom":this.globals.push(...Z);break;case"transaction":this.actions.push(...Z);break;case"atom_family":case"mutable_atom_family":{let[_,G]=Z;this.perspectives.push({type:"realtime_perspective",resourceAtoms:_,viewAtoms:G})}break}return this}};var QT=E4({key:"usersInRoomIndex",class:G2}),Z5=E4({key:"roomIndex",class:G2}),NF={enteredAtEpoch:0},E8=V6({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(Y)=>typeof Y==="string",isBType:(Y)=>typeof Y==="string"},NF),zT=O6({key:"usersInMyRoomView",get:(Y)=>({find:Z})=>{let X=N9(E8);return[Z(X,Y)]}});import{spawn as IF}from"child_process";var X5=class{listeners;globalListeners;handleEvent(Y,...Z){for(let _ of this.globalListeners)_(Y,...Z);let X=this.listeners.get(Y);if(X)for(let _ of X)_(...Z)}id="no_id_retrieved";emit;constructor(Y){this.emit=Y,this.listeners=new Map,this.globalListeners=new Set}on(Y,Z){let X=this.listeners.get(Y);if(X)X.add(Z);else this.listeners.set(Y,new Set([Z]));return this}onAny(Y){return this.globalListeners.add(Y),this}off(Y,Z){let X=this.listeners.get(Y);if(X)if(Z)X.delete(Z);else this.listeners.delete(Y);return this}offAny(Y){return this.globalListeners.delete(Y),this}},KF=class extends X5{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(Y){if(Array.isArray(Y)){let[Z,...X]=Y;switch(Z){case"i":this.logger.info(...X);break;case"w":this.logger.warn(...X);break;case"e":this.logger.error(...X);break;default:return}}}constructor(Y,Z,X){super((_,...G)=>{let $=JSON.stringify([_,...G])+"\x03",W=(H)=>{if(H.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",W)};return this.process.stdin.once("error",W),this.process.stdin.write($),this});if(this.process=Y,this.key=Z,this.logger=X??{info:(..._)=>{console.info(this.id,this.key,..._)},warn:(..._)=>{console.warn(this.id,this.key,..._)},error:(..._)=>{console.error(this.id,this.key,..._)}},this.process.stdout.on("data",(_)=>{let G=_.toString();if(G==="ALIVE")return;this.unprocessedEvents.push(...G.split("\x03"));let $=this.unprocessedEvents.shift();this.incompleteData+=$??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let W=X1(this.incompleteData);this.handleEvent(...W);while(this.unprocessedEvents.length>0){let H=this.unprocessedEvents.shift();if(H){if(this.unprocessedEvents.length===0)this.incompleteData=H;W=X1(H),this.handleEvent(...W)}}this.incompleteData=""}catch(W){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(W)}}),this.process.stderr.on("data",(_)=>{let G=_.toString();this.unprocessedLogs.push(...G.split("\x03"));let $=this.unprocessedLogs.shift();this.incompleteLog+=$??"";try{let W=X1(this.incompleteLog);this.handleLog(W);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)W=X1(this.incompleteLog),this.handleLog(W)}catch(W){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(W),console.error("\u274C\u274C\u274C\uFE0F")}}),Y.pid)this.id=Y.pid.toString()}},TF=class extends X5{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(Y){super((...Z)=>{return this.out.next(Z),this});this.id=Y,this.in=new W0,this.out=new W0,this.in.subscribe("socket",(Z)=>{this.handleEvent(...Z)})}dispose(){for(let Y of this.disposalFunctions)Y()}},W7=class extends X5{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...Y){this.process.stderr.write(Q0(Y.map((Z)=>Z instanceof G2?`{ ${Z.toJSON().members.join(" | ")} }`:Z))+"\x03")}logger={info:(...Y)=>{this.log("i",...Y)},warn:(...Y)=>{this.log("w",...Y)},error:(...Y)=>{this.log("e",...Y)}};constructor(){super((Y,...Z)=>{let X=JSON.stringify([Y,...Z]);return this.process.stdout.write(X+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(Y)=>{let Z=Y.toString();this.unprocessedEvents.push(...Z.split("\x03"));let X=this.unprocessedEvents.shift();this.incompleteData+=X??"";try{let _=X1(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",_),this.handleEvent(..._);while(this.unprocessedEvents.length>0){let G=this.unprocessedEvents.shift();if(G){if(this.unprocessedEvents.length===0)this.incompleteData=G;let $=X1(G);this.handleEvent(...$)}}this.incompleteData=""}catch(_){if(_ instanceof Error)this.logger.error("\u2757",_.message,_.cause,_.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(Y)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${Y}`)}),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",(Y)=>{this.logger.info("\uD83D\uDC64","user",Y,"joined");let Z=new TF(`user:${Y}`);this.relays.set(Y,Z),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let X of this.relayServices){let _=X(Z);if(_)Z.disposalFunctions.push(_)}this.on(`user:${Y}`,(...X)=>{Z.in.next(X)}),Z.out.subscribe("socket",(X)=>{this.emit(...X)})}),this.on("user-leaves",(Y)=>{let Z=this.relays.get(Y);if(this.off(`relay:${Y}`),Z)Z.dispose(),this.relays.delete(Y)}),process.stdout.write("ALIVE")}relay(Y){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(Y)}},H7=X8({key:"roomArguments",default:["echo",["Hello World!"]]}),BF=O6({key:"room",get:(Y)=>async({get:Z,find:X})=>{let _=X(H7,Y),G=Z(_),[$,W]=G,H=await new Promise((Q)=>{let J=IF($,W,{env:process.env}),z=(E)=>{if(E.toString()==="ALIVE")J.stdout.off("data",z),Q(J)};J.stdout.on("data",z)});return new KF(H,Y)}}),wT=_8({key:"createRoom",do:({get:Y,set:Z,find:X},_,G,$)=>{let W=$?[G,$]:[G],H=X(H7,_);Z(H,W),Z(Z5,(z)=>z.add(_));let Q=X(BF,_);return Y(Q)}}),RT=_8({key:"joinRoom",do:(Y,Z,X,_)=>{let G={enteredAtEpoch:_};return H8(E8,($)=>{$.set({room:Z,user:X},G)},Y.env().store),G}}),NT=_8({key:"leaveRoom",do:(Y,Z,X)=>{H8(E8,(_)=>{_.delete({room:Z,user:X})},Y.env().store)}}),IT=_8({key:"destroyRoom",do:(Y,Z)=>{H8(E8,(X)=>{X.delete({room:Z})},Y.env().store),Y.set(Z5,(X)=>(X.delete(Z),X))}});var KT=X8({key:"redactor",default:{occlude:(Y)=>Y}}),TT=X8({key:"unacknowledgedUpdates",default:()=>[]}),BT=X8({key:"sockets",default:null}),CT=E4({key:"socketsIndex",class:G2}),qT=E4({key:"usersIndex",class:G2}),jT=V6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(Y)=>Y.startsWith("user::"),isBType:(Y)=>Y.startsWith("socket::")});var{file:g3,serve:uE}=globalThis.Bun;import{readFileSync as z7}from"fs";import{createServer as SF}from"http";import{createServer as PF}from"https";import{resolve as G5}from"path";function J7(Y,Z){if(Y instanceof Promise)throw new Error(Z)}function CF(Y,Z){let X={},_=[];for(let G in Y){let $=Y[G]["~standard"].validate(Z[G]);if(J7($,`Validation must be synchronous, but ${G} returned a Promise.`),$.issues){_.push(...$.issues.map((W)=>({...W,message:W.message,path:[G,...W.path??[]]})));continue}X[G]=$.value}if(_.length)return{issues:_};return{value:X}}function _5(Y){let Z=Y.runtimeEnvStrict??Y.runtimeEnv??process.env;if(Y.emptyStringAsUndefined??!1){for(let[k,m]of Object.entries(Z))if(m==="")delete Z[k]}if(!!Y.skipValidation)return Z;let G=typeof Y.client==="object"?Y.client:{},$=typeof Y.server==="object"?Y.server:{},W=typeof Y.shared==="object"?Y.shared:{},H=Y.isServer??(typeof window==="undefined"||("Deno"in window)),Q=H?{...$,...W,...G}:{...G,...W},J=Y.createFinalSchema?.(Q,H)["~standard"].validate(Z)??CF(Q,Z);J7(J,"Validation must be synchronous");let z=Y.onValidationError??((k)=>{throw console.error("\u274C Invalid environment variables:",k),new Error("Invalid environment variables")}),E=Y.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(J.issues)return z(J.issues);let V=(k)=>{if(!Y.clientPrefix)return!0;return!k.startsWith(Y.clientPrefix)&&!(k in W)},D=(k)=>{return H||!V(k)},R=(k)=>{return k==="__esModule"||k==="$$typeof"},w=(Y.extends??[]).reduce((k,m)=>{return Object.assign(k,m)},{}),f=Object.assign(w,J.value);return new Proxy(f,{get(k,m){if(typeof m!=="string")return;if(R(m))return;if(!D(m))return E(m);return Reflect.get(k,m)}})}var qF="__vite_start_time"in globalThis,jF=typeof window!=="undefined",pT="vitest"in globalThis,H2=F1("string"),Q7=F1('"true" | "false" | undefined'),y1=_5({isServer:!qF&&!jF,server:{CI:F1("string | undefined").pipe(Boolean),POSTGRES_USER:H2,POSTGRES_PASSWORD:H2,POSTGRES_DATABASE:H2,POSTGRES_HOST:H2,POSTGRES_PORT:H2.pipe((Y)=>Number.parseInt(Y,10)),BACKEND_PORT:H2.pipe((Y)=>Number.parseInt(Y,10)),RUN_WORKERS_FROM_SOURCE:Q7.pipe((Y)=>Y==="true"),FRONTEND_PORT:H2.pipe((Y)=>Number.parseInt(Y,10)),FRONTEND_ORIGINS:H2.pipe.try((Y)=>JSON.parse(Y),F1("string[]")),API_KEY_OPENAI:F1("string | undefined"),API_KEY_RESEND:F1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:H2,VITE_DEV_FRONTEND_HOST:F1("string | undefined"),VITE_DEV_HTTPS:Q7.pipe((Y)=>Y==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var U7=G5(import.meta.dirname,"../dev"),T6=y1.VITE_DEV_HTTPS?{cert:z7(G5(U7,"./cert.pem"),"utf-8"),key:z7(G5(U7,"./key.pem"),"utf-8")}:void 0;function iT(Y){if(T6)return PF(T6,Y);return SF({},Y)}import hE from"path";var F=Symbol.for("drizzle:entityKind");function M(Y,Z){if(!Y||typeof Y!=="object")return!1;if(Y instanceof Z)return!0;if(!Object.prototype.hasOwnProperty.call(Z,F))throw new Error(`Class "${Z.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let X=Object.getPrototypeOf(Y).constructor;if(X)while(X){if(F in X&&X[F]===Z[F])return!0;X=Object.getPrototypeOf(X)}return!1}class E0{constructor(Y,Z){this.table=Y,this.config=Z,this.name=Z.name,this.keyAsName=Z.keyAsName,this.notNull=Z.notNull,this.default=Z.default,this.defaultFn=Z.defaultFn,this.onUpdateFn=Z.onUpdateFn,this.hasDefault=Z.hasDefault,this.primary=Z.primaryKey,this.isUnique=Z.isUnique,this.uniqueName=Z.uniqueName,this.uniqueType=Z.uniqueType,this.dataType=Z.dataType,this.columnType=Z.columnType,this.generated=Z.generated,this.generatedIdentity=Z.generatedIdentity}static[F]="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(Y){return Y}mapToDriverValue(Y){return Y}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class $5{static[F]="ColumnBuilder";config;constructor(Y,Z,X){this.config={name:Y,keyAsName:Y==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:Z,columnType:X,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(Y){return this.config.default=Y,this.config.hasDefault=!0,this}$defaultFn(Y){return this.config.defaultFn=Y,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(Y){return this.config.onUpdateFn=Y,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(Y){if(this.config.name!=="")return;this.config.name=Y}}var g1=Symbol.for("drizzle:Name");class W5{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(Y,Z){if(this.reference=()=>{let{name:X,columns:_,foreignColumns:G}=Y();return{name:X,columns:_,foreignTable:G[0].table,foreignColumns:G}},Z)this._onUpdate=Z.onUpdate,this._onDelete=Z.onDelete}onUpdate(Y){return this._onUpdate=Y===void 0?"no action":Y,this}onDelete(Y){return this._onDelete=Y===void 0?"no action":Y,this}build(Y){return new F7(Y,this)}}class F7{constructor(Y,Z){this.table=Y,this.reference=Z.reference,this.onUpdate=Z._onUpdate,this.onDelete=Z._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:Y,columns:Z,foreignColumns:X}=this.reference(),_=Z.map((W)=>W.name),G=X.map((W)=>W.name),$=[this.table[g1],..._,X[0].table[g1],...G];return Y??`${$.join("_")}_fk`}}function B6(Y,...Z){return Y(...Z)}function E7(Y,Z){return`${Y[g1]}_${Z.join("_")}_unique`}function V7(Y,Z,X){for(let _=Z;_<Y.length;_++){let G=Y[_];if(G==="\\"){_++;continue}if(G==='"')return[Y.slice(Z,_).replace(/\\/g,""),_+1];if(X)continue;if(G===","||G==="}")return[Y.slice(Z,_).replace(/\\/g,""),_]}return[Y.slice(Z).replace(/\\/g,""),Y.length]}function O7(Y,Z=0){let X=[],_=Z,G=!1;while(_<Y.length){let $=Y[_];if($===","){if(G||_===Z)X.push("");G=!0,_++;continue}if(G=!1,$==="\\"){_+=2;continue}if($==='"'){let[Q,J]=V7(Y,_+1,!0);X.push(Q),_=J;continue}if($==="}")return[X,_+1];if($==="{"){let[Q,J]=O7(Y,_+1);X.push(Q),_=J;continue}let[W,H]=V7(Y,_,!1);X.push(W),_=H}return[X,_]}function D7(Y){let[Z]=O7(Y,1);return Z}function H5(Y){return`{${Y.map((Z)=>{if(Array.isArray(Z))return H5(Z);if(typeof Z==="string")return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Z}`}).join(",")}}`}class b extends $5{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(Y){return new M7(this.config.name,this,Y)}references(Y,Z={}){return this.foreignKeyConfigs.push({ref:Y,actions:Z}),this}unique(Y,Z){return this.config.isUnique=!0,this.config.uniqueName=Y,this.config.uniqueType=Z?.nulls,this}generatedAlwaysAs(Y){return this.config.generated={as:Y,type:"always",mode:"stored"},this}buildForeignKeys(Y,Z){return this.foreignKeyConfigs.map(({ref:X,actions:_})=>{return B6((G,$)=>{let W=new W5(()=>{let H=G();return{columns:[Y],foreignColumns:[H]}});if($.onUpdate)W.onUpdate($.onUpdate);if($.onDelete)W.onDelete($.onDelete);return W.build(Z)},X,_)})}buildExtraConfigColumn(Y){return new L7(Y,this.config)}}class j extends E0{constructor(Y,Z){if(!Z.uniqueName)Z.uniqueName=E7(Y,[Z.name]);super(Y,Z);this.table=Y}static[F]="PgColumn"}class L7 extends j{static[F]="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(Y){return this.indexConfig.opClass=Y,this}}class V8{static[F]="IndexedColumn";constructor(Y,Z,X,_){this.name=Y,this.keyAsName=Z,this.type=X,this.indexConfig=_}name;keyAsName;type;indexConfig}class M7 extends b{static[F]="PgArrayBuilder";constructor(Y,Z,X){super(Y,"array","PgArray");this.config.baseBuilder=Z,this.config.size=X}build(Y){let Z=this.config.baseBuilder.build(Y);return new J5(Y,this.config,Z)}}class J5 extends j{constructor(Y,Z,X,_){super(Y,Z);this.baseColumn=X,this.range=_,this.size=Z.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(Y){if(typeof Y==="string")Y=D7(Y);return Y.map((Z)=>this.baseColumn.mapFromDriverValue(Z))}mapToDriverValue(Y,Z=!1){let X=Y.map((_)=>_===null?null:M(this.baseColumn,J5)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Z)return X;return H5(X)}}class A7 extends b{static[F]="PgEnumObjectColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumObjectColumn");this.config.enum=Z}build(Y){return new w7(Y,this.config)}}class w7 extends j{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}var C6=Symbol.for("drizzle:isPgEnum");function R7(Y){return!!Y&&typeof Y==="function"&&C6 in Y&&Y[C6]===!0}class N7 extends b{static[F]="PgEnumColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumColumn");this.config.enum=Z}build(Y){return new I7(Y,this.config)}}class I7 extends j{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}function O8(Y,Z){return Array.isArray(Z)?vF(Y,[...Z],void 0):xF(Y,Z,void 0)}function vF(Y,Z,X){let _=Object.assign((G)=>new N7(G??"",_),{enumName:Y,enumValues:Z,schema:X,[C6]:!0});return _}function xF(Y,Z,X){let _=Object.assign((G)=>new A7(G??"",_),{enumName:Y,enumValues:Object.values(Z),schema:X,[C6]:!0});return _}class P0{static[F]="Subquery";constructor(Y,Z,X,_=!1,G=[]){this._={brand:"Subquery",sql:Y,selectedFields:Z,alias:X,isWith:_,usedTables:G}}}class D8 extends P0{static[F]="WithSubquery"}var K7="0.44.5";var Q5,z5,V0={startActiveSpan(Y,Z){if(!Q5)return Z();if(!z5)z5=Q5.trace.getTracer("drizzle-orm",K7);return B6((X,_)=>_.startActiveSpan(Y,(G)=>{try{return Z(G)}catch($){throw G.setStatus({code:X.SpanStatusCode.ERROR,message:$ instanceof Error?$.message:"Unknown error"}),$}finally{G.end()}}),Q5,z5)}};var A0=Symbol.for("drizzle:ViewBaseConfig");var y2=Symbol.for("drizzle:Schema"),q6=Symbol.for("drizzle:Columns"),T7=Symbol.for("drizzle:ExtraConfigColumns"),U5=Symbol.for("drizzle:OriginalName"),F5=Symbol.for("drizzle:BaseName"),L8=Symbol.for("drizzle:IsAlias"),B7=Symbol.for("drizzle:ExtraConfigBuilder"),fF=Symbol.for("drizzle:IsDrizzleTable");class S{static[F]="Table";static Symbol={Name:g1,Schema:y2,OriginalName:U5,Columns:q6,ExtraConfigColumns:T7,BaseName:F5,IsAlias:L8,ExtraConfigBuilder:B7};[g1];[U5];[y2];[q6];[T7];[F5];[L8]=!1;[fF]=!0;[B7]=void 0;constructor(Y,Z,X){this[g1]=this[U5]=Y,this[y2]=Z,this[F5]=X}}function d0(Y){return Y[g1]}function g2(Y){return`${Y[y2]??"public"}.${Y[g1]}`}function E5(Y){return Y!==null&&Y!==void 0&&typeof Y.getSQL==="function"}function hF(Y){let Z={sql:"",params:[]};for(let X of Y)if(Z.sql+=X.sql,Z.params.push(...X.params),X.typings?.length){if(!Z.typings)Z.typings=[];Z.typings.push(...X.typings)}return Z}class m0{static[F]="StringChunk";value;constructor(Y){this.value=Array.isArray(Y)?Y:[Y]}getSQL(){return new h([this])}}class h{constructor(Y){this.queryChunks=Y;for(let Z of Y)if(M(Z,S)){let X=Z[S.Symbol.Schema];this.usedTables.push(X===void 0?Z[S.Symbol.Name]:X+"."+Z[S.Symbol.Name])}}static[F]="SQL";decoder=q7;shouldInlineParams=!1;usedTables=[];append(Y){return this.queryChunks.push(...Y.queryChunks),this}toQuery(Y){return V0.startActiveSpan("drizzle.buildSQL",(Z)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,Y);return Z?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams(Y,Z){let X=Object.assign({},Z,{inlineParams:Z.inlineParams||this.shouldInlineParams,paramStartIndex:Z.paramStartIndex||{value:0}}),{casing:_,escapeName:G,escapeParam:$,prepareTyping:W,inlineParams:H,paramStartIndex:Q}=X;return hF(Y.map((J)=>{if(M(J,m0))return{sql:J.value.join(""),params:[]};if(M(J,j6))return{sql:G(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let z=[new m0("(")];for(let[E,V]of J.entries())if(z.push(V),E<J.length-1)z.push(new m0(", "));return z.push(new m0(")")),this.buildQueryFromSourceParams(z,X)}if(M(J,h))return this.buildQueryFromSourceParams(J.queryChunks,{...X,inlineParams:H||J.shouldInlineParams});if(M(J,S)){let z=J[S.Symbol.Schema],E=J[S.Symbol.Name];return{sql:z===void 0||J[L8]?G(E):G(z)+"."+G(E),params:[]}}if(M(J,E0)){let z=_.getColumnCasing(J);if(Z.invokeSource==="indexes")return{sql:G(z),params:[]};let E=J.table[S.Symbol.Schema];return{sql:J.table[L8]||E===void 0?G(J.table[S.Symbol.Name])+"."+G(z):G(E)+"."+G(J.table[S.Symbol.Name])+"."+G(z),params:[]}}if(M(J,V1)){let z=J[A0].schema,E=J[A0].name;return{sql:z===void 0||J[A0].isAlias?G(E):G(z)+"."+G(E),params:[]}}if(M(J,A1)){if(M(J.value,N2))return{sql:$(Q.value++,J),params:[J],typings:["none"]};let z=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(M(z,h))return this.buildQueryFromSourceParams([z],X);if(H)return{sql:this.mapInlineParam(z,X),params:[]};let E=["none"];if(W)E=[W(J.encoder)];return{sql:$(Q.value++,z),params:[z],typings:E}}if(M(J,N2))return{sql:$(Q.value++,J),params:[J],typings:["none"]};if(M(J,h.Aliased)&&J.fieldAlias!==void 0)return{sql:G(J.fieldAlias),params:[]};if(M(J,P0)){if(J._.isWith)return{sql:G(J._.alias),params:[]};return this.buildQueryFromSourceParams([new m0("("),J._.sql,new m0(") "),new j6(J._.alias)],X)}if(R7(J)){if(J.schema)return{sql:G(J.schema)+"."+G(J.enumName),params:[]};return{sql:G(J.enumName),params:[]}}if(E5(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],X);return this.buildQueryFromSourceParams([new m0("("),J.getSQL(),new m0(")")],X)}if(H)return{sql:this.mapInlineParam(J,X),params:[]};return{sql:$(Q.value++,J),params:[J],typings:["none"]}}))}mapInlineParam(Y,{escapeString:Z}){if(Y===null)return"null";if(typeof Y==="number"||typeof Y==="boolean")return Y.toString();if(typeof Y==="string")return Z(Y);if(typeof Y==="object"){let X=Y.toString();if(X==="[object Object]")return Z(JSON.stringify(Y));return Z(X)}throw new Error("Unexpected param value: "+Y)}getSQL(){return this}as(Y){if(Y===void 0)return this;return new h.Aliased(this,Y)}mapWith(Y){return this.decoder=typeof Y==="function"?{mapFromDriverValue:Y}:Y,this}inlineParams(){return this.shouldInlineParams=!0,this}if(Y){return Y?this:void 0}}class j6{constructor(Y){this.value=Y}static[F]="Name";brand;getSQL(){return new h([this])}}function C7(Y){return typeof Y==="object"&&Y!==null&&"mapToDriverValue"in Y&&typeof Y.mapToDriverValue==="function"}var q7={mapFromDriverValue:(Y)=>Y},j7={mapToDriverValue:(Y)=>Y},kB={...q7,...j7};class A1{constructor(Y,Z=j7){this.value=Y,this.encoder=Z}static[F]="Param";brand;getSQL(){return new h([this])}}function O(Y,...Z){let X=[];if(Z.length>0||Y.length>0&&Y[0]!=="")X.push(new m0(Y[0]));for(let[_,G]of Z.entries())X.push(G,new m0(Y[_+1]));return new h(X)}((Y)=>{function Z(){return new h([])}Y.empty=Z;function X(Q){return new h(Q)}Y.fromList=X;function _(Q){return new h([new m0(Q)])}Y.raw=_;function G(Q,J){let z=[];for(let[E,V]of Q.entries()){if(E>0&&J!==void 0)z.push(J);z.push(V)}return new h(z)}Y.join=G;function $(Q){return new j6(Q)}Y.identifier=$;function W(Q){return new N2(Q)}Y.placeholder=W;function H(Q,J){return new A1(Q,J)}Y.param=H})(O||(O={}));((Y)=>{class Z{constructor(X,_){this.sql=X,this.fieldAlias=_}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Z(this.sql,this.fieldAlias)}}Y.Aliased=Z})(h||(h={}));class N2{constructor(Y){this.name=Y}static[F]="Placeholder";getSQL(){return new h([this])}}function V5(Y,Z){return Y.map((X)=>{if(M(X,N2)){if(!(X.name in Z))throw new Error(`No value for placeholder "${X.name}" was provided`);return Z[X.name]}if(M(X,A1)&&M(X.value,N2)){if(!(X.value.name in Z))throw new Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue(Z[X.value.name])}return X})}var kF=Symbol.for("drizzle:IsDrizzleView");class V1{static[F]="View";[A0];[kF]=!0;constructor({name:Y,schema:Z,selectedFields:X,query:_}){this[A0]={name:Y,originalName:Y,schema:Z,selectedFields:X,query:_,isExisting:!_,isAlias:!1}}getSQL(){return new h([this])}}E0.prototype.getSQL=function(){return new h([this])};S.prototype.getSQL=function(){return new h([this])};P0.prototype.getSQL=function(){return new h([this])};class L4{constructor(Y){this.table=Y}static[F]="ColumnAliasProxyHandler";get(Y,Z){if(Z==="table")return this.table;return Y[Z]}}class M8{constructor(Y,Z){this.alias=Y,this.replaceOriginalName=Z}static[F]="TableAliasProxyHandler";get(Y,Z){if(Z===S.Symbol.IsAlias)return!0;if(Z===S.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Z===S.Symbol.OriginalName)return this.alias;if(Z===A0)return{...Y[A0],name:this.alias,isAlias:!0};if(Z===S.Symbol.Columns){let _=Y[S.Symbol.Columns];if(!_)return _;let G={};return Object.keys(_).map(($)=>{G[$]=new Proxy(_[$],new L4(new Proxy(Y,this)))}),G}let X=Y[Z];if(M(X,E0))return new Proxy(X,new L4(new Proxy(Y,this)));return X}}function S6(Y,Z){return new Proxy(Y,new M8(Z,!1))}function o1(Y,Z){return new Proxy(Y,new L4(new Proxy(Y.table,new M8(Z,!1))))}function O5(Y,Z){return new h.Aliased(A8(Y.sql,Z),Y.fieldAlias)}function A8(Y,Z){return O.join(Y.queryChunks.map((X)=>{if(M(X,E0))return o1(X,Z);if(M(X,h))return A8(X,Z);if(M(X,h.Aliased))return O5(X,Z);return X}))}class P6 extends Error{static[F]="DrizzleError";constructor({message:Y,cause:Z}){super(Y);this.name="DrizzleError",this.cause=Z}}class J2 extends Error{constructor(Y,Z,X){super(`Failed query: ${Y}
60
+ params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrace(this,J2),X)this.cause=X}}class D5 extends P6{static[F]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class S7{static[F]="ConsoleLogWriter";write(Y){console.log(Y)}}class L5{static[F]="DefaultLogger";writer;constructor(Y){this.writer=Y?.writer??new S7}logQuery(Y,Z){let X=Z.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),_=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${Y}${_}`)}}class M5{static[F]="NoopLogger";logQuery(){}}class G1{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(Y){return this.then(void 0,Y)}finally(Y){return this.then((Z)=>{return Y?.(),Z},(Z)=>{throw Y?.(),Z})}then(Y,Z){return this.execute().then(Y,Z)}}function P7(Y,Z,X){let _={},G=Y.reduce(($,{path:W,field:H},Q)=>{let J;if(M(H,E0))J=H;else if(M(H,h))J=H.decoder;else J=H.sql.decoder;let z=$;for(let[E,V]of W.entries())if(E<W.length-1){if(!(V in z))z[V]={};z=z[V]}else{let D=Z[Q],R=z[V]=D===null?null:J.mapFromDriverValue(D);if(X&&M(H,E0)&&W.length===2){let w=W[0];if(!(w in _))_[w]=R===null?d0(H.table):!1;else if(typeof _[w]==="string"&&_[w]!==d0(H.table))_[w]=!1}}return $},{});if(X&&Object.keys(_).length>0){for(let[$,W]of Object.entries(_))if(typeof W==="string"&&!X[W])G[$]=null}return G}function C1(Y,Z){return Object.entries(Y).reduce((X,[_,G])=>{if(typeof _!=="string")return X;let $=Z?[...Z,_]:[_];if(M(G,E0)||M(G,h)||M(G,h.Aliased))X.push({path:$,field:G});else if(M(G,S))X.push(...C1(G[S.Symbol.Columns],$));else X.push(...C1(G,$));return X},[])}function w8(Y,Z){let X=Object.keys(Y),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let[G,$]of X.entries())if($!==_[G])return!1;return!0}function v6(Y,Z){let X=Object.entries(Z).filter(([,_])=>_!==void 0).map(([_,G])=>{if(M(G,h)||M(G,E0))return[_,G];else return[_,new A1(G,Y[S.Symbol.Columns][_])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function v7(Y,Z){for(let X of Z)for(let _ of Object.getOwnPropertyNames(X.prototype)){if(_==="constructor")continue;Object.defineProperty(Y.prototype,_,Object.getOwnPropertyDescriptor(X.prototype,_)||Object.create(null))}}function x7(Y){return Y[S.Symbol.Columns]}function Q2(Y){return M(Y,P0)?Y._.alias:M(Y,V1)?Y[A0].name:M(Y,h)?void 0:Y[S.Symbol.IsAlias]?Y[S.Symbol.Name]:Y[S.Symbol.BaseName]}function X0(Y,Z){return{name:typeof Y==="string"&&Y.length>0?Y:"",config:typeof Y==="object"?Y:Z}}function f7(Y){if(typeof Y!=="object"||Y===null)return!1;if(Y.constructor.name!=="Object")return!1;if("logger"in Y){let Z=typeof Y.logger;if(Z!=="boolean"&&(Z!=="object"||typeof Y.logger.logQuery!=="function")&&Z!=="undefined")return!1;return!0}if("schema"in Y){let Z=typeof Y.schema;if(Z!=="object"&&Z!=="undefined")return!1;return!0}if("casing"in Y){let Z=typeof Y.casing;if(Z!=="string"&&Z!=="undefined")return!1;return!0}if("mode"in Y){if(Y.mode!=="default"||Y.mode!=="planetscale"||Y.mode!==void 0)return!1;return!0}if("connection"in Y){let Z=typeof Y.connection;if(Z!=="string"&&Z!=="object"&&Z!=="undefined")return!1;return!0}if("client"in Y){let Z=typeof Y.client;if(Z!=="object"&&Z!=="function"&&Z!=="undefined")return!1;return!0}if(Object.keys(Y).length===0)return!0;return!1}class I2 extends b{static[F]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(Y){if(Y){let{name:Z,...X}=Y;this.config.generatedIdentity={type:"always",sequenceName:Z,sequenceOptions:X}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(Y){if(Y){let{name:Z,...X}=Y;this.config.generatedIdentity={type:"byDefault",sequenceName:Z,sequenceOptions:X}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class h7 extends I2{static[F]="PgBigInt53Builder";constructor(Y){super(Y,"number","PgBigInt53")}build(Y){return new k7(Y,this.config)}}class k7 extends j{static[F]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class b7 extends I2{static[F]="PgBigInt64Builder";constructor(Y){super(Y,"bigint","PgBigInt64")}build(Y){return new y7(Y,this.config)}}class y7 extends j{static[F]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(Y){return BigInt(Y)}}function g7(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new h7(X);return new b7(X)}class p7 extends b{static[F]="PgBigSerial53Builder";constructor(Y){super(Y,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new m7(Y,this.config)}}class m7 extends j{static[F]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class u7 extends b{static[F]="PgBigSerial64Builder";constructor(Y){super(Y,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(Y){return new d7(Y,this.config)}}class d7 extends j{static[F]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(Y){return BigInt(Y)}}function c7(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new p7(X);return new u7(X)}class l7 extends b{static[F]="PgBooleanBuilder";constructor(Y){super(Y,"boolean","PgBoolean")}build(Y){return new o7(Y,this.config)}}class o7 extends j{static[F]="PgBoolean";getSQLType(){return"boolean"}}function R8(Y){return new l7(Y??"")}class i7 extends b{static[F]="PgCharBuilder";constructor(Y,Z){super(Y,"string","PgChar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new r7(Y,this.config)}}class r7 extends j{static[F]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function n7(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new i7(X,_)}class s7 extends b{static[F]="PgCidrBuilder";constructor(Y){super(Y,"string","PgCidr")}build(Y){return new t7(Y,this.config)}}class t7 extends j{static[F]="PgCidr";getSQLType(){return"cidr"}}function a7(Y){return new s7(Y??"")}class e7 extends b{static[F]="PgCustomColumnBuilder";constructor(Y,Z,X){super(Y,"custom","PgCustomColumn");this.config.fieldConfig=Z,this.config.customTypeParams=X}build(Y){return new Y$(Y,this.config)}}class Y$ extends j{static[F]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(Y,Z){super(Y,Z);this.sqlName=Z.customTypeParams.dataType(Z.fieldConfig),this.mapTo=Z.customTypeParams.toDriver,this.mapFrom=Z.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(Y){return typeof this.mapFrom==="function"?this.mapFrom(Y):Y}mapToDriverValue(Y){return typeof this.mapTo==="function"?this.mapTo(Y):Y}}function Z$(Y){return(Z,X)=>{let{name:_,config:G}=X0(Z,X);return new e7(_,G,Y)}}class z2 extends b{static[F]="PgDateColumnBaseBuilder";defaultNow(){return this.default(O`now()`)}}class X$ extends z2{static[F]="PgDateBuilder";constructor(Y){super(Y,"date","PgDate")}build(Y){return new x6(Y,this.config)}}class x6 extends j{static[F]="PgDate";getSQLType(){return"date"}mapFromDriverValue(Y){return new Date(Y)}mapToDriverValue(Y){return Y.toISOString()}}class _$ extends z2{static[F]="PgDateStringBuilder";constructor(Y){super(Y,"string","PgDateString")}build(Y){return new f6(Y,this.config)}}class f6 extends j{static[F]="PgDateString";getSQLType(){return"date"}}function G$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="date")return new X$(X);return new _$(X)}class $$ extends b{static[F]="PgDoublePrecisionBuilder";constructor(Y){super(Y,"number","PgDoublePrecision")}build(Y){return new W$(Y,this.config)}}class W$ extends j{static[F]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function H$(Y){return new $$(Y??"")}class J$ extends b{static[F]="PgInetBuilder";constructor(Y){super(Y,"string","PgInet")}build(Y){return new Q$(Y,this.config)}}class Q$ extends j{static[F]="PgInet";getSQLType(){return"inet"}}function z$(Y){return new J$(Y??"")}class U$ extends I2{static[F]="PgIntegerBuilder";constructor(Y){super(Y,"number","PgInteger")}build(Y){return new F$(Y,this.config)}}class F$ extends j{static[F]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseInt(Y);return Y}}function N8(Y){return new U$(Y??"")}class E$ extends b{static[F]="PgIntervalBuilder";constructor(Y,Z){super(Y,"string","PgInterval");this.config.intervalConfig=Z}build(Y){return new V$(Y,this.config)}}class V$ extends j{static[F]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let Y=this.fields?` ${this.fields}`:"",Z=this.precision?`(${this.precision})`:"";return`interval${Y}${Z}`}}function O$(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new E$(X,_)}class D$ extends b{static[F]="PgJsonBuilder";constructor(Y){super(Y,"json","PgJson")}build(Y){return new h6(Y,this.config)}}class h6 extends j{static[F]="PgJson";constructor(Y,Z){super(Y,Z)}getSQLType(){return"json"}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}}function L$(Y){return new D$(Y??"")}class M$ extends b{static[F]="PgJsonbBuilder";constructor(Y){super(Y,"json","PgJsonb")}build(Y){return new k6(Y,this.config)}}class k6 extends j{static[F]="PgJsonb";constructor(Y,Z){super(Y,Z)}getSQLType(){return"jsonb"}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}}function A$(Y){return new M$(Y??"")}class w$ extends b{static[F]="PgLineBuilder";constructor(Y){super(Y,"array","PgLine")}build(Y){return new R$(Y,this.config)}}class R$ extends j{static[F]="PgLine";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,_]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X),Number.parseFloat(_)]}mapToDriverValue(Y){return`{${Y[0]},${Y[1]},${Y[2]}}`}}class N$ extends b{static[F]="PgLineABCBuilder";constructor(Y){super(Y,"json","PgLineABC")}build(Y){return new I$(Y,this.config)}}class I$ extends j{static[F]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,_]=Y.slice(1,-1).split(",");return{a:Number.parseFloat(Z),b:Number.parseFloat(X),c:Number.parseFloat(_)}}mapToDriverValue(Y){return`{${Y.a},${Y.b},${Y.c}}`}}function K$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new w$(X);return new N$(X)}class T$ extends b{static[F]="PgMacaddrBuilder";constructor(Y){super(Y,"string","PgMacaddr")}build(Y){return new B$(Y,this.config)}}class B$ extends j{static[F]="PgMacaddr";getSQLType(){return"macaddr"}}function C$(Y){return new T$(Y??"")}class q$ extends b{static[F]="PgMacaddr8Builder";constructor(Y){super(Y,"string","PgMacaddr8")}build(Y){return new j$(Y,this.config)}}class j$ extends j{static[F]="PgMacaddr8";getSQLType(){return"macaddr8"}}function S$(Y){return new q$(Y??"")}class P$ extends b{static[F]="PgNumericBuilder";constructor(Y,Z,X){super(Y,"string","PgNumeric");this.config.precision=Z,this.config.scale=X}build(Y){return new b6(Y,this.config)}}class b6 extends j{static[F]="PgNumeric";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.scale}mapFromDriverValue(Y){if(typeof Y==="string")return Y;return String(Y)}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 v$ extends b{static[F]="PgNumericNumberBuilder";constructor(Y,Z,X){super(Y,"number","PgNumericNumber");this.config.precision=Z,this.config.scale=X}build(Y){return new x$(Y,this.config)}}class x$ extends j{static[F]="PgNumericNumber";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.scale}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}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 f$ extends b{static[F]="PgNumericBigIntBuilder";constructor(Y,Z,X){super(Y,"bigint","PgNumericBigInt");this.config.precision=Z,this.config.scale=X}build(Y){return new h$(Y,this.config)}}class h$ extends j{static[F]="PgNumericBigInt";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.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 k$(Y,Z){let{name:X,config:_}=X0(Y,Z),G=_?.mode;return G==="number"?new v$(X,_?.precision,_?.scale):G==="bigint"?new f$(X,_?.precision,_?.scale):new P$(X,_?.precision,_?.scale)}class b$ extends b{static[F]="PgPointTupleBuilder";constructor(Y){super(Y,"array","PgPointTuple")}build(Y){return new y$(Y,this.config)}}class y$ extends j{static[F]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(Y){if(typeof Y==="string"){let[Z,X]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X)]}return[Y.x,Y.y]}mapToDriverValue(Y){return`(${Y[0]},${Y[1]})`}}class g$ extends b{static[F]="PgPointObjectBuilder";constructor(Y){super(Y,"json","PgPointObject")}build(Y){return new p$(Y,this.config)}}class p$ extends j{static[F]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(Y){if(typeof Y==="string"){let[Z,X]=Y.slice(1,-1).split(",");return{x:Number.parseFloat(Z),y:Number.parseFloat(X)}}return Y}mapToDriverValue(Y){return`(${Y.x},${Y.y})`}}function m$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new b$(X);return new g$(X)}function bF(Y){let Z=[];for(let X=0;X<Y.length;X+=2)Z.push(Number.parseInt(Y.slice(X,X+2),16));return new Uint8Array(Z)}function u$(Y,Z){let X=new ArrayBuffer(8),_=new DataView(X);for(let G=0;G<8;G++)_.setUint8(G,Y[Z+G]);return _.getFloat64(0,!0)}function A5(Y){let Z=bF(Y),X=0,_=Z[X];X+=1;let G=new DataView(Z.buffer),$=G.getUint32(X,_===1);X+=4;let W;if($&536870912)W=G.getUint32(X,_===1),X+=4;if(($&65535)===1){let H=u$(Z,X);X+=8;let Q=u$(Z,X);return X+=8,[H,Q]}throw new Error("Unsupported geometry type")}class d$ extends b{static[F]="PgGeometryBuilder";constructor(Y){super(Y,"array","PgGeometry")}build(Y){return new c$(Y,this.config)}}class c$ extends j{static[F]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){return A5(Y)}mapToDriverValue(Y){return`point(${Y[0]} ${Y[1]})`}}class l$ extends b{static[F]="PgGeometryObjectBuilder";constructor(Y){super(Y,"json","PgGeometryObject")}build(Y){return new o$(Y,this.config)}}class o$ extends j{static[F]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){let Z=A5(Y);return{x:Z[0],y:Z[1]}}mapToDriverValue(Y){return`point(${Y.x} ${Y.y})`}}function i$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new d$(X);return new l$(X)}class r$ extends b{static[F]="PgRealBuilder";constructor(Y,Z){super(Y,"number","PgReal");this.config.length=Z}build(Y){return new n$(Y,this.config)}}class n$ extends j{static[F]="PgReal";constructor(Y,Z){super(Y,Z)}getSQLType(){return"real"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function s$(Y){return new r$(Y??"")}class t$ extends b{static[F]="PgSerialBuilder";constructor(Y){super(Y,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new a$(Y,this.config)}}class a$ extends j{static[F]="PgSerial";getSQLType(){return"serial"}}function e$(Y){return new t$(Y??"")}class YW extends I2{static[F]="PgSmallIntBuilder";constructor(Y){super(Y,"number","PgSmallInt")}build(Y){return new ZW(Y,this.config)}}class ZW extends j{static[F]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number(Y);return Y}}function XW(Y){return new YW(Y??"")}class _W extends b{static[F]="PgSmallSerialBuilder";constructor(Y){super(Y,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new GW(Y,this.config)}}class GW extends j{static[F]="PgSmallSerial";getSQLType(){return"smallserial"}}function $W(Y){return new _W(Y??"")}class WW extends b{static[F]="PgTextBuilder";constructor(Y,Z){super(Y,"string","PgText");this.config.enumValues=Z.enum}build(Y){return new HW(Y,this.config)}}class HW extends j{static[F]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function JW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new WW(X,_)}class QW extends z2{constructor(Y,Z,X){super(Y,"string","PgTime");this.withTimezone=Z,this.precision=X,this.config.withTimezone=Z,this.config.precision=X}static[F]="PgTimeBuilder";build(Y){return new y6(Y,this.config)}}class y6 extends j{static[F]="PgTime";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function zW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new QW(X,_.withTimezone??!1,_.precision)}class UW extends z2{static[F]="PgTimestampBuilder";constructor(Y,Z,X){super(Y,"date","PgTimestamp");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new g6(Y,this.config)}}class g6 extends j{static[F]="PgTimestamp";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(Y)=>{return new Date(this.withTimezone?Y:Y+"+0000")};mapToDriverValue=(Y)=>{return Y.toISOString()}}class FW extends z2{static[F]="PgTimestampStringBuilder";constructor(Y,Z,X){super(Y,"string","PgTimestampString");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new p6(Y,this.config)}}class p6 extends j{static[F]="PgTimestampString";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function EW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="string")return new FW(X,_.withTimezone??!1,_.precision);return new UW(X,_?.withTimezone??!1,_?.precision)}class VW extends b{static[F]="PgUUIDBuilder";constructor(Y){super(Y,"string","PgUUID")}defaultRandom(){return this.default(O`gen_random_uuid()`)}build(Y){return new m6(Y,this.config)}}class m6 extends j{static[F]="PgUUID";getSQLType(){return"uuid"}}function q1(Y){return new VW(Y??"")}class OW extends b{static[F]="PgVarcharBuilder";constructor(Y,Z){super(Y,"string","PgVarchar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new DW(Y,this.config)}}class DW extends j{static[F]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function t0(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new OW(X,_)}class LW extends b{static[F]="PgBinaryVectorBuilder";constructor(Y,Z){super(Y,"string","PgBinaryVector");this.config.dimensions=Z.dimensions}build(Y){return new MW(Y,this.config)}}class MW extends j{static[F]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function AW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new LW(X,_)}class wW extends b{static[F]="PgHalfVectorBuilder";constructor(Y,Z){super(Y,"array","PgHalfVector");this.config.dimensions=Z.dimensions}build(Y){return new RW(Y,this.config)}}class RW extends j{static[F]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){return Y.slice(1,-1).split(",").map((Z)=>Number.parseFloat(Z))}}function NW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new wW(X,_)}class IW extends b{static[F]="PgSparseVectorBuilder";constructor(Y,Z){super(Y,"string","PgSparseVector");this.config.dimensions=Z.dimensions}build(Y){return new KW(Y,this.config)}}class KW extends j{static[F]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function TW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new IW(X,_)}class BW extends b{static[F]="PgVectorBuilder";constructor(Y,Z){super(Y,"array","PgVector");this.config.dimensions=Z.dimensions}build(Y){return new CW(Y,this.config)}}class CW extends j{static[F]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){return Y.slice(1,-1).split(",").map((Z)=>Number.parseFloat(Z))}}function qW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new BW(X,_)}function jW(){return{bigint:g7,bigserial:c7,boolean:R8,char:n7,cidr:a7,customType:Z$,date:G$,doublePrecision:H$,inet:z$,integer:N8,interval:O$,json:L$,jsonb:A$,line:K$,macaddr:C$,macaddr8:S$,numeric:k$,point:m$,geometry:i$,real:s$,serial:e$,smallint:XW,smallserial:$W,text:JW,time:zW,timestamp:EW,uuid:q1,varchar:t0,bit:AW,halfvec:NW,sparsevec:TW,vector:qW}}var w5=Symbol.for("drizzle:PgInlineForeignKeys"),SW=Symbol.for("drizzle:EnableRLS");class u0 extends S{static[F]="PgTable";static Symbol=Object.assign({},S.Symbol,{InlineForeignKeys:w5,EnableRLS:SW});[w5]=[];[SW]=!1;[S.Symbol.ExtraConfigBuilder]=void 0;[S.Symbol.ExtraConfigColumns]={}}function yF(Y,Z,X,_,G=Y){let $=new u0(Y,_,G),W=typeof Z==="function"?Z(jW()):Z,H=Object.fromEntries(Object.entries(W).map(([z,E])=>{let V=E;V.setName(z);let D=V.build($);return $[w5].push(...V.buildForeignKeys(D,$)),[z,D]})),Q=Object.fromEntries(Object.entries(W).map(([z,E])=>{let V=E;V.setName(z);let D=V.buildExtraConfigColumn($);return[z,D]})),J=Object.assign($,H);if(J[S.Symbol.Columns]=H,J[S.Symbol.ExtraConfigColumns]=Q,X)J[u0.Symbol.ExtraConfigBuilder]=X;return Object.assign(J,{enableRLS:()=>{return J[u0.Symbol.EnableRLS]=!0,J}})}var K2=(Y,Z,X)=>{return yF(Y,Z,X,void 0)};function PW(...Y){if(Y[0].columns)return new I8(Y[0].columns,Y[0].name);return new I8(Y)}class I8{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(Y,Z){this.columns=Y,this.name=Z}build(Y){return new vW(Y,this.columns,this.name)}}class vW{constructor(Y,Z,X){this.table=Y,this.columns=Z,this.name=X}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[u0.Symbol.Name]}_${this.columns.map((Y)=>Y.name).join("_")}_pk`}}function O1(Y,Z){if(C7(Z)&&!E5(Y)&&!M(Y,A1)&&!M(Y,N2)&&!M(Y,E0)&&!M(Y,S)&&!M(Y,V1))return new A1(Y,Z);return Y}var u6=(Y,Z)=>{return O`${Y} = ${O1(Z,Y)}`},xW=(Y,Z)=>{return O`${Y} <> ${O1(Z,Y)}`};function K8(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new h(Z);return new h([new m0("("),O.join(Z,new m0(" and ")),new m0(")")])}function fW(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new h(Z);return new h([new m0("("),O.join(Z,new m0(" or ")),new m0(")")])}function hW(Y){return O`not ${Y}`}var kW=(Y,Z)=>{return O`${Y} > ${O1(Z,Y)}`},bW=(Y,Z)=>{return O`${Y} >= ${O1(Z,Y)}`},yW=(Y,Z)=>{return O`${Y} < ${O1(Z,Y)}`},gW=(Y,Z)=>{return O`${Y} <= ${O1(Z,Y)}`};function pW(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return O`false`;return O`${Y} in ${Z.map((X)=>O1(X,Y))}`}return O`${Y} in ${O1(Z,Y)}`}function mW(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return O`true`;return O`${Y} not in ${Z.map((X)=>O1(X,Y))}`}return O`${Y} not in ${O1(Z,Y)}`}function uW(Y){return O`${Y} is null`}function dW(Y){return O`${Y} is not null`}function cW(Y){return O`exists ${Y}`}function lW(Y){return O`not exists ${Y}`}function oW(Y,Z,X){return O`${Y} between ${O1(Z,Y)} and ${O1(X,Y)}`}function iW(Y,Z,X){return O`${Y} not between ${O1(Z,Y)} and ${O1(X,Y)}`}function rW(Y,Z){return O`${Y} like ${Z}`}function nW(Y,Z){return O`${Y} not like ${Z}`}function sW(Y,Z){return O`${Y} ilike ${Z}`}function tW(Y,Z){return O`${Y} not ilike ${Z}`}function aW(Y){return O`${Y} asc`}function eW(Y){return O`${Y} desc`}class R5{constructor(Y,Z,X){this.sourceTable=Y,this.referencedTable=Z,this.relationName=X,this.referencedTableName=Z[S.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName}class Y3{constructor(Y,Z){this.table=Y,this.config=Z}static[F]="Relations"}class T2 extends R5{constructor(Y,Z,X,_){super(Y,Z,X?.relationName);this.config=X,this.isNullable=_}static[F]="One";withFieldName(Y){let Z=new T2(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Z.fieldName=Y,Z}}class T8 extends R5{constructor(Y,Z,X){super(Y,Z,X?.relationName);this.config=X}static[F]="Many";withFieldName(Y){let Z=new T8(this.sourceTable,this.referencedTable,this.config);return Z.fieldName=Y,Z}}function Z3(){return{and:K8,between:oW,eq:u6,exists:cW,gt:kW,gte:bW,ilike:sW,inArray:pW,isNull:uW,isNotNull:dW,like:rW,lt:yW,lte:gW,ne:xW,not:hW,notBetween:iW,notExists:lW,notLike:nW,notIlike:tW,notInArray:mW,or:fW,sql:O}}function X3(){return{sql:O,asc:aW,desc:eW}}function _3(Y,Z){if(Object.keys(Y).length===1&&"default"in Y&&!M(Y.default,S))Y=Y.default;let X={},_={},G={};for(let[$,W]of Object.entries(Y))if(M(W,S)){let H=g2(W),Q=_[H];X[H]=$,G[$]={tsName:$,dbName:W[S.Symbol.Name],schema:W[S.Symbol.Schema],columns:W[S.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let z of Object.values(W[S.Symbol.Columns]))if(z.primary)G[$].primaryKey.push(z);let J=W[S.Symbol.ExtraConfigBuilder]?.(W[S.Symbol.ExtraConfigColumns]);if(J){for(let z of Object.values(J))if(M(z,I8))G[$].primaryKey.push(...z.columns)}}else if(M(W,Y3)){let H=g2(W.table),Q=X[H],J=W.config(Z(W.table)),z;for(let[E,V]of Object.entries(J))if(Q){let D=G[Q];if(D.relations[E]=V,z)D.primaryKey.push(...z)}else{if(!(H in _))_[H]={relations:{},primaryKey:z};_[H].relations[E]=V}}return{tables:G,tableNamesMap:X}}function gF(Y){return function Z(X,_){return new T2(Y,X,_,_?.fields.reduce((G,$)=>G&&$.notNull,!0)??!1)}}function pF(Y){return function Z(X,_){return new T8(Y,X,_)}}function G3(Y,Z,X){if(M(X,T2)&&X.config)return{fields:X.config.fields,references:X.config.references};let _=Z[g2(X.referencedTable)];if(!_)throw new Error(`Table "${X.referencedTable[S.Symbol.Name]}" not found in schema`);let G=Y[_];if(!G)throw new Error(`Table "${_}" not found in schema`);let $=X.sourceTable,W=Z[g2($)];if(!W)throw new Error(`Table "${$[S.Symbol.Name]}" not found in schema`);let H=[];for(let Q of Object.values(G.relations))if(X.relationName&&X!==Q&&Q.relationName===X.relationName||!X.relationName&&Q.referencedTable===X.sourceTable)H.push(Q);if(H.length>1)throw X.relationName?new Error(`There are multiple relations with name "${X.relationName}" in table "${_}"`):new Error(`There are multiple relations between "${_}" and "${X.sourceTable[S.Symbol.Name]}". Please specify relation name`);if(H[0]&&M(H[0],T2)&&H[0].config)return{fields:H[0].config.references,references:H[0].config.fields};throw new Error(`There is not enough information to infer relation "${W}.${X.fieldName}"`)}function $3(Y){return{one:gF(Y),many:pF(Y)}}function d6(Y,Z,X,_,G=($)=>$){let $={};for(let[W,H]of _.entries())if(H.isJson){let Q=Z.relations[H.tsKey],J=X[W],z=typeof J==="string"?JSON.parse(J):J;$[H.tsKey]=M(Q,T2)?z&&d6(Y,Y[H.relationTableTsKey],z,H.selection,G):z.map((E)=>d6(Y,Y[H.relationTableTsKey],E,H.selection,G))}else{let Q=G(X[W]),J=H.field,z;if(M(J,E0))z=J;else if(M(J,h))z=J.decoder;else z=J.sql.decoder;$[H.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return $}import zE from"os";import UE from"fs";var c6=new Map,N5=new Map,I5=Symbol("OriginError"),M4={};class j1 extends Promise{constructor(Y,Z,X,_,G={}){let $,W;super((H,Q)=>{$=H,W=Q});this.tagged=Array.isArray(Y.raw),this.strings=Y,this.args=Z,this.handler=X,this.canceller=_,this.options=G,this.state=null,this.statement=null,this.resolve=(H)=>(this.active=!1,$(H)),this.reject=(H)=>(this.active=!1,W(H)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[I5]=this.handler.debug?new Error:this.tagged&&mF(this.strings)}get origin(){return(this.handler.debug?this[I5].stack:this.tagged&&N5.has(this.strings)?N5.get(this.strings):N5.set(this.strings,this[I5].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(Y=1,Z){if(this.options.simple=!1,typeof Y==="function")Z=Y,Y=1;if(this.cursorRows=Y,typeof Z==="function")return this.cursorFn=Z,this;let X;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};X&&X();let _=new Promise((G,$)=>{this.cursorFn=(W)=>{return G({value:W,done:!1}),new Promise((H)=>X=H)},this.resolve=()=>(this.active=!1,G({done:!0})),this.reject=(W)=>(this.active=!1,$(W))});return this.execute(),_},return(){return X&&X(M4),{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(Y){return this.forEachFn=Y,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 mF(Y){if(c6.has(Y))return c6.get(Y);let Z=Error.stackTraceLimit;return Error.stackTraceLimit=4,c6.set(Y,new Error),Error.stackTraceLimit=Z,c6.get(Y)}class A4 extends Error{constructor(Y){super(Y.message);this.name=this.constructor.name,Object.assign(this,Y)}}var f0={connection:W3,postgres:H3,generic:J3,notSupported:Q3};function W3(Y,Z,X){let{host:_,port:G}=X||Z,$=Object.assign(new Error("write "+Y+" "+(Z.path||_+":"+G)),{code:Y,errno:Y,address:Z.path||_},Z.path?{}:{port:G});return Error.captureStackTrace($,W3),$}function H3(Y){let Z=new A4(Y);return Error.captureStackTrace(Z,H3),Z}function J3(Y,Z){let X=Object.assign(new Error(Y+": "+Z),{code:Y});return Error.captureStackTrace(X,J3),X}function Q3(Y){let Z=Object.assign(new Error(Y+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:Y});return Error.captureStackTrace(Z,Q3),Z}var uF={string:{to:25,from:null,serialize:(Y)=>""+Y},number:{to:0,from:[21,23,26,700,701],serialize:(Y)=>""+Y,parse:(Y)=>+Y},json:{to:114,from:[114,3802],serialize:(Y)=>JSON.stringify(Y),parse:(Y)=>JSON.parse(Y)},boolean:{to:16,from:16,serialize:(Y)=>Y===!0?"t":"f",parse:(Y)=>Y==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(Y)=>(Y instanceof Date?Y:new Date(Y)).toISOString(),parse:(Y)=>new Date(Y)},bytea:{to:17,from:17,serialize:(Y)=>"\\x"+Buffer.from(Y).toString("hex"),parse:(Y)=>Buffer.from(Y.slice(2),"hex")}};class i6{then(){K5()}catch(){K5()}finally(){K5()}}class j8 extends i6{constructor(Y){super();this.value=s6(Y)}}class i1 extends i6{constructor(Y,Z,X){super();this.value=Y,this.type=Z,this.array=X}}class r6 extends i6{constructor(Y,Z){super();this.first=Y,this.rest=Z}build(Y,Z,X,_){let G=dF.map(([$,W])=>({fn:W,i:Y.search($)})).sort(($,W)=>$.i-W.i).pop();return G.i===-1?j5(this.first,_):G.fn(this.first,this.rest,Z,X,_)}}function n6(Y,Z,X,_){let G=Y instanceof i1?Y.value:Y;if(G===void 0){if(Y instanceof i1?Y.value=_.transform.undefined:G=Y=_.transform.undefined,G===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(Y instanceof i1?(Z.push(Y.value),Y.array?Y.array[Y.type||o6(Y.value)]||Y.type||E3(Y.value):Y.type):(Z.push(Y),o6(Y)))}var U3=O3(uF);function C5(Y,Z,X,_,G,$){for(let W=1;W<Y.strings.length;W++)Z+=q5(Z,X,_,G,$)+Y.strings[W],X=Y.args[W];return Z}function q5(Y,Z,X,_,G){return Z instanceof r6?Z.build(Y,X,_,G):Z instanceof j1?B5(Z,X,_,G):Z instanceof j8?Z.value:Z&&Z[0]instanceof j1?Z.reduce(($,W)=>$+" "+B5(W,X,_,G),""):n6(Z,X,_,G)}function B5(Y,Z,X,_){return Y.fragment=!0,C5(Y,Y.strings[0],Y.args[0],Z,X,_)}function F3(Y,Z,X,_,G){return Y.map(($)=>"("+_.map((W)=>q5("values",$[W],Z,X,G)).join(",")+")").join(",")}function z3(Y,Z,X,_,G){let $=Array.isArray(Y[0]),W=Z.length?Z.flat():Object.keys($?Y[0]:Y);return F3($?Y:[Y],X,_,W,G)}function l6(Y,Z,X,_,G){if(typeof Y==="string"&&(Y=[Y].concat(Z)),Array.isArray(Y))return j5(Y,G);let $;return(Z.length?Z.flat():Object.keys(Y)).map((H)=>{return $=Y[H],($ instanceof j1?B5($,X,_,G):$ instanceof j8?$.value:n6($,X,_,G))+" as "+s6(G.transform.column.to?G.transform.column.to(H):H)}).join(",")}var dF=Object.entries({values:z3,in:(...Y)=>{let Z=z3(...Y);return Z==="()"?"(null)":Z},select:l6,as:l6,returning:l6,"\\(":l6,update(Y,Z,X,_,G){return(Z.length?Z.flat():Object.keys(Y)).map(($)=>s6(G.transform.column.to?G.transform.column.to($):$)+"="+q5("values",Y[$],X,_,G))},insert(Y,Z,X,_,G){let $=Z.length?Z.flat():Object.keys(Array.isArray(Y)?Y[0]:Y);return"("+j5($,G)+")values"+F3(Array.isArray(Y)?Y:[Y],X,_,$,G)}}).map(([Y,Z])=>[new RegExp("((?:^|[\\s(])"+Y+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Z]);function K5(){throw f0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:cF,parsers:lF}=U3;function E3(Y){if(Array.isArray(Y))return E3(Y[0]);return typeof Y==="string"?1009:0}var V3=function(Y){let Z=O3(Y||{});return{serializers:Object.assign({},cF,Z.serializers),parsers:Object.assign({},lF,Z.parsers)}};function O3(Y){return Object.keys(Y).reduce((Z,X)=>{if(Y[X].from&&[].concat(Y[X].from).forEach((_)=>Z.parsers[_]=Y[X].parse),Y[X].serialize)Z.serializers[Y[X].to]=Y[X].serialize,Y[X].from&&[].concat(Y[X].from).forEach((_)=>Z.serializers[_]=Y[X].serialize);return Z},{parsers:{},serializers:{}})}function j5(Y,{transform:{column:Z}}){return Y.map((X)=>s6(Z.to?Z.to(X):X)).join(",")}var s6=function Y(Z){return'"'+Z.replace(/"/g,'""').replace(/\./g,'"."')+'"'},o6=function Y(Z){return Z instanceof i1?Z.type:Z instanceof Date?1184:Z instanceof Uint8Array?17:Z===!0||Z===!1?16:typeof Z==="bigint"?20:Array.isArray(Z)?Y(Z[0]):0},oF=/\\/g,iF=/"/g;function rF(Y){return Y.replace(oF,"\\\\").replace(iF,"\\\"")}var D3=function Y(Z,X,_,G){if(Array.isArray(Z)===!1)return Z;if(!Z.length)return"{}";let $=Z[0],W=G===1020?";":",";if(Array.isArray($)&&!$.type)return"{"+Z.map((H)=>Y(H,X,_,G)).join(W)+"}";return"{"+Z.map((H)=>{if(H===void 0){if(H=_.transform.undefined,H===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return H===null?"null":'"'+rF(X?X(H.type?H.value:H):""+H)+'"'}).join(W)+"}"},T5={i:0,char:null,str:"",quoted:!1,last:0},L3=function Y(Z,X,_){return T5.i=T5.last=0,M3(T5,Z,X,_)};function M3(Y,Z,X,_){let G=[],$=_===1020?";":",";for(;Y.i<Z.length;Y.i++){if(Y.char=Z[Y.i],Y.quoted)if(Y.char==="\\")Y.str+=Z[++Y.i];else if(Y.char==='"')G.push(X?X(Y.str):Y.str),Y.str="",Y.quoted=Z[Y.i+1]==='"',Y.last=Y.i+2;else Y.str+=Y.char;else if(Y.char==='"')Y.quoted=!0;else if(Y.char==="{")Y.last=++Y.i,G.push(M3(Y,Z,X,_));else if(Y.char==="}"){Y.quoted=!1,Y.last<Y.i&&G.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;break}else if(Y.char===$&&Y.p!=="}"&&Y.p!=='"')G.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;Y.p=Y.char}return Y.last<Y.i&&G.push(X?X(Z.slice(Y.last,Y.i+1)):Z.slice(Y.last,Y.i+1)),G}var p2=(Y)=>{let Z=Y[0];for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},m2=(Y)=>{let Z=Y[0].toUpperCase();for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},u2=(Y)=>Y.replace(/_/g,"-"),B8=(Y)=>Y.replace(/([A-Z])/g,"_$1").toLowerCase(),C8=(Y)=>(Y.slice(0,1)+Y.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),q8=(Y)=>Y.replace(/-/g,"_");function S5(Y){return function Z(X,_){return typeof X==="object"&&X!==null&&(_.type===114||_.type===3802)?Array.isArray(X)?X.map((G)=>Z(G,_)):Object.entries(X).reduce((G,[$,W])=>Object.assign(G,{[Y($)]:Z(W,_)}),{}):X}}p2.column={from:p2};p2.value={from:S5(p2)};B8.column={to:B8};var P5={...p2};P5.column.to=B8;m2.column={from:m2};m2.value={from:S5(m2)};C8.column={to:C8};var v5={...m2};v5.column.to=C8;u2.column={from:u2};u2.value={from:S5(u2)};q8.column={to:q8};var x5={...u2};x5.column.to=q8;import A3 from"net";import aF from"tls";import S8 from"crypto";import f5 from"stream";import{performance as w3}from"perf_hooks";class d2 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 w1=nF;function nF(Y=[]){let Z=Y.slice(),X=0;return{get length(){return Z.length-X},remove:(_)=>{let G=Z.indexOf(_);return G===-1?null:(Z.splice(G,1),_)},push:(_)=>(Z.push(_),_),shift:()=>{let _=Z[X++];if(X===Z.length)X=0,Z=[];else Z[X-1]=void 0;return _}}}var a0=Buffer.allocUnsafe(256),sF="BCcDdEFfHPpQSX".split("").reduce((Y,Z)=>{let X=Z.charCodeAt(0);return Y[Z]=()=>{return a0[0]=X,z0.i=5,z0},Y},{}),z0=Object.assign(tF,sF,{N:String.fromCharCode(0),i:0,inc(Y){return z0.i+=Y,z0},str(Y){let Z=Buffer.byteLength(Y);return t6(Z),z0.i+=a0.write(Y,z0.i,Z,"utf8"),z0},i16(Y){return t6(2),a0.writeUInt16BE(Y,z0.i),z0.i+=2,z0},i32(Y,Z){if(Z||Z===0)return a0.writeUInt32BE(Y,Z),z0;return t6(4),a0.writeUInt32BE(Y,z0.i),z0.i+=4,z0},z(Y){return t6(Y),a0.fill(0,z0.i,z0.i+Y),z0.i+=Y,z0},raw(Y){return a0=Buffer.concat([a0.subarray(0,z0.i),Y]),z0.i=a0.length,z0},end(Y=1){a0.writeUInt32BE(z0.i-Y,Y);let Z=a0.subarray(0,z0.i);return z0.i=0,a0=Buffer.allocUnsafe(256),Z}}),c=z0;function t6(Y){if(a0.length-z0.i<Y){let Z=a0,X=Z.length;a0=Buffer.allocUnsafe(X+(X>>1)+Y),Z.copy(a0)}}function tF(){return z0.i=0,z0}var b5=I3,eF=1,B2=c().S().end(),R3=c().H().end(),YE=c().i32(8).i32(80877103).end(8),ZE=Buffer.concat([c().E().str(c.N).i32(0).end(),B2]),XE=c().D().str("S").str(c.N).end(),w4=()=>{},_E=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),GE={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 I3(Y,Z={},{onopen:X=w4,onend:_=w4,onclose:G=w4}={}){let{ssl:$,max:W,user:H,host:Q,port:J,database:z,parsers:E,transform:V,onnotice:D,onnotify:R,onparameter:w,max_pipeline:f,keep_alive:v,backoff:k,target_session_attrs:m}=Y,T=w1(),K=eF++,C={pid:null,secret:null},q=k5(UY,Y.idle_timeout),g=k5(UY,Y.max_lifetime),o=k5(o3,Y.connect_timeout),N=null,s,p=new d2,a=Buffer.alloc(0),U0=Y.fetch_types,h0={},W1={},r1=Math.random().toString(36).slice(2),B=1,u=0,G0=0,O0=0,k0=0,t=0,J0=0,v0=0,T0=null,w0=null,o0=!1,D0=null,S1=null,c0=null,U2=null,b0=null,R0=null,P1=null,m1=null,x=null,K4=null,i0={queue:Z.closed,idleTimer:q,connect(U){c0=U,zX()},terminate:B4,execute:T4,cancel:u3,end:UY,count:0,id:K};return Z.closed&&Z.closed.push(i0),i0;async function m3(){let U;try{U=Y.socket?await Promise.resolve(Y.socket(Y)):new A3.Socket}catch(L){i2(L);return}return U.on("error",i2),U.on("close",UX),U.on("drain",JX),U}async function u3({pid:U,secret:L},l,$0){try{s=c().i32(16).i32(80877102).i32(U).i32(L).end(16),await QX(),N.once("error",$0),N.once("close",l)}catch(C0){$0(C0)}}function T4(U){if(o0)return y8(U,f0.connection("CONNECTION_DESTROYED",Y));if(U.cancelled)return;try{return U.state=C,x?T.push(U):(x=U,x.active=!0),l3(U),l0(d3(U))&&!U.describeFirst&&!U.cursorFn&&T.length<f&&(!U.options.onexecute||U.options.onexecute(i0))}catch(L){return T.length===0&&l0(B2),u1(L),!0}}function d3(U){if(U.parameters.length>=65534)throw f0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return U.options.simple?c().Q().str(U.statement.string+c.N).end():U.describeFirst?Buffer.concat([$X(U),R3]):U.prepare?U.prepared?b8(U):Buffer.concat([$X(U),b8(U)]):c3(U)}function $X(U){return Buffer.concat([EX(U.statement.string,U.parameters,U.statement.types,U.statement.name),SH("S",U.statement.name)])}function b8(U){return Buffer.concat([jH(U.parameters,U.statement.types,U.statement.name,U.cursorName),U.cursorFn?VX("",U.cursorRows):ZE])}function c3(U){return Buffer.concat([EX(U.statement.string,U.parameters,U.statement.types),XE,b8(U)])}function l3(U){let L=[],l=[],$0=C5(U,U.strings[0],U.args[0],L,l,Y);!U.tagged&&U.args.forEach((C0)=>n6(C0,L,l,Y)),U.prepare=Y.prepare&&("prepare"in U.options?U.options.prepare:!0),U.string=$0,U.signature=U.prepare&&l+$0,U.onlyDescribe&&delete W1[U.signature],U.parameters=U.parameters||L,U.prepared=U.prepare&&U.signature in W1,U.describeFirst=U.onlyDescribe||L.length&&!U.prepared,U.statement=U.prepared?W1[U.signature]:{string:$0,types:l,name:U.prepare?r1+B++:""},typeof Y.debug==="function"&&Y.debug(K,$0,L,l)}function l0(U,L){if(R0=R0?Buffer.concat([R0,U]):Buffer.from(U),L||R0.length>=1024)return WX(L);return w0===null&&(w0=setImmediate(WX)),!0}function WX(U){let L=N.write(R0,U);return w0!==null&&clearImmediate(w0),R0=w0=null,L}function o3(){u1(f0.connection("CONNECT_TIMEOUT",Y,N)),N.destroy()}async function HX(){if(l0(YE),!await new Promise((L)=>N.once("data",(l)=>L(l[0]===83)))&&$==="prefer")return o2();N.removeAllListeners(),N=aF.connect({socket:N,servername:A3.isIP(N.host)?void 0:N.host,...$==="require"||$==="allow"||$==="prefer"?{rejectUnauthorized:!1}:$==="verify-full"?{}:typeof $==="object"?$:{}}),N.on("secureConnect",o2),N.on("error",i2),N.on("close",UX),N.on("drain",JX)}function JX(){!x&&X(i0)}function zY(U){if(D0){if(D0.push(U),G0-=U.length,G0>0)return}a=D0?Buffer.concat(D0,t-G0):a.length===0?U:Buffer.concat([a,U],a.length+U.length);while(a.length>4){if(t=a.readUInt32BE(1),t>=a.length){G0=t-a.length,D0=[a];break}try{i3(a.subarray(0,t+1))}catch(L){x&&(x.cursorFn||x.describeFirst)&&l0(B2),u1(L)}a=a.subarray(t+1),G0=0,D0=null}}async function QX(){if(o0=!1,h0={},N||(N=await m3()),!N)return;if(o.start(),Y.socket)return $?HX():o2();if(N.on("connect",$?HX:o2),Y.path)return N.connect(Y.path);N.ssl=$,N.connect(J[O0],Q[O0]),N.host=Q[O0],N.port=J[O0],O0=(O0+1)%J.length}function zX(){setTimeout(QX,u?u+J0-w3.now():0)}function o2(){try{W1={},U0=Y.fetch_types,r1=Math.random().toString(36).slice(2),B=1,g.start(),N.on("data",zY),v&&N.setKeepAlive&&N.setKeepAlive(!0,1000*v);let U=vH();l0(U)}catch(U){i2(U)}}function i2(U){if(i0.queue===Z.connecting&&Y.host[k0+1])return;u1(U);while(T.length)y8(T.shift(),U)}function u1(U){b0&&(b0.destroy(U),b0=null),x&&y8(x,U),c0&&(y8(c0,U),c0=null)}function y8(U,L){if(U.reserve)return U.reject(L);if(!L||typeof L!=="object")L=new Error(L);"query"in L||"parameters"in L||Object.defineProperties(L,{stack:{value:L.stack+U.origin.replace(/.*\n/,`
61
+ `),enumerable:Y.debug},query:{value:U.string,enumerable:Y.debug},parameters:{value:U.parameters,enumerable:Y.debug},args:{value:U.args,enumerable:Y.debug},types:{value:U.statement&&U.statement.types,enumerable:Y.debug}}),U.reject(L)}function UY(){return U2||(!i0.reserved&&_(i0),!i0.reserved&&!c0&&!x&&T.length===0?(B4(),new Promise((U)=>N&&N.readyState!=="closed"?N.once("close",U):U())):U2=new Promise((U)=>P1=U))}function B4(){if(o0=!0,b0||x||c0||T.length)i2(f0.connection("CONNECTION_DESTROYED",Y));if(clearImmediate(w0),N)N.removeListener("data",zY),N.removeListener("connect",o2),N.readyState==="open"&&N.end(c().X().end());P1&&(P1(),U2=P1=null)}async function UX(U){if(a=Buffer.alloc(0),G0=0,D0=null,clearImmediate(w0),N.removeListener("data",zY),N.removeListener("connect",o2),q.cancel(),g.cancel(),o.cancel(),N.removeAllListeners(),N=null,c0)return zX();!U&&(x||T.length)&&i2(f0.connection("CONNECTION_CLOSED",Y,N)),u=w3.now(),U&&Y.shared.retries++,J0=(typeof k==="function"?k(Y.shared.retries):k)*1000,G(i0,f0.connection("CONNECTION_CLOSED",Y,N))}function i3(U,L=U[0]){(L===68?r3:L===100?RH:L===65?OH:L===83?n3:L===90?s3:L===67?t3:L===50?FX:L===49?a3:L===116?e3:L===84?YH:L===82?ZH:L===110?HH:L===75?JH:L===69?EH:L===115?DH:L===51?LH:L===71?MH:L===78?IH:L===72?AH:L===99?NH:L===73?KH:L===86?TH:L===118?BH:L===87?wH:CH)(U)}function r3(U){let L=7,l,$0,C0,r0=x.isRaw?new Array(x.statement.columns.length):{};for(let e0=0;e0<x.statement.columns.length;e0++)$0=x.statement.columns[e0],l=U.readInt32BE(L),L+=4,C0=l===-1?null:x.isRaw===!0?U.subarray(L,L+=l):$0.parser===void 0?U.toString("utf8",L,L+=l):$0.parser.array===!0?$0.parser(U.toString("utf8",L+1,L+=l)):$0.parser(U.toString("utf8",L,L+=l)),x.isRaw?r0[e0]=x.isRaw===!0?C0:V.value.from?V.value.from(C0,$0):C0:r0[$0.name]=V.value.from?V.value.from(C0,$0):C0;x.forEachFn?x.forEachFn(V.row.from?V.row.from(r0):r0,p):p[v0++]=V.row.from?V.row.from(r0):r0}function n3(U){let[L,l]=U.toString("utf8",5,U.length-1).split(c.N);if(h0[L]=l,Y.parameters[L]!==l)Y.parameters[L]=l,w&&w(L,l)}function s3(U){if(x&&x.options.simple&&x.resolve(S1||p),x=S1=null,p=new d2,o.cancel(),c0){if(m){if(!h0.in_hot_standby||!h0.default_transaction_read_only)return FH();else if(UH(m,h0))return B4()}if(U0)return c0.reserve&&(c0=null),QH();c0&&!c0.reserve&&T4(c0),Y.shared.retries=k0=0,c0=null;return}while(T.length&&(x=T.shift())&&(x.active=!0,x.cancelled))I3(Y).cancel(x.state,x.cancelled.resolve,x.cancelled.reject);if(x)return;i0.reserved?!i0.reserved.release&&U[5]===73?U2?B4():(i0.reserved=null,X(i0)):i0.reserved():U2?B4():X(i0)}function t3(U){v0=0;for(let L=U.length-1;L>0;L--){if(U[L]===32&&U[L+1]<58&&p.count===null)p.count=+U.toString("utf8",L+1,U.length-1);if(U[L-1]>=65){p.command=U.toString("utf8",5,L),p.state=C;break}}if(K4&&(K4(),K4=null),p.command==="BEGIN"&&W!==1&&!i0.reserved)return u1(f0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(x.options.simple)return FX();if(x.cursorFn)p.count&&x.cursorFn(p),l0(B2);x.resolve(p)}function a3(){x.parsing=!1}function FX(){!p.statement&&(p.statement=x.statement),p.columns=x.statement.columns}function e3(U){let L=U.readUInt16BE(5);for(let l=0;l<L;++l)!x.statement.types[l]&&(x.statement.types[l]=U.readUInt32BE(7+l*4));x.prepare&&(W1[x.signature]=x.statement),x.describeFirst&&!x.onlyDescribe&&(l0(b8(x)),x.describeFirst=!1)}function YH(U){if(p.command)S1=S1||[p],S1.push(p=new d2),p.count=null,x.statement.columns=null;let L=U.readUInt16BE(5),l=7,$0;x.statement.columns=Array(L);for(let C0=0;C0<L;++C0){$0=l;while(U[l++]!==0);let r0=U.readUInt32BE(l),e0=U.readUInt16BE(l+4),F2=U.readUInt32BE(l+6);x.statement.columns[C0]={name:V.column.from?V.column.from(U.toString("utf8",$0,l-1)):U.toString("utf8",$0,l-1),parser:E[F2],table:r0,number:e0,type:F2},l+=18}if(p.statement=x.statement,x.onlyDescribe)return x.resolve(x.statement),l0(B2)}async function ZH(U,L=U.readUInt32BE(5)){(L===3?XH:L===5?_H:L===10?GH:L===11?$H:L===12?WH:L!==0?qH:w4)(U,L)}async function XH(){let U=await FY();l0(c().p().str(U).z(1).end())}async function _H(U){let L="md5"+await N3(Buffer.concat([Buffer.from(await N3(await FY()+H)),U.subarray(9)]));l0(c().p().str(L).z(1).end())}async function GH(){m1=(await S8.randomBytes(18)).toString("base64"),c().p().str("SCRAM-SHA-256"+c.N);let U=c.i;l0(c.inc(4).str("n,,n=*,r="+m1).i32(c.i-U-4,U).end())}async function $H(U){let L=U.toString("utf8",9).split(",").reduce((e0,F2)=>(e0[F2[0]]=F2.slice(2),e0),{}),l=await S8.pbkdf2Sync(await FY(),Buffer.from(L.s,"base64"),parseInt(L.i),32,"sha256"),$0=await a6(l,"Client Key"),C0="n=*,r="+m1+",r="+L.r+",s="+L.s+",i="+L.i+",c=biws,r="+L.r;T0=(await a6(await a6(l,"Server Key"),C0)).toString("base64");let r0="c=biws,r="+L.r+",p="+WE($0,Buffer.from(await a6(await $E($0),C0))).toString("base64");l0(c().p().str(r0).end())}function WH(U){if(U.toString("utf8",9).split(c.N,1)[0].slice(2)===T0)return;u1(f0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),N.destroy()}function FY(){return Promise.resolve(typeof Y.pass==="function"?Y.pass():Y.pass)}function HH(){if(p.statement=x.statement,p.statement.columns=[],x.onlyDescribe)return x.resolve(x.statement),l0(B2)}function JH(U){C.pid=U.readUInt32BE(5),C.secret=U.readUInt32BE(9)}async function QH(){U0=!1,(await new j1([`
62
62
  select b.oid, b.typarray
63
63
  from pg_catalog.pg_type a
64
64
  left join pg_catalog.pg_type b on b.oid = a.typelem
65
65
  where a.typcategory = 'A'
66
66
  group by b.oid, b.typarray
67
67
  order by b.oid
68
- `],[],C4)).forEach(({oid:L,typarray:l})=>QH(L,l))}function QH(z,L){if(!!Y.parsers[L]&&!!Y.serializers[L])return;let l=Y.parsers[z];Y.shared.typeArrayMap[z]=L,Y.parsers[L]=($0)=>D3($0,l,L),Y.parsers[L].array=!0,Y.serializers[L]=($0)=>V3($0,Y.serializers[z],Y,L)}function UH(z,L){return z==="read-write"&&L.default_transaction_read_only==="on"||z==="read-only"&&L.default_transaction_read_only==="off"||z==="primary"&&L.in_hot_standby==="on"||z==="standby"&&L.in_hot_standby==="off"||z==="prefer-standby"&&L.in_hot_standby==="off"&&Y.host[k0]}function zH(){let z=new j1([`
68
+ `],[],T4)).forEach(({oid:L,typarray:l})=>zH(L,l))}function zH(U,L){if(!!Y.parsers[L]&&!!Y.serializers[L])return;let l=Y.parsers[U];Y.shared.typeArrayMap[U]=L,Y.parsers[L]=($0)=>L3($0,l,L),Y.parsers[L].array=!0,Y.serializers[L]=($0)=>D3($0,Y.serializers[U],Y,L)}function UH(U,L){return U==="read-write"&&L.default_transaction_read_only==="on"||U==="read-only"&&L.default_transaction_read_only==="off"||U==="primary"&&L.in_hot_standby==="on"||U==="standby"&&L.in_hot_standby==="off"||U==="prefer-standby"&&L.in_hot_standby==="off"&&Y.host[k0]}function FH(){let U=new j1([`
69
69
  show transaction_read_only;
70
70
  select pg_catalog.pg_is_in_recovery()
71
- `],[],C4,null,{simple:!0});z.resolve=([[L],[l]])=>{h0.default_transaction_read_only=L.transaction_read_only,h0.in_hot_standby=l.pg_is_in_recovery?"on":"off"},z.execute()}function FH(z){x&&(x.cursorFn||x.describeFirst)&&l0(C2);let L=f0.postgres(f5(z));x&&x.retried?u1(x.retried):x&&x.prepared&&XE.has(L.routine)?EH(x,L):u1(L)}function EH(z,L){delete H1[z.signature],z.retried=L,C4(z)}function OH(z){if(!A)return;let L=9;while(z[L++]!==0);A(z.toString("utf8",9,L-1),z.toString("utf8",L,z.length-1))}async function VH(){try{let z=await Promise.resolve(x.cursorFn(p));v0=0,z===w4?l0(SH(x.portal)):(p=new c2,l0(EX("",x.cursorRows)))}catch(z){l0(C2),x.reject(z)}}function DH(){p.count&&x.cursorFn(p),x.resolve(p)}function LH(){b0=new x5.Writable({autoDestroy:!0,write(z,L,l){K.write(c().d().raw(z).end(),l)},destroy(z,L){L(z),K.write(c().f().str(z+c.N).end()),b0=null},final(z){K.write(c().c().end()),B4=z}}),x.resolve(b0)}function MH(){b0=new x5.Readable({read(){K.resume()}}),x.resolve(b0)}function AH(){b0=new x5.Duplex({autoDestroy:!0,read(){K.resume()},write(z,L,l){K.write(c().d().raw(z).end(),l)},destroy(z,L){L(z),K.write(c().f().str(z+c.N).end()),b0=null},final(z){K.write(c().c().end()),B4=z}}),x.resolve(b0)}function wH(z){b0&&(b0.push(z.subarray(5))||K.pause())}function RH(){b0&&b0.push(null),b0=null}function NH(z){D?D(f5(z)):console.log(f5(z))}function IH(){}function TH(){u1(f0.notSupported("FunctionCallResponse"))}function KH(){u1(f0.notSupported("NegotiateProtocolVersion"))}function BH(z){console.error("Postgres.js : Unknown Message:",z[0])}function CH(z,L){console.error("Postgres.js : Unknown Auth:",L)}function qH(z,L,l="",$0=""){let C0,n0;return c().B().str($0+c.N).str(l+c.N).i16(0).i16(z.length),z.forEach((Z1,F2)=>{if(Z1===null)return c.i32(4294967295);n0=L[F2],z[F2]=Z1=n0 in Y.serializers?Y.serializers[n0](Z1):""+Z1,C0=c.i,c.inc(4).str(Z1).i32(c.i-C0-4,C0)}),c.i16(0),c.end()}function FX(z,L,l,$0=""){return c().P().str($0+c.N).str(z+c.N).i16(L.length),L.forEach((C0,n0)=>c.i32(l[n0]||0)),c.end()}function jH(z,L=""){return c().D().str(z).str(L+c.N).end()}function EX(z="",L=0){return Buffer.concat([c().E().str(z+c.N).i32(L).end(),w3])}function SH(z=""){return Buffer.concat([c().C().str("P").str(z+c.N).end(),c().S().end()])}function PH(){return a||c().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:H,database:U,client_encoding:"UTF8"},Y.connection)).filter(([,z])=>z).map(([z,L])=>z+c.N+L).join(c.N)).z(2).end(0)}}function f5(Y){let Z={},X=5;for(let _=5;_<Y.length-1;_++)if(Y[_]===0)Z[_E[Y[X]]]=Y.toString("utf8",X+1,_),X=_+1;return Z}function R3(Y){return P8.createHash("md5").update(Y).digest("hex")}function t6(Y,Z){return P8.createHmac("sha256",Y).update(Z).digest()}function GE(Y){return P8.createHash("sha256").update(Y).digest()}function $E(Y,Z){let X=Math.max(Y.length,Z.length),_=Buffer.allocUnsafe(X);for(let G=0;G<X;G++)_[G]=Y[G]^Z[G];return _}function h5(Y,Z){if(Z=typeof Z==="function"?Z():Z,!Z)return{cancel:N4,start:N4};let X;return{cancel(){X&&(clearTimeout(X),X=null)},start(){X&&clearTimeout(X),X=setTimeout(_,Z*1000,arguments)}};function _(G){Y.apply(null,G),X=null}}var I3=()=>{};function b5(Y,Z){let X=new Map,_="postgresjs_"+Math.random().toString(36).slice(2),G={},$,W,H=!1,Q=F.sql=Y({...Z,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...Z.connection,replication:"database"},onclose:async function(){if(H)return;W=null,G.pid=G.secret=void 0,V(await D(Q,_,Z.publications)),X.forEach((w)=>w.forEach(({onsubscribe:f})=>f()))},no_subscribe:!0}),J=Q.end,U=Q.close;return Q.end=async()=>{return H=!0,W&&await new Promise((w)=>(W.once("close",w),W.end())),J()},Q.close=async()=>{return W&&await new Promise((w)=>(W.once("close",w),W.end())),U()},F;async function F(w,f,v=I3,k=I3){if(w=JE(w),!$)$=D(Q,_,Z.publications);let m={fn:f,onsubscribe:v},T=X.has(w)?X.get(w).add(m):X.set(w,new Set([m])).get(w),I=()=>{T.delete(m),T.size===0&&X.delete(w)};return $.then((q)=>{return V(q),v(),W&&W.on("error",k),{unsubscribe:I,state:G,sql:Q}})}function V(w){W=w.stream,G.pid=w.state.pid,G.secret=w.state.secret}async function D(w,f,v){if(!v)throw new Error("Missing publication names");let k=await w.unsafe(`CREATE_REPLICATION_SLOT ${f} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[m]=k,T=await w.unsafe(`START_REPLICATION SLOT ${f} LOGICAL ${m.consistent_point} (proto_version '1', publication_names '${v}')`).writable(),I={lsn:Buffer.concat(m.consistent_point.split("/").map((K)=>Buffer.from(("00000000"+K).slice(-8),"hex")))};return T.on("data",C),T.on("error",q),T.on("close",w.close),{stream:T,state:k.state};function q(K){console.error("Unexpected error during logical streaming - reconnecting",K)}function C(K){if(K[0]===119)HE(K.subarray(25),I,w.options.parsers,g,Z.transform);else if(K[0]===107&&K[17])I.lsn=K.subarray(1,9),n()}function g(K,a){let p=a.relation.schema+"."+a.relation.table;A("*",K,a),A("*:"+p,K,a),a.relation.keys.length&&A("*:"+p+"="+a.relation.keys.map((e)=>K[e.name]),K,a),A(a.command,K,a),A(a.command+":"+p,K,a),a.relation.keys.length&&A(a.command+":"+p+"="+a.relation.keys.map((e)=>K[e.name]),K,a)}function n(){let K=Buffer.alloc(34);K[0]=114,K.fill(I.lsn,1),K.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),T.write(K)}}function A(w,f,v){X.has(w)&&X.get(w).forEach(({fn:k})=>k(f,v,w))}}function WE(Y){return new Date(Date.UTC(2000,0,1)+Number(Y/BigInt(1000)))}function HE(Y,Z,X,_,G){let $=(W,[H,Q])=>(W[H.charCodeAt(0)]=Q,W);Object.entries({R:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)]={schema:W.toString("utf8",H+=4,H=W.indexOf(0,H))||"pg_catalog",table:W.toString("utf8",H+1,H=W.indexOf(0,H+1)),columns:Array(W.readUInt16BE(H+=2)),keys:[]};H+=2;let J=0,U;while(H<W.length)U=Q.columns[J++]={key:W[H++],name:G.column.from?G.column.from(W.toString("utf8",H,H=W.indexOf(0,H))):W.toString("utf8",H,H=W.indexOf(0,H)),type:W.readUInt32BE(H+=1),parser:X[W.readUInt32BE(H)],atttypmod:W.readUInt32BE(H+=4)},U.key&&Q.keys.push(U),H+=4},Y:()=>{},O:()=>{},B:(W)=>{Z.date=WE(W.readBigInt64BE(9)),Z.lsn=W.subarray(1,9)},I:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)],{row:J}=a6(W,Q.columns,H+=7,G);_(J,{command:"insert",relation:Q})},D:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)];H+=4;let J=W[H]===75;_(J||W[H]===79?a6(W,Q.columns,H+=3,G).row:null,{command:"delete",relation:Q,key:J})},U:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)];H+=4;let J=W[H]===75,U=J||W[H]===79?a6(W,Q.columns,H+=3,G):null;U&&(H=U.i);let{row:F}=a6(W,Q.columns,H+3,G);_(F,{command:"update",relation:Q,key:J,old:U&&U.row})},T:()=>{},C:()=>{}}).reduce($,{})[Y[0]](Y)}function a6(Y,Z,X,_){let G,$,W,H=_.raw?new Array(Z.length):{};for(let Q=0;Q<Z.length;Q++)G=Y[X++],$=Z[Q],W=G===110?null:G===117?void 0:$.parser===void 0?Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X)):$.parser.array===!0?$.parser(Y.toString("utf8",X+5,X+=4+Y.readUInt32BE(X))):$.parser(Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X))),_.raw?H[Q]=_.raw===!0?W:_.value.from?_.value.from(W,$):W:H[$.name]=_.value.from?_.value.from(W,$):W;return{i:X,row:_.row.from?_.row.from(H):H}}function JE(Y){let Z=Y.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!Z)throw new Error("Malformed subscribe pattern: "+Y);let[,X,_,G]=Z;return(X||"*")+(_?":"+(_.indexOf(".")===-1?"public."+_:_):"")+(G?"="+G:"")}import T3 from"stream";function y5(Y,Z,X=393216){return new Promise(async(_,G)=>{await Y.begin(async($)=>{let W;!Z&&([{oid:Z}]=await $`select lo_creat(-1) as oid`);let[{fd:H}]=await $`select lo_open(${Z}, ${X}) as fd`,Q={writable:U,readable:J,close:()=>$`select lo_close(${H})`.then(W),tell:()=>$`select lo_tell64(${H})`,read:(F)=>$`select loread(${H}, ${F}) as data`,write:(F)=>$`select lowrite(${H}, ${F})`,truncate:(F)=>$`select lo_truncate64(${H}, ${F})`,seek:(F,V=0)=>$`select lo_lseek64(${H}, ${F}, ${V})`,size:()=>$`
71
+ `],[],T4,null,{simple:!0});U.resolve=([[L],[l]])=>{h0.default_transaction_read_only=L.transaction_read_only,h0.in_hot_standby=l.pg_is_in_recovery?"on":"off"},U.execute()}function EH(U){x&&(x.cursorFn||x.describeFirst)&&l0(B2);let L=f0.postgres(h5(U));x&&x.retried?u1(x.retried):x&&x.prepared&&_E.has(L.routine)?VH(x,L):u1(L)}function VH(U,L){delete W1[U.signature],U.retried=L,T4(U)}function OH(U){if(!R)return;let L=9;while(U[L++]!==0);R(U.toString("utf8",9,L-1),U.toString("utf8",L,U.length-1))}async function DH(){try{let U=await Promise.resolve(x.cursorFn(p));v0=0,U===M4?l0(PH(x.portal)):(p=new d2,l0(VX("",x.cursorRows)))}catch(U){l0(B2),x.reject(U)}}function LH(){p.count&&x.cursorFn(p),x.resolve(p)}function MH(){b0=new f5.Writable({autoDestroy:!0,write(U,L,l){N.write(c().d().raw(U).end(),l)},destroy(U,L){L(U),N.write(c().f().str(U+c.N).end()),b0=null},final(U){N.write(c().c().end()),K4=U}}),x.resolve(b0)}function AH(){b0=new f5.Readable({read(){N.resume()}}),x.resolve(b0)}function wH(){b0=new f5.Duplex({autoDestroy:!0,read(){N.resume()},write(U,L,l){N.write(c().d().raw(U).end(),l)},destroy(U,L){L(U),N.write(c().f().str(U+c.N).end()),b0=null},final(U){N.write(c().c().end()),K4=U}}),x.resolve(b0)}function RH(U){b0&&(b0.push(U.subarray(5))||N.pause())}function NH(){b0&&b0.push(null),b0=null}function IH(U){D?D(h5(U)):console.log(h5(U))}function KH(){}function TH(){u1(f0.notSupported("FunctionCallResponse"))}function BH(){u1(f0.notSupported("NegotiateProtocolVersion"))}function CH(U){console.error("Postgres.js : Unknown Message:",U[0])}function qH(U,L){console.error("Postgres.js : Unknown Auth:",L)}function jH(U,L,l="",$0=""){let C0,r0;return c().B().str($0+c.N).str(l+c.N).i16(0).i16(U.length),U.forEach((e0,F2)=>{if(e0===null)return c.i32(4294967295);r0=L[F2],U[F2]=e0=r0 in Y.serializers?Y.serializers[r0](e0):""+e0,C0=c.i,c.inc(4).str(e0).i32(c.i-C0-4,C0)}),c.i16(0),c.end()}function EX(U,L,l,$0=""){return c().P().str($0+c.N).str(U+c.N).i16(L.length),L.forEach((C0,r0)=>c.i32(l[r0]||0)),c.end()}function SH(U,L=""){return c().D().str(U).str(L+c.N).end()}function VX(U="",L=0){return Buffer.concat([c().E().str(U+c.N).i32(L).end(),R3])}function PH(U=""){return Buffer.concat([c().C().str("P").str(U+c.N).end(),c().S().end()])}function vH(){return s||c().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:H,database:z,client_encoding:"UTF8"},Y.connection)).filter(([,U])=>U).map(([U,L])=>U+c.N+L).join(c.N)).z(2).end(0)}}function h5(Y){let Z={},X=5;for(let _=5;_<Y.length-1;_++)if(Y[_]===0)Z[GE[Y[X]]]=Y.toString("utf8",X+1,_),X=_+1;return Z}function N3(Y){return S8.createHash("md5").update(Y).digest("hex")}function a6(Y,Z){return S8.createHmac("sha256",Y).update(Z).digest()}function $E(Y){return S8.createHash("sha256").update(Y).digest()}function WE(Y,Z){let X=Math.max(Y.length,Z.length),_=Buffer.allocUnsafe(X);for(let G=0;G<X;G++)_[G]=Y[G]^Z[G];return _}function k5(Y,Z){if(Z=typeof Z==="function"?Z():Z,!Z)return{cancel:w4,start:w4};let X;return{cancel(){X&&(clearTimeout(X),X=null)},start(){X&&clearTimeout(X),X=setTimeout(_,Z*1000,arguments)}};function _(G){Y.apply(null,G),X=null}}var K3=()=>{};function y5(Y,Z){let X=new Map,_="postgresjs_"+Math.random().toString(36).slice(2),G={},$,W,H=!1,Q=E.sql=Y({...Z,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...Z.connection,replication:"database"},onclose:async function(){if(H)return;W=null,G.pid=G.secret=void 0,V(await D(Q,_,Z.publications)),X.forEach((w)=>w.forEach(({onsubscribe:f})=>f()))},no_subscribe:!0}),J=Q.end,z=Q.close;return Q.end=async()=>{return H=!0,W&&await new Promise((w)=>(W.once("close",w),W.end())),J()},Q.close=async()=>{return W&&await new Promise((w)=>(W.once("close",w),W.end())),z()},E;async function E(w,f,v=K3,k=K3){if(w=QE(w),!$)$=D(Q,_,Z.publications);let m={fn:f,onsubscribe:v},T=X.has(w)?X.get(w).add(m):X.set(w,new Set([m])).get(w),K=()=>{T.delete(m),T.size===0&&X.delete(w)};return $.then((C)=>{return V(C),v(),W&&W.on("error",k),{unsubscribe:K,state:G,sql:Q}})}function V(w){W=w.stream,G.pid=w.state.pid,G.secret=w.state.secret}async function D(w,f,v){if(!v)throw new Error("Missing publication names");let k=await w.unsafe(`CREATE_REPLICATION_SLOT ${f} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[m]=k,T=await w.unsafe(`START_REPLICATION SLOT ${f} LOGICAL ${m.consistent_point} (proto_version '1', publication_names '${v}')`).writable(),K={lsn:Buffer.concat(m.consistent_point.split("/").map((N)=>Buffer.from(("00000000"+N).slice(-8),"hex")))};return T.on("data",q),T.on("error",C),T.on("close",w.close),{stream:T,state:k.state};function C(N){console.error("Unexpected error during logical streaming - reconnecting",N)}function q(N){if(N[0]===119)JE(N.subarray(25),K,w.options.parsers,g,Z.transform);else if(N[0]===107&&N[17])K.lsn=N.subarray(1,9),o()}function g(N,s){let p=s.relation.schema+"."+s.relation.table;R("*",N,s),R("*:"+p,N,s),s.relation.keys.length&&R("*:"+p+"="+s.relation.keys.map((a)=>N[a.name]),N,s),R(s.command,N,s),R(s.command+":"+p,N,s),s.relation.keys.length&&R(s.command+":"+p+"="+s.relation.keys.map((a)=>N[a.name]),N,s)}function o(){let N=Buffer.alloc(34);N[0]=114,N.fill(K.lsn,1),N.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),T.write(N)}}function R(w,f,v){X.has(w)&&X.get(w).forEach(({fn:k})=>k(f,v,w))}}function HE(Y){return new Date(Date.UTC(2000,0,1)+Number(Y/BigInt(1000)))}function JE(Y,Z,X,_,G){let $=(W,[H,Q])=>(W[H.charCodeAt(0)]=Q,W);Object.entries({R:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)]={schema:W.toString("utf8",H+=4,H=W.indexOf(0,H))||"pg_catalog",table:W.toString("utf8",H+1,H=W.indexOf(0,H+1)),columns:Array(W.readUInt16BE(H+=2)),keys:[]};H+=2;let J=0,z;while(H<W.length)z=Q.columns[J++]={key:W[H++],name:G.column.from?G.column.from(W.toString("utf8",H,H=W.indexOf(0,H))):W.toString("utf8",H,H=W.indexOf(0,H)),type:W.readUInt32BE(H+=1),parser:X[W.readUInt32BE(H)],atttypmod:W.readUInt32BE(H+=4)},z.key&&Q.keys.push(z),H+=4},Y:()=>{},O:()=>{},B:(W)=>{Z.date=HE(W.readBigInt64BE(9)),Z.lsn=W.subarray(1,9)},I:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)],{row:J}=e6(W,Q.columns,H+=7,G);_(J,{command:"insert",relation:Q})},D:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)];H+=4;let J=W[H]===75;_(J||W[H]===79?e6(W,Q.columns,H+=3,G).row:null,{command:"delete",relation:Q,key:J})},U:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)];H+=4;let J=W[H]===75,z=J||W[H]===79?e6(W,Q.columns,H+=3,G):null;z&&(H=z.i);let{row:E}=e6(W,Q.columns,H+3,G);_(E,{command:"update",relation:Q,key:J,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce($,{})[Y[0]](Y)}function e6(Y,Z,X,_){let G,$,W,H=_.raw?new Array(Z.length):{};for(let Q=0;Q<Z.length;Q++)G=Y[X++],$=Z[Q],W=G===110?null:G===117?void 0:$.parser===void 0?Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X)):$.parser.array===!0?$.parser(Y.toString("utf8",X+5,X+=4+Y.readUInt32BE(X))):$.parser(Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X))),_.raw?H[Q]=_.raw===!0?W:_.value.from?_.value.from(W,$):W:H[$.name]=_.value.from?_.value.from(W,$):W;return{i:X,row:_.row.from?_.row.from(H):H}}function QE(Y){let Z=Y.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!Z)throw new Error("Malformed subscribe pattern: "+Y);let[,X,_,G]=Z;return(X||"*")+(_?":"+(_.indexOf(".")===-1?"public."+_:_):"")+(G?"="+G:"")}import T3 from"stream";function g5(Y,Z,X=393216){return new Promise(async(_,G)=>{await Y.begin(async($)=>{let W;!Z&&([{oid:Z}]=await $`select lo_creat(-1) as oid`);let[{fd:H}]=await $`select lo_open(${Z}, ${X}) as fd`,Q={writable:z,readable:J,close:()=>$`select lo_close(${H})`.then(W),tell:()=>$`select lo_tell64(${H})`,read:(E)=>$`select loread(${H}, ${E}) as data`,write:(E)=>$`select lowrite(${H}, ${E})`,truncate:(E)=>$`select lo_truncate64(${H}, ${E})`,seek:(E,V=0)=>$`select lo_lseek64(${H}, ${E}, ${V})`,size:()=>$`
72
72
  select
73
73
  lo_lseek64(${H}, location, 0) as position,
74
74
  seek.size
@@ -78,10 +78,10 @@ params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrac
78
78
  tell.location
79
79
  from (select lo_tell64($1) as location) tell
80
80
  ) seek
81
- `};return _(Q),new Promise(async(F)=>W=F);async function J({highWaterMark:F=16384,start:V=0,end:D=1/0}={}){let A=D-V;return V&&await Q.seek(V),new T3.Readable({highWaterMark:F,async read(w){let f=w>A?w-A:w;A-=w;let[{data:v}]=await Q.read(f);if(this.push(v),v.length<w)this.push(null)}})}async function U({highWaterMark:F=16384,start:V=0}={}){return V&&await Q.seek(V),new T3.Writable({highWaterMark:F,write(D,A,w){Q.write(D).then(()=>w(),w)}})}}).catch(G)})}Object.assign(e6,{PostgresError:R4,toPascal:u2,pascal:P5,toCamel:m2,camel:S5,toKebab:d2,kebab:v5,fromPascal:q8,fromCamel:C8,fromKebab:j8,BigInt:{to:20,from:[20],parse:(Y)=>BigInt(Y),serialize:(Y)=>Y.toString()}});var I4=e6;function e6(Y,Z){let X=zE(Y,Z),_=X.no_subscribe||b5(e6,{...X}),G=!1,$=N1(),W=N1(),H=N1(),Q=N1(),J=N1(),U=N1(),F=N1(),V=N1(),D={connecting:W,reserved:H,closed:Q,ended:J,open:U,busy:F,full:V},A=[...Array(X.max)].map(()=>k5(X,D,{onopen:H1,onend:h0,onclose:r1})),w=f(g);return Object.assign(w,{get parameters(){return X.parameters},largeObject:y5.bind(null,w),subscribe:_,CLOSE:w4,END:w4,PostgresError:R4,options:X,reserve:m,listen:v,begin:T,close:p,end:a}),w;function f(B){return B.debug=X.debug,Object.entries(X.types).reduce((s,[J0,v0])=>{return s[J0]=(K0)=>new i1(K0,v0.to),s},u),Object.assign(G0,{types:u,typed:u,unsafe:I0,notify:k,array:C,json:q,file:k0}),G0;function u(s,J0){return new i1(s,J0)}function G0(s,...J0){return s&&Array.isArray(s.raw)?new j1(s,J0,B,K):typeof s==="string"&&!J0.length?new S8(X.transform.column.to?X.transform.column.to(s):s):new i6(s,J0)}function I0(s,J0=[],v0={}){return arguments.length===2&&!Array.isArray(J0)&&(v0=J0,J0=[]),new j1([s],J0,B,K,{prepare:!1,...v0,simple:"simple"in v0?v0.simple:J0.length===0})}function k0(s,J0=[],v0={}){return arguments.length===2&&!Array.isArray(J0)&&(v0=J0,J0=[]),new j1([],J0,(A0)=>{UE.readFile(s,"utf8",(i0,V0)=>{if(i0)return A0.reject(i0);A0.strings=[V0],B(A0)})},K,{...v0,simple:"simple"in v0?v0.simple:J0.length===0})}}async function v(B,u,G0){let I0={fn:u,onlisten:G0},k0=v.sql||(v.sql=e6({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(v.channels).forEach(([A0,{listeners:i0}])=>{delete v.channels[A0],Promise.all(i0.map((V0)=>v(A0,V0.fn,V0.onlisten).catch(()=>{})))})},onnotify(A0,i0){A0 in v.channels&&v.channels[A0].listeners.forEach((V0)=>V0.fn(i0))}})),s=v.channels||(v.channels={});if(B in s){s[B].listeners.push(I0);let A0=await s[B].result;return I0.onlisten&&I0.onlisten(),{state:A0.state,unlisten:K0}}s[B]={result:k0`listen ${k0.unsafe('"'+B.replace(/"/g,'""')+'"')}`,listeners:[I0]};let v0=await s[B].result;return I0.onlisten&&I0.onlisten(),{state:v0.state,unlisten:K0};async function K0(){if(B in s===!1)return;if(s[B].listeners=s[B].listeners.filter((A0)=>A0!==I0),s[B].listeners.length)return;return delete s[B],k0`unlisten ${k0.unsafe('"'+B.replace(/"/g,'""')+'"')}`}}async function k(B,u){return await w`select pg_notify(${B}, ${""+u})`}async function m(){let B=N1(),u=U.length?U.shift():await new Promise((k0,s)=>{let J0={reserve:k0,reject:s};$.push(J0),Q.length&&z0(Q.shift(),J0)});I(u,H),u.reserved=()=>B.length?u.execute(B.shift()):I(u,H),u.reserved.release=!0;let G0=f(I0);return G0.release=()=>{u.reserved=null,H1(u)},G0;function I0(k0){u.queue===V?B.push(k0):u.execute(k0)||I(u,V)}}async function T(B,u){!u&&(u=B,B="");let G0=N1(),I0=0,k0,s=null;try{return await w.unsafe("begin "+B.replace(/[^a-z ]/ig,""),[],{onexecute:v0}).execute(),await Promise.race([J0(k0,u),new Promise((K0,A0)=>k0.onclose=A0)])}catch(K0){throw K0}async function J0(K0,A0,i0){let V0=f(b0);V0.savepoint=z2,V0.prepare=(w0)=>s=w0.replace(/[^a-z0-9$-_. ]/gi);let S1,c0;i0&&await V0`savepoint ${V0(i0)}`;try{if(c0=await new Promise((w0,P1)=>{let m1=A0(V0);Promise.resolve(Array.isArray(m1)?Promise.all(m1):m1).then(w0,P1)}),S1)throw S1}catch(w0){throw await(i0?V0`rollback to ${V0(i0)}`:V0`rollback`),w0 instanceof R4&&w0.code==="25P02"&&S1||w0}if(!i0)s?await V0`prepare transaction '${V0.unsafe(s)}'`:await V0`commit`;return c0;function z2(w0,P1){if(w0&&Array.isArray(w0.raw))return z2((m1)=>m1.apply(m1,arguments));return arguments.length===1&&(P1=w0,w0=null),J0(K0,P1,"s"+I0+++(w0?"_"+w0:""))}function b0(w0){w0.catch((P1)=>S1||(S1=P1)),K0.queue===V?G0.push(w0):K0.execute(w0)||I(K0,V)}}function v0(K0){k0=K0,I(K0,H),K0.reserved=()=>G0.length?K0.execute(G0.shift()):I(K0,H)}}function I(B,u){return B.queue.remove(B),u.push(B),B.queue=u,u===U?B.idleTimer.start():B.idleTimer.cancel(),B}function q(B){return new i1(B,3802)}function C(B,u){if(!Array.isArray(B))return C(Array.from(arguments));return new i1(B,u||(B.length?l6(B)||25:0),X.shared.typeArrayMap)}function g(B){if(G)return B.reject(f0.connection("CONNECTION_ENDED",X,X));if(U.length)return n(U.shift(),B);if(Q.length)return z0(Q.shift(),B);F.length?n(F.shift(),B):$.push(B)}function n(B,u){return B.execute(u)?I(B,F):I(B,V)}function K(B){return new Promise((u,G0)=>{B.state?B.active?k5(X).cancel(B.state,u,G0):B.cancelled={resolve:u,reject:G0}:($.remove(B),B.cancelled=!0,B.reject(f0.generic("57014","canceling statement due to user request")),u())})}async function a({timeout:B=null}={}){if(G)return G;await 1;let u;return G=Promise.race([new Promise((G0)=>B!==null&&(u=setTimeout(e,B*1000,G0))),Promise.all(A.map((G0)=>G0.end()).concat(v.sql?v.sql.end({timeout:0}):[],_.sql?_.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(u))}async function p(){await Promise.all(A.map((B)=>B.end()))}async function e(B){await Promise.all(A.map((u)=>u.terminate()));while($.length)$.shift().reject(f0.connection("CONNECTION_DESTROYED",X));B()}function z0(B,u){return I(B,W),B.connect(u),B}function h0(B){I(B,J)}function H1(B){if($.length===0)return I(B,U);let u=Math.ceil($.length/(W.length+1)),G0=!0;while(G0&&$.length&&u-- >0){let I0=$.shift();if(I0.reserve)return I0.reserve(B);G0=B.execute(I0)}G0?I(B,F):I(B,V)}function r1(B,u){I(B,Q),B.reserved=null,B.onclose&&(B.onclose(u),B.onclose=null),X.onclose&&X.onclose(B.id),$.length&&z0(B,$.shift())}}function zE(Y,Z){if(Y&&Y.shared)return Y;let X=process.env,_=(!Y||typeof Y==="string"?Z:Y)||{},{url:G,multihost:$}=DE(Y),W=[...G.searchParams].reduce((V,[D,A])=>(V[D]=A,V),{}),H=_.hostname||_.host||$||G.hostname||X.PGHOST||"localhost",Q=_.port||G.port||X.PGPORT||5432,J=_.user||_.username||G.username||X.PGUSERNAME||X.PGUSER||LE();_.no_prepare&&(_.prepare=!1),W.sslmode&&(W.ssl=W.sslmode,delete W.sslmode),"timeout"in _&&(console.log("The timeout option is deprecated, use idle_timeout instead"),_.idle_timeout=_.timeout),W.sslrootcert==="system"&&(W.ssl="verify-full");let U=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],F={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:OE,max_pipeline:100,backoff:EE,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(H)?H:H.split(",").map((V)=>V.split(":")[0]),port:Array.isArray(Q)?Q:H.split(",").map((V)=>parseInt(V.split(":")[1]||Q)),path:_.path||H.indexOf("/")>-1&&H+"/.s.PGSQL."+Q,database:_.database||_.db||(G.pathname||"").slice(1)||X.PGDATABASE||J,user:J,pass:_.pass||_.password||G.password||X.PGPASSWORD||"",...Object.entries(F).reduce((V,[D,A])=>{let w=D in _?_[D]:(D in W)?W[D]==="disable"||W[D]==="false"?!1:W[D]:X["PG"+D.toUpperCase()]||A;return V[D]=typeof w==="string"&&U.includes(D)?+w:w,V},{}),connection:{application_name:X.PGAPPNAME||"postgres.js",..._.connection,...Object.entries(W).reduce((V,[D,A])=>((D in F)||(V[D]=A),V),{})},types:_.types||{},target_session_attrs:FE(_,G,X),onnotice:_.onnotice,onnotify:_.onnotify,onclose:_.onclose,onparameter:_.onparameter,socket:_.socket,transform:VE(_.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...E3(_.types)}}function FE(Y,Z,X){let _=Y.target_session_attrs||Z.searchParams.get("target_session_attrs")||X.PGTARGETSESSIONATTRS;if(!_||["read-write","read-only","primary","standby","prefer-standby"].includes(_))return _;throw new Error("target_session_attrs "+_+" is not supported")}function EE(Y){return(0.5+Math.random()/2)*Math.min(3**Y/100,20)}function OE(){return 60*(30+Math.random()*30)}function VE(Y){return{undefined:Y.undefined,column:{from:typeof Y.column==="function"?Y.column:Y.column&&Y.column.from,to:Y.column&&Y.column.to},value:{from:typeof Y.value==="function"?Y.value:Y.value&&Y.value.from,to:Y.value&&Y.value.to},row:{from:typeof Y.row==="function"?Y.row:Y.row&&Y.row.from,to:Y.row&&Y.row.to}}}function DE(Y){if(!Y||typeof Y!=="string")return{url:{searchParams:new Map}};let Z=Y;Z=Z.slice(Z.indexOf("://")+3).split(/[?/]/)[0],Z=decodeURIComponent(Z.slice(Z.indexOf("@")+1));let X=new URL(Y.replace(Z,Z.split(",")[0]));return{url:{username:decodeURIComponent(X.username),password:decodeURIComponent(X.password),host:X.host,hostname:X.hostname,port:X.port,pathname:X.pathname,searchParams:X.searchParams},multihost:Z.indexOf(",")>-1&&Z}}function LE(){try{return QE.userInfo().username}catch(Y){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class j0{static[E]="SelectionProxyHandler";config;constructor(Y){this.config={...Y}}get(Y,Z){if(Z==="_")return{...Y._,selectedFields:new Proxy(Y._.selectedFields,this)};if(Z===M0)return{...Y[M0],selectedFields:new Proxy(Y[M0].selectedFields,this)};if(typeof Z==="symbol")return Y[Z];let _=(M(Y,P0)?Y._.selectedFields:M(Y,O1)?Y[M0].selectedFields:Y)[Z];if(M(_,h.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!_.isSelectionField)return _.sql;let G=_.clone();return G.isSelectionField=!0,G}if(M(_,h)){if(this.config.sqlBehavior==="sql")return _;throw new Error(`You tried to reference "${Z}" 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(M(_,E0)){if(this.config.alias)return new Proxy(_,new A4(new Proxy(_.table,new A8(this.config.alias,this.config.replaceOriginalName??!1))));return _}if(typeof _!=="object"||_===null)return _;return new Proxy(_,new j0(this.config))}}class K3{constructor(Y,Z){this.unique=Y,this.name=Z}static[E]="PgIndexBuilderOn";on(...Y){return new YY(Y.map((Z)=>{if(M(Z,h))return Z;Z=Z;let X=new V8(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=JSON.parse(JSON.stringify(Z.defaultConfig)),X}),this.unique,!1,this.name)}onOnly(...Y){return new YY(Y.map((Z)=>{if(M(Z,h))return Z;Z=Z;let X=new V8(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=Z.defaultConfig,X}),this.unique,!0,this.name)}using(Y,...Z){return new YY(Z.map((X)=>{if(M(X,h))return X;X=X;let _=new V8(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),_}),this.unique,!0,this.name,Y)}}class YY{static[E]="PgIndexBuilder";config;constructor(Y,Z,X,_,G="btree"){this.config={name:_,columns:Y,unique:Z,only:X,method:G}}concurrently(){return this.config.concurrently=!0,this}with(Y){return this.config.with=Y,this}where(Y){return this.config.where=Y,this}build(Y){return new B3(this.config,Y)}}class B3{static[E]="PgIndex";config;constructor(Y,Z){this.config={...Y,table:Z}}}function g5(Y){return new K3(!0,Y)}function ME(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function AE(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,_,G)=>{let $=G===0?_.toLowerCase():`${_[0].toUpperCase()}${_.slice(1)}`;return X+$},"")}function wE(Y){return Y}class p5{static[E]="CasingCache";cache={};cachedTables={};convert;constructor(Y){this.convert=Y==="snake_case"?ME:Y==="camelCase"?AE:wE}getColumnCasing(Y){if(!Y.keyAsName)return Y.name;let Z=Y.table[S.Symbol.Schema]??"public",X=Y.table[S.Symbol.OriginalName],_=`${Z}.${X}.${Y.name}`;if(!this.cache[_])this.cacheTable(Y.table);return this.cache[_]}cacheTable(Y){let Z=Y[S.Symbol.Schema]??"public",X=Y[S.Symbol.OriginalName],_=`${Z}.${X}`;if(!this.cachedTables[_]){for(let G of Object.values(Y[S.Symbol.Columns])){let $=`${_}.${G.name}`;this.cache[$]=this.convert(G.name)}this.cachedTables[_]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class v8 extends O1{static[E]="PgViewBase"}class l2{static[E]="PgDialect";casing;constructor(Y){this.casing=new p5(Y?.casing)}async migrate(Y,Z,X){let _=typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",G=typeof X==="string"?"drizzle":X.migrationsSchema??"drizzle",$=O`
81
+ `};return _(Q),new Promise(async(E)=>W=E);async function J({highWaterMark:E=16384,start:V=0,end:D=1/0}={}){let R=D-V;return V&&await Q.seek(V),new T3.Readable({highWaterMark:E,async read(w){let f=w>R?w-R:w;R-=w;let[{data:v}]=await Q.read(f);if(this.push(v),v.length<w)this.push(null)}})}async function z({highWaterMark:E=16384,start:V=0}={}){return V&&await Q.seek(V),new T3.Writable({highWaterMark:E,write(D,R,w){Q.write(D).then(()=>w(),w)}})}}).catch(G)})}Object.assign(YY,{PostgresError:A4,toPascal:m2,pascal:v5,toCamel:p2,camel:P5,toKebab:u2,kebab:x5,fromPascal:C8,fromCamel:B8,fromKebab:q8,BigInt:{to:20,from:[20],parse:(Y)=>BigInt(Y),serialize:(Y)=>Y.toString()}});var R4=YY;function YY(Y,Z){let X=FE(Y,Z),_=X.no_subscribe||y5(YY,{...X}),G=!1,$=w1(),W=w1(),H=w1(),Q=w1(),J=w1(),z=w1(),E=w1(),V=w1(),D={connecting:W,reserved:H,closed:Q,ended:J,open:z,busy:E,full:V},R=[...Array(X.max)].map(()=>b5(X,D,{onopen:W1,onend:h0,onclose:r1})),w=f(g);return Object.assign(w,{get parameters(){return X.parameters},largeObject:g5.bind(null,w),subscribe:_,CLOSE:M4,END:M4,PostgresError:A4,options:X,reserve:m,listen:v,begin:T,close:p,end:s}),w;function f(B){return B.debug=X.debug,Object.entries(X.types).reduce((t,[J0,v0])=>{return t[J0]=(T0)=>new i1(T0,v0.to),t},u),Object.assign(G0,{types:u,typed:u,unsafe:O0,notify:k,array:q,json:C,file:k0}),G0;function u(t,J0){return new i1(t,J0)}function G0(t,...J0){return t&&Array.isArray(t.raw)?new j1(t,J0,B,N):typeof t==="string"&&!J0.length?new j8(X.transform.column.to?X.transform.column.to(t):t):new r6(t,J0)}function O0(t,J0=[],v0={}){return arguments.length===2&&!Array.isArray(J0)&&(v0=J0,J0=[]),new j1([t],J0,B,N,{prepare:!1,...v0,simple:"simple"in v0?v0.simple:J0.length===0})}function k0(t,J0=[],v0={}){return arguments.length===2&&!Array.isArray(J0)&&(v0=J0,J0=[]),new j1([],J0,(w0)=>{UE.readFile(t,"utf8",(o0,D0)=>{if(o0)return w0.reject(o0);w0.strings=[D0],B(w0)})},N,{...v0,simple:"simple"in v0?v0.simple:J0.length===0})}}async function v(B,u,G0){let O0={fn:u,onlisten:G0},k0=v.sql||(v.sql=YY({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(v.channels).forEach(([w0,{listeners:o0}])=>{delete v.channels[w0],Promise.all(o0.map((D0)=>v(w0,D0.fn,D0.onlisten).catch(()=>{})))})},onnotify(w0,o0){w0 in v.channels&&v.channels[w0].listeners.forEach((D0)=>D0.fn(o0))}})),t=v.channels||(v.channels={});if(B in t){t[B].listeners.push(O0);let w0=await t[B].result;return O0.onlisten&&O0.onlisten(),{state:w0.state,unlisten:T0}}t[B]={result:k0`listen ${k0.unsafe('"'+B.replace(/"/g,'""')+'"')}`,listeners:[O0]};let v0=await t[B].result;return O0.onlisten&&O0.onlisten(),{state:v0.state,unlisten:T0};async function T0(){if(B in t===!1)return;if(t[B].listeners=t[B].listeners.filter((w0)=>w0!==O0),t[B].listeners.length)return;return delete t[B],k0`unlisten ${k0.unsafe('"'+B.replace(/"/g,'""')+'"')}`}}async function k(B,u){return await w`select pg_notify(${B}, ${""+u})`}async function m(){let B=w1(),u=z.length?z.shift():await new Promise((k0,t)=>{let J0={reserve:k0,reject:t};$.push(J0),Q.length&&U0(Q.shift(),J0)});K(u,H),u.reserved=()=>B.length?u.execute(B.shift()):K(u,H),u.reserved.release=!0;let G0=f(O0);return G0.release=()=>{u.reserved=null,W1(u)},G0;function O0(k0){u.queue===V?B.push(k0):u.execute(k0)||K(u,V)}}async function T(B,u){!u&&(u=B,B="");let G0=w1(),O0=0,k0,t=null;try{return await w.unsafe("begin "+B.replace(/[^a-z ]/ig,""),[],{onexecute:v0}).execute(),await Promise.race([J0(k0,u),new Promise((T0,w0)=>k0.onclose=w0)])}catch(T0){throw T0}async function J0(T0,w0,o0){let D0=f(b0);D0.savepoint=U2,D0.prepare=(R0)=>t=R0.replace(/[^a-z0-9$-_. ]/gi);let S1,c0;o0&&await D0`savepoint ${D0(o0)}`;try{if(c0=await new Promise((R0,P1)=>{let m1=w0(D0);Promise.resolve(Array.isArray(m1)?Promise.all(m1):m1).then(R0,P1)}),S1)throw S1}catch(R0){throw await(o0?D0`rollback to ${D0(o0)}`:D0`rollback`),R0 instanceof A4&&R0.code==="25P02"&&S1||R0}if(!o0)t?await D0`prepare transaction '${D0.unsafe(t)}'`:await D0`commit`;return c0;function U2(R0,P1){if(R0&&Array.isArray(R0.raw))return U2((m1)=>m1.apply(m1,arguments));return arguments.length===1&&(P1=R0,R0=null),J0(T0,P1,"s"+O0+++(R0?"_"+R0:""))}function b0(R0){R0.catch((P1)=>S1||(S1=P1)),T0.queue===V?G0.push(R0):T0.execute(R0)||K(T0,V)}}function v0(T0){k0=T0,K(T0,H),T0.reserved=()=>G0.length?T0.execute(G0.shift()):K(T0,H)}}function K(B,u){return B.queue.remove(B),u.push(B),B.queue=u,u===z?B.idleTimer.start():B.idleTimer.cancel(),B}function C(B){return new i1(B,3802)}function q(B,u){if(!Array.isArray(B))return q(Array.from(arguments));return new i1(B,u||(B.length?o6(B)||25:0),X.shared.typeArrayMap)}function g(B){if(G)return B.reject(f0.connection("CONNECTION_ENDED",X,X));if(z.length)return o(z.shift(),B);if(Q.length)return U0(Q.shift(),B);E.length?o(E.shift(),B):$.push(B)}function o(B,u){return B.execute(u)?K(B,E):K(B,V)}function N(B){return new Promise((u,G0)=>{B.state?B.active?b5(X).cancel(B.state,u,G0):B.cancelled={resolve:u,reject:G0}:($.remove(B),B.cancelled=!0,B.reject(f0.generic("57014","canceling statement due to user request")),u())})}async function s({timeout:B=null}={}){if(G)return G;await 1;let u;return G=Promise.race([new Promise((G0)=>B!==null&&(u=setTimeout(a,B*1000,G0))),Promise.all(R.map((G0)=>G0.end()).concat(v.sql?v.sql.end({timeout:0}):[],_.sql?_.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(u))}async function p(){await Promise.all(R.map((B)=>B.end()))}async function a(B){await Promise.all(R.map((u)=>u.terminate()));while($.length)$.shift().reject(f0.connection("CONNECTION_DESTROYED",X));B()}function U0(B,u){return K(B,W),B.connect(u),B}function h0(B){K(B,J)}function W1(B){if($.length===0)return K(B,z);let u=Math.ceil($.length/(W.length+1)),G0=!0;while(G0&&$.length&&u-- >0){let O0=$.shift();if(O0.reserve)return O0.reserve(B);G0=B.execute(O0)}G0?K(B,E):K(B,V)}function r1(B,u){K(B,Q),B.reserved=null,B.onclose&&(B.onclose(u),B.onclose=null),X.onclose&&X.onclose(B.id),$.length&&U0(B,$.shift())}}function FE(Y,Z){if(Y&&Y.shared)return Y;let X=process.env,_=(!Y||typeof Y==="string"?Z:Y)||{},{url:G,multihost:$}=LE(Y),W=[...G.searchParams].reduce((V,[D,R])=>(V[D]=R,V),{}),H=_.hostname||_.host||$||G.hostname||X.PGHOST||"localhost",Q=_.port||G.port||X.PGPORT||5432,J=_.user||_.username||G.username||X.PGUSERNAME||X.PGUSER||ME();_.no_prepare&&(_.prepare=!1),W.sslmode&&(W.ssl=W.sslmode,delete W.sslmode),"timeout"in _&&(console.log("The timeout option is deprecated, use idle_timeout instead"),_.idle_timeout=_.timeout),W.sslrootcert==="system"&&(W.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],E={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:OE,max_pipeline:100,backoff:VE,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(H)?H:H.split(",").map((V)=>V.split(":")[0]),port:Array.isArray(Q)?Q:H.split(",").map((V)=>parseInt(V.split(":")[1]||Q)),path:_.path||H.indexOf("/")>-1&&H+"/.s.PGSQL."+Q,database:_.database||_.db||(G.pathname||"").slice(1)||X.PGDATABASE||J,user:J,pass:_.pass||_.password||G.password||X.PGPASSWORD||"",...Object.entries(E).reduce((V,[D,R])=>{let w=D in _?_[D]:(D in W)?W[D]==="disable"||W[D]==="false"?!1:W[D]:X["PG"+D.toUpperCase()]||R;return V[D]=typeof w==="string"&&z.includes(D)?+w:w,V},{}),connection:{application_name:X.PGAPPNAME||"postgres.js",..._.connection,...Object.entries(W).reduce((V,[D,R])=>((D in E)||(V[D]=R),V),{})},types:_.types||{},target_session_attrs:EE(_,G,X),onnotice:_.onnotice,onnotify:_.onnotify,onclose:_.onclose,onparameter:_.onparameter,socket:_.socket,transform:DE(_.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...V3(_.types)}}function EE(Y,Z,X){let _=Y.target_session_attrs||Z.searchParams.get("target_session_attrs")||X.PGTARGETSESSIONATTRS;if(!_||["read-write","read-only","primary","standby","prefer-standby"].includes(_))return _;throw new Error("target_session_attrs "+_+" is not supported")}function VE(Y){return(0.5+Math.random()/2)*Math.min(3**Y/100,20)}function OE(){return 60*(30+Math.random()*30)}function DE(Y){return{undefined:Y.undefined,column:{from:typeof Y.column==="function"?Y.column:Y.column&&Y.column.from,to:Y.column&&Y.column.to},value:{from:typeof Y.value==="function"?Y.value:Y.value&&Y.value.from,to:Y.value&&Y.value.to},row:{from:typeof Y.row==="function"?Y.row:Y.row&&Y.row.from,to:Y.row&&Y.row.to}}}function LE(Y){if(!Y||typeof Y!=="string")return{url:{searchParams:new Map}};let Z=Y;Z=Z.slice(Z.indexOf("://")+3).split(/[?/]/)[0],Z=decodeURIComponent(Z.slice(Z.indexOf("@")+1));let X=new URL(Y.replace(Z,Z.split(",")[0]));return{url:{username:decodeURIComponent(X.username),password:decodeURIComponent(X.password),host:X.host,hostname:X.hostname,port:X.port,pathname:X.pathname,searchParams:X.searchParams},multihost:Z.indexOf(",")>-1&&Z}}function ME(){try{return zE.userInfo().username}catch(Y){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class q0{static[F]="SelectionProxyHandler";config;constructor(Y){this.config={...Y}}get(Y,Z){if(Z==="_")return{...Y._,selectedFields:new Proxy(Y._.selectedFields,this)};if(Z===A0)return{...Y[A0],selectedFields:new Proxy(Y[A0].selectedFields,this)};if(typeof Z==="symbol")return Y[Z];let _=(M(Y,P0)?Y._.selectedFields:M(Y,V1)?Y[A0].selectedFields:Y)[Z];if(M(_,h.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!_.isSelectionField)return _.sql;let G=_.clone();return G.isSelectionField=!0,G}if(M(_,h)){if(this.config.sqlBehavior==="sql")return _;throw new Error(`You tried to reference "${Z}" 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(M(_,E0)){if(this.config.alias)return new Proxy(_,new L4(new Proxy(_.table,new M8(this.config.alias,this.config.replaceOriginalName??!1))));return _}if(typeof _!=="object"||_===null)return _;return new Proxy(_,new q0(this.config))}}class B3{constructor(Y,Z){this.unique=Y,this.name=Z}static[F]="PgIndexBuilderOn";on(...Y){return new ZY(Y.map((Z)=>{if(M(Z,h))return Z;Z=Z;let X=new V8(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=JSON.parse(JSON.stringify(Z.defaultConfig)),X}),this.unique,!1,this.name)}onOnly(...Y){return new ZY(Y.map((Z)=>{if(M(Z,h))return Z;Z=Z;let X=new V8(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=Z.defaultConfig,X}),this.unique,!0,this.name)}using(Y,...Z){return new ZY(Z.map((X)=>{if(M(X,h))return X;X=X;let _=new V8(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),_}),this.unique,!0,this.name,Y)}}class ZY{static[F]="PgIndexBuilder";config;constructor(Y,Z,X,_,G="btree"){this.config={name:_,columns:Y,unique:Z,only:X,method:G}}concurrently(){return this.config.concurrently=!0,this}with(Y){return this.config.with=Y,this}where(Y){return this.config.where=Y,this}build(Y){return new C3(this.config,Y)}}class C3{static[F]="PgIndex";config;constructor(Y,Z){this.config={...Y,table:Z}}}function p5(Y){return new B3(!0,Y)}function AE(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function wE(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,_,G)=>{let $=G===0?_.toLowerCase():`${_[0].toUpperCase()}${_.slice(1)}`;return X+$},"")}function RE(Y){return Y}class m5{static[F]="CasingCache";cache={};cachedTables={};convert;constructor(Y){this.convert=Y==="snake_case"?AE:Y==="camelCase"?wE:RE}getColumnCasing(Y){if(!Y.keyAsName)return Y.name;let Z=Y.table[S.Symbol.Schema]??"public",X=Y.table[S.Symbol.OriginalName],_=`${Z}.${X}.${Y.name}`;if(!this.cache[_])this.cacheTable(Y.table);return this.cache[_]}cacheTable(Y){let Z=Y[S.Symbol.Schema]??"public",X=Y[S.Symbol.OriginalName],_=`${Z}.${X}`;if(!this.cachedTables[_]){for(let G of Object.values(Y[S.Symbol.Columns])){let $=`${_}.${G.name}`;this.cache[$]=this.convert(G.name)}this.cachedTables[_]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class P8 extends V1{static[F]="PgViewBase"}class c2{static[F]="PgDialect";casing;constructor(Y){this.casing=new m5(Y?.casing)}async migrate(Y,Z,X){let _=typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",G=typeof X==="string"?"drizzle":X.migrationsSchema??"drizzle",$=O`
82
82
  CREATE TABLE IF NOT EXISTS ${O.identifier(G)}.${O.identifier(_)} (
83
83
  id SERIAL PRIMARY KEY,
84
84
  hash text NOT NULL,
85
85
  created_at bigint
86
86
  )
87
- `;await Z.execute(O`CREATE SCHEMA IF NOT EXISTS ${O.identifier(G)}`),await Z.execute($);let H=(await Z.all(O`select id, hash, created_at from ${O.identifier(G)}.${O.identifier(_)} order by created_at desc limit 1`))[0];await Z.transaction(async(Q)=>{for await(let J of Y)if(!H||Number(H.created_at)<J.folderMillis){for(let U of J.sql)await Q.execute(O.raw(U));await Q.execute(O`insert into ${O.identifier(G)}.${O.identifier(_)} ("hash", "created_at") values(${J.hash}, ${J.folderMillis})`)}})}escapeName(Y){return`"${Y}"`}escapeParam(Y){return`$${Y+1}`}escapeString(Y){return`'${Y.replace(/'/g,"''")}'`}buildWithCTE(Y){if(!Y?.length)return;let Z=[O`with `];for(let[X,_]of Y.entries())if(Z.push(O`${O.identifier(_._.alias)} as (${_._.sql})`),X<Y.length-1)Z.push(O`, `);return Z.push(O` `),O.join(Z)}buildDeleteQuery({table:Y,where:Z,returning:X,withList:_}){let G=this.buildWithCTE(_),$=X?O` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,W=Z?O` where ${Z}`:void 0;return O`${G}delete from ${Y}${W}${$}`}buildUpdateSet(Y,Z){let X=Y[S.Symbol.Columns],_=Object.keys(X).filter(($)=>Z[$]!==void 0||X[$]?.onUpdateFn!==void 0),G=_.length;return O.join(_.flatMap(($,W)=>{let H=X[$],Q=Z[$]??O.param(H.onUpdateFn(),H),J=O`${O.identifier(this.casing.getColumnCasing(H))} = ${Q}`;if(W<G-1)return[J,O.raw(", ")];return[J]}))}buildUpdateQuery({table:Y,set:Z,where:X,returning:_,withList:G,from:$,joins:W}){let H=this.buildWithCTE(G),Q=Y[u0.Symbol.Name],J=Y[u0.Symbol.Schema],U=Y[u0.Symbol.OriginalName],F=Q===U?void 0:Q,V=O`${J?O`${O.identifier(J)}.`:void 0}${O.identifier(U)}${F&&O` ${O.identifier(F)}`}`,D=this.buildUpdateSet(Y,Z),A=$&&O.join([O.raw(" from "),this.buildFromTable($)]),w=this.buildJoins(W),f=_?O` returning ${this.buildSelection(_,{isSingleTable:!$})}`:void 0,v=X?O` where ${X}`:void 0;return O`${H}update ${V} set ${D}${A}${w}${v}${f}`}buildSelection(Y,{isSingleTable:Z=!1}={}){let X=Y.length,_=Y.flatMap(({field:G},$)=>{let W=[];if(M(G,h.Aliased)&&G.isSelectionField)W.push(O.identifier(G.fieldAlias));else if(M(G,h.Aliased)||M(G,h)){let H=M(G,h.Aliased)?G.sql:G;if(Z)W.push(new h(H.queryChunks.map((Q)=>{if(M(Q,j))return O.identifier(this.casing.getColumnCasing(Q));return Q})));else W.push(H);if(M(G,h.Aliased))W.push(O` as ${O.identifier(G.fieldAlias)}`)}else if(M(G,E0))if(Z)W.push(O.identifier(this.casing.getColumnCasing(G)));else W.push(G);if($<X-1)W.push(O`, `);return W});return O.join(_)}buildJoins(Y){if(!Y||Y.length===0)return;let Z=[];for(let[X,_]of Y.entries()){if(X===0)Z.push(O` `);let G=_.table,$=_.lateral?O` lateral`:void 0,W=_.on?O` on ${_.on}`:void 0;if(M(G,u0)){let H=G[u0.Symbol.Name],Q=G[u0.Symbol.Schema],J=G[u0.Symbol.OriginalName],U=H===J?void 0:_.alias;Z.push(O`${O.raw(_.joinType)} join${$} ${Q?O`${O.identifier(Q)}.`:void 0}${O.identifier(J)}${U&&O` ${O.identifier(U)}`}${W}`)}else if(M(G,O1)){let H=G[M0].name,Q=G[M0].schema,J=G[M0].originalName,U=H===J?void 0:_.alias;Z.push(O`${O.raw(_.joinType)} join${$} ${Q?O`${O.identifier(Q)}.`:void 0}${O.identifier(J)}${U&&O` ${O.identifier(U)}`}${W}`)}else Z.push(O`${O.raw(_.joinType)} join${$} ${G}${W}`);if(X<Y.length-1)Z.push(O` `)}return O.join(Z)}buildFromTable(Y){if(M(Y,S)&&Y[S.Symbol.IsAlias]){let Z=O`${O.identifier(Y[S.Symbol.OriginalName])}`;if(Y[S.Symbol.Schema])Z=O`${O.identifier(Y[S.Symbol.Schema])}.${Z}`;return O`${Z} ${O.identifier(Y[S.Symbol.Name])}`}return Y}buildSelectQuery({withList:Y,fields:Z,fieldsFlat:X,where:_,having:G,table:$,joins:W,orderBy:H,groupBy:Q,limit:J,offset:U,lockingClause:F,distinct:V,setOperators:D}){let A=X??C1(Z);for(let e of A)if(M(e.field,E0)&&d0(e.field.table)!==(M($,P0)?$._.alias:M($,v8)?$[M0].name:M($,h)?void 0:d0($))&&!((z0)=>W?.some(({alias:h0})=>h0===(z0[S.Symbol.IsAlias]?d0(z0):z0[S.Symbol.BaseName])))(e.field.table)){let z0=d0(e.field.table);throw new Error(`Your "${e.path.join("->")}" field references a column "${z0}"."${e.field.name}", but the table "${z0}" is not part of the query! Did you forget to join it?`)}let w=!W||W.length===0,f=this.buildWithCTE(Y),v;if(V)v=V===!0?O` distinct`:O` distinct on (${O.join(V.on,O`, `)})`;let k=this.buildSelection(A,{isSingleTable:w}),m=this.buildFromTable($),T=this.buildJoins(W),I=_?O` where ${_}`:void 0,q=G?O` having ${G}`:void 0,C;if(H&&H.length>0)C=O` order by ${O.join(H,O`, `)}`;let g;if(Q&&Q.length>0)g=O` group by ${O.join(Q,O`, `)}`;let n=typeof J==="object"||typeof J==="number"&&J>=0?O` limit ${J}`:void 0,K=U?O` offset ${U}`:void 0,a=O.empty();if(F){let e=O` for ${O.raw(F.strength)}`;if(F.config.of)e.append(O` of ${O.join(Array.isArray(F.config.of)?F.config.of:[F.config.of],O`, `)}`);if(F.config.noWait)e.append(O` nowait`);else if(F.config.skipLocked)e.append(O` skip locked`);a.append(e)}let p=O`${f}select${v} ${k} from ${m}${T}${I}${g}${q}${C}${n}${K}${a}`;if(D.length>0)return this.buildSetOperations(p,D);return p}buildSetOperations(Y,Z){let[X,..._]=Z;if(!X)throw new Error("Cannot pass undefined values to any set operator");if(_.length===0)return this.buildSetOperationQuery({leftSelect:Y,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:Y,setOperator:X}),_)}buildSetOperationQuery({leftSelect:Y,setOperator:{type:Z,isAll:X,rightSelect:_,limit:G,orderBy:$,offset:W}}){let H=O`(${Y.getSQL()}) `,Q=O`(${_.getSQL()})`,J;if($&&$.length>0){let D=[];for(let A of $)if(M(A,j))D.push(O.identifier(A.name));else if(M(A,h)){for(let w=0;w<A.queryChunks.length;w++){let f=A.queryChunks[w];if(M(f,j))A.queryChunks[w]=O.identifier(f.name)}D.push(O`${A}`)}else D.push(O`${A}`);J=O` order by ${O.join(D,O`, `)} `}let U=typeof G==="object"||typeof G==="number"&&G>=0?O` limit ${G}`:void 0,F=O.raw(`${Z} ${X?"all ":""}`),V=W?O` offset ${W}`:void 0;return O`${H}${F}${Q}${J}${U}${V}`}buildInsertQuery({table:Y,values:Z,onConflict:X,returning:_,withList:G,select:$,overridingSystemValue_:W}){let H=[],Q=Y[S.Symbol.Columns],J=Object.entries(Q).filter(([f,v])=>!v.shouldDisableInsert()),U=J.map(([,f])=>O.identifier(this.casing.getColumnCasing(f)));if($){let f=Z;if(M(f,h))H.push(f);else H.push(f.getSQL())}else{let f=Z;H.push(O.raw("values "));for(let[v,k]of f.entries()){let m=[];for(let[T,I]of J){let q=k[T];if(q===void 0||M(q,R1)&&q.value===void 0)if(I.defaultFn!==void 0){let C=I.defaultFn(),g=M(C,h)?C:O.param(C,I);m.push(g)}else if(!I.default&&I.onUpdateFn!==void 0){let C=I.onUpdateFn(),g=M(C,h)?C:O.param(C,I);m.push(g)}else m.push(O`default`);else m.push(q)}if(H.push(m),v<f.length-1)H.push(O`, `)}}let F=this.buildWithCTE(G),V=O.join(H),D=_?O` returning ${this.buildSelection(_,{isSingleTable:!0})}`:void 0,A=X?O` on conflict ${X}`:void 0,w=W===!0?O`overriding system value `:void 0;return O`${F}insert into ${Y} ${U} ${w}${V}${A}${D}`}buildRefreshMaterializedViewQuery({view:Y,concurrently:Z,withNoData:X}){let _=Z?O` concurrently`:void 0,G=X?O` with no data`:void 0;return O`refresh materialized view${_} ${Y}${G}`}prepareTyping(Y){if(M(Y,h6)||M(Y,f6))return"json";else if(M(Y,k6))return"decimal";else if(M(Y,b6))return"time";else if(M(Y,y6)||M(Y,g6))return"timestamp";else if(M(Y,v6)||M(Y,x6))return"date";else if(M(Y,p6))return"uuid";else return"none"}sqlToQuery(Y,Z){return Y.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:Z})}buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:_,tableConfig:G,queryConfig:$,tableAlias:W,nestedQueryRelation:H,joinOn:Q}){let J=[],U,F,V=[],D,A=[];if($===!0)J=Object.entries(G.columns).map(([v,k])=>({dbKey:k.name,tsKey:v,field:o1(k,W),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let f=Object.fromEntries(Object.entries(G.columns).map(([q,C])=>[q,o1(C,W)]));if($.where){let q=typeof $.where==="function"?$.where(f,Y3()):$.where;D=q&&w8(q,W)}let v=[],k=[];if($.columns){let q=!1;for(let[C,g]of Object.entries($.columns)){if(g===void 0)continue;if(C in G.columns){if(!q&&g===!0)q=!0;k.push(C)}}if(k.length>0)k=q?k.filter((C)=>$.columns?.[C]===!0):Object.keys(G.columns).filter((C)=>!k.includes(C))}else k=Object.keys(G.columns);for(let q of k){let C=G.columns[q];v.push({tsKey:q,value:C})}let m=[];if($.with)m=Object.entries($.with).filter((q)=>!!q[1]).map(([q,C])=>({tsKey:q,queryConfig:C,relation:G.relations[q]}));let T;if($.extras){T=typeof $.extras==="function"?$.extras(f,{sql:O}):$.extras;for(let[q,C]of Object.entries(T))v.push({tsKey:q,value:O5(C,W)})}for(let{tsKey:q,value:C}of v)J.push({dbKey:M(C,h.Aliased)?C.fieldAlias:G.columns[q].name,tsKey:q,field:M(C,E0)?o1(C,W):C,relationTableTsKey:void 0,isJson:!1,selection:[]});let I=typeof $.orderBy==="function"?$.orderBy(f,Z3()):$.orderBy??[];if(!Array.isArray(I))I=[I];V=I.map((q)=>{if(M(q,E0))return o1(q,W);return w8(q,W)}),U=$.limit,F=$.offset;for(let{tsKey:q,queryConfig:C,relation:g}of m){let n=_3(Z,X,g),K=p2(g.referencedTable),a=X[K],p=`${W}_${q}`,e=K8(...n.fields.map((H1,r1)=>m6(o1(n.references[r1],p),o1(H1,W)))),z0=this.buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:Y[a],tableConfig:Z[a],queryConfig:M(g,B2)?C===!0?{limit:1}:{...C,limit:1}:C,tableAlias:p,joinOn:e,nestedQueryRelation:g}),h0=O`${O.identifier(p)}.${O.identifier("data")}`.as(q);A.push({on:O`true`,table:new P0(z0.sql,{},p),alias:p,joinType:"left",lateral:!0}),J.push({dbKey:q,tsKey:q,field:h0,relationTableTsKey:a,isJson:!0,selection:z0.selection})}}if(J.length===0)throw new S6({message:`No fields selected for table "${G.tsName}" ("${W}")`});let w;if(D=K8(Q,D),H){let f=O`json_build_array(${O.join(J.map(({field:m,tsKey:T,isJson:I})=>I?O`${O.identifier(`${W}_${T}`)}.${O.identifier("data")}`:M(m,h.Aliased)?m.sql:m),O`, `)})`;if(M(H,B8))f=O`coalesce(json_agg(${f}${V.length>0?O` order by ${O.join(V,O`, `)}`:void 0}), '[]'::json)`;let v=[{dbKey:"data",tsKey:"data",field:f.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:J}];if(U!==void 0||F!==void 0||V.length>0)w=this.buildSelectQuery({table:j6(_,W),fields:{},fieldsFlat:[{path:[],field:O.raw("*")}],where:D,limit:U,offset:F,orderBy:V,setOperators:[]}),D=void 0,U=void 0,F=void 0,V=[];else w=j6(_,W);w=this.buildSelectQuery({table:M(w,u0)?w:new P0(w,{},W),fields:{},fieldsFlat:v.map(({field:m})=>({path:[],field:M(m,E0)?o1(m,W):m})),joins:A,where:D,limit:U,offset:F,orderBy:V,setOperators:[]})}else w=this.buildSelectQuery({table:j6(_,W),fields:{},fieldsFlat:J.map(({field:f})=>({path:[],field:M(f,E0)?o1(f,W):f})),joins:A,where:D,limit:U,offset:F,orderBy:V,setOperators:[]});return{tableTsKey:G.tsName,sql:w,selection:J}}}class m5{static[E]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class W1{static[E]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(Y){if(this.fields=Y.fields,this.session=Y.session,this.dialect=Y.dialect,Y.withList)this.withList=Y.withList;this.distinct=Y.distinct}authToken;setToken(Y){return this.authToken=Y,this}from(Y){let Z=!!this.fields,X=Y,_;if(this.fields)_=this.fields;else if(M(X,P0))_=Object.fromEntries(Object.keys(X._.selectedFields).map((G)=>[G,X[G]]));else if(M(X,v8))_=X[M0].selectedFields;else if(M(X,h))_={};else _=v7(X);return new u5({table:X,fields:_,isPartialSelect:Z,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class C3 extends m5{static[E]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:Y,fields:Z,isPartialSelect:X,session:_,dialect:G,withList:$,distinct:W}){super();this.config={withList:$,table:Y,fields:{...Z},distinct:W,setOperators:[]},this.isPartialSelect=X,this.session=_,this.dialect=G,this._={selectedFields:Z,config:this.config},this.tableName=Q2(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let H of p1(Y))this.usedTables.add(H)}getUsedTables(){return[...this.usedTables]}createJoin(Y,Z){return(X,_)=>{let G=this.tableName,$=Q2(X);for(let W of p1(X))this.usedTables.add(W);if(typeof $==="string"&&this.config.joins?.some((W)=>W.alias===$))throw new Error(`Alias "${$}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof G==="string")this.config.fields={[G]:this.config.fields};if(typeof $==="string"&&!M(X,h)){let W=M(X,P0)?X._.selectedFields:M(X,O1)?X[M0].selectedFields:X[S.Symbol.Columns];this.config.fields[$]=W}}if(typeof _==="function")_=_(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:_,table:X,joinType:Y,alias:$,lateral:Z}),typeof $==="string")switch(Y){case"left":{this.joinsNotNullableMap[$]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([W])=>[W,!1])),this.joinsNotNullableMap[$]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[$]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([W])=>[W,!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(Y,Z){return(X)=>{let _=typeof X==="function"?X(RE()):X;if(!R8(this.getSelectedFields(),_.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:Y,isAll:Z,rightSelect:_}),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(Y){return this.config.setOperators.push(...Y),this}where(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=Y,this}having(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=Y,this}groupBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(Z)?Z:[Z]}else this.config.groupBy=Y;return this}orderBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray(Z)?Z:[Z];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=X;else this.config.orderBy=X}else{let Z=Y;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Z;else this.config.orderBy=Z}return this}limit(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=Y;else this.config.limit=Y;return this}offset(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=Y;else this.config.offset=Y;return this}for(Y,Z={}){return this.config.lockingClause={strength:Y,config:Z},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}as(Y){let Z=[];if(Z.push(...p1(this.config.table)),this.config.joins)for(let X of this.config.joins)Z.push(...p1(X.table));return new Proxy(new P0(this.getSQL(),this.config.fields,Y,!1,[...new Set(Z)]),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new j0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(Y){return this.cacheConfig=Y===void 0?{config:{},enable:!0,autoInvalidate:!0}:Y===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...Y},this}}class u5 extends C3{static[E]="PgSelect";_prepare(Y){let{session:Z,config:X,dialect:_,joinsNotNullableMap:G,authToken:$,cacheConfig:W,usedTables:H}=this;if(!Z)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:Q}=X;return O0.startActiveSpan("drizzle.prepareQuery",()=>{let J=C1(Q),U=Z.prepareQuery(_.sqlToQuery(this.getSQL()),J,Y,!0,void 0,{type:"select",tables:[...H]},W);return U.joinsNotNullableMap=G,U.setToken($)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return O0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}P7(u5,[$1]);function T4(Y,Z){return(X,_,...G)=>{let $=[_,...G].map((W)=>({type:Y,isAll:Z,rightSelect:W}));for(let W of $)if(!R8(X.getSelectedFields(),W.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return X.addSetOperators($)}}var RE=()=>({union:NE,unionAll:IE,intersect:TE,intersectAll:KE,except:BE,exceptAll:CE}),NE=T4("union",!1),IE=T4("union",!0),TE=T4("intersect",!1),KE=T4("intersect",!0),BE=T4("except",!1),CE=T4("except",!0);class x8{static[E]="PgQueryBuilder";dialect;dialectConfig;constructor(Y){this.dialect=M(Y,l2)?Y:void 0,this.dialectConfig=M(Y,l2)?void 0:Y}$with=(Y,Z)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(X);return new Proxy(new L8(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...Y){let Z=this;function X($){return new W1({fields:$??void 0,session:void 0,dialect:Z.getDialect(),withList:Y})}function _($){return new W1({fields:$??void 0,session:void 0,dialect:Z.getDialect(),distinct:!0})}function G($,W){return new W1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),distinct:{on:$}})}return{select:X,selectDistinct:_,selectDistinctOn:G}}select(Y){return new W1({fields:Y??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(Y){return new W1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(Y,Z){return new W1({fields:Z??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:Y}})}getDialect(){if(!this.dialect)this.dialect=new l2(this.dialectConfig);return this.dialect}}function p1(Y){if(M(Y,u0))return[Y[g2]?`${Y[g2]}.${Y[S.Symbol.BaseName]}`:Y[S.Symbol.BaseName]];if(M(Y,P0))return Y._.usedTables??[];if(M(Y,h))return Y.usedTables??[];return[]}class ZY extends $1{constructor(Y,Z,X,_){super();this.session=Z,this.dialect=X,this.config={table:Y,withList:_}}static[E]="PgDelete";config;cacheConfig;where(Y){return this.config.where=Y,this}returning(Y=this.config.table[S.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=C1(Y),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return O0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"delete",tables:p1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return O0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class XY{constructor(Y,Z,X,_,G){this.table=Y,this.session=Z,this.dialect=X,this.withList=_,this.overridingSystemValue_=G}static[E]="PgInsertBuilder";authToken;setToken(Y){return this.authToken=Y,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(Y){if(Y=Array.isArray(Y)?Y:[Y],Y.length===0)throw new Error("values() must be called with at least one value");let Z=Y.map((X)=>{let _={},G=this.table[S.Symbol.Columns];for(let $ of Object.keys(X)){let W=X[$];_[$]=M(W,h)?W:new R1(W,G[$])}return _});return new d5(this.table,Z,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(Y){let Z=typeof Y==="function"?Y(new x8):Y;if(!M(Z,h)&&!R8(this.table[C6],Z._.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 d5(this.table,Z,this.session,this.dialect,this.withList,!0)}}class d5 extends $1{constructor(Y,Z,X,_,G,$,W){super();this.session=X,this.dialect=_,this.config={table:Y,values:Z,withList:G,select:$,overridingSystemValue_:W}}static[E]="PgInsert";config;cacheConfig;returning(Y=this.config.table[S.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=C1(Y),this}onConflictDoNothing(Y={}){if(Y.target===void 0)this.config.onConflict=O`do nothing`;else{let Z="";Z=Array.isArray(Y.target)?Y.target.map((_)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(_))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target));let X=Y.where?O` where ${Y.where}`:void 0;this.config.onConflict=O`(${O.raw(Z)})${X} do nothing`}return this}onConflictDoUpdate(Y){if(Y.where&&(Y.targetWhere||Y.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 Z=Y.where?O` where ${Y.where}`:void 0,X=Y.targetWhere?O` where ${Y.targetWhere}`:void 0,_=Y.setWhere?O` where ${Y.setWhere}`:void 0,G=this.dialect.buildUpdateSet(this.config.table,P6(this.config.table,Y.set)),$="";return $=Array.isArray(Y.target)?Y.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target)),this.config.onConflict=O`(${O.raw($)})${X} do update set ${G}${Z}${_}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return O0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:p1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return O0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class c5 extends $1{constructor(Y,Z,X){super();this.session=Z,this.dialect=X,this.config={view:Y}}static[E]="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:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return O0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,Y,!0)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return O0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}class _Y{constructor(Y,Z,X,_){this.table=Y,this.session=Z,this.dialect=X,this.withList=_}static[E]="PgUpdateBuilder";authToken;setToken(Y){return this.authToken=Y,this}set(Y){return new q3(this.table,P6(this.table,Y),this.session,this.dialect,this.withList).setToken(this.authToken)}}class q3 extends $1{constructor(Y,Z,X,_,G){super();this.session=X,this.dialect=_,this.config={set:Z,table:Y,withList:G,joins:[]},this.tableName=Q2(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[E]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(Y){let Z=Y,X=Q2(Z);if(typeof X==="string")this.joinsNotNullableMap[X]=!0;return this.config.from=Z,this}getTableLikeFields(Y){if(M(Y,u0))return Y[S.Symbol.Columns];else if(M(Y,P0))return Y._.selectedFields;return Y[M0].selectedFields}createJoin(Y){return(Z,X)=>{let _=Q2(Z);if(typeof _==="string"&&this.config.joins.some((G)=>G.alias===_))throw new Error(`Alias "${_}" is already used in this query`);if(typeof X==="function"){let G=this.config.from&&!M(this.config.from,h)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[S.Symbol.Columns],new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:X,table:Z,joinType:Y,alias:_}),typeof _==="string")switch(Y){case"left":{this.joinsNotNullableMap[_]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!0;break}case"inner":{this.joinsNotNullableMap[_]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(Y){return this.config.where=Y,this}returning(Y){if(!Y){if(Y=Object.assign({},this.config.table[S.Symbol.Columns]),this.config.from){let Z=Q2(this.config.from);if(typeof Z==="string"&&this.config.from&&!M(this.config.from,h)){let X=this.getTableLikeFields(this.config.from);Y[Z]=X}for(let X of this.config.joins){let _=Q2(X.table);if(typeof _==="string"&&!M(X.table,h)){let G=this.getTableLikeFields(X.table);Y[_]=G}}}}return this.config.returningFields=Y,this.config.returning=C1(Y),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){let Z=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:p1(this.config.table)},this.cacheConfig);return Z.joinsNotNullableMap=this.joinsNotNullableMap,Z}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return this._prepare().execute(Y,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class f8 extends h{constructor(Y){super(f8.buildEmbeddedCount(Y.source,Y.filters).queryChunks);this.params=Y,this.mapWith(Number),this.session=Y.session,this.sql=f8.buildCount(Y.source,Y.filters)}sql;token;static[E]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(Y,Z){return O`(select count(*) from ${Y}${O.raw(" where ").if(Z)}${Z})`}static buildCount(Y,Z){return O`select count(*) as count from ${Y}${O.raw(" where ").if(Z)}${Z};`}setToken(Y){return this.token=Y,this}then(Y,Z){return Promise.resolve(this.session.count(this.sql,this.token)).then(Y,Z)}catch(Y){return this.then(void 0,Y)}finally(Y){return this.then((Z)=>{return Y?.(),Z},(Z)=>{throw Y?.(),Z})}}class o5{constructor(Y,Z,X,_,G,$,W){this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=_,this.tableConfig=G,this.dialect=$,this.session=W}static[E]="PgRelationalQueryBuilder";findMany(Y){return new l5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?Y:{},"many")}findFirst(Y){return new l5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?{...Y,limit:1}:{limit:1},"first")}}class l5 extends $1{constructor(Y,Z,X,_,G,$,W,H,Q){super();this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=_,this.tableConfig=G,this.dialect=$,this.session=W,this.config=H,this.mode=Q}static[E]="PgRelationalQuery";_prepare(Y){return O0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Z,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,Y,!0,(_,G)=>{let $=_.map((W)=>u6(this.schema,this.tableConfig,W,Z.selection,G));if(this.mode==="first")return $[0];return $})})}prepare(Y){return this._prepare(Y)}_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 Y=this._getQuery(),Z=this.dialect.sqlToQuery(Y.sql);return{query:Y,builtQuery:Z}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(Y){return this.authToken=Y,this}execute(){return O0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class i5 extends $1{constructor(Y,Z,X,_){super();this.execute=Y,this.sql=Z,this.query=X,this.mapBatchResult=_}static[E]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(Y,Z){return Z?this.mapBatchResult(Y):Y}_prepare(){return this}isResponseInArrayMode(){return!1}}class h8{constructor(Y,Z,X){if(this.dialect=Y,this.session=Z,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap,session:Z}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:Z},this.query={},this._.schema)for(let[_,G]of Object.entries(this._.schema))this.query[_]=new o5(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[_],G,Y,Z);this.$cache={invalidate:async(_)=>{}}}static[E]="PgDatabase";query;$with=(Y,Z)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(new x8(X.dialect));return new Proxy(new L8(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(Y,Z){return new f8({source:Y,filters:Z,session:this.session})}$cache;with(...Y){let Z=this;function X(Q){return new W1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y})}function _(Q){return new W1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:!0})}function G(Q,J){return new W1({fields:J??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:{on:Q}})}function $(Q){return new _Y(Q,Z.session,Z.dialect,Y)}function W(Q){return new XY(Q,Z.session,Z.dialect,Y)}function H(Q){return new ZY(Q,Z.session,Z.dialect,Y)}return{select:X,selectDistinct:_,selectDistinctOn:G,update:$,insert:W,delete:H}}select(Y){return new W1({fields:Y??void 0,session:this.session,dialect:this.dialect})}selectDistinct(Y){return new W1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(Y,Z){return new W1({fields:Z??void 0,session:this.session,dialect:this.dialect,distinct:{on:Y}})}update(Y){return new _Y(Y,this.session,this.dialect)}insert(Y){return new XY(Y,this.session,this.dialect)}delete(Y){return new ZY(Y,this.session,this.dialect)}refreshMaterializedView(Y){return new c5(Y,this.session,this.dialect)}authToken;execute(Y){let Z=typeof Y==="string"?O.raw(Y):Y.getSQL(),X=this.dialect.sqlToQuery(Z),_=this.session.prepareQuery(X,void 0,void 0,!1);return new i5(()=>_.execute(void 0,this.authToken),Z,X,(G)=>_.mapResult(G,!0))}transaction(Y,Z){return this.session.transaction(Y,Z)}}class j3{static[E]="Cache"}class k8 extends j3{strategy(){return"all"}static[E]="NoopCache";async get(Y){return}async put(Y,Z,X,_){}async onMutate(Y){}}async function r5(Y,Z){let X=`${Y}-${JSON.stringify(Z)}`,G=new TextEncoder().encode(X),$=await crypto.subtle.digest("SHA-256",G);return[...new Uint8Array($)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}class n5{constructor(Y,Z,X,_){if(this.query=Y,this.cache=Z,this.queryMetadata=X,this.cacheConfig=_,Z&&Z.strategy()==="all"&&_===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(Y,Z){return Y}setToken(Y){return this.authToken=Y,this}static[E]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(Y,Z,X){if(this.cache===void 0||M(this.cache,k8)||this.queryMetadata===void 0)try{return await X()}catch(_){throw new J2(Y,Z,_)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await X()}catch(_){throw new J2(Y,Z,_)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[_]=await Promise.all([X(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return _}catch(_){throw new J2(Y,Z,_)}if(!this.cacheConfig)try{return await X()}catch(_){throw new J2(Y,Z,_)}if(this.queryMetadata.type==="select"){let _=await this.cache.get(this.cacheConfig.tag??await r5(Y,Z),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(_===void 0){let G;try{G=await X()}catch($){throw new J2(Y,Z,$)}return await this.cache.put(this.cacheConfig.tag??await r5(Y,Z),G,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),G}return _}try{return await X()}catch(_){throw new J2(Y,Z,_)}}}class s5{constructor(Y){this.dialect=Y}static[E]="PgSession";execute(Y,Z){return O0.startActiveSpan("drizzle.operation",()=>{return O0.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(Y),void 0,void 0,!1)}).setToken(Z).execute(void 0,Z)})}all(Y){return this.prepareQuery(this.dialect.sqlToQuery(Y),void 0,void 0,!1).all()}async count(Y,Z){let X=await this.execute(Y,Z);return Number(X[0].count)}}class t5 extends h8{constructor(Y,Z,X,_=0){super(Y,Z,X);this.schema=X,this.nestedIndex=_}static[E]="PgTransaction";rollback(){throw new V5}getTransactionConfigSQL(Y){let Z=[];if(Y.isolationLevel)Z.push(`isolation level ${Y.isolationLevel}`);if(Y.accessMode)Z.push(Y.accessMode);if(typeof Y.deferrable==="boolean")Z.push(Y.deferrable?"deferrable":"not deferrable");return O.raw(Z.join(" "))}setTransaction(Y){return this.session.execute(O`set transaction ${this.getTransactionConfigSQL(Y)}`)}}class S3 extends n5{constructor(Y,Z,X,_,G,$,W,H,Q,J){super({sql:Z,params:X},G,$,W);this.client=Y,this.queryString=Z,this.params=X,this.logger=_,this.fields=H,this._isResponseInArrayMode=Q,this.customResultMapper=J}static[E]="PostgresJsPreparedQuery";async execute(Y={}){return O0.startActiveSpan("drizzle.execute",async(Z)=>{let X=E5(this.params,Y);Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X);let{fields:_,queryString:G,client:$,joinsNotNullableMap:W,customResultMapper:H}=this;if(!_&&!H)return O0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(G,X,async()=>{return await $.unsafe(G,X)})});let Q=await O0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":G,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(G,X,async()=>{return await $.unsafe(G,X).values()})});return O0.startActiveSpan("drizzle.mapResponse",()=>{return H?H(Q):Q.map((J)=>S7(_,J,W))})})}all(Y={}){return O0.startActiveSpan("drizzle.execute",async(Z)=>{let X=E5(this.params,Y);return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),O0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(this.queryString,X,async()=>{return this.client.unsafe(this.queryString,X)})})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class b8 extends s5{constructor(Y,Z,X,_={}){super(Z);this.client=Y,this.schema=X,this.options=_,this.logger=_.logger??new L5,this.cache=_.cache??new k8}static[E]="PostgresJsSession";logger;cache;prepareQuery(Y,Z,X,_,G,$,W){return new S3(this.client,Y.sql,Y.params,this.logger,this.cache,$,W,Z,_,G)}query(Y,Z){return this.logger.logQuery(Y,Z),this.client.unsafe(Y,Z).values()}queryObjects(Y,Z){return this.client.unsafe(Y,Z)}transaction(Y,Z){return this.client.begin(async(X)=>{let _=new b8(X,this.dialect,this.schema,this.options),G=new a5(this.dialect,_,this.schema);if(Z)await G.setTransaction(Z);return Y(G)})}}class a5 extends t5{constructor(Y,Z,X,_=0){super(Y,Z,X,_);this.session=Z}static[E]="PostgresJsTransaction";transaction(Y){return this.session.client.savepoint((Z)=>{let X=new b8(Z,this.dialect,this.schema,this.session.options),_=new a5(this.dialect,X,this.schema);return Y(_)})}}class P3 extends h8{static[E]="PostgresJsDatabase"}function K4(Y,Z={}){let X=(Q)=>Q;for(let Q of["1184","1082","1083","1114","1182","1185","1115","1231"])Y.options.parsers[Q]=X,Y.options.serializers[Q]=X;Y.options.serializers["114"]=X,Y.options.serializers["3802"]=X;let _=new l2({casing:Z.casing}),G;if(Z.logger===!0)G=new D5;else if(Z.logger!==!1)G=Z.logger;let $;if(Z.schema){let Q=X3(Z.schema,G3);$={fullSchema:Z.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let W=new b8(Y,_,$,{logger:G,cache:Z.cache}),H=new P3(_,W,$);if(H.$client=Y,H.$cache=Z.cache,H.$cache)H.$cache.invalidate=Z.cache?.onMutate;return H}function GY(...Y){if(typeof Y[0]==="string"){let Z=I4(Y[0]);return K4(Z,Y[1])}if(x7(Y[0])){let{connection:Z,client:X,..._}=Y[0];if(X)return K4(X,_);if(typeof Z==="object"&&Z.url!==void 0){let{url:$,...W}=Z,H=I4($,W);return K4(H,_)}let G=I4(Z);return K4(G,_)}return K4(Y[0],Y[1])}((Y)=>{function Z(X){return K4({options:{parsers:{},serializers:{}}},X)}Y.mock=Z})(GY||(GY={}));var YX={};kH(YX,{users:()=>o2,untrackedUserColumnNames:()=>qE,twoFactorMethod:()=>k3,trackedUserColumnName:()=>jE,trackableUserColumnNames:()=>f3,signInHistory:()=>PE,role:()=>x3,players:()=>e5,passwordResetAttempts:()=>vE,games:()=>WY,banishedIps:()=>xE,accountActions:()=>SE,accountAction:()=>h3});function q2(){return e0({length:24}).$type()}function v3(Y){return O`lower(${Y})`}var $Y=O`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,x3=D8("role",["admin","user"]),o2=K2("users",{id:q1().primaryKey().defaultRandom(),username:e0({length:16}).notNull(),emailOffered:e0({length:254}).notNull(),emailVerified:e0({length:254}),password:e0({length:254}),createdAtIso:q2().notNull().default($Y),createdIp:e0({length:45}).notNull(),isActive:N8().notNull().default(!1),verifiedAtIso:q2(),userRole:x3().default("user")},(Y)=>[g5("usernameUniqueIndex").on(v3(Y.username)),g5("emailVerifiedUniqueIndex").on(v3(Y.emailVerified))]),qE=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],f3=["username","emailOffered","emailVerified","password","userRole"],jE=D8("trackedUserColumnName",f3),h3=D8("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),SE=K2("accountActions",{userId:q1().references(()=>o2.id).primaryKey(),action:h3().notNull(),code:e0({length:254}).notNull(),wrongCodeCount:I8().notNull().default(0),expiresAtIso:q2().notNull()}),WY=K2("games",{id:q1().primaryKey().defaultRandom()}),e5=K2("players",{userId:q1().notNull().references(()=>o2.id,{onDelete:"cascade"}),gameId:q1().notNull().references(()=>WY.id,{onDelete:"cascade"}),score:I8().notNull()},(Y)=>[SW({name:"players_userId_gameId_pk",columns:[Y.userId,Y.gameId]})]),PE=K2("signInHistory",{id:q1().primaryKey().defaultRandom(),userId:q1().references(()=>o2.id,{onDelete:"cascade"}),signInTimeIso:q2().notNull().default($Y),ipAddress:e0({length:45}).notNull(),userAgent:e0({length:1024}),successful:N8().notNull().default(!1)}),k3=D8("twoFactorMethod",["email","phone"]),vE=K2("passwordResetAttempts",{id:q1().primaryKey().defaultRandom(),userId:q1().notNull().references(()=>o2.id,{onDelete:"cascade"}),requestedIp:e0({length:45}).notNull(),requestedAtIso:q2().notNull().default($Y),succeededIp:e0({length:45}),succeededAtIso:q2(),verificationMethod:k3().notNull()}),xE=K2("banishedIps",{ip:e0({length:45}).primaryKey(),reason:e0({length:2048}).notNull(),banishedAtIso:q2().notNull().default($Y),banishedUntilIso:q2()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class ZX{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(fE.resolve(__dirname,"notify_update.sql"));let Y=[d0(o2),d0(WY),d0(e5)];await this.sql`SELECT create_notify_triggers(${this.sql.array(Y)})`,await this.sql.listen("table_update",(Z)=>{let X=Z.split(","),_=X[0],G=X[1],$=`${_}("${G}")`;if(this.observers.has($))this.observers.get($).next($)})}constructor(Y=!1,Z={host:y1.POSTGRES_HOST,port:y1.POSTGRES_PORT,user:y1.POSTGRES_USER,password:y1.POSTGRES_PASSWORD,database:y1.POSTGRES_DATABASE}){this.options=Z,this.sql=I4(Z),this.drizzle=GY(this.sql,{schema:YX,logger:Y})}observe(Y,Z){if(!this.observers.has(Y))this.observers.set(Y,new W0);this.observers.get(Y).subscribe("SINGLETON",Z)}}var HY={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 hE(Y){return Number.parseInt(Y,10)}var kE=E1(HY),bE=kE.keyof().pipe((Y)=>hE(Y)),b3=E1([bE,"string"]);var _X=new $7,{logger:D1}=_X;Object.assign(console,D1,{log:D1.info});D1.info("ready");var XX=g3(import.meta.dir,"..","app"),Gf=new ZX({logQuery(Y,Z){D1.info("\uD83D\uDCDD query",Y,Z)}});mE({hostname:"0.0.0.0",port:y1.FRONTEND_PORT??3333,...T6??void 0,async fetch(Y){try{let Z=new Date,X=new URL(Y.url);if(D1.info(Y.method,X.pathname),X.pathname==="/")return new Response(Bun.file(g3(XX,"index.html")));if(X.pathname==="/index.html")return Response.redirect("/");let _=gE(XX,X.pathname),G=pE(_);if(!G.startsWith(XX))throw[403,"Access Denied"];if(!await y3(G).exists())return Response.redirect("/");return new Response(y3(G))}catch(Z){let X=b3(Z);if(X instanceof E1.errors===!1){let[_,G]=X,W=`${HY[_]}. ${G}`;return D1.info(`\u274C ${_}: ${W}`),new Response(W,{status:_})}if(Z instanceof Error)D1.error(Z.message);else{let _=I6(Z);D1.error("frontend server threw",_)}return new Response(HY[500],{status:500})}}});function JY(){D1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{D1.info("\u2757 received SIGINT; exiting gracefully"),JY()});process.on("SIGTERM",()=>{D1.info("\u2757 received SIGTERM; exiting gracefully"),JY()});process.on("exit",()=>{D1.info("\u2757 received exit; exiting gracefully"),JY()});_X.on("timeToStop",()=>{D1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),JY()});var{version:uE}=await Bun.file(yE.resolve(import.meta.dir,"../package.json")).json();D1.info(`\uD83D\uDEEB frontend v${uE} running at http://localhost:${y1.FRONTEND_PORT}/`);_X.emit("alive");
87
+ `;await Z.execute(O`CREATE SCHEMA IF NOT EXISTS ${O.identifier(G)}`),await Z.execute($);let H=(await Z.all(O`select id, hash, created_at from ${O.identifier(G)}.${O.identifier(_)} order by created_at desc limit 1`))[0];await Z.transaction(async(Q)=>{for await(let J of Y)if(!H||Number(H.created_at)<J.folderMillis){for(let z of J.sql)await Q.execute(O.raw(z));await Q.execute(O`insert into ${O.identifier(G)}.${O.identifier(_)} ("hash", "created_at") values(${J.hash}, ${J.folderMillis})`)}})}escapeName(Y){return`"${Y}"`}escapeParam(Y){return`$${Y+1}`}escapeString(Y){return`'${Y.replace(/'/g,"''")}'`}buildWithCTE(Y){if(!Y?.length)return;let Z=[O`with `];for(let[X,_]of Y.entries())if(Z.push(O`${O.identifier(_._.alias)} as (${_._.sql})`),X<Y.length-1)Z.push(O`, `);return Z.push(O` `),O.join(Z)}buildDeleteQuery({table:Y,where:Z,returning:X,withList:_}){let G=this.buildWithCTE(_),$=X?O` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,W=Z?O` where ${Z}`:void 0;return O`${G}delete from ${Y}${W}${$}`}buildUpdateSet(Y,Z){let X=Y[S.Symbol.Columns],_=Object.keys(X).filter(($)=>Z[$]!==void 0||X[$]?.onUpdateFn!==void 0),G=_.length;return O.join(_.flatMap(($,W)=>{let H=X[$],Q=Z[$]??O.param(H.onUpdateFn(),H),J=O`${O.identifier(this.casing.getColumnCasing(H))} = ${Q}`;if(W<G-1)return[J,O.raw(", ")];return[J]}))}buildUpdateQuery({table:Y,set:Z,where:X,returning:_,withList:G,from:$,joins:W}){let H=this.buildWithCTE(G),Q=Y[u0.Symbol.Name],J=Y[u0.Symbol.Schema],z=Y[u0.Symbol.OriginalName],E=Q===z?void 0:Q,V=O`${J?O`${O.identifier(J)}.`:void 0}${O.identifier(z)}${E&&O` ${O.identifier(E)}`}`,D=this.buildUpdateSet(Y,Z),R=$&&O.join([O.raw(" from "),this.buildFromTable($)]),w=this.buildJoins(W),f=_?O` returning ${this.buildSelection(_,{isSingleTable:!$})}`:void 0,v=X?O` where ${X}`:void 0;return O`${H}update ${V} set ${D}${R}${w}${v}${f}`}buildSelection(Y,{isSingleTable:Z=!1}={}){let X=Y.length,_=Y.flatMap(({field:G},$)=>{let W=[];if(M(G,h.Aliased)&&G.isSelectionField)W.push(O.identifier(G.fieldAlias));else if(M(G,h.Aliased)||M(G,h)){let H=M(G,h.Aliased)?G.sql:G;if(Z)W.push(new h(H.queryChunks.map((Q)=>{if(M(Q,j))return O.identifier(this.casing.getColumnCasing(Q));return Q})));else W.push(H);if(M(G,h.Aliased))W.push(O` as ${O.identifier(G.fieldAlias)}`)}else if(M(G,E0))if(Z)W.push(O.identifier(this.casing.getColumnCasing(G)));else W.push(G);if($<X-1)W.push(O`, `);return W});return O.join(_)}buildJoins(Y){if(!Y||Y.length===0)return;let Z=[];for(let[X,_]of Y.entries()){if(X===0)Z.push(O` `);let G=_.table,$=_.lateral?O` lateral`:void 0,W=_.on?O` on ${_.on}`:void 0;if(M(G,u0)){let H=G[u0.Symbol.Name],Q=G[u0.Symbol.Schema],J=G[u0.Symbol.OriginalName],z=H===J?void 0:_.alias;Z.push(O`${O.raw(_.joinType)} join${$} ${Q?O`${O.identifier(Q)}.`:void 0}${O.identifier(J)}${z&&O` ${O.identifier(z)}`}${W}`)}else if(M(G,V1)){let H=G[A0].name,Q=G[A0].schema,J=G[A0].originalName,z=H===J?void 0:_.alias;Z.push(O`${O.raw(_.joinType)} join${$} ${Q?O`${O.identifier(Q)}.`:void 0}${O.identifier(J)}${z&&O` ${O.identifier(z)}`}${W}`)}else Z.push(O`${O.raw(_.joinType)} join${$} ${G}${W}`);if(X<Y.length-1)Z.push(O` `)}return O.join(Z)}buildFromTable(Y){if(M(Y,S)&&Y[S.Symbol.IsAlias]){let Z=O`${O.identifier(Y[S.Symbol.OriginalName])}`;if(Y[S.Symbol.Schema])Z=O`${O.identifier(Y[S.Symbol.Schema])}.${Z}`;return O`${Z} ${O.identifier(Y[S.Symbol.Name])}`}return Y}buildSelectQuery({withList:Y,fields:Z,fieldsFlat:X,where:_,having:G,table:$,joins:W,orderBy:H,groupBy:Q,limit:J,offset:z,lockingClause:E,distinct:V,setOperators:D}){let R=X??C1(Z);for(let a of R)if(M(a.field,E0)&&d0(a.field.table)!==(M($,P0)?$._.alias:M($,P8)?$[A0].name:M($,h)?void 0:d0($))&&!((U0)=>W?.some(({alias:h0})=>h0===(U0[S.Symbol.IsAlias]?d0(U0):U0[S.Symbol.BaseName])))(a.field.table)){let U0=d0(a.field.table);throw new Error(`Your "${a.path.join("->")}" field references a column "${U0}"."${a.field.name}", but the table "${U0}" is not part of the query! Did you forget to join it?`)}let w=!W||W.length===0,f=this.buildWithCTE(Y),v;if(V)v=V===!0?O` distinct`:O` distinct on (${O.join(V.on,O`, `)})`;let k=this.buildSelection(R,{isSingleTable:w}),m=this.buildFromTable($),T=this.buildJoins(W),K=_?O` where ${_}`:void 0,C=G?O` having ${G}`:void 0,q;if(H&&H.length>0)q=O` order by ${O.join(H,O`, `)}`;let g;if(Q&&Q.length>0)g=O` group by ${O.join(Q,O`, `)}`;let o=typeof J==="object"||typeof J==="number"&&J>=0?O` limit ${J}`:void 0,N=z?O` offset ${z}`:void 0,s=O.empty();if(E){let a=O` for ${O.raw(E.strength)}`;if(E.config.of)a.append(O` of ${O.join(Array.isArray(E.config.of)?E.config.of:[E.config.of],O`, `)}`);if(E.config.noWait)a.append(O` nowait`);else if(E.config.skipLocked)a.append(O` skip locked`);s.append(a)}let p=O`${f}select${v} ${k} from ${m}${T}${K}${g}${C}${q}${o}${N}${s}`;if(D.length>0)return this.buildSetOperations(p,D);return p}buildSetOperations(Y,Z){let[X,..._]=Z;if(!X)throw new Error("Cannot pass undefined values to any set operator");if(_.length===0)return this.buildSetOperationQuery({leftSelect:Y,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:Y,setOperator:X}),_)}buildSetOperationQuery({leftSelect:Y,setOperator:{type:Z,isAll:X,rightSelect:_,limit:G,orderBy:$,offset:W}}){let H=O`(${Y.getSQL()}) `,Q=O`(${_.getSQL()})`,J;if($&&$.length>0){let D=[];for(let R of $)if(M(R,j))D.push(O.identifier(R.name));else if(M(R,h)){for(let w=0;w<R.queryChunks.length;w++){let f=R.queryChunks[w];if(M(f,j))R.queryChunks[w]=O.identifier(f.name)}D.push(O`${R}`)}else D.push(O`${R}`);J=O` order by ${O.join(D,O`, `)} `}let z=typeof G==="object"||typeof G==="number"&&G>=0?O` limit ${G}`:void 0,E=O.raw(`${Z} ${X?"all ":""}`),V=W?O` offset ${W}`:void 0;return O`${H}${E}${Q}${J}${z}${V}`}buildInsertQuery({table:Y,values:Z,onConflict:X,returning:_,withList:G,select:$,overridingSystemValue_:W}){let H=[],Q=Y[S.Symbol.Columns],J=Object.entries(Q).filter(([f,v])=>!v.shouldDisableInsert()),z=J.map(([,f])=>O.identifier(this.casing.getColumnCasing(f)));if($){let f=Z;if(M(f,h))H.push(f);else H.push(f.getSQL())}else{let f=Z;H.push(O.raw("values "));for(let[v,k]of f.entries()){let m=[];for(let[T,K]of J){let C=k[T];if(C===void 0||M(C,A1)&&C.value===void 0)if(K.defaultFn!==void 0){let q=K.defaultFn(),g=M(q,h)?q:O.param(q,K);m.push(g)}else if(!K.default&&K.onUpdateFn!==void 0){let q=K.onUpdateFn(),g=M(q,h)?q:O.param(q,K);m.push(g)}else m.push(O`default`);else m.push(C)}if(H.push(m),v<f.length-1)H.push(O`, `)}}let E=this.buildWithCTE(G),V=O.join(H),D=_?O` returning ${this.buildSelection(_,{isSingleTable:!0})}`:void 0,R=X?O` on conflict ${X}`:void 0,w=W===!0?O`overriding system value `:void 0;return O`${E}insert into ${Y} ${z} ${w}${V}${R}${D}`}buildRefreshMaterializedViewQuery({view:Y,concurrently:Z,withNoData:X}){let _=Z?O` concurrently`:void 0,G=X?O` with no data`:void 0;return O`refresh materialized view${_} ${Y}${G}`}prepareTyping(Y){if(M(Y,k6)||M(Y,h6))return"json";else if(M(Y,b6))return"decimal";else if(M(Y,y6))return"time";else if(M(Y,g6)||M(Y,p6))return"timestamp";else if(M(Y,x6)||M(Y,f6))return"date";else if(M(Y,m6))return"uuid";else return"none"}sqlToQuery(Y,Z){return Y.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:Z})}buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:_,tableConfig:G,queryConfig:$,tableAlias:W,nestedQueryRelation:H,joinOn:Q}){let J=[],z,E,V=[],D,R=[];if($===!0)J=Object.entries(G.columns).map(([v,k])=>({dbKey:k.name,tsKey:v,field:o1(k,W),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let f=Object.fromEntries(Object.entries(G.columns).map(([C,q])=>[C,o1(q,W)]));if($.where){let C=typeof $.where==="function"?$.where(f,Z3()):$.where;D=C&&A8(C,W)}let v=[],k=[];if($.columns){let C=!1;for(let[q,g]of Object.entries($.columns)){if(g===void 0)continue;if(q in G.columns){if(!C&&g===!0)C=!0;k.push(q)}}if(k.length>0)k=C?k.filter((q)=>$.columns?.[q]===!0):Object.keys(G.columns).filter((q)=>!k.includes(q))}else k=Object.keys(G.columns);for(let C of k){let q=G.columns[C];v.push({tsKey:C,value:q})}let m=[];if($.with)m=Object.entries($.with).filter((C)=>!!C[1]).map(([C,q])=>({tsKey:C,queryConfig:q,relation:G.relations[C]}));let T;if($.extras){T=typeof $.extras==="function"?$.extras(f,{sql:O}):$.extras;for(let[C,q]of Object.entries(T))v.push({tsKey:C,value:O5(q,W)})}for(let{tsKey:C,value:q}of v)J.push({dbKey:M(q,h.Aliased)?q.fieldAlias:G.columns[C].name,tsKey:C,field:M(q,E0)?o1(q,W):q,relationTableTsKey:void 0,isJson:!1,selection:[]});let K=typeof $.orderBy==="function"?$.orderBy(f,X3()):$.orderBy??[];if(!Array.isArray(K))K=[K];V=K.map((C)=>{if(M(C,E0))return o1(C,W);return A8(C,W)}),z=$.limit,E=$.offset;for(let{tsKey:C,queryConfig:q,relation:g}of m){let o=G3(Z,X,g),N=g2(g.referencedTable),s=X[N],p=`${W}_${C}`,a=K8(...o.fields.map((W1,r1)=>u6(o1(o.references[r1],p),o1(W1,W)))),U0=this.buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:Y[s],tableConfig:Z[s],queryConfig:M(g,T2)?q===!0?{limit:1}:{...q,limit:1}:q,tableAlias:p,joinOn:a,nestedQueryRelation:g}),h0=O`${O.identifier(p)}.${O.identifier("data")}`.as(C);R.push({on:O`true`,table:new P0(U0.sql,{},p),alias:p,joinType:"left",lateral:!0}),J.push({dbKey:C,tsKey:C,field:h0,relationTableTsKey:s,isJson:!0,selection:U0.selection})}}if(J.length===0)throw new P6({message:`No fields selected for table "${G.tsName}" ("${W}")`});let w;if(D=K8(Q,D),H){let f=O`json_build_array(${O.join(J.map(({field:m,tsKey:T,isJson:K})=>K?O`${O.identifier(`${W}_${T}`)}.${O.identifier("data")}`:M(m,h.Aliased)?m.sql:m),O`, `)})`;if(M(H,T8))f=O`coalesce(json_agg(${f}${V.length>0?O` order by ${O.join(V,O`, `)}`:void 0}), '[]'::json)`;let v=[{dbKey:"data",tsKey:"data",field:f.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:J}];if(z!==void 0||E!==void 0||V.length>0)w=this.buildSelectQuery({table:S6(_,W),fields:{},fieldsFlat:[{path:[],field:O.raw("*")}],where:D,limit:z,offset:E,orderBy:V,setOperators:[]}),D=void 0,z=void 0,E=void 0,V=[];else w=S6(_,W);w=this.buildSelectQuery({table:M(w,u0)?w:new P0(w,{},W),fields:{},fieldsFlat:v.map(({field:m})=>({path:[],field:M(m,E0)?o1(m,W):m})),joins:R,where:D,limit:z,offset:E,orderBy:V,setOperators:[]})}else w=this.buildSelectQuery({table:S6(_,W),fields:{},fieldsFlat:J.map(({field:f})=>({path:[],field:M(f,E0)?o1(f,W):f})),joins:R,where:D,limit:z,offset:E,orderBy:V,setOperators:[]});return{tableTsKey:G.tsName,sql:w,selection:J}}}class u5{static[F]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class $1{static[F]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(Y){if(this.fields=Y.fields,this.session=Y.session,this.dialect=Y.dialect,Y.withList)this.withList=Y.withList;this.distinct=Y.distinct}authToken;setToken(Y){return this.authToken=Y,this}from(Y){let Z=!!this.fields,X=Y,_;if(this.fields)_=this.fields;else if(M(X,P0))_=Object.fromEntries(Object.keys(X._.selectedFields).map((G)=>[G,X[G]]));else if(M(X,P8))_=X[A0].selectedFields;else if(M(X,h))_={};else _=x7(X);return new d5({table:X,fields:_,isPartialSelect:Z,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class q3 extends u5{static[F]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:Y,fields:Z,isPartialSelect:X,session:_,dialect:G,withList:$,distinct:W}){super();this.config={withList:$,table:Y,fields:{...Z},distinct:W,setOperators:[]},this.isPartialSelect=X,this.session=_,this.dialect=G,this._={selectedFields:Z,config:this.config},this.tableName=Q2(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let H of p1(Y))this.usedTables.add(H)}getUsedTables(){return[...this.usedTables]}createJoin(Y,Z){return(X,_)=>{let G=this.tableName,$=Q2(X);for(let W of p1(X))this.usedTables.add(W);if(typeof $==="string"&&this.config.joins?.some((W)=>W.alias===$))throw new Error(`Alias "${$}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof G==="string")this.config.fields={[G]:this.config.fields};if(typeof $==="string"&&!M(X,h)){let W=M(X,P0)?X._.selectedFields:M(X,V1)?X[A0].selectedFields:X[S.Symbol.Columns];this.config.fields[$]=W}}if(typeof _==="function")_=_(new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:_,table:X,joinType:Y,alias:$,lateral:Z}),typeof $==="string")switch(Y){case"left":{this.joinsNotNullableMap[$]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([W])=>[W,!1])),this.joinsNotNullableMap[$]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[$]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([W])=>[W,!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(Y,Z){return(X)=>{let _=typeof X==="function"?X(NE()):X;if(!w8(this.getSelectedFields(),_.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:Y,isAll:Z,rightSelect:_}),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(Y){return this.config.setOperators.push(...Y),this}where(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=Y,this}having(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=Y,this}groupBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(Z)?Z:[Z]}else this.config.groupBy=Y;return this}orderBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray(Z)?Z:[Z];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=X;else this.config.orderBy=X}else{let Z=Y;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Z;else this.config.orderBy=Z}return this}limit(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=Y;else this.config.limit=Y;return this}offset(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=Y;else this.config.offset=Y;return this}for(Y,Z={}){return this.config.lockingClause={strength:Y,config:Z},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}as(Y){let Z=[];if(Z.push(...p1(this.config.table)),this.config.joins)for(let X of this.config.joins)Z.push(...p1(X.table));return new Proxy(new P0(this.getSQL(),this.config.fields,Y,!1,[...new Set(Z)]),new q0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new q0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(Y){return this.cacheConfig=Y===void 0?{config:{},enable:!0,autoInvalidate:!0}:Y===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...Y},this}}class d5 extends q3{static[F]="PgSelect";_prepare(Y){let{session:Z,config:X,dialect:_,joinsNotNullableMap:G,authToken:$,cacheConfig:W,usedTables:H}=this;if(!Z)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:Q}=X;return V0.startActiveSpan("drizzle.prepareQuery",()=>{let J=C1(Q),z=Z.prepareQuery(_.sqlToQuery(this.getSQL()),J,Y,!0,void 0,{type:"select",tables:[...H]},W);return z.joinsNotNullableMap=G,z.setToken($)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return V0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}v7(d5,[G1]);function N4(Y,Z){return(X,_,...G)=>{let $=[_,...G].map((W)=>({type:Y,isAll:Z,rightSelect:W}));for(let W of $)if(!w8(X.getSelectedFields(),W.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return X.addSetOperators($)}}var NE=()=>({union:IE,unionAll:KE,intersect:TE,intersectAll:BE,except:CE,exceptAll:qE}),IE=N4("union",!1),KE=N4("union",!0),TE=N4("intersect",!1),BE=N4("intersect",!0),CE=N4("except",!1),qE=N4("except",!0);class v8{static[F]="PgQueryBuilder";dialect;dialectConfig;constructor(Y){this.dialect=M(Y,c2)?Y:void 0,this.dialectConfig=M(Y,c2)?void 0:Y}$with=(Y,Z)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(X);return new Proxy(new D8(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new q0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...Y){let Z=this;function X($){return new $1({fields:$??void 0,session:void 0,dialect:Z.getDialect(),withList:Y})}function _($){return new $1({fields:$??void 0,session:void 0,dialect:Z.getDialect(),distinct:!0})}function G($,W){return new $1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),distinct:{on:$}})}return{select:X,selectDistinct:_,selectDistinctOn:G}}select(Y){return new $1({fields:Y??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(Y){return new $1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(Y,Z){return new $1({fields:Z??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:Y}})}getDialect(){if(!this.dialect)this.dialect=new c2(this.dialectConfig);return this.dialect}}function p1(Y){if(M(Y,u0))return[Y[y2]?`${Y[y2]}.${Y[S.Symbol.BaseName]}`:Y[S.Symbol.BaseName]];if(M(Y,P0))return Y._.usedTables??[];if(M(Y,h))return Y.usedTables??[];return[]}class XY extends G1{constructor(Y,Z,X,_){super();this.session=Z,this.dialect=X,this.config={table:Y,withList:_}}static[F]="PgDelete";config;cacheConfig;where(Y){return this.config.where=Y,this}returning(Y=this.config.table[S.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=C1(Y),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return V0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"delete",tables:p1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return V0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new q0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class _Y{constructor(Y,Z,X,_,G){this.table=Y,this.session=Z,this.dialect=X,this.withList=_,this.overridingSystemValue_=G}static[F]="PgInsertBuilder";authToken;setToken(Y){return this.authToken=Y,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(Y){if(Y=Array.isArray(Y)?Y:[Y],Y.length===0)throw new Error("values() must be called with at least one value");let Z=Y.map((X)=>{let _={},G=this.table[S.Symbol.Columns];for(let $ of Object.keys(X)){let W=X[$];_[$]=M(W,h)?W:new A1(W,G[$])}return _});return new c5(this.table,Z,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(Y){let Z=typeof Y==="function"?Y(new v8):Y;if(!M(Z,h)&&!w8(this.table[q6],Z._.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 c5(this.table,Z,this.session,this.dialect,this.withList,!0)}}class c5 extends G1{constructor(Y,Z,X,_,G,$,W){super();this.session=X,this.dialect=_,this.config={table:Y,values:Z,withList:G,select:$,overridingSystemValue_:W}}static[F]="PgInsert";config;cacheConfig;returning(Y=this.config.table[S.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=C1(Y),this}onConflictDoNothing(Y={}){if(Y.target===void 0)this.config.onConflict=O`do nothing`;else{let Z="";Z=Array.isArray(Y.target)?Y.target.map((_)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(_))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target));let X=Y.where?O` where ${Y.where}`:void 0;this.config.onConflict=O`(${O.raw(Z)})${X} do nothing`}return this}onConflictDoUpdate(Y){if(Y.where&&(Y.targetWhere||Y.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 Z=Y.where?O` where ${Y.where}`:void 0,X=Y.targetWhere?O` where ${Y.targetWhere}`:void 0,_=Y.setWhere?O` where ${Y.setWhere}`:void 0,G=this.dialect.buildUpdateSet(this.config.table,v6(this.config.table,Y.set)),$="";return $=Array.isArray(Y.target)?Y.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target)),this.config.onConflict=O`(${O.raw($)})${X} do update set ${G}${Z}${_}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return V0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:p1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return V0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new q0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class l5 extends G1{constructor(Y,Z,X){super();this.session=Z,this.dialect=X,this.config={view:Y}}static[F]="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:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return V0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,Y,!0)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return V0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}class GY{constructor(Y,Z,X,_){this.table=Y,this.session=Z,this.dialect=X,this.withList=_}static[F]="PgUpdateBuilder";authToken;setToken(Y){return this.authToken=Y,this}set(Y){return new j3(this.table,v6(this.table,Y),this.session,this.dialect,this.withList).setToken(this.authToken)}}class j3 extends G1{constructor(Y,Z,X,_,G){super();this.session=X,this.dialect=_,this.config={set:Z,table:Y,withList:G,joins:[]},this.tableName=Q2(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[F]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(Y){let Z=Y,X=Q2(Z);if(typeof X==="string")this.joinsNotNullableMap[X]=!0;return this.config.from=Z,this}getTableLikeFields(Y){if(M(Y,u0))return Y[S.Symbol.Columns];else if(M(Y,P0))return Y._.selectedFields;return Y[A0].selectedFields}createJoin(Y){return(Z,X)=>{let _=Q2(Z);if(typeof _==="string"&&this.config.joins.some((G)=>G.alias===_))throw new Error(`Alias "${_}" is already used in this query`);if(typeof X==="function"){let G=this.config.from&&!M(this.config.from,h)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[S.Symbol.Columns],new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:X,table:Z,joinType:Y,alias:_}),typeof _==="string")switch(Y){case"left":{this.joinsNotNullableMap[_]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!0;break}case"inner":{this.joinsNotNullableMap[_]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(Y){return this.config.where=Y,this}returning(Y){if(!Y){if(Y=Object.assign({},this.config.table[S.Symbol.Columns]),this.config.from){let Z=Q2(this.config.from);if(typeof Z==="string"&&this.config.from&&!M(this.config.from,h)){let X=this.getTableLikeFields(this.config.from);Y[Z]=X}for(let X of this.config.joins){let _=Q2(X.table);if(typeof _==="string"&&!M(X.table,h)){let G=this.getTableLikeFields(X.table);Y[_]=G}}}}return this.config.returningFields=Y,this.config.returning=C1(Y),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){let Z=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:p1(this.config.table)},this.cacheConfig);return Z.joinsNotNullableMap=this.joinsNotNullableMap,Z}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return this._prepare().execute(Y,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new q0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class x8 extends h{constructor(Y){super(x8.buildEmbeddedCount(Y.source,Y.filters).queryChunks);this.params=Y,this.mapWith(Number),this.session=Y.session,this.sql=x8.buildCount(Y.source,Y.filters)}sql;token;static[F]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(Y,Z){return O`(select count(*) from ${Y}${O.raw(" where ").if(Z)}${Z})`}static buildCount(Y,Z){return O`select count(*) as count from ${Y}${O.raw(" where ").if(Z)}${Z};`}setToken(Y){return this.token=Y,this}then(Y,Z){return Promise.resolve(this.session.count(this.sql,this.token)).then(Y,Z)}catch(Y){return this.then(void 0,Y)}finally(Y){return this.then((Z)=>{return Y?.(),Z},(Z)=>{throw Y?.(),Z})}}class i5{constructor(Y,Z,X,_,G,$,W){this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=_,this.tableConfig=G,this.dialect=$,this.session=W}static[F]="PgRelationalQueryBuilder";findMany(Y){return new o5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?Y:{},"many")}findFirst(Y){return new o5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?{...Y,limit:1}:{limit:1},"first")}}class o5 extends G1{constructor(Y,Z,X,_,G,$,W,H,Q){super();this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=_,this.tableConfig=G,this.dialect=$,this.session=W,this.config=H,this.mode=Q}static[F]="PgRelationalQuery";_prepare(Y){return V0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Z,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,Y,!0,(_,G)=>{let $=_.map((W)=>d6(this.schema,this.tableConfig,W,Z.selection,G));if(this.mode==="first")return $[0];return $})})}prepare(Y){return this._prepare(Y)}_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 Y=this._getQuery(),Z=this.dialect.sqlToQuery(Y.sql);return{query:Y,builtQuery:Z}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(Y){return this.authToken=Y,this}execute(){return V0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class r5 extends G1{constructor(Y,Z,X,_){super();this.execute=Y,this.sql=Z,this.query=X,this.mapBatchResult=_}static[F]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(Y,Z){return Z?this.mapBatchResult(Y):Y}_prepare(){return this}isResponseInArrayMode(){return!1}}class f8{constructor(Y,Z,X){if(this.dialect=Y,this.session=Z,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap,session:Z}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:Z},this.query={},this._.schema)for(let[_,G]of Object.entries(this._.schema))this.query[_]=new i5(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[_],G,Y,Z);this.$cache={invalidate:async(_)=>{}}}static[F]="PgDatabase";query;$with=(Y,Z)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(new v8(X.dialect));return new Proxy(new D8(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new q0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(Y,Z){return new x8({source:Y,filters:Z,session:this.session})}$cache;with(...Y){let Z=this;function X(Q){return new $1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y})}function _(Q){return new $1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:!0})}function G(Q,J){return new $1({fields:J??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:{on:Q}})}function $(Q){return new GY(Q,Z.session,Z.dialect,Y)}function W(Q){return new _Y(Q,Z.session,Z.dialect,Y)}function H(Q){return new XY(Q,Z.session,Z.dialect,Y)}return{select:X,selectDistinct:_,selectDistinctOn:G,update:$,insert:W,delete:H}}select(Y){return new $1({fields:Y??void 0,session:this.session,dialect:this.dialect})}selectDistinct(Y){return new $1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(Y,Z){return new $1({fields:Z??void 0,session:this.session,dialect:this.dialect,distinct:{on:Y}})}update(Y){return new GY(Y,this.session,this.dialect)}insert(Y){return new _Y(Y,this.session,this.dialect)}delete(Y){return new XY(Y,this.session,this.dialect)}refreshMaterializedView(Y){return new l5(Y,this.session,this.dialect)}authToken;execute(Y){let Z=typeof Y==="string"?O.raw(Y):Y.getSQL(),X=this.dialect.sqlToQuery(Z),_=this.session.prepareQuery(X,void 0,void 0,!1);return new r5(()=>_.execute(void 0,this.authToken),Z,X,(G)=>_.mapResult(G,!0))}transaction(Y,Z){return this.session.transaction(Y,Z)}}class S3{static[F]="Cache"}class h8 extends S3{strategy(){return"all"}static[F]="NoopCache";async get(Y){return}async put(Y,Z,X,_){}async onMutate(Y){}}async function n5(Y,Z){let X=`${Y}-${JSON.stringify(Z)}`,G=new TextEncoder().encode(X),$=await crypto.subtle.digest("SHA-256",G);return[...new Uint8Array($)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}class s5{constructor(Y,Z,X,_){if(this.query=Y,this.cache=Z,this.queryMetadata=X,this.cacheConfig=_,Z&&Z.strategy()==="all"&&_===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(Y,Z){return Y}setToken(Y){return this.authToken=Y,this}static[F]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(Y,Z,X){if(this.cache===void 0||M(this.cache,h8)||this.queryMetadata===void 0)try{return await X()}catch(_){throw new J2(Y,Z,_)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await X()}catch(_){throw new J2(Y,Z,_)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[_]=await Promise.all([X(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return _}catch(_){throw new J2(Y,Z,_)}if(!this.cacheConfig)try{return await X()}catch(_){throw new J2(Y,Z,_)}if(this.queryMetadata.type==="select"){let _=await this.cache.get(this.cacheConfig.tag??await n5(Y,Z),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(_===void 0){let G;try{G=await X()}catch($){throw new J2(Y,Z,$)}return await this.cache.put(this.cacheConfig.tag??await n5(Y,Z),G,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),G}return _}try{return await X()}catch(_){throw new J2(Y,Z,_)}}}class t5{constructor(Y){this.dialect=Y}static[F]="PgSession";execute(Y,Z){return V0.startActiveSpan("drizzle.operation",()=>{return V0.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(Y),void 0,void 0,!1)}).setToken(Z).execute(void 0,Z)})}all(Y){return this.prepareQuery(this.dialect.sqlToQuery(Y),void 0,void 0,!1).all()}async count(Y,Z){let X=await this.execute(Y,Z);return Number(X[0].count)}}class a5 extends f8{constructor(Y,Z,X,_=0){super(Y,Z,X);this.schema=X,this.nestedIndex=_}static[F]="PgTransaction";rollback(){throw new D5}getTransactionConfigSQL(Y){let Z=[];if(Y.isolationLevel)Z.push(`isolation level ${Y.isolationLevel}`);if(Y.accessMode)Z.push(Y.accessMode);if(typeof Y.deferrable==="boolean")Z.push(Y.deferrable?"deferrable":"not deferrable");return O.raw(Z.join(" "))}setTransaction(Y){return this.session.execute(O`set transaction ${this.getTransactionConfigSQL(Y)}`)}}class P3 extends s5{constructor(Y,Z,X,_,G,$,W,H,Q,J){super({sql:Z,params:X},G,$,W);this.client=Y,this.queryString=Z,this.params=X,this.logger=_,this.fields=H,this._isResponseInArrayMode=Q,this.customResultMapper=J}static[F]="PostgresJsPreparedQuery";async execute(Y={}){return V0.startActiveSpan("drizzle.execute",async(Z)=>{let X=V5(this.params,Y);Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X);let{fields:_,queryString:G,client:$,joinsNotNullableMap:W,customResultMapper:H}=this;if(!_&&!H)return V0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(G,X,async()=>{return await $.unsafe(G,X)})});let Q=await V0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":G,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(G,X,async()=>{return await $.unsafe(G,X).values()})});return V0.startActiveSpan("drizzle.mapResponse",()=>{return H?H(Q):Q.map((J)=>P7(_,J,W))})})}all(Y={}){return V0.startActiveSpan("drizzle.execute",async(Z)=>{let X=V5(this.params,Y);return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),V0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(this.queryString,X,async()=>{return this.client.unsafe(this.queryString,X)})})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class k8 extends t5{constructor(Y,Z,X,_={}){super(Z);this.client=Y,this.schema=X,this.options=_,this.logger=_.logger??new M5,this.cache=_.cache??new h8}static[F]="PostgresJsSession";logger;cache;prepareQuery(Y,Z,X,_,G,$,W){return new P3(this.client,Y.sql,Y.params,this.logger,this.cache,$,W,Z,_,G)}query(Y,Z){return this.logger.logQuery(Y,Z),this.client.unsafe(Y,Z).values()}queryObjects(Y,Z){return this.client.unsafe(Y,Z)}transaction(Y,Z){return this.client.begin(async(X)=>{let _=new k8(X,this.dialect,this.schema,this.options),G=new e5(this.dialect,_,this.schema);if(Z)await G.setTransaction(Z);return Y(G)})}}class e5 extends a5{constructor(Y,Z,X,_=0){super(Y,Z,X,_);this.session=Z}static[F]="PostgresJsTransaction";transaction(Y){return this.session.client.savepoint((Z)=>{let X=new k8(Z,this.dialect,this.schema,this.session.options),_=new e5(this.dialect,X,this.schema);return Y(_)})}}class v3 extends f8{static[F]="PostgresJsDatabase"}function I4(Y,Z={}){let X=(Q)=>Q;for(let Q of["1184","1082","1083","1114","1182","1185","1115","1231"])Y.options.parsers[Q]=X,Y.options.serializers[Q]=X;Y.options.serializers["114"]=X,Y.options.serializers["3802"]=X;let _=new c2({casing:Z.casing}),G;if(Z.logger===!0)G=new L5;else if(Z.logger!==!1)G=Z.logger;let $;if(Z.schema){let Q=_3(Z.schema,$3);$={fullSchema:Z.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let W=new k8(Y,_,$,{logger:G,cache:Z.cache}),H=new v3(_,W,$);if(H.$client=Y,H.$cache=Z.cache,H.$cache)H.$cache.invalidate=Z.cache?.onMutate;return H}function $Y(...Y){if(typeof Y[0]==="string"){let Z=R4(Y[0]);return I4(Z,Y[1])}if(f7(Y[0])){let{connection:Z,client:X,..._}=Y[0];if(X)return I4(X,_);if(typeof Z==="object"&&Z.url!==void 0){let{url:$,...W}=Z,H=R4($,W);return I4(H,_)}let G=R4(Z);return I4(G,_)}return I4(Y[0],Y[1])}((Y)=>{function Z(X){return I4({options:{parsers:{},serializers:{}}},X)}Y.mock=Z})($Y||($Y={}));var ZX={};bH(ZX,{users:()=>l2,untrackedUserColumnNames:()=>jE,twoFactorMethod:()=>b3,trackedUserColumnName:()=>SE,trackableUserColumnNames:()=>h3,signInHistory:()=>vE,role:()=>f3,players:()=>YX,passwordResetAttempts:()=>xE,games:()=>HY,banishedIps:()=>fE,accountActions:()=>PE,accountAction:()=>k3});function C2(){return t0({length:24}).$type()}function x3(Y){return O`lower(${Y})`}var WY=O`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,f3=O8("role",["admin","user"]),l2=K2("users",{id:q1().primaryKey().defaultRandom(),username:t0({length:16}).notNull(),emailOffered:t0({length:254}).notNull(),emailVerified:t0({length:254}),password:t0({length:254}),createdAtIso:C2().notNull().default(WY),createdIp:t0({length:45}).notNull(),isActive:R8().notNull().default(!1),verifiedAtIso:C2(),userRole:f3().default("user")},(Y)=>[p5("usernameUniqueIndex").on(x3(Y.username)),p5("emailVerifiedUniqueIndex").on(x3(Y.emailVerified))]),jE=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],h3=["username","emailOffered","emailVerified","password","userRole"],SE=O8("trackedUserColumnName",h3),k3=O8("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),PE=K2("accountActions",{userId:q1().references(()=>l2.id).primaryKey(),action:k3().notNull(),code:t0({length:254}).notNull(),wrongCodeCount:N8().notNull().default(0),expiresAtIso:C2().notNull()}),HY=K2("games",{id:q1().primaryKey().defaultRandom()}),YX=K2("players",{userId:q1().notNull().references(()=>l2.id,{onDelete:"cascade"}),gameId:q1().notNull().references(()=>HY.id,{onDelete:"cascade"}),score:N8().notNull()},(Y)=>[PW({name:"players_userId_gameId_pk",columns:[Y.userId,Y.gameId]})]),vE=K2("signInHistory",{id:q1().primaryKey().defaultRandom(),userId:q1().references(()=>l2.id,{onDelete:"cascade"}),signInTimeIso:C2().notNull().default(WY),ipAddress:t0({length:45}).notNull(),userAgent:t0({length:1024}),successful:R8().notNull().default(!1)}),b3=O8("twoFactorMethod",["email","phone"]),xE=K2("passwordResetAttempts",{id:q1().primaryKey().defaultRandom(),userId:q1().notNull().references(()=>l2.id,{onDelete:"cascade"}),requestedIp:t0({length:45}).notNull(),requestedAtIso:C2().notNull().default(WY),succeededIp:t0({length:45}),succeededAtIso:C2(),verificationMethod:b3().notNull()}),fE=K2("banishedIps",{ip:t0({length:45}).primaryKey(),reason:t0({length:2048}).notNull(),banishedAtIso:C2().notNull().default(WY),banishedUntilIso:C2()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class XX{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(hE.resolve(__dirname,"notify_update.sql"));let Y=[d0(l2),d0(HY),d0(YX)];await this.sql`SELECT create_notify_triggers(${this.sql.array(Y)})`,await this.sql.listen("table_update",(Z)=>{let X=Z.split(","),_=X[0],G=X[1],$=`${_}("${G}")`;if(this.observers.has($))this.observers.get($).next($)})}constructor(Y=!1,Z={host:y1.POSTGRES_HOST,port:y1.POSTGRES_PORT,user:y1.POSTGRES_USER,password:y1.POSTGRES_PASSWORD,database:y1.POSTGRES_DATABASE}){this.options=Z,this.sql=R4(Z),this.drizzle=$Y(this.sql,{schema:ZX,logger:Y})}observe(Y,Z){if(!this.observers.has(Y))this.observers.set(Y,new W0);this.observers.get(Y).subscribe("SINGLETON",Z)}}var JY={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 kE(Y){return Number.parseInt(Y,10)}var bE=F1(JY),yE=bE.keyof().pipe((Y)=>kE(Y)),y3=F1([yE,"string"]);var GX=new W7,{logger:D1}=GX;Object.assign(console,D1,{log:D1.info});D1.info("ready");var _X=p3(import.meta.dir,"..","app"),$f=new XX({logQuery(Y,Z){D1.info("\uD83D\uDCDD query",Y,Z)}});uE({hostname:"0.0.0.0",port:y1.FRONTEND_PORT??3333,...T6??void 0,async fetch(Y){try{let Z=new Date,X=new URL(Y.url);if(D1.info(Y.method,X.pathname),X.pathname==="/")return new Response(Bun.file(p3(_X,"index.html")));if(X.pathname==="/index.html")return Response.redirect("/");let _=pE(_X,X.pathname),G=mE(_);if(!G.startsWith(_X))throw[403,"Access Denied"];if(!await g3(G).exists())return Response.redirect("/");return new Response(g3(G))}catch(Z){let X=y3(Z);if(X instanceof F1.errors===!1){let[_,G]=X,W=`${JY[_]}. ${G}`;return D1.info(`\u274C ${_}: ${W}`),new Response(W,{status:_})}if(Z instanceof Error)D1.error(Z.message);else{let _=K6(Z);D1.error("frontend server threw",_)}return new Response(JY[500],{status:500})}}});function QY(){D1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{D1.info("\u2757 received SIGINT; exiting gracefully"),QY()});process.on("SIGTERM",()=>{D1.info("\u2757 received SIGTERM; exiting gracefully"),QY()});process.on("exit",()=>{D1.info("\u2757 received exit; exiting gracefully"),QY()});GX.on("timeToStop",()=>{D1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),QY()});var{version:dE}=await Bun.file(gE.resolve(import.meta.dir,"../package.json")).json();D1.info(`\uD83D\uDEEB frontend v${dE} running at http://localhost:${y1.FRONTEND_PORT}/`);GX.emit("alive");