tempest.games 0.2.62 → 0.2.64

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,81 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var pH=Object.create;var{getPrototypeOf:mH,defineProperty:EX,getOwnPropertyNames:uH}=Object;var dH=Object.prototype.hasOwnProperty;var iE=(X,Y,Z)=>{Z=X!=null?pH(mH(X)):{};let _=Y||!X||!X.__esModule?EX(Z,"default",{value:X,enumerable:!0}):Z;for(let G of uH(X))if(!dH.call(_,G))EX(_,G,{get:()=>X[G],enumerable:!0});return _};var nE=(X,Y)=>()=>(Y||X((Y={exports:{}}).exports,Y),Y.exports);var cH=(X,Y)=>{for(var Z in Y)EX(X,Z,{get:Y[Z],enumerable:!0,configurable:!0,set:(_)=>Y[Z]=()=>_})};var rE=(X,Y)=>()=>(X&&(Y=X(X=0)),Y);var sE=import.meta.require;import uE,{join as dE,normalize as cE,resolve as i$}from"path";var U4=(X)=>Array.isArray(X)?X:[X],N5=(X,Y)=>{let Z=[[],[]];for(let _ of X)if(Y(_))Z[0].push(_);else Z[1].push(_);return Z},g2=Array,r1=(X,Y)=>X.includes(Y),I5=(X,Y=0)=>[...Array(X)].map((Z,_)=>_+Y),s=(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)},K5=(...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},B5=(X,Y)=>X.reduce((Z,_)=>{let G=_[Y];return Z[G]=s(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"},T5={...G1,function:"a function"};class C5 extends Error{}var e=(X)=>C4(X,C5),C4=(X,Y=Error)=>{throw new Y(X)};class C8 extends Error{name="ParseError"}var w=(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]=s(Z[J.group],z);else Z[J]=z}return G?Object.values(Z):Z};var OX=Object.entries;var f0=(X,Y)=>(X in Y),i4=(X,Y)=>(Y in X);class VX{constructor(X){Object.assign(this,X)}}var q5=class{};class q8 extends q5{}var lH=(X,Y)=>{let Z={},_={},G;for(G in X)if(G in Y)Z[G]=X[G];else _[G]=X[G];return[Z,_]};var j5=(X,Y)=>lH(X,Y)[1],l1=(X)=>Object.keys(X).length===0,q4=(X)=>[...Object.entries(X),...Object.getOwnPropertySymbols(X).map((Y)=>[Y,X[Y]])],S5=(X,Y)=>Object.defineProperties(X,Object.getOwnPropertyDescriptors(Y)),P5=(X)=>{let Y=Object.keys(X).sort(),Z={};for(let _=0;_<Y.length;_++)Z[Y[_]]=X[Y[_]];return Z};var O1=P1("represents an uninitialized value"),v5=(X)=>Object.values(X).filter((Y)=>{if(typeof Y==="number")return!0;return typeof X[Y]!=="number"});var DX={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},LX=globalThis.File??Blob,MX={ArrayBuffer,Blob,File:LX,FormData,Headers,Request,Response,URL},oH={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},j4={...DX,...MX,...oH,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,iH={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"},nH={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"},rH={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"},x5={...iH,...nH,...rH},P8=(X)=>{let Y=Object(X).name??null;return Y&&f0(Y,j4)&&j4[Y]===X?Y:null};var AX=(X,Y)=>{let Z=X.prototype;while(Z!==null){if(Z===Y.prototype)return!0;Z=Object.getPrototypeOf(Z)}return!1};var f5=(X)=>h5(X,new Map),h5=(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=h5($.value,Y)}}return Object.defineProperties(_,G),_};var sH=(X)=>{let Y=O1;return()=>Y===O1?Y=X():Y},E4=(X)=>typeof X==="function"&&X.length===0;var k5=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:
3
+ var iH=Object.create;var{getPrototypeOf:nH,defineProperty:DX,getOwnPropertyNames:rH}=Object;var sH=Object.prototype.hasOwnProperty;var ZO=(X,Y,Z)=>{Z=X!=null?iH(nH(X)):{};let _=Y||!X||!X.__esModule?DX(Z,"default",{value:X,enumerable:!0}):Z;for(let G of rH(X))if(!sH.call(_,G))DX(_,G,{get:()=>X[G],enumerable:!0});return _};var _O=(X,Y)=>()=>(Y||X((Y={exports:{}}).exports,Y),Y.exports);var tH=(X,Y)=>{for(var Z in Y)DX(X,Z,{get:Y[Z],enumerable:!0,configurable:!0,set:(_)=>Y[Z]=()=>_})};var GO=(X,Y)=>()=>(X&&(Y=X(X=0)),Y);var WO=import.meta.require;import tE,{join as aE,normalize as eE,resolve as XH}from"path";var p2=(X,Y)=>new RegExp(X,Y);Object.assign(p2,{cast:p2});var E4=(X)=>Array.isArray(X)?X:[X],T5=(X,Y)=>{let Z=[[],[]];for(let _ of X)if(Y(_))Z[0].push(_);else Z[1].push(_);return Z},m2=Array,v1=(X,Y)=>X.includes(Y),C5=(X,Y=0)=>[...Array(X)].map((Z,_)=>_+Y),s=(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},t1=(X,Y)=>{if(Y===void 0||Y===null)return X??[];if(X===void 0||X===null)return E4(Y);return X.concat(Y)},q5=(...X)=>X.reduce(t1,[]),l1=(X,Y,Z)=>{if(X===void 0)return Array.isArray(Y)?Y:[Y];let _=Z?.isEqual??((G,W)=>G===W);for(let G of E4(Y))if(!X.some((W)=>_(W,G)))X.push(G);return X},j5=(X,Y)=>X.reduce((Z,_)=>{let G=_[Y];return Z[G]=s(Z[G],_),Z},{}),a1=(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"},S5={...G1,function:"a function"};class P5 extends Error{}var e=(X)=>C4(X,P5),C4=(X,Y=Error)=>{throw new Y(X)};class q8 extends Error{name="ParseError"}var M=(X)=>C4(X,q8),x1=(X)=>` ${X}`,v5="\u200B";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]=s(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),n4=(X,Y)=>(Y in X);class AX{constructor(X){Object.assign(this,X)}}var x5=class{};class j8 extends x5{}var aH=(X,Y)=>{let Z={},_={},G;for(G in X)if(G in Y)Z[G]=X[G];else _[G]=X[G];return[Z,_]};var u2=(X,Y)=>aH(X,Y)[1],o1=(X)=>Object.keys(X).length===0,q4=(X)=>[...Object.entries(X),...Object.getOwnPropertySymbols(X).map((Y)=>[Y,X[Y]])],f5=(X,Y)=>Object.defineProperties(X,Object.getOwnPropertyDescriptors(Y)),h5=(X)=>{let Y=Object.keys(X).sort(),Z={};for(let _=0;_<Y.length;_++)Z[Y[_]]=X[Y[_]];return Z};var W1=x1(`unset${v5}`),k5=(X)=>Object.values(X).filter((Y)=>{if(typeof Y==="number")return!0;return typeof X[Y]!=="number"});var MX={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},eH={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},j4={...MX,...wX,...eH,String,Number,Boolean},S8=(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},P8=(X)=>typeof X==="object"&&X!==null?S8(X)??"object":x0(X);var Q0=Array.isArray,XJ={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"},YJ={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"},ZJ={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"},b5={...XJ,...YJ,...ZJ},v8=(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 y5=(X)=>g5(X,new Map),g5=(X,Y)=>{if(typeof X!=="object"||X===null)return X;if(Y?.has(X))return Y.get(X);let Z=v8(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=g5($.value,Y)}}return Object.defineProperties(_,G),_};var _J=(X)=>{let Y=W1;return()=>Y===W1?Y=X():Y},O4=(X)=>typeof X==="function"&&X.length===0;var p5=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
4
  Message: ${_}
5
5
  Source: (${X.slice(0,-1)}) => {
6
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 b5=sH(()=>{try{return Function("return false")()}catch{return!0}});var LO=P1("brand");var y5=P1("arkInferred");var RO=P1("args");class o0{constructor(){}}var tH=()=>{try{return((Error().stack?.split(`
8
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},aH=globalThis.process?.env??{},g5={fileName:tH,env:aH};var p5=(X)=>X[0].toUpperCase()+X.slice(1);var RX=(X)=>new RegExp(eH(X),typeof X==="string"?"":X.flags);var eH=(X)=>{return`^(?:${typeof X==="string"?X:X.source})$`};var a1={negativeLookahead:(X)=>`(?!${X})`,nonCapturingGroup:(X)=>`(?:${X})`},v8="\\",O4={" ":1,"\n":1,"\t":1};var XJ=/^-0\.?0*$/.source,u5=/[1-9]\d*/.source,YJ=/\.\d+/.source,ZJ=/\.\d*[1-9]/.source,d5=(X)=>RX(a1.negativeLookahead(XJ)+a1.nonCapturingGroup("-?"+a1.nonCapturingGroup(a1.nonCapturingGroup("0|"+u5)+a1.nonCapturingGroup(X.decimalPattern)+"?")+(X.allowDecimalOnly?"|"+X.decimalPattern:"")+"?")),m5=d5({decimalPattern:ZJ,allowDecimalOnly:!1}),_J=m5.test.bind(m5),p2=d5({decimalPattern:YJ,allowDecimalOnly:!0}),CO=p2.test.bind(p2),GJ=/^-?\d*\.?\d*$/,WJ=(X)=>X.length!==0&&GJ.test(X),x8=RX(a1.negativeLookahead("^-0$")+"-?"+a1.nonCapturingGroup(a1.nonCapturingGroup("0|"+u5))),$J=x8.test.bind(x8),wX=/^-?\d+$/,HJ=wX.test.bind(wX),c5={number:"a number",bigint:"a bigint",integer:"an integer"},l5=(X,Y)=>`'${X}' was parsed as ${c5[Y]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,JJ=(X,Y)=>Y==="number"?_J(X):$J(X),QJ=(X,Y)=>Y==="number"?Number(X):Number.parseInt(X),zJ=(X,Y)=>Y==="number"?WJ(X):HJ(X),o5=(X,Y)=>NX(X,"number",Y),i5=(X,Y)=>NX(X,"number",{...Y,strict:!0}),n5=(X,Y)=>NX(X,"integer",Y),NX=(X,Y,Z)=>{let _=QJ(X,Y);if(!Number.isNaN(_)){if(zJ(X,Y)){if(Z?.strict)return JJ(X,Y)?_:w(l5(X,Y));return _}}return Z?.errorOnFail?w(Z?.errorOnFail===!0?`Failed to parse ${c5[Y]} from '${X}'`:Z?.errorOnFail):void 0},r5=(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(wX.test(Y))return w(l5(X,"bigint"))};var FJ="0.49.0",UJ={version:FJ,filename:g5.fileName(),FileConstructor:LX},S4=UJ,s5=new Map,IX=Object.create(null),f8=(X)=>{let Y=s5.get(X);if(Y)return Y;let Z=EJ(X);if(IX[Z])Z=`${Z}${IX[Z]++}`;else IX[Z]=1;return S4[Z]=X,s5.set(X,Z),Z},V4=(X)=>/^[$A-Z_a-z][\w$]*$/.test(X),EJ=(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 t5=(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?m2(Z,Y?.indent??0,""):JSON.stringify(k8(Z,n4,[]),null,Y?.indent):m2(Z,Y?.indent??0,"");case"symbol":return n4.onSymbol(X);default:return h8(X)}},m2=(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(($)=>m2($,Y,_)).join(`,
7
+ }`)}}};class $1{constructor(X,...[Y]){return Object.assign(Object.setPrototypeOf(X.bind(Y?.bind??this),this.constructor.prototype),Y?.attach)}}var m5=_J(()=>{try{return Function("return false")()}catch{return!0}});var jO=x1("brand");var u5=x1("arkInferred");var vO=x1("args");class o0{constructor(){}}var GJ=()=>{try{return((Error().stack?.split(`
8
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},WJ=globalThis.process?.env??{},d5={fileName:GJ,env:WJ};var c5=(X)=>X[0].toUpperCase()+X.slice(1);var IX=(X)=>new RegExp($J(X),typeof X==="string"?"":X.flags);var $J=(X)=>{return`^(?:${typeof X==="string"?X:X.source})$`};var e1={negativeLookahead:(X)=>`(?!${X})`,nonCapturingGroup:(X)=>`(?:${X})`},S4="\\",V4={" ":1,"\n":1,"\t":1};var HJ=/^-0\.?0*$/.source,o5=/[1-9]\d*/.source,JJ=/\.\d+/.source,QJ=/\.\d*[1-9]/.source,i5=(X)=>IX(e1.negativeLookahead(HJ)+e1.nonCapturingGroup("-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+o5)+e1.nonCapturingGroup(X.decimalPattern)+"?")+(X.allowDecimalOnly?"|"+X.decimalPattern:"")+"?")),l5=i5({decimalPattern:QJ,allowDecimalOnly:!1}),zJ=l5.test.bind(l5),d2=i5({decimalPattern:JJ,allowDecimalOnly:!0}),gO=d2.test.bind(d2),FJ=/^-?\d*\.?\d*$/,UJ=(X)=>X.length!==0&&FJ.test(X),x8=IX(e1.negativeLookahead("^-0$")+"-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+o5))),EJ=x8.test.bind(x8),KX=/^-?\d+$/,OJ=KX.test.bind(KX),n5={number:"a number",bigint:"a bigint",integer:"an integer"},r5=(X,Y)=>`'${X}' was parsed as ${n5[Y]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,VJ=(X,Y)=>Y==="number"?zJ(X):EJ(X),DJ=(X,Y)=>Y==="number"?Number(X):Number.parseInt(X),LJ=(X,Y)=>Y==="number"?UJ(X):OJ(X),s5=(X,Y)=>BX(X,"number",Y),t5=(X,Y)=>BX(X,"number",{...Y,strict:!0}),a5=(X,Y)=>BX(X,"integer",Y),BX=(X,Y,Z)=>{let _=DJ(X,Y);if(!Number.isNaN(_)){if(LJ(X,Y)){if(Z?.strict)return VJ(X,Y)?_:M(r5(X,Y));return _}}return Z?.errorOnFail?M(Z?.errorOnFail===!0?`Failed to parse ${n5[Y]} from '${X}'`:Z?.errorOnFail):void 0},e5=(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 M(r5(X,"bigint"))};var AJ="0.50.0",MJ={version:AJ,filename:d5.fileName(),FileConstructor:RX},P4=MJ,X_=new Map,TX=Object.create(null),f8=(X)=>{let Y=X_.get(X);if(Y)return Y;let Z=RJ(X);if(TX[Z])Z=`${Z}${TX[Z]++}`;else TX[Z]=1;return P4[Z]=X,X_.set(X,Z),Z},D4=(X)=>/^[$A-Z_a-z][\w$]*$/.test(X),RJ=(X)=>{switch(typeof X){case"object":{if(X===null)break;let Y=S8(X)??"object";return Y[0].toLowerCase()+Y.slice(1)}case"function":return D4(X.name)?X.name:"fn";case"symbol":return X.description&&D4(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 Y_=(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?c2(Z,Y?.indent??0,""):JSON.stringify(k8(Z,r4,[]),null,Y?.indent):c2(Z,Y?.indent??0,"");case"symbol":return r4.onSymbol(X);default:return h8(X)}},c2=(X,Y,Z)=>{if(typeof X==="function")return r4.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(($)=>c2($,Y,_)).join(`,
9
9
  `+_);return Y?`[
10
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=m2(H,Y,_);return`${_}${Q}: ${J}`});if(W.length===0)return"{}";return Y?`{
11
+ ${Z}]`:`[${W}]`}let G=X.constructor.name;if(G==="Object"){let W=q4(X).map(([$,H])=>{let Q=typeof $==="symbol"?r4.onSymbol($):D4($)?$:JSON.stringify($),J=c2(H,Y,_);return`${_}${Q}: ${J}`});if(W.length===0)return"{}";return Y?`{
12
12
  ${W.join(`,
13
13
  `)}
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=`${OJ[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+=`.${DJ(H,3)}`;else if(VJ.test(J))J=J.slice(0,-3);return`${J+z}, ${Q}`},OJ=["January","February","March","April","May","June","July","August","September","October","November","December"],VJ=/:\d\d:00$/,DJ=(X,Y)=>String(X).padStart(Y,"0");var a5=(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 w(`${c(Y)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return G},e1=(X,...Y)=>X.reduce((Z,_)=>a5(Z,_,...Y),"");class b8 extends g2{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=a5(X,Z),Y.push(X);return this.cache.stringifyAncestors=Y}}class KX{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 aO=P1("implementedTraits");var BX="$ark",LJ=2;while(BX in globalThis)BX=`$ark${LJ++}`;var e5=BX;globalThis[e5]=S4;var N=S4,MJ=(X)=>`${e5}.${X}`,N0=(X)=>MJ(f8(X));class u2 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 TX(X,Y)}index(X,Y=!1){return X_(`${X}`,Y)}line(X){return this.body+=`${" ".repeat(this.indentation)}${X}
14
+ ${Z}}`:`{${W.join(", ")}}`}if(X instanceof Date)return v4(X);if("expression"in X&&typeof X.expression==="string")return X.expression;return G},r4={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 r4.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 r4.onSymbol(X);case"bigint":return Y.onBigInt?.(X)??`${X}n`;case"undefined":return Y.onUndefined??"undefined";case"string":return X.replaceAll("\\","\\\\");default:return X}},v4=(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=`${wJ[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+=`.${IJ(H,3)}`;else if(NJ.test(J))J=J.slice(0,-3);return`${J+z}, ${Q}`},wJ=["January","February","March","April","May","June","July","August","September","October","November","December"],NJ=/:\d\d:00$/,IJ=(X,Y)=>String(X).padStart(Y,"0");var Z_=(X,Y,...[Z])=>{let _=Z?.stringifySymbol??c,G=X;switch(typeof Y){case"string":G=D4(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 M(`${c(Y)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return G},X4=(X,...Y)=>X.reduce((Z,_)=>Z_(Z,_,...Y),"");class b8 extends m2{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=X4(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let X="",Y=[X];for(let Z of this)X=Z_(X,Z),Y.push(X);return this.cache.stringifyAncestors=Y}}class y8{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))break;else Y+=this.shift();return Y}shiftUntilEscapable(X){let Y="";while(this.lookahead)if(this.lookahead===S4)if(this.shift(),X(this,Y))Y+=this.shift();else if(this.lookahead===S4)Y+=this.shift();else Y+=`${S4}${this.shift()}`;else if(X(this,Y))break;else 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 V4))}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 __=(X,Y)=>`Unmatched ${X}${Y===""?"":` before ${Y}`}`,l2=(X)=>`Missing ${X}`;var zV=x1("implementedTraits");var CX="$ark",KJ=2;while(CX in globalThis)CX=`$ark${KJ++}`;var G_=CX;globalThis[G_]=P4;var N=P4,BJ=(X)=>`${G_}.${X}`,N0=(X)=>BJ(f8(X));class o2 extends j8{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 qX(X,Y)}index(X,Y=!1){return W_(`${X}`,Y)}line(X){return this.body+=`${" ".repeat(this.indentation)}${X}
15
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
16
  `).map((Z)=>" ".repeat(Y)+`${Z}`).join(`
17
- `):this.body} }`}compile(){return new k5(...this.argNames,this.body)}}var X4=(X)=>_1(X,"object")||typeof X==="symbol"?N0(X):h8(X),TX=(X,Y=!1)=>{if(typeof X==="string"&&V4(X))return`${Y?"?":""}.${X}`;return X_(AJ(X),Y)},AJ=(X)=>typeof X==="symbol"?N0(X):JSON.stringify(X),X_=(X,Y=!1)=>`${Y?"?.":""}[${X}]`;class y8 extends u2{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 d2=(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 Y_=["unit","proto","domain"],r4=["required","optional","index","sequence"],CX=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],c2=[...CX,...r4,"structure","predicate"],s4=["alias","union","morph","unit","intersection","proto","domain"],RJ=[...s4,...c2],l2=d(c2,(X,Y)=>[Y,1]),Z_=d([...r4,"undeclared"],(X,Y)=>[Y,1]),__=d(RJ,(X,Y)=>[Y,X]),t4=(X)=>typeof X==="string"&&(X in __);var a4=(X)=>__[X],o2=(X)=>s4.slice(a4(X)+1),hV=[...o2("union"),"alias"],kV=[...o2("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 G_ 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 wJ={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:G_,throw:(...X)=>{throw new M0.Error(...X)},throwInternalOperandError:(X,Y)=>e(`Unexpected JSON Schema input for ${X}: ${c(Y)}`),defaultConfig:wJ};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[_]=qX(X.toJsonSchema,Y.toJsonSchema);else if(t4(_))Z[_]={...X[_],...Y[_]};else Z[_]=Y[_]}return Z},qX=(X,Y)=>{if(!X)return Y??{};if(!Y)return X;let Z={...X},_;for(_ in Y)if(_==="fallback")Z.fallback=NJ(X.fallback,Y.fallback);else Z[_]=Y[_];return Z},NJ=(X,Y)=>{X=W_(X),Y=W_(Y);let Z={},_;for(_ in M0.defaultConfig.fallback)Z[_]=Y[_]??Y.default??X[_]??X.default??M0.defaultConfig.fallback[_];return Z},W_=(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=_,S5(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:K5(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 g2{[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 jX(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]=s(this.byAncestorPath[Y],X)}}class jX extends Error{name="TraversalError";constructor(X){if(X.length===1)super(X.summary);else super(`
19
- `+X.map((Y)=>` \u2022 ${IJ(Y)}`).join(`
20
- `));Object.defineProperty(this,"arkErrors",{value:X,enumerable:!1})}}var IJ=(X)=>X.toString().split(`
17
+ `):this.body} }`}compile(){return new p5(...this.argNames,this.body)}}var Y4=(X)=>_1(X,"object")||typeof X==="symbol"?N0(X):h8(X),qX=(X,Y=!1)=>{if(typeof X==="string"&&D4(X))return`${Y?"?":""}.${X}`;return W_(TJ(X),Y)},TJ=(X)=>typeof X==="symbol"?N0(X):JSON.stringify(X),W_=(X,Y=!1)=>`${Y?"?.":""}[${X}]`;class g8 extends o2{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 i2=(X)=>d(X,(Y,Z)=>[Y,Q0(Z)?[...Z]:Z]),t0=x1("arkKind"),f=(X,Y)=>X?.[t0]===Y,E0=(X)=>f(X,"root")||f(X,"constraint");var $_=["unit","proto","domain"],s4=["required","optional","index","sequence"],jX=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],SX=[...jX,"structure","predicate"],n2=[...SX,...s4],t4=["alias","union","morph","unit","intersection","proto","domain"],CJ=[...t4,...n2],r2=d(n2,(X,Y)=>[Y,1]),H_=d([...s4,"undeclared"],(X,Y)=>[Y,1]),J_=d(CJ,(X,Y)=>[Y,X]),a4=(X)=>typeof X==="string"&&(X in J_);var e4=(X)=>J_[X],s2=(X)=>t4.slice(e4(X)+1),iV=[...s2("union"),"alias"],nV=[...s2("morph"),"alias"],R1=(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 Y4(X)},L4=(X)=>{let Y="{ ";for(let[Z,_]of Object.entries(X))Y+=`${Z}: ${Y4(_)}, `;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 Q_ 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 qJ={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(X)=>A0.throw("arrayObject",X),arrayPostfix:(X)=>A0.throw("arrayPostfix",X),defaultValue:(X)=>A0.throw("defaultValue",X),domain:(X)=>A0.throw("domain",X),morph:(X)=>A0.throw("morph",X),patternIntersection:(X)=>A0.throw("patternIntersection",X),predicate:(X)=>A0.throw("predicate",X),proto:(X)=>A0.throw("proto",X),symbolKey:(X)=>A0.throw("symbolKey",X),unit:(X)=>A0.throw("unit",X),date:(X)=>A0.throw("date",X)}},A0={Error:Q_,throw:(...X)=>{throw new A0.Error(...X)},throwInternalOperandError:(X,Y)=>e(`Unexpected JSON Schema input for ${X}: ${c(Y)}`),defaultConfig:qJ};N.config??={};var p8=(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(a4(_))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=jJ(X.fallback,Y.fallback);else Z[_]=Y[_];return Z},jJ=(X,Y)=>{X=z_(X),Y=z_(Y);let Z={},_;for(_ in A0.defaultConfig.fallback)Z[_]=Y[_]??Y.default??X[_]??X.default??A0.defaultConfig.fallback[_];return Z},z_=(X)=>typeof X==="function"?{default:X}:X??{};class A4 extends j8{[t0]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:X,relativePath:Y,...Z},_){super();this.input=Z,this.ctx=_,f5(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:q5(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 A4(X({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(X){return this.code===X}get propString(){return X4(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 H1 extends m2{[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){let Y=this.byPath[X.propString];if(Y){if(X===Y)return;if(Y.hasCode("union")&&Y.errors.length===0)return;let Z=X.hasCode("union")&&X.errors.length===0?X:new A4({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++}transform(X){let Y=new H1(this.ctx);for(let Z of this)Y.add(X(Z));return Y}merge(X){for(let Y of X)this.add(new A4({...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
+ `)}addAncestorPaths(X){for(let Y of X.path.stringifyAncestors())this.byAncestorPath[Y]=s(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 ${SJ(Y)}`).join(`
20
+ `));Object.defineProperty(this,"arkErrors",{value:X,enumerable:!1})}}var SJ=(X)=>X.toString().split(`
21
21
  `).join(`
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)=>CJ(_,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_(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=TJ(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(Y_,this.kind)}isConstraint(){return r1(c2,this.kind)}isStructural(){return r1(r4,this.kind)}isRefinement(){return r1(CX,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($_(Y,Z));return X},find:(X)=>X[0],assertFind:(X,Y,Z)=>{if(X.length===0)C4($_(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}},$_=(X,Y)=>`${X} had no references matching ${c(Y)}.`,KJ=(X)=>e1(X,{stringifyNonKey:(Y)=>Y.expression}),BJ=/"(\$ark\.[^"]+)"/g,TJ=(X)=>JSON.stringify(X).replaceAll(BJ,"$1"),f1=(X,Y)=>({path:X,node:Y,propString:KJ(X)}),H_=(X,Y)=>X.propString===Y.propString&&X.node.equals(Y.node),SX=(X,Y)=>c1(X,Y,{isEqual:H_}),CJ=(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 vX(`Intersection${_&&` at ${_}`} of ${J_(Y,Z)}`)}return`The following intersections result in unsatisfiable types:
23
- \u2022 ${this.map(({path:X,l:Y,r:Z})=>`${X}: ${J_(Y,Z)}`).join(`
24
- \u2022 `)}`}throw(){return w(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 J_=(X,Y)=>`${PX(X)} and ${PX(Y)}`,PX=(X)=>E0(X)?X.expression:Q0(X)?X.map(PX).join(" | ")||"never":String(X),vX=(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?xX(X,Y,Z):X.hasKindIn(...s4)?qJ(X,Y,Z):xX(X,Y,Z);if(E0($)){if(X.equals($))$=X;else if(Y.equals($))$=Y}return e4[G]=$,$},xX=(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}},qJ=(X,Y,Z)=>X.includesTransform||Y.includesTransform?Z.invert?Q_(Y,X,Z):Q_(X,Y,Z):xX(X,Y,Z),Q_=(X,Y,Z)=>X.distribute((_)=>jJ(_,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($)}),jJ=(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,SJ(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 l2)?_:[]).sort((Z,_)=>Z.precedence<_.precedence?-1:Z.precedence>_.precedence?1:Z.kind==="predicate"&&_.kind==="predicate"?0:Z.hash<_.hash?-1:1)},SJ=(X)=>{let Y={};for(let Z of X)if(Z.hasOpenIntersection())Y[Z.kind]=s(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},z_=(...X)=>w(F_(...X)),F_=(X,Y,Z)=>{let _=Z.hasKind("morph")?"a morph":Z.isUnknown()?"unknown":Z.exclude(Y).defaultShortDescription;return`${p5(X)} operand must be ${Y.description} (was ${_})`};var U_=(X,Y,Z)=>new M4(X,Y,Z,Z,null);class i2 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]))w(PJ(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 i2}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:t5(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 PJ=(X,Y,Z)=>`${X} must be assignable to ${Y} (was ${Z})`;var vJ=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 E_ extends R1{serializedPredicate=N0(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 fX={implementation:vJ,Node:E_};var xJ=l({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(X)=>Number.isInteger(X)?X:w(fJ(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/hJ(X.rule,Y.rule))})},obviatesBasisDescription:!0});class O_ 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 hX={implementation:xJ,Node:O_};var fJ=(X)=>`divisor must be an integer (was ${X})`,hJ=(X,Y)=>{let Z,_=X,G=Y;while(G!==0)Z=G,G=_%G,_=Z;return _};class V1 extends Y4{boundOperandKind=gJ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=pJ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${kJ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?mJ(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 kJ={"<":">=","<=":">",">":"<=",">=":"<"},bJ={min:"max",minLength:"maxLength",after:"before"},n2={parse:(X)=>X||void 0},r2=(X)=>(Y)=>{if(typeof Y==="number")return{rule:Y};let{exclusive:Z,..._}=Y;return Z?{..._,rule:X==="minLength"?_.rule+1:_.rule-1}:_},s2=(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}:_},t2=(X)=>typeof X==="string"||typeof X==="number"?new Date(X):X,yJ=(X,Y)=>`${X} bound must be a positive integer (was ${Y})`,Z8=(X)=>(Y)=>{if(!Number.isInteger(Y)||Y<0)w(yJ(X,Y));return Y},gJ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},pJ=(X,Y)=>`${f0(X,bJ)?">":"<"}${Y?"":"="}`,mJ=(X)=>typeof X==="string"?X:new Date(X).toLocaleString(),V_=(X)=>`Bounded expression ${X} must be exactly one of number, string, Array, or Date`;var uJ=l({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t2,serialize:(X)=>X.toISOString()}},normalize:s2("after"),defaults:{description:(X)=>`${X.collapsibleLimitString} or later`,actual:P4},intersections:{after:(X,Y)=>X.isStricterThan(Y)?X:Y}});class D_ extends V1{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 kX={implementation:uJ,Node:D_};var dJ=l({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t2,serialize:(X)=>X.toISOString()}},normalize:s2("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 L_ extends V1{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 bX={implementation:dJ,Node:L_};var cJ=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 M_ 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 yX={implementation:cJ,Node:M_};var lJ=l({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:n2},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 A_ extends V1{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 gX={implementation:lJ,Node:A_};var oJ=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:r2("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 R_ extends V1{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 pX={implementation:oJ,Node:R_};var iJ=l({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:n2},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 w_ extends V1{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 mX={implementation:iJ,Node:w_};var nJ=l({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Z8("minLength")}},reduce:(X)=>X.rule===0?N.intrinsic.unknown:void 0,normalize:r2("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 N_ extends V1{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 uX={implementation:nJ,Node:N_};var I_={min:mX.implementation,max:gX.implementation,minLength:uX.implementation,maxLength:pX.implementation,exactLength:yX.implementation,after:kX.implementation,before:bX.implementation},K_={min:mX.Node,max:gX.Node,minLength:uX.Node,maxLength:pX.Node,exactLength:yX.Node,after:kX.Node,before:bX.Node};var rJ=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 B_ 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 dX={implementation:rJ,Node:B_};var d8=(X,Y)=>{let Z=sJ(X);if(Y&&!Y.includes(Z))return w(`Root of kind ${Z} should be one of ${Y}`);return Z},sJ=(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 w(T_(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 l2)))return"intersection";if("proto"in X)return"proto";if("domain"in X)return"domain";return w(T_(X))},T_=(X)=>`${c(X)} is not a valid type schema`,C_={},tJ=(X)=>Q0(X)?X.map((Y)=>Y.collapsibleJson):X.collapsibleJson,a0={};N.nodesByRegisteredId=a0;var cX=(X)=>{return C_[X]??=0,`${X}${++C_[X]}`},lX=(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=OX(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 w(`Key ${z} is not valid on ${X.kind} schema`);let O=F.parse?F.parse(J[1],X):J[1];if(O!==O1&&(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 aJ(J,$)}}return oX({id:X.id,kind:X.kind,inner:_,meta:$,$:X.$})},oX=({id:X,kind:Y,inner:Z,meta:_,$:G,ignoreCache:W})=>{let $=_8[Y],H=OX(Z),Q=[],J={};for(let[j,P]of H){let h=$.keys[j],i=h.serialize??(h.child?tJ: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=a2(F,"description",!0);J=a2(J,$.collapsibleKey,!1);let O=JSON.stringify({kind:Y,...J});z=a2(z,$.collapsibleKey,!1);let D=a2(z,$.collapsibleKey,!0),A=JSON.stringify({kind:Y,...z});if(G.nodesByHash[A]&&!W)return G.nodesByHash[A];let R={id:X,kind:Y,impl:$,inner:Z,innerEntries:H,innerJson:J,innerHash:O,meta:_,metaJson:F,json:z,hash:A,collapsibleJson:D,children:Q};if(Y!=="intersection"){for(let j in Z)if(j!=="in"&&j!=="out")R[j]=Z[j]}let v=new j_[Y](R,G);return G.nodesByHash[A]=v},q_=(X,Y)=>{if(X.id===Y)return X;if(E0(a0[Y]))e(`Unexpected attempt to overwrite node id ${Y}`);return oX({id:Y,kind:X.kind,inner:X.inner,meta:X.meta,$:X.$,ignoreCache:!0})},aJ=(X,Y,Z)=>{if(Z&&E0(a0[Z]))e(`Unexpected attempt to overwrite node id ${Z}`);return oX({id:Z??cX(Y.alias??X.kind),kind:X.kind,inner:X.inner,meta:Y,$:X.$})},a2=(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:w(iX(X.default,Y.default)):X.default:Y.hasDefault()?Y.default:O1;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=s(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 iX=(X,Y)=>`Invalid intersection of default values ${c(X)} & ${c(Y)}`;var eJ=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 S_ 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=YQ(this);defaultValueMorphRef=this.defaultValueMorph&&N0(this.defaultValueMorph)}var o8={implementation:eJ,Node:S_},XQ={},YQ=(X)=>{if(!X.hasDefault())return;let Y=`{${X.compiledKey}: ${X.value.id} = ${A1(X.default)}}`;return XQ[Y]??=nX(X.key,X.value,X.default)},nX=(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")&&!_)w(ZQ(Z));let G=X.in(_?Y():Y);if(G instanceof W1){if(Z===null)w(`Default ${G.summary}`);let W=G.transform(($)=>$.transform((H)=>({...H,prefixPath:[Z]})));w(`Default for ${W.summary}`)}return Y},ZQ=(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 w(`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 w(_Q);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=qX(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)w(vX(`keyof ${this.expression}`));return this._keyof=this.$.finalize(X)}get props(){if(this.branches.length!==1)return w(GQ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(X){let Y=this.$.parseDefinition(X);return this.$.schema(Y.distribute((Z)=>this.applyStructuralOperation("merge",[P_(Z)??w(v_("merge",Z.expression))])))}applyStructuralOperation(X,Y){return this.distribute((Z)=>{if(Z.equals(N.intrinsic.object)&&X!=="merge")return Z;let _=P_(Z);if(!_)w(v_(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:
22
+ `);class f1{path=[];errors=new H1(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 X4(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 A4(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 A4){this.errors.add($);break}if($ instanceof H1){if(!W)this.errors.merge($);this.queuedMorphs=[];break}if(_===void 0)this.root=$;else _[Z]=$;this.applyQueuedMorphs()}}}var J1=(X,Y,Z)=>{if(!Z)return Y();Z.path.push(X);let _=Y();return Z.path.pop(),_};class u8 extends $1{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.hasKind("sequence")&&this.inner.defaultables!==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)=>fJ(_,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)=>U_(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 f1(_,this.$.resolvedConfig)):(_)=>this.traverseAllows(_)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Y,Z)=>{if(this.allows(Y))return Y;let _=new f1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)};case"contextual":return(Y,Z)=>{let _=new f1(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 f1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,e(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=xJ(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=e4(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.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter("rawIn",this.getIo("in"))}get out(){return this.cacheGetter("out",this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter("rawOut",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==="in"?$.rawIn:$.rawOut):X==="in"?W.rawIn:W.rawOut}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(!v1(X,this.kind))C4(`${this.kind} node was not one of asserted kinds ${X}`);return this}isBasis(){return v1($_,this.kind)}isConstraint(){return v1(n2,this.kind)}isStructural(){return v1(s4,this.kind)}isRefinement(){return v1(SX,this.kind)}isRoot(){return v1(t4,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=m8.normalize(X);return this._select(Y)}_select(X){let Y=m8.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 m8.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")&&!o1(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=m8.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&&E4(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 m8={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(F_(Y,Z));return X},find:(X)=>X[0],assertFind:(X,Y,Z)=>{if(X.length===0)C4(F_(Y,Z));return X[0]}},normalize:(X)=>typeof X==="function"?{boundary:"references",method:"filter",where:X}:typeof X==="string"?f0(X,m8.applyBoundary)?{method:"filter",boundary:X}:{boundary:"references",method:"filter",kind:X}:{boundary:"references",method:"filter",...X}},F_=(X,Y)=>`${X} had no references matching ${c(Y)}.`,PJ=(X)=>X4(X,{stringifyNonKey:(Y)=>Y.expression}),vJ=/"(\$ark\.[^"]+)"/g,xJ=(X)=>JSON.stringify(X).replaceAll(vJ,"$1"),h1=(X,Y)=>({path:X,node:Y,propString:PJ(X)}),U_=(X,Y)=>X.propString===Y.propString&&X.node.equals(Y.node),xX=(X,Y)=>l1(X,Y,{isEqual:U_}),fJ=(X,Y)=>l1(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],_=X4(X);return hX(`Intersection${_&&` at ${_}`} of ${E_(Y,Z)}`)}return`The following intersections result in unsatisfiable types:
23
+ \u2022 ${this.map(({path:X,l:Y,r:Z})=>`${X}: ${E_(Y,Z)}`).join(`
24
+ \u2022 `)}`}throw(){return M(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 E_=(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 X8={},Q1=(X,Y,Z)=>O0(X,Y,{$:Z,invert:!1,pipe:!1}),d8=(X,Y,Z)=>O0(X,Y,{$:Z,invert:!1,pipe:!0}),O0=(X,Y,Z)=>{let _=Z.pipe?"|>":"&",G=`${X.hash}${_}${Y.hash}`;if(X8[G]!==void 0)return X8[G];if(!Z.pipe){let H=`${Y.hash}${_}${X.hash}`;if(X8[H]!==void 0){let Q=X8[H],J=Q instanceof C?Q.invert():Q;return X8[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(...t4)?hJ(X,Y,Z):kX(X,Y,Z);if(E0($)){if(X.equals($))$=X;else if(Y.equals($))$=Y}return X8[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}},hJ=(X,Y,Z)=>X.includesTransform||Y.includesTransform?Z.invert?O_(Y,X,Z):O_(X,Y,Z):kX(X,Y,Z),O_=(X,Y,Z)=>X.distribute((_)=>kJ(_,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.rawIn.equals(G[Q].rawIn)))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.rawIn.configure(W,"self")})}let $={branches:G};if(W)$.meta=W;return Z.$.parseSchema($)}),kJ=(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.rawIn,Z);if(G instanceof C)return G;return Z.$.node("morph",{morphs:[Y],in:G})}return Z.$.node("morph",{morphs:[Y],in:X})};class w1 extends u8{constructor(X,Y){super(X,Y);Object.defineProperty(this,t0,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(X){return Q1(this,X,this.$)}}class Z4 extends w1{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(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return L4(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()?[_]:_},Y8=(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,bJ(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(G.isRoot())return X.roots.push(G),X.l.splice(_),Y8(X);if(!Z)X.l[_]=G,Z=!0;else if(!X.l.includes(G))return e(`Unexpectedly encountered multiple distinct intersection results for refinement ${Y}`)}if(!Z)X.l.push(Y);if(X.kind==="intersection"){if(Y.impliedSiblings)for(let _ of Y.impliedSiblings)l1(X.r,_)}return Y8(X)},Z8=(X)=>{return Object.entries(X).flatMap(([Z,_])=>(Z in r2)?_:[]).sort((Z,_)=>Z.precedence<_.precedence?-1:Z.precedence>_.precedence?1:Z.kind==="predicate"&&_.kind==="predicate"?0:Z.hash<_.hash?-1:1)},bJ=(X)=>{let Y={};for(let Z of X)if(Z.hasOpenIntersection())Y[Z.kind]=s(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},V_=(...X)=>M(D_(...X)),D_=(X,Y,Z)=>{let _=Z.hasKind("morph")?"a morph":Z.isUnknown()?"unknown":Z.exclude(Y).defaultShortDescription;return`${c5(X)} operand must be ${Y.description} (was ${_})`};var L_=(X,Y,Z)=>new M4(X,Y,Z,Z,null);class t2 extends $1{}class M4 extends $1{[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]))M(yJ(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 t2}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:Y_(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 yJ=(X,Y,Z)=>`${X} must be assignable to ${Y} (was ${Z})`;var gJ=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 A_ extends w1{serializedPredicate=N0(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=L4(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:gJ,Node:A_};var pJ=l({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(X)=>Number.isInteger(X)?X:M(mJ(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/uJ(X.rule,Y.rule))})},obviatesBasisDescription:!0});class M_ extends Z4{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:pJ,Node:M_};var mJ=(X)=>`divisor must be an integer (was ${X})`,uJ=(X,Y)=>{let Z,_=X,G=Y;while(G!==0)Z=G,G=_%G,_=Z;return _};class D1 extends Z4{boundOperandKind=oJ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=iJ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${dJ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?nJ(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 dJ={"<":">=","<=":">",">":"<=",">=":"<"},cJ={min:"max",minLength:"maxLength",after:"before"},a2={parse:(X)=>X||void 0},e2=(X)=>(Y)=>{if(typeof Y==="number")return{rule:Y};let{exclusive:Z,..._}=Y;return Z?{..._,rule:X==="minLength"?_.rule+1:_.rule-1}:_},X6=(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}:_},Y6=(X)=>typeof X==="string"||typeof X==="number"?new Date(X):X,lJ=(X,Y)=>`${X} bound must be a positive integer (was ${Y})`,_8=(X)=>(Y)=>{if(!Number.isInteger(Y)||Y<0)M(lJ(X,Y));return Y},oJ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},iJ=(X,Y)=>`${f0(X,cJ)?">":"<"}${Y?"":"="}`,nJ=(X)=>typeof X==="string"?X:new Date(X).toLocaleString(),R_=(X)=>`Bounded expression ${X} must be exactly one of number, string, Array, or Date`;var rJ=l({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Y6,serialize:(X)=>X.toISOString()}},normalize:X6("after"),defaults:{description:(X)=>`${X.collapsibleLimitString} or later`,actual:v4},intersections:{after:(X,Y)=>X.isStricterThan(Y)?X:Y}});class w_ extends D1{impliedBasis=N.intrinsic.Date.internal;collapsibleLimitString=v4(this.rule);traverseAllows=(X)=>X>=this.rule;reduceJsonSchema(X,Y){return Y.fallback.date({code:"date",base:X,after:this.rule})}}var gX={implementation:rJ,Node:w_};var sJ=l({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Y6,serialize:(X)=>X.toISOString()}},normalize:X6("before"),defaults:{description:(X)=>`${X.collapsibleLimitString} or earlier`,actual:v4},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 N_ extends D1{collapsibleLimitString=v4(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:sJ,Node:N_};var tJ=l({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:_8("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 I_ extends Z4{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 A0.throwInternalOperandError("exactLength",X)}}}var mX={implementation:tJ,Node:I_};var aJ=l({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:a2},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 K_ 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:aJ,Node:K_};var eJ=l({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_8("maxLength")}},reduce:(X,Y)=>X.rule===0?Y.node("exactLength",X):void 0,normalize:e2("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 B_ 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 A0.throwInternalOperandError("maxLength",X)}}}var dX={implementation:eJ,Node:B_};var XQ=l({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:a2},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 T_ 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:XQ,Node:T_};var YQ=l({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_8("minLength")}},reduce:(X)=>X.rule===0?N.intrinsic.unknown:void 0,normalize:e2("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 C_ 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 A0.throwInternalOperandError("minLength",X)}}}var lX={implementation:YQ,Node:C_};var q_={min:cX.implementation,max:uX.implementation,minLength:lX.implementation,maxLength:dX.implementation,exactLength:mX.implementation,after:gX.implementation,before:pX.implementation},j_={min:cX.Node,max:uX.Node,minLength:lX.Node,maxLength:dX.Node,exactLength:mX.Node,after:gX.Node,before:pX.Node};var ZQ=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 S_ extends Z4{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:ZQ,Node:S_};var c8=(X,Y)=>{let Z=_Q(X);if(Y&&!Y.includes(Z))return M(`Root of kind ${Z} should be one of ${Y}`);return Z},_Q=(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 M(P_(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 r2)))return"intersection";if("proto"in X)return"proto";if("domain"in X)return"domain";return M(P_(X))},P_=(X)=>`${c(X)} is not a valid type schema`,v_={},GQ=(X)=>Q0(X)?X.map((Y)=>Y.collapsibleJson):X.collapsibleJson,a0={};N.nodesByRegisteredId=a0;var iX=(X)=>{return v_[X]??=0,`${X}${++v_[X]}`},nX=(X)=>{let Y=G8[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])=>a4(J)?a4(z)?e4(J)-e4(z):1:a4(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 M(`Key ${z} is not valid on ${X.kind} schema`);let O=F.parse?F.parse(J[1],X):J[1];if(O!==W1&&(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 WQ(J,$)}}return rX({id:X.id,kind:X.kind,inner:_,meta:$,$:X.$})},rX=({id:X,kind:Y,inner:Z,meta:_,$:G,ignoreCache:W})=>{let $=G8[Y],H=LX(Z),Q=[],J={};for(let[j,P]of H){let h=$.keys[j],i=h.serialize??(h.child?GQ:R1);if(J[j]=i(P),h.child===!0){let g=P;if(Q0(g))Q.push(...g);else Q.push(g)}else if(typeof h.child==="function")Q.push(...h.child(P))}if($.finalizeInnerJson)J=$.finalizeInnerJson(J);let z={...J},F={};if(!o1(_))F=d(_,(j,P)=>[j,j==="examples"?P:R1(P)]),z.meta=Z6(F,"description",!0);J=Z6(J,$.collapsibleKey,!1);let O=JSON.stringify({kind:Y,...J});z=Z6(z,$.collapsibleKey,!1);let D=Z6(z,$.collapsibleKey,!0),w=JSON.stringify({kind:Y,...z});if(G.nodesByHash[w]&&!W)return G.nodesByHash[w];let R={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")R[j]=Z[j]}let v=new f_[Y](R,G);return G.nodesByHash[w]=v},x_=(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})},WQ=(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.$})},Z6=(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 l8=(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:M(sX(X.default,Y.default)):X.default:Y.hasDefault()?Y.default:W1;return Z.$.node("optional",{key:_,value:G,default:$})};class o8 extends w1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=N.intrinsic.object.internal;serializedKey=Y4(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=s(this.value.flatRefs.map((X)=>h1([this.key,...X.path],X.node)),h1([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 J1(this.key,()=>this.value.traverseAllows(X[this.key],Y),Y);return this.optional};traverseApply=(X,Y)=>{if(this.key in X)J1(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 $Q=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:l8}});class h_ extends o8{constructor(...X){super(...X);if("default"in this.inner)n8(this.value,this.inner.default,this.key)}get rawIn(){let X=super.rawIn;if(!this.hasDefault())return X;return this.$.node("optional",u2(X.inner,{default:!0}),{prereduced:!0})}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=JQ(this);defaultValueMorphRef=this.defaultValueMorph&&N0(this.defaultValueMorph)}var i8={implementation:$Q,Node:h_},HQ={},JQ=(X)=>{if(!X.hasDefault())return;let Y=`{${X.compiledKey}: ${X.value.id} = ${R1(X.default)}}`;return HQ[Y]??=tX(X.key,X.value,X.default)},tX=(X,Y,Z)=>{if(typeof Z==="function")return Y.includesTransform?(G,W)=>{return J1(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 J1(X,()=>Y(G[X]=Z,W),W),G}:(G)=>{return G[X]=_,G}},n8=(X,Y,Z)=>{let _=O4(Y);if(_1(Y,"object")&&!_)M(QQ(Z));let G=X.in(_?Y():Y);if(G instanceof H1){if(Z===null)M(`Default ${G.summary}`);let W=G.transform(($)=>$.transform((H)=>({...H,prefixPath:[Z]})));M(`Default for ${W.summary}`)}return Y},QQ=(X)=>{return`Non-primitive default ${X===null?"":typeof X==="number"?`for value at [${X}] `:`for ${Y4(X)} `}must be specified as a function like () => ({my: 'object'})`};class N1 extends u8{constructor(X,Y){super(X,Y);Object.defineProperty(this,t0,{value:"root",enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(X)=>{let Y=this(X);if(Y instanceof H1)return Y;return{value:Y}},toJSONSchema:(X)=>{if(X.target&&X.target!=="draft-2020-12")return M(`JSONSchema target '${X.target}' is not supported (must be "draft-2020-12")`);if(X.io==="input")return this.rawIn.toJsonSchema();return this.rawOut.toJsonSchema()}}}as(){return this}brand(X){if(X==="")return M(zQ);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 Q1(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)M(hX(`keyof ${this.expression}`));return this._keyof=this.$.finalize(X)}get props(){if(this.branches.length!==1)return M(FQ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(X){let Y=this.$.parseDefinition(X);return this.$.schema(Y.distribute((Z)=>this.applyStructuralOperation("merge",[k_(Z)??M(b_("merge",Z.expression))])))}applyStructuralOperation(X,Y){return this.distribute((Z)=>{if(Z.equals(N.intrinsic.object)&&X!=="merge")return Z;let _=k_(Z);if(!_)M(b_(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",{domain:"object",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 n8(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
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 z_(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"?j5(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 _Q="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,P_=(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},GQ=(X)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
- ${X}`,v_=(X,Y)=>`${X} operand must be an object (was ${Y})`;var o1=(X,Y)=>d(o2(X),(Z,_)=>[_,Y]);var WQ=(X)=>typeof X==="string"?{reference:X}:X,x_=(X)=>X instanceof C?N.intrinsic.never.internal:X,$Q=l({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(X)=>X.startsWith("$")?X:`$ark.${X}`},resolve:{}},normalize:WQ,defaults:{description:(X)=>X.reference},intersections:{alias:(X,Y,Z)=>Z.$.lazilyResolve(()=>x_(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(()=>x_(O0(X.resolution,Y,Z)),`${X.reference}${Z.pipe?"=>":"&"}${Y.id}`)})}});class f_ 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 w(HQ(Y.id,Z));Z.push(Y.id),Y=a0[Y.id]}if(!f(Y,"root"))return e(`Unexpected resolution for reference ${this.reference}
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=d8(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:X==="in"?this.rawIn:this.rawOut;if(G.hasKind("morph")||_.impliedBasis&&!G.extends(_.impliedBasis))return V_(Y,_.impliedBasis,this);let W=this.$.node("intersection",{[_.kind]:_}),$=X==="out"?d8(this,W,this.$):Q1(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"?u2(G,{undeclared:1}):{...G,undeclared:Y}:G,Z?void 0:{shouldTransform:(_)=>!v1(s4,_.kind)}))}hasEqualMorphs(X){if(!this.includesTransform&&!X.includesTransform)return!0;if(!a1(this.shallowMorphs,X.shallowMorphs))return!1;if(!a1(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",W8(X))}lessThan(X){return this.constrain("max",W8(X))}atLeastLength(X){return this.constrain("minLength",X)}atMostLength(X){return this.constrain("maxLength",X)}moreThanLength(X){return this.constrain("minLength",W8(X))}lessThanLength(X){return this.constrain("maxLength",W8(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",W8(X))}earlierThan(X){return this.constrain("before",W8(X))}}var zQ="Expected a non-empty brand name after #",W8=(X)=>typeof X==="object"&&!(X instanceof Date)?{...X,exclusive:!0}:{rule:X,exclusive:!0},r8=(X,Y)=>f(Y,"root")?f(X,"root")?X.extends(Y):Y.allows(X):f(X,"root")?X.hasUnit(Y):Y===X,k_=(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},FQ=(X)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
+ ${X}`,b_=(X,Y)=>`${X} operand must be an object (was ${Y})`;var i1=(X,Y)=>d(s2(X),(Z,_)=>[_,Y]);var UQ=(X)=>typeof X==="string"?{reference:X}:X,y_=(X)=>X instanceof C?N.intrinsic.never.internal:X,EQ=l({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(X)=>X.startsWith("$")?X:`$ark.${X}`},resolve:{}},normalize:UQ,defaults:{description:(X)=>X.reference},intersections:{alias:(X,Y,Z)=>Z.$.lazilyResolve(()=>y_(O0(X.resolution,Y.resolution,Z)),`${X.reference}${Z.pipe?"=>":"&"}${Y.reference}`),...i1("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(()=>y_(O0(X.resolution,Y,Z)),`${X.reference}${Z.pipe?"=>":"&"}${Y.id}`)})}});class g_ extends N1{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 M(OQ(Y.id,Z));Z.push(Y.id),Y=a0[Y.id]}if(!f(Y,"root"))return e(`Unexpected resolution for reference ${this.reference}
28
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]=s(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]=s(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 HQ=(X,Y)=>`Alias '${X}' has a shallow resolution cycle: ${[...Y,X].join("->")}`,r8={implementation:$Q,Node:f_};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 JQ=l({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(X)=>typeof X==="string"?{domain:X}:i4(X,"numberAllowsNaN")&&X.domain!=="number"?w(e2.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 h_ 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 e2={implementation:JQ,Node:h_,writeBadAllowNanMessage:(X)=>`numberAllowsNaN may only be specified with domain "number" (was ${X})`};var QQ=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($,Z_)){if(_)w(`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)=>k_({},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(`
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]=s(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]=s(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 OQ=(X,Y)=>`Alias '${X}' has a shallow resolution cycle: ${[...Y,X].join("->")}`,s8={implementation:EQ,Node:g_};class x4 extends N1{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 L4(this.errorContext)}compile(X){if(X.traversalKind==="Allows")X.return(this.compiledCondition);else X.if(this.compiledNegation,()=>X.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}var VQ=l({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(X)=>typeof X==="string"?{domain:X}:n4(X,"numberAllowsNaN")&&X.domain!=="number"?M(_6.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 p_ extends x4{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 _6={implementation:VQ,Node:p_,writeBadAllowNanMessage:(X)=>`numberAllowsNaN may only be specified with domain "number" (was ${X})`};var DQ=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($,H_)){if(_)M(`Flattened structure key ${$} cannot be specified alongside a root 'structure' key.`);return G[$]=H,[]}return[$,H]});if(f(G,"constraint")||!o1(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)=>m_({},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.prestructurals.some((Z)=>Z.impl.obviatesBasisDescription))Y.push(X.basis.description);if(X.prestructurals.length){let Z=X.prestructurals.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
30
  \u25E6 `)}`,problem:(X)=>`(${X.actual}) must be...
31
- ${X.expected}`},intersections:{intersection:(X,Y,Z)=>k_(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 b_ extends w1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((X)=>X.isRefinement());structure=this.inner.structure;expression=zQ(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 rX={implementation:QQ,Node:b_},zQ=(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},k_=(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 FQ=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:N0(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 w(UQ(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 y_ extends w1{serializedMorphs=this.morphs.map(N0);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 sX={implementation:FQ,Node:y_},UQ=(X,Y)=>`The intersection of distinct morphs at a single path is indeterminate:
31
+ ${X.expected}`},intersections:{intersection:(X,Y,Z)=>m_(X.inner,Y.inner,Z),...i1("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 u_ extends N1{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter((X)=>{if(!X.isRefinement())return!1;if(v1(jX,X.kind))this.prestructurals.push(X);return!0});structure=this.inner.structure;expression=LQ(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.prestructurals.length){for(let _=0;_<this.prestructurals.length-1;_++)if(this.prestructurals[_].traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>Z)return;if(this.prestructurals.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.prestructurals.length){for(let Y=0;Y<this.prestructurals.length-1;Y++)X.check(this.prestructurals[Y]),X.returnIfFailFast();if(X.check(this.prestructurals.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:DQ,Node:u_},LQ=(X)=>{if(X.structure?.expression)return X.structure.expression;let Y=X.basis&&!X.prestructurals.some((G)=>G.impl.obviatesBasisExpression)?X.basis.nestableExpression:"",Z=X.prestructurals.map((G)=>G.expression).join(" & "),_=`${Y}${Y?" ":""}${Z}`;if(_==="Array == 0")return"[]";return _||"unknown"},m_=(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 Y8({kind:"intersection",baseInner:_,l:Z8(X),r:Z8(Y),roots:[],ctx:Z})};var AQ=l({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)},morphs:{parse:E4,serialize:(X)=>X.map((Y)=>f(Y,"root")?Y.json:N0(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.rawIn.description} to ${X.rawOut?.description??"unknown"}`},intersections:{morph:(X,Y,Z)=>{if(!X.hasEqualMorphs(Y))return M(MQ(X.expression,Y.expression));let _=O0(X.rawIn,Y.rawIn,Z);if(_ instanceof C)return _;let G={morphs:X.morphs};if(X.declaredIn||Y.declaredIn){let W=O0(X.rawIn,Y.rawIn,Z);if(W instanceof C)return W.throw();else G.declaredIn=W}if(X.declaredOut||Y.declaredOut){let W=O0(X.rawOut,Y.rawOut,Z);if(W instanceof C)return W.throw();else G.declaredOut=W}return _.distribute((W)=>Z.$.node("morph",{...G,in:W}),Z.$.parseSchema)},...i1("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 d_ extends N1{serializedMorphs=this.morphs.map(N0);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.rawOut:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get rawIn(){return this.declaredIn??this.inner.in?.rawIn??N.intrinsic.unknown.internal}get rawOut(){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.rawIn.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.rawOut.expression}>`;get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(X){return X.fallback.morph({code:"morph",base:this.rawIn.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 a1(this.morphs,X.morphs,{isEqual:(Y,Z)=>Y===Z||f(Y,"root")&&f(Z,"root")&&Y.equals(Z)})}}var eX={implementation:AQ,Node:d_},MQ=(X,Y)=>`The intersection of distinct morphs at a single path is indeterminate:
32
32
  Left: ${X}
33
- Right: ${Y}`;var EQ=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")w(s8.writeInvalidSchemaMessage(Y.proto));if(i4(Y,"dateAllowsInvalid")&&Y.proto!==Date)w(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?x5[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:AX(X.proto,Y.proto)?X:AX(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 g_ 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:EQ,Node:g_,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 OQ=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=KQ(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=B5(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)w(TQ(X.expression,Y.expression));if(_=tX(Y.branches,X.branches,Z),_ instanceof C)_.invert()}else _=tX(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 _=tX(X.branches,[Y],Z);if(_ instanceof C)return _;if(_.length===1)return _[0];return Z.$.parseSchema(X.ordered?{branches:_,ordered:!0}:{branches:_})})}});class u_ 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?wQ(this.discriminant):null;expression=this.distribute((X)=>X.nestableExpression,IQ);createBranchedOptimisticRootApply(){return(X,Y)=>{let Z=this.traverseOptimistic(X);if(Z!==O1)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 O1};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?`${N0(z.contextFreeMorph)}(${X.data})`:X.data} : "${O1}"`:X.invoke(z)}`)}return X}),X.traversalKind==="Allows"){X.return(G?`"${O1}"`:!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"?N0(J):JSON.stringify(J)),H=JSON.stringify(W),Q=this.discriminant.kind==="domain"?`${AQ}[${Y}]`:`${RQ}(${Y})`;X.line(`ctx.errorFromNodeContext({
33
+ Right: ${Y}`;var RQ=l({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(X)=>v8(X)??R1(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")M(t8.writeInvalidSchemaMessage(Y.proto));if(n4(Y,"dateAllowsInvalid")&&Y.proto!==Date)M(t8.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?b5[X.builtinName]:`an instance of ${X.proto.name}`,actual:(X)=>X instanceof Date&&X.toString()==="Invalid Date"?"an invalid Date":P8(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 c_ extends x4{builtinName=v8(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 t8={implementation:RQ,Node:c_,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 wQ=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.rawIn.rawOr(W.rawIn)})}}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=PQ(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,$8),expected:(X)=>{let Y=j5(X.errors,"propString"),Z=Object.entries(Y).map(([_,G])=>{let W=[];for(let Q of G)l1(W,Q.expected);let $=$8(W),H=G.every((Q)=>Q.actual===G[0].actual)?G[0].actual:c(G[0].data);return`${_&&`${_} `}must be ${$}${H&&` (was ${H})`}`});return $8(Z)},problem:(X)=>X.expected,message:(X)=>{if(X.problem[0]==="[")return`value at ${X.problem}`;return 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)M(xQ(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:_})},...i1("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 i_ extends N1{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.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?qQ(this.discriminant):null;expression=this.distribute((X)=>X.nestableExpression,SQ);createBranchedOptimisticRootApply(){return(X,Y)=>{let Z=this.traverseOptimistic(X);if(Z!==W1)return Z;let _=new f1(X,this.$.resolvedConfig);return this.traverseApply(X,_),_.finalize(Y)}}get shallowMorphs(){return this.branches.reduce((X,Y)=>l1(X,Y.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((X)=>X.defaultShortDescription,$8)}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&&n4(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 W1};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}`,O;if(z===!0)O=G?"data":"true";else if(G)if(z.rootApplyStrategy==="branchedOptimistic")O=X.invoke(z,{kind:"Optimistic"});else if(z.contextFreeMorph)O=`${X.invoke(z)} ? ${N0(z.contextFreeMorph)}(data) : "${W1}"`;else O=`${X.invoke(z)} ? data : "${W1}"`;else O=X.invoke(z);X.line(`${F}: return ${O}`)}return X}),X.traversalKind==="Allows"){X.return(G?`"${W1}"`:!1);return}let W=$8(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"?N0(J):JSON.stringify(J)),H=JSON.stringify(W),Q=this.discriminant.kind==="domain"?`${TQ}[${Y}]`:`${CQ}(${Y})`;X.line(`ctx.errorFromNodeContext({
34
34
  code: "predicate",
35
35
  expected: ${H},
36
36
  actual: ${Q},
37
37
  relativePath: [${$}],
38
38
  meta: ${this.compiledMeta}
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?`${N0(Z.contextFreeMorph)}(${X.data})`:X.data:!0));X.return(Y?`"${O1}"`:!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:A}=J;z=`"${typeof D==="string"?D:D.domain}"`,F=`"${typeof A==="string"?A:A.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?LQ(X,this.branches):X;if(!Y.length)return null;let Z=VQ(Y,this),_={};for(let G in Z.best.cases){let W=DQ(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 VQ=(X,Y)=>{let Z=X.sort((W,$)=>Object.keys($.cases).length-Object.keys(W.cases).length)[0],_={kind:Z.kind,path:Z.path,optionallyChainedPropString:d_(Z.path)},G=Y.branches.map((W,$)=>({originalIndex:$,branch:W}));return{best:Z,location:_,defaultEntries:G,node:Y}},DQ=(X,Y)=>{let Z=X.best.cases[Y],_=MQ(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=p_(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=p_(H.branch,X.location);G?.push({originalIndex:H.originalIndex,branch:Q})}W.push(H)}}return X.defaultEntries=W,G},LQ=(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})},MQ=(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:[...I5(W).map(($)=>({})),_]}:{domain:"object",required:[{key:W,value:_}]})}return _},d_=(X)=>X.reduce((Y,Z)=>Y+TX(Z,!0),"data"),AQ=N0(T5),RQ=N0(c),aX={implementation:OQ,Node:u_},wQ=(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])}),NQ={delimiter:" | ",finalDelimiter:" | "},IQ=(X)=>W8(X,NQ),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?_:""}${$}`},tX=(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},KQ=({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)BQ(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])},BQ=(X,Y)=>{if(!X.includesTransform&&!Y.includesTransform)return;if(!t1(X.shallowMorphs,Y.shallowMorphs))w(m_(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)}))w(m_(X.expression,Y.expression))},p_=(X,Y)=>X.transform((Z,_)=>{if(Z==="domain"||Z==="unit")return null;return _},{shouldTransform:(Z,_)=>{let G=d_(_.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"}}),m_=(X,Y)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
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?`${N0(Z.contextFreeMorph)}(data)`:"data":!0));X.return(Y?`"${W1}"`:!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,$)=>[`${$.rawIn.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=Q1(W.rawIn,H.rawIn,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)=>a1(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=l1(O.cases[z].branchIndices,G);else O.cases[z]??={branchIndices:[G],condition:J.l};if(O.cases[F])O.cases[F].branchIndices=l1(O.cases[F].branchIndices,$);else O.cases[F]??={branchIndices:[$],condition:J.r}}}}}let Y=this.ordered?KQ(X,this.branches):X;if(!Y.length)return null;let Z=NQ(Y,this),_={};for(let G in Z.best.cases){let W=IQ(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 NQ=(X,Y)=>{let _=X.sort(($,H)=>$.path.length===H.path.length?Object.keys(H.cases).length-Object.keys($.cases).length:$.path.length-H.path.length)[0],G={kind:_.kind,path:_.path,optionallyChainedPropString:n_(_.path)},W=Y.branches.map(($,H)=>({originalIndex:H,branch:$}));return{best:_,location:G,defaultEntries:W,node:Y}},IQ=(X,Y)=>{let Z=X.best.cases[Y],_=BQ(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=l_(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.rawIn.overlaps(_)){let Q=l_(H.branch,X.location);G?.push({originalIndex:H.originalIndex,branch:Q})}W.push(H)}}return X.defaultEntries=W,G},KQ=(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})},BQ=(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:[...C5(W).map(($)=>({})),_]}:{domain:"object",required:[{key:W,value:_}]})}return _},n_=(X)=>X.reduce((Y,Z)=>Y+qX(Z,!0),"data"),TQ=N0(S5),CQ=N0(c),YY={implementation:wQ,Node:i_},qQ=(X)=>({kind:X.kind,path:X.path.map((Y)=>typeof Y==="string"?Y:Y4(Y)),cases:d(X.cases,(Y,Z)=>[Y,Z===!0?Z:Z.hasKind("union")&&Z.discriminantJson?Z.discriminantJson:Z.json])}),jQ={delimiter:" | ",finalDelimiter:" | "},SQ=(X)=>$8(X,jQ),$8=(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},PQ=({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=Q1(X[_].rawIn,X[G].rawIn,X[0].$);if(W instanceof C)continue;if(!Y)vQ(X[_],X[G]);if(W.equals(X[_].rawIn))Z[_]=!!Y;else if(W.equals(X[G].rawIn))Z[G]=!1}return X.filter((_,G)=>Z[G])},vQ=(X,Y)=>{if(!X.includesTransform&&!Y.includesTransform)return;if(!a1(X.shallowMorphs,Y.shallowMorphs))M(o_(X.expression,Y.expression));if(!a1(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)}))M(o_(X.expression,Y.expression))},l_=(X,Y)=>X.transform((Z,_)=>{if(Z==="domain"||Z==="unit")return null;return _},{shouldTransform:(Z,_)=>{let G=n_(_.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"}}),o_=(X,Y)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
40
40
  Left: ${X}
41
- Right: ${Y}`,TQ=(X,Y)=>`The intersection of two ordered unions is indeterminate:
41
+ Right: ${Y}`,xQ=(X,Y)=>`The intersection of two ordered unions is indeterminate:
42
42
  Left: ${X}
43
- Right: ${Y}`;var CQ=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 l_ extends v4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=c_(this.unit,this.serializedValue);compiledNegation=c_(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 eX={implementation:CQ,Node:l_},c_=(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 qQ=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 w(SQ(Z.expression));let _=Z.branches.filter((G)=>G.hasKind("unit"));if(_.length)return w(jQ(_.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 o_ extends R1{impliedBasis=N.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=s(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 XY={implementation:qQ,Node:o_},jQ=(X)=>`Index keys ${X.join(", ")} should be specified as named props.`,SQ=(X)=>`Indexed key definition '${X}' must be a string or symbol`;var PQ=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 i_ 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 YY={implementation:PQ,Node:i_};var vQ=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 w(kQ);if(X.optionals?.length||X.defaultables?.length)return w(_Y)}if(X.minVariadicLength&&!X.variadic)return w("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",n_(G[0].result)):Z.$.node("union",G.map((W)=>({proto:Array,sequence:n_(W.result)})))}}});class r_ extends R1{impliedBasis=N.intrinsic.Array.internal;tuple=hQ(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 SX(this.flatRefs,this.prevariadic.flatMap((X,Y)=>s(X.node.flatRefs.map((Z)=>f1([`${Y}`,...Z.path],Z.node)),f1([`${Y}`],X.node)))),SX(this.flatRefs,this.variadicOrPostfix.flatMap((X)=>s(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=fQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?N0(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 xQ={},fQ=(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(nX(G,W,$)),Z+=`${G}: ${W.id} = ${A1($)}, `}return Z+="]",xQ[Z]??=Y},ZY={implementation:vQ,Node:r_},hQ=(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},n_=(X)=>X.reduce((Y,Z)=>{if(Z.kind==="variadic")Y.variadic=Z.node;else if(Z.kind==="defaultables")Y.defaultables=s(Y.defaultables,[[Z.node,Z.default]]);else Y[Z.kind]=s(Y[Z.kind],Z.node);return Y},{}),_Y="A postfix required element cannot follow an optional or defaultable element",kQ="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)w(iX(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 a_=(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??"{}"},bQ=a_("description"),yQ=a_("expression"),s_=(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},gQ=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=s(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]=s(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:bQ},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=X6(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=X6(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=s_(H,$,Y);if(Q instanceof C)return Q}for(let[H,Q]of G.entries()){let J=s_(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 e_ 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=N0(this.propsByKey);expression=yQ(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 w(`Map result must have kind "required" or "optional" (was ${Z.kind})`);return Y[Z.kind]=s(Y[Z.kind],Z),Y}let G=Z.kind??_?.kind??"required",W=d(Z,($,H)=>($ in o8.implementation.keys)?[$,H]:[]);return Y[G]=s(Y[G],this.$.node(G,W)),Y},{}))}assertHasKeys(X){let Y=X.filter((Z)=>!n8(Z,this.keyof()));if(Y.length)return w(t_(this.expression,Y))}get(X,...Y){let Z,_=!1,G=dQ(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 w(cQ(G.expression,this.sequence.expression));return w(t_(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=s(Y.required,X.required);if(X.optional)Y.optional=s(Y.optional,X.optional);if(X.index)Y.index=s(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=d2(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",mQ(this))}structuralMorphRef=this.structuralMorph&&N0(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(["),uQ(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 GY={},pQ=(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},mQ=(X)=>{let Y=pQ(X);if(!Y)return;if(GY[Y])return GY[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 GY[Y]=Z},uQ=(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")})},WY={implementation:gQ,Node:e_},dQ=(X)=>{if(f(X,"root")&&X.hasKind("unit"))X=X.unit;if(typeof X==="number")X=`${X}`;return X},cQ=(X,Y)=>`${X} is not allowed as an array index on ${Y}. Use the 'nonNegativeIntegerString' keyword instead.`,X6=(X,Y,Z)=>{let[_,G]=N5(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]=s(W[H.kind],H)}if(G.length)W.index=Z.node("index",{signature:G,value:Y});return W},lQ=(X)=>f(X,"root")?X.expression:c(X),t_=(X,Y)=>`Key${Y.length===1?"":"s"} ${Y.map(lQ).join(", ")} ${Y.length===1?"does":"do"} not exist on ${X}`;var _8={...I_,alias:r8.implementation,domain:e2.implementation,unit:eX.implementation,proto:s8.implementation,union:aX.implementation,morph:sX.implementation,intersection:rX.implementation,divisor:hX.implementation,pattern:dX.implementation,predicate:fX.implementation,required:YY.implementation,optional:o8.implementation,index:XY.implementation,sequence:ZY.implementation,structure:WY.implementation};N.defaultConfig=P5(Object.assign(d(_8,(X,Y)=>[X,Y.defaults]),{jitless:b5(),clone:f5,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:M0.defaultConfig}));N.resolvedConfig=g8(N.defaultConfig,N.config);var j_={...K_,alias:r8.Node,domain:e2.Node,unit:eX.Node,proto:s8.Node,union:aX.Node,morph:sX.Node,intersection:rX.Node,divisor:hX.Node,pattern:dX.Node,predicate:fX.Node,required:YY.Node,optional:o8.Node,index:XY.Node,sequence:ZY.Node,structure:WY.Node};class $8 extends VX{get[t0](){return"module"}}var $Y=(X,Y)=>new $8(d(X,(Z,_)=>[Z,f(_,"module")?$Y(_,Y):Y.bindReference(_)]));var oQ=(X)=>Q0(X)?X:("branches"in X)&&Q0(X.branches)?X.branches:void 0,iQ=(X,Y)=>w(`Node of kind ${Y} is not valid as a ${X} definition`),X9=(X)=>`#${X} duplicates public alias ${X}`,HY={};N.ambient??={};var Y9,_9="function $",nQ=(X)=>G9(X,W9(X)),G9=(X,Y)=>{let Z=Y.write(_9,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}},W9=(X)=>new u2().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},
43
+ Right: ${Y}`;var fQ=l({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(X)=>X instanceof Date?X.toISOString():R1(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),...i1("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 s_ extends x4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=r_(this.unit,this.serializedValue);compiledNegation=r_(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:fQ,Node:s_},r_=(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 hQ=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 M(bQ(Z.expression));let _=Z.branches.filter((G)=>G.hasKind("unit"));if(_.length)return M(kQ(_.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 t_ extends w1{impliedBasis=N.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=s(this.value.flatRefs.map((X)=>h1([this.signature,...X.path],X.node)),h1([this.signature],this.value));traverseAllows=(X,Y)=>q4(X).every((Z)=>{if(this.signature.traverseAllows(Z[0],Y))return J1(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))J1(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:hQ,Node:t_},kQ=(X)=>`Index keys ${X.join(", ")} should be specified as named props.`,bQ=(X)=>`Indexed key definition '${X}' must be a string or symbol`;var yQ=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:l8,optional:l8}});class a_ extends o8{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=L4(this.errorContext)}var GY={implementation:yQ,Node:a_};var gQ=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 n8(_,Z[1],null),[_,Z[1]]})},serialize:(X)=>X.map((Y)=>[Y[0].collapsibleJson,R1(Y[1])]),reduceIo:(X,Y,Z)=>{if(X==="in"){Y.optionals=Z.map((_)=>_[0].rawIn);return}Y.prefix=Z.map((_)=>_[0].rawOut);return}},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 M(dQ);if(X.optionals?.length||X.defaultables?.length)return M($Y)}if(X.minVariadicLength&&!X.variadic)return M("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 _=a8({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",e_(G[0].result)):Z.$.node("union",G.map((W)=>({proto:Array,sequence:e_(W.result)})))}}});class Y9 extends w1{impliedBasis=N.intrinsic.Array.internal;tuple=uQ(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=t1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return xX(this.flatRefs,this.prevariadic.flatMap((X,Y)=>s(X.node.flatRefs.map((Z)=>h1([`${Y}`,...Z.path],Z.node)),h1([`${Y}`],X.node)))),xX(this.flatRefs,this.variadicOrPostfix.flatMap((X)=>s(X.flatRefs.map((Y)=>h1([N.intrinsic.nonNegativeIntegerString.internal,...Y.path],Y.node)),h1([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=mQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?N0(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++)J1(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(`${_} >= data.length`,()=>X.traversalKind==="Allows"?X.return(!0):X.return()),X.traverseKey(_,`data[${_}]`,Z)}if(this.variadic){if(this.postfix)X.const("firstPostfixIndex",`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 pQ={},mQ=(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} = ${R1($)}, `}return Z+="]",pQ[Z]??=Y},WY={implementation:gQ,Node:Y9},uQ=(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},e_=(X)=>X.reduce((Y,Z)=>{if(Z.kind==="variadic")Y.variadic=Z.node;else if(Z.kind==="defaultables")Y.defaultables=s(Y.defaultables,[[Z.node,Z.default]]);else Y[Z.kind]=s(Y[Z.kind],Z.node);return Y},{}),$Y="A postfix required element cannot follow an optional or defaultable element",dQ="A postfix element requires a variadic element",a8=(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=a8({...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=a8({...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}`,X9(Y)&&X9(_)?"required":"optional")),X.result=[...X.result,{kind:H,node:N.intrinsic.never.internal}];else if(H==="optionals"||H==="defaultables")return X;else return a8({...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)M(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 a8(X)},X9=(X)=>X.kind==="prefix"||X.kind==="postfix";var G9=(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??"{}"},cQ=G9("description"),lQ=G9("expression"),Z9=(X,Y,Z)=>{let _=X.required?"required":"optional";if(!Y.signature.allows(X.key))return null;let G=Q1(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},oQ=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=s(Y.required,Z.map((_)=>X==="in"?_.rawIn:_.rawOut));return}},optional:{child:!0,parse:i0("optional"),reduceIo:(X,Y,Z)=>{if(X==="in"){Y.optional=Z.map((_)=>_.rawIn);return}for(let _ of Z)Y[_.outProp.kind]=s(Y[_.outProp.kind],_.outProp.rawOut)}},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==="reject"){Y.undeclared="reject";return}if(X==="in")delete Y.undeclared;else Y.undeclared="reject"}}},defaults:{description:cQ},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=Q1(Q,J.signature,Z.$);if(z instanceof C)return[];let F=G6(z,J.value,Z.$);if(F.required)G.required=t1(G.required,F.required);if(F.optional)G.optional=t1(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=Q1(Q,J.signature,Z.$);if(z instanceof C)return[];let F=G6(z,J.value,Z.$);if(F.required)_.required=t1(_.required,F.required);if(F.optional)_.optional=t1(_.optional,F.optional);return F.index??[]})}let $={};if(X.undeclared||Y.undeclared)$.undeclared=X.undeclared==="reject"||Y.undeclared==="reject"?"reject":"delete";let H=Y8({kind:"structure",baseInner:$,l:Z8(_),r:Z8(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=Z9(H,$,Y);if(Q instanceof C)return Q}for(let[H,Q]of G.entries()){let J=Z9(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 W9 extends w1{impliedBasis=N.intrinsic.object.internal;impliedSiblings=this.children.flatMap((X)=>X.impliedSiblings??[]);props=t1(this.required,this.optional);propsByKey=d(this.props,(X,Y)=>[Y.key,Y]);propsByKeyReference=N0(this.propsByKey);expression=lQ(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 M(`Map result must have kind "required" or "optional" (was ${Z.kind})`);return Y[Z.kind]=s(Y[Z.kind],Z),Y}let G=Z.kind??_?.kind??"required",W=d(Z,($,H)=>($ in i8.implementation.keys)?[$,H]:[]);return Y[G]=s(Y[G],this.$.node(G,W)),Y},{}))}assertHasKeys(X){let Y=X.filter((Z)=>!r8(Z,this.keyof()));if(Y.length)return M(_9(this.expression,Y))}get(X,...Y){let Z,_=!1,G=sQ(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(r8(G,$.signature))Z=Z?.and($.value)??$.value}if(this.sequence&&r8(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 M(tQ(G.expression,this.sequence.expression));return M(_9(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=s(Y.required,X.required);if(X.optional)Y.optional=s(Y.optional,X.optional);if(X.index)Y.index=s(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=i2(this.inner),_=(G)=>{let W=Y.some(($)=>r8(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(!J1($,()=>H.value.traverseAllows(Y[$],Z),Z))return!1}else if(J1($,()=>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",nQ(this))}structuralMorphRef=this.structuralMorph&&N0(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(["),rQ(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 A0.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.rawIn.toJsonSchemaRecurse(Y),out:G.rawOut.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={},iQ=(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},nQ=(X)=>{let Y=iQ(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},rQ=(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:oQ,Node:W9},sQ=(X)=>{if(f(X,"root")&&X.hasKind("unit"))X=X.unit;if(typeof X==="number")X=`${X}`;return X},tQ=(X,Y)=>`${X} is not allowed as an array index on ${Y}. Use the 'nonNegativeIntegerString' keyword instead.`,G6=(X,Y,Z)=>{let[_,G]=T5(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]=s(W[H.kind],H)}if(G.length)W.index=Z.node("index",{signature:G,value:Y});return W},aQ=(X)=>f(X,"root")?X.expression:c(X),_9=(X,Y)=>`Key${Y.length===1?"":"s"} ${Y.map(aQ).join(", ")} ${Y.length===1?"does":"do"} not exist on ${X}`;var G8={...q_,alias:s8.implementation,domain:_6.implementation,unit:ZY.implementation,proto:t8.implementation,union:YY.implementation,morph:eX.implementation,intersection:aX.implementation,divisor:yX.implementation,pattern:oX.implementation,predicate:bX.implementation,required:GY.implementation,optional:i8.implementation,index:_Y.implementation,sequence:WY.implementation,structure:JY.implementation};N.defaultConfig=h5(Object.assign(d(G8,(X,Y)=>[X,Y.defaults]),{jitless:m5(),clone:y5,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:A0.defaultConfig}));N.resolvedConfig=p8(N.defaultConfig,N.config);var f_={...j_,alias:s8.Node,domain:_6.Node,unit:ZY.Node,proto:t8.Node,union:YY.Node,morph:eX.Node,intersection:aX.Node,divisor:yX.Node,pattern:oX.Node,predicate:bX.Node,required:GY.Node,optional:i8.Node,index:_Y.Node,sequence:WY.Node,structure:JY.Node};class H8 extends AX{get[t0](){return"module"}}var QY=(X,Y)=>new H8(d(X,(Z,_)=>[Z,f(_,"module")?QY(_,Y):Y.bindReference(_)]));var eQ=(X)=>Q0(X)?X:("branches"in X)&&Q0(X.branches)?X.branches:void 0,Xz=(X,Y)=>M(`Node of kind ${Y} is not valid as a ${X} definition`),$9=(X)=>`#${X} duplicates public alias ${X}`,zY={};N.ambient??={};var H9,Q9="function $",Yz=(X)=>z9(X,F9(X)),z9=(X,Y)=>{let Z=Y.write(Q9,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}},F9=(X)=>new o2().return(X.reduce((Y,Z)=>{let _=new g8({kind:"Allows"}).indent();Z.compile(_);let G=_.write(`${Z.id}Allows`),W=new g8({kind:"Apply"}).indent();Z.compile(W);let $=W.write(`${Z.id}Apply`),H=`${Y}${G},
44
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},
45
+ `;if(!Z.hasKind("union"))return H;let Q=new g8({kind:"Allows",optimistic:!0}).indent();Z.compile(Q);let J=Q.write(`${Z.id}Optimistic`);return`${H}${J},
46
46
  `},`{
47
- `)+"}");class Y6{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(HY).length}`,this.name in HY)w(`A Scope already named ${this.name} already exists`);HY[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)w(X9(W));this.aliases[W]=G}else{if(W in this.aliases)w(X9(_));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}}Y9??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[Y9.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 i2(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 $=oQ(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:iQ(_,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)??w(zY(X))}maybeResolveRoot(X){let Y=this.maybeResolve(X);if(f(Y,"generic"))return;return Y}maybeResolveSubalias(X){return JY(this.aliases,X)??JY(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)w(J9(X));return this.resolutions[X]=this.bindReference(Z.root)}return this.resolutions[X]=this.parse(Z,{alias:X})}createParseContext(X){let Y=X.id??cX(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")?$Y(_,this):Z9(this.maybeResolve(Z))}for(let Z of this.lazyResolutions)Z.resolution;if(this._exportedResolutions=H9(this,this._exports),this._json=$9(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let Z=W9(this.references);this.precompilation=Z.write(_9,4),G9(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=lX(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=q_(G,_.id);return a0[_.id]=G,G}finalize(X){if(Z9(X),!X.precompilation&&!this.resolvedConfig.jitless)nQ(X.references);return X}}class QY extends Y6{parseOwnDefinitionFormat(X,Y){return lX(Y)}preparseOwnDefinitionFormat(X,Y){return this.preparseNode(d8(X),X,Y)}preparseOwnAliasEntry(X,Y){return[X,Y]}normalizeRootScopeValue(X){return X}}var Z9=(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},$9=(X)=>d(X,(Y,Z)=>[Y,f(Z,"root")||f(Z,"generic")?Z.json:f(Z,"module")?$9(Z):e(`Unexpected resolution ${c(Z)}`)]),JY=(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 w(rQ(_));let W=Y.slice(Z+1),$=G[W];if($===void 0)return JY(G,W);if(f($,"root")||f($,"generic"))return $;if(f($,"module"))return $.root??w(J9(Y));e(`Unexpected resolution for alias '${Y}': ${c($)}`)},Z6=(X,Y)=>new QY(X,Y),a8=new QY({});var H9=(X,Y)=>{let Z={};for(let _ in Y){let G=Y[_];if(f(G,"module")){let W=H9(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},zY=(X)=>`'${X}' is unresolvable`,rQ=(X)=>`'${X}' must reference a module to be accessed using dot syntax`,J9=(X)=>`Reference to submodule '${X}' must specify an alias`;a8.export();var{schema:G0,node:H8,defineSchema:mR,generic:N1}=a8;var FY="^(?:0|[1-9]\\d*)$",sQ=new RegExp(FY),cR=N0(sQ);var Q9=Z6({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={...Q9};var z9=Z6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:FY}},{prereducedAliases:!0}).export();Object.assign(N.intrinsic,z9);var tQ=Z6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),k={...Q9,...z9,...tQ,emptyStructure:H8("structure",{},{prereduced:!0})};N.intrinsic={...k};var U9=(X)=>typeof X==="string"&&X[0]==="d"&&(X[1]==="'"||X[1]==='"')&&X.at(-1)===X[1],F9=(X)=>X.toString()!=="Invalid Date",E9=(X)=>X.slice(2,-1),UY=(X)=>`'${X}' could not be parsed by the Date constructor`,O9=(X,Y)=>aQ(X,Y),aQ=(X,Y)=>{let Z=new Date(X);if(F9(Z))return Z;let _=o5(X);if(_!==void 0){let G=new Date(_);if(F9(G))return G}return Y?w(Y===!0?UY(X):Y):void 0};var EY=(X,Y)=>{let Z=X.scanner.shiftUntil(eQ[D9[Y]]);if(X.scanner.lookahead==="")return X.error(Yz(Z,Y));if(X.scanner.shift(),Y==="/"){try{new RegExp(Z)}catch(_){w(String(_))}X.root=X.ctx.$.node("intersection",{domain:"string",pattern:Z},{prereduced:!0})}else if(f0(Y,OY))X.root=X.ctx.$.node("unit",{unit:Z});else{let _=O9(Z,UY(Z));X.root=X.ctx.$.node("unit",{meta:Z,unit:_})}},OY={"'":1,'"':1},V9={"/":1,"'":1,'"':1},D9={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},eQ={"'":(X)=>X.lookahead==="'",'"':(X)=>X.lookahead==='"',"/":(X)=>X.lookahead==="/"},Xz={'"':"double-quote","'":"single-quote","/":"forward slash"},Yz=(X,Y)=>`${Y}${X} requires a closing ${Xz[D9[Y]]}`;var L9=(X)=>`Private type references should not include '#'. Use '${X}' instead.`,_6="Optional definitions like 'string?' are only valid as properties in an object or tuple",G6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var M9={">":!0,">=":!0},A9={"<":!0,"<=":!0};var J8={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},R9=(X)=>`Unmatched )${X===""?"":` before ${X}`}`,W6=(X)=>`Missing ${X}`,w9=(X,Y)=>`Left bounds are only valid when paired with right bounds (try ...${Y}${X})`,$6=(X)=>`Left-bounded expressions must specify their limits using < or <= (was ${X})`,N9=(X,Y,Z,_)=>`An expression may have at most one left bound (parsed ${X}${J8[Y]}, ${Z}${J8[_]})`;var I9=(X,Y,Z)=>K9(X,Y,Z,[]),K9=(X,Y,Z,_)=>{let G=Z.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Y.params.length)return Z.error(VY(X,Y.names,_.map((W)=>W.expression)));return _}if(G.finalizer===",")return K9(X,Y,Z,_);return G.error(W6(">"))},VY=(X,Y,Z)=>`${X}<${Y.join(", ")}> requires exactly ${Y.length} args (got ${Z.length}${Z.length===0?"":`: ${Z.join(", ")}`})`;var DY=(X)=>{let Y=X.scanner.shiftUntilNextTerminator();if(Y==="keyof")X.addPrefix("keyof");else X.root=_z(X,Y)},Zz=(X,Y,Z)=>{if(Z.scanner.shiftUntilNonWhitespace(),Z.scanner.shift()!=="<")return Z.error(VY(X,Y.names,[]));let G=I9(X,Y,Z);return Y(...G)},_z=(X,Y)=>Gz(X,Y)??Wz(X,Y)??X.error(Y===""?X.scanner.lookahead==="#"?L9(X.shiftedByOne().scanner.shiftUntilNextTerminator()):LY(X):zY(Y)),Gz=(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 Zz(Y,Z,X);return w(`Unexpected resolution ${c(Z)}`)},Wz=(X,Y)=>{let Z=i5(Y);if(Z!==void 0)return X.ctx.$.node("unit",{unit:Z});let _=r5(Y);if(_!==void 0)return X.ctx.$.node("unit",{unit:_})},LY=(X)=>{let Y=X.previousOperator();return Y?MY(Y,X.scanner.unscanned):$z(X.scanner.unscanned)},MY=(X,Y="")=>`Token '${X}' requires a right operand${Y?` before '${Y}'`:""}`,$z=(X)=>`Expected an expression${X?` before '${X}'`:""}`;var AY=(X)=>X.scanner.lookahead===""?X.error(LY(X)):X.scanner.lookahead==="("?X.shiftedByOne().reduceGroupOpen():X.scanner.lookaheadIsIn(V9)?EY(X,X.scanner.shift()):X.scanner.lookaheadIsIn(O4)?AY(X.shiftedByOne()):X.scanner.lookahead==="d"?X.scanner.nextLookahead in OY?EY(X,`${X.scanner.shift()}${X.scanner.shift()}`):DY(X):DY(X);class Z4 extends KX{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 T9=(X,Y)=>{let Z=Hz(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 Qz(X,Z)},C9={"<":1,">":1,"=":1},Hz=(X,Y)=>X.scanner.lookaheadIs("=")?`${Y}${X.scanner.shift()}`:Y;var B9=(X,Y,Z,_)=>{if(Z.extends(N.intrinsic.number)){if(typeof Y!=="number")return w(RY(X,Y,_));return X==="=="?["min","max"]:X[0]===">"?["min"]:["max"]}if(Z.extends(N.intrinsic.lengthBoundable)){if(typeof Y!=="number")return w(RY(X,Y,_));return X==="=="?["exactLength"]:X[0]===">"?["minLength"]:["maxLength"]}if(Z.extends(N.intrinsic.Date))return X==="=="?["after","before"]:X[0]===">"?["after"]:["before"];return w(V_(Z.expression))},Jz=(X)=>({rule:U9(X.limit)?E9(X.limit):X.limit,exclusive:X.comparator.length===1}),Qz=(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(RY(Y,W,"right"));let $=G.unit,H=Y.length===1,Q=B9(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,A9))return X.error($6(Y));let J=B9(X.branches.leftBound.comparator,X.branches.leftBound.limit,Z,"left");X.constrainRoot(J[0],Jz(X.branches.leftBound)),X.branches.leftBound=null},RY=(X,Y,Z)=>`Comparator ${Z==="left"?J8[X]:X} must be ${Z==="left"?"preceded":"followed"} by a corresponding literal (was ${Y})`;var q9=(X)=>{X.scanner.shiftUntilNonWhitespace();let Y=X.scanner.shiftUntilNextTerminator();X.root=X.root.brand(Y)};var S9=(X)=>{let Y=X.scanner.shiftUntilNextTerminator(),Z=n5(Y,{errorOnFail:j9(Y)});if(Z===0)X.error(j9(0));X.root=X.root.constrain("divisor",Z)},j9=(X)=>`% operator must be followed by a non-zero integer literal (was ${X})`;var wY=(X)=>{let Y=X.scanner.shift();return Y===""?X.finalize(""):Y==="["?X.scanner.shift()==="]"?X.setRoot(X.root.array()):X.error(zz):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,C9)?T9(X,Y):Y==="%"?S9(X):Y==="#"?q9(X):(Y in O4)?wY(X):X.error(H6(Y))},H6=(X,Y="")=>`'${X}' is not allowed here${Y&&` (should be ${Y})`}`,zz="Missing expected ']'";var P9=(X)=>{let Y=X.unsetRoot();X.parseOperand();let Z=X.unsetRoot();if(!Z.hasKind("unit"))return X.error(Fz(Z.expression));let _=Z.unit instanceof Date?()=>new Date(Z.unit):Z.unit;return[Y,"=",_]},Fz=(X)=>`Default value '${X}' must a literal value`;var NY=(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=Uz(_);if(_.finalizer===">")w(H6(">"));return G},Uz=(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=P9(X);else if(X.finalizer==="?")Y=[Y,"?"];if(X.scanner.shiftUntilNonWhitespace(),X.scanner.lookahead)w(H6(X.scanner.lookahead));return Y},e8=(X)=>{while(X.finalizer===void 0)Ez(X);return X},Ez=(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 w(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(W6(")"));this.finalizeBranches(),this.finalizer=X}reduceLeftBound(X,Y){let Z=J8[Y];if(!f0(Z,M9))return this.error($6(Y));if(this.branches.leftBound)return this.error(N9(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(R9(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 wY(this)}parseOperand(){return AY(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(w9(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 Oz="An empty string is not a valid generic parameter name",J6=(X,Y,Z)=>{X.shiftUntilNonWhitespace();let _=X.shiftUntilNextTerminator();if(_===""){if(X.lookahead===""&&Y.length)return Y;return w(Oz)}return X.shiftUntilNonWhitespace(),Vz(X,_,Y,Z)},v9="extends ",Vz=(X,Y,Z,_)=>{if(X.shiftUntilNonWhitespace(),X.unscanned.startsWith(v9))X.jumpForward(v9.length);else{if(X.lookahead===",")X.shift();return Z.push(Y),J6(X,Z,_)}let G=e8(new Q8(X,_));return Z.push([Y,G.root]),J6(X,Z,_)};class IY 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)w(Lz);if(this.branches.length)w(Dz);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)w("default may only be specified as the last key of a switch definition");return this.default(_)}if(typeof _!=="function")return w(`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:x9};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:x9},"self");return this.$.finalize(_)}}var x9=(X)=>X.throw(),Dz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",Lz="At most one key matcher may be specified per expression";var Q6=(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 z6(X,Y)},f9="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",h9="Only required keys may specify default values, e.g. { value: 'number = 0' }";var k9=(X,Y)=>{let Z,_={},G=q4(X);for(let[$,H]of G){let Q=Rz($);if(Q.kind==="spread"){if(!l1(_))return w(Az);let D=Y.$.parseOwnDefinitionFormat(H,Y);if(D.equals(k.object))continue;if(!D.hasKind("intersection")||!D.basis?.equals(k.object))return w(wz(D.expression));Z=D.structure;continue}if(Q.kind==="undeclared"){if(H!=="reject"&&H!=="delete"&&H!=="ignore")w(Mz(H));_.undeclared=H;continue}let J=Q6(H,Y),z=Q;if(Q.kind==="required"){if(!Q0(J))KY(_,"required",{key:Q.normalized,value:J},Y);else KY(_,"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]==="?")w(f9);if(J[1]==="=")w(h9)}if(Q.kind==="optional"){KY(_,"optional",{key:Q.normalized,value:J},Y);continue}let F=Y.$.parseOwnDefinitionFormat(z.normalized,Y),O=X6(F,J,Y.$);if(O.index)_.index=s(_.index,O.index);if(O.required)_.required=s(_.required,O.required)}let W=Y.$.node("structure",_);return Y.$.parseSchema({domain:"object",structure:Z?.merge(W)??W})},KY=(X,Y,Z,_)=>{X[Y]=s(X[Y],_.$.node(Y,Z))},Mz=(X)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${c(X)})`,Az="Spread operator may only be used as the first key in an object",Rz=(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},wz=(X)=>`Spread operand must resolve to an object literal type (was ${X})`;var y9=(X,Y)=>Pz(X)?u9[X[0]](X,Y):jz(X)?m9[X[1]](X,Y):null,Nz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[1],Y).keyof(),BY=(X,Y)=>{if(X[2]===void 0)return w(MY(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},Iz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[0],Y).array(),Kz=(X,Y)=>{if(typeof X[2]!=="function")return w(g9("=>",X[2]));return Y.$.parseOwnDefinitionFormat(X[0],Y).pipe(X[2])},g9=(X,Y)=>`${X===":"?"Narrow":"Morph"} expression requires a function following '${X}' (was ${typeof Y})`,Bz=(X,Y)=>{if(typeof X[2]!=="function")return w(g9(":",X[2]));return Y.$.parseOwnDefinitionFormat(X[0],Y).constrain("predicate",X[2])},Tz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[0],Y).configureReferences(X[2],"shallow"),p9=(X)=>X,Cz=p9({"[]":Iz,"?":()=>w(_6)}),qz=p9({"|":BY,"&":BY,":":Bz,"=>":Kz,"|>":BY,"@":Tz,"=":()=>w(G6)}),m9={...Cz,...qz},jz=(X)=>m9[X[1]]!==void 0,Sz=(X)=>X,u9=Sz({keyof:Nz,instanceof:(X,Y)=>{if(typeof X[1]!=="function")return w(b9(S8(X[1])));let Z=X.slice(1).map((_)=>typeof _==="function"?Y.$.node("proto",{proto:_}):w(b9(S8(_))));return Z.length===1?Z[0]:Y.$.node("union",{branches:Z})},"===":(X,Y)=>Y.$.units(X.slice(1))}),Pz=(X)=>u9[X[0]]!==void 0,b9=(X)=>`Expected a constructor following 'instanceof' operator (was ${X})`;var l9=(X,Y)=>{let Z=[{}],_=0;while(_<X.length){let G=!1;if(X[_]==="..."&&_<X.length-1)G=!0,_++;let W=Q6(X[_],Y),[$,H,Q]=!Q0(W)?[W]:W;if(_++,G){if(!$.extends(N.intrinsic.Array))return w(fz($.expression));Z=Z.flatMap((J)=>$.distribute((z)=>xz(d2(J),z)))}else Z=Z.map((J)=>{if(H==="?")return o9(J,$);if(H==="=")return vz(J,$,Q);return TY(J,$)})}return Y.$.parseSchema(Z.map((G)=>l1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},TY=(X,Y)=>{if(X.defaultables||X.optionals)return w(X.variadic?_Y:hz);if(X.variadic)X.postfix=s(X.postfix,Y);else X.prefix=s(X.prefix,Y);return X},o9=(X,Y)=>{if(X.variadic)return w(i9);return X.optionals=s(X.optionals,Y),X},vz=(X,Y,Z)=>{if(X.variadic)return w(i9);if(X.optionals)return w(kz);return X.defaultables=s(X.defaultables,[[Y,Z]]),X},d9=(X,Y)=>{if(X.postfix)w(c9);if(X.variadic){if(!X.variadic.equals(Y))w(c9)}else X.variadic=Y.internal;return X},xz=(X,Y)=>{let Z=Y.select({method:"find",kind:"sequence"});if(!Z)return d9(X,N.intrinsic.unknown);if(Z.prefix)for(let _ of Z.prefix)TY(X,_);if(Z.optionals)for(let _ of Z.optionals)o9(X,_);if(Z.variadic)d9(X,Z.variadic);if(Z.postfix)for(let _ of Z.postfix)TY(X,_);return X},fz=(X)=>`Spread element must be an array (was ${X})`,c9="A tuple may have at most one variadic element",hz="A required element may not follow an optional element",i9="An optional element may not follow a variadic element";var kz="A defaultable element may not follow an optional element without a default";var bz={},z6=(X,Y)=>{if(typeof X==="string"){if(Y.args&&Object.keys(Y.args).some((_)=>X.includes(_)))return NY(X,Y);let Z=bz[Y.$.name]??={};return Z[X]??=NY(X,Y)}return _1(X,"object")?yz(X,Y):w(CY(x0(X)))},yz=(X,Y)=>{let Z=j8(X);switch(Z){case void 0:if(f(X,"root"))return X;return k9(X,Y);case"Array":return gz(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 w(CY("Function"))}default:return w(CY(Z??c(X)))}},gz=(X,Y)=>y9(X,Y)??l9(X,Y),CY=(X)=>`Type definitions must be strings or objects (was ${X})`;class qY 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 F6 extends Y6{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)!==">")w("'>' 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 U_(W,Y,this)}]}parseGenericParams(X,Y){return J6(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 _=z6(X,Y);if(Q0(_)){if(_[1]==="=")return w(G6);if(_[1]==="?")return w(_6)}return _}unit=(X)=>this.units([X]);valueOf=(X)=>this.units(v5(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 IY(this);declare=()=>({type:this.type});define(X){return X}type=new qY(this);static scope=(X,Y={})=>new F6(X,Y);static module=(X,Y={})=>this.scope(X,Y).export()}var jY=Object.assign(F6.scope,{define:(X)=>X}),r=F6;class n9 extends o0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var pz=N1(["base",k.object],["props",k.object])((X)=>X.base.merge(X.props),n9),r9=r.module({Key:k.key,Merge:pz});class s9 extends o0{}var mz=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)},s9),t9=r.module({root:k.Array,readonly:"root",index:k.nonNegativeIntegerString,liftFrom:mz},{name:"Array"});var SY=G0(["string",S4.FileConstructor]),uz=SY.rawOr(SY.array()),a9=G0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:uz}}),e9=r.module({root:["instanceof",FormData],value:SY,parsed:a9,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:a9})},{name:"FormData"});var XG=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 dz={Boolean:1,Number:1,String:1},YG=r.module({...d({...DX,...MX},(X,Y)=>(X in dz)?[]:[X,["instanceof",Y]]),Array:t9,TypedArray:XG,FormData:e9});var cz=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"}),lz=G0({domain:"number",divisor:1}),U6=r.module({root:k.number,integer:lz,epoch:cz,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",_)},ZG=A0(x8,"a well-formed integer string"),OG=r.module({root:ZG,parse:G0({in:ZG,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"}),oz=A0(/^[\dA-Fa-f]+$/,"hex characters only"),iz=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"}),_G=A0(/^[A-Z].*$/,"capitalized"),nz=r.module({root:G0({in:"string",morphs:(X)=>X.charAt(0).toUpperCase()+X.slice(1),declaredOut:_G}),preformatted:_G},{name:"string.capitalize"}),rz=(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)},sz=/^(?: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}))$/,tz=G0({domain:"string",pattern:{meta:"a credit card number",rule:sz.source},predicate:{meta:"a credit card number",predicate:rz}});var az=/^([+-]?\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 ez=(X)=>!Number.isNaN(new Date(X).valueOf()),GG=G0({domain:"string",predicate:{meta:"a parsable date",predicate:ez}}).assertHasKind("intersection"),WG=OG.root.internal.narrow((X,Y)=>{let Z=Number.parseInt(X),_=U6.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"),XF=r.module({root:WG,parse:G0({in:WG,morphs:(X)=>new Date(X),declaredOut:k.Date})},{name:"string.date.epoch"}),$G=A0(az,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),YF=r.module({root:$G,parse:G0({in:$G,morphs:(X)=>new Date(X),declaredOut:k.Date})},{name:"string.date.iso"}),ZF=r.module({root:GG,parse:G0({declaredIn:GG,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:YF,epoch:XF},{name:"string.date"}),_F=A0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),HG="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A4=`(${HG}[.]){3}${HG}`,GF=new RegExp(`^${A4}$`),q0="(?:[0-9a-fA-F]{1,4})",WF=new RegExp(`^((?:${q0}:){7}(?:${q0}|:)|(?:${q0}:){6}(?:${A4}|:${q0}|:)|(?:${q0}:){5}(?::${A4}|(:${q0}){1,2}|:)|(?:${q0}:){4}(?:(:${q0}){0,1}:${A4}|(:${q0}){1,3}|:)|(?:${q0}:){3}(?:(:${q0}){0,2}:${A4}|(:${q0}){1,4}|:)|(?:${q0}:){2}(?:(:${q0}){0,3}:${A4}|(:${q0}){1,5}|:)|(?:${q0}:){1}(?:(:${q0}){0,4}:${A4}|(:${q0}){1,6}|:)|(?::((?::${q0}){0,5}:${A4}|(?::${q0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),$F=r.module({root:["v4 | v6","@","an IP address"],v4:A0(GF,"an IPv4 address","ipv4"),v6:A0(WF,"an IPv6 address","ipv6")},{name:"string.ip"}),F8="a JSON string",VG=(X)=>{if(!(X instanceof SyntaxError))throw X;return`must be ${F8} (${X})`},HF=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:VG(Z)})}}}}),JF=(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:VG(Z)})}},QF=r.module({root:HF,parse:G0({meta:"safe JSON string parser",in:"string",morphs:JF,declaredOut:k.jsonObject})},{name:"string.json"}),JG=A0(/^[a-z]*$/,"only lowercase letters"),zF=r.module({root:G0({in:"string",morphs:(X)=>X.toLowerCase(),declaredOut:JG}),preformatted:JG},{name:"string.lower"}),DG=["NFC","NFD","NFKC","NFKD"],Y2=d(DG,(X,Y)=>[Y,G0({domain:"string",predicate:(Z)=>Z.normalize(Y)===Z,meta:`${Y}-normalized unicode`})]),E6=d(DG,(X,Y)=>[Y,G0({in:"string",morphs:(Z)=>Z.normalize(Y),declaredOut:Y2[Y]})]),FF=r.module({root:E6.NFC,preformatted:Y2.NFC},{name:"string.normalize.NFC"}),UF=r.module({root:E6.NFD,preformatted:Y2.NFD},{name:"string.normalize.NFD"}),EF=r.module({root:E6.NFKC,preformatted:Y2.NFKC},{name:"string.normalize.NFKC"}),OF=r.module({root:E6.NFKD,preformatted:Y2.NFKD},{name:"string.normalize.NFKD"}),VF=r.module({root:"NFC",NFC:FF,NFD:UF,NFKC:EF,NFKD:OF},{name:"string.normalize"}),QG=A0(p2,"a well-formed numeric string"),DF=r.module({root:QG,parse:G0({in:QG,morphs:(X)=>Number.parseFloat(X),declaredOut:k.number})},{name:"string.numeric"}),zG="a regex pattern",LF=G0({domain:"string",predicate:{meta:zG,predicate:(X,Y)=>{try{return new RegExp(X),!0}catch(Z){return Y.reject({code:"predicate",expected:zG,problem:String(Z)})}}},meta:{format:"regex"}}),MF=/^(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-]+)*))?$/,AF=A0(MF,"a semantic version (see https://semver.org/)"),FG=A0(/^\S.*\S$|^\S?$/,"trimmed"),RF=r.module({root:G0({in:"string",morphs:(X)=>X.trim(),declaredOut:FG}),preformatted:FG},{name:"string.trim"}),UG=A0(/^[A-Z]*$/,"only uppercase letters"),wF=r.module({root:G0({in:"string",morphs:(X)=>X.toUpperCase(),declaredOut:UG}),preformatted:UG},{name:"string.upper"}),NF=(X)=>{if(URL.canParse)return URL.canParse(X);try{return new URL(X),!0}catch{return!1}},EG=G0({domain:"string",predicate:{meta:"a URL string",predicate:NF},meta:{format:"uri"}}),IF=r.module({root:EG,parse:G0({declaredIn:EG,in:"string",morphs:(X,Y)=>{try{return new URL(X)}catch{return Y.error("a URL string")}},declaredOut:G0(URL)})},{name:"string.url"}),KF=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"}),LG=r.module({root:k.string,alpha:A0(/^[A-Za-z]*$/,"only letters"),alphanumeric:A0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:oz,base64:iz,capitalize:nz,creditCard:tz,date:ZF,digits:A0(/^\d*$/,"only digits 0-9"),email:_F,integer:OG,ip:$F,json:QF,lower:zF,normalize:VF,numeric:DF,regex:LF,semver:AF,trim:RF,upper:wF,url:IF,uuid:KF},{name:"string"});var MG=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}),AG=r.module({root:k.unknown,any:k.unknown},{name:"unknown"}),BF=r.module({root:k.jsonObject,stringify:H8("morph",{in:k.jsonObject,morphs:(X)=>JSON.stringify(X),declaredOut:k.string})},{name:"object.json"}),RG=r.module({root:k.object,json:BF},{name:"object"});class wG extends o0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var TF=N1(["K",k.key],"V")((X)=>({domain:"object",index:{signature:X.K,value:X.V}}),wG);class NG extends o0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var CF=N1(["T",k.object],["K",k.key])((X)=>X.T.pick(X.K),NG);class IG extends o0{description='omit a set of properties from an object like `Omit(User, "age")`'}var qF=N1(["T",k.object],["K",k.key])((X)=>X.T.omit(X.K),IG);class KG extends o0{description="make all named properties of an object optional like `Partial(User)`"}var jF=N1(["T",k.object])((X)=>X.T.partial(),KG);class BG extends o0{description="make all named properties of an object required like `Required(User)`"}var SF=N1(["T",k.object])((X)=>X.T.required(),BG);class TG extends o0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var PF=N1("T","U")((X)=>X.T.exclude(X.U),TG);class CG extends o0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var vF=N1("T","U")((X)=>X.T.extract(X.U),CG),qG=r.module({Exclude:PF,Extract:vF,Omit:qF,Partial:jF,Pick:CF,Record:TF,Required:SF});var R4=jY({...MG,...qG,...YG,...r9,string:LG,number:U6,object:RG,unknown:AG},{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),xF=R4.match,fF=R4.generic,UK=R4.schema,hF=R4.define,kF=R4.declare;function U8(X){return M6(D1.STORE,X,void 0)}function E8(X){return _2(D1.STORE,X)}function vY(...X){return h1(D1.STORE,...X)}function O6(X){return hG(D1.STORE,X)}function jG(X){return kG(X,D1.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 PY=(X)=>(Y,Z,_,G,...W)=>{console[X](`${Y} ${_4[Z]} \`${_}\` ${G}`,...W)},bF={error:PY("error"),info:PY("info"),warn:PY("warn")},SG=class{logLevel;filter;logger;constructor(X,Y,Z=bF){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)}}};function Z2(X,Y){return[X,Y].sort().join("\x1F")}function PG(X){if(typeof X==="string"===!1)return null;let[Y,Z]=X.split("==");if(!Z)return null;let _=Y.slice(4),[G,W]=Z.split("++");if(_&&G&&W)return[_,G,W];return null}function V6(X){return bY(D1.STORE,X)}function D6(X){return kY(D1.STORE,X)}function X1(X){return JSON.parse(X)}var j0=(X)=>JSON.stringify(X),yK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function bG(X){let Y={},Z=0;for(let _ of X)Y[_]=Z,Y[Z]=_,++Z;return Y}var yG="\x01",gG="\x02",pG="\x03",mG="\x04",gY=(X)=>{switch(typeof X){case"string":return pG+X;case"number":return mG+X;case"boolean":return yG+ +X;case"object":return gG}},pY=(X)=>{switch(X[0]){case pG:return X.slice(1);case mG:return+X.slice(1);case yG:return X.slice(1)==="1";case gG:return null}};var uG=bG(["add","delete","clear"]),G4=class X extends Set{mode="record";subject=new Y0;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=uG[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=uG[Z];if(G==="clear")return{type:"clear",values:_.split("\x1E").map(pY)};return{type:G,value:pY(_)}}};function vG(X=Math.random){return X().toString(36).slice(2)}function t(X){while(X.child!==null)X=X.child;return X}function nY(X){while(X.parent!==null)X=X.parent;return X}var pF=/^\[object (?:Async|Generator|AsyncGenerator)?Function\]$/;function $2(X){let Y=Object.prototype.toString.call(X);return pF.test(Y)}function dY(X,Y){if($2(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}},Y0=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)}},mF=class extends Y0{state;constructor(X){super();this.state=X}next(X){this.state=X,super.next(X)}},uF=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}},oG=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}},dF=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 oG(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 dF(_.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 oG){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 cF=(X)=>{X.logger.info("\uD83E\uDE82","transaction",X.transactionMeta.update.token.key,"Aborting transaction"),X.parent.child=null};function xY(X,Y,Z){return(..._)=>{return B0(X,Y).run(_,Z)}}function lF(X,Y,Z){let{token:_,update:{newValue:G,oldValue:W}}=Y;k1(X,_,Z==="newValue"?G:W)}function oF(X){let{stack:Y}=X;if(Y)return`
47
+ `)+"}");class W6{config;resolvedConfig;name;get[t0](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(X,Y){if(this.config=p8(N.config,Y),this.resolvedConfig=p8(N.resolvedConfig,Y),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(zY).length}`,this.name in zY)M(`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)M($9(W));this.aliases[W]=G}else{if(W in this.aliases)M($9(_));this.aliases[W]=G,this.exportedNames.push(W)}if(!f(G,"module")&&!f(G,"generic")&&!O4(G)){let $=this.preparseOwnDefinitionFormat(G,{alias:W});this.resolutions[W]=f($,"root")?this.bindReference($):this.createParseContext($).id}}H9??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[H9.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 t2(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(c8(X),X,Y);preparseNode(X,Y,Z){let _=typeof X==="string"?X:c8(Y,X);if(E0(Y)&&Y.kind===_)return Y;if(_==="alias"&&!Z?.prereduced){let{reference:$}=s8.implementation.normalize(Y,this);if($.startsWith("$")){let H=this.resolveRoot($.slice(1));Y=H,_=H.kind}}else if(_==="union"&&_1(Y,"object")){let $=eQ(Y);if($?.length===1)Y=$[0],_=c8(Y)}if(E0(Y)&&Y.kind===_)return Y;let W=G8[_].normalize?.(Y,this)??Y;if(E0(W))return W.kind===_?W:Xz(_,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)??M(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)M(O9(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 f1(X,this.resolvedConfig)}import(...X){return new H8(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):J9(this.maybeResolve(Z))}for(let Z of this.lazyResolutions)Z.resolution;if(this._exportedResolutions=E9(this,this._exports),this._json=U9(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let Z=F9(this.references);this.precompilation=Z.write(Q9,4),z9(this.references,Z)}this.resolved=!0}let Y=X.length?X:this.exportedNames;return new H8(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=x_(G,_.id);return a0[_.id]=G,G}finalize(X){if(J9(X),!X.precompilation&&!this.resolvedConfig.jitless)Yz(X.references);return X}}class UY extends W6{parseOwnDefinitionFormat(X,Y){return nX(Y)}preparseOwnDefinitionFormat(X,Y){return this.preparseNode(c8(X),X,Y)}preparseOwnAliasEntry(X,Y){return[X,Y]}normalizeRootScopeValue(X){return X}}var J9=(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},U9=(X)=>d(X,(Y,Z)=>[Y,f(Z,"root")||f(Z,"generic")?Z.json:f(Z,"module")?U9(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 M(Zz(_));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??M(O9(Y));e(`Unexpected resolution for alias '${Y}': ${c($)}`)},$6=(X,Y)=>new UY(X,Y),e8=new UY({});var E9=(X,Y)=>{let Z={};for(let _ in Y){let G=Y[_];if(f(G,"module")){let W=E9(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`,Zz=(X)=>`'${X}' must reference a module to be accessed using dot syntax`,O9=(X)=>`Reference to submodule '${X}' must specify an alias`;e8.export();var{schema:G0,node:J8,defineSchema:eR,generic:I1}=e8;var OY="^(?:0|[1-9]\\d*)$",_z=new RegExp(OY),Zw=N0(_z);var V9=$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={...V9};var D9=$6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:OY}},{prereducedAliases:!0}).export();Object.assign(N.intrinsic,D9);var Gz=$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={...V9,...D9,...Gz,emptyStructure:J8("structure",{},{prereduced:!0})};N.intrinsic={...k};var A9=(X)=>typeof X==="string"&&X[0]==="d"&&(X[1]==="'"||X[1]==='"')&&X.at(-1)===X[1],L9=(X)=>X.toString()!=="Invalid Date",M9=(X)=>X.slice(2,-1),VY=(X)=>`'${X}' could not be parsed by the Date constructor`,R9=(X,Y)=>Wz(X,Y),Wz=(X,Y)=>{let Z=new Date(X);if(L9(Z))return Z;let _=s5(X);if(_!==void 0){let G=new Date(_);if(L9(G))return G}return Y?M(Y===!0?VY(X):Y):void 0};var DY=(X,Y)=>{let Z=X.scanner.shiftUntilEscapable(Hz[N9[Y]]);if(X.scanner.lookahead==="")return X.error(Qz(Z,Y));if(X.scanner.shift(),Y==="/"){try{new RegExp(Z)}catch(_){M(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 _=R9(Z,VY(Z));X.root=X.ctx.$.node("unit",{meta:Z,unit:_})}},LY={"'":1,'"':1},w9={"/":1,"'":1,'"':1},$z={"d'":"'",'d"':'"',"'":"'",'"':'"'},N9={...$z,"/":"/"},Hz={"'":(X)=>X.lookahead==="'",'"':(X)=>X.lookahead==='"',"/":(X)=>X.lookahead==="/"},Jz={'"':"double-quote","'":"single-quote","/":"forward slash"},Qz=(X,Y)=>`${Y}${X} requires a closing ${Jz[N9[Y]]}`;var I9=(X)=>`Private type references should not include '#'. Use '${X}' instead.`,H6="Optional definitions like 'string?' are only valid as properties in an object or tuple",J6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var n1={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...V4};var K9=(X,Y)=>X===">"?Y[0]==="="?Y[1]==="=":Y.trimStart()===""||f0(Y.trimStart()[0],n1):X==="="?Y[0]!=="=":X===","||X==="?";var B9=(X,Y,Z)=>T9(X,Y,Z,[]),T9=(X,Y,Z,_)=>{let G=Z.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Y.params.length)return Z.error(AY(X,Y.names,_.map((W)=>W.expression)));return _}if(G.finalizer===",")return T9(X,Y,Z,_);return G.error(l2(">"))},AY=(X,Y,Z)=>`${X}<${Y.join(", ")}> requires exactly ${Y.length} args (got ${Z.length}${Z.length===0?"":`: ${Z.join(", ")}`})`;var MY=(X)=>{let Y=X.scanner.shiftUntilLookahead(n1);if(Y==="keyof")X.addPrefix("keyof");else X.root=Fz(X,Y)},zz=(X,Y,Z)=>{if(Z.scanner.shiftUntilNonWhitespace(),Z.scanner.shift()!=="<")return Z.error(AY(X,Y.names,[]));let G=B9(X,Y,Z);return Y(...G)},Fz=(X,Y)=>Uz(X,Y)??Ez(X,Y)??X.error(Y===""?X.scanner.lookahead==="#"?I9(X.shiftedByOne().scanner.shiftUntilLookahead(n1)):RY(X):EY(Y)),Uz=(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 zz(Y,Z,X);return M(`Unexpected resolution ${c(Z)}`)},Ez=(X,Y)=>{let Z=t5(Y);if(Z!==void 0)return X.ctx.$.node("unit",{unit:Z});let _=e5(Y);if(_!==void 0)return X.ctx.$.node("unit",{unit:_})},RY=(X)=>{let Y=X.previousOperator();return Y?wY(Y,X.scanner.unscanned):Oz(X.scanner.unscanned)},wY=(X,Y="")=>`Token '${X}' requires a right operand${Y?` before '${Y}'`:""}`,Oz=(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(w9)?DY(X,X.scanner.shift()):X.scanner.lookaheadIsIn(V4)?NY(X.shiftedByOne()):X.scanner.lookahead==="d"?X.scanner.nextLookahead in LY?DY(X,`${X.scanner.shift()}${X.scanner.shift()}`):MY(X):MY(X);var C9={">":!0,">=":!0},q9={"<":!0,"<=":!0};var Q8={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},j9=(X,Y)=>`Left bounds are only valid when paired with right bounds (try ...${Y}${X})`,Q6=(X)=>`Left-bounded expressions must specify their limits using < or <= (was ${X})`,S9=(X,Y,Z,_)=>`An expression may have at most one left bound (parsed ${X}${Q8[Y]}, ${Z}${Q8[_]})`;var v9=(X,Y)=>{let Z=Vz(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 Lz(X,Z)},x9={"<":1,">":1,"=":1},Vz=(X,Y)=>X.scanner.lookaheadIs("=")?`${Y}${X.scanner.shift()}`:Y;var P9=(X,Y,Z,_)=>{if(Z.extends(N.intrinsic.number)){if(typeof Y!=="number")return M(IY(X,Y,_));return X==="=="?["min","max"]:X[0]===">"?["min"]:["max"]}if(Z.extends(N.intrinsic.lengthBoundable)){if(typeof Y!=="number")return M(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 M(R_(Z.expression))},Dz=(X)=>({rule:A9(X.limit)?M9(X.limit):X.limit,exclusive:X.comparator.length===1}),Lz=(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=P9(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,q9))return X.error(Q6(Y));let J=P9(X.branches.leftBound.comparator,X.branches.leftBound.limit,Z,"left");X.constrainRoot(J[0],Dz(X.branches.leftBound)),X.branches.leftBound=null},IY=(X,Y,Z)=>`Comparator ${Z==="left"?Q8[X]:X} must be ${Z==="left"?"preceded":"followed"} by a corresponding literal (was ${Y})`;var f9=(X)=>{X.scanner.shiftUntilNonWhitespace();let Y=X.scanner.shiftUntilLookahead(n1);X.root=X.root.brand(Y)};var k9=(X)=>{X.scanner.shiftUntilNonWhitespace();let Y=X.scanner.shiftUntilLookahead(n1),Z=a5(Y,{errorOnFail:h9(Y)});if(Z===0)X.error(h9(0));X.root=X.root.constrain("divisor",Z)},h9=(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(Az):Y==="|"?X.scanner.lookahead===">"?X.shiftedByOne().pushRootToBranch("|>"):X.pushRootToBranch(Y):Y==="&"?X.pushRootToBranch(Y):Y===")"?X.finalizeGroup():K9(Y,X.scanner.unscanned)?X.finalize(Y):f0(Y,x9)?v9(X,Y):Y==="%"?k9(X):Y==="#"?f9(X):(Y in V4)?KY(X):X.error(z6(Y))},z6=(X,Y="")=>`'${X}' is not allowed here${Y&&` (should be ${Y})`}`,Az="Missing expected ']'";var b9=(X)=>{let Y=X.unsetRoot();X.parseOperand();let Z=X.unsetRoot();if(!Z.hasKind("unit"))return X.error(Mz(Z.expression));let _=Z.unit instanceof Date?()=>new Date(Z.unit):Z.unit;return[Y,"=",_]},Mz=(X)=>`Default value '${X}' must be 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 z8(new y8(X),Y),G=Rz(_);if(_.finalizer===">")M(z6(">"));return G},Rz=(X)=>{X.parseOperand();let Y=X2(X).root;if(!Y)return e(`Root was unexpectedly unset after parsing string '${X.scanner.scanned}'`);if(X.finalizer==="=")Y=b9(X);else if(X.finalizer==="?")Y=[Y,"?"];if(X.scanner.shiftUntilNonWhitespace(),X.scanner.lookahead)M(z6(X.scanner.lookahead));return Y},X2=(X)=>{while(X.finalizer===void 0)wz(X);return X},wz=(X)=>X.hasRoot()?X.parseOperator():X.parseOperand();class z8{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 M(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(l2(")"));this.finalizeBranches(),this.finalizer=X}reduceLeftBound(X,Y){let Z=Q8[Y];if(!f0(Z,C9))return this.error(Q6(Y));if(this.branches.leftBound)return this.error(S9(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(__(")",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 X2(new z8(this.scanner,this.ctx))}parseOperator(){return KY(this)}parseOperand(){return NY(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(j9(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 Nz="An empty string is not a valid generic parameter name",F6=(X,Y,Z)=>{X.shiftUntilNonWhitespace();let _=X.shiftUntilLookahead(n1);if(_===""){if(X.lookahead===""&&Y.length)return Y;return M(Nz)}return X.shiftUntilNonWhitespace(),Iz(X,_,Y,Z)},y9="extends ",Iz=(X,Y,Z,_)=>{if(X.shiftUntilNonWhitespace(),X.unscanned.startsWith(y9))X.jumpForward(y9.length);else{if(X.lookahead===",")X.shift();return Z.push(Y),F6(X,Z,_)}let G=X2(new z8(X,_));return Z.push([Y,G.root]),F6(X,Z,_)};class TY extends $1{constructor(X){let Y={$:X,raw:X.fn};super((...Z)=>{let _=Z.indexOf(":"),G=_===-1?Z.length-1:_-1,W=Z.slice(0,G+1),$=X.parse(W).assertHasKind("intersection"),H=X.intrinsic.unknown;if(_!==-1){if(_!==Z.length-2)return M(Kz);H=X.parse(Z[_+1])}return(Q)=>new g9(Q,$,H)},{attach:Y})}}class g9 extends $1{raw;params;returns;expression;constructor(X,Y,Z){let _=`typed ${X.name}`,G={[_]:(...$)=>{let H=Y.assert($),Q=X(...H);return Z.assert(Q)}}[_];super(G);this.raw=X,this.params=Y,this.returns=Z;let W=Y.expression;if(W[0]==="["&&W.at(-1)==="]")W=W.slice(1,-1);else if(W.endsWith("[]"))W=`...${W}`;this.expression=`(${W}) => ${Z?.expression??"unknown"}`}}var Kz=`":" must be followed by exactly one return type e.g:
48
+ fn("string", ":", "number")(s => s.length)`;class CY extends $1{$;constructor(X){super((...Y)=>new Y2(X)(...Y),{bind:X});this.$=X}in(X){return new Y2(this.$,X===void 0?void 0:this.$.parse(X))}at(X,Y){return new Y2(this.$).at(X,Y)}case(X,Y){return new Y2(this.$).case(X,Y)}}class Y2 extends $1{$;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)M(Tz);if(this.branches.length)M(Bz);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)M("default may only be specified as the last key of a switch definition");return this.default(_)}if(typeof _!=="function")return M(`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:p9};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:p9},"self");return this.$.finalize(_)}}var p9=(X)=>X.throw(),Bz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",Tz="At most one key matcher may be specified per expression";var U6=(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 E6(X,Y)},m9="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",u9="Only required keys may specify default values, e.g. { value: 'number = 0' }";var d9=(X,Y)=>{let Z,_={},G=q4(X);for(let[$,H]of G){let Q=jz($);if(Q.kind==="spread"){if(!o1(_))return M(qz);let D=Y.$.parseOwnDefinitionFormat(H,Y);if(D.equals(k.object))continue;if(!D.hasKind("intersection")||!D.basis?.equals(k.object))return M(Sz(D.expression));Z=D.structure;continue}if(Q.kind==="undeclared"){if(H!=="reject"&&H!=="delete"&&H!=="ignore")M(Cz(H));_.undeclared=H;continue}let J=U6(H,Y),z=Q;if(Q.kind==="required"){if(!Q0(J))qY(_,"required",{key:Q.normalized,value:J},Y);else qY(_,"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]==="?")M(m9);if(J[1]==="=")M(u9)}if(Q.kind==="optional"){qY(_,"optional",{key:Q.normalized,value:J},Y);continue}let F=Y.$.parseOwnDefinitionFormat(z.normalized,Y),O=G6(F,J,Y.$);if(O.index)_.index=s(_.index,O.index);if(O.required)_.required=s(_.required,O.required)}let W=Y.$.node("structure",_);return Y.$.parseSchema({domain:"object",structure:Z?.merge(W)??W})},qY=(X,Y,Z,_)=>{X[Y]=s(X[Y],_.$.node(Y,Z))},Cz=(X)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${c(X)})`,qz="Spread operator may only be used as the first key in an object",jz=(X)=>typeof X==="symbol"?{kind:"required",normalized:X}:X.at(-1)==="?"?X.at(-2)===S4?{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]===S4&&X[1]==="["&&X.at(-1)==="]"?{kind:"required",normalized:X.slice(1)}:X==="..."?{kind:"spread"}:X==="+"?{kind:"undeclared"}:{kind:"required",normalized:X==="\\..."?"...":X==="\\+"?"+":X},Sz=(X)=>`Spread operand must resolve to an object literal type (was ${X})`;var l9=(X,Y)=>pz(X)?r9[X[0]](X,Y):yz(X)?n9[X[1]](X,Y):null,Pz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[1],Y).keyof(),jY=(X,Y)=>{if(X[2]===void 0)return M(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]==="&"?Q1(Z,_,Y.$):d8(Z,_,Y.$);if(G instanceof C)return G.throw();return G},vz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[0],Y).array(),xz=(X,Y)=>{if(typeof X[2]!=="function")return M(o9("=>",X[2]));return Y.$.parseOwnDefinitionFormat(X[0],Y).pipe(X[2])},o9=(X,Y)=>`${X===":"?"Narrow":"Morph"} expression requires a function following '${X}' (was ${typeof Y})`,fz=(X,Y)=>{if(typeof X[2]!=="function")return M(o9(":",X[2]));return Y.$.parseOwnDefinitionFormat(X[0],Y).constrain("predicate",X[2])},hz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[0],Y).configure(X[2],X[3]),i9=(X)=>X,kz=i9({"[]":vz,"?":()=>M(H6)}),bz=i9({"|":jY,"&":jY,":":fz,"=>":xz,"|>":jY,"@":hz,"=":()=>M(J6)}),n9={...kz,...bz},yz=(X)=>n9[X[1]]!==void 0,gz=(X)=>X,r9=gz({keyof:Pz,instanceof:(X,Y)=>{if(typeof X[1]!=="function")return M(c9(P8(X[1])));let Z=X.slice(1).map((_)=>typeof _==="function"?Y.$.node("proto",{proto:_}):M(c9(P8(_))));return Z.length===1?Z[0]:Y.$.node("union",{branches:Z})},"===":(X,Y)=>Y.$.units(X.slice(1))}),pz=(X)=>r9[X[0]]!==void 0,c9=(X)=>`Expected a constructor following 'instanceof' operator (was ${X})`;var a9=(X,Y)=>{let Z=[{}],_=0;while(_<X.length){let G=!1;if(X[_]==="..."&&_<X.length-1)G=!0,_++;let W=U6(X[_],Y),[$,H,Q]=!Q0(W)?[W]:W;if(_++,G){if(!$.extends(N.intrinsic.Array))return M(dz($.expression));Z=Z.flatMap((J)=>$.distribute((z)=>uz(i2(J),z)))}else Z=Z.map((J)=>{if(H==="?")return e9(J,$);if(H==="=")return mz(J,$,Q);return SY(J,$)})}return Y.$.parseSchema(Z.map((G)=>o1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},SY=(X,Y)=>{if(X.defaultables||X.optionals)return M(X.variadic?$Y:cz);if(X.variadic)X.postfix=s(X.postfix,Y);else X.prefix=s(X.prefix,Y);return X},e9=(X,Y)=>{if(X.variadic)return M(XG);return X.optionals=s(X.optionals,Y),X},mz=(X,Y,Z)=>{if(X.variadic)return M(XG);if(X.optionals)return M(lz);return X.defaultables=s(X.defaultables,[[Y,Z]]),X},s9=(X,Y)=>{if(X.postfix)M(t9);if(X.variadic){if(!X.variadic.equals(Y))M(t9)}else X.variadic=Y.internal;return X},uz=(X,Y)=>{let Z=Y.select({method:"find",kind:"sequence"});if(!Z)return s9(X,N.intrinsic.unknown);if(Z.prefix)for(let _ of Z.prefix)SY(X,_);if(Z.optionals)for(let _ of Z.optionals)e9(X,_);if(Z.variadic)s9(X,Z.variadic);if(Z.postfix)for(let _ of Z.postfix)SY(X,_);return X},dz=(X)=>`Spread element must be an array (was ${X})`,t9="A tuple may have at most one variadic element",cz="A required element may not follow an optional element",XG="An optional element may not follow a variadic element";var lz="A defaultable element may not follow an optional element without a default";var oz={},E6=(X,Y)=>{if(typeof X==="string"){if(Y.args&&Object.keys(Y.args).some((_)=>X.includes(_)))return BY(X,Y);let Z=oz[Y.$.name]??={};return Z[X]??=BY(X,Y)}return _1(X,"object")?iz(X,Y):M(PY(x0(X)))},iz=(X,Y)=>{let Z=S8(X);switch(Z){case void 0:if(f(X,"root"))return X;return d9(X,Y);case"Array":return nz(X,Y);case"RegExp":return Y.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0});case"Function":{let _=O4(X)?X():X;if(f(_,"root"))return _;return M(PY("Function"))}default:return M(PY(Z??c(X)))}},nz=(X,Y)=>l9(X,Y)??a9(X,Y),PY=(X)=>`Type definitions must be strings or objects (was ${X})`;class vY extends $1{constructor(X){let Y=Object.assign({errors:H1,hkt:o0,$:X,raw:X.parse,module:X.constructor.module,scope:X.constructor.scope,declare:X.declare,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,fn:X.fn},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)},{attach:Y})}}var F8=N;class O6 extends W6{get ambientAttachments(){if(!F8.typeAttachments)return;return this.cacheGetter("ambientAttachments",d(F8.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)!==">")M("'>' 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 L_(W,Y,this)}]}parseGenericParams(X,Y){return F6(new y8(X),[],this.createParseContext({...Y,def:X,prefix:"generic"}))}normalizeRootScopeValue(X){if(O4(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 _=E6(X,Y);if(Q0(_)){if(_[1]==="=")return M(J6);if(_[1]==="?")return M(H6)}return _}unit=(X)=>this.units([X]);valueOf=(X)=>this.units(k5(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);fn=new TY(this);match=new CY(this);declare=()=>({type:this.type});define(X){return X}type=new vY(this);static scope=(X,Y={})=>new O6(X,Y);static module=(X,Y={})=>this.scope(X,Y).export()}var xY=Object.assign(O6.scope,{define:(X)=>X}),r=O6;class YG extends o0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var rz=I1(["base",k.object],["props",k.object])((X)=>X.base.merge(X.props),YG),ZG=r.module({Key:k.key,Merge:rz});class _G extends o0{}var sz=I1("element")((X)=>{let Y=X.element.exclude(k.Array),Z=Y.array();return Y.rawOr(Z).pipe(E4).distribute((_)=>_.assertHasKind("morph").declareOut(Z),G0)},_G),GG=r.module({root:k.Array,readonly:"root",index:k.nonNegativeIntegerString,liftFrom:sz},{name:"Array"});var fY=G0(["string",P4.FileConstructor]),tz=fY.rawOr(fY.array()),WG=G0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:tz}}),$G=r.module({root:["instanceof",FormData],value:fY,parsed:WG,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 P4.FileConstructor)Y[Z]=[G,_];else G.push(_)}else Y[Z]=_;return Y},declaredOut:WG})},{name:"FormData"});var HG=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 az={Boolean:1,Number:1,String:1},JG=r.module({...d({...MX,...wX},(X,Y)=>(X in az)?[]:[X,["instanceof",Y]]),Array:GG,TypedArray:HG,FormData:$G});var ez=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"}),XF=G0({domain:"number",divisor:1}),V6=r.module({root:k.number,integer:XF,epoch:ez,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 M0=(X,Y,Z)=>{let _={domain:"string",pattern:{rule:X.source,flags:X.flags,meta:Y}};if(Z)_.meta={format:Z};return J8("intersection",_)},QG=M0(x8,"a well-formed integer string"),wG=r.module({root:QG,parse:G0({in:QG,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"}),YF=M0(/^[\dA-Fa-f]+$/,"hex characters only"),ZF=r.module({root:M0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:M0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),zG=M0(/^[A-Z].*$/,"capitalized"),_F=r.module({root:G0({in:"string",morphs:(X)=>X.charAt(0).toUpperCase()+X.slice(1),declaredOut:zG}),preformatted:zG},{name:"string.capitalize"}),GF=(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)},WF=/^(?: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}))$/,$F=G0({domain:"string",pattern:{meta:"a credit card number",rule:WF.source},predicate:{meta:"a credit card number",predicate:GF}});var HF=/^([+-]?\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 JF=(X)=>!Number.isNaN(new Date(X).valueOf()),FG=G0({domain:"string",predicate:{meta:"a parsable date",predicate:JF}}).assertHasKind("intersection"),UG=wG.root.internal.narrow((X,Y)=>{let Z=Number.parseInt(X),_=V6.epoch(Z);if(_ instanceof H1)return Y.errors.merge(_),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),QF=r.module({root:UG,parse:G0({in:UG,morphs:(X)=>new Date(X),declaredOut:k.Date})},{name:"string.date.epoch"}),EG=M0(HF,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),zF=r.module({root:EG,parse:G0({in:EG,morphs:(X)=>new Date(X),declaredOut:k.Date})},{name:"string.date.iso"}),FF=r.module({root:FG,parse:G0({declaredIn:FG,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:QF},{name:"string.date"}),UF=M0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),OG="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",R4=`(${OG}[.]){3}${OG}`,EF=new RegExp(`^${R4}$`),q0="(?:[0-9a-fA-F]{1,4})",OF=new RegExp(`^((?:${q0}:){7}(?:${q0}|:)|(?:${q0}:){6}(?:${R4}|:${q0}|:)|(?:${q0}:){5}(?::${R4}|(:${q0}){1,2}|:)|(?:${q0}:){4}(?:(:${q0}){0,1}:${R4}|(:${q0}){1,3}|:)|(?:${q0}:){3}(?:(:${q0}){0,2}:${R4}|(:${q0}){1,4}|:)|(?:${q0}:){2}(?:(:${q0}){0,3}:${R4}|(:${q0}){1,5}|:)|(?:${q0}:){1}(?:(:${q0}){0,4}:${R4}|(:${q0}){1,6}|:)|(?::((?::${q0}){0,5}:${R4}|(?::${q0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),VF=r.module({root:["v4 | v6","@","an IP address"],v4:M0(EF,"an IPv4 address","ipv4"),v6:M0(OF,"an IPv6 address","ipv6")},{name:"string.ip"}),U8="a JSON string",NG=(X)=>{if(!(X instanceof SyntaxError))throw X;return`must be ${U8} (${X})`},DF=G0({meta:U8,domain:"string",predicate:{meta:U8,predicate:(X,Y)=>{try{return JSON.parse(X),!0}catch(Z){return Y.reject({code:"predicate",expected:U8,problem:NG(Z)})}}}}),LF=(X,Y)=>{if(X.length===0)return Y.error({code:"predicate",expected:U8,actual:"empty"});try{return JSON.parse(X)}catch(Z){return Y.error({code:"predicate",expected:U8,problem:NG(Z)})}},AF=r.module({root:DF,parse:G0({meta:"safe JSON string parser",in:"string",morphs:LF,declaredOut:k.jsonObject})},{name:"string.json"}),VG=M0(/^[a-z]*$/,"only lowercase letters"),MF=r.module({root:G0({in:"string",morphs:(X)=>X.toLowerCase(),declaredOut:VG}),preformatted:VG},{name:"string.lower"}),IG=["NFC","NFD","NFKC","NFKD"],Z2=d(IG,(X,Y)=>[Y,G0({domain:"string",predicate:(Z)=>Z.normalize(Y)===Z,meta:`${Y}-normalized unicode`})]),D6=d(IG,(X,Y)=>[Y,G0({in:"string",morphs:(Z)=>Z.normalize(Y),declaredOut:Z2[Y]})]),RF=r.module({root:D6.NFC,preformatted:Z2.NFC},{name:"string.normalize.NFC"}),wF=r.module({root:D6.NFD,preformatted:Z2.NFD},{name:"string.normalize.NFD"}),NF=r.module({root:D6.NFKC,preformatted:Z2.NFKC},{name:"string.normalize.NFKC"}),IF=r.module({root:D6.NFKD,preformatted:Z2.NFKD},{name:"string.normalize.NFKD"}),KF=r.module({root:"NFC",NFC:RF,NFD:wF,NFKC:NF,NFKD:IF},{name:"string.normalize"}),DG=M0(d2,"a well-formed numeric string"),BF=r.module({root:DG,parse:G0({in:DG,morphs:(X)=>Number.parseFloat(X),declaredOut:k.number})},{name:"string.numeric"}),LG="a regex pattern",TF=G0({domain:"string",predicate:{meta:LG,predicate:(X,Y)=>{try{return new RegExp(X),!0}catch(Z){return Y.reject({code:"predicate",expected:LG,problem:String(Z)})}}},meta:{format:"regex"}}),CF=/^(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-]+)*))?$/,qF=M0(CF,"a semantic version (see https://semver.org/)"),AG=M0(/^\S.*\S$|^\S?$/,"trimmed"),jF=r.module({root:G0({in:"string",morphs:(X)=>X.trim(),declaredOut:AG}),preformatted:AG},{name:"string.trim"}),MG=M0(/^[A-Z]*$/,"only uppercase letters"),SF=r.module({root:G0({in:"string",morphs:(X)=>X.toUpperCase(),declaredOut:MG}),preformatted:MG},{name:"string.upper"}),PF=(X)=>URL.canParse(X),RG=G0({domain:"string",predicate:{meta:"a URL string",predicate:PF},meta:{format:"uri"}}),vF=r.module({root:RG,parse:G0({declaredIn:RG,in:"string",morphs:(X,Y)=>{try{return new URL(X)}catch{return Y.error("a URL string")}},declaredOut:G0(URL)})},{name:"string.url"}),xF=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:M0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:M0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:M0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:M0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:M0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:M0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:M0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:M0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),KG=r.module({root:k.string,alpha:M0(/^[A-Za-z]*$/,"only letters"),alphanumeric:M0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:YF,base64:ZF,capitalize:_F,creditCard:$F,date:FF,digits:M0(/^\d*$/,"only digits 0-9"),email:UF,integer:wG,ip:VF,json:AF,lower:MF,normalize:KF,numeric:BF,regex:TF,semver:qF,trim:jF,upper:SF,url:vF,uuid:xF},{name:"string"});var BG=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}),TG=r.module({root:k.unknown,any:k.unknown},{name:"unknown"}),fF=r.module({root:k.jsonObject,stringify:J8("morph",{in:k.jsonObject,morphs:(X)=>JSON.stringify(X),declaredOut:k.string})},{name:"object.json"}),CG=r.module({root:k.object,json:fF},{name:"object"});class qG extends o0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var hF=I1(["K",k.key],"V")((X)=>({domain:"object",index:{signature:X.K,value:X.V}}),qG);class jG extends o0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var kF=I1(["T",k.object],["K",k.key])((X)=>X.T.pick(X.K),jG);class SG extends o0{description='omit a set of properties from an object like `Omit(User, "age")`'}var bF=I1(["T",k.object],["K",k.key])((X)=>X.T.omit(X.K),SG);class PG extends o0{description="make all named properties of an object optional like `Partial(User)`"}var yF=I1(["T",k.object])((X)=>X.T.partial(),PG);class vG extends o0{description="make all named properties of an object required like `Required(User)`"}var gF=I1(["T",k.object])((X)=>X.T.required(),vG);class xG extends o0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var pF=I1("T","U")((X)=>X.T.exclude(X.U),xG);class fG extends o0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var mF=I1("T","U")((X)=>X.T.extract(X.U),fG),hG=r.module({Exclude:pF,Extract:mF,Omit:bF,Partial:yF,Pick:kF,Record:hF,Required:gF});var _4=xY({...BG,...hG,...JG,...ZG,string:KG,number:V6,object:CG,unknown:TG},{prereducedAliases:!0,name:"ark"}),h0=_4.export();Object.assign(F8.ambient,h0);F8.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 z1=Object.assign(_4.type,F8.typeAttachments),uF=_4.match,SK=_4.fn,dF=_4.generic,PK=_4.schema,cF=_4.define,lF=_4.declare;function E8(X){return w6(L1.STORE,X,void 0)}function O8(X){return G2(L1.STORE,X)}function kY(...X){return k1(L1.STORE,...X)}function L6(X){return uG(L1.STORE,X)}function kG(X){return dG(X,L1.STORE)}var G4={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 hY=(X)=>(Y,Z,_,G,...W)=>{console[X](`${Y} ${G4[Z]} \`${_}\` ${G}`,...W)},oF={error:hY("error"),info:hY("info"),warn:hY("warn")},bG=class{logLevel;filter;logger;constructor(X,Y,Z=oF){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)}}};function _2(X,Y){return[X,Y].sort().join("\x1F")}function yG(X){if(typeof X==="string"===!1)return null;let[Y,Z]=X.split("==");if(!Z)return null;let _=Y.slice(4),[G,W]=Z.split("++");if(_&&G&&W)return[_,G,W];return null}function A6(X){return mY(L1.STORE,X)}function M6(X){return pY(L1.STORE,X)}function X1(X){return JSON.parse(X)}var j0=(X)=>JSON.stringify(X),GB=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function cG(X){let Y={},Z=0;for(let _ of X)Y[_]=Z,Y[Z]=_,++Z;return Y}var lG="\x01",oG="\x02",iG="\x03",nG="\x04",dY=(X)=>{switch(typeof X){case"string":return iG+X;case"number":return nG+X;case"boolean":return lG+ +X;case"object":return oG}},cY=(X)=>{switch(X[0]){case iG:return X.slice(1);case nG:return+X.slice(1);case lG:return X.slice(1)==="1";case oG:return null}};var rG=cG(["add","delete","clear"]),W4=class X extends Set{mode="record";subject=new Y0;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=rG[Y.type]+"\x1F";if(Y.type==="clear")return Z+Y.values.map(dY).join("\x1E");return Z+dY(Y.value)}static unpackUpdate(Y){let[Z,_]=Y.split("\x1F"),G=rG[Z];if(G==="clear")return{type:"clear",values:_.split("\x1E").map(cY)};return{type:G,value:cY(_)}}};function gG(X=Math.random){return X().toString(36).slice(2)}function t(X){while(X.child!==null)X=X.child;return X}function aY(X){while(X.parent!==null)X=X.parent;return X}var rF=/^\[object (?:Async|Generator|AsyncGenerator)?Function\]$/;function H2(X){let Y=Object.prototype.toString.call(X);return rF.test(Y)}function iY(X,Y){if(H2(X))return X(Y);return X}var nY=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}},Y0=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)}},sF=class extends Y0{state;constructor(X){super();this.state=X}next(X){this.state=X,super.next(X)}},tF=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 g1(X){let Y={key:X.key,type:X.type};if("family"in X)Y.family=X.family;return Y}var y1=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}},eG=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}},aF=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=new eG(this.source.get(X));return super.set(X,Y),Y}}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)}},$4=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 aF(_.relations),this.contents=new y1(_.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 eG){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 D8(X){return X.startsWith("\uD83D\uDD0D ")}var eF=(X)=>{X.logger.info("\uD83E\uDE82","transaction",X.transactionMeta.update.token.key,"Aborting transaction"),X.parent.child=null};function bY(X,Y,Z){return(..._)=>{return B0(X,Y).run(_,Z)}}function XU(X,Y,Z){let{token:_,update:{newValue:G,oldValue:W}}=Y;b1(X,_,Z==="newValue"?G:W)}function YU(X){let{stack:Y}=X;if(Y)return`
48
49
  `+Y.split(`
49
50
  `)?.slice(1)?.join(`
50
- `);return""}function fY(X,Y,Z,_="any"){let G=Y,W=j0(Z),$=[],H=t(X);if(Array.isArray(G))for(let z of G){let F=j0(z);if(H.molecules.get(F))X.moleculeGraph.set(F,W,{source:F});else $.push(F)}else{let z=j0(G);if(H.molecules.get(z))X.moleculeGraph.set(z,W,{source:z});else $.push(z)}let Q=new Y0;if($.length===0)H.molecules.set(W,{key:Z,stringKey:W,dependsOn:_,subject:Q});let J={type:"molecule_creation",key:Z,provenance:G,timestamp:Date.now()};if(Q1(H)&&H.transactionMeta.phase==="building")H.transactionMeta.update.subEvents.push(J);else H.on.moleculeCreation.next(J);for(let z of $){let F=X.disposalTraces.buffer.find((O)=>O?.key===z);X.logger.error("\u274C","key",Z,"allocation failed:",`Could not allocate to ${z} in store "${X.config.name}".`,F?`
51
+ `);return""}function yY(X,Y,Z,_="any"){let G=Y,W=j0(Z),$=[],H=t(X);if(Array.isArray(G))for(let z of G){let F=j0(z);if(H.molecules.get(F))X.moleculeGraph.set(F,W,{source:F});else $.push(F)}else{let z=j0(G);if(H.molecules.get(z))X.moleculeGraph.set(z,W,{source:z});else $.push(z)}let Q=new Y0;if($.length===0)H.molecules.set(W,{key:Z,stringKey:W,dependsOn:_,subject:Q});let J={type:"molecule_creation",key:Z,provenance:G,timestamp:Date.now()};if(F1(H)&&H.transactionMeta.phase==="building")H.transactionMeta.update.subEvents.push(J);else H.on.moleculeCreation.next(J);for(let z of $){let F=X.disposalTraces.buffer.find((O)=>O?.key===z);X.logger.error("\u274C","key",Z,"allocation failed:",`Could not allocate to ${z} in store "${X.config.name}".`,F?`
51
52
  ${z} was most recently disposed
52
- ${F.trace}`:`No previous disposal trace for ${z} was found.`)}return Z}function rY(X,Y){let Z=j0(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
+ ${F.trace}`:`No previous disposal trace for ${z} was found.`)}return Z}function eY(X,Y){let Z=j0(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
54
  This state was most recently deallocated
54
- ${O.trace}`:`No previous disposal trace for ${Z} was found.`);return}_.subject.next();let G=X.keyRefsInJoins.getRelatedKeys(Z);if(G)for(let O of G){let D=X.joins.get(O);if(D)D.relations.delete(Y)}else{let O=PG(Y);if(O){let[,D,A]=O,R=X.keyRefsInJoins.getRelatedKey(Z2(D,A));if(R){let v=X.joins.get(R);if(v)v.relations.delete(D,A)}}}X.keyRefsInJoins.delete(Z);let W=[],$=[],H=X.moleculeGraph.getRelationEntries({downstreamMoleculeKey:Z});if(H)for(let[O,{source:D}]of H)if(D===Z){let A=X1(O);rY(X,A)}else W.push(D);let Q=X.moleculeData.getRelatedKeys(_.stringKey);if(Q)for(let O of Q){let D=X.families.get(O),A=h1(X,D,Y);$.push([D.key,A]),G2(X,D,Y)}let J={type:"molecule_disposal",key:_.key,values:$,provenance:W,timestamp:Date.now()};X.molecules.delete(Z);let z=Q1(X)&&X.transactionMeta.phase==="building";if(z)X.transactionMeta.update.subEvents.push(J);if(X.moleculeGraph.delete(_.stringKey),X.keyRefsInJoins.delete(_.stringKey),X.moleculeData.delete(_.stringKey),!z)X.on.moleculeDisposal.next(J);X.molecules.delete(_.stringKey);let F=oF(Error());X.disposalTraces.add({key:Z,trace:F})}function hY(X,Y,Z,_){let G=j0(Z),W=t(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
+ ${O.trace}`:`No previous disposal trace for ${Z} was found.`);return}_.subject.next();let G=X.keyRefsInJoins.getRelatedKeys(Z);if(G)for(let O of G){let D=X.joins.get(O);if(D)D.relations.delete(Y)}else{let O=yG(Y);if(O){let[,D,w]=O,R=X.keyRefsInJoins.getRelatedKey(_2(D,w));if(R){let v=X.joins.get(R);if(v)v.relations.delete(D,w)}}}X.keyRefsInJoins.delete(Z);let W=[],$=[],H=X.moleculeGraph.getRelationEntries({downstreamMoleculeKey:Z});if(H)for(let[O,{source:D}]of H)if(D===Z)eY(X,X1(O));else W.push(D);let Q=X.moleculeData.getRelatedKeys(_.stringKey);if(Q)for(let O of Q){let D=X.families.get(O),w=k1(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=F1(X)&&X.transactionMeta.phase==="building";if(z)X.transactionMeta.update.subEvents.push(J);if(X.moleculeGraph.delete(_.stringKey),X.keyRefsInJoins.delete(_.stringKey),X.moleculeData.delete(_.stringKey),!z)X.on.moleculeDisposal.next(J);X.molecules.delete(_.stringKey);let F=YU(Error());X.disposalTraces.add({key:Z,trace:F})}function gY(X,Y,Z,_){let G=j0(Z),W=t(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
56
  ${G} was most recently disposed
56
57
  ${F.trace}`:`No previous disposal trace for ${G} was found.`),Z}let H=j0(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
58
  ${H} was most recently disposed
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(Q1(W)&&W.transactionMeta.phase==="building")W.transactionMeta.update.subEvents.push(z);return Z}function iF(X,Y,Z){switch(Z){case"newValue":iG(X,Y);break;case"oldValue":G2(X,Y.token);break}}function nF(X,Y,Z){switch(Z){case"newValue":G2(X,Y.token);break;case"oldValue":if(iG(X,Y),Y.subType==="atom")X.valueMap.set(Y.token.key,Y.value);break}}function iG(X,Y){let{token:Z}=Y;if(Y.subType==="writable"&&Y.value)k1(X,Z,Y.value);else h1(X,Z)}function rF(X,Y,Z){switch(Z){case"newValue":fY(X,Y.provenance,Y.key);break;case"oldValue":rY(X,Y.key);break}}function sF(X,Y,Z){switch(Z){case"newValue":rY(X,Y.key);break;case"oldValue":{let _=Y.provenance.map(X1);fY(X,_,Y.key);for(let[G,W]of Y.values){let $=X.families.get(G);if($){h1(X,$,Y.key);let H=`${G}(${j0(Y.key)})`;X.valueMap.set(H,W)}}}break}}function tF(X,Y,Z){switch(Z){case"newValue":for(let _ of Y.to)hY(X,_,Y.key,Y.exclusive?"exclusive":void 0);break;case"oldValue":{let _="exclusive";for(let G of Y.from)hY(X,G,Y.key,_),_=void 0}break}}function nG(X,Y,Z){let _=Z==="newValue"?Y.subEvents:[...Y.subEvents].reverse();for(let G of _)switch(G.type){case"atom_update":lF(X,G,Z);break;case"state_creation":iF(X,G,Z);break;case"state_disposal":nF(X,G,Z);break;case"molecule_creation":rF(X,G,Z);break;case"molecule_disposal":sF(X,G,Z);break;case"molecule_transfer":tF(X,G,Z);break;case"transaction_outcome":nG(X,G,Z);break}}function O8(X){return"epoch"in X.transactionMeta}function Q1(X){return"phase"in X.transactionMeta}function rG(X,Y){return X.transactionMeta.actionContinuities.getRelatedKey(Y)}function aF(X,Y){return X.transactionMeta.epoch.get(Y)}function eF(X,Y){let Z=rG(X,Y);if(Z===void 0)return;return aF(X,Z)}function XU(X,Y,Z){let _=rG(X,Y);if(_!==void 0)X.transactionMeta.epoch.set(_,Z)}function YU(X,Y){let Z=t(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),nG(_,Z.transactionMeta.update,"newValue"),O8(_))XU(_,Z.transactionMeta.update.token.key,Z.transactionMeta.update.epoch),B0(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(Q1(_))_.transactionMeta.update.subEvents.push(Z.transactionMeta.update);_.on.transactionApplying.next(null)}function ZU(X){return{store:X}}var _U=(X,Y,Z,_)=>{let G=t(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(),keyRefsInJoins:G.keyRefsInJoins.overlay(),miscResources:new b1(G.miscResources)},$=eF(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)=>{L6(Q,...J)},run:(J,z=vG())=>xY(Q,J,z),find:(...J)=>e0(X,...J),json:(J)=>h4(Q,J),dispose:(...J)=>{G2(Q,...J)},env:()=>ZU(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 kY(X,Y){let{key:Z}=Y,_=X.transactions.has(Z),G={key:Z,type:"transaction",run:($,H)=>{let Q=y1(G),J=_U(X,Q,$,H);try{let{toolkit:z}=J.transactionMeta,F=Y.do(z,...$);return YU(J,F),F}catch(z){throw cF(J),X.logger.warn("\uD83D\uDCA5","transaction",Z,"caught:",z),z}},install:($)=>kY($,Y),subject:new Y0};t(X).transactions.set(Z,G);let W=y1(G);if(!_)X.on.transactionCreation.next(W);return W}var xG=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 uF(100);molecules=new Map;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(":")});keyRefsInJoins=new W4({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});miscResources=new Map;on={atomCreation:new Y0,atomDisposal:new Y0,selectorCreation:new Y0,selectorDisposal:new Y0,timelineCreation:new Y0,transactionCreation:new Y0,transactionApplying:new mF(null),operationClose:new Y0,moleculeCreation:new Y0,moleculeDisposal:new Y0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new SG("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=A6(_);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)}}},D1={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new xG({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};var GU=class extends Error{constructor(X,Y){super(`${_4[X.type]} ${j0(X.key)} not found in store "${Y.config.name}".`)}};function B0(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 GU(Y,X)}function sG(X,Y,Z,_){let G=X.disposalTraces.buffer.find((W)=>W?.key===j0(_));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 R6(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($2(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 MU(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 R6(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 sY(X,Y){return B0(X,{key:Y.family.key,type:`${Y.type}_family`})}var dG={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"},H2=Symbol("MUST_CREATE"),WU=Symbol("DO_NOT_CREATE");function J2(X,Y,Z,_){let G=j0(_),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=dG[H];return{counterfeit:!0,key:J,type:z,family:{key:Q,subKey:G}}}let $;if(X===H2){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=dG[H];return{key:J,type:z,family:{key:Q,subKey:G}}}return $}function tY(X,...Y){let Z,_,G,W,$;if(Y.length===1){if($=Y[0],"family"in $){let Q=sY(X,$);if(G=B0(X,Q),W=X1($.family.subKey),Z=Q2(X,Q,W),"counterfeit"in $)return{token:$,family:G,subKey:W,isNew:!1};if(!Z)_=J2(H2,X,Q,W),$=_;else $=Z}}else if(G=B0(X,Y[0]),W=Y[1],Z=Q2(X,G,W),!Z)_=J2(H2,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=t(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(Q1(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}=tY(X,...Y);if("counterfeit"in Z&&_&&G)return sG(X,Z,_,G);let W=B0(X,Z);return f4(X,W)}function Q2(X,Y,Z){let _=j0(Z),G=`${Y.key}(${_})`,W=t(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 _=B0(X,Y),G=Q2(X,Y,Z);if(G)return G;return J2(WU,X,_,Z)}function z2(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 Y0,J={...W,create:(z)=>{let F=j0(z),O={key:_,subKey:F},D=`${_}(${F})`,A=t(X),R={key:D,get:Y.get(z)};if(Y.catch)R.catch=Y.catch;return YZ(A,R,O)},internalRoles:Z,subject:H,install:(z)=>z2(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 _2(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 Y0,H={..._,create:(Q)=>{let J=j0(Q),z={key:Y.key,subKey:J},F=`${Y.key}(${J})`,O=t(X),D=Y.default,A={key:F,default:$2(D)?()=>D(Q):D};if(Y.effects)A.effects=Y.effects(Q);if(Y.catch)A.catch=Y.catch;return x4(O,A,z)},default:Y.default,subject:W,install:(Q)=>_2(Q,Y),internalRoles:Z};if(X.families.set(Y.key,H),$2(Y.default)===!1)X.defaults.set(Y.key,Y.default);return _}function tG(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 Y0,J={...W,create:(z)=>{let F=j0(z),O={key:_,subKey:F},D=`${_}(${F})`,A=t(X);return XZ(A,{key:D,const:Y.const(z),get:Y.get(z)},O)},internalRoles:Z,subject:H,install:(z)=>tG(z,Y),default:Y.const};return X.families.set(_,J),W}function aG(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 Y0,J={...W,create:(z)=>{let F=j0(z),O={key:_,subKey:F},D=`${_}(${F})`,A=t(X);return ZZ(A,{key:D,const:Y.const(z),get:Y.get(z),set:Y.set(z)},O)},internalRoles:Z,subject:H,install:(z)=>aG(z,Y),default:Y.const};return X.families.set(_,J),W}function aY(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 Y0,J={...W,create:(z)=>{let F=j0(z),O={key:_,subKey:F},D=`${_}(${F})`,A=t(X),R={key:D,get:Y.get(z),set:Y.set(z)};if(Y.catch)R.catch=Y.catch;return _Z(A,R,O)},internalRoles:Z,subject:H,install:(z)=>aY(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 aG(X,Y,void 0);if(_)return tG(X,Y,void 0);if(Z)return aY(X,Y);return z2(X,Y)}function G2(X,...Y){let Z;if(Y.length===1)Z=Y[0];else{let _=Y[0],G=Y[1];Z=e0(X,_,G)}try{B0(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":W7(X,Z);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":EU(X,Z);break}}function eG(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}"${Q1(X)?` ${X.transactionMeta.phase} "${X.transactionMeta.update.token.key}"`:""}`),X}function X7(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 Y7=(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)},N6=(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=t(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(Q1(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(Q1(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($Z(Y,"tracker:signal")){let F=H.slice(1),O=X.atoms.get(F);if(f4(X,O,"mut").do(z.newValue)===null===!0)WZ(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),N6(X,Y.key),WZ(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($2(Y.default))Z=R6(X,Y);else Z=Y.default;return oY(X,Y,Z)}}}function $U(X,Y){let Z;switch(Y.type){case"atom":case"mutable_atom":Z=mY(X,Y);break;case"writable_held_selector":{let _=F2(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 _=R6(X,Y),G=F2(X,Y.key);for(let $ of G.values()){let H=mY(X,$);lY(X,Y,H,!1)}let W=R6(X,Y);Z={oldValue:_,newValue:W}}break}return Z}function k1(X,...Y){D8(w6,X,...Y)}var iY=Symbol("RESET");function L6(X,...Y){let Z=[...Y,iY];k1(X,...Z)}function HU(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),N6(X,H),Y.setSelf(G),{oldValue:_,newValue:G}}var JU=(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":_=HU(X,Y,Z);break}return _},w6=Symbol("OWN_OP"),eY=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($=sY(Y,W),H=X1(W.family.subKey),_=Q2(Y,$,H),!_)W=G=J2(H2,Y,$,H);else W=_}else if($=B0(Y,Z[0]),H=Z[1],Q=Z[2],_=Q2(Y,$,H),!_)W=G=J2(H2,Y,$,H);else W=_;let J=Q===iY?"reset":"set",z;if(X===w6){let D=eG(Y,W);if(typeof D==="number"){let A=D,R=Y.on.operationClose.subscribe(`waiting to ${J} "${W.key}" at T-${A}`,function(){R(),Y.logger.info("\uD83D\uDFE2",W.type,W.key,"resuming deferred",J,`from T-${A}`),D8(X,Y,W,Q)});return}z=D}else z=Y;if("counterfeit"in W&&"family"in W){let D=W.family.subKey,A=Y.disposalTraces.buffer.find((R)=>R?.key===D);Y.logger.error("\u274C",W.type,W.key,"could not be",J,"because key",D,"is not allocated.",A?`this key was previously disposed:${A.trace}`:"(no previous disposal trace found)");return}let F=B0(z,W),O;if(Q===iY)O=$U(z,F);else O=JU(z,F,Q);if(lY(z,F,O,Boolean(G),$),X===w6)X7(z)}var Z7=(X,Y)=>t(X).atoms.has(Y),QU=(X,Y)=>t(X).writableSelectors.has(Y),zU=(X,Y)=>t(X).readonlySelectors.has(Y),FU=(X,Y)=>Z7(X,Y)||QU(X,Y)||zU(X,Y);function cG(X,Y){return t(X).selectorGraph.getRelationEntries({downstreamSelectorKey:Y}).filter(([Z,{source:_}])=>_!==Y).map(([Z,{source:_}])=>_).filter((Z)=>FU(X,Z))}function F2(X,Y,Z=new Set){let _=cG(X,Y),G=new Map;while(_.length>0){let W=_.pop();if(Z.has(W))continue;if(Z.add(W),Z7(X,W)){let $=X.atoms.get(W);G.set($.key,$)}else _.push(...cG(X,W))}return G}function UU(X,Y,Z,_,G){let W=t(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=F2(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 I6(X,Y,Z,_){return{get:(...G)=>{let W=t(X),{token:$,family:H,subKey:Q}=tY(X,...G),J;if("counterfeit"in $&&H&&Q)J=sG(X,$,H,Q);else{let z=B0(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}),UU(X,Y,Z,$,_),J},set:(...G)=>{let W=t(X);D8(eY,W,...G)},find:(...G)=>e0(X,...G),json:(G)=>h4(X,G)}}function XZ(X,Y,Z){let _=t(X),G=new Y0,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}=I6(_,"readonly_held_selector",$,W),D={...Y,type:"readonly_held_selector",subject:G,getFrom:(R)=>{let v=R.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[j,{source:P}]of v)if(P!==$)R.selectorGraph.delete(j,$);return R.selectorAtoms.delete($),Y.get({get:J,find:z,json:F},H),K1(R,D,H),X.logger.info("\u2728","readonly_held_selector",$,"=",H),W.clear(),H},install:(R)=>XZ(R,Y,Z)};if(Z)D.family=Z;_.readonlySelectors.set($,D);let A={key:$,type:"readonly_held_selector"};if(Z)A.family=Z;return A}function YZ(X,Y,Z){let _=t(X),G=new Y0,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}=I6(_,"readonly_pure_selector",$,W),O={...Y,type:"readonly_pure_selector",subject:G,getFrom:()=>{let A=t(X),R=A.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[P,{source:h}]of R)if(h!==$)A.selectorGraph.delete(P,$);A.selectorAtoms.delete($);let v=Y.get({get:Q,find:J,json:z}),j=K1(A,O,v);return X.logger.info("\u2728","readonly_pure_selector",$,"=",j),W.clear(),j},install:(A)=>YZ(A,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 ZZ(X,Y,Z){let _=t(X),G=new Y0,W=new Set,{key:$,const:H}=Y,Q="writable_held_selector";X.logger.info("\uD83D\uDD28","writable_held_selector",$,"is being created");let J=I6(_,"writable_held_selector",$,W),{find:z,get:F,json:O}=J,D={find:z,get:F,json:O},v={...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,v,H),X.logger.info("\u2728","writable_held_selector",$,"=",H),W.clear(),H},setSelf:()=>{Y.set(J,H)},install:(P)=>ZZ(P,Y,Z)};if(Z)v.family=Z;_.writableSelectors.set($,v);let j={key:$,type:"writable_held_selector"};if(Z)j.family=Z;return j}function _Z(X,Y,Z){let _=t(X),G=new Y0,W=new Set,$=Y.key,H="writable_pure_selector";X.logger.info("\uD83D\uDD28","writable_pure_selector",$,"is being created");let Q=I6(_,"writable_pure_selector",$,W),{find:J,get:z,json:F}=Q,O={find:J,get:z,json:F},R={...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,R,h);return X.logger.info("\u2728","writable_pure_selector",$,"=",i),W.clear(),i},setSelf:(j)=>{Y.set(Q,j)},install:(j)=>_Z(j,Y,Z)};if(Z)R.family=Z;_.writableSelectors.set($,R);let v={key:$,type:"writable_pure_selector"};if(Z)v.family=Z;return v}function fG(X,Y){let Z="set"in Y,_="const"in Y;if(_&&Z){let W=ZZ(X,Y,void 0);return X.on.selectorCreation.next(W),W}if(_){let W=XZ(X,Y,void 0);return X.on.selectorCreation.next(W),W}if(Z){let W=_Z(X,Y,void 0);return X.on.selectorCreation.next(W),W}let G=YZ(X,Y,void 0);return X.on.selectorCreation.next(G),G}function EU(X,Y){let Z=t(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"},B0(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"},B0(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"},B0(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"},B0(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"),Q1(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 OU=(X,Y)=>{let Z=t(X);if(Z.operation.open)return Z.operation.prev.get(Y.key);return Z.valueMap.get(Y.key)},lG=(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=OU(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 U2(X,Y,Z,_){function G(F){if(X.operation.open){if(W?.type==="atom"&&$Z(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)}tY(X,Y);let W=B0(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 F2(X,W.key))H.set(F,lG(X,W,O));Q=function(O){let D=F2(X,W.key);for(let[A,R]of H)if(D.get(A))D.delete(A);else R(),H.delete(A);for(let[A,R]of D)H.set(A,lG(X,W,R));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 VU=(X,Y,Z,_)=>{let G=B0(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 GZ=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=Q1(Z)?Z.transactionMeta.update.token.key:"main",$=`tracker-from-core:${G}:${W}:${_}`,H=(Q)=>{D8(eY,Z,Y,Q)};this.unsubscribeFromInnerValue=h1(Z,X).subscribe($,H),this.unsubscribeFromState=U2(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=Q1(Z)?Z.transactionMeta.update.token.key:"main",$=`tracker-to-core:${G}:${W}:${_}`;U2(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=VU(Z,{key:z,type:"timeline"},$,function(D){F(),k1(Z,X,(A)=>{if(D==="redo"&&Q)A.do(Q);else if(D==="undo"&&J)A.undo(J);return A})});return}k1(Z,X,(F)=>(F.do(Q),F))},{inboundTracker:!0}))}mutableAtomToken;latestSignalToken;[Symbol.dispose];constructor(X,Y){let Z=t(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 M6(X,Y,Z){X.logger.info("\uD83D\uDD28","atom",Y.key,`creating in store "${X.config.name}"`);let _=t(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 Y0,Q={...Y,type:$,install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${z.config.name}"`),M6(z,Y,Z)},subject:H};if(Z)Q.family=Z;_.atoms.set(Q.key,Q);let J=y1(Q);if(new GZ(J,X),!Z)fG(X,{key:`${G}:JSON`,get:({get:z})=>z(J).toJSON(),set:({set:z},F)=>{z(J,Y.class.fromJSON(F))}});if(Y.effects){let z=0,F=[];for(let O of Y.effects){let D=O({resetSelf:()=>{L6(X,J)},setSelf:(A)=>{k1(X,J,A)},onSet:(A)=>U2(X,J,`effect[${z}]`,A),token:J,store:nY(X)});if(D)F.push(D);++z}Q.cleanup=()=>{for(let O of F)O()}}return X.on.atomCreation.next(J),J}var DU=class{trackers=new Map;latestSignalAtoms;mutableAtoms;constructor(X,Y){let Z=_2(Y,{key:`*${X.key}`,default:null},["mutable","updates"]);this.latestSignalAtoms=B0(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 GZ($,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 Y0,H={..._,create:(Q)=>{let J=j0(Q),z={key:Y.key,subKey:J},F=`${Y.key}(${J})`,O=t(X),D={key:F,class:Y.class};if(Y.effects)D.effects=Y.effects(Q);return M6(O,D,z)},class:Y.class,subject:W,install:(Q)=>yY(Q,Y),internalRoles:Z};return X.families.set(Y.key,H),aY(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 DU(H,X),_}var LU=(X,Y)=>{let Z=t(Y),_=`${X.key}:JSON`;return Z.families.get(_)},h4=(X,Y)=>{if(Y.family){let Z=t(X),_={key:`${Y.family.key}:JSON`,type:"writable_pure_selector_family"},G=B0(Z,_),W=X1(Y.family.subKey);return e0(X,G,W)}return{type:"writable_pure_selector",key:`${Y.key}:JSON`}};var A6=(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(eG(X,Y),K1(X,Y,J),W){case"atom":WZ(X,Y);break;case"readonly_pure_selector":case"writable_pure_selector":G7(X,_);break}X7(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 MU(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"&&Q1(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 GZ(G,W),_=Q}return _}function _7(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 WZ(X,Y){let Z=t(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(Y7(Z,$))continue;_7(Z,$),N6(Z,$)}}}function G7(X,Y){let Z=t(X),_=Z.selectorGraph.getRelationEntries({upstreamSelectorKey:Y}).filter(([G,{source:W}])=>W===Y);for(let[G]of _){if(Y7(Z,G))continue;_7(Z,G),N6(Z,G),G7(X,G)}}function x4(X,Y,Z,_){let{key:W}=Y;X.logger.info("\uD83D\uDD28","atom",W,"is being created");let $=t(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 Y0,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 A=D({resetSelf:()=>{L6(X,z)},setSelf:(R)=>{k1(X,z,R)},onSet:(R)=>U2(X,z,`effect[${F}]`,R),token:z,store:nY(X)});if(A)O.push(A);++F}J.cleanup=()=>{for(let D of O)D()}}return X.on.atomCreation.next(z),z}function $Z(X,Y){if("internalRoles"in X===!1)return!1;return X.internalRoles.includes(Y)}function W7(X,Y){let Z=t(X),{key:_,family:G}=Y,W=B0(Z,Y);if(!G)X.logger.error("\u274C","atom",_,"Standalone atoms cannot be disposed.");else{W.cleanup?.();let $=X.valueMap.get(W.key),H=sY(X,Y),Q=B0(X,H).subject,J={type:"state_disposal",subType:"atom",token:Y,value:$,timestamp:Date.now()};Q.next(J);let z=Q1(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=A6(Y);W7(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(([A])=>A===W.family?.key),D=$Z(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 $7=class{toolkit;options;relations;states;relatedKeysAtoms;transact(X,Y){let Z=this.toolkit;this.toolkit=X,Y(this),this.toolkit=Z}store;[Symbol.dispose](){}constructor(X,Y=D1.STORE){this.store=Y,this.options=X,this.store.miscResources.set(`join:${X.key}`,this),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:A,set:R}=z,v=D(G,F),j=A(v);for(let P of j){if(O.includes(P))continue;R(G,P,(h)=>{return h.delete(F),h})}R(v,(P)=>{P.clear();for(let h of O){let i=D(G,h),p=A(i),y=p.has(F);if(this.relations.cardinality==="1:n"){let m=[];for(let _0 of p){if(_0===F)continue;let u0;if(D8(eY,this.store,G,_0,(K)=>{return K.delete(h),u0=K.size,K}),u0===0)m.push(_0)}if(!y&&p.size>0)R(i,(_0)=>{return _0.clear(),_0});for(let _0 of m)Y.keyRefsInJoins.delete(Z2(h,_0))}if(!y)R(i,(m)=>{return m.add(F),m});P.add(h)}return P})},$=(z,F,O)=>{let{set:D}=z;D(G,F,(A)=>{for(let R of O)A.add(R);return A});for(let A of O)D(G,A,(R)=>{return R.add(F),R});return!0},H=new W4(X,{externalStore:{getRelatedKeys:(z)=>this.toolkit.get(G,z),addRelation:(z,F)=>{this.store.keyRefsInJoins.set(`"${z}"`,X.key),this.store.keyRefsInJoins.set(`"${F}"`,X.key),this.store.keyRefsInJoins.set(Z2(z,F),X.key),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,(D)=>{return D.delete(F),D}),this.toolkit.set(G,F,(D)=>{return D.delete(z),D});let O=Z2(z,F);this.store.keyRefsInJoins.delete(O)},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=()=>z2(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 z2(Y,{key:`${X.key}/multipleRelatedKeys`,get:(z)=>({get:F})=>{let O=LU(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)}`,A={[O]:z,[D]:F};this.relations=H,this.states=A;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 hG(X,Y){return X.joins.set(Y.key,new $7(Y)),{key:Y.key,type:"join",a:Y.between[0],b:Y.between[1],cardinality:Y.cardinality}}function HZ(X,Y){let Z=Y.joins.get(X.key);if(Z===void 0){let _=D1.STORE.joins.get(X.key);if(_===void 0)throw Error(`Join "${X.key}" not found in store "${Y.config.name}"`);let G=nY(Y);Z=new $7(_.options,G),Y.joins.set(X.key,Z)}return Z}function W2(X,Y,Z){let _=HZ(X,Z),G=t(Z);if(Q1(G)){let{toolkit:W}=G.transactionMeta;_.transact(W,({relations:$})=>{Y($)})}else Y(_.relations)}function gF(X,Y,Z){let _=HZ(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 kG(X,Y){return HZ(X,Y).relatedKeysAtoms}var AU=(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)},RU=(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 JZ=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}},J7=new JZ({number:(X)=>typeof X==="number",string:(X)=>typeof X==="string",boolean:(X)=>typeof X==="boolean",null:(X)=>X===null});function Q7(X){if(!X)return!1;return Object.getPrototypeOf(X)===Object.prototype}var z7=new JZ({object:Q7,array:(X)=>Array.isArray(X)}),wU=new JZ({...J7.supported,...z7.supported}),K6=(X)=>{if(X===void 0)return"undefined";let Y=wU.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=D1.STORE){this.store=Y,this.atomIndex=AU(this.store),this.selectorIndex=RU(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=vY(this.atomIndex),_=vY(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}},H7=(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]):Q7(G)?Object.entries(G):[];for(let[Q,J]of H){let z=Z([..._,Q],J);if(z?.jobComplete)return z}return{}};Z([],X)};function NU(X,Y){return{summary:`${X<Y?"+":"-"}${Math.abs(X-Y)} (${X} \u2192 ${Y})`}}function IU(X,Y){return{summary:`${X.length<Y.length?"+":"-"}${Math.abs(X.length-Y.length)} ("${X}" \u2192 "${Y}")`}}function KU(X,Y){return{summary:`${X} \u2192 ${Y}`}}function F7(X,Y,Z){let _="",G=[],W=[],$=[];return H7(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])}}}),H7(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 BU(X,Y,Z){return F7(X,Y,Z)}var TU=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=K6(X),W=K6(Y);if(G===W)return{summary:`${G} \u2192 ${W}`};return{summary:`Type change: ${G} \u2192 ${W}`}}},JB=new TU(J7,z7,{number:NU,string:IU,boolean:KU,null:()=>({summary:"No Change"}),object:F7,array:BU});var CU=E8({key:"mutex",default:!1}),qU=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 qU;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}),U7=U8({key:"roomIndex",class:G4});var E2=O6({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(X)=>typeof X==="string",isBType:(X)=>typeof X==="string"}),DB=V6({key:"usersInMyRoomView",get:(X)=>({find:Y})=>{let Z=jG(E2);return[Y(Z,X)]}});var TB=E8({key:"redactor",default:{occlude:(X)=>X}}),CB=E8({key:"unacknowledgedUpdates",default:()=>[]});var QZ=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 QZ{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(`
59
+ ${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(F1(W)&&W.transactionMeta.phase==="building")W.transactionMeta.update.subEvents.push(z);return Z}function ZU(X,Y,Z){switch(Z){case"newValue":X7(X,Y);break;case"oldValue":W2(X,Y.token);break}}function _U(X,Y,Z){switch(Z){case"newValue":W2(X,Y.token);break;case"oldValue":if(X7(X,Y),Y.subType==="atom")X.valueMap.set(Y.token.key,Y.value);break}}function X7(X,Y){let{token:Z}=Y;if(Y.subType==="writable"&&Y.value)b1(X,Z,Y.value);else k1(X,Z)}function GU(X,Y,Z){switch(Z){case"newValue":yY(X,Y.provenance,Y.key);break;case"oldValue":eY(X,Y.key);break}}function WU(X,Y,Z){switch(Z){case"newValue":eY(X,Y.key);break;case"oldValue":yY(X,Y.provenance.map(X1),Y.key);for(let[_,G]of Y.values){let W=X.families.get(_);if(W){k1(X,W,Y.key);let $=`${_}(${j0(Y.key)})`;X.valueMap.set($,G)}}break}}function $U(X,Y,Z){switch(Z){case"newValue":for(let _ of Y.to)gY(X,_,Y.key,Y.exclusive?"exclusive":void 0);break;case"oldValue":{let _="exclusive";for(let G of Y.from)gY(X,G,Y.key,_),_=void 0}break}}function Y7(X,Y,Z){let _=Z==="newValue"?Y.subEvents:[...Y.subEvents].reverse();for(let G of _)switch(G.type){case"atom_update":XU(X,G,Z);break;case"state_creation":ZU(X,G,Z);break;case"state_disposal":_U(X,G,Z);break;case"molecule_creation":GU(X,G,Z);break;case"molecule_disposal":WU(X,G,Z);break;case"molecule_transfer":$U(X,G,Z);break;case"transaction_outcome":Y7(X,G,Z);break}}function V8(X){return"epoch"in X.transactionMeta}function F1(X){return"phase"in X.transactionMeta}function Z7(X,Y){return X.transactionMeta.actionContinuities.getRelatedKey(Y)}function HU(X,Y){return X.transactionMeta.epoch.get(Y)}function JU(X,Y){let Z=Z7(X,Y);if(Z===void 0)return;return HU(X,Z)}function QU(X,Y,Z){let _=Z7(X,Y);if(_!==void 0)X.transactionMeta.epoch.set(_,Z)}function zU(X,Y){let Z=t(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),Y7(_,Z.transactionMeta.update,"newValue"),V8(_))QU(_,Z.transactionMeta.update.token.key,Z.transactionMeta.update.epoch),B0(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(F1(_))_.transactionMeta.update.subEvents.push(Z.transactionMeta.update);_.on.transactionApplying.next(null)}function FU(X){return{store:X}}var UU=(X,Y,Z,_)=>{let G=t(X),W={parent:G,child:null,on:G.on,loggers:G.loggers,logger:G.logger,config:G.config,atoms:new y1(G.atoms),atomsThatAreDefault:new Set(G.atomsThatAreDefault),families:new y1(G.families),joins:new y1(G.joins),operation:{open:!1},readonlySelectors:new y1(G.readonlySelectors),timelines:new y1(G.timelines),timelineTopics:G.timelineTopics.overlay(),trackers:new Map,transactions:new y1(G.transactions),selectorAtoms:G.selectorAtoms.overlay(),selectorGraph:G.selectorGraph.overlay(),writableSelectors:new y1(G.writableSelectors),valueMap:new y1(G.valueMap),defaults:G.defaults,disposalTraces:X.disposalTraces.copy(),molecules:new y1(G.molecules),moleculeGraph:G.moleculeGraph.overlay(),moleculeData:G.moleculeData.overlay(),keyRefsInJoins:G.keyRefsInJoins.overlay(),miscResources:new y1(G.miscResources)},$=JU(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)=>k1(Q,...J),set:(...J)=>{b1(Q,...J)},reset:(...J)=>{R6(Q,...J)},run:(J,z=gG())=>bY(Q,J,z),find:(...J)=>e0(X,...J),json:(J)=>k4(Q,J),dispose:(...J)=>{W2(Q,...J)},env:()=>FU(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 pY(X,Y){let{key:Z}=Y,_=X.transactions.has(Z),G={key:Z,type:"transaction",run:($,H)=>{let Q=UU(X,g1(G),$,H);try{let{toolkit:J}=Q.transactionMeta,z=Y.do(J,...$);return zU(Q,z),z}catch(J){throw eF(Q),X.logger.warn("\uD83D\uDCA5","transaction",Z,"caught:",J),J}},install:($)=>pY($,Y),subject:new Y0};t(X).transactions.set(Z,G);let W=g1(G);if(!_)X.on.transactionCreation.next(W);return W}var pG=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:(...X)=>X.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 tF(100);molecules=new Map;moleculeGraph=new $4({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});moleculeData=new $4({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});keyRefsInJoins=new $4({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});miscResources=new Map;on={atomCreation:new Y0,atomDisposal:new Y0,selectorCreation:new Y0,selectorDisposal:new Y0,timelineCreation:new Y0,transactionCreation:new Y0,transactionApplying:new sF(null),operationClose:new Y0,moleculeCreation:new Y0,moleculeDisposal:new Y0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral",isProduction:globalThis.process?.env?.NODE_ENV==="production"};loggers=[new bG("warn",(X,Y,Z)=>!D8(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},V8(Y))this.transactionMeta={epoch:new Map(Y?.transactionMeta.epoch),actionContinuities:new $4(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=k4(Y,_),W=N6(_);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)}}},L1={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new pG({name:"IMPLICIT_STORE",lifespan:"ephemeral",isProduction:globalThis.process?.env?.NODE_ENV==="production"}),globalThis.ATOM_IO_IMPLICIT_STORE}};var EU=class extends Error{constructor(X,Y){super(`${G4[X.type]} ${j0(X.key)} not found in store "${Y.config.name}".`)}};function B0(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 EU(Y,X)}function _7(X,Y,Z,_){let G=X.disposalTraces.buffer.find((W)=>W?.key===j0(_));switch(X.logger.error("\u274C",Y.type,Y.key,"gets a fallback value because key",_,"is not allocated",G?`This key was previously disposed:
60
+ ${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 I6(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 B1(X,Y,$)}throw $}return B1(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=B1(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 B1(X,Y,W)}}}function h4(X,Y,Z){if(X.valueMap.has(Y.key))return CU(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 I6(X,Y);case"mutable_atom":{let G=new Y.class;return X.logger.info("\u2728",Y.type,_,"created new instance",G),B1(X,Y,G)}}}function XZ(X,Y){return B0(X,{key:Y.family.key,type:`${Y.type}_family`})}var sG={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"),OU=Symbol("DO_NOT_CREATE");function Q2(X,Y,Z,_){let G=j0(_),W=Y.molecules.get(G);if(!W&&Y.config.lifespan==="immortal"){let{type:H,key:Q}=Z;return Y.logger.warn("\uD83D\uDCA3","key",G,"was used to mint a counterfeit token for",H,`"${Q}"`),{counterfeit:!0,key:`${Q}(${G})`,type:sG[H],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;return{key:`${Q}(${G})`,type:sG[H],family:{key:Q,subKey:G}}}return $}function YZ(X,...Y){let Z,_,G,W,$;if(Y.length===1){if($=Y[0],"family"in $){let Q=XZ(X,$);if(G=B0(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=B0(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=t(X);if($.family){if(V8(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(F1(z)&&z.on.transactionApplying.state===null)z.transactionMeta.update.subEvents.push(J)}}return{token:$,family:G,subKey:W,isNew:Boolean(_)}}function k1(X,...Y){let{token:Z,family:_,subKey:G}=YZ(X,...Y);if("counterfeit"in Z&&_&&G)return _7(X,Z,_,G);return h4(X,B0(X,Z))}function z2(X,Y,Z){let _=j0(Z),G=`${Y.key}(${_})`,W=t(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 g1($);return $}function e0(X,Y,Z){let _=B0(X,Y),G=z2(X,Y,Z);if(G)return G;return Q2(OU,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.config.isProduction===!0)X.logger.error("\u2757","readonly_pure_selector_family",_,`Overwriting an existing ${G4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Y0,J={...W,create:(z)=>{let F=j0(z),O={key:_,subKey:F},D=`${_}(${F})`,w=t(X),R={key:D,get:Y.get(z)};if(Y.catch)R.catch=Y.catch;return WZ(w,R,O)},internalRoles:Z,subject:H,install:(z)=>F2(z,Y),default:(z)=>{return Y.get(z)({get:(...F)=>k1(X,...F),find:(...F)=>e0(X,...F),json:(F)=>k4(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.config.isProduction===!0)X.logger.error("\u2757","atom_family",Y.key,`Overwriting an existing ${G4[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 Y0,H={..._,create:(Q)=>{let J=j0(Q),z={key:Y.key,subKey:J},F=`${Y.key}(${J})`,O=t(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 f4(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 G7(X,Y,Z){let _=Y.key,G="readonly_held_selector_family",W={key:_,type:"readonly_held_selector_family"},$=X.families.get(_);if($&&X.config.isProduction===!0)X.logger.error("\u2757","readonly_held_selector_family",_,`Overwriting an existing ${G4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Y0,J={...W,create:(z)=>{let F=j0(z),O={key:_,subKey:F},D=`${_}(${F})`;return GZ(t(X),{key:D,const:Y.const(z),get:Y.get(z)},O)},internalRoles:Z,subject:H,install:(z)=>G7(z,Y),default:Y.const};return X.families.set(_,J),W}function W7(X,Y,Z){let _=Y.key,G="writable_held_selector_family",W={key:_,type:"writable_held_selector_family"},$=X.families.get(_);if($&&X.config.isProduction===!0)X.logger.error("\u2757","writable_held_selector_family",_,`Overwriting an existing ${G4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Y0,J={...W,create:(z)=>{let F=j0(z),O={key:_,subKey:F},D=`${_}(${F})`;return $Z(t(X),{key:D,const:Y.const(z),get:Y.get(z),set:Y.set(z)},O)},internalRoles:Z,subject:H,install:(z)=>W7(z,Y),default:Y.const};return X.families.set(_,J),W}function ZZ(X,Y,Z){let _=Y.key,G="writable_pure_selector_family",W={key:_,type:"writable_pure_selector_family"},$=X.families.get(_);if($&&X.config.isProduction===!0)X.logger.error("\u2757","writable_pure_selector_family",_,`Overwriting an existing ${G4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Y0,J={...W,create:(z)=>{let F=j0(z),O={key:_,subKey:F},D=`${_}(${F})`,w=t(X),R={key:D,get:Y.get(z),set:Y.set(z)};if(Y.catch)R.catch=Y.catch;return HZ(w,R,O)},internalRoles:Z,subject:H,install:(z)=>ZZ(z,Y),default:(z)=>{return Y.get(z)({get:(...F)=>k1(X,...F),find:(...F)=>e0(X,...F),json:(F)=>k4(X,F)})}};return X.families.set(_,J),W}function mY(X,Y){let Z="set"in Y,_="const"in Y;if(_&&Z)return W7(X,Y,void 0);if(_)return G7(X,Y,void 0);if(Z)return ZZ(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{B0(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":U7(X,Z);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":NU(X,Z);break}}function $7(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}"${F1(X)?` ${X.transactionMeta.phase} "${X.transactionMeta.update.token.key}"`:""}`),X}function H7(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 J7=(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 rY(X,Y,{oldValue:Z,newValue:_},G,W){let $=g1(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=t(X);if($.family){if(V8(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(F1(O)&&O.on.transactionApplying.state===null)O.transactionMeta.update.subEvents.push(F)}return}let{key:H,subject:Q,type:J}=Y,z={oldValue:oY(Z)?Z.READONLY_VIEW:Z,newValue:oY(_)?_.READONLY_VIEW:_};if(V8(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(F1(X)&&(J==="mutable_atom"||J==="atom")){if(X.on.transactionApplying.state===null){if(oY(_))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(zZ(Y,"tracker:signal")){let F=H.slice(1),O=X.atoms.get(F);if(h4(X,O,"mut").do(z.newValue)===null===!0)QZ(X,O)}}}var sY=(X,Y,Z)=>{let _=h4(X,Y,"mut"),G=iY(Z,_);return X.logger.info("\u2B50","atom",Y.key,"setting value",G),G=B1(X,Y,G),B6(X,Y.key),QZ(X,Y),{oldValue:_,newValue:G}};function lY(X,Y){switch(Y.type){case"mutable_atom":return sY(X,Y,new Y.class);case"atom":{let Z;if(H2(Y.default))Z=I6(X,Y);else Z=Y.default;return sY(X,Y,Z)}}}function VU(X,Y){let Z;switch(Y.type){case"atom":case"mutable_atom":Z=lY(X,Y);break;case"writable_held_selector":{let _=U2(X,Y.key);for(let W of _.values())rY(X,Y,lY(X,W),!1);let G=Y.getFrom(X);Z={oldValue:G,newValue:G}}break;case"writable_pure_selector":{let _=I6(X,Y),G=U2(X,Y.key);for(let W of G.values())rY(X,Y,lY(X,W),!1);Z={oldValue:_,newValue:I6(X,Y)}}break}return Z}function b1(X,...Y){L8(K6,X,...Y)}var tY=Symbol("RESET");function R6(X,...Y){b1(X,...[...Y,tY])}function DU(X,Y,Z){let _,G,W,{type:$,key:H}=Y;switch(Y.type){case"writable_pure_selector":_=h4(X,Y,"mut"),G=iY(Z,_),G=B1(X,Y,G);break;case"writable_held_selector":W=Y.const,iY(Z,W),_=W,G=W}return X.logger.info("\u2B50",$,H,"setting to",G),B6(X,H),Y.setSelf(G),{oldValue:_,newValue:G}}var LU=(X,Y,Z)=>{let _;switch(Y.type){case"atom":case"mutable_atom":_=sY(X,Y,Z);break;case"writable_pure_selector":case"writable_held_selector":_=DU(X,Y,Z);break}return _},K6=Symbol("OWN_OP"),_Z=Symbol("JOIN_OP");function L8(X,Y,...Z){let _,G,W,$,H,Q;if(Z.length===2){if(W=Z[0],Q=Z[1],"family"in W)if($=XZ(Y,W),H=X1(W.family.subKey),_=z2(Y,$,H),!_)W=G=Q2(J2,Y,$,H);else W=_}else if($=B0(Y,Z[0]),H=Z[1],Q=Z[2],_=z2(Y,$,H),!_)W=G=Q2(J2,Y,$,H);else W=_;let J=Q===tY?"reset":"set",z;if(X===K6){let D=$7(Y,W);if(typeof D==="number"){let w=D,R=Y.on.operationClose.subscribe(`waiting to ${J} "${W.key}" at T-${w}`,function(){R(),Y.logger.info("\uD83D\uDFE2",W.type,W.key,"resuming deferred",J,`from T-${w}`),L8(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((R)=>R?.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=B0(z,W),O;if(Q===tY)O=VU(z,F);else O=LU(z,F,Q);if(rY(z,F,O,Boolean(G),$),X===K6)H7(z)}var Q7=(X,Y)=>t(X).atoms.has(Y),AU=(X,Y)=>t(X).writableSelectors.has(Y),MU=(X,Y)=>t(X).readonlySelectors.has(Y),RU=(X,Y)=>Q7(X,Y)||AU(X,Y)||MU(X,Y);function tG(X,Y){return t(X).selectorGraph.getRelationEntries({downstreamSelectorKey:Y}).filter(([Z,{source:_}])=>_!==Y).map(([Z,{source:_}])=>_).filter((Z)=>RU(X,Z))}function U2(X,Y,Z=new Set){let _=tG(X,Y),G=new Map;while(_.length>0){let W=_.pop();if(Z.has(W))continue;if(Z.add(W),Q7(X,W)){let $=X.atoms.get(W);G.set($.key,$)}else _.push(...tG(X,W))}return G}function wU(X,Y,Z,_,G){let W=t(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=t(X),{token:$,family:H,subKey:Q}=YZ(X,...G),J;if("counterfeit"in $&&H&&Q)J=_7(X,$,H,Q);else J=h4(X,B0(X,$));return X.logger.info("\uD83D\uDD0C",Y,Z,`registers dependency ( "${$.key}" =`,J,")"),W.selectorGraph.set({upstreamSelectorKey:$.key,downstreamSelectorKey:Z},{source:$.key}),wU(X,Y,Z,$,_),J},set:(...G)=>{L8(_Z,t(X),...G)},find:(...G)=>e0(X,...G),json:(G)=>k4(X,G)}}function GZ(X,Y,Z){let _=t(X),G=new Y0,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:(R)=>{let v=R.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[j,{source:P}]of v)if(P!==$)R.selectorGraph.delete(j,$);return R.selectorAtoms.delete($),Y.get({get:J,find:z,json:F},H),B1(R,D,H),X.logger.info("\u2728","readonly_held_selector",$,"=",H),W.clear(),H},install:(R)=>GZ(R,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 WZ(X,Y,Z){let _=t(X),G=new Y0,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=t(X),R=w.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[j,{source:P}]of R)if(P!==$)w.selectorGraph.delete(j,$);w.selectorAtoms.delete($);let v=B1(w,O,Y.get({get:Q,find:J,json:z}));return X.logger.info("\u2728","readonly_pure_selector",$,"=",v),W.clear(),v},install:(w)=>WZ(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 $Z(X,Y,Z){let _=t(X),G=new Y0,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},v={...Y,type:"writable_held_selector",subject:G,getFrom:(P)=>{let h=P.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[i,{source:g}]of h)if(g!==$)P.selectorGraph.delete(i,$);return P.selectorAtoms.delete($),Y.get(D,H),B1(P,v,H),X.logger.info("\u2728","writable_held_selector",$,"=",H),W.clear(),H},setSelf:()=>{Y.set(J,H)},install:(P)=>$Z(P,Y,Z)};if(Z)v.family=Z;_.writableSelectors.set($,v);let j={key:$,type:"writable_held_selector"};if(Z)j.family=Z;return j}function HZ(X,Y,Z){let _=t(X),G=new Y0,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},R={...Y,type:"writable_pure_selector",subject:G,getFrom:(j)=>{let P=j.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[i,{source:g}]of P)if(g!==$)j.selectorGraph.delete(i,$);j.selectorAtoms.delete($);let h=B1(j,R,Y.get(O));return X.logger.info("\u2728","writable_pure_selector",$,"=",h),W.clear(),h},setSelf:(j)=>{Y.set(Q,j)},install:(j)=>HZ(j,Y,Z)};if(Z)R.family=Z;_.writableSelectors.set($,R);let v={key:$,type:"writable_pure_selector"};if(Z)v.family=Z;return v}function mG(X,Y){let Z="set"in Y,_="const"in Y;if(_&&Z){let W=$Z(X,Y,void 0);return X.on.selectorCreation.next(W),W}if(_){let W=GZ(X,Y,void 0);return X.on.selectorCreation.next(W),W}if(Z){let W=HZ(X,Y,void 0);return X.on.selectorCreation.next(W),W}let G=WZ(X,Y,void 0);return X.on.selectorCreation.next(G),G}function NU(X,Y){let Z=t(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"},B0(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"},B0(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"},B0(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"},B0(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"),F1(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 IU=(X,Y)=>{let Z=t(X);if(Z.operation.open)return Z.operation.prev.get(Y.key);return Z.valueMap.get(Y.key)},aG=(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=IU(X,Y),W=h4(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"&&zZ(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)}YZ(X,Y);let W=B0(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($){h4(X,W);for(let[F,O]of U2(X,W.key))H.set(F,aG(X,W,O));Q=function(O){let D=U2(X,W.key);for(let[w,R]of H)if(D.get(w))D.delete(w);else R(),H.delete(w);for(let[w,R]of D)H.set(w,aG(X,W,R));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 KU=(X,Y,Z,_)=>{let G=B0(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 JZ=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=f4(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=`tracker-from-core:${Z.config.name}:${F1(Z)?Z.transactionMeta.update.token.key:"main"}:${_}`,W=($)=>{L8(_Z,Z,Y,$)};this.unsubscribeFromInnerValue=k1(Z,X).subscribe(G,W),this.unsubscribeFromState=E2(Z,X,G,function(H){if(H.newValue!==H.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=H.newValue.subscribe(G,W)}.bind(this))}supplySignalsToCore(X,Y,Z){let _=X.key,G=`tracker-to-core:${Z.config.name}:${F1(Z)?Z.transactionMeta.update.token.key:"main"}:${_}`;E2(Z,Y,G,Object.assign(function({newValue:$,oldValue:H}){let Q=Z.timelineTopics.getRelatedKey(Y.key);if(Q&&Z.timelines.get(Q)?.timeTraveling){let J=KU(Z,{key:Q,type:"timeline"},G,function(F){J(),b1(Z,X,(O)=>{if(F==="redo"&&$)O.do($);else if(F==="undo"&&H)O.undo(H);return O})});return}b1(Z,X,(J)=>(J.do($),J))},{inboundTracker:!0}))}mutableAtomToken;latestSignalToken;[Symbol.dispose];constructor(X,Y){let Z=t(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 _=t(X),{key:G}=Y,W=_.atoms.get(G),$="mutable_atom";if(W?.type===$&&X.config.isProduction===!0)return X.logger.error("\u274C",$,G,"Tried to create atom, but it already exists in the store."),g1(W);let H=new Y0,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=g1(Q);if(new JZ(J,X),!Z)mG(X,{key:`${G}:JSON`,get:({get:z})=>z(J).toJSON(),set:({set:z},F)=>{z(J,Y.class.fromJSON(F))}});if(Y.effects){let z=0,F=[];for(let O of Y.effects){let D=O({resetSelf:()=>{R6(X,J)},setSelf:(w)=>{b1(X,J,w)},onSet:(w)=>E2(X,J,`effect[${z}]`,w),token:J,store:aY(X)});if(D)F.push(D);++z}Q.cleanup=()=>{for(let O of F)O()}}return X.on.atomCreation.next(J),J}var BU=class{trackers=new Map;latestSignalAtoms;mutableAtoms;constructor(X,Y){this.latestSignalAtoms=B0(Y,G2(Y,{key:`*${X.key}`,default:null},["mutable","updates"])),this.mutableAtoms=X;let Z=(_)=>{let{type:G,token:W}=_;if(W.family){let $=X1(W.family.subKey);switch(G){case"state_creation":this.trackers.set($,new JZ(W,Y));break;case"state_disposal":{let H=this.trackers.get($);if(H)H[Symbol.dispose](),this.trackers.delete($)}}}};this.mutableAtoms.subject.subscribe(`store=${Y.config.name}::tracker-atom-family`,Z)}};function uY(X,Y,Z){let _={key:Y.key,type:"mutable_atom_family"},G=X.families.get(Y.key);if(G&&X.config.isProduction===!0)X.logger.error("\u2757","mutable_atom_family",Y.key,`Overwriting an existing ${G4[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 Y0,H={..._,create:(Q)=>{let J=j0(Q),z={key:Y.key,subKey:J},F=`${Y.key}(${J})`,O=t(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)=>uY(Q,Y),internalRoles:Z};return X.families.set(Y.key,H),ZZ(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 BU(H,X),_}var TU=(X,Y)=>{let Z=t(Y),_=`${X.key}:JSON`;return Z.families.get(_)},k4=(X,Y)=>{if(Y.family)return e0(X,B0(t(X),{key:`${Y.family.key}:JSON`,type:"writable_pure_selector_family"}),X1(Y.family.subKey));return{type:"writable_pure_selector",key:`${Y.key}:JSON`}};var N6=(X)=>{let Y={type:"atom",key:`*${X.key}`};if(X.family)Y.family={key:`*${X.family.key}`,subKey:X.family.subKey};return Y};function oY(X){return typeof X==="object"&&X!==null&&"do"in X&&"undo"in X&&"subscribe"in X&&"READONLY_VIEW"in X&&"toJSON"in X}function B1(X,Y,Z){let{key:_,subject:G,type:W}=Y,$=X.valueMap.get(_);if($ instanceof nY&&!$.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 nY(Z);return X.valueMap.set(_,H),H.then(function(J){if(X.valueMap.get(_)===H){switch($7(X,Y),B1(X,Y,J),W){case"atom":QZ(X,Y);break;case"readonly_pure_selector":case"writable_pure_selector":F7(X,_);break}H7(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 CU(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"&&F1(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 JZ(G,W),_=Q}return _}function z7(X,Y){let Z=X.valueMap.get(Y);if(Z instanceof nY){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 QZ(X,Y){let Z=t(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(J7(Z,$))continue;z7(Z,$),B6(Z,$)}}}function F7(X,Y){let Z=t(X),_=Z.selectorGraph.getRelationEntries({upstreamSelectorKey:Y}).filter(([G,{source:W}])=>W===Y);for(let[G]of _){if(J7(Z,G))continue;z7(Z,G),B6(Z,G),F7(X,G)}}function f4(X,Y,Z,_){let{key:W}=Y;X.logger.info("\uD83D\uDD28","atom",W,"is being created");let $=t(X),H=$.atoms.get(W);if(H?.type==="atom"&&X.config.isProduction===!0)return X.logger.error("\u274C","atom",W,"Tried to create atom, but it already exists in the store."),g1(H);let Q=new Y0,J={...Y,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",W,`installing in store "${F.config.name}"`),f4(F,Y,Z)},subject:Q};if(Z)J.family=Z;if(_)J.internalRoles=_;$.atoms.set(W,J);let z=g1(J);if(Y.effects){let F=0,O=[];for(let D of Y.effects){let w=D({resetSelf:()=>{R6(X,z)},setSelf:(R)=>{b1(X,z,R)},onSet:(R)=>E2(X,z,`effect[${F}]`,R),token:z,store:aY(X)});if(w)O.push(w);++F}J.cleanup=()=>{for(let D of O)D()}}return X.on.atomCreation.next(z),z}function zZ(X,Y){if("internalRoles"in X===!1)return!1;return X.internalRoles.includes(Y)}function U7(X,Y){let Z=t(X),{key:_,family:G}=Y,W=B0(Z,Y);if(!G)X.logger.error("\u274C","atom",_,"Standalone atoms cannot be disposed.");else{W.cleanup?.();let $=X.valueMap.get(W.key),H=B0(X,XZ(X,Y)).subject,Q={type:"state_disposal",subType:"atom",token:Y,value:$,timestamp:Date.now()};H.next(Q);let J=F1(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")U7(X,N6(Y)),X.trackers.delete(_);if(X.logger.info("\uD83D\uDD25","atom",_,"deleted"),J&&Z.transactionMeta.phase==="building"){let z=Z.transactionMeta.update.subEvents.at(-1),F=z?.type==="molecule_disposal"&&z.values.some(([D])=>D===W.family?.key),O=zZ(W,"tracker:signal");if(!F&&!O)Z.transactionMeta.update.subEvents.push(Q)}else X.on.atomDisposal.next(Y)}}function K1(X){return X[0].toUpperCase()+X.slice(1)}var E7=class{toolkit;options;relations;states;relatedKeysAtoms;transact(X,Y){let Z=this.toolkit;this.toolkit=X,Y(this),this.toolkit=Z}store;[Symbol.dispose](){}constructor(X,Y=L1.STORE){this.store=Y,this.options=X,this.store.miscResources.set(`join:${X.key}`,this),this.toolkit={get:(...z)=>k1(Y,...z),set:(...z)=>{b1(Y,...z)},find:(...z)=>e0(Y,...z),json:(z)=>k4(Y,z)};let Z=X.between[0],_=X.between[1],G=uY(Y,{key:`${X.key}/relatedKeys`,class:W4},["join","relations"]);this.relatedKeysAtoms=G;let W=(z,F,O)=>{let{find:D,get:w,set:R}=z,v=D(G,F),j=w(v);for(let P of j){if(O.includes(P))continue;R(G,P,(h)=>{return h.delete(F),h})}R(v,(P)=>{P.clear();for(let h of O){let i=D(G,h),g=w(i),p=g.has(F);if(this.relations.cardinality==="1:n"){let m=[];for(let _0 of g){if(_0===F)continue;let u0;if(L8(_Z,this.store,G,_0,(K)=>{return K.delete(h),u0=K.size,K}),u0===0)m.push(_0)}if(!p&&g.size>0)R(i,(_0)=>{return _0.clear(),_0});for(let _0 of m)Y.keyRefsInJoins.delete(_2(h,_0))}if(!p)R(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 R of O)w.add(R);return w});for(let w of O)D(G,w,(R)=>{return R.add(F),R});return!0},H=new $4(X,{externalStore:{getRelatedKeys:(z)=>this.toolkit.get(G,z),addRelation:(z,F)=>{this.store.keyRefsInJoins.set(`"${z}"`,X.key),this.store.keyRefsInJoins.set(`"${F}"`,X.key),this.store.keyRefsInJoins.set(_2(z,F),X.key),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,(D)=>{return D.delete(F),D}),this.toolkit.set(G,F,(D)=>{return D.delete(z),D});let O=_2(z,F);this.store.keyRefsInJoins.delete(O)},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})=>{return F(TU(G,Y),z)}},["join","keys"])};switch(X.cardinality){case"1:1":{let z=Q(),F=`${Z}KeyOf${K1(_)}`,O=`${_}KeyOf${K1(Z)}`;this.relations=H,this.states={[F]:z,[O]:z};break}case"1:n":{let z=Q(),F=J(),O=`${Z}KeyOf${K1(_)}`,D=`${_}KeysOf${K1(Z)}`,w={[O]:z,[D]:F};this.relations=H,this.states=w;break}case"n:n":{let z=J(),F=`${Z}KeysOf${K1(_)}`,O=`${_}KeysOf${K1(Z)}`;this.relations=H,this.states={[F]:z,[O]:z}}}}};function uG(X,Y){return X.joins.set(Y.key,new E7(Y)),{key:Y.key,type:"join",a:Y.between[0],b:Y.between[1],cardinality:Y.cardinality}}function FZ(X,Y){let Z=Y.joins.get(X.key);if(Z===void 0){let _=L1.STORE.joins.get(X.key);if(_===void 0)throw Error(`Join "${X.key}" not found in store "${Y.config.name}"`);let G=aY(Y);Z=new E7(_.options,G),Y.joins.set(X.key,Z)}return Z}function $2(X,Y,Z){let _=FZ(X,Z),G=t(Z);if(F1(G)){let{toolkit:W}=G.transactionMeta;_.transact(W,({relations:$})=>{Y($)})}else Y(_.relations)}function nF(X,Y,Z){let _=FZ(X,Z),G;switch(X.cardinality){case"1:1":{let W=`${X.a}KeyOf${K1(X.b)}`,$=`${X.b}KeyOf${K1(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${K1(X.b)}`,$=`${X.b}KeysOf${K1(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${K1(X.b)}`,$=`${X.b}KeysOf${K1(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 dG(X,Y){return FZ(X,Y).relatedKeysAtoms}var qU=(X)=>{return f4(X,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Y=new Map;for(let[Z,_]of X.atoms){if(D8(Z))continue;let G=g1(_);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(D8(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)},jU=(X)=>{return f4(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(D8(_))continue;let W=g1(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(D8(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 UZ=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}},V7=new UZ({number:(X)=>typeof X==="number",string:(X)=>typeof X==="string",boolean:(X)=>typeof X==="boolean",null:(X)=>X===null});function D7(X){if(!X)return!1;return Object.getPrototypeOf(X)===Object.prototype}var L7=new UZ({object:D7,array:(X)=>Array.isArray(X)}),SU=new UZ({...V7.supported,...L7.supported}),C6=(X)=>{if(X===void 0)return"undefined";let Y=SU.refine(X);if(Y)return Y.type;return Object.getPrototypeOf(X).constructor.name};var CB=class X{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Y=L1.STORE){this.store=Y,this.atomIndex=qU(this.store),this.selectorIndex=jU(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=kY(this.atomIndex),_=kY(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);H.push([z,F])}}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);H.push([z,F])}}return H}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},O7=(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]):D7(G)?Object.entries(G):[];for(let[Q,J]of H){let z=Z([..._,Q],J);if(z?.jobComplete)return z}return{}};Z([],X)};function PU(X,Y){return{summary:`${X<Y?"+":"-"}${Math.abs(X-Y)} (${X} \u2192 ${Y})`}}function vU(X,Y){return{summary:`${X.length<Y.length?"+":"-"}${Math.abs(X.length-Y.length)} ("${X}" \u2192 "${Y}")`}}function xU(X,Y){return{summary:`${X} \u2192 ${Y}`}}function A7(X,Y,Z){let _="",G=[],W=[],$=[];return O7(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])}}}),O7(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 fU(X,Y,Z){return A7(X,Y,Z)}var hU=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}`}}},qB=new hU(V7,L7,{number:PU,string:vU,boolean:xU,null:()=>({summary:"No Change"}),object:A7,array:fU});var kU=O8({key:"mutex",default:!1}),bU=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)}},fB=class X{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Y){this.key=Y}static existing=new bU;static create(Y,Z){let{type:_,globals:G,actions:W,perspectives:$}=Z(new X(Y)),H={type:_,key:Y,globals:G,actions:W,perspectives:$};return X.existing.set(Y,H),H}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 hB=E8({key:"usersInRoomIndex",class:W4}),M7=E8({key:"roomIndex",class:W4});var O2=L6({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(X)=>typeof X==="string",isBType:(X)=>typeof X==="string"}),kB=A6({key:"usersInMyRoomView",get:(X)=>({find:Y})=>{return[Y(kG(O2),X)]}});var oB=O8({key:"redactor",default:{occlude:(X)=>X}}),iB=O8({key:"unacknowledgedUpdates",default:()=>[]});var EZ=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}},nB=class extends EZ{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
61
  \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
62
  \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
63
  \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()}},jU=class extends QZ{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(X){super((...Y)=>{return this.out.next(Y),this});this.id=X,this.in=new Y0,this.out=new Y0,this.in.subscribe("socket",(Y)=>{this.handleEvent(...Y)})}dispose(){for(let X of this.disposalFunctions)X()}},O7=class extends QZ{incompleteData="";unprocessedEvents=[];relays;relayServices;proc;id="#####";log(...X){this.proc.stderr.write(j0(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 `))}}++$}}),X.pid)this.id=X.pid.toString()}},yU=class extends EZ{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(X){super((...Y)=>{return this.out.next(Y),this});this.id=X,this.in=new Y0,this.out=new Y0,this.in.subscribe("socket",(Y)=>{this.handleEvent(...Y)})}dispose(){for(let X of this.disposalFunctions)X()}},w7=class extends EZ{incompleteData="";unprocessedEvents=[];relays;relayServices;proc;id="#####";log(...X){this.proc.stderr.write(j0(X.map((Y)=>Y instanceof W4?`{ ${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
65
  \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 jU(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 E7=new Map;var jB=D6({key:"joinRoom",do:(X,Y,Z,_)=>{let G={enteredAtEpoch:_};return W2(E2,(W)=>{W.set({room:Y,user:Z})},X.env().store),G}}),SB=D6({key:"leaveRoom",do:({env:X},Y,Z)=>{W2(E2,(_)=>{_.delete({room:Y,user:Z})},X().store)}}),PB=D6({key:"destroyRoom",do:({set:X,env:Y},Z)=>{W2(E2,(G)=>{G.delete({room:Z})},Y().store),X(U7,(G)=>(G.delete(Z),G));let _=E7.get(Z);if(_)_.emit("exit"),E7.delete(Z)}}),vB=E8({key:"sockets",default:null}),xB=U8({key:"socketsIndex",class:G4}),fB=U8({key:"usersIndex",class:G4}),hB=O6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(X)=>X.startsWith("user::"),isBType:(X)=>X.startsWith("socket::")}),kB=V6({key:"userMutualSituationalAwarenessIndexes",get:(X)=>()=>{return[X]}});var{file:o$,serve:lE}=globalThis.Bun;import{readFileSync as L7}from"fs";import{createServer as xU}from"http";import{createServer as fU}from"https";import{resolve as FZ}from"path";function V7(X,Y){if(X instanceof Promise)throw Error(Y)}function SU(X,Y){let Z={},_=[];for(let G in X){let W=X[G]["~standard"].validate(Y[G]);if(V7(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 zZ(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)??SU(Q,Y);V7(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)},A=(P)=>{return P==="__esModule"||P==="$$typeof"},R=(X.extends??[]).reduce((P,h)=>{return Object.assign(P,h)},{}),v=Object.assign(R,J.value);return new Proxy(v,{get(P,h){if(typeof h!=="string")return;if(A(h))return;if(!D(h))return F(h);return Reflect.get(P,h)}})}var PU="__vite_start_time"in globalThis,vU=typeof window<"u",iB="vitest"in globalThis,$4=J1("string"),D7=J1('"true" | "false" | undefined'),g1=zZ({isServer:!PU&&!vU,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:D7.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:D7.pipe((X)=>X==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var M7=FZ(import.meta.dirname,"../dev"),B6=g1.VITE_DEV_HTTPS?{cert:L7(FZ(M7,"./cert.pem"),"utf-8"),key:L7(FZ(M7,"./key.pem"),"utf-8")}:void 0;function XT(X){if(B6)return fU(B6,X);return xU({},X)}import yE 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 UZ{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 EZ{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 A7(X,this)}}class A7{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 T6(X,...Y){return X(...Y)}function R7(X,Y){return`${X[p1]}_${Y.join("_")}_unique`}function w7(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 N7(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]=w7(X,_+1,!0);Z.push(Q),_=J;continue}if(W==="}")return[Z,_+1];if(W==="{"){let[Q,J]=N7(X,_+1);Z.push(Q),_=J;continue}let[$,H]=w7(X,_,!1);Z.push($),_=H}return[Z,_]}function I7(X){let[Y]=N7(X,1);return Y}function OZ(X){return`{${X.map((Y)=>{if(Array.isArray(Y))return OZ(Y);if(typeof Y==="string")return`"${Y.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Y}`}).join(",")}}`}class x extends UZ{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(X){return new B7(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 T6((G,W)=>{let $=new EZ(()=>{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 K7(X,this.config)}}class B extends z0{constructor(X,Y){if(!Y.uniqueName)Y.uniqueName=R7(X,[Y.name]);super(X,Y);this.table=X}static[E]="PgColumn"}class K7 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 O2{static[E]="IndexedColumn";constructor(X,Y,Z,_){this.name=X,this.keyAsName=Y,this.type=Z,this.indexConfig=_}name;keyAsName;type;indexConfig}class B7 extends x{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 VZ(X,this.config,Y)}}class VZ 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=I7(X);return X.map((Y)=>this.baseColumn.mapFromDriverValue(Y))}mapToDriverValue(X,Y=!1){let Z=X.map((_)=>_===null?null:M(this.baseColumn,VZ)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Y)return Z;return OZ(Z)}}class T7 extends x{static[E]="PgEnumObjectColumnBuilder";constructor(X,Y){super(X,"string","PgEnumObjectColumn");this.config.enum=Y}build(X){return new C7(X,this.config)}}class C7 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 C6=Symbol.for("drizzle:isPgEnum");function q7(X){return!!X&&typeof X==="function"&&C6 in X&&X[C6]===!0}class j7 extends x{static[E]="PgEnumColumnBuilder";constructor(X,Y){super(X,"string","PgEnumColumn");this.config.enum=Y}build(X){return new S7(X,this.config)}}class S7 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 V2(X,Y){return Array.isArray(Y)?hU(X,[...Y],void 0):kU(X,Y,void 0)}function hU(X,Y,Z){let _=Object.assign((G)=>new j7(G??"",_),{enumName:X,enumValues:Y,schema:Z,[C6]:!0});return _}function kU(X,Y,Z){let _=Object.assign((G)=>new T7(G??"",_),{enumName:X,enumValues:Object.values(Y),schema:Z,[C6]:!0});return _}class T0{static[E]="Subquery";constructor(X,Y,Z,_=!1,G=[]){this._={brand:"Subquery",sql:X,selectedFields:Y,alias:Z,isWith:_,usedTables:G}}}class D2 extends T0{static[E]="WithSubquery"}var P7="0.44.5";var DZ,LZ,F0={startActiveSpan(X,Y){if(!DZ)return Y();if(!LZ)LZ=DZ.trace.getTracer("drizzle-orm",P7);return T6((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()}}),DZ,LZ)}};var V0=Symbol.for("drizzle:ViewBaseConfig");var k4=Symbol.for("drizzle:Schema"),q6=Symbol.for("drizzle:Columns"),v7=Symbol.for("drizzle:ExtraConfigColumns"),MZ=Symbol.for("drizzle:OriginalName"),AZ=Symbol.for("drizzle:BaseName"),L2=Symbol.for("drizzle:IsAlias"),x7=Symbol.for("drizzle:ExtraConfigBuilder"),bU=Symbol.for("drizzle:IsDrizzleTable");class T{static[E]="Table";static Symbol={Name:p1,Schema:k4,OriginalName:MZ,Columns:q6,ExtraConfigColumns:v7,BaseName:AZ,IsAlias:L2,ExtraConfigBuilder:x7};[p1];[MZ];[k4];[q6];[v7];[AZ];[L2]=!1;[bU]=!0;[x7]=void 0;constructor(X,Y,Z){this[p1]=this[MZ]=X,this[k4]=Y,this[AZ]=Z}}function y0(X){return X[p1]}function b4(X){return`${X[k4]??"public"}.${X[p1]}`}function RZ(X){return X!==null&&X!==void 0&&typeof X.getSQL==="function"}function yU(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=h7;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 yU(X.map((J)=>{if(M(J,k0))return{sql:J.value.join(""),params:[]};if(M(J,j6))return{sql:G(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let z=[new 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[L2]?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[L2]||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,z1)){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,T0)){if(J._.isWith)return{sql:G(J._.alias),params:[]};return this.buildQueryFromSourceParams([new k0("("),J._.sql,new k0(") "),new j6(J._.alias)],Z)}if(q7(J)){if(J.schema)return{sql:G(J.schema)+"."+G(J.enumName),params:[]};return{sql:G(J.enumName),params:[]}}if(RZ(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 j6{constructor(X){this.value=X}static[E]="Name";brand;getSQL(){return new S([this])}}function f7(X){return typeof X==="object"&&X!==null&&"mapToDriverValue"in X&&typeof X.mapToDriverValue==="function"}var h7={mapFromDriverValue:(X)=>X},k7={mapToDriverValue:(X)=>X},dT={...h7,...k7};class L1{constructor(X,Y=k7){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 j6(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 wZ(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 gU=Symbol.for("drizzle:IsDrizzleView");class z1{static[E]="View";[V0];[gU]=!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])};T0.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 M2{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 S6(X,Y){return new Proxy(X,new M2(Y,!1))}function i1(X,Y){return new Proxy(X,new L8(new Proxy(X.table,new M2(Y,!1))))}function NZ(X,Y){return new S.Aliased(A2(X.sql,Y),X.fieldAlias)}function A2(X,Y){return V.join(X.queryChunks.map((Z)=>{if(M(Z,z0))return i1(Z,Y);if(M(Z,S))return A2(Z,Y);if(M(Z,S.Aliased))return NZ(Z,Y);return Z}))}class P6 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 IZ extends P6{static[E]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class b7{static[E]="ConsoleLogWriter";write(X){console.log(X)}}class KZ{static[E]="DefaultLogger";writer;constructor(X){this.writer=X?.writer??new b7}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 BZ{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 y7(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],A=z[O]=D===null?null:J.mapFromDriverValue(D);if(Z&&M(H,z0)&&$.length===2){let R=$[0];if(!(R in _))_[R]=A===null?y0(H.table):!1;else if(typeof _[R]==="string"&&_[R]!==y0(H.table))_[R]=!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 R2(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 v6(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 g7(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 p7(X){return X[T.Symbol.Columns]}function J4(X){return M(X,T0)?X._.alias:M(X,z1)?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 m7(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 x{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 u7 extends N4{static[E]="PgBigInt53Builder";constructor(X){super(X,"number","PgBigInt53")}build(X){return new d7(X,this.config)}}class d7 extends B{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}}class c7 extends N4{static[E]="PgBigInt64Builder";constructor(X){super(X,"bigint","PgBigInt64")}build(X){return new l7(X,this.config)}}class l7 extends B{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(X){return BigInt(X)}}function o7(X,Y){let{name:Z,config:_}=a(X,Y);if(_.mode==="number")return new u7(Z);return new c7(Z)}class i7 extends x{static[E]="PgBigSerial53Builder";constructor(X){super(X,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new n7(X,this.config)}}class n7 extends B{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}}class r7 extends x{static[E]="PgBigSerial64Builder";constructor(X){super(X,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(X){return new s7(X,this.config)}}class s7 extends B{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(X){return BigInt(X)}}function t7(X,Y){let{name:Z,config:_}=a(X,Y);if(_.mode==="number")return new i7(Z);return new r7(Z)}class a7 extends x{static[E]="PgBooleanBuilder";constructor(X){super(X,"boolean","PgBoolean")}build(X){return new e7(X,this.config)}}class e7 extends B{static[E]="PgBoolean";getSQLType(){return"boolean"}}function w2(X){return new a7(X??"")}class X3 extends x{static[E]="PgCharBuilder";constructor(X,Y){super(X,"string","PgChar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(X){return new Y3(X,this.config)}}class Y3 extends B{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function Z3(X,Y={}){let{name:Z,config:_}=a(X,Y);return new X3(Z,_)}class _3 extends x{static[E]="PgCidrBuilder";constructor(X){super(X,"string","PgCidr")}build(X){return new G3(X,this.config)}}class G3 extends B{static[E]="PgCidr";getSQLType(){return"cidr"}}function W3(X){return new _3(X??"")}class $3 extends x{static[E]="PgCustomColumnBuilder";constructor(X,Y,Z){super(X,"custom","PgCustomColumn");this.config.fieldConfig=Y,this.config.customTypeParams=Z}build(X){return new H3(X,this.config)}}class H3 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 J3(X){return(Y,Z)=>{let{name:_,config:G}=a(Y,Z);return new $3(_,G,X)}}class Q4 extends x{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(V`now()`)}}class Q3 extends Q4{static[E]="PgDateBuilder";constructor(X){super(X,"date","PgDate")}build(X){return new x6(X,this.config)}}class x6 extends B{static[E]="PgDate";getSQLType(){return"date"}mapFromDriverValue(X){return new Date(X)}mapToDriverValue(X){return X.toISOString()}}class z3 extends Q4{static[E]="PgDateStringBuilder";constructor(X){super(X,"string","PgDateString")}build(X){return new f6(X,this.config)}}class f6 extends B{static[E]="PgDateString";getSQLType(){return"date"}}function F3(X,Y){let{name:Z,config:_}=a(X,Y);if(_?.mode==="date")return new Q3(Z);return new z3(Z)}class U3 extends x{static[E]="PgDoublePrecisionBuilder";constructor(X){super(X,"number","PgDoublePrecision")}build(X){return new E3(X,this.config)}}class E3 extends B{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(X){if(typeof X==="string")return Number.parseFloat(X);return X}}function O3(X){return new U3(X??"")}class V3 extends x{static[E]="PgInetBuilder";constructor(X){super(X,"string","PgInet")}build(X){return new D3(X,this.config)}}class D3 extends B{static[E]="PgInet";getSQLType(){return"inet"}}function L3(X){return new V3(X??"")}class M3 extends N4{static[E]="PgIntegerBuilder";constructor(X){super(X,"number","PgInteger")}build(X){return new A3(X,this.config)}}class A3 extends B{static[E]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(X){if(typeof X==="string")return Number.parseInt(X);return X}}function N2(X){return new M3(X??"")}class R3 extends x{static[E]="PgIntervalBuilder";constructor(X,Y){super(X,"string","PgInterval");this.config.intervalConfig=Y}build(X){return new w3(X,this.config)}}class w3 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 N3(X,Y={}){let{name:Z,config:_}=a(X,Y);return new R3(Z,_)}class I3 extends x{static[E]="PgJsonBuilder";constructor(X){super(X,"json","PgJson")}build(X){return new h6(X,this.config)}}class h6 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 K3(X){return new I3(X??"")}class B3 extends x{static[E]="PgJsonbBuilder";constructor(X){super(X,"json","PgJsonb")}build(X){return new k6(X,this.config)}}class k6 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 T3(X){return new B3(X??"")}class C3 extends x{static[E]="PgLineBuilder";constructor(X){super(X,"array","PgLine")}build(X){return new q3(X,this.config)}}class q3 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 j3 extends x{static[E]="PgLineABCBuilder";constructor(X){super(X,"json","PgLineABC")}build(X){return new S3(X,this.config)}}class S3 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 P3(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new C3(Z);return new j3(Z)}class v3 extends x{static[E]="PgMacaddrBuilder";constructor(X){super(X,"string","PgMacaddr")}build(X){return new x3(X,this.config)}}class x3 extends B{static[E]="PgMacaddr";getSQLType(){return"macaddr"}}function f3(X){return new v3(X??"")}class h3 extends x{static[E]="PgMacaddr8Builder";constructor(X){super(X,"string","PgMacaddr8")}build(X){return new k3(X,this.config)}}class k3 extends B{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}}function b3(X){return new h3(X??"")}class y3 extends x{static[E]="PgNumericBuilder";constructor(X,Y,Z){super(X,"string","PgNumeric");this.config.precision=Y,this.config.scale=Z}build(X){return new b6(X,this.config)}}class b6 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 g3 extends x{static[E]="PgNumericNumberBuilder";constructor(X,Y,Z){super(X,"number","PgNumericNumber");this.config.precision=Y,this.config.scale=Z}build(X){return new p3(X,this.config)}}class p3 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 m3 extends x{static[E]="PgNumericBigIntBuilder";constructor(X,Y,Z){super(X,"bigint","PgNumericBigInt");this.config.precision=Y,this.config.scale=Z}build(X){return new u3(X,this.config)}}class u3 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 d3(X,Y){let{name:Z,config:_}=a(X,Y),G=_?.mode;return G==="number"?new g3(Z,_?.precision,_?.scale):G==="bigint"?new m3(Z,_?.precision,_?.scale):new y3(Z,_?.precision,_?.scale)}class c3 extends x{static[E]="PgPointTupleBuilder";constructor(X){super(X,"array","PgPointTuple")}build(X){return new l3(X,this.config)}}class l3 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 o3 extends x{static[E]="PgPointObjectBuilder";constructor(X){super(X,"json","PgPointObject")}build(X){return new i3(X,this.config)}}class i3 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 n3(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new c3(Z);return new o3(Z)}function pU(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 r3(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 TZ(X){let Y=pU(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=r3(Y,Z);Z+=8;let Q=r3(Y,Z);return Z+=8,[H,Q]}throw Error("Unsupported geometry type")}class s3 extends x{static[E]="PgGeometryBuilder";constructor(X){super(X,"array","PgGeometry")}build(X){return new t3(X,this.config)}}class t3 extends B{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(X){return TZ(X)}mapToDriverValue(X){return`point(${X[0]} ${X[1]})`}}class a3 extends x{static[E]="PgGeometryObjectBuilder";constructor(X){super(X,"json","PgGeometryObject")}build(X){return new e3(X,this.config)}}class e3 extends B{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(X){let Y=TZ(X);return{x:Y[0],y:Y[1]}}mapToDriverValue(X){return`point(${X.x} ${X.y})`}}function XW(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new s3(Z);return new a3(Z)}class YW extends x{static[E]="PgRealBuilder";constructor(X,Y){super(X,"number","PgReal");this.config.length=Y}build(X){return new ZW(X,this.config)}}class ZW 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 _W(X){return new YW(X??"")}class GW extends x{static[E]="PgSerialBuilder";constructor(X){super(X,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new WW(X,this.config)}}class WW extends B{static[E]="PgSerial";getSQLType(){return"serial"}}function $W(X){return new GW(X??"")}class HW extends N4{static[E]="PgSmallIntBuilder";constructor(X){super(X,"number","PgSmallInt")}build(X){return new JW(X,this.config)}}class JW extends B{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(X)=>{if(typeof X==="string")return Number(X);return X}}function QW(X){return new HW(X??"")}class zW extends x{static[E]="PgSmallSerialBuilder";constructor(X){super(X,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new FW(X,this.config)}}class FW extends B{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}}function UW(X){return new zW(X??"")}class EW extends x{static[E]="PgTextBuilder";constructor(X,Y){super(X,"string","PgText");this.config.enumValues=Y.enum}build(X){return new OW(X,this.config)}}class OW extends B{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function VW(X,Y={}){let{name:Z,config:_}=a(X,Y);return new EW(Z,_)}class DW 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 y6(X,this.config)}}class y6 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 LW(X,Y={}){let{name:Z,config:_}=a(X,Y);return new DW(Z,_.withTimezone??!1,_.precision)}class MW 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 g6(X,this.config)}}class g6 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 AW 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 p6(X,this.config)}}class p6 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 RW(X,Y={}){let{name:Z,config:_}=a(X,Y);if(_?.mode==="string")return new AW(Z,_.withTimezone??!1,_.precision);return new MW(Z,_?.withTimezone??!1,_?.precision)}class wW extends x{static[E]="PgUUIDBuilder";constructor(X){super(X,"string","PgUUID")}defaultRandom(){return this.default(V`gen_random_uuid()`)}build(X){return new m6(X,this.config)}}class m6 extends B{static[E]="PgUUID";getSQLType(){return"uuid"}}function T1(X){return new wW(X??"")}class NW extends x{static[E]="PgVarcharBuilder";constructor(X,Y){super(X,"string","PgVarchar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(X){return new IW(X,this.config)}}class IW 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 NW(Z,_)}class KW extends x{static[E]="PgBinaryVectorBuilder";constructor(X,Y){super(X,"string","PgBinaryVector");this.config.dimensions=Y.dimensions}build(X){return new BW(X,this.config)}}class BW extends B{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function TW(X,Y){let{name:Z,config:_}=a(X,Y);return new KW(Z,_)}class CW extends x{static[E]="PgHalfVectorBuilder";constructor(X,Y){super(X,"array","PgHalfVector");this.config.dimensions=Y.dimensions}build(X){return new qW(X,this.config)}}class qW 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 jW(X,Y){let{name:Z,config:_}=a(X,Y);return new CW(Z,_)}class SW extends x{static[E]="PgSparseVectorBuilder";constructor(X,Y){super(X,"string","PgSparseVector");this.config.dimensions=Y.dimensions}build(X){return new PW(X,this.config)}}class PW extends B{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function vW(X,Y){let{name:Z,config:_}=a(X,Y);return new SW(Z,_)}class xW extends x{static[E]="PgVectorBuilder";constructor(X,Y){super(X,"array","PgVector");this.config.dimensions=Y.dimensions}build(X){return new fW(X,this.config)}}class fW 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 hW(X,Y){let{name:Z,config:_}=a(X,Y);return new xW(Z,_)}function kW(){return{bigint:o7,bigserial:t7,boolean:w2,char:Z3,cidr:W3,customType:J3,date:F3,doublePrecision:O3,inet:L3,integer:N2,interval:N3,json:K3,jsonb:T3,line:P3,macaddr:f3,macaddr8:b3,numeric:d3,point:n3,geometry:XW,real:_W,serial:$W,smallint:QW,smallserial:UW,text:VW,time:LW,timestamp:RW,uuid:T1,varchar:n0,bit:TW,halfvec:jW,sparsevec:vW,vector:hW}}var CZ=Symbol.for("drizzle:PgInlineForeignKeys"),bW=Symbol.for("drizzle:EnableRLS");class b0 extends T{static[E]="PgTable";static Symbol=Object.assign({},T.Symbol,{InlineForeignKeys:CZ,EnableRLS:bW});[CZ]=[];[bW]=!1;[T.Symbol.ExtraConfigBuilder]=void 0;[T.Symbol.ExtraConfigColumns]={}}function mU(X,Y,Z,_,G=X){let W=new b0(X,_,G),$=typeof Y==="function"?Y(kW()):Y,H=Object.fromEntries(Object.entries($).map(([z,F])=>{let O=F;O.setName(z);let D=O.build(W);return W[CZ].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 mU(X,Y,Z,void 0)};function yW(...X){if(X[0].columns)return new I2(X[0].columns,X[0].name);return new I2(X)}class I2{static[E]="PgPrimaryKeyBuilder";columns;name;constructor(X,Y){this.columns=X,this.name=Y}build(X){return new gW(X,this.columns,this.name)}}class gW{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 F1(X,Y){if(f7(Y)&&!RZ(X)&&!M(X,L1)&&!M(X,w4)&&!M(X,z0)&&!M(X,T)&&!M(X,z1))return new L1(X,Y);return X}var u6=(X,Y)=>{return V`${X} = ${F1(Y,X)}`},pW=(X,Y)=>{return V`${X} <> ${F1(Y,X)}`};function K2(...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 mW(...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 uW(X){return V`not ${X}`}var dW=(X,Y)=>{return V`${X} > ${F1(Y,X)}`},cW=(X,Y)=>{return V`${X} >= ${F1(Y,X)}`},lW=(X,Y)=>{return V`${X} < ${F1(Y,X)}`},oW=(X,Y)=>{return V`${X} <= ${F1(Y,X)}`};function iW(X,Y){if(Array.isArray(Y)){if(Y.length===0)return V`false`;return V`${X} in ${Y.map((Z)=>F1(Z,X))}`}return V`${X} in ${F1(Y,X)}`}function nW(X,Y){if(Array.isArray(Y)){if(Y.length===0)return V`true`;return V`${X} not in ${Y.map((Z)=>F1(Z,X))}`}return V`${X} not in ${F1(Y,X)}`}function rW(X){return V`${X} is null`}function sW(X){return V`${X} is not null`}function tW(X){return V`exists ${X}`}function aW(X){return V`not exists ${X}`}function eW(X,Y,Z){return V`${X} between ${F1(Y,X)} and ${F1(Z,X)}`}function X$(X,Y,Z){return V`${X} not between ${F1(Y,X)} and ${F1(Z,X)}`}function Y$(X,Y){return V`${X} like ${Y}`}function Z$(X,Y){return V`${X} not like ${Y}`}function _$(X,Y){return V`${X} ilike ${Y}`}function G$(X,Y){return V`${X} not ilike ${Y}`}function W$(X){return V`${X} asc`}function $$(X){return V`${X} desc`}class qZ{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 H${constructor(X,Y){this.table=X,this.config=Y}static[E]="Relations"}class K4 extends qZ{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 B2 extends qZ{constructor(X,Y,Z){super(X,Y,Z?.relationName);this.config=Z}static[E]="Many";withFieldName(X){let Y=new B2(this.sourceTable,this.referencedTable,this.config);return Y.fieldName=X,Y}}function J$(){return{and:K2,between:eW,eq:u6,exists:tW,gt:dW,gte:cW,ilike:_$,inArray:iW,isNull:rW,isNotNull:sW,like:Y$,lt:lW,lte:oW,ne:pW,not:uW,notBetween:X$,notExists:aW,notLike:Z$,notIlike:G$,notInArray:nW,or:mW,sql:V}}function Q$(){return{sql:V,asc:W$,desc:$$}}function z$(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,I2))G[W].primaryKey.push(...z.columns)}}else if(M($,H$)){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 uU(X){return function(Z,_){return new K4(X,Z,_,_?.fields.reduce((G,W)=>G&&W.notNull,!0)??!1)}}function dU(X){return function(Z,_){return new B2(X,Z,_)}}function F$(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 U$(X){return{one:uU(X),many:dU(X)}}function d6(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&&d6(X,X[H.relationTableTsKey],z,H.selection,G):z.map((F)=>d6(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 EE from"os";import OE from"fs";var c6=new Map,jZ=new Map,SZ=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[SZ]=this.handler.debug?Error():this.tagged&&cU(this.strings)}get origin(){return(this.handler.debug?this[SZ].stack:this.tagged&&jZ.has(this.strings)?jZ.get(this.strings):jZ.set(this.strings,this[SZ].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 cU(X){if(c6.has(X))return c6.get(X);let Y=Error.stackTraceLimit;return Error.stackTraceLimit=4,c6.set(X,Error()),Error.stackTraceLimit=Y,c6.get(X)}class A8 extends Error{constructor(X){super(X.message);this.name=this.constructor.name,Object.assign(this,X)}}var S0={connection:E$,postgres:O$,generic:V$,notSupported:D$};function E$(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,E$),W}function O$(X){let Y=new A8(X);return Error.captureStackTrace(Y,O$),Y}function V$(X,Y){let Z=Object.assign(Error(X+": "+Y),{code:X});return Error.captureStackTrace(Z,V$),Z}function D$(X){let Y=Object.assign(Error(X+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:X});return Error.captureStackTrace(Y,D$),Y}var lU={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 i6{then(){PZ()}catch(){PZ()}finally(){PZ()}}class j2 extends i6{constructor(X){super();this.value=s6(X)}}class n1 extends i6{constructor(X,Y,Z){super();this.value=X,this.type=Y,this.array=Z}}class n6 extends i6{constructor(X,Y){super();this.first=X,this.rest=Y}build(X,Y,Z,_){let G=oU.map(([W,$])=>({fn:$,i:X.search(W)})).sort((W,$)=>W.i-$.i).pop();return G.i===-1?kZ(this.first,_):G.fn(this.first,this.rest,Y,Z,_)}}function r6(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||o6(X.value)]||X.type||R$(X.value):X.type):(Y.push(X),o6(X)))}var M$=N$(lU);function fZ(X,Y,Z,_,G,W){for(let $=1;$<X.strings.length;$++)Y+=hZ(Y,Z,_,G,W)+X.strings[$],Z=X.args[$];return Y}function hZ(X,Y,Z,_,G){return Y instanceof n6?Y.build(X,Z,_,G):Y instanceof C1?xZ(Y,Z,_,G):Y instanceof j2?Y.value:Y&&Y[0]instanceof C1?Y.reduce((W,$)=>W+" "+xZ($,Z,_,G),""):r6(Y,Z,_,G)}function xZ(X,Y,Z,_){return X.fragment=!0,fZ(X,X.strings[0],X.args[0],Y,Z,_)}function A$(X,Y,Z,_,G){return X.map((W)=>"("+_.map(($)=>hZ("values",W[$],Y,Z,G)).join(",")+")").join(",")}function L$(X,Y,Z,_,G){let W=Array.isArray(X[0]),$=Y.length?Y.flat():Object.keys(W?X[0]:X);return A$(W?X:[X],Z,_,$,G)}function l6(X,Y,Z,_,G){if(typeof X==="string"&&(X=[X].concat(Y)),Array.isArray(X))return kZ(X,G);let W;return(Y.length?Y.flat():Object.keys(X)).map((H)=>{return W=X[H],(W instanceof C1?xZ(W,Z,_,G):W instanceof j2?W.value:r6(W,Z,_,G))+" as "+s6(G.transform.column.to?G.transform.column.to(H):H)}).join(",")}var oU=Object.entries({values:L$,in:(...X)=>{let Y=L$(...X);return Y==="()"?"(null)":Y},select:l6,as:l6,returning:l6,"\\(":l6,update(X,Y,Z,_,G){return(Y.length?Y.flat():Object.keys(X)).map((W)=>s6(G.transform.column.to?G.transform.column.to(W):W)+"="+hZ("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"("+kZ(W,G)+")values"+A$(Array.isArray(X)?X:[X],Z,_,W,G)}}).map(([X,Y])=>[new RegExp("((?:^|[\\s(])"+X+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Y]);function PZ(){throw S0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:iU,parsers:nU}=M$;function R$(X){if(Array.isArray(X))return R$(X[0]);return typeof X==="string"?1009:0}var w$=function(X){let Y=N$(X||{});return{serializers:Object.assign({},iU,Y.serializers),parsers:Object.assign({},nU,Y.parsers)}};function N$(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 kZ(X,{transform:{column:Y}}){return X.map((Z)=>s6(Y.to?Y.to(Z):Z)).join(",")}var s6=function(Y){return'"'+Y.replace(/"/g,'""').replace(/\./g,'"."')+'"'},o6=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},rU=/\\/g,sU=/"/g;function tU(X){return X.replace(rU,"\\\\").replace(sU,"\\\"")}var I$=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":'"'+tU(Z?Z(H.type?H.value:H):""+H)+'"'}).join($)+"}"},vZ={i:0,char:null,str:"",quoted:!1,last:0},K$=function(Y,Z,_){return vZ.i=vZ.last=0,B$(vZ,Y,Z,_)};function B$(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(B$(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,"-"),T2=(X)=>X.replace(/([A-Z])/g,"_$1").toLowerCase(),C2=(X)=>(X.slice(0,1)+X.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),q2=(X)=>X.replace(/-/g,"_");function bZ(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:bZ(y4)};T2.column={to:T2};var yZ={...y4};yZ.column.to=T2;g4.column={from:g4};g4.value={from:bZ(g4)};C2.column={to:C2};var gZ={...g4};gZ.column.to=C2;p4.column={from:p4};p4.value={from:bZ(p4)};q2.column={to:q2};var pZ={...p4};pZ.column.to=q2;import T$ from"net";import YE from"tls";import S2 from"crypto";import mZ from"stream";import{performance as C$}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=aU;function aU(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),eU="BCcDdEFfHPpQSX".split("").reduce((X,Y)=>{let Z=Y.charCodeAt(0);return X[Y]=()=>{return r0[0]=Z,H0.i=5,H0},X},{}),H0=Object.assign(XE,eU,{N:String.fromCharCode(0),i:0,inc(X){return H0.i+=X,H0},str(X){let Y=Buffer.byteLength(X);return t6(Y),H0.i+=r0.write(X,H0.i,Y,"utf8"),H0},i16(X){return t6(2),r0.writeUInt16BE(X,H0.i),H0.i+=2,H0},i32(X,Y){if(Y||Y===0)return r0.writeUInt32BE(X,Y),H0;return t6(4),r0.writeUInt32BE(X,H0.i),H0.i+=4,H0},z(X){return t6(X),r0.fill(0,H0.i,H0.i+X),H0.i+=X,H0},raw(X){return r0=Buffer.concat([r0.subarray(0,H0.i),X]),H0.i=r0.length,H0},end(X=1){r0.writeUInt32BE(H0.i-X,X);let Y=r0.subarray(0,H0.i);return H0.i=0,r0=Buffer.allocUnsafe(256),Y}}),b=H0;function t6(X){if(r0.length-H0.i<X){let Y=r0,Z=Y.length;r0=Buffer.allocUnsafe(Z+(Z>>1)+X),Y.copy(r0)}}function XE(){return H0.i=0,H0}var cZ=S$,ZE=1,B4=b().S().end(),q$=b().H().end(),_E=b().i32(8).i32(80877103).end(8),GE=Buffer.concat([b().E().str(b.N).i32(0).end(),B4]),WE=b().D().str("S").str(b.N).end(),R8=()=>{},$E=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),HE={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 S$(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:A,onparameter:R,max_pipeline:v,keep_alive:j,backoff:P,target_session_attrs:h}=X,i=M1(),p=ZE++,y={pid:null,secret:null},m=dZ(FX,X.idle_timeout),_0=dZ(FX,X.max_lifetime),u0=dZ(e$,X.connect_timeout),K=null,J0,o=new m4,X0=Buffer.alloc(0),g0=X.fetch_types,E1={},q1={},c4=Math.random().toString(36).slice(2),I=1,u=0,W0=0,R0=0,P0=0,n=0,$0=0,C0=0,w0=null,D0=null,d0=!1,U0=null,j1=null,p0=null,z4=null,v0=null,L0=null,S1=null,u1=null,q=null,K8=null,c0={queue:Y.closed,idleTimer:m,connect(U){p0=U,L5()},terminate:T8,execute:B8,cancel:r$,end:FX,count:0,id:p};return Y.closed&&Y.closed.push(c0),c0;async function n$(){let U;try{U=X.socket?await Promise.resolve(X.socket(X)):new T$.Socket}catch(L){o4(L);return}return U.on("error",o4),U.on("close",M5),U.on("drain",V5),U}async function r$({pid:U,secret:L},g,Z0){try{J0=b().i32(16).i32(80877102).i32(U).i32(L).end(16),await D5(),K.once("error",Z0),K.once("close",g)}catch(I0){Z0(I0)}}function B8(U){if(d0)return y2(U,S0.connection("CONNECTION_DESTROYED",X));if(U.cancelled)return;try{return U.state=y,q?i.push(U):(q=U,q.active=!0),a$(U),m0(s$(U))&&!U.describeFirst&&!U.cursorFn&&i.length<v&&(!U.options.onexecute||U.options.onexecute(c0))}catch(L){return i.length===0&&m0(B4),d1(L),!0}}function s$(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([U5(U),q$]):U.prepare?U.prepared?b2(U):Buffer.concat([U5(U),b2(U)]):t$(U)}function U5(U){return Buffer.concat([R5(U.statement.string,U.parameters,U.statement.types,U.statement.name),bH("S",U.statement.name)])}function b2(U){return Buffer.concat([kH(U.parameters,U.statement.types,U.statement.name,U.cursorName),U.cursorFn?w5("",U.cursorRows):GE])}function t$(U){return Buffer.concat([R5(U.statement.string,U.parameters,U.statement.types),WE,b2(U)])}function a$(U){let L=[],g=[],Z0=fZ(U,U.strings[0],U.args[0],L,g,X);!U.tagged&&U.args.forEach((I0)=>r6(I0,L,g,X)),U.prepare=X.prepare&&("prepare"in U.options?U.options.prepare:!0),U.string=Z0,U.signature=U.prepare&&g+Z0,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:Z0,types:g,name:U.prepare?c4+I++:""},typeof X.debug==="function"&&X.debug(p,Z0,L,g)}function m0(U,L){if(L0=L0?Buffer.concat([L0,U]):Buffer.from(U),L||L0.length>=1024)return E5(L);return D0===null&&(D0=setImmediate(E5)),!0}function E5(U){let L=K.write(L0,U);return D0!==null&&clearImmediate(D0),L0=D0=null,L}function e$(){d1(S0.connection("CONNECT_TIMEOUT",X,K)),K.destroy()}async function O5(){if(m0(_E),!await new Promise((L)=>K.once("data",(g)=>L(g[0]===83)))&&W==="prefer")return l4();K.removeAllListeners(),K=YE.connect({socket:K,servername:T$.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",M5),K.on("drain",V5)}function V5(){!q&&Z(c0)}function zX(U){if(U0){if(U0.push(U),W0-=U.length,W0>0)return}X0=U0?Buffer.concat(U0,n-W0):X0.length===0?U:Buffer.concat([X0,U],X0.length+U.length);while(X0.length>4){if(n=X0.readUInt32BE(1),n>=X0.length){W0=n-X0.length,U0=[X0];break}try{XH(X0.subarray(0,n+1))}catch(L){q&&(q.cursorFn||q.describeFirst)&&m0(B4),d1(L)}X0=X0.subarray(n+1),W0=0,U0=null}}async function D5(){if(d0=!1,E1={},K||(K=await n$()),!K)return;if(u0.start(),X.socket)return W?O5():l4();if(K.on("connect",W?O5: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 L5(){setTimeout(D5,u?u+$0-C$.now():0)}function l4(){try{q1={},g0=X.fetch_types,c4=Math.random().toString(36).slice(2),I=1,_0.start(),K.on("data",zX),j&&K.setKeepAlive&&K.setKeepAlive(!0,1000*j);let U=gH();m0(U)}catch(U){o4(U)}}function o4(U){if(c0.queue===Y.connecting&&X.host[P0+1])return;d1(U);while(i.length)y2(i.shift(),U)}function d1(U){v0&&(v0.destroy(U),v0=null),q&&y2(q,U),p0&&(y2(p0,U),p0=null)}function y2(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 FX(){return z4||(!c0.reserved&&_(c0),!c0.reserved&&!p0&&!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||p0||i.length)o4(S0.connection("CONNECTION_DESTROYED",X));if(clearImmediate(D0),K)K.removeListener("data",zX),K.removeListener("connect",l4),K.readyState==="open"&&K.end(b().X().end());S1&&(S1(),z4=S1=null)}async function M5(U){if(X0=Buffer.alloc(0),W0=0,U0=null,clearImmediate(D0),K.removeListener("data",zX),K.removeListener("connect",l4),m.cancel(),_0.cancel(),u0.cancel(),K.removeAllListeners(),K=null,p0)return L5();!U&&(q||i.length)&&o4(S0.connection("CONNECTION_CLOSED",X,K)),u=C$.now(),U&&X.shared.retries++,$0=(typeof P==="function"?P(X.shared.retries):P)*1000,G(c0,S0.connection("CONNECTION_CLOSED",X,K))}function XH(U,L=U[0]){(L===68?YH:L===100?qH:L===65?NH:L===83?ZH:L===90?_H:L===67?GH:L===50?A5:L===49?WH:L===116?$H:L===84?HH:L===82?JH:L===110?OH:L===75?VH:L===69?RH:L===115?IH:L===51?KH:L===71?BH:L===78?SH:L===72?TH:L===99?jH:L===73?PH:L===86?vH:L===118?xH:L===87?CH:fH)(U)}function YH(U){let L=7,g,Z0,I0,l0=q.isRaw?Array(q.statement.columns.length):{};for(let s0=0;s0<q.statement.columns.length;s0++)Z0=q.statement.columns[s0],g=U.readInt32BE(L),L+=4,I0=g===-1?null:q.isRaw===!0?U.subarray(L,L+=g):Z0.parser===void 0?U.toString("utf8",L,L+=g):Z0.parser.array===!0?Z0.parser(U.toString("utf8",L+1,L+=g)):Z0.parser(U.toString("utf8",L,L+=g)),q.isRaw?l0[s0]=q.isRaw===!0?I0:O.value.from?O.value.from(I0,Z0):I0:l0[Z0.name]=O.value.from?O.value.from(I0,Z0):I0;q.forEachFn?q.forEachFn(O.row.from?O.row.from(l0):l0,o):o[C0++]=O.row.from?O.row.from(l0):l0}function ZH(U){let[L,g]=U.toString("utf8",5,U.length-1).split(b.N);if(E1[L]=g,X.parameters[L]!==g)X.parameters[L]=g,R&&R(L,g)}function _H(U){if(q&&q.options.simple&&q.resolve(j1||o),q=j1=null,o=new m4,u0.cancel(),p0){if(h){if(!E1.in_hot_standby||!E1.default_transaction_read_only)return AH();else if(MH(h,E1))return T8()}if(g0)return p0.reserve&&(p0=null),DH();p0&&!p0.reserve&&B8(p0),X.shared.retries=P0=0,p0=null;return}while(i.length&&(q=i.shift())&&(q.active=!0,q.cancelled))S$(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 GH(U){C0=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 A5();if(q.cursorFn)o.count&&q.cursorFn(o),m0(B4);q.resolve(o)}function WH(){q.parsing=!1}function A5(){!o.statement&&(o.statement=q.statement),o.columns=q.statement.columns}function $H(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&&(m0(b2(q)),q.describeFirst=!1)}function HH(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,Z0;q.statement.columns=Array(L);for(let I0=0;I0<L;++I0){Z0=g;while(U[g++]!==0);let l0=U.readUInt32BE(g),s0=U.readUInt16BE(g+4),F4=U.readUInt32BE(g+6);q.statement.columns[I0]={name:O.column.from?O.column.from(U.toString("utf8",Z0,g-1)):U.toString("utf8",Z0,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),m0(B4)}async function JH(U,L=U.readUInt32BE(5)){(L===3?QH:L===5?zH:L===10?FH:L===11?UH:L===12?EH:L!==0?hH:R8)(U,L)}async function QH(){let U=await UX();m0(b().p().str(U).z(1).end())}async function zH(U){let L="md5"+await j$(Buffer.concat([Buffer.from(await j$(await UX()+H)),U.subarray(9)]));m0(b().p().str(L).z(1).end())}async function FH(){u1=(await S2.randomBytes(18)).toString("base64"),b().p().str("SCRAM-SHA-256"+b.N);let U=b.i;m0(b.inc(4).str("n,,n=*,r="+u1).i32(b.i-U-4,U).end())}async function UH(U){let L=U.toString("utf8",9).split(",").reduce((s0,F4)=>(s0[F4[0]]=F4.slice(2),s0),{}),g=await S2.pbkdf2Sync(await UX(),Buffer.from(L.s,"base64"),parseInt(L.i),32,"sha256"),Z0=await a6(g,"Client Key"),I0="n=*,r="+u1+",r="+L.r+",s="+L.s+",i="+L.i+",c=biws,r="+L.r;w0=(await a6(await a6(g,"Server Key"),I0)).toString("base64");let l0="c=biws,r="+L.r+",p="+QE(Z0,Buffer.from(await a6(await JE(Z0),I0))).toString("base64");m0(b().p().str(l0).end())}function EH(U){if(U.toString("utf8",9).split(b.N,1)[0].slice(2)===w0)return;d1(S0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),K.destroy()}function UX(){return Promise.resolve(typeof X.pass==="function"?X.pass():X.pass)}function OH(){if(o.statement=q.statement,o.statement.columns=[],q.onlyDescribe)return q.resolve(q.statement),m0(B4)}function VH(U){y.pid=U.readUInt32BE(5),y.secret=U.readUInt32BE(9)}async function DH(){g0=!1,(await new C1([`
66
+ \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 yU(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 R7=new Map;var rB=M6({key:"joinRoom",do:(X,Y,Z,_)=>{let G={enteredAtEpoch:_};return $2(O2,(W)=>{W.set({room:Y,user:Z})},X.env().store),G}}),sB=M6({key:"leaveRoom",do:({env:X},Y,Z)=>{$2(O2,(_)=>{_.delete({room:Y,user:Z})},X().store)}}),tB=M6({key:"destroyRoom",do:({set:X,env:Y},Z)=>{$2(O2,(G)=>{G.delete({room:Z})},Y().store),X(M7,(G)=>(G.delete(Z),G));let _=R7.get(Z);if(_)_.emit("exit"),R7.delete(Z)}}),aB=O8({key:"sockets",default:null}),eB=E8({key:"socketsIndex",class:W4}),XT=E8({key:"usersIndex",class:W4}),YT=L6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(X)=>X.startsWith("user::"),isBType:(X)=>X.startsWith("socket::")}),ZT=A6({key:"userMutualSituationalAwarenessIndexes",get:(X)=>()=>{return[X]}});var{file:e$,serve:XO}=globalThis.Bun;import{readFileSync as K7}from"fs";import{createServer as uU}from"http";import{createServer as dU}from"https";import{resolve as VZ}from"path";function N7(X,Y){if(X instanceof Promise)throw Error(Y)}function gU(X,Y){let Z={},_=[];for(let G in X){let W=X[G]["~standard"].validate(Y[G]);if(N7(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 OZ(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)??gU(Q,Y);N7(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"},R=(X.extends??[]).reduce((P,h)=>{return Object.assign(P,h)},{}),v=Object.assign(R,J.value);return new Proxy(v,{get(P,h){if(typeof h!=="string")return;if(w(h))return;if(!D(h))return F(h);return Reflect.get(P,h)}})}var pU="__vite_start_time"in globalThis,mU=typeof window<"u",ET="vitest"in globalThis,H4=z1("string"),I7=z1('"true" | "false" | undefined'),p1=OZ({isServer:!pU&&!mU,server:{CI:z1("string | undefined").pipe(Boolean),POSTGRES_USER:H4,POSTGRES_PASSWORD:H4,POSTGRES_DATABASE:H4,POSTGRES_HOST:H4,POSTGRES_PORT:H4.pipe((X)=>Number.parseInt(X,10)),BACKEND_PORT:H4.pipe((X)=>Number.parseInt(X,10)),RUN_WORKERS_FROM_SOURCE:I7.pipe((X)=>X==="true"),FRONTEND_PORT:H4.pipe((X)=>Number.parseInt(X,10)),FRONTEND_ORIGINS:H4.pipe.try((X)=>JSON.parse(X),z1("string[]")),API_KEY_OPENAI:z1("string | undefined"),API_KEY_RESEND:z1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:H4,VITE_DEV_FRONTEND_HOST:z1("string | undefined"),VITE_DEV_HTTPS:I7.pipe((X)=>X==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var B7=VZ(import.meta.dirname,"../dev"),q6=p1.VITE_DEV_HTTPS?{cert:K7(VZ(B7,"./cert.pem"),"utf-8"),key:K7(VZ(B7,"./key.pem"),"utf-8")}:void 0;function RT(X){if(q6)return dU(q6,X);return uU({},X)}import iE from"path";var E=Symbol.for("drizzle:entityKind");function A(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 DZ{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 m1=Symbol.for("drizzle:Name");class LZ{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 T7(X,this)}}class T7{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[m1],..._,Z[0].table[m1],...G];return X??`${W.join("_")}_fk`}}function j6(X,...Y){return X(...Y)}function C7(X,Y){return`${X[m1]}_${Y.join("_")}_unique`}function q7(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 j7(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]=q7(X,_+1,!0);Z.push(Q),_=J;continue}if(W==="}")return[Z,_+1];if(W==="{"){let[Q,J]=j7(X,_+1);Z.push(Q),_=J;continue}let[$,H]=q7(X,_,!1);Z.push($),_=H}return[Z,_]}function S7(X){let[Y]=j7(X,1);return Y}function AZ(X){return`{${X.map((Y)=>{if(Array.isArray(Y))return AZ(Y);if(typeof Y==="string")return`"${Y.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Y}`}).join(",")}}`}class x extends DZ{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(X){return new v7(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 LZ(()=>{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 P7(X,this.config)}}class B extends z0{constructor(X,Y){if(!Y.uniqueName)Y.uniqueName=C7(X,[Y.name]);super(X,Y);this.table=X}static[E]="PgColumn"}class P7 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 v7 extends x{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 MZ(X,this.config,Y)}}class MZ 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=S7(X);return X.map((Y)=>this.baseColumn.mapFromDriverValue(Y))}mapToDriverValue(X,Y=!1){let Z=X.map((_)=>_===null?null:A(this.baseColumn,MZ)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Y)return Z;return AZ(Z)}}class x7 extends x{static[E]="PgEnumObjectColumnBuilder";constructor(X,Y){super(X,"string","PgEnumObjectColumn");this.config.enum=Y}build(X){return new f7(X,this.config)}}class f7 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 h7(X){return!!X&&typeof X==="function"&&S6 in X&&X[S6]===!0}class k7 extends x{static[E]="PgEnumColumnBuilder";constructor(X,Y){super(X,"string","PgEnumColumn");this.config.enum=Y}build(X){return new b7(X,this.config)}}class b7 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)?cU(X,[...Y],void 0):lU(X,Y,void 0)}function cU(X,Y,Z){let _=Object.assign((G)=>new k7(G??"",_),{enumName:X,enumValues:Y,schema:Z,[S6]:!0});return _}function lU(X,Y,Z){let _=Object.assign((G)=>new x7(G??"",_),{enumName:X,enumValues:Object.values(Y),schema:Z,[S6]:!0});return _}class T0{static[E]="Subquery";constructor(X,Y,Z,_=!1,G=[]){this._={brand:"Subquery",sql:X,selectedFields:Y,alias:Z,isWith:_,usedTables:G}}}class L2 extends T0{static[E]="WithSubquery"}var y7="0.44.6";var RZ,wZ,F0={startActiveSpan(X,Y){if(!RZ)return Y();if(!wZ)wZ=RZ.trace.getTracer("drizzle-orm",y7);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()}}),RZ,wZ)}};var V0=Symbol.for("drizzle:ViewBaseConfig");var b4=Symbol.for("drizzle:Schema"),P6=Symbol.for("drizzle:Columns"),g7=Symbol.for("drizzle:ExtraConfigColumns"),NZ=Symbol.for("drizzle:OriginalName"),IZ=Symbol.for("drizzle:BaseName"),A2=Symbol.for("drizzle:IsAlias"),p7=Symbol.for("drizzle:ExtraConfigBuilder"),oU=Symbol.for("drizzle:IsDrizzleTable");class T{static[E]="Table";static Symbol={Name:m1,Schema:b4,OriginalName:NZ,Columns:P6,ExtraConfigColumns:g7,BaseName:IZ,IsAlias:A2,ExtraConfigBuilder:p7};[m1];[NZ];[b4];[P6];[g7];[IZ];[A2]=!1;[oU]=!0;[p7]=void 0;constructor(X,Y,Z){this[m1]=this[NZ]=X,this[b4]=Y,this[IZ]=Z}}function y0(X){return X[m1]}function y4(X){return`${X[b4]??"public"}.${X[m1]}`}function KZ(X){return X!==null&&X!==void 0&&typeof X.getSQL==="function"}function iU(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(A(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=u7;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 iU(X.map((J)=>{if(A(J,k0))return{sql:J.value.join(""),params:[]};if(A(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(A(J,S))return this.buildQueryFromSourceParams(J.queryChunks,{...Z,inlineParams:H||J.shouldInlineParams});if(A(J,T)){let z=J[T.Symbol.Schema],F=J[T.Symbol.Name];return{sql:z===void 0||J[A2]?G(F):G(z)+"."+G(F),params:[]}}if(A(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[A2]||F===void 0?G(J.table[T.Symbol.Name])+"."+G(z):G(F)+"."+G(J.table[T.Symbol.Name])+"."+G(z),params:[]}}if(A(J,U1)){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(A(J,A1)){if(A(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(A(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(A(J,w4))return{sql:W(Q.value++,J),params:[J],typings:["none"]};if(A(J,S.Aliased)&&J.fieldAlias!==void 0)return{sql:G(J.fieldAlias),params:[]};if(A(J,T0)){if(J._.isWith)return{sql:G(J._.alias),params:[]};return this.buildQueryFromSourceParams([new k0("("),J._.sql,new k0(") "),new v6(J._.alias)],Z)}if(h7(J)){if(J.schema)return{sql:G(J.schema)+"."+G(J.enumName),params:[]};return{sql:G(J.enumName),params:[]}}if(KZ(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 m7(X){return typeof X==="object"&&X!==null&&"mapToDriverValue"in X&&typeof X.mapToDriverValue==="function"}var u7={mapFromDriverValue:(X)=>X},d7={mapToDriverValue:(X)=>X},QC={...u7,...d7};class A1{constructor(X,Y=d7){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 A1(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 BZ(X,Y){return X.map((Z)=>{if(A(Z,w4)){if(!(Z.name in Y))throw Error(`No value for placeholder "${Z.name}" was provided`);return Y[Z.name]}if(A(Z,A1)&&A(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 nU=Symbol.for("drizzle:IsDrizzleView");class U1{static[E]="View";[V0];[nU]=!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])};T0.prototype.getSQL=function(){return new S([this])};class A8{constructor(X){this.table=X}static[E]="ColumnAliasProxyHandler";get(X,Y){if(Y==="table")return this.table;return X[Y]}}class M2{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 A8(new Proxy(X,this)))}),G}let Z=X[Y];if(A(Z,z0))return new Proxy(Z,new A8(new Proxy(X,this)));return Z}}function x6(X,Y){return new Proxy(X,new M2(Y,!1))}function r1(X,Y){return new Proxy(X,new A8(new Proxy(X.table,new M2(Y,!1))))}function TZ(X,Y){return new S.Aliased(R2(X.sql,Y),X.fieldAlias)}function R2(X,Y){return V.join(X.queryChunks.map((Z)=>{if(A(Z,z0))return r1(Z,Y);if(A(Z,S))return R2(Z,Y);if(A(Z,S.Aliased))return TZ(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 J4 extends Error{constructor(X,Y,Z){super(`Failed query: ${X}
67
+ params: ${Y}`);if(this.query=X,this.params=Y,this.cause=Z,Error.captureStackTrace(this,J4),Z)this.cause=Z}}class CZ extends f6{static[E]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class c7{static[E]="ConsoleLogWriter";write(X){console.log(X)}}class qZ{static[E]="DefaultLogger";writer;constructor(X){this.writer=X?.writer??new c7}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 jZ{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 l7(X,Y,Z){let _={},G=X.reduce((W,{path:$,field:H},Q)=>{let J;if(A(H,z0))J=H;else if(A(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&&A(H,z0)&&$.length===2){let R=$[0];if(!(R in _))_[R]=w===null?y0(H.table):!1;else if(typeof _[R]==="string"&&_[R]!==y0(H.table))_[R]=!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 T1(X,Y){return Object.entries(X).reduce((Z,[_,G])=>{if(typeof _!=="string")return Z;let W=Y?[...Y,_]:[_];if(A(G,z0)||A(G,S)||A(G,S.Aliased))Z.push({path:W,field:G});else if(A(G,T))Z.push(...T1(G[T.Symbol.Columns],W));else Z.push(...T1(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(A(G,S)||A(G,z0))return[_,G];else return[_,new A1(G,X[T.Symbol.Columns][_])]});if(Z.length===0)throw Error("No values to set");return Object.fromEntries(Z)}function o7(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 i7(X){return X[T.Symbol.Columns]}function Q4(X){return A(X,T0)?X._.alias:A(X,U1)?X[V0].name:A(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 n7(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 x{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 r7 extends N4{static[E]="PgBigInt53Builder";constructor(X){super(X,"number","PgBigInt53")}build(X){return new s7(X,this.config)}}class s7 extends B{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}}class t7 extends N4{static[E]="PgBigInt64Builder";constructor(X){super(X,"bigint","PgBigInt64")}build(X){return new a7(X,this.config)}}class a7 extends B{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(X){return BigInt(X)}}function e7(X,Y){let{name:Z,config:_}=a(X,Y);if(_.mode==="number")return new r7(Z);return new t7(Z)}class X3 extends x{static[E]="PgBigSerial53Builder";constructor(X){super(X,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new Y3(X,this.config)}}class Y3 extends B{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}}class Z3 extends x{static[E]="PgBigSerial64Builder";constructor(X){super(X,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(X){return new _3(X,this.config)}}class _3 extends B{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(X){return BigInt(X)}}function G3(X,Y){let{name:Z,config:_}=a(X,Y);if(_.mode==="number")return new X3(Z);return new Z3(Z)}class W3 extends x{static[E]="PgBooleanBuilder";constructor(X){super(X,"boolean","PgBoolean")}build(X){return new $3(X,this.config)}}class $3 extends B{static[E]="PgBoolean";getSQLType(){return"boolean"}}function N2(X){return new W3(X??"")}class H3 extends x{static[E]="PgCharBuilder";constructor(X,Y){super(X,"string","PgChar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(X){return new J3(X,this.config)}}class J3 extends B{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function Q3(X,Y={}){let{name:Z,config:_}=a(X,Y);return new H3(Z,_)}class z3 extends x{static[E]="PgCidrBuilder";constructor(X){super(X,"string","PgCidr")}build(X){return new F3(X,this.config)}}class F3 extends B{static[E]="PgCidr";getSQLType(){return"cidr"}}function U3(X){return new z3(X??"")}class E3 extends x{static[E]="PgCustomColumnBuilder";constructor(X,Y,Z){super(X,"custom","PgCustomColumn");this.config.fieldConfig=Y,this.config.customTypeParams=Z}build(X){return new O3(X,this.config)}}class O3 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 V3(X){return(Y,Z)=>{let{name:_,config:G}=a(Y,Z);return new E3(_,G,X)}}class z4 extends x{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(V`now()`)}}class D3 extends z4{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 L3 extends z4{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 A3(X,Y){let{name:Z,config:_}=a(X,Y);if(_?.mode==="date")return new D3(Z);return new L3(Z)}class M3 extends x{static[E]="PgDoublePrecisionBuilder";constructor(X){super(X,"number","PgDoublePrecision")}build(X){return new R3(X,this.config)}}class R3 extends B{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(X){if(typeof X==="string")return Number.parseFloat(X);return X}}function w3(X){return new M3(X??"")}class N3 extends x{static[E]="PgInetBuilder";constructor(X){super(X,"string","PgInet")}build(X){return new I3(X,this.config)}}class I3 extends B{static[E]="PgInet";getSQLType(){return"inet"}}function K3(X){return new N3(X??"")}class B3 extends N4{static[E]="PgIntegerBuilder";constructor(X){super(X,"number","PgInteger")}build(X){return new T3(X,this.config)}}class T3 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 B3(X??"")}class C3 extends x{static[E]="PgIntervalBuilder";constructor(X,Y){super(X,"string","PgInterval");this.config.intervalConfig=Y}build(X){return new q3(X,this.config)}}class q3 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 j3(X,Y={}){let{name:Z,config:_}=a(X,Y);return new C3(Z,_)}class S3 extends x{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 P3(X){return new S3(X??"")}class v3 extends x{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 x3(X){return new v3(X??"")}class f3 extends x{static[E]="PgLineBuilder";constructor(X){super(X,"array","PgLine")}build(X){return new h3(X,this.config)}}class h3 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 k3 extends x{static[E]="PgLineABCBuilder";constructor(X){super(X,"json","PgLineABC")}build(X){return new b3(X,this.config)}}class b3 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 y3(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new f3(Z);return new k3(Z)}class g3 extends x{static[E]="PgMacaddrBuilder";constructor(X){super(X,"string","PgMacaddr")}build(X){return new p3(X,this.config)}}class p3 extends B{static[E]="PgMacaddr";getSQLType(){return"macaddr"}}function m3(X){return new g3(X??"")}class u3 extends x{static[E]="PgMacaddr8Builder";constructor(X){super(X,"string","PgMacaddr8")}build(X){return new d3(X,this.config)}}class d3 extends B{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}}function c3(X){return new u3(X??"")}class l3 extends x{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 o3 extends x{static[E]="PgNumericNumberBuilder";constructor(X,Y,Z){super(X,"number","PgNumericNumber");this.config.precision=Y,this.config.scale=Z}build(X){return new i3(X,this.config)}}class i3 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 n3 extends x{static[E]="PgNumericBigIntBuilder";constructor(X,Y,Z){super(X,"bigint","PgNumericBigInt");this.config.precision=Y,this.config.scale=Z}build(X){return new r3(X,this.config)}}class r3 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 s3(X,Y){let{name:Z,config:_}=a(X,Y),G=_?.mode;return G==="number"?new o3(Z,_?.precision,_?.scale):G==="bigint"?new n3(Z,_?.precision,_?.scale):new l3(Z,_?.precision,_?.scale)}class t3 extends x{static[E]="PgPointTupleBuilder";constructor(X){super(X,"array","PgPointTuple")}build(X){return new a3(X,this.config)}}class a3 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 e3 extends x{static[E]="PgPointObjectBuilder";constructor(X){super(X,"json","PgPointObject")}build(X){return new XW(X,this.config)}}class XW 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 YW(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new t3(Z);return new e3(Z)}function rU(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 ZW(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 SZ(X){let Y=rU(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=ZW(Y,Z);Z+=8;let Q=ZW(Y,Z);return Z+=8,[H,Q]}throw Error("Unsupported geometry type")}class _W extends x{static[E]="PgGeometryBuilder";constructor(X){super(X,"array","PgGeometry")}build(X){return new GW(X,this.config)}}class GW extends B{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(X){return SZ(X)}mapToDriverValue(X){return`point(${X[0]} ${X[1]})`}}class WW extends x{static[E]="PgGeometryObjectBuilder";constructor(X){super(X,"json","PgGeometryObject")}build(X){return new $W(X,this.config)}}class $W extends B{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(X){let Y=SZ(X);return{x:Y[0],y:Y[1]}}mapToDriverValue(X){return`point(${X.x} ${X.y})`}}function HW(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new _W(Z);return new WW(Z)}class JW extends x{static[E]="PgRealBuilder";constructor(X,Y){super(X,"number","PgReal");this.config.length=Y}build(X){return new QW(X,this.config)}}class QW 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 zW(X){return new JW(X??"")}class FW extends x{static[E]="PgSerialBuilder";constructor(X){super(X,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new UW(X,this.config)}}class UW extends B{static[E]="PgSerial";getSQLType(){return"serial"}}function EW(X){return new FW(X??"")}class OW extends N4{static[E]="PgSmallIntBuilder";constructor(X){super(X,"number","PgSmallInt")}build(X){return new VW(X,this.config)}}class VW extends B{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(X)=>{if(typeof X==="string")return Number(X);return X}}function DW(X){return new OW(X??"")}class LW extends x{static[E]="PgSmallSerialBuilder";constructor(X){super(X,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new AW(X,this.config)}}class AW extends B{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}}function MW(X){return new LW(X??"")}class RW extends x{static[E]="PgTextBuilder";constructor(X,Y){super(X,"string","PgText");this.config.enumValues=Y.enum}build(X){return new wW(X,this.config)}}class wW extends B{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function NW(X,Y={}){let{name:Z,config:_}=a(X,Y);return new RW(Z,_)}class IW extends z4{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 KW(X,Y={}){let{name:Z,config:_}=a(X,Y);return new IW(Z,_.withTimezone??!1,_.precision)}class BW extends z4{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 TW extends z4{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 CW(X,Y={}){let{name:Z,config:_}=a(X,Y);if(_?.mode==="string")return new TW(Z,_.withTimezone??!1,_.precision);return new BW(Z,_?.withTimezone??!1,_?.precision)}class qW extends x{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 C1(X){return new qW(X??"")}class jW extends x{static[E]="PgVarcharBuilder";constructor(X,Y){super(X,"string","PgVarchar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(X){return new SW(X,this.config)}}class SW 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 jW(Z,_)}class PW extends x{static[E]="PgBinaryVectorBuilder";constructor(X,Y){super(X,"string","PgBinaryVector");this.config.dimensions=Y.dimensions}build(X){return new vW(X,this.config)}}class vW extends B{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function xW(X,Y){let{name:Z,config:_}=a(X,Y);return new PW(Z,_)}class fW extends x{static[E]="PgHalfVectorBuilder";constructor(X,Y){super(X,"array","PgHalfVector");this.config.dimensions=Y.dimensions}build(X){return new hW(X,this.config)}}class hW 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 kW(X,Y){let{name:Z,config:_}=a(X,Y);return new fW(Z,_)}class bW extends x{static[E]="PgSparseVectorBuilder";constructor(X,Y){super(X,"string","PgSparseVector");this.config.dimensions=Y.dimensions}build(X){return new yW(X,this.config)}}class yW extends B{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function gW(X,Y){let{name:Z,config:_}=a(X,Y);return new bW(Z,_)}class pW extends x{static[E]="PgVectorBuilder";constructor(X,Y){super(X,"array","PgVector");this.config.dimensions=Y.dimensions}build(X){return new mW(X,this.config)}}class mW 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 uW(X,Y){let{name:Z,config:_}=a(X,Y);return new pW(Z,_)}function dW(){return{bigint:e7,bigserial:G3,boolean:N2,char:Q3,cidr:U3,customType:V3,date:A3,doublePrecision:w3,inet:K3,integer:I2,interval:j3,json:P3,jsonb:x3,line:y3,macaddr:m3,macaddr8:c3,numeric:s3,point:YW,geometry:HW,real:zW,serial:EW,smallint:DW,smallserial:MW,text:NW,time:KW,timestamp:CW,uuid:C1,varchar:n0,bit:xW,halfvec:kW,sparsevec:gW,vector:uW}}var PZ=Symbol.for("drizzle:PgInlineForeignKeys"),cW=Symbol.for("drizzle:EnableRLS");class b0 extends T{static[E]="PgTable";static Symbol=Object.assign({},T.Symbol,{InlineForeignKeys:PZ,EnableRLS:cW});[PZ]=[];[cW]=!1;[T.Symbol.ExtraConfigBuilder]=void 0;[T.Symbol.ExtraConfigColumns]={}}function sU(X,Y,Z,_,G=X){let W=new b0(X,_,G),$=typeof Y==="function"?Y(dW()):Y,H=Object.fromEntries(Object.entries($).map(([z,F])=>{let O=F;O.setName(z);let D=O.build(W);return W[PZ].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 sU(X,Y,Z,void 0)};function lW(...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 oW(X,this.columns,this.name)}}class oW{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 E1(X,Y){if(m7(Y)&&!KZ(X)&&!A(X,A1)&&!A(X,w4)&&!A(X,z0)&&!A(X,T)&&!A(X,U1))return new A1(X,Y);return X}var l6=(X,Y)=>{return V`${X} = ${E1(Y,X)}`},iW=(X,Y)=>{return V`${X} <> ${E1(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 nW(...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 rW(X){return V`not ${X}`}var sW=(X,Y)=>{return V`${X} > ${E1(Y,X)}`},tW=(X,Y)=>{return V`${X} >= ${E1(Y,X)}`},aW=(X,Y)=>{return V`${X} < ${E1(Y,X)}`},eW=(X,Y)=>{return V`${X} <= ${E1(Y,X)}`};function X$(X,Y){if(Array.isArray(Y)){if(Y.length===0)return V`false`;return V`${X} in ${Y.map((Z)=>E1(Z,X))}`}return V`${X} in ${E1(Y,X)}`}function Y$(X,Y){if(Array.isArray(Y)){if(Y.length===0)return V`true`;return V`${X} not in ${Y.map((Z)=>E1(Z,X))}`}return V`${X} not in ${E1(Y,X)}`}function Z$(X){return V`${X} is null`}function _$(X){return V`${X} is not null`}function G$(X){return V`exists ${X}`}function W$(X){return V`not exists ${X}`}function $$(X,Y,Z){return V`${X} between ${E1(Y,X)} and ${E1(Z,X)}`}function H$(X,Y,Z){return V`${X} not between ${E1(Y,X)} and ${E1(Z,X)}`}function J$(X,Y){return V`${X} like ${Y}`}function Q$(X,Y){return V`${X} not like ${Y}`}function z$(X,Y){return V`${X} ilike ${Y}`}function F$(X,Y){return V`${X} not ilike ${Y}`}function U$(X){return V`${X} asc`}function E$(X){return V`${X} desc`}class vZ{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 O${constructor(X,Y){this.table=X,this.config=Y}static[E]="Relations"}class K4 extends vZ{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 vZ{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 V$(){return{and:B2,between:$$,eq:l6,exists:G$,gt:sW,gte:tW,ilike:z$,inArray:X$,isNull:Z$,isNotNull:_$,like:J$,lt:aW,lte:eW,ne:iW,not:rW,notBetween:H$,notExists:W$,notLike:Q$,notIlike:F$,notInArray:Y$,or:nW,sql:V}}function D$(){return{sql:V,asc:U$,desc:E$}}function L$(X,Y){if(Object.keys(X).length===1&&"default"in X&&!A(X.default,T))X=X.default;let Z={},_={},G={};for(let[W,$]of Object.entries(X))if(A($,T)){let H=y4($),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(A(z,K2))G[W].primaryKey.push(...z.columns)}}else if(A($,O$)){let H=y4($.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 tU(X){return function(Z,_){return new K4(X,Z,_,_?.fields.reduce((G,W)=>G&&W.notNull,!0)??!1)}}function aU(X){return function(Z,_){return new T2(X,Z,_)}}function A$(X,Y,Z){if(A(Z,K4)&&Z.config)return{fields:Z.config.fields,references:Z.config.references};let _=Y[y4(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[y4(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]&&A(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 M$(X){return{one:tU(X),many:aU(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]=A(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(A(J,z0))z=J;else if(A(J,S))z=J.decoder;else z=J.sql.decoder;W[H.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return W}import NE from"os";import IE from"fs";var i6=new Map,xZ=new Map,fZ=Symbol("OriginError"),M8={};class q1 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[fZ]=this.handler.debug?Error():this.tagged&&eU(this.strings)}get origin(){return(this.handler.debug?this[fZ].stack:this.tagged&&xZ.has(this.strings)?xZ.get(this.strings):xZ.set(this.strings,this[fZ].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 eU(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 R8 extends Error{constructor(X){super(X.message);this.name=this.constructor.name,Object.assign(this,X)}}var S0={connection:R$,postgres:w$,generic:N$,notSupported:I$};function R$(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,R$),W}function w$(X){let Y=new R8(X);return Error.captureStackTrace(Y,w$),Y}function N$(X,Y){let Z=Object.assign(Error(X+": "+Y),{code:X});return Error.captureStackTrace(Z,N$),Z}function I$(X){let Y=Object.assign(Error(X+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:X});return Error.captureStackTrace(Y,I$),Y}var XE={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(){hZ()}catch(){hZ()}finally(){hZ()}}class S2 extends s6{constructor(X){super();this.value=e6(X)}}class s1 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=YE.map(([W,$])=>({fn:$,i:X.search(W)})).sort((W,$)=>W.i-$.i).pop();return G.i===-1?pZ(this.first,_):G.fn(this.first,this.rest,Y,Z,_)}}function a6(X,Y,Z,_){let G=X instanceof s1?X.value:X;if(G===void 0){if(X instanceof s1?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 s1?(Y.push(X.value),X.array?X.array[X.type||r6(X.value)]||X.type||C$(X.value):X.type):(Y.push(X),r6(X)))}var B$=j$(XE);function yZ(X,Y,Z,_,G,W){for(let $=1;$<X.strings.length;$++)Y+=gZ(Y,Z,_,G,W)+X.strings[$],Z=X.args[$];return Y}function gZ(X,Y,Z,_,G){return Y instanceof t6?Y.build(X,Z,_,G):Y instanceof q1?bZ(Y,Z,_,G):Y instanceof S2?Y.value:Y&&Y[0]instanceof q1?Y.reduce((W,$)=>W+" "+bZ($,Z,_,G),""):a6(Y,Z,_,G)}function bZ(X,Y,Z,_){return X.fragment=!0,yZ(X,X.strings[0],X.args[0],Y,Z,_)}function T$(X,Y,Z,_,G){return X.map((W)=>"("+_.map(($)=>gZ("values",W[$],Y,Z,G)).join(",")+")").join(",")}function K$(X,Y,Z,_,G){let W=Array.isArray(X[0]),$=Y.length?Y.flat():Object.keys(W?X[0]:X);return T$(W?X:[X],Z,_,$,G)}function n6(X,Y,Z,_,G){if(typeof X==="string"&&(X=[X].concat(Y)),Array.isArray(X))return pZ(X,G);let W;return(Y.length?Y.flat():Object.keys(X)).map((H)=>{return W=X[H],(W instanceof q1?bZ(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 YE=Object.entries({values:K$,in:(...X)=>{let Y=K$(...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)+"="+gZ("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"("+pZ(W,G)+")values"+T$(Array.isArray(X)?X:[X],Z,_,W,G)}}).map(([X,Y])=>[new RegExp("((?:^|[\\s(])"+X+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Y]);function hZ(){throw S0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:ZE,parsers:_E}=B$;function C$(X){if(Array.isArray(X))return C$(X[0]);return typeof X==="string"?1009:0}var q$=function(X){let Y=j$(X||{});return{serializers:Object.assign({},ZE,Y.serializers),parsers:Object.assign({},_E,Y.parsers)}};function j$(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 pZ(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 s1?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},GE=/\\/g,WE=/"/g;function $E(X){return X.replace(GE,"\\\\").replace(WE,"\\\"")}var S$=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":'"'+$E(Z?Z(H.type?H.value:H):""+H)+'"'}).join($)+"}"},kZ={i:0,char:null,str:"",quoted:!1,last:0},P$=function(Y,Z,_){return kZ.i=kZ.last=0,v$(kZ,Y,Z,_)};function v$(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(v$(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 g4=(X)=>{let Y=X[0];for(let Z=1;Z<X.length;Z++)Y+=X[Z]==="_"?X[++Z].toUpperCase():X[Z];return Y},p4=(X)=>{let Y=X[0].toUpperCase();for(let Z=1;Z<X.length;Z++)Y+=X[Z]==="_"?X[++Z].toUpperCase():X[Z];return Y},m4=(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 mZ(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}}g4.column={from:g4};g4.value={from:mZ(g4)};C2.column={to:C2};var uZ={...g4};uZ.column.to=C2;p4.column={from:p4};p4.value={from:mZ(p4)};q2.column={to:q2};var dZ={...p4};dZ.column.to=q2;m4.column={from:m4};m4.value={from:mZ(m4)};j2.column={to:j2};var cZ={...m4};cZ.column.to=j2;import x$ from"net";import zE from"tls";import P2 from"crypto";import lZ from"stream";import{performance as f$}from"perf_hooks";class u4 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=HE;function HE(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),JE="BCcDdEFfHPpQSX".split("").reduce((X,Y)=>{let Z=Y.charCodeAt(0);return X[Y]=()=>{return r0[0]=Z,H0.i=5,H0},X},{}),H0=Object.assign(QE,JE,{N:String.fromCharCode(0),i:0,inc(X){return H0.i+=X,H0},str(X){let Y=Buffer.byteLength(X);return XX(Y),H0.i+=r0.write(X,H0.i,Y,"utf8"),H0},i16(X){return XX(2),r0.writeUInt16BE(X,H0.i),H0.i+=2,H0},i32(X,Y){if(Y||Y===0)return r0.writeUInt32BE(X,Y),H0;return XX(4),r0.writeUInt32BE(X,H0.i),H0.i+=4,H0},z(X){return XX(X),r0.fill(0,H0.i,H0.i+X),H0.i+=X,H0},raw(X){return r0=Buffer.concat([r0.subarray(0,H0.i),X]),H0.i=r0.length,H0},end(X=1){r0.writeUInt32BE(H0.i-X,X);let Y=r0.subarray(0,H0.i);return H0.i=0,r0=Buffer.allocUnsafe(256),Y}}),b=H0;function XX(X){if(r0.length-H0.i<X){let Y=r0,Z=Y.length;r0=Buffer.allocUnsafe(Z+(Z>>1)+X),Y.copy(r0)}}function QE(){return H0.i=0,H0}var nZ=b$,FE=1,B4=b().S().end(),h$=b().H().end(),UE=b().i32(8).i32(80877103).end(8),EE=Buffer.concat([b().E().str(b.N).i32(0).end(),B4]),OE=b().D().str("S").str(b.N).end(),w8=()=>{},VE=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),DE={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 b$(X,Y={},{onopen:Z=w8,onend:_=w8,onclose:G=w8}={}){let{ssl:W,max:$,user:H,host:Q,port:J,database:z,parsers:F,transform:O,onnotice:D,onnotify:w,onparameter:R,max_pipeline:v,keep_alive:j,backoff:P,target_session_attrs:h}=X,i=M1(),g=FE++,p={pid:null,secret:null},m=iZ(OX,X.idle_timeout),_0=iZ(OX,X.max_lifetime),u0=iZ($H,X.connect_timeout),K=null,J0,o=new u4,X0=Buffer.alloc(0),g0=X.fetch_types,V1={},j1={},l4=Math.random().toString(36).slice(2),I=1,u=0,W0=0,R0=0,P0=0,n=0,$0=0,C0=0,w0=null,D0=null,d0=!1,U0=null,S1=null,p0=null,F4=null,v0=null,L0=null,P1=null,d1=null,q=null,B8=null,c0={queue:Y.closed,idleTimer:m,connect(U){p0=U,w5()},terminate:C8,execute:T8,cancel:ZH,end:OX,count:0,id:g};return Y.closed&&Y.closed.push(c0),c0;async function YH(){let U;try{U=X.socket?await Promise.resolve(X.socket(X)):new x$.Socket}catch(L){i4(L);return}return U.on("error",i4),U.on("close",N5),U.on("drain",M5),U}async function ZH({pid:U,secret:L},y,Z0){try{J0=b().i32(16).i32(80877102).i32(U).i32(L).end(16),await R5(),K.once("error",Z0),K.once("close",y)}catch(I0){Z0(I0)}}function T8(U){if(d0)return g2(U,S0.connection("CONNECTION_DESTROYED",X));if(U.cancelled)return;try{return U.state=p,q?i.push(U):(q=U,q.active=!0),WH(U),m0(_H(U))&&!U.describeFirst&&!U.cursorFn&&i.length<v&&(!U.options.onexecute||U.options.onexecute(c0))}catch(L){return i.length===0&&m0(B4),c1(L),!0}}function _H(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([D5(U),h$]):U.prepare?U.prepared?y2(U):Buffer.concat([D5(U),y2(U)]):GH(U)}function D5(U){return Buffer.concat([K5(U.statement.string,U.parameters,U.statement.types,U.statement.name),cH("S",U.statement.name)])}function y2(U){return Buffer.concat([dH(U.parameters,U.statement.types,U.statement.name,U.cursorName),U.cursorFn?B5("",U.cursorRows):EE])}function GH(U){return Buffer.concat([K5(U.statement.string,U.parameters,U.statement.types),OE,y2(U)])}function WH(U){let L=[],y=[],Z0=yZ(U,U.strings[0],U.args[0],L,y,X);!U.tagged&&U.args.forEach((I0)=>a6(I0,L,y,X)),U.prepare=X.prepare&&("prepare"in U.options?U.options.prepare:!0),U.string=Z0,U.signature=U.prepare&&y+Z0,U.onlyDescribe&&delete j1[U.signature],U.parameters=U.parameters||L,U.prepared=U.prepare&&U.signature in j1,U.describeFirst=U.onlyDescribe||L.length&&!U.prepared,U.statement=U.prepared?j1[U.signature]:{string:Z0,types:y,name:U.prepare?l4+I++:""},typeof X.debug==="function"&&X.debug(g,Z0,L,y)}function m0(U,L){if(L0=L0?Buffer.concat([L0,U]):Buffer.from(U),L||L0.length>=1024)return L5(L);return D0===null&&(D0=setImmediate(L5)),!0}function L5(U){let L=K.write(L0,U);return D0!==null&&clearImmediate(D0),L0=D0=null,L}function $H(){c1(S0.connection("CONNECT_TIMEOUT",X,K)),K.destroy()}async function A5(){if(m0(UE),!await new Promise((L)=>K.once("data",(y)=>L(y[0]===83)))&&W==="prefer")return o4();K.removeAllListeners(),K=zE.connect({socket:K,servername:x$.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",o4),K.on("error",i4),K.on("close",N5),K.on("drain",M5)}function M5(){!q&&Z(c0)}function EX(U){if(U0){if(U0.push(U),W0-=U.length,W0>0)return}X0=U0?Buffer.concat(U0,n-W0):X0.length===0?U:Buffer.concat([X0,U],X0.length+U.length);while(X0.length>4){if(n=X0.readUInt32BE(1),n>=X0.length){W0=n-X0.length,U0=[X0];break}try{HH(X0.subarray(0,n+1))}catch(L){q&&(q.cursorFn||q.describeFirst)&&m0(B4),c1(L)}X0=X0.subarray(n+1),W0=0,U0=null}}async function R5(){if(d0=!1,V1={},K||(K=await YH()),!K)return;if(u0.start(),X.socket)return W?A5():o4();if(K.on("connect",W?A5:o4),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 w5(){setTimeout(R5,u?u+$0-f$.now():0)}function o4(){try{j1={},g0=X.fetch_types,l4=Math.random().toString(36).slice(2),I=1,_0.start(),K.on("data",EX),j&&K.setKeepAlive&&K.setKeepAlive(!0,1000*j);let U=oH();m0(U)}catch(U){i4(U)}}function i4(U){if(c0.queue===Y.connecting&&X.host[P0+1])return;c1(U);while(i.length)g2(i.shift(),U)}function c1(U){v0&&(v0.destroy(U),v0=null),q&&g2(q,U),p0&&(g2(p0,U),p0=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/,`
68
+ `),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 F4||(!c0.reserved&&_(c0),!c0.reserved&&!p0&&!q&&i.length===0?(C8(),new Promise((U)=>K&&K.readyState!=="closed"?K.once("close",U):U())):F4=new Promise((U)=>P1=U))}function C8(){if(d0=!0,v0||q||p0||i.length)i4(S0.connection("CONNECTION_DESTROYED",X));if(clearImmediate(D0),K)K.removeListener("data",EX),K.removeListener("connect",o4),K.readyState==="open"&&K.end(b().X().end());P1&&(P1(),F4=P1=null)}async function N5(U){if(X0=Buffer.alloc(0),W0=0,U0=null,clearImmediate(D0),K.removeListener("data",EX),K.removeListener("connect",o4),m.cancel(),_0.cancel(),u0.cancel(),K.removeAllListeners(),K=null,p0)return w5();!U&&(q||i.length)&&i4(S0.connection("CONNECTION_CLOSED",X,K)),u=f$.now(),U&&X.shared.retries++,$0=(typeof P==="function"?P(X.shared.retries):P)*1000,G(c0,S0.connection("CONNECTION_CLOSED",X,K))}function HH(U,L=U[0]){(L===68?JH:L===100?hH:L===65?jH:L===83?QH:L===90?zH:L===67?FH:L===50?I5:L===49?UH:L===116?EH:L===84?OH:L===82?VH:L===110?wH:L===75?NH:L===69?CH:L===115?SH:L===51?PH:L===71?vH:L===78?bH:L===72?xH:L===99?kH:L===73?yH:L===86?gH:L===118?pH:L===87?fH:mH)(U)}function JH(U){let L=7,y,Z0,I0,l0=q.isRaw?Array(q.statement.columns.length):{};for(let s0=0;s0<q.statement.columns.length;s0++)Z0=q.statement.columns[s0],y=U.readInt32BE(L),L+=4,I0=y===-1?null:q.isRaw===!0?U.subarray(L,L+=y):Z0.parser===void 0?U.toString("utf8",L,L+=y):Z0.parser.array===!0?Z0.parser(U.toString("utf8",L+1,L+=y)):Z0.parser(U.toString("utf8",L,L+=y)),q.isRaw?l0[s0]=q.isRaw===!0?I0:O.value.from?O.value.from(I0,Z0):I0:l0[Z0.name]=O.value.from?O.value.from(I0,Z0):I0;q.forEachFn?q.forEachFn(O.row.from?O.row.from(l0):l0,o):o[C0++]=O.row.from?O.row.from(l0):l0}function QH(U){let[L,y]=U.toString("utf8",5,U.length-1).split(b.N);if(V1[L]=y,X.parameters[L]!==y)X.parameters[L]=y,R&&R(L,y)}function zH(U){if(q&&q.options.simple&&q.resolve(S1||o),q=S1=null,o=new u4,u0.cancel(),p0){if(h){if(!V1.in_hot_standby||!V1.default_transaction_read_only)return TH();else if(BH(h,V1))return C8()}if(g0)return p0.reserve&&(p0=null),IH();p0&&!p0.reserve&&T8(p0),X.shared.retries=P0=0,p0=null;return}while(i.length&&(q=i.shift())&&(q.active=!0,q.cancelled))b$(X).cancel(q.state,q.cancelled.resolve,q.cancelled.reject);if(q)return;c0.reserved?!c0.reserved.release&&U[5]===73?F4?C8():(c0.reserved=null,Z(c0)):c0.reserved():F4?C8():Z(c0)}function FH(U){C0=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=p;break}}if(B8&&(B8(),B8=null),o.command==="BEGIN"&&$!==1&&!c0.reserved)return c1(S0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(q.options.simple)return I5();if(q.cursorFn)o.count&&q.cursorFn(o),m0(B4);q.resolve(o)}function UH(){q.parsing=!1}function I5(){!o.statement&&(o.statement=q.statement),o.columns=q.statement.columns}function EH(U){let L=U.readUInt16BE(5);for(let y=0;y<L;++y)!q.statement.types[y]&&(q.statement.types[y]=U.readUInt32BE(7+y*4));q.prepare&&(j1[q.signature]=q.statement),q.describeFirst&&!q.onlyDescribe&&(m0(y2(q)),q.describeFirst=!1)}function OH(U){if(o.command)S1=S1||[o],S1.push(o=new u4),o.count=null,q.statement.columns=null;let L=U.readUInt16BE(5),y=7,Z0;q.statement.columns=Array(L);for(let I0=0;I0<L;++I0){Z0=y;while(U[y++]!==0);let l0=U.readUInt32BE(y),s0=U.readUInt16BE(y+4),U4=U.readUInt32BE(y+6);q.statement.columns[I0]={name:O.column.from?O.column.from(U.toString("utf8",Z0,y-1)):U.toString("utf8",Z0,y-1),parser:F[U4],table:l0,number:s0,type:U4},y+=18}if(o.statement=q.statement,q.onlyDescribe)return q.resolve(q.statement),m0(B4)}async function VH(U,L=U.readUInt32BE(5)){(L===3?DH:L===5?LH:L===10?AH:L===11?MH:L===12?RH:L!==0?uH:w8)(U,L)}async function DH(){let U=await VX();m0(b().p().str(U).z(1).end())}async function LH(U){let L="md5"+await k$(Buffer.concat([Buffer.from(await k$(await VX()+H)),U.subarray(9)]));m0(b().p().str(L).z(1).end())}async function AH(){d1=(await P2.randomBytes(18)).toString("base64"),b().p().str("SCRAM-SHA-256"+b.N);let U=b.i;m0(b.inc(4).str("n,,n=*,r="+d1).i32(b.i-U-4,U).end())}async function MH(U){let L=U.toString("utf8",9).split(",").reduce((s0,U4)=>(s0[U4[0]]=U4.slice(2),s0),{}),y=await P2.pbkdf2Sync(await VX(),Buffer.from(L.s,"base64"),parseInt(L.i),32,"sha256"),Z0=await YX(y,"Client Key"),I0="n=*,r="+d1+",r="+L.r+",s="+L.s+",i="+L.i+",c=biws,r="+L.r;w0=(await YX(await YX(y,"Server Key"),I0)).toString("base64");let l0="c=biws,r="+L.r+",p="+AE(Z0,Buffer.from(await YX(await LE(Z0),I0))).toString("base64");m0(b().p().str(l0).end())}function RH(U){if(U.toString("utf8",9).split(b.N,1)[0].slice(2)===w0)return;c1(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 wH(){if(o.statement=q.statement,o.statement.columns=[],q.onlyDescribe)return q.resolve(q.statement),m0(B4)}function NH(U){p.pid=U.readUInt32BE(5),p.secret=U.readUInt32BE(9)}async function IH(){g0=!1,(await new q1([`
68
69
  select b.oid, b.typarray
69
70
  from pg_catalog.pg_type a
70
71
  left join pg_catalog.pg_type b on b.oid = a.typelem
71
72
  where a.typcategory = 'A'
72
73
  group by b.oid, b.typarray
73
74
  order by b.oid
74
- `],[],B8)).forEach(({oid:L,typarray:g})=>LH(L,g))}function LH(U,L){if(!!X.parsers[L]&&!!X.serializers[L])return;let g=X.parsers[U];X.shared.typeArrayMap[U]=L,X.parsers[L]=(Z0)=>K$(Z0,g,L),X.parsers[L].array=!0,X.serializers[L]=(Z0)=>I$(Z0,X.serializers[U],X,L)}function MH(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 AH(){let U=new C1([`
75
+ `],[],T8)).forEach(({oid:L,typarray:y})=>KH(L,y))}function KH(U,L){if(!!X.parsers[L]&&!!X.serializers[L])return;let y=X.parsers[U];X.shared.typeArrayMap[U]=L,X.parsers[L]=(Z0)=>P$(Z0,y,L),X.parsers[L].array=!0,X.serializers[L]=(Z0)=>S$(Z0,X.serializers[U],X,L)}function BH(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 TH(){let U=new q1([`
75
76
  show transaction_read_only;
76
77
  select pg_catalog.pg_is_in_recovery()
77
- `],[],B8,null,{simple:!0});U.resolve=([[L],[g]])=>{E1.default_transaction_read_only=L.transaction_read_only,E1.in_hot_standby=g.pg_is_in_recovery?"on":"off"},U.execute()}function RH(U){q&&(q.cursorFn||q.describeFirst)&&m0(B4);let L=S0.postgres(uZ(U));q&&q.retried?d1(q.retried):q&&q.prepared&&$E.has(L.routine)?wH(q,L):d1(L)}function wH(U,L){delete q1[U.signature],U.retried=L,B8(U)}function NH(U){if(!A)return;let L=9;while(U[L++]!==0);A(U.toString("utf8",9,L-1),U.toString("utf8",L,U.length-1))}async function IH(){try{let U=await Promise.resolve(q.cursorFn(o));C0=0,U===M8?m0(yH(q.portal)):(o=new m4,m0(w5("",q.cursorRows)))}catch(U){m0(B4),q.reject(U)}}function KH(){o.count&&q.cursorFn(o),q.resolve(o)}function BH(){v0=new mZ.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 TH(){v0=new mZ.Readable({read(){K.resume()}}),q.resolve(v0)}function CH(){v0=new mZ.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 qH(U){v0&&(v0.push(U.subarray(5))||K.pause())}function jH(){v0&&v0.push(null),v0=null}function SH(U){D?D(uZ(U)):console.log(uZ(U))}function PH(){}function vH(){d1(S0.notSupported("FunctionCallResponse"))}function xH(){d1(S0.notSupported("NegotiateProtocolVersion"))}function fH(U){console.error("Postgres.js : Unknown Message:",U[0])}function hH(U,L){console.error("Postgres.js : Unknown Auth:",L)}function kH(U,L,g="",Z0=""){let I0,l0;return b().B().str(Z0+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,I0=b.i,b.inc(4).str(s0).i32(b.i-I0-4,I0)}),b.i16(0),b.end()}function R5(U,L,g,Z0=""){return b().P().str(Z0+b.N).str(U+b.N).i16(L.length),L.forEach((I0,l0)=>b.i32(g[l0]||0)),b.end()}function bH(U,L=""){return b().D().str(U).str(L+b.N).end()}function w5(U="",L=0){return Buffer.concat([b().E().str(U+b.N).i32(L).end(),q$])}function yH(U=""){return Buffer.concat([b().C().str("P").str(U+b.N).end(),b().S().end()])}function gH(){return J0||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 uZ(X){let Y={},Z=5;for(let _=5;_<X.length-1;_++)if(X[_]===0)Y[HE[X[Z]]]=X.toString("utf8",Z+1,_),Z=_+1;return Y}function j$(X){return S2.createHash("md5").update(X).digest("hex")}function a6(X,Y){return S2.createHmac("sha256",X).update(Y).digest()}function JE(X){return S2.createHash("sha256").update(X).digest()}function QE(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 dZ(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 P$=()=>{};function lZ(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((R)=>R.forEach(({onsubscribe:v})=>v()))},no_subscribe:!0}),J=Q.end,z=Q.close;return Q.end=async()=>{return H=!0,$&&await new Promise((R)=>($.once("close",R),$.end())),J()},Q.close=async()=>{return $&&await new Promise((R)=>($.once("close",R),$.end())),z()},F;async function F(R,v,j=P$,P=P$){if(R=UE(R),!W)W=D(Q,_,Y.publications);let h={fn:v,onsubscribe:j},i=Z.has(R)?Z.get(R).add(h):Z.set(R,new Set([h])).get(R),p=()=>{i.delete(h),i.size===0&&Z.delete(R)};return W.then((y)=>{return O(y),j(),$&&$.on("error",P),{unsubscribe:p,state:G,sql:Q}})}function O(R){$=R.stream,G.pid=R.state.pid,G.secret=R.state.secret}async function D(R,v,j){if(!j)throw Error("Missing publication names");let P=await R.unsafe(`CREATE_REPLICATION_SLOT ${v} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[h]=P,i=await R.unsafe(`START_REPLICATION SLOT ${v} 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",R.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)FE(K.subarray(25),p,R.options.parsers,_0,Y.transform);else if(K[0]===107&&K[17])p.lsn=K.subarray(1,9),u0()}function _0(K,J0){let o=J0.relation.schema+"."+J0.relation.table;A("*",K,J0),A("*:"+o,K,J0),J0.relation.keys.length&&A("*:"+o+"="+J0.relation.keys.map((X0)=>K[X0.name]),K,J0),A(J0.command,K,J0),A(J0.command+":"+o,K,J0),J0.relation.keys.length&&A(J0.command+":"+o+"="+J0.relation.keys.map((X0)=>K[X0.name]),K,J0)}function u0(){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 A(R,v,j){Z.has(R)&&Z.get(R).forEach(({fn:P})=>P(v,j,R))}}function zE(X){return new Date(Date.UTC(2000,0,1)+Number(X/BigInt(1000)))}function FE(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=zE($.readBigInt64BE(9)),Y.lsn=$.subarray(1,9)},I:($)=>{let H=1,Q=Y[$.readUInt32BE(H)],{row:J}=e6($,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?e6($,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?e6($,Q.columns,H+=3,G):null;z&&(H=z.i);let{row:F}=e6($,Q.columns,H+3,G);_(F,{command:"update",relation:Q,key:J,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce(W,{})[X[0]](X)}function e6(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 UE(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 v$ from"stream";function oZ(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
+ `],[],T8,null,{simple:!0});U.resolve=([[L],[y]])=>{V1.default_transaction_read_only=L.transaction_read_only,V1.in_hot_standby=y.pg_is_in_recovery?"on":"off"},U.execute()}function CH(U){q&&(q.cursorFn||q.describeFirst)&&m0(B4);let L=S0.postgres(oZ(U));q&&q.retried?c1(q.retried):q&&q.prepared&&VE.has(L.routine)?qH(q,L):c1(L)}function qH(U,L){delete j1[U.signature],U.retried=L,T8(U)}function jH(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 SH(){try{let U=await Promise.resolve(q.cursorFn(o));C0=0,U===M8?m0(lH(q.portal)):(o=new u4,m0(B5("",q.cursorRows)))}catch(U){m0(B4),q.reject(U)}}function PH(){o.count&&q.cursorFn(o),q.resolve(o)}function vH(){v0=new lZ.Writable({autoDestroy:!0,write(U,L,y){K.write(b().d().raw(U).end(),y)},destroy(U,L){L(U),K.write(b().f().str(U+b.N).end()),v0=null},final(U){K.write(b().c().end()),B8=U}}),q.resolve(v0)}function xH(){v0=new lZ.Readable({read(){K.resume()}}),q.resolve(v0)}function fH(){v0=new lZ.Duplex({autoDestroy:!0,read(){K.resume()},write(U,L,y){K.write(b().d().raw(U).end(),y)},destroy(U,L){L(U),K.write(b().f().str(U+b.N).end()),v0=null},final(U){K.write(b().c().end()),B8=U}}),q.resolve(v0)}function hH(U){v0&&(v0.push(U.subarray(5))||K.pause())}function kH(){v0&&v0.push(null),v0=null}function bH(U){D?D(oZ(U)):console.log(oZ(U))}function yH(){}function gH(){c1(S0.notSupported("FunctionCallResponse"))}function pH(){c1(S0.notSupported("NegotiateProtocolVersion"))}function mH(U){console.error("Postgres.js : Unknown Message:",U[0])}function uH(U,L){console.error("Postgres.js : Unknown Auth:",L)}function dH(U,L,y="",Z0=""){let I0,l0;return b().B().str(Z0+b.N).str(y+b.N).i16(0).i16(U.length),U.forEach((s0,U4)=>{if(s0===null)return b.i32(4294967295);l0=L[U4],U[U4]=s0=l0 in X.serializers?X.serializers[l0](s0):""+s0,I0=b.i,b.inc(4).str(s0).i32(b.i-I0-4,I0)}),b.i16(0),b.end()}function K5(U,L,y,Z0=""){return b().P().str(Z0+b.N).str(U+b.N).i16(L.length),L.forEach((I0,l0)=>b.i32(y[l0]||0)),b.end()}function cH(U,L=""){return b().D().str(U).str(L+b.N).end()}function B5(U="",L=0){return Buffer.concat([b().E().str(U+b.N).i32(L).end(),h$])}function lH(U=""){return Buffer.concat([b().C().str("P").str(U+b.N).end(),b().S().end()])}function oH(){return J0||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 oZ(X){let Y={},Z=5;for(let _=5;_<X.length-1;_++)if(X[_]===0)Y[DE[X[Z]]]=X.toString("utf8",Z+1,_),Z=_+1;return Y}function k$(X){return P2.createHash("md5").update(X).digest("hex")}function YX(X,Y){return P2.createHmac("sha256",X).update(Y).digest()}function LE(X){return P2.createHash("sha256").update(X).digest()}function AE(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 iZ(X,Y){if(Y=typeof Y==="function"?Y():Y,!Y)return{cancel:w8,start:w8};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 y$=()=>{};function rZ(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((R)=>R.forEach(({onsubscribe:v})=>v()))},no_subscribe:!0}),J=Q.end,z=Q.close;return Q.end=async()=>{return H=!0,$&&await new Promise((R)=>($.once("close",R),$.end())),J()},Q.close=async()=>{return $&&await new Promise((R)=>($.once("close",R),$.end())),z()},F;async function F(R,v,j=y$,P=y$){if(R=wE(R),!W)W=D(Q,_,Y.publications);let h={fn:v,onsubscribe:j},i=Z.has(R)?Z.get(R).add(h):Z.set(R,new Set([h])).get(R),g=()=>{i.delete(h),i.size===0&&Z.delete(R)};return W.then((p)=>{return O(p),j(),$&&$.on("error",P),{unsubscribe:g,state:G,sql:Q}})}function O(R){$=R.stream,G.pid=R.state.pid,G.secret=R.state.secret}async function D(R,v,j){if(!j)throw Error("Missing publication names");let P=await R.unsafe(`CREATE_REPLICATION_SLOT ${v} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[h]=P,i=await R.unsafe(`START_REPLICATION SLOT ${v} LOGICAL ${h.consistent_point} (proto_version '1', publication_names '${j}')`).writable(),g={lsn:Buffer.concat(h.consistent_point.split("/").map((K)=>Buffer.from(("00000000"+K).slice(-8),"hex")))};return i.on("data",m),i.on("error",p),i.on("close",R.close),{stream:i,state:P.state};function p(K){console.error("Unexpected error during logical streaming - reconnecting",K)}function m(K){if(K[0]===119)RE(K.subarray(25),g,R.options.parsers,_0,Y.transform);else if(K[0]===107&&K[17])g.lsn=K.subarray(1,9),u0()}function _0(K,J0){let o=J0.relation.schema+"."+J0.relation.table;w("*",K,J0),w("*:"+o,K,J0),J0.relation.keys.length&&w("*:"+o+"="+J0.relation.keys.map((X0)=>K[X0.name]),K,J0),w(J0.command,K,J0),w(J0.command+":"+o,K,J0),J0.relation.keys.length&&w(J0.command+":"+o+"="+J0.relation.keys.map((X0)=>K[X0.name]),K,J0)}function u0(){let K=Buffer.alloc(34);K[0]=114,K.fill(g.lsn,1),K.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),i.write(K)}}function w(R,v,j){Z.has(R)&&Z.get(R).forEach(({fn:P})=>P(v,j,R))}}function ME(X){return new Date(Date.UTC(2000,0,1)+Number(X/BigInt(1000)))}function RE(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=ME($.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 wE(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 g$ from"stream";function sZ(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
79
  select
79
80
  lo_lseek64(${H}, location, 0) as position,
80
81
  seek.size
@@ -84,10 +85,10 @@ params: ${Y}`);if(this.query=X,this.params=Y,this.cause=Z,Error.captureStackTrac
84
85
  tell.location
85
86
  from (select lo_tell64($1) as location) tell
86
87
  ) seek
87
- `};return _(Q),new Promise(async(F)=>$=F);async function J({highWaterMark:F=16384,start:O=0,end:D=1/0}={}){let A=D-O;return O&&await Q.seek(O),new v$.Readable({highWaterMark:F,async read(R){let v=R>A?R-A:R;A-=R;let[{data:j}]=await Q.read(v);if(this.push(j),j.length<R)this.push(null)}})}async function z({highWaterMark:F=16384,start:O=0}={}){return O&&await Q.seek(O),new v$.Writable({highWaterMark:F,write(D,A,R){Q.write(D).then(()=>R(),R)}})}}).catch(G)})}Object.assign(XX,{PostgresError:A8,toPascal:g4,pascal:gZ,toCamel:y4,camel:yZ,toKebab:p4,kebab:pZ,fromPascal:C2,fromCamel:T2,fromKebab:q2,BigInt:{to:20,from:[20],parse:(X)=>BigInt(X),serialize:(X)=>X.toString()}});var w8=XX;function XX(X,Y){let Z=VE(X,Y),_=Z.no_subscribe||lZ(XX,{...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},A=[...Array(Z.max)].map(()=>cZ(Z,D,{onopen:q1,onend:E1,onclose:c4})),R=v(_0);return Object.assign(R,{get parameters(){return Z.parameters},largeObject:oZ.bind(null,R),subscribe:_,CLOSE:M8,END:M8,PostgresError:A8,options:Z,reserve:h,listen:j,begin:i,close:o,end:J0}),R;function v(I){return I.debug=Z.debug,Object.entries(Z.types).reduce((n,[$0,C0])=>{return n[$0]=(w0)=>new n1(w0,C0.to),n},u),Object.assign(W0,{types:u,typed:u,unsafe:R0,notify:P,array:m,json:y,file:P0}),W0;function u(n,$0){return new n1(n,$0)}function W0(n,...$0){return n&&Array.isArray(n.raw)?new C1(n,$0,I,K):typeof n==="string"&&!$0.length?new j2(Z.transform.column.to?Z.transform.column.to(n):n):new n6(n,$0)}function R0(n,$0=[],C0={}){return arguments.length===2&&!Array.isArray($0)&&(C0=$0,$0=[]),new C1([n],$0,I,K,{prepare:!1,...C0,simple:"simple"in C0?C0.simple:$0.length===0})}function P0(n,$0=[],C0={}){return arguments.length===2&&!Array.isArray($0)&&(C0=$0,$0=[]),new C1([],$0,(D0)=>{OE.readFile(n,"utf8",(d0,U0)=>{if(d0)return D0.reject(d0);D0.strings=[U0],I(D0)})},K,{...C0,simple:"simple"in C0?C0.simple:$0.length===0})}}async function j(I,u,W0){let R0={fn:u,onlisten:W0},P0=j.sql||(j.sql=XX({...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:w0}}n[I]={result:P0`listen ${P0.unsafe('"'+I.replace(/"/g,'""')+'"')}`,listeners:[R0]};let C0=await n[I].result;return R0.onlisten&&R0.onlisten(),{state:C0.state,unlisten:w0};async function w0(){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 R`select pg_notify(${I}, ${""+u})`}async function h(){let I=M1(),u=z.length?z.shift():await new Promise((P0,n)=>{let $0={reserve:P0,reject:n};W.push($0),Q.length&&g0(Q.shift(),$0)});p(u,H),u.reserved=()=>I.length?u.execute(I.shift()):p(u,H),u.reserved.release=!0;let W0=v(R0);return W0.release=()=>{u.reserved=null,q1(u)},W0;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 W0=M1(),R0=0,P0,n=null;try{return await R.unsafe("begin "+I.replace(/[^a-z ]/ig,""),[],{onexecute:C0}).execute(),await Promise.race([$0(P0,u),new Promise((w0,D0)=>P0.onclose=D0)])}catch(w0){throw w0}async function $0(w0,D0,d0){let U0=v(v0);U0.savepoint=z4,U0.prepare=(L0)=>n=L0.replace(/[^a-z0-9$-_. ]/gi);let j1,p0;d0&&await U0`savepoint ${U0(d0)}`;try{if(p0=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 p0;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),$0(w0,S1,"s"+R0+++(L0?"_"+L0:""))}function v0(L0){L0.catch((S1)=>j1||(j1=S1)),w0.queue===O?W0.push(L0):w0.execute(L0)||p(w0,O)}}function C0(w0){P0=w0,p(w0,H),w0.reserved=()=>W0.length?w0.execute(W0.shift()):p(w0,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?o6(I)||25:0),Z.shared.typeArrayMap)}function _0(I){if(G)return I.reject(S0.connection("CONNECTION_ENDED",Z,Z));if(z.length)return u0(z.shift(),I);if(Q.length)return g0(Q.shift(),I);F.length?u0(F.shift(),I):W.push(I)}function u0(I,u){return I.execute(u)?p(I,F):p(I,O)}function K(I){return new Promise((u,W0)=>{I.state?I.active?cZ(Z).cancel(I.state,u,W0):I.cancelled={resolve:u,reject:W0}:(W.remove(I),I.cancelled=!0,I.reject(S0.generic("57014","canceling statement due to user request")),u())})}async function J0({timeout:I=null}={}){if(G)return G;await 1;let u;return G=Promise.race([new Promise((W0)=>I!==null&&(u=setTimeout(X0,I*1000,W0))),Promise.all(A.map((W0)=>W0.end()).concat(j.sql?j.sql.end({timeout:0}):[],_.sql?_.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(u))}async function o(){await Promise.all(A.map((I)=>I.end()))}async function X0(I){await Promise.all(A.map((u)=>u.terminate()));while(W.length)W.shift().reject(S0.connection("CONNECTION_DESTROYED",Z));I()}function g0(I,u){return p(I,$),I.connect(u),I}function E1(I){p(I,J)}function q1(I){if(W.length===0)return p(I,z);let u=Math.ceil(W.length/($.length+1)),W0=!0;while(W0&&W.length&&u-- >0){let R0=W.shift();if(R0.reserve)return R0.reserve(I);W0=I.execute(R0)}W0?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&&g0(I,W.shift())}}function VE(X,Y){if(X&&X.shared)return X;let Z=process.env,_=(!X||typeof X==="string"?Y:X)||{},{url:G,multihost:W}=RE(X),$=[...G.searchParams].reduce((O,[D,A])=>(O[D]=A,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||wE();_.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:ME,max_pipeline:100,backoff:LE,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,A])=>{let R=D in _?_[D]:(D in $)?$[D]==="disable"||$[D]==="false"?!1:$[D]:Z["PG"+D.toUpperCase()]||A;return O[D]=typeof R==="string"&&z.includes(D)?+R:R,O},{}),connection:{application_name:Z.PGAPPNAME||"postgres.js",..._.connection,...Object.entries($).reduce((O,[D,A])=>((D in F)||(O[D]=A),O),{})},types:_.types||{},target_session_attrs:DE(_,G,Z),onnotice:_.onnotice,onnotify:_.onnotify,onclose:_.onclose,onparameter:_.onparameter,socket:_.socket,transform:AE(_.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...w$(_.types)}}function DE(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 LE(X){return(0.5+Math.random()/2)*Math.min(3**X/100,20)}function ME(){return 60*(30+Math.random()*30)}function AE(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 RE(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 wE(){try{return EE.userInfo().username}catch(X){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class K0{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,T0)?X._.selectedFields:M(X,z1)?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 M2(this.config.alias,this.config.replaceOriginalName??!1))));return _}if(typeof _!=="object"||_===null)return _;return new Proxy(_,new K0(this.config))}}class x${constructor(X,Y){this.unique=X,this.name=Y}static[E]="PgIndexBuilderOn";on(...X){return new YX(X.map((Y)=>{if(M(Y,S))return Y;Y=Y;let Z=new O2(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 YX(X.map((Y)=>{if(M(Y,S))return Y;Y=Y;let Z=new O2(Y.name,!!Y.keyAsName,Y.columnType,Y.indexConfig);return Y.indexConfig=Y.defaultConfig,Z}),this.unique,!0,this.name)}using(X,...Y){return new YX(Y.map((Z)=>{if(M(Z,S))return Z;Z=Z;let _=new O2(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=JSON.parse(JSON.stringify(Z.defaultConfig)),_}),this.unique,!0,this.name,X)}}class YX{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 f$(this.config,X)}}class f${static[E]="PgIndex";config;constructor(X,Y){this.config={...X,table:Y}}}function iZ(X){return new x$(!0,X)}function NE(X){return(X.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((Z)=>Z.toLowerCase()).join("_")}function IE(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 KE(X){return X}class nZ{static[E]="CasingCache";cache={};cachedTables={};convert;constructor(X){this.convert=X==="snake_case"?NE:X==="camelCase"?IE:KE}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 P2 extends z1{static[E]="PgViewBase"}class u4{static[E]="PgDialect";casing;constructor(X){this.casing=new nZ(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
+ `};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 g$.Readable({highWaterMark:F,async read(R){let v=R>w?R-w:R;w-=R;let[{data:j}]=await Q.read(v);if(this.push(j),j.length<R)this.push(null)}})}async function z({highWaterMark:F=16384,start:O=0}={}){return O&&await Q.seek(O),new g$.Writable({highWaterMark:F,write(D,w,R){Q.write(D).then(()=>R(),R)}})}}).catch(G)})}Object.assign(_X,{PostgresError:R8,toPascal:p4,pascal:dZ,toCamel:g4,camel:uZ,toKebab:m4,kebab:cZ,fromPascal:q2,fromCamel:C2,fromKebab:j2,BigInt:{to:20,from:[20],parse:(X)=>BigInt(X),serialize:(X)=>X.toString()}});var N8=_X;function _X(X,Y){let Z=KE(X,Y),_=Z.no_subscribe||rZ(_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(()=>nZ(Z,D,{onopen:j1,onend:V1,onclose:l4})),R=v(_0);return Object.assign(R,{get parameters(){return Z.parameters},largeObject:sZ.bind(null,R),subscribe:_,CLOSE:M8,END:M8,PostgresError:R8,options:Z,reserve:h,listen:j,begin:i,close:o,end:J0}),R;function v(I){return I.debug=Z.debug,Object.entries(Z.types).reduce((n,[$0,C0])=>{return n[$0]=(w0)=>new s1(w0,C0.to),n},u),Object.assign(W0,{types:u,typed:u,unsafe:R0,notify:P,array:m,json:p,file:P0}),W0;function u(n,$0){return new s1(n,$0)}function W0(n,...$0){return n&&Array.isArray(n.raw)?new q1(n,$0,I,K):typeof n==="string"&&!$0.length?new S2(Z.transform.column.to?Z.transform.column.to(n):n):new t6(n,$0)}function R0(n,$0=[],C0={}){return arguments.length===2&&!Array.isArray($0)&&(C0=$0,$0=[]),new q1([n],$0,I,K,{prepare:!1,...C0,simple:"simple"in C0?C0.simple:$0.length===0})}function P0(n,$0=[],C0={}){return arguments.length===2&&!Array.isArray($0)&&(C0=$0,$0=[]),new q1([],$0,(D0)=>{IE.readFile(n,"utf8",(d0,U0)=>{if(d0)return D0.reject(d0);D0.strings=[U0],I(D0)})},K,{...C0,simple:"simple"in C0?C0.simple:$0.length===0})}}async function j(I,u,W0){let R0={fn:u,onlisten:W0},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:w0}}n[I]={result:P0`listen ${P0.unsafe('"'+I.replace(/"/g,'""')+'"')}`,listeners:[R0]};let C0=await n[I].result;return R0.onlisten&&R0.onlisten(),{state:C0.state,unlisten:w0};async function w0(){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 R`select pg_notify(${I}, ${""+u})`}async function h(){let I=M1(),u=z.length?z.shift():await new Promise((P0,n)=>{let $0={reserve:P0,reject:n};W.push($0),Q.length&&g0(Q.shift(),$0)});g(u,H),u.reserved=()=>I.length?u.execute(I.shift()):g(u,H),u.reserved.release=!0;let W0=v(R0);return W0.release=()=>{u.reserved=null,j1(u)},W0;function R0(P0){u.queue===O?I.push(P0):u.execute(P0)||g(u,O)}}async function i(I,u){!u&&(u=I,I="");let W0=M1(),R0=0,P0,n=null;try{return await R.unsafe("begin "+I.replace(/[^a-z ]/ig,""),[],{onexecute:C0}).execute(),await Promise.race([$0(P0,u),new Promise((w0,D0)=>P0.onclose=D0)])}catch(w0){throw w0}async function $0(w0,D0,d0){let U0=v(v0);U0.savepoint=F4,U0.prepare=(L0)=>n=L0.replace(/[^a-z0-9$-_. ]/gi);let S1,p0;d0&&await U0`savepoint ${U0(d0)}`;try{if(p0=await new Promise((L0,P1)=>{let d1=D0(U0);Promise.resolve(Array.isArray(d1)?Promise.all(d1):d1).then(L0,P1)}),S1)throw S1}catch(L0){throw await(d0?U0`rollback to ${U0(d0)}`:U0`rollback`),L0 instanceof R8&&L0.code==="25P02"&&S1||L0}if(!d0)n?await U0`prepare transaction '${U0.unsafe(n)}'`:await U0`commit`;return p0;function F4(L0,P1){if(L0&&Array.isArray(L0.raw))return F4((d1)=>d1.apply(d1,arguments));return arguments.length===1&&(P1=L0,L0=null),$0(w0,P1,"s"+R0+++(L0?"_"+L0:""))}function v0(L0){L0.catch((P1)=>S1||(S1=P1)),w0.queue===O?W0.push(L0):w0.execute(L0)||g(w0,O)}}function C0(w0){P0=w0,g(w0,H),w0.reserved=()=>W0.length?w0.execute(W0.shift()):g(w0,H)}}function g(I,u){return I.queue.remove(I),u.push(I),I.queue=u,u===z?I.idleTimer.start():I.idleTimer.cancel(),I}function p(I){return new s1(I,3802)}function m(I,u){if(!Array.isArray(I))return m(Array.from(arguments));return new s1(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 u0(z.shift(),I);if(Q.length)return g0(Q.shift(),I);F.length?u0(F.shift(),I):W.push(I)}function u0(I,u){return I.execute(u)?g(I,F):g(I,O)}function K(I){return new Promise((u,W0)=>{I.state?I.active?nZ(Z).cancel(I.state,u,W0):I.cancelled={resolve:u,reject:W0}:(W.remove(I),I.cancelled=!0,I.reject(S0.generic("57014","canceling statement due to user request")),u())})}async function J0({timeout:I=null}={}){if(G)return G;await 1;let u;return G=Promise.race([new Promise((W0)=>I!==null&&(u=setTimeout(X0,I*1000,W0))),Promise.all(w.map((W0)=>W0.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 g0(I,u){return g(I,$),I.connect(u),I}function V1(I){g(I,J)}function j1(I){if(W.length===0)return g(I,z);let u=Math.ceil(W.length/($.length+1)),W0=!0;while(W0&&W.length&&u-- >0){let R0=W.shift();if(R0.reserve)return R0.reserve(I);W0=I.execute(R0)}W0?g(I,F):g(I,O)}function l4(I,u){g(I,Q),I.reserved=null,I.onclose&&(I.onclose(u),I.onclose=null),Z.onclose&&Z.onclose(I.id),W.length&&g0(I,W.shift())}}function KE(X,Y){if(X&&X.shared)return X;let Z=process.env,_=(!X||typeof X==="string"?Y:X)||{},{url:G,multihost:W}=jE(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||SE();_.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:CE,max_pipeline:100,backoff:TE,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 R=D in _?_[D]:(D in $)?$[D]==="disable"||$[D]==="false"?!1:$[D]:Z["PG"+D.toUpperCase()]||w;return O[D]=typeof R==="string"&&z.includes(D)?+R:R,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:BE(_,G,Z),onnotice:_.onnotice,onnotify:_.onnotify,onclose:_.onclose,onparameter:_.onparameter,socket:_.socket,transform:qE(_.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...q$(_.types)}}function BE(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 TE(X){return(0.5+Math.random()/2)*Math.min(3**X/100,20)}function CE(){return 60*(30+Math.random()*30)}function qE(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 jE(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 SE(){try{return NE.userInfo().username}catch(X){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class K0{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 _=(A(X,T0)?X._.selectedFields:A(X,U1)?X[V0].selectedFields:X)[Y];if(A(_,S.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!_.isSelectionField)return _.sql;let G=_.clone();return G.isSelectionField=!0,G}if(A(_,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(A(_,z0)){if(this.config.alias)return new Proxy(_,new A8(new Proxy(_.table,new M2(this.config.alias,this.config.replaceOriginalName??!1))));return _}if(typeof _!=="object"||_===null)return _;return new Proxy(_,new K0(this.config))}}class p${constructor(X,Y){this.unique=X,this.name=Y}static[E]="PgIndexBuilderOn";on(...X){return new GX(X.map((Y)=>{if(A(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(A(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(A(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 m$(this.config,X)}}class m${static[E]="PgIndex";config;constructor(X,Y){this.config={...X,table:Y}}}function tZ(X){return new p$(!0,X)}function PE(X){return(X.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((Z)=>Z.toLowerCase()).join("_")}function vE(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 xE(X){return X}class aZ{static[E]="CasingCache";cache={};cachedTables={};convert;constructor(X){this.convert=X==="snake_case"?PE:X==="camelCase"?vE:xE}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 U1{static[E]="PgViewBase"}class d4{static[E]="PgDialect";casing;constructor(X){this.casing=new aZ(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
89
  CREATE TABLE IF NOT EXISTS ${V.identifier(G)}.${V.identifier(_)} (
89
90
  id SERIAL PRIMARY KEY,
90
91
  hash text NOT NULL,
91
92
  created_at bigint
92
93
  )
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),A=W&&V.join([V.raw(" from "),this.buildFromTable(W)]),R=this.buildJoins($),v=_?V` returning ${this.buildSelection(_,{isSingleTable:!W})}`:void 0,j=Z?V` where ${Z}`:void 0;return V`${H}update ${O} set ${D}${A}${R}${j}${v}`}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,z1)){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 A=Z??B1(Y);for(let X0 of A)if(M(X0.field,z0)&&y0(X0.field.table)!==(M(W,T0)?W._.alias:M(W,P2)?W[V0].name:M(W,S)?void 0:y0(W))&&!((g0)=>$?.some(({alias:E1})=>E1===(g0[T.Symbol.IsAlias]?y0(g0):g0[T.Symbol.BaseName])))(X0.field.table)){let g0=y0(X0.field.table);throw Error(`Your "${X0.path.join("->")}" field references a column "${g0}"."${X0.field.name}", but the table "${g0}" is not part of the query! Did you forget to join it?`)}let R=!$||$.length===0,v=this.buildWithCTE(X),j;if(O)j=O===!0?V` distinct`:V` distinct on (${V.join(O.on,V`, `)})`;let P=this.buildSelection(A,{isSingleTable:R}),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 u0=typeof J==="object"||typeof J==="number"&&J>=0?V` limit ${J}`:void 0,K=z?V` offset ${z}`:void 0,J0=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`);J0.append(X0)}let o=V`${v}select${j} ${P} from ${h}${i}${p}${_0}${y}${m}${u0}${K}${J0}`;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 A of W)if(M(A,B))D.push(V.identifier(A.name));else if(M(A,S)){for(let R=0;R<A.queryChunks.length;R++){let v=A.queryChunks[R];if(M(v,B))A.queryChunks[R]=V.identifier(v.name)}D.push(V`${A}`)}else D.push(V`${A}`);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(([v,j])=>!j.shouldDisableInsert()),z=J.map(([,v])=>V.identifier(this.casing.getColumnCasing(v)));if(W){let v=Y;if(M(v,S))H.push(v);else H.push(v.getSQL())}else{let v=Y;H.push(V.raw("values "));for(let[j,P]of v.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<v.length-1)H.push(V`, `)}}let F=this.buildWithCTE(G),O=V.join(H),D=_?V` returning ${this.buildSelection(_,{isSingleTable:!0})}`:void 0,A=Z?V` on conflict ${Z}`:void 0,R=$===!0?V`overriding system value `:void 0;return V`${F}insert into ${X} ${z} ${R}${O}${A}${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,k6)||M(X,h6))return"json";else if(M(X,b6))return"decimal";else if(M(X,y6))return"time";else if(M(X,g6)||M(X,p6))return"timestamp";else if(M(X,x6)||M(X,f6))return"date";else if(M(X,m6))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,A=[];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 v=Object.fromEntries(Object.entries(G.columns).map(([y,m])=>[y,i1(m,$)]));if(W.where){let y=typeof W.where==="function"?W.where(v,J$()):W.where;D=y&&A2(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(v,{sql:V}):W.extras;for(let[y,m]of Object.entries(i))j.push({tsKey:y,value:NZ(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(v,Q$()):W.orderBy??[];if(!Array.isArray(p))p=[p];O=p.map((y)=>{if(M(y,z0))return i1(y,$);return A2(y,$)}),z=W.limit,F=W.offset;for(let{tsKey:y,queryConfig:m,relation:_0}of h){let u0=F$(Y,Z,_0),K=b4(_0.referencedTable),J0=Z[K],o=`${$}_${y}`,X0=K2(...u0.fields.map((q1,c4)=>u6(i1(u0.references[c4],o),i1(q1,$)))),g0=this.buildRelationalQueryWithoutPK({fullSchema:X,schema:Y,tableNamesMap:Z,table:X[J0],tableConfig:Y[J0],queryConfig:M(_0,K4)?m===!0?{limit:1}:{...m,limit:1}:m,tableAlias:o,joinOn:X0,nestedQueryRelation:_0}),E1=V`${V.identifier(o)}.${V.identifier("data")}`.as(y);A.push({on:V`true`,table:new T0(g0.sql,{},o),alias:o,joinType:"left",lateral:!0}),J.push({dbKey:y,tsKey:y,field:E1,relationTableTsKey:J0,isJson:!0,selection:g0.selection})}}if(J.length===0)throw new P6({message:`No fields selected for table "${G.tsName}" ("${$}")`});let R;if(D=K2(Q,D),H){let v=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,B2))v=V`coalesce(json_agg(${v}${O.length>0?V` order by ${V.join(O,V`, `)}`:void 0}), '[]'::json)`;let j=[{dbKey:"data",tsKey:"data",field:v.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:J}];if(z!==void 0||F!==void 0||O.length>0)R=this.buildSelectQuery({table:S6(_,$),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 R=S6(_,$);R=this.buildSelectQuery({table:M(R,b0)?R:new T0(R,{},$),fields:{},fieldsFlat:j.map(({field:h})=>({path:[],field:M(h,z0)?i1(h,$):h})),joins:A,where:D,limit:z,offset:F,orderBy:O,setOperators:[]})}else R=this.buildSelectQuery({table:S6(_,$),fields:{},fieldsFlat:J.map(({field:v})=>({path:[],field:M(v,z0)?i1(v,$):v})),joins:A,where:D,limit:z,offset:F,orderBy:O,setOperators:[]});return{tableTsKey:G.tsName,sql:R,selection:J}}}class rZ{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,T0))_=Object.fromEntries(Object.keys(Z._.selectedFields).map((G)=>[G,Z[G]]));else if(M(Z,P2))_=Z[V0].selectedFields;else if(M(Z,S))_={};else _=p7(Z);return new sZ({table:Z,fields:_,isPartialSelect:Y,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class h$ extends rZ{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,T0)?Z._.selectedFields:M(Z,z1)?Z[V0].selectedFields:Z[T.Symbol.Columns];this.config.fields[W]=$}}if(typeof _==="function")_=_(new Proxy(this.config.fields,new K0({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(BE()):Z;if(!R2(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 K0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=X,this}having(X){if(typeof X==="function")X=X(new Proxy(this.config.fields,new K0({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 K0({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 K0({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 T0(this.getSQL(),this.config.fields,X,!1,[...new Set(Y)]),new K0({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new K0({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 sZ extends h${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)})}}g7(sZ,[Y1]);function N8(X,Y){return(Z,_,...G)=>{let W=[_,...G].map(($)=>({type:X,isAll:Y,rightSelect:$}));for(let $ of W)if(!R2(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 BE=()=>({union:TE,unionAll:CE,intersect:qE,intersectAll:jE,except:SE,exceptAll:PE}),TE=N8("union",!1),CE=N8("union",!0),qE=N8("intersect",!1),jE=N8("intersect",!0),SE=N8("except",!1),PE=N8("except",!0);class v2{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 D2(G.getSQL(),Y??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),X,!0),new K0({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,T0))return X._.usedTables??[];if(M(X,S))return X.usedTables??[];return[]}class ZX 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 K0({alias:y0(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 tZ(this.table,Y,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(X){let Y=typeof X==="function"?X(new v2):X;if(!M(Y,S)&&!R2(this.table[q6],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 tZ(this.table,Y,this.session,this.dialect,this.withList,!0)}}class tZ 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,v6(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 K0({alias:y0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class aZ 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 GX{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 k$(this.table,v6(this.table,X),this.session,this.dialect,this.withList).setToken(this.authToken)}}class k$ 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,T0))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 K0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new K0({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 K0({alias:y0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class x2 extends S{constructor(X){super(x2.buildEmbeddedCount(X.source,X.filters).queryChunks);this.params=X,this.mapWith(Number),this.session=X.session,this.sql=x2.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 X5{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 eZ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?X:{},"many")}findFirst(X){return new eZ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?{...X,limit:1}:{limit:1},"first")}}class eZ 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(($)=>d6(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 Y5 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 f2{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 X5(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 v2(Z.dialect));return new Proxy(new D2(G.getSQL(),Y??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),X,!0),new K0({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(X,Y){return new x2({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 GX(Q,Y.session,Y.dialect,X)}function $(Q){return new _X(Q,Y.session,Y.dialect,X)}function H(Q){return new ZX(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 GX(X,this.session,this.dialect)}insert(X){return new _X(X,this.session,this.dialect)}delete(X){return new ZX(X,this.session,this.dialect)}refreshMaterializedView(X){return new aZ(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 Y5(()=>_.execute(void 0,this.authToken),Y,Z,(G)=>_.mapResult(G,!0))}transaction(X,Y){return this.session.transaction(X,Y)}}class b${static[E]="Cache"}class h2 extends b${strategy(){return"all"}static[E]="NoopCache";async get(X){return}async put(X,Y,Z,_){}async onMutate(X){}}async function Z5(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 _5{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,h2)||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 Z5(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 Z5(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 G5{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 W5 extends f2{constructor(X,Y,Z,_=0){super(X,Y,Z);this.schema=Z,this.nestedIndex=_}static[E]="PgTransaction";rollback(){throw new IZ}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 y$ extends _5{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=wZ(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)=>y7(_,J,$))})})}all(X={}){return F0.startActiveSpan("drizzle.execute",async(Y)=>{let Z=wZ(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 k2 extends G5{constructor(X,Y,Z,_={}){super(Y);this.client=X,this.schema=Z,this.options=_,this.logger=_.logger??new BZ,this.cache=_.cache??new h2}static[E]="PostgresJsSession";logger;cache;prepareQuery(X,Y,Z,_,G,W,$){return new y$(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 k2(Z,this.dialect,this.schema,this.options),G=new $5(this.dialect,_,this.schema);if(Y)await G.setTransaction(Y);return X(G)})}}class $5 extends W5{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 k2(Y,this.dialect,this.schema,this.session.options),_=new $5(this.dialect,Z,this.schema);return X(_)})}}class g$ extends f2{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 KZ;else if(Y.logger!==!1)G=Y.logger;let W;if(Y.schema){let Q=z$(Y.schema,U$);W={fullSchema:Y.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let $=new k2(X,_,W,{logger:G,cache:Y.cache}),H=new g$(_,$,W);if(H.$client=X,H.$cache=Y.cache,H.$cache)H.$cache.invalidate=Y.cache?.onMutate;return H}function WX(...X){if(typeof X[0]==="string"){let Y=w8(X[0]);return I8(Y,X[1])}if(m7(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})(WX||(WX={}));var J5={};cH(J5,{users:()=>d4,untrackedUserColumnNames:()=>vE,twoFactorMethod:()=>c$,trackedUserColumnName:()=>xE,trackableUserColumnNames:()=>u$,signInHistory:()=>hE,role:()=>m$,players:()=>H5,passwordResetAttempts:()=>kE,games:()=>HX,banishedIps:()=>bE,accountActions:()=>fE,accountAction:()=>d$});function T4(){return n0({length:24}).$type()}function p$(X){return V`lower(${X})`}var $X=V`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,m$=V2("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($X),createdIp:n0({length:45}).notNull(),isActive:w2().notNull().default(!1),verifiedAtIso:T4(),userRole:m$().default("user")},(X)=>[iZ("usernameUniqueIndex").on(p$(X.username)),iZ("emailVerifiedUniqueIndex").on(p$(X.emailVerified))]),vE=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],u$=["username","emailOffered","emailVerified","password","userRole"],xE=V2("trackedUserColumnName",u$),d$=V2("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),fE=I4("accountActions",{userId:T1().references(()=>d4.id).primaryKey(),action:d$().notNull(),code:n0({length:254}).notNull(),wrongCodeCount:N2().notNull().default(0),expiresAtIso:T4().notNull()}),HX=I4("games",{id:T1().primaryKey().defaultRandom()}),H5=I4("players",{userId:T1().notNull().references(()=>d4.id,{onDelete:"cascade"}),gameId:T1().notNull().references(()=>HX.id,{onDelete:"cascade"}),score:N2().notNull()},(X)=>[yW({name:"players_userId_gameId_pk",columns:[X.userId,X.gameId]})]),hE=I4("signInHistory",{id:T1().primaryKey().defaultRandom(),userId:T1().references(()=>d4.id,{onDelete:"cascade"}),signInTimeIso:T4().notNull().default($X),ipAddress:n0({length:45}).notNull(),userAgent:n0({length:1024}),successful:w2().notNull().default(!1)}),c$=V2("twoFactorMethod",["email","phone"]),kE=I4("passwordResetAttempts",{id:T1().primaryKey().defaultRandom(),userId:T1().notNull().references(()=>d4.id,{onDelete:"cascade"}),requestedIp:n0({length:45}).notNull(),requestedAtIso:T4().notNull().default($X),succeededIp:n0({length:45}),succeededAtIso:T4(),verificationMethod:c$().notNull()}),bE=I4("banishedIps",{ip:n0({length:45}).primaryKey(),reason:n0({length:2048}).notNull(),banishedAtIso:T4().notNull().default($X),banishedUntilIso:T4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class Q5{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(yE.resolve(__dirname,"notify_update.sql"));let X=[y0(d4),y0(HX),y0(H5)];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=WX(this.sql,{schema:J5,logger:X})}observe(X,Y){if(!this.observers.has(X))this.observers.set(X,new Y0);this.observers.get(X).subscribe("SINGLETON",Y)}}var JX={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 gE(X){return Number.parseInt(X,10)}var pE=J1(JX),mE=pE.keyof().pipe((X)=>gE(X)),l$=J1([mE,"string"]);var F5=new O7(process),{logger:U1}=F5;Object.assign(console,U1,{log:U1.info});U1.info("ready");var z5=i$(import.meta.dir,"..","app"),Uf=new Q5({logQuery(X,Y){U1.info("\uD83D\uDCDD query",X,Y)}});lE({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...B6??void 0,async fetch(X){try{let Y=new Date,Z=new URL(X.url);if(U1.info(X.method,Z.pathname),Z.pathname==="/")return new Response(Bun.file(i$(z5,"index.html")));if(Z.pathname==="/index.html")return Response.redirect("/");let _=dE(z5,Z.pathname),G=cE(_);if(!G.startsWith(z5))throw[403,"Access Denied"];if(!await o$(G).exists())return Response.redirect("/");return new Response(o$(G))}catch(Y){let Z=l$(Y);if(Z instanceof J1.errors===!1){let[_,G]=Z,$=`${JX[_]}. ${G}`;return U1.info(`\u274C ${_}: ${$}`),new Response($,{status:_})}if(Y instanceof Error)U1.error(Y.message);else{let _=K6(Y);U1.error("frontend server threw",_)}return new Response(JX[500],{status:500})}}});function QX(){U1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{U1.info("\u2757 received SIGINT; exiting gracefully"),QX()});process.on("SIGTERM",()=>{U1.info("\u2757 received SIGTERM; exiting gracefully"),QX()});process.on("exit",()=>{U1.info("\u2757 received exit; exiting gracefully"),QX()});F5.on("timeToStop",()=>{U1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),QX()});var{version:oE}=await Bun.file(uE.resolve(import.meta.dir,"../package.json")).json();U1.info(`\uD83D\uDEEB frontend v${oE} running at http://localhost:${g1.FRONTEND_PORT}/`);F5.emit("alive");
94
+ `;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)]),R=this.buildJoins($),v=_?V` returning ${this.buildSelection(_,{isSingleTable:!W})}`:void 0,j=Z?V` where ${Z}`:void 0;return V`${H}update ${O} set ${D}${w}${R}${j}${v}`}buildSelection(X,{isSingleTable:Y=!1}={}){let Z=X.length,_=X.flatMap(({field:G},W)=>{let $=[];if(A(G,S.Aliased)&&G.isSelectionField)$.push(V.identifier(G.fieldAlias));else if(A(G,S.Aliased)||A(G,S)){let H=A(G,S.Aliased)?G.sql:G;if(Y)$.push(new S(H.queryChunks.map((Q)=>{if(A(Q,B))return V.identifier(this.casing.getColumnCasing(Q));return Q})));else $.push(H);if(A(G,S.Aliased))$.push(V` as ${V.identifier(G.fieldAlias)}`)}else if(A(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(A(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(A(G,U1)){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(A(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??T1(Y);for(let X0 of w)if(A(X0.field,z0)&&y0(X0.field.table)!==(A(W,T0)?W._.alias:A(W,v2)?W[V0].name:A(W,S)?void 0:y0(W))&&!((g0)=>$?.some(({alias:V1})=>V1===(g0[T.Symbol.IsAlias]?y0(g0):g0[T.Symbol.BaseName])))(X0.field.table)){let g0=y0(X0.field.table);throw Error(`Your "${X0.path.join("->")}" field references a column "${g0}"."${X0.field.name}", but the table "${g0}" is not part of the query! Did you forget to join it?`)}let R=!$||$.length===0,v=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:R}),h=this.buildFromTable(W),i=this.buildJoins($),g=_?V` where ${_}`:void 0,p=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 u0=typeof J==="object"||typeof J==="number"&&J>=0?V` limit ${J}`:void 0,K=z?V` offset ${z}`:void 0,J0=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`);J0.append(X0)}let o=V`${v}select${j} ${P} from ${h}${i}${g}${_0}${p}${m}${u0}${K}${J0}`;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(A(w,B))D.push(V.identifier(w.name));else if(A(w,S)){for(let R=0;R<w.queryChunks.length;R++){let v=w.queryChunks[R];if(A(v,B))w.queryChunks[R]=V.identifier(v.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(([v,j])=>!j.shouldDisableInsert()),z=J.map(([,v])=>V.identifier(this.casing.getColumnCasing(v)));if(W){let v=Y;if(A(v,S))H.push(v);else H.push(v.getSQL())}else{let v=Y;H.push(V.raw("values "));for(let[j,P]of v.entries()){let h=[];for(let[i,g]of J){let p=P[i];if(p===void 0||A(p,A1)&&p.value===void 0)if(g.defaultFn!==void 0){let m=g.defaultFn(),_0=A(m,S)?m:V.param(m,g);h.push(_0)}else if(!g.default&&g.onUpdateFn!==void 0){let m=g.onUpdateFn(),_0=A(m,S)?m:V.param(m,g);h.push(_0)}else h.push(V`default`);else h.push(p)}if(H.push(h),j<v.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,R=$===!0?V`overriding system value `:void 0;return V`${F}insert into ${X} ${z} ${R}${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(A(X,g6)||A(X,y6))return"json";else if(A(X,p6))return"decimal";else if(A(X,m6))return"time";else if(A(X,u6)||A(X,d6))return"timestamp";else if(A(X,k6)||A(X,b6))return"date";else if(A(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:r1(P,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let v=Object.fromEntries(Object.entries(G.columns).map(([p,m])=>[p,r1(m,$)]));if(W.where){let p=typeof W.where==="function"?W.where(v,V$()):W.where;D=p&&R2(p,$)}let j=[],P=[];if(W.columns){let p=!1;for(let[m,_0]of Object.entries(W.columns)){if(_0===void 0)continue;if(m in G.columns){if(!p&&_0===!0)p=!0;P.push(m)}}if(P.length>0)P=p?P.filter((m)=>W.columns?.[m]===!0):Object.keys(G.columns).filter((m)=>!P.includes(m))}else P=Object.keys(G.columns);for(let p of P){let m=G.columns[p];j.push({tsKey:p,value:m})}let h=[];if(W.with)h=Object.entries(W.with).filter((p)=>!!p[1]).map(([p,m])=>({tsKey:p,queryConfig:m,relation:G.relations[p]}));let i;if(W.extras){i=typeof W.extras==="function"?W.extras(v,{sql:V}):W.extras;for(let[p,m]of Object.entries(i))j.push({tsKey:p,value:TZ(m,$)})}for(let{tsKey:p,value:m}of j)J.push({dbKey:A(m,S.Aliased)?m.fieldAlias:G.columns[p].name,tsKey:p,field:A(m,z0)?r1(m,$):m,relationTableTsKey:void 0,isJson:!1,selection:[]});let g=typeof W.orderBy==="function"?W.orderBy(v,D$()):W.orderBy??[];if(!Array.isArray(g))g=[g];O=g.map((p)=>{if(A(p,z0))return r1(p,$);return R2(p,$)}),z=W.limit,F=W.offset;for(let{tsKey:p,queryConfig:m,relation:_0}of h){let u0=A$(Y,Z,_0),K=y4(_0.referencedTable),J0=Z[K],o=`${$}_${p}`,X0=B2(...u0.fields.map((j1,l4)=>l6(r1(u0.references[l4],o),r1(j1,$)))),g0=this.buildRelationalQueryWithoutPK({fullSchema:X,schema:Y,tableNamesMap:Z,table:X[J0],tableConfig:Y[J0],queryConfig:A(_0,K4)?m===!0?{limit:1}:{...m,limit:1}:m,tableAlias:o,joinOn:X0,nestedQueryRelation:_0}),V1=V`${V.identifier(o)}.${V.identifier("data")}`.as(p);w.push({on:V`true`,table:new T0(g0.sql,{},o),alias:o,joinType:"left",lateral:!0}),J.push({dbKey:p,tsKey:p,field:V1,relationTableTsKey:J0,isJson:!0,selection:g0.selection})}}if(J.length===0)throw new f6({message:`No fields selected for table "${G.tsName}" ("${$}")`});let R;if(D=B2(Q,D),H){let v=V`json_build_array(${V.join(J.map(({field:h,tsKey:i,isJson:g})=>g?V`${V.identifier(`${$}_${i}`)}.${V.identifier("data")}`:A(h,S.Aliased)?h.sql:h),V`, `)})`;if(A(H,T2))v=V`coalesce(json_agg(${v}${O.length>0?V` order by ${V.join(O,V`, `)}`:void 0}), '[]'::json)`;let j=[{dbKey:"data",tsKey:"data",field:v.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:J}];if(z!==void 0||F!==void 0||O.length>0)R=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 R=x6(_,$);R=this.buildSelectQuery({table:A(R,b0)?R:new T0(R,{},$),fields:{},fieldsFlat:j.map(({field:h})=>({path:[],field:A(h,z0)?r1(h,$):h})),joins:w,where:D,limit:z,offset:F,orderBy:O,setOperators:[]})}else R=this.buildSelectQuery({table:x6(_,$),fields:{},fieldsFlat:J.map(({field:v})=>({path:[],field:A(v,z0)?r1(v,$):v})),joins:w,where:D,limit:z,offset:F,orderBy:O,setOperators:[]});return{tableTsKey:G.tsName,sql:R,selection:J}}}class eZ{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(A(Z,T0))_=Object.fromEntries(Object.keys(Z._.selectedFields).map((G)=>[G,Z[G]]));else if(A(Z,v2))_=Z[V0].selectedFields;else if(A(Z,S))_={};else _=i7(Z);return new X5({table:Z,fields:_,isPartialSelect:Y,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class u$ extends eZ{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=Q4(X),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let H of u1(X))this.usedTables.add(H)}getUsedTables(){return[...this.usedTables]}createJoin(X,Y){return(Z,_)=>{let G=this.tableName,W=Q4(Z);for(let $ of u1(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"&&!A(Z,S)){let $=A(Z,T0)?Z._.selectedFields:A(Z,U1)?Z[V0].selectedFields:Z[T.Symbol.Columns];this.config.fields[W]=$}}if(typeof _==="function")_=_(new Proxy(this.config.fields,new K0({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(fE()):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 K0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=X,this}having(X){if(typeof X==="function")X=X(new Proxy(this.config.fields,new K0({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 K0({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 K0({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(...u1(this.config.table)),this.config.joins)for(let Z of this.config.joins)Y.push(...u1(Z.table));return new Proxy(new T0(this.getSQL(),this.config.fields,X,!1,[...new Set(Y)]),new K0({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new K0({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 X5 extends u${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=T1(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)})}}o7(X5,[Y1]);function I8(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 fE=()=>({union:hE,unionAll:kE,intersect:bE,intersectAll:yE,except:gE,exceptAll:pE}),hE=I8("union",!1),kE=I8("union",!0),bE=I8("intersect",!1),yE=I8("intersect",!0),gE=I8("except",!1),pE=I8("except",!0);class x2{static[E]="PgQueryBuilder";dialect;dialectConfig;constructor(X){this.dialect=A(X,d4)?X:void 0,this.dialectConfig=A(X,d4)?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 K0({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 d4(this.dialectConfig);return this.dialect}}function u1(X){if(A(X,b0))return[X[b4]?`${X[b4]}.${X[T.Symbol.BaseName]}`:X[T.Symbol.BaseName]];if(A(X,T0))return X._.usedTables??[];if(A(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=T1(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:u1(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 K0({alias:y0(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]=A($,S)?$:new A1($,G[W])}return _});return new Y5(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(!A(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 Y5(this.table,Y,this.session,this.dialect,this.withList,!0)}}class Y5 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=T1(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:u1(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 K0({alias:y0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class Z5 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 d$(this.table,h6(this.table,X),this.session,this.dialect,this.withList).setToken(this.authToken)}}class d$ extends Y1{constructor(X,Y,Z,_,G){super();this.session=Z,this.dialect=_,this.config={set:Y,table:X,withList:G,joins:[]},this.tableName=Q4(X),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[E]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(X){let Y=X,Z=Q4(Y);if(typeof Z==="string")this.joinsNotNullableMap[Z]=!0;return this.config.from=Y,this}getTableLikeFields(X){if(A(X,b0))return X[T.Symbol.Columns];else if(A(X,T0))return X._.selectedFields;return X[V0].selectedFields}createJoin(X){return(Y,Z)=>{let _=Q4(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&&!A(this.config.from,S)?this.getTableLikeFields(this.config.from):void 0;Z=Z(new Proxy(this.config.table[T.Symbol.Columns],new K0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new K0({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=Q4(this.config.from);if(typeof Y==="string"&&this.config.from&&!A(this.config.from,S)){let Z=this.getTableLikeFields(this.config.from);X[Y]=Z}for(let Z of this.config.joins){let _=Q4(Z.table);if(typeof _==="string"&&!A(Z.table,S)){let G=this.getTableLikeFields(Z.table);X[_]=G}}}}return this.config.returningFields=X,this.config.returning=T1(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:u1(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 K0({alias:y0(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 G5{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 _5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?X:{},"many")}findFirst(X){return new _5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?{...X,limit:1}:{limit:1},"first")}}class _5 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 W5 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 G5(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 K0({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 Z5(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 W5(()=>_.execute(void 0,this.authToken),Y,Z,(G)=>_.mapResult(G,!0))}transaction(X,Y){return this.session.transaction(X,Y)}}class c${static[E]="Cache"}class k2 extends c${strategy(){return"all"}static[E]="NoopCache";async get(X){return}async put(X,Y,Z,_){}async onMutate(X){}}async function $5(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 H5{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||A(this.cache,k2)||this.queryMetadata===void 0)try{return await Z()}catch(_){throw new J4(X,Y,_)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await Z()}catch(_){throw new J4(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 J4(X,Y,_)}if(!this.cacheConfig)try{return await Z()}catch(_){throw new J4(X,Y,_)}if(this.queryMetadata.type==="select"){let _=await this.cache.get(this.cacheConfig.tag??await $5(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 J4(X,Y,W)}return await this.cache.put(this.cacheConfig.tag??await $5(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 J4(X,Y,_)}}}class J5{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 Q5 extends h2{constructor(X,Y,Z,_=0){super(X,Y,Z);this.schema=Z,this.nestedIndex=_}static[E]="PgTransaction";rollback(){throw new CZ}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 l$ extends H5{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=BZ(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)=>l7(_,J,$))})})}all(X={}){return F0.startActiveSpan("drizzle.execute",async(Y)=>{let Z=BZ(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 J5{constructor(X,Y,Z,_={}){super(Y);this.client=X,this.schema=Z,this.options=_,this.logger=_.logger??new jZ,this.cache=_.cache??new k2}static[E]="PostgresJsSession";logger;cache;prepareQuery(X,Y,Z,_,G,W,$){return new l$(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 z5(this.dialect,_,this.schema);if(Y)await G.setTransaction(Y);return X(G)})}}class z5 extends Q5{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 z5(this.dialect,Z,this.schema);return X(_)})}}class o$ extends h2{static[E]="PostgresJsDatabase"}function K8(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 d4({casing:Y.casing}),G;if(Y.logger===!0)G=new qZ;else if(Y.logger!==!1)G=Y.logger;let W;if(Y.schema){let Q=L$(Y.schema,M$);W={fullSchema:Y.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let $=new b2(X,_,W,{logger:G,cache:Y.cache}),H=new o$(_,$,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=N8(X[0]);return K8(Y,X[1])}if(n7(X[0])){let{connection:Y,client:Z,..._}=X[0];if(Z)return K8(Z,_);if(typeof Y==="object"&&Y.url!==void 0){let{url:W,...$}=Y,H=N8(W,$);return K8(H,_)}let G=N8(Y);return K8(G,_)}return K8(X[0],X[1])}((X)=>{function Y(Z){return K8({options:{parsers:{},serializers:{}}},Z)}X.mock=Y})(JX||(JX={}));var U5={};tH(U5,{users:()=>c4,untrackedUserColumnNames:()=>mE,twoFactorMethod:()=>t$,trackedUserColumnName:()=>uE,trackableUserColumnNames:()=>r$,signInHistory:()=>cE,role:()=>n$,players:()=>F5,passwordResetAttempts:()=>lE,games:()=>zX,banishedIps:()=>oE,accountActions:()=>dE,accountAction:()=>s$});function T4(){return n0({length:24}).$type()}function i$(X){return V`lower(${X})`}var QX=V`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,n$=D2("role",["admin","user"]),c4=I4("users",{id:C1().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:n$().default("user")},(X)=>[tZ("usernameUniqueIndex").on(i$(X.username)),tZ("emailVerifiedUniqueIndex").on(i$(X.emailVerified))]),mE=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],r$=["username","emailOffered","emailVerified","password","userRole"],uE=D2("trackedUserColumnName",r$),s$=D2("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),dE=I4("accountActions",{userId:C1().references(()=>c4.id).primaryKey(),action:s$().notNull(),code:n0({length:254}).notNull(),wrongCodeCount:I2().notNull().default(0),expiresAtIso:T4().notNull()}),zX=I4("games",{id:C1().primaryKey().defaultRandom()}),F5=I4("players",{userId:C1().notNull().references(()=>c4.id,{onDelete:"cascade"}),gameId:C1().notNull().references(()=>zX.id,{onDelete:"cascade"}),score:I2().notNull()},(X)=>[lW({name:"players_userId_gameId_pk",columns:[X.userId,X.gameId]})]),cE=I4("signInHistory",{id:C1().primaryKey().defaultRandom(),userId:C1().references(()=>c4.id,{onDelete:"cascade"}),signInTimeIso:T4().notNull().default(QX),ipAddress:n0({length:45}).notNull(),userAgent:n0({length:1024}),successful:N2().notNull().default(!1)}),t$=D2("twoFactorMethod",["email","phone"]),lE=I4("passwordResetAttempts",{id:C1().primaryKey().defaultRandom(),userId:C1().notNull().references(()=>c4.id,{onDelete:"cascade"}),requestedIp:n0({length:45}).notNull(),requestedAtIso:T4().notNull().default(QX),succeededIp:n0({length:45}),succeededAtIso:T4(),verificationMethod:t$().notNull()}),oE=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 E5{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(iE.resolve(__dirname,"notify_update.sql"));let X=[y0(c4),y0(zX),y0(F5)];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:p1.POSTGRES_HOST,port:p1.POSTGRES_PORT,user:p1.POSTGRES_USER,password:p1.POSTGRES_PASSWORD,database:p1.POSTGRES_DATABASE}){this.options=Y,this.sql=N8(Y),this.drizzle=JX(this.sql,{schema:U5,logger:X})}observe(X,Y){if(!this.observers.has(X))this.observers.set(X,new Y0);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 nE(X){return Number.parseInt(X,10)}var rE=z1(FX),sE=rE.keyof().pipe((X)=>nE(X)),a$=z1([sE,"string"]);var V5=new w7(process),{logger:O1}=V5;Object.assign(console,O1,{log:O1.info});O1.info("ready");var O5=XH(import.meta.dir,"..","app"),vf=new E5({logQuery(X,Y){O1.info("\uD83D\uDCDD query",X,Y)}});XO({hostname:"0.0.0.0",port:p1.FRONTEND_PORT??3333,...q6??void 0,async fetch(X){try{let Y=new Date,Z=new URL(X.url);if(O1.info(X.method,Z.pathname),Z.pathname==="/")return new Response(Bun.file(XH(O5,"index.html")));if(Z.pathname==="/index.html")return Response.redirect("/");let _=aE(O5,Z.pathname),G=eE(_);if(!G.startsWith(O5))throw[403,"Access Denied"];if(!await e$(G).exists())return Response.redirect("/");return new Response(e$(G))}catch(Y){let Z=a$(Y);if(Z instanceof z1.errors===!1){let[_,G]=Z,$=`${FX[_]}. ${G}`;return O1.info(`\u274C ${_}: ${$}`),new Response($,{status:_})}if(Y instanceof Error)O1.error(Y.message);else{let _=C6(Y);O1.error("frontend server threw",_)}return new Response(FX[500],{status:500})}}});function UX(){O1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{O1.info("\u2757 received SIGINT; exiting gracefully"),UX()});process.on("SIGTERM",()=>{O1.info("\u2757 received SIGTERM; exiting gracefully"),UX()});process.on("exit",()=>{O1.info("\u2757 received exit; exiting gracefully"),UX()});V5.on("timeToStop",()=>{O1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),UX()});var{version:YO}=await Bun.file(tE.resolve(import.meta.dir,"../package.json")).json();O1.info(`\uD83D\uDEEB frontend v${YO} running at http://localhost:${p1.FRONTEND_PORT}/`);V5.emit("alive");