tempest.games 0.2.58 → 0.2.60

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,80 +1,80 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var cH=Object.create;var{getPrototypeOf:lH,defineProperty:DY,getOwnPropertyNames:oH}=Object;var iH=Object.prototype.hasOwnProperty;var aE=(Y,Z,X)=>{X=Y!=null?cH(lH(Y)):{};let G=Z||!Y||!Y.__esModule?DY(X,"default",{value:Y,enumerable:!0}):X;for(let _ of oH(Y))if(!iH.call(G,_))DY(G,_,{get:()=>Y[_],enumerable:!0});return G};var eE=(Y,Z)=>()=>(Z||Y((Z={exports:{}}).exports,Z),Z.exports);var nH=(Y,Z)=>{for(var X in Z)DY(Y,X,{get:Z[X],enumerable:!0,configurable:!0,set:(G)=>Z[X]=()=>G})};var YV=(Y,Z)=>()=>(Y&&(Z=Y(Y=0)),Z);var ZV=import.meta.require;import iE,{join as nE,normalize as rE,resolve as tW}from"path";var U4=(Y)=>Array.isArray(Y)?Y:[Y],RX=(Y,Z)=>{let X=[[],[]];for(let G of Y)if(Z(G))X[0].push(G);else X[1].push(G);return X},p8=Array,s1=(Y,Z)=>Y.includes(Z),wX=(Y,Z=0)=>[...Array(Y)].map((X,G)=>G+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},t1=(Y,Z)=>{if(Z===void 0||Z===null)return Y??[];if(Y===void 0||Y===null)return U4(Z);return Y.concat(Z)},NX=(...Y)=>Y.reduce(t1,[]),c1=(Y,Z,X)=>{if(Y===void 0)return Array.isArray(Z)?Z:[Z];let G=X?.isEqual??((_,$)=>_===$);for(let _ of U4(Z))if(!Y.some(($)=>G($,_)))Y.push(_);return Y},IX=(Y,Z)=>Y.reduce((X,G)=>{let _=G[Z];return X[_]=Z0(X[_],G),X},{}),a1=(Y,Z,X)=>Y.length===Z.length&&Y.every(X?.isEqual?(G,_)=>X.isEqual(G,Z[_]):(G,_)=>G===Z[_]);var W1=(Y,Z)=>y0(Y)===Z,y0=(Y)=>{let Z=typeof Y;return Z==="object"?Y===null?"null":"object":Z==="function"?"object":Z},H1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},KX={...H1,function:"a function"};class BX extends Error{}var G0=(Y)=>C4(Y,BX),C4=(Y,Z=Error)=>{throw new Z(Y)};class q2 extends Error{name="ParseError"}var A=(Y)=>C4(Y,q2),S1=(Y)=>` ${Y}`;var o=(Y,Z)=>{let X={},G=Array.isArray(Y),_=!1;for(let[$,W]of Object.entries(Y).entries()){let H=G?Z($,W[1]):Z(...W,$);_||=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 _?Object.values(X):X};var LY=Object.entries;var g0=(Y,Z)=>(Y in Z),n4=(Y,Z)=>(Z in Y);class MY{constructor(Y){Object.assign(this,Y)}}var TX=class{};class j2 extends TX{}var rH=(Y,Z)=>{let X={},G={},_;for(_ in Y)if(_ in Z)X[_]=Y[_];else G[_]=Y[_];return[X,G]};var CX=(Y,Z)=>rH(Y,Z)[1],l1=(Y)=>Object.keys(Y).length===0,q4=(Y)=>[...Object.entries(Y),...Object.getOwnPropertySymbols(Y).map((Z)=>[Z,Y[Z]])],qX=(Y,Z)=>Object.defineProperties(Y,Object.getOwnPropertyDescriptors(Z)),jX=(Y)=>{let Z=Object.keys(Y).sort(),X={};for(let G=0;G<Z.length;G++)X[Z[G]]=Y[Z[G]];return X};var L1=S1("represents an uninitialized value"),PX=(Y)=>Object.values(Y).filter((Z)=>{if(typeof Z==="number")return!0;return typeof Y[Z]!=="number"});var AY={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},RY=globalThis.File??Blob,wY={ArrayBuffer,Blob,File:RY,FormData,Headers,Request,Response,URL},sH={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},j4={...AY,...wY,...sH,String,Number,Boolean},P2=(Y)=>{let Z=Object.getPrototypeOf(Y);while(Z?.constructor&&(!g0(Z.constructor.name,j4)||!(Y instanceof j4[Z.constructor.name])))Z=Object.getPrototypeOf(Z);let X=Z?.constructor?.name;if(X===void 0||X==="Object")return;return X},S2=(Y)=>typeof Y==="object"&&Y!==null?P2(Y)??"object":y0(Y);var F0=Array.isArray,tH={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"},aH={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"},eH={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"},SX={...tH,...aH,...eH},v2=(Y)=>{let Z=Object(Y).name??null;return Z&&g0(Z,j4)&&j4[Z]===Y?Z:null};var NY=(Y,Z)=>{let X=Y.prototype;while(X!==null){if(X===Z.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var vX=(Y)=>xX(Y,new Map),xX=(Y,Z)=>{if(typeof Y!=="object"||Y===null)return Y;if(Z?.has(Y))return Z.get(Y);let X=v2(Y.constructor);if(X==="Date")return new Date(Y.getTime());if(X&&X!=="Array")return Y;let G=Array.isArray(Y)?Y.slice():Object.create(Object.getPrototypeOf(Y)),_=Object.getOwnPropertyDescriptors(Y);if(Z){Z.set(Y,G);for(let $ in _){let W=_[$];if("get"in W||"set"in W)continue;W.value=xX(W.value,Z)}}return Object.defineProperties(G,_),G};var YJ=(Y)=>{let Z=L1;return()=>Z===L1?Z=Y():Z},E4=(Y)=>typeof Y==="function"&&Y.length===0;var fX=class extends Function{constructor(...Y){let Z=Y.slice(0,-1),X=Y.at(-1);try{super(...Z,X)}catch(G){return G0(`Encountered an unexpected error while compiling your definition:
4
- Message: ${G}
5
- Source: (${Y.slice(0,-1)}) => {
6
- ${Y.at(-1)}
7
- }`)}}};class v1{constructor(Y,...[Z]){return Object.assign(Object.setPrototypeOf(Y.bind(Z?.bind??this),this.constructor.prototype),Z?.attach)}}var hX=YJ(()=>{try{return Function("return false")()}catch{return!0}});var NV=S1("brand");var kX=S1("arkInferred");var BV=S1("args");class r0{constructor(){}}var ZJ=()=>{try{return((Error().stack?.split(`
8
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},XJ=globalThis.process?.env??{},bX={fileName:ZJ,env:XJ};var yX=(Y)=>Y[0].toUpperCase()+Y.slice(1);var IY=(Y)=>new RegExp(GJ(Y),typeof Y==="string"?"":Y.flags);var GJ=(Y)=>{return`^(?:${typeof Y==="string"?Y:Y.source})$`};var e1={negativeLookahead:(Y)=>`(?!${Y})`,nonCapturingGroup:(Y)=>`(?:${Y})`},x2="\\",V4={" ":1,"\n":1,"\t":1};var _J=/^-0\.?0*$/.source,pX=/[1-9]\d*/.source,$J=/\.\d+/.source,WJ=/\.\d*[1-9]/.source,mX=(Y)=>IY(e1.negativeLookahead(_J)+e1.nonCapturingGroup("-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+pX)+e1.nonCapturingGroup(Y.decimalPattern)+"?")+(Y.allowDecimalOnly?"|"+Y.decimalPattern:"")+"?")),gX=mX({decimalPattern:WJ,allowDecimalOnly:!1}),HJ=gX.test.bind(gX),m8=mX({decimalPattern:$J,allowDecimalOnly:!0}),vV=m8.test.bind(m8),JJ=/^-?\d*\.?\d*$/,QJ=(Y)=>Y.length!==0&&JJ.test(Y),f2=IY(e1.negativeLookahead("^-0$")+"-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+pX))),zJ=f2.test.bind(f2),KY=/^-?\d+$/,FJ=KY.test.bind(KY),uX={number:"a number",bigint:"a bigint",integer:"an integer"},dX=(Y,Z)=>`'${Y}' was parsed as ${uX[Z]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,UJ=(Y,Z)=>Z==="number"?HJ(Y):zJ(Y),EJ=(Y,Z)=>Z==="number"?Number(Y):Number.parseInt(Y),VJ=(Y,Z)=>Z==="number"?QJ(Y):FJ(Y),cX=(Y,Z)=>BY(Y,"number",Z),lX=(Y,Z)=>BY(Y,"number",{...Z,strict:!0}),oX=(Y,Z)=>BY(Y,"integer",Z),BY=(Y,Z,X)=>{let G=EJ(Y,Z);if(!Number.isNaN(G)){if(VJ(Y,Z)){if(X?.strict)return UJ(Y,Z)?G:A(dX(Y,Z));return G}}return X?.errorOnFail?A(X?.errorOnFail===!0?`Failed to parse ${uX[Z]} from '${Y}'`:X?.errorOnFail):void 0},iX=(Y)=>{if(Y[Y.length-1]!=="n")return;let Z=Y.slice(0,-1),X;try{X=BigInt(Z)}catch{return}if(f2.test(Z))return X;if(KY.test(Z))return A(dX(Y,"bigint"))};var OJ="0.49.0",DJ={version:OJ,filename:bX.fileName(),FileConstructor:RY},P4=DJ,nX=new Map,TY=Object.create(null),h2=(Y)=>{let Z=nX.get(Y);if(Z)return Z;let X=LJ(Y);if(TY[X])X=`${X}${TY[X]++}`;else TY[X]=1;return P4[X]=Y,nX.set(Y,X),X},O4=(Y)=>/^[$A-Z_a-z][\w$]*$/.test(Y),LJ=(Y)=>{switch(typeof Y){case"object":{if(Y===null)break;let Z=P2(Y)??"object";return Z[0].toLowerCase()+Z.slice(1)}case"function":return O4(Y.name)?Y.name:"fn";case"symbol":return Y.description&&O4(Y.description)?Y.description:"symbol"}return G0(`Unexpected attempt to register serializable value of type ${y0(Y)}`)};var k2=(Y)=>typeof Y==="string"?JSON.stringify(Y):typeof Y==="bigint"?`${Y}n`:`${Y}`;var rX=(Y,Z={})=>b2(Y,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...Z},[]);var i=(Y,Z)=>{switch(y0(Y)){case"object":let X=Y,G=X.constructor.name;return G==="Object"||G==="Array"?Z?.quoteKeys===!1?u8(X,Z?.indent??0,""):JSON.stringify(b2(X,r4,[]),null,Z?.indent):u8(X,Z?.indent??0,"");case"symbol":return r4.onSymbol(Y);default:return k2(Y)}},u8=(Y,Z,X)=>{if(typeof Y==="function")return r4.onFunction(Y);if(typeof Y!=="object"||Y===null)return k2(Y);let G=X+" ".repeat(Z);if(Array.isArray(Y)){if(Y.length===0)return"[]";let $=Y.map((W)=>u8(W,Z,G)).join(`,
9
- `+G);return Z?`[
10
- ${G}${$}
11
- ${X}]`:`[${$}]`}let _=Y.constructor.name;if(_==="Object"){let $=q4(Y).map(([W,H])=>{let Q=typeof W==="symbol"?r4.onSymbol(W):O4(W)?W:JSON.stringify(W),J=u8(H,Z,G);return`${G}${Q}: ${J}`});if($.length===0)return"{}";return Z?`{
12
- ${$.join(`,
3
+ var mH=Object.create;var{getPrototypeOf:uH,defineProperty:DX,getOwnPropertyNames:dH}=Object;var cH=Object.prototype.hasOwnProperty;var nE=(X,Y,Z)=>{Z=X!=null?mH(uH(X)):{};let _=Y||!X||!X.__esModule?DX(Z,"default",{value:X,enumerable:!0}):Z;for(let G of dH(X))if(!cH.call(_,G))DX(_,G,{get:()=>X[G],enumerable:!0});return _};var rE=(X,Y)=>()=>(Y||X((Y={exports:{}}).exports,Y),Y.exports);var lH=(X,Y)=>{for(var Z in Y)DX(X,Z,{get:Y[Z],enumerable:!0,configurable:!0,set:(_)=>Y[Z]=()=>_})};var sE=(X,Y)=>()=>(X&&(Y=X(X=0)),Y);var tE=import.meta.require;import dE,{join as cE,normalize as lE,resolve as n$}from"path";var U4=(X)=>Array.isArray(X)?X:[X],w5=(X,Y)=>{let Z=[[],[]];for(let _ of X)if(Y(_))Z[0].push(_);else Z[1].push(_);return Z},p2=Array,r1=(X,Y)=>X.includes(Y),N5=(X,Y=0)=>[...Array(X)].map((Z,_)=>_+Y),t=(X,Y,Z)=>{if(X===void 0)return Y===void 0?[]:Array.isArray(Y)?Y:[Y];if(Z?.prepend)if(Array.isArray(Y))X.unshift(...Y);else X.unshift(Y);else if(Array.isArray(Y))X.push(...Y);else X.push(Y);return X},s1=(X,Y)=>{if(Y===void 0||Y===null)return X??[];if(X===void 0||X===null)return U4(Y);return X.concat(Y)},I5=(...X)=>X.reduce(s1,[]),c1=(X,Y,Z)=>{if(X===void 0)return Array.isArray(Y)?Y:[Y];let _=Z?.isEqual??((G,W)=>G===W);for(let G of U4(Y))if(!X.some((W)=>_(W,G)))X.push(G);return X},K5=(X,Y)=>X.reduce((Z,_)=>{let G=_[Y];return Z[G]=t(Z[G],_),Z},{}),t1=(X,Y,Z)=>X.length===Y.length&&X.every(Z?.isEqual?(_,G)=>Z.isEqual(_,Y[G]):(_,G)=>_===Y[G]);var _1=(X,Y)=>x0(X)===Y,x0=(X)=>{let Y=typeof X;return Y==="object"?X===null?"null":"object":Y==="function"?"object":Y},G1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},B5={...G1,function:"a function"};class T5 extends Error{}var e=(X)=>C4(X,T5),C4=(X,Y=Error)=>{throw new Y(X)};class C8 extends Error{name="ParseError"}var R=(X)=>C4(X,C8),P1=(X)=>` ${X}`;var d=(X,Y)=>{let Z={},_=Array.isArray(X),G=!1;for(let[W,$]of Object.entries(X).entries()){let H=_?Y(W,$[1]):Y(...$,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")Z[J.group]=t(Z[J.group],z);else Z[J]=z}return G?Object.values(Z):Z};var LX=Object.entries;var f0=(X,Y)=>(X in Y),i4=(X,Y)=>(Y in X);class MX{constructor(X){Object.assign(this,X)}}var C5=class{};class q8 extends C5{}var oH=(X,Y)=>{let Z={},_={},G;for(G in X)if(G in Y)Z[G]=X[G];else _[G]=X[G];return[Z,_]};var q5=(X,Y)=>oH(X,Y)[1],l1=(X)=>Object.keys(X).length===0,q4=(X)=>[...Object.entries(X),...Object.getOwnPropertySymbols(X).map((Y)=>[Y,X[Y]])],j5=(X,Y)=>Object.defineProperties(X,Object.getOwnPropertyDescriptors(Y)),S5=(X)=>{let Y=Object.keys(X).sort(),Z={};for(let _=0;_<Y.length;_++)Z[Y[_]]=X[Y[_]];return Z};var V1=P1("represents an uninitialized value"),P5=(X)=>Object.values(X).filter((Y)=>{if(typeof Y==="number")return!0;return typeof X[Y]!=="number"});var AX={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},RX=globalThis.File??Blob,wX={ArrayBuffer,Blob,File:RX,FormData,Headers,Request,Response,URL},iH={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},j4={...AX,...wX,...iH,String,Number,Boolean},j8=(X)=>{let Y=Object.getPrototypeOf(X);while(Y?.constructor&&(!f0(Y.constructor.name,j4)||!(X instanceof j4[Y.constructor.name])))Y=Object.getPrototypeOf(Y);let Z=Y?.constructor?.name;if(Z===void 0||Z==="Object")return;return Z},S8=(X)=>typeof X==="object"&&X!==null?j8(X)??"object":x0(X);var Q0=Array.isArray,nH={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"},rH={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"},sH={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"},v5={...nH,...rH,...sH},P8=(X)=>{let Y=Object(X).name??null;return Y&&f0(Y,j4)&&j4[Y]===X?Y:null};var NX=(X,Y)=>{let Z=X.prototype;while(Z!==null){if(Z===Y.prototype)return!0;Z=Object.getPrototypeOf(Z)}return!1};var x5=(X)=>f5(X,new Map),f5=(X,Y)=>{if(typeof X!=="object"||X===null)return X;if(Y?.has(X))return Y.get(X);let Z=P8(X.constructor);if(Z==="Date")return new Date(X.getTime());if(Z&&Z!=="Array")return X;let _=Array.isArray(X)?X.slice():Object.create(Object.getPrototypeOf(X)),G=Object.getOwnPropertyDescriptors(X);if(Y){Y.set(X,_);for(let W in G){let $=G[W];if("get"in $||"set"in $)continue;$.value=f5($.value,Y)}}return Object.defineProperties(_,G),_};var tH=(X)=>{let Y=V1;return()=>Y===V1?Y=X():Y},E4=(X)=>typeof X==="function"&&X.length===0;var h5=class extends Function{constructor(...X){let Y=X.slice(0,-1),Z=X.at(-1);try{super(...Y,Z)}catch(_){return e(`Encountered an unexpected error while compiling your definition:
4
+ Message: ${_}
5
+ Source: (${X.slice(0,-1)}) => {
6
+ ${X.at(-1)}
7
+ }`)}}};class v1{constructor(X,...[Y]){return Object.assign(Object.setPrototypeOf(X.bind(Y?.bind??this),this.constructor.prototype),Y?.attach)}}var k5=tH(()=>{try{return Function("return false")()}catch{return!0}});var MO=P1("brand");var b5=P1("arkInferred");var wO=P1("args");class o0{constructor(){}}var aH=()=>{try{return((Error().stack?.split(`
8
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},eH=globalThis.process?.env??{},y5={fileName:aH,env:eH};var g5=(X)=>X[0].toUpperCase()+X.slice(1);var IX=(X)=>new RegExp(XJ(X),typeof X==="string"?"":X.flags);var XJ=(X)=>{return`^(?:${typeof X==="string"?X:X.source})$`};var a1={negativeLookahead:(X)=>`(?!${X})`,nonCapturingGroup:(X)=>`(?:${X})`},v8="\\",O4={" ":1,"\n":1,"\t":1};var YJ=/^-0\.?0*$/.source,m5=/[1-9]\d*/.source,ZJ=/\.\d+/.source,_J=/\.\d*[1-9]/.source,u5=(X)=>IX(a1.negativeLookahead(YJ)+a1.nonCapturingGroup("-?"+a1.nonCapturingGroup(a1.nonCapturingGroup("0|"+m5)+a1.nonCapturingGroup(X.decimalPattern)+"?")+(X.allowDecimalOnly?"|"+X.decimalPattern:"")+"?")),p5=u5({decimalPattern:_J,allowDecimalOnly:!1}),GJ=p5.test.bind(p5),m2=u5({decimalPattern:ZJ,allowDecimalOnly:!0}),qO=m2.test.bind(m2),WJ=/^-?\d*\.?\d*$/,$J=(X)=>X.length!==0&&WJ.test(X),x8=IX(a1.negativeLookahead("^-0$")+"-?"+a1.nonCapturingGroup(a1.nonCapturingGroup("0|"+m5))),HJ=x8.test.bind(x8),KX=/^-?\d+$/,JJ=KX.test.bind(KX),d5={number:"a number",bigint:"a bigint",integer:"an integer"},c5=(X,Y)=>`'${X}' was parsed as ${d5[Y]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,QJ=(X,Y)=>Y==="number"?GJ(X):HJ(X),zJ=(X,Y)=>Y==="number"?Number(X):Number.parseInt(X),FJ=(X,Y)=>Y==="number"?$J(X):JJ(X),l5=(X,Y)=>BX(X,"number",Y),o5=(X,Y)=>BX(X,"number",{...Y,strict:!0}),i5=(X,Y)=>BX(X,"integer",Y),BX=(X,Y,Z)=>{let _=zJ(X,Y);if(!Number.isNaN(_)){if(FJ(X,Y)){if(Z?.strict)return QJ(X,Y)?_:R(c5(X,Y));return _}}return Z?.errorOnFail?R(Z?.errorOnFail===!0?`Failed to parse ${d5[Y]} from '${X}'`:Z?.errorOnFail):void 0},n5=(X)=>{if(X[X.length-1]!=="n")return;let Y=X.slice(0,-1),Z;try{Z=BigInt(Y)}catch{return}if(x8.test(Y))return Z;if(KX.test(Y))return R(c5(X,"bigint"))};var UJ="0.49.0",EJ={version:UJ,filename:y5.fileName(),FileConstructor:RX},S4=EJ,r5=new Map,TX=Object.create(null),f8=(X)=>{let Y=r5.get(X);if(Y)return Y;let Z=OJ(X);if(TX[Z])Z=`${Z}${TX[Z]++}`;else TX[Z]=1;return S4[Z]=X,r5.set(X,Z),Z},V4=(X)=>/^[$A-Z_a-z][\w$]*$/.test(X),OJ=(X)=>{switch(typeof X){case"object":{if(X===null)break;let Y=j8(X)??"object";return Y[0].toLowerCase()+Y.slice(1)}case"function":return V4(X.name)?X.name:"fn";case"symbol":return X.description&&V4(X.description)?X.description:"symbol"}return e(`Unexpected attempt to register serializable value of type ${x0(X)}`)};var h8=(X)=>typeof X==="string"?JSON.stringify(X):typeof X==="bigint"?`${X}n`:`${X}`;var s5=(X,Y={})=>k8(X,{onUndefined:"$ark.undefined",onBigInt:(Z)=>`$ark.bigint-${Z}`,...Y},[]);var c=(X,Y)=>{switch(x0(X)){case"object":let Z=X,_=Z.constructor.name;return _==="Object"||_==="Array"?Y?.quoteKeys===!1?u2(Z,Y?.indent??0,""):JSON.stringify(k8(Z,n4,[]),null,Y?.indent):u2(Z,Y?.indent??0,"");case"symbol":return n4.onSymbol(X);default:return h8(X)}},u2=(X,Y,Z)=>{if(typeof X==="function")return n4.onFunction(X);if(typeof X!=="object"||X===null)return h8(X);let _=Z+" ".repeat(Y);if(Array.isArray(X)){if(X.length===0)return"[]";let W=X.map(($)=>u2($,Y,_)).join(`,
9
+ `+_);return Y?`[
10
+ ${_}${W}
11
+ ${Z}]`:`[${W}]`}let G=X.constructor.name;if(G==="Object"){let W=q4(X).map(([$,H])=>{let Q=typeof $==="symbol"?n4.onSymbol($):V4($)?$:JSON.stringify($),J=u2(H,Y,_);return`${_}${Q}: ${J}`});if(W.length===0)return"{}";return Y?`{
12
+ ${W.join(`,
13
13
  `)}
14
- ${X}}`:`{${$.join(", ")}}`}if(Y instanceof Date)return S4(Y);if("expression"in Y&&typeof Y.expression==="string")return Y.expression;return _},r4={onCycle:()=>"(cycle)",onSymbol:(Y)=>`Symbol(${h2(Y)})`,onFunction:(Y)=>`Function(${h2(Y)})`},b2=(Y,Z,X)=>{switch(y0(Y)){case"object":{let G=Y;if("toJSON"in G&&typeof G.toJSON==="function")return G.toJSON();if(typeof G==="function")return r4.onFunction(G);if(X.includes(G))return"(cycle)";let _=[...X,G];if(Array.isArray(G))return G.map((W)=>b2(W,Z,_));if(G instanceof Date)return G.toDateString();let $={};for(let W in G)$[W]=b2(G[W],Z,_);for(let W of Object.getOwnPropertySymbols(G))$[Z.onSymbol?.(W)??W.toString()]=b2(G[W],Z,_);return $}case"symbol":return r4.onSymbol(Y);case"bigint":return Z.onBigInt?.(Y)??`${Y}n`;case"undefined":return Z.onUndefined??"undefined";case"string":return Y.replaceAll("\\","\\\\");default:return Y}},S4=(Y)=>{let Z=Y.getFullYear(),X=Y.getMonth(),G=Y.getDate(),_=Y.getHours(),$=Y.getMinutes(),W=Y.getSeconds(),H=Y.getMilliseconds();if(X===0&&G===1&&_===0&&$===0&&W===0&&H===0)return`${Z}`;let Q=`${MJ[X]} ${G}, ${Z}`;if(_===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+=`.${RJ(H,3)}`;else if(AJ.test(J))J=J.slice(0,-3);return`${J+z}, ${Q}`},MJ=["January","February","March","April","May","June","July","August","September","October","November","December"],AJ=/:\d\d:00$/,RJ=(Y,Z)=>String(Y).padStart(Z,"0");var sX=(Y,Z,...[X])=>{let G=X?.stringifySymbol??i,_=Y;switch(typeof Z){case"string":_=O4(Z)?Y===""?Z:`${Y}.${Z}`:`${Y}[${JSON.stringify(Z)}]`;break;case"number":_=`${Y}[${Z}]`;break;case"symbol":_=`${Y}[${G(Z)}]`;break;default:if(X?.stringifyNonKey)_=`${Y}[${X.stringifyNonKey(Z)}]`;else A(`${i(Z)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return _},Y4=(Y,...Z)=>Y.reduce((X,G)=>sX(X,G,...Z),"");class y2 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=Y4(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Y="",Z=[Y];for(let X of this)Y=sX(Y,X),Z.push(Y);return this.cache.stringifyAncestors=Z}}class CY{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]===x2)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 V4))}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 GO=S1("implementedTraits");var qY="$ark",wJ=2;while(qY in globalThis)qY=`$ark${wJ++}`;var tX=qY;globalThis[tX]=P4;var I=P4,NJ=(Y)=>`${tX}.${Y}`,T0=(Y)=>NJ(h2(Y));class d8 extends j2{argNames;body="";constructor(...Y){super();this.argNames=Y;for(let Z of Y){if(Z in this)throw 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 jY(Y,Z)}index(Y,Z=!1){return aX(`${Y}`,Z)}line(Y){return this.body+=`${" ".repeat(this.indentation)}${Y}
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
- `).map((X)=>" ".repeat(Z)+`${X}`).join(`
17
- `):this.body} }`}compile(){return new fX(...this.argNames,this.body)}}var Z4=(Y)=>W1(Y,"object")||typeof Y==="symbol"?T0(Y):k2(Y),jY=(Y,Z=!1)=>{if(typeof Y==="string"&&O4(Y))return`${Z?"?":""}.${Y}`;return aX(IJ(Y),Z)},IJ=(Y)=>typeof Y==="symbol"?T0(Y):JSON.stringify(Y),aX=(Y,Z=!1)=>`${Z?"?.":""}[${Y}]`;class g2 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,G=typeof Y==="string"?!0:this.requiresContextFor(Y),_=typeof Y==="string"?Y:Y.id;if(G)return`${this.referenceToId(_,Z)}(${X}, ${this.ctx})`;return`${this.referenceToId(_,Z)}(${X})`}referenceToId(Y,Z){let X=Z?.kind??this.traversalKind,G=`this.${Y}${X}`;return Z?.bind?`${G}.bind(${Z?.bind})`:G}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 G=this.requiresContextFor(X);if(G)this.line(`${this.ctx}.path.push(${Y})`);if(this.check(X,{arg:Z}),G)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]),Y1=S1("arkKind"),y=(Y,Z)=>Y?.[Y1]===Z,D0=(Y)=>y(Y,"root")||y(Y,"constraint");var eX=["unit","proto","domain"],s4=["required","optional","index","sequence"],PY=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],l8=[...PY,...s4,"structure","predicate"],t4=["alias","union","morph","unit","intersection","proto","domain"],KJ=[...t4,...l8],o8=o(l8,(Y,Z)=>[Z,1]),YG=o([...s4,"undeclared"],(Y,Z)=>[Z,1]),ZG=o(KJ,(Y,Z)=>[Z,Y]),a4=(Y)=>typeof Y==="string"&&(Y in ZG);var e4=(Y)=>ZG[Y],i8=(Y)=>t4.slice(e4(Y)+1),pO=[...i8("union"),"alias"],mO=[...i8("morph"),"alias"],w1=(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 Z4(Y)},D4=(Y)=>{let Z="{ ";for(let[X,G]of Object.entries(Y))Z+=`${X}: ${Z4(G)}, `;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 G=`${X.propString} ${X.problem}`;if(G[0]==="[")return`value at ${G}`;return G};return Z};class XG 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 BJ={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Y)=>w0.throw("arrayObject",Y),arrayPostfix:(Y)=>w0.throw("arrayPostfix",Y),defaultValue:(Y)=>w0.throw("defaultValue",Y),domain:(Y)=>w0.throw("domain",Y),morph:(Y)=>w0.throw("morph",Y),patternIntersection:(Y)=>w0.throw("patternIntersection",Y),predicate:(Y)=>w0.throw("predicate",Y),proto:(Y)=>w0.throw("proto",Y),symbolKey:(Y)=>w0.throw("symbolKey",Y),unit:(Y)=>w0.throw("unit",Y),date:(Y)=>w0.throw("date",Y)}},w0={Error:XG,throw:(...Y)=>{throw new w0.Error(...Y)},throwInternalOperandError:(Y,Z)=>G0(`Unexpected JSON Schema input for ${Y}: ${i(Z)}`),defaultConfig:BJ};I.config??={};var p2=(Y,Z)=>{if(!Z)return Y;let X={...Y},G;for(G in Z){let _={...Y.keywords};if(G==="keywords"){for(let $ in Z[G]){let W=Z.keywords[$];if(W===void 0)continue;_[$]=typeof W==="string"?{description:W}:W}X.keywords=_}else if(G==="toJsonSchema")X[G]=SY(Y.toJsonSchema,Z.toJsonSchema);else if(a4(G))X[G]={...Y[G],...Z[G]};else X[G]=Z[G]}return X},SY=(Y,Z)=>{if(!Y)return Z??{};if(!Z)return Y;let X={...Y},G;for(G in Z)if(G==="fallback")X.fallback=TJ(Y.fallback,Z.fallback);else X[G]=Z[G];return X},TJ=(Y,Z)=>{Y=GG(Y),Z=GG(Z);let X={},G;for(G in w0.defaultConfig.fallback)X[G]=Z[G]??Z.default??Y[G]??Y.default??w0.defaultConfig.fallback[G];return X},GG=(Y)=>typeof Y==="function"?{default:Y}:Y??{};class L4 extends j2{[Y1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Y,relativePath:Z,...X},G){super();this.input=X,this.ctx=G,qX(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:NX(Y,J.path,Z)})))});this.nodeConfig=G.config[this.code];let $=[...X.path??G.path];if(Z)$.push(...Z);if(Y)$.unshift(...Y);this.path=new y2(...$),this.data="data"in X?X.data:_}transform(Y){return new L4(Y({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(Y){return this.code===Y}get propString(){return Y4(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 J1 extends p8{[Y1]="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 vY(this)}add(Y){if(this.includes(Y))return;this._add(Y)}transform(Y){let Z=new J1(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 L4({...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 L4({code:"intersection",errors:Z.hasCode("intersection")?[...Z.errors,Y]:[Z,Y]},this.ctx),G=this.indexOf(Z);this.mutable[G===-1?this.length:G]=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 vY extends Error{name="TraversalError";constructor(Y){if(Y.length===1)super(Y.summary);else super(`
19
- `+Y.map((Z)=>` \u2022 ${CJ(Z)}`).join(`
20
- `));Object.defineProperty(this,"arkErrors",{value:Y,enumerable:!1})}}var CJ=(Y)=>Y.toString().split(`
14
+ ${Z}}`:`{${W.join(", ")}}`}if(X instanceof Date)return P4(X);if("expression"in X&&typeof X.expression==="string")return X.expression;return G},n4={onCycle:()=>"(cycle)",onSymbol:(X)=>`Symbol(${f8(X)})`,onFunction:(X)=>`Function(${f8(X)})`},k8=(X,Y,Z)=>{switch(x0(X)){case"object":{let _=X;if("toJSON"in _&&typeof _.toJSON==="function")return _.toJSON();if(typeof _==="function")return n4.onFunction(_);if(Z.includes(_))return"(cycle)";let G=[...Z,_];if(Array.isArray(_))return _.map(($)=>k8($,Y,G));if(_ instanceof Date)return _.toDateString();let W={};for(let $ in _)W[$]=k8(_[$],Y,G);for(let $ of Object.getOwnPropertySymbols(_))W[Y.onSymbol?.($)??$.toString()]=k8(_[$],Y,G);return W}case"symbol":return n4.onSymbol(X);case"bigint":return Y.onBigInt?.(X)??`${X}n`;case"undefined":return Y.onUndefined??"undefined";case"string":return X.replaceAll("\\","\\\\");default:return X}},P4=(X)=>{let Y=X.getFullYear(),Z=X.getMonth(),_=X.getDate(),G=X.getHours(),W=X.getMinutes(),$=X.getSeconds(),H=X.getMilliseconds();if(Z===0&&_===1&&G===0&&W===0&&$===0&&H===0)return`${Y}`;let Q=`${VJ[Z]} ${_}, ${Y}`;if(G===0&&W===0&&$===0&&H===0)return Q;let J=X.toLocaleTimeString(),z=J.endsWith(" AM")||J.endsWith(" PM")?J.slice(-3):"";if(z)J=J.slice(0,-z.length);if(H)J+=`.${LJ(H,3)}`;else if(DJ.test(J))J=J.slice(0,-3);return`${J+z}, ${Q}`},VJ=["January","February","March","April","May","June","July","August","September","October","November","December"],DJ=/:\d\d:00$/,LJ=(X,Y)=>String(X).padStart(Y,"0");var t5=(X,Y,...[Z])=>{let _=Z?.stringifySymbol??c,G=X;switch(typeof Y){case"string":G=V4(Y)?X===""?Y:`${X}.${Y}`:`${X}[${JSON.stringify(Y)}]`;break;case"number":G=`${X}[${Y}]`;break;case"symbol":G=`${X}[${_(Y)}]`;break;default:if(Z?.stringifyNonKey)G=`${X}[${Z.stringifyNonKey(Y)}]`;else R(`${c(Y)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return G},e1=(X,...Y)=>X.reduce((Z,_)=>t5(Z,_,...Y),"");class b8 extends p2{cache={};constructor(...X){super();this.push(...X)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let X=0;X<this.length;X++)this.cache.json.push(typeof this[X]==="symbol"?c(this[X]):this[X]);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 X="",Y=[X];for(let Z of this)X=t5(X,Z),Y.push(X);return this.cache.stringifyAncestors=Y}}class CX{chars;i;def;constructor(X){this.def=X,this.chars=[...X],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(X){let Y="";while(this.lookahead){if(X(this,Y))if(Y[Y.length-1]===v8)Y=Y.slice(0,-1);else break;Y+=this.shift()}return Y}shiftUntilLookahead(X){return typeof X==="string"?this.shiftUntil((Y)=>Y.lookahead===X):this.shiftUntil((Y)=>(Y.lookahead in X))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in O4))}jumpToIndex(X){this.i=X<0?this.length+X:X}jumpForward(X){this.i+=X}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(X,Y){return this.chars.slice(X,Y).join("")}lookaheadIs(X){return this.lookahead===X}lookaheadIsIn(X){return this.lookahead in X}}var eO=P1("implementedTraits");var qX="$ark",MJ=2;while(qX in globalThis)qX=`$ark${MJ++}`;var a5=qX;globalThis[a5]=S4;var N=S4,AJ=(X)=>`${a5}.${X}`,I0=(X)=>AJ(f8(X));class d2 extends q8{argNames;body="";constructor(...X){super();this.argNames=X;for(let Y of X){if(Y in this)throw Error(`Arg name '${Y}' would overwrite an existing property on FunctionBody`);this[Y]=Y}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(X,Y=!1){return jX(X,Y)}index(X,Y=!1){return e5(`${X}`,Y)}line(X){return this.body+=`${" ".repeat(this.indentation)}${X}
15
+ `,this}const(X,Y){return this.line(`const ${X} = ${Y}`),this}let(X,Y){return this.line(`let ${X} = ${Y}`)}set(X,Y){return this.line(`${X} = ${Y}`)}if(X,Y){return this.block(`if (${X})`,Y)}elseIf(X,Y){return this.block(`else if (${X})`,Y)}else(X){return this.block("else",X)}for(X,Y,Z=0){return this.block(`for (let i = ${Z}; ${X}; i++)`,Y)}forIn(X,Y){return this.block(`for (const k in ${X})`,Y)}block(X,Y,Z=""){return this.line(`${X} {`),this.indent(),Y(this),this.dedent(),this.line(`}${Z}`)}return(X=""){return this.line(`return ${X}`)}write(X="anonymous",Y=0){return`${X}(${this.argNames.join(", ")}) { ${Y?this.body.split(`
16
+ `).map((Z)=>" ".repeat(Y)+`${Z}`).join(`
17
+ `):this.body} }`}compile(){return new h5(...this.argNames,this.body)}}var X4=(X)=>_1(X,"object")||typeof X==="symbol"?I0(X):h8(X),jX=(X,Y=!1)=>{if(typeof X==="string"&&V4(X))return`${Y?"?":""}.${X}`;return e5(RJ(X),Y)},RJ=(X)=>typeof X==="symbol"?I0(X):JSON.stringify(X),e5=(X,Y=!1)=>`${Y?"?.":""}[${X}]`;class y8 extends d2{traversalKind;optimistic;constructor(X){super("data","ctx");this.traversalKind=X.kind,this.optimistic=X.optimistic===!0}invoke(X,Y){let Z=Y?.arg??this.data,_=typeof X==="string"?!0:this.requiresContextFor(X),G=typeof X==="string"?X:X.id;if(_)return`${this.referenceToId(G,Y)}(${Z}, ${this.ctx})`;return`${this.referenceToId(G,Y)}(${Z})`}referenceToId(X,Y){let Z=Y?.kind??this.traversalKind,_=`this.${X}${Z}`;return Y?.bind?`${_}.bind(${Y?.bind})`:_}requiresContextFor(X){return this.traversalKind==="Apply"||X.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(X,Y,Z){let _=this.requiresContextFor(Z);if(_)this.line(`${this.ctx}.path.push(${X})`);if(this.check(Z,{arg:Y}),_)this.line(`${this.ctx}.path.pop()`);return this}check(X,Y){return this.traversalKind==="Allows"?this.if(`!${this.invoke(X,Y)}`,()=>this.return(!1)):this.line(this.invoke(X,Y))}}var c2=(X)=>d(X,(Y,Z)=>[Y,Q0(Z)?[...Z]:Z]),t0=P1("arkKind"),f=(X,Y)=>X?.[t0]===Y,E0=(X)=>f(X,"root")||f(X,"constraint");var X_=["unit","proto","domain"],r4=["required","optional","index","sequence"],SX=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],l2=[...SX,...r4,"structure","predicate"],s4=["alias","union","morph","unit","intersection","proto","domain"],wJ=[...s4,...l2],o2=d(l2,(X,Y)=>[Y,1]),Y_=d([...r4,"undeclared"],(X,Y)=>[Y,1]),Z_=d(wJ,(X,Y)=>[Y,X]),t4=(X)=>typeof X==="string"&&(X in Z_);var a4=(X)=>Z_[X],i2=(X)=>s4.slice(a4(X)+1),kV=[...i2("union"),"alias"],bV=[...i2("morph"),"alias"],A1=(X)=>{if(typeof X==="string"||typeof X==="boolean"||X===null)return X;if(typeof X==="number"){if(Number.isNaN(X))return"NaN";if(X===Number.POSITIVE_INFINITY)return"Infinity";if(X===Number.NEGATIVE_INFINITY)return"-Infinity";return X}return X4(X)},D4=(X)=>{let Y="{ ";for(let[Z,_]of Object.entries(X))Y+=`${Z}: ${X4(_)}, `;return Y+" }"},l=(X)=>{let Y=X;if(Y.hasAssociatedError)Y.defaults.expected??=(Z)=>("description"in Z)?Z.description:Y.defaults.description(Z),Y.defaults.actual??=(Z)=>c(Z),Y.defaults.problem??=(Z)=>`must be ${Z.expected}${Z.actual?` (was ${Z.actual})`:""}`,Y.defaults.message??=(Z)=>{if(Z.path.length===0)return Z.problem;let _=`${Z.propString} ${Z.problem}`;if(_[0]==="[")return`value at ${_}`;return _};return Y};class __ extends Error{name="ToJsonSchemaError";code;context;constructor(X,Y){super(c(Y,{quoteKeys:!1,indent:4}));this.code=X,this.context=Y}hasCode(X){return this.code===X}}var NJ={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(X)=>M0.throw("arrayObject",X),arrayPostfix:(X)=>M0.throw("arrayPostfix",X),defaultValue:(X)=>M0.throw("defaultValue",X),domain:(X)=>M0.throw("domain",X),morph:(X)=>M0.throw("morph",X),patternIntersection:(X)=>M0.throw("patternIntersection",X),predicate:(X)=>M0.throw("predicate",X),proto:(X)=>M0.throw("proto",X),symbolKey:(X)=>M0.throw("symbolKey",X),unit:(X)=>M0.throw("unit",X),date:(X)=>M0.throw("date",X)}},M0={Error:__,throw:(...X)=>{throw new M0.Error(...X)},throwInternalOperandError:(X,Y)=>e(`Unexpected JSON Schema input for ${X}: ${c(Y)}`),defaultConfig:NJ};N.config??={};var g8=(X,Y)=>{if(!Y)return X;let Z={...X},_;for(_ in Y){let G={...X.keywords};if(_==="keywords"){for(let W in Y[_]){let $=Y.keywords[W];if($===void 0)continue;G[W]=typeof $==="string"?{description:$}:$}Z.keywords=G}else if(_==="toJsonSchema")Z[_]=PX(X.toJsonSchema,Y.toJsonSchema);else if(t4(_))Z[_]={...X[_],...Y[_]};else Z[_]=Y[_]}return Z},PX=(X,Y)=>{if(!X)return Y??{};if(!Y)return X;let Z={...X},_;for(_ in Y)if(_==="fallback")Z.fallback=IJ(X.fallback,Y.fallback);else Z[_]=Y[_];return Z},IJ=(X,Y)=>{X=G_(X),Y=G_(Y);let Z={},_;for(_ in M0.defaultConfig.fallback)Z[_]=Y[_]??Y.default??X[_]??X.default??M0.defaultConfig.fallback[_];return Z},G_=(X)=>typeof X==="function"?{default:X}:X??{};class L4 extends q8{[t0]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:X,relativePath:Y,...Z},_){super();this.input=Z,this.ctx=_,j5(this,Z);let G=_.data;if(Z.code==="union")Z.errors=Z.errors.flatMap(($)=>{let H=$.hasCode("union")?$.errors:[$];if(!X&&!Y)return H;return H.map((Q)=>Q.transform((J)=>({...J,path:I5(X,J.path,Y)})))});this.nodeConfig=_.config[this.code];let W=[...Z.path??_.path];if(Y)W.push(...Y);if(X)W.unshift(...X);this.path=new b8(...W),this.data="data"in Z?Z.data:G}transform(X){return new L4(X({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(X){return this.code===X}get propString(){return e1(this.path)}get expected(){if(this.input.expected)return this.input.expected;let X=this.meta?.expected??this.nodeConfig.expected;return typeof X==="function"?X(this.input):X}get actual(){if(this.input.actual)return this.input.actual;let X=this.meta?.actual??this.nodeConfig.actual;return typeof X==="function"?X(this.data):X}get problem(){if(this.input.problem)return this.input.problem;let X=this.meta?.problem??this.nodeConfig.problem;return typeof X==="function"?X(this):X}get message(){if(this.input.message)return this.input.message;let X=this.meta?.message??this.nodeConfig.message;return typeof X==="function"?X(this):X}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 W1 extends p2{[t0]="errors";ctx;constructor(X){super();this.ctx=X}byPath=Object.create(null);get flatByPath(){return d(this.byPath,(X,Y)=>[X,Y.flat])}get flatProblemsByPath(){return d(this.byPath,(X,Y)=>[X,Y.flat.map((Z)=>Z.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new vX(this)}add(X){if(this.includes(X))return;this._add(X)}transform(X){let Y=new W1(this.ctx);for(let Z of this)Y.add(X(Z));return Y}merge(X){for(let Y of X){if(this.includes(Y))continue;this._add(new L4({...Y,path:[...this.ctx.path,...Y.path]},this.ctx))}}affectsPath(X){if(this.length===0)return!1;return X.stringifyAncestors().some((Y)=>(Y in this.byPath))||X.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((X)=>X.toJSON())]}toString(){return this.join(`
18
+ `)}_add(X){let Y=this.byPath[X.propString];if(Y){if(Y.hasCode("union")&&Y.errors.length===0)return;let Z=X.hasCode("union")&&X.errors.length===0?X:new L4({code:"intersection",errors:Y.hasCode("intersection")?[...Y.errors,X]:[Y,X]},this.ctx),_=this.indexOf(Y);this.mutable[_===-1?this.length:_]=Z,this.byPath[X.propString]=Z,this.addAncestorPaths(X)}else this.byPath[X.propString]=X,this.addAncestorPaths(X),this.mutable.push(X);this.count++}addAncestorPaths(X){for(let Y of X.path.stringifyAncestors())this.byAncestorPath[Y]=t(this.byAncestorPath[Y],X)}}class vX extends Error{name="TraversalError";constructor(X){if(X.length===1)super(X.summary);else super(`
19
+ `+X.map((Y)=>` \u2022 ${KJ(Y)}`).join(`
20
+ `));Object.defineProperty(this,"arkErrors",{value:X,enumerable:!1})}}var KJ=(X)=>X.toString().split(`
21
21
  `).join(`
22
- `);class x1{path=[];errors=new J1(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 Y4(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 y2(...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 L4(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),G;if(X!==void 0){G=this.root;for(let _=0;_<Y.length-1;_++)G=G[Y[_]]}for(let _ of Z){this.path=[...Y];let $=D0(_),W=_(G===void 0?this.root:G[X],this);if(W instanceof L4){this.errors.add(W);break}if(W instanceof J1){if(!$)this.errors.merge(W);break}if(G===void 0)this.root=W;else G[X]=W;this.applyQueuedMorphs()}}}var Q1=(Y,Z,X)=>{if(!X)return Z();X.path.push(Y);let G=Z();return X.path.pop(),G};class u2 extends v1{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(_)return this.traverseApply(G,_),_.hasError()?_.errors:_.data;return this.rootApply(G,$)},{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,_)=>SJ(G,_.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let G=0;G<this.children.length;G++){if(this.includesTransform||=this.children[G].includesTransform,this.includesContextualPredicate||=this.children[G].includesContextualPredicate,this.isCyclic||=this.children[G].isCyclic,!X){let _=this.children[G].flatRefs;for(let $=0;$<_.length;$++){let W=_[$];if(!this.flatRefs.some((H)=>$G(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[G].referencesById)}this.flatRefs.sort((G,_)=>G.path.length>_.path.length?1:G.path.length<_.path.length?-1:G.propString>_.propString?1:G.propString<_.propString?-1:G.node.expression<_.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((G)=>G.length===1||G.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((G)=>G.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(G)=>this.traverseAllows(G,new x1(G,this.$.resolvedConfig)):(G)=>this.traverseAllows(G)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Z,X)=>{if(this.allows(Z))return Z;let G=new x1(Z,this.$.resolvedConfig);return this.traverseApply(Z,G),G.finalize(X)};case"contextual":return(Z,X)=>{let G=new x1(Z,this.$.resolvedConfig);return this.traverseApply(Z,G),G.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 G=new x1(Z,this.$.resolvedConfig);return this.traverseApply(Z,G),G.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,G0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=PJ(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=e4(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,G]of this.innerEntries){let _=this.impl.keys[X];if(_.reduceIo)_.reduceIo(Y,Z,G);else if(_.child){let $=G;Z[X]=F0($)?$.map((W)=>W[Y]):$[Y]}else Z[X]=G}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)C4(`${this.kind} node was not of asserted kind ${Y}`);return this}hasKindIn(...Y){return Y.includes(this.kind)}assertHasKindIn(...Y){if(!s1(Y,this.kind))C4(`${this.kind} node was not one of asserted kinds ${Y}`);return this}isBasis(){return s1(eX,this.kind)}isConstraint(){return s1(l8,this.kind)}isStructural(){return s1(s4,this.kind)}isRefinement(){return s1(PY,this.kind)}isRoot(){return s1(t4,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=m2.normalize(Y);return this._select(Z)}_select(Y){let Z=m2.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 m2.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 G;if(Z.seen[this.id]=()=>G,this.hasKind("structure")&&this.undeclared!==Z.undeclaredKeyHandling)Z={...Z,undeclaredKeyHandling:this.undeclared};let _=o(this.inner,(J,z)=>{if(!this.impl.keys[J].child)return[J,z];let U=z;if(!F0(U)){let L=U._transform(Y,Z);return L?[J,L]:[]}if(U.length===0)return[J,z];let O=U.flatMap((L)=>{return L._transform(Y,Z)??[]});return O.length?[J,O]:[]});delete Z.seen[this.id];let $=Object.assign(_,{meta:this.meta}),W=Z.selected&&!Z.selected.includes(this)?$:Y(this.kind,$,Z);if(W===null)return null;if(D0(W))return G=W;let H=Object.keys(W);if((H.length===0||H.length===1&&H[0]==="meta")&&!l1(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 G=X.node(this.kind,W,Z.parseOptions)}configureReferences(Y,Z="references"){let X=m2.normalize(Z),G=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,G(this.kind,{...this.inner,meta:this.meta}));let _=this._select(X),$=_&&U4(_),W=X.boundary==="child"?(H,Q)=>Q.root.children.includes(H):X.boundary==="shallow"?(H)=>H.kind!=="structure":()=>!0;return this.$.finalize(this.transform(G,{shouldTransform:W,selected:$}))}}var m2={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)C4(_G(Z,X));return Y},find:(Y)=>Y[0],assertFind:(Y,Z,X)=>{if(Y.length===0)C4(_G(Z,X));return Y[0]}},normalize:(Y)=>typeof Y==="function"?{boundary:"references",method:"filter",where:Y}:typeof Y==="string"?g0(Y,m2.applyBoundary)?{method:"filter",boundary:Y}:{boundary:"references",method:"filter",kind:Y}:{boundary:"references",method:"filter",...Y}},_G=(Y,Z)=>`${Y} had no references matching ${i(Z)}.`,qJ=(Y)=>Y4(Y,{stringifyNonKey:(Z)=>Z.expression}),jJ=/"(\$ark\.[^"]+)"/g,PJ=(Y)=>JSON.stringify(Y).replaceAll(jJ,"$1"),f1=(Y,Z)=>({path:Y,node:Z,propString:qJ(Y)}),$G=(Y,Z)=>Y.propString===Z.propString&&Y.node.equals(Z.node),xY=(Y,Z)=>c1(Y,Z,{isEqual:$G}),SJ=(Y,Z)=>c1(Y,Z,{isEqual:(X,G)=>X.equals(G)});class S extends Array{static init(Y,Z,X,G){return new S({kind:Y,l:Z,r:X,path:G?.path??[],optional:G?.optional??!1})}add(Y,Z,X,G){return this.push({kind:Y,l:Z,r:X,path:G?.path??[],optional:G?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Y,l:Z,r:X}=this[0],G=Y4(Y);return hY(`Intersection${G&&` at ${G}`} of ${WG(Z,X)}`)}return`The following intersections result in unsatisfiable types:
23
- \u2022 ${this.map(({path:Y,l:Z,r:X})=>`${Y}: ${WG(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 S))return new S(...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 WG=(Y,Z)=>`${fY(Y)} and ${fY(Z)}`,fY=(Y)=>D0(Y)?Y.expression:F0(Y)?Y.map(fY).join(" | ")||"never":String(Y),hY=(Y)=>`${Y} results in an unsatisfiable type`;var Y2={},z1=(Y,Z,X)=>L0(Y,Z,{$:X,invert:!1,pipe:!1}),d2=(Y,Z,X)=>L0(Y,Z,{$:X,invert:!1,pipe:!0}),L0=(Y,Z,X)=>{let G=X.pipe?"|>":"&",_=`${Y.hash}${G}${Z.hash}`;if(Y2[_]!==void 0)return Y2[_];if(!X.pipe){let H=`${Z.hash}${G}${Y.hash}`;if(Y2[H]!==void 0){let Q=Y2[H],J=Q instanceof S?Q.invert():Q;return Y2[_]=J,J}}let $=!X.pipe||!Y.includesTransform&&!Z.includesTransform;if($&&Y.equals(Z))return Y;let W=$?kY(Y,Z,X):Y.hasKindIn(...t4)?vJ(Y,Z,X):kY(Y,Z,X);if(D0(W)){if(Y.equals(W))W=Y;else if(Z.equals(W))W=Z}return Y2[_]=W,W},kY=(Y,Z,X)=>{let G=Y.precedence<Z.precedence?Y.kind:Z.kind,_=Y.impl.intersections[Z.kind]??Z.impl.intersections[Y.kind];if(_===void 0)return null;else if(G===Y.kind)return _(Y,Z,X);else{let $=_(Z,Y,{...X,invert:!X.invert});if($ instanceof S)$=$.invert();return $}},vJ=(Y,Z,X)=>Y.includesTransform||Z.includesTransform?X.invert?HG(Z,Y,X):HG(Y,Z,X):kY(Y,Z,X),HG=(Y,Z,X)=>Y.distribute((G)=>xJ(G,Z,X),(G)=>{let _=G.filter(D0);if(_.length===0)return S.init("union",Y.branches,Z.branches);if(_.length<Y.branches.length||!Y.branches.every((H,Q)=>H.in.equals(_[Q].in)))return X.$.parseSchema(_);let $;if(_.length===1){let H=_[0];if(!$)return H;return X.$.node("morph",{...H.inner,in:H.in.configure($,"self")})}let W={branches:_};if($)W.meta=$;return X.$.parseSchema(W)}),xJ=(Y,Z,X)=>{if(Y.hasKind("morph")){let _=[...Y.morphs];if(Y.lastMorphIfNode){let $=L0(Y.lastMorphIfNode,Z,X);if($ instanceof S)return $;_[_.length-1]=$}else _.push(Z);return X.$.node("morph",{morphs:_,in:Y.inner.in})}if(Z.hasKind("morph")){let _=L0(Y,Z.in,X);if(_ instanceof S)return _;return X.$.node("morph",{morphs:[Z],in:_})}return X.$.node("morph",{morphs:[Z],in:Y})};class N1 extends u2{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,Y1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Y){return z1(this,Y,this.$)}}class X4 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 D4(this.errorContext)}}var s0=(Y)=>(Z,X)=>{if(F0(Z)){if(Z.length===0)return;let _=Z.map(($)=>X.$.node(Y,$));if(Y==="predicate")return _;return _.sort(($,W)=>$.hash<W.hash?-1:1)}let G=X.$.node(Y,Z);return G.hasOpenIntersection()?[G]:G},Z2=(Y)=>{let Z=Y.r.shift();if(!Z){let G=Y.l.length===0&&Y.kind==="structure"?I.intrinsic.unknown.internal:Y.ctx.$.node(Y.kind,Object.assign(Y.baseInner,fJ(Y.l)),{prereduced:!0});for(let _ of Y.roots){if(G instanceof S)return G;G=L0(_,G,Y.ctx)}return G}let X=!1;for(let G=0;G<Y.l.length;G++){let _=L0(Y.l[G],Z,Y.ctx);if(_===null)continue;if(_ instanceof S)return _;if(!X){if(_.isRoot())return Y.roots.push(_),Y.l.splice(G),Z2(Y);Y.l[G]=_,X=!0}else if(!Y.l.includes(_))return G0(`Unexpectedly encountered multiple distinct intersection results for refinement ${_}`)}if(!X)Y.l.push(Z);if(Y.kind==="intersection"){if(Z.impliedSiblings)for(let G of Z.impliedSiblings)c1(Y.r,G)}return Z2(Y)},X2=(Y)=>{return Object.entries(Y).flatMap(([X,G])=>(X in o8)?G:[]).sort((X,G)=>X.precedence<G.precedence?-1:X.precedence>G.precedence?1:X.kind==="predicate"&&G.kind==="predicate"?0:X.hash<G.hash?-1:1)},fJ=(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 G0(`Unexpected intersection of closed refinements of kind ${X.kind}`);Z[X.kind]=X}return Z},JG=(...Y)=>A(QG(...Y)),QG=(Y,Z,X)=>{let G=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Z).defaultShortDescription;return`${yX(Y)} operand must be ${Z.description} (was ${G})`};var zG=(Y,Z,X)=>new M4(Y,Z,X,X,null);class n8 extends v1{}class M4 extends v1{[Y1]="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]))A(hJ(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$=G,this.hkt=_,this.description=_?new _().description??`a generic type for ${_.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof n8}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:rX(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 hJ=(Y,Z,X)=>`${Y} must be assignable to ${Z} (was ${X})`;var kJ=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 FG extends N1{serializedPredicate=T0(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=D4(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 bY={implementation:kJ,Node:FG};var bJ=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Y)=>Number.isInteger(Y)?Y:A(yJ(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/gJ(Y.rule,Z.rule))})},obviatesBasisDescription:!0});class UG extends X4{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 yY={implementation:bJ,Node:UG};var yJ=(Y)=>`divisor must be an integer (was ${Y})`,gJ=(Y,Z)=>{let X,G=Y,_=Z;while(_!==0)X=_,_=G%_,G=X;return G};class M1 extends X4{boundOperandKind=dJ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=cJ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${pJ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?lJ(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 pJ={"<":">=","<=":">",">":"<=",">=":"<"},mJ={min:"max",minLength:"maxLength",after:"before"},r8={parse:(Y)=>Y||void 0},s8=(Y)=>(Z)=>{if(typeof Z==="number")return{rule:Z};let{exclusive:X,...G}=Z;return X?{...G,rule:Y==="minLength"?G.rule+1:G.rule-1}:G},t8=(Y)=>(Z)=>{if(typeof Z==="number"||typeof Z==="string"||Z instanceof Date)return{rule:Z};let{exclusive:X,...G}=Z;if(!X)return G;let _=typeof G.rule==="number"?G.rule:typeof G.rule==="string"?new Date(G.rule).valueOf():G.rule.valueOf();return X?{...G,rule:Y==="after"?_+1:_-1}:G},a8=(Y)=>typeof Y==="string"||typeof Y==="number"?new Date(Y):Y,uJ=(Y,Z)=>`${Y} bound must be a positive integer (was ${Z})`,G2=(Y)=>(Z)=>{if(!Number.isInteger(Z)||Z<0)A(uJ(Y,Z));return Z},dJ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},cJ=(Y,Z)=>`${g0(Y,mJ)?">":"<"}${Z?"":"="}`,lJ=(Y)=>typeof Y==="string"?Y:new Date(Y).toLocaleString(),EG=(Y)=>`Bounded expression ${Y} must be exactly one of number, string, Array, or Date`;var oJ=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:S4},intersections:{after:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class VG extends M1{impliedBasis=I.intrinsic.Date.internal;collapsibleLimitString=S4(this.rule);traverseAllows=(Y)=>Y>=this.rule;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,after:this.rule})}}var gY={implementation:oJ,Node:VG};var iJ=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:S4},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:S.init("range",Y,Z)}});class OG extends M1{collapsibleLimitString=S4(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 pY={implementation:iJ,Node:OG};var nJ=r({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:G2("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)=>S.init("unit",X.$.node("unit",{unit:Y.rule}),X.$.node("unit",{unit:Z.rule}),{path:["length"]}),minLength:(Y,Z)=>Y.rule>=Z.rule?Y:S.init("range",Y,Z),maxLength:(Y,Z)=>Y.rule<=Z.rule?Y:S.init("range",Y,Z)}});class DG extends X4{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 w0.throwInternalOperandError("exactLength",Y)}}}var mY={implementation:nJ,Node:DG};var rJ=r({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:S.init("range",Y,Z)},obviatesBasisDescription:!0});class LG 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 uY={implementation:rJ,Node:LG};var sJ=r({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:G2("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:S.init("range",Y,Z)}});class MG 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 w0.throwInternalOperandError("maxLength",Y)}}}var dY={implementation:sJ,Node:MG};var tJ=r({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 AG 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 cY={implementation:tJ,Node:AG};var aJ=r({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:G2("minLength")}},reduce:(Y)=>Y.rule===0?I.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 RG 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 w0.throwInternalOperandError("minLength",Y)}}}var lY={implementation:aJ,Node:RG};var wG={min:cY.implementation,max:uY.implementation,minLength:lY.implementation,maxLength:dY.implementation,exactLength:mY.implementation,after:gY.implementation,before:pY.implementation},NG={min:cY.Node,max:uY.Node,minLength:lY.Node,maxLength:dY.Node,exactLength:mY.Node,after:gY.Node,before:pY.Node};var eJ=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 IG extends X4{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 oY={implementation:eJ,Node:IG};var c2=(Y,Z)=>{let X=YQ(Y);if(Z&&!Z.includes(X))return A(`Root of kind ${X} should be one of ${Z}`);return X},YQ=(Y)=>{if(y(Y,"root"))return Y.kind;if(typeof Y==="string")return Y[0]==="$"?"alias":(Y in H1)?"domain":"proto";if(typeof Y==="function")return"proto";if(typeof Y!=="object"||Y===null)return A(KG(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 A(KG(Y))},KG=(Y)=>`${i(Y)} is not a valid type schema`,BG={},ZQ=(Y)=>F0(Y)?Y.map((Z)=>Z.collapsibleJson):Y.collapsibleJson,Z1={};I.nodesByRegisteredId=Z1;var iY=(Y)=>{return BG[Y]??=0,`${Y}${++BG[Y]}`},nY=(Y)=>{let Z=_2[Y.kind],X=Z.applyConfig?.(Y.def,Y.$.resolvedConfig)??Y.def,G={},{meta:_,...$}=X,W=_===void 0?{}:typeof _==="string"?{description:_}:_,H=LY($).sort(([J],[z])=>a4(J)?a4(z)?e4(J)-e4(z):1:a4(z)?-1:J<z?-1:1).filter(([J,z])=>{if(J.startsWith("meta.")){let U=J.slice(5);return W[U]=z,!1}return!0});for(let J of H){let z=J[0],U=Z.keys[z];if(!U)return A(`Key ${z} is not valid on ${Y.kind} schema`);let O=U.parse?U.parse(J[1],Y):J[1];if(O!==L1&&(O!==void 0||U.preserveUndefined))G[z]=O}if(Z.reduce&&!Y.prereduced){let J=Z.reduce(G,Y.$);if(J){if(J instanceof S)return J.throw();return XQ(J,W)}}return rY({id:Y.id,kind:Y.kind,inner:G,meta:W,$:Y.$})},rY=({id:Y,kind:Z,inner:X,meta:G,$:_,ignoreCache:$})=>{let W=_2[Z],H=LY(X),Q=[],J={};for(let[x,h]of H){let g=W.keys[x],B=g.serialize??(g.child?ZQ:w1);if(J[x]=B(h),g.child===!0){let K=h;if(F0(K))Q.push(...K);else Q.push(K)}else if(typeof g.child==="function")Q.push(...g.child(h))}if(W.finalizeInnerJson)J=W.finalizeInnerJson(J);let z={...J},U={};if(!l1(G))U=o(G,(x,h)=>[x,x==="examples"?h:w1(h)]),z.meta=e8(U,"description",!0);J=e8(J,W.collapsibleKey,!1);let O=JSON.stringify({kind:Z,...J});z=e8(z,W.collapsibleKey,!1);let L=e8(z,W.collapsibleKey,!0),w=JSON.stringify({kind:Z,...z});if(_.nodesByHash[w]&&!$)return _.nodesByHash[w];let R={id:Y,kind:Z,impl:W,inner:X,innerEntries:H,innerJson:J,innerHash:O,meta:G,metaJson:U,json:z,hash:w,collapsibleJson:L,children:Q};if(Z!=="intersection"){for(let x in X)if(x!=="in"&&x!=="out")R[x]=X[x]}let b=new CG[Z](R,_);return _.nodesByHash[w]=b},TG=(Y,Z)=>{if(Y.id===Z)return Y;if(D0(Z1[Z]))G0(`Unexpected attempt to overwrite node id ${Z}`);return rY({id:Z,kind:Y.kind,inner:Y.inner,meta:Y.meta,$:Y.$,ignoreCache:!0})},XQ=(Y,Z,X)=>{if(X&&D0(Z1[X]))G0(`Unexpected attempt to overwrite node id ${X}`);return rY({id:X??iY(Z.alias??Y.kind),kind:Y.kind,inner:Y.inner,meta:Z,$:Y.$})},e8=(Y,Z,X)=>{let G=Object.keys(Y);if(G.length===1&&G[0]===Z){let _=Y[Z];if(X)return _;if(W1(_,"object")&&(Object.keys(_).length===1||Array.isArray(_)))return _}return Y};var l2=(Y,Z,X)=>{if(Y.key!==Z.key)return null;let G=Y.key,_=L0(Y.value,Z.value,X),$=Y.required||Z.required?"required":"optional";if(_ instanceof S)if($==="optional")_=I.intrinsic.never.internal;else return _.withPrefixKey(Y.key,Y.required&&Z.required?"required":"optional");if($==="required")return X.$.node("required",{key:G,value:_});let W=Y.hasDefault()?Z.hasDefault()?Y.default===Z.default?Y.default:A(sY(Y.default,Z.default)):Y.default:Z.hasDefault()?Z.default:L1;return X.$.node("optional",{key:G,value:_,default:W})};class o2 extends N1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=I.intrinsic.object.internal;serializedKey=Z4(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=Z0(this.value.flatRefs.map((Y)=>f1([this.key,...Y.path],Y.node)),f1([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 Q1(this.key,()=>this.value.traverseAllows(Y[this.key],Z),Z);return this.optional};traverseApply=(Y,Z)=>{if(this.key in Y)Q1(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 sY=(Y,Z)=>`Invalid intersection of default values ${i(Y)} & ${i(Z)}`;var GQ=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(u.undefined)},{prereduced:!0})}},defaults:{description:(Y)=>`${Y.compiledKey}?: ${Y.value.description}`},intersections:{optional:l2}});class qG extends o2{constructor(...Y){super(...Y);if("default"in this.inner)n2(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=$Q(this);defaultValueMorphRef=this.defaultValueMorph&&T0(this.defaultValueMorph)}var i2={implementation:GQ,Node:qG},_Q={},$Q=(Y)=>{if(!Y.hasDefault())return;let Z=`{${Y.compiledKey}: ${Y.value.id} = ${w1(Y.default)}}`;return _Q[Z]??=tY(Y.key,Y.value,Y.default)},tY=(Y,Z,X)=>{if(typeof X==="function")return Z.includesTransform?(_,$)=>{return Q1(Y,()=>Z(_[Y]=X(),$),$),_}:(_)=>{return _[Y]=X(),_};let G=Z.includesTransform?Z.assert(X):X;return W1(G,"object")?(_,$)=>{return Q1(Y,()=>Z(_[Y]=X,$),$),_}:(_)=>{return _[Y]=G,_}},n2=(Y,Z,X)=>{let G=E4(Z);if(W1(Z,"object")&&!G)A(WQ(X));let _=Y.in(G?Z():Z);if(_ instanceof J1){if(X===null)A(`Default ${_.summary}`);let $=_.transform((W)=>W.transform((H)=>({...H,prefixPath:[X]})));A(`Default for ${$.summary}`)}return Z},WQ=(Y)=>{return`Non-primitive default ${Y===null?"":typeof Y==="number"?`for value at [${Y}] `:`for ${Z4(Y)} `}must be specified as a function like () => ({my: 'object'})`};class I1 extends u2{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 J1)return Z;return{value:Z}},toJSONSchema:(Y)=>{if(Y.target&&Y.target!=="draft-2020-12")return A(`JSONSchema target '${Y.target}' is not supported (must be "draft-2020-12")`);if(Y.io==="input")return this.in.toJsonSchema();return this.out.toJsonSchema()}}}as(){return this}brand(Y){if(Y==="")return A(HQ);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=SY(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,_)=>_.isRoot()&&!_.alwaysExpandJsonSchema?[_.id,_.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 S)return X;return this.$.finalize(X)}rawIntersect(Y){return z1(this,Y,this.$)}toNeverIfDisjoint(){return this}and(Y){let Z=this.intersect(Y);return Z instanceof S?Z.throw():Z}rawAnd(Y){let Z=this.rawIntersect(Y);return Z instanceof S?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(hY(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Y)}get props(){if(this.branches.length!==1)return A(JQ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(Z.distribute((X)=>this.applyStructuralOperation("merge",[jG(X)??A(PG("merge",X.expression))])))}applyStructuralOperation(Y,Z){return this.distribute((X)=>{if(X.equals(I.intrinsic.object)&&Y!=="merge")return X;let G=jG(X);if(!G)A(PG(Y,X.expression));if(Y==="keyof")return G.keyof();if(Y==="get")return G.get(...Z);if(Y==="props")return G.props;let _=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 S)}extends(Y){let Z=this.intersect(Y);return!(Z instanceof S)&&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 n2(this,Y,null),[this,"=",Y]}from(Y){return this.assert(Y)}_pipe(...Y){let Z=Y.reduce((X,G)=>X.rawPipeOnce(G),this);return this.$.finalize(Z)}tryPipe(...Y){let Z=Y.reduce((X,G)=>X.rawPipeOnce(y(G,"root")?G:(_,$)=>{try{return G(_,$)}catch(W){return $.error({code:"predicate",predicate:G,actual:`aborted due to error:
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=d2(this,Y,this.$);if(Z instanceof S)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 G=this.$.node(Z,X);if(G.isRoot())return G.isUnknown()?this:G0(`Unexpected constraint node ${G}`);let _=Y==="root"?this:this[Y];if(_.hasKind("morph")||G.impliedBasis&&!_.extends(G.impliedBasis))return JG(Z,G.impliedBasis,this);let $=this.$.node("intersection",{[G.kind]:G}),W=Y==="out"?d2(this,$,this.$):z1(this,$,this.$);if(W instanceof S)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,_)=>G==="structure"?Z==="ignore"?CX(_,{undeclared:1}):{..._,undeclared:Z}:_,X?void 0:{shouldTransform:(G)=>!s1(s4,G.kind)}))}hasEqualMorphs(Y){if(!this.includesTransform&&!Y.includesTransform)return!0;if(!a1(this.shallowMorphs,Y.shallowMorphs))return!1;if(!a1(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",$2(Y))}lessThan(Y){return this.constrain("max",$2(Y))}atLeastLength(Y){return this.constrain("minLength",Y)}atMostLength(Y){return this.constrain("maxLength",Y)}moreThanLength(Y){return this.constrain("minLength",$2(Y))}lessThanLength(Y){return this.constrain("maxLength",$2(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",$2(Y))}earlierThan(Y){return this.constrain("before",$2(Y))}}var HQ="Expected a non-empty brand name after #",$2=(Y)=>typeof Y==="object"&&!(Y instanceof Date)?{...Y,exclusive:!0}:{rule:Y,exclusive:!0},r2=(Y,Z)=>y(Z,"root")?y(Y,"root")?Y.extends(Z):Z.allows(Y):y(Y,"root")?Y.hasUnit(Z):Z===Y,jG=(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},JQ=(Y)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
- ${Y}`,PG=(Y,Z)=>`${Y} operand must be an object (was ${Z})`;var o1=(Y,Z)=>o(i8(Y),(X,G)=>[G,Z]);var QQ=(Y)=>typeof Y==="string"?{reference:Y}:Y,SG=(Y)=>Y instanceof S?I.intrinsic.never.internal:Y,zQ=r({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Y)=>Y.startsWith("$")?Y:`$ark.${Y}`},resolve:{}},normalize:QQ,defaults:{description:(Y)=>Y.reference},intersections:{alias:(Y,Z,X)=>X.$.lazilyResolve(()=>SG(L0(Y.resolution,Z.resolution,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.reference}`),...o1("alias",(Y,Z,X)=>{if(Z.isUnknown())return Y;if(Z.isNever())return Z;if(Z.isBasis()&&!Z.overlaps(I.intrinsic.object))return S.init("assignability",I.intrinsic.object,Z);return X.$.lazilyResolve(()=>SG(L0(Y.resolution,Z,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.id}`)})}});class vG 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(FQ(Z.id,X));X.push(Z.id),Z=Z1[Z.id]}if(!y(Z,"root"))return G0(`Unexpected resolution for reference ${this.reference}
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 G0(`Unexpected resolution for reference ${this.reference}: ${i(Z)}`)}get defaultShortDescription(){return H1.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 FQ=(Y,Z)=>`Alias '${Y}' has a shallow resolution cycle: ${[...Z,Y].join("->")}`,s2={implementation:zQ,Node:vG};class v4 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 D4(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 UQ=r({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Y)=>typeof Y==="string"?{domain:Y}:n4(Y,"numberAllowsNaN")&&Y.domain!=="number"?A(Y6.writeBadAllowNanMessage(Y.domain)):Y,applyConfig:(Y,Z)=>Y.numberAllowsNaN===void 0&&Y.domain==="number"&&Z.numberAllowsNaN?{...Y,numberAllowsNaN:!0}:Y,defaults:{description:(Y)=>H1[Y.domain],actual:(Y)=>Number.isNaN(Y)?"NaN":H1[y0(Y)]},intersections:{domain:(Y,Z)=>Y.domain==="number"&&Z.domain==="number"?Y.numberAllowsNaN?Z:Y:S.init("domain",Y,Z)}});class xG extends v4{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 H1[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:UQ,Node:xG,writeBadAllowNanMessage:(Y)=>`numberAllowsNaN may only be specified with domain "number" (was ${Y})`};var EQ=r({kind:"intersection",hasAssociatedError:!0,normalize:(Y)=>{if(D0(Y))return Y;let{structure:Z,...X}=Y,G=!!Z,_=Z??{},$=o(X,(W,H)=>{if(g0(W,YG)){if(G)A(`Flattened structure key ${W} cannot be specified alongside a root 'structure' key.`);return _[W]=H,[]}return[W,H]});if(y(_,"constraint")||!l1(_))$.structure=_;return $},finalizeInnerJson:({structure:Y,...Z})=>W1(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,$=_.variadic&&Object.keys(_).length===1?_.variadic:_;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)=>fG({},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,_)=>G.kind==="min"&&_.kind==="max"?-1:0).map((G)=>G.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
- \u25E6 `)}`,problem:(Y)=>`(${Y.actual}) must be...
31
- ${Y.expected}`},intersections:{intersection:(Y,Z,X)=>fG(Y.inner,Z.inner,X),...o1("intersection",(Y,Z,X)=>{if(Y.children.length===0)return Z;let{domain:G,proto:_,...$}=Y.inner,W=_??G,H=W?L0(W,Z,X):Z;return H instanceof S?H:Y?.basis?.equals(H)?Y:Y.$.node("intersection",{...$,[H.kind]:H},{prereduced:!0})})}});class hG extends I1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((Y)=>Y.isRefinement());structure=this.inner.structure;expression=VQ(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 G=0;G<this.refinements.length-1;G++)if(this.refinements[G].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 G=0;G<this.inner.predicate.length-1;G++)if(this.inner.predicate[G].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 aY={implementation:EQ,Node:hG},VQ=(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},fG=(Y,Z,X)=>{let G={},_=Y.proto??Y.domain,$=Z.proto??Z.domain,W=_?$?L0(_,$,X):_:$;if(W instanceof S)return W;if(W)G[W.kind]=W;return Z2({kind:"intersection",baseInner:G,l:X2(Y),r:X2(Z),roots:[],ctx:X})};var OQ=r({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},morphs:{parse:U4,serialize:(Y)=>Y.map((Z)=>y(Z,"root")?Z.json:T0(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(DQ(Y.expression,Z.expression));let G=L0(Y.in,Z.in,X);if(G instanceof S)return G;let _={morphs:Y.morphs};if(Y.declaredIn||Z.declaredIn){let $=L0(Y.in,Z.in,X);if($ instanceof S)return $.throw();else _.declaredIn=$}if(Y.declaredOut||Z.declaredOut){let $=L0(Y.out,Z.out,X);if($ instanceof S)return $.throw();else _.declaredOut=$}return G.distribute(($)=>X.$.node("morph",{..._,in:$}),X.$.parseSchema)},...o1("morph",(Y,Z,X)=>{let G=Y.inner.in?L0(Y.inner.in,Z,X):Z;return G instanceof S?G:G.equals(Y.inner.in)?Y:X.$.node("morph",{...Y.inner,in:G})})}});class kG extends I1{serializedMorphs=this.morphs.map(T0);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 a1(this.morphs,Y.morphs,{isEqual:(Z,X)=>Z===X||y(Z,"root")&&y(X,"root")&&Z.equals(X)})}}var eY={implementation:OQ,Node:kG},DQ=(Y,Z)=>`The intersection of distinct morphs at a single path is indeterminate:
32
- Left: ${Y}
33
- Right: ${Z}`;var LQ=r({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Y)=>v2(Y)??w1(Y)},dateAllowsInvalid:{}},normalize:(Y)=>{let Z=typeof Y==="string"?{proto:j4[Y]}:typeof Y==="function"?D0(Y)?Y:{proto:Y}:typeof Y.proto==="string"?{...Y,proto:j4[Y.proto]}:Y;if(typeof Z.proto!=="function")A(t2.writeInvalidSchemaMessage(Z.proto));if(n4(Z,"dateAllowsInvalid")&&Z.proto!==Date)A(t2.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?SX[Y.builtinName]:`an instance of ${Y.proto.name}`,actual:(Y)=>Y instanceof Date&&Y.toString()==="Invalid Date"?"an invalid Date":S2(Y)},intersections:{proto:(Y,Z)=>Y.proto===Date&&Z.proto===Date?Y.dateAllowsInvalid?Z:Y:NY(Y.proto,Z.proto)?Y:NY(Z.proto,Y.proto)?Z:S.init("proto",Y,Z),domain:(Y,Z)=>Z.domain==="object"?Y:S.init("domain",I.intrinsic.object.internal,Z)}});class bG extends v4{builtinName=v2(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 t2={implementation:LQ,Node:bG,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 MQ=r({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Y,Z)=>{let X=[];for(let G of Y){let _=y(G,"root")?G.branches:Z.$.parseSchema(G).branches;for(let $ of _)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,_)=>G.hash<_.hash?-1:1);return X}}},normalize:(Y)=>F0(Y)?{branches:Y}:Y,reduce:(Y,Z)=>{let X=qQ(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,W2),expected:(Y)=>{let Z=IX(Y.errors,"propString"),X=Object.entries(Z).map(([G,_])=>{let $=[];for(let Q of _)c1($,Q.expected);let W=W2($),H=_.every((Q)=>Q.actual===_[0].actual)?_[0].actual:i(_[0].data);return`${G&&`${G} `}must be ${W}${H&&` (was ${H})`}`});return W2(X)},problem:(Y)=>Y.expected,message:(Y)=>Y.problem},intersections:{union:(Y,Z,X)=>{if(Y.isNever!==Z.isNever)return S.init("presence",Y,Z);let G;if(Y.ordered){if(Z.ordered)A(PQ(Y.expression,Z.expression));if(G=YZ(Z.branches,Y.branches,X),G instanceof S)G.invert()}else G=YZ(Y.branches,Z.branches,X);if(G instanceof S)return G;return X.$.parseSchema(Y.ordered||Z.ordered?{branches:G,ordered:!0}:{branches:G})},...o1("union",(Y,Z,X)=>{let G=YZ(Y.branches,[Z],X);if(G instanceof S)return G;if(G.length===1)return G[0];return X.$.parseSchema(Y.ordered?{branches:G,ordered:!0}:{branches:G})})}});class pG 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?BQ(this.discriminant):null;expression=this.distribute((Y)=>Y.nestableExpression,CQ);createBranchedOptimisticRootApply(){return(Y,Z)=>{let X=this.traverseOptimistic(Y);if(X!==L1)return X;let G=new x1(Y,this.$.resolvedConfig);return this.traverseApply(Y,G),G.finalize(Z)}}get shallowMorphs(){return this.branches.reduce((Y,Z)=>c1(Y,Z.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Y)=>Y.defaultShortDescription,W2)}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&&n4(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 G=0;G<this.branches.length;G++){if(Z.pushBranch(),this.branches[G].traverseApply(Y,Z),!Z.hasError()){if(this.branches[G].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,G=Object.keys(X),{optimistic:_}=Y;if(Y.optimistic=!1,Y.block(`switch(${Z})`,()=>{for(let J in X){let z=X[J],U=J==="default"?J:`case ${J}`;Y.line(`${U}: return ${z===!0?_?Y.data:z:_?`${Y.invoke(z)} ? ${z.contextFreeMorph?`${T0(z.contextFreeMorph)}(${Y.data})`:Y.data} : "${L1}"`:Y.invoke(z)}`)}return Y}),Y.traversalKind==="Allows"){Y.return(_?`"${L1}"`:!1);return}let $=W2(this.discriminant.kind==="domain"?G.map((J)=>{let z=J.slice(1,-1);return z==="function"?H1.object:H1[z]}):G),W=this.discriminant.path.map((J)=>typeof J==="symbol"?T0(J):JSON.stringify(J)),H=JSON.stringify($),Q=this.discriminant.kind==="domain"?`${IQ}[${Z}]`:`${KQ}(${Z})`;Y.line(`ctx.errorFromNodeContext({
22
+ `);class x1{path=[];errors=new W1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(X,Y){this.root=X,this.config=Y}get data(){let X=this.root;for(let Y of this.path)X=X?.[Y];return X}get propString(){return e1(this.path)}reject(X){return this.error(X),!1}mustBe(X){return this.error(X),!1}error(X){let Y=typeof X==="object"?X.code?X:{...X,code:"predicate"}:{code:"predicate",expected:X};return this.errorFromContext(Y)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(X){let Y={path:new b8(...this.path),morphs:X};if(this.currentBranch)this.currentBranch.queuedMorphs.push(Y);else this.queuedMorphs.push(Y)}finalize(X){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 X?X(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(X){return this.errorFromContext(X)}errorFromContext(X){let Y=new L4(X,this);if(this.currentBranch)this.currentBranch.error=Y;else this.errors.add(Y);return Y}applyQueuedMorphs(){while(this.queuedMorphs.length){let X=this.queuedMorphs;this.queuedMorphs=[];for(let{path:Y,morphs:Z}of X){if(this.errors.affectsPath(Y))continue;this.applyMorphsAtPath(Y,Z)}}}applyMorphsAtPath(X,Y){let Z=X.at(-1),_;if(Z!==void 0){_=this.root;for(let G=0;G<X.length-1;G++)_=_[X[G]]}for(let G of Y){this.path=[...X];let W=E0(G),$=G(_===void 0?this.root:_[Z],this);if($ instanceof L4){this.errors.add($);break}if($ instanceof W1){if(!W)this.errors.merge($);break}if(_===void 0)this.root=$;else _[Z]=$;this.applyQueuedMorphs()}}}var $1=(X,Y,Z)=>{if(!Z)return Y();Z.path.push(X);let _=Y();return Z.path.pop(),_};class m8 extends v1{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(X,Y){super((_,G,W=this.onFail)=>{if(G)return this.traverseApply(_,G),G.hasError()?G.errors:G.data;return this.rootApply(_,W)},{attach:X});this.attachments=X,this.$=Y,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)=>qJ(_,G.shallowReferences),[this]);let Z=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,!Z){let G=this.children[_].flatRefs;for(let W=0;W<G.length;W++){let $=G[W];if(!this.flatRefs.some((H)=>$_(H,$))){this.flatRefs.push($);for(let H of $.node.branches)if(H.hasKind("morph")||H.hasKind("intersection")&&H.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:$.path,propString:$.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 x1(_,this.$.resolvedConfig)):(_)=>this.traverseAllows(_)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Y,Z)=>{if(this.allows(Y))return Y;let _=new x1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)};case"contextual":return(Y,Z)=>{let _=new x1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let X=this.$.resolvedConfig.clone;return(Y,Z)=>{if(this.allows(Y))return this.contextFreeMorph(X&&(typeof Y==="object"&&Y!==null||typeof Y==="function")?X(Y):Y);let _=new x1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,e(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=CJ(this.metaJson);cacheGetter(X,Y){return Object.defineProperty(this,X,{value:Y}),Y}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=a4(this.kind);precompilation;assert=(X,Y)=>this(X,Y,(Z)=>Z.throw());traverse(X,Y){return this(X,Y,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(X){if(!this.includesTransform)return this;let Y={};for(let[Z,_]of this.innerEntries){let G=this.impl.keys[Z];if(G.reduceIo)G.reduceIo(X,Y,_);else if(G.child){let W=_;Y[Z]=Q0(W)?W.map(($)=>$[X]):W[X]}else Y[Z]=_}return this.$.node(this.kind,Y)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(X){let Y=E0(X)?X:this.$.parseDefinition(X);return this.innerHash===Y.innerHash}ifEquals(X){return this.equals(X)?this:void 0}hasKind(X){return this.kind===X}assertHasKind(X){if(this.kind!==X)C4(`${this.kind} node was not of asserted kind ${X}`);return this}hasKindIn(...X){return X.includes(this.kind)}assertHasKindIn(...X){if(!r1(X,this.kind))C4(`${this.kind} node was not one of asserted kinds ${X}`);return this}isBasis(){return r1(X_,this.kind)}isConstraint(){return r1(l2,this.kind)}isStructural(){return r1(r4,this.kind)}isRefinement(){return r1(SX,this.kind)}isRoot(){return r1(s4,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(X){return this.hasKind("unit")&&this.allows(X)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(X){let Y=p8.normalize(X);return this._select(Y)}_select(X){let Y=p8.applyBoundary[X.boundary??"references"](this);if(X.kind)Y=Y.filter((Z)=>Z.kind===X.kind);if(X.where)Y=Y.filter(X.where);return p8.applyMethod[X.method??"filter"](Y,this,X)}transform(X,Y){return this._transform(X,this._createTransformContext(Y))}_createTransformContext(X){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:X?.prereduced??!1},undeclaredKeyHandling:void 0,...X}}_transform(X,Y){let Z=Y.bindScope??this.$;if(Y.seen[this.id])return this.$.lazilyResolve(Y.seen[this.id]);if(Y.shouldTransform?.(this,Y)===!1)return this;let _;if(Y.seen[this.id]=()=>_,this.hasKind("structure")&&this.undeclared!==Y.undeclaredKeyHandling)Y={...Y,undeclaredKeyHandling:this.undeclared};let G=d(this.inner,(J,z)=>{if(!this.impl.keys[J].child)return[J,z];let F=z;if(!Q0(F)){let D=F._transform(X,Y);return D?[J,D]:[]}if(F.length===0)return[J,z];let O=F.flatMap((D)=>{return D._transform(X,Y)??[]});return O.length?[J,O]:[]});delete Y.seen[this.id];let W=Object.assign(G,{meta:this.meta}),$=Y.selected&&!Y.selected.includes(this)?W:X(this.kind,W,Y);if($===null)return null;if(E0($))return _=$;let H=Object.keys($);if((H.length===0||H.length===1&&H[0]==="meta")&&!l1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in $))return Y.undeclaredKeyHandling?{...$,value:N.intrinsic.unknown}:null;if(this.kind==="morph")$.in??=N.intrinsic.unknown;return _=Z.node(this.kind,$,Y.parseOptions)}configureReferences(X,Y="references"){let Z=p8.normalize(Y),_=typeof X==="string"?(H,Q)=>({...Q,meta:{...Q.meta,description:X}}):typeof X==="function"?(H,Q)=>({...Q,meta:X(Q.meta)}):(H,Q)=>({...Q,meta:{...Q.meta,...X}});if(Z.boundary==="self")return this.$.node(this.kind,_(this.kind,{...this.inner,meta:this.meta}));let G=this._select(Z),W=G&&U4(G),$=Z.boundary==="child"?(H,Q)=>Q.root.children.includes(H):Z.boundary==="shallow"?(H)=>H.kind!=="structure":()=>!0;return this.$.finalize(this.transform(_,{shouldTransform:$,selected:W}))}}var p8={applyBoundary:{self:(X)=>[X],child:(X)=>[...X.children],shallow:(X)=>[...X.shallowReferences],references:(X)=>[...X.references]},applyMethod:{filter:(X)=>X,assertFilter:(X,Y,Z)=>{if(X.length===0)C4(W_(Y,Z));return X},find:(X)=>X[0],assertFind:(X,Y,Z)=>{if(X.length===0)C4(W_(Y,Z));return X[0]}},normalize:(X)=>typeof X==="function"?{boundary:"references",method:"filter",where:X}:typeof X==="string"?f0(X,p8.applyBoundary)?{method:"filter",boundary:X}:{boundary:"references",method:"filter",kind:X}:{boundary:"references",method:"filter",...X}},W_=(X,Y)=>`${X} had no references matching ${c(Y)}.`,BJ=(X)=>e1(X,{stringifyNonKey:(Y)=>Y.expression}),TJ=/"(\$ark\.[^"]+)"/g,CJ=(X)=>JSON.stringify(X).replaceAll(TJ,"$1"),f1=(X,Y)=>({path:X,node:Y,propString:BJ(X)}),$_=(X,Y)=>X.propString===Y.propString&&X.node.equals(Y.node),xX=(X,Y)=>c1(X,Y,{isEqual:$_}),qJ=(X,Y)=>c1(X,Y,{isEqual:(Z,_)=>Z.equals(_)});class C extends Array{static init(X,Y,Z,_){return new C({kind:X,l:Y,r:Z,path:_?.path??[],optional:_?.optional??!1})}add(X,Y,Z,_){return this.push({kind:X,l:Y,r:Z,path:_?.path??[],optional:_?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:X,l:Y,r:Z}=this[0],_=e1(X);return hX(`Intersection${_&&` at ${_}`} of ${H_(Y,Z)}`)}return`The following intersections result in unsatisfiable types:
23
+ \u2022 ${this.map(({path:X,l:Y,r:Z})=>`${X}: ${H_(Y,Z)}`).join(`
24
+ \u2022 `)}`}throw(){return R(this.describeReasons())}invert(){let X=this.map((Y)=>({...Y,l:Y.r,r:Y.l}));if(!(X instanceof C))return new C(...X);return X}withPrefixKey(X,Y){return this.map((Z)=>({...Z,path:[X,...Z.path],optional:Z.optional||Y==="optional"}))}toNeverIfDisjoint(){return N.intrinsic.never}}var H_=(X,Y)=>`${fX(X)} and ${fX(Y)}`,fX=(X)=>E0(X)?X.expression:Q0(X)?X.map(fX).join(" | ")||"never":String(X),hX=(X)=>`${X} results in an unsatisfiable type`;var e4={},H1=(X,Y,Z)=>O0(X,Y,{$:Z,invert:!1,pipe:!1}),u8=(X,Y,Z)=>O0(X,Y,{$:Z,invert:!1,pipe:!0}),O0=(X,Y,Z)=>{let _=Z.pipe?"|>":"&",G=`${X.hash}${_}${Y.hash}`;if(e4[G]!==void 0)return e4[G];if(!Z.pipe){let H=`${Y.hash}${_}${X.hash}`;if(e4[H]!==void 0){let Q=e4[H],J=Q instanceof C?Q.invert():Q;return e4[G]=J,J}}let W=!Z.pipe||!X.includesTransform&&!Y.includesTransform;if(W&&X.equals(Y))return X;let $=W?kX(X,Y,Z):X.hasKindIn(...s4)?jJ(X,Y,Z):kX(X,Y,Z);if(E0($)){if(X.equals($))$=X;else if(Y.equals($))$=Y}return e4[G]=$,$},kX=(X,Y,Z)=>{let _=X.precedence<Y.precedence?X.kind:Y.kind,G=X.impl.intersections[Y.kind]??Y.impl.intersections[X.kind];if(G===void 0)return null;else if(_===X.kind)return G(X,Y,Z);else{let W=G(Y,X,{...Z,invert:!Z.invert});if(W instanceof C)W=W.invert();return W}},jJ=(X,Y,Z)=>X.includesTransform||Y.includesTransform?Z.invert?J_(Y,X,Z):J_(X,Y,Z):kX(X,Y,Z),J_=(X,Y,Z)=>X.distribute((_)=>SJ(_,Y,Z),(_)=>{let G=_.filter(E0);if(G.length===0)return C.init("union",X.branches,Y.branches);if(G.length<X.branches.length||!X.branches.every((H,Q)=>H.in.equals(G[Q].in)))return Z.$.parseSchema(G);let W;if(G.length===1){let H=G[0];if(!W)return H;return Z.$.node("morph",{...H.inner,in:H.in.configure(W,"self")})}let $={branches:G};if(W)$.meta=W;return Z.$.parseSchema($)}),SJ=(X,Y,Z)=>{if(X.hasKind("morph")){let G=[...X.morphs];if(X.lastMorphIfNode){let W=O0(X.lastMorphIfNode,Y,Z);if(W instanceof C)return W;G[G.length-1]=W}else G.push(Y);return Z.$.node("morph",{morphs:G,in:X.inner.in})}if(Y.hasKind("morph")){let G=O0(X,Y.in,Z);if(G instanceof C)return G;return Z.$.node("morph",{morphs:[Y],in:G})}return Z.$.node("morph",{morphs:[Y],in:X})};class R1 extends m8{constructor(X,Y){super(X,Y);Object.defineProperty(this,t0,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(X){return H1(this,X,this.$)}}class Y4 extends R1{traverseApply=(X,Y)=>{if(!this.traverseAllows(X,Y))Y.errorFromNodeContext(this.errorContext)};compile(X){if(X.traversalKind==="Allows")X.return(this.compiledCondition);else X.if(this.compiledNegation,()=>X.line(`${X.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return D4(this.errorContext)}}var i0=(X)=>(Y,Z)=>{if(Q0(Y)){if(Y.length===0)return;let G=Y.map((W)=>Z.$.node(X,W));if(X==="predicate")return G;return G.sort((W,$)=>W.hash<$.hash?-1:1)}let _=Z.$.node(X,Y);return _.hasOpenIntersection()?[_]:_},X8=(X)=>{let Y=X.r.shift();if(!Y){let _=X.l.length===0&&X.kind==="structure"?N.intrinsic.unknown.internal:X.ctx.$.node(X.kind,Object.assign(X.baseInner,PJ(X.l)),{prereduced:!0});for(let G of X.roots){if(_ instanceof C)return _;_=O0(G,_,X.ctx)}return _}let Z=!1;for(let _=0;_<X.l.length;_++){let G=O0(X.l[_],Y,X.ctx);if(G===null)continue;if(G instanceof C)return G;if(!Z){if(G.isRoot())return X.roots.push(G),X.l.splice(_),X8(X);X.l[_]=G,Z=!0}else if(!X.l.includes(G))return e(`Unexpectedly encountered multiple distinct intersection results for refinement ${G}`)}if(!Z)X.l.push(Y);if(X.kind==="intersection"){if(Y.impliedSiblings)for(let _ of Y.impliedSiblings)c1(X.r,_)}return X8(X)},Y8=(X)=>{return Object.entries(X).flatMap(([Z,_])=>(Z in o2)?_:[]).sort((Z,_)=>Z.precedence<_.precedence?-1:Z.precedence>_.precedence?1:Z.kind==="predicate"&&_.kind==="predicate"?0:Z.hash<_.hash?-1:1)},PJ=(X)=>{let Y={};for(let Z of X)if(Z.hasOpenIntersection())Y[Z.kind]=t(Y[Z.kind],Z);else{if(Y[Z.kind])return e(`Unexpected intersection of closed refinements of kind ${Z.kind}`);Y[Z.kind]=Z}return Y},Q_=(...X)=>R(z_(...X)),z_=(X,Y,Z)=>{let _=Z.hasKind("morph")?"a morph":Z.isUnknown()?"unknown":Z.exclude(Y).defaultShortDescription;return`${g5(X)} operand must be ${Y.description} (was ${_})`};var F_=(X,Y,Z)=>new M4(X,Y,Z,Z,null);class n2 extends v1{}class M4 extends v1{[t0]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(X,Y,Z,_,G){super((...W)=>{let $=d(this.names,(H,Q)=>{let J=this.arg$.parse(W[H]);if(!J.extends(this.constraints[H]))R(vJ(Q,this.constraints[H].expression,J.expression));return[Q,J]});if(this.defIsLazy()){let H=this.bodyDef($);return this.$.parse(H)}return this.$.parse(Y,{args:$})});this.paramDefs=X,this.bodyDef=Y,this.$=Z,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 n2}cacheGetter(X,Y){return Object.defineProperty(this,X,{value:Y}),Y}get json(){return this.cacheGetter("json",{params:this.params.map((X)=>X[1].isUnknown()?X[0]:[X[0],X[1].json]),body:s5(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((X)=>typeof X==="string"?[X,N.intrinsic.unknown]:[X[0],this.$.parse(X[1])]))}get names(){return this.cacheGetter("names",this.params.map((X)=>X[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((X)=>X[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var vJ=(X,Y,Z)=>`${X} must be assignable to ${Y} (was ${Z})`;var xJ=l({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(X)=>typeof X==="function"?{predicate:X}:X,defaults:{description:(X)=>`valid according to ${X.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class U_ extends R1{serializedPredicate=I0(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=D4(this.errorContext);traverseApply=(X,Y)=>{if(!this.predicate(X,Y.external)&&!Y.hasError())Y.errorFromNodeContext(this.errorContext)};compile(X){if(X.traversalKind==="Allows"){X.return(this.compiledCondition);return}X.if(`${this.compiledNegation} && !ctx.hasError()`,()=>X.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(X,Y){return Y.fallback.predicate({code:"predicate",base:X,predicate:this.predicate})}}var bX={implementation:xJ,Node:U_};var fJ=l({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(X)=>Number.isInteger(X)?X:R(hJ(X))}},normalize:(X)=>typeof X==="number"?{rule:X}:X,hasAssociatedError:!0,defaults:{description:(X)=>X.rule===1?"an integer":X.rule===2?"even":`a multiple of ${X.rule}`},intersections:{divisor:(X,Y,Z)=>Z.$.node("divisor",{rule:Math.abs(X.rule*Y.rule/kJ(X.rule,Y.rule))})},obviatesBasisDescription:!0});class E_ extends Y4{traverseAllows=(X)=>X%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=N.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(X){if(X.type="integer",this.rule===1)return X;return X.multipleOf=this.rule,X}}var yX={implementation:fJ,Node:E_};var hJ=(X)=>`divisor must be an integer (was ${X})`,kJ=(X,Y)=>{let Z,_=X,G=Y;while(G!==0)Z=G,G=_%G,_=Z;return _};class D1 extends Y4{boundOperandKind=pJ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=mJ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${bJ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?uJ(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(X){return(this.limitKind==="upper"?this.numericLimit<X.numericLimit:this.numericLimit>X.numericLimit)||this.numericLimit===X.numericLimit&&this.exclusive===!0&&!X.exclusive}overlapsRange(X){if(this.isStricterThan(X))return!1;if(this.numericLimit===X.numericLimit&&(this.exclusive||X.exclusive))return!1;return!0}overlapIsUnit(X){return this.numericLimit===X.numericLimit&&!this.exclusive&&!X.exclusive}}var bJ={"<":">=","<=":">",">":"<=",">=":"<"},yJ={min:"max",minLength:"maxLength",after:"before"},r2={parse:(X)=>X||void 0},s2=(X)=>(Y)=>{if(typeof Y==="number")return{rule:Y};let{exclusive:Z,..._}=Y;return Z?{..._,rule:X==="minLength"?_.rule+1:_.rule-1}:_},t2=(X)=>(Y)=>{if(typeof Y==="number"||typeof Y==="string"||Y instanceof Date)return{rule:Y};let{exclusive:Z,..._}=Y;if(!Z)return _;let G=typeof _.rule==="number"?_.rule:typeof _.rule==="string"?new Date(_.rule).valueOf():_.rule.valueOf();return Z?{..._,rule:X==="after"?G+1:G-1}:_},a2=(X)=>typeof X==="string"||typeof X==="number"?new Date(X):X,gJ=(X,Y)=>`${X} bound must be a positive integer (was ${Y})`,Z8=(X)=>(Y)=>{if(!Number.isInteger(Y)||Y<0)R(gJ(X,Y));return Y},pJ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},mJ=(X,Y)=>`${f0(X,yJ)?">":"<"}${Y?"":"="}`,uJ=(X)=>typeof X==="string"?X:new Date(X).toLocaleString(),O_=(X)=>`Bounded expression ${X} must be exactly one of number, string, Array, or Date`;var dJ=l({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a2,serialize:(X)=>X.toISOString()}},normalize:t2("after"),defaults:{description:(X)=>`${X.collapsibleLimitString} or later`,actual:P4},intersections:{after:(X,Y)=>X.isStricterThan(Y)?X:Y}});class V_ extends D1{impliedBasis=N.intrinsic.Date.internal;collapsibleLimitString=P4(this.rule);traverseAllows=(X)=>X>=this.rule;reduceJsonSchema(X,Y){return Y.fallback.date({code:"date",base:X,after:this.rule})}}var gX={implementation:dJ,Node:V_};var cJ=l({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a2,serialize:(X)=>X.toISOString()}},normalize:t2("before"),defaults:{description:(X)=>`${X.collapsibleLimitString} or earlier`,actual:P4},intersections:{before:(X,Y)=>X.isStricterThan(Y)?X:Y,after:(X,Y,Z)=>X.overlapsRange(Y)?X.overlapIsUnit(Y)?Z.$.node("unit",{unit:X.rule}):null:C.init("range",X,Y)}});class D_ extends D1{collapsibleLimitString=P4(this.rule);traverseAllows=(X)=>X<=this.rule;impliedBasis=N.intrinsic.Date.internal;reduceJsonSchema(X,Y){return Y.fallback.date({code:"date",base:X,before:this.rule})}}var pX={implementation:cJ,Node:D_};var lJ=l({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:Z8("exactLength")}},normalize:(X)=>typeof X==="number"?{rule:X}:X,hasAssociatedError:!0,defaults:{description:(X)=>`exactly length ${X.rule}`,actual:(X)=>`${X.length}`},intersections:{exactLength:(X,Y,Z)=>C.init("unit",Z.$.node("unit",{unit:X.rule}),Z.$.node("unit",{unit:Y.rule}),{path:["length"]}),minLength:(X,Y)=>X.rule>=Y.rule?X:C.init("range",X,Y),maxLength:(X,Y)=>X.rule<=Y.rule?X:C.init("range",X,Y)}});class L_ extends Y4{traverseAllows=(X)=>X.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=N.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(X){switch(X.type){case"string":return X.minLength=this.rule,X.maxLength=this.rule,X;case"array":return X.minItems=this.rule,X.maxItems=this.rule,X;default:return M0.throwInternalOperandError("exactLength",X)}}}var mX={implementation:lJ,Node:L_};var oJ=l({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r2},normalize:(X)=>typeof X==="number"?{rule:X}:X,defaults:{description:(X)=>{if(X.rule===0)return X.exclusive?"negative":"non-positive";return`${X.exclusive?"less than":"at most"} ${X.rule}`}},intersections:{max:(X,Y)=>X.isStricterThan(Y)?X:Y,min:(X,Y,Z)=>X.overlapsRange(Y)?X.overlapIsUnit(Y)?Z.$.node("unit",{unit:X.rule}):null:C.init("range",X,Y)},obviatesBasisDescription:!0});class M_ extends D1{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(X)=>X<this.rule:(X)=>X<=this.rule;reduceJsonSchema(X){if(this.exclusive)X.exclusiveMaximum=this.rule;else X.maximum=this.rule;return X}}var uX={implementation:oJ,Node:M_};var iJ=l({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Z8("maxLength")}},reduce:(X,Y)=>X.rule===0?Y.node("exactLength",X):void 0,normalize:s2("maxLength"),defaults:{description:(X)=>`at most length ${X.rule}`,actual:(X)=>`${X.length}`},intersections:{maxLength:(X,Y)=>X.isStricterThan(Y)?X:Y,minLength:(X,Y,Z)=>X.overlapsRange(Y)?X.overlapIsUnit(Y)?Z.$.node("exactLength",{rule:X.rule}):null:C.init("range",X,Y)}});class A_ extends D1{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(X)=>X.length<=this.rule;reduceJsonSchema(X){switch(X.type){case"string":return X.maxLength=this.rule,X;case"array":return X.maxItems=this.rule,X;default:return M0.throwInternalOperandError("maxLength",X)}}}var dX={implementation:iJ,Node:A_};var nJ=l({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r2},normalize:(X)=>typeof X==="number"?{rule:X}:X,defaults:{description:(X)=>{if(X.rule===0)return X.exclusive?"positive":"non-negative";return`${X.exclusive?"more than":"at least"} ${X.rule}`}},intersections:{min:(X,Y)=>X.isStricterThan(Y)?X:Y},obviatesBasisDescription:!0});class R_ extends D1{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(X)=>X>this.rule:(X)=>X>=this.rule;reduceJsonSchema(X){if(this.exclusive)X.exclusiveMinimum=this.rule;else X.minimum=this.rule;return X}}var cX={implementation:nJ,Node:R_};var rJ=l({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Z8("minLength")}},reduce:(X)=>X.rule===0?N.intrinsic.unknown:void 0,normalize:s2("minLength"),defaults:{description:(X)=>X.rule===1?"non-empty":`at least length ${X.rule}`,actual:(X)=>X.length===0?"":`${X.length}`},intersections:{minLength:(X,Y)=>X.isStricterThan(Y)?X:Y}});class w_ extends D1{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(X)=>X.length>=this.rule;reduceJsonSchema(X){switch(X.type){case"string":return X.minLength=this.rule,X;case"array":return X.minItems=this.rule,X;default:return M0.throwInternalOperandError("minLength",X)}}}var lX={implementation:rJ,Node:w_};var N_={min:cX.implementation,max:uX.implementation,minLength:lX.implementation,maxLength:dX.implementation,exactLength:mX.implementation,after:gX.implementation,before:pX.implementation},I_={min:cX.Node,max:uX.Node,minLength:lX.Node,maxLength:dX.Node,exactLength:mX.Node,after:gX.Node,before:pX.Node};var sJ=l({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(X)=>typeof X==="string"?{rule:X}:X instanceof RegExp?X.flags?{rule:X.source,flags:X.flags}:{rule:X.source}:X,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(X)=>`matched by ${X.rule}`},intersections:{pattern:()=>null}});class K_ extends Y4{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(X,Y){if(X.pattern)return Y.fallback.patternIntersection({code:"patternIntersection",base:X,pattern:this.rule});return X.pattern=this.rule,X}}var oX={implementation:sJ,Node:K_};var d8=(X,Y)=>{let Z=tJ(X);if(Y&&!Y.includes(Z))return R(`Root of kind ${Z} should be one of ${Y}`);return Z},tJ=(X)=>{if(f(X,"root"))return X.kind;if(typeof X==="string")return X[0]==="$"?"alias":(X in G1)?"domain":"proto";if(typeof X==="function")return"proto";if(typeof X!=="object"||X===null)return R(B_(X));if("morphs"in X)return"morph";if("branches"in X||Q0(X))return"union";if("unit"in X)return"unit";if("reference"in X)return"alias";let Y=Object.keys(X);if(Y.length===0||Y.some((Z)=>(Z in o2)))return"intersection";if("proto"in X)return"proto";if("domain"in X)return"domain";return R(B_(X))},B_=(X)=>`${c(X)} is not a valid type schema`,T_={},aJ=(X)=>Q0(X)?X.map((Y)=>Y.collapsibleJson):X.collapsibleJson,a0={};N.nodesByRegisteredId=a0;var iX=(X)=>{return T_[X]??=0,`${X}${++T_[X]}`},nX=(X)=>{let Y=_8[X.kind],Z=Y.applyConfig?.(X.def,X.$.resolvedConfig)??X.def,_={},{meta:G,...W}=Z,$=G===void 0?{}:typeof G==="string"?{description:G}:G,H=LX(W).sort(([J],[z])=>t4(J)?t4(z)?a4(J)-a4(z):1:t4(z)?-1:J<z?-1:1).filter(([J,z])=>{if(J.startsWith("meta.")){let F=J.slice(5);return $[F]=z,!1}return!0});for(let J of H){let z=J[0],F=Y.keys[z];if(!F)return R(`Key ${z} is not valid on ${X.kind} schema`);let O=F.parse?F.parse(J[1],X):J[1];if(O!==V1&&(O!==void 0||F.preserveUndefined))_[z]=O}if(Y.reduce&&!X.prereduced){let J=Y.reduce(_,X.$);if(J){if(J instanceof C)return J.throw();return eJ(J,$)}}return rX({id:X.id,kind:X.kind,inner:_,meta:$,$:X.$})},rX=({id:X,kind:Y,inner:Z,meta:_,$:G,ignoreCache:W})=>{let $=_8[Y],H=LX(Z),Q=[],J={};for(let[j,P]of H){let h=$.keys[j],i=h.serialize??(h.child?aJ:A1);if(J[j]=i(P),h.child===!0){let p=P;if(Q0(p))Q.push(...p);else Q.push(p)}else if(typeof h.child==="function")Q.push(...h.child(P))}if($.finalizeInnerJson)J=$.finalizeInnerJson(J);let z={...J},F={};if(!l1(_))F=d(_,(j,P)=>[j,j==="examples"?P:A1(P)]),z.meta=e2(F,"description",!0);J=e2(J,$.collapsibleKey,!1);let O=JSON.stringify({kind:Y,...J});z=e2(z,$.collapsibleKey,!1);let D=e2(z,$.collapsibleKey,!0),w=JSON.stringify({kind:Y,...z});if(G.nodesByHash[w]&&!W)return G.nodesByHash[w];let A={id:X,kind:Y,impl:$,inner:Z,innerEntries:H,innerJson:J,innerHash:O,meta:_,metaJson:F,json:z,hash:w,collapsibleJson:D,children:Q};if(Y!=="intersection"){for(let j in Z)if(j!=="in"&&j!=="out")A[j]=Z[j]}let x=new q_[Y](A,G);return G.nodesByHash[w]=x},C_=(X,Y)=>{if(X.id===Y)return X;if(E0(a0[Y]))e(`Unexpected attempt to overwrite node id ${Y}`);return rX({id:Y,kind:X.kind,inner:X.inner,meta:X.meta,$:X.$,ignoreCache:!0})},eJ=(X,Y,Z)=>{if(Z&&E0(a0[Z]))e(`Unexpected attempt to overwrite node id ${Z}`);return rX({id:Z??iX(Y.alias??X.kind),kind:X.kind,inner:X.inner,meta:Y,$:X.$})},e2=(X,Y,Z)=>{let _=Object.keys(X);if(_.length===1&&_[0]===Y){let G=X[Y];if(Z)return G;if(_1(G,"object")&&(Object.keys(G).length===1||Array.isArray(G)))return G}return X};var c8=(X,Y,Z)=>{if(X.key!==Y.key)return null;let _=X.key,G=O0(X.value,Y.value,Z),W=X.required||Y.required?"required":"optional";if(G instanceof C)if(W==="optional")G=N.intrinsic.never.internal;else return G.withPrefixKey(X.key,X.required&&Y.required?"required":"optional");if(W==="required")return Z.$.node("required",{key:_,value:G});let $=X.hasDefault()?Y.hasDefault()?X.default===Y.default?X.default:R(sX(X.default,Y.default)):X.default:Y.hasDefault()?Y.default:V1;return Z.$.node("optional",{key:_,value:G,default:$})};class l8 extends R1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=N.intrinsic.object.internal;serializedKey=X4(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=t(this.value.flatRefs.map((X)=>f1([this.key,...X.path],X.node)),f1([this.key],this.value));_transform(X,Y){Y.path.push(this.key);let Z=super._transform(X,Y);return Y.path.pop(),Z}hasDefault(){return"default"in this.inner}traverseAllows=(X,Y)=>{if(this.key in X)return $1(this.key,()=>this.value.traverseAllows(X[this.key],Y),Y);return this.optional};traverseApply=(X,Y)=>{if(this.key in X)$1(this.key,()=>this.value.traverseApply(X[this.key],Y),Y);else if(this.hasKind("required"))Y.errorFromNodeContext(this.errorContext)};compile(X){if(X.if(`${this.serializedKey} in data`,()=>X.traverseKey(this.serializedKey,`data${X.prop(this.key)}`,this.value)),this.hasKind("required"))X.else(()=>X.traversalKind==="Apply"?X.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):X.return(!1));if(X.traversalKind==="Allows")X.return(!0)}}var sX=(X,Y)=>`Invalid intersection of default values ${c(X)} & ${c(Y)}`;var XQ=l({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)},default:{preserveUndefined:!0}},normalize:(X)=>X,reduce:(X,Y)=>{if(Y.resolvedConfig.exactOptionalPropertyTypes===!1){if(!X.value.allows(void 0))return Y.node("optional",{...X,value:X.value.or(k.undefined)},{prereduced:!0})}},defaults:{description:(X)=>`${X.compiledKey}?: ${X.value.description}`},intersections:{optional:c8}});class j_ extends l8{constructor(...X){super(...X);if("default"in this.inner)i8(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:X,...Y}=this.inner;return this.cacheGetter("outProp",this.$.node("required",Y,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${c(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=ZQ(this);defaultValueMorphRef=this.defaultValueMorph&&I0(this.defaultValueMorph)}var o8={implementation:XQ,Node:j_},YQ={},ZQ=(X)=>{if(!X.hasDefault())return;let Y=`{${X.compiledKey}: ${X.value.id} = ${A1(X.default)}}`;return YQ[Y]??=tX(X.key,X.value,X.default)},tX=(X,Y,Z)=>{if(typeof Z==="function")return Y.includesTransform?(G,W)=>{return $1(X,()=>Y(G[X]=Z(),W),W),G}:(G)=>{return G[X]=Z(),G};let _=Y.includesTransform?Y.assert(Z):Z;return _1(_,"object")?(G,W)=>{return $1(X,()=>Y(G[X]=Z,W),W),G}:(G)=>{return G[X]=_,G}},i8=(X,Y,Z)=>{let _=E4(Y);if(_1(Y,"object")&&!_)R(_Q(Z));let G=X.in(_?Y():Y);if(G instanceof W1){if(Z===null)R(`Default ${G.summary}`);let W=G.transform(($)=>$.transform((H)=>({...H,prefixPath:[Z]})));R(`Default for ${W.summary}`)}return Y},_Q=(X)=>{return`Non-primitive default ${X===null?"":typeof X==="number"?`for value at [${X}] `:`for ${X4(X)} `}must be specified as a function like () => ({my: 'object'})`};class w1 extends m8{constructor(X,Y){super(X,Y);Object.defineProperty(this,t0,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(X)=>{let Y=this(X);if(Y instanceof W1)return Y;return{value:Y}},toJSONSchema:(X)=>{if(X.target&&X.target!=="draft-2020-12")return R(`JSONSchema target '${X.target}' is not supported (must be "draft-2020-12")`);if(X.io==="input")return this.in.toJsonSchema();return this.out.toJsonSchema()}}}as(){return this}brand(X){if(X==="")return R(GQ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(X,Y){let Z=this.branches.map(X);return Y?.(Z)??Z}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(X={}){let Y=PX(this.$.resolvedConfig.toJsonSchema,X);Y.useRefs||=this.isCyclic;let Z=typeof Y.dialect==="string"?{$schema:Y.dialect}:{};if(Object.assign(Z,this.toJsonSchemaRecurse(Y)),Y.useRefs)Z.$defs=d(this.references,(_,G)=>G.isRoot()&&!G.alwaysExpandJsonSchema?[G.id,G.toResolvedJsonSchema(Y)]:[]);return Z}toJsonSchemaRecurse(X){if(X.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(X)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(X){let Y=this.innerToJsonSchema(X);return Object.assign(Y,this.metaJson)}intersect(X){let Y=this.$.parseDefinition(X),Z=this.rawIntersect(Y);if(Z instanceof C)return Z;return this.$.finalize(Z)}rawIntersect(X){return H1(this,X,this.$)}toNeverIfDisjoint(){return this}and(X){let Y=this.intersect(X);return Y instanceof C?Y.throw():Y}rawAnd(X){let Y=this.rawIntersect(X);return Y instanceof C?Y.throw():Y}or(X){let Y=this.$.parseDefinition(X);return this.$.finalize(this.rawOr(Y))}rawOr(X){let Y=[...this.branches,...X.branches];return this.$.node("union",Y)}map(X){return this.$.schema(this.applyStructuralOperation("map",[X]))}pick(...X){return this.$.schema(this.applyStructuralOperation("pick",X))}omit(...X){return this.$.schema(this.applyStructuralOperation("omit",X))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let X=this.applyStructuralOperation("keyof",[]).reduce((Y,Z)=>Y.intersect(Z).toNeverIfDisjoint(),N.intrinsic.unknown.internal);if(X.branches.length===0)R(hX(`keyof ${this.expression}`));return this._keyof=this.$.finalize(X)}get props(){if(this.branches.length!==1)return R(WQ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(X){let Y=this.$.parseDefinition(X);return this.$.schema(Y.distribute((Z)=>this.applyStructuralOperation("merge",[S_(Z)??R(P_("merge",Z.expression))])))}applyStructuralOperation(X,Y){return this.distribute((Z)=>{if(Z.equals(N.intrinsic.object)&&X!=="merge")return Z;let _=S_(Z);if(!_)R(P_(X,Z.expression));if(X==="keyof")return _.keyof();if(X==="get")return _.get(...Y);if(X==="props")return _.props;let G=X==="required"?"require":X==="partial"?"optionalize":X;return this.$.node("intersection",{...Z.inner,structure:_[G](...Y)})})}get(...X){if(X[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",X))}extract(X){let Y=this.$.parseDefinition(X);return this.$.schema(this.branches.filter((Z)=>Z.extends(Y)))}exclude(X){let Y=this.$.parseDefinition(X);return this.$.schema(this.branches.filter((Z)=>!Z.extends(Y)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(X){return!(this.intersect(X)instanceof C)}extends(X){let Y=this.intersect(X);return!(Y instanceof C)&&this.equals(Y)}ifExtends(X){return this.extends(X)?this:void 0}subsumes(X){return this.$.parseDefinition(X).extends(this)}configure(X,Y="shallow"){return this.configureReferences(X,Y)}describe(X,Y="shallow"){return this.configure({description:X},Y)}optional(){return[this,"?"]}default(X){return i8(this,X,null),[this,"=",X]}from(X){return this.assert(X)}_pipe(...X){let Y=X.reduce((Z,_)=>Z.rawPipeOnce(_),this);return this.$.finalize(Y)}tryPipe(...X){let Y=X.reduce((Z,_)=>Z.rawPipeOnce(f(_,"root")?_:(G,W)=>{try{return _(G,W)}catch($){return W.error({code:"predicate",predicate:_,actual:`aborted due to error:
25
+ ${$}
26
+ `})}}),this);return this.$.finalize(Y)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(X){return this.$.finalize(this.toNode(this.$.parseDefinition(X)))}toNode(X){let Y=u8(this,X,this.$);if(Y instanceof C)return Y.throw();return Y}rawPipeOnce(X){if(f(X,"root"))return this.toNode(X);return this.distribute((Y)=>Y.hasKind("morph")?this.$.node("morph",{in:Y.inner.in,morphs:[...Y.morphs,X]}):this.$.node("morph",{in:Y,morphs:[X]}),this.$.parseSchema)}narrow(X){return this.constrainOut("predicate",X)}constrain(X,Y){return this._constrain("root",X,Y)}constrainIn(X,Y){return this._constrain("in",X,Y)}constrainOut(X,Y){return this._constrain("out",X,Y)}_constrain(X,Y,Z){let _=this.$.node(Y,Z);if(_.isRoot())return _.isUnknown()?this:e(`Unexpected constraint node ${_}`);let G=X==="root"?this:this[X];if(G.hasKind("morph")||_.impliedBasis&&!G.extends(_.impliedBasis))return Q_(Y,_.impliedBasis,this);let W=this.$.node("intersection",{[_.kind]:_}),$=X==="out"?u8(this,W,this.$):H1(this,W,this.$);if($ instanceof C)$.throw();return this.$.finalize($)}onUndeclaredKey(X){let Y=typeof X==="string"?X:X.rule,Z=typeof X==="string"?!1:X.deep;return this.$.finalize(this.transform((_,G)=>_==="structure"?Y==="ignore"?q5(G,{undeclared:1}):{...G,undeclared:Y}:G,Z?void 0:{shouldTransform:(_)=>!r1(r4,_.kind)}))}hasEqualMorphs(X){if(!this.includesTransform&&!X.includesTransform)return!0;if(!t1(this.shallowMorphs,X.shallowMorphs))return!1;if(!t1(this.flatMorphs,X.flatMorphs,{isEqual:(Y,Z)=>Y.propString===Z.propString&&(Y.node.hasKind("morph")&&Z.node.hasKind("morph")?Y.node.hasEqualMorphs(Z.node):Y.node.hasKind("intersection")&&Z.node.hasKind("intersection")?Y.node.structure?.structuralMorphRef===Z.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(X){return this.onUndeclaredKey({rule:X,deep:!0})}filter(X){return this.constrainIn("predicate",X)}divisibleBy(X){return this.constrain("divisor",X)}matching(X){return this.constrain("pattern",X)}atLeast(X){return this.constrain("min",X)}atMost(X){return this.constrain("max",X)}moreThan(X){return this.constrain("min",G8(X))}lessThan(X){return this.constrain("max",G8(X))}atLeastLength(X){return this.constrain("minLength",X)}atMostLength(X){return this.constrain("maxLength",X)}moreThanLength(X){return this.constrain("minLength",G8(X))}lessThanLength(X){return this.constrain("maxLength",G8(X))}exactlyLength(X){return this.constrain("exactLength",X)}atOrAfter(X){return this.constrain("after",X)}atOrBefore(X){return this.constrain("before",X)}laterThan(X){return this.constrain("after",G8(X))}earlierThan(X){return this.constrain("before",G8(X))}}var GQ="Expected a non-empty brand name after #",G8=(X)=>typeof X==="object"&&!(X instanceof Date)?{...X,exclusive:!0}:{rule:X,exclusive:!0},n8=(X,Y)=>f(Y,"root")?f(X,"root")?X.extends(Y):Y.allows(X):f(X,"root")?X.hasUnit(Y):Y===X,S_=(X)=>{if(X.hasKind("morph"))return null;if(X.hasKind("intersection"))return X.inner.structure??(X.basis?.domain==="object"?X.$.bindReference(N.intrinsic.emptyStructure):null);if(X.isBasis()&&X.domain==="object")return X.$.bindReference(N.intrinsic.emptyStructure);return null},WQ=(X)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
+ ${X}`,P_=(X,Y)=>`${X} operand must be an object (was ${Y})`;var o1=(X,Y)=>d(i2(X),(Z,_)=>[_,Y]);var $Q=(X)=>typeof X==="string"?{reference:X}:X,v_=(X)=>X instanceof C?N.intrinsic.never.internal:X,HQ=l({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(X)=>X.startsWith("$")?X:`$ark.${X}`},resolve:{}},normalize:$Q,defaults:{description:(X)=>X.reference},intersections:{alias:(X,Y,Z)=>Z.$.lazilyResolve(()=>v_(O0(X.resolution,Y.resolution,Z)),`${X.reference}${Z.pipe?"=>":"&"}${Y.reference}`),...o1("alias",(X,Y,Z)=>{if(Y.isUnknown())return X;if(Y.isNever())return Y;if(Y.isBasis()&&!Y.overlaps(N.intrinsic.object))return C.init("assignability",N.intrinsic.object,Y);return Z.$.lazilyResolve(()=>v_(O0(X.resolution,Y,Z)),`${X.reference}${Z.pipe?"=>":"&"}${Y.id}`)})}});class x_ extends w1{expression=this.reference;structure=void 0;get resolution(){let X=this._resolve();return a0[this.id]=X}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let X=this.reference,Y=a0[X],Z=[];while(f(Y,"context")){if(Z.includes(Y.id))return R(JQ(Y.id,Z));Z.push(Y.id),Y=a0[Y.id]}if(!f(Y,"root"))return e(`Unexpected resolution for reference ${this.reference}
28
+ Seen: [${Z.join("->")}]
29
+ Resolution: ${c(Y)}`);return Y}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let X=this.reference.slice(1),Y=this.$.resolutions[X];if(typeof Y==="string")return Y;if(f(Y,"root"))return Y.id;return e(`Unexpected resolution for reference ${this.reference}: ${c(Y)}`)}get defaultShortDescription(){return G1.object}innerToJsonSchema(X){return this.resolution.toJsonSchemaRecurse(X)}traverseAllows=(X,Y)=>{let Z=Y.seen[this.reference];if(Z?.includes(X))return!0;return Y.seen[this.reference]=t(Z,X),this.resolution.traverseAllows(X,Y)};traverseApply=(X,Y)=>{let Z=Y.seen[this.reference];if(Z?.includes(X))return;Y.seen[this.reference]=t(Z,X),this.resolution.traverseApply(X,Y)};compile(X){let Y=this.resolutionId;X.if(`ctx.seen.${Y} && ctx.seen.${Y}.includes(data)`,()=>X.return(!0)),X.if(`!ctx.seen.${Y}`,()=>X.line(`ctx.seen.${Y} = []`)),X.line(`ctx.seen.${Y}.push(data)`),X.return(X.invoke(Y))}}var JQ=(X,Y)=>`Alias '${X}' has a shallow resolution cycle: ${[...Y,X].join("->")}`,r8={implementation:HQ,Node:x_};class v4 extends w1{traverseApply=(X,Y)=>{if(!this.traverseAllows(X,Y))Y.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return D4(this.errorContext)}compile(X){if(X.traversalKind==="Allows")X.return(this.compiledCondition);else X.if(this.compiledNegation,()=>X.line(`${X.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var QQ=l({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(X)=>typeof X==="string"?{domain:X}:i4(X,"numberAllowsNaN")&&X.domain!=="number"?R(X6.writeBadAllowNanMessage(X.domain)):X,applyConfig:(X,Y)=>X.numberAllowsNaN===void 0&&X.domain==="number"&&Y.numberAllowsNaN?{...X,numberAllowsNaN:!0}:X,defaults:{description:(X)=>G1[X.domain],actual:(X)=>Number.isNaN(X)?"NaN":G1[x0(X)]},intersections:{domain:(X,Y)=>X.domain==="number"&&Y.domain==="number"?X.numberAllowsNaN?Y:X:C.init("domain",X,Y)}});class f_ extends v4{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(X)=>typeof X==="number"&&!Number.isNaN(X):(X)=>x0(X)===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 G1[this.domain]}innerToJsonSchema(X){if(this.domain==="bigint"||this.domain==="symbol")return X.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var X6={implementation:QQ,Node:f_,writeBadAllowNanMessage:(X)=>`numberAllowsNaN may only be specified with domain "number" (was ${X})`};var zQ=l({kind:"intersection",hasAssociatedError:!0,normalize:(X)=>{if(E0(X))return X;let{structure:Y,...Z}=X,_=!!Y,G=Y??{},W=d(Z,($,H)=>{if(f0($,Y_)){if(_)R(`Flattened structure key ${$} cannot be specified alongside a root 'structure' key.`);return G[$]=H,[]}return[$,H]});if(f(G,"constraint")||!l1(G))W.structure=G;return W},finalizeInnerJson:({structure:X,...Y})=>_1(X,"object")?{...X,...Y}:Y,keys:{domain:{child:!0,parse:(X,Y)=>Y.$.node("domain",X)},proto:{child:!0,parse:(X,Y)=>Y.$.node("proto",X)},structure:{child:!0,parse:(X,Y)=>Y.$.node("structure",X),serialize:(X)=>{if(!X.sequence?.minLength)return X.collapsibleJson;let{sequence:Y,...Z}=X.collapsibleJson,{minVariadicLength:_,...G}=Y,W=G.variadic&&Object.keys(G).length===1?G.variadic:G;return{...Z,sequence:W}}},divisor:{child:!0,parse:i0("divisor")},max:{child:!0,parse:i0("max")},min:{child:!0,parse:i0("min")},maxLength:{child:!0,parse:i0("maxLength")},minLength:{child:!0,parse:i0("minLength")},exactLength:{child:!0,parse:i0("exactLength")},before:{child:!0,parse:i0("before")},after:{child:!0,parse:i0("after")},pattern:{child:!0,parse:i0("pattern")},predicate:{child:!0,parse:i0("predicate")}},reduce:(X,Y)=>h_({},X,{$:Y,invert:!1,pipe:!1}),defaults:{description:(X)=>{if(X.children.length===0)return"unknown";if(X.structure)return X.structure.description;let Y=[];if(X.basis&&!X.refinements.some((Z)=>Z.impl.obviatesBasisDescription))Y.push(X.basis.description);if(X.refinements.length){let Z=X.refinements.toSorted((_,G)=>_.kind==="min"&&G.kind==="max"?-1:0).map((_)=>_.description);Y.push(...Z)}if(X.inner.predicate)Y.push(...X.inner.predicate.map((Z)=>Z.description));return Y.join(" and ")},expected:(X)=>` \u25E6 ${X.errors.map((Y)=>Y.expected).join(`
30
+ \u25E6 `)}`,problem:(X)=>`(${X.actual}) must be...
31
+ ${X.expected}`},intersections:{intersection:(X,Y,Z)=>h_(X.inner,Y.inner,Z),...o1("intersection",(X,Y,Z)=>{if(X.children.length===0)return Y;let{domain:_,proto:G,...W}=X.inner,$=G??_,H=$?O0($,Y,Z):Y;return H instanceof C?H:X?.basis?.equals(H)?X:X.$.node("intersection",{...W,[H.kind]:H},{prereduced:!0})})}});class k_ extends w1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((X)=>X.isRefinement());structure=this.inner.structure;expression=FQ(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(X){return this.children.reduce((Y,Z)=>Z.isBasis()?Z.toJsonSchemaRecurse(X):Z.reduceJsonSchema(Y,X),{})}traverseAllows=(X,Y)=>this.children.every((Z)=>Z.traverseAllows(X,Y));traverseApply=(X,Y)=>{let Z=Y.currentErrorCount;if(this.basis){if(this.basis.traverseApply(X,Y),Y.currentErrorCount>Z)return}if(this.refinements.length){for(let _=0;_<this.refinements.length-1;_++)if(this.refinements[_].traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>Z)return;if(this.refinements.at(-1).traverseApply(X,Y),Y.currentErrorCount>Z)return}if(this.structure){if(this.structure.traverseApply(X,Y),Y.currentErrorCount>Z)return}if(this.inner.predicate){for(let _=0;_<this.inner.predicate.length-1;_++)if(this.inner.predicate[_].traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>Z)return;this.inner.predicate.at(-1).traverseApply(X,Y)}};compile(X){if(X.traversalKind==="Allows"){for(let Y of this.children)X.check(Y);X.return(!0);return}if(X.initializeErrorCount(),this.basis){if(X.check(this.basis),this.children.length>1)X.returnIfFail()}if(this.refinements.length){for(let Y=0;Y<this.refinements.length-1;Y++)X.check(this.refinements[Y]),X.returnIfFailFast();if(X.check(this.refinements.at(-1)),this.structure||this.inner.predicate)X.returnIfFail()}if(this.structure){if(X.check(this.structure),this.inner.predicate)X.returnIfFail()}if(this.inner.predicate){for(let Y=0;Y<this.inner.predicate.length-1;Y++)X.check(this.inner.predicate[Y]),X.returnIfFail();X.check(this.inner.predicate.at(-1))}}}var aX={implementation:zQ,Node:k_},FQ=(X)=>{let Y=X.structure?.expression||`${X.basis&&!X.refinements.some((Z)=>Z.impl.obviatesBasisExpression)?X.basis.nestableExpression+" ":""}${X.refinements.map((Z)=>Z.expression).join(" & ")}`||"unknown";if(Y==="Array == 0")Y="[]";return Y},h_=(X,Y,Z)=>{let _={},G=X.proto??X.domain,W=Y.proto??Y.domain,$=G?W?O0(G,W,Z):G:W;if($ instanceof C)return $;if($)_[$.kind]=$;return X8({kind:"intersection",baseInner:_,l:Y8(X),r:Y8(Y),roots:[],ctx:Z})};var UQ=l({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)},morphs:{parse:U4,serialize:(X)=>X.map((Y)=>f(Y,"root")?Y.json:I0(Y))},declaredIn:{child:!1,serialize:(X)=>X.json},declaredOut:{child:!1,serialize:(X)=>X.json}},normalize:(X)=>X,defaults:{description:(X)=>`a morph from ${X.in.description} to ${X.out?.description??"unknown"}`},intersections:{morph:(X,Y,Z)=>{if(!X.hasEqualMorphs(Y))return R(EQ(X.expression,Y.expression));let _=O0(X.in,Y.in,Z);if(_ instanceof C)return _;let G={morphs:X.morphs};if(X.declaredIn||Y.declaredIn){let W=O0(X.in,Y.in,Z);if(W instanceof C)return W.throw();else G.declaredIn=W}if(X.declaredOut||Y.declaredOut){let W=O0(X.out,Y.out,Z);if(W instanceof C)return W.throw();else G.declaredOut=W}return _.distribute((W)=>Z.$.node("morph",{...G,in:W}),Z.$.parseSchema)},...o1("morph",(X,Y,Z)=>{let _=X.inner.in?O0(X.inner.in,Y,Z):Y;return _ instanceof C?_:_.equals(X.inner.in)?X:Z.$.node("morph",{...X.inner,in:_})})}});class b_ extends w1{serializedMorphs=this.morphs.map(I0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=f(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(X){return this.$.node("morph",{...this.inner,declaredIn:X})}declareOut(X){return this.$.node("morph",{...this.inner,declaredOut:X})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(X){return X.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(X),out:this.introspectableOut?.toJsonSchemaRecurse(X)??null})}compile(X){if(X.traversalKind==="Allows"){if(!this.introspectableIn)return;X.return(X.invoke(this.introspectableIn));return}if(this.introspectableIn)X.line(X.invoke(this.introspectableIn));X.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(X,Y)=>!this.introspectableIn||this.introspectableIn.traverseAllows(X,Y);traverseApply=(X,Y)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(X,Y);Y.queueMorphs(this.morphs)};hasEqualMorphs(X){return t1(this.morphs,X.morphs,{isEqual:(Y,Z)=>Y===Z||f(Y,"root")&&f(Z,"root")&&Y.equals(Z)})}}var eX={implementation:UQ,Node:b_},EQ=(X,Y)=>`The intersection of distinct morphs at a single path is indeterminate:
32
+ Left: ${X}
33
+ Right: ${Y}`;var OQ=l({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(X)=>P8(X)??A1(X)},dateAllowsInvalid:{}},normalize:(X)=>{let Y=typeof X==="string"?{proto:j4[X]}:typeof X==="function"?E0(X)?X:{proto:X}:typeof X.proto==="string"?{...X,proto:j4[X.proto]}:X;if(typeof Y.proto!=="function")R(s8.writeInvalidSchemaMessage(Y.proto));if(i4(Y,"dateAllowsInvalid")&&Y.proto!==Date)R(s8.writeBadInvalidDateMessage(Y.proto));return Y},applyConfig:(X,Y)=>{if(X.dateAllowsInvalid===void 0&&X.proto===Date&&Y.dateAllowsInvalid)return{...X,dateAllowsInvalid:!0};return X},defaults:{description:(X)=>X.builtinName?v5[X.builtinName]:`an instance of ${X.proto.name}`,actual:(X)=>X instanceof Date&&X.toString()==="Invalid Date"?"an invalid Date":S8(X)},intersections:{proto:(X,Y)=>X.proto===Date&&Y.proto===Date?X.dateAllowsInvalid?Y:X:NX(X.proto,Y.proto)?X:NX(Y.proto,X.proto)?Y:C.init("proto",X,Y),domain:(X,Y)=>Y.domain==="object"?X:C.init("domain",N.intrinsic.object.internal,Y)}});class y_ extends v4{builtinName=P8(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(X)=>X instanceof Date&&X.toString()!=="Invalid Date":(X)=>X instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(X){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return X.fallback.date?.({code:"date",base:{}})??X.fallback.proto({code:"proto",base:{},proto:this.proto});default:return X.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 s8={implementation:OQ,Node:y_,writeBadInvalidDateMessage:(X)=>`dateAllowsInvalid may only be specified with constructor Date (was ${X.name})`,writeInvalidSchemaMessage:(X)=>`instanceOf operand must be a function (was ${x0(X)})`};var VQ=l({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(X,Y)=>{let Z=[];for(let _ of X){let G=f(_,"root")?_.branches:Y.$.parseSchema(_).branches;for(let W of G)if(W.hasKind("morph")){let $=Z.findIndex((H)=>H.hasKind("morph")&&H.hasEqualMorphs(W));if($===-1)Z.push(W);else{let H=Z[$];Z[$]=Y.$.node("morph",{...H.inner,in:H.in.rawOr(W.in)})}}else Z.push(W)}if(!Y.def.ordered)Z.sort((_,G)=>_.hash<G.hash?-1:1);return Z}}},normalize:(X)=>Q0(X)?{branches:X}:X,reduce:(X,Y)=>{let Z=BQ(X);if(Z.length===1)return Z[0];if(Z.length===X.branches.length)return;return Y.node("union",{...X,branches:Z},{prereduced:!0})},defaults:{description:(X)=>X.distribute((Y)=>Y.description,W8),expected:(X)=>{let Y=K5(X.errors,"propString"),Z=Object.entries(Y).map(([_,G])=>{let W=[];for(let Q of G)c1(W,Q.expected);let $=W8(W),H=G.every((Q)=>Q.actual===G[0].actual)?G[0].actual:c(G[0].data);return`${_&&`${_} `}must be ${$}${H&&` (was ${H})`}`});return W8(Z)},problem:(X)=>X.expected,message:(X)=>X.problem},intersections:{union:(X,Y,Z)=>{if(X.isNever!==Y.isNever)return C.init("presence",X,Y);let _;if(X.ordered){if(Y.ordered)R(CQ(X.expression,Y.expression));if(_=XY(Y.branches,X.branches,Z),_ instanceof C)_.invert()}else _=XY(X.branches,Y.branches,Z);if(_ instanceof C)return _;return Z.$.parseSchema(X.ordered||Y.ordered?{branches:_,ordered:!0}:{branches:_})},...o1("union",(X,Y,Z)=>{let _=XY(X.branches,[Y],Z);if(_ instanceof C)return _;if(_.length===1)return _[0];return Z.$.parseSchema(X.ordered?{branches:_,ordered:!0}:{branches:_})})}});class m_ extends w1{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let X=[],Y=-1;for(let Z of this.branches){if(Z.hasKind("unit")&&Z.domain==="boolean"){if(Y===-1)Y=X.length,X.push(Z);else X[Y]=N.intrinsic.boolean;continue}X.push(Z)}return X}unitBranches=this.branches.filter((X)=>X.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?NQ(this.discriminant):null;expression=this.distribute((X)=>X.nestableExpression,KQ);createBranchedOptimisticRootApply(){return(X,Y)=>{let Z=this.traverseOptimistic(X);if(Z!==V1)return Z;let _=new x1(X,this.$.resolvedConfig);return this.traverseApply(X,_),_.finalize(Y)}}get shallowMorphs(){return this.branches.reduce((X,Y)=>c1(X,Y.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((X)=>X.defaultShortDescription,W8)}innerToJsonSchema(X){if(this.branchGroups.length===1&&this.branchGroups[0].equals(N.intrinsic.boolean))return{type:"boolean"};let Y=this.branchGroups.map((Z)=>Z.toJsonSchemaRecurse(X));if(Y.every((Z)=>Object.keys(Z).length===1&&i4(Z,"const")))return{enum:Y.map((Z)=>Z.const)};return{anyOf:Y}}traverseAllows=(X,Y)=>this.branches.some((Z)=>Z.traverseAllows(X,Y));traverseApply=(X,Y)=>{let Z=[];for(let _=0;_<this.branches.length;_++){if(Y.pushBranch(),this.branches[_].traverseApply(X,Y),!Y.hasError()){if(this.branches[_].includesTransform)return Y.queuedMorphs.push(...Y.popBranch().queuedMorphs);return Y.popBranch()}Z.push(Y.popBranch().error)}Y.errorFromNodeContext({code:"union",errors:Z,meta:this.meta})};traverseOptimistic=(X)=>{for(let Y=0;Y<this.branches.length;Y++){let Z=this.branches[Y];if(Z.traverseAllows(X)){if(Z.contextFreeMorph)return Z.contextFreeMorph(X);return X}}return V1};compile(X){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(X);let Y=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")Y=`typeof ${Y} === "object" ? ${Y} === null ? "null" : "object" : typeof ${Y} === "function" ? "object" : typeof ${Y}`;let Z=this.discriminant.cases,_=Object.keys(Z),{optimistic:G}=X;if(X.optimistic=!1,X.block(`switch(${Y})`,()=>{for(let J in Z){let z=Z[J],F=J==="default"?J:`case ${J}`;X.line(`${F}: return ${z===!0?G?X.data:z:G?`${X.invoke(z)} ? ${z.contextFreeMorph?`${I0(z.contextFreeMorph)}(${X.data})`:X.data} : "${V1}"`:X.invoke(z)}`)}return X}),X.traversalKind==="Allows"){X.return(G?`"${V1}"`:!1);return}let W=W8(this.discriminant.kind==="domain"?_.map((J)=>{let z=J.slice(1,-1);return z==="function"?G1.object:G1[z]}):_),$=this.discriminant.path.map((J)=>typeof J==="symbol"?I0(J):JSON.stringify(J)),H=JSON.stringify(W),Q=this.discriminant.kind==="domain"?`${RQ}[${Y}]`:`${wQ}(${Y})`;X.line(`ctx.errorFromNodeContext({
34
34
  code: "predicate",
35
35
  expected: ${H},
36
36
  actual: ${Q},
37
- relativePath: [${W}],
37
+ relativePath: [${$}],
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?`${T0(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 _=o(this.unitBranches,($,W)=>[`${W.in.serializedValue}`,W.hasKind("morph")?W:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:_}}let Y=[];for(let _=0;_<this.branches.length-1;_++){let $=this.branches[_];for(let W=_+1;W<this.branches.length;W++){let H=this.branches[W],Q=z1($.in,H.in,$.$);if(!(Q instanceof S))continue;for(let J of Q){if(!J.kind||J.optional)continue;let z,U;if(J.kind==="domain"){let{l:L,r:w}=J;z=`"${typeof L==="string"?L:L.domain}"`,U=`"${typeof w==="string"?w:w.domain}"`}else if(J.kind==="unit")z=J.l.serializedValue,U=J.r.serializedValue;else continue;let O=Y.find((L)=>a1(L.path,J.path)&&L.kind===J.kind);if(!O)Y.push({kind:J.kind,cases:{[z]:{branchIndices:[_],condition:J.l},[U]:{branchIndices:[W],condition:J.r}},path:J.path});else{if(O.cases[z])O.cases[z].branchIndices=c1(O.cases[z].branchIndices,_);else O.cases[z]??={branchIndices:[_],condition:J.l};if(O.cases[U])O.cases[U].branchIndices=c1(O.cases[U].branchIndices,W);else O.cases[U]??={branchIndices:[W],condition:J.r}}}}}let Z=this.ordered?wQ(Y,this.branches):Y;if(!Z.length)return null;let X=AQ(Z,this),G={};for(let _ in X.best.cases){let $=RQ(X,_);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 _=X.defaultEntries.map(($)=>$.branch);G.default=this.$.node("union",this.ordered?{branches:_,ordered:!0}:_,{prereduced:!0}),Object.assign(this.referencesById,G.default.referencesById)}return Object.assign(X.location,{cases:G})}}var AQ=(Y,Z)=>{let X=Y.sort(($,W)=>Object.keys(W.cases).length-Object.keys($.cases).length)[0],G={kind:X.kind,path:X.path,optionallyChainedPropString:mG(X.path)},_=Z.branches.map(($,W)=>({originalIndex:W,branch:$}));return{best:X,location:G,defaultEntries:_,node:Z}},RQ=(Y,Z)=>{let X=Y.best.cases[Z],G=NQ(X.condition,Y.location.path,Y.node.$),_=[],$=[];for(let W=0;W<Y.defaultEntries.length;W++){let H=Y.defaultEntries[W];if(X.branchIndices.includes(H.originalIndex)){let Q=yG(Y.node.branches[H.originalIndex],Y.location);if(Q===null)_=null;else _?.push({originalIndex:H.originalIndex,branch:Q})}else if(H.branch.hasKind("alias")&&G.hasKind("domain")&&G.domain==="object")_?.push(H);else{if(H.branch.in.overlaps(G)){let Q=yG(H.branch,Y.location);_?.push({originalIndex:H.originalIndex,branch:Q})}$.push(H)}}return Y.defaultEntries=$,_},wQ=(Y,Z)=>{return Y.filter((G)=>{let _=Object.values(G.cases).map(($)=>$.branchIndices);for(let $=0;$<_.length-1;$++){let W=_[$];for(let H=$+1;H<_.length;H++){let Q=_[H];for(let J of W)for(let z of Q)if(J>z){if(Z[J].overlaps(Z[z]))return!1}}}return!0})},NQ=(Y,Z,X)=>{let G=Y==="undefined"?X.node("unit",{unit:void 0}):Y==="null"?X.node("unit",{unit:null}):Y==="boolean"?X.units([!0,!1]):Y;for(let _=Z.length-1;_>=0;_--){let $=Z[_];G=X.node("intersection",typeof $==="number"?{proto:"Array",sequence:[...wX($).map((W)=>({})),G]}:{domain:"object",required:[{key:$,value:G}]})}return G},mG=(Y)=>Y.reduce((Z,X)=>Z+jY(X,!0),"data"),IQ=T0(KX),KQ=T0(i),ZZ={implementation:MQ,Node:pG},BQ=(Y)=>({kind:Y.kind,path:Y.path.map((Z)=>typeof Z==="string"?Z:Z4(Z)),cases:o(Y.cases,(Z,X)=>[Z,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),TQ={delimiter:" | ",finalDelimiter:" | "},CQ=(Y)=>W2(Y,TQ),W2=(Y,Z)=>{let X=Z?.delimiter??", ",G=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 _={},$=Y.filter((H)=>_[H]?!1:_[H]=!0),W=$.pop();return`${$.join(X)}${$.length?G:""}${W}`},YZ=(Y,Z,X)=>{let G=Z.map(()=>[]);for(let $=0;$<Y.length;$++){let W={};for(let H=0;H<Z.length;H++){if(G[H]===null)continue;if(Y[$].equals(Z[H])){G[H]=null,W={};break}let Q=L0(Y[$],Z[H],X);if(Q instanceof S)continue;if(Q.equals(Y[$])){G[H].push(Y[$]),W={};break}if(Q.equals(Z[H]))G[H]=null;else W[H]=Q}for(let H in W)G[H][$]=W[H]}let _=G.flatMap(($,W)=>$?.flatMap((H)=>H.branches)??Z[W]);return _.length===0?S.init("union",Y,Z):_},qQ=({branches:Y,ordered:Z})=>{if(Y.length<2)return Y;let X=Y.map(()=>!0);for(let G=0;G<Y.length;G++)for(let _=G+1;_<Y.length&&X[G]&&X[_];_++){if(Y[G].equals(Y[_])){X[_]=!1;continue}let $=z1(Y[G].in,Y[_].in,Y[0].$);if($ instanceof S)continue;if(!Z)jQ(Y[G],Y[_]);if($.equals(Y[G].in))X[G]=!!Z;else if($.equals(Y[_].in))X[_]=!1}return Y.filter((G,_)=>X[_])},jQ=(Y,Z)=>{if(!Y.includesTransform&&!Z.includesTransform)return;if(!a1(Y.shallowMorphs,Z.shallowMorphs))A(gG(Y.expression,Z.expression));if(!a1(Y.flatMorphs,Z.flatMorphs,{isEqual:(X,G)=>X.propString===G.propString&&(X.node.hasKind("morph")&&G.node.hasKind("morph")?X.node.hasEqualMorphs(G.node):X.node.hasKind("intersection")&&G.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===G.node.structure?.structuralMorphRef:!1)}))A(gG(Y.expression,Z.expression))},yG=(Y,Z)=>Y.transform((X,G)=>{if(X==="domain"||X==="unit")return null;return G},{shouldTransform:(X,G)=>{let _=mG(G.path);if(!Z.optionallyChainedPropString.startsWith(_))return!1;if(X.hasKind("domain")&&X.domain==="object")return!0;if((X.hasKind("domain")||Z.kind==="unit")&&_===Z.optionallyChainedPropString)return!0;return X.children.length!==0&&X.kind!=="index"}}),gG=(Y,Z)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
40
- Left: ${Y}
41
- Right: ${Z}`,PQ=(Y,Z)=>`The intersection of two ordered unions is indeterminate:
42
- Left: ${Y}
43
- Right: ${Z}`;var SQ=r({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Y)=>Y instanceof Date?Y.toISOString():w1(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)=>S.init("unit",Y,Z),...o1("unit",(Y,Z)=>{if(Z.allows(Y.unit))return Y;let X=Z.hasKind("intersection")?Z.basis:Z;if(X){let G=X.hasKind("domain")?X:I.intrinsic.object;if(Y.domain!==G.domain){let _=Y.domain==="undefined"||Y.domain==="null"||Y.domain==="boolean"?Y.domain:I.intrinsic[Y.domain];return S.init("domain",_,G)}}return S.init("assignability",Y,Z.hasKind("intersection")?Z.children.find((G)=>!G.allows(Y.unit)):Z)})}});class dG extends v4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=uG(this.unit,this.serializedValue);compiledNegation=uG(this.unit,this.serializedValue,"negated");expression=i(this.unit);domain=y0(this.unit);get defaultShortDescription(){return this.domain==="object"?H1.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 XZ={implementation:SQ,Node:dG},uG=(Y,Z,X)=>{if(Y instanceof Date){let G=`data instanceof Date && data.toISOString() === ${Z}`;return X?`!(${G})`:G}if(Number.isNaN(Y))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${Z}`};var vQ=r({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(fQ(X.expression));let G=X.branches.filter((_)=>_.hasKind("unit"));if(G.length)return A(xQ(G.map((_)=>i(_.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 G=L0(Y.value,Z.value,X),_=G instanceof S?I.intrinsic.never.internal:G;return X.$.node("index",{signature:Y.signature,value:_})}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 cG extends N1{impliedBasis=I.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=Z0(this.value.flatRefs.map((Y)=>f1([this.signature,...Y.path],Y.node)),f1([this.signature],this.value));traverseAllows=(Y,Z)=>q4(Y).every((X)=>{if(this.signature.traverseAllows(X[0],Z))return Q1(X[0],()=>this.value.traverseAllows(X[1],Z),Z);return!0});traverseApply=(Y,Z)=>{for(let X of q4(Y))if(this.signature.traverseAllows(X[0],Z))Q1(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 GZ={implementation:vQ,Node:cG},xQ=(Y)=>`Index keys ${Y.join(", ")} should be specified as named props.`,fQ=(Y)=>`Indexed key definition '${Y}' must be a string or symbol`;var hQ=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:l2,optional:l2}});class lG extends o2{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=D4(this.errorContext)}var _Z={implementation:hQ,Node:lG};var kQ=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 G=Z.$.parseSchema(X[0]);return n2(G,X[1],null),[G,X[1]]})},serialize:(Y)=>Y.map((Z)=>[Z[0].collapsibleJson,w1(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(pQ);if(Y.optionals?.length||Y.defaultables?.length)return A(WZ)}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,G=Y.prefix?.slice()??[],_=Y.defaultables?.slice()??[],$=Y.optionals?.slice()??[],W=Y.postfix?.slice()??[];if(Y.variadic){while($.at(-1)?.equals(Y.variadic))$.pop();if($.length===0&&_.length===0)while(G.at(-1)?.equals(Y.variadic))G.pop(),X++;while(W[0]?.equals(Y.variadic))W.shift(),X++}else if($.length===0&&_.length===0)G.push(...W.splice(0));if(X!==Y.minVariadicLength||Y.prefix&&Y.prefix.length!==G.length)return Z.node("sequence",{...Y,prefix:G,defaultables:_,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 G=a2({l:Y.tuple,r:Z.tuple,disjoint:new S,result:[],fixedVariants:[],ctx:X}),_=G.disjoint.length===0?[G,...G.fixedVariants]:G.fixedVariants;return _.length===0?G.disjoint:_.length===1?X.$.node("sequence",oG(_[0].result)):X.$.node("union",_.map(($)=>({proto:Array,sequence:oG($.result)})))}}});class iG extends N1{impliedBasis=I.intrinsic.Array.internal;tuple=gQ(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=t1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return xY(this.flatRefs,this.prevariadic.flatMap((Y,Z)=>Z0(Y.node.flatRefs.map((X)=>f1([`${Z}`,...X.path],X.node)),f1([`${Z}`],Y.node)))),xY(this.flatRefs,this.variadicOrPostfix.flatMap((Y)=>Z0(Y.flatRefs.map((Z)=>f1([I.intrinsic.nonNegativeIntegerString.internal,...Z.path],Z.node)),f1([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=yQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?T0(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??G0(`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++)Q1(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 G=`${Z+this.prefixLength}`;Y.if(`${G} >= ${Y.data}.length`,()=>Y.traversalKind==="Allows"?Y.return(!0):Y.return()),Y.traverseKey(G,`data[${G}]`,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 G=`firstPostfixIndex + ${Z}`;Y.traverseKey(G,`data[${G}]`,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 G=X.node.toJsonSchemaRecurse(Z);if(X.kind==="defaultables"){let _=typeof X.default==="function"?X.default():X.default;G.default=I.intrinsic.jsonData.allows(_)?_:Z.fallback.defaultValue({code:"defaultValue",base:G,value:_})}return G});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 G=this.postfix.map((_)=>_.toJsonSchemaRecurse(Z));Y=Z.fallback.arrayPostfix({code:"arrayPostfix",base:X,elements:G})}}else Y.items=!1,delete Y.maxItems;return Y}}var bQ={},yQ=(Y)=>{if(!Y.defaultables)return[];let Z=[],X="[",G=Y.prefixLength+Y.defaultablesLength-1;for(let _=Y.prefixLength;_<=G;_++){let[$,W]=Y.defaultables[_-Y.prefixLength];Z.push(tY(_,$,W)),X+=`${_}: ${$.id} = ${w1(W)}, `}return X+="]",bQ[X]??=Z},$Z={implementation:kQ,Node:iG},gQ=(Y)=>{let Z=[];if(Y.prefix)for(let X of Y.prefix)Z.push({kind:"prefix",node:X});if(Y.defaultables)for(let[X,G]of Y.defaultables)Z.push({kind:"defaultables",node:X,default:G});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},oG=(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},{}),WZ="A postfix required element cannot follow an optional or defaultable element",pQ="A postfix element requires a variadic element",a2=(Y)=>{let[Z,...X]=Y.l,[G,..._]=Y.r;if(!Z||!G)return Y;let $=X.at(-1)?.kind==="postfix",W=_.at(-1)?.kind==="postfix",H=Z.kind==="prefix"||G.kind==="prefix"?"prefix":Z.kind==="postfix"||G.kind==="postfix"?"postfix":Z.kind==="variadic"&&G.kind==="variadic"?"variadic":$||W?"prefix":Z.kind==="defaultables"||G.kind==="defaultables"?"defaultables":"optionals";if(Z.kind==="prefix"&&G.kind==="variadic"&&W){let U=a2({...Y,fixedVariants:[],r:_.map((O)=>({...O,kind:"prefix"}))});if(U.disjoint.length===0)Y.fixedVariants.push(U)}else if(G.kind==="prefix"&&Z.kind==="variadic"&&$){let U=a2({...Y,fixedVariants:[],l:X.map((O)=>({...O,kind:"prefix"}))});if(U.disjoint.length===0)Y.fixedVariants.push(U)}let Q=L0(Z.node,G.node,Y.ctx);if(Q instanceof S)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 a2({...Y,fixedVariants:[],l:X.map((U)=>({...U,kind:"prefix"})),r:X.map((U)=>({...U,kind:"prefix"}))});else if(H==="defaultables"){if(Z.kind==="defaultables"&&G.kind==="defaultables"&&Z.default!==G.default)A(sY(Z.default,G.default));Y.result=[...Y.result,{kind:H,node:Q,default:Z.kind==="defaultables"?Z.default:G.kind==="defaultables"?G.default:G0(`Unexpected defaultable intersection from ${Z.kind} and ${G.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&&(G.kind==="variadic"||z===1))Y.l=X;if(G.kind!=="variadic"||z>=J&&(Z.kind==="variadic"||J===1))Y.r=_;return a2(Y)};var sG=(Y)=>(Z)=>{if(Z.props.length||Z.index){let X=Z.index?.map((_)=>_[Y])??[];for(let _ of Z.props)X.push(_[Y]);if(Z.undeclared)X.push(`+ (undeclared): ${Z.undeclared}`);let G=`{ ${X.join(", ")} }`;return Z.sequence?`${G} & ${Z.sequence.description}`:G}return Z.sequence?.description??"{}"},mQ=sG("description"),uQ=sG("expression"),nG=(Y,Z,X)=>{let G=Y.required?"required":"optional";if(!Z.signature.allows(Y.key))return null;let _=z1(Y.value,Z.value,X);if(_ instanceof S)return G==="optional"?X.node("optional",{key:Y.key,value:I.intrinsic.never.internal}):_.withPrefixKey(Y.key,Y.kind);return null},dQ=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:s0("required"),reduceIo:(Y,Z,X)=>{Z.required=Z0(Z.required,X.map((G)=>G[Y]));return}},optional:{child:!0,parse:s0("optional"),reduceIo:(Y,Z,X)=>{if(Y==="in"){Z.optional=X.map((G)=>G.in);return}for(let G of X)Z[G.outProp.kind]=Z0(Z[G.outProp.kind],G.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:mQ},intersections:{structure:(Y,Z,X)=>{let G={...Y.inner},_={...Z.inner},$=new S;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(_.optional)_.optional=_.optional.filter((J)=>Q.allows(J.key));if(_.index)_.index=_.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let z=z1(Q,J.signature,X.$);if(z instanceof S)return[];let U=Z6(z,J.value,X.$);if(U.required)_.required=t1(_.required,U.required);if(U.optional)_.optional=t1(_.optional,U.optional);return U.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(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=z1(Q,J.signature,X.$);if(z instanceof S)return[];let U=Z6(z,J.value,X.$);if(U.required)G.required=t1(G.required,U.required);if(U.optional)G.optional=t1(G.optional,U.optional);return U.index??[]})}let W={};if(Y.undeclared||Z.undeclared)W.undeclared=Y.undeclared==="reject"||Z.undeclared==="reject"?"reject":"delete";let H=Z2({kind:"structure",baseInner:W,l:X2(G),r:X2(_),roots:[],ctx:X});if(H instanceof S)$.push(...H);if($.length)return $;return H}},reduce:(Y,Z)=>{if(Y.index){if(!(Y.required||Y.optional))return;let X=!1,G=Y.required??[],_=Y.optional??[],$=[..._];for(let W of Y.index){for(let H of G){let Q=nG(H,W,Z);if(Q instanceof S)return Q}for(let[H,Q]of _.entries()){let J=nG(Q,W,Z);if(J instanceof S)return J;if(J===null)continue;$[H]=J,X=!0}}if(X)return Z.node("structure",{...Y,optional:$},{prereduced:!0})}}});class tG extends N1{impliedBasis=I.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Y)=>Y.impliedSiblings??[]);props=t1(this.required,this.optional);propsByKey=o(this.props,(Y,Z)=>[Z.key,Z]);propsByKeyReference=T0(this.propsByKey);expression=uQ(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 G=this.propsByKey[X.key];if(D0(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 _=X.kind??G?.kind??"required",$=o(X,(W,H)=>(W in i2.implementation.keys)?[W,H]:[]);return Z[_]=Z0(Z[_],this.$.node(_,$)),Z},{}))}assertHasKeys(Y){let Z=Y.filter((X)=>!r2(X,this.keyof()));if(Z.length)return A(rG(this.expression,Z))}get(Y,...Z){let X,G=!1,_=iQ(Y);if((typeof _==="string"||typeof _==="symbol")&&this.propsByKey[_])X=this.propsByKey[_].value,G=this.propsByKey[_].required;if(this.index){for(let W of this.index)if(r2(_,W.signature))X=X?.and(W.value)??W.value}if(this.sequence&&r2(_,I.intrinsic.nonNegativeIntegerString))if(y(_,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let W=Number.parseInt(_);if(W<this.sequence.prevariadic.length){let H=this.sequence.prevariadic[W].node;X=X?.and(H)??H,G||=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(_,"root")&&_.extends(I.intrinsic.number))return A(nQ(_.expression,this.sequence.expression));return A(rG(this.expression,[_]))}let $=X.get(...Z);return G?$:$.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=c8(this.inner),G=(_)=>{let $=Z.some((W)=>r2(_,W));return Y==="pick"?$:!$};if(X.required)X.required=X.required.filter((_)=>G(_.key));if(X.optional)X.optional=X.optional.filter((_)=>G(_.key));if(X.index)X.index=X.index.filter((_)=>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 G=X?.currentErrorCount??0;for(let _=0;_<this.props.length;_++)if(Y==="Allows"){if(!this.props[_].traverseAllows(Z,X))return!1}else if(this.props[_].traverseApply(Z,X),X.failFast&&X.currentErrorCount>G)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>G)return!1}if(this.index||this.undeclared==="reject"){let _=Object.keys(Z);_.push(...Object.getOwnPropertySymbols(Z));for(let $=0;$<_.length;$++){let W=_[$];if(this.index){for(let H of this.index)if(H.signature.traverseAllows(W,X)){if(Y==="Allows"){if(!Q1(W,()=>H.value.traverseAllows(Z[W],X),X))return!1}else if(Q1(W,()=>H.value.traverseApply(Z[W],X),X),X.failFast&&X.currentErrorCount>G)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",lQ(this))}structuralMorphRef=this.structuralMorph&&T0(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(["),oQ(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 w0.throwInternalOperandError("structure",Y)}}reduceObjectJsonSchema(Y,Z){if(this.props.length){Y.properties={};for(let X of this.props){let G=X.value.toJsonSchemaRecurse(Z);if(typeof X.key==="symbol"){Z.fallback.symbolKey({code:"symbolKey",base:Y,key:X.key,value:G,optional:X.optional});continue}if(X.hasDefault()){let _=typeof X.default==="function"?X.default():X.default;G.default=I.intrinsic.jsonData.allows(_)?_:Z.fallback.defaultValue({code:"defaultValue",base:G,value:_})}Y.properties[X.key]=G}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 G=X.value.toJsonSchemaRecurse(Z);if(X.signature.equals(I.intrinsic.string)){Y.additionalProperties=G;continue}for(let _ of X.signature.branches){if(!_.extends(I.intrinsic.string)){Y=Z.fallback.symbolKey({code:"symbolKey",base:Y,key:null,value:G,optional:!1});continue}let $={type:"string"};if(_.hasKind("morph"))$=Z.fallback.morph({code:"morph",base:_.in.toJsonSchemaRecurse(Z),out:_.out.toJsonSchemaRecurse(Z)});if(!_.hasKind("intersection"))return G0(`Unexpected index branch kind ${_.kind}.`);let{pattern:W}=_.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]=G}}}if(this.undeclared&&!Y.additionalProperties)Y.additionalProperties=!1;return Y}}var HZ={},cQ=(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+=u.nonNegativeIntegerString.id;else for(let X=0;X<Y.sequence.tuple.length;X++)Z+=X+" | ";Z+=")"}return Z},lQ=(Y)=>{let Z=cQ(Y);if(!Z)return;if(HZ[Z])return HZ[Z];let X=(G,_)=>{for(let $=0;$<Y.defaultable.length;$++)if(!(Y.defaultable[$].key in G))Y.defaultable[$].defaultValueMorph(G,_);if(Y.sequence?.defaultables)for(let $=G.length-Y.sequence.prefixLength;$<Y.sequence.defaultables.length;$++)Y.sequence.defaultValueMorphs[$](G,_);if(Y.undeclared==="delete"){for(let $ in G)if(!Y.declaresKey($))delete G[$]}return G};return HZ[Z]=X},oQ=(Y,Z)=>{let G=`(data${Z.defaultable.some((_)=>_.defaultValueMorph.length===2)||Z.sequence?.defaultValueMorphs.some((_)=>_.length===2)?", ctx":""})`;return Y.block(`${G} => `,(_)=>{for(let $=0;$<Z.defaultable.length;$++){let{serializedKey:W,defaultValueMorphRef:H}=Z.defaultable[$];_.if(`!(${W} in data)`,(Q)=>Q.line(`${H}${G}`))}if(Z.sequence?.defaultables)_.for(`i < ${Z.sequence.defaultables.length}`,($)=>$.set("data[i]",5),`data.length - ${Z.sequence.prefixLength}`);if(Z.undeclared==="delete")_.forIn("data",($)=>$.if(`!(${Z._compileDeclaresKey($)})`,(W)=>W.line("delete data[k]")));return _.return("data")})},JZ={implementation:dQ,Node:tG},iQ=(Y)=>{if(y(Y,"root")&&Y.hasKind("unit"))Y=Y.unit;if(typeof Y==="number")Y=`${Y}`;return Y},nQ=(Y,Z)=>`${Y} is not allowed as an array index on ${Z}. Use the 'nonNegativeIntegerString' keyword instead.`,Z6=(Y,Z,X)=>{let[G,_]=RX(Y.branches,(W)=>W.hasKind("unit"));if(!G.length)return{index:X.node("index",{signature:Y,value:Z})};let $={};for(let W of G){let H=X.node("required",{key:W.unit,value:Z});$[H.kind]=Z0($[H.kind],H)}if(_.length)$.index=X.node("index",{signature:_,value:Z});return $},rQ=(Y)=>y(Y,"root")?Y.expression:i(Y),rG=(Y,Z)=>`Key${Z.length===1?"":"s"} ${Z.map(rQ).join(", ")} ${Z.length===1?"does":"do"} not exist on ${Y}`;var _2={...wG,alias:s2.implementation,domain:Y6.implementation,unit:XZ.implementation,proto:t2.implementation,union:ZZ.implementation,morph:eY.implementation,intersection:aY.implementation,divisor:yY.implementation,pattern:oY.implementation,predicate:bY.implementation,required:_Z.implementation,optional:i2.implementation,index:GZ.implementation,sequence:$Z.implementation,structure:JZ.implementation};I.defaultConfig=jX(Object.assign(o(_2,(Y,Z)=>[Y,Z.defaults]),{jitless:hX(),clone:vX,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:w0.defaultConfig}));I.resolvedConfig=p2(I.defaultConfig,I.config);var CG={...NG,alias:s2.Node,domain:Y6.Node,unit:XZ.Node,proto:t2.Node,union:ZZ.Node,morph:eY.Node,intersection:aY.Node,divisor:yY.Node,pattern:oY.Node,predicate:bY.Node,required:_Z.Node,optional:i2.Node,index:GZ.Node,sequence:$Z.Node,structure:JZ.Node};class H2 extends MY{get[Y1](){return"module"}}var QZ=(Y,Z)=>new H2(o(Y,(X,G)=>[X,y(G,"module")?QZ(G,Z):Z.bindReference(G)]));var sQ=(Y)=>F0(Y)?Y:("branches"in Y)&&F0(Y.branches)?Y.branches:void 0,tQ=(Y,Z)=>A(`Node of kind ${Z} is not valid as a ${Y} definition`),aG=(Y)=>`#${Y} duplicates public alias ${Y}`,zZ={};I.ambient??={};var eG,Z9="function $",aQ=(Y)=>X9(Y,G9(Y)),X9=(Y,Z)=>{let X=Z.write(Z9,4),G=Z.compile()();for(let _ of Y){if(_.precompilation)continue;if(_.traverseAllows=G[`${_.id}Allows`].bind(G),_.isRoot()&&!_.allowsRequiresContext)_.allows=_.traverseAllows;if(_.traverseApply=G[`${_.id}Apply`].bind(G),G[`${_.id}Optimistic`])_.traverseOptimistic=G[`${_.id}Optimistic`].bind(G);_.precompilation=X}},G9=(Y)=>new d8().return(Y.reduce((Z,X)=>{let G=new g2({kind:"Allows"}).indent();X.compile(G);let _=G.write(`${X.id}Allows`),$=new g2({kind:"Apply"}).indent();X.compile($);let W=$.write(`${X.id}Apply`),H=`${Z}${_},
44
- ${W},
45
- `;if(!X.hasKind("union"))return H;let Q=new g2({kind:"Allows",optimistic:!0}).indent();X.compile(Q);let J=Q.write(`${X.id}Optimistic`);return`${H}${J},
39
+ })`)}compileIndiscriminable(X){if(X.traversalKind==="Apply"){X.const("errors","[]");for(let Y of this.branches)X.line("ctx.pushBranch()").line(X.invoke(Y)).if("!ctx.hasError()",()=>X.return(Y.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");X.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:Y}=X;X.optimistic=!1;for(let Z of this.branches)X.if(`${X.invoke(Z)}`,()=>X.return(Y?Z.contextFreeMorph?`${I0(Z.contextFreeMorph)}(${X.data})`:X.data:!0));X.return(Y?`"${V1}"`:!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=d(this.unitBranches,(W,$)=>[`${$.in.serializedValue}`,$.hasKind("morph")?$:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:G}}let X=[];for(let G=0;G<this.branches.length-1;G++){let W=this.branches[G];for(let $=G+1;$<this.branches.length;$++){let H=this.branches[$],Q=H1(W.in,H.in,W.$);if(!(Q instanceof C))continue;for(let J of Q){if(!J.kind||J.optional)continue;let z,F;if(J.kind==="domain"){let{l:D,r:w}=J;z=`"${typeof D==="string"?D:D.domain}"`,F=`"${typeof w==="string"?w:w.domain}"`}else if(J.kind==="unit")z=J.l.serializedValue,F=J.r.serializedValue;else continue;let O=X.find((D)=>t1(D.path,J.path)&&D.kind===J.kind);if(!O)X.push({kind:J.kind,cases:{[z]:{branchIndices:[G],condition:J.l},[F]:{branchIndices:[$],condition:J.r}},path:J.path});else{if(O.cases[z])O.cases[z].branchIndices=c1(O.cases[z].branchIndices,G);else O.cases[z]??={branchIndices:[G],condition:J.l};if(O.cases[F])O.cases[F].branchIndices=c1(O.cases[F].branchIndices,$);else O.cases[F]??={branchIndices:[$],condition:J.r}}}}}let Y=this.ordered?MQ(X,this.branches):X;if(!Y.length)return null;let Z=DQ(Y,this),_={};for(let G in Z.best.cases){let W=LQ(Z,G);if(W===null){_[G]=!0;continue}if(W.length===this.branches.length)return null;if(this.ordered)W.sort((Q,J)=>Q.originalIndex-J.originalIndex);let $=W.map((Q)=>Q.branch),H=$.length===1?$[0]:this.$.node("union",this.ordered?{branches:$,ordered:!0}:$);Object.assign(this.referencesById,H.referencesById),_[G]=H}if(Z.defaultEntries.length){let G=Z.defaultEntries.map((W)=>W.branch);_.default=this.$.node("union",this.ordered?{branches:G,ordered:!0}:G,{prereduced:!0}),Object.assign(this.referencesById,_.default.referencesById)}return Object.assign(Z.location,{cases:_})}}var DQ=(X,Y)=>{let Z=X.sort((W,$)=>Object.keys($.cases).length-Object.keys(W.cases).length)[0],_={kind:Z.kind,path:Z.path,optionallyChainedPropString:u_(Z.path)},G=Y.branches.map((W,$)=>({originalIndex:$,branch:W}));return{best:Z,location:_,defaultEntries:G,node:Y}},LQ=(X,Y)=>{let Z=X.best.cases[Y],_=AQ(Z.condition,X.location.path,X.node.$),G=[],W=[];for(let $=0;$<X.defaultEntries.length;$++){let H=X.defaultEntries[$];if(Z.branchIndices.includes(H.originalIndex)){let Q=g_(X.node.branches[H.originalIndex],X.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=g_(H.branch,X.location);G?.push({originalIndex:H.originalIndex,branch:Q})}W.push(H)}}return X.defaultEntries=W,G},MQ=(X,Y)=>{return X.filter((_)=>{let G=Object.values(_.cases).map((W)=>W.branchIndices);for(let W=0;W<G.length-1;W++){let $=G[W];for(let H=W+1;H<G.length;H++){let Q=G[H];for(let J of $)for(let z of Q)if(J>z){if(Y[J].overlaps(Y[z]))return!1}}}return!0})},AQ=(X,Y,Z)=>{let _=X==="undefined"?Z.node("unit",{unit:void 0}):X==="null"?Z.node("unit",{unit:null}):X==="boolean"?Z.units([!0,!1]):X;for(let G=Y.length-1;G>=0;G--){let W=Y[G];_=Z.node("intersection",typeof W==="number"?{proto:"Array",sequence:[...N5(W).map(($)=>({})),_]}:{domain:"object",required:[{key:W,value:_}]})}return _},u_=(X)=>X.reduce((Y,Z)=>Y+jX(Z,!0),"data"),RQ=I0(B5),wQ=I0(c),YY={implementation:VQ,Node:m_},NQ=(X)=>({kind:X.kind,path:X.path.map((Y)=>typeof Y==="string"?Y:X4(Y)),cases:d(X.cases,(Y,Z)=>[Y,Z===!0?Z:Z.hasKind("union")&&Z.discriminantJson?Z.discriminantJson:Z.json])}),IQ={delimiter:" | ",finalDelimiter:" | "},KQ=(X)=>W8(X,IQ),W8=(X,Y)=>{let Z=Y?.delimiter??", ",_=Y?.finalDelimiter??" or ";if(X.length===0)return"never";if(X.length===1)return X[0];if(X.length===2&&X[0]==="false"&&X[1]==="true"||X[0]==="true"&&X[1]==="false")return"boolean";let G={},W=X.filter((H)=>G[H]?!1:G[H]=!0),$=W.pop();return`${W.join(Z)}${W.length?_:""}${$}`},XY=(X,Y,Z)=>{let _=Y.map(()=>[]);for(let W=0;W<X.length;W++){let $={};for(let H=0;H<Y.length;H++){if(_[H]===null)continue;if(X[W].equals(Y[H])){_[H]=null,$={};break}let Q=O0(X[W],Y[H],Z);if(Q instanceof C)continue;if(Q.equals(X[W])){_[H].push(X[W]),$={};break}if(Q.equals(Y[H]))_[H]=null;else $[H]=Q}for(let H in $)_[H][W]=$[H]}let G=_.flatMap((W,$)=>W?.flatMap((H)=>H.branches)??Y[$]);return G.length===0?C.init("union",X,Y):G},BQ=({branches:X,ordered:Y})=>{if(X.length<2)return X;let Z=X.map(()=>!0);for(let _=0;_<X.length;_++)for(let G=_+1;G<X.length&&Z[_]&&Z[G];G++){if(X[_].equals(X[G])){Z[G]=!1;continue}let W=H1(X[_].in,X[G].in,X[0].$);if(W instanceof C)continue;if(!Y)TQ(X[_],X[G]);if(W.equals(X[_].in))Z[_]=!!Y;else if(W.equals(X[G].in))Z[G]=!1}return X.filter((_,G)=>Z[G])},TQ=(X,Y)=>{if(!X.includesTransform&&!Y.includesTransform)return;if(!t1(X.shallowMorphs,Y.shallowMorphs))R(p_(X.expression,Y.expression));if(!t1(X.flatMorphs,Y.flatMorphs,{isEqual:(Z,_)=>Z.propString===_.propString&&(Z.node.hasKind("morph")&&_.node.hasKind("morph")?Z.node.hasEqualMorphs(_.node):Z.node.hasKind("intersection")&&_.node.hasKind("intersection")?Z.node.structure?.structuralMorphRef===_.node.structure?.structuralMorphRef:!1)}))R(p_(X.expression,Y.expression))},g_=(X,Y)=>X.transform((Z,_)=>{if(Z==="domain"||Z==="unit")return null;return _},{shouldTransform:(Z,_)=>{let G=u_(_.path);if(!Y.optionallyChainedPropString.startsWith(G))return!1;if(Z.hasKind("domain")&&Z.domain==="object")return!0;if((Z.hasKind("domain")||Y.kind==="unit")&&G===Y.optionallyChainedPropString)return!0;return Z.children.length!==0&&Z.kind!=="index"}}),p_=(X,Y)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
40
+ Left: ${X}
41
+ Right: ${Y}`,CQ=(X,Y)=>`The intersection of two ordered unions is indeterminate:
42
+ Left: ${X}
43
+ Right: ${Y}`;var qQ=l({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(X)=>X instanceof Date?X.toISOString():A1(X)}},normalize:(X)=>X,defaults:{description:(X)=>c(X.unit),problem:({expected:X,actual:Y})=>`${X===Y?`must be reference equal to ${X} (serialized to the same value)`:`must be ${X} (was ${Y})`}`},intersections:{unit:(X,Y)=>C.init("unit",X,Y),...o1("unit",(X,Y)=>{if(Y.allows(X.unit))return X;let Z=Y.hasKind("intersection")?Y.basis:Y;if(Z){let _=Z.hasKind("domain")?Z:N.intrinsic.object;if(X.domain!==_.domain){let G=X.domain==="undefined"||X.domain==="null"||X.domain==="boolean"?X.domain:N.intrinsic[X.domain];return C.init("domain",G,_)}}return C.init("assignability",X,Y.hasKind("intersection")?Y.children.find((_)=>!_.allows(X.unit)):Y)})}});class c_ extends v4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=d_(this.unit,this.serializedValue);compiledNegation=d_(this.unit,this.serializedValue,"negated");expression=c(this.unit);domain=x0(this.unit);get defaultShortDescription(){return this.domain==="object"?G1.object:this.description}innerToJsonSchema(X){return this.unit===null?{type:"null"}:N.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:X.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(X)=>X instanceof Date&&X.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(X)=>Number.isNaN(X):(X)=>X===this.unit}var ZY={implementation:qQ,Node:c_},d_=(X,Y,Z)=>{if(X instanceof Date){let _=`data instanceof Date && data.toISOString() === ${Y}`;return Z?`!(${_})`:_}if(Number.isNaN(X))return`${Z?"!":""}Number.isNaN(data)`;return`data ${Z?"!":"="}== ${Y}`};var jQ=l({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(X,Y)=>{let Z=Y.$.parseSchema(X);if(!Z.extends(N.intrinsic.key))return R(PQ(Z.expression));let _=Z.branches.filter((G)=>G.hasKind("unit"));if(_.length)return R(SQ(_.map((G)=>c(G.unit))));return Z}},value:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)}},normalize:(X)=>X,defaults:{description:(X)=>`[${X.signature.expression}]: ${X.value.description}`},intersections:{index:(X,Y,Z)=>{if(X.signature.equals(Y.signature)){let _=O0(X.value,Y.value,Z),G=_ instanceof C?N.intrinsic.never.internal:_;return Z.$.node("index",{signature:X.signature,value:G})}if(X.signature.extends(Y.signature)&&X.value.subsumes(Y.value))return Y;if(Y.signature.extends(X.signature)&&Y.value.subsumes(X.value))return X;return null}}});class l_ extends R1{impliedBasis=N.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=t(this.value.flatRefs.map((X)=>f1([this.signature,...X.path],X.node)),f1([this.signature],this.value));traverseAllows=(X,Y)=>q4(X).every((Z)=>{if(this.signature.traverseAllows(Z[0],Y))return $1(Z[0],()=>this.value.traverseAllows(Z[1],Y),Y);return!0});traverseApply=(X,Y)=>{for(let Z of q4(X))if(this.signature.traverseAllows(Z[0],Y))$1(Z[0],()=>this.value.traverseApply(Z[1],Y),Y)};_transform(X,Y){Y.path.push(this.signature);let Z=super._transform(X,Y);return Y.path.pop(),Z}compile(){}}var _Y={implementation:jQ,Node:l_},SQ=(X)=>`Index keys ${X.join(", ")} should be specified as named props.`,PQ=(X)=>`Indexed key definition '${X}' must be a string or symbol`;var vQ=l({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)}},normalize:(X)=>X,defaults:{description:(X)=>`${X.compiledKey}: ${X.value.description}`,expected:(X)=>X.missingValueDescription,actual:()=>"missing"},intersections:{required:c8,optional:c8}});class o_ extends l8{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=D4(this.errorContext)}var GY={implementation:vQ,Node:o_};var xQ=l({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>Y.$.parseSchema(Z))}},optionals:{child:!0,parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>Y.$.parseSchema(Z))}},defaultables:{child:(X)=>X.map((Y)=>Y[0]),parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>{let _=Y.$.parseSchema(Z[0]);return i8(_,Z[1],null),[_,Z[1]]})},serialize:(X)=>X.map((Y)=>[Y[0].collapsibleJson,A1(Y[1])])},variadic:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X,Y)},minVariadicLength:{parse:(X)=>X===0?void 0:X},postfix:{child:!0,parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>Y.$.parseSchema(Z))}}},normalize:(X)=>{if(typeof X==="string")return{variadic:X};if("variadic"in X||"prefix"in X||"defaultables"in X||"optionals"in X||"postfix"in X||"minVariadicLength"in X){if(X.postfix?.length){if(!X.variadic)return R(bQ);if(X.optionals?.length||X.defaultables?.length)return R($Y)}if(X.minVariadicLength&&!X.variadic)return R("minVariadicLength may not be specified without a variadic element");return X}return{variadic:X}},reduce:(X,Y)=>{let Z=X.minVariadicLength??0,_=X.prefix?.slice()??[],G=X.defaultables?.slice()??[],W=X.optionals?.slice()??[],$=X.postfix?.slice()??[];if(X.variadic){while(W.at(-1)?.equals(X.variadic))W.pop();if(W.length===0&&G.length===0)while(_.at(-1)?.equals(X.variadic))_.pop(),Z++;while($[0]?.equals(X.variadic))$.shift(),Z++}else if(W.length===0&&G.length===0)_.push(...$.splice(0));if(Z!==X.minVariadicLength||X.prefix&&X.prefix.length!==_.length)return Y.node("sequence",{...X,prefix:_,defaultables:G,optionals:W,postfix:$,minVariadicLength:Z},{prereduced:!0})},defaults:{description:(X)=>{if(X.isVariadicOnly)return`${X.variadic.nestableExpression}[]`;return`[${X.tuple.map((Z)=>Z.kind==="defaultables"?`${Z.node.nestableExpression} = ${c(Z.default)}`:Z.kind==="optionals"?`${Z.node.nestableExpression}?`:Z.kind==="variadic"?`...${Z.node.nestableExpression}[]`:Z.node.expression).join(", ")}]`}},intersections:{sequence:(X,Y,Z)=>{let _=t8({l:X.tuple,r:Y.tuple,disjoint:new C,result:[],fixedVariants:[],ctx:Z}),G=_.disjoint.length===0?[_,..._.fixedVariants]:_.fixedVariants;return G.length===0?_.disjoint:G.length===1?Z.$.node("sequence",i_(G[0].result)):Z.$.node("union",G.map((W)=>({proto:Array,sequence:i_(W.result)})))}}});class n_ extends R1{impliedBasis=N.intrinsic.Array.internal;tuple=kQ(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((X)=>{if(X.kind==="defaultables"||X.kind==="optionals")return this.defaultablesAndOptionals.push(X.node),!0;return X.kind==="prefix"});variadicOrPostfix=s1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return xX(this.flatRefs,this.prevariadic.flatMap((X,Y)=>t(X.node.flatRefs.map((Z)=>f1([`${Y}`,...Z.path],Z.node)),f1([`${Y}`],X.node)))),xX(this.flatRefs,this.variadicOrPostfix.flatMap((X)=>t(X.flatRefs.map((Y)=>f1([N.intrinsic.nonNegativeIntegerString.internal,...Y.path],Y.node)),f1([N.intrinsic.nonNegativeIntegerString.internal],X)))),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=hQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?I0(this.defaultValueMorphs):void 0;elementAtIndex(X,Y){if(Y<this.prevariadic.length)return this.tuple[Y];let Z=X.length-this.postfixLength;if(Y>=Z)return{kind:"postfix",node:this.postfix[Y-Z]};return{kind:"variadic",node:this.variadic??e(`Unexpected attempt to access index ${Y} on ${this}`)}}traverseAllows=(X,Y)=>{for(let Z=0;Z<X.length;Z++)if(!this.elementAtIndex(X,Z).node.traverseAllows(X[Z],Y))return!1;return!0};traverseApply=(X,Y)=>{let Z=0;for(;Z<X.length;Z++)$1(Z,()=>this.elementAtIndex(X,Z).node.traverseApply(X[Z],Y),Y)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(X){if(this.prefix)for(let[Y,Z]of this.prefix.entries())X.traverseKey(`${Y}`,`data[${Y}]`,Z);for(let[Y,Z]of this.defaultablesAndOptionals.entries()){let _=`${Y+this.prefixLength}`;X.if(`${_} >= ${X.data}.length`,()=>X.traversalKind==="Allows"?X.return(!0):X.return()),X.traverseKey(_,`data[${_}]`,Z)}if(this.variadic){if(this.postfix)X.const("firstPostfixIndex",`${X.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(X.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>X.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Y,Z]of this.postfix.entries()){let _=`firstPostfixIndex + ${Y}`;X.traverseKey(_,`data[${_}]`,Z)}}if(X.traversalKind==="Allows")X.return(!0)}_transform(X,Y){Y.path.push(N.intrinsic.nonNegativeIntegerString.internal);let Z=super._transform(X,Y);return Y.path.pop(),Z}expression=this.description;reduceJsonSchema(X,Y){if(this.prevariadic.length)X.prefixItems=this.prevariadic.map((Z)=>{let _=Z.node.toJsonSchemaRecurse(Y);if(Z.kind==="defaultables"){let G=typeof Z.default==="function"?Z.default():Z.default;_.default=N.intrinsic.jsonData.allows(G)?G:Y.fallback.defaultValue({code:"defaultValue",base:_,value:G})}return _});if(this.minLength)X.minItems=this.minLength;if(this.variadic){let Z=Object.assign(X,{items:this.variadic.toJsonSchemaRecurse(Y)});if(this.maxLength)Z.maxItems=this.maxLength;if(this.postfix){let _=this.postfix.map((G)=>G.toJsonSchemaRecurse(Y));X=Y.fallback.arrayPostfix({code:"arrayPostfix",base:Z,elements:_})}}else X.items=!1,delete X.maxItems;return X}}var fQ={},hQ=(X)=>{if(!X.defaultables)return[];let Y=[],Z="[",_=X.prefixLength+X.defaultablesLength-1;for(let G=X.prefixLength;G<=_;G++){let[W,$]=X.defaultables[G-X.prefixLength];Y.push(tX(G,W,$)),Z+=`${G}: ${W.id} = ${A1($)}, `}return Z+="]",fQ[Z]??=Y},WY={implementation:xQ,Node:n_},kQ=(X)=>{let Y=[];if(X.prefix)for(let Z of X.prefix)Y.push({kind:"prefix",node:Z});if(X.defaultables)for(let[Z,_]of X.defaultables)Y.push({kind:"defaultables",node:Z,default:_});if(X.optionals)for(let Z of X.optionals)Y.push({kind:"optionals",node:Z});if(X.variadic)Y.push({kind:"variadic",node:X.variadic});if(X.postfix)for(let Z of X.postfix)Y.push({kind:"postfix",node:Z});return Y},i_=(X)=>X.reduce((Y,Z)=>{if(Z.kind==="variadic")Y.variadic=Z.node;else if(Z.kind==="defaultables")Y.defaultables=t(Y.defaultables,[[Z.node,Z.default]]);else Y[Z.kind]=t(Y[Z.kind],Z.node);return Y},{}),$Y="A postfix required element cannot follow an optional or defaultable element",bQ="A postfix element requires a variadic element",t8=(X)=>{let[Y,...Z]=X.l,[_,...G]=X.r;if(!Y||!_)return X;let W=Z.at(-1)?.kind==="postfix",$=G.at(-1)?.kind==="postfix",H=Y.kind==="prefix"||_.kind==="prefix"?"prefix":Y.kind==="postfix"||_.kind==="postfix"?"postfix":Y.kind==="variadic"&&_.kind==="variadic"?"variadic":W||$?"prefix":Y.kind==="defaultables"||_.kind==="defaultables"?"defaultables":"optionals";if(Y.kind==="prefix"&&_.kind==="variadic"&&$){let F=t8({...X,fixedVariants:[],r:G.map((O)=>({...O,kind:"prefix"}))});if(F.disjoint.length===0)X.fixedVariants.push(F)}else if(_.kind==="prefix"&&Y.kind==="variadic"&&W){let F=t8({...X,fixedVariants:[],l:Z.map((O)=>({...O,kind:"prefix"}))});if(F.disjoint.length===0)X.fixedVariants.push(F)}let Q=O0(Y.node,_.node,X.ctx);if(Q instanceof C)if(H==="prefix"||H==="postfix")X.disjoint.push(...Q.withPrefixKey(H==="prefix"?X.result.length:`-${Z.length+1}`,"required")),X.result=[...X.result,{kind:H,node:N.intrinsic.never.internal}];else if(H==="optionals"||H==="defaultables")return X;else return t8({...X,fixedVariants:[],l:Z.map((F)=>({...F,kind:"prefix"})),r:Z.map((F)=>({...F,kind:"prefix"}))});else if(H==="defaultables"){if(Y.kind==="defaultables"&&_.kind==="defaultables"&&Y.default!==_.default)R(sX(Y.default,_.default));X.result=[...X.result,{kind:H,node:Q,default:Y.kind==="defaultables"?Y.default:_.kind==="defaultables"?_.default:e(`Unexpected defaultable intersection from ${Y.kind} and ${_.kind} elements.`)}]}else X.result=[...X.result,{kind:H,node:Q}];let J=X.l.length,z=X.r.length;if(Y.kind!=="variadic"||J>=z&&(_.kind==="variadic"||z===1))X.l=Z;if(_.kind!=="variadic"||z>=J&&(Y.kind==="variadic"||J===1))X.r=G;return t8(X)};var t_=(X)=>(Y)=>{if(Y.props.length||Y.index){let Z=Y.index?.map((G)=>G[X])??[];for(let G of Y.props)Z.push(G[X]);if(Y.undeclared)Z.push(`+ (undeclared): ${Y.undeclared}`);let _=`{ ${Z.join(", ")} }`;return Y.sequence?`${_} & ${Y.sequence.description}`:_}return Y.sequence?.description??"{}"},yQ=t_("description"),gQ=t_("expression"),r_=(X,Y,Z)=>{let _=X.required?"required":"optional";if(!Y.signature.allows(X.key))return null;let G=H1(X.value,Y.value,Z);if(G instanceof C)return _==="optional"?Z.node("optional",{key:X.key,value:N.intrinsic.never.internal}):G.withPrefixKey(X.key,X.kind);return null},pQ=l({kind:"structure",hasAssociatedError:!1,normalize:(X)=>X,applyConfig:(X,Y)=>{if(!X.undeclared&&Y.onUndeclaredKey!=="ignore")return{...X,undeclared:Y.onUndeclaredKey};return X},keys:{required:{child:!0,parse:i0("required"),reduceIo:(X,Y,Z)=>{Y.required=t(Y.required,Z.map((_)=>_[X]));return}},optional:{child:!0,parse:i0("optional"),reduceIo:(X,Y,Z)=>{if(X==="in"){Y.optional=Z.map((_)=>_.in);return}for(let _ of Z)Y[_.outProp.kind]=t(Y[_.outProp.kind],_.outProp.out)}},index:{child:!0,parse:i0("index")},sequence:{child:!0,parse:i0("sequence")},undeclared:{parse:(X)=>X==="ignore"?void 0:X,reduceIo:(X,Y,Z)=>{if(Z!=="delete")return;if(X==="in")delete Y.undeclared;else Y.undeclared="reject"}}},defaults:{description:yQ},intersections:{structure:(X,Y,Z)=>{let _={...X.inner},G={...Y.inner},W=new C;if(X.undeclared){let Q=X.keyof();for(let J of Y.requiredKeys)if(!Q.allows(J))W.add("presence",N.intrinsic.never.internal,Y.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=H1(Q,J.signature,Z.$);if(z instanceof C)return[];let F=Y6(z,J.value,Z.$);if(F.required)G.required=s1(G.required,F.required);if(F.optional)G.optional=s1(G.optional,F.optional);return F.index??[]})}if(Y.undeclared){let Q=Y.keyof();for(let J of X.requiredKeys)if(!Q.allows(J))W.add("presence",X.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 z=H1(Q,J.signature,Z.$);if(z instanceof C)return[];let F=Y6(z,J.value,Z.$);if(F.required)_.required=s1(_.required,F.required);if(F.optional)_.optional=s1(_.optional,F.optional);return F.index??[]})}let $={};if(X.undeclared||Y.undeclared)$.undeclared=X.undeclared==="reject"||Y.undeclared==="reject"?"reject":"delete";let H=X8({kind:"structure",baseInner:$,l:Y8(_),r:Y8(G),roots:[],ctx:Z});if(H instanceof C)W.push(...H);if(W.length)return W;return H}},reduce:(X,Y)=>{if(X.index){if(!(X.required||X.optional))return;let Z=!1,_=X.required??[],G=X.optional??[],W=[...G];for(let $ of X.index){for(let H of _){let Q=r_(H,$,Y);if(Q instanceof C)return Q}for(let[H,Q]of G.entries()){let J=r_(Q,$,Y);if(J instanceof C)return J;if(J===null)continue;W[H]=J,Z=!0}}if(Z)return Y.node("structure",{...X,optional:W},{prereduced:!0})}}});class a_ extends R1{impliedBasis=N.intrinsic.object.internal;impliedSiblings=this.children.flatMap((X)=>X.impliedSiblings??[]);props=s1(this.required,this.optional);propsByKey=d(this.props,(X,Y)=>[Y.key,Y]);propsByKeyReference=I0(this.propsByKey);expression=gQ(this);requiredKeys=this.required?.map((X)=>X.key)??[];optionalKeys=this.optional?.map((X)=>X.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let X=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Y}of this.index)X=X.concat(Y.branches);return this._keyof=this.$.node("union",X)}map(X){return this.$.node("structure",this.props.flatMap(X).reduce((Y,Z)=>{let _=this.propsByKey[Z.key];if(E0(Z)){if(Z.kind!=="required"&&Z.kind!=="optional")return R(`Map result must have kind "required" or "optional" (was ${Z.kind})`);return Y[Z.kind]=t(Y[Z.kind],Z),Y}let G=Z.kind??_?.kind??"required",W=d(Z,($,H)=>($ in o8.implementation.keys)?[$,H]:[]);return Y[G]=t(Y[G],this.$.node(G,W)),Y},{}))}assertHasKeys(X){let Y=X.filter((Z)=>!n8(Z,this.keyof()));if(Y.length)return R(s_(this.expression,Y))}get(X,...Y){let Z,_=!1,G=cQ(X);if((typeof G==="string"||typeof G==="symbol")&&this.propsByKey[G])Z=this.propsByKey[G].value,_=this.propsByKey[G].required;if(this.index){for(let $ of this.index)if(n8(G,$.signature))Z=Z?.and($.value)??$.value}if(this.sequence&&n8(G,N.intrinsic.nonNegativeIntegerString))if(f(G,"root")){if(this.sequence.variadic)Z=Z?.and(this.sequence.element)??this.sequence.element}else{let $=Number.parseInt(G);if($<this.sequence.prevariadic.length){let H=this.sequence.prevariadic[$].node;Z=Z?.and(H)??H,_||=$<this.sequence.prefixLength}else if(this.sequence.variadic){let H=this.$.node("union",this.sequence.variadicOrPostfix);Z=Z?.and(H)??H}}if(!Z){if(this.sequence?.variadic&&f(G,"root")&&G.extends(N.intrinsic.number))return R(lQ(G.expression,this.sequence.expression));return R(s_(this.expression,[G]))}let W=Z.get(...Y);return _?W:W.or(N.intrinsic.undefined)}pick(...X){return this.assertHasKeys(X),this.$.node("structure",this.filterKeys("pick",X))}omit(...X){return this.assertHasKeys(X),this.$.node("structure",this.filterKeys("omit",X))}optionalize(){let{required:X,...Y}=this.inner;return this.$.node("structure",{...Y,optional:this.props.map((Z)=>Z.hasKind("required")?this.$.node("optional",Z.inner):Z)})}require(){let{optional:X,...Y}=this.inner;return this.$.node("structure",{...Y,required:this.props.map((Z)=>Z.hasKind("optional")?{key:Z.key,value:Z.value}:Z)})}merge(X){let Y=this.filterKeys("omit",[X.keyof()]);if(X.required)Y.required=t(Y.required,X.required);if(X.optional)Y.optional=t(Y.optional,X.optional);if(X.index)Y.index=t(Y.index,X.index);if(X.sequence)Y.sequence=X.sequence;if(X.undeclared)Y.undeclared=X.undeclared;else delete Y.undeclared;return this.$.node("structure",Y)}filterKeys(X,Y){let Z=c2(this.inner),_=(G)=>{let W=Y.some(($)=>n8(G,$));return X==="pick"?W:!W};if(Z.required)Z.required=Z.required.filter((G)=>_(G.key));if(Z.optional)Z.optional=Z.optional.filter((G)=>_(G.key));if(Z.index)Z.index=Z.index.filter((G)=>_(G.signature));return Z}traverseAllows=(X,Y)=>this._traverse("Allows",X,Y);traverseApply=(X,Y)=>this._traverse("Apply",X,Y);_traverse=(X,Y,Z)=>{let _=Z?.currentErrorCount??0;for(let G=0;G<this.props.length;G++)if(X==="Allows"){if(!this.props[G].traverseAllows(Y,Z))return!1}else if(this.props[G].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>_)return!1;if(this.sequence){if(X==="Allows"){if(!this.sequence.traverseAllows(Y,Z))return!1}else if(this.sequence.traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>_)return!1}if(this.index||this.undeclared==="reject"){let G=Object.keys(Y);G.push(...Object.getOwnPropertySymbols(Y));for(let W=0;W<G.length;W++){let $=G[W];if(this.index){for(let H of this.index)if(H.signature.traverseAllows($,Z)){if(X==="Allows"){if(!$1($,()=>H.value.traverseAllows(Y[$],Z),Z))return!1}else if($1($,()=>H.value.traverseApply(Y[$],Z),Z),Z.failFast&&Z.currentErrorCount>_)return!1}}if(this.undeclared==="reject"&&!this.declaresKey($)){if(X==="Allows")return!1;if(Z.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[$],meta:this.meta}),Z.failFast)return!1}}}if(this.structuralMorph&&Z&&!Z.hasError())Z.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((X)=>X.hasDefault())??[])}declaresKey=(X)=>(X in this.propsByKey)||this.index?.some((Y)=>Y.signature.allows(X))||this.sequence!==void 0&&N.intrinsic.nonNegativeIntegerString.allows(X);_compileDeclaresKey(X){let Y=[];if(this.props.length)Y.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let Z of this.index)Y.push(X.invoke(Z.signature,{kind:"Allows",arg:"k"}));if(this.sequence)Y.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return Y.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",uQ(this))}structuralMorphRef=this.structuralMorph&&I0(this.structuralMorph);compile(X){if(X.traversalKind==="Apply")X.initializeErrorCount();for(let Y of this.props)if(X.check(Y),X.traversalKind==="Apply")X.returnIfFailFast();if(this.sequence){if(X.check(this.sequence),X.traversalKind==="Apply")X.returnIfFailFast()}if(this.index||this.undeclared==="reject")X.const("keys","Object.keys(data)"),X.line("keys.push(...Object.getOwnPropertySymbols(data))"),X.for("i < keys.length",()=>this.compileExhaustiveEntry(X));if(X.traversalKind==="Allows")return X.return(!0);if(this.structuralMorphRef)X.if("ctx && !ctx.hasError()",()=>{return X.line("ctx.queueMorphs(["),dQ(X,this),X.line("])")})}compileExhaustiveEntry(X){if(X.const("k","keys[i]"),this.index)for(let Y of this.index)X.if(`${X.invoke(Y.signature,{arg:"k",kind:"Allows"})}`,()=>X.traverseKey("k","data[k]",Y.value));if(this.undeclared==="reject")X.if(`!(${this._compileDeclaresKey(X)})`,()=>{if(X.traversalKind==="Allows")return X.return(!1);return X.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>X.return())});return X}reduceJsonSchema(X,Y){switch(X.type){case"object":return this.reduceObjectJsonSchema(X,Y);case"array":let Z=this.sequence?.reduceJsonSchema(X,Y)??X;if(this.props.length||this.index)return Y.fallback.arrayObject({code:"arrayObject",base:Z,object:this.reduceObjectJsonSchema({type:"object"},Y)});return Z;default:return M0.throwInternalOperandError("structure",X)}}reduceObjectJsonSchema(X,Y){if(this.props.length){X.properties={};for(let Z of this.props){let _=Z.value.toJsonSchemaRecurse(Y);if(typeof Z.key==="symbol"){Y.fallback.symbolKey({code:"symbolKey",base:X,key:Z.key,value:_,optional:Z.optional});continue}if(Z.hasDefault()){let G=typeof Z.default==="function"?Z.default():Z.default;_.default=N.intrinsic.jsonData.allows(G)?G:Y.fallback.defaultValue({code:"defaultValue",base:_,value:G})}X.properties[Z.key]=_}if(this.requiredKeys.length&&X.properties)X.required=this.requiredKeys.filter((Z)=>typeof Z==="string"&&(Z in X.properties))}if(this.index)for(let Z of this.index){let _=Z.value.toJsonSchemaRecurse(Y);if(Z.signature.equals(N.intrinsic.string)){X.additionalProperties=_;continue}for(let G of Z.signature.branches){if(!G.extends(N.intrinsic.string)){X=Y.fallback.symbolKey({code:"symbolKey",base:X,key:null,value:_,optional:!1});continue}let W={type:"string"};if(G.hasKind("morph"))W=Y.fallback.morph({code:"morph",base:G.in.toJsonSchemaRecurse(Y),out:G.out.toJsonSchemaRecurse(Y)});if(!G.hasKind("intersection"))return e(`Unexpected index branch kind ${G.kind}.`);let{pattern:$}=G.inner;if($){let H=Object.assign(W,{pattern:$[0].rule});for(let Q=1;Q<$.length;Q++)W=Y.fallback.patternIntersection({code:"patternIntersection",base:H,pattern:$[Q].rule});X.patternProperties??={},X.patternProperties[H.pattern]=_}}}if(this.undeclared&&!X.additionalProperties)X.additionalProperties=!1;return X}}var HY={},mQ=(X)=>{let Y="";for(let Z=0;Z<X.defaultable.length;Z++)Y+=X.defaultable[Z].defaultValueMorphRef;if(X.sequence?.defaultValueMorphsReference)Y+=X.sequence?.defaultValueMorphsReference;if(X.undeclared==="delete"){if(Y+="delete !(",X.required)for(let Z of X.required)Y+=Z.compiledKey+" | ";if(X.optional)for(let Z of X.optional)Y+=Z.compiledKey+" | ";if(X.index)for(let Z of X.index)Y+=Z.signature.id+" | ";if(X.sequence)if(X.sequence.maxLength===null)Y+=k.nonNegativeIntegerString.id;else for(let Z=0;Z<X.sequence.tuple.length;Z++)Y+=Z+" | ";Y+=")"}return Y},uQ=(X)=>{let Y=mQ(X);if(!Y)return;if(HY[Y])return HY[Y];let Z=(_,G)=>{for(let W=0;W<X.defaultable.length;W++)if(!(X.defaultable[W].key in _))X.defaultable[W].defaultValueMorph(_,G);if(X.sequence?.defaultables)for(let W=_.length-X.sequence.prefixLength;W<X.sequence.defaultables.length;W++)X.sequence.defaultValueMorphs[W](_,G);if(X.undeclared==="delete"){for(let W in _)if(!X.declaresKey(W))delete _[W]}return _};return HY[Y]=Z},dQ=(X,Y)=>{let _=`(data${Y.defaultable.some((G)=>G.defaultValueMorph.length===2)||Y.sequence?.defaultValueMorphs.some((G)=>G.length===2)?", ctx":""})`;return X.block(`${_} => `,(G)=>{for(let W=0;W<Y.defaultable.length;W++){let{serializedKey:$,defaultValueMorphRef:H}=Y.defaultable[W];G.if(`!(${$} in data)`,(Q)=>Q.line(`${H}${_}`))}if(Y.sequence?.defaultables)G.for(`i < ${Y.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${Y.sequence.prefixLength}`);if(Y.undeclared==="delete")G.forIn("data",(W)=>W.if(`!(${Y._compileDeclaresKey(W)})`,($)=>$.line("delete data[k]")));return G.return("data")})},JY={implementation:pQ,Node:a_},cQ=(X)=>{if(f(X,"root")&&X.hasKind("unit"))X=X.unit;if(typeof X==="number")X=`${X}`;return X},lQ=(X,Y)=>`${X} is not allowed as an array index on ${Y}. Use the 'nonNegativeIntegerString' keyword instead.`,Y6=(X,Y,Z)=>{let[_,G]=w5(X.branches,($)=>$.hasKind("unit"));if(!_.length)return{index:Z.node("index",{signature:X,value:Y})};let W={};for(let $ of _){let H=Z.node("required",{key:$.unit,value:Y});W[H.kind]=t(W[H.kind],H)}if(G.length)W.index=Z.node("index",{signature:G,value:Y});return W},oQ=(X)=>f(X,"root")?X.expression:c(X),s_=(X,Y)=>`Key${Y.length===1?"":"s"} ${Y.map(oQ).join(", ")} ${Y.length===1?"does":"do"} not exist on ${X}`;var _8={...N_,alias:r8.implementation,domain:X6.implementation,unit:ZY.implementation,proto:s8.implementation,union:YY.implementation,morph:eX.implementation,intersection:aX.implementation,divisor:yX.implementation,pattern:oX.implementation,predicate:bX.implementation,required:GY.implementation,optional:o8.implementation,index:_Y.implementation,sequence:WY.implementation,structure:JY.implementation};N.defaultConfig=S5(Object.assign(d(_8,(X,Y)=>[X,Y.defaults]),{jitless:k5(),clone:x5,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:M0.defaultConfig}));N.resolvedConfig=g8(N.defaultConfig,N.config);var q_={...I_,alias:r8.Node,domain:X6.Node,unit:ZY.Node,proto:s8.Node,union:YY.Node,morph:eX.Node,intersection:aX.Node,divisor:yX.Node,pattern:oX.Node,predicate:bX.Node,required:GY.Node,optional:o8.Node,index:_Y.Node,sequence:WY.Node,structure:JY.Node};class $8 extends MX{get[t0](){return"module"}}var QY=(X,Y)=>new $8(d(X,(Z,_)=>[Z,f(_,"module")?QY(_,Y):Y.bindReference(_)]));var iQ=(X)=>Q0(X)?X:("branches"in X)&&Q0(X.branches)?X.branches:void 0,nQ=(X,Y)=>R(`Node of kind ${Y} is not valid as a ${X} definition`),e_=(X)=>`#${X} duplicates public alias ${X}`,zY={};N.ambient??={};var X9,Z9="function $",rQ=(X)=>_9(X,G9(X)),_9=(X,Y)=>{let Z=Y.write(Z9,4),_=Y.compile()();for(let G of X){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=Z}},G9=(X)=>new d2().return(X.reduce((Y,Z)=>{let _=new y8({kind:"Allows"}).indent();Z.compile(_);let G=_.write(`${Z.id}Allows`),W=new y8({kind:"Apply"}).indent();Z.compile(W);let $=W.write(`${Z.id}Apply`),H=`${Y}${G},
44
+ ${$},
45
+ `;if(!Z.hasKind("union"))return H;let Q=new y8({kind:"Allows",optimistic:!0}).indent();Z.compile(Q);let J=Q.write(`${Z.id}Optimistic`);return`${H}${J},
46
46
  `},`{
47
- `)+"}");class X6{config;resolvedConfig;name;get[Y1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Y,Z){if(this.config=p2(I.config,Z),this.resolvedConfig=p2(I.resolvedConfig,Z),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(zZ).length}`,this.name in zZ)A(`A Scope already named ${this.name} already exists`);zZ[this.name]=this;let X=Object.entries(Y).map((G)=>this.preparseOwnAliasEntry(...G));for(let[G,_]of X){let $=G;if(G[0]==="#"){if($=G.slice(1),$ in this.aliases)A(aG($));this.aliases[$]=_}else{if($ in this.aliases)A(aG(G));this.aliases[$]=_,this.exportedNames.push($)}if(!y(_,"module")&&!y(_,"generic")&&!E4(_)){let W=this.preparseOwnDefinitionFormat(_,{alias:$});this.resolutions[$]=y(W,"root")?this.bindReference(W):this.createParseContext(W).id}}eG??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[eG.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=I.intrinsic?o(I.intrinsic,(G,_)=>G.startsWith("json")?[]:[G,this.bindReference(_)]):{}}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,G)=>new M4(Y,G?new n8(X):X,Z,Z,G??null)};units=(Y,Z)=>{let X=[];for(let _ of Y)if(!X.includes(_))X.push(_);let G=X.map((_)=>this.node("unit",{unit:_},Z));return this.node("union",G,{...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(c2(Y),Y,Z);preparseNode(Y,Z,X){let G=typeof Y==="string"?Y:c2(Z,Y);if(D0(Z)&&Z.kind===G)return Z;if(G==="alias"&&!X?.prereduced){let{reference:W}=s2.implementation.normalize(Z,this);if(W.startsWith("$")){let H=this.resolveRoot(W.slice(1));Z=H,G=H.kind}}else if(G==="union"&&W1(Z,"object")){let W=sQ(Z);if(W?.length===1)Z=W[0],G=c2(Z)}if(D0(Z)&&Z.kind===G)return Z;let $=_2[G].normalize?.(Z,this)??Z;if(D0($))return $.kind===G?$:tQ(G,$.kind);return{...X,$:this,kind:G,def:$,prefix:X.alias??G}}bindReference(Y){let Z;if(D0(Y))Z=Y.$===this?Y:new Y.constructor(Y.attachments,this);else Z=Y.$===this?Y:new M4(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(EZ(Y))}maybeResolveRoot(Y){let Z=this.maybeResolve(Y);if(y(Z,"generic"))return;return Z}maybeResolveSubalias(Y){return FZ(this.aliases,Y)??FZ(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 G=Z1[Z];if(y(G,"root"))return this.resolutions[Y]=G;if(y(G,"context")){if(G.phase==="resolving")return this.node("alias",{reference:`$${Y}`},{prereduced:!0});if(G.phase==="resolved")return G0(`Unexpected resolved context for was uncached by its scope: ${i(G)}`);G.phase="resolving";let _=this.bindReference(this.parseOwnDefinitionFormat(G.def,G));return G.phase="resolved",Z1[_.id]=_,Z1[G.id]=_,this.resolutions[Y]=_}return G0(`Unexpected nodesById entry for ${Z}: ${i(G)}`)}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(W9(Y));return this.resolutions[Y]=this.bindReference(X.root)}return this.resolutions[Y]=this.parse(X,{alias:Y})}createParseContext(Y){let Z=Y.id??iY(Y.prefix);return Z1[Z]=Object.assign(Y,{[Y1]:"context",$:this,id:Z,phase:"unresolved"})}traversal(Y){return new x1(Y,this.resolvedConfig)}import(...Y){return new H2(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 G=this.aliases[X];this._exports[X]=y(G,"module")?QZ(G,this):Y9(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=$9(this,this._exports),this._json=_9(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=G9(this.references);this.precompilation=X.write(Z9,4),X9(this.references,X)}this.resolved=!0}let Z=Y.length?Y:this.exportedNames;return new H2(o(Z,(X,G)=>[G,this._exports[G]]))}resolve(Y){return this.export()[Y]}node=(Y,Z,X={})=>{let G=this.preparseNode(Y,Z,X);if(D0(G))return this.bindReference(G);let _=this.createParseContext(G),$=nY(_),W=this.bindReference($);return Z1[_.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 G=this.createParseContext(X);Z1[G.id]=G;let _=this.bindReference(this.parseOwnDefinitionFormat(Y,G));if(_.isCyclic)_=TG(_,G.id);return Z1[G.id]=_,_}finalize(Y){if(Y9(Y),!Y.precompilation&&!this.resolvedConfig.jitless)aQ(Y.references);return Y}}class UZ extends X6{parseOwnDefinitionFormat(Y,Z){return nY(Z)}preparseOwnDefinitionFormat(Y,Z){return this.preparseNode(c2(Y),Y,Z)}preparseOwnAliasEntry(Y,Z){return[Y,Z]}normalizeRootScopeValue(Y){return Y}}var Y9=(Y)=>{let Z=Y.references.filter((X)=>X.hasKind("alias"));for(let X of Z){Object.assign(X.referencesById,X.resolution.referencesById);for(let G of Y.references)if(X.id in G.referencesById)Object.assign(G.referencesById,X.referencesById)}return Y},_9=(Y)=>o(Y,(Z,X)=>[Z,y(X,"root")||y(X,"generic")?X.json:y(X,"module")?_9(X):G0(`Unexpected resolution ${i(X)}`)]),FZ=(Y,Z)=>{let X=Z.indexOf(".");if(X===-1)return;let G=Z.slice(0,X),_=Y[G];if(_===void 0)return;if(!y(_,"module"))return A(eQ(G));let $=Z.slice(X+1),W=_[$];if(W===void 0)return FZ(_,$);if(y(W,"root")||y(W,"generic"))return W;if(y(W,"module"))return W.root??A(W9(Z));G0(`Unexpected resolution for alias '${Z}': ${i(W)}`)},G6=(Y,Z)=>new UZ(Y,Z),e2=new UZ({});var $9=(Y,Z)=>{let X={};for(let G in Z){let _=Z[G];if(y(_,"module")){let $=$9(Y,_),W=o($,(H,Q)=>[`${G}.${H}`,Q]);Object.assign(X,W)}else if(y(_,"root")||y(_,"generic"))X[G]=_;else G0(`Unexpected scope resolution ${i(_)}`)}return X},EZ=(Y)=>`'${Y}' is unresolvable`,eQ=(Y)=>`'${Y}' must reference a module to be accessed using dot syntax`,W9=(Y)=>`Reference to submodule '${Y}' must specify an alias`;e2.export();var{schema:H0,node:J2,defineSchema:oR,generic:K1}=e2;var VZ="^(?:0|[1-9]\\d*)$",Yz=new RegExp(VZ),rR=T0(Yz);var H9=G6({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={...H9};var J9=G6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:VZ}},{prereducedAliases:!0}).export();Object.assign(I.intrinsic,J9);var Zz=G6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),u={...H9,...J9,...Zz,emptyStructure:J2("structure",{},{prereduced:!0})};I.intrinsic={...u};var z9=(Y)=>typeof Y==="string"&&Y[0]==="d"&&(Y[1]==="'"||Y[1]==='"')&&Y.at(-1)===Y[1],Q9=(Y)=>Y.toString()!=="Invalid Date",F9=(Y)=>Y.slice(2,-1),OZ=(Y)=>`'${Y}' could not be parsed by the Date constructor`,U9=(Y,Z)=>Xz(Y,Z),Xz=(Y,Z)=>{let X=new Date(Y);if(Q9(X))return X;let G=cX(Y);if(G!==void 0){let _=new Date(G);if(Q9(_))return _}return Z?A(Z===!0?OZ(Y):Z):void 0};var DZ=(Y,Z)=>{let X=Y.scanner.shiftUntil(Gz[V9[Z]]);if(Y.scanner.lookahead==="")return Y.error($z(X,Z));if(Y.scanner.shift(),Z==="/"){try{new RegExp(X)}catch(G){A(String(G))}Y.root=Y.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(g0(Z,LZ))Y.root=Y.ctx.$.node("unit",{unit:X});else{let G=U9(X,OZ(X));Y.root=Y.ctx.$.node("unit",{meta:X,unit:G})}},LZ={"'":1,'"':1},E9={"/":1,"'":1,'"':1},V9={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},Gz={"'":(Y)=>Y.lookahead==="'",'"':(Y)=>Y.lookahead==='"',"/":(Y)=>Y.lookahead==="/"},_z={'"':"double-quote","'":"single-quote","/":"forward slash"},$z=(Y,Z)=>`${Z}${Y} requires a closing ${_z[V9[Z]]}`;var O9=(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",$6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var D9={">":!0,">=":!0},L9={"<":!0,"<=":!0};var Q2={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},M9=(Y)=>`Unmatched )${Y===""?"":` before ${Y}`}`,W6=(Y)=>`Missing ${Y}`,A9=(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})`,R9=(Y,Z,X,G)=>`An expression may have at most one left bound (parsed ${Y}${Q2[Z]}, ${X}${Q2[G]})`;var w9=(Y,Z,X)=>N9(Y,Z,X,[]),N9=(Y,Z,X,G)=>{let _=X.parseUntilFinalizer();if(G.push(_.root),_.finalizer===">"){if(G.length!==Z.params.length)return X.error(MZ(Y,Z.names,G.map(($)=>$.expression)));return G}if(_.finalizer===",")return N9(Y,Z,X,G);return _.error(W6(">"))},MZ=(Y,Z,X)=>`${Y}<${Z.join(", ")}> requires exactly ${Z.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var AZ=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator();if(Z==="keyof")Y.addPrefix("keyof");else Y.root=Hz(Y,Z)},Wz=(Y,Z,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(MZ(Y,Z.names,[]));let _=w9(Y,Z,X);return Z(..._)},Hz=(Y,Z)=>Jz(Y,Z)??Qz(Y,Z)??Y.error(Z===""?Y.scanner.lookahead==="#"?O9(Y.shiftedByOne().scanner.shiftUntilNextTerminator()):RZ(Y):EZ(Z)),Jz=(Y,Z)=>{if(Y.ctx.args?.[Z]){let G=Y.ctx.args[Z];if(typeof G!=="string")return G;return Y.ctx.$.node("alias",{reference:G},{prereduced:!0})}let X=Y.ctx.$.maybeResolve(Z);if(y(X,"root"))return X;if(X===void 0)return;if(y(X,"generic"))return Wz(Z,X,Y);return A(`Unexpected resolution ${i(X)}`)},Qz=(Y,Z)=>{let X=lX(Z);if(X!==void 0)return Y.ctx.$.node("unit",{unit:X});let G=iX(Z);if(G!==void 0)return Y.ctx.$.node("unit",{unit:G})},RZ=(Y)=>{let Z=Y.previousOperator();return Z?wZ(Z,Y.scanner.unscanned):zz(Y.scanner.unscanned)},wZ=(Y,Z="")=>`Token '${Y}' requires a right operand${Z?` before '${Z}'`:""}`,zz=(Y)=>`Expected an expression${Y?` before '${Y}'`:""}`;var NZ=(Y)=>Y.scanner.lookahead===""?Y.error(RZ(Y)):Y.scanner.lookahead==="("?Y.shiftedByOne().reduceGroupOpen():Y.scanner.lookaheadIsIn(E9)?DZ(Y,Y.scanner.shift()):Y.scanner.lookaheadIsIn(V4)?NZ(Y.shiftedByOne()):Y.scanner.lookahead==="d"?Y.scanner.nextLookahead in LZ?DZ(Y,`${Y.scanner.shift()}${Y.scanner.shift()}`):AZ(Y):AZ(Y);class G4 extends CY{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in G4.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...V4};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(Y,Z)=>Y===">"?Z[0]==="="?Z[1]==="=":Z.trimStart()===""||g0(Z.trimStart()[0],G4.terminatingChars):Y==="="?Z[0]!=="=":Y===","||Y==="?"}var K9=(Y,Z)=>{let X=Fz(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 G=`d'${Y.root.description??Y.root.unit.toISOString()}'`;Y.unsetRoot(),Y.reduceLeftBound(G,X);return}}return Ez(Y,X)},B9={"<":1,">":1,"=":1},Fz=(Y,Z)=>Y.scanner.lookaheadIs("=")?`${Z}${Y.scanner.shift()}`:Z;var I9=(Y,Z,X,G)=>{if(X.extends(I.intrinsic.number)){if(typeof Z!=="number")return A(IZ(Y,Z,G));return Y==="=="?["min","max"]:Y[0]===">"?["min"]:["max"]}if(X.extends(I.intrinsic.lengthBoundable)){if(typeof Z!=="number")return A(IZ(Y,Z,G));return Y==="=="?["exactLength"]:Y[0]===">"?["minLength"]:["maxLength"]}if(X.extends(I.intrinsic.Date))return Y==="=="?["after","before"]:Y[0]===">"?["after"]:["before"];return A(EG(X.expression))},Uz=(Y)=>({rule:z9(Y.limit)?F9(Y.limit):Y.limit,exclusive:Y.comparator.length===1}),Ez=(Y,Z)=>{let X=Y.unsetRoot(),G=Y.scanner.location;Y.parseOperand();let _=Y.unsetRoot(),$=Y.scanner.sliceChars(G,Y.scanner.location);if(Y.root=X,!_.hasKind("unit")||typeof _.unit!=="number"&&!(_.unit instanceof Date))return Y.error(IZ(Z,$,"right"));let W=_.unit,H=Z.length===1,Q=I9(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,L9))return Y.error(H6(Z));let J=I9(Y.branches.leftBound.comparator,Y.branches.leftBound.limit,X,"left");Y.constrainRoot(J[0],Uz(Y.branches.leftBound)),Y.branches.leftBound=null},IZ=(Y,Z,X)=>`Comparator ${X==="left"?Q2[Y]:Y} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Z})`;var T9=(Y)=>{Y.scanner.shiftUntilNonWhitespace();let Z=Y.scanner.shiftUntilNextTerminator();Y.root=Y.root.brand(Z)};var q9=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator(),X=oX(Z,{errorOnFail:C9(Z)});if(X===0)Y.error(C9(0));Y.root=Y.root.constrain("divisor",X)},C9=(Y)=>`% operator must be followed by a non-zero integer literal (was ${Y})`;var KZ=(Y)=>{let Z=Y.scanner.shift();return Z===""?Y.finalize(""):Z==="["?Y.scanner.shift()==="]"?Y.setRoot(Y.root.array()):Y.error(Vz):Z==="|"?Y.scanner.lookahead===">"?Y.shiftedByOne().pushRootToBranch("|>"):Y.pushRootToBranch(Z):Z==="&"?Y.pushRootToBranch(Z):Z===")"?Y.finalizeGroup():G4.lookaheadIsFinalizing(Z,Y.scanner.unscanned)?Y.finalize(Z):g0(Z,B9)?K9(Y,Z):Z==="%"?q9(Y):Z==="#"?T9(Y):(Z in V4)?KZ(Y):Y.error(J6(Z))},J6=(Y,Z="")=>`'${Y}' is not allowed here${Z&&` (should be ${Z})`}`,Vz="Missing expected ']'";var j9=(Y)=>{let Z=Y.unsetRoot();Y.parseOperand();let X=Y.unsetRoot();if(!X.hasKind("unit"))return Y.error(Oz(X.expression));let G=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Z,"=",G]},Oz=(Y)=>`Default value '${Y}' must a literal value`;var BZ=(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 G=new z2(new G4(Y),Z),_=Dz(G);if(G.finalizer===">")A(J6(">"));return _},Dz=(Y)=>{Y.parseOperand();let Z=Y8(Y).root;if(!Z)return G0(`Root was unexpectedly unset after parsing string '${Y.scanner.scanned}'`);if(Y.finalizer==="=")Z=j9(Y);else if(Y.finalizer==="?")Z=[Z,"?"];if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.lookahead)A(J6(Y.scanner.lookahead));return Z},Y8=(Y)=>{while(Y.finalizer===void 0)Lz(Y);return Y},Lz=(Y)=>Y.hasRoot()?Y.parseOperator():Y.parseOperand();class z2{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(W6(")"));this.finalizeBranches(),this.finalizer=Y}reduceLeftBound(Y,Z){let X=Q2[Z];if(!g0(X,D9))return this.error(H6(Z));if(this.branches.leftBound)return this.error(R9(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(M9(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():G0(`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 Y8(new z2(this.scanner,this.ctx))}parseOperator(){return KZ(this)}parseOperand(){return NZ(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(A9(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 Mz="An empty string is not a valid generic parameter name",Q6=(Y,Z,X)=>{Y.shiftUntilNonWhitespace();let G=Y.shiftUntilNextTerminator();if(G===""){if(Y.lookahead===""&&Z.length)return Z;return A(Mz)}return Y.shiftUntilNonWhitespace(),Az(Y,G,Z,X)},P9="extends ",Az=(Y,Z,X,G)=>{if(Y.shiftUntilNonWhitespace(),Y.unscanned.startsWith(P9))Y.jumpForward(P9.length);else{if(Y.lookahead===",")Y.shift();return X.push(Z),Q6(Y,X,G)}let _=Y8(new z2(Y,G));return X.push([Z,_.root]),Q6(Y,X,G)};class TZ extends v1{$;constructor(Y){super((...Z)=>new Z8(Y)(...Z),{bind:Y});this.$=Y}in(Y){return new Z8(this.$,Y===void 0?void 0:this.$.parse(Y))}at(Y,Z){return new Z8(this.$).at(Y,Z)}case(Y,Z){return new Z8(this.$).case(Y,Z)}}class Z8 extends v1{$;in;key;branches=[];constructor(Y,Z){super((X)=>this.caseEntries(Object.entries(X).map(([G,_])=>G==="default"?[G,_]:[this.$.parse(G),_])));this.$=Y,this.in=Z}at(Y,Z){if(this.key)A(wz);if(this.branches.length)A(Rz);return this.key=Y,Z?this.match(Z):this}case(Y,Z){return this.caseEntry(this.$.parse(Y),Z)}caseEntry(Y,Z){let G=(this.key?this.$.parse({[this.key]:Y}):Y).pipe(Z);return this.branches.push(G),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,G]=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(G)}if(typeof G!=="function")return A(`Value for case "${X}" must be a function (was ${y0(G)})`);this.caseEntry(X,G)}return this}default(Y){if(typeof Y==="function")this.case(u.unknown,Y);let Z={branches:this.branches,ordered:!0};if(Y==="never"||Y==="assert")Z.meta={onFail:S9};let X=this.$.node("union",Z);if(!this.in)return this.$.finalize(X);let G=this.in.pipe(X);if(Y==="never"||Y==="assert")G=G.configureReferences({onFail:S9},"self");return this.$.finalize(G)}}var S9=(Y)=>Y.throw(),Rz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",wz="At most one key matcher may be specified per expression";var z6=(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 F6(Y,Z)},v9="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",x9="Only required keys may specify default values, e.g. { value: 'number = 0' }";var f9=(Y,Z)=>{let X,G={},_=q4(Y);for(let[W,H]of _){let Q=Kz(W);if(Q.kind==="spread"){if(!l1(G))return A(Iz);let L=Z.$.parseOwnDefinitionFormat(H,Z);if(L.equals(u.object))continue;if(!L.hasKind("intersection")||!L.basis?.equals(u.object))return A(Bz(L.expression));X=L.structure;continue}if(Q.kind==="undeclared"){if(H!=="reject"&&H!=="delete"&&H!=="ignore")A(Nz(H));G.undeclared=H;continue}let J=z6(H,Z),z=Q;if(Q.kind==="required"){if(!F0(J))CZ(G,"required",{key:Q.normalized,value:J},Z);else CZ(G,"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(v9);if(J[1]==="=")A(x9)}if(Q.kind==="optional"){CZ(G,"optional",{key:Q.normalized,value:J},Z);continue}let U=Z.$.parseOwnDefinitionFormat(z.normalized,Z),O=Z6(U,J,Z.$);if(O.index)G.index=Z0(G.index,O.index);if(O.required)G.required=Z0(G.required,O.required)}let $=Z.$.node("structure",G);return Z.$.parseSchema({domain:"object",structure:X?.merge($)??$})},CZ=(Y,Z,X,G)=>{Y[Z]=Z0(Y[Z],G.$.node(Z,X))},Nz=(Y)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${i(Y)})`,Iz="Spread operator may only be used as the first key in an object",Kz=(Y)=>typeof Y==="symbol"?{kind:"required",normalized:Y}:Y.at(-1)==="?"?Y.at(-2)===x2?{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]===x2&&Y[1]==="["&&Y.at(-1)==="]"?{kind:"required",normalized:Y.slice(1)}:Y==="..."?{kind:"spread"}:Y==="+"?{kind:"undeclared"}:{kind:"required",normalized:Y==="\\..."?"...":Y==="\\+"?"+":Y},Bz=(Y)=>`Spread operand must resolve to an object literal type (was ${Y})`;var k9=(Y,Z)=>hz(Y)?p9[Y[0]](Y,Z):xz(Y)?g9[Y[1]](Y,Z):null,Tz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[1],Z).keyof(),qZ=(Y,Z)=>{if(Y[2]===void 0)return A(wZ(Y[1],""));let X=Z.$.parseOwnDefinitionFormat(Y[0],Z),G=Z.$.parseOwnDefinitionFormat(Y[2],Z);if(Y[1]==="|")return Z.$.node("union",{branches:[X,G]});let _=Y[1]==="&"?z1(X,G,Z.$):d2(X,G,Z.$);if(_ instanceof S)return _.throw();return _},Cz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).array(),qz=(Y,Z)=>{if(typeof Y[2]!=="function")return A(b9("=>",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).pipe(Y[2])},b9=(Y,Z)=>`${Y===":"?"Narrow":"Morph"} expression requires a function following '${Y}' (was ${typeof Z})`,jz=(Y,Z)=>{if(typeof Y[2]!=="function")return A(b9(":",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).constrain("predicate",Y[2])},Pz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).configureReferences(Y[2],"shallow"),y9=(Y)=>Y,Sz=y9({"[]":Cz,"?":()=>A(_6)}),vz=y9({"|":qZ,"&":qZ,":":jz,"=>":qz,"|>":qZ,"@":Pz,"=":()=>A($6)}),g9={...Sz,...vz},xz=(Y)=>g9[Y[1]]!==void 0,fz=(Y)=>Y,p9=fz({keyof:Tz,instanceof:(Y,Z)=>{if(typeof Y[1]!=="function")return A(h9(S2(Y[1])));let X=Y.slice(1).map((G)=>typeof G==="function"?Z.$.node("proto",{proto:G}):A(h9(S2(G))));return X.length===1?X[0]:Z.$.node("union",{branches:X})},"===":(Y,Z)=>Z.$.units(Y.slice(1))}),hz=(Y)=>p9[Y[0]]!==void 0,h9=(Y)=>`Expected a constructor following 'instanceof' operator (was ${Y})`;var d9=(Y,Z)=>{let X=[{}],G=0;while(G<Y.length){let _=!1;if(Y[G]==="..."&&G<Y.length-1)_=!0,G++;let $=z6(Y[G],Z),[W,H,Q]=!F0($)?[$]:$;if(G++,_){if(!W.extends(I.intrinsic.Array))return A(yz(W.expression));X=X.flatMap((J)=>W.distribute((z)=>bz(c8(J),z)))}else X=X.map((J)=>{if(H==="?")return c9(J,W);if(H==="=")return kz(J,W,Q);return jZ(J,W)})}return Z.$.parseSchema(X.map((_)=>l1(_)?{proto:Array,exactLength:0}:{proto:Array,sequence:_}))},jZ=(Y,Z)=>{if(Y.defaultables||Y.optionals)return A(Y.variadic?WZ:gz);if(Y.variadic)Y.postfix=Z0(Y.postfix,Z);else Y.prefix=Z0(Y.prefix,Z);return Y},c9=(Y,Z)=>{if(Y.variadic)return A(l9);return Y.optionals=Z0(Y.optionals,Z),Y},kz=(Y,Z,X)=>{if(Y.variadic)return A(l9);if(Y.optionals)return A(pz);return Y.defaultables=Z0(Y.defaultables,[[Z,X]]),Y},m9=(Y,Z)=>{if(Y.postfix)A(u9);if(Y.variadic){if(!Y.variadic.equals(Z))A(u9)}else Y.variadic=Z.internal;return Y},bz=(Y,Z)=>{let X=Z.select({method:"find",kind:"sequence"});if(!X)return m9(Y,I.intrinsic.unknown);if(X.prefix)for(let G of X.prefix)jZ(Y,G);if(X.optionals)for(let G of X.optionals)c9(Y,G);if(X.variadic)m9(Y,X.variadic);if(X.postfix)for(let G of X.postfix)jZ(Y,G);return Y},yz=(Y)=>`Spread element must be an array (was ${Y})`,u9="A tuple may have at most one variadic element",gz="A required element may not follow an optional element",l9="An optional element may not follow a variadic element";var pz="A defaultable element may not follow an optional element without a default";var mz={},F6=(Y,Z)=>{if(typeof Y==="string"){if(Z.args&&Object.keys(Z.args).some((G)=>Y.includes(G)))return BZ(Y,Z);let X=mz[Z.$.name]??={};return X[Y]??=BZ(Y,Z)}return W1(Y,"object")?uz(Y,Z):A(PZ(y0(Y)))},uz=(Y,Z)=>{let X=P2(Y);switch(X){case void 0:if(y(Y,"root"))return Y;return f9(Y,Z);case"Array":return dz(Y,Z);case"RegExp":return Z.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0});case"Function":{let G=E4(Y)?Y():Y;if(y(G,"root"))return G;return A(PZ("Function"))}default:return A(PZ(X??i(Y)))}},dz=(Y,Z)=>k9(Y,Z)??d9(Y,Z),PZ=(Y)=>`Type definitions must be strings or objects (was ${Y})`;class SZ extends v1{constructor(Y){let Z=Object.assign({errors:J1,hkt:r0,$: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 G=X[0].slice(1,-1),_=Y.parseGenericParams(G,{});return new M4(_,X[1],Y,Y,null)}return Y.parse(X)},{bind:Y,attach:Z})}}var F2=I;class U6 extends X6{get ambientAttachments(){if(!F2.typeAttachments)return;return this.cacheGetter("ambientAttachments",o(F2.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 G=Y.slice(0,X),_=Y.slice(X+1,-1);return[G,()=>{let $=this.parseGenericParams(_,{alias:G});return zG($,Z,this)}]}parseGenericParams(Y,Z){return Q6(new G4(Y),[],this.createParseContext({...Z,def:Y,prefix:"generic"}))}normalizeRootScopeValue(Y){if(E4(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 G=F6(Y,Z);if(F0(G)){if(G[1]==="=")return A($6);if(G[1]==="?")return A(_6)}return G}unit=(Y)=>this.units([Y]);valueOf=(Y)=>this.units(PX(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 TZ(this);declare=()=>({type:this.type});define(Y){return Y}type=new SZ(this);static scope=(Y,Z={})=>new U6(Y,Z);static module=(Y,Z={})=>this.scope(Y,Z).export()}var vZ=Object.assign(U6.scope,{define:(Y)=>Y}),e=U6;class o9 extends r0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var cz=K1(["base",u.object],["props",u.object])((Y)=>Y.base.merge(Y.props),o9),i9=e.module({Key:u.key,Merge:cz});class n9 extends r0{}var lz=K1("element")((Y)=>{let Z=Y.element.exclude(u.Array),X=Z.array();return Z.rawOr(X).pipe(U4).distribute((G)=>G.assertHasKind("morph").declareOut(X),H0)},n9),r9=e.module({root:u.Array,readonly:"root",index:u.nonNegativeIntegerString,liftFrom:lz},{name:"Array"});var xZ=H0(["string",P4.FileConstructor]),oz=xZ.rawOr(xZ.array()),s9=H0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:oz}}),t9=e.module({root:["instanceof",FormData],value:xZ,parsed:s9,parse:H0({in:FormData,morphs:(Y)=>{let Z={};for(let[X,G]of Y)if(X in Z){let _=Z[X];if(typeof _==="string"||_ instanceof P4.FileConstructor)Z[X]=[_,G];else _.push(G)}else Z[X]=G;return Z},declaredOut:s9})},{name:"FormData"});var a9=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 iz={Boolean:1,Number:1,String:1},e9=e.module({...o({...AY,...wY},(Y,Z)=>(Y in iz)?[]:[Y,["instanceof",Z]]),Array:r9,TypedArray:a9,FormData:t9});var nz=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"}),rz=H0({domain:"number",divisor:1}),E6=e.module({root:u.number,integer:rz,epoch:nz,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 G={domain:"string",pattern:{rule:Y.source,flags:Y.flags,meta:Z}};if(X)G.meta={format:X};return J2("intersection",G)},Y_=N0(f2,"a well-formed integer string"),U_=e.module({root:Y_,parse:H0({in:Y_,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:u.integer})},{name:"string.integer"}),sz=N0(/^[\dA-Fa-f]+$/,"hex characters only"),tz=e.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"}),Z_=N0(/^[A-Z].*$/,"capitalized"),az=e.module({root:H0({in:"string",morphs:(Y)=>Y.charAt(0).toUpperCase()+Y.slice(1),declaredOut:Z_}),preformatted:Z_},{name:"string.capitalize"}),ez=(Y)=>{let Z=Y.replaceAll(/[ -]+/g,""),X=0,G,_,$=!1;for(let W=Z.length-1;W>=0;W--){if(G=Z.substring(W,W+1),_=Number.parseInt(G,10),$)_*=2,X+=_>=10?_%10+1:_;else X+=_;$=!$}return!!(X%10===0?Z:!1)},YF=/^(?: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}))$/,ZF=H0({domain:"string",pattern:{meta:"a credit card number",rule:YF.source},predicate:{meta:"a credit card number",predicate:ez}});var XF=/^([+-]?\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 GF=(Y)=>!Number.isNaN(new Date(Y).valueOf()),X_=H0({domain:"string",predicate:{meta:"a parsable date",predicate:GF}}).assertHasKind("intersection"),G_=U_.root.internal.narrow((Y,Z)=>{let X=Number.parseInt(Y),G=E6.epoch(X);if(G instanceof J1)return Z.errors.merge(G),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),_F=e.module({root:G_,parse:H0({in:G_,morphs:(Y)=>new Date(Y),declaredOut:u.Date})},{name:"string.date.epoch"}),__=N0(XF,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),$F=e.module({root:__,parse:H0({in:__,morphs:(Y)=>new Date(Y),declaredOut:u.Date})},{name:"string.date.iso"}),WF=e.module({root:X_,parse:H0({declaredIn:X_,in:"string",morphs:(Y,Z)=>{let X=new Date(Y);if(Number.isNaN(X.valueOf()))return Z.error("a parsable date");return X},declaredOut:u.Date}),iso:$F,epoch:_F},{name:"string.date"}),HF=N0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),$_="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A4=`(${$_}[.]){3}${$_}`,JF=new RegExp(`^${A4}$`),x0="(?:[0-9a-fA-F]{1,4})",QF=new RegExp(`^((?:${x0}:){7}(?:${x0}|:)|(?:${x0}:){6}(?:${A4}|:${x0}|:)|(?:${x0}:){5}(?::${A4}|(:${x0}){1,2}|:)|(?:${x0}:){4}(?:(:${x0}){0,1}:${A4}|(:${x0}){1,3}|:)|(?:${x0}:){3}(?:(:${x0}){0,2}:${A4}|(:${x0}){1,4}|:)|(?:${x0}:){2}(?:(:${x0}){0,3}:${A4}|(:${x0}){1,5}|:)|(?:${x0}:){1}(?:(:${x0}){0,4}:${A4}|(:${x0}){1,6}|:)|(?::((?::${x0}){0,5}:${A4}|(?::${x0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),zF=e.module({root:["v4 | v6","@","an IP address"],v4:N0(JF,"an IPv4 address","ipv4"),v6:N0(QF,"an IPv6 address","ipv6")},{name:"string.ip"}),U2="a JSON string",E_=(Y)=>{if(!(Y instanceof SyntaxError))throw Y;return`must be ${U2} (${Y})`},FF=H0({meta:U2,domain:"string",predicate:{meta:U2,predicate:(Y,Z)=>{try{return JSON.parse(Y),!0}catch(X){return Z.reject({code:"predicate",expected:U2,problem:E_(X)})}}}}),UF=(Y,Z)=>{if(Y.length===0)return Z.error({code:"predicate",expected:U2,actual:"empty"});try{return JSON.parse(Y)}catch(X){return Z.error({code:"predicate",expected:U2,problem:E_(X)})}},EF=e.module({root:FF,parse:H0({meta:"safe JSON string parser",in:"string",morphs:UF,declaredOut:u.jsonObject})},{name:"string.json"}),W_=N0(/^[a-z]*$/,"only lowercase letters"),VF=e.module({root:H0({in:"string",morphs:(Y)=>Y.toLowerCase(),declaredOut:W_}),preformatted:W_},{name:"string.lower"}),V_=["NFC","NFD","NFKC","NFKD"],X8=o(V_,(Y,Z)=>[Z,H0({domain:"string",predicate:(X)=>X.normalize(Z)===X,meta:`${Z}-normalized unicode`})]),V6=o(V_,(Y,Z)=>[Z,H0({in:"string",morphs:(X)=>X.normalize(Z),declaredOut:X8[Z]})]),OF=e.module({root:V6.NFC,preformatted:X8.NFC},{name:"string.normalize.NFC"}),DF=e.module({root:V6.NFD,preformatted:X8.NFD},{name:"string.normalize.NFD"}),LF=e.module({root:V6.NFKC,preformatted:X8.NFKC},{name:"string.normalize.NFKC"}),MF=e.module({root:V6.NFKD,preformatted:X8.NFKD},{name:"string.normalize.NFKD"}),AF=e.module({root:"NFC",NFC:OF,NFD:DF,NFKC:LF,NFKD:MF},{name:"string.normalize"}),H_=N0(m8,"a well-formed numeric string"),RF=e.module({root:H_,parse:H0({in:H_,morphs:(Y)=>Number.parseFloat(Y),declaredOut:u.number})},{name:"string.numeric"}),J_="a regex pattern",wF=H0({domain:"string",predicate:{meta:J_,predicate:(Y,Z)=>{try{return new RegExp(Y),!0}catch(X){return Z.reject({code:"predicate",expected:J_,problem:String(X)})}}},meta:{format:"regex"}}),NF=/^(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-]+)*))?$/,IF=N0(NF,"a semantic version (see https://semver.org/)"),Q_=N0(/^\S.*\S$|^\S?$/,"trimmed"),KF=e.module({root:H0({in:"string",morphs:(Y)=>Y.trim(),declaredOut:Q_}),preformatted:Q_},{name:"string.trim"}),z_=N0(/^[A-Z]*$/,"only uppercase letters"),BF=e.module({root:H0({in:"string",morphs:(Y)=>Y.toUpperCase(),declaredOut:z_}),preformatted:z_},{name:"string.upper"}),TF=(Y)=>{if(URL.canParse)return URL.canParse(Y);try{return new URL(Y),!0}catch{return!1}},F_=H0({domain:"string",predicate:{meta:"a URL string",predicate:TF},meta:{format:"uri"}}),CF=e.module({root:F_,parse:H0({declaredIn:F_,in:"string",morphs:(Y,Z)=>{try{return new URL(Y)}catch{return Z.error("a URL string")}},declaredOut:H0(URL)})},{name:"string.url"}),qF=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: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"}),O_=e.module({root:u.string,alpha:N0(/^[A-Za-z]*$/,"only letters"),alphanumeric:N0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:sz,base64:tz,capitalize:az,creditCard:ZF,date:WF,digits:N0(/^\d*$/,"only digits 0-9"),email:HF,integer:U_,ip:zF,json:EF,lower:VF,normalize:AF,numeric:RF,regex:wF,semver:IF,trim:KF,upper:BF,url:CF,uuid:qF},{name:"string"});var D_=e.module({bigint:u.bigint,boolean:u.boolean,false:u.false,never:u.never,null:u.null,number:u.number,object:u.object,string:u.string,symbol:u.symbol,true:u.true,unknown:u.unknown,undefined:u.undefined}),L_=e.module({root:u.unknown,any:u.unknown},{name:"unknown"}),jF=e.module({root:u.jsonObject,stringify:J2("morph",{in:u.jsonObject,morphs:(Y)=>JSON.stringify(Y),declaredOut:u.string})},{name:"object.json"}),M_=e.module({root:u.object,json:jF},{name:"object"});class A_ extends r0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var PF=K1(["K",u.key],"V")((Y)=>({domain:"object",index:{signature:Y.K,value:Y.V}}),A_);class R_ extends r0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var SF=K1(["T",u.object],["K",u.key])((Y)=>Y.T.pick(Y.K),R_);class w_ extends r0{description='omit a set of properties from an object like `Omit(User, "age")`'}var vF=K1(["T",u.object],["K",u.key])((Y)=>Y.T.omit(Y.K),w_);class N_ extends r0{description="make all named properties of an object optional like `Partial(User)`"}var xF=K1(["T",u.object])((Y)=>Y.T.partial(),N_);class I_ extends r0{description="make all named properties of an object required like `Required(User)`"}var fF=K1(["T",u.object])((Y)=>Y.T.required(),I_);class K_ extends r0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var hF=K1("T","U")((Y)=>Y.T.exclude(Y.U),K_);class B_ extends r0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var kF=K1("T","U")((Y)=>Y.T.extract(Y.U),B_),T_=e.module({Exclude:hF,Extract:kF,Omit:vF,Partial:xF,Pick:SF,Record:PF,Required:fF});var R4=vZ({...D_,...T_,...e9,...i9,string:O_,number:E6,object:M_,unknown:L_},{prereducedAliases:!0,name:"ark"}),p0=R4.export();Object.assign(F2.ambient,p0);F2.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(R4.type,F2.typeAttachments),bF=R4.match,yF=R4.generic,LK=R4.schema,gF=R4.define,pF=R4.declare;function E2(Y){return w6(U1.STORE,Y,void 0)}function V2(Y){return O2(U1.STORE,Y)}function hZ(...Y){return h1(U1.STORE,...Y)}function O6(Y,Z){return h_(U1.STORE,Y,Z)}function C_(Y){return k_(Y,U1.STORE)}var _4={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 fZ=(Y)=>(Z,X,G,_,...$)=>{console[Y](`${Z} ${_4[X]} \`${G}\` ${_}`,...$)},mF={error:fZ("error"),info:fZ("info"),warn:fZ("warn")},q_=class{logLevel;filter;logger;constructor(Y,Z,X=mF){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 j_=class{store;deallocateTX;claimTX;constructor(Y=U1.STORE){this.store=Y,this.deallocateTX=S_(Y),this.claimTX=v_(Y),P_(Y,"root")}allocate(Y,Z,X){A6(this.store,Y,Z,X)}deallocate(Y){M6(this.store,this.deallocateTX,kZ())(Y)}claim(Y,Z,X){G8(this.store,Y,Z,X)}};function D6(Y){return bZ(U1.STORE,Y)}function L6(Y){return _8(U1.STORE,Y)}function X1(Y){return JSON.parse(Y)}var Q0=(Y)=>JSON.stringify(Y),uK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var b_=class Y extends Set{mode="record";subject=new _0;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=Array(X),this.subscribe("auto cache",(G)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=G})}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",(G)=>{this.transactionUpdates?.push(G)});try{if(Z(this.child)){for(let G of this.transactionUpdates)this.doStep(G);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(G){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",G),G}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,(G)=>{X(`${this.cacheUpdateNumber}=${G}`)})}emit(Z){this.subject.next(Z)}doStep(Z){let X=Z.indexOf(":"),G=Z.substring(0,X),_=Z.substring(X+1);switch(G){case"add":this.add(JSON.parse(_));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(_));break;case"tx":for(let $ of _.split(";"))this.doStep($)}}getUpdateNumber(Z){let X=Z.indexOf("=");return Number(Z.substring(0,X))}do(Z){let X=Z.indexOf("="),G=Number(Z.substring(0,X)),_=G-this.cacheUpdateNumber;if(_>0||Number.isNaN(_)){if(_===1||Number.isNaN(_)){this.mode="playback";let $=Z.substring(X+1);return this.doStep($),this.mode="record",this.cacheUpdateNumber=G,null}return this.cacheUpdateNumber+1}if(Math.abs(_)<this.cacheLimit){let $=this.cacheIdx+_;if(this.cache[$]===Z)return null;this.mode="playback";let W=!1;while(!W){this.cacheIdx%=this.cacheLimit;let Q=this.cache[this.cacheIdx];if(this.cacheIdx--,!Q)return"OUT_OF_RANGE";this.undo(Q),W=this.cacheIdx===$-1}let H=Z.substring(X+1);return this.doStep(H),this.mode="record",this.cacheUpdateNumber=G,null}return"OUT_OF_RANGE"}undoStep(Z){let X=Z.indexOf(":"),G=Z.substring(0,X),_=Z.substring(X+1);switch(G){case"add":this.delete(JSON.parse(_));break;case"del":this.add(JSON.parse(_));break;case"clear":{let $=JSON.parse(_);for(let W of $)this.add(W);break}case"tx":{let $=_.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 kZ(Y=Math.random){return Y().toString(36).slice(2)}function Y0(Y){while(Y.child!==null)Y=Y.child;return Y}function dF(Y){while(Y.parent!==null)Y=Y.parent;return Y}var cF=/^\[object (?:Async|Generator|AsyncGenerator)?Function\]$/;function H8(Y){let Z=Object.prototype.toString.call(Y);return cF.test(Z)}function mZ(Y,Z){if(H8(Y))return Y(Z);return Y}var uZ=class extends Promise{fate;resolve;reject;done=!1;constructor(Y){let Z,X;super((G,_)=>{Z=G,X=_});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}},_0=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)}},lF=class extends _0{state;constructor(Y){super();this.state=Y}next(Y){this.state=Y,super.next(Y)}},oF=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 y1(Y){let Z={key:Y.key,type:Y.type};if("family"in Y)Z.family=Y.family;return Z}var b1=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)}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}},u_=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}},iF=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 Z=this.source.get(Y),X=new u_(Z);return super.set(Y,X),X}}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)}},$4=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 G=this.relations.get(Z),_=this.relations.get(X);if(G)G.add(X);else G=new Set([X]),this.relations.set(Z,G);if(_)_.add(Z);else _=new Set([Z]),this.relations.set(X,_)}deleteRelation(Z,X){let G=this.relations.get(Z);if(G){if(G.delete(X),G.size===0)this.relations.delete(Z);let _=this.relations.get(X);if(_){if(_.delete(Z),_.size===0)this.relations.delete(X)}}}replaceRelationsUnsafely(Z,X){this.relations.set(Z,new Set(X));for(let G of X){let _=new Set().add(Z);this.relations.set(G,_)}}replaceRelationsSafely(Z,X){let G=this.relations.get(Z),_=this.isAType?.(Z)?Z:void 0,$=_===void 0?Z:void 0;if(G)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(_,$))}}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 G=X?.source;if(G===void 0)this.relations=new Map(Z.relations?.map(([_,$])=>[_,new Set($)])),this.contents=new Map(Z.contents);if(G)this.relations=new iF(G.relations),this.contents=new b1(G.contents)}if(X?.externalStore){let G=X.externalStore;if(this.has=(_,$)=>G.has(_,$),this.addRelation=(_,$)=>{G.addRelation(_,$)},this.deleteRelation=(_,$)=>{G.deleteRelation(_,$)},this.replaceRelationsSafely=(_,$)=>{G.replaceRelationsSafely(_,$)},this.replaceRelationsUnsafely=(_,$)=>{G.replaceRelationsUnsafely(_,$)},this.getRelatedKeys=(_)=>G.getRelatedKeys(_),G.getContent)this.getContentInternal=(_)=>{return G.getContent(_)},this.setContent=(_,$)=>{G.setContent(_,$)},this.deleteContent=(_)=>{G.deleteContent(_)};for(let[_,$]of Z.relations??[]){let W=this.isAType?.(_)?_:void 0,H=W===void 0?_:void 0;for(let Q of $)W??=Q,H??=Q,this.addRelation(W,H)}for(let[_,$]of Z.contents??[])this.setContent(_,$)}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],G=$[this.b],_=void 0;break}case 2:{let $=Z[0];if(typeof $==="string")[X,G]=Z;else X=$[this.a],G=$[this.b],_=Z[1];break}default:X=Z[0],G=Z[1],_=Z[2];break}switch(this.cardinality){case"1:1":{let $=this.getRelatedKey(X);if($&&$!==G)this.delete(X,$)}case"1:n":{let $=this.getRelatedKey(G);if($&&$!==X)this.delete($,G)}break;case"n:n":}if(_){let $=this.makeContentKey(X,G);this.setContent($,_)}return this.addRelation(X,G),this}delete(Z,X){X=typeof X==="string"?X:Z[this.b];let G=typeof Z==="string"?Z:Z[this.a];if(G===void 0&&typeof X==="string"){let _=this.getRelatedKeys(X);if(_)for(let $ of _)this.delete($,X)}else if(typeof G==="string"&&X===void 0){let _=this.getRelatedKeys(G);if(_)for(let $ of _)this.delete(G,$)}else if(typeof G==="string"&&typeof X==="string"){this.deleteRelation(G,X);let _=this.makeContentKey(G,X);this.deleteContent(_)}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((_)=>`"${_}"`).join(", ")}). Only one related key was expected.`);let G;for(let _ of X){G=_;break}return G}}replaceRelations(Z,X,G){let _=!Array.isArray(X),$=_?Object.keys(X):X;if(G?.reckless)this.replaceRelationsUnsafely(Z,$);else this.replaceRelationsSafely(Z,$);if(_)for(let W of $){let H=this.makeContentKey(Z,W),Q=X[W];this.setContent(H,Q)}return this}getContent(Z,X){let G=this.makeContentKey(Z,X);return this.getContentInternal(G)}getRelationEntries(Z){let X=Z[this.a],G=Z[this.b];if(X!==void 0&&G===void 0){let _=this.getRelatedKeys(X);if(_)return[..._].map(($)=>{return[$,this.getContent(X,$)]})}if(X===void 0&&G!==void 0){let _=this.getRelatedKeys(G);if(_)return[..._].map(($)=>{return[$,this.getContent($,G)]})}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:G}=Z;for(let[_,$]of X)if($ instanceof u_){let{source:W}=$;for(let H of $.iterateOwn())W.add(H)}else this.relations.set(_,$);for(let _ of X.deleted)this.relations.delete(_);for(let[_,$]of G)this.contents.set(_,$);for(let _ of G.deleted)this.contents.delete(_)}};function L2(Y){return Y.startsWith("\uD83D\uDD0D ")}var nF=(Y)=>{Y.logger.info("\uD83E\uDE82","transaction",Y.transactionMeta.update.token.key,"Aborting transaction"),Y.parent.child=null};function M6(Y,Z,X){return(...G)=>{return P0(Y,Z).run(G,X)}}function rF(Y,Z,X){let{token:G,update:{newValue:_,oldValue:$}}=Z;k1(Y,G,X==="newValue"?_:$)}function sF(Y){let{stack:Z}=Y;if(Z)return`
48
- `+Z.split(`
47
+ `)+"}");class Z6{config;resolvedConfig;name;get[t0](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(X,Y){if(this.config=g8(N.config,Y),this.resolvedConfig=g8(N.resolvedConfig,Y),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(zY).length}`,this.name in zY)R(`A Scope already named ${this.name} already exists`);zY[this.name]=this;let Z=Object.entries(X).map((_)=>this.preparseOwnAliasEntry(..._));for(let[_,G]of Z){let W=_;if(_[0]==="#"){if(W=_.slice(1),W in this.aliases)R(e_(W));this.aliases[W]=G}else{if(W in this.aliases)R(e_(_));this.aliases[W]=G,this.exportedNames.push(W)}if(!f(G,"module")&&!f(G,"generic")&&!E4(G)){let $=this.preparseOwnDefinitionFormat(G,{alias:W});this.resolutions[W]=f($,"root")?this.bindReference($):this.createParseContext($).id}}X9??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[X9.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=N.intrinsic?d(N.intrinsic,(_,G)=>_.startsWith("json")?[]:[_,this.bindReference(G)]):{}}cacheGetter(X,Y){return Object.defineProperty(this,X,{value:Y}),Y}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(X){return X}generic=(...X)=>{let Y=this;return(Z,_)=>new M4(X,_?new n2(Z):Z,Y,Y,_??null)};units=(X,Y)=>{let Z=[];for(let G of X)if(!Z.includes(G))Z.push(G);let _=Z.map((G)=>this.node("unit",{unit:G},Y));return this.node("union",_,{...Y,prereduced:!0})};lazyResolutions=[];lazilyResolve(X,Y){let Z=this.node("alias",{reference:Y??"synthetic",resolve:X},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(Z);return Z}schema=(X,Y)=>this.finalize(this.parseSchema(X,Y));parseSchema=(X,Y)=>this.node(d8(X),X,Y);preparseNode(X,Y,Z){let _=typeof X==="string"?X:d8(Y,X);if(E0(Y)&&Y.kind===_)return Y;if(_==="alias"&&!Z?.prereduced){let{reference:$}=r8.implementation.normalize(Y,this);if($.startsWith("$")){let H=this.resolveRoot($.slice(1));Y=H,_=H.kind}}else if(_==="union"&&_1(Y,"object")){let $=iQ(Y);if($?.length===1)Y=$[0],_=d8(Y)}if(E0(Y)&&Y.kind===_)return Y;let W=_8[_].normalize?.(Y,this)??Y;if(E0(W))return W.kind===_?W:nQ(_,W.kind);return{...Z,$:this,kind:_,def:W,prefix:Z.alias??_}}bindReference(X){let Y;if(E0(X))Y=X.$===this?X:new X.constructor(X.attachments,this);else Y=X.$===this?X:new M4(X.params,X.bodyDef,X.$,this,X.hkt);if(!this.resolved)Object.assign(this.referencesById,Y.referencesById);return Y}resolveRoot(X){return this.maybeResolveRoot(X)??R(EY(X))}maybeResolveRoot(X){let Y=this.maybeResolve(X);if(f(Y,"generic"))return;return Y}maybeResolveSubalias(X){return FY(this.aliases,X)??FY(this.ambient,X)}get ambient(){return N.ambient}maybeResolve(X){let Y=this.resolutions[X];if(Y){if(typeof Y!=="string")return this.bindReference(Y);let _=a0[Y];if(f(_,"root"))return this.resolutions[X]=_;if(f(_,"context")){if(_.phase==="resolving")return this.node("alias",{reference:`$${X}`},{prereduced:!0});if(_.phase==="resolved")return e(`Unexpected resolved context for was uncached by its scope: ${c(_)}`);_.phase="resolving";let G=this.bindReference(this.parseOwnDefinitionFormat(_.def,_));return _.phase="resolved",a0[G.id]=G,a0[_.id]=G,this.resolutions[X]=G}return e(`Unexpected nodesById entry for ${Y}: ${c(_)}`)}let Z=this.aliases[X]??this.ambient?.[X];if(!Z)return this.maybeResolveSubalias(X);if(Z=this.normalizeRootScopeValue(Z),f(Z,"generic"))return this.resolutions[X]=this.bindReference(Z);if(f(Z,"module")){if(!Z.root)R(H9(X));return this.resolutions[X]=this.bindReference(Z.root)}return this.resolutions[X]=this.parse(Z,{alias:X})}createParseContext(X){let Y=X.id??iX(X.prefix);return a0[Y]=Object.assign(X,{[t0]:"context",$:this,id:Y,phase:"unresolved"})}traversal(X){return new x1(X,this.resolvedConfig)}import(...X){return new $8(d(this.export(...X),(Y,Z)=>[`#${Y}`,Z]))}precompilation;_exportedResolutions;_exports;export(...X){if(!this._exports){this._exports={};for(let Z of this.exportedNames){let _=this.aliases[Z];this._exports[Z]=f(_,"module")?QY(_,this):Y9(this.maybeResolve(Z))}for(let Z of this.lazyResolutions)Z.resolution;if(this._exportedResolutions=$9(this,this._exports),this._json=W9(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let Z=G9(this.references);this.precompilation=Z.write(Z9,4),_9(this.references,Z)}this.resolved=!0}let Y=X.length?X:this.exportedNames;return new $8(d(Y,(Z,_)=>[_,this._exports[_]]))}resolve(X){return this.export()[X]}node=(X,Y,Z={})=>{let _=this.preparseNode(X,Y,Z);if(E0(_))return this.bindReference(_);let G=this.createParseContext(_),W=nX(G),$=this.bindReference(W);return a0[G.id]=$};parse=(X,Y={})=>this.finalize(this.parseDefinition(X,Y));parseDefinition(X,Y={}){if(f(X,"root"))return this.bindReference(X);let Z=this.preparseOwnDefinitionFormat(X,Y);if(f(Z,"root"))return this.bindReference(Z);let _=this.createParseContext(Z);a0[_.id]=_;let G=this.bindReference(this.parseOwnDefinitionFormat(X,_));if(G.isCyclic)G=C_(G,_.id);return a0[_.id]=G,G}finalize(X){if(Y9(X),!X.precompilation&&!this.resolvedConfig.jitless)rQ(X.references);return X}}class UY extends Z6{parseOwnDefinitionFormat(X,Y){return nX(Y)}preparseOwnDefinitionFormat(X,Y){return this.preparseNode(d8(X),X,Y)}preparseOwnAliasEntry(X,Y){return[X,Y]}normalizeRootScopeValue(X){return X}}var Y9=(X)=>{let Y=X.references.filter((Z)=>Z.hasKind("alias"));for(let Z of Y){Object.assign(Z.referencesById,Z.resolution.referencesById);for(let _ of X.references)if(Z.id in _.referencesById)Object.assign(_.referencesById,Z.referencesById)}return X},W9=(X)=>d(X,(Y,Z)=>[Y,f(Z,"root")||f(Z,"generic")?Z.json:f(Z,"module")?W9(Z):e(`Unexpected resolution ${c(Z)}`)]),FY=(X,Y)=>{let Z=Y.indexOf(".");if(Z===-1)return;let _=Y.slice(0,Z),G=X[_];if(G===void 0)return;if(!f(G,"module"))return R(sQ(_));let W=Y.slice(Z+1),$=G[W];if($===void 0)return FY(G,W);if(f($,"root")||f($,"generic"))return $;if(f($,"module"))return $.root??R(H9(Y));e(`Unexpected resolution for alias '${Y}': ${c($)}`)},_6=(X,Y)=>new UY(X,Y),a8=new UY({});var $9=(X,Y)=>{let Z={};for(let _ in Y){let G=Y[_];if(f(G,"module")){let W=$9(X,G),$=d(W,(H,Q)=>[`${_}.${H}`,Q]);Object.assign(Z,$)}else if(f(G,"root")||f(G,"generic"))Z[_]=G;else e(`Unexpected scope resolution ${c(G)}`)}return Z},EY=(X)=>`'${X}' is unresolvable`,sQ=(X)=>`'${X}' must reference a module to be accessed using dot syntax`,H9=(X)=>`Reference to submodule '${X}' must specify an alias`;a8.export();var{schema:G0,node:H8,defineSchema:uR,generic:N1}=a8;var OY="^(?:0|[1-9]\\d*)$",tQ=new RegExp(OY),lR=I0(tQ);var J9=_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={...J9};var Q9=_6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:OY}},{prereducedAliases:!0}).export();Object.assign(N.intrinsic,Q9);var aQ=_6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),k={...J9,...Q9,...aQ,emptyStructure:H8("structure",{},{prereduced:!0})};N.intrinsic={...k};var F9=(X)=>typeof X==="string"&&X[0]==="d"&&(X[1]==="'"||X[1]==='"')&&X.at(-1)===X[1],z9=(X)=>X.toString()!=="Invalid Date",U9=(X)=>X.slice(2,-1),VY=(X)=>`'${X}' could not be parsed by the Date constructor`,E9=(X,Y)=>eQ(X,Y),eQ=(X,Y)=>{let Z=new Date(X);if(z9(Z))return Z;let _=l5(X);if(_!==void 0){let G=new Date(_);if(z9(G))return G}return Y?R(Y===!0?VY(X):Y):void 0};var DY=(X,Y)=>{let Z=X.scanner.shiftUntil(Xz[V9[Y]]);if(X.scanner.lookahead==="")return X.error(Zz(Z,Y));if(X.scanner.shift(),Y==="/"){try{new RegExp(Z)}catch(_){R(String(_))}X.root=X.ctx.$.node("intersection",{domain:"string",pattern:Z},{prereduced:!0})}else if(f0(Y,LY))X.root=X.ctx.$.node("unit",{unit:Z});else{let _=E9(Z,VY(Z));X.root=X.ctx.$.node("unit",{meta:Z,unit:_})}},LY={"'":1,'"':1},O9={"/":1,"'":1,'"':1},V9={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},Xz={"'":(X)=>X.lookahead==="'",'"':(X)=>X.lookahead==='"',"/":(X)=>X.lookahead==="/"},Yz={'"':"double-quote","'":"single-quote","/":"forward slash"},Zz=(X,Y)=>`${Y}${X} requires a closing ${Yz[V9[Y]]}`;var D9=(X)=>`Private type references should not include '#'. Use '${X}' instead.`,G6="Optional definitions like 'string?' are only valid as properties in an object or tuple",W6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var L9={">":!0,">=":!0},M9={"<":!0,"<=":!0};var J8={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},A9=(X)=>`Unmatched )${X===""?"":` before ${X}`}`,$6=(X)=>`Missing ${X}`,R9=(X,Y)=>`Left bounds are only valid when paired with right bounds (try ...${Y}${X})`,H6=(X)=>`Left-bounded expressions must specify their limits using < or <= (was ${X})`,w9=(X,Y,Z,_)=>`An expression may have at most one left bound (parsed ${X}${J8[Y]}, ${Z}${J8[_]})`;var N9=(X,Y,Z)=>I9(X,Y,Z,[]),I9=(X,Y,Z,_)=>{let G=Z.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Y.params.length)return Z.error(MY(X,Y.names,_.map((W)=>W.expression)));return _}if(G.finalizer===",")return I9(X,Y,Z,_);return G.error($6(">"))},MY=(X,Y,Z)=>`${X}<${Y.join(", ")}> requires exactly ${Y.length} args (got ${Z.length}${Z.length===0?"":`: ${Z.join(", ")}`})`;var AY=(X)=>{let Y=X.scanner.shiftUntilNextTerminator();if(Y==="keyof")X.addPrefix("keyof");else X.root=Gz(X,Y)},_z=(X,Y,Z)=>{if(Z.scanner.shiftUntilNonWhitespace(),Z.scanner.shift()!=="<")return Z.error(MY(X,Y.names,[]));let G=N9(X,Y,Z);return Y(...G)},Gz=(X,Y)=>Wz(X,Y)??$z(X,Y)??X.error(Y===""?X.scanner.lookahead==="#"?D9(X.shiftedByOne().scanner.shiftUntilNextTerminator()):RY(X):EY(Y)),Wz=(X,Y)=>{if(X.ctx.args?.[Y]){let _=X.ctx.args[Y];if(typeof _!=="string")return _;return X.ctx.$.node("alias",{reference:_},{prereduced:!0})}let Z=X.ctx.$.maybeResolve(Y);if(f(Z,"root"))return Z;if(Z===void 0)return;if(f(Z,"generic"))return _z(Y,Z,X);return R(`Unexpected resolution ${c(Z)}`)},$z=(X,Y)=>{let Z=o5(Y);if(Z!==void 0)return X.ctx.$.node("unit",{unit:Z});let _=n5(Y);if(_!==void 0)return X.ctx.$.node("unit",{unit:_})},RY=(X)=>{let Y=X.previousOperator();return Y?wY(Y,X.scanner.unscanned):Hz(X.scanner.unscanned)},wY=(X,Y="")=>`Token '${X}' requires a right operand${Y?` before '${Y}'`:""}`,Hz=(X)=>`Expected an expression${X?` before '${X}'`:""}`;var NY=(X)=>X.scanner.lookahead===""?X.error(RY(X)):X.scanner.lookahead==="("?X.shiftedByOne().reduceGroupOpen():X.scanner.lookaheadIsIn(O9)?DY(X,X.scanner.shift()):X.scanner.lookaheadIsIn(O4)?NY(X.shiftedByOne()):X.scanner.lookahead==="d"?X.scanner.nextLookahead in LY?DY(X,`${X.scanner.shift()}${X.scanner.shift()}`):AY(X):AY(X);class Z4 extends CX{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in Z4.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...O4};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(X,Y)=>X===">"?Y[0]==="="?Y[1]==="=":Y.trimStart()===""||f0(Y.trimStart()[0],Z4.terminatingChars):X==="="?Y[0]!=="=":X===","||X==="?"}var B9=(X,Y)=>{let Z=Jz(X,Y);if(X.root.hasKind("unit")){if(typeof X.root.unit==="number"){X.reduceLeftBound(X.root.unit,Z),X.unsetRoot();return}if(X.root.unit instanceof Date){let _=`d'${X.root.description??X.root.unit.toISOString()}'`;X.unsetRoot(),X.reduceLeftBound(_,Z);return}}return zz(X,Z)},T9={"<":1,">":1,"=":1},Jz=(X,Y)=>X.scanner.lookaheadIs("=")?`${Y}${X.scanner.shift()}`:Y;var K9=(X,Y,Z,_)=>{if(Z.extends(N.intrinsic.number)){if(typeof Y!=="number")return R(IY(X,Y,_));return X==="=="?["min","max"]:X[0]===">"?["min"]:["max"]}if(Z.extends(N.intrinsic.lengthBoundable)){if(typeof Y!=="number")return R(IY(X,Y,_));return X==="=="?["exactLength"]:X[0]===">"?["minLength"]:["maxLength"]}if(Z.extends(N.intrinsic.Date))return X==="=="?["after","before"]:X[0]===">"?["after"]:["before"];return R(O_(Z.expression))},Qz=(X)=>({rule:F9(X.limit)?U9(X.limit):X.limit,exclusive:X.comparator.length===1}),zz=(X,Y)=>{let Z=X.unsetRoot(),_=X.scanner.location;X.parseOperand();let G=X.unsetRoot(),W=X.scanner.sliceChars(_,X.scanner.location);if(X.root=Z,!G.hasKind("unit")||typeof G.unit!=="number"&&!(G.unit instanceof Date))return X.error(IY(Y,W,"right"));let $=G.unit,H=Y.length===1,Q=K9(Y,typeof $==="number"?$:W,Z,"right");for(let z of Q)X.constrainRoot(z,Y==="=="?{rule:$}:{rule:$,exclusive:H});if(!X.branches.leftBound)return;if(!f0(Y,M9))return X.error(H6(Y));let J=K9(X.branches.leftBound.comparator,X.branches.leftBound.limit,Z,"left");X.constrainRoot(J[0],Qz(X.branches.leftBound)),X.branches.leftBound=null},IY=(X,Y,Z)=>`Comparator ${Z==="left"?J8[X]:X} must be ${Z==="left"?"preceded":"followed"} by a corresponding literal (was ${Y})`;var C9=(X)=>{X.scanner.shiftUntilNonWhitespace();let Y=X.scanner.shiftUntilNextTerminator();X.root=X.root.brand(Y)};var j9=(X)=>{let Y=X.scanner.shiftUntilNextTerminator(),Z=i5(Y,{errorOnFail:q9(Y)});if(Z===0)X.error(q9(0));X.root=X.root.constrain("divisor",Z)},q9=(X)=>`% operator must be followed by a non-zero integer literal (was ${X})`;var KY=(X)=>{let Y=X.scanner.shift();return Y===""?X.finalize(""):Y==="["?X.scanner.shift()==="]"?X.setRoot(X.root.array()):X.error(Fz):Y==="|"?X.scanner.lookahead===">"?X.shiftedByOne().pushRootToBranch("|>"):X.pushRootToBranch(Y):Y==="&"?X.pushRootToBranch(Y):Y===")"?X.finalizeGroup():Z4.lookaheadIsFinalizing(Y,X.scanner.unscanned)?X.finalize(Y):f0(Y,T9)?B9(X,Y):Y==="%"?j9(X):Y==="#"?C9(X):(Y in O4)?KY(X):X.error(J6(Y))},J6=(X,Y="")=>`'${X}' is not allowed here${Y&&` (should be ${Y})`}`,Fz="Missing expected ']'";var S9=(X)=>{let Y=X.unsetRoot();X.parseOperand();let Z=X.unsetRoot();if(!Z.hasKind("unit"))return X.error(Uz(Z.expression));let _=Z.unit instanceof Date?()=>new Date(Z.unit):Z.unit;return[Y,"=",_]},Uz=(X)=>`Default value '${X}' must a literal value`;var BY=(X,Y)=>{let Z=Y.$.maybeResolveRoot(X);if(Z)return Z;if(X.endsWith("[]")){let W=Y.$.maybeResolveRoot(X.slice(0,-2));if(W)return W.array()}let _=new Q8(new Z4(X),Y),G=Ez(_);if(_.finalizer===">")R(J6(">"));return G},Ez=(X)=>{X.parseOperand();let Y=e8(X).root;if(!Y)return e(`Root was unexpectedly unset after parsing string '${X.scanner.scanned}'`);if(X.finalizer==="=")Y=S9(X);else if(X.finalizer==="?")Y=[Y,"?"];if(X.scanner.shiftUntilNonWhitespace(),X.scanner.lookahead)R(J6(X.scanner.lookahead));return Y},e8=(X)=>{while(X.finalizer===void 0)Oz(X);return X},Oz=(X)=>X.hasRoot()?X.parseOperator():X.parseOperand();class Q8{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(X,Y){this.scanner=X,this.ctx=Y}error(X){return R(X)}hasRoot(){return this.root!==void 0}setRoot(X){this.root=X}unsetRoot(){let X=this.root;return this.root=void 0,X}constrainRoot(...X){this.root=this.root.constrain(X[0],X[1])}finalize(X){if(this.groups.length)return this.error($6(")"));this.finalizeBranches(),this.finalizer=X}reduceLeftBound(X,Y){let Z=J8[Y];if(!f0(Z,L9))return this.error(H6(Y));if(this.branches.leftBound)return this.error(w9(this.branches.leftBound.limit,this.branches.leftBound.comparator,X,Z));this.branches.leftBound={comparator:Z,limit:X}}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 X=this.groups.pop();if(!X)return this.error(A9(this.scanner.unscanned));this.branches=X}addPrefix(X){this.branches.prefixes.push(X)}applyPrefixes(){while(this.branches.prefixes.length){let X=this.branches.prefixes.pop();this.root=X==="keyof"?this.root.keyof():e(`Unexpected prefix '${X}'`)}}pushRootToBranch(X){this.assertRangeUnset(),this.applyPrefixes();let Y=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(Y)??Y,X==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,X==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return e8(new Q8(this.scanner,this.ctx))}parseOperator(){return KY(this)}parseOperand(){return NY(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(R9(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 Vz="An empty string is not a valid generic parameter name",Q6=(X,Y,Z)=>{X.shiftUntilNonWhitespace();let _=X.shiftUntilNextTerminator();if(_===""){if(X.lookahead===""&&Y.length)return Y;return R(Vz)}return X.shiftUntilNonWhitespace(),Dz(X,_,Y,Z)},P9="extends ",Dz=(X,Y,Z,_)=>{if(X.shiftUntilNonWhitespace(),X.unscanned.startsWith(P9))X.jumpForward(P9.length);else{if(X.lookahead===",")X.shift();return Z.push(Y),Q6(X,Z,_)}let G=e8(new Q8(X,_));return Z.push([Y,G.root]),Q6(X,Z,_)};class TY extends v1{$;constructor(X){super((...Y)=>new X2(X)(...Y),{bind:X});this.$=X}in(X){return new X2(this.$,X===void 0?void 0:this.$.parse(X))}at(X,Y){return new X2(this.$).at(X,Y)}case(X,Y){return new X2(this.$).case(X,Y)}}class X2 extends v1{$;in;key;branches=[];constructor(X,Y){super((Z)=>this.caseEntries(Object.entries(Z).map(([_,G])=>_==="default"?[_,G]:[this.$.parse(_),G])));this.$=X,this.in=Y}at(X,Y){if(this.key)R(Mz);if(this.branches.length)R(Lz);return this.key=X,Y?this.match(Y):this}case(X,Y){return this.caseEntry(this.$.parse(X),Y)}caseEntry(X,Y){let _=(this.key?this.$.parse({[this.key]:X}):X).pipe(Y);return this.branches.push(_),this}match(X){return this(X)}strings(X){return this.caseEntries(Object.entries(X).map(([Y,Z])=>Y==="default"?[Y,Z]:[this.$.node("unit",{unit:Y}),Z]))}caseEntries(X){for(let Y=0;Y<X.length;Y++){let[Z,_]=X[Y];if(Z==="default"){if(Y!==X.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 "${Z}" must be a function (was ${x0(_)})`);this.caseEntry(Z,_)}return this}default(X){if(typeof X==="function")this.case(k.unknown,X);let Y={branches:this.branches,ordered:!0};if(X==="never"||X==="assert")Y.meta={onFail:v9};let Z=this.$.node("union",Y);if(!this.in)return this.$.finalize(Z);let _=this.in.pipe(Z);if(X==="never"||X==="assert")_=_.configureReferences({onFail:v9},"self");return this.$.finalize(_)}}var v9=(X)=>X.throw(),Lz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",Mz="At most one key matcher may be specified per expression";var z6=(X,Y)=>{if(Q0(X)){if(X[1]==="=")return[Y.$.parseOwnDefinitionFormat(X[0],Y),"=",X[2]];if(X[1]==="?")return[Y.$.parseOwnDefinitionFormat(X[0],Y),"?"]}return F6(X,Y)},x9="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",f9="Only required keys may specify default values, e.g. { value: 'number = 0' }";var h9=(X,Y)=>{let Z,_={},G=q4(X);for(let[$,H]of G){let Q=wz($);if(Q.kind==="spread"){if(!l1(_))return R(Rz);let D=Y.$.parseOwnDefinitionFormat(H,Y);if(D.equals(k.object))continue;if(!D.hasKind("intersection")||!D.basis?.equals(k.object))return R(Nz(D.expression));Z=D.structure;continue}if(Q.kind==="undeclared"){if(H!=="reject"&&H!=="delete"&&H!=="ignore")R(Az(H));_.undeclared=H;continue}let J=z6(H,Y),z=Q;if(Q.kind==="required"){if(!Q0(J))CY(_,"required",{key:Q.normalized,value:J},Y);else CY(_,"optional",J[1]==="="?{key:Q.normalized,value:J[0],default:J[2]}:{key:Q.normalized,value:J[0]},Y);continue}if(Q0(J)){if(J[1]==="?")R(x9);if(J[1]==="=")R(f9)}if(Q.kind==="optional"){CY(_,"optional",{key:Q.normalized,value:J},Y);continue}let F=Y.$.parseOwnDefinitionFormat(z.normalized,Y),O=Y6(F,J,Y.$);if(O.index)_.index=t(_.index,O.index);if(O.required)_.required=t(_.required,O.required)}let W=Y.$.node("structure",_);return Y.$.parseSchema({domain:"object",structure:Z?.merge(W)??W})},CY=(X,Y,Z,_)=>{X[Y]=t(X[Y],_.$.node(Y,Z))},Az=(X)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${c(X)})`,Rz="Spread operator may only be used as the first key in an object",wz=(X)=>typeof X==="symbol"?{kind:"required",normalized:X}:X.at(-1)==="?"?X.at(-2)===v8?{kind:"required",normalized:`${X.slice(0,-2)}?`}:{kind:"optional",normalized:X.slice(0,-1)}:X[0]==="["&&X.at(-1)==="]"?{kind:"index",normalized:X.slice(1,-1)}:X[0]===v8&&X[1]==="["&&X.at(-1)==="]"?{kind:"required",normalized:X.slice(1)}:X==="..."?{kind:"spread"}:X==="+"?{kind:"undeclared"}:{kind:"required",normalized:X==="\\..."?"...":X==="\\+"?"+":X},Nz=(X)=>`Spread operand must resolve to an object literal type (was ${X})`;var b9=(X,Y)=>vz(X)?m9[X[0]](X,Y):Sz(X)?p9[X[1]](X,Y):null,Iz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[1],Y).keyof(),qY=(X,Y)=>{if(X[2]===void 0)return R(wY(X[1],""));let Z=Y.$.parseOwnDefinitionFormat(X[0],Y),_=Y.$.parseOwnDefinitionFormat(X[2],Y);if(X[1]==="|")return Y.$.node("union",{branches:[Z,_]});let G=X[1]==="&"?H1(Z,_,Y.$):u8(Z,_,Y.$);if(G instanceof C)return G.throw();return G},Kz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[0],Y).array(),Bz=(X,Y)=>{if(typeof X[2]!=="function")return R(y9("=>",X[2]));return Y.$.parseOwnDefinitionFormat(X[0],Y).pipe(X[2])},y9=(X,Y)=>`${X===":"?"Narrow":"Morph"} expression requires a function following '${X}' (was ${typeof Y})`,Tz=(X,Y)=>{if(typeof X[2]!=="function")return R(y9(":",X[2]));return Y.$.parseOwnDefinitionFormat(X[0],Y).constrain("predicate",X[2])},Cz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[0],Y).configureReferences(X[2],"shallow"),g9=(X)=>X,qz=g9({"[]":Kz,"?":()=>R(G6)}),jz=g9({"|":qY,"&":qY,":":Tz,"=>":Bz,"|>":qY,"@":Cz,"=":()=>R(W6)}),p9={...qz,...jz},Sz=(X)=>p9[X[1]]!==void 0,Pz=(X)=>X,m9=Pz({keyof:Iz,instanceof:(X,Y)=>{if(typeof X[1]!=="function")return R(k9(S8(X[1])));let Z=X.slice(1).map((_)=>typeof _==="function"?Y.$.node("proto",{proto:_}):R(k9(S8(_))));return Z.length===1?Z[0]:Y.$.node("union",{branches:Z})},"===":(X,Y)=>Y.$.units(X.slice(1))}),vz=(X)=>m9[X[0]]!==void 0,k9=(X)=>`Expected a constructor following 'instanceof' operator (was ${X})`;var c9=(X,Y)=>{let Z=[{}],_=0;while(_<X.length){let G=!1;if(X[_]==="..."&&_<X.length-1)G=!0,_++;let W=z6(X[_],Y),[$,H,Q]=!Q0(W)?[W]:W;if(_++,G){if(!$.extends(N.intrinsic.Array))return R(hz($.expression));Z=Z.flatMap((J)=>$.distribute((z)=>fz(c2(J),z)))}else Z=Z.map((J)=>{if(H==="?")return l9(J,$);if(H==="=")return xz(J,$,Q);return jY(J,$)})}return Y.$.parseSchema(Z.map((G)=>l1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},jY=(X,Y)=>{if(X.defaultables||X.optionals)return R(X.variadic?$Y:kz);if(X.variadic)X.postfix=t(X.postfix,Y);else X.prefix=t(X.prefix,Y);return X},l9=(X,Y)=>{if(X.variadic)return R(o9);return X.optionals=t(X.optionals,Y),X},xz=(X,Y,Z)=>{if(X.variadic)return R(o9);if(X.optionals)return R(bz);return X.defaultables=t(X.defaultables,[[Y,Z]]),X},u9=(X,Y)=>{if(X.postfix)R(d9);if(X.variadic){if(!X.variadic.equals(Y))R(d9)}else X.variadic=Y.internal;return X},fz=(X,Y)=>{let Z=Y.select({method:"find",kind:"sequence"});if(!Z)return u9(X,N.intrinsic.unknown);if(Z.prefix)for(let _ of Z.prefix)jY(X,_);if(Z.optionals)for(let _ of Z.optionals)l9(X,_);if(Z.variadic)u9(X,Z.variadic);if(Z.postfix)for(let _ of Z.postfix)jY(X,_);return X},hz=(X)=>`Spread element must be an array (was ${X})`,d9="A tuple may have at most one variadic element",kz="A required element may not follow an optional element",o9="An optional element may not follow a variadic element";var bz="A defaultable element may not follow an optional element without a default";var yz={},F6=(X,Y)=>{if(typeof X==="string"){if(Y.args&&Object.keys(Y.args).some((_)=>X.includes(_)))return BY(X,Y);let Z=yz[Y.$.name]??={};return Z[X]??=BY(X,Y)}return _1(X,"object")?gz(X,Y):R(SY(x0(X)))},gz=(X,Y)=>{let Z=j8(X);switch(Z){case void 0:if(f(X,"root"))return X;return h9(X,Y);case"Array":return pz(X,Y);case"RegExp":return Y.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0});case"Function":{let _=E4(X)?X():X;if(f(_,"root"))return _;return R(SY("Function"))}default:return R(SY(Z??c(X)))}},pz=(X,Y)=>b9(X,Y)??c9(X,Y),SY=(X)=>`Type definitions must be strings or objects (was ${X})`;class PY extends v1{constructor(X){let Y=Object.assign({errors:W1,hkt:o0,$:X,raw:X.parse,module:X.constructor.module,scope:X.constructor.scope,define:X.define,match:X.match,generic:X.generic,schema:X.schema,keywords:X.ambient,unit:X.unit,enumerated:X.enumerated,instanceOf:X.instanceOf,valueOf:X.valueOf,or:X.or,and:X.and,merge:X.merge,pipe:X.pipe},X.ambientAttachments);super((...Z)=>{if(Z.length===1)return X.parse(Z[0]);if(Z.length===2&&typeof Z[0]==="string"&&Z[0][0]==="<"&&Z[0].at(-1)===">"){let _=Z[0].slice(1,-1),G=X.parseGenericParams(_,{});return new M4(G,Z[1],X,X,null)}return X.parse(Z)},{bind:X,attach:Y})}}var z8=N;class U6 extends Z6{get ambientAttachments(){if(!z8.typeAttachments)return;return this.cacheGetter("ambientAttachments",d(z8.typeAttachments,(X,Y)=>[X,this.bindReference(Y)]))}preparseOwnAliasEntry(X,Y){let Z=X.indexOf("<");if(Z===-1){if(f(Y,"module")||f(Y,"generic"))return[X,Y];let W=this.name==="ark"?X:X==="root"?this.name:`${this.name}.${X}`,$=this.resolvedConfig.keywords?.[W];if($)Y=[Y,"@",$];return[X,Y]}if(X.at(-1)!==">")R("'>' must be the last character of a generic declaration in a scope");let _=X.slice(0,Z),G=X.slice(Z+1,-1);return[_,()=>{let W=this.parseGenericParams(G,{alias:_});return F_(W,Y,this)}]}parseGenericParams(X,Y){return Q6(new Z4(X),[],this.createParseContext({...Y,def:X,prefix:"generic"}))}normalizeRootScopeValue(X){if(E4(X)&&!f(X,"generic"))return X();return X}preparseOwnDefinitionFormat(X,Y){return{...Y,def:X,prefix:Y.alias??"type"}}parseOwnDefinitionFormat(X,Y){if(!(Y.alias&&(Y.alias in this.aliases))&&!Y.args)Y.args={this:Y.id};let _=F6(X,Y);if(Q0(_)){if(_[1]==="=")return R(W6);if(_[1]==="?")return R(G6)}return _}unit=(X)=>this.units([X]);valueOf=(X)=>this.units(P5(X));enumerated=(...X)=>this.units(X);instanceOf=(X)=>this.node("proto",{proto:X},{prereduced:!0});or=(...X)=>this.schema(X.map((Y)=>this.parse(Y)));and=(...X)=>X.reduce((Y,Z)=>Y.and(this.parse(Z)),this.intrinsic.unknown);merge=(...X)=>X.reduce((Y,Z)=>Y.merge(this.parse(Z)),this.intrinsic.object);pipe=(...X)=>this.intrinsic.unknown.pipe(...X);match=new TY(this);declare=()=>({type:this.type});define(X){return X}type=new PY(this);static scope=(X,Y={})=>new U6(X,Y);static module=(X,Y={})=>this.scope(X,Y).export()}var vY=Object.assign(U6.scope,{define:(X)=>X}),r=U6;class i9 extends o0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var mz=N1(["base",k.object],["props",k.object])((X)=>X.base.merge(X.props),i9),n9=r.module({Key:k.key,Merge:mz});class r9 extends o0{}var uz=N1("element")((X)=>{let Y=X.element.exclude(k.Array),Z=Y.array();return Y.rawOr(Z).pipe(U4).distribute((_)=>_.assertHasKind("morph").declareOut(Z),G0)},r9),s9=r.module({root:k.Array,readonly:"root",index:k.nonNegativeIntegerString,liftFrom:uz},{name:"Array"});var xY=G0(["string",S4.FileConstructor]),dz=xY.rawOr(xY.array()),t9=G0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:dz}}),a9=r.module({root:["instanceof",FormData],value:xY,parsed:t9,parse:G0({in:FormData,morphs:(X)=>{let Y={};for(let[Z,_]of X)if(Z in Y){let G=Y[Z];if(typeof G==="string"||G instanceof S4.FileConstructor)Y[Z]=[G,_];else G.push(_)}else Y[Z]=_;return Y},declaredOut:t9})},{name:"FormData"});var e9=r.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 cz={Boolean:1,Number:1,String:1},XG=r.module({...d({...AX,...wX},(X,Y)=>(X in cz)?[]:[X,["instanceof",Y]]),Array:s9,TypedArray:e9,FormData:a9});var lz=G0({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"}),oz=G0({domain:"number",divisor:1}),E6=r.module({root:k.number,integer:oz,epoch:lz,safe:G0({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 A0=(X,Y,Z)=>{let _={domain:"string",pattern:{rule:X.source,flags:X.flags,meta:Y}};if(Z)_.meta={format:Z};return H8("intersection",_)},YG=A0(x8,"a well-formed integer string"),EG=r.module({root:YG,parse:G0({in:YG,morphs:(X,Y)=>{let Z=Number.parseInt(X);return Number.isSafeInteger(Z)?Z:Y.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:k.integer})},{name:"string.integer"}),iz=A0(/^[\dA-Fa-f]+$/,"hex characters only"),nz=r.module({root:A0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:A0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),ZG=A0(/^[A-Z].*$/,"capitalized"),rz=r.module({root:G0({in:"string",morphs:(X)=>X.charAt(0).toUpperCase()+X.slice(1),declaredOut:ZG}),preformatted:ZG},{name:"string.capitalize"}),sz=(X)=>{let Y=X.replaceAll(/[ -]+/g,""),Z=0,_,G,W=!1;for(let $=Y.length-1;$>=0;$--){if(_=Y.substring($,$+1),G=Number.parseInt(_,10),W)G*=2,Z+=G>=10?G%10+1:G;else Z+=G;W=!W}return!!(Z%10===0?Y:!1)},tz=/^(?: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}))$/,az=G0({domain:"string",pattern:{meta:"a credit card number",rule:tz.source},predicate:{meta:"a credit card number",predicate:sz}});var ez=/^([+-]?\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 XF=(X)=>!Number.isNaN(new Date(X).valueOf()),_G=G0({domain:"string",predicate:{meta:"a parsable date",predicate:XF}}).assertHasKind("intersection"),GG=EG.root.internal.narrow((X,Y)=>{let Z=Number.parseInt(X),_=E6.epoch(Z);if(_ instanceof W1)return Y.errors.merge(_),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),YF=r.module({root:GG,parse:G0({in:GG,morphs:(X)=>new Date(X),declaredOut:k.Date})},{name:"string.date.epoch"}),WG=A0(ez,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),ZF=r.module({root:WG,parse:G0({in:WG,morphs:(X)=>new Date(X),declaredOut:k.Date})},{name:"string.date.iso"}),_F=r.module({root:_G,parse:G0({declaredIn:_G,in:"string",morphs:(X,Y)=>{let Z=new Date(X);if(Number.isNaN(Z.valueOf()))return Y.error("a parsable date");return Z},declaredOut:k.Date}),iso:ZF,epoch:YF},{name:"string.date"}),GF=A0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),$G="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A4=`(${$G}[.]){3}${$G}`,WF=new RegExp(`^${A4}$`),j0="(?:[0-9a-fA-F]{1,4})",$F=new RegExp(`^((?:${j0}:){7}(?:${j0}|:)|(?:${j0}:){6}(?:${A4}|:${j0}|:)|(?:${j0}:){5}(?::${A4}|(:${j0}){1,2}|:)|(?:${j0}:){4}(?:(:${j0}){0,1}:${A4}|(:${j0}){1,3}|:)|(?:${j0}:){3}(?:(:${j0}){0,2}:${A4}|(:${j0}){1,4}|:)|(?:${j0}:){2}(?:(:${j0}){0,3}:${A4}|(:${j0}){1,5}|:)|(?:${j0}:){1}(?:(:${j0}){0,4}:${A4}|(:${j0}){1,6}|:)|(?::((?::${j0}){0,5}:${A4}|(?::${j0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),HF=r.module({root:["v4 | v6","@","an IP address"],v4:A0(WF,"an IPv4 address","ipv4"),v6:A0($F,"an IPv6 address","ipv6")},{name:"string.ip"}),F8="a JSON string",OG=(X)=>{if(!(X instanceof SyntaxError))throw X;return`must be ${F8} (${X})`},JF=G0({meta:F8,domain:"string",predicate:{meta:F8,predicate:(X,Y)=>{try{return JSON.parse(X),!0}catch(Z){return Y.reject({code:"predicate",expected:F8,problem:OG(Z)})}}}}),QF=(X,Y)=>{if(X.length===0)return Y.error({code:"predicate",expected:F8,actual:"empty"});try{return JSON.parse(X)}catch(Z){return Y.error({code:"predicate",expected:F8,problem:OG(Z)})}},zF=r.module({root:JF,parse:G0({meta:"safe JSON string parser",in:"string",morphs:QF,declaredOut:k.jsonObject})},{name:"string.json"}),HG=A0(/^[a-z]*$/,"only lowercase letters"),FF=r.module({root:G0({in:"string",morphs:(X)=>X.toLowerCase(),declaredOut:HG}),preformatted:HG},{name:"string.lower"}),VG=["NFC","NFD","NFKC","NFKD"],Y2=d(VG,(X,Y)=>[Y,G0({domain:"string",predicate:(Z)=>Z.normalize(Y)===Z,meta:`${Y}-normalized unicode`})]),O6=d(VG,(X,Y)=>[Y,G0({in:"string",morphs:(Z)=>Z.normalize(Y),declaredOut:Y2[Y]})]),UF=r.module({root:O6.NFC,preformatted:Y2.NFC},{name:"string.normalize.NFC"}),EF=r.module({root:O6.NFD,preformatted:Y2.NFD},{name:"string.normalize.NFD"}),OF=r.module({root:O6.NFKC,preformatted:Y2.NFKC},{name:"string.normalize.NFKC"}),VF=r.module({root:O6.NFKD,preformatted:Y2.NFKD},{name:"string.normalize.NFKD"}),DF=r.module({root:"NFC",NFC:UF,NFD:EF,NFKC:OF,NFKD:VF},{name:"string.normalize"}),JG=A0(m2,"a well-formed numeric string"),LF=r.module({root:JG,parse:G0({in:JG,morphs:(X)=>Number.parseFloat(X),declaredOut:k.number})},{name:"string.numeric"}),QG="a regex pattern",MF=G0({domain:"string",predicate:{meta:QG,predicate:(X,Y)=>{try{return new RegExp(X),!0}catch(Z){return Y.reject({code:"predicate",expected:QG,problem:String(Z)})}}},meta:{format:"regex"}}),AF=/^(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-]+)*))?$/,RF=A0(AF,"a semantic version (see https://semver.org/)"),zG=A0(/^\S.*\S$|^\S?$/,"trimmed"),wF=r.module({root:G0({in:"string",morphs:(X)=>X.trim(),declaredOut:zG}),preformatted:zG},{name:"string.trim"}),FG=A0(/^[A-Z]*$/,"only uppercase letters"),NF=r.module({root:G0({in:"string",morphs:(X)=>X.toUpperCase(),declaredOut:FG}),preformatted:FG},{name:"string.upper"}),IF=(X)=>{if(URL.canParse)return URL.canParse(X);try{return new URL(X),!0}catch{return!1}},UG=G0({domain:"string",predicate:{meta:"a URL string",predicate:IF},meta:{format:"uri"}}),KF=r.module({root:UG,parse:G0({declaredIn:UG,in:"string",morphs:(X,Y)=>{try{return new URL(X)}catch{return Y.error("a URL string")}},declaredOut:G0(URL)})},{name:"string.url"}),BF=r.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:A0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:A0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:A0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:A0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:A0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:A0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:A0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:A0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),DG=r.module({root:k.string,alpha:A0(/^[A-Za-z]*$/,"only letters"),alphanumeric:A0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:iz,base64:nz,capitalize:rz,creditCard:az,date:_F,digits:A0(/^\d*$/,"only digits 0-9"),email:GF,integer:EG,ip:HF,json:zF,lower:FF,normalize:DF,numeric:LF,regex:MF,semver:RF,trim:wF,upper:NF,url:KF,uuid:BF},{name:"string"});var LG=r.module({bigint:k.bigint,boolean:k.boolean,false:k.false,never:k.never,null:k.null,number:k.number,object:k.object,string:k.string,symbol:k.symbol,true:k.true,unknown:k.unknown,undefined:k.undefined}),MG=r.module({root:k.unknown,any:k.unknown},{name:"unknown"}),TF=r.module({root:k.jsonObject,stringify:H8("morph",{in:k.jsonObject,morphs:(X)=>JSON.stringify(X),declaredOut:k.string})},{name:"object.json"}),AG=r.module({root:k.object,json:TF},{name:"object"});class RG extends o0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var CF=N1(["K",k.key],"V")((X)=>({domain:"object",index:{signature:X.K,value:X.V}}),RG);class wG extends o0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var qF=N1(["T",k.object],["K",k.key])((X)=>X.T.pick(X.K),wG);class NG extends o0{description='omit a set of properties from an object like `Omit(User, "age")`'}var jF=N1(["T",k.object],["K",k.key])((X)=>X.T.omit(X.K),NG);class IG extends o0{description="make all named properties of an object optional like `Partial(User)`"}var SF=N1(["T",k.object])((X)=>X.T.partial(),IG);class KG extends o0{description="make all named properties of an object required like `Required(User)`"}var PF=N1(["T",k.object])((X)=>X.T.required(),KG);class BG extends o0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var vF=N1("T","U")((X)=>X.T.exclude(X.U),BG);class TG extends o0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var xF=N1("T","U")((X)=>X.T.extract(X.U),TG),CG=r.module({Exclude:vF,Extract:xF,Omit:jF,Partial:SF,Pick:qF,Record:CF,Required:PF});var R4=vY({...LG,...CG,...XG,...n9,string:DG,number:E6,object:AG,unknown:MG},{prereducedAliases:!0,name:"ark"}),h0=R4.export();Object.assign(z8.ambient,h0);z8.typeAttachments={string:h0.string.root,number:h0.number.root,bigint:h0.bigint,boolean:h0.boolean,symbol:h0.symbol,undefined:h0.undefined,null:h0.null,object:h0.object.root,unknown:h0.unknown.root,false:h0.false,true:h0.true,never:h0.never,arrayIndex:h0.Array.index,Key:h0.Key,Record:h0.Record,Array:h0.Array.root,Date:h0.Date};var J1=Object.assign(R4.type,z8.typeAttachments),fF=R4.match,hF=R4.generic,EK=R4.schema,kF=R4.define,bF=R4.declare;function U8(X){return w6(Q1.STORE,X,void 0)}function E8(X){return G2(Q1.STORE,X)}function hY(...X){return h1(Q1.STORE,...X)}function V6(X){return kG(Q1.STORE,X)}function qG(X){return bG(X,Q1.STORE)}var _4={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 fY=(X)=>(Y,Z,_,G,...W)=>{console[X](`${Y} ${_4[Z]} \`${_}\` ${G}`,...W)},yF={error:fY("error"),info:fY("info"),warn:fY("warn")},jG=class{logLevel;filter;logger;constructor(X,Y,Z=yF){this.logLevel=X,this.filter=Y,this.logger=Z}error=(...X)=>{if(this.logLevel!==null){let Y=this.filter?.(...X)??!0;if(Y===!0)this.logger.error(...X);else if(Y)this.logger.error(...Y)}};info=(...X)=>{if(this.logLevel==="info"){let Y=this.filter?.(...X)??!0;if(Y===!0)this.logger.info(...X);else if(Y)this.logger.info(...Y)}};warn=(...X)=>{if(this.logLevel!=="error"&&this.logLevel!==null){let Y=this.filter?.(...X)??!0;if(Y===!0)this.logger.warn(...X);else if(Y)this.logger.warn(...Y)}}};var SG=class{store;deallocateTX;claimTX;constructor(X=Q1.STORE){this.store=X,this.deallocateTX=vG(X),this.claimTX=xG(X),PG(X,"root")}allocate(X,Y,Z){A6(this.store,X,Y,Z)}deallocate(X){M6(this.store,this.deallocateTX,kY())(X)}claim(X,Y,Z){Z2(this.store,X,Y,Z)}};function D6(X){return bY(Q1.STORE,X)}function L6(X){return _2(Q1.STORE,X)}function X1(X){return JSON.parse(X)}var w0=(X)=>JSON.stringify(X),yK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function yG(X){let Y={},Z=0;for(let _ of X)Y[_]=Z,Y[Z]=_,++Z;return Y}var gG="\x01",pG="\x02",mG="\x03",uG="\x04",gY=(X)=>{switch(typeof X){case"string":return mG+X;case"number":return uG+X;case"boolean":return gG+ +X;case"object":return pG}},pY=(X)=>{switch(X[0]){case mG:return X.slice(1);case uG:return+X.slice(1);case gG:return X.slice(1)==="1";case pG:return null}};var dG=yG(["add","delete","clear"]),G4=class X extends Set{mode="record";subject=new Z0;constructor(Y){super(Y);if(Y instanceof X);}READONLY_VIEW=this;toJSON(){return[...this]}static fromJSON(Y){return new X(Y)}add(Y){let Z=super.add(Y);if(this.mode==="record")this.emit({type:"add",value:Y});return Z}clear(){let Y=this.mode==="record"?[...this]:null;if(super.clear(),Y)this.emit({type:"clear",values:Y})}delete(Y){let Z=super.delete(Y);if(this.mode==="record")this.emit({type:"delete",value:Y});return Z}subscribe(Y,Z){return this.subject.subscribe(Y,Z)}emit(Y){this.subject.next(X.packUpdate(Y))}do(Y){this.mode="playback";let Z=X.unpackUpdate(Y);switch(Z.type){case"add":this.add(Z.value);break;case"delete":this.delete(Z.value);break;case"clear":this.clear()}return this.mode="record",null}undo(Y){let Z=X.unpackUpdate(Y);switch(this.mode="playback",Z.type){case"add":this.delete(Z.value);break;case"delete":this.add(Z.value);break;case"clear":{let _=Z.values;for(let G of _)this.add(G)}}return this.mode="record",null}static packUpdate(Y){let Z=dG[Y.type]+"\x1F";if(Y.type==="clear")return Z+Y.values.map(gY).join("\x1E");return Z+gY(Y.value)}static unpackUpdate(Y){let[Z,_]=Y.split("\x1F"),G=dG[Z];if(G==="clear")return{type:"clear",values:_.split("\x1E").map(pY)};return{type:G,value:pY(_)}}};function kY(X=Math.random){return X().toString(36).slice(2)}function s(X){while(X.child!==null)X=X.child;return X}function pF(X){while(X.parent!==null)X=X.parent;return X}var mF=/^\[object (?:Async|Generator|AsyncGenerator)?Function\]$/;function H2(X){let Y=Object.prototype.toString.call(X);return mF.test(Y)}function dY(X,Y){if(H2(X))return X(Y);return X}var cY=class extends Promise{fate;resolve;reject;done=!1;constructor(X){let Y,Z;super((_,G)=>{Y=_,Z=G});this.resolve=Y,this.reject=Z,this.use(X instanceof Promise?X:new Promise(X))}pass(X,Y){if(X===this.fate)this.resolve(Y),this.done=!0}fail(X,Y){if(X===this.fate)this.reject(Y),this.done=!0}use(X){if(this===X)return;if(X instanceof Promise){let Y=X;this.fate=Y,Y.then((Z)=>{this.pass(Y,Z)},(Z)=>{this.fail(Y,Z)})}else this.resolve(X),this.fate=void 0}},Z0=class{Subscriber;subscribers=new Map;subscribe(X,Y){return this.subscribers.set(X,Y),()=>{this.unsubscribe(X)}}unsubscribe(X){this.subscribers.delete(X)}next(X){let Y=this.subscribers.values();for(let Z of Y)Z(X)}},uF=class extends Z0{state;constructor(X){super();this.state=X}next(X){this.state=X,super.next(X)}},dF=class X{_buffer;_index=0;constructor(Y){let Z;if(typeof Y==="number")Z=Y;else Z=Y.length;this._buffer=Array.from({length:Z})}get buffer(){return this._buffer}get index(){return this._index}add(Y){this._buffer[this._index]=Y,this._index=(this._index+1)%this._buffer.length}copy(){let Y=new X([...this._buffer]);return Y._index=this._index,Y}};function y1(X){let Y={key:X.key,type:X.type};if("family"in X)Y.family=X.family;return Y}var b1=class extends Map{deleted=new Set;changed=new Set;source;constructor(X){super();this.source=X}get(X){if(super.has(X))return super.get(X);if(!this.deleted.has(X)&&this.source.has(X))return this.source.get(X)}set(X,Y){if(this.deleted.delete(X),this.source.has(X))this.changed.add(X);return super.set(X,Y)}hasOwn(X){return super.has(X)}has(X){return!this.deleted.has(X)&&(super.has(X)||this.source.has(X))}delete(X){if(this.source.has(X))this.deleted.add(X),this.changed.delete(X);return super.delete(X)}clear(){this.deleted=new Set(this.source.keys()),this.changed.clear(),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let[X,Y]of this.source)if(!this.deleted.has(X)&&!this.changed.has(X))yield[X,Y]}*entries(){yield*this[Symbol.iterator]()}*keys(){yield*super.keys();for(let X of this.source.keys())if(!this.deleted.has(X)&&!this.changed.has(X))yield X}*values(){for(let[,X]of this[Symbol.iterator]())yield X}forEach(X){for(let[Y,Z]of this[Symbol.iterator]())X(Z,Y,this)}get size(){return super.size+this.source.size-this.changed.size-this.deleted.size}},iG=class extends Set{deleted=new Set;source;constructor(X){super();this.source=X}add(X){if(this.source.has(X))return this.deleted.delete(X),this;return super.add(X)}hasOwn(X){return super.has(X)}has(X){return!this.deleted.has(X)&&(super.has(X)||this.source.has(X))}delete(X){if(this.source.has(X))return this.deleted.add(X),!0;return super.delete(X)}clear(){this.deleted=new Set(this.source),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let X of this.source)if(!this.deleted.has(X))yield X}*iterateOwn(){yield*super[Symbol.iterator]()}get size(){return super.size+this.source.size-this.deleted.size}},cF=class extends Map{deleted=new Set;source;constructor(X){super();this.source=X}get(X){if(super.has(X))return super.get(X);if(!this.deleted.has(X)&&this.source.has(X)){let Y=this.source.get(X),Z=new iG(Y);return super.set(X,Z),Z}}set(X,Y){return this.deleted.delete(X),super.set(X,Y)}has(X){return!this.deleted.has(X)&&(super.has(X)||this.source.has(X))}delete(X){return this.deleted.add(X),super.delete(X)}},W4=class X{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(Y,Z)=>`${Y}:${Z}`;warn;getRelatedKeys(Y){return this.relations.get(Y)}addRelation(Y,Z){let _=this.relations.get(Y),G=this.relations.get(Z);if(_)_.add(Z);else _=new Set([Z]),this.relations.set(Y,_);if(G)G.add(Y);else G=new Set([Y]),this.relations.set(Z,G)}deleteRelation(Y,Z){let _=this.relations.get(Y);if(_){if(_.delete(Z),_.size===0)this.relations.delete(Y);let G=this.relations.get(Z);if(G){if(G.delete(Y),G.size===0)this.relations.delete(Z)}}}replaceRelationsUnsafely(Y,Z){this.relations.set(Y,new Set(Z));for(let _ of Z){let G=new Set().add(Y);this.relations.set(_,G)}}replaceRelationsSafely(Y,Z){let _=this.relations.get(Y),G=this.isAType?.(Y)?Y:void 0,W=G===void 0?Y:void 0;if(_)for(let $ of _){G??=$,W??=$;let H=this.relations.get($);if(H){if(H.size===1)this.relations.delete($);else H.delete(Y);this.contents.delete(this.makeContentKey(G,W))}}this.relations.set(Y,new Set(Z));for(let $ of Z){let H=this.relations.get($);if(H)H.add(Y);else H=new Set().add(Y),this.relations.set($,H)}}getContentInternal(Y){return this.contents.get(Y)}setContent(Y,Z){this.contents.set(Y,Z)}deleteContent(Y){this.contents.delete(Y)}constructor(Y,Z){if(this.a=Y.between[0],this.b=Y.between[1],this.cardinality=Y.cardinality,this.isAType=Z?.isAType??null,this.isBType=Z?.isBType??null,this.isContent=Z?.isContent??null,Z?.makeContentKey)this.makeContentKey=Z.makeContentKey;if(!Z?.externalStore){let _=Z?.source;if(_===void 0)this.relations=new Map(Y.relations?.map(([G,W])=>[G,new Set(W)])),this.contents=new Map(Y.contents);if(_)this.relations=new cF(_.relations),this.contents=new b1(_.contents)}if(Z?.externalStore){let _=Z.externalStore;if(this.has=(G,W)=>_.has(G,W),this.addRelation=(G,W)=>{_.addRelation(G,W)},this.deleteRelation=(G,W)=>{_.deleteRelation(G,W)},this.replaceRelationsSafely=(G,W)=>{_.replaceRelationsSafely(G,W)},this.replaceRelationsUnsafely=(G,W)=>{_.replaceRelationsUnsafely(G,W)},this.getRelatedKeys=(G)=>_.getRelatedKeys(G),_.getContent)this.getContentInternal=(G)=>{return _.getContent(G)},this.setContent=(G,W)=>{_.setContent(G,W)},this.deleteContent=(G)=>{_.deleteContent(G)};for(let[G,W]of Y.relations??[]){let $=this.isAType?.(G)?G:void 0,H=$===void 0?G:void 0;for(let Q of W)$??=Q,H??=Q,this.addRelation($,H)}for(let[G,W]of Y.contents??[])this.setContent(G,W)}if(Z?.warn)this.warn=Z.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([Y,Z])=>[Y,[...Z]]),contents:[...this.contents.entries()]}}set(...Y){let Z,_,G;switch(Y.length){case 1:{let W=Y[0];Z=W[this.a],_=W[this.b],G=void 0;break}case 2:{let W=Y[0];if(typeof W==="string")[Z,_]=Y;else Z=W[this.a],_=W[this.b],G=Y[1];break}default:Z=Y[0],_=Y[1],G=Y[2];break}switch(this.cardinality){case"1:1":{let W=this.getRelatedKey(Z);if(W&&W!==_)this.delete(Z,W)}case"1:n":{let W=this.getRelatedKey(_);if(W&&W!==Z)this.delete(W,_)}break;case"n:n":}if(G){let W=this.makeContentKey(Z,_);this.setContent(W,G)}return this.addRelation(Z,_),this}delete(Y,Z){Z=typeof Z==="string"?Z:Y[this.b];let _=typeof Y==="string"?Y:Y[this.a];if(_===void 0&&typeof Z==="string"){let G=this.getRelatedKeys(Z);if(G)for(let W of G)this.delete(W,Z)}else if(typeof _==="string"&&Z===void 0){let G=this.getRelatedKeys(_);if(G)for(let W of G)this.delete(_,W)}else if(typeof _==="string"&&typeof Z==="string"){this.deleteRelation(_,Z);let G=this.makeContentKey(_,Z);this.deleteContent(G)}return this}getRelatedKey(Y){let Z=this.getRelatedKeys(Y);if(Z){if(Z.size>1)this.warn?.(`${Z.size} related keys were found for key "${Y}": (${[...Z].map((G)=>`"${G}"`).join(", ")}). Only one related key was expected.`);let _;for(let G of Z){_=G;break}return _}}replaceRelations(Y,Z,_){let G=!Array.isArray(Z),W=G?Object.keys(Z):Z;if(_?.reckless)this.replaceRelationsUnsafely(Y,W);else this.replaceRelationsSafely(Y,W);if(G)for(let $ of W){let H=this.makeContentKey(Y,$),Q=Z[$];this.setContent(H,Q)}return this}getContent(Y,Z){let _=this.makeContentKey(Y,Z);return this.getContentInternal(_)}getRelationEntries(Y){let Z=Y[this.a],_=Y[this.b];if(Z!==void 0&&_===void 0){let G=this.getRelatedKeys(Z);if(G)return[...G].map((W)=>{return[W,this.getContent(Z,W)]})}if(Z===void 0&&_!==void 0){let G=this.getRelatedKeys(_);if(G)return[...G].map((W)=>{return[W,this.getContent(W,_)]})}return[]}has(Y,Z){if(Z)return this.getRelatedKeys(Y)?.has(Z)??!1;return this.relations.has(Y)}overlay(){let Y={source:this,makeContentKey:this.makeContentKey};if(this.isAType)Y.isAType=this.isAType;if(this.isBType)Y.isBType=this.isBType;if(this.isContent)Y.isContent=this.isContent;if(this.warn)Y.warn=this.warn;return new X({between:[this.a,this.b],cardinality:this.cardinality},Y)}incorporate(Y){let{relations:Z,contents:_}=Y;for(let[G,W]of Z)if(W instanceof iG){let{source:$}=W;for(let H of W.iterateOwn())$.add(H)}else this.relations.set(G,W);for(let G of Z.deleted)this.relations.delete(G);for(let[G,W]of _)this.contents.set(G,W);for(let G of _.deleted)this.contents.delete(G)}};function V8(X){return X.startsWith("\uD83D\uDD0D ")}var lF=(X)=>{X.logger.info("\uD83E\uDE82","transaction",X.transactionMeta.update.token.key,"Aborting transaction"),X.parent.child=null};function M6(X,Y,Z){return(..._)=>{return T0(X,Y).run(_,Z)}}function oF(X,Y,Z){let{token:_,update:{newValue:G,oldValue:W}}=Y;k1(X,_,Z==="newValue"?G:W)}function iF(X){let{stack:Y}=X;if(Y)return`
48
+ `+Y.split(`
49
49
  `)?.slice(1)?.join(`
50
- `);return""}function P_(Y,Z){let X={key:Z,stringKey:Q0(Z),dependsOn:"any"};return Y.molecules.set(Q0(Z),X),Z}function A6(Y,Z,X,G="any"){let _=Z,$=Q0(X),W=[],H=Y0(Y);if(Array.isArray(_))for(let J of _){let z=Q0(J);if(H.molecules.get(z))Y.moleculeGraph.set(z,$,{source:z});else W.push(z)}else{let J=Q0(_);if(H.molecules.get(J))Y.moleculeGraph.set(J,$,{source:J});else W.push(J)}if(W.length===0)H.molecules.set($,{key:X,stringKey:$,dependsOn:G});let Q={type:"molecule_creation",key:X,provenance:_,timestamp:Date.now()};if(E1(H)&&H.transactionMeta.phase==="building")H.transactionMeta.update.subEvents.push(Q);else H.on.moleculeCreation.next(Q);for(let J of W){let z=Y.disposalTraces.buffer.find((U)=>U?.key===J);Y.logger.error("\u274C","key",X,"allocation failed:",`Could not allocate to ${J} in store "${Y.config.name}".`,z?`
50
+ `);return""}function PG(X,Y){let Z={key:Y,stringKey:w0(Y),dependsOn:"any"};return X.molecules.set(w0(Y),Z),Y}function A6(X,Y,Z,_="any"){let G=Y,W=w0(Z),$=[],H=s(X);if(Array.isArray(G))for(let J of G){let z=w0(J);if(H.molecules.get(z))X.moleculeGraph.set(z,W,{source:z});else $.push(z)}else{let J=w0(G);if(H.molecules.get(J))X.moleculeGraph.set(J,W,{source:J});else $.push(J)}if($.length===0)H.molecules.set(W,{key:Z,stringKey:W,dependsOn:_});let Q={type:"molecule_creation",key:Z,provenance:G,timestamp:Date.now()};if(z1(H)&&H.transactionMeta.phase==="building")H.transactionMeta.update.subEvents.push(Q);else H.on.moleculeCreation.next(Q);for(let J of $){let z=X.disposalTraces.buffer.find((F)=>F?.key===J);X.logger.error("\u274C","key",Z,"allocation failed:",`Could not allocate to ${J} in store "${X.config.name}".`,z?`
51
51
  ${J} was most recently disposed
52
- ${z.trace}`:`No previous disposal trace for ${J} was found.`)}return X}function S_(Y){return _8(Y,{key:"[Internal] deallocate",do:(Z,X)=>{K6(Y0(Y),X)}})}function K6(Y,Z){let X=Q0(Z),G=Y.molecules.get(X);if(!G){let O=Y.disposalTraces.buffer.find((L)=>L?.key===X);Y.logger.error("\u274C","key",Z,"deallocation failed:",`Could not find allocation for ${X} in store "${Y.config.name}".`,O?`
52
+ ${z.trace}`:`No previous disposal trace for ${J} was found.`)}return Z}function vG(X){return _2(X,{key:"[Internal] deallocate",do:(Y,Z)=>{K6(s(X),Z)}})}function K6(X,Y){let Z=w0(Y),_=X.molecules.get(Z);if(!_){let O=X.disposalTraces.buffer.find((D)=>D?.key===Z);X.logger.error("\u274C","key",Y,"deallocation failed:",`Could not find allocation for ${Z} in store "${X.config.name}".`,O?`
53
53
  This state was most recently deallocated
54
- ${O.trace}`:`No previous disposal trace for ${X} was found.`);return}let _=Y.moleculeJoins.getRelatedKeys(X);if(_)for(let O of _){let L=Y.joins.get(O);if(L)L.relations.delete(Z)}Y.moleculeJoins.delete(X);let $=[],W=[],H=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:X});if(H)for(let[O,{source:L}]of H)if(L===X){let w=X1(O);K6(Y,w)}else $.push(L);let Q=Y.moleculeData.getRelatedKeys(G.stringKey);if(Q)for(let O of Q){let L=Y.families.get(O),w=h1(Y,L,Z);W.push([L.key,w]),$8(Y,L,Z)}let J={type:"molecule_disposal",key:G.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(G.stringKey),Y.moleculeJoins.delete(G.stringKey),Y.moleculeData.delete(G.stringKey),!z)Y.on.moleculeDisposal.next(J);Y.molecules.delete(G.stringKey);let U=sF(Error());Y.disposalTraces.add({key:X,trace:U})}function v_(Y){return _8(Y,{key:"[Internal] claim",do:(Z,X,G,_)=>{G8(Y,X,G,_)}})}function G8(Y,Z,X,G){let _=Q0(X),$=Y0(Y),W=$.molecules.get(_);if(!W){let U=Y.disposalTraces.buffer.find((O)=>O?.key===_);return Y.logger.error("\u274C","key",_,"claim failed:",`Could not allocate to ${_} in store "${Y.config.name}".`,U?`
55
- ${_} was most recently disposed
56
- ${U.trace}`:`No previous disposal trace for ${_} was found.`),X}let H=Q0(Z),Q=$.molecules.get(H);if(!Q){let U=Y.disposalTraces.buffer.find((O)=>O?.key===H);return Y.logger.error("\u274C","key",X,"claim failed:",`Could not allocate to ${H} in store "${Y.config.name}".`,U?`
54
+ ${O.trace}`:`No previous disposal trace for ${Z} was found.`);return}let G=X.moleculeJoins.getRelatedKeys(Z);if(G)for(let O of G){let D=X.joins.get(O);if(D)D.relations.delete(Y)}X.moleculeJoins.delete(Z);let W=[],$=[],H=X.moleculeGraph.getRelationEntries({downstreamMoleculeKey:Z});if(H)for(let[O,{source:D}]of H)if(D===Z){let w=X1(O);K6(X,w)}else W.push(D);let Q=X.moleculeData.getRelatedKeys(_.stringKey);if(Q)for(let O of Q){let D=X.families.get(O),w=h1(X,D,Y);$.push([D.key,w]),W2(X,D,Y)}let J={type:"molecule_disposal",key:_.key,values:$,provenance:W,timestamp:Date.now()};X.molecules.delete(Z);let z=z1(X)&&X.transactionMeta.phase==="building";if(z)X.transactionMeta.update.subEvents.push(J);if(X.moleculeGraph.delete(_.stringKey),X.moleculeJoins.delete(_.stringKey),X.moleculeData.delete(_.stringKey),!z)X.on.moleculeDisposal.next(J);X.molecules.delete(_.stringKey);let F=iF(Error());X.disposalTraces.add({key:Z,trace:F})}function xG(X){return _2(X,{key:"[Internal] claim",do:(Y,Z,_,G)=>{Z2(X,Z,_,G)}})}function Z2(X,Y,Z,_){let G=w0(Z),W=s(X),$=W.molecules.get(G);if(!$){let F=X.disposalTraces.buffer.find((O)=>O?.key===G);return X.logger.error("\u274C","key",G,"claim failed:",`Could not allocate to ${G} in store "${X.config.name}".`,F?`
55
+ ${G} was most recently disposed
56
+ ${F.trace}`:`No previous disposal trace for ${G} was found.`),Z}let H=w0(Y),Q=W.molecules.get(H);if(!Q){let F=X.disposalTraces.buffer.find((O)=>O?.key===H);return X.logger.error("\u274C","key",Z,"claim failed:",`Could not allocate to ${H} in store "${X.config.name}".`,F?`
57
57
  ${H} was most recently disposed
58
- ${U.trace}`:`No previous disposal trace for ${H} was found.`),X}let J=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:W.stringKey}).filter(([,{source:U}])=>U!==_).map(([U])=>X1(U));if(G)$.moleculeGraph.delete(_);$.moleculeGraph.set({upstreamMoleculeKey:Q.stringKey,downstreamMoleculeKey:W.stringKey},{source:Q.stringKey});let z={type:"molecule_transfer",key:W.key,exclusive:Boolean(G),from:J,to:[Q.key],timestamp:Date.now()};if(E1($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.subEvents.push(z);return X}function tF(Y,Z,X){switch(X){case"newValue":d_(Y,Z);break;case"oldValue":$8(Y,Z.token);break}}function aF(Y,Z,X){switch(X){case"newValue":$8(Y,Z.token);break;case"oldValue":if(d_(Y,Z),Z.subType==="atom")Y.valueMap.set(Z.token.key,Z.value);break}}function d_(Y,Z){let{token:X}=Z;if(Z.subType==="writable"&&Z.value)k1(Y,X,Z.value);else h1(Y,X)}function eF(Y,Z,X){switch(X){case"newValue":A6(Y,Z.provenance,Z.key);break;case"oldValue":K6(Y,Z.key);break}}function YU(Y,Z,X){switch(X){case"newValue":K6(Y,Z.key);break;case"oldValue":{let G=Z.provenance.map(X1);A6(Y,G,Z.key);for(let[_,$]of Z.values){let W=Y.families.get(_);if(W){h1(Y,W,Z.key);let H=`${_}(${Q0(Z.key)})`;Y.valueMap.set(H,$)}}}break}}function ZU(Y,Z,X){switch(X){case"newValue":for(let G of Z.to)G8(Y,G,Z.key,Z.exclusive?"exclusive":void 0);break;case"oldValue":{let G="exclusive";for(let _ of Z.from)G8(Y,_,Z.key,G),G=void 0}break}}function c_(Y,Z,X){let G=X==="newValue"?Z.subEvents:[...Z.subEvents].reverse();for(let _ of G)switch(_.type){case"atom_update":rF(Y,_,X);break;case"state_creation":tF(Y,_,X);break;case"state_disposal":aF(Y,_,X);break;case"molecule_creation":eF(Y,_,X);break;case"molecule_disposal":YU(Y,_,X);break;case"molecule_transfer":ZU(Y,_,X);break;case"transaction_outcome":c_(Y,_,X);break}}function D2(Y){return"epoch"in Y.transactionMeta}function E1(Y){return"phase"in Y.transactionMeta}function l_(Y,Z){return Y.transactionMeta.actionContinuities.getRelatedKey(Z)}function XU(Y,Z){return Y.transactionMeta.epoch.get(Z)}function GU(Y,Z){let X=l_(Y,Z);if(X===void 0)return;return XU(Y,X)}function _U(Y,Z,X){let G=l_(Y,Z);if(G!==void 0)Y.transactionMeta.epoch.set(G,X)}function $U(Y,Z){let X=Y0(Y),{parent:G}=X;X.transactionMeta.phase="applying",X.transactionMeta.update.output=Z,G.child=null,G.on.transactionApplying.next(X.transactionMeta);let{subEvents:_}=X.transactionMeta.update;if(Y.logger.info("\uD83D\uDEC4","transaction",X.transactionMeta.update.token.key,`applying ${_.length} subEvents:`,_),c_(G,X.transactionMeta.update,"newValue"),D2(G))_U(G,X.transactionMeta.update.token.key,X.transactionMeta.update.epoch),P0(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(G))G.transactionMeta.update.subEvents.push(X.transactionMeta.update);G.on.transactionApplying.next(null)}function WU(Y){return{store:Y}}var HU=(Y,Z,X,G)=>{let _=Y0(Y),$={parent:_,child:null,on:_.on,loggers:_.loggers,logger:_.logger,config:_.config,atoms:new b1(_.atoms),atomsThatAreDefault:new Set(_.atomsThatAreDefault),families:new b1(_.families),joins:new b1(_.joins),operation:{open:!1},readonlySelectors:new b1(_.readonlySelectors),timelines:new b1(_.timelines),timelineTopics:_.timelineTopics.overlay(),trackers:new Map,transactions:new b1(_.transactions),selectorAtoms:_.selectorAtoms.overlay(),selectorGraph:_.selectorGraph.overlay(),writableSelectors:new b1(_.writableSelectors),valueMap:new b1(_.valueMap),defaults:_.defaults,disposalTraces:Y.disposalTraces.copy(),molecules:new b1(_.molecules),moleculeGraph:_.moleculeGraph.overlay(),moleculeData:_.moleculeData.overlay(),moleculeJoins:_.moleculeJoins.overlay(),miscResources:new b1(_.miscResources)},W=GU(Y,Z.key),H={phase:"building",update:{type:"transaction_outcome",token:Z,id:G,epoch:W===void 0?NaN:W+1,timestamp:Date.now(),subEvents:[],params:X,output:void 0},toolkit:{get:(...J)=>h1(Q,...J),set:(...J)=>{k1(Q,...J)},reset:(...J)=>{R6(Q,...J)},run:(J,z=kZ())=>M6(Q,J,z),find:(...J)=>j0(Y,...J),json:(J)=>k4(Q,J),dispose:(...J)=>{$8(Q,...J)},env:()=>WU(Q)}},Q=Object.assign($,{transactionMeta:H});return _.child=Q,Y.logger.info("\uD83D\uDEEB","transaction",Z.key,"building with params:",X),Q};function _8(Y,Z){let{key:X}=Z,G=Y.transactions.has(X),_={key:X,type:"transaction",run:(W,H)=>{let Q=y1(_),J=HU(Y,Q,W,H);try{let{toolkit:z}=J.transactionMeta,U=Z.do(z,...W);return $U(J,U),U}catch(z){throw nF(J),Y.logger.warn("\uD83D\uDCA5","transaction",X,"caught:",z),z}},install:(W)=>_8(W,Z),subject:new _0};Y0(Y).transactions.set(X,_);let $=y1(_);if(!G)Y.on.transactionCreation.next($);return $}var x_=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 $4({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new $4({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 $4({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new $4({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new oF(100);molecules=new Map;moleculeJoins=new $4({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeGraph=new $4({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeData=new $4({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});miscResources=new Map;on={atomCreation:new _0,atomDisposal:new _0,selectorCreation:new _0,selectorDisposal:new _0,timelineCreation:new _0,transactionCreation:new _0,transactionApplying:new lF(null),operationClose:new _0,moleculeCreation:new _0,moleculeDisposal:new _0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new q_("warn",(Y,Z,X)=>!L2(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},D2(Z))this.transactionMeta={epoch:new Map(Z?.transactionMeta.epoch),actionContinuities:new $4(Z?.transactionMeta.actionContinuities.toJSON())};for(let[,G]of Z.families){if(G.internalRoles?.includes("mutable")||G.internalRoles?.includes("join"))continue;G.install(this)}let X=new Set;for(let[,G]of Z.atoms){if(X.has(G.key))continue;if(G.install(this),G.type==="mutable_atom"){let _=k4(Z,G),$=Y5(G);X.add(_.key),X.add($.key)}}for(let[,G]of Z.readonlySelectors)G.install(this);for(let[,G]of Z.writableSelectors){if(X.has(G.key))continue;G.install(this)}for(let[,G]of Z.transactions)G.install(this);for(let[,G]of Z.timelines)G.install(this)}}},U1={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new x_({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};var JU=class extends Error{constructor(Y,Z){super(`${_4[Y.type]} ${Q0(Y.key)} not found in store "${Z.config.name}".`)}};function P0(Y,Z){let X,G=Y;while(G!==null){switch(Z.type){case"atom":case"mutable_atom":X=G.atoms.get(Z.key);break;case"writable_pure_selector":case"writable_held_selector":X=G.writableSelectors.get(Z.key);break;case"readonly_pure_selector":case"readonly_held_selector":X=G.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=G.families.get(Z.key);break;case"timeline":X=G.timelines.get(Z.key);break;case"transaction":X=G.transactions.get(Z.key);break}if(X)return X;G=G.child}throw new JU(Z,Y)}function o_(Y,Z,X,G){let _=Y.disposalTraces.buffer.find(($)=>$?.key===Q0(G));switch(Y.logger.error("\u274C",Z.type,Z.key,"gets a fallback value because key",G,"is not allocated",_?`This key was previously disposed:
59
- ${_.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,$),$.READONLY_VIEW}case"atom_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=X.default,W=$(G);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(G);return Y.defaults.set(X.key,$),$}}}function N6(Y,Z){let{type:X,key:G,catch:_}=Z;switch(X){case"readonly_pure_selector":case"writable_pure_selector":{let $;Y.logger.info("\uD83E\uDDEE",X,G,"computing value");try{if($=Z.getFrom(Y),$ instanceof Promise)return $.catch((W)=>{if(Y.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return W}throw W})}catch(W){if(Y.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return B1(Y,Z,W)}throw W}return B1(Y,Z,$)}case"atom":{let $;if(H8(Z.default))try{if($=Z.default(),$ instanceof Promise)$=$.catch((W)=>{if(Y.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return W}throw W})}catch(W){if(Y.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return $=B1(Y,Z,W),Y.logger.info("\u2728",Z.type,G,"computed default",$),$}throw W}else $=Z.default,Y.logger.info("\u2728",Z.type,G,"using static default",$);return B1(Y,Z,$)}}}function h4(Y,Z,X){if(Y.valueMap.has(Z.key))return wU(Y,Z,X);Y.logger.info("\u2754",Z.type,Z.key,"value not found in cache");let{key:G}=Z;switch(Z.type){case"readonly_held_selector":case"writable_held_selector":return Y.logger.info("\uD83E\uDDEE",Z.type,G,"computing value"),Z.getFrom(Y);case"writable_pure_selector":case"readonly_pure_selector":case"atom":return N6(Y,Z);case"mutable_atom":{let _=new Z.class;return Y.logger.info("\u2728",Z.type,G,"created new instance",_),B1(Y,Z,_)}}}function oZ(Y,Z){return P0(Y,{key:Z.family.key,type:`${Z.type}_family`})}var y_={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"},J8=Symbol("MUST_CREATE"),QU=Symbol("DO_NOT_CREATE");function Q8(Y,Z,X,G){let _=Q0(G),$=Z.molecules.get(_);if(!$&&Z.config.lifespan==="immortal"){let{type:H,key:Q}=X;Z.logger.warn("\uD83D\uDCA3","key",_,"was used to mint a counterfeit token for",H,`"${Q}"`);let J=`${Q}(${_})`,z=y_[H];return{counterfeit:!0,key:J,type:z,family:{key:Q,subKey:_}}}let W;if(Y===J8){if(Z.logger.info("\uD83D\uDC6A",X.type,X.key,"adds member",typeof G==="string"?`\`${G}\``:G),W=X.create(G),$)Z.moleculeData.set(_,X.key)}else{let{type:H,key:Q}=X,J=`${Q}(${_})`,z=y_[H];return{key:J,type:z,family:{key:Q,subKey:_}}}return W}function iZ(Y,...Z){let X,G,_,$,W;if(Z.length===1){if(W=Z[0],"family"in W){let Q=oZ(Y,W);if(_=P0(Y,Q),$=X1(W.family.subKey),X=z8(Y,Q,$),"counterfeit"in W)return{token:W,family:_,subKey:$,isNew:!1};if(!X)G=Q8(J8,Y,Q,$),W=G;else W=X}}else if(_=P0(Y,Z[0]),$=Z[1],X=z8(Y,_,$),!X)G=Q8(J8,Y,_,$),W=G;else W=X;let H="counterfeit"in W;if(Boolean(G)&&H===!1&&_){let Q;switch(W.type){case"readonly_pure_selector":case"readonly_held_selector":Q="readable";break;case"atom":case"mutable_atom":case"writable_pure_selector":case"writable_held_selector":Q="writable";break}let J={type:"state_creation",subType:Q,token:W,timestamp:Date.now()};_.subject.next(J);let z=Y0(Y);if(W.family){if(D2(z))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(z)&&z.on.transactionApplying.state===null)z.transactionMeta.update.subEvents.push(J)}}return{token:W,family:_,subKey:$,isNew:Boolean(G)}}function h1(Y,...Z){let{token:X,family:G,subKey:_}=iZ(Y,...Z);if("counterfeit"in X&&G&&_)return o_(Y,X,G,_);let $=P0(Y,X);return h4(Y,$)}function z8(Y,Z,X){let G=Q0(X),_=`${Z.key}(${G})`,$=Y0(Y),W;switch(Z.type){case"atom_family":case"mutable_atom_family":W=$.atoms.get(_);break;case"writable_held_selector_family":case"writable_pure_selector_family":W=$.writableSelectors.get(_);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":W=$.readonlySelectors.get(_);break}if(W)return y1(W);return W}function j0(Y,Z,X){let G=P0(Y,Z),_=z8(Y,Z,X);if(_)return _;return Q8(QU,Y,G,X)}function f4(Y,Z,X){let G=Z.key,_="readonly_pure_selector_family",$={key:G,type:"readonly_pure_selector_family"},W=Y.families.get(G);if(W)Y.logger.error("\u2757","readonly_pure_selector_family",G,`Overwriting an existing ${_4[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 _0,J={...$,create:(z)=>{let U=Q0(z),O={key:G,subKey:U},L=`${G}(${U})`,w=Y0(Y),R={key:L,get:Z.get(z)};if(Z.catch)R.catch=Z.catch;return sZ(w,R,O)},internalRoles:X,subject:H,install:(z)=>f4(z,Z),default:(z)=>{return Z.get(z)({get:(...U)=>h1(Y,...U),find:(...U)=>j0(Y,...U),json:(U)=>k4(Y,U)})}};return Y.families.set(G,J),$}function O2(Y,Z,X){let G={key:Z.key,type:"atom_family"},_=Y.families.get(Z.key);if(_)Y.logger.error("\u2757","atom_family",Z.key,`Overwriting an existing ${_4[_.type]} "${_.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new _0,H={...G,create:(Q)=>{let J=Q0(Q),z={key:Z.key,subKey:J},U=`${Z.key}(${J})`,O=Y0(Y),L=Z.default,w={key:U,default:H8(L)?()=>L(Q):L};if(Z.effects)w.effects=Z.effects(Q);if(Z.catch)w.catch=Z.catch;return x4(O,w,z)},default:Z.default,subject:$,install:(Q)=>O2(Q,Z),internalRoles:X};if(Y.families.set(Z.key,H),H8(Z.default)===!1)Y.defaults.set(Z.key,Z.default);return G}function i_(Y,Z,X){let G=Z.key,_="readonly_held_selector_family",$={key:G,type:"readonly_held_selector_family"},W=Y.families.get(G);if(W)Y.logger.error("\u2757","readonly_held_selector_family",G,`Overwriting an existing ${_4[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 _0,J={...$,create:(z)=>{let U=Q0(z),O={key:G,subKey:U},L=`${G}(${U})`,w=Y0(Y);return rZ(w,{key:L,const:Z.const(z),get:Z.get(z)},O)},internalRoles:X,subject:H,install:(z)=>i_(z,Z),default:Z.const};return Y.families.set(G,J),$}function n_(Y,Z,X){let G=Z.key,_="writable_held_selector_family",$={key:G,type:"writable_held_selector_family"},W=Y.families.get(G);if(W)Y.logger.error("\u2757","writable_held_selector_family",G,`Overwriting an existing ${_4[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 _0,J={...$,create:(z)=>{let U=Q0(z),O={key:G,subKey:U},L=`${G}(${U})`,w=Y0(Y);return tZ(w,{key:L,const:Z.const(z),get:Z.get(z),set:Z.set(z)},O)},internalRoles:X,subject:H,install:(z)=>n_(z,Z),default:Z.const};return Y.families.set(G,J),$}function nZ(Y,Z,X){let G=Z.key,_="writable_pure_selector_family",$={key:G,type:"writable_pure_selector_family"},W=Y.families.get(G);if(W)Y.logger.error("\u2757","writable_pure_selector_family",G,`Overwriting an existing ${_4[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 _0,J={...$,create:(z)=>{let U=Q0(z),O={key:G,subKey:U},L=`${G}(${U})`,w=Y0(Y),R={key:L,get:Z.get(z),set:Z.set(z)};if(Z.catch)R.catch=Z.catch;return aZ(w,R,O)},internalRoles:X,subject:H,install:(z)=>nZ(z,Z),default:(z)=>{return Z.get(z)({get:(...U)=>h1(Y,...U),find:(...U)=>j0(Y,...U),json:(U)=>k4(Y,U)})}};return Y.families.set(G,J),$}function bZ(Y,Z){let X="set"in Z,G="const"in Z;if(G&&X)return n_(Y,Z,void 0);if(G)return i_(Y,Z,void 0);if(X)return nZ(Y,Z);return f4(Y,Z)}function $8(Y,...Z){let X;if(Z.length===1)X=Z[0];else{let G=Z[0],_=Z[1];X=j0(Y,G,_)}try{P0(Y,X)}catch(G){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":X7(Y,X);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":LU(Y,X);break}}function r_(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 s_(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 t_=(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)},B6=(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 dZ(Y,Z,{oldValue:X,newValue:G},_,$){let W=y1(Z);if(_&&$){Z.subject.next({newValue:G});let U={checkpoint:!0,type:"state_creation",subType:"writable",token:W,timestamp:Date.now(),value:G};Y.operation.subEvents.push(U),$.subject.next(U);let O=Y0(Y);if(W.family){if(D2(O))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(O)&&O.on.transactionApplying.state===null)O.transactionMeta.update.subEvents.push(U)}return}let{key:H,subject:Q,type:J}=Z,z={oldValue:pZ(X)?X.READONLY_VIEW:X,newValue:pZ(G)?G.READONLY_VIEW:G};if(D2(Y)){switch(J){case"mutable_atom":Y.logger.info("\uD83D\uDCE2",J,H,"is now (",G,") subscribers:",Q.subscribers.keys());break;case"atom":case"writable_pure_selector":case"writable_held_selector":Y.logger.info("\uD83D\uDCE2",J,H,"went (",X,"->",G,") subscribers:",Q.subscribers.keys())}Q.next(z)}if(E1(Y)&&(J==="mutable_atom"||J==="atom")){if(Y.on.transactionApplying.state===null){if(pZ(G))return;let{timestamp:U}=Y.operation,O={type:"atom_update",token:W,timestamp:U,update:z};Y.transactionMeta.update.subEvents.push(O),Y.logger.info("\uD83D\uDCC1","atom",H,"stowed (",X,"->",G,")");return}if(X5(Z,"tracker:signal")){let U=H.slice(1),O=Y.atoms.get(U);if(h4(Y,O,"mut").do(z.newValue)===null===!0)Z5(Y,O)}}}var cZ=(Y,Z,X)=>{let G=h4(Y,Z,"mut"),_=mZ(X,G);return Y.logger.info("\u2B50","atom",Z.key,"setting value",_),_=B1(Y,Z,_),B6(Y,Z.key),Z5(Y,Z),{oldValue:G,newValue:_}};function gZ(Y,Z){switch(Z.type){case"mutable_atom":return cZ(Y,Z,new Z.class);case"atom":{let X;if(H8(Z.default))X=N6(Y,Z);else X=Z.default;return cZ(Y,Z,X)}}}function zU(Y,Z){let X;switch(Z.type){case"atom":case"mutable_atom":X=gZ(Y,Z);break;case"writable_held_selector":{let G=F8(Y,Z.key);for(let $ of G.values()){let W=gZ(Y,$);dZ(Y,Z,W,!1)}let _=Z.getFrom(Y);X={oldValue:_,newValue:_}}break;case"writable_pure_selector":{let G=N6(Y,Z),_=F8(Y,Z.key);for(let W of _.values()){let H=gZ(Y,W);dZ(Y,Z,H,!1)}let $=N6(Y,Z);X={oldValue:G,newValue:$}}break}return X}function k1(Y,...Z){E8(I6,Y,...Z)}var lZ=Symbol("RESET");function R6(Y,...Z){let X=[...Z,lZ];k1(Y,...X)}function FU(Y,Z,X){let G,_,$,{type:W,key:H}=Z;switch(Z.type){case"writable_pure_selector":G=h4(Y,Z,"mut"),_=mZ(X,G),_=B1(Y,Z,_);break;case"writable_held_selector":$=Z.const,mZ(X,$),G=$,_=$}return Y.logger.info("\u2B50",W,H,"setting to",_),B6(Y,H),Z.setSelf(_),{oldValue:G,newValue:_}}var UU=(Y,Z,X)=>{let G;switch(Z.type){case"atom":case"mutable_atom":G=cZ(Y,Z,X);break;case"writable_pure_selector":case"writable_held_selector":G=FU(Y,Z,X);break}return G},I6=Symbol("OWN_OP"),a_=Symbol("JOIN_OP");function E8(Y,Z,...X){let G,_,$,W,H,Q;if(X.length===2){if($=X[0],Q=X[1],"family"in $)if(W=oZ(Z,$),H=X1($.family.subKey),G=z8(Z,W,H),!G)$=_=Q8(J8,Z,W,H);else $=G}else if(W=P0(Z,X[0]),H=X[1],Q=X[2],G=z8(Z,W,H),!G)$=_=Q8(J8,Z,W,H);else $=G;let J=Q===lZ?"reset":"set",z;if(Y===I6){let L=r_(Z,$);if(typeof L==="number"){let w=L,R=Z.on.operationClose.subscribe(`waiting to ${J} "${$.key}" at T-${w}`,function(){R(),Z.logger.info("\uD83D\uDFE2",$.type,$.key,"resuming deferred",J,`from T-${w}`),E8(Y,Z,$,Q)});return}z=L}else z=Z;if("counterfeit"in $&&"family"in $){let L=$.family.subKey,w=Z.disposalTraces.buffer.find((R)=>R?.key===L);Z.logger.error("\u274C",$.type,$.key,"could not be",J,"because key",L,"is not allocated.",w?`this key was previously disposed:${w.trace}`:"(no previous disposal trace found)");return}let U=P0(z,$),O;if(Q===lZ)O=zU(z,U);else O=UU(z,U,Q);if(dZ(z,U,O,Boolean(_),W),Y===I6)s_(z)}var e_=(Y,Z)=>Y0(Y).atoms.has(Z),EU=(Y,Z)=>Y0(Y).writableSelectors.has(Z),VU=(Y,Z)=>Y0(Y).readonlySelectors.has(Z),OU=(Y,Z)=>e_(Y,Z)||EU(Y,Z)||VU(Y,Z);function g_(Y,Z){return Y0(Y).selectorGraph.getRelationEntries({downstreamSelectorKey:Z}).filter(([X,{source:G}])=>G!==Z).map(([X,{source:G}])=>G).filter((X)=>OU(Y,X))}function F8(Y,Z,X=new Set){let G=g_(Y,Z),_=new Map;while(G.length>0){let $=G.pop();if(X.has($))continue;if(X.add($),e_(Y,$)){let W=Y.atoms.get($);_.set(W.key,W)}else G.push(...g_(Y,$))}return _}function DU(Y,Z,X,G,_){let $=Y0(Y),{type:W,key:H}=G;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=F8(Y,H,_);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})}_.add(H)}function T6(Y,Z,X,G){return{get:(..._)=>{let $=Y0(Y),{token:W,family:H,subKey:Q}=iZ(Y,..._),J;if("counterfeit"in W&&H&&Q)J=o_(Y,W,H,Q);else{let z=P0(Y,W);J=h4(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}),DU(Y,Z,X,W,G),J},set:(..._)=>{let $=Y0(Y);E8(a_,$,..._)},find:(..._)=>j0(Y,..._),json:(_)=>k4(Y,_)}}function rZ(Y,Z,X){let G=Y0(Y),_=new _0,$=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:U}=T6(G,"readonly_held_selector",W,$),L={...Z,type:"readonly_held_selector",subject:_,getFrom:(R)=>{let b=R.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[x,{source:h}]of b)if(h!==W)R.selectorGraph.delete(x,W);return R.selectorAtoms.delete(W),Z.get({get:J,find:z,json:U},H),B1(R,L,H),Y.logger.info("\u2728","readonly_held_selector",W,"=",H),$.clear(),H},install:(R)=>rZ(R,Z,X)};if(X)L.family=X;G.readonlySelectors.set(W,L);let w={key:W,type:"readonly_held_selector"};if(X)w.family=X;return w}function sZ(Y,Z,X){let G=Y0(Y),_=new _0,$=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}=T6(G,"readonly_pure_selector",W,$),O={...Z,type:"readonly_pure_selector",subject:_,getFrom:()=>{let w=Y0(Y),R=w.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[h,{source:g}]of R)if(g!==W)w.selectorGraph.delete(h,W);w.selectorAtoms.delete(W);let b=Z.get({get:Q,find:J,json:z}),x=B1(w,O,b);return Y.logger.info("\u2728","readonly_pure_selector",W,"=",x),$.clear(),x},install:(w)=>sZ(w,Z,X)};if(X)O.family=X;G.readonlySelectors.set(W,O);let L={key:W,type:"readonly_pure_selector"};if(X)L.family=X;return L}function tZ(Y,Z,X){let G=Y0(Y),_=new _0,$=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=T6(G,"writable_held_selector",W,$),{find:z,get:U,json:O}=J,L={find:z,get:U,json:O},b={...Z,type:"writable_held_selector",subject:_,getFrom:(h)=>{let g=h.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[B,{source:K}]of g)if(K!==W)h.selectorGraph.delete(B,W);return h.selectorAtoms.delete(W),Z.get(L,H),B1(h,b,H),Y.logger.info("\u2728","writable_held_selector",W,"=",H),$.clear(),H},setSelf:()=>{Z.set(J,H)},install:(h)=>tZ(h,Z,X)};if(X)b.family=X;G.writableSelectors.set(W,b);let x={key:W,type:"writable_held_selector"};if(X)x.family=X;return x}function aZ(Y,Z,X){let G=Y0(Y),_=new _0,$=new Set,W=Z.key,H="writable_pure_selector";Y.logger.info("\uD83D\uDD28","writable_pure_selector",W,"is being created");let Q=T6(G,"writable_pure_selector",W,$),{find:J,get:z,json:U}=Q,O={find:J,get:z,json:U},R={...Z,type:"writable_pure_selector",subject:_,getFrom:(x)=>{let h=x.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[K,{source:C}]of h)if(C!==W)x.selectorGraph.delete(K,W);x.selectorAtoms.delete(W);let g=Z.get(O),B=B1(x,R,g);return Y.logger.info("\u2728","writable_pure_selector",W,"=",B),$.clear(),B},setSelf:(x)=>{Z.set(Q,x)},install:(x)=>aZ(x,Z,X)};if(X)R.family=X;G.writableSelectors.set(W,R);let b={key:W,type:"writable_pure_selector"};if(X)b.family=X;return b}function f_(Y,Z){let X="set"in Z,G="const"in Z;if(G&&X){let $=tZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}if(G){let $=rZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}if(X){let $=aZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}let _=sZ(Y,Z,void 0);return Y.on.selectorCreation.next(_),_}function LU(Y,Z){let X=Y0(Y),{key:G,type:_,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 W;switch(Z.type){case"writable_held_selector":X.writableSelectors.delete(G),W={key:$.key,type:"writable_held_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"writable_pure_selector":X.writableSelectors.delete(G),W={key:$.key,type:"writable_pure_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"readonly_held_selector":X.readonlySelectors.delete(G),W={key:$.key,type:"readonly_held_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"readonly_pure_selector":X.readonlySelectors.delete(G),W={key:$.key,type:"readonly_pure_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break}if(X.valueMap.delete(G),X.selectorAtoms.delete(G),X.selectorGraph.delete(G),X.moleculeData.delete($.key,$.subKey),Y.logger.info("\uD83D\uDD25",Z.type,G,"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)}}var MU=(Y,Z)=>{let X=Y0(Y);if(X.operation.open)return X.operation.prev.get(Z.key);return X.valueMap.get(Z.key)},p_=(Y,Z,X)=>{return X.subject.subscribe(`${Z.type}:${Z.key}`,(G)=>{Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"root",X.key,"went",G.oldValue,"->",G.newValue);let _=MU(Y,Z),$=h4(Y,Z);Y.logger.info("\u2728",Z.type,Z.key,"went",_,"->",$),Z.subject.next({newValue:$,oldValue:_})})};function U8(Y,Z,X,G){function _(U){if(Y.operation.open){if($?.type==="atom"&&X5($,"tracker:signal")&&"*"+Y.operation.token.key===Z.key&&"inboundTracker"in G)return;let O=Y.on.operationClose.subscribe(`state subscription ${X}`,()=>{O(),G(U)})}else G(U)}iZ(Y,Z);let $=P0(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=_;if(W){h4(Y,$);for(let[U,O]of F8(Y,$.key))H.set(U,p_(Y,$,O));Q=function(O){let L=F8(Y,$.key);for(let[w,R]of H)if(L.get(w))L.delete(w);else R(),H.delete(w);for(let[w,R]of L)H.set(w,p_(Y,$,R));_(O)}}let J=$.subject.subscribe(X,Q);return()=>{Y.logger.info("\uD83D\uDE48",$.type,$.key,`Removing subscription "${X}"`),J();for(let U of H.values())U()}}var AU=(Y,Z,X,G)=>{let _=P0(Y,Z);Y.logger.info("\uD83D\uDC40","timeline",Z.key,`Adding subscription "${X}"`);let $=_.subject.subscribe(X,G);return()=>{Y.logger.info("\uD83D\uDE48","timeline",Z.key,`Removing subscription "${X}" from timeline`),$()}};var eZ=class{initializeSignalAtom(Y,Z){let X=`*${Y.key}`;Z.atoms.delete(X),Z.valueMap.delete(X);let G=Y.family?{key:`*${Y.family.key}`,subKey:Y.family.subKey}:void 0,_=x4(Z,{key:X,default:null},G,["tracker:signal"]);if(Z.parent?.valueMap.has(X)){let $=Z.parent.valueMap.get(X);Z.valueMap.set(X,$)}return _}unsubscribeFromInnerValue;unsubscribeFromState;captureSignalsFromCore(Y,Z,X){let G=Y.key,_=X.config.name,$=E1(X)?X.transactionMeta.update.token.key:"main",W=`tracker-from-core:${_}:${$}:${G}`,H=(Q)=>{E8(a_,X,Z,Q)};this.unsubscribeFromInnerValue=h1(X,Y).subscribe(W,H),this.unsubscribeFromState=U8(X,Y,W,function(J){if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe(W,H)}.bind(this))}supplySignalsToCore(Y,Z,X){let G=Y.key,_=X.config.name,$=E1(X)?X.transactionMeta.update.token.key:"main",W=`tracker-to-core:${_}:${$}:${G}`;U8(X,Z,W,Object.assign(function({newValue:Q,oldValue:J}){let z=X.timelineTopics.getRelatedKey(Z.key);if(z&&X.timelines.get(z)?.timeTraveling){let U=AU(X,{key:z,type:"timeline"},W,function(L){U(),k1(X,Y,(w)=>{if(L==="redo"&&Q)w.do(Q);else if(L==="undo"&&J)w.undo(J);return w})});return}k1(X,Y,(U)=>(U.do(Q),U))},{inboundTracker:!0}))}mutableAtomToken;latestSignalToken;[Symbol.dispose];constructor(Y,Z){let X=Y0(Z),G=this.initializeSignalAtom(Y,X);this.mutableAtomToken=Y,this.latestSignalToken=G,this.captureSignalsFromCore(Y,G,X),this.supplySignalsToCore(Y,G,X),X.trackers.set(Y.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(Y.key)}}};function w6(Y,Z,X){Y.logger.info("\uD83D\uDD28","atom",Z.key,`creating in store "${Y.config.name}"`);let G=Y0(Y),{key:_}=Z,$=G.atoms.get(_),W="mutable_atom";if($&&$.type===W)return Y.logger.error("\u274C",W,_,"Tried to create atom, but it already exists in the store."),y1($);let H=new _0,Q={...Z,type:W,install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",_,`installing in store "${z.config.name}"`),w6(z,Z,X)},subject:H};if(X)Q.family=X;G.atoms.set(Q.key,Q);let J=y1(Q);if(Z.effects){let z=0,U=[];for(let O of Z.effects){let L=O({resetSelf:()=>{R6(Y,J)},setSelf:(w)=>{k1(Y,J,w)},onSet:(w)=>U8(Y,J,`effect[${z}]`,w)});if(L)U.push(L);++z}Q.cleanup=()=>{for(let O of U)O()}}if(new eZ(J,Y),!X)f_(Y,{key:`${_}:JSON`,get:({get:z})=>z(J).toJSON(),set:({set:z},U)=>{z(J,Z.class.fromJSON(U))}});return Y.on.atomCreation.next(J),J}var RU=class{trackers=new Map;latestSignalAtoms;mutableAtoms;constructor(Y,Z){let X=O2(Z,{key:`*${Y.key}`,default:null},["mutable","updates"]);this.latestSignalAtoms=P0(Z,X),this.mutableAtoms=Y;let G=(_)=>{let{type:$,token:W}=_;if(W.family){let H=X1(W.family.subKey);switch($){case"state_creation":this.trackers.set(H,new eZ(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`,G)}};function yZ(Y,Z,X){let G={key:Z.key,type:"mutable_atom_family"},_=Y.families.get(Z.key);if(_)Y.logger.error("\u2757","mutable_atom_family",Z.key,`Overwriting an existing ${_4[_.type]} "${_.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new _0,H={...G,create:(Q)=>{let J=Q0(Q),z={key:Z.key,subKey:J},U=`${Z.key}(${J})`,O=Y0(Y),L={key:U,class:Z.class};if(Z.effects)L.effects=Z.effects(Q);return w6(O,L,z)},class:Z.class,subject:$,install:(Q)=>yZ(Q,Z),internalRoles:X};return Y.families.set(Z.key,H),nZ(Y,{key:`${Z.key}:JSON`,get:(Q)=>({get:J})=>J(G,Q).toJSON(),set:(Q)=>({set:J},z)=>{J(G,Q,Z.class.fromJSON(z))}},["mutable","json"]),new RU(H,Y),G}var m_=(Y,Z)=>{let X=Y0(Z),G=`${Y.key}:JSON`;return X.families.get(G)},k4=(Y,Z)=>{if(Z.family){let X=Y0(Y),G={key:`${Z.family.key}:JSON`,type:"writable_pure_selector_family"},_=P0(X,G),$=X1(Z.family.subKey);return j0(Y,_,$)}return{type:"writable_pure_selector",key:`${Z.key}:JSON`}};var Y5=(Y)=>{let Z={type:"atom",key:`*${Y.key}`};if(Y.family)Z.family={key:`*${Y.family.key}`,subKey:Y.family.subKey};return Z};function pZ(Y){return typeof Y==="object"&&Y!==null&&"do"in Y&&"undo"in Y&&"subscribe"in Y&&"READONLY_VIEW"in Y&&"toJSON"in Y}function B1(Y,Z,X){let{key:G,subject:_,type:$}=Z,W=Y.valueMap.get(G);if(W instanceof uZ&&!W.done){let H=W;if(X instanceof Promise)return H.use(X),H;return Y.valueMap.set(G,X),X}if(X instanceof Promise){let H=new uZ(X);return Y.valueMap.set(G,H),H.then(function(J){if(Y.valueMap.get(G)===H){switch(r_(Y,Z),B1(Y,Z,J),$){case"atom":Z5(Y,Z);break;case"readonly_pure_selector":case"writable_pure_selector":Z7(Y,G);break}s_(Y),_.next({newValue:J,oldValue:H})}}).catch((Q)=>{Y.logger.error("\uD83D\uDCA5",Z.type,G,"rejected:",Q)}),H}return Y.logger.info("\uD83D\uDCDD",Z.type,Z.key,"writing to cache",X),Y.valueMap.set(G,X),X}function wU(Y,Z,X){Y.logger.info("\uD83D\uDCD6",Z.type,Z.key,"reading cached value");let G=Y.valueMap.get(Z.key);if(X==="mut"&&Z.type==="mutable_atom"&&E1(Y)){let _=Z,{parent:$}=Y;if(Y.valueMap.hasOwn(_.key))return G;let W=$.valueMap.get(_.key);Y.logger.info("\uD83D\uDCC3","atom",_.key,"copying");let H=W.toJSON(),Q=_.class.fromJSON(H);Y.valueMap.set(_.key,Q),new eZ(_,$),G=Q}return G}function Y7(Y,Z){let X=Y.valueMap.get(Z);if(X instanceof uZ){let G=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if(G)G.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")}function Z5(Y,Z){let X=Y0(Y),{key:G,type:_}=Z,$=X.selectorAtoms.getRelatedKeys(G);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(t_(X,W))continue;Y7(X,W),B6(X,W)}}}function Z7(Y,Z){let X=Y0(Y),G=X.selectorGraph.getRelationEntries({upstreamSelectorKey:Z}).filter(([_,{source:$}])=>$===Z);for(let[_]of G){if(t_(X,_))continue;Y7(X,_),B6(X,_),Z7(Y,_)}}function x4(Y,Z,X,G){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."),y1(H);let Q=new _0,J={...Z,type:"atom",install:(U)=>{return U.logger.info("\uD83D\uDEE0\uFE0F","atom",$,`installing in store "${U.config.name}"`),x4(U,Z,X)},subject:Q};if(X)J.family=X;if(G)J.internalRoles=G;W.atoms.set($,J);let z=y1(J);if(Z.effects){let U=0,O=[];for(let L of Z.effects){let w=L({resetSelf:()=>{R6(Y,z)},setSelf:(R)=>{k1(Y,z,R)},onSet:(R)=>U8(Y,z,`effect[${U}]`,R)});if(w)O.push(w);++U}J.cleanup=()=>{for(let L of O)L()}}return Y.on.atomCreation.next(z),z}function X5(Y,Z){if("internalRoles"in Y===!1)return!1;return Y.internalRoles.includes(Z)}function X7(Y,Z){let X=Y0(Y),{key:G,family:_}=Z,$=P0(X,Z);if(!_)Y.logger.error("\u274C","atom",G,"Standalone atoms cannot be disposed.");else{$.cleanup?.();let W=Y.valueMap.get($.key),H=oZ(Y,Z),Q=P0(Y,H).subject,J={type:"state_disposal",subType:"atom",token:Z,value:W,timestamp:Date.now()};Q.next(J);let z=E1(X);if(X.atoms.delete(G),X.valueMap.delete(G),X.selectorAtoms.delete(G),X.atomsThatAreDefault.delete(G),X.moleculeData.delete(_.key,_.subKey),Y.timelineTopics.delete(G),Z.type==="mutable_atom"){let U=Y5(Z);X7(Y,U),Y.trackers.delete(G)}if(Y.logger.info("\uD83D\uDD25","atom",G,"deleted"),z&&X.transactionMeta.phase==="building"){let U=X.transactionMeta.update.subEvents.at(-1),O=U?.type==="molecule_disposal"&&U.values.some(([w])=>w===$.family?.key),L=X5($,"tracker:signal");if(!O&&!L)X.transactionMeta.update.subEvents.push(J)}else Y.on.atomDisposal.next(Z)}}function K0(Y){return Y[0].toUpperCase()+Y.slice(1)}var G7=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=U1.STORE){this.store=X,this.realm=new j_(X),this.options=Y,this.defaultContent=Z,this.store.miscResources.set(`join:${Y.key}`,this),this.realm.allocate("root",Y.key),this.toolkit={get:(...B)=>h1(X,...B),set:(...B)=>{k1(X,...B)},find:(...B)=>j0(X,...B),json:(B)=>k4(X,B)};let G=Y.between[0],_=Y.between[1],$=yZ(X,{key:`${Y.key}/relatedKeys`,class:b_},["join","relations"]);this.core={relatedKeysAtoms:$};let W=({get:B},K)=>B($,K),H=({set:B},K,C)=>{if(!this.store.molecules.has(Q0(K)))this.realm.allocate(Y.key,K);B($,K,(q)=>q.add(C)),B($,C,(q)=>q.add(K))},Q=({set:B},K,C)=>{B($,K,(N)=>{return N.delete(C),N}),B($,C,(N)=>{return N.delete(K),N});let[q,c]=[K,C].sort(),n=`${q}:${c}`;this.store.moleculeJoins.delete(n)},J=(B,K,C)=>{let{find:q,get:c,set:n}=B,N=q($,K),s=c(N);for(let p of s){if(C.includes(p))continue;n($,p,(t)=>{return t.delete(K),t})}n(N,(p)=>{return p.transaction((t)=>{t.clear();for(let I0 of C){let h0=W(B,I0),$1=h0.has(K);if(this.relations.cardinality==="1:n"){let r1=[];for(let T of h0){if(T===K)continue;let m=W(B,T);if(m.delete(I0),m.size===0)r1.push(T)}if(!$1&&h0.size>0)h0.clear();for(let T of r1){let[m,$0]=[I0,T].sort(),V0=`${m}:${$0}`;X.moleculeJoins.delete(V0)}}if(!$1)h0.add(K);t.add(I0)}return!0}),p})},z=(B,K,C)=>{let{set:q}=B;q($,K,(c)=>{return c.transaction((n)=>{for(let N of C)n.add(N);return!0}),c});for(let c of C)q($,c,(n)=>{return n.add(K),n});return!0},U=(B,K,C)=>{let q=W(B,K);return C?q.has(C):q.size>0},O={getRelatedKeys:(B)=>W(this.toolkit,B),addRelation:(B,K)=>{this.store.moleculeJoins.set(`"${B}"`,Y.key),this.store.moleculeJoins.set(`"${K}"`,Y.key),H(this.toolkit,B,K)},deleteRelation:(B,K)=>{Q(this.toolkit,B,K)},replaceRelationsSafely:(B,K)=>{J(this.toolkit,B,K)},replaceRelationsUnsafely:(B,K)=>{z(this.toolkit,B,K)},has:(B,K)=>U(this.toolkit,B,K)},L,w;if(Z){w=O2(X,{key:`${Y.key}/content`,default:Z},["join","content"]);let B=({get:C},q)=>C(w,q),K=({set:C},q,c)=>{C(w,q,c)};L=Object.assign(O,{getContent:(C)=>{return B(this.toolkit,C)},setContent:(C,q)=>{K(this.toolkit,C,q)},deleteContent:(C)=>{}})}else L=O;let R=new $4(Y,{externalStore:L,isAType:Y.isAType,isBType:Y.isBType,makeContentKey:(...B)=>{let[K,C]=B,[q,c]=B.sort(),n=`${q}:${c}`,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,n,"all"),this.realm.claim(C,n),this.store.moleculeJoins.set(n,Y.key),n}}),b=()=>f4(X,{key:`${Y.key}/singleRelatedKey`,get:(B)=>({get:K})=>{let C=K($,B);for(let q of C)return q;return null}},["join","keys"]),x=()=>{return f4(X,{key:`${Y.key}/multipleRelatedKeys`,get:(B)=>({get:K})=>{let C=m_($,X);return K(C,B).members}},["join","keys"])},h=()=>f4(X,{key:`${Y.key}/singleRelatedEntry`,get:(B)=>({get:K})=>{let C=K($,B);for(let q of C){let c=R.isAType?.(B)?B:void 0,n=c===void 0?B:void 0;c??=q,n??=q;let N=R.makeContentKey(c,n),s=K(w,N);return[q,s]}return null}},["join","entries"]),g=()=>f4(X,{key:`${Y.key}/multipleRelatedEntries`,get:(B)=>({get:K})=>{let C=m_($,X);return K(C,B).members.map((q)=>{let c=R.isAType?.(B)?B:void 0,n=c===void 0?B:void 0;c??=q,n??=q;let N=R.makeContentKey(c,n),s=K(w,N);return[q,s]})}},["join","entries"]);switch(Y.cardinality){case"1:1":{let B=b(),K=`${G}KeyOf${K0(_)}`,C=`${_}KeyOf${K0(G)}`,q={[K]:B,[C]:B},c;if(Z){let n=h(),N=`${G}EntryOf${K0(_)}`,s=`${_}EntryOf${K0(G)}`,p={[N]:n,[s]:n};c=Object.assign(q,p)}else c=q;this.relations=R,this.states=c;break}case"1:n":{let B=b(),K=x(),C=`${G}KeyOf${K0(_)}`,q=`${_}KeysOf${K0(G)}`,c={[C]:B,[q]:K},n;if(Z){let N=h(),s=g(),p=`${G}EntryOf${K0(_)}`,t=`${_}EntriesOf${K0(G)}`,I0={[p]:N,[t]:s};n=Object.assign(c,I0)}else n=c;this.relations=R,this.states=n;break}case"n:n":{let B=x(),K=`${G}KeysOf${K0(_)}`,C=`${_}KeysOf${K0(G)}`,q={[K]:B,[C]:B},c;if(Z){let n=g(),N=`${G}EntriesOf${K0(_)}`,s=`${_}EntriesOf${K0(G)}`,p={[N]:n,[s]:n};c=Object.assign(q,p)}else c=q;this.relations=R,this.states=c}}}};function h_(Y,Z,X){return Y.joins.set(Z.key,new G7(Z,X,Y)),{key:Z.key,type:"join",a:Z.between[0],b:Z.between[1],cardinality:Z.cardinality}}function G5(Y,Z){let X=Z.joins.get(Y.key);if(X===void 0){let G=U1.STORE.joins.get(Y.key);if(G===void 0)throw Error(`Join "${Y.key}" not found in store "${Z.config.name}"`);let _=dF(Z);X=new G7(G.options,G.defaultContent,_),Z.joins.set(Y.key,X)}return X}function W8(Y,Z,X){let G=G5(Y,X),_=Y0(X);if(E1(_)){let{toolkit:$}=_.transactionMeta;G.transact($,({relations:W})=>{Z(W)})}else Z(G.relations)}function uF(Y,Z,X){let G=G5(Y,X),_;switch(Y.cardinality){case"1:1":{let $=`${Y.a}KeyOf${K0(Y.b)}`,W=`${Y.b}KeyOf${K0(Y.a)}`;_={get[$](){let Q=G.states[$];return j0(X,Q,Z)},get[W](){let Q=G.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntryOf${K0(Y.b)}`;if(H in G.states){let Q=`${Y.b}EntryOf${K0(Y.a)}`;Object.assign(_,{get[H](){let J=G.states[H];return j0(X,J,Z)},get[Q](){let J=G.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)}`;_={get[$](){let Q=G.states[$];return j0(X,Q,Z)},get[W](){let Q=G.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntryOf${K0(Y.b)}`;if(H in G.states){let Q=`${Y.b}EntriesOf${K0(Y.a)}`;Object.assign(_,{get[H](){let J=G.states[H];return j0(X,J,Z)},get[Q](){let J=G.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)}`;_={get[$](){let Q=G.states[$];return j0(X,Q,Z)},get[W](){let Q=G.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntriesOf${K0(Y.b)}`;if(H in G.states){let Q=`${Y.b}EntriesOf${K0(Y.a)}`;Object.assign(_,{get[H](){let J=G.states[H];return j0(X,J,Z)},get[Q](){let J=G.states[Q];return j0(X,J,Z)}})}}}return _}function k_(Y,Z){return G5(Y,Z).core.relatedKeysAtoms}function _7(Y){let Z={},X=0;for(let G of Y)Z[G]=X,Z[X]=G,++X;return Z}var $7="\x01",W7="\x02",H7="\x03",J7="\x04",_5=(Y)=>{switch(typeof Y){case"string":return H7+Y;case"number":return J7+Y;case"boolean":return $7+ +Y;case"object":return W7}},$5=(Y)=>{switch(Y[0]){case H7:return Y.slice(1);case J7:return+Y.slice(1);case $7:return Y.slice(1)==="1";case W7:return null}};var NU=(Y)=>{return x4(Y,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Z=new Map;for(let[X,G]of Y.atoms){if(L2(X))continue;let _=y1(G);if(G.family){let $=Z.get(G.family.key);if(!$||!("familyMembers"in $))$={key:G.family.key,familyMembers:new Map},Z.set(G.family.key,$);$.familyMembers.set(G.family.subKey,_)}else Z.set(X,_)}return Z},effects:[({setSelf:Z})=>{Y.on.atomCreation.subscribe("introspection",(X)=>{if(L2(X.key))return;Z((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W===void 0||!("familyMembers"in W))W={key:_,familyMembers:new Map},G.set(_,W);W.familyMembers.set($,X)}else G.set(X.key,X);return new Map(G)})}),Y.on.atomDisposal.subscribe("introspection",(X)=>{Z((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)G.delete(_)}}return new Map(G)})})}]},void 0)},IU=(Y)=>{return x4(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(L2(G))continue;let $=y1(_);if(_.family){let W=Z.get(_.family.key);if(!W||!("familyMembers"in W))W={key:_.family.key,familyMembers:new Map},Z.set(_.family.key,W);W.familyMembers.set(_.family.subKey,$)}else Z.set(G,$)}return Z},effects:[({setSelf:Z})=>{Y.on.selectorCreation.subscribe("introspection",(X)=>{if(L2(X.key))return;Z((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W===void 0||!("familyMembers"in W))W={key:_,familyMembers:new Map},G.set(_,W);W.familyMembers.set($,X)}else G.set(X.key,X);return new Map(G)})}),Y.on.selectorDisposal.subscribe("introspection",(X)=>{Z((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)G.delete(_)}}else G.delete(X.key);return new Map(G)})})}]},void 0)};var W5=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(G){try{if(Y instanceof X)return{type:Z,data:Y}}catch(_){}}return null}},z7=new W5({number:(Y)=>typeof Y==="number",string:(Y)=>typeof Y==="string",boolean:(Y)=>typeof Y==="boolean",null:(Y)=>Y===null});function F7(Y){if(!Y)return!1;return Object.getPrototypeOf(Y)===Object.prototype}var U7=new W5({object:F7,array:(Y)=>Array.isArray(Y)}),KU=new W5({...z7.supported,...U7.supported}),C6=(Y)=>{if(Y===void 0)return"undefined";let Z=KU.refine(Y);if(Z)return Z.type;return Object.getPrototypeOf(Y).constructor.name};var zB=class Y{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Z=U1.STORE){this.store=Z,this.atomIndex=NU(this.store),this.selectorIndex=IU(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 Error("This Auditor has been disposed");let X=hZ(this.atomIndex),G=hZ(this.selectorIndex),_=[...X.values()].filter((Q)=>("familyMembers"in Q)),$=[...G.values()].filter((Q)=>("familyMembers"in Q)),W=performance.now(),H=[];if(Z.atomFamilies)for(let Q of _){let J=Q.familyMembers.values();for(let z of J){let U=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,O=W-U;H.push([z,O])}}if(Z.selectorFamilies)for(let Q of $){let J=Q.familyMembers.values();for(let z of J){let U=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,O=W-U;H.push([z,O])}}return H}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},Q7=(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(_)?_.map((Q,J)=>[J,Q]):F7(_)?Object.entries(_):[];for(let[Q,J]of H){let z=X([...G,Q],J);if(z?.jobComplete)return z}return{}};X([],Y)};function BU(Y,Z){return{summary:`${Y<Z?"+":"-"}${Math.abs(Y-Z)} (${Y} \u2192 ${Z})`}}function TU(Y,Z){return{summary:`${Y.length<Z.length?"+":"-"}${Math.abs(Y.length-Z.length)} ("${Y}" \u2192 "${Z}")`}}function CU(Y,Z){return{summary:`${Y} \u2192 ${Z}`}}function E7(Y,Z,X){let G="",_=[],$=[],W=[];return Q7(Y,(H,Q)=>{let J;for(J of H){let z=Z[J];if(z===void 0)$.push([J,JSON.stringify(Q)]);else{let U=X(Q,z);if(U.summary!=="No Change")W.push([J,U])}}}),Q7(Z,(H,Q)=>{let J;for(J of H)if(Y[J]===void 0)_.push([J,JSON.stringify(Q)])}),G=`\uFF5E${W.length} \uFF0B${_.length} \uFF0D${$.length}`,{summary:G,added:_,removed:$,changed:W}}function qU(Y,Z,X){return E7(Y,Z,X)}var jU=class{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(Y,Z,X){this.leafRefinery=Y,this.treeRefinery=Z,this.leafDiffers={},this.treeDiffers={};for(let G of Object.keys(Y.supported)){let _=X[G];this.leafDiffers[G]=_}for(let G of Object.keys(Z.supported)){let _=X[G];this.treeDiffers[G]=_}}diff(Y,Z){if(Y===Z)return{summary:"No Change"};let X=this.leafRefinery.refine(Y)??this.treeRefinery.refine(Y),G=this.leafRefinery.refine(Z)??this.treeRefinery.refine(Z);if(X!==null&&G!==null){if(X.type===G.type){if(X.type in this.leafDiffers)return this.leafDiffers[X.type](X.data,G.data);if(X.type in this.treeDiffers)return this.treeDiffers[X.type](X.data,G.data,(W,H)=>this.diff(W,H))}}let _=C6(Y),$=C6(Z);if(_===$)return{summary:`${_} \u2192 ${$}`};return{summary:`Type change: ${_} \u2192 ${$}`}}},FB=new jU(z7,U7,{number:BU,string:TU,boolean:CU,null:()=>({summary:"No Change"}),object:E7,array:qU});var O7=_7(["add","delete","clear"]);function PU(Y){let Z=O7[Y.type]+"\x1F";if(Y.type==="clear")return Z+Y.values.map(_5).join("\x1E");return Z+_5(Y.value)}function V7(Y){let[Z,X]=Y.split("\x1F"),G=O7[Z];if(G==="clear")return{type:"clear",values:X.split("\x1E").map($5)};return{type:G,value:$5(X)}}var b4=class Y extends Set{mode="record";subject=new _0;constructor(Z){super(Z);if(Z instanceof Y);}READONLY_VIEW=this;toJSON(){return[...this]}static fromJSON(Z){return new Y(Z)}add(Z){let X=super.add(Z);if(this.mode==="record")this.emit({type:"add",value:Z});return X}clear(){let Z=this.mode==="record"?[...this]:null;if(super.clear(),Z)this.emit({type:"clear",values:Z})}delete(Z){let X=super.delete(Z);if(this.mode==="record")this.emit({type:"delete",value:Z});return X}subscribe(Z,X){return this.subject.subscribe(Z,X)}emit(Z){this.subject.next(PU(Z))}do(Z){this.mode="playback";let X=V7(Z);switch(X.type){case"add":this.add(X.value);break;case"delete":this.delete(X.value);break;case"clear":this.clear()}return this.mode="record",null}undo(Z){let X=V7(Z);switch(this.mode="playback",X.type){case"add":this.delete(X.value);break;case"delete":this.add(X.value);break;case"clear":{let G=X.values;for(let _ of G)this.add(_)}}return this.mode="record",null}};var SU=V2({key:"mutex",default:!1}),vU=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)}},AB=class Y{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Z){this.key=Z}static existing=new vU;static create(Z,X){let G=new Y(Z),{type:_,globals:$,actions:W,perspectives:H}=X(G),Q={type:_,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[X,G]=Z;this.perspectives.push({type:"realtime_perspective",resourceAtoms:X,viewAtoms:G})}break}return this}};var RB=E2({key:"usersInRoomIndex",class:b4}),D7=E2({key:"roomIndex",class:b4}),xU={enteredAtEpoch:0},V8=O6({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(Y)=>typeof Y==="string",isBType:(Y)=>typeof Y==="string"},xU),wB=D6({key:"usersInMyRoomView",get:(Y)=>({find:Z})=>{let X=C_(V8);return[Z(X,Y)]}});var SB=V2({key:"redactor",default:{occlude:(Y)=>Y}}),vB=V2({key:"unacknowledgedUpdates",default:()=>[]});var H5=class{listeners;globalListeners;handleEvent(...Y){let[Z,...X]=Y;for(let _ of this.globalListeners)_(Z,...X);let G=this.listeners.get(Z);if(G)for(let _ of G)_(...X)}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}},xB=class extends H5{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";proc;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}}}constructor(Y,Z,X){super((G,..._)=>{let $=JSON.stringify([G,..._])+"\x03",W=(H)=>{if(H.code==="EPIPE")console.error("EPIPE error during write",this.proc.stdin);this.proc.stdin.removeListener("error",W)};return this.proc.stdin.once("error",W),this.proc.stdin.write($),this});if(this.proc=Y,this.key=Z,this.logger=X??{info:(...G)=>{console.info(this.id,this.key,...G)},warn:(...G)=>{console.warn(this.id,this.key,...G)},error:(...G)=>{console.error(this.id,this.key,...G)}},this.proc.stdout.on("data",(G)=>{let _=G.toString();if(_==="ALIVE"){this.logger.info(_);return}let $=_.split("\x03"),W=$[0];$[0]=this.incompleteData+W;let H=0;for(let Q of $){if(Q==="")continue;try{let J=X1(Q);this.handleEvent(...J),this.incompleteData=""}catch(J){if(J instanceof Error)console.error(["\u274C Malformed data received from child process","",Q,"",J.message].join(`
60
- \u274C `));try{if(H===0){this.incompleteData=Q;let z=X1(W);this.handleEvent(...z),this.incompleteData=""}else this.incompleteData+=Q}catch(z){if(z instanceof Error)console.error(["\u274C Malformed data received from child process","",W,"",z.message].join(`
61
- \u274C `))}}++H}}),this.proc.stderr.on("data",(G)=>{let _=G.toString().split("\x03"),$=_[0];_[0]=this.incompleteData+$;let W=0;for(let H of _){if(H==="")continue;try{let Q=X1(H);this.handleLog(Q),this.incompleteData=""}catch(Q){if(Q instanceof Error)console.error(["\u274C Malformed log received from child process","",H,"",Q.message].join(`
62
- \u274C `));try{if(W===0){this.incompleteData=H;let J=X1($);this.handleLog(J),this.incompleteData=""}else this.incompleteData+=H}catch(J){if(J instanceof Error)console.error(["\u274C Malformed log received from child process...","",$,"",J.message].join(`
63
- \u274C `))}}++W}}),Y.pid)this.id=Y.pid.toString()}},fU=class extends H5{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(Y){super((...Z)=>{return this.out.next(Z),this});this.id=Y,this.in=new _0,this.out=new _0,this.in.subscribe("socket",(Z)=>{this.handleEvent(...Z)})}dispose(){for(let Y of this.disposalFunctions)Y()}},M7=class extends H5{incompleteData="";unprocessedEvents=[];relays;relayServices;proc;id="#####";log(...Y){this.proc.stderr.write(Q0(Y.map((Z)=>Z instanceof b4?`{ ${Z.toJSON().join(" | ")} }`:Z))+"\x03")}logger={info:(...Y)=>{this.log("i",...Y)},warn:(...Y)=>{this.log("w",...Y)},error:(...Y)=>{this.log("e",...Y)}};constructor(Y){super((Z,...X)=>{let G=JSON.stringify([Z,...X]);return this.proc.stdout.write(G+"\x03"),this});if(this.proc=Y,this.proc.stdin.resume(),this.relays=new Map,this.relayServices=[],this.proc.stdin.on("data",(Z)=>{let X=Z.toString().split("\x03"),G=X[0];X[0]=this.incompleteData+G;let _=0;for(let $ of X){if($==="")continue;try{let W=X1($);this.logger.info("\uD83C\uDFB0","received",W),this.handleEvent(...W),this.incompleteData=""}catch(W){if(W instanceof Error)this.logger.error(["received malformed data from parent process:","",$,"",W.message].join(`
64
- \u274C `));try{if(_===0){this.incompleteData=$;let H=X1(G);this.logger.info("\uD83C\uDFB0","received",H),this.handleEvent(...H),this.incompleteData=""}else this.incompleteData+=$}catch(H){if(H instanceof Error)this.logger.error(["received malformed data from parent process:","",G,"",H.message].join(`
65
- \u274C `))}}++_}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),this.proc.exit(0)}),this.proc.pid)this.id=this.proc.pid?.toString();this.on("user-joins",(Z)=>{this.logger.info("\uD83D\uDC64","user",Z,"joined");let X=`user::${Z}`,G=new fU(X);this.relays.set(Z,G),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let _ of this.relayServices){let $=_(G,X);if($)G.disposalFunctions.push($)}this.on(X,(..._)=>{G.in.next(_)}),G.out.subscribe("socket",(_)=>{this.emit(..._)})}),this.on("user-leaves",(Z)=>{let X=this.relays.get(Z);if(this.off(`relay:${Z}`),X)X.dispose(),this.relays.delete(Z)}),this.proc.stdout.write("ALIVE")}receiveRelay(Y){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(Y)}};var L7=new Map;var fB=L6({key:"joinRoom",do:(Y,Z,X,G)=>{let _={enteredAtEpoch:G};return W8(V8,($)=>{$.set({room:Z,user:X},_)},Y.env().store),_}}),hB=L6({key:"leaveRoom",do:({env:Y},Z,X)=>{W8(V8,(G)=>{G.delete({room:Z,user:X})},Y().store)}}),kB=L6({key:"destroyRoom",do:({set:Y,env:Z},X)=>{W8(V8,(_)=>{_.delete({room:X})},Z().store),Y(D7,(_)=>(_.delete(X),_));let G=L7.get(X);if(G)G.emit("exit"),L7.delete(X)}}),bB=V2({key:"sockets",default:null}),yB=E2({key:"socketsIndex",class:b4}),gB=E2({key:"usersIndex",class:b4}),pB=O6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(Y)=>Y.startsWith("user::"),isBType:(Y)=>Y.startsWith("socket::")}),mB=D6({key:"userMutualSituationalAwarenessIndexes",get:(Y)=>()=>{return[Y]}});var{file:sW,serve:sE}=globalThis.Bun;import{readFileSync as w7}from"fs";import{createServer as yU}from"http";import{createServer as gU}from"https";import{resolve as Q5}from"path";function A7(Y,Z){if(Y instanceof Promise)throw Error(Z)}function hU(Y,Z){let X={},G=[];for(let _ in Y){let $=Y[_]["~standard"].validate(Z[_]);if(A7($,`Validation must be synchronous, but ${_} returned a Promise.`),$.issues){G.push(...$.issues.map((W)=>({...W,message:W.message,path:[_,...W.path??[]]})));continue}X[_]=$.value}if(G.length)return{issues:G};return{value:X}}function J5(Y){let Z=Y.runtimeEnvStrict??Y.runtimeEnv??process.env;if(Y.emptyStringAsUndefined??!1){for(let[h,g]of Object.entries(Z))if(g==="")delete Z[h]}if(!!Y.skipValidation)return Z;let _=typeof Y.client==="object"?Y.client:{},$=typeof Y.server==="object"?Y.server:{},W=typeof Y.shared==="object"?Y.shared:{},H=Y.isServer??(typeof window>"u"||("Deno"in window)),Q=H?{...$,...W,..._}:{..._,...W},J=Y.createFinalSchema?.(Q,H)["~standard"].validate(Z)??hU(Q,Z);A7(J,"Validation must be synchronous");let z=Y.onValidationError??((h)=>{throw console.error("\u274C Invalid environment variables:",h),Error("Invalid environment variables")}),U=Y.onInvalidAccess??(()=>{throw Error("\u274C Attempted to access a server-side environment variable on the client")});if(J.issues)return z(J.issues);let O=(h)=>{if(!Y.clientPrefix)return!0;return!h.startsWith(Y.clientPrefix)&&!(h in W)},L=(h)=>{return H||!O(h)},w=(h)=>{return h==="__esModule"||h==="$$typeof"},R=(Y.extends??[]).reduce((h,g)=>{return Object.assign(h,g)},{}),b=Object.assign(R,J.value);return new Proxy(b,{get(h,g){if(typeof g!=="string")return;if(w(g))return;if(!L(g))return U(g);return Reflect.get(h,g)}})}var kU="__vite_start_time"in globalThis,bU=typeof window<"u",aB="vitest"in globalThis,W4=F1("string"),R7=F1('"true" | "false" | undefined'),g1=J5({isServer:!kU&&!bU,server:{CI:F1("string | undefined").pipe(Boolean),POSTGRES_USER:W4,POSTGRES_PASSWORD:W4,POSTGRES_DATABASE:W4,POSTGRES_HOST:W4,POSTGRES_PORT:W4.pipe((Y)=>Number.parseInt(Y,10)),BACKEND_PORT:W4.pipe((Y)=>Number.parseInt(Y,10)),RUN_WORKERS_FROM_SOURCE:R7.pipe((Y)=>Y==="true"),FRONTEND_PORT:W4.pipe((Y)=>Number.parseInt(Y,10)),FRONTEND_ORIGINS:W4.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:W4,VITE_DEV_FRONTEND_HOST:F1("string | undefined"),VITE_DEV_HTTPS:R7.pipe((Y)=>Y==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var N7=Q5(import.meta.dirname,"../dev"),q6=g1.VITE_DEV_HTTPS?{cert:w7(Q5(N7,"./cert.pem"),"utf-8"),key:w7(Q5(N7,"./key.pem"),"utf-8")}:void 0;function $T(Y){if(q6)return gU(q6,Y);return yU({},Y)}import dE 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 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 U0{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 z5{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 p1=Symbol.for("drizzle:Name");class F5{static[E]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(Y,Z){if(this.reference=()=>{let{name:X,columns:G,foreignColumns:_}=Y();return{name:X,columns:G,foreignTable:_[0].table,foreignColumns:_}},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 I7(Y,this)}}class I7{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(),G=Z.map((W)=>W.name),_=X.map((W)=>W.name),$=[this.table[p1],...G,X[0].table[p1],..._];return Y??`${$.join("_")}_fk`}}function j6(Y,...Z){return Y(...Z)}function K7(Y,Z){return`${Y[p1]}_${Z.join("_")}_unique`}function B7(Y,Z,X){for(let G=Z;G<Y.length;G++){let _=Y[G];if(_==="\\"){G++;continue}if(_==='"')return[Y.slice(Z,G).replace(/\\/g,""),G+1];if(X)continue;if(_===","||_==="}")return[Y.slice(Z,G).replace(/\\/g,""),G]}return[Y.slice(Z).replace(/\\/g,""),Y.length]}function T7(Y,Z=0){let X=[],G=Z,_=!1;while(G<Y.length){let $=Y[G];if($===","){if(_||G===Z)X.push("");_=!0,G++;continue}if(_=!1,$==="\\"){G+=2;continue}if($==='"'){let[Q,J]=B7(Y,G+1,!0);X.push(Q),G=J;continue}if($==="}")return[X,G+1];if($==="{"){let[Q,J]=T7(Y,G+1);X.push(Q),G=J;continue}let[W,H]=B7(Y,G,!1);X.push(W),G=H}return[X,G]}function C7(Y){let[Z]=T7(Y,1);return Z}function U5(Y){return`{${Y.map((Z)=>{if(Array.isArray(Z))return U5(Z);if(typeof Z==="string")return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Z}`}).join(",")}}`}class k extends z5{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(Y){return new j7(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:G})=>{return j6((_,$)=>{let W=new F5(()=>{let H=_();return{columns:[Y],foreignColumns:[H]}});if($.onUpdate)W.onUpdate($.onUpdate);if($.onDelete)W.onDelete($.onDelete);return W.build(Z)},X,G)})}buildExtraConfigColumn(Y){return new q7(Y,this.config)}}class j extends U0{constructor(Y,Z){if(!Z.uniqueName)Z.uniqueName=K7(Y,[Z.name]);super(Y,Z);this.table=Y}static[E]="PgColumn"}class q7 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 O8{static[E]="IndexedColumn";constructor(Y,Z,X,G){this.name=Y,this.keyAsName=Z,this.type=X,this.indexConfig=G}name;keyAsName;type;indexConfig}class j7 extends k{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 E5(Y,this.config,Z)}}class E5 extends j{constructor(Y,Z,X,G){super(Y,Z);this.baseColumn=X,this.range=G,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=C7(Y);return Y.map((Z)=>this.baseColumn.mapFromDriverValue(Z))}mapToDriverValue(Y,Z=!1){let X=Y.map((G)=>G===null?null:M(this.baseColumn,E5)?this.baseColumn.mapToDriverValue(G,!0):this.baseColumn.mapToDriverValue(G));if(Z)return X;return U5(X)}}class P7 extends k{static[E]="PgEnumObjectColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumObjectColumn");this.config.enum=Z}build(Y){return new S7(Y,this.config)}}class S7 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 P6=Symbol.for("drizzle:isPgEnum");function v7(Y){return!!Y&&typeof Y==="function"&&P6 in Y&&Y[P6]===!0}class x7 extends k{static[E]="PgEnumColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumColumn");this.config.enum=Z}build(Y){return new f7(Y,this.config)}}class f7 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)?pU(Y,[...Z],void 0):mU(Y,Z,void 0)}function pU(Y,Z,X){let G=Object.assign((_)=>new x7(_??"",G),{enumName:Y,enumValues:Z,schema:X,[P6]:!0});return G}function mU(Y,Z,X){let G=Object.assign((_)=>new P7(_??"",G),{enumName:Y,enumValues:Object.values(Z),schema:X,[P6]:!0});return G}class S0{static[E]="Subquery";constructor(Y,Z,X,G=!1,_=[]){this._={brand:"Subquery",sql:Y,selectedFields:Z,alias:X,isWith:G,usedTables:_}}}class L8 extends S0{static[E]="WithSubquery"}var h7="0.44.5";var V5,O5,E0={startActiveSpan(Y,Z){if(!V5)return Z();if(!O5)O5=V5.trace.getTracer("drizzle-orm",h7);return j6((X,G)=>G.startActiveSpan(Y,(_)=>{try{return Z(_)}catch($){throw _.setStatus({code:X.SpanStatusCode.ERROR,message:$ instanceof Error?$.message:"Unknown error"}),$}finally{_.end()}}),V5,O5)}};var M0=Symbol.for("drizzle:ViewBaseConfig");var y4=Symbol.for("drizzle:Schema"),S6=Symbol.for("drizzle:Columns"),k7=Symbol.for("drizzle:ExtraConfigColumns"),D5=Symbol.for("drizzle:OriginalName"),L5=Symbol.for("drizzle:BaseName"),M8=Symbol.for("drizzle:IsAlias"),b7=Symbol.for("drizzle:ExtraConfigBuilder"),uU=Symbol.for("drizzle:IsDrizzleTable");class P{static[E]="Table";static Symbol={Name:p1,Schema:y4,OriginalName:D5,Columns:S6,ExtraConfigColumns:k7,BaseName:L5,IsAlias:M8,ExtraConfigBuilder:b7};[p1];[D5];[y4];[S6];[k7];[L5];[M8]=!1;[uU]=!0;[b7]=void 0;constructor(Y,Z,X){this[p1]=this[D5]=Y,this[y4]=Z,this[L5]=X}}function d0(Y){return Y[p1]}function g4(Y){return`${Y[y4]??"public"}.${Y[p1]}`}function M5(Y){return Y!==null&&Y!==void 0&&typeof Y.getSQL==="function"}function dU(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 f([this])}}class f{constructor(Y){this.queryChunks=Y;for(let Z of Y)if(M(Z,P)){let X=Z[P.Symbol.Schema];this.usedTables.push(X===void 0?Z[P.Symbol.Name]:X+"."+Z[P.Symbol.Name])}}static[E]="SQL";decoder=g7;shouldInlineParams=!1;usedTables=[];append(Y){return this.queryChunks.push(...Y.queryChunks),this}toQuery(Y){return E0.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:G,escapeName:_,escapeParam:$,prepareTyping:W,inlineParams:H,paramStartIndex:Q}=X;return dU(Y.map((J)=>{if(M(J,m0))return{sql:J.value.join(""),params:[]};if(M(J,v6))return{sql:_(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let z=[new m0("(")];for(let[U,O]of J.entries())if(z.push(O),U<J.length-1)z.push(new m0(", "));return z.push(new m0(")")),this.buildQueryFromSourceParams(z,X)}if(M(J,f))return this.buildQueryFromSourceParams(J.queryChunks,{...X,inlineParams:H||J.shouldInlineParams});if(M(J,P)){let z=J[P.Symbol.Schema],U=J[P.Symbol.Name];return{sql:z===void 0||J[M8]?_(U):_(z)+"."+_(U),params:[]}}if(M(J,U0)){let z=G.getColumnCasing(J);if(Z.invokeSource==="indexes")return{sql:_(z),params:[]};let U=J.table[P.Symbol.Schema];return{sql:J.table[M8]||U===void 0?_(J.table[P.Symbol.Name])+"."+_(z):_(U)+"."+_(J.table[P.Symbol.Name])+"."+_(z),params:[]}}if(M(J,V1)){let z=J[M0].schema,U=J[M0].name;return{sql:z===void 0||J[M0].isAlias?_(U):_(z)+"."+_(U),params:[]}}if(M(J,A1)){if(M(J.value,w4))return{sql:$(Q.value++,J),params:[J],typings:["none"]};let z=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(M(z,f))return this.buildQueryFromSourceParams([z],X);if(H)return{sql:this.mapInlineParam(z,X),params:[]};let U=["none"];if(W)U=[W(J.encoder)];return{sql:$(Q.value++,z),params:[z],typings:U}}if(M(J,w4))return{sql:$(Q.value++,J),params:[J],typings:["none"]};if(M(J,f.Aliased)&&J.fieldAlias!==void 0)return{sql:_(J.fieldAlias),params:[]};if(M(J,S0)){if(J._.isWith)return{sql:_(J._.alias),params:[]};return this.buildQueryFromSourceParams([new m0("("),J._.sql,new m0(") "),new v6(J._.alias)],X)}if(v7(J)){if(J.schema)return{sql:_(J.schema)+"."+_(J.enumName),params:[]};return{sql:_(J.enumName),params:[]}}if(M5(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 Error("Unexpected param value: "+Y)}getSQL(){return this}as(Y){if(Y===void 0)return this;return new f.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 v6{constructor(Y){this.value=Y}static[E]="Name";brand;getSQL(){return new f([this])}}function y7(Y){return typeof Y==="object"&&Y!==null&&"mapToDriverValue"in Y&&typeof Y.mapToDriverValue==="function"}var g7={mapFromDriverValue:(Y)=>Y},p7={mapToDriverValue:(Y)=>Y},nT={...g7,...p7};class A1{constructor(Y,Z=p7){this.value=Y,this.encoder=Z}static[E]="Param";brand;getSQL(){return new f([this])}}function V(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(_,new m0(Y[G+1]));return new f(X)}((Y)=>{function Z(){return new f([])}Y.empty=Z;function X(Q){return new f(Q)}Y.fromList=X;function G(Q){return new f([new m0(Q)])}Y.raw=G;function _(Q,J){let z=[];for(let[U,O]of Q.entries()){if(U>0&&J!==void 0)z.push(J);z.push(O)}return new f(z)}Y.join=_;function $(Q){return new v6(Q)}Y.identifier=$;function W(Q){return new w4(Q)}Y.placeholder=W;function H(Q,J){return new A1(Q,J)}Y.param=H})(V||(V={}));((Y)=>{class Z{constructor(X,G){this.sql=X,this.fieldAlias=G}static[E]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Z(this.sql,this.fieldAlias)}}Y.Aliased=Z})(f||(f={}));class w4{constructor(Y){this.name=Y}static[E]="Placeholder";getSQL(){return new f([this])}}function A5(Y,Z){return Y.map((X)=>{if(M(X,w4)){if(!(X.name in Z))throw Error(`No value for placeholder "${X.name}" was provided`);return Z[X.name]}if(M(X,A1)&&M(X.value,w4)){if(!(X.value.name in Z))throw Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue(Z[X.value.name])}return X})}var cU=Symbol.for("drizzle:IsDrizzleView");class V1{static[E]="View";[M0];[cU]=!0;constructor({name:Y,schema:Z,selectedFields:X,query:G}){this[M0]={name:Y,originalName:Y,schema:Z,selectedFields:X,query:G,isExisting:!G,isAlias:!1}}getSQL(){return new f([this])}}U0.prototype.getSQL=function(){return new f([this])};P.prototype.getSQL=function(){return new f([this])};S0.prototype.getSQL=function(){return new f([this])};class M2{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===P.Symbol.IsAlias)return!0;if(Z===P.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Z===P.Symbol.OriginalName)return this.alias;if(Z===M0)return{...Y[M0],name:this.alias,isAlias:!0};if(Z===P.Symbol.Columns){let G=Y[P.Symbol.Columns];if(!G)return G;let _={};return Object.keys(G).map(($)=>{_[$]=new Proxy(G[$],new M2(new Proxy(Y,this)))}),_}let X=Y[Z];if(M(X,U0))return new Proxy(X,new M2(new Proxy(Y,this)));return X}}function x6(Y,Z){return new Proxy(Y,new A8(Z,!1))}function i1(Y,Z){return new Proxy(Y,new M2(new Proxy(Y.table,new A8(Z,!1))))}function R5(Y,Z){return new f.Aliased(R8(Y.sql,Z),Y.fieldAlias)}function R8(Y,Z){return V.join(Y.queryChunks.map((X)=>{if(M(X,U0))return i1(X,Z);if(M(X,f))return R8(X,Z);if(M(X,f.Aliased))return R5(X,Z);return X}))}class f6 extends Error{static[E]="DrizzleError";constructor({message:Y,cause:Z}){super(Y);this.name="DrizzleError",this.cause=Z}}class H4 extends Error{constructor(Y,Z,X){super(`Failed query: ${Y}
66
- params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrace(this,H4),X)this.cause=X}}class w5 extends f6{static[E]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class m7{static[E]="ConsoleLogWriter";write(Y){console.log(Y)}}class N5{static[E]="DefaultLogger";writer;constructor(Y){this.writer=Y?.writer??new m7}logQuery(Y,Z){let X=Z.map((_)=>{try{return JSON.stringify(_)}catch{return String(_)}}),G=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${Y}${G}`)}}class I5{static[E]="NoopLogger";logQuery(){}}class G1{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 u7(Y,Z,X){let G={},_=Y.reduce(($,{path:W,field:H},Q)=>{let J;if(M(H,U0))J=H;else if(M(H,f))J=H.decoder;else J=H.sql.decoder;let z=$;for(let[U,O]of W.entries())if(U<W.length-1){if(!(O in z))z[O]={};z=z[O]}else{let L=Z[Q],w=z[O]=L===null?null:J.mapFromDriverValue(L);if(X&&M(H,U0)&&W.length===2){let R=W[0];if(!(R in G))G[R]=w===null?d0(H.table):!1;else if(typeof G[R]==="string"&&G[R]!==d0(H.table))G[R]=!1}}return $},{});if(X&&Object.keys(G).length>0){for(let[$,W]of Object.entries(G))if(typeof W==="string"&&!X[W])_[$]=null}return _}function T1(Y,Z){return Object.entries(Y).reduce((X,[G,_])=>{if(typeof G!=="string")return X;let $=Z?[...Z,G]:[G];if(M(_,U0)||M(_,f)||M(_,f.Aliased))X.push({path:$,field:_});else if(M(_,P))X.push(...T1(_[P.Symbol.Columns],$));else X.push(...T1(_,$));return X},[])}function w8(Y,Z){let X=Object.keys(Y),G=Object.keys(Z);if(X.length!==G.length)return!1;for(let[_,$]of X.entries())if($!==G[_])return!1;return!0}function h6(Y,Z){let X=Object.entries(Z).filter(([,G])=>G!==void 0).map(([G,_])=>{if(M(_,f)||M(_,U0))return[G,_];else return[G,new A1(_,Y[P.Symbol.Columns][G])]});if(X.length===0)throw Error("No values to set");return Object.fromEntries(X)}function d7(Y,Z){for(let X of Z)for(let G of Object.getOwnPropertyNames(X.prototype)){if(G==="constructor")continue;Object.defineProperty(Y.prototype,G,Object.getOwnPropertyDescriptor(X.prototype,G)||Object.create(null))}}function c7(Y){return Y[P.Symbol.Columns]}function J4(Y){return M(Y,S0)?Y._.alias:M(Y,V1)?Y[M0].name:M(Y,f)?void 0:Y[P.Symbol.IsAlias]?Y[P.Symbol.Name]:Y[P.Symbol.BaseName]}function X0(Y,Z){return{name:typeof Y==="string"&&Y.length>0?Y:"",config:typeof Y==="object"?Y:Z}}function l7(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 N4 extends k{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 o7 extends N4{static[E]="PgBigInt53Builder";constructor(Y){super(Y,"number","PgBigInt53")}build(Y){return new i7(Y,this.config)}}class i7 extends j{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class n7 extends N4{static[E]="PgBigInt64Builder";constructor(Y){super(Y,"bigint","PgBigInt64")}build(Y){return new r7(Y,this.config)}}class r7 extends j{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(Y){return BigInt(Y)}}function s7(Y,Z){let{name:X,config:G}=X0(Y,Z);if(G.mode==="number")return new o7(X);return new n7(X)}class t7 extends k{static[E]="PgBigSerial53Builder";constructor(Y){super(Y,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new a7(Y,this.config)}}class a7 extends j{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class e7 extends k{static[E]="PgBigSerial64Builder";constructor(Y){super(Y,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(Y){return new Y$(Y,this.config)}}class Y$ extends j{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(Y){return BigInt(Y)}}function Z$(Y,Z){let{name:X,config:G}=X0(Y,Z);if(G.mode==="number")return new t7(X);return new e7(X)}class X$ extends k{static[E]="PgBooleanBuilder";constructor(Y){super(Y,"boolean","PgBoolean")}build(Y){return new G$(Y,this.config)}}class G$ extends j{static[E]="PgBoolean";getSQLType(){return"boolean"}}function N8(Y){return new X$(Y??"")}class _$ extends k{static[E]="PgCharBuilder";constructor(Y,Z){super(Y,"string","PgChar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new $$(Y,this.config)}}class $$ extends j{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function W$(Y,Z={}){let{name:X,config:G}=X0(Y,Z);return new _$(X,G)}class H$ extends k{static[E]="PgCidrBuilder";constructor(Y){super(Y,"string","PgCidr")}build(Y){return new J$(Y,this.config)}}class J$ extends j{static[E]="PgCidr";getSQLType(){return"cidr"}}function Q$(Y){return new H$(Y??"")}class z$ extends k{static[E]="PgCustomColumnBuilder";constructor(Y,Z,X){super(Y,"custom","PgCustomColumn");this.config.fieldConfig=Z,this.config.customTypeParams=X}build(Y){return new F$(Y,this.config)}}class F$ 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 U$(Y){return(Z,X)=>{let{name:G,config:_}=X0(Z,X);return new z$(G,_,Y)}}class Q4 extends k{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(V`now()`)}}class E$ extends Q4{static[E]="PgDateBuilder";constructor(Y){super(Y,"date","PgDate")}build(Y){return new k6(Y,this.config)}}class k6 extends j{static[E]="PgDate";getSQLType(){return"date"}mapFromDriverValue(Y){return new Date(Y)}mapToDriverValue(Y){return Y.toISOString()}}class V$ extends Q4{static[E]="PgDateStringBuilder";constructor(Y){super(Y,"string","PgDateString")}build(Y){return new b6(Y,this.config)}}class b6 extends j{static[E]="PgDateString";getSQLType(){return"date"}}function O$(Y,Z){let{name:X,config:G}=X0(Y,Z);if(G?.mode==="date")return new E$(X);return new V$(X)}class D$ extends k{static[E]="PgDoublePrecisionBuilder";constructor(Y){super(Y,"number","PgDoublePrecision")}build(Y){return new L$(Y,this.config)}}class L$ extends j{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function M$(Y){return new D$(Y??"")}class A$ extends k{static[E]="PgInetBuilder";constructor(Y){super(Y,"string","PgInet")}build(Y){return new R$(Y,this.config)}}class R$ extends j{static[E]="PgInet";getSQLType(){return"inet"}}function w$(Y){return new A$(Y??"")}class N$ extends N4{static[E]="PgIntegerBuilder";constructor(Y){super(Y,"number","PgInteger")}build(Y){return new I$(Y,this.config)}}class I$ 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 N$(Y??"")}class K$ extends k{static[E]="PgIntervalBuilder";constructor(Y,Z){super(Y,"string","PgInterval");this.config.intervalConfig=Z}build(Y){return new B$(Y,this.config)}}class B$ 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 T$(Y,Z={}){let{name:X,config:G}=X0(Y,Z);return new K$(X,G)}class C$ extends k{static[E]="PgJsonBuilder";constructor(Y){super(Y,"json","PgJson")}build(Y){return new y6(Y,this.config)}}class y6 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 q$(Y){return new C$(Y??"")}class j$ extends k{static[E]="PgJsonbBuilder";constructor(Y){super(Y,"json","PgJsonb")}build(Y){return new g6(Y,this.config)}}class g6 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 P$(Y){return new j$(Y??"")}class S$ extends k{static[E]="PgLineBuilder";constructor(Y){super(Y,"array","PgLine")}build(Y){return new v$(Y,this.config)}}class v$ extends j{static[E]="PgLine";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,G]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X),Number.parseFloat(G)]}mapToDriverValue(Y){return`{${Y[0]},${Y[1]},${Y[2]}}`}}class x$ extends k{static[E]="PgLineABCBuilder";constructor(Y){super(Y,"json","PgLineABC")}build(Y){return new f$(Y,this.config)}}class f$ extends j{static[E]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,G]=Y.slice(1,-1).split(",");return{a:Number.parseFloat(Z),b:Number.parseFloat(X),c:Number.parseFloat(G)}}mapToDriverValue(Y){return`{${Y.a},${Y.b},${Y.c}}`}}function h$(Y,Z){let{name:X,config:G}=X0(Y,Z);if(!G?.mode||G.mode==="tuple")return new S$(X);return new x$(X)}class k$ extends k{static[E]="PgMacaddrBuilder";constructor(Y){super(Y,"string","PgMacaddr")}build(Y){return new b$(Y,this.config)}}class b$ extends j{static[E]="PgMacaddr";getSQLType(){return"macaddr"}}function y$(Y){return new k$(Y??"")}class g$ extends k{static[E]="PgMacaddr8Builder";constructor(Y){super(Y,"string","PgMacaddr8")}build(Y){return new p$(Y,this.config)}}class p$ extends j{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}}function m$(Y){return new g$(Y??"")}class u$ extends k{static[E]="PgNumericBuilder";constructor(Y,Z,X){super(Y,"string","PgNumeric");this.config.precision=Z,this.config.scale=X}build(Y){return new p6(Y,this.config)}}class p6 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 d$ extends k{static[E]="PgNumericNumberBuilder";constructor(Y,Z,X){super(Y,"number","PgNumericNumber");this.config.precision=Z,this.config.scale=X}build(Y){return new c$(Y,this.config)}}class c$ 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 l$ extends k{static[E]="PgNumericBigIntBuilder";constructor(Y,Z,X){super(Y,"bigint","PgNumericBigInt");this.config.precision=Z,this.config.scale=X}build(Y){return new o$(Y,this.config)}}class o$ 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 i$(Y,Z){let{name:X,config:G}=X0(Y,Z),_=G?.mode;return _==="number"?new d$(X,G?.precision,G?.scale):_==="bigint"?new l$(X,G?.precision,G?.scale):new u$(X,G?.precision,G?.scale)}class n$ extends k{static[E]="PgPointTupleBuilder";constructor(Y){super(Y,"array","PgPointTuple")}build(Y){return new r$(Y,this.config)}}class r$ 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 s$ extends k{static[E]="PgPointObjectBuilder";constructor(Y){super(Y,"json","PgPointObject")}build(Y){return new t$(Y,this.config)}}class t$ 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 a$(Y,Z){let{name:X,config:G}=X0(Y,Z);if(!G?.mode||G.mode==="tuple")return new n$(X);return new s$(X)}function lU(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 e$(Y,Z){let X=new ArrayBuffer(8),G=new DataView(X);for(let _=0;_<8;_++)G.setUint8(_,Y[Z+_]);return G.getFloat64(0,!0)}function K5(Y){let Z=lU(Y),X=0,G=Z[X];X+=1;let _=new DataView(Z.buffer),$=_.getUint32(X,G===1);X+=4;let W;if($&536870912)W=_.getUint32(X,G===1),X+=4;if(($&65535)===1){let H=e$(Z,X);X+=8;let Q=e$(Z,X);return X+=8,[H,Q]}throw Error("Unsupported geometry type")}class Y3 extends k{static[E]="PgGeometryBuilder";constructor(Y){super(Y,"array","PgGeometry")}build(Y){return new Z3(Y,this.config)}}class Z3 extends j{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){return K5(Y)}mapToDriverValue(Y){return`point(${Y[0]} ${Y[1]})`}}class X3 extends k{static[E]="PgGeometryObjectBuilder";constructor(Y){super(Y,"json","PgGeometryObject")}build(Y){return new G3(Y,this.config)}}class G3 extends j{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){let Z=K5(Y);return{x:Z[0],y:Z[1]}}mapToDriverValue(Y){return`point(${Y.x} ${Y.y})`}}function _3(Y,Z){let{name:X,config:G}=X0(Y,Z);if(!G?.mode||G.mode==="tuple")return new Y3(X);return new X3(X)}class $3 extends k{static[E]="PgRealBuilder";constructor(Y,Z){super(Y,"number","PgReal");this.config.length=Z}build(Y){return new W3(Y,this.config)}}class W3 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 H3(Y){return new $3(Y??"")}class J3 extends k{static[E]="PgSerialBuilder";constructor(Y){super(Y,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new Q3(Y,this.config)}}class Q3 extends j{static[E]="PgSerial";getSQLType(){return"serial"}}function z3(Y){return new J3(Y??"")}class F3 extends N4{static[E]="PgSmallIntBuilder";constructor(Y){super(Y,"number","PgSmallInt")}build(Y){return new U3(Y,this.config)}}class U3 extends j{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number(Y);return Y}}function E3(Y){return new F3(Y??"")}class V3 extends k{static[E]="PgSmallSerialBuilder";constructor(Y){super(Y,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new O3(Y,this.config)}}class O3 extends j{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}}function D3(Y){return new V3(Y??"")}class L3 extends k{static[E]="PgTextBuilder";constructor(Y,Z){super(Y,"string","PgText");this.config.enumValues=Z.enum}build(Y){return new M3(Y,this.config)}}class M3 extends j{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function A3(Y,Z={}){let{name:X,config:G}=X0(Y,Z);return new L3(X,G)}class R3 extends Q4{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 m6(Y,this.config)}}class m6 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 w3(Y,Z={}){let{name:X,config:G}=X0(Y,Z);return new R3(X,G.withTimezone??!1,G.precision)}class N3 extends Q4{static[E]="PgTimestampBuilder";constructor(Y,Z,X){super(Y,"date","PgTimestamp");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new u6(Y,this.config)}}class u6 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 I3 extends Q4{static[E]="PgTimestampStringBuilder";constructor(Y,Z,X){super(Y,"string","PgTimestampString");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new d6(Y,this.config)}}class d6 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 K3(Y,Z={}){let{name:X,config:G}=X0(Y,Z);if(G?.mode==="string")return new I3(X,G.withTimezone??!1,G.precision);return new N3(X,G?.withTimezone??!1,G?.precision)}class B3 extends k{static[E]="PgUUIDBuilder";constructor(Y){super(Y,"string","PgUUID")}defaultRandom(){return this.default(V`gen_random_uuid()`)}build(Y){return new c6(Y,this.config)}}class c6 extends j{static[E]="PgUUID";getSQLType(){return"uuid"}}function C1(Y){return new B3(Y??"")}class T3 extends k{static[E]="PgVarcharBuilder";constructor(Y,Z){super(Y,"string","PgVarchar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new C3(Y,this.config)}}class C3 extends j{static[E]="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:G}=X0(Y,Z);return new T3(X,G)}class q3 extends k{static[E]="PgBinaryVectorBuilder";constructor(Y,Z){super(Y,"string","PgBinaryVector");this.config.dimensions=Z.dimensions}build(Y){return new j3(Y,this.config)}}class j3 extends j{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function P3(Y,Z){let{name:X,config:G}=X0(Y,Z);return new q3(X,G)}class S3 extends k{static[E]="PgHalfVectorBuilder";constructor(Y,Z){super(Y,"array","PgHalfVector");this.config.dimensions=Z.dimensions}build(Y){return new v3(Y,this.config)}}class v3 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 x3(Y,Z){let{name:X,config:G}=X0(Y,Z);return new S3(X,G)}class f3 extends k{static[E]="PgSparseVectorBuilder";constructor(Y,Z){super(Y,"string","PgSparseVector");this.config.dimensions=Z.dimensions}build(Y){return new h3(Y,this.config)}}class h3 extends j{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function k3(Y,Z){let{name:X,config:G}=X0(Y,Z);return new f3(X,G)}class b3 extends k{static[E]="PgVectorBuilder";constructor(Y,Z){super(Y,"array","PgVector");this.config.dimensions=Z.dimensions}build(Y){return new y3(Y,this.config)}}class y3 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 g3(Y,Z){let{name:X,config:G}=X0(Y,Z);return new b3(X,G)}function p3(){return{bigint:s7,bigserial:Z$,boolean:N8,char:W$,cidr:Q$,customType:U$,date:O$,doublePrecision:M$,inet:w$,integer:I8,interval:T$,json:q$,jsonb:P$,line:h$,macaddr:y$,macaddr8:m$,numeric:i$,point:a$,geometry:_3,real:H3,serial:z3,smallint:E3,smallserial:D3,text:A3,time:w3,timestamp:K3,uuid:C1,varchar:t0,bit:P3,halfvec:x3,sparsevec:k3,vector:g3}}var B5=Symbol.for("drizzle:PgInlineForeignKeys"),m3=Symbol.for("drizzle:EnableRLS");class u0 extends P{static[E]="PgTable";static Symbol=Object.assign({},P.Symbol,{InlineForeignKeys:B5,EnableRLS:m3});[B5]=[];[m3]=!1;[P.Symbol.ExtraConfigBuilder]=void 0;[P.Symbol.ExtraConfigColumns]={}}function oU(Y,Z,X,G,_=Y){let $=new u0(Y,G,_),W=typeof Z==="function"?Z(p3()):Z,H=Object.fromEntries(Object.entries(W).map(([z,U])=>{let O=U;O.setName(z);let L=O.build($);return $[B5].push(...O.buildForeignKeys(L,$)),[z,L]})),Q=Object.fromEntries(Object.entries(W).map(([z,U])=>{let O=U;O.setName(z);let L=O.buildExtraConfigColumn($);return[z,L]})),J=Object.assign($,H);if(J[P.Symbol.Columns]=H,J[P.Symbol.ExtraConfigColumns]=Q,X)J[u0.Symbol.ExtraConfigBuilder]=X;return Object.assign(J,{enableRLS:()=>{return J[u0.Symbol.EnableRLS]=!0,J}})}var I4=(Y,Z,X)=>{return oU(Y,Z,X,void 0)};function u3(...Y){if(Y[0].columns)return new K8(Y[0].columns,Y[0].name);return new K8(Y)}class K8{static[E]="PgPrimaryKeyBuilder";columns;name;constructor(Y,Z){this.columns=Y,this.name=Z}build(Y){return new d3(Y,this.columns,this.name)}}class d3{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 O1(Y,Z){if(y7(Z)&&!M5(Y)&&!M(Y,A1)&&!M(Y,w4)&&!M(Y,U0)&&!M(Y,P)&&!M(Y,V1))return new A1(Y,Z);return Y}var l6=(Y,Z)=>{return V`${Y} = ${O1(Z,Y)}`},c3=(Y,Z)=>{return V`${Y} <> ${O1(Z,Y)}`};function B8(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new f(Z);return new f([new m0("("),V.join(Z,new m0(" and ")),new m0(")")])}function l3(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new f(Z);return new f([new m0("("),V.join(Z,new m0(" or ")),new m0(")")])}function o3(Y){return V`not ${Y}`}var i3=(Y,Z)=>{return V`${Y} > ${O1(Z,Y)}`},n3=(Y,Z)=>{return V`${Y} >= ${O1(Z,Y)}`},r3=(Y,Z)=>{return V`${Y} < ${O1(Z,Y)}`},s3=(Y,Z)=>{return V`${Y} <= ${O1(Z,Y)}`};function t3(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return V`false`;return V`${Y} in ${Z.map((X)=>O1(X,Y))}`}return V`${Y} in ${O1(Z,Y)}`}function a3(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return V`true`;return V`${Y} not in ${Z.map((X)=>O1(X,Y))}`}return V`${Y} not in ${O1(Z,Y)}`}function e3(Y){return V`${Y} is null`}function YW(Y){return V`${Y} is not null`}function ZW(Y){return V`exists ${Y}`}function XW(Y){return V`not exists ${Y}`}function GW(Y,Z,X){return V`${Y} between ${O1(Z,Y)} and ${O1(X,Y)}`}function _W(Y,Z,X){return V`${Y} not between ${O1(Z,Y)} and ${O1(X,Y)}`}function $W(Y,Z){return V`${Y} like ${Z}`}function WW(Y,Z){return V`${Y} not like ${Z}`}function HW(Y,Z){return V`${Y} ilike ${Z}`}function JW(Y,Z){return V`${Y} not ilike ${Z}`}function QW(Y){return V`${Y} asc`}function zW(Y){return V`${Y} desc`}class T5{constructor(Y,Z,X){this.sourceTable=Y,this.referencedTable=Z,this.relationName=X,this.referencedTableName=Z[P.Symbol.Name]}static[E]="Relation";referencedTableName;fieldName}class FW{constructor(Y,Z){this.table=Y,this.config=Z}static[E]="Relations"}class K4 extends T5{constructor(Y,Z,X,G){super(Y,Z,X?.relationName);this.config=X,this.isNullable=G}static[E]="One";withFieldName(Y){let Z=new K4(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Z.fieldName=Y,Z}}class T8 extends T5{constructor(Y,Z,X){super(Y,Z,X?.relationName);this.config=X}static[E]="Many";withFieldName(Y){let Z=new T8(this.sourceTable,this.referencedTable,this.config);return Z.fieldName=Y,Z}}function UW(){return{and:B8,between:GW,eq:l6,exists:ZW,gt:i3,gte:n3,ilike:HW,inArray:t3,isNull:e3,isNotNull:YW,like:$W,lt:r3,lte:s3,ne:c3,not:o3,notBetween:_W,notExists:XW,notLike:WW,notIlike:JW,notInArray:a3,or:l3,sql:V}}function EW(){return{sql:V,asc:QW,desc:zW}}function VW(Y,Z){if(Object.keys(Y).length===1&&"default"in Y&&!M(Y.default,P))Y=Y.default;let X={},G={},_={};for(let[$,W]of Object.entries(Y))if(M(W,P)){let H=g4(W),Q=G[H];X[H]=$,_[$]={tsName:$,dbName:W[P.Symbol.Name],schema:W[P.Symbol.Schema],columns:W[P.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let z of Object.values(W[P.Symbol.Columns]))if(z.primary)_[$].primaryKey.push(z);let J=W[P.Symbol.ExtraConfigBuilder]?.(W[P.Symbol.ExtraConfigColumns]);if(J){for(let z of Object.values(J))if(M(z,K8))_[$].primaryKey.push(...z.columns)}}else if(M(W,FW)){let H=g4(W.table),Q=X[H],J=W.config(Z(W.table)),z;for(let[U,O]of Object.entries(J))if(Q){let L=_[Q];if(L.relations[U]=O,z)L.primaryKey.push(...z)}else{if(!(H in G))G[H]={relations:{},primaryKey:z};G[H].relations[U]=O}}return{tables:_,tableNamesMap:X}}function iU(Y){return function(X,G){return new K4(Y,X,G,G?.fields.reduce((_,$)=>_&&$.notNull,!0)??!1)}}function nU(Y){return function(X,G){return new T8(Y,X,G)}}function OW(Y,Z,X){if(M(X,K4)&&X.config)return{fields:X.config.fields,references:X.config.references};let G=Z[g4(X.referencedTable)];if(!G)throw Error(`Table "${X.referencedTable[P.Symbol.Name]}" not found in schema`);let _=Y[G];if(!_)throw Error(`Table "${G}" not found in schema`);let $=X.sourceTable,W=Z[g4($)];if(!W)throw Error(`Table "${$[P.Symbol.Name]}" not found in schema`);let H=[];for(let Q of Object.values(_.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?Error(`There are multiple relations with name "${X.relationName}" in table "${G}"`):Error(`There are multiple relations between "${G}" and "${X.sourceTable[P.Symbol.Name]}". Please specify relation name`);if(H[0]&&M(H[0],K4)&&H[0].config)return{fields:H[0].config.references,references:H[0].config.fields};throw Error(`There is not enough information to infer relation "${W}.${X.fieldName}"`)}function DW(Y){return{one:iU(Y),many:nU(Y)}}function o6(Y,Z,X,G,_=($)=>$){let $={};for(let[W,H]of G.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,K4)?z&&o6(Y,Y[H.relationTableTsKey],z,H.selection,_):z.map((U)=>o6(Y,Y[H.relationTableTsKey],U,H.selection,_))}else{let Q=_(X[W]),J=H.field,z;if(M(J,U0))z=J;else if(M(J,f))z=J.decoder;else z=J.sql.decoder;$[H.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return $}import ME from"os";import AE from"fs";var i6=new Map,C5=new Map,q5=Symbol("OriginError"),A2={};class q1 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=G,this.options=_,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[q5]=this.handler.debug?Error():this.tagged&&rU(this.strings)}get origin(){return(this.handler.debug?this[q5].stack:this.tagged&&C5.has(this.strings)?C5.get(this.strings):C5.set(this.strings,this[q5].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 G=new Promise((_,$)=>{this.cursorFn=(W)=>{return _({value:W,done:!1}),new Promise((H)=>X=H)},this.resolve=()=>(this.active=!1,_({done:!0})),this.reject=(W)=>(this.active=!1,$(W))});return this.execute(),G},return(){return X&&X(A2),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw 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 rU(Y){if(i6.has(Y))return i6.get(Y);let Z=Error.stackTraceLimit;return Error.stackTraceLimit=4,i6.set(Y,Error()),Error.stackTraceLimit=Z,i6.get(Y)}class R2 extends Error{constructor(Y){super(Y.message);this.name=this.constructor.name,Object.assign(this,Y)}}var f0={connection:LW,postgres:MW,generic:AW,notSupported:RW};function LW(Y,Z,X){let{host:G,port:_}=X||Z,$=Object.assign(Error("write "+Y+" "+(Z.path||G+":"+_)),{code:Y,errno:Y,address:Z.path||G},Z.path?{}:{port:_});return Error.captureStackTrace($,LW),$}function MW(Y){let Z=new R2(Y);return Error.captureStackTrace(Z,MW),Z}function AW(Y,Z){let X=Object.assign(Error(Y+": "+Z),{code:Y});return Error.captureStackTrace(X,AW),X}function RW(Y){let Z=Object.assign(Error(Y+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:Y});return Error.captureStackTrace(Z,RW),Z}var sU={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 s6{then(){j5()}catch(){j5()}finally(){j5()}}class P8 extends s6{constructor(Y){super();this.value=e6(Y)}}class n1 extends s6{constructor(Y,Z,X){super();this.value=Y,this.type=Z,this.array=X}}class t6 extends s6{constructor(Y,Z){super();this.first=Y,this.rest=Z}build(Y,Z,X,G){let _=tU.map(([$,W])=>({fn:W,i:Y.search($)})).sort(($,W)=>$.i-W.i).pop();return _.i===-1?f5(this.first,G):_.fn(this.first,this.rest,Z,X,G)}}function a6(Y,Z,X,G){let _=Y instanceof n1?Y.value:Y;if(_===void 0){if(Y instanceof n1?Y.value=G.transform.undefined:_=Y=G.transform.undefined,_===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(Y instanceof n1?(Z.push(Y.value),Y.array?Y.array[Y.type||r6(Y.value)]||Y.type||KW(Y.value):Y.type):(Z.push(Y),r6(Y)))}var NW=TW(sU);function v5(Y,Z,X,G,_,$){for(let W=1;W<Y.strings.length;W++)Z+=x5(Z,X,G,_,$)+Y.strings[W],X=Y.args[W];return Z}function x5(Y,Z,X,G,_){return Z instanceof t6?Z.build(Y,X,G,_):Z instanceof q1?S5(Z,X,G,_):Z instanceof P8?Z.value:Z&&Z[0]instanceof q1?Z.reduce(($,W)=>$+" "+S5(W,X,G,_),""):a6(Z,X,G,_)}function S5(Y,Z,X,G){return Y.fragment=!0,v5(Y,Y.strings[0],Y.args[0],Z,X,G)}function IW(Y,Z,X,G,_){return Y.map(($)=>"("+G.map((W)=>x5("values",$[W],Z,X,_)).join(",")+")").join(",")}function wW(Y,Z,X,G,_){let $=Array.isArray(Y[0]),W=Z.length?Z.flat():Object.keys($?Y[0]:Y);return IW($?Y:[Y],X,G,W,_)}function n6(Y,Z,X,G,_){if(typeof Y==="string"&&(Y=[Y].concat(Z)),Array.isArray(Y))return f5(Y,_);let $;return(Z.length?Z.flat():Object.keys(Y)).map((H)=>{return $=Y[H],($ instanceof q1?S5($,X,G,_):$ instanceof P8?$.value:a6($,X,G,_))+" as "+e6(_.transform.column.to?_.transform.column.to(H):H)}).join(",")}var tU=Object.entries({values:wW,in:(...Y)=>{let Z=wW(...Y);return Z==="()"?"(null)":Z},select:n6,as:n6,returning:n6,"\\(":n6,update(Y,Z,X,G,_){return(Z.length?Z.flat():Object.keys(Y)).map(($)=>e6(_.transform.column.to?_.transform.column.to($):$)+"="+x5("values",Y[$],X,G,_))},insert(Y,Z,X,G,_){let $=Z.length?Z.flat():Object.keys(Array.isArray(Y)?Y[0]:Y);return"("+f5($,_)+")values"+IW(Array.isArray(Y)?Y:[Y],X,G,$,_)}}).map(([Y,Z])=>[new RegExp("((?:^|[\\s(])"+Y+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Z]);function j5(){throw f0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:aU,parsers:eU}=NW;function KW(Y){if(Array.isArray(Y))return KW(Y[0]);return typeof Y==="string"?1009:0}var BW=function(Y){let Z=TW(Y||{});return{serializers:Object.assign({},aU,Z.serializers),parsers:Object.assign({},eU,Z.parsers)}};function TW(Y){return Object.keys(Y).reduce((Z,X)=>{if(Y[X].from&&[].concat(Y[X].from).forEach((G)=>Z.parsers[G]=Y[X].parse),Y[X].serialize)Z.serializers[Y[X].to]=Y[X].serialize,Y[X].from&&[].concat(Y[X].from).forEach((G)=>Z.serializers[G]=Y[X].serialize);return Z},{parsers:{},serializers:{}})}function f5(Y,{transform:{column:Z}}){return Y.map((X)=>e6(Z.to?Z.to(X):X)).join(",")}var e6=function(Z){return'"'+Z.replace(/"/g,'""').replace(/\./g,'"."')+'"'},r6=function Y(Z){return Z instanceof n1?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},YE=/\\/g,ZE=/"/g;function XE(Y){return Y.replace(YE,"\\\\").replace(ZE,"\\\"")}var CW=function Y(Z,X,G,_){if(Array.isArray(Z)===!1)return Z;if(!Z.length)return"{}";let $=Z[0],W=_===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=G.transform.undefined,H===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return H===null?"null":'"'+XE(X?X(H.type?H.value:H):""+H)+'"'}).join(W)+"}"},P5={i:0,char:null,str:"",quoted:!1,last:0},qW=function(Z,X,G){return P5.i=P5.last=0,jW(P5,Z,X,G)};function jW(Y,Z,X,G){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==='"')_.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,_.push(jW(Y,Z,X,G));else if(Y.char==="}"){Y.quoted=!1,Y.last<Y.i&&_.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!=='"')_.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&&_.push(X?X(Z.slice(Y.last,Y.i+1)):Z.slice(Y.last,Y.i+1)),_}var p4=(Y)=>{let Z=Y[0];for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},m4=(Y)=>{let Z=Y[0].toUpperCase();for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},u4=(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 h5(Y){return function Z(X,G){return typeof X==="object"&&X!==null&&(G.type===114||G.type===3802)?Array.isArray(X)?X.map((_)=>Z(_,G)):Object.entries(X).reduce((_,[$,W])=>Object.assign(_,{[Y($)]:Z(W,G)}),{}):X}}p4.column={from:p4};p4.value={from:h5(p4)};C8.column={to:C8};var k5={...p4};k5.column.to=C8;m4.column={from:m4};m4.value={from:h5(m4)};q8.column={to:q8};var b5={...m4};b5.column.to=q8;u4.column={from:u4};u4.value={from:h5(u4)};j8.column={to:j8};var y5={...u4};y5.column.to=j8;import PW from"net";import WE from"tls";import S8 from"crypto";import g5 from"stream";import{performance as SW}from"perf_hooks";class d4 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 R1=GE;function GE(Y=[]){let Z=Y.slice(),X=0;return{get length(){return Z.length-X},remove:(G)=>{let _=Z.indexOf(G);return _===-1?null:(Z.splice(_,1),G)},push:(G)=>(Z.push(G),G),shift:()=>{let G=Z[X++];if(X===Z.length)X=0,Z=[];else Z[X-1]=void 0;return G}}}var a0=Buffer.allocUnsafe(256),_E="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($E,_E,{N:String.fromCharCode(0),i:0,inc(Y){return z0.i+=Y,z0},str(Y){let Z=Buffer.byteLength(Y);return YY(Z),z0.i+=a0.write(Y,z0.i,Z,"utf8"),z0},i16(Y){return YY(2),a0.writeUInt16BE(Y,z0.i),z0.i+=2,z0},i32(Y,Z){if(Z||Z===0)return a0.writeUInt32BE(Y,Z),z0;return YY(4),a0.writeUInt32BE(Y,z0.i),z0.i+=4,z0},z(Y){return YY(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}}),d=z0;function YY(Y){if(a0.length-z0.i<Y){let Z=a0,X=Z.length;a0=Buffer.allocUnsafe(X+(X>>1)+Y),Z.copy(a0)}}function $E(){return z0.i=0,z0}var u5=fW,HE=1,B4=d().S().end(),vW=d().H().end(),JE=d().i32(8).i32(80877103).end(8),QE=Buffer.concat([d().E().str(d.N).i32(0).end(),B4]),zE=d().D().str("S").str(d.N).end(),w2=()=>{},FE=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),UE={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 fW(Y,Z={},{onopen:X=w2,onend:G=w2,onclose:_=w2}={}){let{ssl:$,max:W,user:H,host:Q,port:J,database:z,parsers:U,transform:O,onnotice:L,onnotify:w,onparameter:R,max_pipeline:b,keep_alive:x,backoff:h,target_session_attrs:g}=Y,B=R1(),K=HE++,C={pid:null,secret:null},q=m5(VY,Y.idle_timeout),c=m5(VY,Y.max_lifetime),n=m5(GH,Y.connect_timeout),N=null,s,p=new d4,t=Buffer.alloc(0),I0=Y.fetch_types,h0={},$1={},r1=Math.random().toString(36).slice(2),T=1,m=0,$0=0,V0=0,k0=0,a=0,J0=0,v0=0,B0=null,A0=null,o0=!1,O0=null,j1=null,c0=null,z4=null,b0=null,R0=null,P1=null,u1=null,v=null,B2=null,i0={queue:Z.closed,idleTimer:q,connect(F){c0=F,OX()},terminate:C2,execute:T2,cancel:eW,end:VY,count:0,id:K};return Z.closed&&Z.closed.push(i0),i0;async function aW(){let F;try{F=Y.socket?await Promise.resolve(Y.socket(Y)):new PW.Socket}catch(D){i4(D);return}return F.on("error",i4),F.on("close",DX),F.on("drain",EX),F}async function eW({pid:F,secret:D},l,W0){try{s=d().i32(16).i32(80877102).i32(F).i32(D).end(16),await VX(),N.once("error",W0),N.once("close",l)}catch(C0){W0(C0)}}function T2(F){if(o0)return g8(F,f0.connection("CONNECTION_DESTROYED",Y));if(F.cancelled)return;try{return F.state=C,v?B.push(F):(v=F,v.active=!0),XH(F),l0(YH(F))&&!F.describeFirst&&!F.cursorFn&&B.length<b&&(!F.options.onexecute||F.options.onexecute(i0))}catch(D){return B.length===0&&l0(B4),d1(D),!0}}function YH(F){if(F.parameters.length>=65534)throw f0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return F.options.simple?d().Q().str(F.statement.string+d.N).end():F.describeFirst?Buffer.concat([zX(F),vW]):F.prepare?F.prepared?y8(F):Buffer.concat([zX(F),y8(F)]):ZH(F)}function zX(F){return Buffer.concat([MX(F.statement.string,F.parameters,F.statement.types,F.statement.name),mH("S",F.statement.name)])}function y8(F){return Buffer.concat([pH(F.parameters,F.statement.types,F.statement.name,F.cursorName),F.cursorFn?AX("",F.cursorRows):QE])}function ZH(F){return Buffer.concat([MX(F.statement.string,F.parameters,F.statement.types),zE,y8(F)])}function XH(F){let D=[],l=[],W0=v5(F,F.strings[0],F.args[0],D,l,Y);!F.tagged&&F.args.forEach((C0)=>a6(C0,D,l,Y)),F.prepare=Y.prepare&&("prepare"in F.options?F.options.prepare:!0),F.string=W0,F.signature=F.prepare&&l+W0,F.onlyDescribe&&delete $1[F.signature],F.parameters=F.parameters||D,F.prepared=F.prepare&&F.signature in $1,F.describeFirst=F.onlyDescribe||D.length&&!F.prepared,F.statement=F.prepared?$1[F.signature]:{string:W0,types:l,name:F.prepare?r1+T++:""},typeof Y.debug==="function"&&Y.debug(K,W0,D,l)}function l0(F,D){if(R0=R0?Buffer.concat([R0,F]):Buffer.from(F),D||R0.length>=1024)return FX(D);return A0===null&&(A0=setImmediate(FX)),!0}function FX(F){let D=N.write(R0,F);return A0!==null&&clearImmediate(A0),R0=A0=null,D}function GH(){d1(f0.connection("CONNECT_TIMEOUT",Y,N)),N.destroy()}async function UX(){if(l0(JE),!await new Promise((D)=>N.once("data",(l)=>D(l[0]===83)))&&$==="prefer")return o4();N.removeAllListeners(),N=WE.connect({socket:N,servername:PW.isIP(N.host)?void 0:N.host,...$==="require"||$==="allow"||$==="prefer"?{rejectUnauthorized:!1}:$==="verify-full"?{}:typeof $==="object"?$:{}}),N.on("secureConnect",o4),N.on("error",i4),N.on("close",DX),N.on("drain",EX)}function EX(){!v&&X(i0)}function EY(F){if(O0){if(O0.push(F),$0-=F.length,$0>0)return}t=O0?Buffer.concat(O0,a-$0):t.length===0?F:Buffer.concat([t,F],t.length+F.length);while(t.length>4){if(a=t.readUInt32BE(1),a>=t.length){$0=a-t.length,O0=[t];break}try{_H(t.subarray(0,a+1))}catch(D){v&&(v.cursorFn||v.describeFirst)&&l0(B4),d1(D)}t=t.subarray(a+1),$0=0,O0=null}}async function VX(){if(o0=!1,h0={},N||(N=await aW()),!N)return;if(n.start(),Y.socket)return $?UX():o4();if(N.on("connect",$?UX:o4),Y.path)return N.connect(Y.path);N.ssl=$,N.connect(J[V0],Q[V0]),N.host=Q[V0],N.port=J[V0],V0=(V0+1)%J.length}function OX(){setTimeout(VX,m?m+J0-SW.now():0)}function o4(){try{$1={},I0=Y.fetch_types,r1=Math.random().toString(36).slice(2),T=1,c.start(),N.on("data",EY),x&&N.setKeepAlive&&N.setKeepAlive(!0,1000*x);let F=dH();l0(F)}catch(F){i4(F)}}function i4(F){if(i0.queue===Z.connecting&&Y.host[k0+1])return;d1(F);while(B.length)g8(B.shift(),F)}function d1(F){b0&&(b0.destroy(F),b0=null),v&&g8(v,F),c0&&(g8(c0,F),c0=null)}function g8(F,D){if(F.reserve)return F.reject(D);if(!D||typeof D!=="object")D=Error(D);"query"in D||"parameters"in D||Object.defineProperties(D,{stack:{value:D.stack+F.origin.replace(/.*\n/,`
67
- `),enumerable:Y.debug},query:{value:F.string,enumerable:Y.debug},parameters:{value:F.parameters,enumerable:Y.debug},args:{value:F.args,enumerable:Y.debug},types:{value:F.statement&&F.statement.types,enumerable:Y.debug}}),F.reject(D)}function VY(){return z4||(!i0.reserved&&G(i0),!i0.reserved&&!c0&&!v&&B.length===0?(C2(),new Promise((F)=>N&&N.readyState!=="closed"?N.once("close",F):F())):z4=new Promise((F)=>P1=F))}function C2(){if(o0=!0,b0||v||c0||B.length)i4(f0.connection("CONNECTION_DESTROYED",Y));if(clearImmediate(A0),N)N.removeListener("data",EY),N.removeListener("connect",o4),N.readyState==="open"&&N.end(d().X().end());P1&&(P1(),z4=P1=null)}async function DX(F){if(t=Buffer.alloc(0),$0=0,O0=null,clearImmediate(A0),N.removeListener("data",EY),N.removeListener("connect",o4),q.cancel(),c.cancel(),n.cancel(),N.removeAllListeners(),N=null,c0)return OX();!F&&(v||B.length)&&i4(f0.connection("CONNECTION_CLOSED",Y,N)),m=SW.now(),F&&Y.shared.retries++,J0=(typeof h==="function"?h(Y.shared.retries):h)*1000,_(i0,f0.connection("CONNECTION_CLOSED",Y,N))}function _H(F,D=F[0]){(D===68?$H:D===100?vH:D===65?TH:D===83?WH:D===90?HH:D===67?JH:D===50?LX:D===49?QH:D===116?zH:D===84?FH:D===82?UH:D===110?MH:D===75?AH:D===69?KH:D===115?CH:D===51?qH:D===71?jH:D===78?fH:D===72?PH:D===99?xH:D===73?hH:D===86?kH:D===118?bH:D===87?SH:yH)(F)}function $H(F){let D=7,l,W0,C0,n0=v.isRaw?Array(v.statement.columns.length):{};for(let e0=0;e0<v.statement.columns.length;e0++)W0=v.statement.columns[e0],l=F.readInt32BE(D),D+=4,C0=l===-1?null:v.isRaw===!0?F.subarray(D,D+=l):W0.parser===void 0?F.toString("utf8",D,D+=l):W0.parser.array===!0?W0.parser(F.toString("utf8",D+1,D+=l)):W0.parser(F.toString("utf8",D,D+=l)),v.isRaw?n0[e0]=v.isRaw===!0?C0:O.value.from?O.value.from(C0,W0):C0:n0[W0.name]=O.value.from?O.value.from(C0,W0):C0;v.forEachFn?v.forEachFn(O.row.from?O.row.from(n0):n0,p):p[v0++]=O.row.from?O.row.from(n0):n0}function WH(F){let[D,l]=F.toString("utf8",5,F.length-1).split(d.N);if(h0[D]=l,Y.parameters[D]!==l)Y.parameters[D]=l,R&&R(D,l)}function HH(F){if(v&&v.options.simple&&v.resolve(j1||p),v=j1=null,p=new d4,n.cancel(),c0){if(g){if(!h0.in_hot_standby||!h0.default_transaction_read_only)return IH();else if(NH(g,h0))return C2()}if(I0)return c0.reserve&&(c0=null),RH();c0&&!c0.reserve&&T2(c0),Y.shared.retries=k0=0,c0=null;return}while(B.length&&(v=B.shift())&&(v.active=!0,v.cancelled))fW(Y).cancel(v.state,v.cancelled.resolve,v.cancelled.reject);if(v)return;i0.reserved?!i0.reserved.release&&F[5]===73?z4?C2():(i0.reserved=null,X(i0)):i0.reserved():z4?C2():X(i0)}function JH(F){v0=0;for(let D=F.length-1;D>0;D--){if(F[D]===32&&F[D+1]<58&&p.count===null)p.count=+F.toString("utf8",D+1,F.length-1);if(F[D-1]>=65){p.command=F.toString("utf8",5,D),p.state=C;break}}if(B2&&(B2(),B2=null),p.command==="BEGIN"&&W!==1&&!i0.reserved)return d1(f0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(v.options.simple)return LX();if(v.cursorFn)p.count&&v.cursorFn(p),l0(B4);v.resolve(p)}function QH(){v.parsing=!1}function LX(){!p.statement&&(p.statement=v.statement),p.columns=v.statement.columns}function zH(F){let D=F.readUInt16BE(5);for(let l=0;l<D;++l)!v.statement.types[l]&&(v.statement.types[l]=F.readUInt32BE(7+l*4));v.prepare&&($1[v.signature]=v.statement),v.describeFirst&&!v.onlyDescribe&&(l0(y8(v)),v.describeFirst=!1)}function FH(F){if(p.command)j1=j1||[p],j1.push(p=new d4),p.count=null,v.statement.columns=null;let D=F.readUInt16BE(5),l=7,W0;v.statement.columns=Array(D);for(let C0=0;C0<D;++C0){W0=l;while(F[l++]!==0);let n0=F.readUInt32BE(l),e0=F.readUInt16BE(l+4),F4=F.readUInt32BE(l+6);v.statement.columns[C0]={name:O.column.from?O.column.from(F.toString("utf8",W0,l-1)):F.toString("utf8",W0,l-1),parser:U[F4],table:n0,number:e0,type:F4},l+=18}if(p.statement=v.statement,v.onlyDescribe)return v.resolve(v.statement),l0(B4)}async function UH(F,D=F.readUInt32BE(5)){(D===3?EH:D===5?VH:D===10?OH:D===11?DH:D===12?LH:D!==0?gH:w2)(F,D)}async function EH(){let F=await OY();l0(d().p().str(F).z(1).end())}async function VH(F){let D="md5"+await xW(Buffer.concat([Buffer.from(await xW(await OY()+H)),F.subarray(9)]));l0(d().p().str(D).z(1).end())}async function OH(){u1=(await S8.randomBytes(18)).toString("base64"),d().p().str("SCRAM-SHA-256"+d.N);let F=d.i;l0(d.inc(4).str("n,,n=*,r="+u1).i32(d.i-F-4,F).end())}async function DH(F){let D=F.toString("utf8",9).split(",").reduce((e0,F4)=>(e0[F4[0]]=F4.slice(2),e0),{}),l=await S8.pbkdf2Sync(await OY(),Buffer.from(D.s,"base64"),parseInt(D.i),32,"sha256"),W0=await ZY(l,"Client Key"),C0="n=*,r="+u1+",r="+D.r+",s="+D.s+",i="+D.i+",c=biws,r="+D.r;B0=(await ZY(await ZY(l,"Server Key"),C0)).toString("base64");let n0="c=biws,r="+D.r+",p="+VE(W0,Buffer.from(await ZY(await EE(W0),C0))).toString("base64");l0(d().p().str(n0).end())}function LH(F){if(F.toString("utf8",9).split(d.N,1)[0].slice(2)===B0)return;d1(f0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),N.destroy()}function OY(){return Promise.resolve(typeof Y.pass==="function"?Y.pass():Y.pass)}function MH(){if(p.statement=v.statement,p.statement.columns=[],v.onlyDescribe)return v.resolve(v.statement),l0(B4)}function AH(F){C.pid=F.readUInt32BE(5),C.secret=F.readUInt32BE(9)}async function RH(){I0=!1,(await new q1([`
58
+ ${F.trace}`:`No previous disposal trace for ${H} was found.`),Z}let J=X.moleculeGraph.getRelationEntries({downstreamMoleculeKey:$.stringKey}).filter(([,{source:F}])=>F!==G).map(([F])=>X1(F));if(_)W.moleculeGraph.delete(G);W.moleculeGraph.set({upstreamMoleculeKey:Q.stringKey,downstreamMoleculeKey:$.stringKey},{source:Q.stringKey});let z={type:"molecule_transfer",key:$.key,exclusive:Boolean(_),from:J,to:[Q.key],timestamp:Date.now()};if(z1(W)&&W.transactionMeta.phase==="building")W.transactionMeta.update.subEvents.push(z);return Z}function nF(X,Y,Z){switch(Z){case"newValue":nG(X,Y);break;case"oldValue":W2(X,Y.token);break}}function rF(X,Y,Z){switch(Z){case"newValue":W2(X,Y.token);break;case"oldValue":if(nG(X,Y),Y.subType==="atom")X.valueMap.set(Y.token.key,Y.value);break}}function nG(X,Y){let{token:Z}=Y;if(Y.subType==="writable"&&Y.value)k1(X,Z,Y.value);else h1(X,Z)}function sF(X,Y,Z){switch(Z){case"newValue":A6(X,Y.provenance,Y.key);break;case"oldValue":K6(X,Y.key);break}}function tF(X,Y,Z){switch(Z){case"newValue":K6(X,Y.key);break;case"oldValue":{let _=Y.provenance.map(X1);A6(X,_,Y.key);for(let[G,W]of Y.values){let $=X.families.get(G);if($){h1(X,$,Y.key);let H=`${G}(${w0(Y.key)})`;X.valueMap.set(H,W)}}}break}}function aF(X,Y,Z){switch(Z){case"newValue":for(let _ of Y.to)Z2(X,_,Y.key,Y.exclusive?"exclusive":void 0);break;case"oldValue":{let _="exclusive";for(let G of Y.from)Z2(X,G,Y.key,_),_=void 0}break}}function rG(X,Y,Z){let _=Z==="newValue"?Y.subEvents:[...Y.subEvents].reverse();for(let G of _)switch(G.type){case"atom_update":oF(X,G,Z);break;case"state_creation":nF(X,G,Z);break;case"state_disposal":rF(X,G,Z);break;case"molecule_creation":sF(X,G,Z);break;case"molecule_disposal":tF(X,G,Z);break;case"molecule_transfer":aF(X,G,Z);break;case"transaction_outcome":rG(X,G,Z);break}}function O8(X){return"epoch"in X.transactionMeta}function z1(X){return"phase"in X.transactionMeta}function sG(X,Y){return X.transactionMeta.actionContinuities.getRelatedKey(Y)}function eF(X,Y){return X.transactionMeta.epoch.get(Y)}function XU(X,Y){let Z=sG(X,Y);if(Z===void 0)return;return eF(X,Z)}function YU(X,Y,Z){let _=sG(X,Y);if(_!==void 0)X.transactionMeta.epoch.set(_,Z)}function ZU(X,Y){let Z=s(X),{parent:_}=Z;Z.transactionMeta.phase="applying",Z.transactionMeta.update.output=Y,_.child=null,_.on.transactionApplying.next(Z.transactionMeta);let{subEvents:G}=Z.transactionMeta.update;if(X.logger.info("\uD83D\uDEC4","transaction",Z.transactionMeta.update.token.key,`applying ${G.length} subEvents:`,G),rG(_,Z.transactionMeta.update,"newValue"),O8(_))YU(_,Z.transactionMeta.update.token.key,Z.transactionMeta.update.epoch),T0(X,{key:Z.transactionMeta.update.token.key,type:"transaction"})?.subject.next(Z.transactionMeta.update),X.logger.info("\uD83D\uDEEC","transaction",Z.transactionMeta.update.token.key,"applied");else if(z1(_))_.transactionMeta.update.subEvents.push(Z.transactionMeta.update);_.on.transactionApplying.next(null)}function _U(X){return{store:X}}var GU=(X,Y,Z,_)=>{let G=s(X),W={parent:G,child:null,on:G.on,loggers:G.loggers,logger:G.logger,config:G.config,atoms:new b1(G.atoms),atomsThatAreDefault:new Set(G.atomsThatAreDefault),families:new b1(G.families),joins:new b1(G.joins),operation:{open:!1},readonlySelectors:new b1(G.readonlySelectors),timelines:new b1(G.timelines),timelineTopics:G.timelineTopics.overlay(),trackers:new Map,transactions:new b1(G.transactions),selectorAtoms:G.selectorAtoms.overlay(),selectorGraph:G.selectorGraph.overlay(),writableSelectors:new b1(G.writableSelectors),valueMap:new b1(G.valueMap),defaults:G.defaults,disposalTraces:X.disposalTraces.copy(),molecules:new b1(G.molecules),moleculeGraph:G.moleculeGraph.overlay(),moleculeData:G.moleculeData.overlay(),moleculeJoins:G.moleculeJoins.overlay(),miscResources:new b1(G.miscResources)},$=XU(X,Y.key),H={phase:"building",update:{type:"transaction_outcome",token:Y,id:_,epoch:$===void 0?NaN:$+1,timestamp:Date.now(),subEvents:[],params:Z,output:void 0},toolkit:{get:(...J)=>h1(Q,...J),set:(...J)=>{k1(Q,...J)},reset:(...J)=>{R6(Q,...J)},run:(J,z=kY())=>M6(Q,J,z),find:(...J)=>e0(X,...J),json:(J)=>h4(Q,J),dispose:(...J)=>{W2(Q,...J)},env:()=>_U(Q)}},Q=Object.assign(W,{transactionMeta:H});return G.child=Q,X.logger.info("\uD83D\uDEEB","transaction",Y.key,"building with params:",Z),Q};function _2(X,Y){let{key:Z}=Y,_=X.transactions.has(Z),G={key:Z,type:"transaction",run:($,H)=>{let Q=y1(G),J=GU(X,Q,$,H);try{let{toolkit:z}=J.transactionMeta,F=Y.do(z,...$);return ZU(J,F),F}catch(z){throw lF(J),X.logger.warn("\uD83D\uDCA5","transaction",Z,"caught:",z),z}},install:($)=>_2($,Y),subject:new Z0};s(X).transactions.set(Z,G);let W=y1(G);if(!_)X.on.transactionCreation.next(W);return W}var fG=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 W4({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new W4({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new W4({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new W4({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new dF(100);molecules=new Map;moleculeJoins=new W4({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});moleculeGraph=new W4({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});moleculeData=new W4({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});miscResources=new Map;on={atomCreation:new Z0,atomDisposal:new Z0,selectorCreation:new Z0,selectorDisposal:new Z0,timelineCreation:new Z0,transactionCreation:new Z0,transactionApplying:new uF(null),operationClose:new Z0,moleculeCreation:new Z0,moleculeDisposal:new Z0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new jG("warn",(X,Y,Z)=>!V8(Z))];logger={error:(...X)=>{for(let Y of this.loggers)Y.error(...X)},info:(...X)=>{for(let Y of this.loggers)Y.info(...X)},warn:(...X)=>{for(let Y of this.loggers)Y.warn(...X)}};constructor(X,Y=null){if(this.config={...Y?.config,...X},Y!==null){if(this.operation={...Y?.operation},O8(Y))this.transactionMeta={epoch:new Map(Y?.transactionMeta.epoch),actionContinuities:new W4(Y?.transactionMeta.actionContinuities.toJSON())};for(let[,_]of Y.families){if(_.internalRoles?.includes("mutable")||_.internalRoles?.includes("join"))continue;_.install(this)}let Z=new Set;for(let[,_]of Y.atoms){if(Z.has(_.key))continue;if(_.install(this),_.type==="mutable_atom"){let G=h4(Y,_),W=_Z(_);Z.add(G.key),Z.add(W.key)}}for(let[,_]of Y.readonlySelectors)_.install(this);for(let[,_]of Y.writableSelectors){if(Z.has(_.key))continue;_.install(this)}for(let[,_]of Y.transactions)_.install(this);for(let[,_]of Y.timelines)_.install(this)}}},Q1={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new fG({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};var WU=class extends Error{constructor(X,Y){super(`${_4[X.type]} ${w0(X.key)} not found in store "${Y.config.name}".`)}};function T0(X,Y){let Z,_=X;while(_!==null){switch(Y.type){case"atom":case"mutable_atom":Z=_.atoms.get(Y.key);break;case"writable_pure_selector":case"writable_held_selector":Z=_.writableSelectors.get(Y.key);break;case"readonly_pure_selector":case"readonly_held_selector":Z=_.readonlySelectors.get(Y.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":Z=_.families.get(Y.key);break;case"timeline":Z=_.timelines.get(Y.key);break;case"transaction":Z=_.transactions.get(Y.key);break}if(Z)return Z;_=_.child}throw new WU(Y,X)}function tG(X,Y,Z,_){let G=X.disposalTraces.buffer.find((W)=>W?.key===w0(_));switch(X.logger.error("\u274C",Y.type,Y.key,"gets a fallback value because key",_,"is not allocated",G?`This key was previously disposed:
59
+ ${G.trace}`:"(no previous disposal trace found)"),Z.type){case"mutable_atom_family":{if(X.defaults.has(Z.key))return X.defaults.get(Z.key);let W=new Z.class;return X.defaults.set(Z.key,W),W.READONLY_VIEW}case"atom_family":{if(X.defaults.has(Z.key))return X.defaults.get(Z.key);let W=Z.default,$=W(_);return X.defaults.set(Z.key,$),$}case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(X.defaults.has(Z.key))return X.defaults.get(Z.key);let W=Z.default(_);return X.defaults.set(Z.key,W),W}}}function N6(X,Y){let{type:Z,key:_,catch:G}=Y;switch(Z){case"readonly_pure_selector":case"writable_pure_selector":{let W;X.logger.info("\uD83E\uDDEE",Z,_,"computing value");try{if(W=Y.getFrom(X),W instanceof Promise)return W.catch(($)=>{if(X.logger.error("\uD83D\uDCA5",Z,_,"rejected:",$),G){for(let H of G)if($ instanceof H)return $}throw $})}catch($){if(X.logger.error("\uD83D\uDCA5",Z,_,"rejected:",$),G){for(let H of G)if($ instanceof H)return K1(X,Y,$)}throw $}return K1(X,Y,W)}case"atom":{let W;if(H2(Y.default))try{if(W=Y.default(),W instanceof Promise)W=W.catch(($)=>{if(X.logger.error("\uD83D\uDCA5",Z,_,"rejected:",$),G){for(let H of G)if($ instanceof H)return $}throw $})}catch($){if(X.logger.error("\uD83D\uDCA5",Z,_,"rejected:",$),G){for(let H of G)if($ instanceof H)return W=K1(X,Y,$),X.logger.info("\u2728",Y.type,_,"computed default",W),W}throw $}else W=Y.default,X.logger.info("\u2728",Y.type,_,"using static default",W);return K1(X,Y,W)}}}function f4(X,Y,Z){if(X.valueMap.has(Y.key))return AU(X,Y,Z);X.logger.info("\u2754",Y.type,Y.key,"value not found in cache");let{key:_}=Y;switch(Y.type){case"readonly_held_selector":case"writable_held_selector":return X.logger.info("\uD83E\uDDEE",Y.type,_,"computing value"),Y.getFrom(X);case"writable_pure_selector":case"readonly_pure_selector":case"atom":return N6(X,Y);case"mutable_atom":{let G=new Y.class;return X.logger.info("\u2728",Y.type,_,"created new instance",G),K1(X,Y,G)}}}function nY(X,Y){return T0(X,{key:Y.family.key,type:`${Y.type}_family`})}var cG={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"},J2=Symbol("MUST_CREATE"),$U=Symbol("DO_NOT_CREATE");function Q2(X,Y,Z,_){let G=w0(_),W=Y.molecules.get(G);if(!W&&Y.config.lifespan==="immortal"){let{type:H,key:Q}=Z;Y.logger.warn("\uD83D\uDCA3","key",G,"was used to mint a counterfeit token for",H,`"${Q}"`);let J=`${Q}(${G})`,z=cG[H];return{counterfeit:!0,key:J,type:z,family:{key:Q,subKey:G}}}let $;if(X===J2){if(Y.logger.info("\uD83D\uDC6A",Z.type,Z.key,"adds member",typeof _==="string"?`\`${_}\``:_),$=Z.create(_),W)Y.moleculeData.set(G,Z.key)}else{let{type:H,key:Q}=Z,J=`${Q}(${G})`,z=cG[H];return{key:J,type:z,family:{key:Q,subKey:G}}}return $}function rY(X,...Y){let Z,_,G,W,$;if(Y.length===1){if($=Y[0],"family"in $){let Q=nY(X,$);if(G=T0(X,Q),W=X1($.family.subKey),Z=z2(X,Q,W),"counterfeit"in $)return{token:$,family:G,subKey:W,isNew:!1};if(!Z)_=Q2(J2,X,Q,W),$=_;else $=Z}}else if(G=T0(X,Y[0]),W=Y[1],Z=z2(X,G,W),!Z)_=Q2(J2,X,G,W),$=_;else $=Z;let H="counterfeit"in $;if(Boolean(_)&&H===!1&&G){let Q;switch($.type){case"readonly_pure_selector":case"readonly_held_selector":Q="readable";break;case"atom":case"mutable_atom":case"writable_pure_selector":case"writable_held_selector":Q="writable";break}let J={type:"state_creation",subType:Q,token:$,timestamp:Date.now()};G.subject.next(J);let z=s(X);if($.family){if(O8(z))switch($.type){case"atom":case"mutable_atom":X.on.atomCreation.next($);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":X.on.selectorCreation.next($);break}else if(z1(z)&&z.on.transactionApplying.state===null)z.transactionMeta.update.subEvents.push(J)}}return{token:$,family:G,subKey:W,isNew:Boolean(_)}}function h1(X,...Y){let{token:Z,family:_,subKey:G}=rY(X,...Y);if("counterfeit"in Z&&_&&G)return tG(X,Z,_,G);let W=T0(X,Z);return f4(X,W)}function z2(X,Y,Z){let _=w0(Z),G=`${Y.key}(${_})`,W=s(X),$;switch(Y.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($)return y1($);return $}function e0(X,Y,Z){let _=T0(X,Y),G=z2(X,Y,Z);if(G)return G;return Q2($U,X,_,Z)}function F2(X,Y,Z){let _=Y.key,G="readonly_pure_selector_family",W={key:_,type:"readonly_pure_selector_family"},$=X.families.get(_);if($)X.logger.error("\u2757","readonly_pure_selector_family",_,`Overwriting an existing ${_4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Z0,J={...W,create:(z)=>{let F=w0(z),O={key:_,subKey:F},D=`${_}(${F})`,w=s(X),A={key:D,get:Y.get(z)};if(Y.catch)A.catch=Y.catch;return eY(w,A,O)},internalRoles:Z,subject:H,install:(z)=>F2(z,Y),default:(z)=>{return Y.get(z)({get:(...F)=>h1(X,...F),find:(...F)=>e0(X,...F),json:(F)=>h4(X,F)})}};return X.families.set(_,J),W}function G2(X,Y,Z){let _={key:Y.key,type:"atom_family"},G=X.families.get(Y.key);if(G)X.logger.error("\u2757","atom_family",Y.key,`Overwriting an existing ${_4[G.type]} "${G.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let W=new Z0,H={..._,create:(Q)=>{let J=w0(Q),z={key:Y.key,subKey:J},F=`${Y.key}(${J})`,O=s(X),D=Y.default,w={key:F,default:H2(D)?()=>D(Q):D};if(Y.effects)w.effects=Y.effects(Q);if(Y.catch)w.catch=Y.catch;return x4(O,w,z)},default:Y.default,subject:W,install:(Q)=>G2(Q,Y),internalRoles:Z};if(X.families.set(Y.key,H),H2(Y.default)===!1)X.defaults.set(Y.key,Y.default);return _}function aG(X,Y,Z){let _=Y.key,G="readonly_held_selector_family",W={key:_,type:"readonly_held_selector_family"},$=X.families.get(_);if($)X.logger.error("\u2757","readonly_held_selector_family",_,`Overwriting an existing ${_4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Z0,J={...W,create:(z)=>{let F=w0(z),O={key:_,subKey:F},D=`${_}(${F})`,w=s(X);return aY(w,{key:D,const:Y.const(z),get:Y.get(z)},O)},internalRoles:Z,subject:H,install:(z)=>aG(z,Y),default:Y.const};return X.families.set(_,J),W}function eG(X,Y,Z){let _=Y.key,G="writable_held_selector_family",W={key:_,type:"writable_held_selector_family"},$=X.families.get(_);if($)X.logger.error("\u2757","writable_held_selector_family",_,`Overwriting an existing ${_4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Z0,J={...W,create:(z)=>{let F=w0(z),O={key:_,subKey:F},D=`${_}(${F})`,w=s(X);return XZ(w,{key:D,const:Y.const(z),get:Y.get(z),set:Y.set(z)},O)},internalRoles:Z,subject:H,install:(z)=>eG(z,Y),default:Y.const};return X.families.set(_,J),W}function sY(X,Y,Z){let _=Y.key,G="writable_pure_selector_family",W={key:_,type:"writable_pure_selector_family"},$=X.families.get(_);if($)X.logger.error("\u2757","writable_pure_selector_family",_,`Overwriting an existing ${_4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Z0,J={...W,create:(z)=>{let F=w0(z),O={key:_,subKey:F},D=`${_}(${F})`,w=s(X),A={key:D,get:Y.get(z),set:Y.set(z)};if(Y.catch)A.catch=Y.catch;return YZ(w,A,O)},internalRoles:Z,subject:H,install:(z)=>sY(z,Y),default:(z)=>{return Y.get(z)({get:(...F)=>h1(X,...F),find:(...F)=>e0(X,...F),json:(F)=>h4(X,F)})}};return X.families.set(_,J),W}function bY(X,Y){let Z="set"in Y,_="const"in Y;if(_&&Z)return eG(X,Y,void 0);if(_)return aG(X,Y,void 0);if(Z)return sY(X,Y);return F2(X,Y)}function W2(X,...Y){let Z;if(Y.length===1)Z=Y[0];else{let _=Y[0],G=Y[1];Z=e0(X,_,G)}try{T0(X,Z)}catch(_){X.logger.error("\u274C",Z.type,Z.key,`could not be disposed because it was not found in the store "${X.config.name}".`);return}switch(Z.type){case"atom":case"mutable_atom":$7(X,Z);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":OU(X,Z);break}}function X7(X,Y){if(X.operation.open){let Z=performance.now();return X.logger.info("\uD83D\uDEAB",Y.type,Y.key,`deferring setState at T-${Z} until setState for "${X.operation.token.key}" is done`),Z}return X.operation={open:!0,done:new Set,prev:new Map,timestamp:Date.now(),token:Y,subEvents:[]},X.logger.info("\u2B55",Y.type,Y.key,`operation start in store "${X.config.name}"${z1(X)?` ${X.transactionMeta.phase} "${X.transactionMeta.update.token.key}"`:""}`),X}function Y7(X){if(X.operation.open)X.logger.info("\uD83D\uDD34",X.operation.token.type,X.operation.token.key,`operation done in store "${X.config.name}"`);X.operation={open:!1},X.on.operationClose.next(X.operation)}var Z7=(X,Y)=>{if(!X.operation.open)return X.logger.error("\uD83D\uDC1E","unknown",Y,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return X.operation.done.has(Y)},B6=(X,Y)=>{if(!X.operation.open){X.logger.error("\uD83D\uDC1E","unknown",Y,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}X.operation.done.add(Y)};function lY(X,Y,{oldValue:Z,newValue:_},G,W){let $=y1(Y);if(G&&W){Y.subject.next({newValue:_});let F={checkpoint:!0,type:"state_creation",subType:"writable",token:$,timestamp:Date.now(),value:_};X.operation.subEvents.push(F),W.subject.next(F);let O=s(X);if($.family){if(O8(O))switch($.type){case"atom":case"mutable_atom":X.on.atomCreation.next($);break;case"writable_pure_selector":case"writable_held_selector":X.on.selectorCreation.next($);break}else if(z1(O)&&O.on.transactionApplying.state===null)O.transactionMeta.update.subEvents.push(F)}return}let{key:H,subject:Q,type:J}=Y,z={oldValue:uY(Z)?Z.READONLY_VIEW:Z,newValue:uY(_)?_.READONLY_VIEW:_};if(O8(X)){switch(J){case"mutable_atom":X.logger.info("\uD83D\uDCE2",J,H,"is now (",_,") subscribers:",Q.subscribers.keys());break;case"atom":case"writable_pure_selector":case"writable_held_selector":X.logger.info("\uD83D\uDCE2",J,H,"went (",Z,"->",_,") subscribers:",Q.subscribers.keys())}Q.next(z)}if(z1(X)&&(J==="mutable_atom"||J==="atom")){if(X.on.transactionApplying.state===null){if(uY(_))return;let{timestamp:F}=X.operation,O={type:"atom_update",token:$,timestamp:F,update:z};X.transactionMeta.update.subEvents.push(O),X.logger.info("\uD83D\uDCC1","atom",H,"stowed (",Z,"->",_,")");return}if(WZ(Y,"tracker:signal")){let F=H.slice(1),O=X.atoms.get(F);if(f4(X,O,"mut").do(z.newValue)===null===!0)GZ(X,O)}}}var oY=(X,Y,Z)=>{let _=f4(X,Y,"mut"),G=dY(Z,_);return X.logger.info("\u2B50","atom",Y.key,"setting value",G),G=K1(X,Y,G),B6(X,Y.key),GZ(X,Y),{oldValue:_,newValue:G}};function mY(X,Y){switch(Y.type){case"mutable_atom":return oY(X,Y,new Y.class);case"atom":{let Z;if(H2(Y.default))Z=N6(X,Y);else Z=Y.default;return oY(X,Y,Z)}}}function HU(X,Y){let Z;switch(Y.type){case"atom":case"mutable_atom":Z=mY(X,Y);break;case"writable_held_selector":{let _=U2(X,Y.key);for(let W of _.values()){let $=mY(X,W);lY(X,Y,$,!1)}let G=Y.getFrom(X);Z={oldValue:G,newValue:G}}break;case"writable_pure_selector":{let _=N6(X,Y),G=U2(X,Y.key);for(let $ of G.values()){let H=mY(X,$);lY(X,Y,H,!1)}let W=N6(X,Y);Z={oldValue:_,newValue:W}}break}return Z}function k1(X,...Y){D8(I6,X,...Y)}var iY=Symbol("RESET");function R6(X,...Y){let Z=[...Y,iY];k1(X,...Z)}function JU(X,Y,Z){let _,G,W,{type:$,key:H}=Y;switch(Y.type){case"writable_pure_selector":_=f4(X,Y,"mut"),G=dY(Z,_),G=K1(X,Y,G);break;case"writable_held_selector":W=Y.const,dY(Z,W),_=W,G=W}return X.logger.info("\u2B50",$,H,"setting to",G),B6(X,H),Y.setSelf(G),{oldValue:_,newValue:G}}var QU=(X,Y,Z)=>{let _;switch(Y.type){case"atom":case"mutable_atom":_=oY(X,Y,Z);break;case"writable_pure_selector":case"writable_held_selector":_=JU(X,Y,Z);break}return _},I6=Symbol("OWN_OP"),tY=Symbol("JOIN_OP");function D8(X,Y,...Z){let _,G,W,$,H,Q;if(Z.length===2){if(W=Z[0],Q=Z[1],"family"in W)if($=nY(Y,W),H=X1(W.family.subKey),_=z2(Y,$,H),!_)W=G=Q2(J2,Y,$,H);else W=_}else if($=T0(Y,Z[0]),H=Z[1],Q=Z[2],_=z2(Y,$,H),!_)W=G=Q2(J2,Y,$,H);else W=_;let J=Q===iY?"reset":"set",z;if(X===I6){let D=X7(Y,W);if(typeof D==="number"){let w=D,A=Y.on.operationClose.subscribe(`waiting to ${J} "${W.key}" at T-${w}`,function(){A(),Y.logger.info("\uD83D\uDFE2",W.type,W.key,"resuming deferred",J,`from T-${w}`),D8(X,Y,W,Q)});return}z=D}else z=Y;if("counterfeit"in W&&"family"in W){let D=W.family.subKey,w=Y.disposalTraces.buffer.find((A)=>A?.key===D);Y.logger.error("\u274C",W.type,W.key,"could not be",J,"because key",D,"is not allocated.",w?`this key was previously disposed:${w.trace}`:"(no previous disposal trace found)");return}let F=T0(z,W),O;if(Q===iY)O=HU(z,F);else O=QU(z,F,Q);if(lY(z,F,O,Boolean(G),$),X===I6)Y7(z)}var _7=(X,Y)=>s(X).atoms.has(Y),zU=(X,Y)=>s(X).writableSelectors.has(Y),FU=(X,Y)=>s(X).readonlySelectors.has(Y),UU=(X,Y)=>_7(X,Y)||zU(X,Y)||FU(X,Y);function lG(X,Y){return s(X).selectorGraph.getRelationEntries({downstreamSelectorKey:Y}).filter(([Z,{source:_}])=>_!==Y).map(([Z,{source:_}])=>_).filter((Z)=>UU(X,Z))}function U2(X,Y,Z=new Set){let _=lG(X,Y),G=new Map;while(_.length>0){let W=_.pop();if(Z.has(W))continue;if(Z.add(W),_7(X,W)){let $=X.atoms.get(W);G.set($.key,$)}else _.push(...lG(X,W))}return G}function EU(X,Y,Z,_,G){let W=s(X),{type:$,key:H}=_;if($==="atom"||$==="mutable_atom")W.selectorAtoms.set({selectorKey:Z,atomKey:H}),X.logger.info("\uD83D\uDD0D",Y,Z,`discovers root atom "${H}"`);else{let Q=U2(X,H,G);X.logger.info("\uD83D\uDD0D",Y,Z,`discovers root atoms: [ ${[...Q.values()].map((J)=>`"${J.key}"`).join(", ")} ]`);for(let{key:J}of Q.values())W.selectorAtoms=W.selectorAtoms.set({selectorKey:Z,atomKey:J})}G.add(H)}function T6(X,Y,Z,_){return{get:(...G)=>{let W=s(X),{token:$,family:H,subKey:Q}=rY(X,...G),J;if("counterfeit"in $&&H&&Q)J=tG(X,$,H,Q);else{let z=T0(X,$);J=f4(X,z)}return X.logger.info("\uD83D\uDD0C",Y,Z,`registers dependency ( "${$.key}" =`,J,")"),W.selectorGraph.set({upstreamSelectorKey:$.key,downstreamSelectorKey:Z},{source:$.key}),EU(X,Y,Z,$,_),J},set:(...G)=>{let W=s(X);D8(tY,W,...G)},find:(...G)=>e0(X,...G),json:(G)=>h4(X,G)}}function aY(X,Y,Z){let _=s(X),G=new Z0,W=new Set,{key:$,const:H}=Y,Q="readonly_held_selector";X.logger.info("\uD83D\uDD28","readonly_held_selector",$,"is being created");let{get:J,find:z,json:F}=T6(_,"readonly_held_selector",$,W),D={...Y,type:"readonly_held_selector",subject:G,getFrom:(A)=>{let x=A.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[j,{source:P}]of x)if(P!==$)A.selectorGraph.delete(j,$);return A.selectorAtoms.delete($),Y.get({get:J,find:z,json:F},H),K1(A,D,H),X.logger.info("\u2728","readonly_held_selector",$,"=",H),W.clear(),H},install:(A)=>aY(A,Y,Z)};if(Z)D.family=Z;_.readonlySelectors.set($,D);let w={key:$,type:"readonly_held_selector"};if(Z)w.family=Z;return w}function eY(X,Y,Z){let _=s(X),G=new Z0,W=new Set,$=Y.key,H="readonly_pure_selector";X.logger.info("\uD83D\uDD28","readonly_pure_selector",$,"is being created");let{get:Q,find:J,json:z}=T6(_,"readonly_pure_selector",$,W),O={...Y,type:"readonly_pure_selector",subject:G,getFrom:()=>{let w=s(X),A=w.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[P,{source:h}]of A)if(h!==$)w.selectorGraph.delete(P,$);w.selectorAtoms.delete($);let x=Y.get({get:Q,find:J,json:z}),j=K1(w,O,x);return X.logger.info("\u2728","readonly_pure_selector",$,"=",j),W.clear(),j},install:(w)=>eY(w,Y,Z)};if(Z)O.family=Z;_.readonlySelectors.set($,O);let D={key:$,type:"readonly_pure_selector"};if(Z)D.family=Z;return D}function XZ(X,Y,Z){let _=s(X),G=new Z0,W=new Set,{key:$,const:H}=Y,Q="writable_held_selector";X.logger.info("\uD83D\uDD28","writable_held_selector",$,"is being created");let J=T6(_,"writable_held_selector",$,W),{find:z,get:F,json:O}=J,D={find:z,get:F,json:O},x={...Y,type:"writable_held_selector",subject:G,getFrom:(P)=>{let h=P.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[i,{source:p}]of h)if(p!==$)P.selectorGraph.delete(i,$);return P.selectorAtoms.delete($),Y.get(D,H),K1(P,x,H),X.logger.info("\u2728","writable_held_selector",$,"=",H),W.clear(),H},setSelf:()=>{Y.set(J,H)},install:(P)=>XZ(P,Y,Z)};if(Z)x.family=Z;_.writableSelectors.set($,x);let j={key:$,type:"writable_held_selector"};if(Z)j.family=Z;return j}function YZ(X,Y,Z){let _=s(X),G=new Z0,W=new Set,$=Y.key,H="writable_pure_selector";X.logger.info("\uD83D\uDD28","writable_pure_selector",$,"is being created");let Q=T6(_,"writable_pure_selector",$,W),{find:J,get:z,json:F}=Q,O={find:J,get:z,json:F},A={...Y,type:"writable_pure_selector",subject:G,getFrom:(j)=>{let P=j.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[p,{source:y}]of P)if(y!==$)j.selectorGraph.delete(p,$);j.selectorAtoms.delete($);let h=Y.get(O),i=K1(j,A,h);return X.logger.info("\u2728","writable_pure_selector",$,"=",i),W.clear(),i},setSelf:(j)=>{Y.set(Q,j)},install:(j)=>YZ(j,Y,Z)};if(Z)A.family=Z;_.writableSelectors.set($,A);let x={key:$,type:"writable_pure_selector"};if(Z)x.family=Z;return x}function hG(X,Y){let Z="set"in Y,_="const"in Y;if(_&&Z){let W=XZ(X,Y,void 0);return X.on.selectorCreation.next(W),W}if(_){let W=aY(X,Y,void 0);return X.on.selectorCreation.next(W),W}if(Z){let W=YZ(X,Y,void 0);return X.on.selectorCreation.next(W),W}let G=eY(X,Y,void 0);return X.on.selectorCreation.next(G),G}function OU(X,Y){let Z=s(X),{key:_,type:G,family:W}=Y;if(!W)X.logger.error("\u274C",G,_,"Standalone selectors cannot be disposed.");else{if(Z.molecules.get(W.subKey))Z.moleculeData.delete(W.subKey,W.key);let $;switch(Y.type){case"writable_held_selector":Z.writableSelectors.delete(_),$={key:W.key,type:"writable_held_selector_family"},T0(X,$).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break;case"writable_pure_selector":Z.writableSelectors.delete(_),$={key:W.key,type:"writable_pure_selector_family"},T0(X,$).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break;case"readonly_held_selector":Z.readonlySelectors.delete(_),$={key:W.key,type:"readonly_held_selector_family"},T0(X,$).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break;case"readonly_pure_selector":Z.readonlySelectors.delete(_),$={key:W.key,type:"readonly_pure_selector_family"},T0(X,$).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break}if(Z.valueMap.delete(_),Z.selectorAtoms.delete(_),Z.selectorGraph.delete(_),Z.moleculeData.delete(W.key,W.subKey),X.logger.info("\uD83D\uDD25",Y.type,_,"deleted"),z1(Z)&&Z.transactionMeta.phase==="building")Z.transactionMeta.update.subEvents.push({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});else X.on.selectorDisposal.next(Y)}}var VU=(X,Y)=>{let Z=s(X);if(Z.operation.open)return Z.operation.prev.get(Y.key);return Z.valueMap.get(Y.key)},oG=(X,Y,Z)=>{return Z.subject.subscribe(`${Y.type}:${Y.key}`,(_)=>{X.logger.info("\uD83D\uDCE2",Y.type,Y.key,"root",Z.key,"went",_.oldValue,"->",_.newValue);let G=VU(X,Y),W=f4(X,Y);X.logger.info("\u2728",Y.type,Y.key,"went",G,"->",W),Y.subject.next({newValue:W,oldValue:G})})};function E2(X,Y,Z,_){function G(F){if(X.operation.open){if(W?.type==="atom"&&WZ(W,"tracker:signal")&&"*"+X.operation.token.key===Y.key&&"inboundTracker"in _)return;let O=X.on.operationClose.subscribe(`state subscription ${Z}`,()=>{O(),_(F)})}else _(F)}rY(X,Y);let W=T0(X,Y);X.logger.info("\uD83D\uDC40",W.type,W.key,`Adding subscription "${Z}"`);let $=W.type==="writable_pure_selector"||W.type==="readonly_pure_selector",H=new Map,Q=G;if($){f4(X,W);for(let[F,O]of U2(X,W.key))H.set(F,oG(X,W,O));Q=function(O){let D=U2(X,W.key);for(let[w,A]of H)if(D.get(w))D.delete(w);else A(),H.delete(w);for(let[w,A]of D)H.set(w,oG(X,W,A));G(O)}}let J=W.subject.subscribe(Z,Q);return()=>{X.logger.info("\uD83D\uDE48",W.type,W.key,`Removing subscription "${Z}"`),J();for(let F of H.values())F()}}var DU=(X,Y,Z,_)=>{let G=T0(X,Y);X.logger.info("\uD83D\uDC40","timeline",Y.key,`Adding subscription "${Z}"`);let W=G.subject.subscribe(Z,_);return()=>{X.logger.info("\uD83D\uDE48","timeline",Y.key,`Removing subscription "${Z}" from timeline`),W()}};var ZZ=class{initializeSignalAtom(X,Y){let Z=`*${X.key}`;Y.atoms.delete(Z),Y.valueMap.delete(Z);let _=X.family?{key:`*${X.family.key}`,subKey:X.family.subKey}:void 0,G=x4(Y,{key:Z,default:null},_,["tracker:signal"]);if(Y.parent?.valueMap.has(Z)){let W=Y.parent.valueMap.get(Z);Y.valueMap.set(Z,W)}return G}unsubscribeFromInnerValue;unsubscribeFromState;captureSignalsFromCore(X,Y,Z){let _=X.key,G=Z.config.name,W=z1(Z)?Z.transactionMeta.update.token.key:"main",$=`tracker-from-core:${G}:${W}:${_}`,H=(Q)=>{D8(tY,Z,Y,Q)};this.unsubscribeFromInnerValue=h1(Z,X).subscribe($,H),this.unsubscribeFromState=E2(Z,X,$,function(J){if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe($,H)}.bind(this))}supplySignalsToCore(X,Y,Z){let _=X.key,G=Z.config.name,W=z1(Z)?Z.transactionMeta.update.token.key:"main",$=`tracker-to-core:${G}:${W}:${_}`;E2(Z,Y,$,Object.assign(function({newValue:Q,oldValue:J}){let z=Z.timelineTopics.getRelatedKey(Y.key);if(z&&Z.timelines.get(z)?.timeTraveling){let F=DU(Z,{key:z,type:"timeline"},$,function(D){F(),k1(Z,X,(w)=>{if(D==="redo"&&Q)w.do(Q);else if(D==="undo"&&J)w.undo(J);return w})});return}k1(Z,X,(F)=>(F.do(Q),F))},{inboundTracker:!0}))}mutableAtomToken;latestSignalToken;[Symbol.dispose];constructor(X,Y){let Z=s(Y),_=this.initializeSignalAtom(X,Z);this.mutableAtomToken=X,this.latestSignalToken=_,this.captureSignalsFromCore(X,_,Z),this.supplySignalsToCore(X,_,Z),Z.trackers.set(X.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),Z.trackers.delete(X.key)}}};function w6(X,Y,Z){X.logger.info("\uD83D\uDD28","atom",Y.key,`creating in store "${X.config.name}"`);let _=s(X),{key:G}=Y,W=_.atoms.get(G),$="mutable_atom";if(W&&W.type===$)return X.logger.error("\u274C",$,G,"Tried to create atom, but it already exists in the store."),y1(W);let H=new Z0,Q={...Y,type:$,install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${z.config.name}"`),w6(z,Y,Z)},subject:H};if(Z)Q.family=Z;_.atoms.set(Q.key,Q);let J=y1(Q);if(Y.effects){let z=0,F=[];for(let O of Y.effects){let D=O({resetSelf:()=>{R6(X,J)},setSelf:(w)=>{k1(X,J,w)},onSet:(w)=>E2(X,J,`effect[${z}]`,w)});if(D)F.push(D);++z}Q.cleanup=()=>{for(let O of F)O()}}if(new ZZ(J,X),!Z)hG(X,{key:`${G}:JSON`,get:({get:z})=>z(J).toJSON(),set:({set:z},F)=>{z(J,Y.class.fromJSON(F))}});return X.on.atomCreation.next(J),J}var LU=class{trackers=new Map;latestSignalAtoms;mutableAtoms;constructor(X,Y){let Z=G2(Y,{key:`*${X.key}`,default:null},["mutable","updates"]);this.latestSignalAtoms=T0(Y,Z),this.mutableAtoms=X;let _=(G)=>{let{type:W,token:$}=G;if($.family){let H=X1($.family.subKey);switch(W){case"state_creation":this.trackers.set(H,new ZZ($,Y));break;case"state_disposal":{let Q=this.trackers.get(H);if(Q)Q[Symbol.dispose](),this.trackers.delete(H)}}}};this.mutableAtoms.subject.subscribe(`store=${Y.config.name}::tracker-atom-family`,_)}};function yY(X,Y,Z){let _={key:Y.key,type:"mutable_atom_family"},G=X.families.get(Y.key);if(G)X.logger.error("\u2757","mutable_atom_family",Y.key,`Overwriting an existing ${_4[G.type]} "${G.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let W=new Z0,H={..._,create:(Q)=>{let J=w0(Q),z={key:Y.key,subKey:J},F=`${Y.key}(${J})`,O=s(X),D={key:F,class:Y.class};if(Y.effects)D.effects=Y.effects(Q);return w6(O,D,z)},class:Y.class,subject:W,install:(Q)=>yY(Q,Y),internalRoles:Z};return X.families.set(Y.key,H),sY(X,{key:`${Y.key}:JSON`,get:(Q)=>({get:J})=>J(_,Q).toJSON(),set:(Q)=>({set:J},z)=>{J(_,Q,Y.class.fromJSON(z))}},["mutable","json"]),new LU(H,X),_}var MU=(X,Y)=>{let Z=s(Y),_=`${X.key}:JSON`;return Z.families.get(_)},h4=(X,Y)=>{if(Y.family){let Z=s(X),_={key:`${Y.family.key}:JSON`,type:"writable_pure_selector_family"},G=T0(Z,_),W=X1(Y.family.subKey);return e0(X,G,W)}return{type:"writable_pure_selector",key:`${Y.key}:JSON`}};var _Z=(X)=>{let Y={type:"atom",key:`*${X.key}`};if(X.family)Y.family={key:`*${X.family.key}`,subKey:X.family.subKey};return Y};function uY(X){return typeof X==="object"&&X!==null&&"do"in X&&"undo"in X&&"subscribe"in X&&"READONLY_VIEW"in X&&"toJSON"in X}function K1(X,Y,Z){let{key:_,subject:G,type:W}=Y,$=X.valueMap.get(_);if($ instanceof cY&&!$.done){let H=$;if(Z instanceof Promise)return H.use(Z),H;return X.valueMap.set(_,Z),Z}if(Z instanceof Promise){let H=new cY(Z);return X.valueMap.set(_,H),H.then(function(J){if(X.valueMap.get(_)===H){switch(X7(X,Y),K1(X,Y,J),W){case"atom":GZ(X,Y);break;case"readonly_pure_selector":case"writable_pure_selector":W7(X,_);break}Y7(X),G.next({newValue:J,oldValue:H})}}).catch((Q)=>{X.logger.error("\uD83D\uDCA5",Y.type,_,"rejected:",Q)}),H}return X.logger.info("\uD83D\uDCDD",Y.type,Y.key,"writing to cache",Z),X.valueMap.set(_,Z),Z}function AU(X,Y,Z){X.logger.info("\uD83D\uDCD6",Y.type,Y.key,"reading cached value");let _=X.valueMap.get(Y.key);if(Z==="mut"&&Y.type==="mutable_atom"&&z1(X)){let G=Y,{parent:W}=X;if(X.valueMap.hasOwn(G.key))return _;let $=W.valueMap.get(G.key);X.logger.info("\uD83D\uDCC3","atom",G.key,"copying");let H=$.toJSON(),Q=G.class.fromJSON(H);X.valueMap.set(G.key,Q),new ZZ(G,W),_=Q}return _}function G7(X,Y){let Z=X.valueMap.get(Y);if(Z instanceof cY){let _=X.writableSelectors.get(Y)??X.readonlySelectors.get(Y);if(_)_.getFrom(X);return}if(X.operation.open)X.operation.prev.set(Y,Z);X.valueMap.delete(Y),X.logger.info("\uD83D\uDDD1","state",Y,"evicted")}function GZ(X,Y){let Z=s(X),{key:_,type:G}=Y,W=Z.selectorAtoms.getRelatedKeys(_);if(Z.logger.info("\uD83E\uDDF9",G,_,W?`evicting ${W.size} states downstream:`:"no downstream states",W??"to evict"),W){if(Z.operation.open)Z.logger.info("\uD83E\uDDF9",G,_,`[ ${[...Z.operation.done].join(", ")} ] already done`);for(let $ of W){if(Z7(Z,$))continue;G7(Z,$),B6(Z,$)}}}function W7(X,Y){let Z=s(X),_=Z.selectorGraph.getRelationEntries({upstreamSelectorKey:Y}).filter(([G,{source:W}])=>W===Y);for(let[G]of _){if(Z7(Z,G))continue;G7(Z,G),B6(Z,G),W7(X,G)}}function x4(X,Y,Z,_){let{key:W}=Y;X.logger.info("\uD83D\uDD28","atom",W,"is being created");let $=s(X),H=$.atoms.get(W);if(H&&H.type==="atom")return X.logger.error("\u274C","atom",W,"Tried to create atom, but it already exists in the store."),y1(H);let Q=new Z0,J={...Y,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",W,`installing in store "${F.config.name}"`),x4(F,Y,Z)},subject:Q};if(Z)J.family=Z;if(_)J.internalRoles=_;$.atoms.set(W,J);let z=y1(J);if(Y.effects){let F=0,O=[];for(let D of Y.effects){let w=D({resetSelf:()=>{R6(X,z)},setSelf:(A)=>{k1(X,z,A)},onSet:(A)=>E2(X,z,`effect[${F}]`,A)});if(w)O.push(w);++F}J.cleanup=()=>{for(let D of O)D()}}return X.on.atomCreation.next(z),z}function WZ(X,Y){if("internalRoles"in X===!1)return!1;return X.internalRoles.includes(Y)}function $7(X,Y){let Z=s(X),{key:_,family:G}=Y,W=T0(Z,Y);if(!G)X.logger.error("\u274C","atom",_,"Standalone atoms cannot be disposed.");else{W.cleanup?.();let $=X.valueMap.get(W.key),H=nY(X,Y),Q=T0(X,H).subject,J={type:"state_disposal",subType:"atom",token:Y,value:$,timestamp:Date.now()};Q.next(J);let z=z1(Z);if(Z.atoms.delete(_),Z.valueMap.delete(_),Z.selectorAtoms.delete(_),Z.atomsThatAreDefault.delete(_),Z.moleculeData.delete(G.key,G.subKey),X.timelineTopics.delete(_),Y.type==="mutable_atom"){let F=_Z(Y);$7(X,F),X.trackers.delete(_)}if(X.logger.info("\uD83D\uDD25","atom",_,"deleted"),z&&Z.transactionMeta.phase==="building"){let F=Z.transactionMeta.update.subEvents.at(-1),O=F?.type==="molecule_disposal"&&F.values.some(([w])=>w===W.family?.key),D=WZ(W,"tracker:signal");if(!O&&!D)Z.transactionMeta.update.subEvents.push(J)}else X.on.atomDisposal.next(Y)}}function I1(X){return X[0].toUpperCase()+X.slice(1)}var H7=class{toolkit;options;relations;states;relatedKeysAtoms;transact(X,Y){let Z=this.toolkit;this.toolkit=X,Y(this),this.toolkit=Z}store;realm;[Symbol.dispose](){}constructor(X,Y=Q1.STORE){this.store=Y,this.realm=new SG(Y),this.options=X,this.store.miscResources.set(`join:${X.key}`,this),this.realm.allocate("root",X.key),this.toolkit={get:(...z)=>h1(Y,...z),set:(...z)=>{k1(Y,...z)},find:(...z)=>e0(Y,...z),json:(z)=>h4(Y,z)};let Z=X.between[0],_=X.between[1],G=yY(Y,{key:`${X.key}/relatedKeys`,class:G4},["join","relations"]);this.relatedKeysAtoms=G;let W=(z,F,O)=>{let{find:D,get:w,set:A}=z,x=D(G,F),j=w(x);for(let P of j){if(O.includes(P))continue;A(G,P,(h)=>{return h.delete(F),h})}A(x,(P)=>{P.clear();for(let h of O){let i=D(G,h),p=w(i),y=p.has(F);if(this.relations.cardinality==="1:n"){let m=[];for(let _0 of p){if(_0===F)continue;let y0;if(D8(tY,this.store,G,_0,(K)=>{return K.delete(h),y0=K.size,K}),y0===0)m.push(_0)}if(!y&&p.size>0)A(i,(_0)=>{return _0.clear(),_0});for(let _0 of m){let[y0,K]=[h,_0].sort(),W0=`${y0}:${K}`;Y.moleculeJoins.delete(W0)}}if(!y)A(i,(m)=>{return m.add(F),m});P.add(h)}return P})},$=(z,F,O)=>{let{set:D}=z;D(G,F,(w)=>{for(let A of O)w.add(A);return w});for(let w of O)D(G,w,(A)=>{return A.add(F),A});return!0},H=new W4(X,{externalStore:{getRelatedKeys:(z)=>this.toolkit.get(G,z),addRelation:(z,F)=>{if(this.store.moleculeJoins.set(`"${z}"`,X.key),this.store.moleculeJoins.set(`"${F}"`,X.key),!this.store.molecules.has(w0(z)))this.realm.allocate(X.key,z);if(!this.store.molecules.has(w0(F)))this.realm.allocate(X.key,F);this.toolkit.set(G,z,(O)=>O.add(F)),this.toolkit.set(G,F,(O)=>O.add(z))},deleteRelation:(z,F)=>{this.toolkit.set(G,z,(A)=>{return A.delete(F),A}),this.toolkit.set(G,F,(A)=>{return A.delete(z),A});let[O,D]=[z,F].sort(),w=`${O}:${D}`;this.store.moleculeJoins.delete(w)},replaceRelationsSafely:(z,F)=>{W(this.toolkit,z,F)},replaceRelationsUnsafely:(z,F)=>{$(this.toolkit,z,F)},has:(z,F)=>{let O=this.toolkit.get(G,z);return F?O.has(F):O.size>0}},isAType:X.isAType,isBType:X.isBType}),Q=()=>F2(Y,{key:`${X.key}/singleRelatedKey`,get:(z)=>({get:F})=>{let O=F(G,z);for(let D of O)return D;return null}},["join","keys"]),J=()=>{return F2(Y,{key:`${X.key}/multipleRelatedKeys`,get:(z)=>({get:F})=>{let O=MU(G,Y);return F(O,z)}},["join","keys"])};switch(X.cardinality){case"1:1":{let z=Q(),F=`${Z}KeyOf${I1(_)}`,O=`${_}KeyOf${I1(Z)}`;this.relations=H,this.states={[F]:z,[O]:z};break}case"1:n":{let z=Q(),F=J(),O=`${Z}KeyOf${I1(_)}`,D=`${_}KeysOf${I1(Z)}`,w={[O]:z,[D]:F};this.relations=H,this.states=w;break}case"n:n":{let z=J(),F=`${Z}KeysOf${I1(_)}`,O=`${_}KeysOf${I1(Z)}`;this.relations=H,this.states={[F]:z,[O]:z}}}}};function kG(X,Y){return X.joins.set(Y.key,new H7(Y)),{key:Y.key,type:"join",a:Y.between[0],b:Y.between[1],cardinality:Y.cardinality}}function $Z(X,Y){let Z=Y.joins.get(X.key);if(Z===void 0){let _=Q1.STORE.joins.get(X.key);if(_===void 0)throw Error(`Join "${X.key}" not found in store "${Y.config.name}"`);let G=pF(Y);Z=new H7(_.options,G),Y.joins.set(X.key,Z)}return Z}function $2(X,Y,Z){let _=$Z(X,Z),G=s(Z);if(z1(G)){let{toolkit:W}=G.transactionMeta;_.transact(W,({relations:$})=>{Y($)})}else Y(_.relations)}function gF(X,Y,Z){let _=$Z(X,Z),G;switch(X.cardinality){case"1:1":{let W=`${X.a}KeyOf${I1(X.b)}`,$=`${X.b}KeyOf${I1(X.a)}`;G={get[W](){let H=_.states[W];return e0(Z,H,Y)},get[$](){let H=_.states[$];return e0(Z,H,Y)}};break}case"1:n":{let W=`${X.a}KeyOf${I1(X.b)}`,$=`${X.b}KeysOf${I1(X.a)}`;G={get[W](){let H=_.states[W];return e0(Z,H,Y)},get[$](){let H=_.states[$];return e0(Z,H,Y)}};break}case"n:n":{let W=`${X.a}KeysOf${I1(X.b)}`,$=`${X.b}KeysOf${I1(X.a)}`;G={get[W](){let H=_.states[W];return e0(Z,H,Y)},get[$](){let H=_.states[$];return e0(Z,H,Y)}}}}return G}function bG(X,Y){return $Z(X,Y).relatedKeysAtoms}var RU=(X)=>{return x4(X,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Y=new Map;for(let[Z,_]of X.atoms){if(V8(Z))continue;let G=y1(_);if(_.family){let W=Y.get(_.family.key);if(!W||!("familyMembers"in W))W={key:_.family.key,familyMembers:new Map},Y.set(_.family.key,W);W.familyMembers.set(_.family.subKey,G)}else Y.set(Z,G)}return Y},effects:[({setSelf:Y})=>{X.on.atomCreation.subscribe("introspection",(Z)=>{if(V8(Z.key))return;Y((_)=>{if(Z.family){let{key:G,subKey:W}=Z.family,$=_.get(G);if($===void 0||!("familyMembers"in $))$={key:G,familyMembers:new Map},_.set(G,$);$.familyMembers.set(W,Z)}else _.set(Z.key,Z);return new Map(_)})}),X.on.atomDisposal.subscribe("introspection",(Z)=>{Y((_)=>{if(Z.family){let{key:G,subKey:W}=Z.family,$=_.get(G);if($&&"familyMembers"in $){if($.familyMembers.delete(W),$.familyMembers.size===0)_.delete(G)}}return new Map(_)})})}]},void 0)},wU=(X)=>{return x4(X,{key:"\uD83D\uDD0D Selector Token Index",default:()=>{let Y=new Map;for(let Z of[X.readonlySelectors,X.writableSelectors])for(let[_,G]of Z){if(V8(_))continue;let W=y1(G);if(G.family){let $=Y.get(G.family.key);if(!$||!("familyMembers"in $))$={key:G.family.key,familyMembers:new Map},Y.set(G.family.key,$);$.familyMembers.set(G.family.subKey,W)}else Y.set(_,W)}return Y},effects:[({setSelf:Y})=>{X.on.selectorCreation.subscribe("introspection",(Z)=>{if(V8(Z.key))return;Y((_)=>{if(Z.family){let{key:G,subKey:W}=Z.family,$=_.get(G);if($===void 0||!("familyMembers"in $))$={key:G,familyMembers:new Map},_.set(G,$);$.familyMembers.set(W,Z)}else _.set(Z.key,Z);return new Map(_)})}),X.on.selectorDisposal.subscribe("introspection",(Z)=>{Y((_)=>{if(Z.family){let{key:G,subKey:W}=Z.family,$=_.get(G);if($&&"familyMembers"in $){if($.familyMembers.delete(W),$.familyMembers.size===0)_.delete(G)}}else _.delete(Z.key);return new Map(_)})})}]},void 0)};var HZ=class{supported;constructor(X){this.supported=X}refine(X){for(let[Y,Z]of Object.entries(this.supported))try{if(Z(X)===!0&&Z!==Boolean)return{type:Y,data:X}}catch(_){try{if(X instanceof Z)return{type:Y,data:X}}catch(G){}}return null}},Q7=new HZ({number:(X)=>typeof X==="number",string:(X)=>typeof X==="string",boolean:(X)=>typeof X==="boolean",null:(X)=>X===null});function z7(X){if(!X)return!1;return Object.getPrototypeOf(X)===Object.prototype}var F7=new HZ({object:z7,array:(X)=>Array.isArray(X)}),NU=new HZ({...Q7.supported,...F7.supported}),C6=(X)=>{if(X===void 0)return"undefined";let Y=NU.refine(X);if(Y)return Y.type;return Object.getPrototypeOf(X).constructor.name};var HB=class X{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Y=Q1.STORE){this.store=Y,this.atomIndex=RU(this.store),this.selectorIndex=wU(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:Z})=>{this.statesCreatedAt.set(Z,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:Z})=>{this.statesCreatedAt.delete(Z)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:Z})=>{this.statesCreatedAt.set(Z,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:Z})=>{this.statesCreatedAt.delete(Z)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(Y=X.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw Error("This Auditor has been disposed");let Z=hY(this.atomIndex),_=hY(this.selectorIndex),G=[...Z.values()].filter((Q)=>("familyMembers"in Q)),W=[..._.values()].filter((Q)=>("familyMembers"in Q)),$=performance.now(),H=[];if(Y.atomFamilies)for(let Q of G){let J=Q.familyMembers.values();for(let z of J){let F=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,O=$-F;H.push([z,O])}}if(Y.selectorFamilies)for(let Q of W){let J=Q.familyMembers.values();for(let z of J){let F=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,O=$-F;H.push([z,O])}}return H}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},J7=(X,Y)=>{let Z=(_,G)=>{let $=((Q,J)=>{let z=Y(Q,J);if(z)return z;return null})(_,G);if($?.jobComplete??$?.pathComplete)return $;let H=Array.isArray(G)?G.map((Q,J)=>[J,Q]):z7(G)?Object.entries(G):[];for(let[Q,J]of H){let z=Z([..._,Q],J);if(z?.jobComplete)return z}return{}};Z([],X)};function IU(X,Y){return{summary:`${X<Y?"+":"-"}${Math.abs(X-Y)} (${X} \u2192 ${Y})`}}function KU(X,Y){return{summary:`${X.length<Y.length?"+":"-"}${Math.abs(X.length-Y.length)} ("${X}" \u2192 "${Y}")`}}function BU(X,Y){return{summary:`${X} \u2192 ${Y}`}}function U7(X,Y,Z){let _="",G=[],W=[],$=[];return J7(X,(H,Q)=>{let J;for(J of H){let z=Y[J];if(z===void 0)W.push([J,JSON.stringify(Q)]);else{let F=Z(Q,z);if(F.summary!=="No Change")$.push([J,F])}}}),J7(Y,(H,Q)=>{let J;for(J of H)if(X[J]===void 0)G.push([J,JSON.stringify(Q)])}),_=`\uFF5E${$.length} \uFF0B${G.length} \uFF0D${W.length}`,{summary:_,added:G,removed:W,changed:$}}function TU(X,Y,Z){return U7(X,Y,Z)}var CU=class{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(X,Y,Z){this.leafRefinery=X,this.treeRefinery=Y,this.leafDiffers={},this.treeDiffers={};for(let _ of Object.keys(X.supported)){let G=Z[_];this.leafDiffers[_]=G}for(let _ of Object.keys(Y.supported)){let G=Z[_];this.treeDiffers[_]=G}}diff(X,Y){if(X===Y)return{summary:"No Change"};let Z=this.leafRefinery.refine(X)??this.treeRefinery.refine(X),_=this.leafRefinery.refine(Y)??this.treeRefinery.refine(Y);if(Z!==null&&_!==null){if(Z.type===_.type){if(Z.type in this.leafDiffers)return this.leafDiffers[Z.type](Z.data,_.data);if(Z.type in this.treeDiffers)return this.treeDiffers[Z.type](Z.data,_.data,($,H)=>this.diff($,H))}}let G=C6(X),W=C6(Y);if(G===W)return{summary:`${G} \u2192 ${W}`};return{summary:`Type change: ${G} \u2192 ${W}`}}},JB=new CU(Q7,F7,{number:IU,string:KU,boolean:BU,null:()=>({summary:"No Change"}),object:U7,array:TU});var qU=E8({key:"mutex",default:!1}),jU=class extends Map{set(X,Y){if(this.has(X))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:X,value:Y}),this;return super.set(X,Y)}},OB=class X{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Y){this.key=Y}static existing=new jU;static create(Y,Z){let _=new X(Y),{type:G,globals:W,actions:$,perspectives:H}=Z(_),Q={type:G,key:Y,globals:W,actions:$,perspectives:H};return X.existing.set(Y,Q),Q}add(...Y){switch(Y[0].type){case"atom":case"mutable_atom":this.globals.push(...Y);break;case"transaction":this.actions.push(...Y);break;case"atom_family":case"mutable_atom_family":{let[Z,_]=Y;this.perspectives.push({type:"realtime_perspective",resourceAtoms:Z,viewAtoms:_})}break}return this}};var VB=U8({key:"usersInRoomIndex",class:G4}),E7=U8({key:"roomIndex",class:G4});var O2=V6({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(X)=>typeof X==="string",isBType:(X)=>typeof X==="string"}),DB=D6({key:"usersInMyRoomView",get:(X)=>({find:Y})=>{let Z=qG(O2);return[Y(Z,X)]}});var TB=E8({key:"redactor",default:{occlude:(X)=>X}}),CB=E8({key:"unacknowledgedUpdates",default:()=>[]});var JZ=class{listeners;globalListeners;handleEvent(...X){let[Y,...Z]=X;for(let G of this.globalListeners)G(Y,...Z);let _=this.listeners.get(Y);if(_)for(let G of _)G(...Z)}id="no_id_retrieved";emit;constructor(X){this.emit=X,this.listeners=new Map,this.globalListeners=new Set}on(X,Y){let Z=this.listeners.get(X);if(Z)Z.add(Y);else this.listeners.set(X,new Set([Y]));return this}onAny(X){return this.globalListeners.add(X),this}off(X,Y){let Z=this.listeners.get(X);if(Z)if(Y)Z.delete(Y);else this.listeners.delete(X);return this}offAny(X){return this.globalListeners.delete(X),this}},qB=class extends JZ{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";proc;key;logger;handleLog(X){if(Array.isArray(X)){let[Y,...Z]=X;switch(Y){case"i":this.logger.info(...Z);break;case"w":this.logger.warn(...Z);break;case"e":this.logger.error(...Z);break}}}constructor(X,Y,Z){super((_,...G)=>{let W=JSON.stringify([_,...G])+"\x03",$=(H)=>{if(H.code==="EPIPE")console.error("EPIPE error during write",this.proc.stdin);this.proc.stdin.removeListener("error",$)};return this.proc.stdin.once("error",$),this.proc.stdin.write(W),this});if(this.proc=X,this.key=Y,this.logger=Z??{info:(..._)=>{console.info(this.id,this.key,..._)},warn:(..._)=>{console.warn(this.id,this.key,..._)},error:(..._)=>{console.error(this.id,this.key,..._)}},this.proc.stdout.on("data",(_)=>{let G=_.toString();if(G==="ALIVE"){this.logger.info(G);return}let W=G.split("\x03"),$=W[0];W[0]=this.incompleteData+$;let H=0;for(let Q of W){if(Q==="")continue;try{let J=X1(Q);this.handleEvent(...J),this.incompleteData=""}catch(J){if(J instanceof Error)console.error(["\u274C Malformed data received from child process","",Q,"",J.message].join(`
60
+ \u274C `));try{if(H===0){this.incompleteData=Q;let z=X1($);this.handleEvent(...z),this.incompleteData=""}else this.incompleteData+=Q}catch(z){if(z instanceof Error)console.error(["\u274C Malformed data received from child process","",$,"",z.message].join(`
61
+ \u274C `))}}++H}}),this.proc.stderr.on("data",(_)=>{let G=_.toString().split("\x03"),W=G[0];G[0]=this.incompleteData+W;let $=0;for(let H of G){if(H==="")continue;try{let Q=X1(H);this.handleLog(Q),this.incompleteData=""}catch(Q){if(Q instanceof Error)console.error(["\u274C Malformed log received from child process","",H,"",Q.message].join(`
62
+ \u274C `));try{if($===0){this.incompleteData=H;let J=X1(W);this.handleLog(J),this.incompleteData=""}else this.incompleteData+=H}catch(J){if(J instanceof Error)console.error(["\u274C Malformed log received from child process...","",W,"",J.message].join(`
63
+ \u274C `))}}++$}}),X.pid)this.id=X.pid.toString()}},SU=class extends JZ{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(X){super((...Y)=>{return this.out.next(Y),this});this.id=X,this.in=new Z0,this.out=new Z0,this.in.subscribe("socket",(Y)=>{this.handleEvent(...Y)})}dispose(){for(let X of this.disposalFunctions)X()}},V7=class extends JZ{incompleteData="";unprocessedEvents=[];relays;relayServices;proc;id="#####";log(...X){this.proc.stderr.write(w0(X.map((Y)=>Y instanceof G4?`{ ${Y.toJSON().join(" | ")} }`:Y))+"\x03")}logger={info:(...X)=>{this.log("i",...X)},warn:(...X)=>{this.log("w",...X)},error:(...X)=>{this.log("e",...X)}};constructor(X){super((Y,...Z)=>{let _=JSON.stringify([Y,...Z]);return this.proc.stdout.write(_+"\x03"),this});if(this.proc=X,this.proc.stdin.resume(),this.relays=new Map,this.relayServices=[],this.proc.stdin.on("data",(Y)=>{let Z=Y.toString().split("\x03"),_=Z[0];Z[0]=this.incompleteData+_;let G=0;for(let W of Z){if(W==="")continue;try{let $=X1(W);this.logger.info("\uD83C\uDFB0","received",$),this.handleEvent(...$),this.incompleteData=""}catch($){if($ instanceof Error)this.logger.error(["received malformed data from parent process:","",W,"",$.message].join(`
64
+ \u274C `));try{if(G===0){this.incompleteData=W;let H=X1(_);this.logger.info("\uD83C\uDFB0","received",H),this.handleEvent(...H),this.incompleteData=""}else this.incompleteData+=W}catch(H){if(H instanceof Error)this.logger.error(["received malformed data from parent process:","",_,"",H.message].join(`
65
+ \u274C `))}}++G}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),this.proc.exit(0)}),this.proc.pid)this.id=this.proc.pid?.toString();this.on("user-joins",(Y)=>{this.logger.info("\uD83D\uDC64","user",Y,"joined");let Z=`user::${Y}`,_=new SU(Z);this.relays.set(Y,_),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let G of this.relayServices){let W=G(_,Z);if(W)_.disposalFunctions.push(W)}this.on(Z,(...G)=>{_.in.next(G)}),_.out.subscribe("socket",(G)=>{this.emit(...G)})}),this.on("user-leaves",(Y)=>{let Z=this.relays.get(Y);if(this.off(`relay:${Y}`),Z)Z.dispose(),this.relays.delete(Y)}),this.proc.stdout.write("ALIVE")}receiveRelay(X){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(X)}};var O7=new Map;var jB=L6({key:"joinRoom",do:(X,Y,Z,_)=>{let G={enteredAtEpoch:_};return $2(O2,(W)=>{W.set({room:Y,user:Z})},X.env().store),G}}),SB=L6({key:"leaveRoom",do:({env:X},Y,Z)=>{$2(O2,(_)=>{_.delete({room:Y,user:Z})},X().store)}}),PB=L6({key:"destroyRoom",do:({set:X,env:Y},Z)=>{$2(O2,(G)=>{G.delete({room:Z})},Y().store),X(E7,(G)=>(G.delete(Z),G));let _=O7.get(Z);if(_)_.emit("exit"),O7.delete(Z)}}),vB=E8({key:"sockets",default:null}),xB=U8({key:"socketsIndex",class:G4}),fB=U8({key:"usersIndex",class:G4}),hB=V6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(X)=>X.startsWith("user::"),isBType:(X)=>X.startsWith("socket::")}),kB=D6({key:"userMutualSituationalAwarenessIndexes",get:(X)=>()=>{return[X]}});var{file:i$,serve:oE}=globalThis.Bun;import{readFileSync as M7}from"fs";import{createServer as fU}from"http";import{createServer as hU}from"https";import{resolve as zZ}from"path";function D7(X,Y){if(X instanceof Promise)throw Error(Y)}function PU(X,Y){let Z={},_=[];for(let G in X){let W=X[G]["~standard"].validate(Y[G]);if(D7(W,`Validation must be synchronous, but ${G} returned a Promise.`),W.issues){_.push(...W.issues.map(($)=>({...$,message:$.message,path:[G,...$.path??[]]})));continue}Z[G]=W.value}if(_.length)return{issues:_};return{value:Z}}function QZ(X){let Y=X.runtimeEnvStrict??X.runtimeEnv??process.env;if(X.emptyStringAsUndefined??!1){for(let[P,h]of Object.entries(Y))if(h==="")delete Y[P]}if(!!X.skipValidation)return Y;let G=typeof X.client==="object"?X.client:{},W=typeof X.server==="object"?X.server:{},$=typeof X.shared==="object"?X.shared:{},H=X.isServer??(typeof window>"u"||("Deno"in window)),Q=H?{...W,...$,...G}:{...G,...$},J=X.createFinalSchema?.(Q,H)["~standard"].validate(Y)??PU(Q,Y);D7(J,"Validation must be synchronous");let z=X.onValidationError??((P)=>{throw console.error("\u274C Invalid environment variables:",P),Error("Invalid environment variables")}),F=X.onInvalidAccess??(()=>{throw Error("\u274C Attempted to access a server-side environment variable on the client")});if(J.issues)return z(J.issues);let O=(P)=>{if(!X.clientPrefix)return!0;return!P.startsWith(X.clientPrefix)&&!(P in $)},D=(P)=>{return H||!O(P)},w=(P)=>{return P==="__esModule"||P==="$$typeof"},A=(X.extends??[]).reduce((P,h)=>{return Object.assign(P,h)},{}),x=Object.assign(A,J.value);return new Proxy(x,{get(P,h){if(typeof h!=="string")return;if(w(h))return;if(!D(h))return F(h);return Reflect.get(P,h)}})}var vU="__vite_start_time"in globalThis,xU=typeof window<"u",iB="vitest"in globalThis,$4=J1("string"),L7=J1('"true" | "false" | undefined'),g1=QZ({isServer:!vU&&!xU,server:{CI:J1("string | undefined").pipe(Boolean),POSTGRES_USER:$4,POSTGRES_PASSWORD:$4,POSTGRES_DATABASE:$4,POSTGRES_HOST:$4,POSTGRES_PORT:$4.pipe((X)=>Number.parseInt(X,10)),BACKEND_PORT:$4.pipe((X)=>Number.parseInt(X,10)),RUN_WORKERS_FROM_SOURCE:L7.pipe((X)=>X==="true"),FRONTEND_PORT:$4.pipe((X)=>Number.parseInt(X,10)),FRONTEND_ORIGINS:$4.pipe.try((X)=>JSON.parse(X),J1("string[]")),API_KEY_OPENAI:J1("string | undefined"),API_KEY_RESEND:J1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:$4,VITE_DEV_FRONTEND_HOST:J1("string | undefined"),VITE_DEV_HTTPS:L7.pipe((X)=>X==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var A7=zZ(import.meta.dirname,"../dev"),q6=g1.VITE_DEV_HTTPS?{cert:M7(zZ(A7,"./cert.pem"),"utf-8"),key:M7(zZ(A7,"./key.pem"),"utf-8")}:void 0;function XT(X){if(q6)return hU(q6,X);return fU({},X)}import gE from"path";var E=Symbol.for("drizzle:entityKind");function M(X,Y){if(!X||typeof X!=="object")return!1;if(X instanceof Y)return!0;if(!Object.prototype.hasOwnProperty.call(Y,E))throw Error(`Class "${Y.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 Z=Object.getPrototypeOf(X).constructor;if(Z)while(Z){if(E in Z&&Z[E]===Y[E])return!0;Z=Object.getPrototypeOf(Z)}return!1}class z0{constructor(X,Y){this.table=X,this.config=Y,this.name=Y.name,this.keyAsName=Y.keyAsName,this.notNull=Y.notNull,this.default=Y.default,this.defaultFn=Y.defaultFn,this.onUpdateFn=Y.onUpdateFn,this.hasDefault=Y.hasDefault,this.primary=Y.primaryKey,this.isUnique=Y.isUnique,this.uniqueName=Y.uniqueName,this.uniqueType=Y.uniqueType,this.dataType=Y.dataType,this.columnType=Y.columnType,this.generated=Y.generated,this.generatedIdentity=Y.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(X){return X}mapToDriverValue(X){return X}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class FZ{static[E]="ColumnBuilder";config;constructor(X,Y,Z){this.config={name:X,keyAsName:X==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:Y,columnType:Z,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(X){return this.config.default=X,this.config.hasDefault=!0,this}$defaultFn(X){return this.config.defaultFn=X,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(X){return this.config.onUpdateFn=X,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(X){if(this.config.name!=="")return;this.config.name=X}}var p1=Symbol.for("drizzle:Name");class UZ{static[E]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(X,Y){if(this.reference=()=>{let{name:Z,columns:_,foreignColumns:G}=X();return{name:Z,columns:_,foreignTable:G[0].table,foreignColumns:G}},Y)this._onUpdate=Y.onUpdate,this._onDelete=Y.onDelete}onUpdate(X){return this._onUpdate=X===void 0?"no action":X,this}onDelete(X){return this._onDelete=X===void 0?"no action":X,this}build(X){return new R7(X,this)}}class R7{constructor(X,Y){this.table=X,this.reference=Y.reference,this.onUpdate=Y._onUpdate,this.onDelete=Y._onDelete}static[E]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:X,columns:Y,foreignColumns:Z}=this.reference(),_=Y.map(($)=>$.name),G=Z.map(($)=>$.name),W=[this.table[p1],..._,Z[0].table[p1],...G];return X??`${W.join("_")}_fk`}}function j6(X,...Y){return X(...Y)}function w7(X,Y){return`${X[p1]}_${Y.join("_")}_unique`}function N7(X,Y,Z){for(let _=Y;_<X.length;_++){let G=X[_];if(G==="\\"){_++;continue}if(G==='"')return[X.slice(Y,_).replace(/\\/g,""),_+1];if(Z)continue;if(G===","||G==="}")return[X.slice(Y,_).replace(/\\/g,""),_]}return[X.slice(Y).replace(/\\/g,""),X.length]}function I7(X,Y=0){let Z=[],_=Y,G=!1;while(_<X.length){let W=X[_];if(W===","){if(G||_===Y)Z.push("");G=!0,_++;continue}if(G=!1,W==="\\"){_+=2;continue}if(W==='"'){let[Q,J]=N7(X,_+1,!0);Z.push(Q),_=J;continue}if(W==="}")return[Z,_+1];if(W==="{"){let[Q,J]=I7(X,_+1);Z.push(Q),_=J;continue}let[$,H]=N7(X,_,!1);Z.push($),_=H}return[Z,_]}function K7(X){let[Y]=I7(X,1);return Y}function EZ(X){return`{${X.map((Y)=>{if(Array.isArray(Y))return EZ(Y);if(typeof Y==="string")return`"${Y.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Y}`}).join(",")}}`}class v extends FZ{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(X){return new T7(this.config.name,this,X)}references(X,Y={}){return this.foreignKeyConfigs.push({ref:X,actions:Y}),this}unique(X,Y){return this.config.isUnique=!0,this.config.uniqueName=X,this.config.uniqueType=Y?.nulls,this}generatedAlwaysAs(X){return this.config.generated={as:X,type:"always",mode:"stored"},this}buildForeignKeys(X,Y){return this.foreignKeyConfigs.map(({ref:Z,actions:_})=>{return j6((G,W)=>{let $=new UZ(()=>{let H=G();return{columns:[X],foreignColumns:[H]}});if(W.onUpdate)$.onUpdate(W.onUpdate);if(W.onDelete)$.onDelete(W.onDelete);return $.build(Y)},Z,_)})}buildExtraConfigColumn(X){return new B7(X,this.config)}}class B extends z0{constructor(X,Y){if(!Y.uniqueName)Y.uniqueName=w7(X,[Y.name]);super(X,Y);this.table=X}static[E]="PgColumn"}class B7 extends B{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(X){return this.indexConfig.opClass=X,this}}class V2{static[E]="IndexedColumn";constructor(X,Y,Z,_){this.name=X,this.keyAsName=Y,this.type=Z,this.indexConfig=_}name;keyAsName;type;indexConfig}class T7 extends v{static[E]="PgArrayBuilder";constructor(X,Y,Z){super(X,"array","PgArray");this.config.baseBuilder=Y,this.config.size=Z}build(X){let Y=this.config.baseBuilder.build(X);return new OZ(X,this.config,Y)}}class OZ extends B{constructor(X,Y,Z,_){super(X,Y);this.baseColumn=Z,this.range=_,this.size=Y.size}size;static[E]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(X){if(typeof X==="string")X=K7(X);return X.map((Y)=>this.baseColumn.mapFromDriverValue(Y))}mapToDriverValue(X,Y=!1){let Z=X.map((_)=>_===null?null:M(this.baseColumn,OZ)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Y)return Z;return EZ(Z)}}class C7 extends v{static[E]="PgEnumObjectColumnBuilder";constructor(X,Y){super(X,"string","PgEnumObjectColumn");this.config.enum=Y}build(X){return new q7(X,this.config)}}class q7 extends B{static[E]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(X,Y){super(X,Y);this.enum=Y.enum}getSQLType(){return this.enum.enumName}}var S6=Symbol.for("drizzle:isPgEnum");function j7(X){return!!X&&typeof X==="function"&&S6 in X&&X[S6]===!0}class S7 extends v{static[E]="PgEnumColumnBuilder";constructor(X,Y){super(X,"string","PgEnumColumn");this.config.enum=Y}build(X){return new P7(X,this.config)}}class P7 extends B{static[E]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(X,Y){super(X,Y);this.enum=Y.enum}getSQLType(){return this.enum.enumName}}function D2(X,Y){return Array.isArray(Y)?kU(X,[...Y],void 0):bU(X,Y,void 0)}function kU(X,Y,Z){let _=Object.assign((G)=>new S7(G??"",_),{enumName:X,enumValues:Y,schema:Z,[S6]:!0});return _}function bU(X,Y,Z){let _=Object.assign((G)=>new C7(G??"",_),{enumName:X,enumValues:Object.values(Y),schema:Z,[S6]:!0});return _}class C0{static[E]="Subquery";constructor(X,Y,Z,_=!1,G=[]){this._={brand:"Subquery",sql:X,selectedFields:Y,alias:Z,isWith:_,usedTables:G}}}class L2 extends C0{static[E]="WithSubquery"}var v7="0.44.5";var VZ,DZ,F0={startActiveSpan(X,Y){if(!VZ)return Y();if(!DZ)DZ=VZ.trace.getTracer("drizzle-orm",v7);return j6((Z,_)=>_.startActiveSpan(X,(G)=>{try{return Y(G)}catch(W){throw G.setStatus({code:Z.SpanStatusCode.ERROR,message:W instanceof Error?W.message:"Unknown error"}),W}finally{G.end()}}),VZ,DZ)}};var V0=Symbol.for("drizzle:ViewBaseConfig");var k4=Symbol.for("drizzle:Schema"),P6=Symbol.for("drizzle:Columns"),x7=Symbol.for("drizzle:ExtraConfigColumns"),LZ=Symbol.for("drizzle:OriginalName"),MZ=Symbol.for("drizzle:BaseName"),M2=Symbol.for("drizzle:IsAlias"),f7=Symbol.for("drizzle:ExtraConfigBuilder"),yU=Symbol.for("drizzle:IsDrizzleTable");class T{static[E]="Table";static Symbol={Name:p1,Schema:k4,OriginalName:LZ,Columns:P6,ExtraConfigColumns:x7,BaseName:MZ,IsAlias:M2,ExtraConfigBuilder:f7};[p1];[LZ];[k4];[P6];[x7];[MZ];[M2]=!1;[yU]=!0;[f7]=void 0;constructor(X,Y,Z){this[p1]=this[LZ]=X,this[k4]=Y,this[MZ]=Z}}function g0(X){return X[p1]}function b4(X){return`${X[k4]??"public"}.${X[p1]}`}function AZ(X){return X!==null&&X!==void 0&&typeof X.getSQL==="function"}function gU(X){let Y={sql:"",params:[]};for(let Z of X)if(Y.sql+=Z.sql,Y.params.push(...Z.params),Z.typings?.length){if(!Y.typings)Y.typings=[];Y.typings.push(...Z.typings)}return Y}class k0{static[E]="StringChunk";value;constructor(X){this.value=Array.isArray(X)?X:[X]}getSQL(){return new S([this])}}class S{constructor(X){this.queryChunks=X;for(let Y of X)if(M(Y,T)){let Z=Y[T.Symbol.Schema];this.usedTables.push(Z===void 0?Y[T.Symbol.Name]:Z+"."+Y[T.Symbol.Name])}}static[E]="SQL";decoder=k7;shouldInlineParams=!1;usedTables=[];append(X){return this.queryChunks.push(...X.queryChunks),this}toQuery(X){return F0.startActiveSpan("drizzle.buildSQL",(Y)=>{let Z=this.buildQueryFromSourceParams(this.queryChunks,X);return Y?.setAttributes({"drizzle.query.text":Z.sql,"drizzle.query.params":JSON.stringify(Z.params)}),Z})}buildQueryFromSourceParams(X,Y){let Z=Object.assign({},Y,{inlineParams:Y.inlineParams||this.shouldInlineParams,paramStartIndex:Y.paramStartIndex||{value:0}}),{casing:_,escapeName:G,escapeParam:W,prepareTyping:$,inlineParams:H,paramStartIndex:Q}=Z;return gU(X.map((J)=>{if(M(J,k0))return{sql:J.value.join(""),params:[]};if(M(J,v6))return{sql:G(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let z=[new k0("(")];for(let[F,O]of J.entries())if(z.push(O),F<J.length-1)z.push(new k0(", "));return z.push(new k0(")")),this.buildQueryFromSourceParams(z,Z)}if(M(J,S))return this.buildQueryFromSourceParams(J.queryChunks,{...Z,inlineParams:H||J.shouldInlineParams});if(M(J,T)){let z=J[T.Symbol.Schema],F=J[T.Symbol.Name];return{sql:z===void 0||J[M2]?G(F):G(z)+"."+G(F),params:[]}}if(M(J,z0)){let z=_.getColumnCasing(J);if(Y.invokeSource==="indexes")return{sql:G(z),params:[]};let F=J.table[T.Symbol.Schema];return{sql:J.table[M2]||F===void 0?G(J.table[T.Symbol.Name])+"."+G(z):G(F)+"."+G(J.table[T.Symbol.Name])+"."+G(z),params:[]}}if(M(J,F1)){let z=J[V0].schema,F=J[V0].name;return{sql:z===void 0||J[V0].isAlias?G(F):G(z)+"."+G(F),params:[]}}if(M(J,L1)){if(M(J.value,w4))return{sql:W(Q.value++,J),params:[J],typings:["none"]};let z=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(M(z,S))return this.buildQueryFromSourceParams([z],Z);if(H)return{sql:this.mapInlineParam(z,Z),params:[]};let F=["none"];if($)F=[$(J.encoder)];return{sql:W(Q.value++,z),params:[z],typings:F}}if(M(J,w4))return{sql:W(Q.value++,J),params:[J],typings:["none"]};if(M(J,S.Aliased)&&J.fieldAlias!==void 0)return{sql:G(J.fieldAlias),params:[]};if(M(J,C0)){if(J._.isWith)return{sql:G(J._.alias),params:[]};return this.buildQueryFromSourceParams([new k0("("),J._.sql,new k0(") "),new v6(J._.alias)],Z)}if(j7(J)){if(J.schema)return{sql:G(J.schema)+"."+G(J.enumName),params:[]};return{sql:G(J.enumName),params:[]}}if(AZ(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],Z);return this.buildQueryFromSourceParams([new k0("("),J.getSQL(),new k0(")")],Z)}if(H)return{sql:this.mapInlineParam(J,Z),params:[]};return{sql:W(Q.value++,J),params:[J],typings:["none"]}}))}mapInlineParam(X,{escapeString:Y}){if(X===null)return"null";if(typeof X==="number"||typeof X==="boolean")return X.toString();if(typeof X==="string")return Y(X);if(typeof X==="object"){let Z=X.toString();if(Z==="[object Object]")return Y(JSON.stringify(X));return Y(Z)}throw Error("Unexpected param value: "+X)}getSQL(){return this}as(X){if(X===void 0)return this;return new S.Aliased(this,X)}mapWith(X){return this.decoder=typeof X==="function"?{mapFromDriverValue:X}:X,this}inlineParams(){return this.shouldInlineParams=!0,this}if(X){return X?this:void 0}}class v6{constructor(X){this.value=X}static[E]="Name";brand;getSQL(){return new S([this])}}function h7(X){return typeof X==="object"&&X!==null&&"mapToDriverValue"in X&&typeof X.mapToDriverValue==="function"}var k7={mapFromDriverValue:(X)=>X},b7={mapToDriverValue:(X)=>X},dT={...k7,...b7};class L1{constructor(X,Y=b7){this.value=X,this.encoder=Y}static[E]="Param";brand;getSQL(){return new S([this])}}function V(X,...Y){let Z=[];if(Y.length>0||X.length>0&&X[0]!=="")Z.push(new k0(X[0]));for(let[_,G]of Y.entries())Z.push(G,new k0(X[_+1]));return new S(Z)}((X)=>{function Y(){return new S([])}X.empty=Y;function Z(Q){return new S(Q)}X.fromList=Z;function _(Q){return new S([new k0(Q)])}X.raw=_;function G(Q,J){let z=[];for(let[F,O]of Q.entries()){if(F>0&&J!==void 0)z.push(J);z.push(O)}return new S(z)}X.join=G;function W(Q){return new v6(Q)}X.identifier=W;function $(Q){return new w4(Q)}X.placeholder=$;function H(Q,J){return new L1(Q,J)}X.param=H})(V||(V={}));((X)=>{class Y{constructor(Z,_){this.sql=Z,this.fieldAlias=_}static[E]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Y(this.sql,this.fieldAlias)}}X.Aliased=Y})(S||(S={}));class w4{constructor(X){this.name=X}static[E]="Placeholder";getSQL(){return new S([this])}}function RZ(X,Y){return X.map((Z)=>{if(M(Z,w4)){if(!(Z.name in Y))throw Error(`No value for placeholder "${Z.name}" was provided`);return Y[Z.name]}if(M(Z,L1)&&M(Z.value,w4)){if(!(Z.value.name in Y))throw Error(`No value for placeholder "${Z.value.name}" was provided`);return Z.encoder.mapToDriverValue(Y[Z.value.name])}return Z})}var pU=Symbol.for("drizzle:IsDrizzleView");class F1{static[E]="View";[V0];[pU]=!0;constructor({name:X,schema:Y,selectedFields:Z,query:_}){this[V0]={name:X,originalName:X,schema:Y,selectedFields:Z,query:_,isExisting:!_,isAlias:!1}}getSQL(){return new S([this])}}z0.prototype.getSQL=function(){return new S([this])};T.prototype.getSQL=function(){return new S([this])};C0.prototype.getSQL=function(){return new S([this])};class L8{constructor(X){this.table=X}static[E]="ColumnAliasProxyHandler";get(X,Y){if(Y==="table")return this.table;return X[Y]}}class A2{constructor(X,Y){this.alias=X,this.replaceOriginalName=Y}static[E]="TableAliasProxyHandler";get(X,Y){if(Y===T.Symbol.IsAlias)return!0;if(Y===T.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Y===T.Symbol.OriginalName)return this.alias;if(Y===V0)return{...X[V0],name:this.alias,isAlias:!0};if(Y===T.Symbol.Columns){let _=X[T.Symbol.Columns];if(!_)return _;let G={};return Object.keys(_).map((W)=>{G[W]=new Proxy(_[W],new L8(new Proxy(X,this)))}),G}let Z=X[Y];if(M(Z,z0))return new Proxy(Z,new L8(new Proxy(X,this)));return Z}}function x6(X,Y){return new Proxy(X,new A2(Y,!1))}function i1(X,Y){return new Proxy(X,new L8(new Proxy(X.table,new A2(Y,!1))))}function wZ(X,Y){return new S.Aliased(R2(X.sql,Y),X.fieldAlias)}function R2(X,Y){return V.join(X.queryChunks.map((Z)=>{if(M(Z,z0))return i1(Z,Y);if(M(Z,S))return R2(Z,Y);if(M(Z,S.Aliased))return wZ(Z,Y);return Z}))}class f6 extends Error{static[E]="DrizzleError";constructor({message:X,cause:Y}){super(X);this.name="DrizzleError",this.cause=Y}}class H4 extends Error{constructor(X,Y,Z){super(`Failed query: ${X}
66
+ params: ${Y}`);if(this.query=X,this.params=Y,this.cause=Z,Error.captureStackTrace(this,H4),Z)this.cause=Z}}class NZ extends f6{static[E]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class y7{static[E]="ConsoleLogWriter";write(X){console.log(X)}}class IZ{static[E]="DefaultLogger";writer;constructor(X){this.writer=X?.writer??new y7}logQuery(X,Y){let Z=Y.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),_=Z.length?` -- params: [${Z.join(", ")}]`:"";this.writer.write(`Query: ${X}${_}`)}}class KZ{static[E]="NoopLogger";logQuery(){}}class Y1{static[E]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(X){return this.then(void 0,X)}finally(X){return this.then((Y)=>{return X?.(),Y},(Y)=>{throw X?.(),Y})}then(X,Y){return this.execute().then(X,Y)}}function g7(X,Y,Z){let _={},G=X.reduce((W,{path:$,field:H},Q)=>{let J;if(M(H,z0))J=H;else if(M(H,S))J=H.decoder;else J=H.sql.decoder;let z=W;for(let[F,O]of $.entries())if(F<$.length-1){if(!(O in z))z[O]={};z=z[O]}else{let D=Y[Q],w=z[O]=D===null?null:J.mapFromDriverValue(D);if(Z&&M(H,z0)&&$.length===2){let A=$[0];if(!(A in _))_[A]=w===null?g0(H.table):!1;else if(typeof _[A]==="string"&&_[A]!==g0(H.table))_[A]=!1}}return W},{});if(Z&&Object.keys(_).length>0){for(let[W,$]of Object.entries(_))if(typeof $==="string"&&!Z[$])G[W]=null}return G}function B1(X,Y){return Object.entries(X).reduce((Z,[_,G])=>{if(typeof _!=="string")return Z;let W=Y?[...Y,_]:[_];if(M(G,z0)||M(G,S)||M(G,S.Aliased))Z.push({path:W,field:G});else if(M(G,T))Z.push(...B1(G[T.Symbol.Columns],W));else Z.push(...B1(G,W));return Z},[])}function w2(X,Y){let Z=Object.keys(X),_=Object.keys(Y);if(Z.length!==_.length)return!1;for(let[G,W]of Z.entries())if(W!==_[G])return!1;return!0}function h6(X,Y){let Z=Object.entries(Y).filter(([,_])=>_!==void 0).map(([_,G])=>{if(M(G,S)||M(G,z0))return[_,G];else return[_,new L1(G,X[T.Symbol.Columns][_])]});if(Z.length===0)throw Error("No values to set");return Object.fromEntries(Z)}function p7(X,Y){for(let Z of Y)for(let _ of Object.getOwnPropertyNames(Z.prototype)){if(_==="constructor")continue;Object.defineProperty(X.prototype,_,Object.getOwnPropertyDescriptor(Z.prototype,_)||Object.create(null))}}function m7(X){return X[T.Symbol.Columns]}function J4(X){return M(X,C0)?X._.alias:M(X,F1)?X[V0].name:M(X,S)?void 0:X[T.Symbol.IsAlias]?X[T.Symbol.Name]:X[T.Symbol.BaseName]}function a(X,Y){return{name:typeof X==="string"&&X.length>0?X:"",config:typeof X==="object"?X:Y}}function u7(X){if(typeof X!=="object"||X===null)return!1;if(X.constructor.name!=="Object")return!1;if("logger"in X){let Y=typeof X.logger;if(Y!=="boolean"&&(Y!=="object"||typeof X.logger.logQuery!=="function")&&Y!=="undefined")return!1;return!0}if("schema"in X){let Y=typeof X.schema;if(Y!=="object"&&Y!=="undefined")return!1;return!0}if("casing"in X){let Y=typeof X.casing;if(Y!=="string"&&Y!=="undefined")return!1;return!0}if("mode"in X){if(X.mode!=="default"||X.mode!=="planetscale"||X.mode!==void 0)return!1;return!0}if("connection"in X){let Y=typeof X.connection;if(Y!=="string"&&Y!=="object"&&Y!=="undefined")return!1;return!0}if("client"in X){let Y=typeof X.client;if(Y!=="object"&&Y!=="function"&&Y!=="undefined")return!1;return!0}if(Object.keys(X).length===0)return!0;return!1}class N4 extends v{static[E]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(X){if(X){let{name:Y,...Z}=X;this.config.generatedIdentity={type:"always",sequenceName:Y,sequenceOptions:Z}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(X){if(X){let{name:Y,...Z}=X;this.config.generatedIdentity={type:"byDefault",sequenceName:Y,sequenceOptions:Z}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class d7 extends N4{static[E]="PgBigInt53Builder";constructor(X){super(X,"number","PgBigInt53")}build(X){return new c7(X,this.config)}}class c7 extends B{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}}class l7 extends N4{static[E]="PgBigInt64Builder";constructor(X){super(X,"bigint","PgBigInt64")}build(X){return new o7(X,this.config)}}class o7 extends B{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(X){return BigInt(X)}}function i7(X,Y){let{name:Z,config:_}=a(X,Y);if(_.mode==="number")return new d7(Z);return new l7(Z)}class n7 extends v{static[E]="PgBigSerial53Builder";constructor(X){super(X,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new r7(X,this.config)}}class r7 extends B{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}}class s7 extends v{static[E]="PgBigSerial64Builder";constructor(X){super(X,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(X){return new t7(X,this.config)}}class t7 extends B{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(X){return BigInt(X)}}function a7(X,Y){let{name:Z,config:_}=a(X,Y);if(_.mode==="number")return new n7(Z);return new s7(Z)}class e7 extends v{static[E]="PgBooleanBuilder";constructor(X){super(X,"boolean","PgBoolean")}build(X){return new X3(X,this.config)}}class X3 extends B{static[E]="PgBoolean";getSQLType(){return"boolean"}}function N2(X){return new e7(X??"")}class Y3 extends v{static[E]="PgCharBuilder";constructor(X,Y){super(X,"string","PgChar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(X){return new Z3(X,this.config)}}class Z3 extends B{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function _3(X,Y={}){let{name:Z,config:_}=a(X,Y);return new Y3(Z,_)}class G3 extends v{static[E]="PgCidrBuilder";constructor(X){super(X,"string","PgCidr")}build(X){return new W3(X,this.config)}}class W3 extends B{static[E]="PgCidr";getSQLType(){return"cidr"}}function $3(X){return new G3(X??"")}class H3 extends v{static[E]="PgCustomColumnBuilder";constructor(X,Y,Z){super(X,"custom","PgCustomColumn");this.config.fieldConfig=Y,this.config.customTypeParams=Z}build(X){return new J3(X,this.config)}}class J3 extends B{static[E]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(X,Y){super(X,Y);this.sqlName=Y.customTypeParams.dataType(Y.fieldConfig),this.mapTo=Y.customTypeParams.toDriver,this.mapFrom=Y.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(X){return typeof this.mapFrom==="function"?this.mapFrom(X):X}mapToDriverValue(X){return typeof this.mapTo==="function"?this.mapTo(X):X}}function Q3(X){return(Y,Z)=>{let{name:_,config:G}=a(Y,Z);return new H3(_,G,X)}}class Q4 extends v{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(V`now()`)}}class z3 extends Q4{static[E]="PgDateBuilder";constructor(X){super(X,"date","PgDate")}build(X){return new k6(X,this.config)}}class k6 extends B{static[E]="PgDate";getSQLType(){return"date"}mapFromDriverValue(X){return new Date(X)}mapToDriverValue(X){return X.toISOString()}}class F3 extends Q4{static[E]="PgDateStringBuilder";constructor(X){super(X,"string","PgDateString")}build(X){return new b6(X,this.config)}}class b6 extends B{static[E]="PgDateString";getSQLType(){return"date"}}function U3(X,Y){let{name:Z,config:_}=a(X,Y);if(_?.mode==="date")return new z3(Z);return new F3(Z)}class E3 extends v{static[E]="PgDoublePrecisionBuilder";constructor(X){super(X,"number","PgDoublePrecision")}build(X){return new O3(X,this.config)}}class O3 extends B{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(X){if(typeof X==="string")return Number.parseFloat(X);return X}}function V3(X){return new E3(X??"")}class D3 extends v{static[E]="PgInetBuilder";constructor(X){super(X,"string","PgInet")}build(X){return new L3(X,this.config)}}class L3 extends B{static[E]="PgInet";getSQLType(){return"inet"}}function M3(X){return new D3(X??"")}class A3 extends N4{static[E]="PgIntegerBuilder";constructor(X){super(X,"number","PgInteger")}build(X){return new R3(X,this.config)}}class R3 extends B{static[E]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(X){if(typeof X==="string")return Number.parseInt(X);return X}}function I2(X){return new A3(X??"")}class w3 extends v{static[E]="PgIntervalBuilder";constructor(X,Y){super(X,"string","PgInterval");this.config.intervalConfig=Y}build(X){return new N3(X,this.config)}}class N3 extends B{static[E]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let X=this.fields?` ${this.fields}`:"",Y=this.precision?`(${this.precision})`:"";return`interval${X}${Y}`}}function I3(X,Y={}){let{name:Z,config:_}=a(X,Y);return new w3(Z,_)}class K3 extends v{static[E]="PgJsonBuilder";constructor(X){super(X,"json","PgJson")}build(X){return new y6(X,this.config)}}class y6 extends B{static[E]="PgJson";constructor(X,Y){super(X,Y)}getSQLType(){return"json"}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){if(typeof X==="string")try{return JSON.parse(X)}catch{return X}return X}}function B3(X){return new K3(X??"")}class T3 extends v{static[E]="PgJsonbBuilder";constructor(X){super(X,"json","PgJsonb")}build(X){return new g6(X,this.config)}}class g6 extends B{static[E]="PgJsonb";constructor(X,Y){super(X,Y)}getSQLType(){return"jsonb"}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){if(typeof X==="string")try{return JSON.parse(X)}catch{return X}return X}}function C3(X){return new T3(X??"")}class q3 extends v{static[E]="PgLineBuilder";constructor(X){super(X,"array","PgLine")}build(X){return new j3(X,this.config)}}class j3 extends B{static[E]="PgLine";getSQLType(){return"line"}mapFromDriverValue(X){let[Y,Z,_]=X.slice(1,-1).split(",");return[Number.parseFloat(Y),Number.parseFloat(Z),Number.parseFloat(_)]}mapToDriverValue(X){return`{${X[0]},${X[1]},${X[2]}}`}}class S3 extends v{static[E]="PgLineABCBuilder";constructor(X){super(X,"json","PgLineABC")}build(X){return new P3(X,this.config)}}class P3 extends B{static[E]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(X){let[Y,Z,_]=X.slice(1,-1).split(",");return{a:Number.parseFloat(Y),b:Number.parseFloat(Z),c:Number.parseFloat(_)}}mapToDriverValue(X){return`{${X.a},${X.b},${X.c}}`}}function v3(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new q3(Z);return new S3(Z)}class x3 extends v{static[E]="PgMacaddrBuilder";constructor(X){super(X,"string","PgMacaddr")}build(X){return new f3(X,this.config)}}class f3 extends B{static[E]="PgMacaddr";getSQLType(){return"macaddr"}}function h3(X){return new x3(X??"")}class k3 extends v{static[E]="PgMacaddr8Builder";constructor(X){super(X,"string","PgMacaddr8")}build(X){return new b3(X,this.config)}}class b3 extends B{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}}function y3(X){return new k3(X??"")}class g3 extends v{static[E]="PgNumericBuilder";constructor(X,Y,Z){super(X,"string","PgNumeric");this.config.precision=Y,this.config.scale=Z}build(X){return new p6(X,this.config)}}class p6 extends B{static[E]="PgNumeric";precision;scale;constructor(X,Y){super(X,Y);this.precision=Y.precision,this.scale=Y.scale}mapFromDriverValue(X){if(typeof X==="string")return X;return String(X)}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 p3 extends v{static[E]="PgNumericNumberBuilder";constructor(X,Y,Z){super(X,"number","PgNumericNumber");this.config.precision=Y,this.config.scale=Z}build(X){return new m3(X,this.config)}}class m3 extends B{static[E]="PgNumericNumber";precision;scale;constructor(X,Y){super(X,Y);this.precision=Y.precision,this.scale=Y.scale}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}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 u3 extends v{static[E]="PgNumericBigIntBuilder";constructor(X,Y,Z){super(X,"bigint","PgNumericBigInt");this.config.precision=Y,this.config.scale=Z}build(X){return new d3(X,this.config)}}class d3 extends B{static[E]="PgNumericBigInt";precision;scale;constructor(X,Y){super(X,Y);this.precision=Y.precision,this.scale=Y.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 c3(X,Y){let{name:Z,config:_}=a(X,Y),G=_?.mode;return G==="number"?new p3(Z,_?.precision,_?.scale):G==="bigint"?new u3(Z,_?.precision,_?.scale):new g3(Z,_?.precision,_?.scale)}class l3 extends v{static[E]="PgPointTupleBuilder";constructor(X){super(X,"array","PgPointTuple")}build(X){return new o3(X,this.config)}}class o3 extends B{static[E]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(X){if(typeof X==="string"){let[Y,Z]=X.slice(1,-1).split(",");return[Number.parseFloat(Y),Number.parseFloat(Z)]}return[X.x,X.y]}mapToDriverValue(X){return`(${X[0]},${X[1]})`}}class i3 extends v{static[E]="PgPointObjectBuilder";constructor(X){super(X,"json","PgPointObject")}build(X){return new n3(X,this.config)}}class n3 extends B{static[E]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(X){if(typeof X==="string"){let[Y,Z]=X.slice(1,-1).split(",");return{x:Number.parseFloat(Y),y:Number.parseFloat(Z)}}return X}mapToDriverValue(X){return`(${X.x},${X.y})`}}function r3(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new l3(Z);return new i3(Z)}function mU(X){let Y=[];for(let Z=0;Z<X.length;Z+=2)Y.push(Number.parseInt(X.slice(Z,Z+2),16));return new Uint8Array(Y)}function s3(X,Y){let Z=new ArrayBuffer(8),_=new DataView(Z);for(let G=0;G<8;G++)_.setUint8(G,X[Y+G]);return _.getFloat64(0,!0)}function BZ(X){let Y=mU(X),Z=0,_=Y[Z];Z+=1;let G=new DataView(Y.buffer),W=G.getUint32(Z,_===1);Z+=4;let $;if(W&536870912)$=G.getUint32(Z,_===1),Z+=4;if((W&65535)===1){let H=s3(Y,Z);Z+=8;let Q=s3(Y,Z);return Z+=8,[H,Q]}throw Error("Unsupported geometry type")}class t3 extends v{static[E]="PgGeometryBuilder";constructor(X){super(X,"array","PgGeometry")}build(X){return new a3(X,this.config)}}class a3 extends B{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(X){return BZ(X)}mapToDriverValue(X){return`point(${X[0]} ${X[1]})`}}class e3 extends v{static[E]="PgGeometryObjectBuilder";constructor(X){super(X,"json","PgGeometryObject")}build(X){return new XW(X,this.config)}}class XW extends B{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(X){let Y=BZ(X);return{x:Y[0],y:Y[1]}}mapToDriverValue(X){return`point(${X.x} ${X.y})`}}function YW(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new t3(Z);return new e3(Z)}class ZW extends v{static[E]="PgRealBuilder";constructor(X,Y){super(X,"number","PgReal");this.config.length=Y}build(X){return new _W(X,this.config)}}class _W extends B{static[E]="PgReal";constructor(X,Y){super(X,Y)}getSQLType(){return"real"}mapFromDriverValue=(X)=>{if(typeof X==="string")return Number.parseFloat(X);return X}}function GW(X){return new ZW(X??"")}class WW extends v{static[E]="PgSerialBuilder";constructor(X){super(X,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new $W(X,this.config)}}class $W extends B{static[E]="PgSerial";getSQLType(){return"serial"}}function HW(X){return new WW(X??"")}class JW extends N4{static[E]="PgSmallIntBuilder";constructor(X){super(X,"number","PgSmallInt")}build(X){return new QW(X,this.config)}}class QW extends B{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(X)=>{if(typeof X==="string")return Number(X);return X}}function zW(X){return new JW(X??"")}class FW extends v{static[E]="PgSmallSerialBuilder";constructor(X){super(X,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new UW(X,this.config)}}class UW extends B{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}}function EW(X){return new FW(X??"")}class OW extends v{static[E]="PgTextBuilder";constructor(X,Y){super(X,"string","PgText");this.config.enumValues=Y.enum}build(X){return new VW(X,this.config)}}class VW extends B{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function DW(X,Y={}){let{name:Z,config:_}=a(X,Y);return new OW(Z,_)}class LW extends Q4{constructor(X,Y,Z){super(X,"string","PgTime");this.withTimezone=Y,this.precision=Z,this.config.withTimezone=Y,this.config.precision=Z}static[E]="PgTimeBuilder";build(X){return new m6(X,this.config)}}class m6 extends B{static[E]="PgTime";withTimezone;precision;constructor(X,Y){super(X,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function MW(X,Y={}){let{name:Z,config:_}=a(X,Y);return new LW(Z,_.withTimezone??!1,_.precision)}class AW extends Q4{static[E]="PgTimestampBuilder";constructor(X,Y,Z){super(X,"date","PgTimestamp");this.config.withTimezone=Y,this.config.precision=Z}build(X){return new u6(X,this.config)}}class u6 extends B{static[E]="PgTimestamp";withTimezone;precision;constructor(X,Y){super(X,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(X)=>{return new Date(this.withTimezone?X:X+"+0000")};mapToDriverValue=(X)=>{return X.toISOString()}}class RW extends Q4{static[E]="PgTimestampStringBuilder";constructor(X,Y,Z){super(X,"string","PgTimestampString");this.config.withTimezone=Y,this.config.precision=Z}build(X){return new d6(X,this.config)}}class d6 extends B{static[E]="PgTimestampString";withTimezone;precision;constructor(X,Y){super(X,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function wW(X,Y={}){let{name:Z,config:_}=a(X,Y);if(_?.mode==="string")return new RW(Z,_.withTimezone??!1,_.precision);return new AW(Z,_?.withTimezone??!1,_?.precision)}class NW extends v{static[E]="PgUUIDBuilder";constructor(X){super(X,"string","PgUUID")}defaultRandom(){return this.default(V`gen_random_uuid()`)}build(X){return new c6(X,this.config)}}class c6 extends B{static[E]="PgUUID";getSQLType(){return"uuid"}}function T1(X){return new NW(X??"")}class IW extends v{static[E]="PgVarcharBuilder";constructor(X,Y){super(X,"string","PgVarchar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(X){return new KW(X,this.config)}}class KW extends B{static[E]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function n0(X,Y={}){let{name:Z,config:_}=a(X,Y);return new IW(Z,_)}class BW extends v{static[E]="PgBinaryVectorBuilder";constructor(X,Y){super(X,"string","PgBinaryVector");this.config.dimensions=Y.dimensions}build(X){return new TW(X,this.config)}}class TW extends B{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function CW(X,Y){let{name:Z,config:_}=a(X,Y);return new BW(Z,_)}class qW extends v{static[E]="PgHalfVectorBuilder";constructor(X,Y){super(X,"array","PgHalfVector");this.config.dimensions=Y.dimensions}build(X){return new jW(X,this.config)}}class jW extends B{static[E]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){return X.slice(1,-1).split(",").map((Y)=>Number.parseFloat(Y))}}function SW(X,Y){let{name:Z,config:_}=a(X,Y);return new qW(Z,_)}class PW extends v{static[E]="PgSparseVectorBuilder";constructor(X,Y){super(X,"string","PgSparseVector");this.config.dimensions=Y.dimensions}build(X){return new vW(X,this.config)}}class vW extends B{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function xW(X,Y){let{name:Z,config:_}=a(X,Y);return new PW(Z,_)}class fW extends v{static[E]="PgVectorBuilder";constructor(X,Y){super(X,"array","PgVector");this.config.dimensions=Y.dimensions}build(X){return new hW(X,this.config)}}class hW extends B{static[E]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){return X.slice(1,-1).split(",").map((Y)=>Number.parseFloat(Y))}}function kW(X,Y){let{name:Z,config:_}=a(X,Y);return new fW(Z,_)}function bW(){return{bigint:i7,bigserial:a7,boolean:N2,char:_3,cidr:$3,customType:Q3,date:U3,doublePrecision:V3,inet:M3,integer:I2,interval:I3,json:B3,jsonb:C3,line:v3,macaddr:h3,macaddr8:y3,numeric:c3,point:r3,geometry:YW,real:GW,serial:HW,smallint:zW,smallserial:EW,text:DW,time:MW,timestamp:wW,uuid:T1,varchar:n0,bit:CW,halfvec:SW,sparsevec:xW,vector:kW}}var TZ=Symbol.for("drizzle:PgInlineForeignKeys"),yW=Symbol.for("drizzle:EnableRLS");class b0 extends T{static[E]="PgTable";static Symbol=Object.assign({},T.Symbol,{InlineForeignKeys:TZ,EnableRLS:yW});[TZ]=[];[yW]=!1;[T.Symbol.ExtraConfigBuilder]=void 0;[T.Symbol.ExtraConfigColumns]={}}function uU(X,Y,Z,_,G=X){let W=new b0(X,_,G),$=typeof Y==="function"?Y(bW()):Y,H=Object.fromEntries(Object.entries($).map(([z,F])=>{let O=F;O.setName(z);let D=O.build(W);return W[TZ].push(...O.buildForeignKeys(D,W)),[z,D]})),Q=Object.fromEntries(Object.entries($).map(([z,F])=>{let O=F;O.setName(z);let D=O.buildExtraConfigColumn(W);return[z,D]})),J=Object.assign(W,H);if(J[T.Symbol.Columns]=H,J[T.Symbol.ExtraConfigColumns]=Q,Z)J[b0.Symbol.ExtraConfigBuilder]=Z;return Object.assign(J,{enableRLS:()=>{return J[b0.Symbol.EnableRLS]=!0,J}})}var I4=(X,Y,Z)=>{return uU(X,Y,Z,void 0)};function gW(...X){if(X[0].columns)return new K2(X[0].columns,X[0].name);return new K2(X)}class K2{static[E]="PgPrimaryKeyBuilder";columns;name;constructor(X,Y){this.columns=X,this.name=Y}build(X){return new pW(X,this.columns,this.name)}}class pW{constructor(X,Y,Z){this.table=X,this.columns=Y,this.name=Z}static[E]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[b0.Symbol.Name]}_${this.columns.map((X)=>X.name).join("_")}_pk`}}function U1(X,Y){if(h7(Y)&&!AZ(X)&&!M(X,L1)&&!M(X,w4)&&!M(X,z0)&&!M(X,T)&&!M(X,F1))return new L1(X,Y);return X}var l6=(X,Y)=>{return V`${X} = ${U1(Y,X)}`},mW=(X,Y)=>{return V`${X} <> ${U1(Y,X)}`};function B2(...X){let Y=X.filter((Z)=>Z!==void 0);if(Y.length===0)return;if(Y.length===1)return new S(Y);return new S([new k0("("),V.join(Y,new k0(" and ")),new k0(")")])}function uW(...X){let Y=X.filter((Z)=>Z!==void 0);if(Y.length===0)return;if(Y.length===1)return new S(Y);return new S([new k0("("),V.join(Y,new k0(" or ")),new k0(")")])}function dW(X){return V`not ${X}`}var cW=(X,Y)=>{return V`${X} > ${U1(Y,X)}`},lW=(X,Y)=>{return V`${X} >= ${U1(Y,X)}`},oW=(X,Y)=>{return V`${X} < ${U1(Y,X)}`},iW=(X,Y)=>{return V`${X} <= ${U1(Y,X)}`};function nW(X,Y){if(Array.isArray(Y)){if(Y.length===0)return V`false`;return V`${X} in ${Y.map((Z)=>U1(Z,X))}`}return V`${X} in ${U1(Y,X)}`}function rW(X,Y){if(Array.isArray(Y)){if(Y.length===0)return V`true`;return V`${X} not in ${Y.map((Z)=>U1(Z,X))}`}return V`${X} not in ${U1(Y,X)}`}function sW(X){return V`${X} is null`}function tW(X){return V`${X} is not null`}function aW(X){return V`exists ${X}`}function eW(X){return V`not exists ${X}`}function X$(X,Y,Z){return V`${X} between ${U1(Y,X)} and ${U1(Z,X)}`}function Y$(X,Y,Z){return V`${X} not between ${U1(Y,X)} and ${U1(Z,X)}`}function Z$(X,Y){return V`${X} like ${Y}`}function _$(X,Y){return V`${X} not like ${Y}`}function G$(X,Y){return V`${X} ilike ${Y}`}function W$(X,Y){return V`${X} not ilike ${Y}`}function $$(X){return V`${X} asc`}function H$(X){return V`${X} desc`}class CZ{constructor(X,Y,Z){this.sourceTable=X,this.referencedTable=Y,this.relationName=Z,this.referencedTableName=Y[T.Symbol.Name]}static[E]="Relation";referencedTableName;fieldName}class J${constructor(X,Y){this.table=X,this.config=Y}static[E]="Relations"}class K4 extends CZ{constructor(X,Y,Z,_){super(X,Y,Z?.relationName);this.config=Z,this.isNullable=_}static[E]="One";withFieldName(X){let Y=new K4(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Y.fieldName=X,Y}}class T2 extends CZ{constructor(X,Y,Z){super(X,Y,Z?.relationName);this.config=Z}static[E]="Many";withFieldName(X){let Y=new T2(this.sourceTable,this.referencedTable,this.config);return Y.fieldName=X,Y}}function Q$(){return{and:B2,between:X$,eq:l6,exists:aW,gt:cW,gte:lW,ilike:G$,inArray:nW,isNull:sW,isNotNull:tW,like:Z$,lt:oW,lte:iW,ne:mW,not:dW,notBetween:Y$,notExists:eW,notLike:_$,notIlike:W$,notInArray:rW,or:uW,sql:V}}function z$(){return{sql:V,asc:$$,desc:H$}}function F$(X,Y){if(Object.keys(X).length===1&&"default"in X&&!M(X.default,T))X=X.default;let Z={},_={},G={};for(let[W,$]of Object.entries(X))if(M($,T)){let H=b4($),Q=_[H];Z[H]=W,G[W]={tsName:W,dbName:$[T.Symbol.Name],schema:$[T.Symbol.Schema],columns:$[T.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let z of Object.values($[T.Symbol.Columns]))if(z.primary)G[W].primaryKey.push(z);let J=$[T.Symbol.ExtraConfigBuilder]?.($[T.Symbol.ExtraConfigColumns]);if(J){for(let z of Object.values(J))if(M(z,K2))G[W].primaryKey.push(...z.columns)}}else if(M($,J$)){let H=b4($.table),Q=Z[H],J=$.config(Y($.table)),z;for(let[F,O]of Object.entries(J))if(Q){let D=G[Q];if(D.relations[F]=O,z)D.primaryKey.push(...z)}else{if(!(H in _))_[H]={relations:{},primaryKey:z};_[H].relations[F]=O}}return{tables:G,tableNamesMap:Z}}function dU(X){return function(Z,_){return new K4(X,Z,_,_?.fields.reduce((G,W)=>G&&W.notNull,!0)??!1)}}function cU(X){return function(Z,_){return new T2(X,Z,_)}}function U$(X,Y,Z){if(M(Z,K4)&&Z.config)return{fields:Z.config.fields,references:Z.config.references};let _=Y[b4(Z.referencedTable)];if(!_)throw Error(`Table "${Z.referencedTable[T.Symbol.Name]}" not found in schema`);let G=X[_];if(!G)throw Error(`Table "${_}" not found in schema`);let W=Z.sourceTable,$=Y[b4(W)];if(!$)throw Error(`Table "${W[T.Symbol.Name]}" not found in schema`);let H=[];for(let Q of Object.values(G.relations))if(Z.relationName&&Z!==Q&&Q.relationName===Z.relationName||!Z.relationName&&Q.referencedTable===Z.sourceTable)H.push(Q);if(H.length>1)throw Z.relationName?Error(`There are multiple relations with name "${Z.relationName}" in table "${_}"`):Error(`There are multiple relations between "${_}" and "${Z.sourceTable[T.Symbol.Name]}". Please specify relation name`);if(H[0]&&M(H[0],K4)&&H[0].config)return{fields:H[0].config.references,references:H[0].config.fields};throw Error(`There is not enough information to infer relation "${$}.${Z.fieldName}"`)}function E$(X){return{one:dU(X),many:cU(X)}}function o6(X,Y,Z,_,G=(W)=>W){let W={};for(let[$,H]of _.entries())if(H.isJson){let Q=Y.relations[H.tsKey],J=Z[$],z=typeof J==="string"?JSON.parse(J):J;W[H.tsKey]=M(Q,K4)?z&&o6(X,X[H.relationTableTsKey],z,H.selection,G):z.map((F)=>o6(X,X[H.relationTableTsKey],F,H.selection,G))}else{let Q=G(Z[$]),J=H.field,z;if(M(J,z0))z=J;else if(M(J,S))z=J.decoder;else z=J.sql.decoder;W[H.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return W}import OE from"os";import VE from"fs";var i6=new Map,qZ=new Map,jZ=Symbol("OriginError"),M8={};class C1 extends Promise{constructor(X,Y,Z,_,G={}){let W,$;super((H,Q)=>{W=H,$=Q});this.tagged=Array.isArray(X.raw),this.strings=X,this.args=Y,this.handler=Z,this.canceller=_,this.options=G,this.state=null,this.statement=null,this.resolve=(H)=>(this.active=!1,W(H)),this.reject=(H)=>(this.active=!1,$(H)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[jZ]=this.handler.debug?Error():this.tagged&&lU(this.strings)}get origin(){return(this.handler.debug?this[jZ].stack:this.tagged&&qZ.has(this.strings)?qZ.get(this.strings):qZ.set(this.strings,this[jZ].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(X=1,Y){if(this.options.simple=!1,typeof X==="function")Y=X,X=1;if(this.cursorRows=X,typeof Y==="function")return this.cursorFn=Y,this;let Z;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};Z&&Z();let _=new Promise((G,W)=>{this.cursorFn=($)=>{return G({value:$,done:!1}),new Promise((H)=>Z=H)},this.resolve=()=>(this.active=!1,G({done:!0})),this.reject=($)=>(this.active=!1,W($))});return this.execute(),_},return(){return Z&&Z(M8),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw Error(".stream has been renamed to .forEach")}forEach(X){return this.forEachFn=X,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 lU(X){if(i6.has(X))return i6.get(X);let Y=Error.stackTraceLimit;return Error.stackTraceLimit=4,i6.set(X,Error()),Error.stackTraceLimit=Y,i6.get(X)}class A8 extends Error{constructor(X){super(X.message);this.name=this.constructor.name,Object.assign(this,X)}}var S0={connection:O$,postgres:V$,generic:D$,notSupported:L$};function O$(X,Y,Z){let{host:_,port:G}=Z||Y,W=Object.assign(Error("write "+X+" "+(Y.path||_+":"+G)),{code:X,errno:X,address:Y.path||_},Y.path?{}:{port:G});return Error.captureStackTrace(W,O$),W}function V$(X){let Y=new A8(X);return Error.captureStackTrace(Y,V$),Y}function D$(X,Y){let Z=Object.assign(Error(X+": "+Y),{code:X});return Error.captureStackTrace(Z,D$),Z}function L$(X){let Y=Object.assign(Error(X+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:X});return Error.captureStackTrace(Y,L$),Y}var oU={string:{to:25,from:null,serialize:(X)=>""+X},number:{to:0,from:[21,23,26,700,701],serialize:(X)=>""+X,parse:(X)=>+X},json:{to:114,from:[114,3802],serialize:(X)=>JSON.stringify(X),parse:(X)=>JSON.parse(X)},boolean:{to:16,from:16,serialize:(X)=>X===!0?"t":"f",parse:(X)=>X==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(X)=>(X instanceof Date?X:new Date(X)).toISOString(),parse:(X)=>new Date(X)},bytea:{to:17,from:17,serialize:(X)=>"\\x"+Buffer.from(X).toString("hex"),parse:(X)=>Buffer.from(X.slice(2),"hex")}};class s6{then(){SZ()}catch(){SZ()}finally(){SZ()}}class S2 extends s6{constructor(X){super();this.value=e6(X)}}class n1 extends s6{constructor(X,Y,Z){super();this.value=X,this.type=Y,this.array=Z}}class t6 extends s6{constructor(X,Y){super();this.first=X,this.rest=Y}build(X,Y,Z,_){let G=iU.map(([W,$])=>({fn:$,i:X.search(W)})).sort((W,$)=>W.i-$.i).pop();return G.i===-1?hZ(this.first,_):G.fn(this.first,this.rest,Y,Z,_)}}function a6(X,Y,Z,_){let G=X instanceof n1?X.value:X;if(G===void 0){if(X instanceof n1?X.value=_.transform.undefined:G=X=_.transform.undefined,G===void 0)throw S0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+Z.push(X instanceof n1?(Y.push(X.value),X.array?X.array[X.type||r6(X.value)]||X.type||w$(X.value):X.type):(Y.push(X),r6(X)))}var A$=I$(oU);function xZ(X,Y,Z,_,G,W){for(let $=1;$<X.strings.length;$++)Y+=fZ(Y,Z,_,G,W)+X.strings[$],Z=X.args[$];return Y}function fZ(X,Y,Z,_,G){return Y instanceof t6?Y.build(X,Z,_,G):Y instanceof C1?vZ(Y,Z,_,G):Y instanceof S2?Y.value:Y&&Y[0]instanceof C1?Y.reduce((W,$)=>W+" "+vZ($,Z,_,G),""):a6(Y,Z,_,G)}function vZ(X,Y,Z,_){return X.fragment=!0,xZ(X,X.strings[0],X.args[0],Y,Z,_)}function R$(X,Y,Z,_,G){return X.map((W)=>"("+_.map(($)=>fZ("values",W[$],Y,Z,G)).join(",")+")").join(",")}function M$(X,Y,Z,_,G){let W=Array.isArray(X[0]),$=Y.length?Y.flat():Object.keys(W?X[0]:X);return R$(W?X:[X],Z,_,$,G)}function n6(X,Y,Z,_,G){if(typeof X==="string"&&(X=[X].concat(Y)),Array.isArray(X))return hZ(X,G);let W;return(Y.length?Y.flat():Object.keys(X)).map((H)=>{return W=X[H],(W instanceof C1?vZ(W,Z,_,G):W instanceof S2?W.value:a6(W,Z,_,G))+" as "+e6(G.transform.column.to?G.transform.column.to(H):H)}).join(",")}var iU=Object.entries({values:M$,in:(...X)=>{let Y=M$(...X);return Y==="()"?"(null)":Y},select:n6,as:n6,returning:n6,"\\(":n6,update(X,Y,Z,_,G){return(Y.length?Y.flat():Object.keys(X)).map((W)=>e6(G.transform.column.to?G.transform.column.to(W):W)+"="+fZ("values",X[W],Z,_,G))},insert(X,Y,Z,_,G){let W=Y.length?Y.flat():Object.keys(Array.isArray(X)?X[0]:X);return"("+hZ(W,G)+")values"+R$(Array.isArray(X)?X:[X],Z,_,W,G)}}).map(([X,Y])=>[new RegExp("((?:^|[\\s(])"+X+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Y]);function SZ(){throw S0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:nU,parsers:rU}=A$;function w$(X){if(Array.isArray(X))return w$(X[0]);return typeof X==="string"?1009:0}var N$=function(X){let Y=I$(X||{});return{serializers:Object.assign({},nU,Y.serializers),parsers:Object.assign({},rU,Y.parsers)}};function I$(X){return Object.keys(X).reduce((Y,Z)=>{if(X[Z].from&&[].concat(X[Z].from).forEach((_)=>Y.parsers[_]=X[Z].parse),X[Z].serialize)Y.serializers[X[Z].to]=X[Z].serialize,X[Z].from&&[].concat(X[Z].from).forEach((_)=>Y.serializers[_]=X[Z].serialize);return Y},{parsers:{},serializers:{}})}function hZ(X,{transform:{column:Y}}){return X.map((Z)=>e6(Y.to?Y.to(Z):Z)).join(",")}var e6=function(Y){return'"'+Y.replace(/"/g,'""').replace(/\./g,'"."')+'"'},r6=function X(Y){return Y instanceof n1?Y.type:Y instanceof Date?1184:Y instanceof Uint8Array?17:Y===!0||Y===!1?16:typeof Y==="bigint"?20:Array.isArray(Y)?X(Y[0]):0},sU=/\\/g,tU=/"/g;function aU(X){return X.replace(sU,"\\\\").replace(tU,"\\\"")}var K$=function X(Y,Z,_,G){if(Array.isArray(Y)===!1)return Y;if(!Y.length)return"{}";let W=Y[0],$=G===1020?";":",";if(Array.isArray(W)&&!W.type)return"{"+Y.map((H)=>X(H,Z,_,G)).join($)+"}";return"{"+Y.map((H)=>{if(H===void 0){if(H=_.transform.undefined,H===void 0)throw S0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return H===null?"null":'"'+aU(Z?Z(H.type?H.value:H):""+H)+'"'}).join($)+"}"},PZ={i:0,char:null,str:"",quoted:!1,last:0},B$=function(Y,Z,_){return PZ.i=PZ.last=0,T$(PZ,Y,Z,_)};function T$(X,Y,Z,_){let G=[],W=_===1020?";":",";for(;X.i<Y.length;X.i++){if(X.char=Y[X.i],X.quoted)if(X.char==="\\")X.str+=Y[++X.i];else if(X.char==='"')G.push(Z?Z(X.str):X.str),X.str="",X.quoted=Y[X.i+1]==='"',X.last=X.i+2;else X.str+=X.char;else if(X.char==='"')X.quoted=!0;else if(X.char==="{")X.last=++X.i,G.push(T$(X,Y,Z,_));else if(X.char==="}"){X.quoted=!1,X.last<X.i&&G.push(Z?Z(Y.slice(X.last,X.i)):Y.slice(X.last,X.i)),X.last=X.i+1;break}else if(X.char===W&&X.p!=="}"&&X.p!=='"')G.push(Z?Z(Y.slice(X.last,X.i)):Y.slice(X.last,X.i)),X.last=X.i+1;X.p=X.char}return X.last<X.i&&G.push(Z?Z(Y.slice(X.last,X.i+1)):Y.slice(X.last,X.i+1)),G}var y4=(X)=>{let Y=X[0];for(let Z=1;Z<X.length;Z++)Y+=X[Z]==="_"?X[++Z].toUpperCase():X[Z];return Y},g4=(X)=>{let Y=X[0].toUpperCase();for(let Z=1;Z<X.length;Z++)Y+=X[Z]==="_"?X[++Z].toUpperCase():X[Z];return Y},p4=(X)=>X.replace(/_/g,"-"),C2=(X)=>X.replace(/([A-Z])/g,"_$1").toLowerCase(),q2=(X)=>(X.slice(0,1)+X.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),j2=(X)=>X.replace(/-/g,"_");function kZ(X){return function Y(Z,_){return typeof Z==="object"&&Z!==null&&(_.type===114||_.type===3802)?Array.isArray(Z)?Z.map((G)=>Y(G,_)):Object.entries(Z).reduce((G,[W,$])=>Object.assign(G,{[X(W)]:Y($,_)}),{}):Z}}y4.column={from:y4};y4.value={from:kZ(y4)};C2.column={to:C2};var bZ={...y4};bZ.column.to=C2;g4.column={from:g4};g4.value={from:kZ(g4)};q2.column={to:q2};var yZ={...g4};yZ.column.to=q2;p4.column={from:p4};p4.value={from:kZ(p4)};j2.column={to:j2};var gZ={...p4};gZ.column.to=j2;import C$ from"net";import ZE from"tls";import P2 from"crypto";import pZ from"stream";import{performance as q$}from"perf_hooks";class m4 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 M1=eU;function eU(X=[]){let Y=X.slice(),Z=0;return{get length(){return Y.length-Z},remove:(_)=>{let G=Y.indexOf(_);return G===-1?null:(Y.splice(G,1),_)},push:(_)=>(Y.push(_),_),shift:()=>{let _=Y[Z++];if(Z===Y.length)Z=0,Y=[];else Y[Z-1]=void 0;return _}}}var r0=Buffer.allocUnsafe(256),XE="BCcDdEFfHPpQSX".split("").reduce((X,Y)=>{let Z=Y.charCodeAt(0);return X[Y]=()=>{return r0[0]=Z,J0.i=5,J0},X},{}),J0=Object.assign(YE,XE,{N:String.fromCharCode(0),i:0,inc(X){return J0.i+=X,J0},str(X){let Y=Buffer.byteLength(X);return XX(Y),J0.i+=r0.write(X,J0.i,Y,"utf8"),J0},i16(X){return XX(2),r0.writeUInt16BE(X,J0.i),J0.i+=2,J0},i32(X,Y){if(Y||Y===0)return r0.writeUInt32BE(X,Y),J0;return XX(4),r0.writeUInt32BE(X,J0.i),J0.i+=4,J0},z(X){return XX(X),r0.fill(0,J0.i,J0.i+X),J0.i+=X,J0},raw(X){return r0=Buffer.concat([r0.subarray(0,J0.i),X]),J0.i=r0.length,J0},end(X=1){r0.writeUInt32BE(J0.i-X,X);let Y=r0.subarray(0,J0.i);return J0.i=0,r0=Buffer.allocUnsafe(256),Y}}),b=J0;function XX(X){if(r0.length-J0.i<X){let Y=r0,Z=Y.length;r0=Buffer.allocUnsafe(Z+(Z>>1)+X),Y.copy(r0)}}function YE(){return J0.i=0,J0}var dZ=P$,_E=1,B4=b().S().end(),j$=b().H().end(),GE=b().i32(8).i32(80877103).end(8),WE=Buffer.concat([b().E().str(b.N).i32(0).end(),B4]),$E=b().D().str("S").str(b.N).end(),R8=()=>{},HE=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),JE={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 P$(X,Y={},{onopen:Z=R8,onend:_=R8,onclose:G=R8}={}){let{ssl:W,max:$,user:H,host:Q,port:J,database:z,parsers:F,transform:O,onnotice:D,onnotify:w,onparameter:A,max_pipeline:x,keep_alive:j,backoff:P,target_session_attrs:h}=X,i=M1(),p=_E++,y={pid:null,secret:null},m=uZ(OX,X.idle_timeout),_0=uZ(OX,X.max_lifetime),y0=uZ(XH,X.connect_timeout),K=null,W0,o=new m4,X0=Buffer.alloc(0),p0=X.fetch_types,O1={},q1={},c4=Math.random().toString(36).slice(2),I=1,u=0,$0=0,R0=0,P0=0,n=0,H0=0,q0=0,N0=null,D0=null,d0=!1,U0=null,j1=null,m0=null,z4=null,v0=null,L0=null,S1=null,u1=null,q=null,K8=null,c0={queue:Y.closed,idleTimer:m,connect(U){m0=U,D5()},terminate:T8,execute:B8,cancel:s$,end:OX,count:0,id:p};return Y.closed&&Y.closed.push(c0),c0;async function r$(){let U;try{U=X.socket?await Promise.resolve(X.socket(X)):new C$.Socket}catch(L){o4(L);return}return U.on("error",o4),U.on("close",L5),U.on("drain",O5),U}async function s$({pid:U,secret:L},g,Y0){try{W0=b().i32(16).i32(80877102).i32(U).i32(L).end(16),await V5(),K.once("error",Y0),K.once("close",g)}catch(K0){Y0(K0)}}function B8(U){if(d0)return g2(U,S0.connection("CONNECTION_DESTROYED",X));if(U.cancelled)return;try{return U.state=y,q?i.push(U):(q=U,q.active=!0),e$(U),u0(t$(U))&&!U.describeFirst&&!U.cursorFn&&i.length<x&&(!U.options.onexecute||U.options.onexecute(c0))}catch(L){return i.length===0&&u0(B4),d1(L),!0}}function t$(U){if(U.parameters.length>=65534)throw S0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return U.options.simple?b().Q().str(U.statement.string+b.N).end():U.describeFirst?Buffer.concat([F5(U),j$]):U.prepare?U.prepared?y2(U):Buffer.concat([F5(U),y2(U)]):a$(U)}function F5(U){return Buffer.concat([A5(U.statement.string,U.parameters,U.statement.types,U.statement.name),yH("S",U.statement.name)])}function y2(U){return Buffer.concat([bH(U.parameters,U.statement.types,U.statement.name,U.cursorName),U.cursorFn?R5("",U.cursorRows):WE])}function a$(U){return Buffer.concat([A5(U.statement.string,U.parameters,U.statement.types),$E,y2(U)])}function e$(U){let L=[],g=[],Y0=xZ(U,U.strings[0],U.args[0],L,g,X);!U.tagged&&U.args.forEach((K0)=>a6(K0,L,g,X)),U.prepare=X.prepare&&("prepare"in U.options?U.options.prepare:!0),U.string=Y0,U.signature=U.prepare&&g+Y0,U.onlyDescribe&&delete q1[U.signature],U.parameters=U.parameters||L,U.prepared=U.prepare&&U.signature in q1,U.describeFirst=U.onlyDescribe||L.length&&!U.prepared,U.statement=U.prepared?q1[U.signature]:{string:Y0,types:g,name:U.prepare?c4+I++:""},typeof X.debug==="function"&&X.debug(p,Y0,L,g)}function u0(U,L){if(L0=L0?Buffer.concat([L0,U]):Buffer.from(U),L||L0.length>=1024)return U5(L);return D0===null&&(D0=setImmediate(U5)),!0}function U5(U){let L=K.write(L0,U);return D0!==null&&clearImmediate(D0),L0=D0=null,L}function XH(){d1(S0.connection("CONNECT_TIMEOUT",X,K)),K.destroy()}async function E5(){if(u0(GE),!await new Promise((L)=>K.once("data",(g)=>L(g[0]===83)))&&W==="prefer")return l4();K.removeAllListeners(),K=ZE.connect({socket:K,servername:C$.isIP(K.host)?void 0:K.host,...W==="require"||W==="allow"||W==="prefer"?{rejectUnauthorized:!1}:W==="verify-full"?{}:typeof W==="object"?W:{}}),K.on("secureConnect",l4),K.on("error",o4),K.on("close",L5),K.on("drain",O5)}function O5(){!q&&Z(c0)}function EX(U){if(U0){if(U0.push(U),$0-=U.length,$0>0)return}X0=U0?Buffer.concat(U0,n-$0):X0.length===0?U:Buffer.concat([X0,U],X0.length+U.length);while(X0.length>4){if(n=X0.readUInt32BE(1),n>=X0.length){$0=n-X0.length,U0=[X0];break}try{YH(X0.subarray(0,n+1))}catch(L){q&&(q.cursorFn||q.describeFirst)&&u0(B4),d1(L)}X0=X0.subarray(n+1),$0=0,U0=null}}async function V5(){if(d0=!1,O1={},K||(K=await r$()),!K)return;if(y0.start(),X.socket)return W?E5():l4();if(K.on("connect",W?E5:l4),X.path)return K.connect(X.path);K.ssl=W,K.connect(J[R0],Q[R0]),K.host=Q[R0],K.port=J[R0],R0=(R0+1)%J.length}function D5(){setTimeout(V5,u?u+H0-q$.now():0)}function l4(){try{q1={},p0=X.fetch_types,c4=Math.random().toString(36).slice(2),I=1,_0.start(),K.on("data",EX),j&&K.setKeepAlive&&K.setKeepAlive(!0,1000*j);let U=pH();u0(U)}catch(U){o4(U)}}function o4(U){if(c0.queue===Y.connecting&&X.host[P0+1])return;d1(U);while(i.length)g2(i.shift(),U)}function d1(U){v0&&(v0.destroy(U),v0=null),q&&g2(q,U),m0&&(g2(m0,U),m0=null)}function g2(U,L){if(U.reserve)return U.reject(L);if(!L||typeof L!=="object")L=Error(L);"query"in L||"parameters"in L||Object.defineProperties(L,{stack:{value:L.stack+U.origin.replace(/.*\n/,`
67
+ `),enumerable:X.debug},query:{value:U.string,enumerable:X.debug},parameters:{value:U.parameters,enumerable:X.debug},args:{value:U.args,enumerable:X.debug},types:{value:U.statement&&U.statement.types,enumerable:X.debug}}),U.reject(L)}function OX(){return z4||(!c0.reserved&&_(c0),!c0.reserved&&!m0&&!q&&i.length===0?(T8(),new Promise((U)=>K&&K.readyState!=="closed"?K.once("close",U):U())):z4=new Promise((U)=>S1=U))}function T8(){if(d0=!0,v0||q||m0||i.length)o4(S0.connection("CONNECTION_DESTROYED",X));if(clearImmediate(D0),K)K.removeListener("data",EX),K.removeListener("connect",l4),K.readyState==="open"&&K.end(b().X().end());S1&&(S1(),z4=S1=null)}async function L5(U){if(X0=Buffer.alloc(0),$0=0,U0=null,clearImmediate(D0),K.removeListener("data",EX),K.removeListener("connect",l4),m.cancel(),_0.cancel(),y0.cancel(),K.removeAllListeners(),K=null,m0)return D5();!U&&(q||i.length)&&o4(S0.connection("CONNECTION_CLOSED",X,K)),u=q$.now(),U&&X.shared.retries++,H0=(typeof P==="function"?P(X.shared.retries):P)*1000,G(c0,S0.connection("CONNECTION_CLOSED",X,K))}function YH(U,L=U[0]){(L===68?ZH:L===100?jH:L===65?IH:L===83?_H:L===90?GH:L===67?WH:L===50?M5:L===49?$H:L===116?HH:L===84?JH:L===82?QH:L===110?VH:L===75?DH:L===69?wH:L===115?KH:L===51?BH:L===71?TH:L===78?PH:L===72?CH:L===99?SH:L===73?vH:L===86?xH:L===118?fH:L===87?qH:hH)(U)}function ZH(U){let L=7,g,Y0,K0,l0=q.isRaw?Array(q.statement.columns.length):{};for(let s0=0;s0<q.statement.columns.length;s0++)Y0=q.statement.columns[s0],g=U.readInt32BE(L),L+=4,K0=g===-1?null:q.isRaw===!0?U.subarray(L,L+=g):Y0.parser===void 0?U.toString("utf8",L,L+=g):Y0.parser.array===!0?Y0.parser(U.toString("utf8",L+1,L+=g)):Y0.parser(U.toString("utf8",L,L+=g)),q.isRaw?l0[s0]=q.isRaw===!0?K0:O.value.from?O.value.from(K0,Y0):K0:l0[Y0.name]=O.value.from?O.value.from(K0,Y0):K0;q.forEachFn?q.forEachFn(O.row.from?O.row.from(l0):l0,o):o[q0++]=O.row.from?O.row.from(l0):l0}function _H(U){let[L,g]=U.toString("utf8",5,U.length-1).split(b.N);if(O1[L]=g,X.parameters[L]!==g)X.parameters[L]=g,A&&A(L,g)}function GH(U){if(q&&q.options.simple&&q.resolve(j1||o),q=j1=null,o=new m4,y0.cancel(),m0){if(h){if(!O1.in_hot_standby||!O1.default_transaction_read_only)return RH();else if(AH(h,O1))return T8()}if(p0)return m0.reserve&&(m0=null),LH();m0&&!m0.reserve&&B8(m0),X.shared.retries=P0=0,m0=null;return}while(i.length&&(q=i.shift())&&(q.active=!0,q.cancelled))P$(X).cancel(q.state,q.cancelled.resolve,q.cancelled.reject);if(q)return;c0.reserved?!c0.reserved.release&&U[5]===73?z4?T8():(c0.reserved=null,Z(c0)):c0.reserved():z4?T8():Z(c0)}function WH(U){q0=0;for(let L=U.length-1;L>0;L--){if(U[L]===32&&U[L+1]<58&&o.count===null)o.count=+U.toString("utf8",L+1,U.length-1);if(U[L-1]>=65){o.command=U.toString("utf8",5,L),o.state=y;break}}if(K8&&(K8(),K8=null),o.command==="BEGIN"&&$!==1&&!c0.reserved)return d1(S0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(q.options.simple)return M5();if(q.cursorFn)o.count&&q.cursorFn(o),u0(B4);q.resolve(o)}function $H(){q.parsing=!1}function M5(){!o.statement&&(o.statement=q.statement),o.columns=q.statement.columns}function HH(U){let L=U.readUInt16BE(5);for(let g=0;g<L;++g)!q.statement.types[g]&&(q.statement.types[g]=U.readUInt32BE(7+g*4));q.prepare&&(q1[q.signature]=q.statement),q.describeFirst&&!q.onlyDescribe&&(u0(y2(q)),q.describeFirst=!1)}function JH(U){if(o.command)j1=j1||[o],j1.push(o=new m4),o.count=null,q.statement.columns=null;let L=U.readUInt16BE(5),g=7,Y0;q.statement.columns=Array(L);for(let K0=0;K0<L;++K0){Y0=g;while(U[g++]!==0);let l0=U.readUInt32BE(g),s0=U.readUInt16BE(g+4),F4=U.readUInt32BE(g+6);q.statement.columns[K0]={name:O.column.from?O.column.from(U.toString("utf8",Y0,g-1)):U.toString("utf8",Y0,g-1),parser:F[F4],table:l0,number:s0,type:F4},g+=18}if(o.statement=q.statement,q.onlyDescribe)return q.resolve(q.statement),u0(B4)}async function QH(U,L=U.readUInt32BE(5)){(L===3?zH:L===5?FH:L===10?UH:L===11?EH:L===12?OH:L!==0?kH:R8)(U,L)}async function zH(){let U=await VX();u0(b().p().str(U).z(1).end())}async function FH(U){let L="md5"+await S$(Buffer.concat([Buffer.from(await S$(await VX()+H)),U.subarray(9)]));u0(b().p().str(L).z(1).end())}async function UH(){u1=(await P2.randomBytes(18)).toString("base64"),b().p().str("SCRAM-SHA-256"+b.N);let U=b.i;u0(b.inc(4).str("n,,n=*,r="+u1).i32(b.i-U-4,U).end())}async function EH(U){let L=U.toString("utf8",9).split(",").reduce((s0,F4)=>(s0[F4[0]]=F4.slice(2),s0),{}),g=await P2.pbkdf2Sync(await VX(),Buffer.from(L.s,"base64"),parseInt(L.i),32,"sha256"),Y0=await YX(g,"Client Key"),K0="n=*,r="+u1+",r="+L.r+",s="+L.s+",i="+L.i+",c=biws,r="+L.r;N0=(await YX(await YX(g,"Server Key"),K0)).toString("base64");let l0="c=biws,r="+L.r+",p="+zE(Y0,Buffer.from(await YX(await QE(Y0),K0))).toString("base64");u0(b().p().str(l0).end())}function OH(U){if(U.toString("utf8",9).split(b.N,1)[0].slice(2)===N0)return;d1(S0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),K.destroy()}function VX(){return Promise.resolve(typeof X.pass==="function"?X.pass():X.pass)}function VH(){if(o.statement=q.statement,o.statement.columns=[],q.onlyDescribe)return q.resolve(q.statement),u0(B4)}function DH(U){y.pid=U.readUInt32BE(5),y.secret=U.readUInt32BE(9)}async function LH(){p0=!1,(await new C1([`
68
68
  select b.oid, b.typarray
69
69
  from pg_catalog.pg_type a
70
70
  left join pg_catalog.pg_type b on b.oid = a.typelem
71
71
  where a.typcategory = 'A'
72
72
  group by b.oid, b.typarray
73
73
  order by b.oid
74
- `],[],T2)).forEach(({oid:D,typarray:l})=>wH(D,l))}function wH(F,D){if(!!Y.parsers[D]&&!!Y.serializers[D])return;let l=Y.parsers[F];Y.shared.typeArrayMap[F]=D,Y.parsers[D]=(W0)=>qW(W0,l,D),Y.parsers[D].array=!0,Y.serializers[D]=(W0)=>CW(W0,Y.serializers[F],Y,D)}function NH(F,D){return F==="read-write"&&D.default_transaction_read_only==="on"||F==="read-only"&&D.default_transaction_read_only==="off"||F==="primary"&&D.in_hot_standby==="on"||F==="standby"&&D.in_hot_standby==="off"||F==="prefer-standby"&&D.in_hot_standby==="off"&&Y.host[k0]}function IH(){let F=new q1([`
74
+ `],[],B8)).forEach(({oid:L,typarray:g})=>MH(L,g))}function MH(U,L){if(!!X.parsers[L]&&!!X.serializers[L])return;let g=X.parsers[U];X.shared.typeArrayMap[U]=L,X.parsers[L]=(Y0)=>B$(Y0,g,L),X.parsers[L].array=!0,X.serializers[L]=(Y0)=>K$(Y0,X.serializers[U],X,L)}function AH(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"&&X.host[P0]}function RH(){let U=new C1([`
75
75
  show transaction_read_only;
76
76
  select pg_catalog.pg_is_in_recovery()
77
- `],[],T2,null,{simple:!0});F.resolve=([[D],[l]])=>{h0.default_transaction_read_only=D.transaction_read_only,h0.in_hot_standby=l.pg_is_in_recovery?"on":"off"},F.execute()}function KH(F){v&&(v.cursorFn||v.describeFirst)&&l0(B4);let D=f0.postgres(p5(F));v&&v.retried?d1(v.retried):v&&v.prepared&&FE.has(D.routine)?BH(v,D):d1(D)}function BH(F,D){delete $1[F.signature],F.retried=D,T2(F)}function TH(F){if(!w)return;let D=9;while(F[D++]!==0);w(F.toString("utf8",9,D-1),F.toString("utf8",D,F.length-1))}async function CH(){try{let F=await Promise.resolve(v.cursorFn(p));v0=0,F===A2?l0(uH(v.portal)):(p=new d4,l0(AX("",v.cursorRows)))}catch(F){l0(B4),v.reject(F)}}function qH(){p.count&&v.cursorFn(p),v.resolve(p)}function jH(){b0=new g5.Writable({autoDestroy:!0,write(F,D,l){N.write(d().d().raw(F).end(),l)},destroy(F,D){D(F),N.write(d().f().str(F+d.N).end()),b0=null},final(F){N.write(d().c().end()),B2=F}}),v.resolve(b0)}function PH(){b0=new g5.Readable({read(){N.resume()}}),v.resolve(b0)}function SH(){b0=new g5.Duplex({autoDestroy:!0,read(){N.resume()},write(F,D,l){N.write(d().d().raw(F).end(),l)},destroy(F,D){D(F),N.write(d().f().str(F+d.N).end()),b0=null},final(F){N.write(d().c().end()),B2=F}}),v.resolve(b0)}function vH(F){b0&&(b0.push(F.subarray(5))||N.pause())}function xH(){b0&&b0.push(null),b0=null}function fH(F){L?L(p5(F)):console.log(p5(F))}function hH(){}function kH(){d1(f0.notSupported("FunctionCallResponse"))}function bH(){d1(f0.notSupported("NegotiateProtocolVersion"))}function yH(F){console.error("Postgres.js : Unknown Message:",F[0])}function gH(F,D){console.error("Postgres.js : Unknown Auth:",D)}function pH(F,D,l="",W0=""){let C0,n0;return d().B().str(W0+d.N).str(l+d.N).i16(0).i16(F.length),F.forEach((e0,F4)=>{if(e0===null)return d.i32(4294967295);n0=D[F4],F[F4]=e0=n0 in Y.serializers?Y.serializers[n0](e0):""+e0,C0=d.i,d.inc(4).str(e0).i32(d.i-C0-4,C0)}),d.i16(0),d.end()}function MX(F,D,l,W0=""){return d().P().str(W0+d.N).str(F+d.N).i16(D.length),D.forEach((C0,n0)=>d.i32(l[n0]||0)),d.end()}function mH(F,D=""){return d().D().str(F).str(D+d.N).end()}function AX(F="",D=0){return Buffer.concat([d().E().str(F+d.N).i32(D).end(),vW])}function uH(F=""){return Buffer.concat([d().C().str("P").str(F+d.N).end(),d().S().end()])}function dH(){return s||d().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:H,database:z,client_encoding:"UTF8"},Y.connection)).filter(([,F])=>F).map(([F,D])=>F+d.N+D).join(d.N)).z(2).end(0)}}function p5(Y){let Z={},X=5;for(let G=5;G<Y.length-1;G++)if(Y[G]===0)Z[UE[Y[X]]]=Y.toString("utf8",X+1,G),X=G+1;return Z}function xW(Y){return S8.createHash("md5").update(Y).digest("hex")}function ZY(Y,Z){return S8.createHmac("sha256",Y).update(Z).digest()}function EE(Y){return S8.createHash("sha256").update(Y).digest()}function VE(Y,Z){let X=Math.max(Y.length,Z.length),G=Buffer.allocUnsafe(X);for(let _=0;_<X;_++)G[_]=Y[_]^Z[_];return G}function m5(Y,Z){if(Z=typeof Z==="function"?Z():Z,!Z)return{cancel:w2,start:w2};let X;return{cancel(){X&&(clearTimeout(X),X=null)},start(){X&&clearTimeout(X),X=setTimeout(G,Z*1000,arguments)}};function G(_){Y.apply(null,_),X=null}}var hW=()=>{};function d5(Y,Z){let X=new Map,G="postgresjs_"+Math.random().toString(36).slice(2),_={},$,W,H=!1,Q=U.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,_.pid=_.secret=void 0,O(await L(Q,G,Z.publications)),X.forEach((R)=>R.forEach(({onsubscribe:b})=>b()))},no_subscribe:!0}),J=Q.end,z=Q.close;return Q.end=async()=>{return H=!0,W&&await new Promise((R)=>(W.once("close",R),W.end())),J()},Q.close=async()=>{return W&&await new Promise((R)=>(W.once("close",R),W.end())),z()},U;async function U(R,b,x=hW,h=hW){if(R=LE(R),!$)$=L(Q,G,Z.publications);let g={fn:b,onsubscribe:x},B=X.has(R)?X.get(R).add(g):X.set(R,new Set([g])).get(R),K=()=>{B.delete(g),B.size===0&&X.delete(R)};return $.then((C)=>{return O(C),x(),W&&W.on("error",h),{unsubscribe:K,state:_,sql:Q}})}function O(R){W=R.stream,_.pid=R.state.pid,_.secret=R.state.secret}async function L(R,b,x){if(!x)throw Error("Missing publication names");let h=await R.unsafe(`CREATE_REPLICATION_SLOT ${b} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[g]=h,B=await R.unsafe(`START_REPLICATION SLOT ${b} LOGICAL ${g.consistent_point} (proto_version '1', publication_names '${x}')`).writable(),K={lsn:Buffer.concat(g.consistent_point.split("/").map((N)=>Buffer.from(("00000000"+N).slice(-8),"hex")))};return B.on("data",q),B.on("error",C),B.on("close",R.close),{stream:B,state:h.state};function C(N){console.error("Unexpected error during logical streaming - reconnecting",N)}function q(N){if(N[0]===119)DE(N.subarray(25),K,R.options.parsers,c,Z.transform);else if(N[0]===107&&N[17])K.lsn=N.subarray(1,9),n()}function c(N,s){let p=s.relation.schema+"."+s.relation.table;w("*",N,s),w("*:"+p,N,s),s.relation.keys.length&&w("*:"+p+"="+s.relation.keys.map((t)=>N[t.name]),N,s),w(s.command,N,s),w(s.command+":"+p,N,s),s.relation.keys.length&&w(s.command+":"+p+"="+s.relation.keys.map((t)=>N[t.name]),N,s)}function n(){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),B.write(N)}}function w(R,b,x){X.has(R)&&X.get(R).forEach(({fn:h})=>h(b,x,R))}}function OE(Y){return new Date(Date.UTC(2000,0,1)+Number(Y/BigInt(1000)))}function DE(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:_.column.from?_.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=OE(W.readBigInt64BE(9)),Z.lsn=W.subarray(1,9)},I:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)],{row:J}=XY(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;G(J||W[H]===79?XY(W,Q.columns,H+=3,_).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?XY(W,Q.columns,H+=3,_):null;z&&(H=z.i);let{row:U}=XY(W,Q.columns,H+3,_);G(U,{command:"update",relation:Q,key:J,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce($,{})[Y[0]](Y)}function XY(Y,Z,X,G){let _,$,W,H=G.raw?Array(Z.length):{};for(let Q=0;Q<Z.length;Q++)_=Y[X++],$=Z[Q],W=_===110?null:_===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))),G.raw?H[Q]=G.raw===!0?W:G.value.from?G.value.from(W,$):W:H[$.name]=G.value.from?G.value.from(W,$):W;return{i:X,row:G.row.from?G.row.from(H):H}}function LE(Y){let Z=Y.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!Z)throw Error("Malformed subscribe pattern: "+Y);let[,X,G,_]=Z;return(X||"*")+(G?":"+(G.indexOf(".")===-1?"public."+G:G):"")+(_?"="+_:"")}import kW from"stream";function c5(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:(U)=>$`select loread(${H}, ${U}) as data`,write:(U)=>$`select lowrite(${H}, ${U})`,truncate:(U)=>$`select lo_truncate64(${H}, ${U})`,seek:(U,O=0)=>$`select lo_lseek64(${H}, ${U}, ${O})`,size:()=>$`
77
+ `],[],B8,null,{simple:!0});U.resolve=([[L],[g]])=>{O1.default_transaction_read_only=L.transaction_read_only,O1.in_hot_standby=g.pg_is_in_recovery?"on":"off"},U.execute()}function wH(U){q&&(q.cursorFn||q.describeFirst)&&u0(B4);let L=S0.postgres(mZ(U));q&&q.retried?d1(q.retried):q&&q.prepared&&HE.has(L.routine)?NH(q,L):d1(L)}function NH(U,L){delete q1[U.signature],U.retried=L,B8(U)}function IH(U){if(!w)return;let L=9;while(U[L++]!==0);w(U.toString("utf8",9,L-1),U.toString("utf8",L,U.length-1))}async function KH(){try{let U=await Promise.resolve(q.cursorFn(o));q0=0,U===M8?u0(gH(q.portal)):(o=new m4,u0(R5("",q.cursorRows)))}catch(U){u0(B4),q.reject(U)}}function BH(){o.count&&q.cursorFn(o),q.resolve(o)}function TH(){v0=new pZ.Writable({autoDestroy:!0,write(U,L,g){K.write(b().d().raw(U).end(),g)},destroy(U,L){L(U),K.write(b().f().str(U+b.N).end()),v0=null},final(U){K.write(b().c().end()),K8=U}}),q.resolve(v0)}function CH(){v0=new pZ.Readable({read(){K.resume()}}),q.resolve(v0)}function qH(){v0=new pZ.Duplex({autoDestroy:!0,read(){K.resume()},write(U,L,g){K.write(b().d().raw(U).end(),g)},destroy(U,L){L(U),K.write(b().f().str(U+b.N).end()),v0=null},final(U){K.write(b().c().end()),K8=U}}),q.resolve(v0)}function jH(U){v0&&(v0.push(U.subarray(5))||K.pause())}function SH(){v0&&v0.push(null),v0=null}function PH(U){D?D(mZ(U)):console.log(mZ(U))}function vH(){}function xH(){d1(S0.notSupported("FunctionCallResponse"))}function fH(){d1(S0.notSupported("NegotiateProtocolVersion"))}function hH(U){console.error("Postgres.js : Unknown Message:",U[0])}function kH(U,L){console.error("Postgres.js : Unknown Auth:",L)}function bH(U,L,g="",Y0=""){let K0,l0;return b().B().str(Y0+b.N).str(g+b.N).i16(0).i16(U.length),U.forEach((s0,F4)=>{if(s0===null)return b.i32(4294967295);l0=L[F4],U[F4]=s0=l0 in X.serializers?X.serializers[l0](s0):""+s0,K0=b.i,b.inc(4).str(s0).i32(b.i-K0-4,K0)}),b.i16(0),b.end()}function A5(U,L,g,Y0=""){return b().P().str(Y0+b.N).str(U+b.N).i16(L.length),L.forEach((K0,l0)=>b.i32(g[l0]||0)),b.end()}function yH(U,L=""){return b().D().str(U).str(L+b.N).end()}function R5(U="",L=0){return Buffer.concat([b().E().str(U+b.N).i32(L).end(),j$])}function gH(U=""){return Buffer.concat([b().C().str("P").str(U+b.N).end(),b().S().end()])}function pH(){return W0||b().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:H,database:z,client_encoding:"UTF8"},X.connection)).filter(([,U])=>U).map(([U,L])=>U+b.N+L).join(b.N)).z(2).end(0)}}function mZ(X){let Y={},Z=5;for(let _=5;_<X.length-1;_++)if(X[_]===0)Y[JE[X[Z]]]=X.toString("utf8",Z+1,_),Z=_+1;return Y}function S$(X){return P2.createHash("md5").update(X).digest("hex")}function YX(X,Y){return P2.createHmac("sha256",X).update(Y).digest()}function QE(X){return P2.createHash("sha256").update(X).digest()}function zE(X,Y){let Z=Math.max(X.length,Y.length),_=Buffer.allocUnsafe(Z);for(let G=0;G<Z;G++)_[G]=X[G]^Y[G];return _}function uZ(X,Y){if(Y=typeof Y==="function"?Y():Y,!Y)return{cancel:R8,start:R8};let Z;return{cancel(){Z&&(clearTimeout(Z),Z=null)},start(){Z&&clearTimeout(Z),Z=setTimeout(_,Y*1000,arguments)}};function _(G){X.apply(null,G),Z=null}}var v$=()=>{};function cZ(X,Y){let Z=new Map,_="postgresjs_"+Math.random().toString(36).slice(2),G={},W,$,H=!1,Q=F.sql=X({...Y,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...Y.connection,replication:"database"},onclose:async function(){if(H)return;$=null,G.pid=G.secret=void 0,O(await D(Q,_,Y.publications)),Z.forEach((A)=>A.forEach(({onsubscribe:x})=>x()))},no_subscribe:!0}),J=Q.end,z=Q.close;return Q.end=async()=>{return H=!0,$&&await new Promise((A)=>($.once("close",A),$.end())),J()},Q.close=async()=>{return $&&await new Promise((A)=>($.once("close",A),$.end())),z()},F;async function F(A,x,j=v$,P=v$){if(A=EE(A),!W)W=D(Q,_,Y.publications);let h={fn:x,onsubscribe:j},i=Z.has(A)?Z.get(A).add(h):Z.set(A,new Set([h])).get(A),p=()=>{i.delete(h),i.size===0&&Z.delete(A)};return W.then((y)=>{return O(y),j(),$&&$.on("error",P),{unsubscribe:p,state:G,sql:Q}})}function O(A){$=A.stream,G.pid=A.state.pid,G.secret=A.state.secret}async function D(A,x,j){if(!j)throw Error("Missing publication names");let P=await A.unsafe(`CREATE_REPLICATION_SLOT ${x} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[h]=P,i=await A.unsafe(`START_REPLICATION SLOT ${x} LOGICAL ${h.consistent_point} (proto_version '1', publication_names '${j}')`).writable(),p={lsn:Buffer.concat(h.consistent_point.split("/").map((K)=>Buffer.from(("00000000"+K).slice(-8),"hex")))};return i.on("data",m),i.on("error",y),i.on("close",A.close),{stream:i,state:P.state};function y(K){console.error("Unexpected error during logical streaming - reconnecting",K)}function m(K){if(K[0]===119)UE(K.subarray(25),p,A.options.parsers,_0,Y.transform);else if(K[0]===107&&K[17])p.lsn=K.subarray(1,9),y0()}function _0(K,W0){let o=W0.relation.schema+"."+W0.relation.table;w("*",K,W0),w("*:"+o,K,W0),W0.relation.keys.length&&w("*:"+o+"="+W0.relation.keys.map((X0)=>K[X0.name]),K,W0),w(W0.command,K,W0),w(W0.command+":"+o,K,W0),W0.relation.keys.length&&w(W0.command+":"+o+"="+W0.relation.keys.map((X0)=>K[X0.name]),K,W0)}function y0(){let K=Buffer.alloc(34);K[0]=114,K.fill(p.lsn,1),K.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),i.write(K)}}function w(A,x,j){Z.has(A)&&Z.get(A).forEach(({fn:P})=>P(x,j,A))}}function FE(X){return new Date(Date.UTC(2000,0,1)+Number(X/BigInt(1000)))}function UE(X,Y,Z,_,G){let W=($,[H,Q])=>($[H.charCodeAt(0)]=Q,$);Object.entries({R:($)=>{let H=1,Q=Y[$.readUInt32BE(H)]={schema:$.toString("utf8",H+=4,H=$.indexOf(0,H))||"pg_catalog",table:$.toString("utf8",H+1,H=$.indexOf(0,H+1)),columns:Array($.readUInt16BE(H+=2)),keys:[]};H+=2;let J=0,z;while(H<$.length)z=Q.columns[J++]={key:$[H++],name:G.column.from?G.column.from($.toString("utf8",H,H=$.indexOf(0,H))):$.toString("utf8",H,H=$.indexOf(0,H)),type:$.readUInt32BE(H+=1),parser:Z[$.readUInt32BE(H)],atttypmod:$.readUInt32BE(H+=4)},z.key&&Q.keys.push(z),H+=4},Y:()=>{},O:()=>{},B:($)=>{Y.date=FE($.readBigInt64BE(9)),Y.lsn=$.subarray(1,9)},I:($)=>{let H=1,Q=Y[$.readUInt32BE(H)],{row:J}=ZX($,Q.columns,H+=7,G);_(J,{command:"insert",relation:Q})},D:($)=>{let H=1,Q=Y[$.readUInt32BE(H)];H+=4;let J=$[H]===75;_(J||$[H]===79?ZX($,Q.columns,H+=3,G).row:null,{command:"delete",relation:Q,key:J})},U:($)=>{let H=1,Q=Y[$.readUInt32BE(H)];H+=4;let J=$[H]===75,z=J||$[H]===79?ZX($,Q.columns,H+=3,G):null;z&&(H=z.i);let{row:F}=ZX($,Q.columns,H+3,G);_(F,{command:"update",relation:Q,key:J,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce(W,{})[X[0]](X)}function ZX(X,Y,Z,_){let G,W,$,H=_.raw?Array(Y.length):{};for(let Q=0;Q<Y.length;Q++)G=X[Z++],W=Y[Q],$=G===110?null:G===117?void 0:W.parser===void 0?X.toString("utf8",Z+4,Z+=4+X.readUInt32BE(Z)):W.parser.array===!0?W.parser(X.toString("utf8",Z+5,Z+=4+X.readUInt32BE(Z))):W.parser(X.toString("utf8",Z+4,Z+=4+X.readUInt32BE(Z))),_.raw?H[Q]=_.raw===!0?$:_.value.from?_.value.from($,W):$:H[W.name]=_.value.from?_.value.from($,W):$;return{i:Z,row:_.row.from?_.row.from(H):H}}function EE(X){let Y=X.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!Y)throw Error("Malformed subscribe pattern: "+X);let[,Z,_,G]=Y;return(Z||"*")+(_?":"+(_.indexOf(".")===-1?"public."+_:_):"")+(G?"="+G:"")}import x$ from"stream";function lZ(X,Y,Z=393216){return new Promise(async(_,G)=>{await X.begin(async(W)=>{let $;!Y&&([{oid:Y}]=await W`select lo_creat(-1) as oid`);let[{fd:H}]=await W`select lo_open(${Y}, ${Z}) as fd`,Q={writable:z,readable:J,close:()=>W`select lo_close(${H})`.then($),tell:()=>W`select lo_tell64(${H})`,read:(F)=>W`select loread(${H}, ${F}) as data`,write:(F)=>W`select lowrite(${H}, ${F})`,truncate:(F)=>W`select lo_truncate64(${H}, ${F})`,seek:(F,O=0)=>W`select lo_lseek64(${H}, ${F}, ${O})`,size:()=>W`
78
78
  select
79
79
  lo_lseek64(${H}, location, 0) as position,
80
80
  seek.size
@@ -84,10 +84,10 @@ params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrac
84
84
  tell.location
85
85
  from (select lo_tell64($1) as location) tell
86
86
  ) seek
87
- `};return G(Q),new Promise(async(U)=>W=U);async function J({highWaterMark:U=16384,start:O=0,end:L=1/0}={}){let w=L-O;return O&&await Q.seek(O),new kW.Readable({highWaterMark:U,async read(R){let b=R>w?R-w:R;w-=R;let[{data:x}]=await Q.read(b);if(this.push(x),x.length<R)this.push(null)}})}async function z({highWaterMark:U=16384,start:O=0}={}){return O&&await Q.seek(O),new kW.Writable({highWaterMark:U,write(L,w,R){Q.write(L).then(()=>R(),R)}})}}).catch(_)})}Object.assign(GY,{PostgresError:R2,toPascal:m4,pascal:b5,toCamel:p4,camel:k5,toKebab:u4,kebab:y5,fromPascal:q8,fromCamel:C8,fromKebab:j8,BigInt:{to:20,from:[20],parse:(Y)=>BigInt(Y),serialize:(Y)=>Y.toString()}});var N2=GY;function GY(Y,Z){let X=RE(Y,Z),G=X.no_subscribe||d5(GY,{...X}),_=!1,$=R1(),W=R1(),H=R1(),Q=R1(),J=R1(),z=R1(),U=R1(),O=R1(),L={connecting:W,reserved:H,closed:Q,ended:J,open:z,busy:U,full:O},w=[...Array(X.max)].map(()=>u5(X,L,{onopen:$1,onend:h0,onclose:r1})),R=b(c);return Object.assign(R,{get parameters(){return X.parameters},largeObject:c5.bind(null,R),subscribe:G,CLOSE:A2,END:A2,PostgresError:R2,options:X,reserve:g,listen:x,begin:B,close:p,end:s}),R;function b(T){return T.debug=X.debug,Object.entries(X.types).reduce((a,[J0,v0])=>{return a[J0]=(B0)=>new n1(B0,v0.to),a},m),Object.assign($0,{types:m,typed:m,unsafe:V0,notify:h,array:q,json:C,file:k0}),$0;function m(a,J0){return new n1(a,J0)}function $0(a,...J0){return a&&Array.isArray(a.raw)?new q1(a,J0,T,N):typeof a==="string"&&!J0.length?new P8(X.transform.column.to?X.transform.column.to(a):a):new t6(a,J0)}function V0(a,J0=[],v0={}){return arguments.length===2&&!Array.isArray(J0)&&(v0=J0,J0=[]),new q1([a],J0,T,N,{prepare:!1,...v0,simple:"simple"in v0?v0.simple:J0.length===0})}function k0(a,J0=[],v0={}){return arguments.length===2&&!Array.isArray(J0)&&(v0=J0,J0=[]),new q1([],J0,(A0)=>{AE.readFile(a,"utf8",(o0,O0)=>{if(o0)return A0.reject(o0);A0.strings=[O0],T(A0)})},N,{...v0,simple:"simple"in v0?v0.simple:J0.length===0})}}async function x(T,m,$0){let V0={fn:m,onlisten:$0},k0=x.sql||(x.sql=GY({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(x.channels).forEach(([A0,{listeners:o0}])=>{delete x.channels[A0],Promise.all(o0.map((O0)=>x(A0,O0.fn,O0.onlisten).catch(()=>{})))})},onnotify(A0,o0){A0 in x.channels&&x.channels[A0].listeners.forEach((O0)=>O0.fn(o0))}})),a=x.channels||(x.channels={});if(T in a){a[T].listeners.push(V0);let A0=await a[T].result;return V0.onlisten&&V0.onlisten(),{state:A0.state,unlisten:B0}}a[T]={result:k0`listen ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`,listeners:[V0]};let v0=await a[T].result;return V0.onlisten&&V0.onlisten(),{state:v0.state,unlisten:B0};async function B0(){if(T in a===!1)return;if(a[T].listeners=a[T].listeners.filter((A0)=>A0!==V0),a[T].listeners.length)return;return delete a[T],k0`unlisten ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`}}async function h(T,m){return await R`select pg_notify(${T}, ${""+m})`}async function g(){let T=R1(),m=z.length?z.shift():await new Promise((k0,a)=>{let J0={reserve:k0,reject:a};$.push(J0),Q.length&&I0(Q.shift(),J0)});K(m,H),m.reserved=()=>T.length?m.execute(T.shift()):K(m,H),m.reserved.release=!0;let $0=b(V0);return $0.release=()=>{m.reserved=null,$1(m)},$0;function V0(k0){m.queue===O?T.push(k0):m.execute(k0)||K(m,O)}}async function B(T,m){!m&&(m=T,T="");let $0=R1(),V0=0,k0,a=null;try{return await R.unsafe("begin "+T.replace(/[^a-z ]/ig,""),[],{onexecute:v0}).execute(),await Promise.race([J0(k0,m),new Promise((B0,A0)=>k0.onclose=A0)])}catch(B0){throw B0}async function J0(B0,A0,o0){let O0=b(b0);O0.savepoint=z4,O0.prepare=(R0)=>a=R0.replace(/[^a-z0-9$-_. ]/gi);let j1,c0;o0&&await O0`savepoint ${O0(o0)}`;try{if(c0=await new Promise((R0,P1)=>{let u1=A0(O0);Promise.resolve(Array.isArray(u1)?Promise.all(u1):u1).then(R0,P1)}),j1)throw j1}catch(R0){throw await(o0?O0`rollback to ${O0(o0)}`:O0`rollback`),R0 instanceof R2&&R0.code==="25P02"&&j1||R0}if(!o0)a?await O0`prepare transaction '${O0.unsafe(a)}'`:await O0`commit`;return c0;function z4(R0,P1){if(R0&&Array.isArray(R0.raw))return z4((u1)=>u1.apply(u1,arguments));return arguments.length===1&&(P1=R0,R0=null),J0(B0,P1,"s"+V0+++(R0?"_"+R0:""))}function b0(R0){R0.catch((P1)=>j1||(j1=P1)),B0.queue===O?$0.push(R0):B0.execute(R0)||K(B0,O)}}function v0(B0){k0=B0,K(B0,H),B0.reserved=()=>$0.length?B0.execute($0.shift()):K(B0,H)}}function K(T,m){return T.queue.remove(T),m.push(T),T.queue=m,m===z?T.idleTimer.start():T.idleTimer.cancel(),T}function C(T){return new n1(T,3802)}function q(T,m){if(!Array.isArray(T))return q(Array.from(arguments));return new n1(T,m||(T.length?r6(T)||25:0),X.shared.typeArrayMap)}function c(T){if(_)return T.reject(f0.connection("CONNECTION_ENDED",X,X));if(z.length)return n(z.shift(),T);if(Q.length)return I0(Q.shift(),T);U.length?n(U.shift(),T):$.push(T)}function n(T,m){return T.execute(m)?K(T,U):K(T,O)}function N(T){return new Promise((m,$0)=>{T.state?T.active?u5(X).cancel(T.state,m,$0):T.cancelled={resolve:m,reject:$0}:($.remove(T),T.cancelled=!0,T.reject(f0.generic("57014","canceling statement due to user request")),m())})}async function s({timeout:T=null}={}){if(_)return _;await 1;let m;return _=Promise.race([new Promise(($0)=>T!==null&&(m=setTimeout(t,T*1000,$0))),Promise.all(w.map(($0)=>$0.end()).concat(x.sql?x.sql.end({timeout:0}):[],G.sql?G.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(m))}async function p(){await Promise.all(w.map((T)=>T.end()))}async function t(T){await Promise.all(w.map((m)=>m.terminate()));while($.length)$.shift().reject(f0.connection("CONNECTION_DESTROYED",X));T()}function I0(T,m){return K(T,W),T.connect(m),T}function h0(T){K(T,J)}function $1(T){if($.length===0)return K(T,z);let m=Math.ceil($.length/(W.length+1)),$0=!0;while($0&&$.length&&m-- >0){let V0=$.shift();if(V0.reserve)return V0.reserve(T);$0=T.execute(V0)}$0?K(T,U):K(T,O)}function r1(T,m){K(T,Q),T.reserved=null,T.onclose&&(T.onclose(m),T.onclose=null),X.onclose&&X.onclose(T.id),$.length&&I0(T,$.shift())}}function RE(Y,Z){if(Y&&Y.shared)return Y;let X=process.env,G=(!Y||typeof Y==="string"?Z:Y)||{},{url:_,multihost:$}=BE(Y),W=[..._.searchParams].reduce((O,[L,w])=>(O[L]=w,O),{}),H=G.hostname||G.host||$||_.hostname||X.PGHOST||"localhost",Q=G.port||_.port||X.PGPORT||5432,J=G.user||G.username||_.username||X.PGUSERNAME||X.PGUSER||TE();G.no_prepare&&(G.prepare=!1),W.sslmode&&(W.ssl=W.sslmode,delete W.sslmode),"timeout"in G&&(console.log("The timeout option is deprecated, use idle_timeout instead"),G.idle_timeout=G.timeout),W.sslrootcert==="system"&&(W.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],U={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:IE,max_pipeline:100,backoff:NE,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((O)=>O.split(":")[0]),port:Array.isArray(Q)?Q:H.split(",").map((O)=>parseInt(O.split(":")[1]||Q)),path:G.path||H.indexOf("/")>-1&&H+"/.s.PGSQL."+Q,database:G.database||G.db||(_.pathname||"").slice(1)||X.PGDATABASE||J,user:J,pass:G.pass||G.password||_.password||X.PGPASSWORD||"",...Object.entries(U).reduce((O,[L,w])=>{let R=L in G?G[L]:(L in W)?W[L]==="disable"||W[L]==="false"?!1:W[L]:X["PG"+L.toUpperCase()]||w;return O[L]=typeof R==="string"&&z.includes(L)?+R:R,O},{}),connection:{application_name:X.PGAPPNAME||"postgres.js",...G.connection,...Object.entries(W).reduce((O,[L,w])=>((L in U)||(O[L]=w),O),{})},types:G.types||{},target_session_attrs:wE(G,_,X),onnotice:G.onnotice,onnotify:G.onnotify,onclose:G.onclose,onparameter:G.onparameter,socket:G.socket,transform:KE(G.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...BW(G.types)}}function wE(Y,Z,X){let G=Y.target_session_attrs||Z.searchParams.get("target_session_attrs")||X.PGTARGETSESSIONATTRS;if(!G||["read-write","read-only","primary","standby","prefer-standby"].includes(G))return G;throw Error("target_session_attrs "+G+" is not supported")}function NE(Y){return(0.5+Math.random()/2)*Math.min(3**Y/100,20)}function IE(){return 60*(30+Math.random()*30)}function KE(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 BE(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 TE(){try{return ME.userInfo().username}catch(Y){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class q0{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 G=(M(Y,S0)?Y._.selectedFields:M(Y,V1)?Y[M0].selectedFields:Y)[Z];if(M(G,f.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!G.isSelectionField)return G.sql;let _=G.clone();return _.isSelectionField=!0,_}if(M(G,f)){if(this.config.sqlBehavior==="sql")return G;throw 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(G,U0)){if(this.config.alias)return new Proxy(G,new M2(new Proxy(G.table,new A8(this.config.alias,this.config.replaceOriginalName??!1))));return G}if(typeof G!=="object"||G===null)return G;return new Proxy(G,new q0(this.config))}}class bW{constructor(Y,Z){this.unique=Y,this.name=Z}static[E]="PgIndexBuilderOn";on(...Y){return new _Y(Y.map((Z)=>{if(M(Z,f))return Z;Z=Z;let X=new O8(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 _Y(Y.map((Z)=>{if(M(Z,f))return Z;Z=Z;let X=new O8(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=Z.defaultConfig,X}),this.unique,!0,this.name)}using(Y,...Z){return new _Y(Z.map((X)=>{if(M(X,f))return X;X=X;let G=new O8(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),G}),this.unique,!0,this.name,Y)}}class _Y{static[E]="PgIndexBuilder";config;constructor(Y,Z,X,G,_="btree"){this.config={name:G,columns:Y,unique:Z,only:X,method:_}}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 yW(this.config,Y)}}class yW{static[E]="PgIndex";config;constructor(Y,Z){this.config={...Y,table:Z}}}function l5(Y){return new bW(!0,Y)}function CE(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function qE(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,G,_)=>{let $=_===0?G.toLowerCase():`${G[0].toUpperCase()}${G.slice(1)}`;return X+$},"")}function jE(Y){return Y}class o5{static[E]="CasingCache";cache={};cachedTables={};convert;constructor(Y){this.convert=Y==="snake_case"?CE:Y==="camelCase"?qE:jE}getColumnCasing(Y){if(!Y.keyAsName)return Y.name;let Z=Y.table[P.Symbol.Schema]??"public",X=Y.table[P.Symbol.OriginalName],G=`${Z}.${X}.${Y.name}`;if(!this.cache[G])this.cacheTable(Y.table);return this.cache[G]}cacheTable(Y){let Z=Y[P.Symbol.Schema]??"public",X=Y[P.Symbol.OriginalName],G=`${Z}.${X}`;if(!this.cachedTables[G]){for(let _ of Object.values(Y[P.Symbol.Columns])){let $=`${G}.${_.name}`;this.cache[$]=this.convert(_.name)}this.cachedTables[G]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class v8 extends V1{static[E]="PgViewBase"}class c4{static[E]="PgDialect";casing;constructor(Y){this.casing=new o5(Y?.casing)}async migrate(Y,Z,X){let G=typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",_=typeof X==="string"?"drizzle":X.migrationsSchema??"drizzle",$=V`
88
- CREATE TABLE IF NOT EXISTS ${V.identifier(_)}.${V.identifier(G)} (
87
+ `};return _(Q),new Promise(async(F)=>$=F);async function J({highWaterMark:F=16384,start:O=0,end:D=1/0}={}){let w=D-O;return O&&await Q.seek(O),new x$.Readable({highWaterMark:F,async read(A){let x=A>w?A-w:A;w-=A;let[{data:j}]=await Q.read(x);if(this.push(j),j.length<A)this.push(null)}})}async function z({highWaterMark:F=16384,start:O=0}={}){return O&&await Q.seek(O),new x$.Writable({highWaterMark:F,write(D,w,A){Q.write(D).then(()=>A(),A)}})}}).catch(G)})}Object.assign(_X,{PostgresError:A8,toPascal:g4,pascal:yZ,toCamel:y4,camel:bZ,toKebab:p4,kebab:gZ,fromPascal:q2,fromCamel:C2,fromKebab:j2,BigInt:{to:20,from:[20],parse:(X)=>BigInt(X),serialize:(X)=>X.toString()}});var w8=_X;function _X(X,Y){let Z=DE(X,Y),_=Z.no_subscribe||cZ(_X,{...Z}),G=!1,W=M1(),$=M1(),H=M1(),Q=M1(),J=M1(),z=M1(),F=M1(),O=M1(),D={connecting:$,reserved:H,closed:Q,ended:J,open:z,busy:F,full:O},w=[...Array(Z.max)].map(()=>dZ(Z,D,{onopen:q1,onend:O1,onclose:c4})),A=x(_0);return Object.assign(A,{get parameters(){return Z.parameters},largeObject:lZ.bind(null,A),subscribe:_,CLOSE:M8,END:M8,PostgresError:A8,options:Z,reserve:h,listen:j,begin:i,close:o,end:W0}),A;function x(I){return I.debug=Z.debug,Object.entries(Z.types).reduce((n,[H0,q0])=>{return n[H0]=(N0)=>new n1(N0,q0.to),n},u),Object.assign($0,{types:u,typed:u,unsafe:R0,notify:P,array:m,json:y,file:P0}),$0;function u(n,H0){return new n1(n,H0)}function $0(n,...H0){return n&&Array.isArray(n.raw)?new C1(n,H0,I,K):typeof n==="string"&&!H0.length?new S2(Z.transform.column.to?Z.transform.column.to(n):n):new t6(n,H0)}function R0(n,H0=[],q0={}){return arguments.length===2&&!Array.isArray(H0)&&(q0=H0,H0=[]),new C1([n],H0,I,K,{prepare:!1,...q0,simple:"simple"in q0?q0.simple:H0.length===0})}function P0(n,H0=[],q0={}){return arguments.length===2&&!Array.isArray(H0)&&(q0=H0,H0=[]),new C1([],H0,(D0)=>{VE.readFile(n,"utf8",(d0,U0)=>{if(d0)return D0.reject(d0);D0.strings=[U0],I(D0)})},K,{...q0,simple:"simple"in q0?q0.simple:H0.length===0})}}async function j(I,u,$0){let R0={fn:u,onlisten:$0},P0=j.sql||(j.sql=_X({...Z,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(j.channels).forEach(([D0,{listeners:d0}])=>{delete j.channels[D0],Promise.all(d0.map((U0)=>j(D0,U0.fn,U0.onlisten).catch(()=>{})))})},onnotify(D0,d0){D0 in j.channels&&j.channels[D0].listeners.forEach((U0)=>U0.fn(d0))}})),n=j.channels||(j.channels={});if(I in n){n[I].listeners.push(R0);let D0=await n[I].result;return R0.onlisten&&R0.onlisten(),{state:D0.state,unlisten:N0}}n[I]={result:P0`listen ${P0.unsafe('"'+I.replace(/"/g,'""')+'"')}`,listeners:[R0]};let q0=await n[I].result;return R0.onlisten&&R0.onlisten(),{state:q0.state,unlisten:N0};async function N0(){if(I in n===!1)return;if(n[I].listeners=n[I].listeners.filter((D0)=>D0!==R0),n[I].listeners.length)return;return delete n[I],P0`unlisten ${P0.unsafe('"'+I.replace(/"/g,'""')+'"')}`}}async function P(I,u){return await A`select pg_notify(${I}, ${""+u})`}async function h(){let I=M1(),u=z.length?z.shift():await new Promise((P0,n)=>{let H0={reserve:P0,reject:n};W.push(H0),Q.length&&p0(Q.shift(),H0)});p(u,H),u.reserved=()=>I.length?u.execute(I.shift()):p(u,H),u.reserved.release=!0;let $0=x(R0);return $0.release=()=>{u.reserved=null,q1(u)},$0;function R0(P0){u.queue===O?I.push(P0):u.execute(P0)||p(u,O)}}async function i(I,u){!u&&(u=I,I="");let $0=M1(),R0=0,P0,n=null;try{return await A.unsafe("begin "+I.replace(/[^a-z ]/ig,""),[],{onexecute:q0}).execute(),await Promise.race([H0(P0,u),new Promise((N0,D0)=>P0.onclose=D0)])}catch(N0){throw N0}async function H0(N0,D0,d0){let U0=x(v0);U0.savepoint=z4,U0.prepare=(L0)=>n=L0.replace(/[^a-z0-9$-_. ]/gi);let j1,m0;d0&&await U0`savepoint ${U0(d0)}`;try{if(m0=await new Promise((L0,S1)=>{let u1=D0(U0);Promise.resolve(Array.isArray(u1)?Promise.all(u1):u1).then(L0,S1)}),j1)throw j1}catch(L0){throw await(d0?U0`rollback to ${U0(d0)}`:U0`rollback`),L0 instanceof A8&&L0.code==="25P02"&&j1||L0}if(!d0)n?await U0`prepare transaction '${U0.unsafe(n)}'`:await U0`commit`;return m0;function z4(L0,S1){if(L0&&Array.isArray(L0.raw))return z4((u1)=>u1.apply(u1,arguments));return arguments.length===1&&(S1=L0,L0=null),H0(N0,S1,"s"+R0+++(L0?"_"+L0:""))}function v0(L0){L0.catch((S1)=>j1||(j1=S1)),N0.queue===O?$0.push(L0):N0.execute(L0)||p(N0,O)}}function q0(N0){P0=N0,p(N0,H),N0.reserved=()=>$0.length?N0.execute($0.shift()):p(N0,H)}}function p(I,u){return I.queue.remove(I),u.push(I),I.queue=u,u===z?I.idleTimer.start():I.idleTimer.cancel(),I}function y(I){return new n1(I,3802)}function m(I,u){if(!Array.isArray(I))return m(Array.from(arguments));return new n1(I,u||(I.length?r6(I)||25:0),Z.shared.typeArrayMap)}function _0(I){if(G)return I.reject(S0.connection("CONNECTION_ENDED",Z,Z));if(z.length)return y0(z.shift(),I);if(Q.length)return p0(Q.shift(),I);F.length?y0(F.shift(),I):W.push(I)}function y0(I,u){return I.execute(u)?p(I,F):p(I,O)}function K(I){return new Promise((u,$0)=>{I.state?I.active?dZ(Z).cancel(I.state,u,$0):I.cancelled={resolve:u,reject:$0}:(W.remove(I),I.cancelled=!0,I.reject(S0.generic("57014","canceling statement due to user request")),u())})}async function W0({timeout:I=null}={}){if(G)return G;await 1;let u;return G=Promise.race([new Promise(($0)=>I!==null&&(u=setTimeout(X0,I*1000,$0))),Promise.all(w.map(($0)=>$0.end()).concat(j.sql?j.sql.end({timeout:0}):[],_.sql?_.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(u))}async function o(){await Promise.all(w.map((I)=>I.end()))}async function X0(I){await Promise.all(w.map((u)=>u.terminate()));while(W.length)W.shift().reject(S0.connection("CONNECTION_DESTROYED",Z));I()}function p0(I,u){return p(I,$),I.connect(u),I}function O1(I){p(I,J)}function q1(I){if(W.length===0)return p(I,z);let u=Math.ceil(W.length/($.length+1)),$0=!0;while($0&&W.length&&u-- >0){let R0=W.shift();if(R0.reserve)return R0.reserve(I);$0=I.execute(R0)}$0?p(I,F):p(I,O)}function c4(I,u){p(I,Q),I.reserved=null,I.onclose&&(I.onclose(u),I.onclose=null),Z.onclose&&Z.onclose(I.id),W.length&&p0(I,W.shift())}}function DE(X,Y){if(X&&X.shared)return X;let Z=process.env,_=(!X||typeof X==="string"?Y:X)||{},{url:G,multihost:W}=wE(X),$=[...G.searchParams].reduce((O,[D,w])=>(O[D]=w,O),{}),H=_.hostname||_.host||W||G.hostname||Z.PGHOST||"localhost",Q=_.port||G.port||Z.PGPORT||5432,J=_.user||_.username||G.username||Z.PGUSERNAME||Z.PGUSER||NE();_.no_prepare&&(_.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in _&&(console.log("The timeout option is deprecated, use idle_timeout instead"),_.idle_timeout=_.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],F={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:AE,max_pipeline:100,backoff:ME,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((O)=>O.split(":")[0]),port:Array.isArray(Q)?Q:H.split(",").map((O)=>parseInt(O.split(":")[1]||Q)),path:_.path||H.indexOf("/")>-1&&H+"/.s.PGSQL."+Q,database:_.database||_.db||(G.pathname||"").slice(1)||Z.PGDATABASE||J,user:J,pass:_.pass||_.password||G.password||Z.PGPASSWORD||"",...Object.entries(F).reduce((O,[D,w])=>{let A=D in _?_[D]:(D in $)?$[D]==="disable"||$[D]==="false"?!1:$[D]:Z["PG"+D.toUpperCase()]||w;return O[D]=typeof A==="string"&&z.includes(D)?+A:A,O},{}),connection:{application_name:Z.PGAPPNAME||"postgres.js",..._.connection,...Object.entries($).reduce((O,[D,w])=>((D in F)||(O[D]=w),O),{})},types:_.types||{},target_session_attrs:LE(_,G,Z),onnotice:_.onnotice,onnotify:_.onnotify,onclose:_.onclose,onparameter:_.onparameter,socket:_.socket,transform:RE(_.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...N$(_.types)}}function LE(X,Y,Z){let _=X.target_session_attrs||Y.searchParams.get("target_session_attrs")||Z.PGTARGETSESSIONATTRS;if(!_||["read-write","read-only","primary","standby","prefer-standby"].includes(_))return _;throw Error("target_session_attrs "+_+" is not supported")}function ME(X){return(0.5+Math.random()/2)*Math.min(3**X/100,20)}function AE(){return 60*(30+Math.random()*30)}function RE(X){return{undefined:X.undefined,column:{from:typeof X.column==="function"?X.column:X.column&&X.column.from,to:X.column&&X.column.to},value:{from:typeof X.value==="function"?X.value:X.value&&X.value.from,to:X.value&&X.value.to},row:{from:typeof X.row==="function"?X.row:X.row&&X.row.from,to:X.row&&X.row.to}}}function wE(X){if(!X||typeof X!=="string")return{url:{searchParams:new Map}};let Y=X;Y=Y.slice(Y.indexOf("://")+3).split(/[?/]/)[0],Y=decodeURIComponent(Y.slice(Y.indexOf("@")+1));let Z=new URL(X.replace(Y,Y.split(",")[0]));return{url:{username:decodeURIComponent(Z.username),password:decodeURIComponent(Z.password),host:Z.host,hostname:Z.hostname,port:Z.port,pathname:Z.pathname,searchParams:Z.searchParams},multihost:Y.indexOf(",")>-1&&Y}}function NE(){try{return OE.userInfo().username}catch(X){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class B0{static[E]="SelectionProxyHandler";config;constructor(X){this.config={...X}}get(X,Y){if(Y==="_")return{...X._,selectedFields:new Proxy(X._.selectedFields,this)};if(Y===V0)return{...X[V0],selectedFields:new Proxy(X[V0].selectedFields,this)};if(typeof Y==="symbol")return X[Y];let _=(M(X,C0)?X._.selectedFields:M(X,F1)?X[V0].selectedFields:X)[Y];if(M(_,S.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!_.isSelectionField)return _.sql;let G=_.clone();return G.isSelectionField=!0,G}if(M(_,S)){if(this.config.sqlBehavior==="sql")return _;throw Error(`You tried to reference "${Y}" 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(_,z0)){if(this.config.alias)return new Proxy(_,new L8(new Proxy(_.table,new A2(this.config.alias,this.config.replaceOriginalName??!1))));return _}if(typeof _!=="object"||_===null)return _;return new Proxy(_,new B0(this.config))}}class f${constructor(X,Y){this.unique=X,this.name=Y}static[E]="PgIndexBuilderOn";on(...X){return new GX(X.map((Y)=>{if(M(Y,S))return Y;Y=Y;let Z=new V2(Y.name,!!Y.keyAsName,Y.columnType,Y.indexConfig);return Y.indexConfig=JSON.parse(JSON.stringify(Y.defaultConfig)),Z}),this.unique,!1,this.name)}onOnly(...X){return new GX(X.map((Y)=>{if(M(Y,S))return Y;Y=Y;let Z=new V2(Y.name,!!Y.keyAsName,Y.columnType,Y.indexConfig);return Y.indexConfig=Y.defaultConfig,Z}),this.unique,!0,this.name)}using(X,...Y){return new GX(Y.map((Z)=>{if(M(Z,S))return Z;Z=Z;let _=new V2(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=JSON.parse(JSON.stringify(Z.defaultConfig)),_}),this.unique,!0,this.name,X)}}class GX{static[E]="PgIndexBuilder";config;constructor(X,Y,Z,_,G="btree"){this.config={name:_,columns:X,unique:Y,only:Z,method:G}}concurrently(){return this.config.concurrently=!0,this}with(X){return this.config.with=X,this}where(X){return this.config.where=X,this}build(X){return new h$(this.config,X)}}class h${static[E]="PgIndex";config;constructor(X,Y){this.config={...X,table:Y}}}function oZ(X){return new f$(!0,X)}function IE(X){return(X.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((Z)=>Z.toLowerCase()).join("_")}function KE(X){return(X.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((Z,_,G)=>{let W=G===0?_.toLowerCase():`${_[0].toUpperCase()}${_.slice(1)}`;return Z+W},"")}function BE(X){return X}class iZ{static[E]="CasingCache";cache={};cachedTables={};convert;constructor(X){this.convert=X==="snake_case"?IE:X==="camelCase"?KE:BE}getColumnCasing(X){if(!X.keyAsName)return X.name;let Y=X.table[T.Symbol.Schema]??"public",Z=X.table[T.Symbol.OriginalName],_=`${Y}.${Z}.${X.name}`;if(!this.cache[_])this.cacheTable(X.table);return this.cache[_]}cacheTable(X){let Y=X[T.Symbol.Schema]??"public",Z=X[T.Symbol.OriginalName],_=`${Y}.${Z}`;if(!this.cachedTables[_]){for(let G of Object.values(X[T.Symbol.Columns])){let W=`${_}.${G.name}`;this.cache[W]=this.convert(G.name)}this.cachedTables[_]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class v2 extends F1{static[E]="PgViewBase"}class u4{static[E]="PgDialect";casing;constructor(X){this.casing=new iZ(X?.casing)}async migrate(X,Y,Z){let _=typeof Z==="string"?"__drizzle_migrations":Z.migrationsTable??"__drizzle_migrations",G=typeof Z==="string"?"drizzle":Z.migrationsSchema??"drizzle",W=V`
88
+ CREATE TABLE IF NOT EXISTS ${V.identifier(G)}.${V.identifier(_)} (
89
89
  id SERIAL PRIMARY KEY,
90
90
  hash text NOT NULL,
91
91
  created_at bigint
92
92
  )
93
- `;await Z.execute(V`CREATE SCHEMA IF NOT EXISTS ${V.identifier(_)}`),await Z.execute($);let H=(await Z.all(V`select id, hash, created_at from ${V.identifier(_)}.${V.identifier(G)} 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(V.raw(z));await Q.execute(V`insert into ${V.identifier(_)}.${V.identifier(G)} ("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=[V`with `];for(let[X,G]of Y.entries())if(Z.push(V`${V.identifier(G._.alias)} as (${G._.sql})`),X<Y.length-1)Z.push(V`, `);return Z.push(V` `),V.join(Z)}buildDeleteQuery({table:Y,where:Z,returning:X,withList:G}){let _=this.buildWithCTE(G),$=X?V` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,W=Z?V` where ${Z}`:void 0;return V`${_}delete from ${Y}${W}${$}`}buildUpdateSet(Y,Z){let X=Y[P.Symbol.Columns],G=Object.keys(X).filter(($)=>Z[$]!==void 0||X[$]?.onUpdateFn!==void 0),_=G.length;return V.join(G.flatMap(($,W)=>{let H=X[$],Q=Z[$]??V.param(H.onUpdateFn(),H),J=V`${V.identifier(this.casing.getColumnCasing(H))} = ${Q}`;if(W<_-1)return[J,V.raw(", ")];return[J]}))}buildUpdateQuery({table:Y,set:Z,where:X,returning:G,withList:_,from:$,joins:W}){let H=this.buildWithCTE(_),Q=Y[u0.Symbol.Name],J=Y[u0.Symbol.Schema],z=Y[u0.Symbol.OriginalName],U=Q===z?void 0:Q,O=V`${J?V`${V.identifier(J)}.`:void 0}${V.identifier(z)}${U&&V` ${V.identifier(U)}`}`,L=this.buildUpdateSet(Y,Z),w=$&&V.join([V.raw(" from "),this.buildFromTable($)]),R=this.buildJoins(W),b=G?V` returning ${this.buildSelection(G,{isSingleTable:!$})}`:void 0,x=X?V` where ${X}`:void 0;return V`${H}update ${O} set ${L}${w}${R}${x}${b}`}buildSelection(Y,{isSingleTable:Z=!1}={}){let X=Y.length,G=Y.flatMap(({field:_},$)=>{let W=[];if(M(_,f.Aliased)&&_.isSelectionField)W.push(V.identifier(_.fieldAlias));else if(M(_,f.Aliased)||M(_,f)){let H=M(_,f.Aliased)?_.sql:_;if(Z)W.push(new f(H.queryChunks.map((Q)=>{if(M(Q,j))return V.identifier(this.casing.getColumnCasing(Q));return Q})));else W.push(H);if(M(_,f.Aliased))W.push(V` as ${V.identifier(_.fieldAlias)}`)}else if(M(_,U0))if(Z)W.push(V.identifier(this.casing.getColumnCasing(_)));else W.push(_);if($<X-1)W.push(V`, `);return W});return V.join(G)}buildJoins(Y){if(!Y||Y.length===0)return;let Z=[];for(let[X,G]of Y.entries()){if(X===0)Z.push(V` `);let _=G.table,$=G.lateral?V` lateral`:void 0,W=G.on?V` on ${G.on}`:void 0;if(M(_,u0)){let H=_[u0.Symbol.Name],Q=_[u0.Symbol.Schema],J=_[u0.Symbol.OriginalName],z=H===J?void 0:G.alias;Z.push(V`${V.raw(G.joinType)} join${$} ${Q?V`${V.identifier(Q)}.`:void 0}${V.identifier(J)}${z&&V` ${V.identifier(z)}`}${W}`)}else if(M(_,V1)){let H=_[M0].name,Q=_[M0].schema,J=_[M0].originalName,z=H===J?void 0:G.alias;Z.push(V`${V.raw(G.joinType)} join${$} ${Q?V`${V.identifier(Q)}.`:void 0}${V.identifier(J)}${z&&V` ${V.identifier(z)}`}${W}`)}else Z.push(V`${V.raw(G.joinType)} join${$} ${_}${W}`);if(X<Y.length-1)Z.push(V` `)}return V.join(Z)}buildFromTable(Y){if(M(Y,P)&&Y[P.Symbol.IsAlias]){let Z=V`${V.identifier(Y[P.Symbol.OriginalName])}`;if(Y[P.Symbol.Schema])Z=V`${V.identifier(Y[P.Symbol.Schema])}.${Z}`;return V`${Z} ${V.identifier(Y[P.Symbol.Name])}`}return Y}buildSelectQuery({withList:Y,fields:Z,fieldsFlat:X,where:G,having:_,table:$,joins:W,orderBy:H,groupBy:Q,limit:J,offset:z,lockingClause:U,distinct:O,setOperators:L}){let w=X??T1(Z);for(let t of w)if(M(t.field,U0)&&d0(t.field.table)!==(M($,S0)?$._.alias:M($,v8)?$[M0].name:M($,f)?void 0:d0($))&&!((I0)=>W?.some(({alias:h0})=>h0===(I0[P.Symbol.IsAlias]?d0(I0):I0[P.Symbol.BaseName])))(t.field.table)){let I0=d0(t.field.table);throw Error(`Your "${t.path.join("->")}" field references a column "${I0}"."${t.field.name}", but the table "${I0}" is not part of the query! Did you forget to join it?`)}let R=!W||W.length===0,b=this.buildWithCTE(Y),x;if(O)x=O===!0?V` distinct`:V` distinct on (${V.join(O.on,V`, `)})`;let h=this.buildSelection(w,{isSingleTable:R}),g=this.buildFromTable($),B=this.buildJoins(W),K=G?V` where ${G}`:void 0,C=_?V` having ${_}`:void 0,q;if(H&&H.length>0)q=V` order by ${V.join(H,V`, `)}`;let c;if(Q&&Q.length>0)c=V` group by ${V.join(Q,V`, `)}`;let n=typeof J==="object"||typeof J==="number"&&J>=0?V` limit ${J}`:void 0,N=z?V` offset ${z}`:void 0,s=V.empty();if(U){let t=V` for ${V.raw(U.strength)}`;if(U.config.of)t.append(V` of ${V.join(Array.isArray(U.config.of)?U.config.of:[U.config.of],V`, `)}`);if(U.config.noWait)t.append(V` nowait`);else if(U.config.skipLocked)t.append(V` skip locked`);s.append(t)}let p=V`${b}select${x} ${h} from ${g}${B}${K}${c}${C}${q}${n}${N}${s}`;if(L.length>0)return this.buildSetOperations(p,L);return p}buildSetOperations(Y,Z){let[X,...G]=Z;if(!X)throw Error("Cannot pass undefined values to any set operator");if(G.length===0)return this.buildSetOperationQuery({leftSelect:Y,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:Y,setOperator:X}),G)}buildSetOperationQuery({leftSelect:Y,setOperator:{type:Z,isAll:X,rightSelect:G,limit:_,orderBy:$,offset:W}}){let H=V`(${Y.getSQL()}) `,Q=V`(${G.getSQL()})`,J;if($&&$.length>0){let L=[];for(let w of $)if(M(w,j))L.push(V.identifier(w.name));else if(M(w,f)){for(let R=0;R<w.queryChunks.length;R++){let b=w.queryChunks[R];if(M(b,j))w.queryChunks[R]=V.identifier(b.name)}L.push(V`${w}`)}else L.push(V`${w}`);J=V` order by ${V.join(L,V`, `)} `}let z=typeof _==="object"||typeof _==="number"&&_>=0?V` limit ${_}`:void 0,U=V.raw(`${Z} ${X?"all ":""}`),O=W?V` offset ${W}`:void 0;return V`${H}${U}${Q}${J}${z}${O}`}buildInsertQuery({table:Y,values:Z,onConflict:X,returning:G,withList:_,select:$,overridingSystemValue_:W}){let H=[],Q=Y[P.Symbol.Columns],J=Object.entries(Q).filter(([b,x])=>!x.shouldDisableInsert()),z=J.map(([,b])=>V.identifier(this.casing.getColumnCasing(b)));if($){let b=Z;if(M(b,f))H.push(b);else H.push(b.getSQL())}else{let b=Z;H.push(V.raw("values "));for(let[x,h]of b.entries()){let g=[];for(let[B,K]of J){let C=h[B];if(C===void 0||M(C,A1)&&C.value===void 0)if(K.defaultFn!==void 0){let q=K.defaultFn(),c=M(q,f)?q:V.param(q,K);g.push(c)}else if(!K.default&&K.onUpdateFn!==void 0){let q=K.onUpdateFn(),c=M(q,f)?q:V.param(q,K);g.push(c)}else g.push(V`default`);else g.push(C)}if(H.push(g),x<b.length-1)H.push(V`, `)}}let U=this.buildWithCTE(_),O=V.join(H),L=G?V` returning ${this.buildSelection(G,{isSingleTable:!0})}`:void 0,w=X?V` on conflict ${X}`:void 0,R=W===!0?V`overriding system value `:void 0;return V`${U}insert into ${Y} ${z} ${R}${O}${w}${L}`}buildRefreshMaterializedViewQuery({view:Y,concurrently:Z,withNoData:X}){let G=Z?V` concurrently`:void 0,_=X?V` with no data`:void 0;return V`refresh materialized view${G} ${Y}${_}`}prepareTyping(Y){if(M(Y,g6)||M(Y,y6))return"json";else if(M(Y,p6))return"decimal";else if(M(Y,m6))return"time";else if(M(Y,u6)||M(Y,d6))return"timestamp";else if(M(Y,k6)||M(Y,b6))return"date";else if(M(Y,c6))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:G,tableConfig:_,queryConfig:$,tableAlias:W,nestedQueryRelation:H,joinOn:Q}){let J=[],z,U,O=[],L,w=[];if($===!0)J=Object.entries(_.columns).map(([x,h])=>({dbKey:h.name,tsKey:x,field:i1(h,W),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let b=Object.fromEntries(Object.entries(_.columns).map(([C,q])=>[C,i1(q,W)]));if($.where){let C=typeof $.where==="function"?$.where(b,UW()):$.where;L=C&&R8(C,W)}let x=[],h=[];if($.columns){let C=!1;for(let[q,c]of Object.entries($.columns)){if(c===void 0)continue;if(q in _.columns){if(!C&&c===!0)C=!0;h.push(q)}}if(h.length>0)h=C?h.filter((q)=>$.columns?.[q]===!0):Object.keys(_.columns).filter((q)=>!h.includes(q))}else h=Object.keys(_.columns);for(let C of h){let q=_.columns[C];x.push({tsKey:C,value:q})}let g=[];if($.with)g=Object.entries($.with).filter((C)=>!!C[1]).map(([C,q])=>({tsKey:C,queryConfig:q,relation:_.relations[C]}));let B;if($.extras){B=typeof $.extras==="function"?$.extras(b,{sql:V}):$.extras;for(let[C,q]of Object.entries(B))x.push({tsKey:C,value:R5(q,W)})}for(let{tsKey:C,value:q}of x)J.push({dbKey:M(q,f.Aliased)?q.fieldAlias:_.columns[C].name,tsKey:C,field:M(q,U0)?i1(q,W):q,relationTableTsKey:void 0,isJson:!1,selection:[]});let K=typeof $.orderBy==="function"?$.orderBy(b,EW()):$.orderBy??[];if(!Array.isArray(K))K=[K];O=K.map((C)=>{if(M(C,U0))return i1(C,W);return R8(C,W)}),z=$.limit,U=$.offset;for(let{tsKey:C,queryConfig:q,relation:c}of g){let n=OW(Z,X,c),N=g4(c.referencedTable),s=X[N],p=`${W}_${C}`,t=B8(...n.fields.map(($1,r1)=>l6(i1(n.references[r1],p),i1($1,W)))),I0=this.buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:Y[s],tableConfig:Z[s],queryConfig:M(c,K4)?q===!0?{limit:1}:{...q,limit:1}:q,tableAlias:p,joinOn:t,nestedQueryRelation:c}),h0=V`${V.identifier(p)}.${V.identifier("data")}`.as(C);w.push({on:V`true`,table:new S0(I0.sql,{},p),alias:p,joinType:"left",lateral:!0}),J.push({dbKey:C,tsKey:C,field:h0,relationTableTsKey:s,isJson:!0,selection:I0.selection})}}if(J.length===0)throw new f6({message:`No fields selected for table "${_.tsName}" ("${W}")`});let R;if(L=B8(Q,L),H){let b=V`json_build_array(${V.join(J.map(({field:g,tsKey:B,isJson:K})=>K?V`${V.identifier(`${W}_${B}`)}.${V.identifier("data")}`:M(g,f.Aliased)?g.sql:g),V`, `)})`;if(M(H,T8))b=V`coalesce(json_agg(${b}${O.length>0?V` order by ${V.join(O,V`, `)}`:void 0}), '[]'::json)`;let x=[{dbKey:"data",tsKey:"data",field:b.as("data"),isJson:!0,relationTableTsKey:_.tsName,selection:J}];if(z!==void 0||U!==void 0||O.length>0)R=this.buildSelectQuery({table:x6(G,W),fields:{},fieldsFlat:[{path:[],field:V.raw("*")}],where:L,limit:z,offset:U,orderBy:O,setOperators:[]}),L=void 0,z=void 0,U=void 0,O=[];else R=x6(G,W);R=this.buildSelectQuery({table:M(R,u0)?R:new S0(R,{},W),fields:{},fieldsFlat:x.map(({field:g})=>({path:[],field:M(g,U0)?i1(g,W):g})),joins:w,where:L,limit:z,offset:U,orderBy:O,setOperators:[]})}else R=this.buildSelectQuery({table:x6(G,W),fields:{},fieldsFlat:J.map(({field:b})=>({path:[],field:M(b,U0)?i1(b,W):b})),joins:w,where:L,limit:z,offset:U,orderBy:O,setOperators:[]});return{tableTsKey:_.tsName,sql:R,selection:J}}}class i5{static[E]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class _1{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,G;if(this.fields)G=this.fields;else if(M(X,S0))G=Object.fromEntries(Object.keys(X._.selectedFields).map((_)=>[_,X[_]]));else if(M(X,v8))G=X[M0].selectedFields;else if(M(X,f))G={};else G=c7(X);return new n5({table:X,fields:G,isPartialSelect:Z,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class gW extends i5{static[E]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:Y,fields:Z,isPartialSelect:X,session:G,dialect:_,withList:$,distinct:W}){super();this.config={withList:$,table:Y,fields:{...Z},distinct:W,setOperators:[]},this.isPartialSelect=X,this.session=G,this.dialect=_,this._={selectedFields:Z,config:this.config},this.tableName=J4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let H of m1(Y))this.usedTables.add(H)}getUsedTables(){return[...this.usedTables]}createJoin(Y,Z){return(X,G)=>{let _=this.tableName,$=J4(X);for(let W of m1(X))this.usedTables.add(W);if(typeof $==="string"&&this.config.joins?.some((W)=>W.alias===$))throw Error(`Alias "${$}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof _==="string")this.config.fields={[_]:this.config.fields};if(typeof $==="string"&&!M(X,f)){let W=M(X,S0)?X._.selectedFields:M(X,V1)?X[M0].selectedFields:X[P.Symbol.Columns];this.config.fields[$]=W}}if(typeof G==="function")G=G(new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:G,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 G=typeof X==="function"?X(PE()):X;if(!w8(this.getSelectedFields(),G.getSelectedFields()))throw 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:G}),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(...m1(this.config.table)),this.config.joins)for(let X of this.config.joins)Z.push(...m1(X.table));return new Proxy(new S0(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 n5 extends gW{static[E]="PgSelect";_prepare(Y){let{session:Z,config:X,dialect:G,joinsNotNullableMap:_,authToken:$,cacheConfig:W,usedTables:H}=this;if(!Z)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:Q}=X;return E0.startActiveSpan("drizzle.prepareQuery",()=>{let J=T1(Q),z=Z.prepareQuery(G.sqlToQuery(this.getSQL()),J,Y,!0,void 0,{type:"select",tables:[...H]},W);return z.joinsNotNullableMap=_,z.setToken($)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}d7(n5,[G1]);function I2(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 Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return X.addSetOperators($)}}var PE=()=>({union:SE,unionAll:vE,intersect:xE,intersectAll:fE,except:hE,exceptAll:kE}),SE=I2("union",!1),vE=I2("union",!0),xE=I2("intersect",!1),fE=I2("intersect",!0),hE=I2("except",!1),kE=I2("except",!0);class x8{static[E]="PgQueryBuilder";dialect;dialectConfig;constructor(Y){this.dialect=M(Y,c4)?Y:void 0,this.dialectConfig=M(Y,c4)?void 0:Y}$with=(Y,Z)=>{let X=this;return{as:(_)=>{if(typeof _==="function")_=_(X);return new Proxy(new L8(_.getSQL(),Z??("getSelectedFields"in _?_.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 G($){return new _1({fields:$??void 0,session:void 0,dialect:Z.getDialect(),distinct:!0})}function _($,W){return new _1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),distinct:{on:$}})}return{select:X,selectDistinct:G,selectDistinctOn:_}}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 c4(this.dialectConfig);return this.dialect}}function m1(Y){if(M(Y,u0))return[Y[y4]?`${Y[y4]}.${Y[P.Symbol.BaseName]}`:Y[P.Symbol.BaseName]];if(M(Y,S0))return Y._.usedTables??[];if(M(Y,f))return Y.usedTables??[];return[]}class $Y extends G1{constructor(Y,Z,X,G){super();this.session=Z,this.dialect=X,this.config={table:Y,withList:G}}static[E]="PgDelete";config;cacheConfig;where(Y){return this.config.where=Y,this}returning(Y=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=T1(Y),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"delete",tables:m1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return E0.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 WY{constructor(Y,Z,X,G,_){this.table=Y,this.session=Z,this.dialect=X,this.withList=G,this.overridingSystemValue_=_}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 Error("values() must be called with at least one value");let Z=Y.map((X)=>{let G={},_=this.table[P.Symbol.Columns];for(let $ of Object.keys(X)){let W=X[$];G[$]=M(W,f)?W:new A1(W,_[$])}return G});return new r5(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,f)&&!w8(this.table[S6],Z._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new r5(this.table,Z,this.session,this.dialect,this.withList,!0)}}class r5 extends G1{constructor(Y,Z,X,G,_,$,W){super();this.session=X,this.dialect=G,this.config={table:Y,values:Z,withList:_,select:$,overridingSystemValue_:W}}static[E]="PgInsert";config;cacheConfig;returning(Y=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=T1(Y),this}onConflictDoNothing(Y={}){if(Y.target===void 0)this.config.onConflict=V`do nothing`;else{let Z="";Z=Array.isArray(Y.target)?Y.target.map((G)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(G))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target));let X=Y.where?V` where ${Y.where}`:void 0;this.config.onConflict=V`(${V.raw(Z)})${X} do nothing`}return this}onConflictDoUpdate(Y){if(Y.where&&(Y.targetWhere||Y.setWhere))throw 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?V` where ${Y.where}`:void 0,X=Y.targetWhere?V` where ${Y.targetWhere}`:void 0,G=Y.setWhere?V` where ${Y.setWhere}`:void 0,_=this.dialect.buildUpdateSet(this.config.table,h6(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=V`(${V.raw($)})${X} do update set ${_}${Z}${G}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:m1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return E0.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 s5 extends G1{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 Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw 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 E0.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 E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}class HY{constructor(Y,Z,X,G){this.table=Y,this.session=Z,this.dialect=X,this.withList=G}static[E]="PgUpdateBuilder";authToken;setToken(Y){return this.authToken=Y,this}set(Y){return new pW(this.table,h6(this.table,Y),this.session,this.dialect,this.withList).setToken(this.authToken)}}class pW extends G1{constructor(Y,Z,X,G,_){super();this.session=X,this.dialect=G,this.config={set:Z,table:Y,withList:_,joins:[]},this.tableName=J4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[E]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(Y){let Z=Y,X=J4(Z);if(typeof X==="string")this.joinsNotNullableMap[X]=!0;return this.config.from=Z,this}getTableLikeFields(Y){if(M(Y,u0))return Y[P.Symbol.Columns];else if(M(Y,S0))return Y._.selectedFields;return Y[M0].selectedFields}createJoin(Y){return(Z,X)=>{let G=J4(Z);if(typeof G==="string"&&this.config.joins.some((_)=>_.alias===G))throw Error(`Alias "${G}" is already used in this query`);if(typeof X==="function"){let _=this.config.from&&!M(this.config.from,f)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[P.Symbol.Columns],new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),_&&new Proxy(_,new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:X,table:Z,joinType:Y,alias:G}),typeof G==="string")switch(Y){case"left":{this.joinsNotNullableMap[G]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([_])=>[_,!1])),this.joinsNotNullableMap[G]=!0;break}case"inner":{this.joinsNotNullableMap[G]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([_])=>[_,!1])),this.joinsNotNullableMap[G]=!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[P.Symbol.Columns]),this.config.from){let Z=J4(this.config.from);if(typeof Z==="string"&&this.config.from&&!M(this.config.from,f)){let X=this.getTableLikeFields(this.config.from);Y[Z]=X}for(let X of this.config.joins){let G=J4(X.table);if(typeof G==="string"&&!M(X.table,f)){let _=this.getTableLikeFields(X.table);Y[G]=_}}}}return this.config.returningFields=Y,this.config.returning=T1(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:m1(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 f8 extends f{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 V`(select count(*) from ${Y}${V.raw(" where ").if(Z)}${Z})`}static buildCount(Y,Z){return V`select count(*) as count from ${Y}${V.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 a5{constructor(Y,Z,X,G,_,$,W){this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=G,this.tableConfig=_,this.dialect=$,this.session=W}static[E]="PgRelationalQueryBuilder";findMany(Y){return new t5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?Y:{},"many")}findFirst(Y){return new t5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?{...Y,limit:1}:{limit:1},"first")}}class t5 extends G1{constructor(Y,Z,X,G,_,$,W,H,Q){super();this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=G,this.tableConfig=_,this.dialect=$,this.session=W,this.config=H,this.mode=Q}static[E]="PgRelationalQuery";_prepare(Y){return E0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Z,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,Y,!0,(G,_)=>{let $=G.map((W)=>o6(this.schema,this.tableConfig,W,Z.selection,_));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 E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class e5 extends G1{constructor(Y,Z,X,G){super();this.execute=Y,this.sql=Z,this.query=X,this.mapBatchResult=G}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[G]=new a5(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[G],_,Y,Z);this.$cache={invalidate:async(G)=>{}}}static[E]="PgDatabase";query;$with=(Y,Z)=>{let X=this;return{as:(_)=>{if(typeof _==="function")_=_(new x8(X.dialect));return new Proxy(new L8(_.getSQL(),Z??("getSelectedFields"in _?_.getSelectedFields()??{}:{}),Y,!0),new q0({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 _1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y})}function G(Q){return new _1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:!0})}function _(Q,J){return new _1({fields:J??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:{on:Q}})}function $(Q){return new HY(Q,Z.session,Z.dialect,Y)}function W(Q){return new WY(Q,Z.session,Z.dialect,Y)}function H(Q){return new $Y(Q,Z.session,Z.dialect,Y)}return{select:X,selectDistinct:G,selectDistinctOn:_,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 HY(Y,this.session,this.dialect)}insert(Y){return new WY(Y,this.session,this.dialect)}delete(Y){return new $Y(Y,this.session,this.dialect)}refreshMaterializedView(Y){return new s5(Y,this.session,this.dialect)}authToken;execute(Y){let Z=typeof Y==="string"?V.raw(Y):Y.getSQL(),X=this.dialect.sqlToQuery(Z),G=this.session.prepareQuery(X,void 0,void 0,!1);return new e5(()=>G.execute(void 0,this.authToken),Z,X,(_)=>G.mapResult(_,!0))}transaction(Y,Z){return this.session.transaction(Y,Z)}}class mW{static[E]="Cache"}class k8 extends mW{strategy(){return"all"}static[E]="NoopCache";async get(Y){return}async put(Y,Z,X,G){}async onMutate(Y){}}async function YX(Y,Z){let X=`${Y}-${JSON.stringify(Z)}`,_=new TextEncoder().encode(X),$=await crypto.subtle.digest("SHA-256",_);return[...new Uint8Array($)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}class ZX{constructor(Y,Z,X,G){if(this.query=Y,this.cache=Z,this.queryMetadata=X,this.cacheConfig=G,Z&&Z.strategy()==="all"&&G===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(G){throw new H4(Y,Z,G)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await X()}catch(G){throw new H4(Y,Z,G)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[G]=await Promise.all([X(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return G}catch(G){throw new H4(Y,Z,G)}if(!this.cacheConfig)try{return await X()}catch(G){throw new H4(Y,Z,G)}if(this.queryMetadata.type==="select"){let G=await this.cache.get(this.cacheConfig.tag??await YX(Y,Z),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(G===void 0){let _;try{_=await X()}catch($){throw new H4(Y,Z,$)}return await this.cache.put(this.cacheConfig.tag??await YX(Y,Z),_,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),_}return G}try{return await X()}catch(G){throw new H4(Y,Z,G)}}}class XX{constructor(Y){this.dialect=Y}static[E]="PgSession";execute(Y,Z){return E0.startActiveSpan("drizzle.operation",()=>{return E0.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 GX extends h8{constructor(Y,Z,X,G=0){super(Y,Z,X);this.schema=X,this.nestedIndex=G}static[E]="PgTransaction";rollback(){throw new w5}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 V.raw(Z.join(" "))}setTransaction(Y){return this.session.execute(V`set transaction ${this.getTransactionConfigSQL(Y)}`)}}class uW extends ZX{constructor(Y,Z,X,G,_,$,W,H,Q,J){super({sql:Z,params:X},_,$,W);this.client=Y,this.queryString=Z,this.params=X,this.logger=G,this.fields=H,this._isResponseInArrayMode=Q,this.customResultMapper=J}static[E]="PostgresJsPreparedQuery";async execute(Y={}){return E0.startActiveSpan("drizzle.execute",async(Z)=>{let X=A5(this.params,Y);Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X);let{fields:G,queryString:_,client:$,joinsNotNullableMap:W,customResultMapper:H}=this;if(!G&&!H)return E0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(_,X,async()=>{return await $.unsafe(_,X)})});let Q=await E0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":_,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(_,X,async()=>{return await $.unsafe(_,X).values()})});return E0.startActiveSpan("drizzle.mapResponse",()=>{return H?H(Q):Q.map((J)=>u7(G,J,W))})})}all(Y={}){return E0.startActiveSpan("drizzle.execute",async(Z)=>{let X=A5(this.params,Y);return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),E0.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 XX{constructor(Y,Z,X,G={}){super(Z);this.client=Y,this.schema=X,this.options=G,this.logger=G.logger??new I5,this.cache=G.cache??new k8}static[E]="PostgresJsSession";logger;cache;prepareQuery(Y,Z,X,G,_,$,W){return new uW(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 G=new b8(X,this.dialect,this.schema,this.options),_=new _X(this.dialect,G,this.schema);if(Z)await _.setTransaction(Z);return Y(_)})}}class _X extends GX{constructor(Y,Z,X,G=0){super(Y,Z,X,G);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),G=new _X(this.dialect,X,this.schema);return Y(G)})}}class dW extends h8{static[E]="PostgresJsDatabase"}function K2(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 G=new c4({casing:Z.casing}),_;if(Z.logger===!0)_=new N5;else if(Z.logger!==!1)_=Z.logger;let $;if(Z.schema){let Q=VW(Z.schema,DW);$={fullSchema:Z.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let W=new b8(Y,G,$,{logger:_,cache:Z.cache}),H=new dW(G,W,$);if(H.$client=Y,H.$cache=Z.cache,H.$cache)H.$cache.invalidate=Z.cache?.onMutate;return H}function JY(...Y){if(typeof Y[0]==="string"){let Z=N2(Y[0]);return K2(Z,Y[1])}if(l7(Y[0])){let{connection:Z,client:X,...G}=Y[0];if(X)return K2(X,G);if(typeof Z==="object"&&Z.url!==void 0){let{url:$,...W}=Z,H=N2($,W);return K2(H,G)}let _=N2(Z);return K2(_,G)}return K2(Y[0],Y[1])}((Y)=>{function Z(X){return K2({options:{parsers:{},serializers:{}}},X)}Y.mock=Z})(JY||(JY={}));var WX={};nH(WX,{users:()=>l4,untrackedUserColumnNames:()=>bE,twoFactorMethod:()=>nW,trackedUserColumnName:()=>yE,trackableUserColumnNames:()=>oW,signInHistory:()=>pE,role:()=>lW,players:()=>$X,passwordResetAttempts:()=>mE,games:()=>zY,banishedIps:()=>uE,accountActions:()=>gE,accountAction:()=>iW});function T4(){return t0({length:24}).$type()}function cW(Y){return V`lower(${Y})`}var QY=V`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,lW=D8("role",["admin","user"]),l4=I4("users",{id:C1().primaryKey().defaultRandom(),username:t0({length:16}).notNull(),emailOffered:t0({length:254}).notNull(),emailVerified:t0({length:254}),password:t0({length:254}),createdAtIso:T4().notNull().default(QY),createdIp:t0({length:45}).notNull(),isActive:N8().notNull().default(!1),verifiedAtIso:T4(),userRole:lW().default("user")},(Y)=>[l5("usernameUniqueIndex").on(cW(Y.username)),l5("emailVerifiedUniqueIndex").on(cW(Y.emailVerified))]),bE=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],oW=["username","emailOffered","emailVerified","password","userRole"],yE=D8("trackedUserColumnName",oW),iW=D8("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),gE=I4("accountActions",{userId:C1().references(()=>l4.id).primaryKey(),action:iW().notNull(),code:t0({length:254}).notNull(),wrongCodeCount:I8().notNull().default(0),expiresAtIso:T4().notNull()}),zY=I4("games",{id:C1().primaryKey().defaultRandom()}),$X=I4("players",{userId:C1().notNull().references(()=>l4.id,{onDelete:"cascade"}),gameId:C1().notNull().references(()=>zY.id,{onDelete:"cascade"}),score:I8().notNull()},(Y)=>[u3({name:"players_userId_gameId_pk",columns:[Y.userId,Y.gameId]})]),pE=I4("signInHistory",{id:C1().primaryKey().defaultRandom(),userId:C1().references(()=>l4.id,{onDelete:"cascade"}),signInTimeIso:T4().notNull().default(QY),ipAddress:t0({length:45}).notNull(),userAgent:t0({length:1024}),successful:N8().notNull().default(!1)}),nW=D8("twoFactorMethod",["email","phone"]),mE=I4("passwordResetAttempts",{id:C1().primaryKey().defaultRandom(),userId:C1().notNull().references(()=>l4.id,{onDelete:"cascade"}),requestedIp:t0({length:45}).notNull(),requestedAtIso:T4().notNull().default(QY),succeededIp:t0({length:45}),succeededAtIso:T4(),verificationMethod:nW().notNull()}),uE=I4("banishedIps",{ip:t0({length:45}).primaryKey(),reason:t0({length:2048}).notNull(),banishedAtIso:T4().notNull().default(QY),banishedUntilIso:T4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class HX{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(dE.resolve(__dirname,"notify_update.sql"));let Y=[d0(l4),d0(zY),d0($X)];await this.sql`SELECT create_notify_triggers(${this.sql.array(Y)})`,await this.sql.listen("table_update",(Z)=>{let X=Z.split(","),G=X[0],_=X[1],$=`${G}("${_}")`;if(this.observers.has($))this.observers.get($).next($)})}constructor(Y=!1,Z={host:g1.POSTGRES_HOST,port:g1.POSTGRES_PORT,user:g1.POSTGRES_USER,password:g1.POSTGRES_PASSWORD,database:g1.POSTGRES_DATABASE}){this.options=Z,this.sql=N2(Z),this.drizzle=JY(this.sql,{schema:WX,logger:Y})}observe(Y,Z){if(!this.observers.has(Y))this.observers.set(Y,new _0);this.observers.get(Y).subscribe("SINGLETON",Z)}}var FY={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 cE(Y){return Number.parseInt(Y,10)}var lE=F1(FY),oE=lE.keyof().pipe((Y)=>cE(Y)),rW=F1([oE,"string"]);var QX=new M7(process),{logger:D1}=QX;Object.assign(console,D1,{log:D1.info});D1.info("ready");var JX=tW(import.meta.dir,"..","app"),Lf=new HX({logQuery(Y,Z){D1.info("\uD83D\uDCDD query",Y,Z)}});sE({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...q6??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(tW(JX,"index.html")));if(X.pathname==="/index.html")return Response.redirect("/");let G=nE(JX,X.pathname),_=rE(G);if(!_.startsWith(JX))throw[403,"Access Denied"];if(!await sW(_).exists())return Response.redirect("/");return new Response(sW(_))}catch(Z){let X=rW(Z);if(X instanceof F1.errors===!1){let[G,_]=X,W=`${FY[G]}. ${_}`;return D1.info(`\u274C ${G}: ${W}`),new Response(W,{status:G})}if(Z instanceof Error)D1.error(Z.message);else{let G=C6(Z);D1.error("frontend server threw",G)}return new Response(FY[500],{status:500})}}});function UY(){D1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{D1.info("\u2757 received SIGINT; exiting gracefully"),UY()});process.on("SIGTERM",()=>{D1.info("\u2757 received SIGTERM; exiting gracefully"),UY()});process.on("exit",()=>{D1.info("\u2757 received exit; exiting gracefully"),UY()});QX.on("timeToStop",()=>{D1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),UY()});var{version:tE}=await Bun.file(iE.resolve(import.meta.dir,"../package.json")).json();D1.info(`\uD83D\uDEEB frontend v${tE} running at http://localhost:${g1.FRONTEND_PORT}/`);QX.emit("alive");
93
+ `;await Y.execute(V`CREATE SCHEMA IF NOT EXISTS ${V.identifier(G)}`),await Y.execute(W);let H=(await Y.all(V`select id, hash, created_at from ${V.identifier(G)}.${V.identifier(_)} order by created_at desc limit 1`))[0];await Y.transaction(async(Q)=>{for await(let J of X)if(!H||Number(H.created_at)<J.folderMillis){for(let z of J.sql)await Q.execute(V.raw(z));await Q.execute(V`insert into ${V.identifier(G)}.${V.identifier(_)} ("hash", "created_at") values(${J.hash}, ${J.folderMillis})`)}})}escapeName(X){return`"${X}"`}escapeParam(X){return`$${X+1}`}escapeString(X){return`'${X.replace(/'/g,"''")}'`}buildWithCTE(X){if(!X?.length)return;let Y=[V`with `];for(let[Z,_]of X.entries())if(Y.push(V`${V.identifier(_._.alias)} as (${_._.sql})`),Z<X.length-1)Y.push(V`, `);return Y.push(V` `),V.join(Y)}buildDeleteQuery({table:X,where:Y,returning:Z,withList:_}){let G=this.buildWithCTE(_),W=Z?V` returning ${this.buildSelection(Z,{isSingleTable:!0})}`:void 0,$=Y?V` where ${Y}`:void 0;return V`${G}delete from ${X}${$}${W}`}buildUpdateSet(X,Y){let Z=X[T.Symbol.Columns],_=Object.keys(Z).filter((W)=>Y[W]!==void 0||Z[W]?.onUpdateFn!==void 0),G=_.length;return V.join(_.flatMap((W,$)=>{let H=Z[W],Q=Y[W]??V.param(H.onUpdateFn(),H),J=V`${V.identifier(this.casing.getColumnCasing(H))} = ${Q}`;if($<G-1)return[J,V.raw(", ")];return[J]}))}buildUpdateQuery({table:X,set:Y,where:Z,returning:_,withList:G,from:W,joins:$}){let H=this.buildWithCTE(G),Q=X[b0.Symbol.Name],J=X[b0.Symbol.Schema],z=X[b0.Symbol.OriginalName],F=Q===z?void 0:Q,O=V`${J?V`${V.identifier(J)}.`:void 0}${V.identifier(z)}${F&&V` ${V.identifier(F)}`}`,D=this.buildUpdateSet(X,Y),w=W&&V.join([V.raw(" from "),this.buildFromTable(W)]),A=this.buildJoins($),x=_?V` returning ${this.buildSelection(_,{isSingleTable:!W})}`:void 0,j=Z?V` where ${Z}`:void 0;return V`${H}update ${O} set ${D}${w}${A}${j}${x}`}buildSelection(X,{isSingleTable:Y=!1}={}){let Z=X.length,_=X.flatMap(({field:G},W)=>{let $=[];if(M(G,S.Aliased)&&G.isSelectionField)$.push(V.identifier(G.fieldAlias));else if(M(G,S.Aliased)||M(G,S)){let H=M(G,S.Aliased)?G.sql:G;if(Y)$.push(new S(H.queryChunks.map((Q)=>{if(M(Q,B))return V.identifier(this.casing.getColumnCasing(Q));return Q})));else $.push(H);if(M(G,S.Aliased))$.push(V` as ${V.identifier(G.fieldAlias)}`)}else if(M(G,z0))if(Y)$.push(V.identifier(this.casing.getColumnCasing(G)));else $.push(G);if(W<Z-1)$.push(V`, `);return $});return V.join(_)}buildJoins(X){if(!X||X.length===0)return;let Y=[];for(let[Z,_]of X.entries()){if(Z===0)Y.push(V` `);let G=_.table,W=_.lateral?V` lateral`:void 0,$=_.on?V` on ${_.on}`:void 0;if(M(G,b0)){let H=G[b0.Symbol.Name],Q=G[b0.Symbol.Schema],J=G[b0.Symbol.OriginalName],z=H===J?void 0:_.alias;Y.push(V`${V.raw(_.joinType)} join${W} ${Q?V`${V.identifier(Q)}.`:void 0}${V.identifier(J)}${z&&V` ${V.identifier(z)}`}${$}`)}else if(M(G,F1)){let H=G[V0].name,Q=G[V0].schema,J=G[V0].originalName,z=H===J?void 0:_.alias;Y.push(V`${V.raw(_.joinType)} join${W} ${Q?V`${V.identifier(Q)}.`:void 0}${V.identifier(J)}${z&&V` ${V.identifier(z)}`}${$}`)}else Y.push(V`${V.raw(_.joinType)} join${W} ${G}${$}`);if(Z<X.length-1)Y.push(V` `)}return V.join(Y)}buildFromTable(X){if(M(X,T)&&X[T.Symbol.IsAlias]){let Y=V`${V.identifier(X[T.Symbol.OriginalName])}`;if(X[T.Symbol.Schema])Y=V`${V.identifier(X[T.Symbol.Schema])}.${Y}`;return V`${Y} ${V.identifier(X[T.Symbol.Name])}`}return X}buildSelectQuery({withList:X,fields:Y,fieldsFlat:Z,where:_,having:G,table:W,joins:$,orderBy:H,groupBy:Q,limit:J,offset:z,lockingClause:F,distinct:O,setOperators:D}){let w=Z??B1(Y);for(let X0 of w)if(M(X0.field,z0)&&g0(X0.field.table)!==(M(W,C0)?W._.alias:M(W,v2)?W[V0].name:M(W,S)?void 0:g0(W))&&!((p0)=>$?.some(({alias:O1})=>O1===(p0[T.Symbol.IsAlias]?g0(p0):p0[T.Symbol.BaseName])))(X0.field.table)){let p0=g0(X0.field.table);throw Error(`Your "${X0.path.join("->")}" field references a column "${p0}"."${X0.field.name}", but the table "${p0}" is not part of the query! Did you forget to join it?`)}let A=!$||$.length===0,x=this.buildWithCTE(X),j;if(O)j=O===!0?V` distinct`:V` distinct on (${V.join(O.on,V`, `)})`;let P=this.buildSelection(w,{isSingleTable:A}),h=this.buildFromTable(W),i=this.buildJoins($),p=_?V` where ${_}`:void 0,y=G?V` having ${G}`:void 0,m;if(H&&H.length>0)m=V` order by ${V.join(H,V`, `)}`;let _0;if(Q&&Q.length>0)_0=V` group by ${V.join(Q,V`, `)}`;let y0=typeof J==="object"||typeof J==="number"&&J>=0?V` limit ${J}`:void 0,K=z?V` offset ${z}`:void 0,W0=V.empty();if(F){let X0=V` for ${V.raw(F.strength)}`;if(F.config.of)X0.append(V` of ${V.join(Array.isArray(F.config.of)?F.config.of:[F.config.of],V`, `)}`);if(F.config.noWait)X0.append(V` nowait`);else if(F.config.skipLocked)X0.append(V` skip locked`);W0.append(X0)}let o=V`${x}select${j} ${P} from ${h}${i}${p}${_0}${y}${m}${y0}${K}${W0}`;if(D.length>0)return this.buildSetOperations(o,D);return o}buildSetOperations(X,Y){let[Z,..._]=Y;if(!Z)throw Error("Cannot pass undefined values to any set operator");if(_.length===0)return this.buildSetOperationQuery({leftSelect:X,setOperator:Z});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:X,setOperator:Z}),_)}buildSetOperationQuery({leftSelect:X,setOperator:{type:Y,isAll:Z,rightSelect:_,limit:G,orderBy:W,offset:$}}){let H=V`(${X.getSQL()}) `,Q=V`(${_.getSQL()})`,J;if(W&&W.length>0){let D=[];for(let w of W)if(M(w,B))D.push(V.identifier(w.name));else if(M(w,S)){for(let A=0;A<w.queryChunks.length;A++){let x=w.queryChunks[A];if(M(x,B))w.queryChunks[A]=V.identifier(x.name)}D.push(V`${w}`)}else D.push(V`${w}`);J=V` order by ${V.join(D,V`, `)} `}let z=typeof G==="object"||typeof G==="number"&&G>=0?V` limit ${G}`:void 0,F=V.raw(`${Y} ${Z?"all ":""}`),O=$?V` offset ${$}`:void 0;return V`${H}${F}${Q}${J}${z}${O}`}buildInsertQuery({table:X,values:Y,onConflict:Z,returning:_,withList:G,select:W,overridingSystemValue_:$}){let H=[],Q=X[T.Symbol.Columns],J=Object.entries(Q).filter(([x,j])=>!j.shouldDisableInsert()),z=J.map(([,x])=>V.identifier(this.casing.getColumnCasing(x)));if(W){let x=Y;if(M(x,S))H.push(x);else H.push(x.getSQL())}else{let x=Y;H.push(V.raw("values "));for(let[j,P]of x.entries()){let h=[];for(let[i,p]of J){let y=P[i];if(y===void 0||M(y,L1)&&y.value===void 0)if(p.defaultFn!==void 0){let m=p.defaultFn(),_0=M(m,S)?m:V.param(m,p);h.push(_0)}else if(!p.default&&p.onUpdateFn!==void 0){let m=p.onUpdateFn(),_0=M(m,S)?m:V.param(m,p);h.push(_0)}else h.push(V`default`);else h.push(y)}if(H.push(h),j<x.length-1)H.push(V`, `)}}let F=this.buildWithCTE(G),O=V.join(H),D=_?V` returning ${this.buildSelection(_,{isSingleTable:!0})}`:void 0,w=Z?V` on conflict ${Z}`:void 0,A=$===!0?V`overriding system value `:void 0;return V`${F}insert into ${X} ${z} ${A}${O}${w}${D}`}buildRefreshMaterializedViewQuery({view:X,concurrently:Y,withNoData:Z}){let _=Y?V` concurrently`:void 0,G=Z?V` with no data`:void 0;return V`refresh materialized view${_} ${X}${G}`}prepareTyping(X){if(M(X,g6)||M(X,y6))return"json";else if(M(X,p6))return"decimal";else if(M(X,m6))return"time";else if(M(X,u6)||M(X,d6))return"timestamp";else if(M(X,k6)||M(X,b6))return"date";else if(M(X,c6))return"uuid";else return"none"}sqlToQuery(X,Y){return X.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:Y})}buildRelationalQueryWithoutPK({fullSchema:X,schema:Y,tableNamesMap:Z,table:_,tableConfig:G,queryConfig:W,tableAlias:$,nestedQueryRelation:H,joinOn:Q}){let J=[],z,F,O=[],D,w=[];if(W===!0)J=Object.entries(G.columns).map(([j,P])=>({dbKey:P.name,tsKey:j,field:i1(P,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let x=Object.fromEntries(Object.entries(G.columns).map(([y,m])=>[y,i1(m,$)]));if(W.where){let y=typeof W.where==="function"?W.where(x,Q$()):W.where;D=y&&R2(y,$)}let j=[],P=[];if(W.columns){let y=!1;for(let[m,_0]of Object.entries(W.columns)){if(_0===void 0)continue;if(m in G.columns){if(!y&&_0===!0)y=!0;P.push(m)}}if(P.length>0)P=y?P.filter((m)=>W.columns?.[m]===!0):Object.keys(G.columns).filter((m)=>!P.includes(m))}else P=Object.keys(G.columns);for(let y of P){let m=G.columns[y];j.push({tsKey:y,value:m})}let h=[];if(W.with)h=Object.entries(W.with).filter((y)=>!!y[1]).map(([y,m])=>({tsKey:y,queryConfig:m,relation:G.relations[y]}));let i;if(W.extras){i=typeof W.extras==="function"?W.extras(x,{sql:V}):W.extras;for(let[y,m]of Object.entries(i))j.push({tsKey:y,value:wZ(m,$)})}for(let{tsKey:y,value:m}of j)J.push({dbKey:M(m,S.Aliased)?m.fieldAlias:G.columns[y].name,tsKey:y,field:M(m,z0)?i1(m,$):m,relationTableTsKey:void 0,isJson:!1,selection:[]});let p=typeof W.orderBy==="function"?W.orderBy(x,z$()):W.orderBy??[];if(!Array.isArray(p))p=[p];O=p.map((y)=>{if(M(y,z0))return i1(y,$);return R2(y,$)}),z=W.limit,F=W.offset;for(let{tsKey:y,queryConfig:m,relation:_0}of h){let y0=U$(Y,Z,_0),K=b4(_0.referencedTable),W0=Z[K],o=`${$}_${y}`,X0=B2(...y0.fields.map((q1,c4)=>l6(i1(y0.references[c4],o),i1(q1,$)))),p0=this.buildRelationalQueryWithoutPK({fullSchema:X,schema:Y,tableNamesMap:Z,table:X[W0],tableConfig:Y[W0],queryConfig:M(_0,K4)?m===!0?{limit:1}:{...m,limit:1}:m,tableAlias:o,joinOn:X0,nestedQueryRelation:_0}),O1=V`${V.identifier(o)}.${V.identifier("data")}`.as(y);w.push({on:V`true`,table:new C0(p0.sql,{},o),alias:o,joinType:"left",lateral:!0}),J.push({dbKey:y,tsKey:y,field:O1,relationTableTsKey:W0,isJson:!0,selection:p0.selection})}}if(J.length===0)throw new f6({message:`No fields selected for table "${G.tsName}" ("${$}")`});let A;if(D=B2(Q,D),H){let x=V`json_build_array(${V.join(J.map(({field:h,tsKey:i,isJson:p})=>p?V`${V.identifier(`${$}_${i}`)}.${V.identifier("data")}`:M(h,S.Aliased)?h.sql:h),V`, `)})`;if(M(H,T2))x=V`coalesce(json_agg(${x}${O.length>0?V` order by ${V.join(O,V`, `)}`:void 0}), '[]'::json)`;let j=[{dbKey:"data",tsKey:"data",field:x.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:J}];if(z!==void 0||F!==void 0||O.length>0)A=this.buildSelectQuery({table:x6(_,$),fields:{},fieldsFlat:[{path:[],field:V.raw("*")}],where:D,limit:z,offset:F,orderBy:O,setOperators:[]}),D=void 0,z=void 0,F=void 0,O=[];else A=x6(_,$);A=this.buildSelectQuery({table:M(A,b0)?A:new C0(A,{},$),fields:{},fieldsFlat:j.map(({field:h})=>({path:[],field:M(h,z0)?i1(h,$):h})),joins:w,where:D,limit:z,offset:F,orderBy:O,setOperators:[]})}else A=this.buildSelectQuery({table:x6(_,$),fields:{},fieldsFlat:J.map(({field:x})=>({path:[],field:M(x,z0)?i1(x,$):x})),joins:w,where:D,limit:z,offset:F,orderBy:O,setOperators:[]});return{tableTsKey:G.tsName,sql:A,selection:J}}}class nZ{static[E]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Z1{static[E]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(X){if(this.fields=X.fields,this.session=X.session,this.dialect=X.dialect,X.withList)this.withList=X.withList;this.distinct=X.distinct}authToken;setToken(X){return this.authToken=X,this}from(X){let Y=!!this.fields,Z=X,_;if(this.fields)_=this.fields;else if(M(Z,C0))_=Object.fromEntries(Object.keys(Z._.selectedFields).map((G)=>[G,Z[G]]));else if(M(Z,v2))_=Z[V0].selectedFields;else if(M(Z,S))_={};else _=m7(Z);return new rZ({table:Z,fields:_,isPartialSelect:Y,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class k$ extends nZ{static[E]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:X,fields:Y,isPartialSelect:Z,session:_,dialect:G,withList:W,distinct:$}){super();this.config={withList:W,table:X,fields:{...Y},distinct:$,setOperators:[]},this.isPartialSelect=Z,this.session=_,this.dialect=G,this._={selectedFields:Y,config:this.config},this.tableName=J4(X),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let H of m1(X))this.usedTables.add(H)}getUsedTables(){return[...this.usedTables]}createJoin(X,Y){return(Z,_)=>{let G=this.tableName,W=J4(Z);for(let $ of m1(Z))this.usedTables.add($);if(typeof W==="string"&&this.config.joins?.some(($)=>$.alias===W))throw Error(`Alias "${W}" 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 W==="string"&&!M(Z,S)){let $=M(Z,C0)?Z._.selectedFields:M(Z,F1)?Z[V0].selectedFields:Z[T.Symbol.Columns];this.config.fields[W]=$}}if(typeof _==="function")_=_(new Proxy(this.config.fields,new B0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:_,table:Z,joinType:X,alias:W,lateral:Y}),typeof W==="string")switch(X){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[W]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[W]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[W]=!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(X,Y){return(Z)=>{let _=typeof Z==="function"?Z(TE()):Z;if(!w2(this.getSelectedFields(),_.getSelectedFields()))throw 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:X,isAll:Y,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(X){return this.config.setOperators.push(...X),this}where(X){if(typeof X==="function")X=X(new Proxy(this.config.fields,new B0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=X,this}having(X){if(typeof X==="function")X=X(new Proxy(this.config.fields,new B0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=X,this}groupBy(...X){if(typeof X[0]==="function"){let Y=X[0](new Proxy(this.config.fields,new B0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(Y)?Y:[Y]}else this.config.groupBy=X;return this}orderBy(...X){if(typeof X[0]==="function"){let Y=X[0](new Proxy(this.config.fields,new B0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),Z=Array.isArray(Y)?Y:[Y];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Z;else this.config.orderBy=Z}else{let Y=X;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Y;else this.config.orderBy=Y}return this}limit(X){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=X;else this.config.limit=X;return this}offset(X){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=X;else this.config.offset=X;return this}for(X,Y={}){return this.config.lockingClause={strength:X,config:Y},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:X,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}as(X){let Y=[];if(Y.push(...m1(this.config.table)),this.config.joins)for(let Z of this.config.joins)Y.push(...m1(Z.table));return new Proxy(new C0(this.getSQL(),this.config.fields,X,!1,[...new Set(Y)]),new B0({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new B0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(X){return this.cacheConfig=X===void 0?{config:{},enable:!0,autoInvalidate:!0}:X===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...X},this}}class rZ extends k${static[E]="PgSelect";_prepare(X){let{session:Y,config:Z,dialect:_,joinsNotNullableMap:G,authToken:W,cacheConfig:$,usedTables:H}=this;if(!Y)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:Q}=Z;return F0.startActiveSpan("drizzle.prepareQuery",()=>{let J=B1(Q),z=Y.prepareQuery(_.sqlToQuery(this.getSQL()),J,X,!0,void 0,{type:"select",tables:[...H]},$);return z.joinsNotNullableMap=G,z.setToken(W)})}prepare(X){return this._prepare(X)}authToken;setToken(X){return this.authToken=X,this}execute=(X)=>{return F0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(X,this.authToken)})}}p7(rZ,[Y1]);function N8(X,Y){return(Z,_,...G)=>{let W=[_,...G].map(($)=>({type:X,isAll:Y,rightSelect:$}));for(let $ of W)if(!w2(Z.getSelectedFields(),$.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return Z.addSetOperators(W)}}var TE=()=>({union:CE,unionAll:qE,intersect:jE,intersectAll:SE,except:PE,exceptAll:vE}),CE=N8("union",!1),qE=N8("union",!0),jE=N8("intersect",!1),SE=N8("intersect",!0),PE=N8("except",!1),vE=N8("except",!0);class x2{static[E]="PgQueryBuilder";dialect;dialectConfig;constructor(X){this.dialect=M(X,u4)?X:void 0,this.dialectConfig=M(X,u4)?void 0:X}$with=(X,Y)=>{let Z=this;return{as:(G)=>{if(typeof G==="function")G=G(Z);return new Proxy(new L2(G.getSQL(),Y??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),X,!0),new B0({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...X){let Y=this;function Z(W){return new Z1({fields:W??void 0,session:void 0,dialect:Y.getDialect(),withList:X})}function _(W){return new Z1({fields:W??void 0,session:void 0,dialect:Y.getDialect(),distinct:!0})}function G(W,$){return new Z1({fields:$??void 0,session:void 0,dialect:Y.getDialect(),distinct:{on:W}})}return{select:Z,selectDistinct:_,selectDistinctOn:G}}select(X){return new Z1({fields:X??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(X){return new Z1({fields:X??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(X,Y){return new Z1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:X}})}getDialect(){if(!this.dialect)this.dialect=new u4(this.dialectConfig);return this.dialect}}function m1(X){if(M(X,b0))return[X[k4]?`${X[k4]}.${X[T.Symbol.BaseName]}`:X[T.Symbol.BaseName]];if(M(X,C0))return X._.usedTables??[];if(M(X,S))return X.usedTables??[];return[]}class WX extends Y1{constructor(X,Y,Z,_){super();this.session=Y,this.dialect=Z,this.config={table:X,withList:_}}static[E]="PgDelete";config;cacheConfig;where(X){return this.config.where=X,this}returning(X=this.config.table[T.Symbol.Columns]){return this.config.returningFields=X,this.config.returning=B1(X),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:X,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(X){return F0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,X,!0,void 0,{type:"delete",tables:m1(this.config.table)},this.cacheConfig)})}prepare(X){return this._prepare(X)}authToken;setToken(X){return this.authToken=X,this}execute=(X)=>{return F0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(X,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new B0({alias:g0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class $X{constructor(X,Y,Z,_,G){this.table=X,this.session=Y,this.dialect=Z,this.withList=_,this.overridingSystemValue_=G}static[E]="PgInsertBuilder";authToken;setToken(X){return this.authToken=X,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(X){if(X=Array.isArray(X)?X:[X],X.length===0)throw Error("values() must be called with at least one value");let Y=X.map((Z)=>{let _={},G=this.table[T.Symbol.Columns];for(let W of Object.keys(Z)){let $=Z[W];_[W]=M($,S)?$:new L1($,G[W])}return _});return new sZ(this.table,Y,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(X){let Y=typeof X==="function"?X(new x2):X;if(!M(Y,S)&&!w2(this.table[P6],Y._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new sZ(this.table,Y,this.session,this.dialect,this.withList,!0)}}class sZ extends Y1{constructor(X,Y,Z,_,G,W,$){super();this.session=Z,this.dialect=_,this.config={table:X,values:Y,withList:G,select:W,overridingSystemValue_:$}}static[E]="PgInsert";config;cacheConfig;returning(X=this.config.table[T.Symbol.Columns]){return this.config.returningFields=X,this.config.returning=B1(X),this}onConflictDoNothing(X={}){if(X.target===void 0)this.config.onConflict=V`do nothing`;else{let Y="";Y=Array.isArray(X.target)?X.target.map((_)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(_))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(X.target));let Z=X.where?V` where ${X.where}`:void 0;this.config.onConflict=V`(${V.raw(Y)})${Z} do nothing`}return this}onConflictDoUpdate(X){if(X.where&&(X.targetWhere||X.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let Y=X.where?V` where ${X.where}`:void 0,Z=X.targetWhere?V` where ${X.targetWhere}`:void 0,_=X.setWhere?V` where ${X.setWhere}`:void 0,G=this.dialect.buildUpdateSet(this.config.table,h6(this.config.table,X.set)),W="";return W=Array.isArray(X.target)?X.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(X.target)),this.config.onConflict=V`(${V.raw(W)})${Z} do update set ${G}${Y}${_}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:X,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(X){return F0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,X,!0,void 0,{type:"insert",tables:m1(this.config.table)},this.cacheConfig)})}prepare(X){return this._prepare(X)}authToken;setToken(X){return this.authToken=X,this}execute=(X)=>{return F0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(X,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new B0({alias:g0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class tZ extends Y1{constructor(X,Y,Z){super();this.session=Y,this.dialect=Z,this.config={view:X}}static[E]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:X,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(X){return F0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,X,!0)})}prepare(X){return this._prepare(X)}authToken;setToken(X){return this.authToken=X,this}execute=(X)=>{return F0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(X,this.authToken)})}}class HX{constructor(X,Y,Z,_){this.table=X,this.session=Y,this.dialect=Z,this.withList=_}static[E]="PgUpdateBuilder";authToken;setToken(X){return this.authToken=X,this}set(X){return new b$(this.table,h6(this.table,X),this.session,this.dialect,this.withList).setToken(this.authToken)}}class b$ extends Y1{constructor(X,Y,Z,_,G){super();this.session=Z,this.dialect=_,this.config={set:Y,table:X,withList:G,joins:[]},this.tableName=J4(X),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[E]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(X){let Y=X,Z=J4(Y);if(typeof Z==="string")this.joinsNotNullableMap[Z]=!0;return this.config.from=Y,this}getTableLikeFields(X){if(M(X,b0))return X[T.Symbol.Columns];else if(M(X,C0))return X._.selectedFields;return X[V0].selectedFields}createJoin(X){return(Y,Z)=>{let _=J4(Y);if(typeof _==="string"&&this.config.joins.some((G)=>G.alias===_))throw Error(`Alias "${_}" is already used in this query`);if(typeof Z==="function"){let G=this.config.from&&!M(this.config.from,S)?this.getTableLikeFields(this.config.from):void 0;Z=Z(new Proxy(this.config.table[T.Symbol.Columns],new B0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new B0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:Z,table:Y,joinType:X,alias:_}),typeof _==="string")switch(X){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(X){return this.config.where=X,this}returning(X){if(!X){if(X=Object.assign({},this.config.table[T.Symbol.Columns]),this.config.from){let Y=J4(this.config.from);if(typeof Y==="string"&&this.config.from&&!M(this.config.from,S)){let Z=this.getTableLikeFields(this.config.from);X[Y]=Z}for(let Z of this.config.joins){let _=J4(Z.table);if(typeof _==="string"&&!M(Z.table,S)){let G=this.getTableLikeFields(Z.table);X[_]=G}}}}return this.config.returningFields=X,this.config.returning=B1(X),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:X,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(X){let Y=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,X,!0,void 0,{type:"insert",tables:m1(this.config.table)},this.cacheConfig);return Y.joinsNotNullableMap=this.joinsNotNullableMap,Y}prepare(X){return this._prepare(X)}authToken;setToken(X){return this.authToken=X,this}execute=(X)=>{return this._prepare().execute(X,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new B0({alias:g0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class f2 extends S{constructor(X){super(f2.buildEmbeddedCount(X.source,X.filters).queryChunks);this.params=X,this.mapWith(Number),this.session=X.session,this.sql=f2.buildCount(X.source,X.filters)}sql;token;static[E]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(X,Y){return V`(select count(*) from ${X}${V.raw(" where ").if(Y)}${Y})`}static buildCount(X,Y){return V`select count(*) as count from ${X}${V.raw(" where ").if(Y)}${Y};`}setToken(X){return this.token=X,this}then(X,Y){return Promise.resolve(this.session.count(this.sql,this.token)).then(X,Y)}catch(X){return this.then(void 0,X)}finally(X){return this.then((Y)=>{return X?.(),Y},(Y)=>{throw X?.(),Y})}}class eZ{constructor(X,Y,Z,_,G,W,$){this.fullSchema=X,this.schema=Y,this.tableNamesMap=Z,this.table=_,this.tableConfig=G,this.dialect=W,this.session=$}static[E]="PgRelationalQueryBuilder";findMany(X){return new aZ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?X:{},"many")}findFirst(X){return new aZ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?{...X,limit:1}:{limit:1},"first")}}class aZ extends Y1{constructor(X,Y,Z,_,G,W,$,H,Q){super();this.fullSchema=X,this.schema=Y,this.tableNamesMap=Z,this.table=_,this.tableConfig=G,this.dialect=W,this.session=$,this.config=H,this.mode=Q}static[E]="PgRelationalQuery";_prepare(X){return F0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Y,builtQuery:Z}=this._toSQL();return this.session.prepareQuery(Z,void 0,X,!0,(_,G)=>{let W=_.map(($)=>o6(this.schema,this.tableConfig,$,Y.selection,G));if(this.mode==="first")return W[0];return W})})}prepare(X){return this._prepare(X)}_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 X=this._getQuery(),Y=this.dialect.sqlToQuery(X.sql);return{query:X,builtQuery:Y}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(X){return this.authToken=X,this}execute(){return F0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class X5 extends Y1{constructor(X,Y,Z,_){super();this.execute=X,this.sql=Y,this.query=Z,this.mapBatchResult=_}static[E]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(X,Y){return Y?this.mapBatchResult(X):X}_prepare(){return this}isResponseInArrayMode(){return!1}}class h2{constructor(X,Y,Z){if(this.dialect=X,this.session=Y,this._=Z?{schema:Z.schema,fullSchema:Z.fullSchema,tableNamesMap:Z.tableNamesMap,session:Y}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:Y},this.query={},this._.schema)for(let[_,G]of Object.entries(this._.schema))this.query[_]=new eZ(Z.fullSchema,this._.schema,this._.tableNamesMap,Z.fullSchema[_],G,X,Y);this.$cache={invalidate:async(_)=>{}}}static[E]="PgDatabase";query;$with=(X,Y)=>{let Z=this;return{as:(G)=>{if(typeof G==="function")G=G(new x2(Z.dialect));return new Proxy(new L2(G.getSQL(),Y??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),X,!0),new B0({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(X,Y){return new f2({source:X,filters:Y,session:this.session})}$cache;with(...X){let Y=this;function Z(Q){return new Z1({fields:Q??void 0,session:Y.session,dialect:Y.dialect,withList:X})}function _(Q){return new Z1({fields:Q??void 0,session:Y.session,dialect:Y.dialect,withList:X,distinct:!0})}function G(Q,J){return new Z1({fields:J??void 0,session:Y.session,dialect:Y.dialect,withList:X,distinct:{on:Q}})}function W(Q){return new HX(Q,Y.session,Y.dialect,X)}function $(Q){return new $X(Q,Y.session,Y.dialect,X)}function H(Q){return new WX(Q,Y.session,Y.dialect,X)}return{select:Z,selectDistinct:_,selectDistinctOn:G,update:W,insert:$,delete:H}}select(X){return new Z1({fields:X??void 0,session:this.session,dialect:this.dialect})}selectDistinct(X){return new Z1({fields:X??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(X,Y){return new Z1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:{on:X}})}update(X){return new HX(X,this.session,this.dialect)}insert(X){return new $X(X,this.session,this.dialect)}delete(X){return new WX(X,this.session,this.dialect)}refreshMaterializedView(X){return new tZ(X,this.session,this.dialect)}authToken;execute(X){let Y=typeof X==="string"?V.raw(X):X.getSQL(),Z=this.dialect.sqlToQuery(Y),_=this.session.prepareQuery(Z,void 0,void 0,!1);return new X5(()=>_.execute(void 0,this.authToken),Y,Z,(G)=>_.mapResult(G,!0))}transaction(X,Y){return this.session.transaction(X,Y)}}class y${static[E]="Cache"}class k2 extends y${strategy(){return"all"}static[E]="NoopCache";async get(X){return}async put(X,Y,Z,_){}async onMutate(X){}}async function Y5(X,Y){let Z=`${X}-${JSON.stringify(Y)}`,G=new TextEncoder().encode(Z),W=await crypto.subtle.digest("SHA-256",G);return[...new Uint8Array(W)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}class Z5{constructor(X,Y,Z,_){if(this.query=X,this.cache=Y,this.queryMetadata=Z,this.cacheConfig=_,Y&&Y.strategy()==="all"&&_===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(X,Y){return X}setToken(X){return this.authToken=X,this}static[E]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(X,Y,Z){if(this.cache===void 0||M(this.cache,k2)||this.queryMetadata===void 0)try{return await Z()}catch(_){throw new H4(X,Y,_)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await Z()}catch(_){throw new H4(X,Y,_)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[_]=await Promise.all([Z(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return _}catch(_){throw new H4(X,Y,_)}if(!this.cacheConfig)try{return await Z()}catch(_){throw new H4(X,Y,_)}if(this.queryMetadata.type==="select"){let _=await this.cache.get(this.cacheConfig.tag??await Y5(X,Y),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(_===void 0){let G;try{G=await Z()}catch(W){throw new H4(X,Y,W)}return await this.cache.put(this.cacheConfig.tag??await Y5(X,Y),G,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),G}return _}try{return await Z()}catch(_){throw new H4(X,Y,_)}}}class _5{constructor(X){this.dialect=X}static[E]="PgSession";execute(X,Y){return F0.startActiveSpan("drizzle.operation",()=>{return F0.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(X),void 0,void 0,!1)}).setToken(Y).execute(void 0,Y)})}all(X){return this.prepareQuery(this.dialect.sqlToQuery(X),void 0,void 0,!1).all()}async count(X,Y){let Z=await this.execute(X,Y);return Number(Z[0].count)}}class G5 extends h2{constructor(X,Y,Z,_=0){super(X,Y,Z);this.schema=Z,this.nestedIndex=_}static[E]="PgTransaction";rollback(){throw new NZ}getTransactionConfigSQL(X){let Y=[];if(X.isolationLevel)Y.push(`isolation level ${X.isolationLevel}`);if(X.accessMode)Y.push(X.accessMode);if(typeof X.deferrable==="boolean")Y.push(X.deferrable?"deferrable":"not deferrable");return V.raw(Y.join(" "))}setTransaction(X){return this.session.execute(V`set transaction ${this.getTransactionConfigSQL(X)}`)}}class g$ extends Z5{constructor(X,Y,Z,_,G,W,$,H,Q,J){super({sql:Y,params:Z},G,W,$);this.client=X,this.queryString=Y,this.params=Z,this.logger=_,this.fields=H,this._isResponseInArrayMode=Q,this.customResultMapper=J}static[E]="PostgresJsPreparedQuery";async execute(X={}){return F0.startActiveSpan("drizzle.execute",async(Y)=>{let Z=RZ(this.params,X);Y?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(Z)}),this.logger.logQuery(this.queryString,Z);let{fields:_,queryString:G,client:W,joinsNotNullableMap:$,customResultMapper:H}=this;if(!_&&!H)return F0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(G,Z,async()=>{return await W.unsafe(G,Z)})});let Q=await F0.startActiveSpan("drizzle.driver.execute",()=>{return Y?.setAttributes({"drizzle.query.text":G,"drizzle.query.params":JSON.stringify(Z)}),this.queryWithCache(G,Z,async()=>{return await W.unsafe(G,Z).values()})});return F0.startActiveSpan("drizzle.mapResponse",()=>{return H?H(Q):Q.map((J)=>g7(_,J,$))})})}all(X={}){return F0.startActiveSpan("drizzle.execute",async(Y)=>{let Z=RZ(this.params,X);return Y?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(Z)}),this.logger.logQuery(this.queryString,Z),F0.startActiveSpan("drizzle.driver.execute",()=>{return Y?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(Z)}),this.queryWithCache(this.queryString,Z,async()=>{return this.client.unsafe(this.queryString,Z)})})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class b2 extends _5{constructor(X,Y,Z,_={}){super(Y);this.client=X,this.schema=Z,this.options=_,this.logger=_.logger??new KZ,this.cache=_.cache??new k2}static[E]="PostgresJsSession";logger;cache;prepareQuery(X,Y,Z,_,G,W,$){return new g$(this.client,X.sql,X.params,this.logger,this.cache,W,$,Y,_,G)}query(X,Y){return this.logger.logQuery(X,Y),this.client.unsafe(X,Y).values()}queryObjects(X,Y){return this.client.unsafe(X,Y)}transaction(X,Y){return this.client.begin(async(Z)=>{let _=new b2(Z,this.dialect,this.schema,this.options),G=new W5(this.dialect,_,this.schema);if(Y)await G.setTransaction(Y);return X(G)})}}class W5 extends G5{constructor(X,Y,Z,_=0){super(X,Y,Z,_);this.session=Y}static[E]="PostgresJsTransaction";transaction(X){return this.session.client.savepoint((Y)=>{let Z=new b2(Y,this.dialect,this.schema,this.session.options),_=new W5(this.dialect,Z,this.schema);return X(_)})}}class p$ extends h2{static[E]="PostgresJsDatabase"}function I8(X,Y={}){let Z=(Q)=>Q;for(let Q of["1184","1082","1083","1114","1182","1185","1115","1231"])X.options.parsers[Q]=Z,X.options.serializers[Q]=Z;X.options.serializers["114"]=Z,X.options.serializers["3802"]=Z;let _=new u4({casing:Y.casing}),G;if(Y.logger===!0)G=new IZ;else if(Y.logger!==!1)G=Y.logger;let W;if(Y.schema){let Q=F$(Y.schema,E$);W={fullSchema:Y.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let $=new b2(X,_,W,{logger:G,cache:Y.cache}),H=new p$(_,$,W);if(H.$client=X,H.$cache=Y.cache,H.$cache)H.$cache.invalidate=Y.cache?.onMutate;return H}function JX(...X){if(typeof X[0]==="string"){let Y=w8(X[0]);return I8(Y,X[1])}if(u7(X[0])){let{connection:Y,client:Z,..._}=X[0];if(Z)return I8(Z,_);if(typeof Y==="object"&&Y.url!==void 0){let{url:W,...$}=Y,H=w8(W,$);return I8(H,_)}let G=w8(Y);return I8(G,_)}return I8(X[0],X[1])}((X)=>{function Y(Z){return I8({options:{parsers:{},serializers:{}}},Z)}X.mock=Y})(JX||(JX={}));var H5={};lH(H5,{users:()=>d4,untrackedUserColumnNames:()=>xE,twoFactorMethod:()=>l$,trackedUserColumnName:()=>fE,trackableUserColumnNames:()=>d$,signInHistory:()=>kE,role:()=>u$,players:()=>$5,passwordResetAttempts:()=>bE,games:()=>zX,banishedIps:()=>yE,accountActions:()=>hE,accountAction:()=>c$});function T4(){return n0({length:24}).$type()}function m$(X){return V`lower(${X})`}var QX=V`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,u$=D2("role",["admin","user"]),d4=I4("users",{id:T1().primaryKey().defaultRandom(),username:n0({length:16}).notNull(),emailOffered:n0({length:254}).notNull(),emailVerified:n0({length:254}),password:n0({length:254}),createdAtIso:T4().notNull().default(QX),createdIp:n0({length:45}).notNull(),isActive:N2().notNull().default(!1),verifiedAtIso:T4(),userRole:u$().default("user")},(X)=>[oZ("usernameUniqueIndex").on(m$(X.username)),oZ("emailVerifiedUniqueIndex").on(m$(X.emailVerified))]),xE=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],d$=["username","emailOffered","emailVerified","password","userRole"],fE=D2("trackedUserColumnName",d$),c$=D2("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),hE=I4("accountActions",{userId:T1().references(()=>d4.id).primaryKey(),action:c$().notNull(),code:n0({length:254}).notNull(),wrongCodeCount:I2().notNull().default(0),expiresAtIso:T4().notNull()}),zX=I4("games",{id:T1().primaryKey().defaultRandom()}),$5=I4("players",{userId:T1().notNull().references(()=>d4.id,{onDelete:"cascade"}),gameId:T1().notNull().references(()=>zX.id,{onDelete:"cascade"}),score:I2().notNull()},(X)=>[gW({name:"players_userId_gameId_pk",columns:[X.userId,X.gameId]})]),kE=I4("signInHistory",{id:T1().primaryKey().defaultRandom(),userId:T1().references(()=>d4.id,{onDelete:"cascade"}),signInTimeIso:T4().notNull().default(QX),ipAddress:n0({length:45}).notNull(),userAgent:n0({length:1024}),successful:N2().notNull().default(!1)}),l$=D2("twoFactorMethod",["email","phone"]),bE=I4("passwordResetAttempts",{id:T1().primaryKey().defaultRandom(),userId:T1().notNull().references(()=>d4.id,{onDelete:"cascade"}),requestedIp:n0({length:45}).notNull(),requestedAtIso:T4().notNull().default(QX),succeededIp:n0({length:45}),succeededAtIso:T4(),verificationMethod:l$().notNull()}),yE=I4("banishedIps",{ip:n0({length:45}).primaryKey(),reason:n0({length:2048}).notNull(),banishedAtIso:T4().notNull().default(QX),banishedUntilIso:T4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class J5{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(gE.resolve(__dirname,"notify_update.sql"));let X=[g0(d4),g0(zX),g0($5)];await this.sql`SELECT create_notify_triggers(${this.sql.array(X)})`,await this.sql.listen("table_update",(Y)=>{let Z=Y.split(","),_=Z[0],G=Z[1],W=`${_}("${G}")`;if(this.observers.has(W))this.observers.get(W).next(W)})}constructor(X=!1,Y={host:g1.POSTGRES_HOST,port:g1.POSTGRES_PORT,user:g1.POSTGRES_USER,password:g1.POSTGRES_PASSWORD,database:g1.POSTGRES_DATABASE}){this.options=Y,this.sql=w8(Y),this.drizzle=JX(this.sql,{schema:H5,logger:X})}observe(X,Y){if(!this.observers.has(X))this.observers.set(X,new Z0);this.observers.get(X).subscribe("SINGLETON",Y)}}var FX={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 pE(X){return Number.parseInt(X,10)}var mE=J1(FX),uE=mE.keyof().pipe((X)=>pE(X)),o$=J1([uE,"string"]);var z5=new V7(process),{logger:E1}=z5;Object.assign(console,E1,{log:E1.info});E1.info("ready");var Q5=n$(import.meta.dir,"..","app"),Uf=new J5({logQuery(X,Y){E1.info("\uD83D\uDCDD query",X,Y)}});oE({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...q6??void 0,async fetch(X){try{let Y=new Date,Z=new URL(X.url);if(E1.info(X.method,Z.pathname),Z.pathname==="/")return new Response(Bun.file(n$(Q5,"index.html")));if(Z.pathname==="/index.html")return Response.redirect("/");let _=cE(Q5,Z.pathname),G=lE(_);if(!G.startsWith(Q5))throw[403,"Access Denied"];if(!await i$(G).exists())return Response.redirect("/");return new Response(i$(G))}catch(Y){let Z=o$(Y);if(Z instanceof J1.errors===!1){let[_,G]=Z,$=`${FX[_]}. ${G}`;return E1.info(`\u274C ${_}: ${$}`),new Response($,{status:_})}if(Y instanceof Error)E1.error(Y.message);else{let _=C6(Y);E1.error("frontend server threw",_)}return new Response(FX[500],{status:500})}}});function UX(){E1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{E1.info("\u2757 received SIGINT; exiting gracefully"),UX()});process.on("SIGTERM",()=>{E1.info("\u2757 received SIGTERM; exiting gracefully"),UX()});process.on("exit",()=>{E1.info("\u2757 received exit; exiting gracefully"),UX()});z5.on("timeToStop",()=>{E1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),UX()});var{version:iE}=await Bun.file(dE.resolve(import.meta.dir,"../package.json")).json();E1.info(`\uD83D\uDEEB frontend v${iE} running at http://localhost:${g1.FRONTEND_PORT}/`);z5.emit("alive");