tempest.games 0.2.60 → 0.2.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,80 +1,80 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var mH=Object.create;var{getPrototypeOf:uH,defineProperty:DX,getOwnPropertyNames:dH}=Object;var cH=Object.prototype.hasOwnProperty;var nE=(X,Y,Z)=>{Z=X!=null?mH(uH(X)):{};let _=Y||!X||!X.__esModule?DX(Z,"default",{value:X,enumerable:!0}):Z;for(let G of dH(X))if(!cH.call(_,G))DX(_,G,{get:()=>X[G],enumerable:!0});return _};var rE=(X,Y)=>()=>(Y||X((Y={exports:{}}).exports,Y),Y.exports);var lH=(X,Y)=>{for(var Z in Y)DX(X,Z,{get:Y[Z],enumerable:!0,configurable:!0,set:(_)=>Y[Z]=()=>_})};var sE=(X,Y)=>()=>(X&&(Y=X(X=0)),Y);var tE=import.meta.require;import dE,{join as cE,normalize as lE,resolve as n$}from"path";var U4=(X)=>Array.isArray(X)?X:[X],w5=(X,Y)=>{let Z=[[],[]];for(let _ of X)if(Y(_))Z[0].push(_);else Z[1].push(_);return Z},p2=Array,r1=(X,Y)=>X.includes(Y),N5=(X,Y=0)=>[...Array(X)].map((Z,_)=>_+Y),t=(X,Y,Z)=>{if(X===void 0)return Y===void 0?[]:Array.isArray(Y)?Y:[Y];if(Z?.prepend)if(Array.isArray(Y))X.unshift(...Y);else X.unshift(Y);else if(Array.isArray(Y))X.push(...Y);else X.push(Y);return X},s1=(X,Y)=>{if(Y===void 0||Y===null)return X??[];if(X===void 0||X===null)return U4(Y);return X.concat(Y)},I5=(...X)=>X.reduce(s1,[]),c1=(X,Y,Z)=>{if(X===void 0)return Array.isArray(Y)?Y:[Y];let _=Z?.isEqual??((G,W)=>G===W);for(let G of U4(Y))if(!X.some((W)=>_(W,G)))X.push(G);return X},K5=(X,Y)=>X.reduce((Z,_)=>{let G=_[Y];return Z[G]=t(Z[G],_),Z},{}),t1=(X,Y,Z)=>X.length===Y.length&&X.every(Z?.isEqual?(_,G)=>Z.isEqual(_,Y[G]):(_,G)=>_===Y[G]);var _1=(X,Y)=>x0(X)===Y,x0=(X)=>{let Y=typeof X;return Y==="object"?X===null?"null":"object":Y==="function"?"object":Y},G1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},B5={...G1,function:"a function"};class T5 extends Error{}var e=(X)=>C4(X,T5),C4=(X,Y=Error)=>{throw new Y(X)};class C8 extends Error{name="ParseError"}var R=(X)=>C4(X,C8),P1=(X)=>` ${X}`;var d=(X,Y)=>{let Z={},_=Array.isArray(X),G=!1;for(let[W,$]of Object.entries(X).entries()){let H=_?Y(W,$[1]):Y(...$,W);G||=typeof H[0]==="number";let Q=Array.isArray(H[0])||H.length===0?H:[H];for(let[J,z]of Q)if(typeof J==="object")Z[J.group]=t(Z[J.group],z);else Z[J]=z}return G?Object.values(Z):Z};var LX=Object.entries;var f0=(X,Y)=>(X in Y),i4=(X,Y)=>(Y in X);class MX{constructor(X){Object.assign(this,X)}}var C5=class{};class q8 extends C5{}var oH=(X,Y)=>{let Z={},_={},G;for(G in X)if(G in Y)Z[G]=X[G];else _[G]=X[G];return[Z,_]};var q5=(X,Y)=>oH(X,Y)[1],l1=(X)=>Object.keys(X).length===0,q4=(X)=>[...Object.entries(X),...Object.getOwnPropertySymbols(X).map((Y)=>[Y,X[Y]])],j5=(X,Y)=>Object.defineProperties(X,Object.getOwnPropertyDescriptors(Y)),S5=(X)=>{let Y=Object.keys(X).sort(),Z={};for(let _=0;_<Y.length;_++)Z[Y[_]]=X[Y[_]];return Z};var V1=P1("represents an uninitialized value"),P5=(X)=>Object.values(X).filter((Y)=>{if(typeof Y==="number")return!0;return typeof X[Y]!=="number"});var AX={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},RX=globalThis.File??Blob,wX={ArrayBuffer,Blob,File:RX,FormData,Headers,Request,Response,URL},iH={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},j4={...AX,...wX,...iH,String,Number,Boolean},j8=(X)=>{let Y=Object.getPrototypeOf(X);while(Y?.constructor&&(!f0(Y.constructor.name,j4)||!(X instanceof j4[Y.constructor.name])))Y=Object.getPrototypeOf(Y);let Z=Y?.constructor?.name;if(Z===void 0||Z==="Object")return;return Z},S8=(X)=>typeof X==="object"&&X!==null?j8(X)??"object":x0(X);var Q0=Array.isArray,nH={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},rH={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},sH={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},v5={...nH,...rH,...sH},P8=(X)=>{let Y=Object(X).name??null;return Y&&f0(Y,j4)&&j4[Y]===X?Y:null};var NX=(X,Y)=>{let Z=X.prototype;while(Z!==null){if(Z===Y.prototype)return!0;Z=Object.getPrototypeOf(Z)}return!1};var x5=(X)=>f5(X,new Map),f5=(X,Y)=>{if(typeof X!=="object"||X===null)return X;if(Y?.has(X))return Y.get(X);let Z=P8(X.constructor);if(Z==="Date")return new Date(X.getTime());if(Z&&Z!=="Array")return X;let _=Array.isArray(X)?X.slice():Object.create(Object.getPrototypeOf(X)),G=Object.getOwnPropertyDescriptors(X);if(Y){Y.set(X,_);for(let W in G){let $=G[W];if("get"in $||"set"in $)continue;$.value=f5($.value,Y)}}return Object.defineProperties(_,G),_};var tH=(X)=>{let Y=V1;return()=>Y===V1?Y=X():Y},E4=(X)=>typeof X==="function"&&X.length===0;var h5=class extends Function{constructor(...X){let Y=X.slice(0,-1),Z=X.at(-1);try{super(...Y,Z)}catch(_){return e(`Encountered an unexpected error while compiling your definition:
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:
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 k5=tH(()=>{try{return Function("return false")()}catch{return!0}});var MO=P1("brand");var b5=P1("arkInferred");var wO=P1("args");class o0{constructor(){}}var aH=()=>{try{return((Error().stack?.split(`
8
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},eH=globalThis.process?.env??{},y5={fileName:aH,env:eH};var g5=(X)=>X[0].toUpperCase()+X.slice(1);var IX=(X)=>new RegExp(XJ(X),typeof X==="string"?"":X.flags);var XJ=(X)=>{return`^(?:${typeof X==="string"?X:X.source})$`};var a1={negativeLookahead:(X)=>`(?!${X})`,nonCapturingGroup:(X)=>`(?:${X})`},v8="\\",O4={" ":1,"\n":1,"\t":1};var YJ=/^-0\.?0*$/.source,m5=/[1-9]\d*/.source,ZJ=/\.\d+/.source,_J=/\.\d*[1-9]/.source,u5=(X)=>IX(a1.negativeLookahead(YJ)+a1.nonCapturingGroup("-?"+a1.nonCapturingGroup(a1.nonCapturingGroup("0|"+m5)+a1.nonCapturingGroup(X.decimalPattern)+"?")+(X.allowDecimalOnly?"|"+X.decimalPattern:"")+"?")),p5=u5({decimalPattern:_J,allowDecimalOnly:!1}),GJ=p5.test.bind(p5),m2=u5({decimalPattern:ZJ,allowDecimalOnly:!0}),qO=m2.test.bind(m2),WJ=/^-?\d*\.?\d*$/,$J=(X)=>X.length!==0&&WJ.test(X),x8=IX(a1.negativeLookahead("^-0$")+"-?"+a1.nonCapturingGroup(a1.nonCapturingGroup("0|"+m5))),HJ=x8.test.bind(x8),KX=/^-?\d+$/,JJ=KX.test.bind(KX),d5={number:"a number",bigint:"a bigint",integer:"an integer"},c5=(X,Y)=>`'${X}' was parsed as ${d5[Y]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,QJ=(X,Y)=>Y==="number"?GJ(X):HJ(X),zJ=(X,Y)=>Y==="number"?Number(X):Number.parseInt(X),FJ=(X,Y)=>Y==="number"?$J(X):JJ(X),l5=(X,Y)=>BX(X,"number",Y),o5=(X,Y)=>BX(X,"number",{...Y,strict:!0}),i5=(X,Y)=>BX(X,"integer",Y),BX=(X,Y,Z)=>{let _=zJ(X,Y);if(!Number.isNaN(_)){if(FJ(X,Y)){if(Z?.strict)return QJ(X,Y)?_:R(c5(X,Y));return _}}return Z?.errorOnFail?R(Z?.errorOnFail===!0?`Failed to parse ${d5[Y]} from '${X}'`:Z?.errorOnFail):void 0},n5=(X)=>{if(X[X.length-1]!=="n")return;let Y=X.slice(0,-1),Z;try{Z=BigInt(Y)}catch{return}if(x8.test(Y))return Z;if(KX.test(Y))return R(c5(X,"bigint"))};var UJ="0.49.0",EJ={version:UJ,filename:y5.fileName(),FileConstructor:RX},S4=EJ,r5=new Map,TX=Object.create(null),f8=(X)=>{let Y=r5.get(X);if(Y)return Y;let Z=OJ(X);if(TX[Z])Z=`${Z}${TX[Z]++}`;else TX[Z]=1;return S4[Z]=X,r5.set(X,Z),Z},V4=(X)=>/^[$A-Z_a-z][\w$]*$/.test(X),OJ=(X)=>{switch(typeof X){case"object":{if(X===null)break;let Y=j8(X)??"object";return Y[0].toLowerCase()+Y.slice(1)}case"function":return V4(X.name)?X.name:"fn";case"symbol":return X.description&&V4(X.description)?X.description:"symbol"}return e(`Unexpected attempt to register serializable value of type ${x0(X)}`)};var h8=(X)=>typeof X==="string"?JSON.stringify(X):typeof X==="bigint"?`${X}n`:`${X}`;var s5=(X,Y={})=>k8(X,{onUndefined:"$ark.undefined",onBigInt:(Z)=>`$ark.bigint-${Z}`,...Y},[]);var c=(X,Y)=>{switch(x0(X)){case"object":let Z=X,_=Z.constructor.name;return _==="Object"||_==="Array"?Y?.quoteKeys===!1?u2(Z,Y?.indent??0,""):JSON.stringify(k8(Z,n4,[]),null,Y?.indent):u2(Z,Y?.indent??0,"");case"symbol":return n4.onSymbol(X);default:return h8(X)}},u2=(X,Y,Z)=>{if(typeof X==="function")return n4.onFunction(X);if(typeof X!=="object"||X===null)return h8(X);let _=Z+" ".repeat(Y);if(Array.isArray(X)){if(X.length===0)return"[]";let W=X.map(($)=>u2($,Y,_)).join(`,
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(`,
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=u2(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"?n4.onSymbol($):V4($)?$:JSON.stringify($),J=m2(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=`${VJ[Z]} ${_}, ${Y}`;if(G===0&&W===0&&$===0&&H===0)return Q;let J=X.toLocaleTimeString(),z=J.endsWith(" AM")||J.endsWith(" PM")?J.slice(-3):"";if(z)J=J.slice(0,-z.length);if(H)J+=`.${LJ(H,3)}`;else if(DJ.test(J))J=J.slice(0,-3);return`${J+z}, ${Q}`},VJ=["January","February","March","April","May","June","July","August","September","October","November","December"],DJ=/:\d\d:00$/,LJ=(X,Y)=>String(X).padStart(Y,"0");var t5=(X,Y,...[Z])=>{let _=Z?.stringifySymbol??c,G=X;switch(typeof Y){case"string":G=V4(Y)?X===""?Y:`${X}.${Y}`:`${X}[${JSON.stringify(Y)}]`;break;case"number":G=`${X}[${Y}]`;break;case"symbol":G=`${X}[${_(Y)}]`;break;default:if(Z?.stringifyNonKey)G=`${X}[${Z.stringifyNonKey(Y)}]`;else R(`${c(Y)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return G},e1=(X,...Y)=>X.reduce((Z,_)=>t5(Z,_,...Y),"");class b8 extends p2{cache={};constructor(...X){super();this.push(...X)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let X=0;X<this.length;X++)this.cache.json.push(typeof this[X]==="symbol"?c(this[X]):this[X]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=e1(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let X="",Y=[X];for(let Z of this)X=t5(X,Z),Y.push(X);return this.cache.stringifyAncestors=Y}}class CX{chars;i;def;constructor(X){this.def=X,this.chars=[...X],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(X){let Y="";while(this.lookahead){if(X(this,Y))if(Y[Y.length-1]===v8)Y=Y.slice(0,-1);else break;Y+=this.shift()}return Y}shiftUntilLookahead(X){return typeof X==="string"?this.shiftUntil((Y)=>Y.lookahead===X):this.shiftUntil((Y)=>(Y.lookahead in X))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in O4))}jumpToIndex(X){this.i=X<0?this.length+X:X}jumpForward(X){this.i+=X}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(X,Y){return this.chars.slice(X,Y).join("")}lookaheadIs(X){return this.lookahead===X}lookaheadIsIn(X){return this.lookahead in X}}var eO=P1("implementedTraits");var qX="$ark",MJ=2;while(qX in globalThis)qX=`$ark${MJ++}`;var a5=qX;globalThis[a5]=S4;var N=S4,AJ=(X)=>`${a5}.${X}`,I0=(X)=>AJ(f8(X));class d2 extends q8{argNames;body="";constructor(...X){super();this.argNames=X;for(let Y of X){if(Y in this)throw Error(`Arg name '${Y}' would overwrite an existing property on FunctionBody`);this[Y]=Y}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(X,Y=!1){return jX(X,Y)}index(X,Y=!1){return e5(`${X}`,Y)}line(X){return this.body+=`${" ".repeat(this.indentation)}${X}
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}
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 h5(...this.argNames,this.body)}}var X4=(X)=>_1(X,"object")||typeof X==="symbol"?I0(X):h8(X),jX=(X,Y=!1)=>{if(typeof X==="string"&&V4(X))return`${Y?"?":""}.${X}`;return e5(RJ(X),Y)},RJ=(X)=>typeof X==="symbol"?I0(X):JSON.stringify(X),e5=(X,Y=!1)=>`${Y?"?.":""}[${X}]`;class y8 extends d2{traversalKind;optimistic;constructor(X){super("data","ctx");this.traversalKind=X.kind,this.optimistic=X.optimistic===!0}invoke(X,Y){let Z=Y?.arg??this.data,_=typeof X==="string"?!0:this.requiresContextFor(X),G=typeof X==="string"?X:X.id;if(_)return`${this.referenceToId(G,Y)}(${Z}, ${this.ctx})`;return`${this.referenceToId(G,Y)}(${Z})`}referenceToId(X,Y){let Z=Y?.kind??this.traversalKind,_=`this.${X}${Z}`;return Y?.bind?`${_}.bind(${Y?.bind})`:_}requiresContextFor(X){return this.traversalKind==="Apply"||X.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(X,Y,Z){let _=this.requiresContextFor(Z);if(_)this.line(`${this.ctx}.path.push(${X})`);if(this.check(Z,{arg:Y}),_)this.line(`${this.ctx}.path.pop()`);return this}check(X,Y){return this.traversalKind==="Allows"?this.if(`!${this.invoke(X,Y)}`,()=>this.return(!1)):this.line(this.invoke(X,Y))}}var c2=(X)=>d(X,(Y,Z)=>[Y,Q0(Z)?[...Z]:Z]),t0=P1("arkKind"),f=(X,Y)=>X?.[t0]===Y,E0=(X)=>f(X,"root")||f(X,"constraint");var X_=["unit","proto","domain"],r4=["required","optional","index","sequence"],SX=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],l2=[...SX,...r4,"structure","predicate"],s4=["alias","union","morph","unit","intersection","proto","domain"],wJ=[...s4,...l2],o2=d(l2,(X,Y)=>[Y,1]),Y_=d([...r4,"undeclared"],(X,Y)=>[Y,1]),Z_=d(wJ,(X,Y)=>[Y,X]),t4=(X)=>typeof X==="string"&&(X in Z_);var a4=(X)=>Z_[X],i2=(X)=>s4.slice(a4(X)+1),kV=[...i2("union"),"alias"],bV=[...i2("morph"),"alias"],A1=(X)=>{if(typeof X==="string"||typeof X==="boolean"||X===null)return X;if(typeof X==="number"){if(Number.isNaN(X))return"NaN";if(X===Number.POSITIVE_INFINITY)return"Infinity";if(X===Number.NEGATIVE_INFINITY)return"-Infinity";return X}return X4(X)},D4=(X)=>{let Y="{ ";for(let[Z,_]of Object.entries(X))Y+=`${Z}: ${X4(_)}, `;return Y+" }"},l=(X)=>{let Y=X;if(Y.hasAssociatedError)Y.defaults.expected??=(Z)=>("description"in Z)?Z.description:Y.defaults.description(Z),Y.defaults.actual??=(Z)=>c(Z),Y.defaults.problem??=(Z)=>`must be ${Z.expected}${Z.actual?` (was ${Z.actual})`:""}`,Y.defaults.message??=(Z)=>{if(Z.path.length===0)return Z.problem;let _=`${Z.propString} ${Z.problem}`;if(_[0]==="[")return`value at ${_}`;return _};return Y};class __ extends Error{name="ToJsonSchemaError";code;context;constructor(X,Y){super(c(Y,{quoteKeys:!1,indent:4}));this.code=X,this.context=Y}hasCode(X){return this.code===X}}var NJ={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(X)=>M0.throw("arrayObject",X),arrayPostfix:(X)=>M0.throw("arrayPostfix",X),defaultValue:(X)=>M0.throw("defaultValue",X),domain:(X)=>M0.throw("domain",X),morph:(X)=>M0.throw("morph",X),patternIntersection:(X)=>M0.throw("patternIntersection",X),predicate:(X)=>M0.throw("predicate",X),proto:(X)=>M0.throw("proto",X),symbolKey:(X)=>M0.throw("symbolKey",X),unit:(X)=>M0.throw("unit",X),date:(X)=>M0.throw("date",X)}},M0={Error:__,throw:(...X)=>{throw new M0.Error(...X)},throwInternalOperandError:(X,Y)=>e(`Unexpected JSON Schema input for ${X}: ${c(Y)}`),defaultConfig:NJ};N.config??={};var g8=(X,Y)=>{if(!Y)return X;let Z={...X},_;for(_ in Y){let G={...X.keywords};if(_==="keywords"){for(let W in Y[_]){let $=Y.keywords[W];if($===void 0)continue;G[W]=typeof $==="string"?{description:$}:$}Z.keywords=G}else if(_==="toJsonSchema")Z[_]=PX(X.toJsonSchema,Y.toJsonSchema);else if(t4(_))Z[_]={...X[_],...Y[_]};else Z[_]=Y[_]}return Z},PX=(X,Y)=>{if(!X)return Y??{};if(!Y)return X;let Z={...X},_;for(_ in Y)if(_==="fallback")Z.fallback=IJ(X.fallback,Y.fallback);else Z[_]=Y[_];return Z},IJ=(X,Y)=>{X=G_(X),Y=G_(Y);let Z={},_;for(_ in M0.defaultConfig.fallback)Z[_]=Y[_]??Y.default??X[_]??X.default??M0.defaultConfig.fallback[_];return Z},G_=(X)=>typeof X==="function"?{default:X}:X??{};class L4 extends q8{[t0]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:X,relativePath:Y,...Z},_){super();this.input=Z,this.ctx=_,j5(this,Z);let G=_.data;if(Z.code==="union")Z.errors=Z.errors.flatMap(($)=>{let H=$.hasCode("union")?$.errors:[$];if(!X&&!Y)return H;return H.map((Q)=>Q.transform((J)=>({...J,path:I5(X,J.path,Y)})))});this.nodeConfig=_.config[this.code];let W=[...Z.path??_.path];if(Y)W.push(...Y);if(X)W.unshift(...X);this.path=new b8(...W),this.data="data"in Z?Z.data:G}transform(X){return new L4(X({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(X){return this.code===X}get propString(){return e1(this.path)}get expected(){if(this.input.expected)return this.input.expected;let X=this.meta?.expected??this.nodeConfig.expected;return typeof X==="function"?X(this.input):X}get actual(){if(this.input.actual)return this.input.actual;let X=this.meta?.actual??this.nodeConfig.actual;return typeof X==="function"?X(this.data):X}get problem(){if(this.input.problem)return this.input.problem;let X=this.meta?.problem??this.nodeConfig.problem;return typeof X==="function"?X(this):X}get message(){if(this.input.message)return this.input.message;let X=this.meta?.message??this.nodeConfig.message;return typeof X==="function"?X(this):X}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class W1 extends p2{[t0]="errors";ctx;constructor(X){super();this.ctx=X}byPath=Object.create(null);get flatByPath(){return d(this.byPath,(X,Y)=>[X,Y.flat])}get flatProblemsByPath(){return d(this.byPath,(X,Y)=>[X,Y.flat.map((Z)=>Z.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new vX(this)}add(X){if(this.includes(X))return;this._add(X)}transform(X){let Y=new W1(this.ctx);for(let Z of this)Y.add(X(Z));return Y}merge(X){for(let Y of X){if(this.includes(Y))continue;this._add(new L4({...Y,path:[...this.ctx.path,...Y.path]},this.ctx))}}affectsPath(X){if(this.length===0)return!1;return X.stringifyAncestors().some((Y)=>(Y in this.byPath))||X.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((X)=>X.toJSON())]}toString(){return this.join(`
18
- `)}_add(X){let Y=this.byPath[X.propString];if(Y){if(Y.hasCode("union")&&Y.errors.length===0)return;let Z=X.hasCode("union")&&X.errors.length===0?X:new L4({code:"intersection",errors:Y.hasCode("intersection")?[...Y.errors,X]:[Y,X]},this.ctx),_=this.indexOf(Y);this.mutable[_===-1?this.length:_]=Z,this.byPath[X.propString]=Z,this.addAncestorPaths(X)}else this.byPath[X.propString]=X,this.addAncestorPaths(X),this.mutable.push(X);this.count++}addAncestorPaths(X){for(let Y of X.path.stringifyAncestors())this.byAncestorPath[Y]=t(this.byAncestorPath[Y],X)}}class vX extends Error{name="TraversalError";constructor(X){if(X.length===1)super(X.summary);else super(`
19
- `+X.map((Y)=>` \u2022 ${KJ(Y)}`).join(`
20
- `));Object.defineProperty(this,"arkErrors",{value:X,enumerable:!1})}}var KJ=(X)=>X.toString().split(`
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(`
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)=>qJ(_,G.shallowReferences),[this]);let Z=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let _=0;_<this.children.length;_++){if(this.includesTransform||=this.children[_].includesTransform,this.includesContextualPredicate||=this.children[_].includesContextualPredicate,this.isCyclic||=this.children[_].isCyclic,!Z){let G=this.children[_].flatRefs;for(let W=0;W<G.length;W++){let $=G[W];if(!this.flatRefs.some((H)=>$_(H,$))){this.flatRefs.push($);for(let H of $.node.branches)if(H.hasKind("morph")||H.hasKind("intersection")&&H.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:$.path,propString:$.propString,node:H})}}}Object.assign(this.referencesById,this.children[_].referencesById)}this.flatRefs.sort((_,G)=>_.path.length>G.path.length?1:_.path.length<G.path.length?-1:_.propString>G.propString?1:_.propString<G.propString?-1:_.node.expression<G.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((_)=>_.length===1||_.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((_)=>_.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(_)=>this.traverseAllows(_,new x1(_,this.$.resolvedConfig)):(_)=>this.traverseAllows(_)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Y,Z)=>{if(this.allows(Y))return Y;let _=new x1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)};case"contextual":return(Y,Z)=>{let _=new x1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let X=this.$.resolvedConfig.clone;return(Y,Z)=>{if(this.allows(Y))return this.contextFreeMorph(X&&(typeof Y==="object"&&Y!==null||typeof Y==="function")?X(Y):Y);let _=new x1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,e(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=CJ(this.metaJson);cacheGetter(X,Y){return Object.defineProperty(this,X,{value:Y}),Y}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=a4(this.kind);precompilation;assert=(X,Y)=>this(X,Y,(Z)=>Z.throw());traverse(X,Y){return this(X,Y,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(X){if(!this.includesTransform)return this;let Y={};for(let[Z,_]of this.innerEntries){let G=this.impl.keys[Z];if(G.reduceIo)G.reduceIo(X,Y,_);else if(G.child){let W=_;Y[Z]=Q0(W)?W.map(($)=>$[X]):W[X]}else Y[Z]=_}return this.$.node(this.kind,Y)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(X){let Y=E0(X)?X:this.$.parseDefinition(X);return this.innerHash===Y.innerHash}ifEquals(X){return this.equals(X)?this:void 0}hasKind(X){return this.kind===X}assertHasKind(X){if(this.kind!==X)C4(`${this.kind} node was not of asserted kind ${X}`);return this}hasKindIn(...X){return X.includes(this.kind)}assertHasKindIn(...X){if(!r1(X,this.kind))C4(`${this.kind} node was not one of asserted kinds ${X}`);return this}isBasis(){return r1(X_,this.kind)}isConstraint(){return r1(l2,this.kind)}isStructural(){return r1(r4,this.kind)}isRefinement(){return r1(SX,this.kind)}isRoot(){return r1(s4,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(X){return this.hasKind("unit")&&this.allows(X)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(X){let Y=p8.normalize(X);return this._select(Y)}_select(X){let Y=p8.applyBoundary[X.boundary??"references"](this);if(X.kind)Y=Y.filter((Z)=>Z.kind===X.kind);if(X.where)Y=Y.filter(X.where);return p8.applyMethod[X.method??"filter"](Y,this,X)}transform(X,Y){return this._transform(X,this._createTransformContext(Y))}_createTransformContext(X){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:X?.prereduced??!1},undeclaredKeyHandling:void 0,...X}}_transform(X,Y){let Z=Y.bindScope??this.$;if(Y.seen[this.id])return this.$.lazilyResolve(Y.seen[this.id]);if(Y.shouldTransform?.(this,Y)===!1)return this;let _;if(Y.seen[this.id]=()=>_,this.hasKind("structure")&&this.undeclared!==Y.undeclaredKeyHandling)Y={...Y,undeclaredKeyHandling:this.undeclared};let G=d(this.inner,(J,z)=>{if(!this.impl.keys[J].child)return[J,z];let F=z;if(!Q0(F)){let D=F._transform(X,Y);return D?[J,D]:[]}if(F.length===0)return[J,z];let O=F.flatMap((D)=>{return D._transform(X,Y)??[]});return O.length?[J,O]:[]});delete Y.seen[this.id];let W=Object.assign(G,{meta:this.meta}),$=Y.selected&&!Y.selected.includes(this)?W:X(this.kind,W,Y);if($===null)return null;if(E0($))return _=$;let H=Object.keys($);if((H.length===0||H.length===1&&H[0]==="meta")&&!l1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in $))return Y.undeclaredKeyHandling?{...$,value:N.intrinsic.unknown}:null;if(this.kind==="morph")$.in??=N.intrinsic.unknown;return _=Z.node(this.kind,$,Y.parseOptions)}configureReferences(X,Y="references"){let Z=p8.normalize(Y),_=typeof X==="string"?(H,Q)=>({...Q,meta:{...Q.meta,description:X}}):typeof X==="function"?(H,Q)=>({...Q,meta:X(Q.meta)}):(H,Q)=>({...Q,meta:{...Q.meta,...X}});if(Z.boundary==="self")return this.$.node(this.kind,_(this.kind,{...this.inner,meta:this.meta}));let G=this._select(Z),W=G&&U4(G),$=Z.boundary==="child"?(H,Q)=>Q.root.children.includes(H):Z.boundary==="shallow"?(H)=>H.kind!=="structure":()=>!0;return this.$.finalize(this.transform(_,{shouldTransform:$,selected:W}))}}var p8={applyBoundary:{self:(X)=>[X],child:(X)=>[...X.children],shallow:(X)=>[...X.shallowReferences],references:(X)=>[...X.references]},applyMethod:{filter:(X)=>X,assertFilter:(X,Y,Z)=>{if(X.length===0)C4(W_(Y,Z));return X},find:(X)=>X[0],assertFind:(X,Y,Z)=>{if(X.length===0)C4(W_(Y,Z));return X[0]}},normalize:(X)=>typeof X==="function"?{boundary:"references",method:"filter",where:X}:typeof X==="string"?f0(X,p8.applyBoundary)?{method:"filter",boundary:X}:{boundary:"references",method:"filter",kind:X}:{boundary:"references",method:"filter",...X}},W_=(X,Y)=>`${X} had no references matching ${c(Y)}.`,BJ=(X)=>e1(X,{stringifyNonKey:(Y)=>Y.expression}),TJ=/"(\$ark\.[^"]+)"/g,CJ=(X)=>JSON.stringify(X).replaceAll(TJ,"$1"),f1=(X,Y)=>({path:X,node:Y,propString:BJ(X)}),$_=(X,Y)=>X.propString===Y.propString&&X.node.equals(Y.node),xX=(X,Y)=>c1(X,Y,{isEqual:$_}),qJ=(X,Y)=>c1(X,Y,{isEqual:(Z,_)=>Z.equals(_)});class C extends Array{static init(X,Y,Z,_){return new C({kind:X,l:Y,r:Z,path:_?.path??[],optional:_?.optional??!1})}add(X,Y,Z,_){return this.push({kind:X,l:Y,r:Z,path:_?.path??[],optional:_?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:X,l:Y,r:Z}=this[0],_=e1(X);return hX(`Intersection${_&&` at ${_}`} of ${H_(Y,Z)}`)}return`The following intersections result in unsatisfiable types:
23
- \u2022 ${this.map(({path:X,l:Y,r:Z})=>`${X}: ${H_(Y,Z)}`).join(`
24
- \u2022 `)}`}throw(){return R(this.describeReasons())}invert(){let X=this.map((Y)=>({...Y,l:Y.r,r:Y.l}));if(!(X instanceof C))return new C(...X);return X}withPrefixKey(X,Y){return this.map((Z)=>({...Z,path:[X,...Z.path],optional:Z.optional||Y==="optional"}))}toNeverIfDisjoint(){return N.intrinsic.never}}var H_=(X,Y)=>`${fX(X)} and ${fX(Y)}`,fX=(X)=>E0(X)?X.expression:Q0(X)?X.map(fX).join(" | ")||"never":String(X),hX=(X)=>`${X} results in an unsatisfiable type`;var e4={},H1=(X,Y,Z)=>O0(X,Y,{$:Z,invert:!1,pipe:!1}),u8=(X,Y,Z)=>O0(X,Y,{$:Z,invert:!1,pipe:!0}),O0=(X,Y,Z)=>{let _=Z.pipe?"|>":"&",G=`${X.hash}${_}${Y.hash}`;if(e4[G]!==void 0)return e4[G];if(!Z.pipe){let H=`${Y.hash}${_}${X.hash}`;if(e4[H]!==void 0){let Q=e4[H],J=Q instanceof C?Q.invert():Q;return e4[G]=J,J}}let W=!Z.pipe||!X.includesTransform&&!Y.includesTransform;if(W&&X.equals(Y))return X;let $=W?kX(X,Y,Z):X.hasKindIn(...s4)?jJ(X,Y,Z):kX(X,Y,Z);if(E0($)){if(X.equals($))$=X;else if(Y.equals($))$=Y}return e4[G]=$,$},kX=(X,Y,Z)=>{let _=X.precedence<Y.precedence?X.kind:Y.kind,G=X.impl.intersections[Y.kind]??Y.impl.intersections[X.kind];if(G===void 0)return null;else if(_===X.kind)return G(X,Y,Z);else{let W=G(Y,X,{...Z,invert:!Z.invert});if(W instanceof C)W=W.invert();return W}},jJ=(X,Y,Z)=>X.includesTransform||Y.includesTransform?Z.invert?J_(Y,X,Z):J_(X,Y,Z):kX(X,Y,Z),J_=(X,Y,Z)=>X.distribute((_)=>SJ(_,Y,Z),(_)=>{let G=_.filter(E0);if(G.length===0)return C.init("union",X.branches,Y.branches);if(G.length<X.branches.length||!X.branches.every((H,Q)=>H.in.equals(G[Q].in)))return Z.$.parseSchema(G);let W;if(G.length===1){let H=G[0];if(!W)return H;return Z.$.node("morph",{...H.inner,in:H.in.configure(W,"self")})}let $={branches:G};if(W)$.meta=W;return Z.$.parseSchema($)}),SJ=(X,Y,Z)=>{if(X.hasKind("morph")){let G=[...X.morphs];if(X.lastMorphIfNode){let W=O0(X.lastMorphIfNode,Y,Z);if(W instanceof C)return W;G[G.length-1]=W}else G.push(Y);return Z.$.node("morph",{morphs:G,in:X.inner.in})}if(Y.hasKind("morph")){let G=O0(X,Y.in,Z);if(G instanceof C)return G;return Z.$.node("morph",{morphs:[Y],in:G})}return Z.$.node("morph",{morphs:[Y],in:X})};class R1 extends m8{constructor(X,Y){super(X,Y);Object.defineProperty(this,t0,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(X){return H1(this,X,this.$)}}class Y4 extends R1{traverseApply=(X,Y)=>{if(!this.traverseAllows(X,Y))Y.errorFromNodeContext(this.errorContext)};compile(X){if(X.traversalKind==="Allows")X.return(this.compiledCondition);else X.if(this.compiledNegation,()=>X.line(`${X.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return D4(this.errorContext)}}var i0=(X)=>(Y,Z)=>{if(Q0(Y)){if(Y.length===0)return;let G=Y.map((W)=>Z.$.node(X,W));if(X==="predicate")return G;return G.sort((W,$)=>W.hash<$.hash?-1:1)}let _=Z.$.node(X,Y);return _.hasOpenIntersection()?[_]:_},X8=(X)=>{let Y=X.r.shift();if(!Y){let _=X.l.length===0&&X.kind==="structure"?N.intrinsic.unknown.internal:X.ctx.$.node(X.kind,Object.assign(X.baseInner,PJ(X.l)),{prereduced:!0});for(let G of X.roots){if(_ instanceof C)return _;_=O0(G,_,X.ctx)}return _}let Z=!1;for(let _=0;_<X.l.length;_++){let G=O0(X.l[_],Y,X.ctx);if(G===null)continue;if(G instanceof C)return G;if(!Z){if(G.isRoot())return X.roots.push(G),X.l.splice(_),X8(X);X.l[_]=G,Z=!0}else if(!X.l.includes(G))return e(`Unexpectedly encountered multiple distinct intersection results for refinement ${G}`)}if(!Z)X.l.push(Y);if(X.kind==="intersection"){if(Y.impliedSiblings)for(let _ of Y.impliedSiblings)c1(X.r,_)}return X8(X)},Y8=(X)=>{return Object.entries(X).flatMap(([Z,_])=>(Z in o2)?_:[]).sort((Z,_)=>Z.precedence<_.precedence?-1:Z.precedence>_.precedence?1:Z.kind==="predicate"&&_.kind==="predicate"?0:Z.hash<_.hash?-1:1)},PJ=(X)=>{let Y={};for(let Z of X)if(Z.hasOpenIntersection())Y[Z.kind]=t(Y[Z.kind],Z);else{if(Y[Z.kind])return e(`Unexpected intersection of closed refinements of kind ${Z.kind}`);Y[Z.kind]=Z}return Y},Q_=(...X)=>R(z_(...X)),z_=(X,Y,Z)=>{let _=Z.hasKind("morph")?"a morph":Z.isUnknown()?"unknown":Z.exclude(Y).defaultShortDescription;return`${g5(X)} operand must be ${Y.description} (was ${_})`};var F_=(X,Y,Z)=>new M4(X,Y,Z,Z,null);class n2 extends v1{}class M4 extends v1{[t0]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(X,Y,Z,_,G){super((...W)=>{let $=d(this.names,(H,Q)=>{let J=this.arg$.parse(W[H]);if(!J.extends(this.constraints[H]))R(vJ(Q,this.constraints[H].expression,J.expression));return[Q,J]});if(this.defIsLazy()){let H=this.bodyDef($);return this.$.parse(H)}return this.$.parse(Y,{args:$})});this.paramDefs=X,this.bodyDef=Y,this.$=Z,this.arg$=_,this.hkt=G,this.description=G?new G().description??`a generic type for ${G.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof n2}cacheGetter(X,Y){return Object.defineProperty(this,X,{value:Y}),Y}get json(){return this.cacheGetter("json",{params:this.params.map((X)=>X[1].isUnknown()?X[0]:[X[0],X[1].json]),body:s5(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((X)=>typeof X==="string"?[X,N.intrinsic.unknown]:[X[0],this.$.parse(X[1])]))}get names(){return this.cacheGetter("names",this.params.map((X)=>X[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((X)=>X[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var vJ=(X,Y,Z)=>`${X} must be assignable to ${Y} (was ${Z})`;var xJ=l({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(X)=>typeof X==="function"?{predicate:X}:X,defaults:{description:(X)=>`valid according to ${X.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class U_ extends R1{serializedPredicate=I0(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=D4(this.errorContext);traverseApply=(X,Y)=>{if(!this.predicate(X,Y.external)&&!Y.hasError())Y.errorFromNodeContext(this.errorContext)};compile(X){if(X.traversalKind==="Allows"){X.return(this.compiledCondition);return}X.if(`${this.compiledNegation} && !ctx.hasError()`,()=>X.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(X,Y){return Y.fallback.predicate({code:"predicate",base:X,predicate:this.predicate})}}var bX={implementation:xJ,Node:U_};var fJ=l({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(X)=>Number.isInteger(X)?X:R(hJ(X))}},normalize:(X)=>typeof X==="number"?{rule:X}:X,hasAssociatedError:!0,defaults:{description:(X)=>X.rule===1?"an integer":X.rule===2?"even":`a multiple of ${X.rule}`},intersections:{divisor:(X,Y,Z)=>Z.$.node("divisor",{rule:Math.abs(X.rule*Y.rule/kJ(X.rule,Y.rule))})},obviatesBasisDescription:!0});class E_ extends Y4{traverseAllows=(X)=>X%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=N.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(X){if(X.type="integer",this.rule===1)return X;return X.multipleOf=this.rule,X}}var yX={implementation:fJ,Node:E_};var hJ=(X)=>`divisor must be an integer (was ${X})`,kJ=(X,Y)=>{let Z,_=X,G=Y;while(G!==0)Z=G,G=_%G,_=Z;return _};class D1 extends Y4{boundOperandKind=pJ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=mJ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${bJ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?uJ(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(X){return(this.limitKind==="upper"?this.numericLimit<X.numericLimit:this.numericLimit>X.numericLimit)||this.numericLimit===X.numericLimit&&this.exclusive===!0&&!X.exclusive}overlapsRange(X){if(this.isStricterThan(X))return!1;if(this.numericLimit===X.numericLimit&&(this.exclusive||X.exclusive))return!1;return!0}overlapIsUnit(X){return this.numericLimit===X.numericLimit&&!this.exclusive&&!X.exclusive}}var bJ={"<":">=","<=":">",">":"<=",">=":"<"},yJ={min:"max",minLength:"maxLength",after:"before"},r2={parse:(X)=>X||void 0},s2=(X)=>(Y)=>{if(typeof Y==="number")return{rule:Y};let{exclusive:Z,..._}=Y;return Z?{..._,rule:X==="minLength"?_.rule+1:_.rule-1}:_},t2=(X)=>(Y)=>{if(typeof Y==="number"||typeof Y==="string"||Y instanceof Date)return{rule:Y};let{exclusive:Z,..._}=Y;if(!Z)return _;let G=typeof _.rule==="number"?_.rule:typeof _.rule==="string"?new Date(_.rule).valueOf():_.rule.valueOf();return Z?{..._,rule:X==="after"?G+1:G-1}:_},a2=(X)=>typeof X==="string"||typeof X==="number"?new Date(X):X,gJ=(X,Y)=>`${X} bound must be a positive integer (was ${Y})`,Z8=(X)=>(Y)=>{if(!Number.isInteger(Y)||Y<0)R(gJ(X,Y));return Y},pJ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},mJ=(X,Y)=>`${f0(X,yJ)?">":"<"}${Y?"":"="}`,uJ=(X)=>typeof X==="string"?X:new Date(X).toLocaleString(),O_=(X)=>`Bounded expression ${X} must be exactly one of number, string, Array, or Date`;var dJ=l({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a2,serialize:(X)=>X.toISOString()}},normalize:t2("after"),defaults:{description:(X)=>`${X.collapsibleLimitString} or later`,actual:P4},intersections:{after:(X,Y)=>X.isStricterThan(Y)?X:Y}});class V_ extends D1{impliedBasis=N.intrinsic.Date.internal;collapsibleLimitString=P4(this.rule);traverseAllows=(X)=>X>=this.rule;reduceJsonSchema(X,Y){return Y.fallback.date({code:"date",base:X,after:this.rule})}}var gX={implementation:dJ,Node:V_};var cJ=l({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a2,serialize:(X)=>X.toISOString()}},normalize:t2("before"),defaults:{description:(X)=>`${X.collapsibleLimitString} or earlier`,actual:P4},intersections:{before:(X,Y)=>X.isStricterThan(Y)?X:Y,after:(X,Y,Z)=>X.overlapsRange(Y)?X.overlapIsUnit(Y)?Z.$.node("unit",{unit:X.rule}):null:C.init("range",X,Y)}});class D_ extends D1{collapsibleLimitString=P4(this.rule);traverseAllows=(X)=>X<=this.rule;impliedBasis=N.intrinsic.Date.internal;reduceJsonSchema(X,Y){return Y.fallback.date({code:"date",base:X,before:this.rule})}}var pX={implementation:cJ,Node:D_};var lJ=l({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:Z8("exactLength")}},normalize:(X)=>typeof X==="number"?{rule:X}:X,hasAssociatedError:!0,defaults:{description:(X)=>`exactly length ${X.rule}`,actual:(X)=>`${X.length}`},intersections:{exactLength:(X,Y,Z)=>C.init("unit",Z.$.node("unit",{unit:X.rule}),Z.$.node("unit",{unit:Y.rule}),{path:["length"]}),minLength:(X,Y)=>X.rule>=Y.rule?X:C.init("range",X,Y),maxLength:(X,Y)=>X.rule<=Y.rule?X:C.init("range",X,Y)}});class L_ extends Y4{traverseAllows=(X)=>X.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=N.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(X){switch(X.type){case"string":return X.minLength=this.rule,X.maxLength=this.rule,X;case"array":return X.minItems=this.rule,X.maxItems=this.rule,X;default:return M0.throwInternalOperandError("exactLength",X)}}}var mX={implementation:lJ,Node:L_};var oJ=l({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r2},normalize:(X)=>typeof X==="number"?{rule:X}:X,defaults:{description:(X)=>{if(X.rule===0)return X.exclusive?"negative":"non-positive";return`${X.exclusive?"less than":"at most"} ${X.rule}`}},intersections:{max:(X,Y)=>X.isStricterThan(Y)?X:Y,min:(X,Y,Z)=>X.overlapsRange(Y)?X.overlapIsUnit(Y)?Z.$.node("unit",{unit:X.rule}):null:C.init("range",X,Y)},obviatesBasisDescription:!0});class M_ extends D1{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(X)=>X<this.rule:(X)=>X<=this.rule;reduceJsonSchema(X){if(this.exclusive)X.exclusiveMaximum=this.rule;else X.maximum=this.rule;return X}}var uX={implementation:oJ,Node:M_};var iJ=l({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Z8("maxLength")}},reduce:(X,Y)=>X.rule===0?Y.node("exactLength",X):void 0,normalize:s2("maxLength"),defaults:{description:(X)=>`at most length ${X.rule}`,actual:(X)=>`${X.length}`},intersections:{maxLength:(X,Y)=>X.isStricterThan(Y)?X:Y,minLength:(X,Y,Z)=>X.overlapsRange(Y)?X.overlapIsUnit(Y)?Z.$.node("exactLength",{rule:X.rule}):null:C.init("range",X,Y)}});class A_ extends D1{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(X)=>X.length<=this.rule;reduceJsonSchema(X){switch(X.type){case"string":return X.maxLength=this.rule,X;case"array":return X.maxItems=this.rule,X;default:return M0.throwInternalOperandError("maxLength",X)}}}var dX={implementation:iJ,Node:A_};var nJ=l({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r2},normalize:(X)=>typeof X==="number"?{rule:X}:X,defaults:{description:(X)=>{if(X.rule===0)return X.exclusive?"positive":"non-negative";return`${X.exclusive?"more than":"at least"} ${X.rule}`}},intersections:{min:(X,Y)=>X.isStricterThan(Y)?X:Y},obviatesBasisDescription:!0});class R_ extends D1{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(X)=>X>this.rule:(X)=>X>=this.rule;reduceJsonSchema(X){if(this.exclusive)X.exclusiveMinimum=this.rule;else X.minimum=this.rule;return X}}var cX={implementation:nJ,Node:R_};var rJ=l({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Z8("minLength")}},reduce:(X)=>X.rule===0?N.intrinsic.unknown:void 0,normalize:s2("minLength"),defaults:{description:(X)=>X.rule===1?"non-empty":`at least length ${X.rule}`,actual:(X)=>X.length===0?"":`${X.length}`},intersections:{minLength:(X,Y)=>X.isStricterThan(Y)?X:Y}});class w_ extends D1{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(X)=>X.length>=this.rule;reduceJsonSchema(X){switch(X.type){case"string":return X.minLength=this.rule,X;case"array":return X.minItems=this.rule,X;default:return M0.throwInternalOperandError("minLength",X)}}}var lX={implementation:rJ,Node:w_};var N_={min:cX.implementation,max:uX.implementation,minLength:lX.implementation,maxLength:dX.implementation,exactLength:mX.implementation,after:gX.implementation,before:pX.implementation},I_={min:cX.Node,max:uX.Node,minLength:lX.Node,maxLength:dX.Node,exactLength:mX.Node,after:gX.Node,before:pX.Node};var sJ=l({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(X)=>typeof X==="string"?{rule:X}:X instanceof RegExp?X.flags?{rule:X.source,flags:X.flags}:{rule:X.source}:X,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(X)=>`matched by ${X.rule}`},intersections:{pattern:()=>null}});class K_ extends Y4{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=N.intrinsic.string.internal;reduceJsonSchema(X,Y){if(X.pattern)return Y.fallback.patternIntersection({code:"patternIntersection",base:X,pattern:this.rule});return X.pattern=this.rule,X}}var oX={implementation:sJ,Node:K_};var d8=(X,Y)=>{let Z=tJ(X);if(Y&&!Y.includes(Z))return R(`Root of kind ${Z} should be one of ${Y}`);return Z},tJ=(X)=>{if(f(X,"root"))return X.kind;if(typeof X==="string")return X[0]==="$"?"alias":(X in G1)?"domain":"proto";if(typeof X==="function")return"proto";if(typeof X!=="object"||X===null)return R(B_(X));if("morphs"in X)return"morph";if("branches"in X||Q0(X))return"union";if("unit"in X)return"unit";if("reference"in X)return"alias";let Y=Object.keys(X);if(Y.length===0||Y.some((Z)=>(Z in o2)))return"intersection";if("proto"in X)return"proto";if("domain"in X)return"domain";return R(B_(X))},B_=(X)=>`${c(X)} is not a valid type schema`,T_={},aJ=(X)=>Q0(X)?X.map((Y)=>Y.collapsibleJson):X.collapsibleJson,a0={};N.nodesByRegisteredId=a0;var iX=(X)=>{return T_[X]??=0,`${X}${++T_[X]}`},nX=(X)=>{let Y=_8[X.kind],Z=Y.applyConfig?.(X.def,X.$.resolvedConfig)??X.def,_={},{meta:G,...W}=Z,$=G===void 0?{}:typeof G==="string"?{description:G}:G,H=LX(W).sort(([J],[z])=>t4(J)?t4(z)?a4(J)-a4(z):1:t4(z)?-1:J<z?-1:1).filter(([J,z])=>{if(J.startsWith("meta.")){let F=J.slice(5);return $[F]=z,!1}return!0});for(let J of H){let z=J[0],F=Y.keys[z];if(!F)return R(`Key ${z} is not valid on ${X.kind} schema`);let O=F.parse?F.parse(J[1],X):J[1];if(O!==V1&&(O!==void 0||F.preserveUndefined))_[z]=O}if(Y.reduce&&!X.prereduced){let J=Y.reduce(_,X.$);if(J){if(J instanceof C)return J.throw();return eJ(J,$)}}return rX({id:X.id,kind:X.kind,inner:_,meta:$,$:X.$})},rX=({id:X,kind:Y,inner:Z,meta:_,$:G,ignoreCache:W})=>{let $=_8[Y],H=LX(Z),Q=[],J={};for(let[j,P]of H){let h=$.keys[j],i=h.serialize??(h.child?aJ:A1);if(J[j]=i(P),h.child===!0){let p=P;if(Q0(p))Q.push(...p);else Q.push(p)}else if(typeof h.child==="function")Q.push(...h.child(P))}if($.finalizeInnerJson)J=$.finalizeInnerJson(J);let z={...J},F={};if(!l1(_))F=d(_,(j,P)=>[j,j==="examples"?P:A1(P)]),z.meta=e2(F,"description",!0);J=e2(J,$.collapsibleKey,!1);let O=JSON.stringify({kind:Y,...J});z=e2(z,$.collapsibleKey,!1);let D=e2(z,$.collapsibleKey,!0),w=JSON.stringify({kind:Y,...z});if(G.nodesByHash[w]&&!W)return G.nodesByHash[w];let A={id:X,kind:Y,impl:$,inner:Z,innerEntries:H,innerJson:J,innerHash:O,meta:_,metaJson:F,json:z,hash:w,collapsibleJson:D,children:Q};if(Y!=="intersection"){for(let j in Z)if(j!=="in"&&j!=="out")A[j]=Z[j]}let x=new q_[Y](A,G);return G.nodesByHash[w]=x},C_=(X,Y)=>{if(X.id===Y)return X;if(E0(a0[Y]))e(`Unexpected attempt to overwrite node id ${Y}`);return rX({id:Y,kind:X.kind,inner:X.inner,meta:X.meta,$:X.$,ignoreCache:!0})},eJ=(X,Y,Z)=>{if(Z&&E0(a0[Z]))e(`Unexpected attempt to overwrite node id ${Z}`);return rX({id:Z??iX(Y.alias??X.kind),kind:X.kind,inner:X.inner,meta:Y,$:X.$})},e2=(X,Y,Z)=>{let _=Object.keys(X);if(_.length===1&&_[0]===Y){let G=X[Y];if(Z)return G;if(_1(G,"object")&&(Object.keys(G).length===1||Array.isArray(G)))return G}return X};var c8=(X,Y,Z)=>{if(X.key!==Y.key)return null;let _=X.key,G=O0(X.value,Y.value,Z),W=X.required||Y.required?"required":"optional";if(G instanceof C)if(W==="optional")G=N.intrinsic.never.internal;else return G.withPrefixKey(X.key,X.required&&Y.required?"required":"optional");if(W==="required")return Z.$.node("required",{key:_,value:G});let $=X.hasDefault()?Y.hasDefault()?X.default===Y.default?X.default:R(sX(X.default,Y.default)):X.default:Y.hasDefault()?Y.default:V1;return Z.$.node("optional",{key:_,value:G,default:$})};class l8 extends R1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=N.intrinsic.object.internal;serializedKey=X4(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=t(this.value.flatRefs.map((X)=>f1([this.key,...X.path],X.node)),f1([this.key],this.value));_transform(X,Y){Y.path.push(this.key);let Z=super._transform(X,Y);return Y.path.pop(),Z}hasDefault(){return"default"in this.inner}traverseAllows=(X,Y)=>{if(this.key in X)return $1(this.key,()=>this.value.traverseAllows(X[this.key],Y),Y);return this.optional};traverseApply=(X,Y)=>{if(this.key in X)$1(this.key,()=>this.value.traverseApply(X[this.key],Y),Y);else if(this.hasKind("required"))Y.errorFromNodeContext(this.errorContext)};compile(X){if(X.if(`${this.serializedKey} in data`,()=>X.traverseKey(this.serializedKey,`data${X.prop(this.key)}`,this.value)),this.hasKind("required"))X.else(()=>X.traversalKind==="Apply"?X.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):X.return(!1));if(X.traversalKind==="Allows")X.return(!0)}}var sX=(X,Y)=>`Invalid intersection of default values ${c(X)} & ${c(Y)}`;var XQ=l({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)},default:{preserveUndefined:!0}},normalize:(X)=>X,reduce:(X,Y)=>{if(Y.resolvedConfig.exactOptionalPropertyTypes===!1){if(!X.value.allows(void 0))return Y.node("optional",{...X,value:X.value.or(k.undefined)},{prereduced:!0})}},defaults:{description:(X)=>`${X.compiledKey}?: ${X.value.description}`},intersections:{optional:c8}});class j_ extends l8{constructor(...X){super(...X);if("default"in this.inner)i8(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:X,...Y}=this.inner;return this.cacheGetter("outProp",this.$.node("required",Y,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${c(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=ZQ(this);defaultValueMorphRef=this.defaultValueMorph&&I0(this.defaultValueMorph)}var o8={implementation:XQ,Node:j_},YQ={},ZQ=(X)=>{if(!X.hasDefault())return;let Y=`{${X.compiledKey}: ${X.value.id} = ${A1(X.default)}}`;return YQ[Y]??=tX(X.key,X.value,X.default)},tX=(X,Y,Z)=>{if(typeof Z==="function")return Y.includesTransform?(G,W)=>{return $1(X,()=>Y(G[X]=Z(),W),W),G}:(G)=>{return G[X]=Z(),G};let _=Y.includesTransform?Y.assert(Z):Z;return _1(_,"object")?(G,W)=>{return $1(X,()=>Y(G[X]=Z,W),W),G}:(G)=>{return G[X]=_,G}},i8=(X,Y,Z)=>{let _=E4(Y);if(_1(Y,"object")&&!_)R(_Q(Z));let G=X.in(_?Y():Y);if(G instanceof W1){if(Z===null)R(`Default ${G.summary}`);let W=G.transform(($)=>$.transform((H)=>({...H,prefixPath:[Z]})));R(`Default for ${W.summary}`)}return Y},_Q=(X)=>{return`Non-primitive default ${X===null?"":typeof X==="number"?`for value at [${X}] `:`for ${X4(X)} `}must be specified as a function like () => ({my: 'object'})`};class w1 extends m8{constructor(X,Y){super(X,Y);Object.defineProperty(this,t0,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(X)=>{let Y=this(X);if(Y instanceof W1)return Y;return{value:Y}},toJSONSchema:(X)=>{if(X.target&&X.target!=="draft-2020-12")return R(`JSONSchema target '${X.target}' is not supported (must be "draft-2020-12")`);if(X.io==="input")return this.in.toJsonSchema();return this.out.toJsonSchema()}}}as(){return this}brand(X){if(X==="")return R(GQ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(X,Y){let Z=this.branches.map(X);return Y?.(Z)??Z}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(X={}){let Y=PX(this.$.resolvedConfig.toJsonSchema,X);Y.useRefs||=this.isCyclic;let Z=typeof Y.dialect==="string"?{$schema:Y.dialect}:{};if(Object.assign(Z,this.toJsonSchemaRecurse(Y)),Y.useRefs)Z.$defs=d(this.references,(_,G)=>G.isRoot()&&!G.alwaysExpandJsonSchema?[G.id,G.toResolvedJsonSchema(Y)]:[]);return Z}toJsonSchemaRecurse(X){if(X.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(X)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(X){let Y=this.innerToJsonSchema(X);return Object.assign(Y,this.metaJson)}intersect(X){let Y=this.$.parseDefinition(X),Z=this.rawIntersect(Y);if(Z instanceof C)return Z;return this.$.finalize(Z)}rawIntersect(X){return H1(this,X,this.$)}toNeverIfDisjoint(){return this}and(X){let Y=this.intersect(X);return Y instanceof C?Y.throw():Y}rawAnd(X){let Y=this.rawIntersect(X);return Y instanceof C?Y.throw():Y}or(X){let Y=this.$.parseDefinition(X);return this.$.finalize(this.rawOr(Y))}rawOr(X){let Y=[...this.branches,...X.branches];return this.$.node("union",Y)}map(X){return this.$.schema(this.applyStructuralOperation("map",[X]))}pick(...X){return this.$.schema(this.applyStructuralOperation("pick",X))}omit(...X){return this.$.schema(this.applyStructuralOperation("omit",X))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let X=this.applyStructuralOperation("keyof",[]).reduce((Y,Z)=>Y.intersect(Z).toNeverIfDisjoint(),N.intrinsic.unknown.internal);if(X.branches.length===0)R(hX(`keyof ${this.expression}`));return this._keyof=this.$.finalize(X)}get props(){if(this.branches.length!==1)return R(WQ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(X){let Y=this.$.parseDefinition(X);return this.$.schema(Y.distribute((Z)=>this.applyStructuralOperation("merge",[S_(Z)??R(P_("merge",Z.expression))])))}applyStructuralOperation(X,Y){return this.distribute((Z)=>{if(Z.equals(N.intrinsic.object)&&X!=="merge")return Z;let _=S_(Z);if(!_)R(P_(X,Z.expression));if(X==="keyof")return _.keyof();if(X==="get")return _.get(...Y);if(X==="props")return _.props;let G=X==="required"?"require":X==="partial"?"optionalize":X;return this.$.node("intersection",{...Z.inner,structure:_[G](...Y)})})}get(...X){if(X[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",X))}extract(X){let Y=this.$.parseDefinition(X);return this.$.schema(this.branches.filter((Z)=>Z.extends(Y)))}exclude(X){let Y=this.$.parseDefinition(X);return this.$.schema(this.branches.filter((Z)=>!Z.extends(Y)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(X){return!(this.intersect(X)instanceof C)}extends(X){let Y=this.intersect(X);return!(Y instanceof C)&&this.equals(Y)}ifExtends(X){return this.extends(X)?this:void 0}subsumes(X){return this.$.parseDefinition(X).extends(this)}configure(X,Y="shallow"){return this.configureReferences(X,Y)}describe(X,Y="shallow"){return this.configure({description:X},Y)}optional(){return[this,"?"]}default(X){return i8(this,X,null),[this,"=",X]}from(X){return this.assert(X)}_pipe(...X){let Y=X.reduce((Z,_)=>Z.rawPipeOnce(_),this);return this.$.finalize(Y)}tryPipe(...X){let Y=X.reduce((Z,_)=>Z.rawPipeOnce(f(_,"root")?_:(G,W)=>{try{return _(G,W)}catch($){return W.error({code:"predicate",predicate:_,actual:`aborted due to error:
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:
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 Q_(Y,_.impliedBasis,this);let W=this.$.node("intersection",{[_.kind]:_}),$=X==="out"?u8(this,W,this.$):H1(this,W,this.$);if($ instanceof C)$.throw();return this.$.finalize($)}onUndeclaredKey(X){let Y=typeof X==="string"?X:X.rule,Z=typeof X==="string"?!1:X.deep;return this.$.finalize(this.transform((_,G)=>_==="structure"?Y==="ignore"?q5(G,{undeclared:1}):{...G,undeclared:Y}:G,Z?void 0:{shouldTransform:(_)=>!r1(r4,_.kind)}))}hasEqualMorphs(X){if(!this.includesTransform&&!X.includesTransform)return!0;if(!t1(this.shallowMorphs,X.shallowMorphs))return!1;if(!t1(this.flatMorphs,X.flatMorphs,{isEqual:(Y,Z)=>Y.propString===Z.propString&&(Y.node.hasKind("morph")&&Z.node.hasKind("morph")?Y.node.hasEqualMorphs(Z.node):Y.node.hasKind("intersection")&&Z.node.hasKind("intersection")?Y.node.structure?.structuralMorphRef===Z.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(X){return this.onUndeclaredKey({rule:X,deep:!0})}filter(X){return this.constrainIn("predicate",X)}divisibleBy(X){return this.constrain("divisor",X)}matching(X){return this.constrain("pattern",X)}atLeast(X){return this.constrain("min",X)}atMost(X){return this.constrain("max",X)}moreThan(X){return this.constrain("min",G8(X))}lessThan(X){return this.constrain("max",G8(X))}atLeastLength(X){return this.constrain("minLength",X)}atMostLength(X){return this.constrain("maxLength",X)}moreThanLength(X){return this.constrain("minLength",G8(X))}lessThanLength(X){return this.constrain("maxLength",G8(X))}exactlyLength(X){return this.constrain("exactLength",X)}atOrAfter(X){return this.constrain("after",X)}atOrBefore(X){return this.constrain("before",X)}laterThan(X){return this.constrain("after",G8(X))}earlierThan(X){return this.constrain("before",G8(X))}}var GQ="Expected a non-empty brand name after #",G8=(X)=>typeof X==="object"&&!(X instanceof Date)?{...X,exclusive:!0}:{rule:X,exclusive:!0},n8=(X,Y)=>f(Y,"root")?f(X,"root")?X.extends(Y):Y.allows(X):f(X,"root")?X.hasUnit(Y):Y===X,S_=(X)=>{if(X.hasKind("morph"))return null;if(X.hasKind("intersection"))return X.inner.structure??(X.basis?.domain==="object"?X.$.bindReference(N.intrinsic.emptyStructure):null);if(X.isBasis()&&X.domain==="object")return X.$.bindReference(N.intrinsic.emptyStructure);return null},WQ=(X)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
- ${X}`,P_=(X,Y)=>`${X} operand must be an object (was ${Y})`;var o1=(X,Y)=>d(i2(X),(Z,_)=>[_,Y]);var $Q=(X)=>typeof X==="string"?{reference:X}:X,v_=(X)=>X instanceof C?N.intrinsic.never.internal:X,HQ=l({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(X)=>X.startsWith("$")?X:`$ark.${X}`},resolve:{}},normalize:$Q,defaults:{description:(X)=>X.reference},intersections:{alias:(X,Y,Z)=>Z.$.lazilyResolve(()=>v_(O0(X.resolution,Y.resolution,Z)),`${X.reference}${Z.pipe?"=>":"&"}${Y.reference}`),...o1("alias",(X,Y,Z)=>{if(Y.isUnknown())return X;if(Y.isNever())return Y;if(Y.isBasis()&&!Y.overlaps(N.intrinsic.object))return C.init("assignability",N.intrinsic.object,Y);return Z.$.lazilyResolve(()=>v_(O0(X.resolution,Y,Z)),`${X.reference}${Z.pipe?"=>":"&"}${Y.id}`)})}});class x_ extends w1{expression=this.reference;structure=void 0;get resolution(){let X=this._resolve();return a0[this.id]=X}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let X=this.reference,Y=a0[X],Z=[];while(f(Y,"context")){if(Z.includes(Y.id))return R(JQ(Y.id,Z));Z.push(Y.id),Y=a0[Y.id]}if(!f(Y,"root"))return e(`Unexpected resolution for reference ${this.reference}
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}
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]=t(Z,X),this.resolution.traverseAllows(X,Y)};traverseApply=(X,Y)=>{let Z=Y.seen[this.reference];if(Z?.includes(X))return;Y.seen[this.reference]=t(Z,X),this.resolution.traverseApply(X,Y)};compile(X){let Y=this.resolutionId;X.if(`ctx.seen.${Y} && ctx.seen.${Y}.includes(data)`,()=>X.return(!0)),X.if(`!ctx.seen.${Y}`,()=>X.line(`ctx.seen.${Y} = []`)),X.line(`ctx.seen.${Y}.push(data)`),X.return(X.invoke(Y))}}var JQ=(X,Y)=>`Alias '${X}' has a shallow resolution cycle: ${[...Y,X].join("->")}`,r8={implementation:HQ,Node:x_};class v4 extends w1{traverseApply=(X,Y)=>{if(!this.traverseAllows(X,Y))Y.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return D4(this.errorContext)}compile(X){if(X.traversalKind==="Allows")X.return(this.compiledCondition);else X.if(this.compiledNegation,()=>X.line(`${X.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var QQ=l({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(X)=>typeof X==="string"?{domain:X}:i4(X,"numberAllowsNaN")&&X.domain!=="number"?R(X6.writeBadAllowNanMessage(X.domain)):X,applyConfig:(X,Y)=>X.numberAllowsNaN===void 0&&X.domain==="number"&&Y.numberAllowsNaN?{...X,numberAllowsNaN:!0}:X,defaults:{description:(X)=>G1[X.domain],actual:(X)=>Number.isNaN(X)?"NaN":G1[x0(X)]},intersections:{domain:(X,Y)=>X.domain==="number"&&Y.domain==="number"?X.numberAllowsNaN?Y:X:C.init("domain",X,Y)}});class f_ extends v4{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(X)=>typeof X==="number"&&!Number.isNaN(X):(X)=>x0(X)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return G1[this.domain]}innerToJsonSchema(X){if(this.domain==="bigint"||this.domain==="symbol")return X.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var X6={implementation:QQ,Node:f_,writeBadAllowNanMessage:(X)=>`numberAllowsNaN may only be specified with domain "number" (was ${X})`};var zQ=l({kind:"intersection",hasAssociatedError:!0,normalize:(X)=>{if(E0(X))return X;let{structure:Y,...Z}=X,_=!!Y,G=Y??{},W=d(Z,($,H)=>{if(f0($,Y_)){if(_)R(`Flattened structure key ${$} cannot be specified alongside a root 'structure' key.`);return G[$]=H,[]}return[$,H]});if(f(G,"constraint")||!l1(G))W.structure=G;return W},finalizeInnerJson:({structure:X,...Y})=>_1(X,"object")?{...X,...Y}:Y,keys:{domain:{child:!0,parse:(X,Y)=>Y.$.node("domain",X)},proto:{child:!0,parse:(X,Y)=>Y.$.node("proto",X)},structure:{child:!0,parse:(X,Y)=>Y.$.node("structure",X),serialize:(X)=>{if(!X.sequence?.minLength)return X.collapsibleJson;let{sequence:Y,...Z}=X.collapsibleJson,{minVariadicLength:_,...G}=Y,W=G.variadic&&Object.keys(G).length===1?G.variadic:G;return{...Z,sequence:W}}},divisor:{child:!0,parse:i0("divisor")},max:{child:!0,parse:i0("max")},min:{child:!0,parse:i0("min")},maxLength:{child:!0,parse:i0("maxLength")},minLength:{child:!0,parse:i0("minLength")},exactLength:{child:!0,parse:i0("exactLength")},before:{child:!0,parse:i0("before")},after:{child:!0,parse:i0("after")},pattern:{child:!0,parse:i0("pattern")},predicate:{child:!0,parse:i0("predicate")}},reduce:(X,Y)=>h_({},X,{$:Y,invert:!1,pipe:!1}),defaults:{description:(X)=>{if(X.children.length===0)return"unknown";if(X.structure)return X.structure.description;let Y=[];if(X.basis&&!X.refinements.some((Z)=>Z.impl.obviatesBasisDescription))Y.push(X.basis.description);if(X.refinements.length){let Z=X.refinements.toSorted((_,G)=>_.kind==="min"&&G.kind==="max"?-1:0).map((_)=>_.description);Y.push(...Z)}if(X.inner.predicate)Y.push(...X.inner.predicate.map((Z)=>Z.description));return Y.join(" and ")},expected:(X)=>` \u25E6 ${X.errors.map((Y)=>Y.expected).join(`
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(`
30
30
  \u25E6 `)}`,problem:(X)=>`(${X.actual}) must be...
31
- ${X.expected}`},intersections:{intersection:(X,Y,Z)=>h_(X.inner,Y.inner,Z),...o1("intersection",(X,Y,Z)=>{if(X.children.length===0)return Y;let{domain:_,proto:G,...W}=X.inner,$=G??_,H=$?O0($,Y,Z):Y;return H instanceof C?H:X?.basis?.equals(H)?X:X.$.node("intersection",{...W,[H.kind]:H},{prereduced:!0})})}});class k_ extends w1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((X)=>X.isRefinement());structure=this.inner.structure;expression=FQ(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(X){return this.children.reduce((Y,Z)=>Z.isBasis()?Z.toJsonSchemaRecurse(X):Z.reduceJsonSchema(Y,X),{})}traverseAllows=(X,Y)=>this.children.every((Z)=>Z.traverseAllows(X,Y));traverseApply=(X,Y)=>{let Z=Y.currentErrorCount;if(this.basis){if(this.basis.traverseApply(X,Y),Y.currentErrorCount>Z)return}if(this.refinements.length){for(let _=0;_<this.refinements.length-1;_++)if(this.refinements[_].traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>Z)return;if(this.refinements.at(-1).traverseApply(X,Y),Y.currentErrorCount>Z)return}if(this.structure){if(this.structure.traverseApply(X,Y),Y.currentErrorCount>Z)return}if(this.inner.predicate){for(let _=0;_<this.inner.predicate.length-1;_++)if(this.inner.predicate[_].traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>Z)return;this.inner.predicate.at(-1).traverseApply(X,Y)}};compile(X){if(X.traversalKind==="Allows"){for(let Y of this.children)X.check(Y);X.return(!0);return}if(X.initializeErrorCount(),this.basis){if(X.check(this.basis),this.children.length>1)X.returnIfFail()}if(this.refinements.length){for(let Y=0;Y<this.refinements.length-1;Y++)X.check(this.refinements[Y]),X.returnIfFailFast();if(X.check(this.refinements.at(-1)),this.structure||this.inner.predicate)X.returnIfFail()}if(this.structure){if(X.check(this.structure),this.inner.predicate)X.returnIfFail()}if(this.inner.predicate){for(let Y=0;Y<this.inner.predicate.length-1;Y++)X.check(this.inner.predicate[Y]),X.returnIfFail();X.check(this.inner.predicate.at(-1))}}}var aX={implementation:zQ,Node:k_},FQ=(X)=>{let Y=X.structure?.expression||`${X.basis&&!X.refinements.some((Z)=>Z.impl.obviatesBasisExpression)?X.basis.nestableExpression+" ":""}${X.refinements.map((Z)=>Z.expression).join(" & ")}`||"unknown";if(Y==="Array == 0")Y="[]";return Y},h_=(X,Y,Z)=>{let _={},G=X.proto??X.domain,W=Y.proto??Y.domain,$=G?W?O0(G,W,Z):G:W;if($ instanceof C)return $;if($)_[$.kind]=$;return X8({kind:"intersection",baseInner:_,l:Y8(X),r:Y8(Y),roots:[],ctx:Z})};var UQ=l({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)},morphs:{parse:U4,serialize:(X)=>X.map((Y)=>f(Y,"root")?Y.json:I0(Y))},declaredIn:{child:!1,serialize:(X)=>X.json},declaredOut:{child:!1,serialize:(X)=>X.json}},normalize:(X)=>X,defaults:{description:(X)=>`a morph from ${X.in.description} to ${X.out?.description??"unknown"}`},intersections:{morph:(X,Y,Z)=>{if(!X.hasEqualMorphs(Y))return R(EQ(X.expression,Y.expression));let _=O0(X.in,Y.in,Z);if(_ instanceof C)return _;let G={morphs:X.morphs};if(X.declaredIn||Y.declaredIn){let W=O0(X.in,Y.in,Z);if(W instanceof C)return W.throw();else G.declaredIn=W}if(X.declaredOut||Y.declaredOut){let W=O0(X.out,Y.out,Z);if(W instanceof C)return W.throw();else G.declaredOut=W}return _.distribute((W)=>Z.$.node("morph",{...G,in:W}),Z.$.parseSchema)},...o1("morph",(X,Y,Z)=>{let _=X.inner.in?O0(X.inner.in,Y,Z):Y;return _ instanceof C?_:_.equals(X.inner.in)?X:Z.$.node("morph",{...X.inner,in:_})})}});class b_ extends w1{serializedMorphs=this.morphs.map(I0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=f(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??N.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??N.intrinsic.unknown.internal}declareIn(X){return this.$.node("morph",{...this.inner,declaredIn:X})}declareOut(X){return this.$.node("morph",{...this.inner,declaredOut:X})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(X){return X.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(X),out:this.introspectableOut?.toJsonSchemaRecurse(X)??null})}compile(X){if(X.traversalKind==="Allows"){if(!this.introspectableIn)return;X.return(X.invoke(this.introspectableIn));return}if(this.introspectableIn)X.line(X.invoke(this.introspectableIn));X.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(X,Y)=>!this.introspectableIn||this.introspectableIn.traverseAllows(X,Y);traverseApply=(X,Y)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(X,Y);Y.queueMorphs(this.morphs)};hasEqualMorphs(X){return t1(this.morphs,X.morphs,{isEqual:(Y,Z)=>Y===Z||f(Y,"root")&&f(Z,"root")&&Y.equals(Z)})}}var eX={implementation:UQ,Node:b_},EQ=(X,Y)=>`The intersection of distinct morphs at a single path is indeterminate:
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:
32
32
  Left: ${X}
33
- Right: ${Y}`;var OQ=l({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(X)=>P8(X)??A1(X)},dateAllowsInvalid:{}},normalize:(X)=>{let Y=typeof X==="string"?{proto:j4[X]}:typeof X==="function"?E0(X)?X:{proto:X}:typeof X.proto==="string"?{...X,proto:j4[X.proto]}:X;if(typeof Y.proto!=="function")R(s8.writeInvalidSchemaMessage(Y.proto));if(i4(Y,"dateAllowsInvalid")&&Y.proto!==Date)R(s8.writeBadInvalidDateMessage(Y.proto));return Y},applyConfig:(X,Y)=>{if(X.dateAllowsInvalid===void 0&&X.proto===Date&&Y.dateAllowsInvalid)return{...X,dateAllowsInvalid:!0};return X},defaults:{description:(X)=>X.builtinName?v5[X.builtinName]:`an instance of ${X.proto.name}`,actual:(X)=>X instanceof Date&&X.toString()==="Invalid Date"?"an invalid Date":S8(X)},intersections:{proto:(X,Y)=>X.proto===Date&&Y.proto===Date?X.dateAllowsInvalid?Y:X:NX(X.proto,Y.proto)?X:NX(Y.proto,X.proto)?Y:C.init("proto",X,Y),domain:(X,Y)=>Y.domain==="object"?X:C.init("domain",N.intrinsic.object.internal,Y)}});class y_ extends v4{builtinName=P8(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(X)=>X instanceof Date&&X.toString()!=="Invalid Date":(X)=>X instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(X){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return X.fallback.date?.({code:"date",base:{}})??X.fallback.proto({code:"proto",base:{},proto:this.proto});default:return X.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var s8={implementation:OQ,Node:y_,writeBadInvalidDateMessage:(X)=>`dateAllowsInvalid may only be specified with constructor Date (was ${X.name})`,writeInvalidSchemaMessage:(X)=>`instanceOf operand must be a function (was ${x0(X)})`};var VQ=l({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(X,Y)=>{let Z=[];for(let _ of X){let G=f(_,"root")?_.branches:Y.$.parseSchema(_).branches;for(let W of G)if(W.hasKind("morph")){let $=Z.findIndex((H)=>H.hasKind("morph")&&H.hasEqualMorphs(W));if($===-1)Z.push(W);else{let H=Z[$];Z[$]=Y.$.node("morph",{...H.inner,in:H.in.rawOr(W.in)})}}else Z.push(W)}if(!Y.def.ordered)Z.sort((_,G)=>_.hash<G.hash?-1:1);return Z}}},normalize:(X)=>Q0(X)?{branches:X}:X,reduce:(X,Y)=>{let Z=BQ(X);if(Z.length===1)return Z[0];if(Z.length===X.branches.length)return;return Y.node("union",{...X,branches:Z},{prereduced:!0})},defaults:{description:(X)=>X.distribute((Y)=>Y.description,W8),expected:(X)=>{let Y=K5(X.errors,"propString"),Z=Object.entries(Y).map(([_,G])=>{let W=[];for(let Q of G)c1(W,Q.expected);let $=W8(W),H=G.every((Q)=>Q.actual===G[0].actual)?G[0].actual:c(G[0].data);return`${_&&`${_} `}must be ${$}${H&&` (was ${H})`}`});return W8(Z)},problem:(X)=>X.expected,message:(X)=>X.problem},intersections:{union:(X,Y,Z)=>{if(X.isNever!==Y.isNever)return C.init("presence",X,Y);let _;if(X.ordered){if(Y.ordered)R(CQ(X.expression,Y.expression));if(_=XY(Y.branches,X.branches,Z),_ instanceof C)_.invert()}else _=XY(X.branches,Y.branches,Z);if(_ instanceof C)return _;return Z.$.parseSchema(X.ordered||Y.ordered?{branches:_,ordered:!0}:{branches:_})},...o1("union",(X,Y,Z)=>{let _=XY(X.branches,[Y],Z);if(_ instanceof C)return _;if(_.length===1)return _[0];return Z.$.parseSchema(X.ordered?{branches:_,ordered:!0}:{branches:_})})}});class m_ extends w1{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let X=[],Y=-1;for(let Z of this.branches){if(Z.hasKind("unit")&&Z.domain==="boolean"){if(Y===-1)Y=X.length,X.push(Z);else X[Y]=N.intrinsic.boolean;continue}X.push(Z)}return X}unitBranches=this.branches.filter((X)=>X.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?NQ(this.discriminant):null;expression=this.distribute((X)=>X.nestableExpression,KQ);createBranchedOptimisticRootApply(){return(X,Y)=>{let Z=this.traverseOptimistic(X);if(Z!==V1)return Z;let _=new x1(X,this.$.resolvedConfig);return this.traverseApply(X,_),_.finalize(Y)}}get shallowMorphs(){return this.branches.reduce((X,Y)=>c1(X,Y.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((X)=>X.defaultShortDescription,W8)}innerToJsonSchema(X){if(this.branchGroups.length===1&&this.branchGroups[0].equals(N.intrinsic.boolean))return{type:"boolean"};let Y=this.branchGroups.map((Z)=>Z.toJsonSchemaRecurse(X));if(Y.every((Z)=>Object.keys(Z).length===1&&i4(Z,"const")))return{enum:Y.map((Z)=>Z.const)};return{anyOf:Y}}traverseAllows=(X,Y)=>this.branches.some((Z)=>Z.traverseAllows(X,Y));traverseApply=(X,Y)=>{let Z=[];for(let _=0;_<this.branches.length;_++){if(Y.pushBranch(),this.branches[_].traverseApply(X,Y),!Y.hasError()){if(this.branches[_].includesTransform)return Y.queuedMorphs.push(...Y.popBranch().queuedMorphs);return Y.popBranch()}Z.push(Y.popBranch().error)}Y.errorFromNodeContext({code:"union",errors:Z,meta:this.meta})};traverseOptimistic=(X)=>{for(let Y=0;Y<this.branches.length;Y++){let Z=this.branches[Y];if(Z.traverseAllows(X)){if(Z.contextFreeMorph)return Z.contextFreeMorph(X);return X}}return V1};compile(X){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(X);let Y=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")Y=`typeof ${Y} === "object" ? ${Y} === null ? "null" : "object" : typeof ${Y} === "function" ? "object" : typeof ${Y}`;let Z=this.discriminant.cases,_=Object.keys(Z),{optimistic:G}=X;if(X.optimistic=!1,X.block(`switch(${Y})`,()=>{for(let J in Z){let z=Z[J],F=J==="default"?J:`case ${J}`;X.line(`${F}: return ${z===!0?G?X.data:z:G?`${X.invoke(z)} ? ${z.contextFreeMorph?`${I0(z.contextFreeMorph)}(${X.data})`:X.data} : "${V1}"`:X.invoke(z)}`)}return X}),X.traversalKind==="Allows"){X.return(G?`"${V1}"`:!1);return}let W=W8(this.discriminant.kind==="domain"?_.map((J)=>{let z=J.slice(1,-1);return z==="function"?G1.object:G1[z]}):_),$=this.discriminant.path.map((J)=>typeof J==="symbol"?I0(J):JSON.stringify(J)),H=JSON.stringify(W),Q=this.discriminant.kind==="domain"?`${RQ}[${Y}]`:`${wQ}(${Y})`;X.line(`ctx.errorFromNodeContext({
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({
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?`${I0(Z.contextFreeMorph)}(${X.data})`:X.data:!0));X.return(Y?`"${V1}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let G=d(this.unitBranches,(W,$)=>[`${$.in.serializedValue}`,$.hasKind("morph")?$:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:G}}let X=[];for(let G=0;G<this.branches.length-1;G++){let W=this.branches[G];for(let $=G+1;$<this.branches.length;$++){let H=this.branches[$],Q=H1(W.in,H.in,W.$);if(!(Q instanceof C))continue;for(let J of Q){if(!J.kind||J.optional)continue;let z,F;if(J.kind==="domain"){let{l:D,r:w}=J;z=`"${typeof D==="string"?D:D.domain}"`,F=`"${typeof w==="string"?w:w.domain}"`}else if(J.kind==="unit")z=J.l.serializedValue,F=J.r.serializedValue;else continue;let O=X.find((D)=>t1(D.path,J.path)&&D.kind===J.kind);if(!O)X.push({kind:J.kind,cases:{[z]:{branchIndices:[G],condition:J.l},[F]:{branchIndices:[$],condition:J.r}},path:J.path});else{if(O.cases[z])O.cases[z].branchIndices=c1(O.cases[z].branchIndices,G);else O.cases[z]??={branchIndices:[G],condition:J.l};if(O.cases[F])O.cases[F].branchIndices=c1(O.cases[F].branchIndices,$);else O.cases[F]??={branchIndices:[$],condition:J.r}}}}}let Y=this.ordered?MQ(X,this.branches):X;if(!Y.length)return null;let Z=DQ(Y,this),_={};for(let G in Z.best.cases){let W=LQ(Z,G);if(W===null){_[G]=!0;continue}if(W.length===this.branches.length)return null;if(this.ordered)W.sort((Q,J)=>Q.originalIndex-J.originalIndex);let $=W.map((Q)=>Q.branch),H=$.length===1?$[0]:this.$.node("union",this.ordered?{branches:$,ordered:!0}:$);Object.assign(this.referencesById,H.referencesById),_[G]=H}if(Z.defaultEntries.length){let G=Z.defaultEntries.map((W)=>W.branch);_.default=this.$.node("union",this.ordered?{branches:G,ordered:!0}:G,{prereduced:!0}),Object.assign(this.referencesById,_.default.referencesById)}return Object.assign(Z.location,{cases:_})}}var DQ=(X,Y)=>{let Z=X.sort((W,$)=>Object.keys($.cases).length-Object.keys(W.cases).length)[0],_={kind:Z.kind,path:Z.path,optionallyChainedPropString:u_(Z.path)},G=Y.branches.map((W,$)=>({originalIndex:$,branch:W}));return{best:Z,location:_,defaultEntries:G,node:Y}},LQ=(X,Y)=>{let Z=X.best.cases[Y],_=AQ(Z.condition,X.location.path,X.node.$),G=[],W=[];for(let $=0;$<X.defaultEntries.length;$++){let H=X.defaultEntries[$];if(Z.branchIndices.includes(H.originalIndex)){let Q=g_(X.node.branches[H.originalIndex],X.location);if(Q===null)G=null;else G?.push({originalIndex:H.originalIndex,branch:Q})}else if(H.branch.hasKind("alias")&&_.hasKind("domain")&&_.domain==="object")G?.push(H);else{if(H.branch.in.overlaps(_)){let Q=g_(H.branch,X.location);G?.push({originalIndex:H.originalIndex,branch:Q})}W.push(H)}}return X.defaultEntries=W,G},MQ=(X,Y)=>{return X.filter((_)=>{let G=Object.values(_.cases).map((W)=>W.branchIndices);for(let W=0;W<G.length-1;W++){let $=G[W];for(let H=W+1;H<G.length;H++){let Q=G[H];for(let J of $)for(let z of Q)if(J>z){if(Y[J].overlaps(Y[z]))return!1}}}return!0})},AQ=(X,Y,Z)=>{let _=X==="undefined"?Z.node("unit",{unit:void 0}):X==="null"?Z.node("unit",{unit:null}):X==="boolean"?Z.units([!0,!1]):X;for(let G=Y.length-1;G>=0;G--){let W=Y[G];_=Z.node("intersection",typeof W==="number"?{proto:"Array",sequence:[...N5(W).map(($)=>({})),_]}:{domain:"object",required:[{key:W,value:_}]})}return _},u_=(X)=>X.reduce((Y,Z)=>Y+jX(Z,!0),"data"),RQ=I0(B5),wQ=I0(c),YY={implementation:VQ,Node:m_},NQ=(X)=>({kind:X.kind,path:X.path.map((Y)=>typeof Y==="string"?Y:X4(Y)),cases:d(X.cases,(Y,Z)=>[Y,Z===!0?Z:Z.hasKind("union")&&Z.discriminantJson?Z.discriminantJson:Z.json])}),IQ={delimiter:" | ",finalDelimiter:" | "},KQ=(X)=>W8(X,IQ),W8=(X,Y)=>{let Z=Y?.delimiter??", ",_=Y?.finalDelimiter??" or ";if(X.length===0)return"never";if(X.length===1)return X[0];if(X.length===2&&X[0]==="false"&&X[1]==="true"||X[0]==="true"&&X[1]==="false")return"boolean";let G={},W=X.filter((H)=>G[H]?!1:G[H]=!0),$=W.pop();return`${W.join(Z)}${W.length?_:""}${$}`},XY=(X,Y,Z)=>{let _=Y.map(()=>[]);for(let W=0;W<X.length;W++){let $={};for(let H=0;H<Y.length;H++){if(_[H]===null)continue;if(X[W].equals(Y[H])){_[H]=null,$={};break}let Q=O0(X[W],Y[H],Z);if(Q instanceof C)continue;if(Q.equals(X[W])){_[H].push(X[W]),$={};break}if(Q.equals(Y[H]))_[H]=null;else $[H]=Q}for(let H in $)_[H][W]=$[H]}let G=_.flatMap((W,$)=>W?.flatMap((H)=>H.branches)??Y[$]);return G.length===0?C.init("union",X,Y):G},BQ=({branches:X,ordered:Y})=>{if(X.length<2)return X;let Z=X.map(()=>!0);for(let _=0;_<X.length;_++)for(let G=_+1;G<X.length&&Z[_]&&Z[G];G++){if(X[_].equals(X[G])){Z[G]=!1;continue}let W=H1(X[_].in,X[G].in,X[0].$);if(W instanceof C)continue;if(!Y)TQ(X[_],X[G]);if(W.equals(X[_].in))Z[_]=!!Y;else if(W.equals(X[G].in))Z[G]=!1}return X.filter((_,G)=>Z[G])},TQ=(X,Y)=>{if(!X.includesTransform&&!Y.includesTransform)return;if(!t1(X.shallowMorphs,Y.shallowMorphs))R(p_(X.expression,Y.expression));if(!t1(X.flatMorphs,Y.flatMorphs,{isEqual:(Z,_)=>Z.propString===_.propString&&(Z.node.hasKind("morph")&&_.node.hasKind("morph")?Z.node.hasEqualMorphs(_.node):Z.node.hasKind("intersection")&&_.node.hasKind("intersection")?Z.node.structure?.structuralMorphRef===_.node.structure?.structuralMorphRef:!1)}))R(p_(X.expression,Y.expression))},g_=(X,Y)=>X.transform((Z,_)=>{if(Z==="domain"||Z==="unit")return null;return _},{shouldTransform:(Z,_)=>{let G=u_(_.path);if(!Y.optionallyChainedPropString.startsWith(G))return!1;if(Z.hasKind("domain")&&Z.domain==="object")return!0;if((Z.hasKind("domain")||Y.kind==="unit")&&G===Y.optionallyChainedPropString)return!0;return Z.children.length!==0&&Z.kind!=="index"}}),p_=(X,Y)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
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:
40
40
  Left: ${X}
41
- Right: ${Y}`,CQ=(X,Y)=>`The intersection of two ordered unions is indeterminate:
41
+ Right: ${Y}`,TQ=(X,Y)=>`The intersection of two ordered unions is indeterminate:
42
42
  Left: ${X}
43
- Right: ${Y}`;var qQ=l({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(X)=>X instanceof Date?X.toISOString():A1(X)}},normalize:(X)=>X,defaults:{description:(X)=>c(X.unit),problem:({expected:X,actual:Y})=>`${X===Y?`must be reference equal to ${X} (serialized to the same value)`:`must be ${X} (was ${Y})`}`},intersections:{unit:(X,Y)=>C.init("unit",X,Y),...o1("unit",(X,Y)=>{if(Y.allows(X.unit))return X;let Z=Y.hasKind("intersection")?Y.basis:Y;if(Z){let _=Z.hasKind("domain")?Z:N.intrinsic.object;if(X.domain!==_.domain){let G=X.domain==="undefined"||X.domain==="null"||X.domain==="boolean"?X.domain:N.intrinsic[X.domain];return C.init("domain",G,_)}}return C.init("assignability",X,Y.hasKind("intersection")?Y.children.find((_)=>!_.allows(X.unit)):Y)})}});class c_ extends v4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=d_(this.unit,this.serializedValue);compiledNegation=d_(this.unit,this.serializedValue,"negated");expression=c(this.unit);domain=x0(this.unit);get defaultShortDescription(){return this.domain==="object"?G1.object:this.description}innerToJsonSchema(X){return this.unit===null?{type:"null"}:N.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:X.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(X)=>X instanceof Date&&X.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(X)=>Number.isNaN(X):(X)=>X===this.unit}var ZY={implementation:qQ,Node:c_},d_=(X,Y,Z)=>{if(X instanceof Date){let _=`data instanceof Date && data.toISOString() === ${Y}`;return Z?`!(${_})`:_}if(Number.isNaN(X))return`${Z?"!":""}Number.isNaN(data)`;return`data ${Z?"!":"="}== ${Y}`};var jQ=l({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(X,Y)=>{let Z=Y.$.parseSchema(X);if(!Z.extends(N.intrinsic.key))return R(PQ(Z.expression));let _=Z.branches.filter((G)=>G.hasKind("unit"));if(_.length)return R(SQ(_.map((G)=>c(G.unit))));return Z}},value:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)}},normalize:(X)=>X,defaults:{description:(X)=>`[${X.signature.expression}]: ${X.value.description}`},intersections:{index:(X,Y,Z)=>{if(X.signature.equals(Y.signature)){let _=O0(X.value,Y.value,Z),G=_ instanceof C?N.intrinsic.never.internal:_;return Z.$.node("index",{signature:X.signature,value:G})}if(X.signature.extends(Y.signature)&&X.value.subsumes(Y.value))return Y;if(Y.signature.extends(X.signature)&&Y.value.subsumes(X.value))return X;return null}}});class l_ extends R1{impliedBasis=N.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=t(this.value.flatRefs.map((X)=>f1([this.signature,...X.path],X.node)),f1([this.signature],this.value));traverseAllows=(X,Y)=>q4(X).every((Z)=>{if(this.signature.traverseAllows(Z[0],Y))return $1(Z[0],()=>this.value.traverseAllows(Z[1],Y),Y);return!0});traverseApply=(X,Y)=>{for(let Z of q4(X))if(this.signature.traverseAllows(Z[0],Y))$1(Z[0],()=>this.value.traverseApply(Z[1],Y),Y)};_transform(X,Y){Y.path.push(this.signature);let Z=super._transform(X,Y);return Y.path.pop(),Z}compile(){}}var _Y={implementation:jQ,Node:l_},SQ=(X)=>`Index keys ${X.join(", ")} should be specified as named props.`,PQ=(X)=>`Indexed key definition '${X}' must be a string or symbol`;var vQ=l({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)}},normalize:(X)=>X,defaults:{description:(X)=>`${X.compiledKey}: ${X.value.description}`,expected:(X)=>X.missingValueDescription,actual:()=>"missing"},intersections:{required:c8,optional:c8}});class o_ extends l8{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=D4(this.errorContext)}var GY={implementation:vQ,Node:o_};var xQ=l({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>Y.$.parseSchema(Z))}},optionals:{child:!0,parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>Y.$.parseSchema(Z))}},defaultables:{child:(X)=>X.map((Y)=>Y[0]),parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>{let _=Y.$.parseSchema(Z[0]);return i8(_,Z[1],null),[_,Z[1]]})},serialize:(X)=>X.map((Y)=>[Y[0].collapsibleJson,A1(Y[1])])},variadic:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X,Y)},minVariadicLength:{parse:(X)=>X===0?void 0:X},postfix:{child:!0,parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>Y.$.parseSchema(Z))}}},normalize:(X)=>{if(typeof X==="string")return{variadic:X};if("variadic"in X||"prefix"in X||"defaultables"in X||"optionals"in X||"postfix"in X||"minVariadicLength"in X){if(X.postfix?.length){if(!X.variadic)return R(bQ);if(X.optionals?.length||X.defaultables?.length)return R($Y)}if(X.minVariadicLength&&!X.variadic)return R("minVariadicLength may not be specified without a variadic element");return X}return{variadic:X}},reduce:(X,Y)=>{let Z=X.minVariadicLength??0,_=X.prefix?.slice()??[],G=X.defaultables?.slice()??[],W=X.optionals?.slice()??[],$=X.postfix?.slice()??[];if(X.variadic){while(W.at(-1)?.equals(X.variadic))W.pop();if(W.length===0&&G.length===0)while(_.at(-1)?.equals(X.variadic))_.pop(),Z++;while($[0]?.equals(X.variadic))$.shift(),Z++}else if(W.length===0&&G.length===0)_.push(...$.splice(0));if(Z!==X.minVariadicLength||X.prefix&&X.prefix.length!==_.length)return Y.node("sequence",{...X,prefix:_,defaultables:G,optionals:W,postfix:$,minVariadicLength:Z},{prereduced:!0})},defaults:{description:(X)=>{if(X.isVariadicOnly)return`${X.variadic.nestableExpression}[]`;return`[${X.tuple.map((Z)=>Z.kind==="defaultables"?`${Z.node.nestableExpression} = ${c(Z.default)}`:Z.kind==="optionals"?`${Z.node.nestableExpression}?`:Z.kind==="variadic"?`...${Z.node.nestableExpression}[]`:Z.node.expression).join(", ")}]`}},intersections:{sequence:(X,Y,Z)=>{let _=t8({l:X.tuple,r:Y.tuple,disjoint:new C,result:[],fixedVariants:[],ctx:Z}),G=_.disjoint.length===0?[_,..._.fixedVariants]:_.fixedVariants;return G.length===0?_.disjoint:G.length===1?Z.$.node("sequence",i_(G[0].result)):Z.$.node("union",G.map((W)=>({proto:Array,sequence:i_(W.result)})))}}});class n_ extends R1{impliedBasis=N.intrinsic.Array.internal;tuple=kQ(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((X)=>{if(X.kind==="defaultables"||X.kind==="optionals")return this.defaultablesAndOptionals.push(X.node),!0;return X.kind==="prefix"});variadicOrPostfix=s1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return xX(this.flatRefs,this.prevariadic.flatMap((X,Y)=>t(X.node.flatRefs.map((Z)=>f1([`${Y}`,...Z.path],Z.node)),f1([`${Y}`],X.node)))),xX(this.flatRefs,this.variadicOrPostfix.flatMap((X)=>t(X.flatRefs.map((Y)=>f1([N.intrinsic.nonNegativeIntegerString.internal,...Y.path],Y.node)),f1([N.intrinsic.nonNegativeIntegerString.internal],X)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=hQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?I0(this.defaultValueMorphs):void 0;elementAtIndex(X,Y){if(Y<this.prevariadic.length)return this.tuple[Y];let Z=X.length-this.postfixLength;if(Y>=Z)return{kind:"postfix",node:this.postfix[Y-Z]};return{kind:"variadic",node:this.variadic??e(`Unexpected attempt to access index ${Y} on ${this}`)}}traverseAllows=(X,Y)=>{for(let Z=0;Z<X.length;Z++)if(!this.elementAtIndex(X,Z).node.traverseAllows(X[Z],Y))return!1;return!0};traverseApply=(X,Y)=>{let Z=0;for(;Z<X.length;Z++)$1(Z,()=>this.elementAtIndex(X,Z).node.traverseApply(X[Z],Y),Y)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(X){if(this.prefix)for(let[Y,Z]of this.prefix.entries())X.traverseKey(`${Y}`,`data[${Y}]`,Z);for(let[Y,Z]of this.defaultablesAndOptionals.entries()){let _=`${Y+this.prefixLength}`;X.if(`${_} >= ${X.data}.length`,()=>X.traversalKind==="Allows"?X.return(!0):X.return()),X.traverseKey(_,`data[${_}]`,Z)}if(this.variadic){if(this.postfix)X.const("firstPostfixIndex",`${X.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(X.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>X.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Y,Z]of this.postfix.entries()){let _=`firstPostfixIndex + ${Y}`;X.traverseKey(_,`data[${_}]`,Z)}}if(X.traversalKind==="Allows")X.return(!0)}_transform(X,Y){Y.path.push(N.intrinsic.nonNegativeIntegerString.internal);let Z=super._transform(X,Y);return Y.path.pop(),Z}expression=this.description;reduceJsonSchema(X,Y){if(this.prevariadic.length)X.prefixItems=this.prevariadic.map((Z)=>{let _=Z.node.toJsonSchemaRecurse(Y);if(Z.kind==="defaultables"){let G=typeof Z.default==="function"?Z.default():Z.default;_.default=N.intrinsic.jsonData.allows(G)?G:Y.fallback.defaultValue({code:"defaultValue",base:_,value:G})}return _});if(this.minLength)X.minItems=this.minLength;if(this.variadic){let Z=Object.assign(X,{items:this.variadic.toJsonSchemaRecurse(Y)});if(this.maxLength)Z.maxItems=this.maxLength;if(this.postfix){let _=this.postfix.map((G)=>G.toJsonSchemaRecurse(Y));X=Y.fallback.arrayPostfix({code:"arrayPostfix",base:Z,elements:_})}}else X.items=!1,delete X.maxItems;return X}}var fQ={},hQ=(X)=>{if(!X.defaultables)return[];let Y=[],Z="[",_=X.prefixLength+X.defaultablesLength-1;for(let G=X.prefixLength;G<=_;G++){let[W,$]=X.defaultables[G-X.prefixLength];Y.push(tX(G,W,$)),Z+=`${G}: ${W.id} = ${A1($)}, `}return Z+="]",fQ[Z]??=Y},WY={implementation:xQ,Node:n_},kQ=(X)=>{let Y=[];if(X.prefix)for(let Z of X.prefix)Y.push({kind:"prefix",node:Z});if(X.defaultables)for(let[Z,_]of X.defaultables)Y.push({kind:"defaultables",node:Z,default:_});if(X.optionals)for(let Z of X.optionals)Y.push({kind:"optionals",node:Z});if(X.variadic)Y.push({kind:"variadic",node:X.variadic});if(X.postfix)for(let Z of X.postfix)Y.push({kind:"postfix",node:Z});return Y},i_=(X)=>X.reduce((Y,Z)=>{if(Z.kind==="variadic")Y.variadic=Z.node;else if(Z.kind==="defaultables")Y.defaultables=t(Y.defaultables,[[Z.node,Z.default]]);else Y[Z.kind]=t(Y[Z.kind],Z.node);return Y},{}),$Y="A postfix required element cannot follow an optional or defaultable element",bQ="A postfix element requires a variadic element",t8=(X)=>{let[Y,...Z]=X.l,[_,...G]=X.r;if(!Y||!_)return X;let W=Z.at(-1)?.kind==="postfix",$=G.at(-1)?.kind==="postfix",H=Y.kind==="prefix"||_.kind==="prefix"?"prefix":Y.kind==="postfix"||_.kind==="postfix"?"postfix":Y.kind==="variadic"&&_.kind==="variadic"?"variadic":W||$?"prefix":Y.kind==="defaultables"||_.kind==="defaultables"?"defaultables":"optionals";if(Y.kind==="prefix"&&_.kind==="variadic"&&$){let F=t8({...X,fixedVariants:[],r:G.map((O)=>({...O,kind:"prefix"}))});if(F.disjoint.length===0)X.fixedVariants.push(F)}else if(_.kind==="prefix"&&Y.kind==="variadic"&&W){let F=t8({...X,fixedVariants:[],l:Z.map((O)=>({...O,kind:"prefix"}))});if(F.disjoint.length===0)X.fixedVariants.push(F)}let Q=O0(Y.node,_.node,X.ctx);if(Q instanceof C)if(H==="prefix"||H==="postfix")X.disjoint.push(...Q.withPrefixKey(H==="prefix"?X.result.length:`-${Z.length+1}`,"required")),X.result=[...X.result,{kind:H,node:N.intrinsic.never.internal}];else if(H==="optionals"||H==="defaultables")return X;else return t8({...X,fixedVariants:[],l:Z.map((F)=>({...F,kind:"prefix"})),r:Z.map((F)=>({...F,kind:"prefix"}))});else if(H==="defaultables"){if(Y.kind==="defaultables"&&_.kind==="defaultables"&&Y.default!==_.default)R(sX(Y.default,_.default));X.result=[...X.result,{kind:H,node:Q,default:Y.kind==="defaultables"?Y.default:_.kind==="defaultables"?_.default:e(`Unexpected defaultable intersection from ${Y.kind} and ${_.kind} elements.`)}]}else X.result=[...X.result,{kind:H,node:Q}];let J=X.l.length,z=X.r.length;if(Y.kind!=="variadic"||J>=z&&(_.kind==="variadic"||z===1))X.l=Z;if(_.kind!=="variadic"||z>=J&&(Y.kind==="variadic"||J===1))X.r=G;return t8(X)};var t_=(X)=>(Y)=>{if(Y.props.length||Y.index){let Z=Y.index?.map((G)=>G[X])??[];for(let G of Y.props)Z.push(G[X]);if(Y.undeclared)Z.push(`+ (undeclared): ${Y.undeclared}`);let _=`{ ${Z.join(", ")} }`;return Y.sequence?`${_} & ${Y.sequence.description}`:_}return Y.sequence?.description??"{}"},yQ=t_("description"),gQ=t_("expression"),r_=(X,Y,Z)=>{let _=X.required?"required":"optional";if(!Y.signature.allows(X.key))return null;let G=H1(X.value,Y.value,Z);if(G instanceof C)return _==="optional"?Z.node("optional",{key:X.key,value:N.intrinsic.never.internal}):G.withPrefixKey(X.key,X.kind);return null},pQ=l({kind:"structure",hasAssociatedError:!1,normalize:(X)=>X,applyConfig:(X,Y)=>{if(!X.undeclared&&Y.onUndeclaredKey!=="ignore")return{...X,undeclared:Y.onUndeclaredKey};return X},keys:{required:{child:!0,parse:i0("required"),reduceIo:(X,Y,Z)=>{Y.required=t(Y.required,Z.map((_)=>_[X]));return}},optional:{child:!0,parse:i0("optional"),reduceIo:(X,Y,Z)=>{if(X==="in"){Y.optional=Z.map((_)=>_.in);return}for(let _ of Z)Y[_.outProp.kind]=t(Y[_.outProp.kind],_.outProp.out)}},index:{child:!0,parse:i0("index")},sequence:{child:!0,parse:i0("sequence")},undeclared:{parse:(X)=>X==="ignore"?void 0:X,reduceIo:(X,Y,Z)=>{if(Z!=="delete")return;if(X==="in")delete Y.undeclared;else Y.undeclared="reject"}}},defaults:{description:yQ},intersections:{structure:(X,Y,Z)=>{let _={...X.inner},G={...Y.inner},W=new C;if(X.undeclared){let Q=X.keyof();for(let J of Y.requiredKeys)if(!Q.allows(J))W.add("presence",N.intrinsic.never.internal,Y.propsByKey[J].value,{path:[J]});if(G.optional)G.optional=G.optional.filter((J)=>Q.allows(J.key));if(G.index)G.index=G.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let z=H1(Q,J.signature,Z.$);if(z instanceof C)return[];let F=Y6(z,J.value,Z.$);if(F.required)G.required=s1(G.required,F.required);if(F.optional)G.optional=s1(G.optional,F.optional);return F.index??[]})}if(Y.undeclared){let Q=Y.keyof();for(let J of X.requiredKeys)if(!Q.allows(J))W.add("presence",X.propsByKey[J].value,N.intrinsic.never.internal,{path:[J]});if(_.optional)_.optional=_.optional.filter((J)=>Q.allows(J.key));if(_.index)_.index=_.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let z=H1(Q,J.signature,Z.$);if(z instanceof C)return[];let F=Y6(z,J.value,Z.$);if(F.required)_.required=s1(_.required,F.required);if(F.optional)_.optional=s1(_.optional,F.optional);return F.index??[]})}let $={};if(X.undeclared||Y.undeclared)$.undeclared=X.undeclared==="reject"||Y.undeclared==="reject"?"reject":"delete";let H=X8({kind:"structure",baseInner:$,l:Y8(_),r:Y8(G),roots:[],ctx:Z});if(H instanceof C)W.push(...H);if(W.length)return W;return H}},reduce:(X,Y)=>{if(X.index){if(!(X.required||X.optional))return;let Z=!1,_=X.required??[],G=X.optional??[],W=[...G];for(let $ of X.index){for(let H of _){let Q=r_(H,$,Y);if(Q instanceof C)return Q}for(let[H,Q]of G.entries()){let J=r_(Q,$,Y);if(J instanceof C)return J;if(J===null)continue;W[H]=J,Z=!0}}if(Z)return Y.node("structure",{...X,optional:W},{prereduced:!0})}}});class a_ extends R1{impliedBasis=N.intrinsic.object.internal;impliedSiblings=this.children.flatMap((X)=>X.impliedSiblings??[]);props=s1(this.required,this.optional);propsByKey=d(this.props,(X,Y)=>[Y.key,Y]);propsByKeyReference=I0(this.propsByKey);expression=gQ(this);requiredKeys=this.required?.map((X)=>X.key)??[];optionalKeys=this.optional?.map((X)=>X.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let X=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Y}of this.index)X=X.concat(Y.branches);return this._keyof=this.$.node("union",X)}map(X){return this.$.node("structure",this.props.flatMap(X).reduce((Y,Z)=>{let _=this.propsByKey[Z.key];if(E0(Z)){if(Z.kind!=="required"&&Z.kind!=="optional")return R(`Map result must have kind "required" or "optional" (was ${Z.kind})`);return Y[Z.kind]=t(Y[Z.kind],Z),Y}let G=Z.kind??_?.kind??"required",W=d(Z,($,H)=>($ in o8.implementation.keys)?[$,H]:[]);return Y[G]=t(Y[G],this.$.node(G,W)),Y},{}))}assertHasKeys(X){let Y=X.filter((Z)=>!n8(Z,this.keyof()));if(Y.length)return R(s_(this.expression,Y))}get(X,...Y){let Z,_=!1,G=cQ(X);if((typeof G==="string"||typeof G==="symbol")&&this.propsByKey[G])Z=this.propsByKey[G].value,_=this.propsByKey[G].required;if(this.index){for(let $ of this.index)if(n8(G,$.signature))Z=Z?.and($.value)??$.value}if(this.sequence&&n8(G,N.intrinsic.nonNegativeIntegerString))if(f(G,"root")){if(this.sequence.variadic)Z=Z?.and(this.sequence.element)??this.sequence.element}else{let $=Number.parseInt(G);if($<this.sequence.prevariadic.length){let H=this.sequence.prevariadic[$].node;Z=Z?.and(H)??H,_||=$<this.sequence.prefixLength}else if(this.sequence.variadic){let H=this.$.node("union",this.sequence.variadicOrPostfix);Z=Z?.and(H)??H}}if(!Z){if(this.sequence?.variadic&&f(G,"root")&&G.extends(N.intrinsic.number))return R(lQ(G.expression,this.sequence.expression));return R(s_(this.expression,[G]))}let W=Z.get(...Y);return _?W:W.or(N.intrinsic.undefined)}pick(...X){return this.assertHasKeys(X),this.$.node("structure",this.filterKeys("pick",X))}omit(...X){return this.assertHasKeys(X),this.$.node("structure",this.filterKeys("omit",X))}optionalize(){let{required:X,...Y}=this.inner;return this.$.node("structure",{...Y,optional:this.props.map((Z)=>Z.hasKind("required")?this.$.node("optional",Z.inner):Z)})}require(){let{optional:X,...Y}=this.inner;return this.$.node("structure",{...Y,required:this.props.map((Z)=>Z.hasKind("optional")?{key:Z.key,value:Z.value}:Z)})}merge(X){let Y=this.filterKeys("omit",[X.keyof()]);if(X.required)Y.required=t(Y.required,X.required);if(X.optional)Y.optional=t(Y.optional,X.optional);if(X.index)Y.index=t(Y.index,X.index);if(X.sequence)Y.sequence=X.sequence;if(X.undeclared)Y.undeclared=X.undeclared;else delete Y.undeclared;return this.$.node("structure",Y)}filterKeys(X,Y){let Z=c2(this.inner),_=(G)=>{let W=Y.some(($)=>n8(G,$));return X==="pick"?W:!W};if(Z.required)Z.required=Z.required.filter((G)=>_(G.key));if(Z.optional)Z.optional=Z.optional.filter((G)=>_(G.key));if(Z.index)Z.index=Z.index.filter((G)=>_(G.signature));return Z}traverseAllows=(X,Y)=>this._traverse("Allows",X,Y);traverseApply=(X,Y)=>this._traverse("Apply",X,Y);_traverse=(X,Y,Z)=>{let _=Z?.currentErrorCount??0;for(let G=0;G<this.props.length;G++)if(X==="Allows"){if(!this.props[G].traverseAllows(Y,Z))return!1}else if(this.props[G].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>_)return!1;if(this.sequence){if(X==="Allows"){if(!this.sequence.traverseAllows(Y,Z))return!1}else if(this.sequence.traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>_)return!1}if(this.index||this.undeclared==="reject"){let G=Object.keys(Y);G.push(...Object.getOwnPropertySymbols(Y));for(let W=0;W<G.length;W++){let $=G[W];if(this.index){for(let H of this.index)if(H.signature.traverseAllows($,Z)){if(X==="Allows"){if(!$1($,()=>H.value.traverseAllows(Y[$],Z),Z))return!1}else if($1($,()=>H.value.traverseApply(Y[$],Z),Z),Z.failFast&&Z.currentErrorCount>_)return!1}}if(this.undeclared==="reject"&&!this.declaresKey($)){if(X==="Allows")return!1;if(Z.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[$],meta:this.meta}),Z.failFast)return!1}}}if(this.structuralMorph&&Z&&!Z.hasError())Z.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((X)=>X.hasDefault())??[])}declaresKey=(X)=>(X in this.propsByKey)||this.index?.some((Y)=>Y.signature.allows(X))||this.sequence!==void 0&&N.intrinsic.nonNegativeIntegerString.allows(X);_compileDeclaresKey(X){let Y=[];if(this.props.length)Y.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let Z of this.index)Y.push(X.invoke(Z.signature,{kind:"Allows",arg:"k"}));if(this.sequence)Y.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return Y.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",uQ(this))}structuralMorphRef=this.structuralMorph&&I0(this.structuralMorph);compile(X){if(X.traversalKind==="Apply")X.initializeErrorCount();for(let Y of this.props)if(X.check(Y),X.traversalKind==="Apply")X.returnIfFailFast();if(this.sequence){if(X.check(this.sequence),X.traversalKind==="Apply")X.returnIfFailFast()}if(this.index||this.undeclared==="reject")X.const("keys","Object.keys(data)"),X.line("keys.push(...Object.getOwnPropertySymbols(data))"),X.for("i < keys.length",()=>this.compileExhaustiveEntry(X));if(X.traversalKind==="Allows")return X.return(!0);if(this.structuralMorphRef)X.if("ctx && !ctx.hasError()",()=>{return X.line("ctx.queueMorphs(["),dQ(X,this),X.line("])")})}compileExhaustiveEntry(X){if(X.const("k","keys[i]"),this.index)for(let Y of this.index)X.if(`${X.invoke(Y.signature,{arg:"k",kind:"Allows"})}`,()=>X.traverseKey("k","data[k]",Y.value));if(this.undeclared==="reject")X.if(`!(${this._compileDeclaresKey(X)})`,()=>{if(X.traversalKind==="Allows")return X.return(!1);return X.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>X.return())});return X}reduceJsonSchema(X,Y){switch(X.type){case"object":return this.reduceObjectJsonSchema(X,Y);case"array":let Z=this.sequence?.reduceJsonSchema(X,Y)??X;if(this.props.length||this.index)return Y.fallback.arrayObject({code:"arrayObject",base:Z,object:this.reduceObjectJsonSchema({type:"object"},Y)});return Z;default:return M0.throwInternalOperandError("structure",X)}}reduceObjectJsonSchema(X,Y){if(this.props.length){X.properties={};for(let Z of this.props){let _=Z.value.toJsonSchemaRecurse(Y);if(typeof Z.key==="symbol"){Y.fallback.symbolKey({code:"symbolKey",base:X,key:Z.key,value:_,optional:Z.optional});continue}if(Z.hasDefault()){let G=typeof Z.default==="function"?Z.default():Z.default;_.default=N.intrinsic.jsonData.allows(G)?G:Y.fallback.defaultValue({code:"defaultValue",base:_,value:G})}X.properties[Z.key]=_}if(this.requiredKeys.length&&X.properties)X.required=this.requiredKeys.filter((Z)=>typeof Z==="string"&&(Z in X.properties))}if(this.index)for(let Z of this.index){let _=Z.value.toJsonSchemaRecurse(Y);if(Z.signature.equals(N.intrinsic.string)){X.additionalProperties=_;continue}for(let G of Z.signature.branches){if(!G.extends(N.intrinsic.string)){X=Y.fallback.symbolKey({code:"symbolKey",base:X,key:null,value:_,optional:!1});continue}let W={type:"string"};if(G.hasKind("morph"))W=Y.fallback.morph({code:"morph",base:G.in.toJsonSchemaRecurse(Y),out:G.out.toJsonSchemaRecurse(Y)});if(!G.hasKind("intersection"))return e(`Unexpected index branch kind ${G.kind}.`);let{pattern:$}=G.inner;if($){let H=Object.assign(W,{pattern:$[0].rule});for(let Q=1;Q<$.length;Q++)W=Y.fallback.patternIntersection({code:"patternIntersection",base:H,pattern:$[Q].rule});X.patternProperties??={},X.patternProperties[H.pattern]=_}}}if(this.undeclared&&!X.additionalProperties)X.additionalProperties=!1;return X}}var HY={},mQ=(X)=>{let Y="";for(let Z=0;Z<X.defaultable.length;Z++)Y+=X.defaultable[Z].defaultValueMorphRef;if(X.sequence?.defaultValueMorphsReference)Y+=X.sequence?.defaultValueMorphsReference;if(X.undeclared==="delete"){if(Y+="delete !(",X.required)for(let Z of X.required)Y+=Z.compiledKey+" | ";if(X.optional)for(let Z of X.optional)Y+=Z.compiledKey+" | ";if(X.index)for(let Z of X.index)Y+=Z.signature.id+" | ";if(X.sequence)if(X.sequence.maxLength===null)Y+=k.nonNegativeIntegerString.id;else for(let Z=0;Z<X.sequence.tuple.length;Z++)Y+=Z+" | ";Y+=")"}return Y},uQ=(X)=>{let Y=mQ(X);if(!Y)return;if(HY[Y])return HY[Y];let Z=(_,G)=>{for(let W=0;W<X.defaultable.length;W++)if(!(X.defaultable[W].key in _))X.defaultable[W].defaultValueMorph(_,G);if(X.sequence?.defaultables)for(let W=_.length-X.sequence.prefixLength;W<X.sequence.defaultables.length;W++)X.sequence.defaultValueMorphs[W](_,G);if(X.undeclared==="delete"){for(let W in _)if(!X.declaresKey(W))delete _[W]}return _};return HY[Y]=Z},dQ=(X,Y)=>{let _=`(data${Y.defaultable.some((G)=>G.defaultValueMorph.length===2)||Y.sequence?.defaultValueMorphs.some((G)=>G.length===2)?", ctx":""})`;return X.block(`${_} => `,(G)=>{for(let W=0;W<Y.defaultable.length;W++){let{serializedKey:$,defaultValueMorphRef:H}=Y.defaultable[W];G.if(`!(${$} in data)`,(Q)=>Q.line(`${H}${_}`))}if(Y.sequence?.defaultables)G.for(`i < ${Y.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${Y.sequence.prefixLength}`);if(Y.undeclared==="delete")G.forIn("data",(W)=>W.if(`!(${Y._compileDeclaresKey(W)})`,($)=>$.line("delete data[k]")));return G.return("data")})},JY={implementation:pQ,Node:a_},cQ=(X)=>{if(f(X,"root")&&X.hasKind("unit"))X=X.unit;if(typeof X==="number")X=`${X}`;return X},lQ=(X,Y)=>`${X} is not allowed as an array index on ${Y}. Use the 'nonNegativeIntegerString' keyword instead.`,Y6=(X,Y,Z)=>{let[_,G]=w5(X.branches,($)=>$.hasKind("unit"));if(!_.length)return{index:Z.node("index",{signature:X,value:Y})};let W={};for(let $ of _){let H=Z.node("required",{key:$.unit,value:Y});W[H.kind]=t(W[H.kind],H)}if(G.length)W.index=Z.node("index",{signature:G,value:Y});return W},oQ=(X)=>f(X,"root")?X.expression:c(X),s_=(X,Y)=>`Key${Y.length===1?"":"s"} ${Y.map(oQ).join(", ")} ${Y.length===1?"does":"do"} not exist on ${X}`;var _8={...N_,alias:r8.implementation,domain:X6.implementation,unit:ZY.implementation,proto:s8.implementation,union:YY.implementation,morph:eX.implementation,intersection:aX.implementation,divisor:yX.implementation,pattern:oX.implementation,predicate:bX.implementation,required:GY.implementation,optional:o8.implementation,index:_Y.implementation,sequence:WY.implementation,structure:JY.implementation};N.defaultConfig=S5(Object.assign(d(_8,(X,Y)=>[X,Y.defaults]),{jitless:k5(),clone:x5,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:M0.defaultConfig}));N.resolvedConfig=g8(N.defaultConfig,N.config);var q_={...I_,alias:r8.Node,domain:X6.Node,unit:ZY.Node,proto:s8.Node,union:YY.Node,morph:eX.Node,intersection:aX.Node,divisor:yX.Node,pattern:oX.Node,predicate:bX.Node,required:GY.Node,optional:o8.Node,index:_Y.Node,sequence:WY.Node,structure:JY.Node};class $8 extends MX{get[t0](){return"module"}}var QY=(X,Y)=>new $8(d(X,(Z,_)=>[Z,f(_,"module")?QY(_,Y):Y.bindReference(_)]));var iQ=(X)=>Q0(X)?X:("branches"in X)&&Q0(X.branches)?X.branches:void 0,nQ=(X,Y)=>R(`Node of kind ${Y} is not valid as a ${X} definition`),e_=(X)=>`#${X} duplicates public alias ${X}`,zY={};N.ambient??={};var X9,Z9="function $",rQ=(X)=>_9(X,G9(X)),_9=(X,Y)=>{let Z=Y.write(Z9,4),_=Y.compile()();for(let G of X){if(G.precompilation)continue;if(G.traverseAllows=_[`${G.id}Allows`].bind(_),G.isRoot()&&!G.allowsRequiresContext)G.allows=G.traverseAllows;if(G.traverseApply=_[`${G.id}Apply`].bind(_),_[`${G.id}Optimistic`])G.traverseOptimistic=_[`${G.id}Optimistic`].bind(_);G.precompilation=Z}},G9=(X)=>new d2().return(X.reduce((Y,Z)=>{let _=new y8({kind:"Allows"}).indent();Z.compile(_);let G=_.write(`${Z.id}Allows`),W=new y8({kind:"Apply"}).indent();Z.compile(W);let $=W.write(`${Z.id}Apply`),H=`${Y}${G},
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},
44
44
  ${$},
45
45
  `;if(!Z.hasKind("union"))return H;let Q=new y8({kind:"Allows",optimistic:!0}).indent();Z.compile(Q);let J=Q.write(`${Z.id}Optimistic`);return`${H}${J},
46
46
  `},`{
47
- `)+"}");class Z6{config;resolvedConfig;name;get[t0](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(X,Y){if(this.config=g8(N.config,Y),this.resolvedConfig=g8(N.resolvedConfig,Y),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(zY).length}`,this.name in zY)R(`A Scope already named ${this.name} already exists`);zY[this.name]=this;let Z=Object.entries(X).map((_)=>this.preparseOwnAliasEntry(..._));for(let[_,G]of Z){let W=_;if(_[0]==="#"){if(W=_.slice(1),W in this.aliases)R(e_(W));this.aliases[W]=G}else{if(W in this.aliases)R(e_(_));this.aliases[W]=G,this.exportedNames.push(W)}if(!f(G,"module")&&!f(G,"generic")&&!E4(G)){let $=this.preparseOwnDefinitionFormat(G,{alias:W});this.resolutions[W]=f($,"root")?this.bindReference($):this.createParseContext($).id}}X9??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[X9.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=N.intrinsic?d(N.intrinsic,(_,G)=>_.startsWith("json")?[]:[_,this.bindReference(G)]):{}}cacheGetter(X,Y){return Object.defineProperty(this,X,{value:Y}),Y}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(X){return X}generic=(...X)=>{let Y=this;return(Z,_)=>new M4(X,_?new n2(Z):Z,Y,Y,_??null)};units=(X,Y)=>{let Z=[];for(let G of X)if(!Z.includes(G))Z.push(G);let _=Z.map((G)=>this.node("unit",{unit:G},Y));return this.node("union",_,{...Y,prereduced:!0})};lazyResolutions=[];lazilyResolve(X,Y){let Z=this.node("alias",{reference:Y??"synthetic",resolve:X},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(Z);return Z}schema=(X,Y)=>this.finalize(this.parseSchema(X,Y));parseSchema=(X,Y)=>this.node(d8(X),X,Y);preparseNode(X,Y,Z){let _=typeof X==="string"?X:d8(Y,X);if(E0(Y)&&Y.kind===_)return Y;if(_==="alias"&&!Z?.prereduced){let{reference:$}=r8.implementation.normalize(Y,this);if($.startsWith("$")){let H=this.resolveRoot($.slice(1));Y=H,_=H.kind}}else if(_==="union"&&_1(Y,"object")){let $=iQ(Y);if($?.length===1)Y=$[0],_=d8(Y)}if(E0(Y)&&Y.kind===_)return Y;let W=_8[_].normalize?.(Y,this)??Y;if(E0(W))return W.kind===_?W:nQ(_,W.kind);return{...Z,$:this,kind:_,def:W,prefix:Z.alias??_}}bindReference(X){let Y;if(E0(X))Y=X.$===this?X:new X.constructor(X.attachments,this);else Y=X.$===this?X:new M4(X.params,X.bodyDef,X.$,this,X.hkt);if(!this.resolved)Object.assign(this.referencesById,Y.referencesById);return Y}resolveRoot(X){return this.maybeResolveRoot(X)??R(EY(X))}maybeResolveRoot(X){let Y=this.maybeResolve(X);if(f(Y,"generic"))return;return Y}maybeResolveSubalias(X){return FY(this.aliases,X)??FY(this.ambient,X)}get ambient(){return N.ambient}maybeResolve(X){let Y=this.resolutions[X];if(Y){if(typeof Y!=="string")return this.bindReference(Y);let _=a0[Y];if(f(_,"root"))return this.resolutions[X]=_;if(f(_,"context")){if(_.phase==="resolving")return this.node("alias",{reference:`$${X}`},{prereduced:!0});if(_.phase==="resolved")return e(`Unexpected resolved context for was uncached by its scope: ${c(_)}`);_.phase="resolving";let G=this.bindReference(this.parseOwnDefinitionFormat(_.def,_));return _.phase="resolved",a0[G.id]=G,a0[_.id]=G,this.resolutions[X]=G}return e(`Unexpected nodesById entry for ${Y}: ${c(_)}`)}let Z=this.aliases[X]??this.ambient?.[X];if(!Z)return this.maybeResolveSubalias(X);if(Z=this.normalizeRootScopeValue(Z),f(Z,"generic"))return this.resolutions[X]=this.bindReference(Z);if(f(Z,"module")){if(!Z.root)R(H9(X));return this.resolutions[X]=this.bindReference(Z.root)}return this.resolutions[X]=this.parse(Z,{alias:X})}createParseContext(X){let Y=X.id??iX(X.prefix);return a0[Y]=Object.assign(X,{[t0]:"context",$:this,id:Y,phase:"unresolved"})}traversal(X){return new x1(X,this.resolvedConfig)}import(...X){return new $8(d(this.export(...X),(Y,Z)=>[`#${Y}`,Z]))}precompilation;_exportedResolutions;_exports;export(...X){if(!this._exports){this._exports={};for(let Z of this.exportedNames){let _=this.aliases[Z];this._exports[Z]=f(_,"module")?QY(_,this):Y9(this.maybeResolve(Z))}for(let Z of this.lazyResolutions)Z.resolution;if(this._exportedResolutions=$9(this,this._exports),this._json=W9(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let Z=G9(this.references);this.precompilation=Z.write(Z9,4),_9(this.references,Z)}this.resolved=!0}let Y=X.length?X:this.exportedNames;return new $8(d(Y,(Z,_)=>[_,this._exports[_]]))}resolve(X){return this.export()[X]}node=(X,Y,Z={})=>{let _=this.preparseNode(X,Y,Z);if(E0(_))return this.bindReference(_);let G=this.createParseContext(_),W=nX(G),$=this.bindReference(W);return a0[G.id]=$};parse=(X,Y={})=>this.finalize(this.parseDefinition(X,Y));parseDefinition(X,Y={}){if(f(X,"root"))return this.bindReference(X);let Z=this.preparseOwnDefinitionFormat(X,Y);if(f(Z,"root"))return this.bindReference(Z);let _=this.createParseContext(Z);a0[_.id]=_;let G=this.bindReference(this.parseOwnDefinitionFormat(X,_));if(G.isCyclic)G=C_(G,_.id);return a0[_.id]=G,G}finalize(X){if(Y9(X),!X.precompilation&&!this.resolvedConfig.jitless)rQ(X.references);return X}}class UY extends Z6{parseOwnDefinitionFormat(X,Y){return nX(Y)}preparseOwnDefinitionFormat(X,Y){return this.preparseNode(d8(X),X,Y)}preparseOwnAliasEntry(X,Y){return[X,Y]}normalizeRootScopeValue(X){return X}}var Y9=(X)=>{let Y=X.references.filter((Z)=>Z.hasKind("alias"));for(let Z of Y){Object.assign(Z.referencesById,Z.resolution.referencesById);for(let _ of X.references)if(Z.id in _.referencesById)Object.assign(_.referencesById,Z.referencesById)}return X},W9=(X)=>d(X,(Y,Z)=>[Y,f(Z,"root")||f(Z,"generic")?Z.json:f(Z,"module")?W9(Z):e(`Unexpected resolution ${c(Z)}`)]),FY=(X,Y)=>{let Z=Y.indexOf(".");if(Z===-1)return;let _=Y.slice(0,Z),G=X[_];if(G===void 0)return;if(!f(G,"module"))return R(sQ(_));let W=Y.slice(Z+1),$=G[W];if($===void 0)return FY(G,W);if(f($,"root")||f($,"generic"))return $;if(f($,"module"))return $.root??R(H9(Y));e(`Unexpected resolution for alias '${Y}': ${c($)}`)},_6=(X,Y)=>new UY(X,Y),a8=new UY({});var $9=(X,Y)=>{let Z={};for(let _ in Y){let G=Y[_];if(f(G,"module")){let W=$9(X,G),$=d(W,(H,Q)=>[`${_}.${H}`,Q]);Object.assign(Z,$)}else if(f(G,"root")||f(G,"generic"))Z[_]=G;else e(`Unexpected scope resolution ${c(G)}`)}return Z},EY=(X)=>`'${X}' is unresolvable`,sQ=(X)=>`'${X}' must reference a module to be accessed using dot syntax`,H9=(X)=>`Reference to submodule '${X}' must specify an alias`;a8.export();var{schema:G0,node:H8,defineSchema:uR,generic:N1}=a8;var OY="^(?:0|[1-9]\\d*)$",tQ=new RegExp(OY),lR=I0(tQ);var J9=_6({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();N.intrinsic={...J9};var Q9=_6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:OY}},{prereducedAliases:!0}).export();Object.assign(N.intrinsic,Q9);var aQ=_6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),k={...J9,...Q9,...aQ,emptyStructure:H8("structure",{},{prereduced:!0})};N.intrinsic={...k};var F9=(X)=>typeof X==="string"&&X[0]==="d"&&(X[1]==="'"||X[1]==='"')&&X.at(-1)===X[1],z9=(X)=>X.toString()!=="Invalid Date",U9=(X)=>X.slice(2,-1),VY=(X)=>`'${X}' could not be parsed by the Date constructor`,E9=(X,Y)=>eQ(X,Y),eQ=(X,Y)=>{let Z=new Date(X);if(z9(Z))return Z;let _=l5(X);if(_!==void 0){let G=new Date(_);if(z9(G))return G}return Y?R(Y===!0?VY(X):Y):void 0};var DY=(X,Y)=>{let Z=X.scanner.shiftUntil(Xz[V9[Y]]);if(X.scanner.lookahead==="")return X.error(Zz(Z,Y));if(X.scanner.shift(),Y==="/"){try{new RegExp(Z)}catch(_){R(String(_))}X.root=X.ctx.$.node("intersection",{domain:"string",pattern:Z},{prereduced:!0})}else if(f0(Y,LY))X.root=X.ctx.$.node("unit",{unit:Z});else{let _=E9(Z,VY(Z));X.root=X.ctx.$.node("unit",{meta:Z,unit:_})}},LY={"'":1,'"':1},O9={"/":1,"'":1,'"':1},V9={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},Xz={"'":(X)=>X.lookahead==="'",'"':(X)=>X.lookahead==='"',"/":(X)=>X.lookahead==="/"},Yz={'"':"double-quote","'":"single-quote","/":"forward slash"},Zz=(X,Y)=>`${Y}${X} requires a closing ${Yz[V9[Y]]}`;var D9=(X)=>`Private type references should not include '#'. Use '${X}' instead.`,G6="Optional definitions like 'string?' are only valid as properties in an object or tuple",W6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var L9={">":!0,">=":!0},M9={"<":!0,"<=":!0};var J8={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},A9=(X)=>`Unmatched )${X===""?"":` before ${X}`}`,$6=(X)=>`Missing ${X}`,R9=(X,Y)=>`Left bounds are only valid when paired with right bounds (try ...${Y}${X})`,H6=(X)=>`Left-bounded expressions must specify their limits using < or <= (was ${X})`,w9=(X,Y,Z,_)=>`An expression may have at most one left bound (parsed ${X}${J8[Y]}, ${Z}${J8[_]})`;var N9=(X,Y,Z)=>I9(X,Y,Z,[]),I9=(X,Y,Z,_)=>{let G=Z.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Y.params.length)return Z.error(MY(X,Y.names,_.map((W)=>W.expression)));return _}if(G.finalizer===",")return I9(X,Y,Z,_);return G.error($6(">"))},MY=(X,Y,Z)=>`${X}<${Y.join(", ")}> requires exactly ${Y.length} args (got ${Z.length}${Z.length===0?"":`: ${Z.join(", ")}`})`;var AY=(X)=>{let Y=X.scanner.shiftUntilNextTerminator();if(Y==="keyof")X.addPrefix("keyof");else X.root=Gz(X,Y)},_z=(X,Y,Z)=>{if(Z.scanner.shiftUntilNonWhitespace(),Z.scanner.shift()!=="<")return Z.error(MY(X,Y.names,[]));let G=N9(X,Y,Z);return Y(...G)},Gz=(X,Y)=>Wz(X,Y)??$z(X,Y)??X.error(Y===""?X.scanner.lookahead==="#"?D9(X.shiftedByOne().scanner.shiftUntilNextTerminator()):RY(X):EY(Y)),Wz=(X,Y)=>{if(X.ctx.args?.[Y]){let _=X.ctx.args[Y];if(typeof _!=="string")return _;return X.ctx.$.node("alias",{reference:_},{prereduced:!0})}let Z=X.ctx.$.maybeResolve(Y);if(f(Z,"root"))return Z;if(Z===void 0)return;if(f(Z,"generic"))return _z(Y,Z,X);return R(`Unexpected resolution ${c(Z)}`)},$z=(X,Y)=>{let Z=o5(Y);if(Z!==void 0)return X.ctx.$.node("unit",{unit:Z});let _=n5(Y);if(_!==void 0)return X.ctx.$.node("unit",{unit:_})},RY=(X)=>{let Y=X.previousOperator();return Y?wY(Y,X.scanner.unscanned):Hz(X.scanner.unscanned)},wY=(X,Y="")=>`Token '${X}' requires a right operand${Y?` before '${Y}'`:""}`,Hz=(X)=>`Expected an expression${X?` before '${X}'`:""}`;var NY=(X)=>X.scanner.lookahead===""?X.error(RY(X)):X.scanner.lookahead==="("?X.shiftedByOne().reduceGroupOpen():X.scanner.lookaheadIsIn(O9)?DY(X,X.scanner.shift()):X.scanner.lookaheadIsIn(O4)?NY(X.shiftedByOne()):X.scanner.lookahead==="d"?X.scanner.nextLookahead in LY?DY(X,`${X.scanner.shift()}${X.scanner.shift()}`):AY(X):AY(X);class Z4 extends CX{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in Z4.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...O4};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(X,Y)=>X===">"?Y[0]==="="?Y[1]==="=":Y.trimStart()===""||f0(Y.trimStart()[0],Z4.terminatingChars):X==="="?Y[0]!=="=":X===","||X==="?"}var B9=(X,Y)=>{let Z=Jz(X,Y);if(X.root.hasKind("unit")){if(typeof X.root.unit==="number"){X.reduceLeftBound(X.root.unit,Z),X.unsetRoot();return}if(X.root.unit instanceof Date){let _=`d'${X.root.description??X.root.unit.toISOString()}'`;X.unsetRoot(),X.reduceLeftBound(_,Z);return}}return zz(X,Z)},T9={"<":1,">":1,"=":1},Jz=(X,Y)=>X.scanner.lookaheadIs("=")?`${Y}${X.scanner.shift()}`:Y;var K9=(X,Y,Z,_)=>{if(Z.extends(N.intrinsic.number)){if(typeof Y!=="number")return R(IY(X,Y,_));return X==="=="?["min","max"]:X[0]===">"?["min"]:["max"]}if(Z.extends(N.intrinsic.lengthBoundable)){if(typeof Y!=="number")return R(IY(X,Y,_));return X==="=="?["exactLength"]:X[0]===">"?["minLength"]:["maxLength"]}if(Z.extends(N.intrinsic.Date))return X==="=="?["after","before"]:X[0]===">"?["after"]:["before"];return R(O_(Z.expression))},Qz=(X)=>({rule:F9(X.limit)?U9(X.limit):X.limit,exclusive:X.comparator.length===1}),zz=(X,Y)=>{let Z=X.unsetRoot(),_=X.scanner.location;X.parseOperand();let G=X.unsetRoot(),W=X.scanner.sliceChars(_,X.scanner.location);if(X.root=Z,!G.hasKind("unit")||typeof G.unit!=="number"&&!(G.unit instanceof Date))return X.error(IY(Y,W,"right"));let $=G.unit,H=Y.length===1,Q=K9(Y,typeof $==="number"?$:W,Z,"right");for(let z of Q)X.constrainRoot(z,Y==="=="?{rule:$}:{rule:$,exclusive:H});if(!X.branches.leftBound)return;if(!f0(Y,M9))return X.error(H6(Y));let J=K9(X.branches.leftBound.comparator,X.branches.leftBound.limit,Z,"left");X.constrainRoot(J[0],Qz(X.branches.leftBound)),X.branches.leftBound=null},IY=(X,Y,Z)=>`Comparator ${Z==="left"?J8[X]:X} must be ${Z==="left"?"preceded":"followed"} by a corresponding literal (was ${Y})`;var C9=(X)=>{X.scanner.shiftUntilNonWhitespace();let Y=X.scanner.shiftUntilNextTerminator();X.root=X.root.brand(Y)};var j9=(X)=>{let Y=X.scanner.shiftUntilNextTerminator(),Z=i5(Y,{errorOnFail:q9(Y)});if(Z===0)X.error(q9(0));X.root=X.root.constrain("divisor",Z)},q9=(X)=>`% operator must be followed by a non-zero integer literal (was ${X})`;var KY=(X)=>{let Y=X.scanner.shift();return Y===""?X.finalize(""):Y==="["?X.scanner.shift()==="]"?X.setRoot(X.root.array()):X.error(Fz):Y==="|"?X.scanner.lookahead===">"?X.shiftedByOne().pushRootToBranch("|>"):X.pushRootToBranch(Y):Y==="&"?X.pushRootToBranch(Y):Y===")"?X.finalizeGroup():Z4.lookaheadIsFinalizing(Y,X.scanner.unscanned)?X.finalize(Y):f0(Y,T9)?B9(X,Y):Y==="%"?j9(X):Y==="#"?C9(X):(Y in O4)?KY(X):X.error(J6(Y))},J6=(X,Y="")=>`'${X}' is not allowed here${Y&&` (should be ${Y})`}`,Fz="Missing expected ']'";var S9=(X)=>{let Y=X.unsetRoot();X.parseOperand();let Z=X.unsetRoot();if(!Z.hasKind("unit"))return X.error(Uz(Z.expression));let _=Z.unit instanceof Date?()=>new Date(Z.unit):Z.unit;return[Y,"=",_]},Uz=(X)=>`Default value '${X}' must a literal value`;var BY=(X,Y)=>{let Z=Y.$.maybeResolveRoot(X);if(Z)return Z;if(X.endsWith("[]")){let W=Y.$.maybeResolveRoot(X.slice(0,-2));if(W)return W.array()}let _=new Q8(new Z4(X),Y),G=Ez(_);if(_.finalizer===">")R(J6(">"));return G},Ez=(X)=>{X.parseOperand();let Y=e8(X).root;if(!Y)return e(`Root was unexpectedly unset after parsing string '${X.scanner.scanned}'`);if(X.finalizer==="=")Y=S9(X);else if(X.finalizer==="?")Y=[Y,"?"];if(X.scanner.shiftUntilNonWhitespace(),X.scanner.lookahead)R(J6(X.scanner.lookahead));return Y},e8=(X)=>{while(X.finalizer===void 0)Oz(X);return X},Oz=(X)=>X.hasRoot()?X.parseOperator():X.parseOperand();class Q8{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(X,Y){this.scanner=X,this.ctx=Y}error(X){return R(X)}hasRoot(){return this.root!==void 0}setRoot(X){this.root=X}unsetRoot(){let X=this.root;return this.root=void 0,X}constrainRoot(...X){this.root=this.root.constrain(X[0],X[1])}finalize(X){if(this.groups.length)return this.error($6(")"));this.finalizeBranches(),this.finalizer=X}reduceLeftBound(X,Y){let Z=J8[Y];if(!f0(Z,L9))return this.error(H6(Y));if(this.branches.leftBound)return this.error(w9(this.branches.leftBound.limit,this.branches.leftBound.comparator,X,Z));this.branches.leftBound={comparator:Z,limit:X}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let X=this.groups.pop();if(!X)return this.error(A9(this.scanner.unscanned));this.branches=X}addPrefix(X){this.branches.prefixes.push(X)}applyPrefixes(){while(this.branches.prefixes.length){let X=this.branches.prefixes.pop();this.root=X==="keyof"?this.root.keyof():e(`Unexpected prefix '${X}'`)}}pushRootToBranch(X){this.assertRangeUnset(),this.applyPrefixes();let Y=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(Y)??Y,X==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,X==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return e8(new Q8(this.scanner,this.ctx))}parseOperator(){return KY(this)}parseOperand(){return NY(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(R9(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var Vz="An empty string is not a valid generic parameter name",Q6=(X,Y,Z)=>{X.shiftUntilNonWhitespace();let _=X.shiftUntilNextTerminator();if(_===""){if(X.lookahead===""&&Y.length)return Y;return R(Vz)}return X.shiftUntilNonWhitespace(),Dz(X,_,Y,Z)},P9="extends ",Dz=(X,Y,Z,_)=>{if(X.shiftUntilNonWhitespace(),X.unscanned.startsWith(P9))X.jumpForward(P9.length);else{if(X.lookahead===",")X.shift();return Z.push(Y),Q6(X,Z,_)}let G=e8(new Q8(X,_));return Z.push([Y,G.root]),Q6(X,Z,_)};class TY extends v1{$;constructor(X){super((...Y)=>new X2(X)(...Y),{bind:X});this.$=X}in(X){return new X2(this.$,X===void 0?void 0:this.$.parse(X))}at(X,Y){return new X2(this.$).at(X,Y)}case(X,Y){return new X2(this.$).case(X,Y)}}class X2 extends v1{$;in;key;branches=[];constructor(X,Y){super((Z)=>this.caseEntries(Object.entries(Z).map(([_,G])=>_==="default"?[_,G]:[this.$.parse(_),G])));this.$=X,this.in=Y}at(X,Y){if(this.key)R(Mz);if(this.branches.length)R(Lz);return this.key=X,Y?this.match(Y):this}case(X,Y){return this.caseEntry(this.$.parse(X),Y)}caseEntry(X,Y){let _=(this.key?this.$.parse({[this.key]:X}):X).pipe(Y);return this.branches.push(_),this}match(X){return this(X)}strings(X){return this.caseEntries(Object.entries(X).map(([Y,Z])=>Y==="default"?[Y,Z]:[this.$.node("unit",{unit:Y}),Z]))}caseEntries(X){for(let Y=0;Y<X.length;Y++){let[Z,_]=X[Y];if(Z==="default"){if(Y!==X.length-1)R("default may only be specified as the last key of a switch definition");return this.default(_)}if(typeof _!=="function")return R(`Value for case "${Z}" must be a function (was ${x0(_)})`);this.caseEntry(Z,_)}return this}default(X){if(typeof X==="function")this.case(k.unknown,X);let Y={branches:this.branches,ordered:!0};if(X==="never"||X==="assert")Y.meta={onFail:v9};let Z=this.$.node("union",Y);if(!this.in)return this.$.finalize(Z);let _=this.in.pipe(Z);if(X==="never"||X==="assert")_=_.configureReferences({onFail:v9},"self");return this.$.finalize(_)}}var v9=(X)=>X.throw(),Lz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",Mz="At most one key matcher may be specified per expression";var z6=(X,Y)=>{if(Q0(X)){if(X[1]==="=")return[Y.$.parseOwnDefinitionFormat(X[0],Y),"=",X[2]];if(X[1]==="?")return[Y.$.parseOwnDefinitionFormat(X[0],Y),"?"]}return F6(X,Y)},x9="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",f9="Only required keys may specify default values, e.g. { value: 'number = 0' }";var h9=(X,Y)=>{let Z,_={},G=q4(X);for(let[$,H]of G){let Q=wz($);if(Q.kind==="spread"){if(!l1(_))return R(Rz);let D=Y.$.parseOwnDefinitionFormat(H,Y);if(D.equals(k.object))continue;if(!D.hasKind("intersection")||!D.basis?.equals(k.object))return R(Nz(D.expression));Z=D.structure;continue}if(Q.kind==="undeclared"){if(H!=="reject"&&H!=="delete"&&H!=="ignore")R(Az(H));_.undeclared=H;continue}let J=z6(H,Y),z=Q;if(Q.kind==="required"){if(!Q0(J))CY(_,"required",{key:Q.normalized,value:J},Y);else CY(_,"optional",J[1]==="="?{key:Q.normalized,value:J[0],default:J[2]}:{key:Q.normalized,value:J[0]},Y);continue}if(Q0(J)){if(J[1]==="?")R(x9);if(J[1]==="=")R(f9)}if(Q.kind==="optional"){CY(_,"optional",{key:Q.normalized,value:J},Y);continue}let F=Y.$.parseOwnDefinitionFormat(z.normalized,Y),O=Y6(F,J,Y.$);if(O.index)_.index=t(_.index,O.index);if(O.required)_.required=t(_.required,O.required)}let W=Y.$.node("structure",_);return Y.$.parseSchema({domain:"object",structure:Z?.merge(W)??W})},CY=(X,Y,Z,_)=>{X[Y]=t(X[Y],_.$.node(Y,Z))},Az=(X)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${c(X)})`,Rz="Spread operator may only be used as the first key in an object",wz=(X)=>typeof X==="symbol"?{kind:"required",normalized:X}:X.at(-1)==="?"?X.at(-2)===v8?{kind:"required",normalized:`${X.slice(0,-2)}?`}:{kind:"optional",normalized:X.slice(0,-1)}:X[0]==="["&&X.at(-1)==="]"?{kind:"index",normalized:X.slice(1,-1)}:X[0]===v8&&X[1]==="["&&X.at(-1)==="]"?{kind:"required",normalized:X.slice(1)}:X==="..."?{kind:"spread"}:X==="+"?{kind:"undeclared"}:{kind:"required",normalized:X==="\\..."?"...":X==="\\+"?"+":X},Nz=(X)=>`Spread operand must resolve to an object literal type (was ${X})`;var b9=(X,Y)=>vz(X)?m9[X[0]](X,Y):Sz(X)?p9[X[1]](X,Y):null,Iz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[1],Y).keyof(),qY=(X,Y)=>{if(X[2]===void 0)return R(wY(X[1],""));let Z=Y.$.parseOwnDefinitionFormat(X[0],Y),_=Y.$.parseOwnDefinitionFormat(X[2],Y);if(X[1]==="|")return Y.$.node("union",{branches:[Z,_]});let G=X[1]==="&"?H1(Z,_,Y.$):u8(Z,_,Y.$);if(G instanceof C)return G.throw();return G},Kz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[0],Y).array(),Bz=(X,Y)=>{if(typeof X[2]!=="function")return R(y9("=>",X[2]));return Y.$.parseOwnDefinitionFormat(X[0],Y).pipe(X[2])},y9=(X,Y)=>`${X===":"?"Narrow":"Morph"} expression requires a function following '${X}' (was ${typeof Y})`,Tz=(X,Y)=>{if(typeof X[2]!=="function")return R(y9(":",X[2]));return Y.$.parseOwnDefinitionFormat(X[0],Y).constrain("predicate",X[2])},Cz=(X,Y)=>Y.$.parseOwnDefinitionFormat(X[0],Y).configureReferences(X[2],"shallow"),g9=(X)=>X,qz=g9({"[]":Kz,"?":()=>R(G6)}),jz=g9({"|":qY,"&":qY,":":Tz,"=>":Bz,"|>":qY,"@":Cz,"=":()=>R(W6)}),p9={...qz,...jz},Sz=(X)=>p9[X[1]]!==void 0,Pz=(X)=>X,m9=Pz({keyof:Iz,instanceof:(X,Y)=>{if(typeof X[1]!=="function")return R(k9(S8(X[1])));let Z=X.slice(1).map((_)=>typeof _==="function"?Y.$.node("proto",{proto:_}):R(k9(S8(_))));return Z.length===1?Z[0]:Y.$.node("union",{branches:Z})},"===":(X,Y)=>Y.$.units(X.slice(1))}),vz=(X)=>m9[X[0]]!==void 0,k9=(X)=>`Expected a constructor following 'instanceof' operator (was ${X})`;var c9=(X,Y)=>{let Z=[{}],_=0;while(_<X.length){let G=!1;if(X[_]==="..."&&_<X.length-1)G=!0,_++;let W=z6(X[_],Y),[$,H,Q]=!Q0(W)?[W]:W;if(_++,G){if(!$.extends(N.intrinsic.Array))return R(hz($.expression));Z=Z.flatMap((J)=>$.distribute((z)=>fz(c2(J),z)))}else Z=Z.map((J)=>{if(H==="?")return l9(J,$);if(H==="=")return xz(J,$,Q);return jY(J,$)})}return Y.$.parseSchema(Z.map((G)=>l1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},jY=(X,Y)=>{if(X.defaultables||X.optionals)return R(X.variadic?$Y:kz);if(X.variadic)X.postfix=t(X.postfix,Y);else X.prefix=t(X.prefix,Y);return X},l9=(X,Y)=>{if(X.variadic)return R(o9);return X.optionals=t(X.optionals,Y),X},xz=(X,Y,Z)=>{if(X.variadic)return R(o9);if(X.optionals)return R(bz);return X.defaultables=t(X.defaultables,[[Y,Z]]),X},u9=(X,Y)=>{if(X.postfix)R(d9);if(X.variadic){if(!X.variadic.equals(Y))R(d9)}else X.variadic=Y.internal;return X},fz=(X,Y)=>{let Z=Y.select({method:"find",kind:"sequence"});if(!Z)return u9(X,N.intrinsic.unknown);if(Z.prefix)for(let _ of Z.prefix)jY(X,_);if(Z.optionals)for(let _ of Z.optionals)l9(X,_);if(Z.variadic)u9(X,Z.variadic);if(Z.postfix)for(let _ of Z.postfix)jY(X,_);return X},hz=(X)=>`Spread element must be an array (was ${X})`,d9="A tuple may have at most one variadic element",kz="A required element may not follow an optional element",o9="An optional element may not follow a variadic element";var bz="A defaultable element may not follow an optional element without a default";var yz={},F6=(X,Y)=>{if(typeof X==="string"){if(Y.args&&Object.keys(Y.args).some((_)=>X.includes(_)))return BY(X,Y);let Z=yz[Y.$.name]??={};return Z[X]??=BY(X,Y)}return _1(X,"object")?gz(X,Y):R(SY(x0(X)))},gz=(X,Y)=>{let Z=j8(X);switch(Z){case void 0:if(f(X,"root"))return X;return h9(X,Y);case"Array":return pz(X,Y);case"RegExp":return Y.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0});case"Function":{let _=E4(X)?X():X;if(f(_,"root"))return _;return R(SY("Function"))}default:return R(SY(Z??c(X)))}},pz=(X,Y)=>b9(X,Y)??c9(X,Y),SY=(X)=>`Type definitions must be strings or objects (was ${X})`;class PY extends v1{constructor(X){let Y=Object.assign({errors:W1,hkt:o0,$:X,raw:X.parse,module:X.constructor.module,scope:X.constructor.scope,define:X.define,match:X.match,generic:X.generic,schema:X.schema,keywords:X.ambient,unit:X.unit,enumerated:X.enumerated,instanceOf:X.instanceOf,valueOf:X.valueOf,or:X.or,and:X.and,merge:X.merge,pipe:X.pipe},X.ambientAttachments);super((...Z)=>{if(Z.length===1)return X.parse(Z[0]);if(Z.length===2&&typeof Z[0]==="string"&&Z[0][0]==="<"&&Z[0].at(-1)===">"){let _=Z[0].slice(1,-1),G=X.parseGenericParams(_,{});return new M4(G,Z[1],X,X,null)}return X.parse(Z)},{bind:X,attach:Y})}}var z8=N;class U6 extends Z6{get ambientAttachments(){if(!z8.typeAttachments)return;return this.cacheGetter("ambientAttachments",d(z8.typeAttachments,(X,Y)=>[X,this.bindReference(Y)]))}preparseOwnAliasEntry(X,Y){let Z=X.indexOf("<");if(Z===-1){if(f(Y,"module")||f(Y,"generic"))return[X,Y];let W=this.name==="ark"?X:X==="root"?this.name:`${this.name}.${X}`,$=this.resolvedConfig.keywords?.[W];if($)Y=[Y,"@",$];return[X,Y]}if(X.at(-1)!==">")R("'>' must be the last character of a generic declaration in a scope");let _=X.slice(0,Z),G=X.slice(Z+1,-1);return[_,()=>{let W=this.parseGenericParams(G,{alias:_});return F_(W,Y,this)}]}parseGenericParams(X,Y){return Q6(new Z4(X),[],this.createParseContext({...Y,def:X,prefix:"generic"}))}normalizeRootScopeValue(X){if(E4(X)&&!f(X,"generic"))return X();return X}preparseOwnDefinitionFormat(X,Y){return{...Y,def:X,prefix:Y.alias??"type"}}parseOwnDefinitionFormat(X,Y){if(!(Y.alias&&(Y.alias in this.aliases))&&!Y.args)Y.args={this:Y.id};let _=F6(X,Y);if(Q0(_)){if(_[1]==="=")return R(W6);if(_[1]==="?")return R(G6)}return _}unit=(X)=>this.units([X]);valueOf=(X)=>this.units(P5(X));enumerated=(...X)=>this.units(X);instanceOf=(X)=>this.node("proto",{proto:X},{prereduced:!0});or=(...X)=>this.schema(X.map((Y)=>this.parse(Y)));and=(...X)=>X.reduce((Y,Z)=>Y.and(this.parse(Z)),this.intrinsic.unknown);merge=(...X)=>X.reduce((Y,Z)=>Y.merge(this.parse(Z)),this.intrinsic.object);pipe=(...X)=>this.intrinsic.unknown.pipe(...X);match=new TY(this);declare=()=>({type:this.type});define(X){return X}type=new PY(this);static scope=(X,Y={})=>new U6(X,Y);static module=(X,Y={})=>this.scope(X,Y).export()}var vY=Object.assign(U6.scope,{define:(X)=>X}),r=U6;class i9 extends o0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var mz=N1(["base",k.object],["props",k.object])((X)=>X.base.merge(X.props),i9),n9=r.module({Key:k.key,Merge:mz});class r9 extends o0{}var uz=N1("element")((X)=>{let Y=X.element.exclude(k.Array),Z=Y.array();return Y.rawOr(Z).pipe(U4).distribute((_)=>_.assertHasKind("morph").declareOut(Z),G0)},r9),s9=r.module({root:k.Array,readonly:"root",index:k.nonNegativeIntegerString,liftFrom:uz},{name:"Array"});var xY=G0(["string",S4.FileConstructor]),dz=xY.rawOr(xY.array()),t9=G0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:dz}}),a9=r.module({root:["instanceof",FormData],value:xY,parsed:t9,parse:G0({in:FormData,morphs:(X)=>{let Y={};for(let[Z,_]of X)if(Z in Y){let G=Y[Z];if(typeof G==="string"||G instanceof S4.FileConstructor)Y[Z]=[G,_];else G.push(_)}else Y[Z]=_;return Y},declaredOut:t9})},{name:"FormData"});var e9=r.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var cz={Boolean:1,Number:1,String:1},XG=r.module({...d({...AX,...wX},(X,Y)=>(X in cz)?[]:[X,["instanceof",Y]]),Array:s9,TypedArray:e9,FormData:a9});var lz=G0({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),oz=G0({domain:"number",divisor:1}),E6=r.module({root:k.number,integer:oz,epoch:lz,safe:G0({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var A0=(X,Y,Z)=>{let _={domain:"string",pattern:{rule:X.source,flags:X.flags,meta:Y}};if(Z)_.meta={format:Z};return H8("intersection",_)},YG=A0(x8,"a well-formed integer string"),EG=r.module({root:YG,parse:G0({in:YG,morphs:(X,Y)=>{let Z=Number.parseInt(X);return Number.isSafeInteger(Z)?Z:Y.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:k.integer})},{name:"string.integer"}),iz=A0(/^[\dA-Fa-f]+$/,"hex characters only"),nz=r.module({root:A0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:A0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),ZG=A0(/^[A-Z].*$/,"capitalized"),rz=r.module({root:G0({in:"string",morphs:(X)=>X.charAt(0).toUpperCase()+X.slice(1),declaredOut:ZG}),preformatted:ZG},{name:"string.capitalize"}),sz=(X)=>{let Y=X.replaceAll(/[ -]+/g,""),Z=0,_,G,W=!1;for(let $=Y.length-1;$>=0;$--){if(_=Y.substring($,$+1),G=Number.parseInt(_,10),W)G*=2,Z+=G>=10?G%10+1:G;else Z+=G;W=!W}return!!(Z%10===0?Y:!1)},tz=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,az=G0({domain:"string",pattern:{meta:"a credit card number",rule:tz.source},predicate:{meta:"a credit card number",predicate:sz}});var ez=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var XF=(X)=>!Number.isNaN(new Date(X).valueOf()),_G=G0({domain:"string",predicate:{meta:"a parsable date",predicate:XF}}).assertHasKind("intersection"),GG=EG.root.internal.narrow((X,Y)=>{let Z=Number.parseInt(X),_=E6.epoch(Z);if(_ instanceof W1)return Y.errors.merge(_),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),YF=r.module({root:GG,parse:G0({in:GG,morphs:(X)=>new Date(X),declaredOut:k.Date})},{name:"string.date.epoch"}),WG=A0(ez,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),ZF=r.module({root:WG,parse:G0({in:WG,morphs:(X)=>new Date(X),declaredOut:k.Date})},{name:"string.date.iso"}),_F=r.module({root:_G,parse:G0({declaredIn:_G,in:"string",morphs:(X,Y)=>{let Z=new Date(X);if(Number.isNaN(Z.valueOf()))return Y.error("a parsable date");return Z},declaredOut:k.Date}),iso:ZF,epoch:YF},{name:"string.date"}),GF=A0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),$G="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A4=`(${$G}[.]){3}${$G}`,WF=new RegExp(`^${A4}$`),j0="(?:[0-9a-fA-F]{1,4})",$F=new RegExp(`^((?:${j0}:){7}(?:${j0}|:)|(?:${j0}:){6}(?:${A4}|:${j0}|:)|(?:${j0}:){5}(?::${A4}|(:${j0}){1,2}|:)|(?:${j0}:){4}(?:(:${j0}){0,1}:${A4}|(:${j0}){1,3}|:)|(?:${j0}:){3}(?:(:${j0}){0,2}:${A4}|(:${j0}){1,4}|:)|(?:${j0}:){2}(?:(:${j0}){0,3}:${A4}|(:${j0}){1,5}|:)|(?:${j0}:){1}(?:(:${j0}){0,4}:${A4}|(:${j0}){1,6}|:)|(?::((?::${j0}){0,5}:${A4}|(?::${j0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),HF=r.module({root:["v4 | v6","@","an IP address"],v4:A0(WF,"an IPv4 address","ipv4"),v6:A0($F,"an IPv6 address","ipv6")},{name:"string.ip"}),F8="a JSON string",OG=(X)=>{if(!(X instanceof SyntaxError))throw X;return`must be ${F8} (${X})`},JF=G0({meta:F8,domain:"string",predicate:{meta:F8,predicate:(X,Y)=>{try{return JSON.parse(X),!0}catch(Z){return Y.reject({code:"predicate",expected:F8,problem:OG(Z)})}}}}),QF=(X,Y)=>{if(X.length===0)return Y.error({code:"predicate",expected:F8,actual:"empty"});try{return JSON.parse(X)}catch(Z){return Y.error({code:"predicate",expected:F8,problem:OG(Z)})}},zF=r.module({root:JF,parse:G0({meta:"safe JSON string parser",in:"string",morphs:QF,declaredOut:k.jsonObject})},{name:"string.json"}),HG=A0(/^[a-z]*$/,"only lowercase letters"),FF=r.module({root:G0({in:"string",morphs:(X)=>X.toLowerCase(),declaredOut:HG}),preformatted:HG},{name:"string.lower"}),VG=["NFC","NFD","NFKC","NFKD"],Y2=d(VG,(X,Y)=>[Y,G0({domain:"string",predicate:(Z)=>Z.normalize(Y)===Z,meta:`${Y}-normalized unicode`})]),O6=d(VG,(X,Y)=>[Y,G0({in:"string",morphs:(Z)=>Z.normalize(Y),declaredOut:Y2[Y]})]),UF=r.module({root:O6.NFC,preformatted:Y2.NFC},{name:"string.normalize.NFC"}),EF=r.module({root:O6.NFD,preformatted:Y2.NFD},{name:"string.normalize.NFD"}),OF=r.module({root:O6.NFKC,preformatted:Y2.NFKC},{name:"string.normalize.NFKC"}),VF=r.module({root:O6.NFKD,preformatted:Y2.NFKD},{name:"string.normalize.NFKD"}),DF=r.module({root:"NFC",NFC:UF,NFD:EF,NFKC:OF,NFKD:VF},{name:"string.normalize"}),JG=A0(m2,"a well-formed numeric string"),LF=r.module({root:JG,parse:G0({in:JG,morphs:(X)=>Number.parseFloat(X),declaredOut:k.number})},{name:"string.numeric"}),QG="a regex pattern",MF=G0({domain:"string",predicate:{meta:QG,predicate:(X,Y)=>{try{return new RegExp(X),!0}catch(Z){return Y.reject({code:"predicate",expected:QG,problem:String(Z)})}}},meta:{format:"regex"}}),AF=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,RF=A0(AF,"a semantic version (see https://semver.org/)"),zG=A0(/^\S.*\S$|^\S?$/,"trimmed"),wF=r.module({root:G0({in:"string",morphs:(X)=>X.trim(),declaredOut:zG}),preformatted:zG},{name:"string.trim"}),FG=A0(/^[A-Z]*$/,"only uppercase letters"),NF=r.module({root:G0({in:"string",morphs:(X)=>X.toUpperCase(),declaredOut:FG}),preformatted:FG},{name:"string.upper"}),IF=(X)=>{if(URL.canParse)return URL.canParse(X);try{return new URL(X),!0}catch{return!1}},UG=G0({domain:"string",predicate:{meta:"a URL string",predicate:IF},meta:{format:"uri"}}),KF=r.module({root:UG,parse:G0({declaredIn:UG,in:"string",morphs:(X,Y)=>{try{return new URL(X)}catch{return Y.error("a URL string")}},declaredOut:G0(URL)})},{name:"string.url"}),BF=r.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:A0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:A0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:A0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:A0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:A0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:A0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:A0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:A0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),DG=r.module({root:k.string,alpha:A0(/^[A-Za-z]*$/,"only letters"),alphanumeric:A0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:iz,base64:nz,capitalize:rz,creditCard:az,date:_F,digits:A0(/^\d*$/,"only digits 0-9"),email:GF,integer:EG,ip:HF,json:zF,lower:FF,normalize:DF,numeric:LF,regex:MF,semver:RF,trim:wF,upper:NF,url:KF,uuid:BF},{name:"string"});var LG=r.module({bigint:k.bigint,boolean:k.boolean,false:k.false,never:k.never,null:k.null,number:k.number,object:k.object,string:k.string,symbol:k.symbol,true:k.true,unknown:k.unknown,undefined:k.undefined}),MG=r.module({root:k.unknown,any:k.unknown},{name:"unknown"}),TF=r.module({root:k.jsonObject,stringify:H8("morph",{in:k.jsonObject,morphs:(X)=>JSON.stringify(X),declaredOut:k.string})},{name:"object.json"}),AG=r.module({root:k.object,json:TF},{name:"object"});class RG extends o0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var CF=N1(["K",k.key],"V")((X)=>({domain:"object",index:{signature:X.K,value:X.V}}),RG);class wG extends o0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var qF=N1(["T",k.object],["K",k.key])((X)=>X.T.pick(X.K),wG);class NG extends o0{description='omit a set of properties from an object like `Omit(User, "age")`'}var jF=N1(["T",k.object],["K",k.key])((X)=>X.T.omit(X.K),NG);class IG extends o0{description="make all named properties of an object optional like `Partial(User)`"}var SF=N1(["T",k.object])((X)=>X.T.partial(),IG);class KG extends o0{description="make all named properties of an object required like `Required(User)`"}var PF=N1(["T",k.object])((X)=>X.T.required(),KG);class BG extends o0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var vF=N1("T","U")((X)=>X.T.exclude(X.U),BG);class TG extends o0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var xF=N1("T","U")((X)=>X.T.extract(X.U),TG),CG=r.module({Exclude:vF,Extract:xF,Omit:jF,Partial:SF,Pick:qF,Record:CF,Required:PF});var R4=vY({...LG,...CG,...XG,...n9,string:DG,number:E6,object:AG,unknown:MG},{prereducedAliases:!0,name:"ark"}),h0=R4.export();Object.assign(z8.ambient,h0);z8.typeAttachments={string:h0.string.root,number:h0.number.root,bigint:h0.bigint,boolean:h0.boolean,symbol:h0.symbol,undefined:h0.undefined,null:h0.null,object:h0.object.root,unknown:h0.unknown.root,false:h0.false,true:h0.true,never:h0.never,arrayIndex:h0.Array.index,Key:h0.Key,Record:h0.Record,Array:h0.Array.root,Date:h0.Date};var J1=Object.assign(R4.type,z8.typeAttachments),fF=R4.match,hF=R4.generic,EK=R4.schema,kF=R4.define,bF=R4.declare;function U8(X){return w6(Q1.STORE,X,void 0)}function E8(X){return G2(Q1.STORE,X)}function hY(...X){return h1(Q1.STORE,...X)}function V6(X){return kG(Q1.STORE,X)}function qG(X){return bG(X,Q1.STORE)}var _4={atom_family:"atom family",atom:"atom",continuity:"continuity",key:"key",mutable_atom_family:"atom family [m]",mutable_atom:"atom [m]",readonly_held_selector_family:"selector family [h]",readonly_held_selector:"selector [h]",readonly_pure_selector_family:"selector family",readonly_pure_selector:"selector",state:"state",timeline:"timeline",transaction:"transaction",unknown:"unknown",writable_held_selector_family:"selector family [wh]",writable_held_selector:"selector [wh]",writable_pure_selector_family:"selector family [w]",writable_pure_selector:"selector [w]"};var fY=(X)=>(Y,Z,_,G,...W)=>{console[X](`${Y} ${_4[Z]} \`${_}\` ${G}`,...W)},yF={error:fY("error"),info:fY("info"),warn:fY("warn")},jG=class{logLevel;filter;logger;constructor(X,Y,Z=yF){this.logLevel=X,this.filter=Y,this.logger=Z}error=(...X)=>{if(this.logLevel!==null){let Y=this.filter?.(...X)??!0;if(Y===!0)this.logger.error(...X);else if(Y)this.logger.error(...Y)}};info=(...X)=>{if(this.logLevel==="info"){let Y=this.filter?.(...X)??!0;if(Y===!0)this.logger.info(...X);else if(Y)this.logger.info(...Y)}};warn=(...X)=>{if(this.logLevel!=="error"&&this.logLevel!==null){let Y=this.filter?.(...X)??!0;if(Y===!0)this.logger.warn(...X);else if(Y)this.logger.warn(...Y)}}};var SG=class{store;deallocateTX;claimTX;constructor(X=Q1.STORE){this.store=X,this.deallocateTX=vG(X),this.claimTX=xG(X),PG(X,"root")}allocate(X,Y,Z){A6(this.store,X,Y,Z)}deallocate(X){M6(this.store,this.deallocateTX,kY())(X)}claim(X,Y,Z){Z2(this.store,X,Y,Z)}};function D6(X){return bY(Q1.STORE,X)}function L6(X){return _2(Q1.STORE,X)}function X1(X){return JSON.parse(X)}var w0=(X)=>JSON.stringify(X),yK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function yG(X){let Y={},Z=0;for(let _ of X)Y[_]=Z,Y[Z]=_,++Z;return Y}var gG="\x01",pG="\x02",mG="\x03",uG="\x04",gY=(X)=>{switch(typeof X){case"string":return mG+X;case"number":return uG+X;case"boolean":return gG+ +X;case"object":return pG}},pY=(X)=>{switch(X[0]){case mG:return X.slice(1);case uG:return+X.slice(1);case gG:return X.slice(1)==="1";case pG:return null}};var dG=yG(["add","delete","clear"]),G4=class X extends Set{mode="record";subject=new Z0;constructor(Y){super(Y);if(Y instanceof X);}READONLY_VIEW=this;toJSON(){return[...this]}static fromJSON(Y){return new X(Y)}add(Y){let Z=super.add(Y);if(this.mode==="record")this.emit({type:"add",value:Y});return Z}clear(){let Y=this.mode==="record"?[...this]:null;if(super.clear(),Y)this.emit({type:"clear",values:Y})}delete(Y){let Z=super.delete(Y);if(this.mode==="record")this.emit({type:"delete",value:Y});return Z}subscribe(Y,Z){return this.subject.subscribe(Y,Z)}emit(Y){this.subject.next(X.packUpdate(Y))}do(Y){this.mode="playback";let Z=X.unpackUpdate(Y);switch(Z.type){case"add":this.add(Z.value);break;case"delete":this.delete(Z.value);break;case"clear":this.clear()}return this.mode="record",null}undo(Y){let Z=X.unpackUpdate(Y);switch(this.mode="playback",Z.type){case"add":this.delete(Z.value);break;case"delete":this.add(Z.value);break;case"clear":{let _=Z.values;for(let G of _)this.add(G)}}return this.mode="record",null}static packUpdate(Y){let Z=dG[Y.type]+"\x1F";if(Y.type==="clear")return Z+Y.values.map(gY).join("\x1E");return Z+gY(Y.value)}static unpackUpdate(Y){let[Z,_]=Y.split("\x1F"),G=dG[Z];if(G==="clear")return{type:"clear",values:_.split("\x1E").map(pY)};return{type:G,value:pY(_)}}};function kY(X=Math.random){return X().toString(36).slice(2)}function s(X){while(X.child!==null)X=X.child;return X}function pF(X){while(X.parent!==null)X=X.parent;return X}var mF=/^\[object (?:Async|Generator|AsyncGenerator)?Function\]$/;function H2(X){let Y=Object.prototype.toString.call(X);return mF.test(Y)}function dY(X,Y){if(H2(X))return X(Y);return X}var cY=class extends Promise{fate;resolve;reject;done=!1;constructor(X){let Y,Z;super((_,G)=>{Y=_,Z=G});this.resolve=Y,this.reject=Z,this.use(X instanceof Promise?X:new Promise(X))}pass(X,Y){if(X===this.fate)this.resolve(Y),this.done=!0}fail(X,Y){if(X===this.fate)this.reject(Y),this.done=!0}use(X){if(this===X)return;if(X instanceof Promise){let Y=X;this.fate=Y,Y.then((Z)=>{this.pass(Y,Z)},(Z)=>{this.fail(Y,Z)})}else this.resolve(X),this.fate=void 0}},Z0=class{Subscriber;subscribers=new Map;subscribe(X,Y){return this.subscribers.set(X,Y),()=>{this.unsubscribe(X)}}unsubscribe(X){this.subscribers.delete(X)}next(X){let Y=this.subscribers.values();for(let Z of Y)Z(X)}},uF=class extends Z0{state;constructor(X){super();this.state=X}next(X){this.state=X,super.next(X)}},dF=class X{_buffer;_index=0;constructor(Y){let Z;if(typeof Y==="number")Z=Y;else Z=Y.length;this._buffer=Array.from({length:Z})}get buffer(){return this._buffer}get index(){return this._index}add(Y){this._buffer[this._index]=Y,this._index=(this._index+1)%this._buffer.length}copy(){let Y=new X([...this._buffer]);return Y._index=this._index,Y}};function y1(X){let Y={key:X.key,type:X.type};if("family"in X)Y.family=X.family;return Y}var b1=class extends Map{deleted=new Set;changed=new Set;source;constructor(X){super();this.source=X}get(X){if(super.has(X))return super.get(X);if(!this.deleted.has(X)&&this.source.has(X))return this.source.get(X)}set(X,Y){if(this.deleted.delete(X),this.source.has(X))this.changed.add(X);return super.set(X,Y)}hasOwn(X){return super.has(X)}has(X){return!this.deleted.has(X)&&(super.has(X)||this.source.has(X))}delete(X){if(this.source.has(X))this.deleted.add(X),this.changed.delete(X);return super.delete(X)}clear(){this.deleted=new Set(this.source.keys()),this.changed.clear(),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let[X,Y]of this.source)if(!this.deleted.has(X)&&!this.changed.has(X))yield[X,Y]}*entries(){yield*this[Symbol.iterator]()}*keys(){yield*super.keys();for(let X of this.source.keys())if(!this.deleted.has(X)&&!this.changed.has(X))yield X}*values(){for(let[,X]of this[Symbol.iterator]())yield X}forEach(X){for(let[Y,Z]of this[Symbol.iterator]())X(Z,Y,this)}get size(){return super.size+this.source.size-this.changed.size-this.deleted.size}},iG=class extends Set{deleted=new Set;source;constructor(X){super();this.source=X}add(X){if(this.source.has(X))return this.deleted.delete(X),this;return super.add(X)}hasOwn(X){return super.has(X)}has(X){return!this.deleted.has(X)&&(super.has(X)||this.source.has(X))}delete(X){if(this.source.has(X))return this.deleted.add(X),!0;return super.delete(X)}clear(){this.deleted=new Set(this.source),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let X of this.source)if(!this.deleted.has(X))yield X}*iterateOwn(){yield*super[Symbol.iterator]()}get size(){return super.size+this.source.size-this.deleted.size}},cF=class extends Map{deleted=new Set;source;constructor(X){super();this.source=X}get(X){if(super.has(X))return super.get(X);if(!this.deleted.has(X)&&this.source.has(X)){let Y=this.source.get(X),Z=new iG(Y);return super.set(X,Z),Z}}set(X,Y){return this.deleted.delete(X),super.set(X,Y)}has(X){return!this.deleted.has(X)&&(super.has(X)||this.source.has(X))}delete(X){return this.deleted.add(X),super.delete(X)}},W4=class X{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(Y,Z)=>`${Y}:${Z}`;warn;getRelatedKeys(Y){return this.relations.get(Y)}addRelation(Y,Z){let _=this.relations.get(Y),G=this.relations.get(Z);if(_)_.add(Z);else _=new Set([Z]),this.relations.set(Y,_);if(G)G.add(Y);else G=new Set([Y]),this.relations.set(Z,G)}deleteRelation(Y,Z){let _=this.relations.get(Y);if(_){if(_.delete(Z),_.size===0)this.relations.delete(Y);let G=this.relations.get(Z);if(G){if(G.delete(Y),G.size===0)this.relations.delete(Z)}}}replaceRelationsUnsafely(Y,Z){this.relations.set(Y,new Set(Z));for(let _ of Z){let G=new Set().add(Y);this.relations.set(_,G)}}replaceRelationsSafely(Y,Z){let _=this.relations.get(Y),G=this.isAType?.(Y)?Y:void 0,W=G===void 0?Y:void 0;if(_)for(let $ of _){G??=$,W??=$;let H=this.relations.get($);if(H){if(H.size===1)this.relations.delete($);else H.delete(Y);this.contents.delete(this.makeContentKey(G,W))}}this.relations.set(Y,new Set(Z));for(let $ of Z){let H=this.relations.get($);if(H)H.add(Y);else H=new Set().add(Y),this.relations.set($,H)}}getContentInternal(Y){return this.contents.get(Y)}setContent(Y,Z){this.contents.set(Y,Z)}deleteContent(Y){this.contents.delete(Y)}constructor(Y,Z){if(this.a=Y.between[0],this.b=Y.between[1],this.cardinality=Y.cardinality,this.isAType=Z?.isAType??null,this.isBType=Z?.isBType??null,this.isContent=Z?.isContent??null,Z?.makeContentKey)this.makeContentKey=Z.makeContentKey;if(!Z?.externalStore){let _=Z?.source;if(_===void 0)this.relations=new Map(Y.relations?.map(([G,W])=>[G,new Set(W)])),this.contents=new Map(Y.contents);if(_)this.relations=new cF(_.relations),this.contents=new b1(_.contents)}if(Z?.externalStore){let _=Z.externalStore;if(this.has=(G,W)=>_.has(G,W),this.addRelation=(G,W)=>{_.addRelation(G,W)},this.deleteRelation=(G,W)=>{_.deleteRelation(G,W)},this.replaceRelationsSafely=(G,W)=>{_.replaceRelationsSafely(G,W)},this.replaceRelationsUnsafely=(G,W)=>{_.replaceRelationsUnsafely(G,W)},this.getRelatedKeys=(G)=>_.getRelatedKeys(G),_.getContent)this.getContentInternal=(G)=>{return _.getContent(G)},this.setContent=(G,W)=>{_.setContent(G,W)},this.deleteContent=(G)=>{_.deleteContent(G)};for(let[G,W]of Y.relations??[]){let $=this.isAType?.(G)?G:void 0,H=$===void 0?G:void 0;for(let Q of W)$??=Q,H??=Q,this.addRelation($,H)}for(let[G,W]of Y.contents??[])this.setContent(G,W)}if(Z?.warn)this.warn=Z.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([Y,Z])=>[Y,[...Z]]),contents:[...this.contents.entries()]}}set(...Y){let Z,_,G;switch(Y.length){case 1:{let W=Y[0];Z=W[this.a],_=W[this.b],G=void 0;break}case 2:{let W=Y[0];if(typeof W==="string")[Z,_]=Y;else Z=W[this.a],_=W[this.b],G=Y[1];break}default:Z=Y[0],_=Y[1],G=Y[2];break}switch(this.cardinality){case"1:1":{let W=this.getRelatedKey(Z);if(W&&W!==_)this.delete(Z,W)}case"1:n":{let W=this.getRelatedKey(_);if(W&&W!==Z)this.delete(W,_)}break;case"n:n":}if(G){let W=this.makeContentKey(Z,_);this.setContent(W,G)}return this.addRelation(Z,_),this}delete(Y,Z){Z=typeof Z==="string"?Z:Y[this.b];let _=typeof Y==="string"?Y:Y[this.a];if(_===void 0&&typeof Z==="string"){let G=this.getRelatedKeys(Z);if(G)for(let W of G)this.delete(W,Z)}else if(typeof _==="string"&&Z===void 0){let G=this.getRelatedKeys(_);if(G)for(let W of G)this.delete(_,W)}else if(typeof _==="string"&&typeof Z==="string"){this.deleteRelation(_,Z);let G=this.makeContentKey(_,Z);this.deleteContent(G)}return this}getRelatedKey(Y){let Z=this.getRelatedKeys(Y);if(Z){if(Z.size>1)this.warn?.(`${Z.size} related keys were found for key "${Y}": (${[...Z].map((G)=>`"${G}"`).join(", ")}). Only one related key was expected.`);let _;for(let G of Z){_=G;break}return _}}replaceRelations(Y,Z,_){let G=!Array.isArray(Z),W=G?Object.keys(Z):Z;if(_?.reckless)this.replaceRelationsUnsafely(Y,W);else this.replaceRelationsSafely(Y,W);if(G)for(let $ of W){let H=this.makeContentKey(Y,$),Q=Z[$];this.setContent(H,Q)}return this}getContent(Y,Z){let _=this.makeContentKey(Y,Z);return this.getContentInternal(_)}getRelationEntries(Y){let Z=Y[this.a],_=Y[this.b];if(Z!==void 0&&_===void 0){let G=this.getRelatedKeys(Z);if(G)return[...G].map((W)=>{return[W,this.getContent(Z,W)]})}if(Z===void 0&&_!==void 0){let G=this.getRelatedKeys(_);if(G)return[...G].map((W)=>{return[W,this.getContent(W,_)]})}return[]}has(Y,Z){if(Z)return this.getRelatedKeys(Y)?.has(Z)??!1;return this.relations.has(Y)}overlay(){let Y={source:this,makeContentKey:this.makeContentKey};if(this.isAType)Y.isAType=this.isAType;if(this.isBType)Y.isBType=this.isBType;if(this.isContent)Y.isContent=this.isContent;if(this.warn)Y.warn=this.warn;return new X({between:[this.a,this.b],cardinality:this.cardinality},Y)}incorporate(Y){let{relations:Z,contents:_}=Y;for(let[G,W]of Z)if(W instanceof iG){let{source:$}=W;for(let H of W.iterateOwn())$.add(H)}else this.relations.set(G,W);for(let G of Z.deleted)this.relations.delete(G);for(let[G,W]of _)this.contents.set(G,W);for(let G of _.deleted)this.contents.delete(G)}};function V8(X){return X.startsWith("\uD83D\uDD0D ")}var lF=(X)=>{X.logger.info("\uD83E\uDE82","transaction",X.transactionMeta.update.token.key,"Aborting transaction"),X.parent.child=null};function M6(X,Y,Z){return(..._)=>{return T0(X,Y).run(_,Z)}}function oF(X,Y,Z){let{token:_,update:{newValue:G,oldValue:W}}=Y;k1(X,_,Z==="newValue"?G:W)}function iF(X){let{stack:Y}=X;if(Y)return`
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`
48
48
  `+Y.split(`
49
49
  `)?.slice(1)?.join(`
50
- `);return""}function PG(X,Y){let Z={key:Y,stringKey:w0(Y),dependsOn:"any"};return X.molecules.set(w0(Y),Z),Y}function A6(X,Y,Z,_="any"){let G=Y,W=w0(Z),$=[],H=s(X);if(Array.isArray(G))for(let J of G){let z=w0(J);if(H.molecules.get(z))X.moleculeGraph.set(z,W,{source:z});else $.push(z)}else{let J=w0(G);if(H.molecules.get(J))X.moleculeGraph.set(J,W,{source:J});else $.push(J)}if($.length===0)H.molecules.set(W,{key:Z,stringKey:W,dependsOn:_});let Q={type:"molecule_creation",key:Z,provenance:G,timestamp:Date.now()};if(z1(H)&&H.transactionMeta.phase==="building")H.transactionMeta.update.subEvents.push(Q);else H.on.moleculeCreation.next(Q);for(let J of $){let z=X.disposalTraces.buffer.find((F)=>F?.key===J);X.logger.error("\u274C","key",Z,"allocation failed:",`Could not allocate to ${J} in store "${X.config.name}".`,z?`
51
- ${J} was most recently disposed
52
- ${z.trace}`:`No previous disposal trace for ${J} was found.`)}return Z}function vG(X){return _2(X,{key:"[Internal] deallocate",do:(Y,Z)=>{K6(s(X),Z)}})}function K6(X,Y){let Z=w0(Y),_=X.molecules.get(Z);if(!_){let O=X.disposalTraces.buffer.find((D)=>D?.key===Z);X.logger.error("\u274C","key",Y,"deallocation failed:",`Could not find allocation for ${Z} in store "${X.config.name}".`,O?`
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
+ ${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
53
  This state was most recently deallocated
54
- ${O.trace}`:`No previous disposal trace for ${Z} was found.`);return}let G=X.moleculeJoins.getRelatedKeys(Z);if(G)for(let O of G){let D=X.joins.get(O);if(D)D.relations.delete(Y)}X.moleculeJoins.delete(Z);let W=[],$=[],H=X.moleculeGraph.getRelationEntries({downstreamMoleculeKey:Z});if(H)for(let[O,{source:D}]of H)if(D===Z){let w=X1(O);K6(X,w)}else W.push(D);let Q=X.moleculeData.getRelatedKeys(_.stringKey);if(Q)for(let O of Q){let D=X.families.get(O),w=h1(X,D,Y);$.push([D.key,w]),W2(X,D,Y)}let J={type:"molecule_disposal",key:_.key,values:$,provenance:W,timestamp:Date.now()};X.molecules.delete(Z);let z=z1(X)&&X.transactionMeta.phase==="building";if(z)X.transactionMeta.update.subEvents.push(J);if(X.moleculeGraph.delete(_.stringKey),X.moleculeJoins.delete(_.stringKey),X.moleculeData.delete(_.stringKey),!z)X.on.moleculeDisposal.next(J);X.molecules.delete(_.stringKey);let F=iF(Error());X.disposalTraces.add({key:Z,trace:F})}function xG(X){return _2(X,{key:"[Internal] claim",do:(Y,Z,_,G)=>{Z2(X,Z,_,G)}})}function Z2(X,Y,Z,_){let G=w0(Z),W=s(X),$=W.molecules.get(G);if(!$){let F=X.disposalTraces.buffer.find((O)=>O?.key===G);return X.logger.error("\u274C","key",G,"claim failed:",`Could not allocate to ${G} in store "${X.config.name}".`,F?`
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
55
  ${G} was most recently disposed
56
- ${F.trace}`:`No previous disposal trace for ${G} was found.`),Z}let H=w0(Y),Q=W.molecules.get(H);if(!Q){let F=X.disposalTraces.buffer.find((O)=>O?.key===H);return X.logger.error("\u274C","key",Z,"claim failed:",`Could not allocate to ${H} in store "${X.config.name}".`,F?`
56
+ ${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
57
  ${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(z1(W)&&W.transactionMeta.phase==="building")W.transactionMeta.update.subEvents.push(z);return Z}function nF(X,Y,Z){switch(Z){case"newValue":nG(X,Y);break;case"oldValue":W2(X,Y.token);break}}function rF(X,Y,Z){switch(Z){case"newValue":W2(X,Y.token);break;case"oldValue":if(nG(X,Y),Y.subType==="atom")X.valueMap.set(Y.token.key,Y.value);break}}function nG(X,Y){let{token:Z}=Y;if(Y.subType==="writable"&&Y.value)k1(X,Z,Y.value);else h1(X,Z)}function sF(X,Y,Z){switch(Z){case"newValue":A6(X,Y.provenance,Y.key);break;case"oldValue":K6(X,Y.key);break}}function tF(X,Y,Z){switch(Z){case"newValue":K6(X,Y.key);break;case"oldValue":{let _=Y.provenance.map(X1);A6(X,_,Y.key);for(let[G,W]of Y.values){let $=X.families.get(G);if($){h1(X,$,Y.key);let H=`${G}(${w0(Y.key)})`;X.valueMap.set(H,W)}}}break}}function aF(X,Y,Z){switch(Z){case"newValue":for(let _ of Y.to)Z2(X,_,Y.key,Y.exclusive?"exclusive":void 0);break;case"oldValue":{let _="exclusive";for(let G of Y.from)Z2(X,G,Y.key,_),_=void 0}break}}function rG(X,Y,Z){let _=Z==="newValue"?Y.subEvents:[...Y.subEvents].reverse();for(let G of _)switch(G.type){case"atom_update":oF(X,G,Z);break;case"state_creation":nF(X,G,Z);break;case"state_disposal":rF(X,G,Z);break;case"molecule_creation":sF(X,G,Z);break;case"molecule_disposal":tF(X,G,Z);break;case"molecule_transfer":aF(X,G,Z);break;case"transaction_outcome":rG(X,G,Z);break}}function O8(X){return"epoch"in X.transactionMeta}function z1(X){return"phase"in X.transactionMeta}function sG(X,Y){return X.transactionMeta.actionContinuities.getRelatedKey(Y)}function eF(X,Y){return X.transactionMeta.epoch.get(Y)}function XU(X,Y){let Z=sG(X,Y);if(Z===void 0)return;return eF(X,Z)}function YU(X,Y,Z){let _=sG(X,Y);if(_!==void 0)X.transactionMeta.epoch.set(_,Z)}function ZU(X,Y){let Z=s(X),{parent:_}=Z;Z.transactionMeta.phase="applying",Z.transactionMeta.update.output=Y,_.child=null,_.on.transactionApplying.next(Z.transactionMeta);let{subEvents:G}=Z.transactionMeta.update;if(X.logger.info("\uD83D\uDEC4","transaction",Z.transactionMeta.update.token.key,`applying ${G.length} subEvents:`,G),rG(_,Z.transactionMeta.update,"newValue"),O8(_))YU(_,Z.transactionMeta.update.token.key,Z.transactionMeta.update.epoch),T0(X,{key:Z.transactionMeta.update.token.key,type:"transaction"})?.subject.next(Z.transactionMeta.update),X.logger.info("\uD83D\uDEEC","transaction",Z.transactionMeta.update.token.key,"applied");else if(z1(_))_.transactionMeta.update.subEvents.push(Z.transactionMeta.update);_.on.transactionApplying.next(null)}function _U(X){return{store:X}}var GU=(X,Y,Z,_)=>{let G=s(X),W={parent:G,child:null,on:G.on,loggers:G.loggers,logger:G.logger,config:G.config,atoms:new b1(G.atoms),atomsThatAreDefault:new Set(G.atomsThatAreDefault),families:new b1(G.families),joins:new b1(G.joins),operation:{open:!1},readonlySelectors:new b1(G.readonlySelectors),timelines:new b1(G.timelines),timelineTopics:G.timelineTopics.overlay(),trackers:new Map,transactions:new b1(G.transactions),selectorAtoms:G.selectorAtoms.overlay(),selectorGraph:G.selectorGraph.overlay(),writableSelectors:new b1(G.writableSelectors),valueMap:new b1(G.valueMap),defaults:G.defaults,disposalTraces:X.disposalTraces.copy(),molecules:new b1(G.molecules),moleculeGraph:G.moleculeGraph.overlay(),moleculeData:G.moleculeData.overlay(),moleculeJoins:G.moleculeJoins.overlay(),miscResources:new b1(G.miscResources)},$=XU(X,Y.key),H={phase:"building",update:{type:"transaction_outcome",token:Y,id:_,epoch:$===void 0?NaN:$+1,timestamp:Date.now(),subEvents:[],params:Z,output:void 0},toolkit:{get:(...J)=>h1(Q,...J),set:(...J)=>{k1(Q,...J)},reset:(...J)=>{R6(Q,...J)},run:(J,z=kY())=>M6(Q,J,z),find:(...J)=>e0(X,...J),json:(J)=>h4(Q,J),dispose:(...J)=>{W2(Q,...J)},env:()=>_U(Q)}},Q=Object.assign(W,{transactionMeta:H});return G.child=Q,X.logger.info("\uD83D\uDEEB","transaction",Y.key,"building with params:",Z),Q};function _2(X,Y){let{key:Z}=Y,_=X.transactions.has(Z),G={key:Z,type:"transaction",run:($,H)=>{let Q=y1(G),J=GU(X,Q,$,H);try{let{toolkit:z}=J.transactionMeta,F=Y.do(z,...$);return ZU(J,F),F}catch(z){throw lF(J),X.logger.warn("\uD83D\uDCA5","transaction",Z,"caught:",z),z}},install:($)=>_2($,Y),subject:new Z0};s(X).transactions.set(Z,G);let W=y1(G);if(!_)X.on.transactionCreation.next(W);return W}var fG=class{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new W4({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new W4({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new W4({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new W4({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new dF(100);molecules=new Map;moleculeJoins=new W4({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});moleculeGraph=new W4({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});moleculeData=new W4({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...X)=>X.sort().join(":")});miscResources=new Map;on={atomCreation:new Z0,atomDisposal:new Z0,selectorCreation:new Z0,selectorDisposal:new Z0,timelineCreation:new Z0,transactionCreation:new Z0,transactionApplying:new uF(null),operationClose:new Z0,moleculeCreation:new Z0,moleculeDisposal:new Z0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new jG("warn",(X,Y,Z)=>!V8(Z))];logger={error:(...X)=>{for(let Y of this.loggers)Y.error(...X)},info:(...X)=>{for(let Y of this.loggers)Y.info(...X)},warn:(...X)=>{for(let Y of this.loggers)Y.warn(...X)}};constructor(X,Y=null){if(this.config={...Y?.config,...X},Y!==null){if(this.operation={...Y?.operation},O8(Y))this.transactionMeta={epoch:new Map(Y?.transactionMeta.epoch),actionContinuities:new W4(Y?.transactionMeta.actionContinuities.toJSON())};for(let[,_]of Y.families){if(_.internalRoles?.includes("mutable")||_.internalRoles?.includes("join"))continue;_.install(this)}let Z=new Set;for(let[,_]of Y.atoms){if(Z.has(_.key))continue;if(_.install(this),_.type==="mutable_atom"){let G=h4(Y,_),W=_Z(_);Z.add(G.key),Z.add(W.key)}}for(let[,_]of Y.readonlySelectors)_.install(this);for(let[,_]of Y.writableSelectors){if(Z.has(_.key))continue;_.install(this)}for(let[,_]of Y.transactions)_.install(this);for(let[,_]of Y.timelines)_.install(this)}}},Q1={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new fG({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};var WU=class extends Error{constructor(X,Y){super(`${_4[X.type]} ${w0(X.key)} not found in store "${Y.config.name}".`)}};function T0(X,Y){let Z,_=X;while(_!==null){switch(Y.type){case"atom":case"mutable_atom":Z=_.atoms.get(Y.key);break;case"writable_pure_selector":case"writable_held_selector":Z=_.writableSelectors.get(Y.key);break;case"readonly_pure_selector":case"readonly_held_selector":Z=_.readonlySelectors.get(Y.key);break;case"atom_family":case"mutable_atom_family":case"writable_pure_selector_family":case"readonly_pure_selector_family":case"writable_held_selector_family":case"readonly_held_selector_family":Z=_.families.get(Y.key);break;case"timeline":Z=_.timelines.get(Y.key);break;case"transaction":Z=_.transactions.get(Y.key);break}if(Z)return Z;_=_.child}throw new WU(Y,X)}function tG(X,Y,Z,_){let G=X.disposalTraces.buffer.find((W)=>W?.key===w0(_));switch(X.logger.error("\u274C",Y.type,Y.key,"gets a fallback value because key",_,"is not allocated",G?`This key was previously disposed:
59
- ${G.trace}`:"(no previous disposal trace found)"),Z.type){case"mutable_atom_family":{if(X.defaults.has(Z.key))return X.defaults.get(Z.key);let W=new Z.class;return X.defaults.set(Z.key,W),W.READONLY_VIEW}case"atom_family":{if(X.defaults.has(Z.key))return X.defaults.get(Z.key);let W=Z.default,$=W(_);return X.defaults.set(Z.key,$),$}case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(X.defaults.has(Z.key))return X.defaults.get(Z.key);let W=Z.default(_);return X.defaults.set(Z.key,W),W}}}function N6(X,Y){let{type:Z,key:_,catch:G}=Y;switch(Z){case"readonly_pure_selector":case"writable_pure_selector":{let W;X.logger.info("\uD83E\uDDEE",Z,_,"computing value");try{if(W=Y.getFrom(X),W instanceof Promise)return W.catch(($)=>{if(X.logger.error("\uD83D\uDCA5",Z,_,"rejected:",$),G){for(let H of G)if($ instanceof H)return $}throw $})}catch($){if(X.logger.error("\uD83D\uDCA5",Z,_,"rejected:",$),G){for(let H of G)if($ instanceof H)return K1(X,Y,$)}throw $}return K1(X,Y,W)}case"atom":{let W;if(H2(Y.default))try{if(W=Y.default(),W instanceof Promise)W=W.catch(($)=>{if(X.logger.error("\uD83D\uDCA5",Z,_,"rejected:",$),G){for(let H of G)if($ instanceof H)return $}throw $})}catch($){if(X.logger.error("\uD83D\uDCA5",Z,_,"rejected:",$),G){for(let H of G)if($ instanceof H)return W=K1(X,Y,$),X.logger.info("\u2728",Y.type,_,"computed default",W),W}throw $}else W=Y.default,X.logger.info("\u2728",Y.type,_,"using static default",W);return K1(X,Y,W)}}}function f4(X,Y,Z){if(X.valueMap.has(Y.key))return AU(X,Y,Z);X.logger.info("\u2754",Y.type,Y.key,"value not found in cache");let{key:_}=Y;switch(Y.type){case"readonly_held_selector":case"writable_held_selector":return X.logger.info("\uD83E\uDDEE",Y.type,_,"computing value"),Y.getFrom(X);case"writable_pure_selector":case"readonly_pure_selector":case"atom":return N6(X,Y);case"mutable_atom":{let G=new Y.class;return X.logger.info("\u2728",Y.type,_,"created new instance",G),K1(X,Y,G)}}}function nY(X,Y){return T0(X,{key:Y.family.key,type:`${Y.type}_family`})}var cG={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"},J2=Symbol("MUST_CREATE"),$U=Symbol("DO_NOT_CREATE");function Q2(X,Y,Z,_){let G=w0(_),W=Y.molecules.get(G);if(!W&&Y.config.lifespan==="immortal"){let{type:H,key:Q}=Z;Y.logger.warn("\uD83D\uDCA3","key",G,"was used to mint a counterfeit token for",H,`"${Q}"`);let J=`${Q}(${G})`,z=cG[H];return{counterfeit:!0,key:J,type:z,family:{key:Q,subKey:G}}}let $;if(X===J2){if(Y.logger.info("\uD83D\uDC6A",Z.type,Z.key,"adds member",typeof _==="string"?`\`${_}\``:_),$=Z.create(_),W)Y.moleculeData.set(G,Z.key)}else{let{type:H,key:Q}=Z,J=`${Q}(${G})`,z=cG[H];return{key:J,type:z,family:{key:Q,subKey:G}}}return $}function rY(X,...Y){let Z,_,G,W,$;if(Y.length===1){if($=Y[0],"family"in $){let Q=nY(X,$);if(G=T0(X,Q),W=X1($.family.subKey),Z=z2(X,Q,W),"counterfeit"in $)return{token:$,family:G,subKey:W,isNew:!1};if(!Z)_=Q2(J2,X,Q,W),$=_;else $=Z}}else if(G=T0(X,Y[0]),W=Y[1],Z=z2(X,G,W),!Z)_=Q2(J2,X,G,W),$=_;else $=Z;let H="counterfeit"in $;if(Boolean(_)&&H===!1&&G){let Q;switch($.type){case"readonly_pure_selector":case"readonly_held_selector":Q="readable";break;case"atom":case"mutable_atom":case"writable_pure_selector":case"writable_held_selector":Q="writable";break}let J={type:"state_creation",subType:Q,token:$,timestamp:Date.now()};G.subject.next(J);let z=s(X);if($.family){if(O8(z))switch($.type){case"atom":case"mutable_atom":X.on.atomCreation.next($);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":X.on.selectorCreation.next($);break}else if(z1(z)&&z.on.transactionApplying.state===null)z.transactionMeta.update.subEvents.push(J)}}return{token:$,family:G,subKey:W,isNew:Boolean(_)}}function h1(X,...Y){let{token:Z,family:_,subKey:G}=rY(X,...Y);if("counterfeit"in Z&&_&&G)return tG(X,Z,_,G);let W=T0(X,Z);return f4(X,W)}function z2(X,Y,Z){let _=w0(Z),G=`${Y.key}(${_})`,W=s(X),$;switch(Y.type){case"atom_family":case"mutable_atom_family":$=W.atoms.get(G);break;case"writable_held_selector_family":case"writable_pure_selector_family":$=W.writableSelectors.get(G);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":$=W.readonlySelectors.get(G);break}if($)return y1($);return $}function e0(X,Y,Z){let _=T0(X,Y),G=z2(X,Y,Z);if(G)return G;return Q2($U,X,_,Z)}function F2(X,Y,Z){let _=Y.key,G="readonly_pure_selector_family",W={key:_,type:"readonly_pure_selector_family"},$=X.families.get(_);if($)X.logger.error("\u2757","readonly_pure_selector_family",_,`Overwriting an existing ${_4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Z0,J={...W,create:(z)=>{let F=w0(z),O={key:_,subKey:F},D=`${_}(${F})`,w=s(X),A={key:D,get:Y.get(z)};if(Y.catch)A.catch=Y.catch;return eY(w,A,O)},internalRoles:Z,subject:H,install:(z)=>F2(z,Y),default:(z)=>{return Y.get(z)({get:(...F)=>h1(X,...F),find:(...F)=>e0(X,...F),json:(F)=>h4(X,F)})}};return X.families.set(_,J),W}function G2(X,Y,Z){let _={key:Y.key,type:"atom_family"},G=X.families.get(Y.key);if(G)X.logger.error("\u2757","atom_family",Y.key,`Overwriting an existing ${_4[G.type]} "${G.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let W=new Z0,H={..._,create:(Q)=>{let J=w0(Q),z={key:Y.key,subKey:J},F=`${Y.key}(${J})`,O=s(X),D=Y.default,w={key:F,default:H2(D)?()=>D(Q):D};if(Y.effects)w.effects=Y.effects(Q);if(Y.catch)w.catch=Y.catch;return x4(O,w,z)},default:Y.default,subject:W,install:(Q)=>G2(Q,Y),internalRoles:Z};if(X.families.set(Y.key,H),H2(Y.default)===!1)X.defaults.set(Y.key,Y.default);return _}function aG(X,Y,Z){let _=Y.key,G="readonly_held_selector_family",W={key:_,type:"readonly_held_selector_family"},$=X.families.get(_);if($)X.logger.error("\u2757","readonly_held_selector_family",_,`Overwriting an existing ${_4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Z0,J={...W,create:(z)=>{let F=w0(z),O={key:_,subKey:F},D=`${_}(${F})`,w=s(X);return aY(w,{key:D,const:Y.const(z),get:Y.get(z)},O)},internalRoles:Z,subject:H,install:(z)=>aG(z,Y),default:Y.const};return X.families.set(_,J),W}function eG(X,Y,Z){let _=Y.key,G="writable_held_selector_family",W={key:_,type:"writable_held_selector_family"},$=X.families.get(_);if($)X.logger.error("\u2757","writable_held_selector_family",_,`Overwriting an existing ${_4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Z0,J={...W,create:(z)=>{let F=w0(z),O={key:_,subKey:F},D=`${_}(${F})`,w=s(X);return XZ(w,{key:D,const:Y.const(z),get:Y.get(z),set:Y.set(z)},O)},internalRoles:Z,subject:H,install:(z)=>eG(z,Y),default:Y.const};return X.families.set(_,J),W}function sY(X,Y,Z){let _=Y.key,G="writable_pure_selector_family",W={key:_,type:"writable_pure_selector_family"},$=X.families.get(_);if($)X.logger.error("\u2757","writable_pure_selector_family",_,`Overwriting an existing ${_4[$.type]} "${$.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new Z0,J={...W,create:(z)=>{let F=w0(z),O={key:_,subKey:F},D=`${_}(${F})`,w=s(X),A={key:D,get:Y.get(z),set:Y.set(z)};if(Y.catch)A.catch=Y.catch;return YZ(w,A,O)},internalRoles:Z,subject:H,install:(z)=>sY(z,Y),default:(z)=>{return Y.get(z)({get:(...F)=>h1(X,...F),find:(...F)=>e0(X,...F),json:(F)=>h4(X,F)})}};return X.families.set(_,J),W}function bY(X,Y){let Z="set"in Y,_="const"in Y;if(_&&Z)return eG(X,Y,void 0);if(_)return aG(X,Y,void 0);if(Z)return sY(X,Y);return F2(X,Y)}function W2(X,...Y){let Z;if(Y.length===1)Z=Y[0];else{let _=Y[0],G=Y[1];Z=e0(X,_,G)}try{T0(X,Z)}catch(_){X.logger.error("\u274C",Z.type,Z.key,`could not be disposed because it was not found in the store "${X.config.name}".`);return}switch(Z.type){case"atom":case"mutable_atom":$7(X,Z);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":OU(X,Z);break}}function X7(X,Y){if(X.operation.open){let Z=performance.now();return X.logger.info("\uD83D\uDEAB",Y.type,Y.key,`deferring setState at T-${Z} until setState for "${X.operation.token.key}" is done`),Z}return X.operation={open:!0,done:new Set,prev:new Map,timestamp:Date.now(),token:Y,subEvents:[]},X.logger.info("\u2B55",Y.type,Y.key,`operation start in store "${X.config.name}"${z1(X)?` ${X.transactionMeta.phase} "${X.transactionMeta.update.token.key}"`:""}`),X}function Y7(X){if(X.operation.open)X.logger.info("\uD83D\uDD34",X.operation.token.type,X.operation.token.key,`operation done in store "${X.config.name}"`);X.operation={open:!1},X.on.operationClose.next(X.operation)}var Z7=(X,Y)=>{if(!X.operation.open)return X.logger.error("\uD83D\uDC1E","unknown",Y,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return X.operation.done.has(Y)},B6=(X,Y)=>{if(!X.operation.open){X.logger.error("\uD83D\uDC1E","unknown",Y,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}X.operation.done.add(Y)};function lY(X,Y,{oldValue:Z,newValue:_},G,W){let $=y1(Y);if(G&&W){Y.subject.next({newValue:_});let F={checkpoint:!0,type:"state_creation",subType:"writable",token:$,timestamp:Date.now(),value:_};X.operation.subEvents.push(F),W.subject.next(F);let O=s(X);if($.family){if(O8(O))switch($.type){case"atom":case"mutable_atom":X.on.atomCreation.next($);break;case"writable_pure_selector":case"writable_held_selector":X.on.selectorCreation.next($);break}else if(z1(O)&&O.on.transactionApplying.state===null)O.transactionMeta.update.subEvents.push(F)}return}let{key:H,subject:Q,type:J}=Y,z={oldValue:uY(Z)?Z.READONLY_VIEW:Z,newValue:uY(_)?_.READONLY_VIEW:_};if(O8(X)){switch(J){case"mutable_atom":X.logger.info("\uD83D\uDCE2",J,H,"is now (",_,") subscribers:",Q.subscribers.keys());break;case"atom":case"writable_pure_selector":case"writable_held_selector":X.logger.info("\uD83D\uDCE2",J,H,"went (",Z,"->",_,") subscribers:",Q.subscribers.keys())}Q.next(z)}if(z1(X)&&(J==="mutable_atom"||J==="atom")){if(X.on.transactionApplying.state===null){if(uY(_))return;let{timestamp:F}=X.operation,O={type:"atom_update",token:$,timestamp:F,update:z};X.transactionMeta.update.subEvents.push(O),X.logger.info("\uD83D\uDCC1","atom",H,"stowed (",Z,"->",_,")");return}if(WZ(Y,"tracker:signal")){let F=H.slice(1),O=X.atoms.get(F);if(f4(X,O,"mut").do(z.newValue)===null===!0)GZ(X,O)}}}var oY=(X,Y,Z)=>{let _=f4(X,Y,"mut"),G=dY(Z,_);return X.logger.info("\u2B50","atom",Y.key,"setting value",G),G=K1(X,Y,G),B6(X,Y.key),GZ(X,Y),{oldValue:_,newValue:G}};function mY(X,Y){switch(Y.type){case"mutable_atom":return oY(X,Y,new Y.class);case"atom":{let Z;if(H2(Y.default))Z=N6(X,Y);else Z=Y.default;return oY(X,Y,Z)}}}function HU(X,Y){let Z;switch(Y.type){case"atom":case"mutable_atom":Z=mY(X,Y);break;case"writable_held_selector":{let _=U2(X,Y.key);for(let W of _.values()){let $=mY(X,W);lY(X,Y,$,!1)}let G=Y.getFrom(X);Z={oldValue:G,newValue:G}}break;case"writable_pure_selector":{let _=N6(X,Y),G=U2(X,Y.key);for(let $ of G.values()){let H=mY(X,$);lY(X,Y,H,!1)}let W=N6(X,Y);Z={oldValue:_,newValue:W}}break}return Z}function k1(X,...Y){D8(I6,X,...Y)}var iY=Symbol("RESET");function R6(X,...Y){let Z=[...Y,iY];k1(X,...Z)}function JU(X,Y,Z){let _,G,W,{type:$,key:H}=Y;switch(Y.type){case"writable_pure_selector":_=f4(X,Y,"mut"),G=dY(Z,_),G=K1(X,Y,G);break;case"writable_held_selector":W=Y.const,dY(Z,W),_=W,G=W}return X.logger.info("\u2B50",$,H,"setting to",G),B6(X,H),Y.setSelf(G),{oldValue:_,newValue:G}}var QU=(X,Y,Z)=>{let _;switch(Y.type){case"atom":case"mutable_atom":_=oY(X,Y,Z);break;case"writable_pure_selector":case"writable_held_selector":_=JU(X,Y,Z);break}return _},I6=Symbol("OWN_OP"),tY=Symbol("JOIN_OP");function D8(X,Y,...Z){let _,G,W,$,H,Q;if(Z.length===2){if(W=Z[0],Q=Z[1],"family"in W)if($=nY(Y,W),H=X1(W.family.subKey),_=z2(Y,$,H),!_)W=G=Q2(J2,Y,$,H);else W=_}else if($=T0(Y,Z[0]),H=Z[1],Q=Z[2],_=z2(Y,$,H),!_)W=G=Q2(J2,Y,$,H);else W=_;let J=Q===iY?"reset":"set",z;if(X===I6){let D=X7(Y,W);if(typeof D==="number"){let w=D,A=Y.on.operationClose.subscribe(`waiting to ${J} "${W.key}" at T-${w}`,function(){A(),Y.logger.info("\uD83D\uDFE2",W.type,W.key,"resuming deferred",J,`from T-${w}`),D8(X,Y,W,Q)});return}z=D}else z=Y;if("counterfeit"in W&&"family"in W){let D=W.family.subKey,w=Y.disposalTraces.buffer.find((A)=>A?.key===D);Y.logger.error("\u274C",W.type,W.key,"could not be",J,"because key",D,"is not allocated.",w?`this key was previously disposed:${w.trace}`:"(no previous disposal trace found)");return}let F=T0(z,W),O;if(Q===iY)O=HU(z,F);else O=QU(z,F,Q);if(lY(z,F,O,Boolean(G),$),X===I6)Y7(z)}var _7=(X,Y)=>s(X).atoms.has(Y),zU=(X,Y)=>s(X).writableSelectors.has(Y),FU=(X,Y)=>s(X).readonlySelectors.has(Y),UU=(X,Y)=>_7(X,Y)||zU(X,Y)||FU(X,Y);function lG(X,Y){return s(X).selectorGraph.getRelationEntries({downstreamSelectorKey:Y}).filter(([Z,{source:_}])=>_!==Y).map(([Z,{source:_}])=>_).filter((Z)=>UU(X,Z))}function U2(X,Y,Z=new Set){let _=lG(X,Y),G=new Map;while(_.length>0){let W=_.pop();if(Z.has(W))continue;if(Z.add(W),_7(X,W)){let $=X.atoms.get(W);G.set($.key,$)}else _.push(...lG(X,W))}return G}function EU(X,Y,Z,_,G){let W=s(X),{type:$,key:H}=_;if($==="atom"||$==="mutable_atom")W.selectorAtoms.set({selectorKey:Z,atomKey:H}),X.logger.info("\uD83D\uDD0D",Y,Z,`discovers root atom "${H}"`);else{let Q=U2(X,H,G);X.logger.info("\uD83D\uDD0D",Y,Z,`discovers root atoms: [ ${[...Q.values()].map((J)=>`"${J.key}"`).join(", ")} ]`);for(let{key:J}of Q.values())W.selectorAtoms=W.selectorAtoms.set({selectorKey:Z,atomKey:J})}G.add(H)}function T6(X,Y,Z,_){return{get:(...G)=>{let W=s(X),{token:$,family:H,subKey:Q}=rY(X,...G),J;if("counterfeit"in $&&H&&Q)J=tG(X,$,H,Q);else{let z=T0(X,$);J=f4(X,z)}return X.logger.info("\uD83D\uDD0C",Y,Z,`registers dependency ( "${$.key}" =`,J,")"),W.selectorGraph.set({upstreamSelectorKey:$.key,downstreamSelectorKey:Z},{source:$.key}),EU(X,Y,Z,$,_),J},set:(...G)=>{let W=s(X);D8(tY,W,...G)},find:(...G)=>e0(X,...G),json:(G)=>h4(X,G)}}function aY(X,Y,Z){let _=s(X),G=new Z0,W=new Set,{key:$,const:H}=Y,Q="readonly_held_selector";X.logger.info("\uD83D\uDD28","readonly_held_selector",$,"is being created");let{get:J,find:z,json:F}=T6(_,"readonly_held_selector",$,W),D={...Y,type:"readonly_held_selector",subject:G,getFrom:(A)=>{let x=A.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[j,{source:P}]of x)if(P!==$)A.selectorGraph.delete(j,$);return A.selectorAtoms.delete($),Y.get({get:J,find:z,json:F},H),K1(A,D,H),X.logger.info("\u2728","readonly_held_selector",$,"=",H),W.clear(),H},install:(A)=>aY(A,Y,Z)};if(Z)D.family=Z;_.readonlySelectors.set($,D);let w={key:$,type:"readonly_held_selector"};if(Z)w.family=Z;return w}function eY(X,Y,Z){let _=s(X),G=new Z0,W=new Set,$=Y.key,H="readonly_pure_selector";X.logger.info("\uD83D\uDD28","readonly_pure_selector",$,"is being created");let{get:Q,find:J,json:z}=T6(_,"readonly_pure_selector",$,W),O={...Y,type:"readonly_pure_selector",subject:G,getFrom:()=>{let w=s(X),A=w.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[P,{source:h}]of A)if(h!==$)w.selectorGraph.delete(P,$);w.selectorAtoms.delete($);let x=Y.get({get:Q,find:J,json:z}),j=K1(w,O,x);return X.logger.info("\u2728","readonly_pure_selector",$,"=",j),W.clear(),j},install:(w)=>eY(w,Y,Z)};if(Z)O.family=Z;_.readonlySelectors.set($,O);let D={key:$,type:"readonly_pure_selector"};if(Z)D.family=Z;return D}function XZ(X,Y,Z){let _=s(X),G=new Z0,W=new Set,{key:$,const:H}=Y,Q="writable_held_selector";X.logger.info("\uD83D\uDD28","writable_held_selector",$,"is being created");let J=T6(_,"writable_held_selector",$,W),{find:z,get:F,json:O}=J,D={find:z,get:F,json:O},x={...Y,type:"writable_held_selector",subject:G,getFrom:(P)=>{let h=P.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[i,{source:p}]of h)if(p!==$)P.selectorGraph.delete(i,$);return P.selectorAtoms.delete($),Y.get(D,H),K1(P,x,H),X.logger.info("\u2728","writable_held_selector",$,"=",H),W.clear(),H},setSelf:()=>{Y.set(J,H)},install:(P)=>XZ(P,Y,Z)};if(Z)x.family=Z;_.writableSelectors.set($,x);let j={key:$,type:"writable_held_selector"};if(Z)j.family=Z;return j}function YZ(X,Y,Z){let _=s(X),G=new Z0,W=new Set,$=Y.key,H="writable_pure_selector";X.logger.info("\uD83D\uDD28","writable_pure_selector",$,"is being created");let Q=T6(_,"writable_pure_selector",$,W),{find:J,get:z,json:F}=Q,O={find:J,get:z,json:F},A={...Y,type:"writable_pure_selector",subject:G,getFrom:(j)=>{let P=j.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[p,{source:y}]of P)if(y!==$)j.selectorGraph.delete(p,$);j.selectorAtoms.delete($);let h=Y.get(O),i=K1(j,A,h);return X.logger.info("\u2728","writable_pure_selector",$,"=",i),W.clear(),i},setSelf:(j)=>{Y.set(Q,j)},install:(j)=>YZ(j,Y,Z)};if(Z)A.family=Z;_.writableSelectors.set($,A);let x={key:$,type:"writable_pure_selector"};if(Z)x.family=Z;return x}function hG(X,Y){let Z="set"in Y,_="const"in Y;if(_&&Z){let W=XZ(X,Y,void 0);return X.on.selectorCreation.next(W),W}if(_){let W=aY(X,Y,void 0);return X.on.selectorCreation.next(W),W}if(Z){let W=YZ(X,Y,void 0);return X.on.selectorCreation.next(W),W}let G=eY(X,Y,void 0);return X.on.selectorCreation.next(G),G}function OU(X,Y){let Z=s(X),{key:_,type:G,family:W}=Y;if(!W)X.logger.error("\u274C",G,_,"Standalone selectors cannot be disposed.");else{if(Z.molecules.get(W.subKey))Z.moleculeData.delete(W.subKey,W.key);let $;switch(Y.type){case"writable_held_selector":Z.writableSelectors.delete(_),$={key:W.key,type:"writable_held_selector_family"},T0(X,$).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break;case"writable_pure_selector":Z.writableSelectors.delete(_),$={key:W.key,type:"writable_pure_selector_family"},T0(X,$).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break;case"readonly_held_selector":Z.readonlySelectors.delete(_),$={key:W.key,type:"readonly_held_selector_family"},T0(X,$).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break;case"readonly_pure_selector":Z.readonlySelectors.delete(_),$={key:W.key,type:"readonly_pure_selector_family"},T0(X,$).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break}if(Z.valueMap.delete(_),Z.selectorAtoms.delete(_),Z.selectorGraph.delete(_),Z.moleculeData.delete(W.key,W.subKey),X.logger.info("\uD83D\uDD25",Y.type,_,"deleted"),z1(Z)&&Z.transactionMeta.phase==="building")Z.transactionMeta.update.subEvents.push({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});else X.on.selectorDisposal.next(Y)}}var VU=(X,Y)=>{let Z=s(X);if(Z.operation.open)return Z.operation.prev.get(Y.key);return Z.valueMap.get(Y.key)},oG=(X,Y,Z)=>{return Z.subject.subscribe(`${Y.type}:${Y.key}`,(_)=>{X.logger.info("\uD83D\uDCE2",Y.type,Y.key,"root",Z.key,"went",_.oldValue,"->",_.newValue);let G=VU(X,Y),W=f4(X,Y);X.logger.info("\u2728",Y.type,Y.key,"went",G,"->",W),Y.subject.next({newValue:W,oldValue:G})})};function E2(X,Y,Z,_){function G(F){if(X.operation.open){if(W?.type==="atom"&&WZ(W,"tracker:signal")&&"*"+X.operation.token.key===Y.key&&"inboundTracker"in _)return;let O=X.on.operationClose.subscribe(`state subscription ${Z}`,()=>{O(),_(F)})}else _(F)}rY(X,Y);let W=T0(X,Y);X.logger.info("\uD83D\uDC40",W.type,W.key,`Adding subscription "${Z}"`);let $=W.type==="writable_pure_selector"||W.type==="readonly_pure_selector",H=new Map,Q=G;if($){f4(X,W);for(let[F,O]of U2(X,W.key))H.set(F,oG(X,W,O));Q=function(O){let D=U2(X,W.key);for(let[w,A]of H)if(D.get(w))D.delete(w);else A(),H.delete(w);for(let[w,A]of D)H.set(w,oG(X,W,A));G(O)}}let J=W.subject.subscribe(Z,Q);return()=>{X.logger.info("\uD83D\uDE48",W.type,W.key,`Removing subscription "${Z}"`),J();for(let F of H.values())F()}}var DU=(X,Y,Z,_)=>{let G=T0(X,Y);X.logger.info("\uD83D\uDC40","timeline",Y.key,`Adding subscription "${Z}"`);let W=G.subject.subscribe(Z,_);return()=>{X.logger.info("\uD83D\uDE48","timeline",Y.key,`Removing subscription "${Z}" from timeline`),W()}};var ZZ=class{initializeSignalAtom(X,Y){let Z=`*${X.key}`;Y.atoms.delete(Z),Y.valueMap.delete(Z);let _=X.family?{key:`*${X.family.key}`,subKey:X.family.subKey}:void 0,G=x4(Y,{key:Z,default:null},_,["tracker:signal"]);if(Y.parent?.valueMap.has(Z)){let W=Y.parent.valueMap.get(Z);Y.valueMap.set(Z,W)}return G}unsubscribeFromInnerValue;unsubscribeFromState;captureSignalsFromCore(X,Y,Z){let _=X.key,G=Z.config.name,W=z1(Z)?Z.transactionMeta.update.token.key:"main",$=`tracker-from-core:${G}:${W}:${_}`,H=(Q)=>{D8(tY,Z,Y,Q)};this.unsubscribeFromInnerValue=h1(Z,X).subscribe($,H),this.unsubscribeFromState=E2(Z,X,$,function(J){if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe($,H)}.bind(this))}supplySignalsToCore(X,Y,Z){let _=X.key,G=Z.config.name,W=z1(Z)?Z.transactionMeta.update.token.key:"main",$=`tracker-to-core:${G}:${W}:${_}`;E2(Z,Y,$,Object.assign(function({newValue:Q,oldValue:J}){let z=Z.timelineTopics.getRelatedKey(Y.key);if(z&&Z.timelines.get(z)?.timeTraveling){let F=DU(Z,{key:z,type:"timeline"},$,function(D){F(),k1(Z,X,(w)=>{if(D==="redo"&&Q)w.do(Q);else if(D==="undo"&&J)w.undo(J);return w})});return}k1(Z,X,(F)=>(F.do(Q),F))},{inboundTracker:!0}))}mutableAtomToken;latestSignalToken;[Symbol.dispose];constructor(X,Y){let Z=s(Y),_=this.initializeSignalAtom(X,Z);this.mutableAtomToken=X,this.latestSignalToken=_,this.captureSignalsFromCore(X,_,Z),this.supplySignalsToCore(X,_,Z),Z.trackers.set(X.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),Z.trackers.delete(X.key)}}};function w6(X,Y,Z){X.logger.info("\uD83D\uDD28","atom",Y.key,`creating in store "${X.config.name}"`);let _=s(X),{key:G}=Y,W=_.atoms.get(G),$="mutable_atom";if(W&&W.type===$)return X.logger.error("\u274C",$,G,"Tried to create atom, but it already exists in the store."),y1(W);let H=new Z0,Q={...Y,type:$,install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${z.config.name}"`),w6(z,Y,Z)},subject:H};if(Z)Q.family=Z;_.atoms.set(Q.key,Q);let J=y1(Q);if(Y.effects){let z=0,F=[];for(let O of Y.effects){let D=O({resetSelf:()=>{R6(X,J)},setSelf:(w)=>{k1(X,J,w)},onSet:(w)=>E2(X,J,`effect[${z}]`,w)});if(D)F.push(D);++z}Q.cleanup=()=>{for(let O of F)O()}}if(new ZZ(J,X),!Z)hG(X,{key:`${G}:JSON`,get:({get:z})=>z(J).toJSON(),set:({set:z},F)=>{z(J,Y.class.fromJSON(F))}});return X.on.atomCreation.next(J),J}var LU=class{trackers=new Map;latestSignalAtoms;mutableAtoms;constructor(X,Y){let Z=G2(Y,{key:`*${X.key}`,default:null},["mutable","updates"]);this.latestSignalAtoms=T0(Y,Z),this.mutableAtoms=X;let _=(G)=>{let{type:W,token:$}=G;if($.family){let H=X1($.family.subKey);switch(W){case"state_creation":this.trackers.set(H,new ZZ($,Y));break;case"state_disposal":{let Q=this.trackers.get(H);if(Q)Q[Symbol.dispose](),this.trackers.delete(H)}}}};this.mutableAtoms.subject.subscribe(`store=${Y.config.name}::tracker-atom-family`,_)}};function yY(X,Y,Z){let _={key:Y.key,type:"mutable_atom_family"},G=X.families.get(Y.key);if(G)X.logger.error("\u2757","mutable_atom_family",Y.key,`Overwriting an existing ${_4[G.type]} "${G.key}" in store "${X.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let W=new Z0,H={..._,create:(Q)=>{let J=w0(Q),z={key:Y.key,subKey:J},F=`${Y.key}(${J})`,O=s(X),D={key:F,class:Y.class};if(Y.effects)D.effects=Y.effects(Q);return w6(O,D,z)},class:Y.class,subject:W,install:(Q)=>yY(Q,Y),internalRoles:Z};return X.families.set(Y.key,H),sY(X,{key:`${Y.key}:JSON`,get:(Q)=>({get:J})=>J(_,Q).toJSON(),set:(Q)=>({set:J},z)=>{J(_,Q,Y.class.fromJSON(z))}},["mutable","json"]),new LU(H,X),_}var MU=(X,Y)=>{let Z=s(Y),_=`${X.key}:JSON`;return Z.families.get(_)},h4=(X,Y)=>{if(Y.family){let Z=s(X),_={key:`${Y.family.key}:JSON`,type:"writable_pure_selector_family"},G=T0(Z,_),W=X1(Y.family.subKey);return e0(X,G,W)}return{type:"writable_pure_selector",key:`${Y.key}:JSON`}};var _Z=(X)=>{let Y={type:"atom",key:`*${X.key}`};if(X.family)Y.family={key:`*${X.family.key}`,subKey:X.family.subKey};return Y};function uY(X){return typeof X==="object"&&X!==null&&"do"in X&&"undo"in X&&"subscribe"in X&&"READONLY_VIEW"in X&&"toJSON"in X}function K1(X,Y,Z){let{key:_,subject:G,type:W}=Y,$=X.valueMap.get(_);if($ instanceof cY&&!$.done){let H=$;if(Z instanceof Promise)return H.use(Z),H;return X.valueMap.set(_,Z),Z}if(Z instanceof Promise){let H=new cY(Z);return X.valueMap.set(_,H),H.then(function(J){if(X.valueMap.get(_)===H){switch(X7(X,Y),K1(X,Y,J),W){case"atom":GZ(X,Y);break;case"readonly_pure_selector":case"writable_pure_selector":W7(X,_);break}Y7(X),G.next({newValue:J,oldValue:H})}}).catch((Q)=>{X.logger.error("\uD83D\uDCA5",Y.type,_,"rejected:",Q)}),H}return X.logger.info("\uD83D\uDCDD",Y.type,Y.key,"writing to cache",Z),X.valueMap.set(_,Z),Z}function AU(X,Y,Z){X.logger.info("\uD83D\uDCD6",Y.type,Y.key,"reading cached value");let _=X.valueMap.get(Y.key);if(Z==="mut"&&Y.type==="mutable_atom"&&z1(X)){let G=Y,{parent:W}=X;if(X.valueMap.hasOwn(G.key))return _;let $=W.valueMap.get(G.key);X.logger.info("\uD83D\uDCC3","atom",G.key,"copying");let H=$.toJSON(),Q=G.class.fromJSON(H);X.valueMap.set(G.key,Q),new ZZ(G,W),_=Q}return _}function G7(X,Y){let Z=X.valueMap.get(Y);if(Z instanceof cY){let _=X.writableSelectors.get(Y)??X.readonlySelectors.get(Y);if(_)_.getFrom(X);return}if(X.operation.open)X.operation.prev.set(Y,Z);X.valueMap.delete(Y),X.logger.info("\uD83D\uDDD1","state",Y,"evicted")}function GZ(X,Y){let Z=s(X),{key:_,type:G}=Y,W=Z.selectorAtoms.getRelatedKeys(_);if(Z.logger.info("\uD83E\uDDF9",G,_,W?`evicting ${W.size} states downstream:`:"no downstream states",W??"to evict"),W){if(Z.operation.open)Z.logger.info("\uD83E\uDDF9",G,_,`[ ${[...Z.operation.done].join(", ")} ] already done`);for(let $ of W){if(Z7(Z,$))continue;G7(Z,$),B6(Z,$)}}}function W7(X,Y){let Z=s(X),_=Z.selectorGraph.getRelationEntries({upstreamSelectorKey:Y}).filter(([G,{source:W}])=>W===Y);for(let[G]of _){if(Z7(Z,G))continue;G7(Z,G),B6(Z,G),W7(X,G)}}function x4(X,Y,Z,_){let{key:W}=Y;X.logger.info("\uD83D\uDD28","atom",W,"is being created");let $=s(X),H=$.atoms.get(W);if(H&&H.type==="atom")return X.logger.error("\u274C","atom",W,"Tried to create atom, but it already exists in the store."),y1(H);let Q=new Z0,J={...Y,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",W,`installing in store "${F.config.name}"`),x4(F,Y,Z)},subject:Q};if(Z)J.family=Z;if(_)J.internalRoles=_;$.atoms.set(W,J);let z=y1(J);if(Y.effects){let F=0,O=[];for(let D of Y.effects){let w=D({resetSelf:()=>{R6(X,z)},setSelf:(A)=>{k1(X,z,A)},onSet:(A)=>E2(X,z,`effect[${F}]`,A)});if(w)O.push(w);++F}J.cleanup=()=>{for(let D of O)D()}}return X.on.atomCreation.next(z),z}function WZ(X,Y){if("internalRoles"in X===!1)return!1;return X.internalRoles.includes(Y)}function $7(X,Y){let Z=s(X),{key:_,family:G}=Y,W=T0(Z,Y);if(!G)X.logger.error("\u274C","atom",_,"Standalone atoms cannot be disposed.");else{W.cleanup?.();let $=X.valueMap.get(W.key),H=nY(X,Y),Q=T0(X,H).subject,J={type:"state_disposal",subType:"atom",token:Y,value:$,timestamp:Date.now()};Q.next(J);let z=z1(Z);if(Z.atoms.delete(_),Z.valueMap.delete(_),Z.selectorAtoms.delete(_),Z.atomsThatAreDefault.delete(_),Z.moleculeData.delete(G.key,G.subKey),X.timelineTopics.delete(_),Y.type==="mutable_atom"){let F=_Z(Y);$7(X,F),X.trackers.delete(_)}if(X.logger.info("\uD83D\uDD25","atom",_,"deleted"),z&&Z.transactionMeta.phase==="building"){let F=Z.transactionMeta.update.subEvents.at(-1),O=F?.type==="molecule_disposal"&&F.values.some(([w])=>w===W.family?.key),D=WZ(W,"tracker:signal");if(!O&&!D)Z.transactionMeta.update.subEvents.push(J)}else X.on.atomDisposal.next(Y)}}function I1(X){return X[0].toUpperCase()+X.slice(1)}var H7=class{toolkit;options;relations;states;relatedKeysAtoms;transact(X,Y){let Z=this.toolkit;this.toolkit=X,Y(this),this.toolkit=Z}store;realm;[Symbol.dispose](){}constructor(X,Y=Q1.STORE){this.store=Y,this.realm=new SG(Y),this.options=X,this.store.miscResources.set(`join:${X.key}`,this),this.realm.allocate("root",X.key),this.toolkit={get:(...z)=>h1(Y,...z),set:(...z)=>{k1(Y,...z)},find:(...z)=>e0(Y,...z),json:(z)=>h4(Y,z)};let Z=X.between[0],_=X.between[1],G=yY(Y,{key:`${X.key}/relatedKeys`,class:G4},["join","relations"]);this.relatedKeysAtoms=G;let W=(z,F,O)=>{let{find:D,get:w,set:A}=z,x=D(G,F),j=w(x);for(let P of j){if(O.includes(P))continue;A(G,P,(h)=>{return h.delete(F),h})}A(x,(P)=>{P.clear();for(let h of O){let i=D(G,h),p=w(i),y=p.has(F);if(this.relations.cardinality==="1:n"){let m=[];for(let _0 of p){if(_0===F)continue;let y0;if(D8(tY,this.store,G,_0,(K)=>{return K.delete(h),y0=K.size,K}),y0===0)m.push(_0)}if(!y&&p.size>0)A(i,(_0)=>{return _0.clear(),_0});for(let _0 of m){let[y0,K]=[h,_0].sort(),W0=`${y0}:${K}`;Y.moleculeJoins.delete(W0)}}if(!y)A(i,(m)=>{return m.add(F),m});P.add(h)}return P})},$=(z,F,O)=>{let{set:D}=z;D(G,F,(w)=>{for(let A of O)w.add(A);return w});for(let w of O)D(G,w,(A)=>{return A.add(F),A});return!0},H=new W4(X,{externalStore:{getRelatedKeys:(z)=>this.toolkit.get(G,z),addRelation:(z,F)=>{if(this.store.moleculeJoins.set(`"${z}"`,X.key),this.store.moleculeJoins.set(`"${F}"`,X.key),!this.store.molecules.has(w0(z)))this.realm.allocate(X.key,z);if(!this.store.molecules.has(w0(F)))this.realm.allocate(X.key,F);this.toolkit.set(G,z,(O)=>O.add(F)),this.toolkit.set(G,F,(O)=>O.add(z))},deleteRelation:(z,F)=>{this.toolkit.set(G,z,(A)=>{return A.delete(F),A}),this.toolkit.set(G,F,(A)=>{return A.delete(z),A});let[O,D]=[z,F].sort(),w=`${O}:${D}`;this.store.moleculeJoins.delete(w)},replaceRelationsSafely:(z,F)=>{W(this.toolkit,z,F)},replaceRelationsUnsafely:(z,F)=>{$(this.toolkit,z,F)},has:(z,F)=>{let O=this.toolkit.get(G,z);return F?O.has(F):O.size>0}},isAType:X.isAType,isBType:X.isBType}),Q=()=>F2(Y,{key:`${X.key}/singleRelatedKey`,get:(z)=>({get:F})=>{let O=F(G,z);for(let D of O)return D;return null}},["join","keys"]),J=()=>{return F2(Y,{key:`${X.key}/multipleRelatedKeys`,get:(z)=>({get:F})=>{let O=MU(G,Y);return F(O,z)}},["join","keys"])};switch(X.cardinality){case"1:1":{let z=Q(),F=`${Z}KeyOf${I1(_)}`,O=`${_}KeyOf${I1(Z)}`;this.relations=H,this.states={[F]:z,[O]:z};break}case"1:n":{let z=Q(),F=J(),O=`${Z}KeyOf${I1(_)}`,D=`${_}KeysOf${I1(Z)}`,w={[O]:z,[D]:F};this.relations=H,this.states=w;break}case"n:n":{let z=J(),F=`${Z}KeysOf${I1(_)}`,O=`${_}KeysOf${I1(Z)}`;this.relations=H,this.states={[F]:z,[O]:z}}}}};function kG(X,Y){return X.joins.set(Y.key,new H7(Y)),{key:Y.key,type:"join",a:Y.between[0],b:Y.between[1],cardinality:Y.cardinality}}function $Z(X,Y){let Z=Y.joins.get(X.key);if(Z===void 0){let _=Q1.STORE.joins.get(X.key);if(_===void 0)throw Error(`Join "${X.key}" not found in store "${Y.config.name}"`);let G=pF(Y);Z=new H7(_.options,G),Y.joins.set(X.key,Z)}return Z}function $2(X,Y,Z){let _=$Z(X,Z),G=s(Z);if(z1(G)){let{toolkit:W}=G.transactionMeta;_.transact(W,({relations:$})=>{Y($)})}else Y(_.relations)}function gF(X,Y,Z){let _=$Z(X,Z),G;switch(X.cardinality){case"1:1":{let W=`${X.a}KeyOf${I1(X.b)}`,$=`${X.b}KeyOf${I1(X.a)}`;G={get[W](){let H=_.states[W];return e0(Z,H,Y)},get[$](){let H=_.states[$];return e0(Z,H,Y)}};break}case"1:n":{let W=`${X.a}KeyOf${I1(X.b)}`,$=`${X.b}KeysOf${I1(X.a)}`;G={get[W](){let H=_.states[W];return e0(Z,H,Y)},get[$](){let H=_.states[$];return e0(Z,H,Y)}};break}case"n:n":{let W=`${X.a}KeysOf${I1(X.b)}`,$=`${X.b}KeysOf${I1(X.a)}`;G={get[W](){let H=_.states[W];return e0(Z,H,Y)},get[$](){let H=_.states[$];return e0(Z,H,Y)}}}}return G}function bG(X,Y){return $Z(X,Y).relatedKeysAtoms}var RU=(X)=>{return x4(X,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Y=new Map;for(let[Z,_]of X.atoms){if(V8(Z))continue;let G=y1(_);if(_.family){let W=Y.get(_.family.key);if(!W||!("familyMembers"in W))W={key:_.family.key,familyMembers:new Map},Y.set(_.family.key,W);W.familyMembers.set(_.family.subKey,G)}else Y.set(Z,G)}return Y},effects:[({setSelf:Y})=>{X.on.atomCreation.subscribe("introspection",(Z)=>{if(V8(Z.key))return;Y((_)=>{if(Z.family){let{key:G,subKey:W}=Z.family,$=_.get(G);if($===void 0||!("familyMembers"in $))$={key:G,familyMembers:new Map},_.set(G,$);$.familyMembers.set(W,Z)}else _.set(Z.key,Z);return new Map(_)})}),X.on.atomDisposal.subscribe("introspection",(Z)=>{Y((_)=>{if(Z.family){let{key:G,subKey:W}=Z.family,$=_.get(G);if($&&"familyMembers"in $){if($.familyMembers.delete(W),$.familyMembers.size===0)_.delete(G)}}return new Map(_)})})}]},void 0)},wU=(X)=>{return x4(X,{key:"\uD83D\uDD0D Selector Token Index",default:()=>{let Y=new Map;for(let Z of[X.readonlySelectors,X.writableSelectors])for(let[_,G]of Z){if(V8(_))continue;let W=y1(G);if(G.family){let $=Y.get(G.family.key);if(!$||!("familyMembers"in $))$={key:G.family.key,familyMembers:new Map},Y.set(G.family.key,$);$.familyMembers.set(G.family.subKey,W)}else Y.set(_,W)}return Y},effects:[({setSelf:Y})=>{X.on.selectorCreation.subscribe("introspection",(Z)=>{if(V8(Z.key))return;Y((_)=>{if(Z.family){let{key:G,subKey:W}=Z.family,$=_.get(G);if($===void 0||!("familyMembers"in $))$={key:G,familyMembers:new Map},_.set(G,$);$.familyMembers.set(W,Z)}else _.set(Z.key,Z);return new Map(_)})}),X.on.selectorDisposal.subscribe("introspection",(Z)=>{Y((_)=>{if(Z.family){let{key:G,subKey:W}=Z.family,$=_.get(G);if($&&"familyMembers"in $){if($.familyMembers.delete(W),$.familyMembers.size===0)_.delete(G)}}else _.delete(Z.key);return new Map(_)})})}]},void 0)};var HZ=class{supported;constructor(X){this.supported=X}refine(X){for(let[Y,Z]of Object.entries(this.supported))try{if(Z(X)===!0&&Z!==Boolean)return{type:Y,data:X}}catch(_){try{if(X instanceof Z)return{type:Y,data:X}}catch(G){}}return null}},Q7=new HZ({number:(X)=>typeof X==="number",string:(X)=>typeof X==="string",boolean:(X)=>typeof X==="boolean",null:(X)=>X===null});function z7(X){if(!X)return!1;return Object.getPrototypeOf(X)===Object.prototype}var F7=new HZ({object:z7,array:(X)=>Array.isArray(X)}),NU=new HZ({...Q7.supported,...F7.supported}),C6=(X)=>{if(X===void 0)return"undefined";let Y=NU.refine(X);if(Y)return Y.type;return Object.getPrototypeOf(X).constructor.name};var HB=class X{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Y=Q1.STORE){this.store=Y,this.atomIndex=RU(this.store),this.selectorIndex=wU(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:Z})=>{this.statesCreatedAt.set(Z,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:Z})=>{this.statesCreatedAt.delete(Z)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:Z})=>{this.statesCreatedAt.set(Z,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:Z})=>{this.statesCreatedAt.delete(Z)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(Y=X.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw Error("This Auditor has been disposed");let Z=hY(this.atomIndex),_=hY(this.selectorIndex),G=[...Z.values()].filter((Q)=>("familyMembers"in Q)),W=[..._.values()].filter((Q)=>("familyMembers"in Q)),$=performance.now(),H=[];if(Y.atomFamilies)for(let Q of G){let J=Q.familyMembers.values();for(let z of J){let F=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,O=$-F;H.push([z,O])}}if(Y.selectorFamilies)for(let Q of W){let J=Q.familyMembers.values();for(let z of J){let F=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,O=$-F;H.push([z,O])}}return H}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},J7=(X,Y)=>{let Z=(_,G)=>{let $=((Q,J)=>{let z=Y(Q,J);if(z)return z;return null})(_,G);if($?.jobComplete??$?.pathComplete)return $;let H=Array.isArray(G)?G.map((Q,J)=>[J,Q]):z7(G)?Object.entries(G):[];for(let[Q,J]of H){let z=Z([..._,Q],J);if(z?.jobComplete)return z}return{}};Z([],X)};function IU(X,Y){return{summary:`${X<Y?"+":"-"}${Math.abs(X-Y)} (${X} \u2192 ${Y})`}}function KU(X,Y){return{summary:`${X.length<Y.length?"+":"-"}${Math.abs(X.length-Y.length)} ("${X}" \u2192 "${Y}")`}}function BU(X,Y){return{summary:`${X} \u2192 ${Y}`}}function U7(X,Y,Z){let _="",G=[],W=[],$=[];return J7(X,(H,Q)=>{let J;for(J of H){let z=Y[J];if(z===void 0)W.push([J,JSON.stringify(Q)]);else{let F=Z(Q,z);if(F.summary!=="No Change")$.push([J,F])}}}),J7(Y,(H,Q)=>{let J;for(J of H)if(X[J]===void 0)G.push([J,JSON.stringify(Q)])}),_=`\uFF5E${$.length} \uFF0B${G.length} \uFF0D${W.length}`,{summary:_,added:G,removed:W,changed:$}}function TU(X,Y,Z){return U7(X,Y,Z)}var CU=class{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(X,Y,Z){this.leafRefinery=X,this.treeRefinery=Y,this.leafDiffers={},this.treeDiffers={};for(let _ of Object.keys(X.supported)){let G=Z[_];this.leafDiffers[_]=G}for(let _ of Object.keys(Y.supported)){let G=Z[_];this.treeDiffers[_]=G}}diff(X,Y){if(X===Y)return{summary:"No Change"};let Z=this.leafRefinery.refine(X)??this.treeRefinery.refine(X),_=this.leafRefinery.refine(Y)??this.treeRefinery.refine(Y);if(Z!==null&&_!==null){if(Z.type===_.type){if(Z.type in this.leafDiffers)return this.leafDiffers[Z.type](Z.data,_.data);if(Z.type in this.treeDiffers)return this.treeDiffers[Z.type](Z.data,_.data,($,H)=>this.diff($,H))}}let G=C6(X),W=C6(Y);if(G===W)return{summary:`${G} \u2192 ${W}`};return{summary:`Type change: ${G} \u2192 ${W}`}}},JB=new CU(Q7,F7,{number:IU,string:KU,boolean:BU,null:()=>({summary:"No Change"}),object:U7,array:TU});var qU=E8({key:"mutex",default:!1}),jU=class extends Map{set(X,Y){if(this.has(X))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:X,value:Y}),this;return super.set(X,Y)}},OB=class X{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Y){this.key=Y}static existing=new jU;static create(Y,Z){let _=new X(Y),{type:G,globals:W,actions:$,perspectives:H}=Z(_),Q={type:G,key:Y,globals:W,actions:$,perspectives:H};return X.existing.set(Y,Q),Q}add(...Y){switch(Y[0].type){case"atom":case"mutable_atom":this.globals.push(...Y);break;case"transaction":this.actions.push(...Y);break;case"atom_family":case"mutable_atom_family":{let[Z,_]=Y;this.perspectives.push({type:"realtime_perspective",resourceAtoms:Z,viewAtoms:_})}break}return this}};var VB=U8({key:"usersInRoomIndex",class:G4}),E7=U8({key:"roomIndex",class:G4});var O2=V6({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(X)=>typeof X==="string",isBType:(X)=>typeof X==="string"}),DB=D6({key:"usersInMyRoomView",get:(X)=>({find:Y})=>{let Z=qG(O2);return[Y(Z,X)]}});var TB=E8({key:"redactor",default:{occlude:(X)=>X}}),CB=E8({key:"unacknowledgedUpdates",default:()=>[]});var JZ=class{listeners;globalListeners;handleEvent(...X){let[Y,...Z]=X;for(let G of this.globalListeners)G(Y,...Z);let _=this.listeners.get(Y);if(_)for(let G of _)G(...Z)}id="no_id_retrieved";emit;constructor(X){this.emit=X,this.listeners=new Map,this.globalListeners=new Set}on(X,Y){let Z=this.listeners.get(X);if(Z)Z.add(Y);else this.listeners.set(X,new Set([Y]));return this}onAny(X){return this.globalListeners.add(X),this}off(X,Y){let Z=this.listeners.get(X);if(Z)if(Y)Z.delete(Y);else this.listeners.delete(X);return this}offAny(X){return this.globalListeners.delete(X),this}},qB=class extends JZ{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";proc;key;logger;handleLog(X){if(Array.isArray(X)){let[Y,...Z]=X;switch(Y){case"i":this.logger.info(...Z);break;case"w":this.logger.warn(...Z);break;case"e":this.logger.error(...Z);break}}}constructor(X,Y,Z){super((_,...G)=>{let W=JSON.stringify([_,...G])+"\x03",$=(H)=>{if(H.code==="EPIPE")console.error("EPIPE error during write",this.proc.stdin);this.proc.stdin.removeListener("error",$)};return this.proc.stdin.once("error",$),this.proc.stdin.write(W),this});if(this.proc=X,this.key=Y,this.logger=Z??{info:(..._)=>{console.info(this.id,this.key,..._)},warn:(..._)=>{console.warn(this.id,this.key,..._)},error:(..._)=>{console.error(this.id,this.key,..._)}},this.proc.stdout.on("data",(_)=>{let G=_.toString();if(G==="ALIVE"){this.logger.info(G);return}let W=G.split("\x03"),$=W[0];W[0]=this.incompleteData+$;let H=0;for(let Q of W){if(Q==="")continue;try{let J=X1(Q);this.handleEvent(...J),this.incompleteData=""}catch(J){if(J instanceof Error)console.error(["\u274C Malformed data received from child process","",Q,"",J.message].join(`
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(`
60
60
  \u274C `));try{if(H===0){this.incompleteData=Q;let z=X1($);this.handleEvent(...z),this.incompleteData=""}else this.incompleteData+=Q}catch(z){if(z instanceof Error)console.error(["\u274C Malformed data received from child process","",$,"",z.message].join(`
61
61
  \u274C `))}}++H}}),this.proc.stderr.on("data",(_)=>{let G=_.toString().split("\x03"),W=G[0];G[0]=this.incompleteData+W;let $=0;for(let H of G){if(H==="")continue;try{let Q=X1(H);this.handleLog(Q),this.incompleteData=""}catch(Q){if(Q instanceof Error)console.error(["\u274C Malformed log received from child process","",H,"",Q.message].join(`
62
62
  \u274C `));try{if($===0){this.incompleteData=H;let J=X1(W);this.handleLog(J),this.incompleteData=""}else this.incompleteData+=H}catch(J){if(J instanceof Error)console.error(["\u274C Malformed log received from child process...","",W,"",J.message].join(`
63
- \u274C `))}}++$}}),X.pid)this.id=X.pid.toString()}},SU=class extends JZ{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(X){super((...Y)=>{return this.out.next(Y),this});this.id=X,this.in=new Z0,this.out=new Z0,this.in.subscribe("socket",(Y)=>{this.handleEvent(...Y)})}dispose(){for(let X of this.disposalFunctions)X()}},V7=class extends JZ{incompleteData="";unprocessedEvents=[];relays;relayServices;proc;id="#####";log(...X){this.proc.stderr.write(w0(X.map((Y)=>Y instanceof G4?`{ ${Y.toJSON().join(" | ")} }`:Y))+"\x03")}logger={info:(...X)=>{this.log("i",...X)},warn:(...X)=>{this.log("w",...X)},error:(...X)=>{this.log("e",...X)}};constructor(X){super((Y,...Z)=>{let _=JSON.stringify([Y,...Z]);return this.proc.stdout.write(_+"\x03"),this});if(this.proc=X,this.proc.stdin.resume(),this.relays=new Map,this.relayServices=[],this.proc.stdin.on("data",(Y)=>{let Z=Y.toString().split("\x03"),_=Z[0];Z[0]=this.incompleteData+_;let G=0;for(let W of Z){if(W==="")continue;try{let $=X1(W);this.logger.info("\uD83C\uDFB0","received",$),this.handleEvent(...$),this.incompleteData=""}catch($){if($ instanceof Error)this.logger.error(["received malformed data from parent process:","",W,"",$.message].join(`
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
64
  \u274C `));try{if(G===0){this.incompleteData=W;let H=X1(_);this.logger.info("\uD83C\uDFB0","received",H),this.handleEvent(...H),this.incompleteData=""}else this.incompleteData+=W}catch(H){if(H instanceof Error)this.logger.error(["received malformed data from parent process:","",_,"",H.message].join(`
65
- \u274C `))}}++G}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),this.proc.exit(0)}),this.proc.pid)this.id=this.proc.pid?.toString();this.on("user-joins",(Y)=>{this.logger.info("\uD83D\uDC64","user",Y,"joined");let Z=`user::${Y}`,_=new SU(Z);this.relays.set(Y,_),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let G of this.relayServices){let W=G(_,Z);if(W)_.disposalFunctions.push(W)}this.on(Z,(...G)=>{_.in.next(G)}),_.out.subscribe("socket",(G)=>{this.emit(...G)})}),this.on("user-leaves",(Y)=>{let Z=this.relays.get(Y);if(this.off(`relay:${Y}`),Z)Z.dispose(),this.relays.delete(Y)}),this.proc.stdout.write("ALIVE")}receiveRelay(X){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(X)}};var O7=new Map;var jB=L6({key:"joinRoom",do:(X,Y,Z,_)=>{let G={enteredAtEpoch:_};return $2(O2,(W)=>{W.set({room:Y,user:Z})},X.env().store),G}}),SB=L6({key:"leaveRoom",do:({env:X},Y,Z)=>{$2(O2,(_)=>{_.delete({room:Y,user:Z})},X().store)}}),PB=L6({key:"destroyRoom",do:({set:X,env:Y},Z)=>{$2(O2,(G)=>{G.delete({room:Z})},Y().store),X(E7,(G)=>(G.delete(Z),G));let _=O7.get(Z);if(_)_.emit("exit"),O7.delete(Z)}}),vB=E8({key:"sockets",default:null}),xB=U8({key:"socketsIndex",class:G4}),fB=U8({key:"usersIndex",class:G4}),hB=V6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(X)=>X.startsWith("user::"),isBType:(X)=>X.startsWith("socket::")}),kB=D6({key:"userMutualSituationalAwarenessIndexes",get:(X)=>()=>{return[X]}});var{file:i$,serve:oE}=globalThis.Bun;import{readFileSync as M7}from"fs";import{createServer as fU}from"http";import{createServer as hU}from"https";import{resolve as zZ}from"path";function D7(X,Y){if(X instanceof Promise)throw Error(Y)}function PU(X,Y){let Z={},_=[];for(let G in X){let W=X[G]["~standard"].validate(Y[G]);if(D7(W,`Validation must be synchronous, but ${G} returned a Promise.`),W.issues){_.push(...W.issues.map(($)=>({...$,message:$.message,path:[G,...$.path??[]]})));continue}Z[G]=W.value}if(_.length)return{issues:_};return{value:Z}}function QZ(X){let Y=X.runtimeEnvStrict??X.runtimeEnv??process.env;if(X.emptyStringAsUndefined??!1){for(let[P,h]of Object.entries(Y))if(h==="")delete Y[P]}if(!!X.skipValidation)return Y;let G=typeof X.client==="object"?X.client:{},W=typeof X.server==="object"?X.server:{},$=typeof X.shared==="object"?X.shared:{},H=X.isServer??(typeof window>"u"||("Deno"in window)),Q=H?{...W,...$,...G}:{...G,...$},J=X.createFinalSchema?.(Q,H)["~standard"].validate(Y)??PU(Q,Y);D7(J,"Validation must be synchronous");let z=X.onValidationError??((P)=>{throw console.error("\u274C Invalid environment variables:",P),Error("Invalid environment variables")}),F=X.onInvalidAccess??(()=>{throw Error("\u274C Attempted to access a server-side environment variable on the client")});if(J.issues)return z(J.issues);let O=(P)=>{if(!X.clientPrefix)return!0;return!P.startsWith(X.clientPrefix)&&!(P in $)},D=(P)=>{return H||!O(P)},w=(P)=>{return P==="__esModule"||P==="$$typeof"},A=(X.extends??[]).reduce((P,h)=>{return Object.assign(P,h)},{}),x=Object.assign(A,J.value);return new Proxy(x,{get(P,h){if(typeof h!=="string")return;if(w(h))return;if(!D(h))return F(h);return Reflect.get(P,h)}})}var vU="__vite_start_time"in globalThis,xU=typeof window<"u",iB="vitest"in globalThis,$4=J1("string"),L7=J1('"true" | "false" | undefined'),g1=QZ({isServer:!vU&&!xU,server:{CI:J1("string | undefined").pipe(Boolean),POSTGRES_USER:$4,POSTGRES_PASSWORD:$4,POSTGRES_DATABASE:$4,POSTGRES_HOST:$4,POSTGRES_PORT:$4.pipe((X)=>Number.parseInt(X,10)),BACKEND_PORT:$4.pipe((X)=>Number.parseInt(X,10)),RUN_WORKERS_FROM_SOURCE:L7.pipe((X)=>X==="true"),FRONTEND_PORT:$4.pipe((X)=>Number.parseInt(X,10)),FRONTEND_ORIGINS:$4.pipe.try((X)=>JSON.parse(X),J1("string[]")),API_KEY_OPENAI:J1("string | undefined"),API_KEY_RESEND:J1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:$4,VITE_DEV_FRONTEND_HOST:J1("string | undefined"),VITE_DEV_HTTPS:L7.pipe((X)=>X==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var A7=zZ(import.meta.dirname,"../dev"),q6=g1.VITE_DEV_HTTPS?{cert:M7(zZ(A7,"./cert.pem"),"utf-8"),key:M7(zZ(A7,"./key.pem"),"utf-8")}:void 0;function XT(X){if(q6)return hU(q6,X);return fU({},X)}import gE from"path";var E=Symbol.for("drizzle:entityKind");function M(X,Y){if(!X||typeof X!=="object")return!1;if(X instanceof Y)return!0;if(!Object.prototype.hasOwnProperty.call(Y,E))throw Error(`Class "${Y.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let Z=Object.getPrototypeOf(X).constructor;if(Z)while(Z){if(E in Z&&Z[E]===Y[E])return!0;Z=Object.getPrototypeOf(Z)}return!1}class z0{constructor(X,Y){this.table=X,this.config=Y,this.name=Y.name,this.keyAsName=Y.keyAsName,this.notNull=Y.notNull,this.default=Y.default,this.defaultFn=Y.defaultFn,this.onUpdateFn=Y.onUpdateFn,this.hasDefault=Y.hasDefault,this.primary=Y.primaryKey,this.isUnique=Y.isUnique,this.uniqueName=Y.uniqueName,this.uniqueType=Y.uniqueType,this.dataType=Y.dataType,this.columnType=Y.columnType,this.generated=Y.generated,this.generatedIdentity=Y.generatedIdentity}static[E]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(X){return X}mapToDriverValue(X){return X}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class FZ{static[E]="ColumnBuilder";config;constructor(X,Y,Z){this.config={name:X,keyAsName:X==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:Y,columnType:Z,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(X){return this.config.default=X,this.config.hasDefault=!0,this}$defaultFn(X){return this.config.defaultFn=X,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(X){return this.config.onUpdateFn=X,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(X){if(this.config.name!=="")return;this.config.name=X}}var p1=Symbol.for("drizzle:Name");class UZ{static[E]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(X,Y){if(this.reference=()=>{let{name:Z,columns:_,foreignColumns:G}=X();return{name:Z,columns:_,foreignTable:G[0].table,foreignColumns:G}},Y)this._onUpdate=Y.onUpdate,this._onDelete=Y.onDelete}onUpdate(X){return this._onUpdate=X===void 0?"no action":X,this}onDelete(X){return this._onDelete=X===void 0?"no action":X,this}build(X){return new R7(X,this)}}class R7{constructor(X,Y){this.table=X,this.reference=Y.reference,this.onUpdate=Y._onUpdate,this.onDelete=Y._onDelete}static[E]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:X,columns:Y,foreignColumns:Z}=this.reference(),_=Y.map(($)=>$.name),G=Z.map(($)=>$.name),W=[this.table[p1],..._,Z[0].table[p1],...G];return X??`${W.join("_")}_fk`}}function j6(X,...Y){return X(...Y)}function w7(X,Y){return`${X[p1]}_${Y.join("_")}_unique`}function N7(X,Y,Z){for(let _=Y;_<X.length;_++){let G=X[_];if(G==="\\"){_++;continue}if(G==='"')return[X.slice(Y,_).replace(/\\/g,""),_+1];if(Z)continue;if(G===","||G==="}")return[X.slice(Y,_).replace(/\\/g,""),_]}return[X.slice(Y).replace(/\\/g,""),X.length]}function I7(X,Y=0){let Z=[],_=Y,G=!1;while(_<X.length){let W=X[_];if(W===","){if(G||_===Y)Z.push("");G=!0,_++;continue}if(G=!1,W==="\\"){_+=2;continue}if(W==='"'){let[Q,J]=N7(X,_+1,!0);Z.push(Q),_=J;continue}if(W==="}")return[Z,_+1];if(W==="{"){let[Q,J]=I7(X,_+1);Z.push(Q),_=J;continue}let[$,H]=N7(X,_,!1);Z.push($),_=H}return[Z,_]}function K7(X){let[Y]=I7(X,1);return Y}function EZ(X){return`{${X.map((Y)=>{if(Array.isArray(Y))return EZ(Y);if(typeof Y==="string")return`"${Y.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Y}`}).join(",")}}`}class v extends FZ{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(X){return new T7(this.config.name,this,X)}references(X,Y={}){return this.foreignKeyConfigs.push({ref:X,actions:Y}),this}unique(X,Y){return this.config.isUnique=!0,this.config.uniqueName=X,this.config.uniqueType=Y?.nulls,this}generatedAlwaysAs(X){return this.config.generated={as:X,type:"always",mode:"stored"},this}buildForeignKeys(X,Y){return this.foreignKeyConfigs.map(({ref:Z,actions:_})=>{return j6((G,W)=>{let $=new UZ(()=>{let H=G();return{columns:[X],foreignColumns:[H]}});if(W.onUpdate)$.onUpdate(W.onUpdate);if(W.onDelete)$.onDelete(W.onDelete);return $.build(Y)},Z,_)})}buildExtraConfigColumn(X){return new B7(X,this.config)}}class B extends z0{constructor(X,Y){if(!Y.uniqueName)Y.uniqueName=w7(X,[Y.name]);super(X,Y);this.table=X}static[E]="PgColumn"}class B7 extends B{static[E]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(X){return this.indexConfig.opClass=X,this}}class V2{static[E]="IndexedColumn";constructor(X,Y,Z,_){this.name=X,this.keyAsName=Y,this.type=Z,this.indexConfig=_}name;keyAsName;type;indexConfig}class T7 extends v{static[E]="PgArrayBuilder";constructor(X,Y,Z){super(X,"array","PgArray");this.config.baseBuilder=Y,this.config.size=Z}build(X){let Y=this.config.baseBuilder.build(X);return new OZ(X,this.config,Y)}}class OZ extends B{constructor(X,Y,Z,_){super(X,Y);this.baseColumn=Z,this.range=_,this.size=Y.size}size;static[E]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(X){if(typeof X==="string")X=K7(X);return X.map((Y)=>this.baseColumn.mapFromDriverValue(Y))}mapToDriverValue(X,Y=!1){let Z=X.map((_)=>_===null?null:M(this.baseColumn,OZ)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Y)return Z;return EZ(Z)}}class C7 extends v{static[E]="PgEnumObjectColumnBuilder";constructor(X,Y){super(X,"string","PgEnumObjectColumn");this.config.enum=Y}build(X){return new q7(X,this.config)}}class q7 extends B{static[E]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(X,Y){super(X,Y);this.enum=Y.enum}getSQLType(){return this.enum.enumName}}var S6=Symbol.for("drizzle:isPgEnum");function j7(X){return!!X&&typeof X==="function"&&S6 in X&&X[S6]===!0}class S7 extends v{static[E]="PgEnumColumnBuilder";constructor(X,Y){super(X,"string","PgEnumColumn");this.config.enum=Y}build(X){return new P7(X,this.config)}}class P7 extends B{static[E]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(X,Y){super(X,Y);this.enum=Y.enum}getSQLType(){return this.enum.enumName}}function D2(X,Y){return Array.isArray(Y)?kU(X,[...Y],void 0):bU(X,Y,void 0)}function kU(X,Y,Z){let _=Object.assign((G)=>new S7(G??"",_),{enumName:X,enumValues:Y,schema:Z,[S6]:!0});return _}function bU(X,Y,Z){let _=Object.assign((G)=>new C7(G??"",_),{enumName:X,enumValues:Object.values(Y),schema:Z,[S6]:!0});return _}class C0{static[E]="Subquery";constructor(X,Y,Z,_=!1,G=[]){this._={brand:"Subquery",sql:X,selectedFields:Y,alias:Z,isWith:_,usedTables:G}}}class L2 extends C0{static[E]="WithSubquery"}var v7="0.44.5";var VZ,DZ,F0={startActiveSpan(X,Y){if(!VZ)return Y();if(!DZ)DZ=VZ.trace.getTracer("drizzle-orm",v7);return j6((Z,_)=>_.startActiveSpan(X,(G)=>{try{return Y(G)}catch(W){throw G.setStatus({code:Z.SpanStatusCode.ERROR,message:W instanceof Error?W.message:"Unknown error"}),W}finally{G.end()}}),VZ,DZ)}};var V0=Symbol.for("drizzle:ViewBaseConfig");var k4=Symbol.for("drizzle:Schema"),P6=Symbol.for("drizzle:Columns"),x7=Symbol.for("drizzle:ExtraConfigColumns"),LZ=Symbol.for("drizzle:OriginalName"),MZ=Symbol.for("drizzle:BaseName"),M2=Symbol.for("drizzle:IsAlias"),f7=Symbol.for("drizzle:ExtraConfigBuilder"),yU=Symbol.for("drizzle:IsDrizzleTable");class T{static[E]="Table";static Symbol={Name:p1,Schema:k4,OriginalName:LZ,Columns:P6,ExtraConfigColumns:x7,BaseName:MZ,IsAlias:M2,ExtraConfigBuilder:f7};[p1];[LZ];[k4];[P6];[x7];[MZ];[M2]=!1;[yU]=!0;[f7]=void 0;constructor(X,Y,Z){this[p1]=this[LZ]=X,this[k4]=Y,this[MZ]=Z}}function g0(X){return X[p1]}function b4(X){return`${X[k4]??"public"}.${X[p1]}`}function AZ(X){return X!==null&&X!==void 0&&typeof X.getSQL==="function"}function gU(X){let Y={sql:"",params:[]};for(let Z of X)if(Y.sql+=Z.sql,Y.params.push(...Z.params),Z.typings?.length){if(!Y.typings)Y.typings=[];Y.typings.push(...Z.typings)}return Y}class k0{static[E]="StringChunk";value;constructor(X){this.value=Array.isArray(X)?X:[X]}getSQL(){return new S([this])}}class S{constructor(X){this.queryChunks=X;for(let Y of X)if(M(Y,T)){let Z=Y[T.Symbol.Schema];this.usedTables.push(Z===void 0?Y[T.Symbol.Name]:Z+"."+Y[T.Symbol.Name])}}static[E]="SQL";decoder=k7;shouldInlineParams=!1;usedTables=[];append(X){return this.queryChunks.push(...X.queryChunks),this}toQuery(X){return F0.startActiveSpan("drizzle.buildSQL",(Y)=>{let Z=this.buildQueryFromSourceParams(this.queryChunks,X);return Y?.setAttributes({"drizzle.query.text":Z.sql,"drizzle.query.params":JSON.stringify(Z.params)}),Z})}buildQueryFromSourceParams(X,Y){let Z=Object.assign({},Y,{inlineParams:Y.inlineParams||this.shouldInlineParams,paramStartIndex:Y.paramStartIndex||{value:0}}),{casing:_,escapeName:G,escapeParam:W,prepareTyping:$,inlineParams:H,paramStartIndex:Q}=Z;return gU(X.map((J)=>{if(M(J,k0))return{sql:J.value.join(""),params:[]};if(M(J,v6))return{sql:G(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let z=[new k0("(")];for(let[F,O]of J.entries())if(z.push(O),F<J.length-1)z.push(new k0(", "));return z.push(new k0(")")),this.buildQueryFromSourceParams(z,Z)}if(M(J,S))return this.buildQueryFromSourceParams(J.queryChunks,{...Z,inlineParams:H||J.shouldInlineParams});if(M(J,T)){let z=J[T.Symbol.Schema],F=J[T.Symbol.Name];return{sql:z===void 0||J[M2]?G(F):G(z)+"."+G(F),params:[]}}if(M(J,z0)){let z=_.getColumnCasing(J);if(Y.invokeSource==="indexes")return{sql:G(z),params:[]};let F=J.table[T.Symbol.Schema];return{sql:J.table[M2]||F===void 0?G(J.table[T.Symbol.Name])+"."+G(z):G(F)+"."+G(J.table[T.Symbol.Name])+"."+G(z),params:[]}}if(M(J,F1)){let z=J[V0].schema,F=J[V0].name;return{sql:z===void 0||J[V0].isAlias?G(F):G(z)+"."+G(F),params:[]}}if(M(J,L1)){if(M(J.value,w4))return{sql:W(Q.value++,J),params:[J],typings:["none"]};let z=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(M(z,S))return this.buildQueryFromSourceParams([z],Z);if(H)return{sql:this.mapInlineParam(z,Z),params:[]};let F=["none"];if($)F=[$(J.encoder)];return{sql:W(Q.value++,z),params:[z],typings:F}}if(M(J,w4))return{sql:W(Q.value++,J),params:[J],typings:["none"]};if(M(J,S.Aliased)&&J.fieldAlias!==void 0)return{sql:G(J.fieldAlias),params:[]};if(M(J,C0)){if(J._.isWith)return{sql:G(J._.alias),params:[]};return this.buildQueryFromSourceParams([new k0("("),J._.sql,new k0(") "),new v6(J._.alias)],Z)}if(j7(J)){if(J.schema)return{sql:G(J.schema)+"."+G(J.enumName),params:[]};return{sql:G(J.enumName),params:[]}}if(AZ(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],Z);return this.buildQueryFromSourceParams([new k0("("),J.getSQL(),new k0(")")],Z)}if(H)return{sql:this.mapInlineParam(J,Z),params:[]};return{sql:W(Q.value++,J),params:[J],typings:["none"]}}))}mapInlineParam(X,{escapeString:Y}){if(X===null)return"null";if(typeof X==="number"||typeof X==="boolean")return X.toString();if(typeof X==="string")return Y(X);if(typeof X==="object"){let Z=X.toString();if(Z==="[object Object]")return Y(JSON.stringify(X));return Y(Z)}throw Error("Unexpected param value: "+X)}getSQL(){return this}as(X){if(X===void 0)return this;return new S.Aliased(this,X)}mapWith(X){return this.decoder=typeof X==="function"?{mapFromDriverValue:X}:X,this}inlineParams(){return this.shouldInlineParams=!0,this}if(X){return X?this:void 0}}class v6{constructor(X){this.value=X}static[E]="Name";brand;getSQL(){return new S([this])}}function h7(X){return typeof X==="object"&&X!==null&&"mapToDriverValue"in X&&typeof X.mapToDriverValue==="function"}var k7={mapFromDriverValue:(X)=>X},b7={mapToDriverValue:(X)=>X},dT={...k7,...b7};class L1{constructor(X,Y=b7){this.value=X,this.encoder=Y}static[E]="Param";brand;getSQL(){return new S([this])}}function V(X,...Y){let Z=[];if(Y.length>0||X.length>0&&X[0]!=="")Z.push(new k0(X[0]));for(let[_,G]of Y.entries())Z.push(G,new k0(X[_+1]));return new S(Z)}((X)=>{function Y(){return new S([])}X.empty=Y;function Z(Q){return new S(Q)}X.fromList=Z;function _(Q){return new S([new k0(Q)])}X.raw=_;function G(Q,J){let z=[];for(let[F,O]of Q.entries()){if(F>0&&J!==void 0)z.push(J);z.push(O)}return new S(z)}X.join=G;function W(Q){return new v6(Q)}X.identifier=W;function $(Q){return new w4(Q)}X.placeholder=$;function H(Q,J){return new L1(Q,J)}X.param=H})(V||(V={}));((X)=>{class Y{constructor(Z,_){this.sql=Z,this.fieldAlias=_}static[E]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Y(this.sql,this.fieldAlias)}}X.Aliased=Y})(S||(S={}));class w4{constructor(X){this.name=X}static[E]="Placeholder";getSQL(){return new S([this])}}function RZ(X,Y){return X.map((Z)=>{if(M(Z,w4)){if(!(Z.name in Y))throw Error(`No value for placeholder "${Z.name}" was provided`);return Y[Z.name]}if(M(Z,L1)&&M(Z.value,w4)){if(!(Z.value.name in Y))throw Error(`No value for placeholder "${Z.value.name}" was provided`);return Z.encoder.mapToDriverValue(Y[Z.value.name])}return Z})}var pU=Symbol.for("drizzle:IsDrizzleView");class F1{static[E]="View";[V0];[pU]=!0;constructor({name:X,schema:Y,selectedFields:Z,query:_}){this[V0]={name:X,originalName:X,schema:Y,selectedFields:Z,query:_,isExisting:!_,isAlias:!1}}getSQL(){return new S([this])}}z0.prototype.getSQL=function(){return new S([this])};T.prototype.getSQL=function(){return new S([this])};C0.prototype.getSQL=function(){return new S([this])};class L8{constructor(X){this.table=X}static[E]="ColumnAliasProxyHandler";get(X,Y){if(Y==="table")return this.table;return X[Y]}}class A2{constructor(X,Y){this.alias=X,this.replaceOriginalName=Y}static[E]="TableAliasProxyHandler";get(X,Y){if(Y===T.Symbol.IsAlias)return!0;if(Y===T.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Y===T.Symbol.OriginalName)return this.alias;if(Y===V0)return{...X[V0],name:this.alias,isAlias:!0};if(Y===T.Symbol.Columns){let _=X[T.Symbol.Columns];if(!_)return _;let G={};return Object.keys(_).map((W)=>{G[W]=new Proxy(_[W],new L8(new Proxy(X,this)))}),G}let Z=X[Y];if(M(Z,z0))return new Proxy(Z,new L8(new Proxy(X,this)));return Z}}function x6(X,Y){return new Proxy(X,new A2(Y,!1))}function i1(X,Y){return new Proxy(X,new L8(new Proxy(X.table,new A2(Y,!1))))}function wZ(X,Y){return new S.Aliased(R2(X.sql,Y),X.fieldAlias)}function R2(X,Y){return V.join(X.queryChunks.map((Z)=>{if(M(Z,z0))return i1(Z,Y);if(M(Z,S))return R2(Z,Y);if(M(Z,S.Aliased))return wZ(Z,Y);return Z}))}class f6 extends Error{static[E]="DrizzleError";constructor({message:X,cause:Y}){super(X);this.name="DrizzleError",this.cause=Y}}class H4 extends Error{constructor(X,Y,Z){super(`Failed query: ${X}
66
- params: ${Y}`);if(this.query=X,this.params=Y,this.cause=Z,Error.captureStackTrace(this,H4),Z)this.cause=Z}}class NZ extends f6{static[E]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class y7{static[E]="ConsoleLogWriter";write(X){console.log(X)}}class IZ{static[E]="DefaultLogger";writer;constructor(X){this.writer=X?.writer??new y7}logQuery(X,Y){let Z=Y.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),_=Z.length?` -- params: [${Z.join(", ")}]`:"";this.writer.write(`Query: ${X}${_}`)}}class KZ{static[E]="NoopLogger";logQuery(){}}class Y1{static[E]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(X){return this.then(void 0,X)}finally(X){return this.then((Y)=>{return X?.(),Y},(Y)=>{throw X?.(),Y})}then(X,Y){return this.execute().then(X,Y)}}function g7(X,Y,Z){let _={},G=X.reduce((W,{path:$,field:H},Q)=>{let J;if(M(H,z0))J=H;else if(M(H,S))J=H.decoder;else J=H.sql.decoder;let z=W;for(let[F,O]of $.entries())if(F<$.length-1){if(!(O in z))z[O]={};z=z[O]}else{let D=Y[Q],w=z[O]=D===null?null:J.mapFromDriverValue(D);if(Z&&M(H,z0)&&$.length===2){let A=$[0];if(!(A in _))_[A]=w===null?g0(H.table):!1;else if(typeof _[A]==="string"&&_[A]!==g0(H.table))_[A]=!1}}return W},{});if(Z&&Object.keys(_).length>0){for(let[W,$]of Object.entries(_))if(typeof $==="string"&&!Z[$])G[W]=null}return G}function B1(X,Y){return Object.entries(X).reduce((Z,[_,G])=>{if(typeof _!=="string")return Z;let W=Y?[...Y,_]:[_];if(M(G,z0)||M(G,S)||M(G,S.Aliased))Z.push({path:W,field:G});else if(M(G,T))Z.push(...B1(G[T.Symbol.Columns],W));else Z.push(...B1(G,W));return Z},[])}function w2(X,Y){let Z=Object.keys(X),_=Object.keys(Y);if(Z.length!==_.length)return!1;for(let[G,W]of Z.entries())if(W!==_[G])return!1;return!0}function h6(X,Y){let Z=Object.entries(Y).filter(([,_])=>_!==void 0).map(([_,G])=>{if(M(G,S)||M(G,z0))return[_,G];else return[_,new L1(G,X[T.Symbol.Columns][_])]});if(Z.length===0)throw Error("No values to set");return Object.fromEntries(Z)}function p7(X,Y){for(let Z of Y)for(let _ of Object.getOwnPropertyNames(Z.prototype)){if(_==="constructor")continue;Object.defineProperty(X.prototype,_,Object.getOwnPropertyDescriptor(Z.prototype,_)||Object.create(null))}}function m7(X){return X[T.Symbol.Columns]}function J4(X){return M(X,C0)?X._.alias:M(X,F1)?X[V0].name:M(X,S)?void 0:X[T.Symbol.IsAlias]?X[T.Symbol.Name]:X[T.Symbol.BaseName]}function a(X,Y){return{name:typeof X==="string"&&X.length>0?X:"",config:typeof X==="object"?X:Y}}function u7(X){if(typeof X!=="object"||X===null)return!1;if(X.constructor.name!=="Object")return!1;if("logger"in X){let Y=typeof X.logger;if(Y!=="boolean"&&(Y!=="object"||typeof X.logger.logQuery!=="function")&&Y!=="undefined")return!1;return!0}if("schema"in X){let Y=typeof X.schema;if(Y!=="object"&&Y!=="undefined")return!1;return!0}if("casing"in X){let Y=typeof X.casing;if(Y!=="string"&&Y!=="undefined")return!1;return!0}if("mode"in X){if(X.mode!=="default"||X.mode!=="planetscale"||X.mode!==void 0)return!1;return!0}if("connection"in X){let Y=typeof X.connection;if(Y!=="string"&&Y!=="object"&&Y!=="undefined")return!1;return!0}if("client"in X){let Y=typeof X.client;if(Y!=="object"&&Y!=="function"&&Y!=="undefined")return!1;return!0}if(Object.keys(X).length===0)return!0;return!1}class N4 extends v{static[E]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(X){if(X){let{name:Y,...Z}=X;this.config.generatedIdentity={type:"always",sequenceName:Y,sequenceOptions:Z}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(X){if(X){let{name:Y,...Z}=X;this.config.generatedIdentity={type:"byDefault",sequenceName:Y,sequenceOptions:Z}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class d7 extends N4{static[E]="PgBigInt53Builder";constructor(X){super(X,"number","PgBigInt53")}build(X){return new c7(X,this.config)}}class c7 extends B{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}}class l7 extends N4{static[E]="PgBigInt64Builder";constructor(X){super(X,"bigint","PgBigInt64")}build(X){return new o7(X,this.config)}}class o7 extends B{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(X){return BigInt(X)}}function i7(X,Y){let{name:Z,config:_}=a(X,Y);if(_.mode==="number")return new d7(Z);return new l7(Z)}class n7 extends v{static[E]="PgBigSerial53Builder";constructor(X){super(X,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new r7(X,this.config)}}class r7 extends B{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}}class s7 extends v{static[E]="PgBigSerial64Builder";constructor(X){super(X,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(X){return new t7(X,this.config)}}class t7 extends B{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(X){return BigInt(X)}}function a7(X,Y){let{name:Z,config:_}=a(X,Y);if(_.mode==="number")return new n7(Z);return new s7(Z)}class e7 extends v{static[E]="PgBooleanBuilder";constructor(X){super(X,"boolean","PgBoolean")}build(X){return new X3(X,this.config)}}class X3 extends B{static[E]="PgBoolean";getSQLType(){return"boolean"}}function N2(X){return new e7(X??"")}class Y3 extends v{static[E]="PgCharBuilder";constructor(X,Y){super(X,"string","PgChar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(X){return new Z3(X,this.config)}}class Z3 extends B{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function _3(X,Y={}){let{name:Z,config:_}=a(X,Y);return new Y3(Z,_)}class G3 extends v{static[E]="PgCidrBuilder";constructor(X){super(X,"string","PgCidr")}build(X){return new W3(X,this.config)}}class W3 extends B{static[E]="PgCidr";getSQLType(){return"cidr"}}function $3(X){return new G3(X??"")}class H3 extends v{static[E]="PgCustomColumnBuilder";constructor(X,Y,Z){super(X,"custom","PgCustomColumn");this.config.fieldConfig=Y,this.config.customTypeParams=Z}build(X){return new J3(X,this.config)}}class J3 extends B{static[E]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(X,Y){super(X,Y);this.sqlName=Y.customTypeParams.dataType(Y.fieldConfig),this.mapTo=Y.customTypeParams.toDriver,this.mapFrom=Y.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(X){return typeof this.mapFrom==="function"?this.mapFrom(X):X}mapToDriverValue(X){return typeof this.mapTo==="function"?this.mapTo(X):X}}function Q3(X){return(Y,Z)=>{let{name:_,config:G}=a(Y,Z);return new H3(_,G,X)}}class Q4 extends v{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(V`now()`)}}class z3 extends Q4{static[E]="PgDateBuilder";constructor(X){super(X,"date","PgDate")}build(X){return new k6(X,this.config)}}class k6 extends B{static[E]="PgDate";getSQLType(){return"date"}mapFromDriverValue(X){return new Date(X)}mapToDriverValue(X){return X.toISOString()}}class F3 extends Q4{static[E]="PgDateStringBuilder";constructor(X){super(X,"string","PgDateString")}build(X){return new b6(X,this.config)}}class b6 extends B{static[E]="PgDateString";getSQLType(){return"date"}}function U3(X,Y){let{name:Z,config:_}=a(X,Y);if(_?.mode==="date")return new z3(Z);return new F3(Z)}class E3 extends v{static[E]="PgDoublePrecisionBuilder";constructor(X){super(X,"number","PgDoublePrecision")}build(X){return new O3(X,this.config)}}class O3 extends B{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(X){if(typeof X==="string")return Number.parseFloat(X);return X}}function V3(X){return new E3(X??"")}class D3 extends v{static[E]="PgInetBuilder";constructor(X){super(X,"string","PgInet")}build(X){return new L3(X,this.config)}}class L3 extends B{static[E]="PgInet";getSQLType(){return"inet"}}function M3(X){return new D3(X??"")}class A3 extends N4{static[E]="PgIntegerBuilder";constructor(X){super(X,"number","PgInteger")}build(X){return new R3(X,this.config)}}class R3 extends B{static[E]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(X){if(typeof X==="string")return Number.parseInt(X);return X}}function I2(X){return new A3(X??"")}class w3 extends v{static[E]="PgIntervalBuilder";constructor(X,Y){super(X,"string","PgInterval");this.config.intervalConfig=Y}build(X){return new N3(X,this.config)}}class N3 extends B{static[E]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let X=this.fields?` ${this.fields}`:"",Y=this.precision?`(${this.precision})`:"";return`interval${X}${Y}`}}function I3(X,Y={}){let{name:Z,config:_}=a(X,Y);return new w3(Z,_)}class K3 extends v{static[E]="PgJsonBuilder";constructor(X){super(X,"json","PgJson")}build(X){return new y6(X,this.config)}}class y6 extends B{static[E]="PgJson";constructor(X,Y){super(X,Y)}getSQLType(){return"json"}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){if(typeof X==="string")try{return JSON.parse(X)}catch{return X}return X}}function B3(X){return new K3(X??"")}class T3 extends v{static[E]="PgJsonbBuilder";constructor(X){super(X,"json","PgJsonb")}build(X){return new g6(X,this.config)}}class g6 extends B{static[E]="PgJsonb";constructor(X,Y){super(X,Y)}getSQLType(){return"jsonb"}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){if(typeof X==="string")try{return JSON.parse(X)}catch{return X}return X}}function C3(X){return new T3(X??"")}class q3 extends v{static[E]="PgLineBuilder";constructor(X){super(X,"array","PgLine")}build(X){return new j3(X,this.config)}}class j3 extends B{static[E]="PgLine";getSQLType(){return"line"}mapFromDriverValue(X){let[Y,Z,_]=X.slice(1,-1).split(",");return[Number.parseFloat(Y),Number.parseFloat(Z),Number.parseFloat(_)]}mapToDriverValue(X){return`{${X[0]},${X[1]},${X[2]}}`}}class S3 extends v{static[E]="PgLineABCBuilder";constructor(X){super(X,"json","PgLineABC")}build(X){return new P3(X,this.config)}}class P3 extends B{static[E]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(X){let[Y,Z,_]=X.slice(1,-1).split(",");return{a:Number.parseFloat(Y),b:Number.parseFloat(Z),c:Number.parseFloat(_)}}mapToDriverValue(X){return`{${X.a},${X.b},${X.c}}`}}function v3(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new q3(Z);return new S3(Z)}class x3 extends v{static[E]="PgMacaddrBuilder";constructor(X){super(X,"string","PgMacaddr")}build(X){return new f3(X,this.config)}}class f3 extends B{static[E]="PgMacaddr";getSQLType(){return"macaddr"}}function h3(X){return new x3(X??"")}class k3 extends v{static[E]="PgMacaddr8Builder";constructor(X){super(X,"string","PgMacaddr8")}build(X){return new b3(X,this.config)}}class b3 extends B{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}}function y3(X){return new k3(X??"")}class g3 extends v{static[E]="PgNumericBuilder";constructor(X,Y,Z){super(X,"string","PgNumeric");this.config.precision=Y,this.config.scale=Z}build(X){return new p6(X,this.config)}}class p6 extends B{static[E]="PgNumeric";precision;scale;constructor(X,Y){super(X,Y);this.precision=Y.precision,this.scale=Y.scale}mapFromDriverValue(X){if(typeof X==="string")return X;return String(X)}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class p3 extends v{static[E]="PgNumericNumberBuilder";constructor(X,Y,Z){super(X,"number","PgNumericNumber");this.config.precision=Y,this.config.scale=Z}build(X){return new m3(X,this.config)}}class m3 extends B{static[E]="PgNumericNumber";precision;scale;constructor(X,Y){super(X,Y);this.precision=Y.precision,this.scale=Y.scale}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class u3 extends v{static[E]="PgNumericBigIntBuilder";constructor(X,Y,Z){super(X,"bigint","PgNumericBigInt");this.config.precision=Y,this.config.scale=Z}build(X){return new d3(X,this.config)}}class d3 extends B{static[E]="PgNumericBigInt";precision;scale;constructor(X,Y){super(X,Y);this.precision=Y.precision,this.scale=Y.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function c3(X,Y){let{name:Z,config:_}=a(X,Y),G=_?.mode;return G==="number"?new p3(Z,_?.precision,_?.scale):G==="bigint"?new u3(Z,_?.precision,_?.scale):new g3(Z,_?.precision,_?.scale)}class l3 extends v{static[E]="PgPointTupleBuilder";constructor(X){super(X,"array","PgPointTuple")}build(X){return new o3(X,this.config)}}class o3 extends B{static[E]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(X){if(typeof X==="string"){let[Y,Z]=X.slice(1,-1).split(",");return[Number.parseFloat(Y),Number.parseFloat(Z)]}return[X.x,X.y]}mapToDriverValue(X){return`(${X[0]},${X[1]})`}}class i3 extends v{static[E]="PgPointObjectBuilder";constructor(X){super(X,"json","PgPointObject")}build(X){return new n3(X,this.config)}}class n3 extends B{static[E]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(X){if(typeof X==="string"){let[Y,Z]=X.slice(1,-1).split(",");return{x:Number.parseFloat(Y),y:Number.parseFloat(Z)}}return X}mapToDriverValue(X){return`(${X.x},${X.y})`}}function r3(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new l3(Z);return new i3(Z)}function mU(X){let Y=[];for(let Z=0;Z<X.length;Z+=2)Y.push(Number.parseInt(X.slice(Z,Z+2),16));return new Uint8Array(Y)}function s3(X,Y){let Z=new ArrayBuffer(8),_=new DataView(Z);for(let G=0;G<8;G++)_.setUint8(G,X[Y+G]);return _.getFloat64(0,!0)}function BZ(X){let Y=mU(X),Z=0,_=Y[Z];Z+=1;let G=new DataView(Y.buffer),W=G.getUint32(Z,_===1);Z+=4;let $;if(W&536870912)$=G.getUint32(Z,_===1),Z+=4;if((W&65535)===1){let H=s3(Y,Z);Z+=8;let Q=s3(Y,Z);return Z+=8,[H,Q]}throw Error("Unsupported geometry type")}class t3 extends v{static[E]="PgGeometryBuilder";constructor(X){super(X,"array","PgGeometry")}build(X){return new a3(X,this.config)}}class a3 extends B{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(X){return BZ(X)}mapToDriverValue(X){return`point(${X[0]} ${X[1]})`}}class e3 extends v{static[E]="PgGeometryObjectBuilder";constructor(X){super(X,"json","PgGeometryObject")}build(X){return new XW(X,this.config)}}class XW extends B{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(X){let Y=BZ(X);return{x:Y[0],y:Y[1]}}mapToDriverValue(X){return`point(${X.x} ${X.y})`}}function YW(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new t3(Z);return new e3(Z)}class ZW extends v{static[E]="PgRealBuilder";constructor(X,Y){super(X,"number","PgReal");this.config.length=Y}build(X){return new _W(X,this.config)}}class _W extends B{static[E]="PgReal";constructor(X,Y){super(X,Y)}getSQLType(){return"real"}mapFromDriverValue=(X)=>{if(typeof X==="string")return Number.parseFloat(X);return X}}function GW(X){return new ZW(X??"")}class WW extends v{static[E]="PgSerialBuilder";constructor(X){super(X,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new $W(X,this.config)}}class $W extends B{static[E]="PgSerial";getSQLType(){return"serial"}}function HW(X){return new WW(X??"")}class JW extends N4{static[E]="PgSmallIntBuilder";constructor(X){super(X,"number","PgSmallInt")}build(X){return new QW(X,this.config)}}class QW extends B{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(X)=>{if(typeof X==="string")return Number(X);return X}}function zW(X){return new JW(X??"")}class FW extends v{static[E]="PgSmallSerialBuilder";constructor(X){super(X,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new UW(X,this.config)}}class UW extends B{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}}function EW(X){return new FW(X??"")}class OW extends v{static[E]="PgTextBuilder";constructor(X,Y){super(X,"string","PgText");this.config.enumValues=Y.enum}build(X){return new VW(X,this.config)}}class VW extends B{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function DW(X,Y={}){let{name:Z,config:_}=a(X,Y);return new OW(Z,_)}class LW extends Q4{constructor(X,Y,Z){super(X,"string","PgTime");this.withTimezone=Y,this.precision=Z,this.config.withTimezone=Y,this.config.precision=Z}static[E]="PgTimeBuilder";build(X){return new m6(X,this.config)}}class m6 extends B{static[E]="PgTime";withTimezone;precision;constructor(X,Y){super(X,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function MW(X,Y={}){let{name:Z,config:_}=a(X,Y);return new LW(Z,_.withTimezone??!1,_.precision)}class AW extends Q4{static[E]="PgTimestampBuilder";constructor(X,Y,Z){super(X,"date","PgTimestamp");this.config.withTimezone=Y,this.config.precision=Z}build(X){return new u6(X,this.config)}}class u6 extends B{static[E]="PgTimestamp";withTimezone;precision;constructor(X,Y){super(X,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(X)=>{return new Date(this.withTimezone?X:X+"+0000")};mapToDriverValue=(X)=>{return X.toISOString()}}class RW extends Q4{static[E]="PgTimestampStringBuilder";constructor(X,Y,Z){super(X,"string","PgTimestampString");this.config.withTimezone=Y,this.config.precision=Z}build(X){return new d6(X,this.config)}}class d6 extends B{static[E]="PgTimestampString";withTimezone;precision;constructor(X,Y){super(X,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function wW(X,Y={}){let{name:Z,config:_}=a(X,Y);if(_?.mode==="string")return new RW(Z,_.withTimezone??!1,_.precision);return new AW(Z,_?.withTimezone??!1,_?.precision)}class NW extends v{static[E]="PgUUIDBuilder";constructor(X){super(X,"string","PgUUID")}defaultRandom(){return this.default(V`gen_random_uuid()`)}build(X){return new c6(X,this.config)}}class c6 extends B{static[E]="PgUUID";getSQLType(){return"uuid"}}function T1(X){return new NW(X??"")}class IW extends v{static[E]="PgVarcharBuilder";constructor(X,Y){super(X,"string","PgVarchar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(X){return new KW(X,this.config)}}class KW extends B{static[E]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function n0(X,Y={}){let{name:Z,config:_}=a(X,Y);return new IW(Z,_)}class BW extends v{static[E]="PgBinaryVectorBuilder";constructor(X,Y){super(X,"string","PgBinaryVector");this.config.dimensions=Y.dimensions}build(X){return new TW(X,this.config)}}class TW extends B{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function CW(X,Y){let{name:Z,config:_}=a(X,Y);return new BW(Z,_)}class qW extends v{static[E]="PgHalfVectorBuilder";constructor(X,Y){super(X,"array","PgHalfVector");this.config.dimensions=Y.dimensions}build(X){return new jW(X,this.config)}}class jW extends B{static[E]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){return X.slice(1,-1).split(",").map((Y)=>Number.parseFloat(Y))}}function SW(X,Y){let{name:Z,config:_}=a(X,Y);return new qW(Z,_)}class PW extends v{static[E]="PgSparseVectorBuilder";constructor(X,Y){super(X,"string","PgSparseVector");this.config.dimensions=Y.dimensions}build(X){return new vW(X,this.config)}}class vW extends B{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function xW(X,Y){let{name:Z,config:_}=a(X,Y);return new PW(Z,_)}class fW extends v{static[E]="PgVectorBuilder";constructor(X,Y){super(X,"array","PgVector");this.config.dimensions=Y.dimensions}build(X){return new hW(X,this.config)}}class hW extends B{static[E]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){return X.slice(1,-1).split(",").map((Y)=>Number.parseFloat(Y))}}function kW(X,Y){let{name:Z,config:_}=a(X,Y);return new fW(Z,_)}function bW(){return{bigint:i7,bigserial:a7,boolean:N2,char:_3,cidr:$3,customType:Q3,date:U3,doublePrecision:V3,inet:M3,integer:I2,interval:I3,json:B3,jsonb:C3,line:v3,macaddr:h3,macaddr8:y3,numeric:c3,point:r3,geometry:YW,real:GW,serial:HW,smallint:zW,smallserial:EW,text:DW,time:MW,timestamp:wW,uuid:T1,varchar:n0,bit:CW,halfvec:SW,sparsevec:xW,vector:kW}}var TZ=Symbol.for("drizzle:PgInlineForeignKeys"),yW=Symbol.for("drizzle:EnableRLS");class b0 extends T{static[E]="PgTable";static Symbol=Object.assign({},T.Symbol,{InlineForeignKeys:TZ,EnableRLS:yW});[TZ]=[];[yW]=!1;[T.Symbol.ExtraConfigBuilder]=void 0;[T.Symbol.ExtraConfigColumns]={}}function uU(X,Y,Z,_,G=X){let W=new b0(X,_,G),$=typeof Y==="function"?Y(bW()):Y,H=Object.fromEntries(Object.entries($).map(([z,F])=>{let O=F;O.setName(z);let D=O.build(W);return W[TZ].push(...O.buildForeignKeys(D,W)),[z,D]})),Q=Object.fromEntries(Object.entries($).map(([z,F])=>{let O=F;O.setName(z);let D=O.buildExtraConfigColumn(W);return[z,D]})),J=Object.assign(W,H);if(J[T.Symbol.Columns]=H,J[T.Symbol.ExtraConfigColumns]=Q,Z)J[b0.Symbol.ExtraConfigBuilder]=Z;return Object.assign(J,{enableRLS:()=>{return J[b0.Symbol.EnableRLS]=!0,J}})}var I4=(X,Y,Z)=>{return uU(X,Y,Z,void 0)};function gW(...X){if(X[0].columns)return new K2(X[0].columns,X[0].name);return new K2(X)}class K2{static[E]="PgPrimaryKeyBuilder";columns;name;constructor(X,Y){this.columns=X,this.name=Y}build(X){return new pW(X,this.columns,this.name)}}class pW{constructor(X,Y,Z){this.table=X,this.columns=Y,this.name=Z}static[E]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[b0.Symbol.Name]}_${this.columns.map((X)=>X.name).join("_")}_pk`}}function U1(X,Y){if(h7(Y)&&!AZ(X)&&!M(X,L1)&&!M(X,w4)&&!M(X,z0)&&!M(X,T)&&!M(X,F1))return new L1(X,Y);return X}var l6=(X,Y)=>{return V`${X} = ${U1(Y,X)}`},mW=(X,Y)=>{return V`${X} <> ${U1(Y,X)}`};function B2(...X){let Y=X.filter((Z)=>Z!==void 0);if(Y.length===0)return;if(Y.length===1)return new S(Y);return new S([new k0("("),V.join(Y,new k0(" and ")),new k0(")")])}function uW(...X){let Y=X.filter((Z)=>Z!==void 0);if(Y.length===0)return;if(Y.length===1)return new S(Y);return new S([new k0("("),V.join(Y,new k0(" or ")),new k0(")")])}function dW(X){return V`not ${X}`}var cW=(X,Y)=>{return V`${X} > ${U1(Y,X)}`},lW=(X,Y)=>{return V`${X} >= ${U1(Y,X)}`},oW=(X,Y)=>{return V`${X} < ${U1(Y,X)}`},iW=(X,Y)=>{return V`${X} <= ${U1(Y,X)}`};function nW(X,Y){if(Array.isArray(Y)){if(Y.length===0)return V`false`;return V`${X} in ${Y.map((Z)=>U1(Z,X))}`}return V`${X} in ${U1(Y,X)}`}function rW(X,Y){if(Array.isArray(Y)){if(Y.length===0)return V`true`;return V`${X} not in ${Y.map((Z)=>U1(Z,X))}`}return V`${X} not in ${U1(Y,X)}`}function sW(X){return V`${X} is null`}function tW(X){return V`${X} is not null`}function aW(X){return V`exists ${X}`}function eW(X){return V`not exists ${X}`}function X$(X,Y,Z){return V`${X} between ${U1(Y,X)} and ${U1(Z,X)}`}function Y$(X,Y,Z){return V`${X} not between ${U1(Y,X)} and ${U1(Z,X)}`}function Z$(X,Y){return V`${X} like ${Y}`}function _$(X,Y){return V`${X} not like ${Y}`}function G$(X,Y){return V`${X} ilike ${Y}`}function W$(X,Y){return V`${X} not ilike ${Y}`}function $$(X){return V`${X} asc`}function H$(X){return V`${X} desc`}class CZ{constructor(X,Y,Z){this.sourceTable=X,this.referencedTable=Y,this.relationName=Z,this.referencedTableName=Y[T.Symbol.Name]}static[E]="Relation";referencedTableName;fieldName}class J${constructor(X,Y){this.table=X,this.config=Y}static[E]="Relations"}class K4 extends CZ{constructor(X,Y,Z,_){super(X,Y,Z?.relationName);this.config=Z,this.isNullable=_}static[E]="One";withFieldName(X){let Y=new K4(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Y.fieldName=X,Y}}class T2 extends CZ{constructor(X,Y,Z){super(X,Y,Z?.relationName);this.config=Z}static[E]="Many";withFieldName(X){let Y=new T2(this.sourceTable,this.referencedTable,this.config);return Y.fieldName=X,Y}}function Q$(){return{and:B2,between:X$,eq:l6,exists:aW,gt:cW,gte:lW,ilike:G$,inArray:nW,isNull:sW,isNotNull:tW,like:Z$,lt:oW,lte:iW,ne:mW,not:dW,notBetween:Y$,notExists:eW,notLike:_$,notIlike:W$,notInArray:rW,or:uW,sql:V}}function z$(){return{sql:V,asc:$$,desc:H$}}function F$(X,Y){if(Object.keys(X).length===1&&"default"in X&&!M(X.default,T))X=X.default;let Z={},_={},G={};for(let[W,$]of Object.entries(X))if(M($,T)){let H=b4($),Q=_[H];Z[H]=W,G[W]={tsName:W,dbName:$[T.Symbol.Name],schema:$[T.Symbol.Schema],columns:$[T.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let z of Object.values($[T.Symbol.Columns]))if(z.primary)G[W].primaryKey.push(z);let J=$[T.Symbol.ExtraConfigBuilder]?.($[T.Symbol.ExtraConfigColumns]);if(J){for(let z of Object.values(J))if(M(z,K2))G[W].primaryKey.push(...z.columns)}}else if(M($,J$)){let H=b4($.table),Q=Z[H],J=$.config(Y($.table)),z;for(let[F,O]of Object.entries(J))if(Q){let D=G[Q];if(D.relations[F]=O,z)D.primaryKey.push(...z)}else{if(!(H in _))_[H]={relations:{},primaryKey:z};_[H].relations[F]=O}}return{tables:G,tableNamesMap:Z}}function dU(X){return function(Z,_){return new K4(X,Z,_,_?.fields.reduce((G,W)=>G&&W.notNull,!0)??!1)}}function cU(X){return function(Z,_){return new T2(X,Z,_)}}function U$(X,Y,Z){if(M(Z,K4)&&Z.config)return{fields:Z.config.fields,references:Z.config.references};let _=Y[b4(Z.referencedTable)];if(!_)throw Error(`Table "${Z.referencedTable[T.Symbol.Name]}" not found in schema`);let G=X[_];if(!G)throw Error(`Table "${_}" not found in schema`);let W=Z.sourceTable,$=Y[b4(W)];if(!$)throw Error(`Table "${W[T.Symbol.Name]}" not found in schema`);let H=[];for(let Q of Object.values(G.relations))if(Z.relationName&&Z!==Q&&Q.relationName===Z.relationName||!Z.relationName&&Q.referencedTable===Z.sourceTable)H.push(Q);if(H.length>1)throw Z.relationName?Error(`There are multiple relations with name "${Z.relationName}" in table "${_}"`):Error(`There are multiple relations between "${_}" and "${Z.sourceTable[T.Symbol.Name]}". Please specify relation name`);if(H[0]&&M(H[0],K4)&&H[0].config)return{fields:H[0].config.references,references:H[0].config.fields};throw Error(`There is not enough information to infer relation "${$}.${Z.fieldName}"`)}function E$(X){return{one:dU(X),many:cU(X)}}function o6(X,Y,Z,_,G=(W)=>W){let W={};for(let[$,H]of _.entries())if(H.isJson){let Q=Y.relations[H.tsKey],J=Z[$],z=typeof J==="string"?JSON.parse(J):J;W[H.tsKey]=M(Q,K4)?z&&o6(X,X[H.relationTableTsKey],z,H.selection,G):z.map((F)=>o6(X,X[H.relationTableTsKey],F,H.selection,G))}else{let Q=G(Z[$]),J=H.field,z;if(M(J,z0))z=J;else if(M(J,S))z=J.decoder;else z=J.sql.decoder;W[H.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return W}import OE from"os";import VE from"fs";var i6=new Map,qZ=new Map,jZ=Symbol("OriginError"),M8={};class C1 extends Promise{constructor(X,Y,Z,_,G={}){let W,$;super((H,Q)=>{W=H,$=Q});this.tagged=Array.isArray(X.raw),this.strings=X,this.args=Y,this.handler=Z,this.canceller=_,this.options=G,this.state=null,this.statement=null,this.resolve=(H)=>(this.active=!1,W(H)),this.reject=(H)=>(this.active=!1,$(H)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[jZ]=this.handler.debug?Error():this.tagged&&lU(this.strings)}get origin(){return(this.handler.debug?this[jZ].stack:this.tagged&&qZ.has(this.strings)?qZ.get(this.strings):qZ.set(this.strings,this[jZ].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(X=1,Y){if(this.options.simple=!1,typeof X==="function")Y=X,X=1;if(this.cursorRows=X,typeof Y==="function")return this.cursorFn=Y,this;let Z;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};Z&&Z();let _=new Promise((G,W)=>{this.cursorFn=($)=>{return G({value:$,done:!1}),new Promise((H)=>Z=H)},this.resolve=()=>(this.active=!1,G({done:!0})),this.reject=($)=>(this.active=!1,W($))});return this.execute(),_},return(){return Z&&Z(M8),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw Error(".stream has been renamed to .forEach")}forEach(X){return this.forEachFn=X,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function lU(X){if(i6.has(X))return i6.get(X);let Y=Error.stackTraceLimit;return Error.stackTraceLimit=4,i6.set(X,Error()),Error.stackTraceLimit=Y,i6.get(X)}class A8 extends Error{constructor(X){super(X.message);this.name=this.constructor.name,Object.assign(this,X)}}var S0={connection:O$,postgres:V$,generic:D$,notSupported:L$};function O$(X,Y,Z){let{host:_,port:G}=Z||Y,W=Object.assign(Error("write "+X+" "+(Y.path||_+":"+G)),{code:X,errno:X,address:Y.path||_},Y.path?{}:{port:G});return Error.captureStackTrace(W,O$),W}function V$(X){let Y=new A8(X);return Error.captureStackTrace(Y,V$),Y}function D$(X,Y){let Z=Object.assign(Error(X+": "+Y),{code:X});return Error.captureStackTrace(Z,D$),Z}function L$(X){let Y=Object.assign(Error(X+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:X});return Error.captureStackTrace(Y,L$),Y}var oU={string:{to:25,from:null,serialize:(X)=>""+X},number:{to:0,from:[21,23,26,700,701],serialize:(X)=>""+X,parse:(X)=>+X},json:{to:114,from:[114,3802],serialize:(X)=>JSON.stringify(X),parse:(X)=>JSON.parse(X)},boolean:{to:16,from:16,serialize:(X)=>X===!0?"t":"f",parse:(X)=>X==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(X)=>(X instanceof Date?X:new Date(X)).toISOString(),parse:(X)=>new Date(X)},bytea:{to:17,from:17,serialize:(X)=>"\\x"+Buffer.from(X).toString("hex"),parse:(X)=>Buffer.from(X.slice(2),"hex")}};class s6{then(){SZ()}catch(){SZ()}finally(){SZ()}}class S2 extends s6{constructor(X){super();this.value=e6(X)}}class n1 extends s6{constructor(X,Y,Z){super();this.value=X,this.type=Y,this.array=Z}}class t6 extends s6{constructor(X,Y){super();this.first=X,this.rest=Y}build(X,Y,Z,_){let G=iU.map(([W,$])=>({fn:$,i:X.search(W)})).sort((W,$)=>W.i-$.i).pop();return G.i===-1?hZ(this.first,_):G.fn(this.first,this.rest,Y,Z,_)}}function a6(X,Y,Z,_){let G=X instanceof n1?X.value:X;if(G===void 0){if(X instanceof n1?X.value=_.transform.undefined:G=X=_.transform.undefined,G===void 0)throw S0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+Z.push(X instanceof n1?(Y.push(X.value),X.array?X.array[X.type||r6(X.value)]||X.type||w$(X.value):X.type):(Y.push(X),r6(X)))}var A$=I$(oU);function xZ(X,Y,Z,_,G,W){for(let $=1;$<X.strings.length;$++)Y+=fZ(Y,Z,_,G,W)+X.strings[$],Z=X.args[$];return Y}function fZ(X,Y,Z,_,G){return Y instanceof t6?Y.build(X,Z,_,G):Y instanceof C1?vZ(Y,Z,_,G):Y instanceof S2?Y.value:Y&&Y[0]instanceof C1?Y.reduce((W,$)=>W+" "+vZ($,Z,_,G),""):a6(Y,Z,_,G)}function vZ(X,Y,Z,_){return X.fragment=!0,xZ(X,X.strings[0],X.args[0],Y,Z,_)}function R$(X,Y,Z,_,G){return X.map((W)=>"("+_.map(($)=>fZ("values",W[$],Y,Z,G)).join(",")+")").join(",")}function M$(X,Y,Z,_,G){let W=Array.isArray(X[0]),$=Y.length?Y.flat():Object.keys(W?X[0]:X);return R$(W?X:[X],Z,_,$,G)}function n6(X,Y,Z,_,G){if(typeof X==="string"&&(X=[X].concat(Y)),Array.isArray(X))return hZ(X,G);let W;return(Y.length?Y.flat():Object.keys(X)).map((H)=>{return W=X[H],(W instanceof C1?vZ(W,Z,_,G):W instanceof S2?W.value:a6(W,Z,_,G))+" as "+e6(G.transform.column.to?G.transform.column.to(H):H)}).join(",")}var iU=Object.entries({values:M$,in:(...X)=>{let Y=M$(...X);return Y==="()"?"(null)":Y},select:n6,as:n6,returning:n6,"\\(":n6,update(X,Y,Z,_,G){return(Y.length?Y.flat():Object.keys(X)).map((W)=>e6(G.transform.column.to?G.transform.column.to(W):W)+"="+fZ("values",X[W],Z,_,G))},insert(X,Y,Z,_,G){let W=Y.length?Y.flat():Object.keys(Array.isArray(X)?X[0]:X);return"("+hZ(W,G)+")values"+R$(Array.isArray(X)?X:[X],Z,_,W,G)}}).map(([X,Y])=>[new RegExp("((?:^|[\\s(])"+X+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Y]);function SZ(){throw S0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:nU,parsers:rU}=A$;function w$(X){if(Array.isArray(X))return w$(X[0]);return typeof X==="string"?1009:0}var N$=function(X){let Y=I$(X||{});return{serializers:Object.assign({},nU,Y.serializers),parsers:Object.assign({},rU,Y.parsers)}};function I$(X){return Object.keys(X).reduce((Y,Z)=>{if(X[Z].from&&[].concat(X[Z].from).forEach((_)=>Y.parsers[_]=X[Z].parse),X[Z].serialize)Y.serializers[X[Z].to]=X[Z].serialize,X[Z].from&&[].concat(X[Z].from).forEach((_)=>Y.serializers[_]=X[Z].serialize);return Y},{parsers:{},serializers:{}})}function hZ(X,{transform:{column:Y}}){return X.map((Z)=>e6(Y.to?Y.to(Z):Z)).join(",")}var e6=function(Y){return'"'+Y.replace(/"/g,'""').replace(/\./g,'"."')+'"'},r6=function X(Y){return Y instanceof n1?Y.type:Y instanceof Date?1184:Y instanceof Uint8Array?17:Y===!0||Y===!1?16:typeof Y==="bigint"?20:Array.isArray(Y)?X(Y[0]):0},sU=/\\/g,tU=/"/g;function aU(X){return X.replace(sU,"\\\\").replace(tU,"\\\"")}var K$=function X(Y,Z,_,G){if(Array.isArray(Y)===!1)return Y;if(!Y.length)return"{}";let W=Y[0],$=G===1020?";":",";if(Array.isArray(W)&&!W.type)return"{"+Y.map((H)=>X(H,Z,_,G)).join($)+"}";return"{"+Y.map((H)=>{if(H===void 0){if(H=_.transform.undefined,H===void 0)throw S0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return H===null?"null":'"'+aU(Z?Z(H.type?H.value:H):""+H)+'"'}).join($)+"}"},PZ={i:0,char:null,str:"",quoted:!1,last:0},B$=function(Y,Z,_){return PZ.i=PZ.last=0,T$(PZ,Y,Z,_)};function T$(X,Y,Z,_){let G=[],W=_===1020?";":",";for(;X.i<Y.length;X.i++){if(X.char=Y[X.i],X.quoted)if(X.char==="\\")X.str+=Y[++X.i];else if(X.char==='"')G.push(Z?Z(X.str):X.str),X.str="",X.quoted=Y[X.i+1]==='"',X.last=X.i+2;else X.str+=X.char;else if(X.char==='"')X.quoted=!0;else if(X.char==="{")X.last=++X.i,G.push(T$(X,Y,Z,_));else if(X.char==="}"){X.quoted=!1,X.last<X.i&&G.push(Z?Z(Y.slice(X.last,X.i)):Y.slice(X.last,X.i)),X.last=X.i+1;break}else if(X.char===W&&X.p!=="}"&&X.p!=='"')G.push(Z?Z(Y.slice(X.last,X.i)):Y.slice(X.last,X.i)),X.last=X.i+1;X.p=X.char}return X.last<X.i&&G.push(Z?Z(Y.slice(X.last,X.i+1)):Y.slice(X.last,X.i+1)),G}var y4=(X)=>{let Y=X[0];for(let Z=1;Z<X.length;Z++)Y+=X[Z]==="_"?X[++Z].toUpperCase():X[Z];return Y},g4=(X)=>{let Y=X[0].toUpperCase();for(let Z=1;Z<X.length;Z++)Y+=X[Z]==="_"?X[++Z].toUpperCase():X[Z];return Y},p4=(X)=>X.replace(/_/g,"-"),C2=(X)=>X.replace(/([A-Z])/g,"_$1").toLowerCase(),q2=(X)=>(X.slice(0,1)+X.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),j2=(X)=>X.replace(/-/g,"_");function kZ(X){return function Y(Z,_){return typeof Z==="object"&&Z!==null&&(_.type===114||_.type===3802)?Array.isArray(Z)?Z.map((G)=>Y(G,_)):Object.entries(Z).reduce((G,[W,$])=>Object.assign(G,{[X(W)]:Y($,_)}),{}):Z}}y4.column={from:y4};y4.value={from:kZ(y4)};C2.column={to:C2};var bZ={...y4};bZ.column.to=C2;g4.column={from:g4};g4.value={from:kZ(g4)};q2.column={to:q2};var yZ={...g4};yZ.column.to=q2;p4.column={from:p4};p4.value={from:kZ(p4)};j2.column={to:j2};var gZ={...p4};gZ.column.to=j2;import C$ from"net";import ZE from"tls";import P2 from"crypto";import pZ from"stream";import{performance as q$}from"perf_hooks";class m4 extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var M1=eU;function eU(X=[]){let Y=X.slice(),Z=0;return{get length(){return Y.length-Z},remove:(_)=>{let G=Y.indexOf(_);return G===-1?null:(Y.splice(G,1),_)},push:(_)=>(Y.push(_),_),shift:()=>{let _=Y[Z++];if(Z===Y.length)Z=0,Y=[];else Y[Z-1]=void 0;return _}}}var r0=Buffer.allocUnsafe(256),XE="BCcDdEFfHPpQSX".split("").reduce((X,Y)=>{let Z=Y.charCodeAt(0);return X[Y]=()=>{return r0[0]=Z,J0.i=5,J0},X},{}),J0=Object.assign(YE,XE,{N:String.fromCharCode(0),i:0,inc(X){return J0.i+=X,J0},str(X){let Y=Buffer.byteLength(X);return XX(Y),J0.i+=r0.write(X,J0.i,Y,"utf8"),J0},i16(X){return XX(2),r0.writeUInt16BE(X,J0.i),J0.i+=2,J0},i32(X,Y){if(Y||Y===0)return r0.writeUInt32BE(X,Y),J0;return XX(4),r0.writeUInt32BE(X,J0.i),J0.i+=4,J0},z(X){return XX(X),r0.fill(0,J0.i,J0.i+X),J0.i+=X,J0},raw(X){return r0=Buffer.concat([r0.subarray(0,J0.i),X]),J0.i=r0.length,J0},end(X=1){r0.writeUInt32BE(J0.i-X,X);let Y=r0.subarray(0,J0.i);return J0.i=0,r0=Buffer.allocUnsafe(256),Y}}),b=J0;function XX(X){if(r0.length-J0.i<X){let Y=r0,Z=Y.length;r0=Buffer.allocUnsafe(Z+(Z>>1)+X),Y.copy(r0)}}function YE(){return J0.i=0,J0}var dZ=P$,_E=1,B4=b().S().end(),j$=b().H().end(),GE=b().i32(8).i32(80877103).end(8),WE=Buffer.concat([b().E().str(b.N).i32(0).end(),B4]),$E=b().D().str("S").str(b.N).end(),R8=()=>{},HE=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),JE={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function P$(X,Y={},{onopen:Z=R8,onend:_=R8,onclose:G=R8}={}){let{ssl:W,max:$,user:H,host:Q,port:J,database:z,parsers:F,transform:O,onnotice:D,onnotify:w,onparameter:A,max_pipeline:x,keep_alive:j,backoff:P,target_session_attrs:h}=X,i=M1(),p=_E++,y={pid:null,secret:null},m=uZ(OX,X.idle_timeout),_0=uZ(OX,X.max_lifetime),y0=uZ(XH,X.connect_timeout),K=null,W0,o=new m4,X0=Buffer.alloc(0),p0=X.fetch_types,O1={},q1={},c4=Math.random().toString(36).slice(2),I=1,u=0,$0=0,R0=0,P0=0,n=0,H0=0,q0=0,N0=null,D0=null,d0=!1,U0=null,j1=null,m0=null,z4=null,v0=null,L0=null,S1=null,u1=null,q=null,K8=null,c0={queue:Y.closed,idleTimer:m,connect(U){m0=U,D5()},terminate:T8,execute:B8,cancel:s$,end:OX,count:0,id:p};return Y.closed&&Y.closed.push(c0),c0;async function r$(){let U;try{U=X.socket?await Promise.resolve(X.socket(X)):new C$.Socket}catch(L){o4(L);return}return U.on("error",o4),U.on("close",L5),U.on("drain",O5),U}async function s$({pid:U,secret:L},g,Y0){try{W0=b().i32(16).i32(80877102).i32(U).i32(L).end(16),await V5(),K.once("error",Y0),K.once("close",g)}catch(K0){Y0(K0)}}function B8(U){if(d0)return g2(U,S0.connection("CONNECTION_DESTROYED",X));if(U.cancelled)return;try{return U.state=y,q?i.push(U):(q=U,q.active=!0),e$(U),u0(t$(U))&&!U.describeFirst&&!U.cursorFn&&i.length<x&&(!U.options.onexecute||U.options.onexecute(c0))}catch(L){return i.length===0&&u0(B4),d1(L),!0}}function t$(U){if(U.parameters.length>=65534)throw S0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return U.options.simple?b().Q().str(U.statement.string+b.N).end():U.describeFirst?Buffer.concat([F5(U),j$]):U.prepare?U.prepared?y2(U):Buffer.concat([F5(U),y2(U)]):a$(U)}function F5(U){return Buffer.concat([A5(U.statement.string,U.parameters,U.statement.types,U.statement.name),yH("S",U.statement.name)])}function y2(U){return Buffer.concat([bH(U.parameters,U.statement.types,U.statement.name,U.cursorName),U.cursorFn?R5("",U.cursorRows):WE])}function a$(U){return Buffer.concat([A5(U.statement.string,U.parameters,U.statement.types),$E,y2(U)])}function e$(U){let L=[],g=[],Y0=xZ(U,U.strings[0],U.args[0],L,g,X);!U.tagged&&U.args.forEach((K0)=>a6(K0,L,g,X)),U.prepare=X.prepare&&("prepare"in U.options?U.options.prepare:!0),U.string=Y0,U.signature=U.prepare&&g+Y0,U.onlyDescribe&&delete q1[U.signature],U.parameters=U.parameters||L,U.prepared=U.prepare&&U.signature in q1,U.describeFirst=U.onlyDescribe||L.length&&!U.prepared,U.statement=U.prepared?q1[U.signature]:{string:Y0,types:g,name:U.prepare?c4+I++:""},typeof X.debug==="function"&&X.debug(p,Y0,L,g)}function u0(U,L){if(L0=L0?Buffer.concat([L0,U]):Buffer.from(U),L||L0.length>=1024)return U5(L);return D0===null&&(D0=setImmediate(U5)),!0}function U5(U){let L=K.write(L0,U);return D0!==null&&clearImmediate(D0),L0=D0=null,L}function XH(){d1(S0.connection("CONNECT_TIMEOUT",X,K)),K.destroy()}async function E5(){if(u0(GE),!await new Promise((L)=>K.once("data",(g)=>L(g[0]===83)))&&W==="prefer")return l4();K.removeAllListeners(),K=ZE.connect({socket:K,servername:C$.isIP(K.host)?void 0:K.host,...W==="require"||W==="allow"||W==="prefer"?{rejectUnauthorized:!1}:W==="verify-full"?{}:typeof W==="object"?W:{}}),K.on("secureConnect",l4),K.on("error",o4),K.on("close",L5),K.on("drain",O5)}function O5(){!q&&Z(c0)}function EX(U){if(U0){if(U0.push(U),$0-=U.length,$0>0)return}X0=U0?Buffer.concat(U0,n-$0):X0.length===0?U:Buffer.concat([X0,U],X0.length+U.length);while(X0.length>4){if(n=X0.readUInt32BE(1),n>=X0.length){$0=n-X0.length,U0=[X0];break}try{YH(X0.subarray(0,n+1))}catch(L){q&&(q.cursorFn||q.describeFirst)&&u0(B4),d1(L)}X0=X0.subarray(n+1),$0=0,U0=null}}async function V5(){if(d0=!1,O1={},K||(K=await r$()),!K)return;if(y0.start(),X.socket)return W?E5():l4();if(K.on("connect",W?E5:l4),X.path)return K.connect(X.path);K.ssl=W,K.connect(J[R0],Q[R0]),K.host=Q[R0],K.port=J[R0],R0=(R0+1)%J.length}function D5(){setTimeout(V5,u?u+H0-q$.now():0)}function l4(){try{q1={},p0=X.fetch_types,c4=Math.random().toString(36).slice(2),I=1,_0.start(),K.on("data",EX),j&&K.setKeepAlive&&K.setKeepAlive(!0,1000*j);let U=pH();u0(U)}catch(U){o4(U)}}function o4(U){if(c0.queue===Y.connecting&&X.host[P0+1])return;d1(U);while(i.length)g2(i.shift(),U)}function d1(U){v0&&(v0.destroy(U),v0=null),q&&g2(q,U),m0&&(g2(m0,U),m0=null)}function g2(U,L){if(U.reserve)return U.reject(L);if(!L||typeof L!=="object")L=Error(L);"query"in L||"parameters"in L||Object.defineProperties(L,{stack:{value:L.stack+U.origin.replace(/.*\n/,`
67
- `),enumerable:X.debug},query:{value:U.string,enumerable:X.debug},parameters:{value:U.parameters,enumerable:X.debug},args:{value:U.args,enumerable:X.debug},types:{value:U.statement&&U.statement.types,enumerable:X.debug}}),U.reject(L)}function OX(){return z4||(!c0.reserved&&_(c0),!c0.reserved&&!m0&&!q&&i.length===0?(T8(),new Promise((U)=>K&&K.readyState!=="closed"?K.once("close",U):U())):z4=new Promise((U)=>S1=U))}function T8(){if(d0=!0,v0||q||m0||i.length)o4(S0.connection("CONNECTION_DESTROYED",X));if(clearImmediate(D0),K)K.removeListener("data",EX),K.removeListener("connect",l4),K.readyState==="open"&&K.end(b().X().end());S1&&(S1(),z4=S1=null)}async function L5(U){if(X0=Buffer.alloc(0),$0=0,U0=null,clearImmediate(D0),K.removeListener("data",EX),K.removeListener("connect",l4),m.cancel(),_0.cancel(),y0.cancel(),K.removeAllListeners(),K=null,m0)return D5();!U&&(q||i.length)&&o4(S0.connection("CONNECTION_CLOSED",X,K)),u=q$.now(),U&&X.shared.retries++,H0=(typeof P==="function"?P(X.shared.retries):P)*1000,G(c0,S0.connection("CONNECTION_CLOSED",X,K))}function YH(U,L=U[0]){(L===68?ZH:L===100?jH:L===65?IH:L===83?_H:L===90?GH:L===67?WH:L===50?M5:L===49?$H:L===116?HH:L===84?JH:L===82?QH:L===110?VH:L===75?DH:L===69?wH:L===115?KH:L===51?BH:L===71?TH:L===78?PH:L===72?CH:L===99?SH:L===73?vH:L===86?xH:L===118?fH:L===87?qH:hH)(U)}function ZH(U){let L=7,g,Y0,K0,l0=q.isRaw?Array(q.statement.columns.length):{};for(let s0=0;s0<q.statement.columns.length;s0++)Y0=q.statement.columns[s0],g=U.readInt32BE(L),L+=4,K0=g===-1?null:q.isRaw===!0?U.subarray(L,L+=g):Y0.parser===void 0?U.toString("utf8",L,L+=g):Y0.parser.array===!0?Y0.parser(U.toString("utf8",L+1,L+=g)):Y0.parser(U.toString("utf8",L,L+=g)),q.isRaw?l0[s0]=q.isRaw===!0?K0:O.value.from?O.value.from(K0,Y0):K0:l0[Y0.name]=O.value.from?O.value.from(K0,Y0):K0;q.forEachFn?q.forEachFn(O.row.from?O.row.from(l0):l0,o):o[q0++]=O.row.from?O.row.from(l0):l0}function _H(U){let[L,g]=U.toString("utf8",5,U.length-1).split(b.N);if(O1[L]=g,X.parameters[L]!==g)X.parameters[L]=g,A&&A(L,g)}function GH(U){if(q&&q.options.simple&&q.resolve(j1||o),q=j1=null,o=new m4,y0.cancel(),m0){if(h){if(!O1.in_hot_standby||!O1.default_transaction_read_only)return RH();else if(AH(h,O1))return T8()}if(p0)return m0.reserve&&(m0=null),LH();m0&&!m0.reserve&&B8(m0),X.shared.retries=P0=0,m0=null;return}while(i.length&&(q=i.shift())&&(q.active=!0,q.cancelled))P$(X).cancel(q.state,q.cancelled.resolve,q.cancelled.reject);if(q)return;c0.reserved?!c0.reserved.release&&U[5]===73?z4?T8():(c0.reserved=null,Z(c0)):c0.reserved():z4?T8():Z(c0)}function WH(U){q0=0;for(let L=U.length-1;L>0;L--){if(U[L]===32&&U[L+1]<58&&o.count===null)o.count=+U.toString("utf8",L+1,U.length-1);if(U[L-1]>=65){o.command=U.toString("utf8",5,L),o.state=y;break}}if(K8&&(K8(),K8=null),o.command==="BEGIN"&&$!==1&&!c0.reserved)return d1(S0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(q.options.simple)return M5();if(q.cursorFn)o.count&&q.cursorFn(o),u0(B4);q.resolve(o)}function $H(){q.parsing=!1}function M5(){!o.statement&&(o.statement=q.statement),o.columns=q.statement.columns}function HH(U){let L=U.readUInt16BE(5);for(let g=0;g<L;++g)!q.statement.types[g]&&(q.statement.types[g]=U.readUInt32BE(7+g*4));q.prepare&&(q1[q.signature]=q.statement),q.describeFirst&&!q.onlyDescribe&&(u0(y2(q)),q.describeFirst=!1)}function JH(U){if(o.command)j1=j1||[o],j1.push(o=new m4),o.count=null,q.statement.columns=null;let L=U.readUInt16BE(5),g=7,Y0;q.statement.columns=Array(L);for(let K0=0;K0<L;++K0){Y0=g;while(U[g++]!==0);let l0=U.readUInt32BE(g),s0=U.readUInt16BE(g+4),F4=U.readUInt32BE(g+6);q.statement.columns[K0]={name:O.column.from?O.column.from(U.toString("utf8",Y0,g-1)):U.toString("utf8",Y0,g-1),parser:F[F4],table:l0,number:s0,type:F4},g+=18}if(o.statement=q.statement,q.onlyDescribe)return q.resolve(q.statement),u0(B4)}async function QH(U,L=U.readUInt32BE(5)){(L===3?zH:L===5?FH:L===10?UH:L===11?EH:L===12?OH:L!==0?kH:R8)(U,L)}async function zH(){let U=await VX();u0(b().p().str(U).z(1).end())}async function FH(U){let L="md5"+await S$(Buffer.concat([Buffer.from(await S$(await VX()+H)),U.subarray(9)]));u0(b().p().str(L).z(1).end())}async function UH(){u1=(await P2.randomBytes(18)).toString("base64"),b().p().str("SCRAM-SHA-256"+b.N);let U=b.i;u0(b.inc(4).str("n,,n=*,r="+u1).i32(b.i-U-4,U).end())}async function EH(U){let L=U.toString("utf8",9).split(",").reduce((s0,F4)=>(s0[F4[0]]=F4.slice(2),s0),{}),g=await P2.pbkdf2Sync(await VX(),Buffer.from(L.s,"base64"),parseInt(L.i),32,"sha256"),Y0=await YX(g,"Client Key"),K0="n=*,r="+u1+",r="+L.r+",s="+L.s+",i="+L.i+",c=biws,r="+L.r;N0=(await YX(await YX(g,"Server Key"),K0)).toString("base64");let l0="c=biws,r="+L.r+",p="+zE(Y0,Buffer.from(await YX(await QE(Y0),K0))).toString("base64");u0(b().p().str(l0).end())}function OH(U){if(U.toString("utf8",9).split(b.N,1)[0].slice(2)===N0)return;d1(S0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),K.destroy()}function VX(){return Promise.resolve(typeof X.pass==="function"?X.pass():X.pass)}function VH(){if(o.statement=q.statement,o.statement.columns=[],q.onlyDescribe)return q.resolve(q.statement),u0(B4)}function DH(U){y.pid=U.readUInt32BE(5),y.secret=U.readUInt32BE(9)}async function LH(){p0=!1,(await new C1([`
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([`
68
68
  select b.oid, b.typarray
69
69
  from pg_catalog.pg_type a
70
70
  left join pg_catalog.pg_type b on b.oid = a.typelem
71
71
  where a.typcategory = 'A'
72
72
  group by b.oid, b.typarray
73
73
  order by b.oid
74
- `],[],B8)).forEach(({oid:L,typarray:g})=>MH(L,g))}function MH(U,L){if(!!X.parsers[L]&&!!X.serializers[L])return;let g=X.parsers[U];X.shared.typeArrayMap[U]=L,X.parsers[L]=(Y0)=>B$(Y0,g,L),X.parsers[L].array=!0,X.serializers[L]=(Y0)=>K$(Y0,X.serializers[U],X,L)}function AH(U,L){return U==="read-write"&&L.default_transaction_read_only==="on"||U==="read-only"&&L.default_transaction_read_only==="off"||U==="primary"&&L.in_hot_standby==="on"||U==="standby"&&L.in_hot_standby==="off"||U==="prefer-standby"&&L.in_hot_standby==="off"&&X.host[P0]}function RH(){let U=new C1([`
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
75
  show transaction_read_only;
76
76
  select pg_catalog.pg_is_in_recovery()
77
- `],[],B8,null,{simple:!0});U.resolve=([[L],[g]])=>{O1.default_transaction_read_only=L.transaction_read_only,O1.in_hot_standby=g.pg_is_in_recovery?"on":"off"},U.execute()}function wH(U){q&&(q.cursorFn||q.describeFirst)&&u0(B4);let L=S0.postgres(mZ(U));q&&q.retried?d1(q.retried):q&&q.prepared&&HE.has(L.routine)?NH(q,L):d1(L)}function NH(U,L){delete q1[U.signature],U.retried=L,B8(U)}function IH(U){if(!w)return;let L=9;while(U[L++]!==0);w(U.toString("utf8",9,L-1),U.toString("utf8",L,U.length-1))}async function KH(){try{let U=await Promise.resolve(q.cursorFn(o));q0=0,U===M8?u0(gH(q.portal)):(o=new m4,u0(R5("",q.cursorRows)))}catch(U){u0(B4),q.reject(U)}}function BH(){o.count&&q.cursorFn(o),q.resolve(o)}function TH(){v0=new pZ.Writable({autoDestroy:!0,write(U,L,g){K.write(b().d().raw(U).end(),g)},destroy(U,L){L(U),K.write(b().f().str(U+b.N).end()),v0=null},final(U){K.write(b().c().end()),K8=U}}),q.resolve(v0)}function CH(){v0=new pZ.Readable({read(){K.resume()}}),q.resolve(v0)}function qH(){v0=new pZ.Duplex({autoDestroy:!0,read(){K.resume()},write(U,L,g){K.write(b().d().raw(U).end(),g)},destroy(U,L){L(U),K.write(b().f().str(U+b.N).end()),v0=null},final(U){K.write(b().c().end()),K8=U}}),q.resolve(v0)}function jH(U){v0&&(v0.push(U.subarray(5))||K.pause())}function SH(){v0&&v0.push(null),v0=null}function PH(U){D?D(mZ(U)):console.log(mZ(U))}function vH(){}function xH(){d1(S0.notSupported("FunctionCallResponse"))}function fH(){d1(S0.notSupported("NegotiateProtocolVersion"))}function hH(U){console.error("Postgres.js : Unknown Message:",U[0])}function kH(U,L){console.error("Postgres.js : Unknown Auth:",L)}function bH(U,L,g="",Y0=""){let K0,l0;return b().B().str(Y0+b.N).str(g+b.N).i16(0).i16(U.length),U.forEach((s0,F4)=>{if(s0===null)return b.i32(4294967295);l0=L[F4],U[F4]=s0=l0 in X.serializers?X.serializers[l0](s0):""+s0,K0=b.i,b.inc(4).str(s0).i32(b.i-K0-4,K0)}),b.i16(0),b.end()}function A5(U,L,g,Y0=""){return b().P().str(Y0+b.N).str(U+b.N).i16(L.length),L.forEach((K0,l0)=>b.i32(g[l0]||0)),b.end()}function yH(U,L=""){return b().D().str(U).str(L+b.N).end()}function R5(U="",L=0){return Buffer.concat([b().E().str(U+b.N).i32(L).end(),j$])}function gH(U=""){return Buffer.concat([b().C().str("P").str(U+b.N).end(),b().S().end()])}function pH(){return W0||b().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:H,database:z,client_encoding:"UTF8"},X.connection)).filter(([,U])=>U).map(([U,L])=>U+b.N+L).join(b.N)).z(2).end(0)}}function mZ(X){let Y={},Z=5;for(let _=5;_<X.length-1;_++)if(X[_]===0)Y[JE[X[Z]]]=X.toString("utf8",Z+1,_),Z=_+1;return Y}function S$(X){return P2.createHash("md5").update(X).digest("hex")}function YX(X,Y){return P2.createHmac("sha256",X).update(Y).digest()}function QE(X){return P2.createHash("sha256").update(X).digest()}function zE(X,Y){let Z=Math.max(X.length,Y.length),_=Buffer.allocUnsafe(Z);for(let G=0;G<Z;G++)_[G]=X[G]^Y[G];return _}function uZ(X,Y){if(Y=typeof Y==="function"?Y():Y,!Y)return{cancel:R8,start:R8};let Z;return{cancel(){Z&&(clearTimeout(Z),Z=null)},start(){Z&&clearTimeout(Z),Z=setTimeout(_,Y*1000,arguments)}};function _(G){X.apply(null,G),Z=null}}var v$=()=>{};function cZ(X,Y){let Z=new Map,_="postgresjs_"+Math.random().toString(36).slice(2),G={},W,$,H=!1,Q=F.sql=X({...Y,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...Y.connection,replication:"database"},onclose:async function(){if(H)return;$=null,G.pid=G.secret=void 0,O(await D(Q,_,Y.publications)),Z.forEach((A)=>A.forEach(({onsubscribe:x})=>x()))},no_subscribe:!0}),J=Q.end,z=Q.close;return Q.end=async()=>{return H=!0,$&&await new Promise((A)=>($.once("close",A),$.end())),J()},Q.close=async()=>{return $&&await new Promise((A)=>($.once("close",A),$.end())),z()},F;async function F(A,x,j=v$,P=v$){if(A=EE(A),!W)W=D(Q,_,Y.publications);let h={fn:x,onsubscribe:j},i=Z.has(A)?Z.get(A).add(h):Z.set(A,new Set([h])).get(A),p=()=>{i.delete(h),i.size===0&&Z.delete(A)};return W.then((y)=>{return O(y),j(),$&&$.on("error",P),{unsubscribe:p,state:G,sql:Q}})}function O(A){$=A.stream,G.pid=A.state.pid,G.secret=A.state.secret}async function D(A,x,j){if(!j)throw Error("Missing publication names");let P=await A.unsafe(`CREATE_REPLICATION_SLOT ${x} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[h]=P,i=await A.unsafe(`START_REPLICATION SLOT ${x} LOGICAL ${h.consistent_point} (proto_version '1', publication_names '${j}')`).writable(),p={lsn:Buffer.concat(h.consistent_point.split("/").map((K)=>Buffer.from(("00000000"+K).slice(-8),"hex")))};return i.on("data",m),i.on("error",y),i.on("close",A.close),{stream:i,state:P.state};function y(K){console.error("Unexpected error during logical streaming - reconnecting",K)}function m(K){if(K[0]===119)UE(K.subarray(25),p,A.options.parsers,_0,Y.transform);else if(K[0]===107&&K[17])p.lsn=K.subarray(1,9),y0()}function _0(K,W0){let o=W0.relation.schema+"."+W0.relation.table;w("*",K,W0),w("*:"+o,K,W0),W0.relation.keys.length&&w("*:"+o+"="+W0.relation.keys.map((X0)=>K[X0.name]),K,W0),w(W0.command,K,W0),w(W0.command+":"+o,K,W0),W0.relation.keys.length&&w(W0.command+":"+o+"="+W0.relation.keys.map((X0)=>K[X0.name]),K,W0)}function y0(){let K=Buffer.alloc(34);K[0]=114,K.fill(p.lsn,1),K.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),i.write(K)}}function w(A,x,j){Z.has(A)&&Z.get(A).forEach(({fn:P})=>P(x,j,A))}}function FE(X){return new Date(Date.UTC(2000,0,1)+Number(X/BigInt(1000)))}function UE(X,Y,Z,_,G){let W=($,[H,Q])=>($[H.charCodeAt(0)]=Q,$);Object.entries({R:($)=>{let H=1,Q=Y[$.readUInt32BE(H)]={schema:$.toString("utf8",H+=4,H=$.indexOf(0,H))||"pg_catalog",table:$.toString("utf8",H+1,H=$.indexOf(0,H+1)),columns:Array($.readUInt16BE(H+=2)),keys:[]};H+=2;let J=0,z;while(H<$.length)z=Q.columns[J++]={key:$[H++],name:G.column.from?G.column.from($.toString("utf8",H,H=$.indexOf(0,H))):$.toString("utf8",H,H=$.indexOf(0,H)),type:$.readUInt32BE(H+=1),parser:Z[$.readUInt32BE(H)],atttypmod:$.readUInt32BE(H+=4)},z.key&&Q.keys.push(z),H+=4},Y:()=>{},O:()=>{},B:($)=>{Y.date=FE($.readBigInt64BE(9)),Y.lsn=$.subarray(1,9)},I:($)=>{let H=1,Q=Y[$.readUInt32BE(H)],{row:J}=ZX($,Q.columns,H+=7,G);_(J,{command:"insert",relation:Q})},D:($)=>{let H=1,Q=Y[$.readUInt32BE(H)];H+=4;let J=$[H]===75;_(J||$[H]===79?ZX($,Q.columns,H+=3,G).row:null,{command:"delete",relation:Q,key:J})},U:($)=>{let H=1,Q=Y[$.readUInt32BE(H)];H+=4;let J=$[H]===75,z=J||$[H]===79?ZX($,Q.columns,H+=3,G):null;z&&(H=z.i);let{row:F}=ZX($,Q.columns,H+3,G);_(F,{command:"update",relation:Q,key:J,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce(W,{})[X[0]](X)}function ZX(X,Y,Z,_){let G,W,$,H=_.raw?Array(Y.length):{};for(let Q=0;Q<Y.length;Q++)G=X[Z++],W=Y[Q],$=G===110?null:G===117?void 0:W.parser===void 0?X.toString("utf8",Z+4,Z+=4+X.readUInt32BE(Z)):W.parser.array===!0?W.parser(X.toString("utf8",Z+5,Z+=4+X.readUInt32BE(Z))):W.parser(X.toString("utf8",Z+4,Z+=4+X.readUInt32BE(Z))),_.raw?H[Q]=_.raw===!0?$:_.value.from?_.value.from($,W):$:H[W.name]=_.value.from?_.value.from($,W):$;return{i:Z,row:_.row.from?_.row.from(H):H}}function EE(X){let Y=X.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!Y)throw Error("Malformed subscribe pattern: "+X);let[,Z,_,G]=Y;return(Z||"*")+(_?":"+(_.indexOf(".")===-1?"public."+_:_):"")+(G?"="+G:"")}import x$ from"stream";function lZ(X,Y,Z=393216){return new Promise(async(_,G)=>{await X.begin(async(W)=>{let $;!Y&&([{oid:Y}]=await W`select lo_creat(-1) as oid`);let[{fd:H}]=await W`select lo_open(${Y}, ${Z}) as fd`,Q={writable:z,readable:J,close:()=>W`select lo_close(${H})`.then($),tell:()=>W`select lo_tell64(${H})`,read:(F)=>W`select loread(${H}, ${F}) as data`,write:(F)=>W`select lowrite(${H}, ${F})`,truncate:(F)=>W`select lo_truncate64(${H}, ${F})`,seek:(F,O=0)=>W`select lo_lseek64(${H}, ${F}, ${O})`,size:()=>W`
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
78
  select
79
79
  lo_lseek64(${H}, location, 0) as position,
80
80
  seek.size
@@ -84,10 +84,10 @@ params: ${Y}`);if(this.query=X,this.params=Y,this.cause=Z,Error.captureStackTrac
84
84
  tell.location
85
85
  from (select lo_tell64($1) as location) tell
86
86
  ) seek
87
- `};return _(Q),new Promise(async(F)=>$=F);async function J({highWaterMark:F=16384,start:O=0,end:D=1/0}={}){let w=D-O;return O&&await Q.seek(O),new x$.Readable({highWaterMark:F,async read(A){let x=A>w?A-w:A;w-=A;let[{data:j}]=await Q.read(x);if(this.push(j),j.length<A)this.push(null)}})}async function z({highWaterMark:F=16384,start:O=0}={}){return O&&await Q.seek(O),new x$.Writable({highWaterMark:F,write(D,w,A){Q.write(D).then(()=>A(),A)}})}}).catch(G)})}Object.assign(_X,{PostgresError:A8,toPascal:g4,pascal:yZ,toCamel:y4,camel:bZ,toKebab:p4,kebab:gZ,fromPascal:q2,fromCamel:C2,fromKebab:j2,BigInt:{to:20,from:[20],parse:(X)=>BigInt(X),serialize:(X)=>X.toString()}});var w8=_X;function _X(X,Y){let Z=DE(X,Y),_=Z.no_subscribe||cZ(_X,{...Z}),G=!1,W=M1(),$=M1(),H=M1(),Q=M1(),J=M1(),z=M1(),F=M1(),O=M1(),D={connecting:$,reserved:H,closed:Q,ended:J,open:z,busy:F,full:O},w=[...Array(Z.max)].map(()=>dZ(Z,D,{onopen:q1,onend:O1,onclose:c4})),A=x(_0);return Object.assign(A,{get parameters(){return Z.parameters},largeObject:lZ.bind(null,A),subscribe:_,CLOSE:M8,END:M8,PostgresError:A8,options:Z,reserve:h,listen:j,begin:i,close:o,end:W0}),A;function x(I){return I.debug=Z.debug,Object.entries(Z.types).reduce((n,[H0,q0])=>{return n[H0]=(N0)=>new n1(N0,q0.to),n},u),Object.assign($0,{types:u,typed:u,unsafe:R0,notify:P,array:m,json:y,file:P0}),$0;function u(n,H0){return new n1(n,H0)}function $0(n,...H0){return n&&Array.isArray(n.raw)?new C1(n,H0,I,K):typeof n==="string"&&!H0.length?new S2(Z.transform.column.to?Z.transform.column.to(n):n):new t6(n,H0)}function R0(n,H0=[],q0={}){return arguments.length===2&&!Array.isArray(H0)&&(q0=H0,H0=[]),new C1([n],H0,I,K,{prepare:!1,...q0,simple:"simple"in q0?q0.simple:H0.length===0})}function P0(n,H0=[],q0={}){return arguments.length===2&&!Array.isArray(H0)&&(q0=H0,H0=[]),new C1([],H0,(D0)=>{VE.readFile(n,"utf8",(d0,U0)=>{if(d0)return D0.reject(d0);D0.strings=[U0],I(D0)})},K,{...q0,simple:"simple"in q0?q0.simple:H0.length===0})}}async function j(I,u,$0){let R0={fn:u,onlisten:$0},P0=j.sql||(j.sql=_X({...Z,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(j.channels).forEach(([D0,{listeners:d0}])=>{delete j.channels[D0],Promise.all(d0.map((U0)=>j(D0,U0.fn,U0.onlisten).catch(()=>{})))})},onnotify(D0,d0){D0 in j.channels&&j.channels[D0].listeners.forEach((U0)=>U0.fn(d0))}})),n=j.channels||(j.channels={});if(I in n){n[I].listeners.push(R0);let D0=await n[I].result;return R0.onlisten&&R0.onlisten(),{state:D0.state,unlisten:N0}}n[I]={result:P0`listen ${P0.unsafe('"'+I.replace(/"/g,'""')+'"')}`,listeners:[R0]};let q0=await n[I].result;return R0.onlisten&&R0.onlisten(),{state:q0.state,unlisten:N0};async function N0(){if(I in n===!1)return;if(n[I].listeners=n[I].listeners.filter((D0)=>D0!==R0),n[I].listeners.length)return;return delete n[I],P0`unlisten ${P0.unsafe('"'+I.replace(/"/g,'""')+'"')}`}}async function P(I,u){return await A`select pg_notify(${I}, ${""+u})`}async function h(){let I=M1(),u=z.length?z.shift():await new Promise((P0,n)=>{let H0={reserve:P0,reject:n};W.push(H0),Q.length&&p0(Q.shift(),H0)});p(u,H),u.reserved=()=>I.length?u.execute(I.shift()):p(u,H),u.reserved.release=!0;let $0=x(R0);return $0.release=()=>{u.reserved=null,q1(u)},$0;function R0(P0){u.queue===O?I.push(P0):u.execute(P0)||p(u,O)}}async function i(I,u){!u&&(u=I,I="");let $0=M1(),R0=0,P0,n=null;try{return await A.unsafe("begin "+I.replace(/[^a-z ]/ig,""),[],{onexecute:q0}).execute(),await Promise.race([H0(P0,u),new Promise((N0,D0)=>P0.onclose=D0)])}catch(N0){throw N0}async function H0(N0,D0,d0){let U0=x(v0);U0.savepoint=z4,U0.prepare=(L0)=>n=L0.replace(/[^a-z0-9$-_. ]/gi);let j1,m0;d0&&await U0`savepoint ${U0(d0)}`;try{if(m0=await new Promise((L0,S1)=>{let u1=D0(U0);Promise.resolve(Array.isArray(u1)?Promise.all(u1):u1).then(L0,S1)}),j1)throw j1}catch(L0){throw await(d0?U0`rollback to ${U0(d0)}`:U0`rollback`),L0 instanceof A8&&L0.code==="25P02"&&j1||L0}if(!d0)n?await U0`prepare transaction '${U0.unsafe(n)}'`:await U0`commit`;return m0;function z4(L0,S1){if(L0&&Array.isArray(L0.raw))return z4((u1)=>u1.apply(u1,arguments));return arguments.length===1&&(S1=L0,L0=null),H0(N0,S1,"s"+R0+++(L0?"_"+L0:""))}function v0(L0){L0.catch((S1)=>j1||(j1=S1)),N0.queue===O?$0.push(L0):N0.execute(L0)||p(N0,O)}}function q0(N0){P0=N0,p(N0,H),N0.reserved=()=>$0.length?N0.execute($0.shift()):p(N0,H)}}function p(I,u){return I.queue.remove(I),u.push(I),I.queue=u,u===z?I.idleTimer.start():I.idleTimer.cancel(),I}function y(I){return new n1(I,3802)}function m(I,u){if(!Array.isArray(I))return m(Array.from(arguments));return new n1(I,u||(I.length?r6(I)||25:0),Z.shared.typeArrayMap)}function _0(I){if(G)return I.reject(S0.connection("CONNECTION_ENDED",Z,Z));if(z.length)return y0(z.shift(),I);if(Q.length)return p0(Q.shift(),I);F.length?y0(F.shift(),I):W.push(I)}function y0(I,u){return I.execute(u)?p(I,F):p(I,O)}function K(I){return new Promise((u,$0)=>{I.state?I.active?dZ(Z).cancel(I.state,u,$0):I.cancelled={resolve:u,reject:$0}:(W.remove(I),I.cancelled=!0,I.reject(S0.generic("57014","canceling statement due to user request")),u())})}async function W0({timeout:I=null}={}){if(G)return G;await 1;let u;return G=Promise.race([new Promise(($0)=>I!==null&&(u=setTimeout(X0,I*1000,$0))),Promise.all(w.map(($0)=>$0.end()).concat(j.sql?j.sql.end({timeout:0}):[],_.sql?_.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(u))}async function o(){await Promise.all(w.map((I)=>I.end()))}async function X0(I){await Promise.all(w.map((u)=>u.terminate()));while(W.length)W.shift().reject(S0.connection("CONNECTION_DESTROYED",Z));I()}function p0(I,u){return p(I,$),I.connect(u),I}function O1(I){p(I,J)}function q1(I){if(W.length===0)return p(I,z);let u=Math.ceil(W.length/($.length+1)),$0=!0;while($0&&W.length&&u-- >0){let R0=W.shift();if(R0.reserve)return R0.reserve(I);$0=I.execute(R0)}$0?p(I,F):p(I,O)}function c4(I,u){p(I,Q),I.reserved=null,I.onclose&&(I.onclose(u),I.onclose=null),Z.onclose&&Z.onclose(I.id),W.length&&p0(I,W.shift())}}function DE(X,Y){if(X&&X.shared)return X;let Z=process.env,_=(!X||typeof X==="string"?Y:X)||{},{url:G,multihost:W}=wE(X),$=[...G.searchParams].reduce((O,[D,w])=>(O[D]=w,O),{}),H=_.hostname||_.host||W||G.hostname||Z.PGHOST||"localhost",Q=_.port||G.port||Z.PGPORT||5432,J=_.user||_.username||G.username||Z.PGUSERNAME||Z.PGUSER||NE();_.no_prepare&&(_.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in _&&(console.log("The timeout option is deprecated, use idle_timeout instead"),_.idle_timeout=_.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],F={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:AE,max_pipeline:100,backoff:ME,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(H)?H:H.split(",").map((O)=>O.split(":")[0]),port:Array.isArray(Q)?Q:H.split(",").map((O)=>parseInt(O.split(":")[1]||Q)),path:_.path||H.indexOf("/")>-1&&H+"/.s.PGSQL."+Q,database:_.database||_.db||(G.pathname||"").slice(1)||Z.PGDATABASE||J,user:J,pass:_.pass||_.password||G.password||Z.PGPASSWORD||"",...Object.entries(F).reduce((O,[D,w])=>{let A=D in _?_[D]:(D in $)?$[D]==="disable"||$[D]==="false"?!1:$[D]:Z["PG"+D.toUpperCase()]||w;return O[D]=typeof A==="string"&&z.includes(D)?+A:A,O},{}),connection:{application_name:Z.PGAPPNAME||"postgres.js",..._.connection,...Object.entries($).reduce((O,[D,w])=>((D in F)||(O[D]=w),O),{})},types:_.types||{},target_session_attrs:LE(_,G,Z),onnotice:_.onnotice,onnotify:_.onnotify,onclose:_.onclose,onparameter:_.onparameter,socket:_.socket,transform:RE(_.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...N$(_.types)}}function LE(X,Y,Z){let _=X.target_session_attrs||Y.searchParams.get("target_session_attrs")||Z.PGTARGETSESSIONATTRS;if(!_||["read-write","read-only","primary","standby","prefer-standby"].includes(_))return _;throw Error("target_session_attrs "+_+" is not supported")}function ME(X){return(0.5+Math.random()/2)*Math.min(3**X/100,20)}function AE(){return 60*(30+Math.random()*30)}function RE(X){return{undefined:X.undefined,column:{from:typeof X.column==="function"?X.column:X.column&&X.column.from,to:X.column&&X.column.to},value:{from:typeof X.value==="function"?X.value:X.value&&X.value.from,to:X.value&&X.value.to},row:{from:typeof X.row==="function"?X.row:X.row&&X.row.from,to:X.row&&X.row.to}}}function wE(X){if(!X||typeof X!=="string")return{url:{searchParams:new Map}};let Y=X;Y=Y.slice(Y.indexOf("://")+3).split(/[?/]/)[0],Y=decodeURIComponent(Y.slice(Y.indexOf("@")+1));let Z=new URL(X.replace(Y,Y.split(",")[0]));return{url:{username:decodeURIComponent(Z.username),password:decodeURIComponent(Z.password),host:Z.host,hostname:Z.hostname,port:Z.port,pathname:Z.pathname,searchParams:Z.searchParams},multihost:Y.indexOf(",")>-1&&Y}}function NE(){try{return OE.userInfo().username}catch(X){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class B0{static[E]="SelectionProxyHandler";config;constructor(X){this.config={...X}}get(X,Y){if(Y==="_")return{...X._,selectedFields:new Proxy(X._.selectedFields,this)};if(Y===V0)return{...X[V0],selectedFields:new Proxy(X[V0].selectedFields,this)};if(typeof Y==="symbol")return X[Y];let _=(M(X,C0)?X._.selectedFields:M(X,F1)?X[V0].selectedFields:X)[Y];if(M(_,S.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!_.isSelectionField)return _.sql;let G=_.clone();return G.isSelectionField=!0,G}if(M(_,S)){if(this.config.sqlBehavior==="sql")return _;throw Error(`You tried to reference "${Y}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(M(_,z0)){if(this.config.alias)return new Proxy(_,new L8(new Proxy(_.table,new A2(this.config.alias,this.config.replaceOriginalName??!1))));return _}if(typeof _!=="object"||_===null)return _;return new Proxy(_,new B0(this.config))}}class f${constructor(X,Y){this.unique=X,this.name=Y}static[E]="PgIndexBuilderOn";on(...X){return new GX(X.map((Y)=>{if(M(Y,S))return Y;Y=Y;let Z=new V2(Y.name,!!Y.keyAsName,Y.columnType,Y.indexConfig);return Y.indexConfig=JSON.parse(JSON.stringify(Y.defaultConfig)),Z}),this.unique,!1,this.name)}onOnly(...X){return new GX(X.map((Y)=>{if(M(Y,S))return Y;Y=Y;let Z=new V2(Y.name,!!Y.keyAsName,Y.columnType,Y.indexConfig);return Y.indexConfig=Y.defaultConfig,Z}),this.unique,!0,this.name)}using(X,...Y){return new GX(Y.map((Z)=>{if(M(Z,S))return Z;Z=Z;let _=new V2(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=JSON.parse(JSON.stringify(Z.defaultConfig)),_}),this.unique,!0,this.name,X)}}class GX{static[E]="PgIndexBuilder";config;constructor(X,Y,Z,_,G="btree"){this.config={name:_,columns:X,unique:Y,only:Z,method:G}}concurrently(){return this.config.concurrently=!0,this}with(X){return this.config.with=X,this}where(X){return this.config.where=X,this}build(X){return new h$(this.config,X)}}class h${static[E]="PgIndex";config;constructor(X,Y){this.config={...X,table:Y}}}function oZ(X){return new f$(!0,X)}function IE(X){return(X.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((Z)=>Z.toLowerCase()).join("_")}function KE(X){return(X.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((Z,_,G)=>{let W=G===0?_.toLowerCase():`${_[0].toUpperCase()}${_.slice(1)}`;return Z+W},"")}function BE(X){return X}class iZ{static[E]="CasingCache";cache={};cachedTables={};convert;constructor(X){this.convert=X==="snake_case"?IE:X==="camelCase"?KE:BE}getColumnCasing(X){if(!X.keyAsName)return X.name;let Y=X.table[T.Symbol.Schema]??"public",Z=X.table[T.Symbol.OriginalName],_=`${Y}.${Z}.${X.name}`;if(!this.cache[_])this.cacheTable(X.table);return this.cache[_]}cacheTable(X){let Y=X[T.Symbol.Schema]??"public",Z=X[T.Symbol.OriginalName],_=`${Y}.${Z}`;if(!this.cachedTables[_]){for(let G of Object.values(X[T.Symbol.Columns])){let W=`${_}.${G.name}`;this.cache[W]=this.convert(G.name)}this.cachedTables[_]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class v2 extends F1{static[E]="PgViewBase"}class u4{static[E]="PgDialect";casing;constructor(X){this.casing=new iZ(X?.casing)}async migrate(X,Y,Z){let _=typeof Z==="string"?"__drizzle_migrations":Z.migrationsTable??"__drizzle_migrations",G=typeof Z==="string"?"drizzle":Z.migrationsSchema??"drizzle",W=V`
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
88
  CREATE TABLE IF NOT EXISTS ${V.identifier(G)}.${V.identifier(_)} (
89
89
  id SERIAL PRIMARY KEY,
90
90
  hash text NOT NULL,
91
91
  created_at bigint
92
92
  )
93
- `;await Y.execute(V`CREATE SCHEMA IF NOT EXISTS ${V.identifier(G)}`),await Y.execute(W);let H=(await Y.all(V`select id, hash, created_at from ${V.identifier(G)}.${V.identifier(_)} order by created_at desc limit 1`))[0];await Y.transaction(async(Q)=>{for await(let J of X)if(!H||Number(H.created_at)<J.folderMillis){for(let z of J.sql)await Q.execute(V.raw(z));await Q.execute(V`insert into ${V.identifier(G)}.${V.identifier(_)} ("hash", "created_at") values(${J.hash}, ${J.folderMillis})`)}})}escapeName(X){return`"${X}"`}escapeParam(X){return`$${X+1}`}escapeString(X){return`'${X.replace(/'/g,"''")}'`}buildWithCTE(X){if(!X?.length)return;let Y=[V`with `];for(let[Z,_]of X.entries())if(Y.push(V`${V.identifier(_._.alias)} as (${_._.sql})`),Z<X.length-1)Y.push(V`, `);return Y.push(V` `),V.join(Y)}buildDeleteQuery({table:X,where:Y,returning:Z,withList:_}){let G=this.buildWithCTE(_),W=Z?V` returning ${this.buildSelection(Z,{isSingleTable:!0})}`:void 0,$=Y?V` where ${Y}`:void 0;return V`${G}delete from ${X}${$}${W}`}buildUpdateSet(X,Y){let Z=X[T.Symbol.Columns],_=Object.keys(Z).filter((W)=>Y[W]!==void 0||Z[W]?.onUpdateFn!==void 0),G=_.length;return V.join(_.flatMap((W,$)=>{let H=Z[W],Q=Y[W]??V.param(H.onUpdateFn(),H),J=V`${V.identifier(this.casing.getColumnCasing(H))} = ${Q}`;if($<G-1)return[J,V.raw(", ")];return[J]}))}buildUpdateQuery({table:X,set:Y,where:Z,returning:_,withList:G,from:W,joins:$}){let H=this.buildWithCTE(G),Q=X[b0.Symbol.Name],J=X[b0.Symbol.Schema],z=X[b0.Symbol.OriginalName],F=Q===z?void 0:Q,O=V`${J?V`${V.identifier(J)}.`:void 0}${V.identifier(z)}${F&&V` ${V.identifier(F)}`}`,D=this.buildUpdateSet(X,Y),w=W&&V.join([V.raw(" from "),this.buildFromTable(W)]),A=this.buildJoins($),x=_?V` returning ${this.buildSelection(_,{isSingleTable:!W})}`:void 0,j=Z?V` where ${Z}`:void 0;return V`${H}update ${O} set ${D}${w}${A}${j}${x}`}buildSelection(X,{isSingleTable:Y=!1}={}){let Z=X.length,_=X.flatMap(({field:G},W)=>{let $=[];if(M(G,S.Aliased)&&G.isSelectionField)$.push(V.identifier(G.fieldAlias));else if(M(G,S.Aliased)||M(G,S)){let H=M(G,S.Aliased)?G.sql:G;if(Y)$.push(new S(H.queryChunks.map((Q)=>{if(M(Q,B))return V.identifier(this.casing.getColumnCasing(Q));return Q})));else $.push(H);if(M(G,S.Aliased))$.push(V` as ${V.identifier(G.fieldAlias)}`)}else if(M(G,z0))if(Y)$.push(V.identifier(this.casing.getColumnCasing(G)));else $.push(G);if(W<Z-1)$.push(V`, `);return $});return V.join(_)}buildJoins(X){if(!X||X.length===0)return;let Y=[];for(let[Z,_]of X.entries()){if(Z===0)Y.push(V` `);let G=_.table,W=_.lateral?V` lateral`:void 0,$=_.on?V` on ${_.on}`:void 0;if(M(G,b0)){let H=G[b0.Symbol.Name],Q=G[b0.Symbol.Schema],J=G[b0.Symbol.OriginalName],z=H===J?void 0:_.alias;Y.push(V`${V.raw(_.joinType)} join${W} ${Q?V`${V.identifier(Q)}.`:void 0}${V.identifier(J)}${z&&V` ${V.identifier(z)}`}${$}`)}else if(M(G,F1)){let H=G[V0].name,Q=G[V0].schema,J=G[V0].originalName,z=H===J?void 0:_.alias;Y.push(V`${V.raw(_.joinType)} join${W} ${Q?V`${V.identifier(Q)}.`:void 0}${V.identifier(J)}${z&&V` ${V.identifier(z)}`}${$}`)}else Y.push(V`${V.raw(_.joinType)} join${W} ${G}${$}`);if(Z<X.length-1)Y.push(V` `)}return V.join(Y)}buildFromTable(X){if(M(X,T)&&X[T.Symbol.IsAlias]){let Y=V`${V.identifier(X[T.Symbol.OriginalName])}`;if(X[T.Symbol.Schema])Y=V`${V.identifier(X[T.Symbol.Schema])}.${Y}`;return V`${Y} ${V.identifier(X[T.Symbol.Name])}`}return X}buildSelectQuery({withList:X,fields:Y,fieldsFlat:Z,where:_,having:G,table:W,joins:$,orderBy:H,groupBy:Q,limit:J,offset:z,lockingClause:F,distinct:O,setOperators:D}){let w=Z??B1(Y);for(let X0 of w)if(M(X0.field,z0)&&g0(X0.field.table)!==(M(W,C0)?W._.alias:M(W,v2)?W[V0].name:M(W,S)?void 0:g0(W))&&!((p0)=>$?.some(({alias:O1})=>O1===(p0[T.Symbol.IsAlias]?g0(p0):p0[T.Symbol.BaseName])))(X0.field.table)){let p0=g0(X0.field.table);throw Error(`Your "${X0.path.join("->")}" field references a column "${p0}"."${X0.field.name}", but the table "${p0}" is not part of the query! Did you forget to join it?`)}let A=!$||$.length===0,x=this.buildWithCTE(X),j;if(O)j=O===!0?V` distinct`:V` distinct on (${V.join(O.on,V`, `)})`;let P=this.buildSelection(w,{isSingleTable:A}),h=this.buildFromTable(W),i=this.buildJoins($),p=_?V` where ${_}`:void 0,y=G?V` having ${G}`:void 0,m;if(H&&H.length>0)m=V` order by ${V.join(H,V`, `)}`;let _0;if(Q&&Q.length>0)_0=V` group by ${V.join(Q,V`, `)}`;let y0=typeof J==="object"||typeof J==="number"&&J>=0?V` limit ${J}`:void 0,K=z?V` offset ${z}`:void 0,W0=V.empty();if(F){let X0=V` for ${V.raw(F.strength)}`;if(F.config.of)X0.append(V` of ${V.join(Array.isArray(F.config.of)?F.config.of:[F.config.of],V`, `)}`);if(F.config.noWait)X0.append(V` nowait`);else if(F.config.skipLocked)X0.append(V` skip locked`);W0.append(X0)}let o=V`${x}select${j} ${P} from ${h}${i}${p}${_0}${y}${m}${y0}${K}${W0}`;if(D.length>0)return this.buildSetOperations(o,D);return o}buildSetOperations(X,Y){let[Z,..._]=Y;if(!Z)throw Error("Cannot pass undefined values to any set operator");if(_.length===0)return this.buildSetOperationQuery({leftSelect:X,setOperator:Z});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:X,setOperator:Z}),_)}buildSetOperationQuery({leftSelect:X,setOperator:{type:Y,isAll:Z,rightSelect:_,limit:G,orderBy:W,offset:$}}){let H=V`(${X.getSQL()}) `,Q=V`(${_.getSQL()})`,J;if(W&&W.length>0){let D=[];for(let w of W)if(M(w,B))D.push(V.identifier(w.name));else if(M(w,S)){for(let A=0;A<w.queryChunks.length;A++){let x=w.queryChunks[A];if(M(x,B))w.queryChunks[A]=V.identifier(x.name)}D.push(V`${w}`)}else D.push(V`${w}`);J=V` order by ${V.join(D,V`, `)} `}let z=typeof G==="object"||typeof G==="number"&&G>=0?V` limit ${G}`:void 0,F=V.raw(`${Y} ${Z?"all ":""}`),O=$?V` offset ${$}`:void 0;return V`${H}${F}${Q}${J}${z}${O}`}buildInsertQuery({table:X,values:Y,onConflict:Z,returning:_,withList:G,select:W,overridingSystemValue_:$}){let H=[],Q=X[T.Symbol.Columns],J=Object.entries(Q).filter(([x,j])=>!j.shouldDisableInsert()),z=J.map(([,x])=>V.identifier(this.casing.getColumnCasing(x)));if(W){let x=Y;if(M(x,S))H.push(x);else H.push(x.getSQL())}else{let x=Y;H.push(V.raw("values "));for(let[j,P]of x.entries()){let h=[];for(let[i,p]of J){let y=P[i];if(y===void 0||M(y,L1)&&y.value===void 0)if(p.defaultFn!==void 0){let m=p.defaultFn(),_0=M(m,S)?m:V.param(m,p);h.push(_0)}else if(!p.default&&p.onUpdateFn!==void 0){let m=p.onUpdateFn(),_0=M(m,S)?m:V.param(m,p);h.push(_0)}else h.push(V`default`);else h.push(y)}if(H.push(h),j<x.length-1)H.push(V`, `)}}let F=this.buildWithCTE(G),O=V.join(H),D=_?V` returning ${this.buildSelection(_,{isSingleTable:!0})}`:void 0,w=Z?V` on conflict ${Z}`:void 0,A=$===!0?V`overriding system value `:void 0;return V`${F}insert into ${X} ${z} ${A}${O}${w}${D}`}buildRefreshMaterializedViewQuery({view:X,concurrently:Y,withNoData:Z}){let _=Y?V` concurrently`:void 0,G=Z?V` with no data`:void 0;return V`refresh materialized view${_} ${X}${G}`}prepareTyping(X){if(M(X,g6)||M(X,y6))return"json";else if(M(X,p6))return"decimal";else if(M(X,m6))return"time";else if(M(X,u6)||M(X,d6))return"timestamp";else if(M(X,k6)||M(X,b6))return"date";else if(M(X,c6))return"uuid";else return"none"}sqlToQuery(X,Y){return X.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:Y})}buildRelationalQueryWithoutPK({fullSchema:X,schema:Y,tableNamesMap:Z,table:_,tableConfig:G,queryConfig:W,tableAlias:$,nestedQueryRelation:H,joinOn:Q}){let J=[],z,F,O=[],D,w=[];if(W===!0)J=Object.entries(G.columns).map(([j,P])=>({dbKey:P.name,tsKey:j,field:i1(P,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let x=Object.fromEntries(Object.entries(G.columns).map(([y,m])=>[y,i1(m,$)]));if(W.where){let y=typeof W.where==="function"?W.where(x,Q$()):W.where;D=y&&R2(y,$)}let j=[],P=[];if(W.columns){let y=!1;for(let[m,_0]of Object.entries(W.columns)){if(_0===void 0)continue;if(m in G.columns){if(!y&&_0===!0)y=!0;P.push(m)}}if(P.length>0)P=y?P.filter((m)=>W.columns?.[m]===!0):Object.keys(G.columns).filter((m)=>!P.includes(m))}else P=Object.keys(G.columns);for(let y of P){let m=G.columns[y];j.push({tsKey:y,value:m})}let h=[];if(W.with)h=Object.entries(W.with).filter((y)=>!!y[1]).map(([y,m])=>({tsKey:y,queryConfig:m,relation:G.relations[y]}));let i;if(W.extras){i=typeof W.extras==="function"?W.extras(x,{sql:V}):W.extras;for(let[y,m]of Object.entries(i))j.push({tsKey:y,value:wZ(m,$)})}for(let{tsKey:y,value:m}of j)J.push({dbKey:M(m,S.Aliased)?m.fieldAlias:G.columns[y].name,tsKey:y,field:M(m,z0)?i1(m,$):m,relationTableTsKey:void 0,isJson:!1,selection:[]});let p=typeof W.orderBy==="function"?W.orderBy(x,z$()):W.orderBy??[];if(!Array.isArray(p))p=[p];O=p.map((y)=>{if(M(y,z0))return i1(y,$);return R2(y,$)}),z=W.limit,F=W.offset;for(let{tsKey:y,queryConfig:m,relation:_0}of h){let y0=U$(Y,Z,_0),K=b4(_0.referencedTable),W0=Z[K],o=`${$}_${y}`,X0=B2(...y0.fields.map((q1,c4)=>l6(i1(y0.references[c4],o),i1(q1,$)))),p0=this.buildRelationalQueryWithoutPK({fullSchema:X,schema:Y,tableNamesMap:Z,table:X[W0],tableConfig:Y[W0],queryConfig:M(_0,K4)?m===!0?{limit:1}:{...m,limit:1}:m,tableAlias:o,joinOn:X0,nestedQueryRelation:_0}),O1=V`${V.identifier(o)}.${V.identifier("data")}`.as(y);w.push({on:V`true`,table:new C0(p0.sql,{},o),alias:o,joinType:"left",lateral:!0}),J.push({dbKey:y,tsKey:y,field:O1,relationTableTsKey:W0,isJson:!0,selection:p0.selection})}}if(J.length===0)throw new f6({message:`No fields selected for table "${G.tsName}" ("${$}")`});let A;if(D=B2(Q,D),H){let x=V`json_build_array(${V.join(J.map(({field:h,tsKey:i,isJson:p})=>p?V`${V.identifier(`${$}_${i}`)}.${V.identifier("data")}`:M(h,S.Aliased)?h.sql:h),V`, `)})`;if(M(H,T2))x=V`coalesce(json_agg(${x}${O.length>0?V` order by ${V.join(O,V`, `)}`:void 0}), '[]'::json)`;let j=[{dbKey:"data",tsKey:"data",field:x.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:J}];if(z!==void 0||F!==void 0||O.length>0)A=this.buildSelectQuery({table:x6(_,$),fields:{},fieldsFlat:[{path:[],field:V.raw("*")}],where:D,limit:z,offset:F,orderBy:O,setOperators:[]}),D=void 0,z=void 0,F=void 0,O=[];else A=x6(_,$);A=this.buildSelectQuery({table:M(A,b0)?A:new C0(A,{},$),fields:{},fieldsFlat:j.map(({field:h})=>({path:[],field:M(h,z0)?i1(h,$):h})),joins:w,where:D,limit:z,offset:F,orderBy:O,setOperators:[]})}else A=this.buildSelectQuery({table:x6(_,$),fields:{},fieldsFlat:J.map(({field:x})=>({path:[],field:M(x,z0)?i1(x,$):x})),joins:w,where:D,limit:z,offset:F,orderBy:O,setOperators:[]});return{tableTsKey:G.tsName,sql:A,selection:J}}}class nZ{static[E]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Z1{static[E]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(X){if(this.fields=X.fields,this.session=X.session,this.dialect=X.dialect,X.withList)this.withList=X.withList;this.distinct=X.distinct}authToken;setToken(X){return this.authToken=X,this}from(X){let Y=!!this.fields,Z=X,_;if(this.fields)_=this.fields;else if(M(Z,C0))_=Object.fromEntries(Object.keys(Z._.selectedFields).map((G)=>[G,Z[G]]));else if(M(Z,v2))_=Z[V0].selectedFields;else if(M(Z,S))_={};else _=m7(Z);return new rZ({table:Z,fields:_,isPartialSelect:Y,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class k$ extends nZ{static[E]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:X,fields:Y,isPartialSelect:Z,session:_,dialect:G,withList:W,distinct:$}){super();this.config={withList:W,table:X,fields:{...Y},distinct:$,setOperators:[]},this.isPartialSelect=Z,this.session=_,this.dialect=G,this._={selectedFields:Y,config:this.config},this.tableName=J4(X),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let H of m1(X))this.usedTables.add(H)}getUsedTables(){return[...this.usedTables]}createJoin(X,Y){return(Z,_)=>{let G=this.tableName,W=J4(Z);for(let $ of m1(Z))this.usedTables.add($);if(typeof W==="string"&&this.config.joins?.some(($)=>$.alias===W))throw Error(`Alias "${W}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof G==="string")this.config.fields={[G]:this.config.fields};if(typeof W==="string"&&!M(Z,S)){let $=M(Z,C0)?Z._.selectedFields:M(Z,F1)?Z[V0].selectedFields:Z[T.Symbol.Columns];this.config.fields[W]=$}}if(typeof _==="function")_=_(new Proxy(this.config.fields,new B0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:_,table:Z,joinType:X,alias:W,lateral:Y}),typeof W==="string")switch(X){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[W]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[W]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[W]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(X,Y){return(Z)=>{let _=typeof Z==="function"?Z(TE()):Z;if(!w2(this.getSelectedFields(),_.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:X,isAll:Y,rightSelect:_}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(X){return this.config.setOperators.push(...X),this}where(X){if(typeof X==="function")X=X(new Proxy(this.config.fields,new B0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=X,this}having(X){if(typeof X==="function")X=X(new Proxy(this.config.fields,new B0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=X,this}groupBy(...X){if(typeof X[0]==="function"){let Y=X[0](new Proxy(this.config.fields,new B0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(Y)?Y:[Y]}else this.config.groupBy=X;return this}orderBy(...X){if(typeof X[0]==="function"){let Y=X[0](new Proxy(this.config.fields,new B0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),Z=Array.isArray(Y)?Y:[Y];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Z;else this.config.orderBy=Z}else{let Y=X;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Y;else this.config.orderBy=Y}return this}limit(X){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=X;else this.config.limit=X;return this}offset(X){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=X;else this.config.offset=X;return this}for(X,Y={}){return this.config.lockingClause={strength:X,config:Y},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:X,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}as(X){let Y=[];if(Y.push(...m1(this.config.table)),this.config.joins)for(let Z of this.config.joins)Y.push(...m1(Z.table));return new Proxy(new C0(this.getSQL(),this.config.fields,X,!1,[...new Set(Y)]),new B0({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new B0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(X){return this.cacheConfig=X===void 0?{config:{},enable:!0,autoInvalidate:!0}:X===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...X},this}}class rZ extends k${static[E]="PgSelect";_prepare(X){let{session:Y,config:Z,dialect:_,joinsNotNullableMap:G,authToken:W,cacheConfig:$,usedTables:H}=this;if(!Y)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:Q}=Z;return F0.startActiveSpan("drizzle.prepareQuery",()=>{let J=B1(Q),z=Y.prepareQuery(_.sqlToQuery(this.getSQL()),J,X,!0,void 0,{type:"select",tables:[...H]},$);return z.joinsNotNullableMap=G,z.setToken(W)})}prepare(X){return this._prepare(X)}authToken;setToken(X){return this.authToken=X,this}execute=(X)=>{return F0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(X,this.authToken)})}}p7(rZ,[Y1]);function N8(X,Y){return(Z,_,...G)=>{let W=[_,...G].map(($)=>({type:X,isAll:Y,rightSelect:$}));for(let $ of W)if(!w2(Z.getSelectedFields(),$.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return Z.addSetOperators(W)}}var TE=()=>({union:CE,unionAll:qE,intersect:jE,intersectAll:SE,except:PE,exceptAll:vE}),CE=N8("union",!1),qE=N8("union",!0),jE=N8("intersect",!1),SE=N8("intersect",!0),PE=N8("except",!1),vE=N8("except",!0);class x2{static[E]="PgQueryBuilder";dialect;dialectConfig;constructor(X){this.dialect=M(X,u4)?X:void 0,this.dialectConfig=M(X,u4)?void 0:X}$with=(X,Y)=>{let Z=this;return{as:(G)=>{if(typeof G==="function")G=G(Z);return new Proxy(new L2(G.getSQL(),Y??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),X,!0),new B0({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...X){let Y=this;function Z(W){return new Z1({fields:W??void 0,session:void 0,dialect:Y.getDialect(),withList:X})}function _(W){return new Z1({fields:W??void 0,session:void 0,dialect:Y.getDialect(),distinct:!0})}function G(W,$){return new Z1({fields:$??void 0,session:void 0,dialect:Y.getDialect(),distinct:{on:W}})}return{select:Z,selectDistinct:_,selectDistinctOn:G}}select(X){return new Z1({fields:X??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(X){return new Z1({fields:X??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(X,Y){return new Z1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:X}})}getDialect(){if(!this.dialect)this.dialect=new u4(this.dialectConfig);return this.dialect}}function m1(X){if(M(X,b0))return[X[k4]?`${X[k4]}.${X[T.Symbol.BaseName]}`:X[T.Symbol.BaseName]];if(M(X,C0))return X._.usedTables??[];if(M(X,S))return X.usedTables??[];return[]}class WX extends Y1{constructor(X,Y,Z,_){super();this.session=Y,this.dialect=Z,this.config={table:X,withList:_}}static[E]="PgDelete";config;cacheConfig;where(X){return this.config.where=X,this}returning(X=this.config.table[T.Symbol.Columns]){return this.config.returningFields=X,this.config.returning=B1(X),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:X,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(X){return F0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,X,!0,void 0,{type:"delete",tables:m1(this.config.table)},this.cacheConfig)})}prepare(X){return this._prepare(X)}authToken;setToken(X){return this.authToken=X,this}execute=(X)=>{return F0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(X,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new B0({alias:g0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class $X{constructor(X,Y,Z,_,G){this.table=X,this.session=Y,this.dialect=Z,this.withList=_,this.overridingSystemValue_=G}static[E]="PgInsertBuilder";authToken;setToken(X){return this.authToken=X,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(X){if(X=Array.isArray(X)?X:[X],X.length===0)throw Error("values() must be called with at least one value");let Y=X.map((Z)=>{let _={},G=this.table[T.Symbol.Columns];for(let W of Object.keys(Z)){let $=Z[W];_[W]=M($,S)?$:new L1($,G[W])}return _});return new sZ(this.table,Y,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(X){let Y=typeof X==="function"?X(new x2):X;if(!M(Y,S)&&!w2(this.table[P6],Y._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new sZ(this.table,Y,this.session,this.dialect,this.withList,!0)}}class sZ extends Y1{constructor(X,Y,Z,_,G,W,$){super();this.session=Z,this.dialect=_,this.config={table:X,values:Y,withList:G,select:W,overridingSystemValue_:$}}static[E]="PgInsert";config;cacheConfig;returning(X=this.config.table[T.Symbol.Columns]){return this.config.returningFields=X,this.config.returning=B1(X),this}onConflictDoNothing(X={}){if(X.target===void 0)this.config.onConflict=V`do nothing`;else{let Y="";Y=Array.isArray(X.target)?X.target.map((_)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(_))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(X.target));let Z=X.where?V` where ${X.where}`:void 0;this.config.onConflict=V`(${V.raw(Y)})${Z} do nothing`}return this}onConflictDoUpdate(X){if(X.where&&(X.targetWhere||X.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let Y=X.where?V` where ${X.where}`:void 0,Z=X.targetWhere?V` where ${X.targetWhere}`:void 0,_=X.setWhere?V` where ${X.setWhere}`:void 0,G=this.dialect.buildUpdateSet(this.config.table,h6(this.config.table,X.set)),W="";return W=Array.isArray(X.target)?X.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(X.target)),this.config.onConflict=V`(${V.raw(W)})${Z} do update set ${G}${Y}${_}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:X,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(X){return F0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,X,!0,void 0,{type:"insert",tables:m1(this.config.table)},this.cacheConfig)})}prepare(X){return this._prepare(X)}authToken;setToken(X){return this.authToken=X,this}execute=(X)=>{return F0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(X,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new B0({alias:g0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class tZ extends Y1{constructor(X,Y,Z){super();this.session=Y,this.dialect=Z,this.config={view:X}}static[E]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:X,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(X){return F0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,X,!0)})}prepare(X){return this._prepare(X)}authToken;setToken(X){return this.authToken=X,this}execute=(X)=>{return F0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(X,this.authToken)})}}class HX{constructor(X,Y,Z,_){this.table=X,this.session=Y,this.dialect=Z,this.withList=_}static[E]="PgUpdateBuilder";authToken;setToken(X){return this.authToken=X,this}set(X){return new b$(this.table,h6(this.table,X),this.session,this.dialect,this.withList).setToken(this.authToken)}}class b$ extends Y1{constructor(X,Y,Z,_,G){super();this.session=Z,this.dialect=_,this.config={set:Y,table:X,withList:G,joins:[]},this.tableName=J4(X),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[E]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(X){let Y=X,Z=J4(Y);if(typeof Z==="string")this.joinsNotNullableMap[Z]=!0;return this.config.from=Y,this}getTableLikeFields(X){if(M(X,b0))return X[T.Symbol.Columns];else if(M(X,C0))return X._.selectedFields;return X[V0].selectedFields}createJoin(X){return(Y,Z)=>{let _=J4(Y);if(typeof _==="string"&&this.config.joins.some((G)=>G.alias===_))throw Error(`Alias "${_}" is already used in this query`);if(typeof Z==="function"){let G=this.config.from&&!M(this.config.from,S)?this.getTableLikeFields(this.config.from):void 0;Z=Z(new Proxy(this.config.table[T.Symbol.Columns],new B0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new B0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:Z,table:Y,joinType:X,alias:_}),typeof _==="string")switch(X){case"left":{this.joinsNotNullableMap[_]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!0;break}case"inner":{this.joinsNotNullableMap[_]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(X){return this.config.where=X,this}returning(X){if(!X){if(X=Object.assign({},this.config.table[T.Symbol.Columns]),this.config.from){let Y=J4(this.config.from);if(typeof Y==="string"&&this.config.from&&!M(this.config.from,S)){let Z=this.getTableLikeFields(this.config.from);X[Y]=Z}for(let Z of this.config.joins){let _=J4(Z.table);if(typeof _==="string"&&!M(Z.table,S)){let G=this.getTableLikeFields(Z.table);X[_]=G}}}}return this.config.returningFields=X,this.config.returning=B1(X),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:X,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(X){let Y=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,X,!0,void 0,{type:"insert",tables:m1(this.config.table)},this.cacheConfig);return Y.joinsNotNullableMap=this.joinsNotNullableMap,Y}prepare(X){return this._prepare(X)}authToken;setToken(X){return this.authToken=X,this}execute=(X)=>{return this._prepare().execute(X,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new B0({alias:g0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class f2 extends S{constructor(X){super(f2.buildEmbeddedCount(X.source,X.filters).queryChunks);this.params=X,this.mapWith(Number),this.session=X.session,this.sql=f2.buildCount(X.source,X.filters)}sql;token;static[E]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(X,Y){return V`(select count(*) from ${X}${V.raw(" where ").if(Y)}${Y})`}static buildCount(X,Y){return V`select count(*) as count from ${X}${V.raw(" where ").if(Y)}${Y};`}setToken(X){return this.token=X,this}then(X,Y){return Promise.resolve(this.session.count(this.sql,this.token)).then(X,Y)}catch(X){return this.then(void 0,X)}finally(X){return this.then((Y)=>{return X?.(),Y},(Y)=>{throw X?.(),Y})}}class eZ{constructor(X,Y,Z,_,G,W,$){this.fullSchema=X,this.schema=Y,this.tableNamesMap=Z,this.table=_,this.tableConfig=G,this.dialect=W,this.session=$}static[E]="PgRelationalQueryBuilder";findMany(X){return new aZ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?X:{},"many")}findFirst(X){return new aZ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?{...X,limit:1}:{limit:1},"first")}}class aZ extends Y1{constructor(X,Y,Z,_,G,W,$,H,Q){super();this.fullSchema=X,this.schema=Y,this.tableNamesMap=Z,this.table=_,this.tableConfig=G,this.dialect=W,this.session=$,this.config=H,this.mode=Q}static[E]="PgRelationalQuery";_prepare(X){return F0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Y,builtQuery:Z}=this._toSQL();return this.session.prepareQuery(Z,void 0,X,!0,(_,G)=>{let W=_.map(($)=>o6(this.schema,this.tableConfig,$,Y.selection,G));if(this.mode==="first")return W[0];return W})})}prepare(X){return this._prepare(X)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let X=this._getQuery(),Y=this.dialect.sqlToQuery(X.sql);return{query:X,builtQuery:Y}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(X){return this.authToken=X,this}execute(){return F0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class X5 extends Y1{constructor(X,Y,Z,_){super();this.execute=X,this.sql=Y,this.query=Z,this.mapBatchResult=_}static[E]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(X,Y){return Y?this.mapBatchResult(X):X}_prepare(){return this}isResponseInArrayMode(){return!1}}class h2{constructor(X,Y,Z){if(this.dialect=X,this.session=Y,this._=Z?{schema:Z.schema,fullSchema:Z.fullSchema,tableNamesMap:Z.tableNamesMap,session:Y}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:Y},this.query={},this._.schema)for(let[_,G]of Object.entries(this._.schema))this.query[_]=new eZ(Z.fullSchema,this._.schema,this._.tableNamesMap,Z.fullSchema[_],G,X,Y);this.$cache={invalidate:async(_)=>{}}}static[E]="PgDatabase";query;$with=(X,Y)=>{let Z=this;return{as:(G)=>{if(typeof G==="function")G=G(new x2(Z.dialect));return new Proxy(new L2(G.getSQL(),Y??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),X,!0),new B0({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(X,Y){return new f2({source:X,filters:Y,session:this.session})}$cache;with(...X){let Y=this;function Z(Q){return new Z1({fields:Q??void 0,session:Y.session,dialect:Y.dialect,withList:X})}function _(Q){return new Z1({fields:Q??void 0,session:Y.session,dialect:Y.dialect,withList:X,distinct:!0})}function G(Q,J){return new Z1({fields:J??void 0,session:Y.session,dialect:Y.dialect,withList:X,distinct:{on:Q}})}function W(Q){return new HX(Q,Y.session,Y.dialect,X)}function $(Q){return new $X(Q,Y.session,Y.dialect,X)}function H(Q){return new WX(Q,Y.session,Y.dialect,X)}return{select:Z,selectDistinct:_,selectDistinctOn:G,update:W,insert:$,delete:H}}select(X){return new Z1({fields:X??void 0,session:this.session,dialect:this.dialect})}selectDistinct(X){return new Z1({fields:X??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(X,Y){return new Z1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:{on:X}})}update(X){return new HX(X,this.session,this.dialect)}insert(X){return new $X(X,this.session,this.dialect)}delete(X){return new WX(X,this.session,this.dialect)}refreshMaterializedView(X){return new tZ(X,this.session,this.dialect)}authToken;execute(X){let Y=typeof X==="string"?V.raw(X):X.getSQL(),Z=this.dialect.sqlToQuery(Y),_=this.session.prepareQuery(Z,void 0,void 0,!1);return new X5(()=>_.execute(void 0,this.authToken),Y,Z,(G)=>_.mapResult(G,!0))}transaction(X,Y){return this.session.transaction(X,Y)}}class y${static[E]="Cache"}class k2 extends y${strategy(){return"all"}static[E]="NoopCache";async get(X){return}async put(X,Y,Z,_){}async onMutate(X){}}async function Y5(X,Y){let Z=`${X}-${JSON.stringify(Y)}`,G=new TextEncoder().encode(Z),W=await crypto.subtle.digest("SHA-256",G);return[...new Uint8Array(W)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}class Z5{constructor(X,Y,Z,_){if(this.query=X,this.cache=Y,this.queryMetadata=Z,this.cacheConfig=_,Y&&Y.strategy()==="all"&&_===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(X,Y){return X}setToken(X){return this.authToken=X,this}static[E]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(X,Y,Z){if(this.cache===void 0||M(this.cache,k2)||this.queryMetadata===void 0)try{return await Z()}catch(_){throw new H4(X,Y,_)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await Z()}catch(_){throw new H4(X,Y,_)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[_]=await Promise.all([Z(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return _}catch(_){throw new H4(X,Y,_)}if(!this.cacheConfig)try{return await Z()}catch(_){throw new H4(X,Y,_)}if(this.queryMetadata.type==="select"){let _=await this.cache.get(this.cacheConfig.tag??await Y5(X,Y),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(_===void 0){let G;try{G=await Z()}catch(W){throw new H4(X,Y,W)}return await this.cache.put(this.cacheConfig.tag??await Y5(X,Y),G,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),G}return _}try{return await Z()}catch(_){throw new H4(X,Y,_)}}}class _5{constructor(X){this.dialect=X}static[E]="PgSession";execute(X,Y){return F0.startActiveSpan("drizzle.operation",()=>{return F0.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(X),void 0,void 0,!1)}).setToken(Y).execute(void 0,Y)})}all(X){return this.prepareQuery(this.dialect.sqlToQuery(X),void 0,void 0,!1).all()}async count(X,Y){let Z=await this.execute(X,Y);return Number(Z[0].count)}}class G5 extends h2{constructor(X,Y,Z,_=0){super(X,Y,Z);this.schema=Z,this.nestedIndex=_}static[E]="PgTransaction";rollback(){throw new NZ}getTransactionConfigSQL(X){let Y=[];if(X.isolationLevel)Y.push(`isolation level ${X.isolationLevel}`);if(X.accessMode)Y.push(X.accessMode);if(typeof X.deferrable==="boolean")Y.push(X.deferrable?"deferrable":"not deferrable");return V.raw(Y.join(" "))}setTransaction(X){return this.session.execute(V`set transaction ${this.getTransactionConfigSQL(X)}`)}}class g$ extends Z5{constructor(X,Y,Z,_,G,W,$,H,Q,J){super({sql:Y,params:Z},G,W,$);this.client=X,this.queryString=Y,this.params=Z,this.logger=_,this.fields=H,this._isResponseInArrayMode=Q,this.customResultMapper=J}static[E]="PostgresJsPreparedQuery";async execute(X={}){return F0.startActiveSpan("drizzle.execute",async(Y)=>{let Z=RZ(this.params,X);Y?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(Z)}),this.logger.logQuery(this.queryString,Z);let{fields:_,queryString:G,client:W,joinsNotNullableMap:$,customResultMapper:H}=this;if(!_&&!H)return F0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(G,Z,async()=>{return await W.unsafe(G,Z)})});let Q=await F0.startActiveSpan("drizzle.driver.execute",()=>{return Y?.setAttributes({"drizzle.query.text":G,"drizzle.query.params":JSON.stringify(Z)}),this.queryWithCache(G,Z,async()=>{return await W.unsafe(G,Z).values()})});return F0.startActiveSpan("drizzle.mapResponse",()=>{return H?H(Q):Q.map((J)=>g7(_,J,$))})})}all(X={}){return F0.startActiveSpan("drizzle.execute",async(Y)=>{let Z=RZ(this.params,X);return Y?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(Z)}),this.logger.logQuery(this.queryString,Z),F0.startActiveSpan("drizzle.driver.execute",()=>{return Y?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(Z)}),this.queryWithCache(this.queryString,Z,async()=>{return this.client.unsafe(this.queryString,Z)})})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class b2 extends _5{constructor(X,Y,Z,_={}){super(Y);this.client=X,this.schema=Z,this.options=_,this.logger=_.logger??new KZ,this.cache=_.cache??new k2}static[E]="PostgresJsSession";logger;cache;prepareQuery(X,Y,Z,_,G,W,$){return new g$(this.client,X.sql,X.params,this.logger,this.cache,W,$,Y,_,G)}query(X,Y){return this.logger.logQuery(X,Y),this.client.unsafe(X,Y).values()}queryObjects(X,Y){return this.client.unsafe(X,Y)}transaction(X,Y){return this.client.begin(async(Z)=>{let _=new b2(Z,this.dialect,this.schema,this.options),G=new W5(this.dialect,_,this.schema);if(Y)await G.setTransaction(Y);return X(G)})}}class W5 extends G5{constructor(X,Y,Z,_=0){super(X,Y,Z,_);this.session=Y}static[E]="PostgresJsTransaction";transaction(X){return this.session.client.savepoint((Y)=>{let Z=new b2(Y,this.dialect,this.schema,this.session.options),_=new W5(this.dialect,Z,this.schema);return X(_)})}}class p$ extends h2{static[E]="PostgresJsDatabase"}function I8(X,Y={}){let Z=(Q)=>Q;for(let Q of["1184","1082","1083","1114","1182","1185","1115","1231"])X.options.parsers[Q]=Z,X.options.serializers[Q]=Z;X.options.serializers["114"]=Z,X.options.serializers["3802"]=Z;let _=new u4({casing:Y.casing}),G;if(Y.logger===!0)G=new IZ;else if(Y.logger!==!1)G=Y.logger;let W;if(Y.schema){let Q=F$(Y.schema,E$);W={fullSchema:Y.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let $=new b2(X,_,W,{logger:G,cache:Y.cache}),H=new p$(_,$,W);if(H.$client=X,H.$cache=Y.cache,H.$cache)H.$cache.invalidate=Y.cache?.onMutate;return H}function JX(...X){if(typeof X[0]==="string"){let Y=w8(X[0]);return I8(Y,X[1])}if(u7(X[0])){let{connection:Y,client:Z,..._}=X[0];if(Z)return I8(Z,_);if(typeof Y==="object"&&Y.url!==void 0){let{url:W,...$}=Y,H=w8(W,$);return I8(H,_)}let G=w8(Y);return I8(G,_)}return I8(X[0],X[1])}((X)=>{function Y(Z){return I8({options:{parsers:{},serializers:{}}},Z)}X.mock=Y})(JX||(JX={}));var H5={};lH(H5,{users:()=>d4,untrackedUserColumnNames:()=>xE,twoFactorMethod:()=>l$,trackedUserColumnName:()=>fE,trackableUserColumnNames:()=>d$,signInHistory:()=>kE,role:()=>u$,players:()=>$5,passwordResetAttempts:()=>bE,games:()=>zX,banishedIps:()=>yE,accountActions:()=>hE,accountAction:()=>c$});function T4(){return n0({length:24}).$type()}function m$(X){return V`lower(${X})`}var QX=V`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,u$=D2("role",["admin","user"]),d4=I4("users",{id:T1().primaryKey().defaultRandom(),username:n0({length:16}).notNull(),emailOffered:n0({length:254}).notNull(),emailVerified:n0({length:254}),password:n0({length:254}),createdAtIso:T4().notNull().default(QX),createdIp:n0({length:45}).notNull(),isActive:N2().notNull().default(!1),verifiedAtIso:T4(),userRole:u$().default("user")},(X)=>[oZ("usernameUniqueIndex").on(m$(X.username)),oZ("emailVerifiedUniqueIndex").on(m$(X.emailVerified))]),xE=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],d$=["username","emailOffered","emailVerified","password","userRole"],fE=D2("trackedUserColumnName",d$),c$=D2("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),hE=I4("accountActions",{userId:T1().references(()=>d4.id).primaryKey(),action:c$().notNull(),code:n0({length:254}).notNull(),wrongCodeCount:I2().notNull().default(0),expiresAtIso:T4().notNull()}),zX=I4("games",{id:T1().primaryKey().defaultRandom()}),$5=I4("players",{userId:T1().notNull().references(()=>d4.id,{onDelete:"cascade"}),gameId:T1().notNull().references(()=>zX.id,{onDelete:"cascade"}),score:I2().notNull()},(X)=>[gW({name:"players_userId_gameId_pk",columns:[X.userId,X.gameId]})]),kE=I4("signInHistory",{id:T1().primaryKey().defaultRandom(),userId:T1().references(()=>d4.id,{onDelete:"cascade"}),signInTimeIso:T4().notNull().default(QX),ipAddress:n0({length:45}).notNull(),userAgent:n0({length:1024}),successful:N2().notNull().default(!1)}),l$=D2("twoFactorMethod",["email","phone"]),bE=I4("passwordResetAttempts",{id:T1().primaryKey().defaultRandom(),userId:T1().notNull().references(()=>d4.id,{onDelete:"cascade"}),requestedIp:n0({length:45}).notNull(),requestedAtIso:T4().notNull().default(QX),succeededIp:n0({length:45}),succeededAtIso:T4(),verificationMethod:l$().notNull()}),yE=I4("banishedIps",{ip:n0({length:45}).primaryKey(),reason:n0({length:2048}).notNull(),banishedAtIso:T4().notNull().default(QX),banishedUntilIso:T4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class J5{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(gE.resolve(__dirname,"notify_update.sql"));let X=[g0(d4),g0(zX),g0($5)];await this.sql`SELECT create_notify_triggers(${this.sql.array(X)})`,await this.sql.listen("table_update",(Y)=>{let Z=Y.split(","),_=Z[0],G=Z[1],W=`${_}("${G}")`;if(this.observers.has(W))this.observers.get(W).next(W)})}constructor(X=!1,Y={host:g1.POSTGRES_HOST,port:g1.POSTGRES_PORT,user:g1.POSTGRES_USER,password:g1.POSTGRES_PASSWORD,database:g1.POSTGRES_DATABASE}){this.options=Y,this.sql=w8(Y),this.drizzle=JX(this.sql,{schema:H5,logger:X})}observe(X,Y){if(!this.observers.has(X))this.observers.set(X,new Z0);this.observers.get(X).subscribe("SINGLETON",Y)}}var FX={100:'"Continue"',101:'"Switching Protocols"',102:'"Processing"',103:'"Early Hints"',200:'"OK"',201:'"Created"',202:'"Accepted"',203:'"Non-Authoritative Information"',204:'"No Content"',205:'"Reset Content"',206:'"Partial Content"',207:'"Multi-Status"',208:'"Already Reported"',226:'"IM Used"',300:'"Multiple Choices"',301:'"Moved Permanently"',302:'"Found"',303:'"See Other"',304:'"Not Modified"',305:'"Use Proxy"',306:'"Switch Proxy"',307:'"Temporary Redirect"',308:'"Permanent Redirect"',400:'"Bad Request"',401:'"Unauthorized"',402:'"Payment Required"',403:'"Forbidden"',404:'"Not Found"',405:'"Method Not Allowed"',406:'"Not Acceptable"',407:'"Proxy Authentication Required"',408:'"Request Timeout"',409:'"Conflict"',410:'"Gone"',411:'"Length Required"',412:'"Precondition Failed"',413:'"Payload Too Large"',414:'"URI Too Long"',415:'"Unsupported Media Type"',416:'"Range Not Satisfiable"',417:'"Expectation Failed"',418:`"I'm a teapot"`,421:'"Misdirected Request"',422:'"Unprocessable Entity"',423:'"Locked"',424:'"Failed Dependency"',425:'"Too Early"',426:'"Upgrade Required"',428:'"Precondition Required"',429:'"Too Many Requests"',431:'"Request Header Fields Too Large"',451:'"Unavailable For Legal Reasons"',500:'"Internal Server Error"',501:'"Not Implemented"',502:'"Bad Gateway"',503:'"Service Unavailable"',504:'"Gateway Timeout"',505:'"HTTP Version Not Supported"',506:'"Variant Also Negotiates"',507:'"Insufficient Storage"',508:'"Loop Detected"',510:'"Not Extended"',511:'"Network Authentication Required"'};function pE(X){return Number.parseInt(X,10)}var mE=J1(FX),uE=mE.keyof().pipe((X)=>pE(X)),o$=J1([uE,"string"]);var z5=new V7(process),{logger:E1}=z5;Object.assign(console,E1,{log:E1.info});E1.info("ready");var Q5=n$(import.meta.dir,"..","app"),Uf=new J5({logQuery(X,Y){E1.info("\uD83D\uDCDD query",X,Y)}});oE({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...q6??void 0,async fetch(X){try{let Y=new Date,Z=new URL(X.url);if(E1.info(X.method,Z.pathname),Z.pathname==="/")return new Response(Bun.file(n$(Q5,"index.html")));if(Z.pathname==="/index.html")return Response.redirect("/");let _=cE(Q5,Z.pathname),G=lE(_);if(!G.startsWith(Q5))throw[403,"Access Denied"];if(!await i$(G).exists())return Response.redirect("/");return new Response(i$(G))}catch(Y){let Z=o$(Y);if(Z instanceof J1.errors===!1){let[_,G]=Z,$=`${FX[_]}. ${G}`;return E1.info(`\u274C ${_}: ${$}`),new Response($,{status:_})}if(Y instanceof Error)E1.error(Y.message);else{let _=C6(Y);E1.error("frontend server threw",_)}return new Response(FX[500],{status:500})}}});function UX(){E1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{E1.info("\u2757 received SIGINT; exiting gracefully"),UX()});process.on("SIGTERM",()=>{E1.info("\u2757 received SIGTERM; exiting gracefully"),UX()});process.on("exit",()=>{E1.info("\u2757 received exit; exiting gracefully"),UX()});z5.on("timeToStop",()=>{E1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),UX()});var{version:iE}=await Bun.file(dE.resolve(import.meta.dir,"../package.json")).json();E1.info(`\uD83D\uDEEB frontend v${iE} running at http://localhost:${g1.FRONTEND_PORT}/`);z5.emit("alive");
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");