tempest.games 0.2.59 → 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.
- package/CHANGELOG.md +15 -0
- package/app/assets/index-x5An0S0o.js +108 -0
- package/app/index.html +1 -1
- package/bin/backend.bun.js +186 -186
- package/bin/backend.worker.game.bun.js +16 -16
- package/bin/backend.worker.tribunal.bun.js +95 -95
- package/bin/frontend.bun.js +60 -60
- package/bin/setup-db.bun.js +52 -52
- package/package.json +17 -17
- package/app/assets/index-DMicbj1C.js +0 -108
package/bin/frontend.bun.js
CHANGED
|
@@ -1,80 +1,80 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
Message: ${
|
|
5
|
-
Source: (${
|
|
6
|
-
${
|
|
7
|
-
}`)}}};class v1{constructor(
|
|
8
|
-
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},
|
|
9
|
-
`+
|
|
10
|
-
${
|
|
11
|
-
${
|
|
12
|
-
${
|
|
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
|
+
Message: ${_}
|
|
5
|
+
Source: (${X.slice(0,-1)}) => {
|
|
6
|
+
${X.at(-1)}
|
|
7
|
+
}`)}}};class v1{constructor(X,...[Y]){return Object.assign(Object.setPrototypeOf(X.bind(Y?.bind??this),this.constructor.prototype),Y?.attach)}}var 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
|
+
`+_);return Y?`[
|
|
10
|
+
${_}${W}
|
|
11
|
+
${Z}]`:`[${W}]`}let G=X.constructor.name;if(G==="Object"){let W=q4(X).map(([$,H])=>{let Q=typeof $==="symbol"?n4.onSymbol($):V4($)?$:JSON.stringify($),J=m2(H,Y,_);return`${_}${Q}: ${J}`});if(W.length===0)return"{}";return Y?`{
|
|
12
|
+
${W.join(`,
|
|
13
13
|
`)}
|
|
14
|
-
${
|
|
15
|
-
`,this}const(Y
|
|
16
|
-
`).map((
|
|
17
|
-
`):this.body} }`}compile(){return new
|
|
18
|
-
`)}_add(
|
|
19
|
-
`+
|
|
20
|
-
`));Object.defineProperty(this,"arkErrors",{value:
|
|
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
|
+
`,this}const(X,Y){return this.line(`const ${X} = ${Y}`),this}let(X,Y){return this.line(`let ${X} = ${Y}`)}set(X,Y){return this.line(`${X} = ${Y}`)}if(X,Y){return this.block(`if (${X})`,Y)}elseIf(X,Y){return this.block(`else if (${X})`,Y)}else(X){return this.block("else",X)}for(X,Y,Z=0){return this.block(`for (let i = ${Z}; ${X}; i++)`,Y)}forIn(X,Y){return this.block(`for (const k in ${X})`,Y)}block(X,Y,Z=""){return this.line(`${X} {`),this.indent(),Y(this),this.dedent(),this.line(`}${Z}`)}return(X=""){return this.line(`return ${X}`)}write(X="anonymous",Y=0){return`${X}(${this.argNames.join(", ")}) { ${Y?this.body.split(`
|
|
16
|
+
`).map((Z)=>" ".repeat(Y)+`${Z}`).join(`
|
|
17
|
+
`):this.body} }`}compile(){return new 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 J1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Y,Z){this.root=Y,this.config=Z}get data(){let Y=this.root;for(let Z of this.path)Y=Y?.[Z];return Y}get propString(){return Y4(this.path)}reject(Y){return this.error(Y),!1}mustBe(Y){return this.error(Y),!1}error(Y){let Z=typeof Y==="object"?Y.code?Y:{...Y,code:"predicate"}:{code:"predicate",expected:Y};return this.errorFromContext(Z)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(Y){let Z={path:new y2(...this.path),morphs:Y};if(this.currentBranch)this.currentBranch.queuedMorphs.push(Z);else this.queuedMorphs.push(Z)}finalize(Y){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return Y?Y(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(Y){return this.errorFromContext(Y)}errorFromContext(Y){let Z=new L4(Y,this);if(this.currentBranch)this.currentBranch.error=Z;else this.errors.add(Z);return Z}applyQueuedMorphs(){while(this.queuedMorphs.length){let Y=this.queuedMorphs;this.queuedMorphs=[];for(let{path:Z,morphs:X}of Y){if(this.errors.affectsPath(Z))continue;this.applyMorphsAtPath(Z,X)}}}applyMorphsAtPath(Y,Z){let X=Y.at(-1),G;if(X!==void 0){G=this.root;for(let _=0;_<Y.length-1;_++)G=G[Y[_]]}for(let _ of Z){this.path=[...Y];let $=D0(_),W=_(G===void 0?this.root:G[X],this);if(W instanceof L4){this.errors.add(W);break}if(W instanceof J1){if(!$)this.errors.merge(W);break}if(G===void 0)this.root=W;else G[X]=W;this.applyQueuedMorphs()}}}var Q1=(Y,Z,X)=>{if(!X)return Z();X.path.push(Y);let G=Z();return X.path.pop(),G};class u2 extends v1{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Y,Z){super((G,_,$=this.onFail)=>{if(_)return this.traverseApply(G,_),_.hasError()?_.errors:_.data;return this.rootApply(G,$)},{attach:Y});this.attachments=Y,this.$=Z,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((G,_)=>PJ(G,_.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let G=0;G<this.children.length;G++){if(this.includesTransform||=this.children[G].includesTransform,this.includesContextualPredicate||=this.children[G].includesContextualPredicate,this.isCyclic||=this.children[G].isCyclic,!X){let _=this.children[G].flatRefs;for(let $=0;$<_.length;$++){let W=_[$];if(!this.flatRefs.some((H)=>$G(H,W))){this.flatRefs.push(W);for(let H of W.node.branches)if(H.hasKind("morph")||H.hasKind("intersection")&&H.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:W.path,propString:W.propString,node:H})}}}Object.assign(this.referencesById,this.children[G].referencesById)}this.flatRefs.sort((G,_)=>G.path.length>_.path.length?1:G.path.length<_.path.length?-1:G.propString>_.propString?1:G.propString<_.propString?-1:G.node.expression<_.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((G)=>G.length===1||G.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((G)=>G.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(G)=>this.traverseAllows(G,new x1(G,this.$.resolvedConfig)):(G)=>this.traverseAllows(G)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Z,X)=>{if(this.allows(Z))return Z;let G=new x1(Z,this.$.resolvedConfig);return this.traverseApply(Z,G),G.finalize(X)};case"contextual":return(Z,X)=>{let G=new x1(Z,this.$.resolvedConfig);return this.traverseApply(Z,G),G.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Y=this.$.resolvedConfig.clone;return(Z,X)=>{if(this.allows(Z))return this.contextFreeMorph(Y&&(typeof Z==="object"&&Z!==null||typeof Z==="function")?Y(Z):Z);let G=new x1(Z,this.$.resolvedConfig);return this.traverseApply(Z,G),G.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,G0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=jJ(this.metaJson);cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=e4(this.kind);precompilation;assert=(Y,Z)=>this(Y,Z,(X)=>X.throw());traverse(Y,Z){return this(Y,Z,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(Y){if(!this.includesTransform)return this;let Z={};for(let[X,G]of this.innerEntries){let _=this.impl.keys[X];if(_.reduceIo)_.reduceIo(Y,Z,G);else if(_.child){let $=G;Z[X]=U0($)?$.map((W)=>W[Y]):$[Y]}else Z[X]=G}return this.$.node(this.kind,Z)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Y){let Z=D0(Y)?Y:this.$.parseDefinition(Y);return this.innerHash===Z.innerHash}ifEquals(Y){return this.equals(Y)?this:void 0}hasKind(Y){return this.kind===Y}assertHasKind(Y){if(this.kind!==Y)C4(`${this.kind} node was not of asserted kind ${Y}`);return this}hasKindIn(...Y){return Y.includes(this.kind)}assertHasKindIn(...Y){if(!s1(Y,this.kind))C4(`${this.kind} node was not one of asserted kinds ${Y}`);return this}isBasis(){return s1(eX,this.kind)}isConstraint(){return s1(l8,this.kind)}isStructural(){return s1(s4,this.kind)}isRefinement(){return s1(PY,this.kind)}isRoot(){return s1(t4,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Y){return this.hasKind("unit")&&this.allows(Y)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Y){let Z=m2.normalize(Y);return this._select(Z)}_select(Y){let Z=m2.applyBoundary[Y.boundary??"references"](this);if(Y.kind)Z=Z.filter((X)=>X.kind===Y.kind);if(Y.where)Z=Z.filter(Y.where);return m2.applyMethod[Y.method??"filter"](Z,this,Y)}transform(Y,Z){return this._transform(Y,this._createTransformContext(Z))}_createTransformContext(Y){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Y?.prereduced??!1},undeclaredKeyHandling:void 0,...Y}}_transform(Y,Z){let X=Z.bindScope??this.$;if(Z.seen[this.id])return this.$.lazilyResolve(Z.seen[this.id]);if(Z.shouldTransform?.(this,Z)===!1)return this;let G;if(Z.seen[this.id]=()=>G,this.hasKind("structure")&&this.undeclared!==Z.undeclaredKeyHandling)Z={...Z,undeclaredKeyHandling:this.undeclared};let _=o(this.inner,(J,z)=>{if(!this.impl.keys[J].child)return[J,z];let F=z;if(!U0(F)){let L=F._transform(Y,Z);return L?[J,L]:[]}if(F.length===0)return[J,z];let O=F.flatMap((L)=>{return L._transform(Y,Z)??[]});return O.length?[J,O]:[]});delete Z.seen[this.id];let $=Object.assign(_,{meta:this.meta}),W=Z.selected&&!Z.selected.includes(this)?$:Y(this.kind,$,Z);if(W===null)return null;if(D0(W))return G=W;let H=Object.keys(W);if((H.length===0||H.length===1&&H[0]==="meta")&&!l1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in W))return Z.undeclaredKeyHandling?{...W,value:I.intrinsic.unknown}:null;if(this.kind==="morph")W.in??=I.intrinsic.unknown;return G=X.node(this.kind,W,Z.parseOptions)}configureReferences(Y,Z="references"){let X=m2.normalize(Z),G=typeof Y==="string"?(H,Q)=>({...Q,meta:{...Q.meta,description:Y}}):typeof Y==="function"?(H,Q)=>({...Q,meta:Y(Q.meta)}):(H,Q)=>({...Q,meta:{...Q.meta,...Y}});if(X.boundary==="self")return this.$.node(this.kind,G(this.kind,{...this.inner,meta:this.meta}));let _=this._select(X),$=_&&F4(_),W=X.boundary==="child"?(H,Q)=>Q.root.children.includes(H):X.boundary==="shallow"?(H)=>H.kind!=="structure":()=>!0;return this.$.finalize(this.transform(G,{shouldTransform:W,selected:$}))}}var m2={applyBoundary:{self:(Y)=>[Y],child:(Y)=>[...Y.children],shallow:(Y)=>[...Y.shallowReferences],references:(Y)=>[...Y.references]},applyMethod:{filter:(Y)=>Y,assertFilter:(Y,Z,X)=>{if(Y.length===0)C4(_G(Z,X));return Y},find:(Y)=>Y[0],assertFind:(Y,Z,X)=>{if(Y.length===0)C4(_G(Z,X));return Y[0]}},normalize:(Y)=>typeof Y==="function"?{boundary:"references",method:"filter",where:Y}:typeof Y==="string"?g0(Y,m2.applyBoundary)?{method:"filter",boundary:Y}:{boundary:"references",method:"filter",kind:Y}:{boundary:"references",method:"filter",...Y}},_G=(Y,Z)=>`${Y} had no references matching ${i(Z)}.`,CJ=(Y)=>Y4(Y,{stringifyNonKey:(Z)=>Z.expression}),qJ=/"(\$ark\.[^"]+)"/g,jJ=(Y)=>JSON.stringify(Y).replaceAll(qJ,"$1"),f1=(Y,Z)=>({path:Y,node:Z,propString:CJ(Y)}),$G=(Y,Z)=>Y.propString===Z.propString&&Y.node.equals(Z.node),xY=(Y,Z)=>c1(Y,Z,{isEqual:$G}),PJ=(Y,Z)=>c1(Y,Z,{isEqual:(X,G)=>X.equals(G)});class S extends Array{static init(Y,Z,X,G){return new S({kind:Y,l:Z,r:X,path:G?.path??[],optional:G?.optional??!1})}add(Y,Z,X,G){return this.push({kind:Y,l:Z,r:X,path:G?.path??[],optional:G?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Y,l:Z,r:X}=this[0],G=Y4(Y);return hY(`Intersection${G&&` at ${G}`} of ${WG(Z,X)}`)}return`The following intersections result in unsatisfiable types:
|
|
23
|
-
\u2022 ${this.map(({path:
|
|
24
|
-
\u2022 `)}`}throw(){return A(this.describeReasons())}invert(){let Y=this.map((Z)=>({...Z,l:Z.r,r:Z.l}));if(!(Y instanceof S))return new S(...Y);return Y}withPrefixKey(Y,Z){return this.map((X)=>({...X,path:[Y,...X.path],optional:X.optional||Z==="optional"}))}toNeverIfDisjoint(){return I.intrinsic.never}}var WG=(Y,Z)=>`${fY(Y)} and ${fY(Z)}`,fY=(Y)=>D0(Y)?Y.expression:U0(Y)?Y.map(fY).join(" | ")||"never":String(Y),hY=(Y)=>`${Y} results in an unsatisfiable type`;var Y2={},z1=(Y,Z,X)=>L0(Y,Z,{$:X,invert:!1,pipe:!1}),d2=(Y,Z,X)=>L0(Y,Z,{$:X,invert:!1,pipe:!0}),L0=(Y,Z,X)=>{let G=X.pipe?"|>":"&",_=`${Y.hash}${G}${Z.hash}`;if(Y2[_]!==void 0)return Y2[_];if(!X.pipe){let H=`${Z.hash}${G}${Y.hash}`;if(Y2[H]!==void 0){let Q=Y2[H],J=Q instanceof S?Q.invert():Q;return Y2[_]=J,J}}let $=!X.pipe||!Y.includesTransform&&!Z.includesTransform;if($&&Y.equals(Z))return Y;let W=$?kY(Y,Z,X):Y.hasKindIn(...t4)?SJ(Y,Z,X):kY(Y,Z,X);if(D0(W)){if(Y.equals(W))W=Y;else if(Z.equals(W))W=Z}return Y2[_]=W,W},kY=(Y,Z,X)=>{let G=Y.precedence<Z.precedence?Y.kind:Z.kind,_=Y.impl.intersections[Z.kind]??Z.impl.intersections[Y.kind];if(_===void 0)return null;else if(G===Y.kind)return _(Y,Z,X);else{let $=_(Z,Y,{...X,invert:!X.invert});if($ instanceof S)$=$.invert();return $}},SJ=(Y,Z,X)=>Y.includesTransform||Z.includesTransform?X.invert?HG(Z,Y,X):HG(Y,Z,X):kY(Y,Z,X),HG=(Y,Z,X)=>Y.distribute((G)=>vJ(G,Z,X),(G)=>{let _=G.filter(D0);if(_.length===0)return S.init("union",Y.branches,Z.branches);if(_.length<Y.branches.length||!Y.branches.every((H,Q)=>H.in.equals(_[Q].in)))return X.$.parseSchema(_);let $;if(_.length===1){let H=_[0];if(!$)return H;return X.$.node("morph",{...H.inner,in:H.in.configure($,"self")})}let W={branches:_};if($)W.meta=$;return X.$.parseSchema(W)}),vJ=(Y,Z,X)=>{if(Y.hasKind("morph")){let _=[...Y.morphs];if(Y.lastMorphIfNode){let $=L0(Y.lastMorphIfNode,Z,X);if($ instanceof S)return $;_[_.length-1]=$}else _.push(Z);return X.$.node("morph",{morphs:_,in:Y.inner.in})}if(Z.hasKind("morph")){let _=L0(Y,Z.in,X);if(_ instanceof S)return _;return X.$.node("morph",{morphs:[Z],in:_})}return X.$.node("morph",{morphs:[Z],in:Y})};class N1 extends u2{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,Y1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Y){return z1(this,Y,this.$)}}class X4 extends N1{traverseApply=(Y,Z)=>{if(!this.traverseAllows(Y,Z))Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.traversalKind==="Allows")Y.return(this.compiledCondition);else Y.if(this.compiledNegation,()=>Y.line(`${Y.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return D4(this.errorContext)}}var s0=(Y)=>(Z,X)=>{if(U0(Z)){if(Z.length===0)return;let _=Z.map(($)=>X.$.node(Y,$));if(Y==="predicate")return _;return _.sort(($,W)=>$.hash<W.hash?-1:1)}let G=X.$.node(Y,Z);return G.hasOpenIntersection()?[G]:G},Z2=(Y)=>{let Z=Y.r.shift();if(!Z){let G=Y.l.length===0&&Y.kind==="structure"?I.intrinsic.unknown.internal:Y.ctx.$.node(Y.kind,Object.assign(Y.baseInner,xJ(Y.l)),{prereduced:!0});for(let _ of Y.roots){if(G instanceof S)return G;G=L0(_,G,Y.ctx)}return G}let X=!1;for(let G=0;G<Y.l.length;G++){let _=L0(Y.l[G],Z,Y.ctx);if(_===null)continue;if(_ instanceof S)return _;if(!X){if(_.isRoot())return Y.roots.push(_),Y.l.splice(G),Z2(Y);Y.l[G]=_,X=!0}else if(!Y.l.includes(_))return G0(`Unexpectedly encountered multiple distinct intersection results for refinement ${_}`)}if(!X)Y.l.push(Z);if(Y.kind==="intersection"){if(Z.impliedSiblings)for(let G of Z.impliedSiblings)c1(Y.r,G)}return Z2(Y)},X2=(Y)=>{return Object.entries(Y).flatMap(([X,G])=>(X in o8)?G:[]).sort((X,G)=>X.precedence<G.precedence?-1:X.precedence>G.precedence?1:X.kind==="predicate"&&G.kind==="predicate"?0:X.hash<G.hash?-1:1)},xJ=(Y)=>{let Z={};for(let X of Y)if(X.hasOpenIntersection())Z[X.kind]=Z0(Z[X.kind],X);else{if(Z[X.kind])return G0(`Unexpected intersection of closed refinements of kind ${X.kind}`);Z[X.kind]=X}return Z},JG=(...Y)=>A(QG(...Y)),QG=(Y,Z,X)=>{let G=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Z).defaultShortDescription;return`${yX(Y)} operand must be ${Z.description} (was ${G})`};var zG=(Y,Z,X)=>new M4(Y,Z,X,X,null);class n8 extends v1{}class M4 extends v1{[Y1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Y,Z,X,G,_){super((...$)=>{let W=o(this.names,(H,Q)=>{let J=this.arg$.parse($[H]);if(!J.extends(this.constraints[H]))A(fJ(Q,this.constraints[H].expression,J.expression));return[Q,J]});if(this.defIsLazy()){let H=this.bodyDef(W);return this.$.parse(H)}return this.$.parse(Z,{args:W})});this.paramDefs=Y,this.bodyDef=Z,this.$=X,this.arg$=G,this.hkt=_,this.description=_?new _().description??`a generic type for ${_.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof n8}cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get json(){return this.cacheGetter("json",{params:this.params.map((Y)=>Y[1].isUnknown()?Y[0]:[Y[0],Y[1].json]),body:rX(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Y)=>typeof Y==="string"?[Y,I.intrinsic.unknown]:[Y[0],this.$.parse(Y[1])]))}get names(){return this.cacheGetter("names",this.params.map((Y)=>Y[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Y)=>Y[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var fJ=(Y,Z,X)=>`${Y} must be assignable to ${Z} (was ${X})`;var hJ=r({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Y)=>typeof Y==="function"?{predicate:Y}:Y,defaults:{description:(Y)=>`valid according to ${Y.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class UG extends N1{serializedPredicate=T0(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=D4(this.errorContext);traverseApply=(Y,Z)=>{if(!this.predicate(Y,Z.external)&&!Z.hasError())Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.traversalKind==="Allows"){Y.return(this.compiledCondition);return}Y.if(`${this.compiledNegation} && !ctx.hasError()`,()=>Y.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Y,Z){return Z.fallback.predicate({code:"predicate",base:Y,predicate:this.predicate})}}var bY={implementation:hJ,Node:UG};var kJ=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Y)=>Number.isInteger(Y)?Y:A(bJ(Y))}},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,hasAssociatedError:!0,defaults:{description:(Y)=>Y.rule===1?"an integer":Y.rule===2?"even":`a multiple of ${Y.rule}`},intersections:{divisor:(Y,Z,X)=>X.$.node("divisor",{rule:Math.abs(Y.rule*Z.rule/yJ(Y.rule,Z.rule))})},obviatesBasisDescription:!0});class FG extends X4{traverseAllows=(Y)=>Y%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=I.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Y){if(Y.type="integer",this.rule===1)return Y;return Y.multipleOf=this.rule,Y}}var yY={implementation:kJ,Node:FG};var bJ=(Y)=>`divisor must be an integer (was ${Y})`,yJ=(Y,Z)=>{let X,G=Y,_=Z;while(_!==0)X=_,_=G%_,G=X;return G};class M1 extends X4{boundOperandKind=uJ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=dJ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${gJ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?cJ(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Y){return(this.limitKind==="upper"?this.numericLimit<Y.numericLimit:this.numericLimit>Y.numericLimit)||this.numericLimit===Y.numericLimit&&this.exclusive===!0&&!Y.exclusive}overlapsRange(Y){if(this.isStricterThan(Y))return!1;if(this.numericLimit===Y.numericLimit&&(this.exclusive||Y.exclusive))return!1;return!0}overlapIsUnit(Y){return this.numericLimit===Y.numericLimit&&!this.exclusive&&!Y.exclusive}}var gJ={"<":">=","<=":">",">":"<=",">=":"<"},pJ={min:"max",minLength:"maxLength",after:"before"},r8={parse:(Y)=>Y||void 0},s8=(Y)=>(Z)=>{if(typeof Z==="number")return{rule:Z};let{exclusive:X,...G}=Z;return X?{...G,rule:Y==="minLength"?G.rule+1:G.rule-1}:G},t8=(Y)=>(Z)=>{if(typeof Z==="number"||typeof Z==="string"||Z instanceof Date)return{rule:Z};let{exclusive:X,...G}=Z;if(!X)return G;let _=typeof G.rule==="number"?G.rule:typeof G.rule==="string"?new Date(G.rule).valueOf():G.rule.valueOf();return X?{...G,rule:Y==="after"?_+1:_-1}:G},a8=(Y)=>typeof Y==="string"||typeof Y==="number"?new Date(Y):Y,mJ=(Y,Z)=>`${Y} bound must be a positive integer (was ${Z})`,G2=(Y)=>(Z)=>{if(!Number.isInteger(Z)||Z<0)A(mJ(Y,Z));return Z},uJ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},dJ=(Y,Z)=>`${g0(Y,pJ)?">":"<"}${Z?"":"="}`,cJ=(Y)=>typeof Y==="string"?Y:new Date(Y).toLocaleString(),EG=(Y)=>`Bounded expression ${Y} must be exactly one of number, string, Array, or Date`;var lJ=r({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a8,serialize:(Y)=>Y.toISOString()}},normalize:t8("after"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or later`,actual:S4},intersections:{after:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class VG extends M1{impliedBasis=I.intrinsic.Date.internal;collapsibleLimitString=S4(this.rule);traverseAllows=(Y)=>Y>=this.rule;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,after:this.rule})}}var gY={implementation:lJ,Node:VG};var oJ=r({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a8,serialize:(Y)=>Y.toISOString()}},normalize:t8("before"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or earlier`,actual:S4},intersections:{before:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,after:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("unit",{unit:Y.rule}):null:S.init("range",Y,Z)}});class OG extends M1{collapsibleLimitString=S4(this.rule);traverseAllows=(Y)=>Y<=this.rule;impliedBasis=I.intrinsic.Date.internal;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,before:this.rule})}}var pY={implementation:oJ,Node:OG};var iJ=r({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:G2("exactLength")}},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,hasAssociatedError:!0,defaults:{description:(Y)=>`exactly length ${Y.rule}`,actual:(Y)=>`${Y.length}`},intersections:{exactLength:(Y,Z,X)=>S.init("unit",X.$.node("unit",{unit:Y.rule}),X.$.node("unit",{unit:Z.rule}),{path:["length"]}),minLength:(Y,Z)=>Y.rule>=Z.rule?Y:S.init("range",Y,Z),maxLength:(Y,Z)=>Y.rule<=Z.rule?Y:S.init("range",Y,Z)}});class DG extends X4{traverseAllows=(Y)=>Y.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=I.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y.maxLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y.maxItems=this.rule,Y;default:return w0.throwInternalOperandError("exactLength",Y)}}}var mY={implementation:iJ,Node:DG};var nJ=r({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r8},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,defaults:{description:(Y)=>{if(Y.rule===0)return Y.exclusive?"negative":"non-positive";return`${Y.exclusive?"less than":"at most"} ${Y.rule}`}},intersections:{max:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,min:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("unit",{unit:Y.rule}):null:S.init("range",Y,Z)},obviatesBasisDescription:!0});class LG extends M1{impliedBasis=I.intrinsic.number.internal;traverseAllows=this.exclusive?(Y)=>Y<this.rule:(Y)=>Y<=this.rule;reduceJsonSchema(Y){if(this.exclusive)Y.exclusiveMaximum=this.rule;else Y.maximum=this.rule;return Y}}var uY={implementation:nJ,Node:LG};var rJ=r({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:G2("maxLength")}},reduce:(Y,Z)=>Y.rule===0?Z.node("exactLength",Y):void 0,normalize:s8("maxLength"),defaults:{description:(Y)=>`at most length ${Y.rule}`,actual:(Y)=>`${Y.length}`},intersections:{maxLength:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,minLength:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("exactLength",{rule:Y.rule}):null:S.init("range",Y,Z)}});class MG extends M1{impliedBasis=I.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length<=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.maxLength=this.rule,Y;case"array":return Y.maxItems=this.rule,Y;default:return w0.throwInternalOperandError("maxLength",Y)}}}var dY={implementation:rJ,Node:MG};var sJ=r({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r8},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,defaults:{description:(Y)=>{if(Y.rule===0)return Y.exclusive?"positive":"non-negative";return`${Y.exclusive?"more than":"at least"} ${Y.rule}`}},intersections:{min:(Y,Z)=>Y.isStricterThan(Z)?Y:Z},obviatesBasisDescription:!0});class AG extends M1{impliedBasis=I.intrinsic.number.internal;traverseAllows=this.exclusive?(Y)=>Y>this.rule:(Y)=>Y>=this.rule;reduceJsonSchema(Y){if(this.exclusive)Y.exclusiveMinimum=this.rule;else Y.minimum=this.rule;return Y}}var cY={implementation:sJ,Node:AG};var tJ=r({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:G2("minLength")}},reduce:(Y)=>Y.rule===0?I.intrinsic.unknown:void 0,normalize:s8("minLength"),defaults:{description:(Y)=>Y.rule===1?"non-empty":`at least length ${Y.rule}`,actual:(Y)=>Y.length===0?"":`${Y.length}`},intersections:{minLength:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class RG extends M1{impliedBasis=I.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length>=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y;default:return w0.throwInternalOperandError("minLength",Y)}}}var lY={implementation:tJ,Node:RG};var wG={min:cY.implementation,max:uY.implementation,minLength:lY.implementation,maxLength:dY.implementation,exactLength:mY.implementation,after:gY.implementation,before:pY.implementation},NG={min:cY.Node,max:uY.Node,minLength:lY.Node,maxLength:dY.Node,exactLength:mY.Node,after:gY.Node,before:pY.Node};var aJ=r({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Y)=>typeof Y==="string"?{rule:Y}:Y instanceof RegExp?Y.flags?{rule:Y.source,flags:Y.flags}:{rule:Y.source}:Y,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Y)=>`matched by ${Y.rule}`},intersections:{pattern:()=>null}});class IG extends X4{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=I.intrinsic.string.internal;reduceJsonSchema(Y,Z){if(Y.pattern)return Z.fallback.patternIntersection({code:"patternIntersection",base:Y,pattern:this.rule});return Y.pattern=this.rule,Y}}var oY={implementation:aJ,Node:IG};var c2=(Y,Z)=>{let X=eJ(Y);if(Z&&!Z.includes(X))return A(`Root of kind ${X} should be one of ${Z}`);return X},eJ=(Y)=>{if(y(Y,"root"))return Y.kind;if(typeof Y==="string")return Y[0]==="$"?"alias":(Y in H1)?"domain":"proto";if(typeof Y==="function")return"proto";if(typeof Y!=="object"||Y===null)return A(KG(Y));if("morphs"in Y)return"morph";if("branches"in Y||U0(Y))return"union";if("unit"in Y)return"unit";if("reference"in Y)return"alias";let Z=Object.keys(Y);if(Z.length===0||Z.some((X)=>(X in o8)))return"intersection";if("proto"in Y)return"proto";if("domain"in Y)return"domain";return A(KG(Y))},KG=(Y)=>`${i(Y)} is not a valid type schema`,BG={},YQ=(Y)=>U0(Y)?Y.map((Z)=>Z.collapsibleJson):Y.collapsibleJson,Z1={};I.nodesByRegisteredId=Z1;var iY=(Y)=>{return BG[Y]??=0,`${Y}${++BG[Y]}`},nY=(Y)=>{let Z=_2[Y.kind],X=Z.applyConfig?.(Y.def,Y.$.resolvedConfig)??Y.def,G={},{meta:_,...$}=X,W=_===void 0?{}:typeof _==="string"?{description:_}:_,H=LY($).sort(([J],[z])=>a4(J)?a4(z)?e4(J)-e4(z):1:a4(z)?-1:J<z?-1:1).filter(([J,z])=>{if(J.startsWith("meta.")){let F=J.slice(5);return W[F]=z,!1}return!0});for(let J of H){let z=J[0],F=Z.keys[z];if(!F)return A(`Key ${z} is not valid on ${Y.kind} schema`);let O=F.parse?F.parse(J[1],Y):J[1];if(O!==L1&&(O!==void 0||F.preserveUndefined))G[z]=O}if(Z.reduce&&!Y.prereduced){let J=Z.reduce(G,Y.$);if(J){if(J instanceof S)return J.throw();return ZQ(J,W)}}return rY({id:Y.id,kind:Y.kind,inner:G,meta:W,$:Y.$})},rY=({id:Y,kind:Z,inner:X,meta:G,$:_,ignoreCache:$})=>{let W=_2[Z],H=LY(X),Q=[],J={};for(let[x,h]of H){let g=W.keys[x],B=g.serialize??(g.child?YQ:w1);if(J[x]=B(h),g.child===!0){let K=h;if(U0(K))Q.push(...K);else Q.push(K)}else if(typeof g.child==="function")Q.push(...g.child(h))}if(W.finalizeInnerJson)J=W.finalizeInnerJson(J);let z={...J},F={};if(!l1(G))F=o(G,(x,h)=>[x,x==="examples"?h:w1(h)]),z.meta=e8(F,"description",!0);J=e8(J,W.collapsibleKey,!1);let O=JSON.stringify({kind:Z,...J});z=e8(z,W.collapsibleKey,!1);let L=e8(z,W.collapsibleKey,!0),w=JSON.stringify({kind:Z,...z});if(_.nodesByHash[w]&&!$)return _.nodesByHash[w];let R={id:Y,kind:Z,impl:W,inner:X,innerEntries:H,innerJson:J,innerHash:O,meta:G,metaJson:F,json:z,hash:w,collapsibleJson:L,children:Q};if(Z!=="intersection"){for(let x in X)if(x!=="in"&&x!=="out")R[x]=X[x]}let b=new CG[Z](R,_);return _.nodesByHash[w]=b},TG=(Y,Z)=>{if(Y.id===Z)return Y;if(D0(Z1[Z]))G0(`Unexpected attempt to overwrite node id ${Z}`);return rY({id:Z,kind:Y.kind,inner:Y.inner,meta:Y.meta,$:Y.$,ignoreCache:!0})},ZQ=(Y,Z,X)=>{if(X&&D0(Z1[X]))G0(`Unexpected attempt to overwrite node id ${X}`);return rY({id:X??iY(Z.alias??Y.kind),kind:Y.kind,inner:Y.inner,meta:Z,$:Y.$})},e8=(Y,Z,X)=>{let G=Object.keys(Y);if(G.length===1&&G[0]===Z){let _=Y[Z];if(X)return _;if(W1(_,"object")&&(Object.keys(_).length===1||Array.isArray(_)))return _}return Y};var l2=(Y,Z,X)=>{if(Y.key!==Z.key)return null;let G=Y.key,_=L0(Y.value,Z.value,X),$=Y.required||Z.required?"required":"optional";if(_ instanceof S)if($==="optional")_=I.intrinsic.never.internal;else return _.withPrefixKey(Y.key,Y.required&&Z.required?"required":"optional");if($==="required")return X.$.node("required",{key:G,value:_});let W=Y.hasDefault()?Z.hasDefault()?Y.default===Z.default?Y.default:A(sY(Y.default,Z.default)):Y.default:Z.hasDefault()?Z.default:L1;return X.$.node("optional",{key:G,value:_,default:W})};class o2 extends N1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=I.intrinsic.object.internal;serializedKey=Z4(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=Z0(this.value.flatRefs.map((Y)=>f1([this.key,...Y.path],Y.node)),f1([this.key],this.value));_transform(Y,Z){Z.path.push(this.key);let X=super._transform(Y,Z);return Z.path.pop(),X}hasDefault(){return"default"in this.inner}traverseAllows=(Y,Z)=>{if(this.key in Y)return Q1(this.key,()=>this.value.traverseAllows(Y[this.key],Z),Z);return this.optional};traverseApply=(Y,Z)=>{if(this.key in Y)Q1(this.key,()=>this.value.traverseApply(Y[this.key],Z),Z);else if(this.hasKind("required"))Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.if(`${this.serializedKey} in data`,()=>Y.traverseKey(this.serializedKey,`data${Y.prop(this.key)}`,this.value)),this.hasKind("required"))Y.else(()=>Y.traversalKind==="Apply"?Y.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Y.return(!1));if(Y.traversalKind==="Allows")Y.return(!0)}}var sY=(Y,Z)=>`Invalid intersection of default values ${i(Y)} & ${i(Z)}`;var XQ=r({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},default:{preserveUndefined:!0}},normalize:(Y)=>Y,reduce:(Y,Z)=>{if(Z.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Y.value.allows(void 0))return Z.node("optional",{...Y,value:Y.value.or(u.undefined)},{prereduced:!0})}},defaults:{description:(Y)=>`${Y.compiledKey}?: ${Y.value.description}`},intersections:{optional:l2}});class qG extends o2{constructor(...Y){super(...Y);if("default"in this.inner)n2(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:Y,...Z}=this.inner;return this.cacheGetter("outProp",this.$.node("required",Z,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${i(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=_Q(this);defaultValueMorphRef=this.defaultValueMorph&&T0(this.defaultValueMorph)}var i2={implementation:XQ,Node:qG},GQ={},_Q=(Y)=>{if(!Y.hasDefault())return;let Z=`{${Y.compiledKey}: ${Y.value.id} = ${w1(Y.default)}}`;return GQ[Z]??=tY(Y.key,Y.value,Y.default)},tY=(Y,Z,X)=>{if(typeof X==="function")return Z.includesTransform?(_,$)=>{return Q1(Y,()=>Z(_[Y]=X(),$),$),_}:(_)=>{return _[Y]=X(),_};let G=Z.includesTransform?Z.assert(X):X;return W1(G,"object")?(_,$)=>{return Q1(Y,()=>Z(_[Y]=X,$),$),_}:(_)=>{return _[Y]=G,_}},n2=(Y,Z,X)=>{let G=E4(Z);if(W1(Z,"object")&&!G)A($Q(X));let _=Y.in(G?Z():Z);if(_ instanceof J1){if(X===null)A(`Default ${_.summary}`);let $=_.transform((W)=>W.transform((H)=>({...H,prefixPath:[X]})));A(`Default for ${$.summary}`)}return Z},$Q=(Y)=>{return`Non-primitive default ${Y===null?"":typeof Y==="number"?`for value at [${Y}] `:`for ${Z4(Y)} `}must be specified as a function like () => ({my: 'object'})`};class I1 extends u2{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,Y1,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Y)=>{let Z=this(Y);if(Z instanceof J1)return Z;return{value:Z}},toJSONSchema:(Y)=>{if(Y.target&&Y.target!=="draft-2020-12")return A(`JSONSchema target '${Y.target}' is not supported (must be "draft-2020-12")`);if(Y.io==="input")return this.in.toJsonSchema();return this.out.toJsonSchema()}}}as(){return this}brand(Y){if(Y==="")return A(WQ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Y,Z){let X=this.branches.map(Y);return Z?.(X)??X}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Y={}){let Z=SY(this.$.resolvedConfig.toJsonSchema,Y);Z.useRefs||=this.isCyclic;let X=typeof Z.dialect==="string"?{$schema:Z.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse(Z)),Z.useRefs)X.$defs=o(this.references,(G,_)=>_.isRoot()&&!_.alwaysExpandJsonSchema?[_.id,_.toResolvedJsonSchema(Z)]:[]);return X}toJsonSchemaRecurse(Y){if(Y.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(Y)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Y){let Z=this.innerToJsonSchema(Y);return Object.assign(Z,this.metaJson)}intersect(Y){let Z=this.$.parseDefinition(Y),X=this.rawIntersect(Z);if(X instanceof S)return X;return this.$.finalize(X)}rawIntersect(Y){return z1(this,Y,this.$)}toNeverIfDisjoint(){return this}and(Y){let Z=this.intersect(Y);return Z instanceof S?Z.throw():Z}rawAnd(Y){let Z=this.rawIntersect(Y);return Z instanceof S?Z.throw():Z}or(Y){let Z=this.$.parseDefinition(Y);return this.$.finalize(this.rawOr(Z))}rawOr(Y){let Z=[...this.branches,...Y.branches];return this.$.node("union",Z)}map(Y){return this.$.schema(this.applyStructuralOperation("map",[Y]))}pick(...Y){return this.$.schema(this.applyStructuralOperation("pick",Y))}omit(...Y){return this.$.schema(this.applyStructuralOperation("omit",Y))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Y=this.applyStructuralOperation("keyof",[]).reduce((Z,X)=>Z.intersect(X).toNeverIfDisjoint(),I.intrinsic.unknown.internal);if(Y.branches.length===0)A(hY(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Y)}get props(){if(this.branches.length!==1)return A(HQ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(Z.distribute((X)=>this.applyStructuralOperation("merge",[jG(X)??A(PG("merge",X.expression))])))}applyStructuralOperation(Y,Z){return this.distribute((X)=>{if(X.equals(I.intrinsic.object)&&Y!=="merge")return X;let G=jG(X);if(!G)A(PG(Y,X.expression));if(Y==="keyof")return G.keyof();if(Y==="get")return G.get(...Z);if(Y==="props")return G.props;let _=Y==="required"?"require":Y==="partial"?"optionalize":Y;return this.$.node("intersection",{...X.inner,structure:G[_](...Z)})})}get(...Y){if(Y[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Y))}extract(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>X.extends(Z)))}exclude(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>!X.extends(Z)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Y){return!(this.intersect(Y)instanceof S)}extends(Y){let Z=this.intersect(Y);return!(Z instanceof S)&&this.equals(Z)}ifExtends(Y){return this.extends(Y)?this:void 0}subsumes(Y){return this.$.parseDefinition(Y).extends(this)}configure(Y,Z="shallow"){return this.configureReferences(Y,Z)}describe(Y,Z="shallow"){return this.configure({description:Y},Z)}optional(){return[this,"?"]}default(Y){return n2(this,Y,null),[this,"=",Y]}from(Y){return this.assert(Y)}_pipe(...Y){let Z=Y.reduce((X,G)=>X.rawPipeOnce(G),this);return this.$.finalize(Z)}tryPipe(...Y){let Z=Y.reduce((X,G)=>X.rawPipeOnce(y(G,"root")?G:(_,$)=>{try{return G(_,$)}catch(W){return $.error({code:"predicate",predicate:G,actual:`aborted due to error:
|
|
25
|
-
${
|
|
26
|
-
`})}}),this);return this.$.finalize(
|
|
27
|
-
${
|
|
28
|
-
Seen: [${
|
|
29
|
-
Resolution: ${
|
|
30
|
-
\u25E6 `)}`,problem:(
|
|
31
|
-
${
|
|
32
|
-
Left: ${
|
|
33
|
-
Right: ${
|
|
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
|
+
${$}
|
|
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
|
+
Seen: [${Z.join("->")}]
|
|
29
|
+
Resolution: ${c(Y)}`);return Y}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let X=this.reference.slice(1),Y=this.$.resolutions[X];if(typeof Y==="string")return Y;if(f(Y,"root"))return Y.id;return e(`Unexpected resolution for reference ${this.reference}: ${c(Y)}`)}get defaultShortDescription(){return G1.object}innerToJsonSchema(X){return this.resolution.toJsonSchemaRecurse(X)}traverseAllows=(X,Y)=>{let Z=Y.seen[this.reference];if(Z?.includes(X))return!0;return Y.seen[this.reference]=s(Z,X),this.resolution.traverseAllows(X,Y)};traverseApply=(X,Y)=>{let Z=Y.seen[this.reference];if(Z?.includes(X))return;Y.seen[this.reference]=s(Z,X),this.resolution.traverseApply(X,Y)};compile(X){let Y=this.resolutionId;X.if(`ctx.seen.${Y} && ctx.seen.${Y}.includes(data)`,()=>X.return(!0)),X.if(`!ctx.seen.${Y}`,()=>X.line(`ctx.seen.${Y} = []`)),X.line(`ctx.seen.${Y}.push(data)`),X.return(X.invoke(Y))}}var HQ=(X,Y)=>`Alias '${X}' has a shallow resolution cycle: ${[...Y,X].join("->")}`,r8={implementation:$Q,Node:f_};class v4 extends w1{traverseApply=(X,Y)=>{if(!this.traverseAllows(X,Y))Y.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return D4(this.errorContext)}compile(X){if(X.traversalKind==="Allows")X.return(this.compiledCondition);else X.if(this.compiledNegation,()=>X.line(`${X.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var JQ=l({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(X)=>typeof X==="string"?{domain:X}:i4(X,"numberAllowsNaN")&&X.domain!=="number"?w(e2.writeBadAllowNanMessage(X.domain)):X,applyConfig:(X,Y)=>X.numberAllowsNaN===void 0&&X.domain==="number"&&Y.numberAllowsNaN?{...X,numberAllowsNaN:!0}:X,defaults:{description:(X)=>G1[X.domain],actual:(X)=>Number.isNaN(X)?"NaN":G1[x0(X)]},intersections:{domain:(X,Y)=>X.domain==="number"&&Y.domain==="number"?X.numberAllowsNaN?Y:X:C.init("domain",X,Y)}});class h_ extends v4{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(X)=>typeof X==="number"&&!Number.isNaN(X):(X)=>x0(X)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return G1[this.domain]}innerToJsonSchema(X){if(this.domain==="bigint"||this.domain==="symbol")return X.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var e2={implementation:JQ,Node:h_,writeBadAllowNanMessage:(X)=>`numberAllowsNaN may only be specified with domain "number" (was ${X})`};var QQ=l({kind:"intersection",hasAssociatedError:!0,normalize:(X)=>{if(E0(X))return X;let{structure:Y,...Z}=X,_=!!Y,G=Y??{},W=d(Z,($,H)=>{if(f0($,Z_)){if(_)w(`Flattened structure key ${$} cannot be specified alongside a root 'structure' key.`);return G[$]=H,[]}return[$,H]});if(f(G,"constraint")||!l1(G))W.structure=G;return W},finalizeInnerJson:({structure:X,...Y})=>_1(X,"object")?{...X,...Y}:Y,keys:{domain:{child:!0,parse:(X,Y)=>Y.$.node("domain",X)},proto:{child:!0,parse:(X,Y)=>Y.$.node("proto",X)},structure:{child:!0,parse:(X,Y)=>Y.$.node("structure",X),serialize:(X)=>{if(!X.sequence?.minLength)return X.collapsibleJson;let{sequence:Y,...Z}=X.collapsibleJson,{minVariadicLength:_,...G}=Y,W=G.variadic&&Object.keys(G).length===1?G.variadic:G;return{...Z,sequence:W}}},divisor:{child:!0,parse:i0("divisor")},max:{child:!0,parse:i0("max")},min:{child:!0,parse:i0("min")},maxLength:{child:!0,parse:i0("maxLength")},minLength:{child:!0,parse:i0("minLength")},exactLength:{child:!0,parse:i0("exactLength")},before:{child:!0,parse:i0("before")},after:{child:!0,parse:i0("after")},pattern:{child:!0,parse:i0("pattern")},predicate:{child:!0,parse:i0("predicate")}},reduce:(X,Y)=>k_({},X,{$:Y,invert:!1,pipe:!1}),defaults:{description:(X)=>{if(X.children.length===0)return"unknown";if(X.structure)return X.structure.description;let Y=[];if(X.basis&&!X.refinements.some((Z)=>Z.impl.obviatesBasisDescription))Y.push(X.basis.description);if(X.refinements.length){let Z=X.refinements.toSorted((_,G)=>_.kind==="min"&&G.kind==="max"?-1:0).map((_)=>_.description);Y.push(...Z)}if(X.inner.predicate)Y.push(...X.inner.predicate.map((Z)=>Z.description));return Y.join(" and ")},expected:(X)=>` \u25E6 ${X.errors.map((Y)=>Y.expected).join(`
|
|
30
|
+
\u25E6 `)}`,problem:(X)=>`(${X.actual}) must be...
|
|
31
|
+
${X.expected}`},intersections:{intersection:(X,Y,Z)=>k_(X.inner,Y.inner,Z),...o1("intersection",(X,Y,Z)=>{if(X.children.length===0)return Y;let{domain:_,proto:G,...W}=X.inner,$=G??_,H=$?O0($,Y,Z):Y;return H instanceof C?H:X?.basis?.equals(H)?X:X.$.node("intersection",{...W,[H.kind]:H},{prereduced:!0})})}});class b_ extends w1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((X)=>X.isRefinement());structure=this.inner.structure;expression=zQ(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(X){return this.children.reduce((Y,Z)=>Z.isBasis()?Z.toJsonSchemaRecurse(X):Z.reduceJsonSchema(Y,X),{})}traverseAllows=(X,Y)=>this.children.every((Z)=>Z.traverseAllows(X,Y));traverseApply=(X,Y)=>{let Z=Y.currentErrorCount;if(this.basis){if(this.basis.traverseApply(X,Y),Y.currentErrorCount>Z)return}if(this.refinements.length){for(let _=0;_<this.refinements.length-1;_++)if(this.refinements[_].traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>Z)return;if(this.refinements.at(-1).traverseApply(X,Y),Y.currentErrorCount>Z)return}if(this.structure){if(this.structure.traverseApply(X,Y),Y.currentErrorCount>Z)return}if(this.inner.predicate){for(let _=0;_<this.inner.predicate.length-1;_++)if(this.inner.predicate[_].traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>Z)return;this.inner.predicate.at(-1).traverseApply(X,Y)}};compile(X){if(X.traversalKind==="Allows"){for(let Y of this.children)X.check(Y);X.return(!0);return}if(X.initializeErrorCount(),this.basis){if(X.check(this.basis),this.children.length>1)X.returnIfFail()}if(this.refinements.length){for(let Y=0;Y<this.refinements.length-1;Y++)X.check(this.refinements[Y]),X.returnIfFailFast();if(X.check(this.refinements.at(-1)),this.structure||this.inner.predicate)X.returnIfFail()}if(this.structure){if(X.check(this.structure),this.inner.predicate)X.returnIfFail()}if(this.inner.predicate){for(let Y=0;Y<this.inner.predicate.length-1;Y++)X.check(this.inner.predicate[Y]),X.returnIfFail();X.check(this.inner.predicate.at(-1))}}}var rX={implementation:QQ,Node:b_},zQ=(X)=>{let Y=X.structure?.expression||`${X.basis&&!X.refinements.some((Z)=>Z.impl.obviatesBasisExpression)?X.basis.nestableExpression+" ":""}${X.refinements.map((Z)=>Z.expression).join(" & ")}`||"unknown";if(Y==="Array == 0")Y="[]";return Y},k_=(X,Y,Z)=>{let _={},G=X.proto??X.domain,W=Y.proto??Y.domain,$=G?W?O0(G,W,Z):G:W;if($ instanceof C)return $;if($)_[$.kind]=$;return X8({kind:"intersection",baseInner:_,l:Y8(X),r:Y8(Y),roots:[],ctx:Z})};var FQ=l({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)},morphs:{parse:U4,serialize:(X)=>X.map((Y)=>f(Y,"root")?Y.json:N0(Y))},declaredIn:{child:!1,serialize:(X)=>X.json},declaredOut:{child:!1,serialize:(X)=>X.json}},normalize:(X)=>X,defaults:{description:(X)=>`a morph from ${X.in.description} to ${X.out?.description??"unknown"}`},intersections:{morph:(X,Y,Z)=>{if(!X.hasEqualMorphs(Y))return w(UQ(X.expression,Y.expression));let _=O0(X.in,Y.in,Z);if(_ instanceof C)return _;let G={morphs:X.morphs};if(X.declaredIn||Y.declaredIn){let W=O0(X.in,Y.in,Z);if(W instanceof C)return W.throw();else G.declaredIn=W}if(X.declaredOut||Y.declaredOut){let W=O0(X.out,Y.out,Z);if(W instanceof C)return W.throw();else G.declaredOut=W}return _.distribute((W)=>Z.$.node("morph",{...G,in:W}),Z.$.parseSchema)},...o1("morph",(X,Y,Z)=>{let _=X.inner.in?O0(X.inner.in,Y,Z):Y;return _ instanceof C?_:_.equals(X.inner.in)?X:Z.$.node("morph",{...X.inner,in:_})})}});class y_ extends w1{serializedMorphs=this.morphs.map(N0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=f(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??N.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??N.intrinsic.unknown.internal}declareIn(X){return this.$.node("morph",{...this.inner,declaredIn:X})}declareOut(X){return this.$.node("morph",{...this.inner,declaredOut:X})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(X){return X.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(X),out:this.introspectableOut?.toJsonSchemaRecurse(X)??null})}compile(X){if(X.traversalKind==="Allows"){if(!this.introspectableIn)return;X.return(X.invoke(this.introspectableIn));return}if(this.introspectableIn)X.line(X.invoke(this.introspectableIn));X.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(X,Y)=>!this.introspectableIn||this.introspectableIn.traverseAllows(X,Y);traverseApply=(X,Y)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(X,Y);Y.queueMorphs(this.morphs)};hasEqualMorphs(X){return t1(this.morphs,X.morphs,{isEqual:(Y,Z)=>Y===Z||f(Y,"root")&&f(Z,"root")&&Y.equals(Z)})}}var sX={implementation:FQ,Node:y_},UQ=(X,Y)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
32
|
+
Left: ${X}
|
|
33
|
+
Right: ${Y}`;var EQ=l({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(X)=>P8(X)??A1(X)},dateAllowsInvalid:{}},normalize:(X)=>{let Y=typeof X==="string"?{proto:j4[X]}:typeof X==="function"?E0(X)?X:{proto:X}:typeof X.proto==="string"?{...X,proto:j4[X.proto]}:X;if(typeof Y.proto!=="function")w(s8.writeInvalidSchemaMessage(Y.proto));if(i4(Y,"dateAllowsInvalid")&&Y.proto!==Date)w(s8.writeBadInvalidDateMessage(Y.proto));return Y},applyConfig:(X,Y)=>{if(X.dateAllowsInvalid===void 0&&X.proto===Date&&Y.dateAllowsInvalid)return{...X,dateAllowsInvalid:!0};return X},defaults:{description:(X)=>X.builtinName?x5[X.builtinName]:`an instance of ${X.proto.name}`,actual:(X)=>X instanceof Date&&X.toString()==="Invalid Date"?"an invalid Date":S8(X)},intersections:{proto:(X,Y)=>X.proto===Date&&Y.proto===Date?X.dateAllowsInvalid?Y:X:AX(X.proto,Y.proto)?X:AX(Y.proto,X.proto)?Y:C.init("proto",X,Y),domain:(X,Y)=>Y.domain==="object"?X:C.init("domain",N.intrinsic.object.internal,Y)}});class g_ extends v4{builtinName=P8(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(X)=>X instanceof Date&&X.toString()!=="Invalid Date":(X)=>X instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(X){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return X.fallback.date?.({code:"date",base:{}})??X.fallback.proto({code:"proto",base:{},proto:this.proto});default:return X.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var s8={implementation:EQ,Node:g_,writeBadInvalidDateMessage:(X)=>`dateAllowsInvalid may only be specified with constructor Date (was ${X.name})`,writeInvalidSchemaMessage:(X)=>`instanceOf operand must be a function (was ${x0(X)})`};var OQ=l({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(X,Y)=>{let Z=[];for(let _ of X){let G=f(_,"root")?_.branches:Y.$.parseSchema(_).branches;for(let W of G)if(W.hasKind("morph")){let $=Z.findIndex((H)=>H.hasKind("morph")&&H.hasEqualMorphs(W));if($===-1)Z.push(W);else{let H=Z[$];Z[$]=Y.$.node("morph",{...H.inner,in:H.in.rawOr(W.in)})}}else Z.push(W)}if(!Y.def.ordered)Z.sort((_,G)=>_.hash<G.hash?-1:1);return Z}}},normalize:(X)=>Q0(X)?{branches:X}:X,reduce:(X,Y)=>{let Z=KQ(X);if(Z.length===1)return Z[0];if(Z.length===X.branches.length)return;return Y.node("union",{...X,branches:Z},{prereduced:!0})},defaults:{description:(X)=>X.distribute((Y)=>Y.description,W8),expected:(X)=>{let Y=B5(X.errors,"propString"),Z=Object.entries(Y).map(([_,G])=>{let W=[];for(let Q of G)c1(W,Q.expected);let $=W8(W),H=G.every((Q)=>Q.actual===G[0].actual)?G[0].actual:c(G[0].data);return`${_&&`${_} `}must be ${$}${H&&` (was ${H})`}`});return W8(Z)},problem:(X)=>X.expected,message:(X)=>X.problem},intersections:{union:(X,Y,Z)=>{if(X.isNever!==Y.isNever)return C.init("presence",X,Y);let _;if(X.ordered){if(Y.ordered)w(TQ(X.expression,Y.expression));if(_=tX(Y.branches,X.branches,Z),_ instanceof C)_.invert()}else _=tX(X.branches,Y.branches,Z);if(_ instanceof C)return _;return Z.$.parseSchema(X.ordered||Y.ordered?{branches:_,ordered:!0}:{branches:_})},...o1("union",(X,Y,Z)=>{let _=tX(X.branches,[Y],Z);if(_ instanceof C)return _;if(_.length===1)return _[0];return Z.$.parseSchema(X.ordered?{branches:_,ordered:!0}:{branches:_})})}});class u_ extends w1{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let X=[],Y=-1;for(let Z of this.branches){if(Z.hasKind("unit")&&Z.domain==="boolean"){if(Y===-1)Y=X.length,X.push(Z);else X[Y]=N.intrinsic.boolean;continue}X.push(Z)}return X}unitBranches=this.branches.filter((X)=>X.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?wQ(this.discriminant):null;expression=this.distribute((X)=>X.nestableExpression,IQ);createBranchedOptimisticRootApply(){return(X,Y)=>{let Z=this.traverseOptimistic(X);if(Z!==O1)return Z;let _=new x1(X,this.$.resolvedConfig);return this.traverseApply(X,_),_.finalize(Y)}}get shallowMorphs(){return this.branches.reduce((X,Y)=>c1(X,Y.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((X)=>X.defaultShortDescription,W8)}innerToJsonSchema(X){if(this.branchGroups.length===1&&this.branchGroups[0].equals(N.intrinsic.boolean))return{type:"boolean"};let Y=this.branchGroups.map((Z)=>Z.toJsonSchemaRecurse(X));if(Y.every((Z)=>Object.keys(Z).length===1&&i4(Z,"const")))return{enum:Y.map((Z)=>Z.const)};return{anyOf:Y}}traverseAllows=(X,Y)=>this.branches.some((Z)=>Z.traverseAllows(X,Y));traverseApply=(X,Y)=>{let Z=[];for(let _=0;_<this.branches.length;_++){if(Y.pushBranch(),this.branches[_].traverseApply(X,Y),!Y.hasError()){if(this.branches[_].includesTransform)return Y.queuedMorphs.push(...Y.popBranch().queuedMorphs);return Y.popBranch()}Z.push(Y.popBranch().error)}Y.errorFromNodeContext({code:"union",errors:Z,meta:this.meta})};traverseOptimistic=(X)=>{for(let Y=0;Y<this.branches.length;Y++){let Z=this.branches[Y];if(Z.traverseAllows(X)){if(Z.contextFreeMorph)return Z.contextFreeMorph(X);return X}}return O1};compile(X){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(X);let Y=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")Y=`typeof ${Y} === "object" ? ${Y} === null ? "null" : "object" : typeof ${Y} === "function" ? "object" : typeof ${Y}`;let Z=this.discriminant.cases,_=Object.keys(Z),{optimistic:G}=X;if(X.optimistic=!1,X.block(`switch(${Y})`,()=>{for(let J in Z){let z=Z[J],F=J==="default"?J:`case ${J}`;X.line(`${F}: return ${z===!0?G?X.data:z:G?`${X.invoke(z)} ? ${z.contextFreeMorph?`${N0(z.contextFreeMorph)}(${X.data})`:X.data} : "${O1}"`:X.invoke(z)}`)}return X}),X.traversalKind==="Allows"){X.return(G?`"${O1}"`:!1);return}let W=W8(this.discriminant.kind==="domain"?_.map((J)=>{let z=J.slice(1,-1);return z==="function"?G1.object:G1[z]}):_),$=this.discriminant.path.map((J)=>typeof J==="symbol"?N0(J):JSON.stringify(J)),H=JSON.stringify(W),Q=this.discriminant.kind==="domain"?`${AQ}[${Y}]`:`${RQ}(${Y})`;X.line(`ctx.errorFromNodeContext({
|
|
34
34
|
code: "predicate",
|
|
35
35
|
expected: ${H},
|
|
36
36
|
actual: ${Q},
|
|
37
|
-
relativePath: [${
|
|
37
|
+
relativePath: [${$}],
|
|
38
38
|
meta: ${this.compiledMeta}
|
|
39
|
-
})`)}compileIndiscriminable(
|
|
40
|
-
Left: ${
|
|
41
|
-
Right: ${
|
|
42
|
-
Left: ${
|
|
43
|
-
Right: ${Z}`;var PQ=r({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Y)=>Y instanceof Date?Y.toISOString():w1(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>i(Y.unit),problem:({expected:Y,actual:Z})=>`${Y===Z?`must be reference equal to ${Y} (serialized to the same value)`:`must be ${Y} (was ${Z})`}`},intersections:{unit:(Y,Z)=>S.init("unit",Y,Z),...o1("unit",(Y,Z)=>{if(Z.allows(Y.unit))return Y;let X=Z.hasKind("intersection")?Z.basis:Z;if(X){let G=X.hasKind("domain")?X:I.intrinsic.object;if(Y.domain!==G.domain){let _=Y.domain==="undefined"||Y.domain==="null"||Y.domain==="boolean"?Y.domain:I.intrinsic[Y.domain];return S.init("domain",_,G)}}return S.init("assignability",Y,Z.hasKind("intersection")?Z.children.find((G)=>!G.allows(Y.unit)):Z)})}});class dG extends v4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=uG(this.unit,this.serializedValue);compiledNegation=uG(this.unit,this.serializedValue,"negated");expression=i(this.unit);domain=y0(this.unit);get defaultShortDescription(){return this.domain==="object"?H1.object:this.description}innerToJsonSchema(Y){return this.unit===null?{type:"null"}:I.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Y.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Y)=>Y instanceof Date&&Y.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Y)=>Number.isNaN(Y):(Y)=>Y===this.unit}var XZ={implementation:PQ,Node:dG},uG=(Y,Z,X)=>{if(Y instanceof Date){let G=`data instanceof Date && data.toISOString() === ${Z}`;return X?`!(${G})`:G}if(Number.isNaN(Y))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${Z}`};var SQ=r({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Y,Z)=>{let X=Z.$.parseSchema(Y);if(!X.extends(I.intrinsic.key))return A(xQ(X.expression));let G=X.branches.filter((_)=>_.hasKind("unit"));if(G.length)return A(vQ(G.map((_)=>i(_.unit))));return X}},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>`[${Y.signature.expression}]: ${Y.value.description}`},intersections:{index:(Y,Z,X)=>{if(Y.signature.equals(Z.signature)){let G=L0(Y.value,Z.value,X),_=G instanceof S?I.intrinsic.never.internal:G;return X.$.node("index",{signature:Y.signature,value:_})}if(Y.signature.extends(Z.signature)&&Y.value.subsumes(Z.value))return Z;if(Z.signature.extends(Y.signature)&&Z.value.subsumes(Y.value))return Y;return null}}});class cG extends N1{impliedBasis=I.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=Z0(this.value.flatRefs.map((Y)=>f1([this.signature,...Y.path],Y.node)),f1([this.signature],this.value));traverseAllows=(Y,Z)=>q4(Y).every((X)=>{if(this.signature.traverseAllows(X[0],Z))return Q1(X[0],()=>this.value.traverseAllows(X[1],Z),Z);return!0});traverseApply=(Y,Z)=>{for(let X of q4(Y))if(this.signature.traverseAllows(X[0],Z))Q1(X[0],()=>this.value.traverseApply(X[1],Z),Z)};_transform(Y,Z){Z.path.push(this.signature);let X=super._transform(Y,Z);return Z.path.pop(),X}compile(){}}var GZ={implementation:SQ,Node:cG},vQ=(Y)=>`Index keys ${Y.join(", ")} should be specified as named props.`,xQ=(Y)=>`Indexed key definition '${Y}' must be a string or symbol`;var fQ=r({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>`${Y.compiledKey}: ${Y.value.description}`,expected:(Y)=>Y.missingValueDescription,actual:()=>"missing"},intersections:{required:l2,optional:l2}});class lG extends o2{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=D4(this.errorContext)}var _Z={implementation:fQ,Node:lG};var hQ=r({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},optionals:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},defaultables:{child:(Y)=>Y.map((Z)=>Z[0]),parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>{let G=Z.$.parseSchema(X[0]);return n2(G,X[1],null),[G,X[1]]})},serialize:(Y)=>Y.map((Z)=>[Z[0].collapsibleJson,w1(Z[1])])},variadic:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y,Z)},minVariadicLength:{parse:(Y)=>Y===0?void 0:Y},postfix:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}}},normalize:(Y)=>{if(typeof Y==="string")return{variadic:Y};if("variadic"in Y||"prefix"in Y||"defaultables"in Y||"optionals"in Y||"postfix"in Y||"minVariadicLength"in Y){if(Y.postfix?.length){if(!Y.variadic)return A(gQ);if(Y.optionals?.length||Y.defaultables?.length)return A(WZ)}if(Y.minVariadicLength&&!Y.variadic)return A("minVariadicLength may not be specified without a variadic element");return Y}return{variadic:Y}},reduce:(Y,Z)=>{let X=Y.minVariadicLength??0,G=Y.prefix?.slice()??[],_=Y.defaultables?.slice()??[],$=Y.optionals?.slice()??[],W=Y.postfix?.slice()??[];if(Y.variadic){while($.at(-1)?.equals(Y.variadic))$.pop();if($.length===0&&_.length===0)while(G.at(-1)?.equals(Y.variadic))G.pop(),X++;while(W[0]?.equals(Y.variadic))W.shift(),X++}else if($.length===0&&_.length===0)G.push(...W.splice(0));if(X!==Y.minVariadicLength||Y.prefix&&Y.prefix.length!==G.length)return Z.node("sequence",{...Y,prefix:G,defaultables:_,optionals:$,postfix:W,minVariadicLength:X},{prereduced:!0})},defaults:{description:(Y)=>{if(Y.isVariadicOnly)return`${Y.variadic.nestableExpression}[]`;return`[${Y.tuple.map((X)=>X.kind==="defaultables"?`${X.node.nestableExpression} = ${i(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(Y,Z,X)=>{let G=a2({l:Y.tuple,r:Z.tuple,disjoint:new S,result:[],fixedVariants:[],ctx:X}),_=G.disjoint.length===0?[G,...G.fixedVariants]:G.fixedVariants;return _.length===0?G.disjoint:_.length===1?X.$.node("sequence",oG(_[0].result)):X.$.node("union",_.map(($)=>({proto:Array,sequence:oG($.result)})))}}});class iG extends N1{impliedBasis=I.intrinsic.Array.internal;tuple=yQ(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((Y)=>{if(Y.kind==="defaultables"||Y.kind==="optionals")return this.defaultablesAndOptionals.push(Y.node),!0;return Y.kind==="prefix"});variadicOrPostfix=t1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return xY(this.flatRefs,this.prevariadic.flatMap((Y,Z)=>Z0(Y.node.flatRefs.map((X)=>f1([`${Z}`,...X.path],X.node)),f1([`${Z}`],Y.node)))),xY(this.flatRefs,this.variadicOrPostfix.flatMap((Y)=>Z0(Y.flatRefs.map((Z)=>f1([I.intrinsic.nonNegativeIntegerString.internal,...Z.path],Z.node)),f1([I.intrinsic.nonNegativeIntegerString.internal],Y)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=bQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?T0(this.defaultValueMorphs):void 0;elementAtIndex(Y,Z){if(Z<this.prevariadic.length)return this.tuple[Z];let X=Y.length-this.postfixLength;if(Z>=X)return{kind:"postfix",node:this.postfix[Z-X]};return{kind:"variadic",node:this.variadic??G0(`Unexpected attempt to access index ${Z} on ${this}`)}}traverseAllows=(Y,Z)=>{for(let X=0;X<Y.length;X++)if(!this.elementAtIndex(Y,X).node.traverseAllows(Y[X],Z))return!1;return!0};traverseApply=(Y,Z)=>{let X=0;for(;X<Y.length;X++)Q1(X,()=>this.elementAtIndex(Y,X).node.traverseApply(Y[X],Z),Z)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Y){if(this.prefix)for(let[Z,X]of this.prefix.entries())Y.traverseKey(`${Z}`,`data[${Z}]`,X);for(let[Z,X]of this.defaultablesAndOptionals.entries()){let G=`${Z+this.prefixLength}`;Y.if(`${G} >= ${Y.data}.length`,()=>Y.traversalKind==="Allows"?Y.return(!0):Y.return()),Y.traverseKey(G,`data[${G}]`,X)}if(this.variadic){if(this.postfix)Y.const("firstPostfixIndex",`${Y.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Y.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Y.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Z,X]of this.postfix.entries()){let G=`firstPostfixIndex + ${Z}`;Y.traverseKey(G,`data[${G}]`,X)}}if(Y.traversalKind==="Allows")Y.return(!0)}_transform(Y,Z){Z.path.push(I.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(Y,Z);return Z.path.pop(),X}expression=this.description;reduceJsonSchema(Y,Z){if(this.prevariadic.length)Y.prefixItems=this.prevariadic.map((X)=>{let G=X.node.toJsonSchemaRecurse(Z);if(X.kind==="defaultables"){let _=typeof X.default==="function"?X.default():X.default;G.default=I.intrinsic.jsonData.allows(_)?_:Z.fallback.defaultValue({code:"defaultValue",base:G,value:_})}return G});if(this.minLength)Y.minItems=this.minLength;if(this.variadic){let X=Object.assign(Y,{items:this.variadic.toJsonSchemaRecurse(Z)});if(this.maxLength)X.maxItems=this.maxLength;if(this.postfix){let G=this.postfix.map((_)=>_.toJsonSchemaRecurse(Z));Y=Z.fallback.arrayPostfix({code:"arrayPostfix",base:X,elements:G})}}else Y.items=!1,delete Y.maxItems;return Y}}var kQ={},bQ=(Y)=>{if(!Y.defaultables)return[];let Z=[],X="[",G=Y.prefixLength+Y.defaultablesLength-1;for(let _=Y.prefixLength;_<=G;_++){let[$,W]=Y.defaultables[_-Y.prefixLength];Z.push(tY(_,$,W)),X+=`${_}: ${$.id} = ${w1(W)}, `}return X+="]",kQ[X]??=Z},$Z={implementation:hQ,Node:iG},yQ=(Y)=>{let Z=[];if(Y.prefix)for(let X of Y.prefix)Z.push({kind:"prefix",node:X});if(Y.defaultables)for(let[X,G]of Y.defaultables)Z.push({kind:"defaultables",node:X,default:G});if(Y.optionals)for(let X of Y.optionals)Z.push({kind:"optionals",node:X});if(Y.variadic)Z.push({kind:"variadic",node:Y.variadic});if(Y.postfix)for(let X of Y.postfix)Z.push({kind:"postfix",node:X});return Z},oG=(Y)=>Y.reduce((Z,X)=>{if(X.kind==="variadic")Z.variadic=X.node;else if(X.kind==="defaultables")Z.defaultables=Z0(Z.defaultables,[[X.node,X.default]]);else Z[X.kind]=Z0(Z[X.kind],X.node);return Z},{}),WZ="A postfix required element cannot follow an optional or defaultable element",gQ="A postfix element requires a variadic element",a2=(Y)=>{let[Z,...X]=Y.l,[G,..._]=Y.r;if(!Z||!G)return Y;let $=X.at(-1)?.kind==="postfix",W=_.at(-1)?.kind==="postfix",H=Z.kind==="prefix"||G.kind==="prefix"?"prefix":Z.kind==="postfix"||G.kind==="postfix"?"postfix":Z.kind==="variadic"&&G.kind==="variadic"?"variadic":$||W?"prefix":Z.kind==="defaultables"||G.kind==="defaultables"?"defaultables":"optionals";if(Z.kind==="prefix"&&G.kind==="variadic"&&W){let F=a2({...Y,fixedVariants:[],r:_.map((O)=>({...O,kind:"prefix"}))});if(F.disjoint.length===0)Y.fixedVariants.push(F)}else if(G.kind==="prefix"&&Z.kind==="variadic"&&$){let F=a2({...Y,fixedVariants:[],l:X.map((O)=>({...O,kind:"prefix"}))});if(F.disjoint.length===0)Y.fixedVariants.push(F)}let Q=L0(Z.node,G.node,Y.ctx);if(Q instanceof S)if(H==="prefix"||H==="postfix")Y.disjoint.push(...Q.withPrefixKey(H==="prefix"?Y.result.length:`-${X.length+1}`,"required")),Y.result=[...Y.result,{kind:H,node:I.intrinsic.never.internal}];else if(H==="optionals"||H==="defaultables")return Y;else return a2({...Y,fixedVariants:[],l:X.map((F)=>({...F,kind:"prefix"})),r:X.map((F)=>({...F,kind:"prefix"}))});else if(H==="defaultables"){if(Z.kind==="defaultables"&&G.kind==="defaultables"&&Z.default!==G.default)A(sY(Z.default,G.default));Y.result=[...Y.result,{kind:H,node:Q,default:Z.kind==="defaultables"?Z.default:G.kind==="defaultables"?G.default:G0(`Unexpected defaultable intersection from ${Z.kind} and ${G.kind} elements.`)}]}else Y.result=[...Y.result,{kind:H,node:Q}];let J=Y.l.length,z=Y.r.length;if(Z.kind!=="variadic"||J>=z&&(G.kind==="variadic"||z===1))Y.l=X;if(G.kind!=="variadic"||z>=J&&(Z.kind==="variadic"||J===1))Y.r=_;return a2(Y)};var sG=(Y)=>(Z)=>{if(Z.props.length||Z.index){let X=Z.index?.map((_)=>_[Y])??[];for(let _ of Z.props)X.push(_[Y]);if(Z.undeclared)X.push(`+ (undeclared): ${Z.undeclared}`);let G=`{ ${X.join(", ")} }`;return Z.sequence?`${G} & ${Z.sequence.description}`:G}return Z.sequence?.description??"{}"},pQ=sG("description"),mQ=sG("expression"),nG=(Y,Z,X)=>{let G=Y.required?"required":"optional";if(!Z.signature.allows(Y.key))return null;let _=z1(Y.value,Z.value,X);if(_ instanceof S)return G==="optional"?X.node("optional",{key:Y.key,value:I.intrinsic.never.internal}):_.withPrefixKey(Y.key,Y.kind);return null},uQ=r({kind:"structure",hasAssociatedError:!1,normalize:(Y)=>Y,applyConfig:(Y,Z)=>{if(!Y.undeclared&&Z.onUndeclaredKey!=="ignore")return{...Y,undeclared:Z.onUndeclaredKey};return Y},keys:{required:{child:!0,parse:s0("required"),reduceIo:(Y,Z,X)=>{Z.required=Z0(Z.required,X.map((G)=>G[Y]));return}},optional:{child:!0,parse:s0("optional"),reduceIo:(Y,Z,X)=>{if(Y==="in"){Z.optional=X.map((G)=>G.in);return}for(let G of X)Z[G.outProp.kind]=Z0(Z[G.outProp.kind],G.outProp.out)}},index:{child:!0,parse:s0("index")},sequence:{child:!0,parse:s0("sequence")},undeclared:{parse:(Y)=>Y==="ignore"?void 0:Y,reduceIo:(Y,Z,X)=>{if(X!=="delete")return;if(Y==="in")delete Z.undeclared;else Z.undeclared="reject"}}},defaults:{description:pQ},intersections:{structure:(Y,Z,X)=>{let G={...Y.inner},_={...Z.inner},$=new S;if(Y.undeclared){let Q=Y.keyof();for(let J of Z.requiredKeys)if(!Q.allows(J))$.add("presence",I.intrinsic.never.internal,Z.propsByKey[J].value,{path:[J]});if(_.optional)_.optional=_.optional.filter((J)=>Q.allows(J.key));if(_.index)_.index=_.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let z=z1(Q,J.signature,X.$);if(z instanceof S)return[];let F=Z6(z,J.value,X.$);if(F.required)_.required=t1(_.required,F.required);if(F.optional)_.optional=t1(_.optional,F.optional);return F.index??[]})}if(Z.undeclared){let Q=Z.keyof();for(let J of Y.requiredKeys)if(!Q.allows(J))$.add("presence",Y.propsByKey[J].value,I.intrinsic.never.internal,{path:[J]});if(G.optional)G.optional=G.optional.filter((J)=>Q.allows(J.key));if(G.index)G.index=G.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let z=z1(Q,J.signature,X.$);if(z instanceof S)return[];let F=Z6(z,J.value,X.$);if(F.required)G.required=t1(G.required,F.required);if(F.optional)G.optional=t1(G.optional,F.optional);return F.index??[]})}let W={};if(Y.undeclared||Z.undeclared)W.undeclared=Y.undeclared==="reject"||Z.undeclared==="reject"?"reject":"delete";let H=Z2({kind:"structure",baseInner:W,l:X2(G),r:X2(_),roots:[],ctx:X});if(H instanceof S)$.push(...H);if($.length)return $;return H}},reduce:(Y,Z)=>{if(Y.index){if(!(Y.required||Y.optional))return;let X=!1,G=Y.required??[],_=Y.optional??[],$=[..._];for(let W of Y.index){for(let H of G){let Q=nG(H,W,Z);if(Q instanceof S)return Q}for(let[H,Q]of _.entries()){let J=nG(Q,W,Z);if(J instanceof S)return J;if(J===null)continue;$[H]=J,X=!0}}if(X)return Z.node("structure",{...Y,optional:$},{prereduced:!0})}}});class tG extends N1{impliedBasis=I.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Y)=>Y.impliedSiblings??[]);props=t1(this.required,this.optional);propsByKey=o(this.props,(Y,Z)=>[Z.key,Z]);propsByKeyReference=T0(this.propsByKey);expression=mQ(this);requiredKeys=this.required?.map((Y)=>Y.key)??[];optionalKeys=this.optional?.map((Y)=>Y.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Y=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Z}of this.index)Y=Y.concat(Z.branches);return this._keyof=this.$.node("union",Y)}map(Y){return this.$.node("structure",this.props.flatMap(Y).reduce((Z,X)=>{let G=this.propsByKey[X.key];if(D0(X)){if(X.kind!=="required"&&X.kind!=="optional")return A(`Map result must have kind "required" or "optional" (was ${X.kind})`);return Z[X.kind]=Z0(Z[X.kind],X),Z}let _=X.kind??G?.kind??"required",$=o(X,(W,H)=>(W in i2.implementation.keys)?[W,H]:[]);return Z[_]=Z0(Z[_],this.$.node(_,$)),Z},{}))}assertHasKeys(Y){let Z=Y.filter((X)=>!r2(X,this.keyof()));if(Z.length)return A(rG(this.expression,Z))}get(Y,...Z){let X,G=!1,_=oQ(Y);if((typeof _==="string"||typeof _==="symbol")&&this.propsByKey[_])X=this.propsByKey[_].value,G=this.propsByKey[_].required;if(this.index){for(let W of this.index)if(r2(_,W.signature))X=X?.and(W.value)??W.value}if(this.sequence&&r2(_,I.intrinsic.nonNegativeIntegerString))if(y(_,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let W=Number.parseInt(_);if(W<this.sequence.prevariadic.length){let H=this.sequence.prevariadic[W].node;X=X?.and(H)??H,G||=W<this.sequence.prefixLength}else if(this.sequence.variadic){let H=this.$.node("union",this.sequence.variadicOrPostfix);X=X?.and(H)??H}}if(!X){if(this.sequence?.variadic&&y(_,"root")&&_.extends(I.intrinsic.number))return A(iQ(_.expression,this.sequence.expression));return A(rG(this.expression,[_]))}let $=X.get(...Z);return G?$:$.or(I.intrinsic.undefined)}pick(...Y){return this.assertHasKeys(Y),this.$.node("structure",this.filterKeys("pick",Y))}omit(...Y){return this.assertHasKeys(Y),this.$.node("structure",this.filterKeys("omit",Y))}optionalize(){let{required:Y,...Z}=this.inner;return this.$.node("structure",{...Z,optional:this.props.map((X)=>X.hasKind("required")?this.$.node("optional",X.inner):X)})}require(){let{optional:Y,...Z}=this.inner;return this.$.node("structure",{...Z,required:this.props.map((X)=>X.hasKind("optional")?{key:X.key,value:X.value}:X)})}merge(Y){let Z=this.filterKeys("omit",[Y.keyof()]);if(Y.required)Z.required=Z0(Z.required,Y.required);if(Y.optional)Z.optional=Z0(Z.optional,Y.optional);if(Y.index)Z.index=Z0(Z.index,Y.index);if(Y.sequence)Z.sequence=Y.sequence;if(Y.undeclared)Z.undeclared=Y.undeclared;else delete Z.undeclared;return this.$.node("structure",Z)}filterKeys(Y,Z){let X=c8(this.inner),G=(_)=>{let $=Z.some((W)=>r2(_,W));return Y==="pick"?$:!$};if(X.required)X.required=X.required.filter((_)=>G(_.key));if(X.optional)X.optional=X.optional.filter((_)=>G(_.key));if(X.index)X.index=X.index.filter((_)=>G(_.signature));return X}traverseAllows=(Y,Z)=>this._traverse("Allows",Y,Z);traverseApply=(Y,Z)=>this._traverse("Apply",Y,Z);_traverse=(Y,Z,X)=>{let G=X?.currentErrorCount??0;for(let _=0;_<this.props.length;_++)if(Y==="Allows"){if(!this.props[_].traverseAllows(Z,X))return!1}else if(this.props[_].traverseApply(Z,X),X.failFast&&X.currentErrorCount>G)return!1;if(this.sequence){if(Y==="Allows"){if(!this.sequence.traverseAllows(Z,X))return!1}else if(this.sequence.traverseApply(Z,X),X.failFast&&X.currentErrorCount>G)return!1}if(this.index||this.undeclared==="reject"){let _=Object.keys(Z);_.push(...Object.getOwnPropertySymbols(Z));for(let $=0;$<_.length;$++){let W=_[$];if(this.index){for(let H of this.index)if(H.signature.traverseAllows(W,X)){if(Y==="Allows"){if(!Q1(W,()=>H.value.traverseAllows(Z[W],X),X))return!1}else if(Q1(W,()=>H.value.traverseApply(Z[W],X),X),X.failFast&&X.currentErrorCount>G)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(W)){if(Y==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[W],meta:this.meta}),X.failFast)return!1}}}if(this.structuralMorph&&X&&!X.hasError())X.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Y)=>Y.hasDefault())??[])}declaresKey=(Y)=>(Y in this.propsByKey)||this.index?.some((Z)=>Z.signature.allows(Y))||this.sequence!==void 0&&I.intrinsic.nonNegativeIntegerString.allows(Y);_compileDeclaresKey(Y){let Z=[];if(this.props.length)Z.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let X of this.index)Z.push(Y.invoke(X.signature,{kind:"Allows",arg:"k"}));if(this.sequence)Z.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return Z.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",cQ(this))}structuralMorphRef=this.structuralMorph&&T0(this.structuralMorph);compile(Y){if(Y.traversalKind==="Apply")Y.initializeErrorCount();for(let Z of this.props)if(Y.check(Z),Y.traversalKind==="Apply")Y.returnIfFailFast();if(this.sequence){if(Y.check(this.sequence),Y.traversalKind==="Apply")Y.returnIfFailFast()}if(this.index||this.undeclared==="reject")Y.const("keys","Object.keys(data)"),Y.line("keys.push(...Object.getOwnPropertySymbols(data))"),Y.for("i < keys.length",()=>this.compileExhaustiveEntry(Y));if(Y.traversalKind==="Allows")return Y.return(!0);if(this.structuralMorphRef)Y.if("ctx && !ctx.hasError()",()=>{return Y.line("ctx.queueMorphs(["),lQ(Y,this),Y.line("])")})}compileExhaustiveEntry(Y){if(Y.const("k","keys[i]"),this.index)for(let Z of this.index)Y.if(`${Y.invoke(Z.signature,{arg:"k",kind:"Allows"})}`,()=>Y.traverseKey("k","data[k]",Z.value));if(this.undeclared==="reject")Y.if(`!(${this._compileDeclaresKey(Y)})`,()=>{if(Y.traversalKind==="Allows")return Y.return(!1);return Y.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Y.return())});return Y}reduceJsonSchema(Y,Z){switch(Y.type){case"object":return this.reduceObjectJsonSchema(Y,Z);case"array":let X=this.sequence?.reduceJsonSchema(Y,Z)??Y;if(this.props.length||this.index)return Z.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},Z)});return X;default:return w0.throwInternalOperandError("structure",Y)}}reduceObjectJsonSchema(Y,Z){if(this.props.length){Y.properties={};for(let X of this.props){let G=X.value.toJsonSchemaRecurse(Z);if(typeof X.key==="symbol"){Z.fallback.symbolKey({code:"symbolKey",base:Y,key:X.key,value:G,optional:X.optional});continue}if(X.hasDefault()){let _=typeof X.default==="function"?X.default():X.default;G.default=I.intrinsic.jsonData.allows(_)?_:Z.fallback.defaultValue({code:"defaultValue",base:G,value:_})}Y.properties[X.key]=G}if(this.requiredKeys.length&&Y.properties)Y.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in Y.properties))}if(this.index)for(let X of this.index){let G=X.value.toJsonSchemaRecurse(Z);if(X.signature.equals(I.intrinsic.string)){Y.additionalProperties=G;continue}for(let _ of X.signature.branches){if(!_.extends(I.intrinsic.string)){Y=Z.fallback.symbolKey({code:"symbolKey",base:Y,key:null,value:G,optional:!1});continue}let $={type:"string"};if(_.hasKind("morph"))$=Z.fallback.morph({code:"morph",base:_.in.toJsonSchemaRecurse(Z),out:_.out.toJsonSchemaRecurse(Z)});if(!_.hasKind("intersection"))return G0(`Unexpected index branch kind ${_.kind}.`);let{pattern:W}=_.inner;if(W){let H=Object.assign($,{pattern:W[0].rule});for(let Q=1;Q<W.length;Q++)$=Z.fallback.patternIntersection({code:"patternIntersection",base:H,pattern:W[Q].rule});Y.patternProperties??={},Y.patternProperties[H.pattern]=G}}}if(this.undeclared&&!Y.additionalProperties)Y.additionalProperties=!1;return Y}}var HZ={},dQ=(Y)=>{let Z="";for(let X=0;X<Y.defaultable.length;X++)Z+=Y.defaultable[X].defaultValueMorphRef;if(Y.sequence?.defaultValueMorphsReference)Z+=Y.sequence?.defaultValueMorphsReference;if(Y.undeclared==="delete"){if(Z+="delete !(",Y.required)for(let X of Y.required)Z+=X.compiledKey+" | ";if(Y.optional)for(let X of Y.optional)Z+=X.compiledKey+" | ";if(Y.index)for(let X of Y.index)Z+=X.signature.id+" | ";if(Y.sequence)if(Y.sequence.maxLength===null)Z+=u.nonNegativeIntegerString.id;else for(let X=0;X<Y.sequence.tuple.length;X++)Z+=X+" | ";Z+=")"}return Z},cQ=(Y)=>{let Z=dQ(Y);if(!Z)return;if(HZ[Z])return HZ[Z];let X=(G,_)=>{for(let $=0;$<Y.defaultable.length;$++)if(!(Y.defaultable[$].key in G))Y.defaultable[$].defaultValueMorph(G,_);if(Y.sequence?.defaultables)for(let $=G.length-Y.sequence.prefixLength;$<Y.sequence.defaultables.length;$++)Y.sequence.defaultValueMorphs[$](G,_);if(Y.undeclared==="delete"){for(let $ in G)if(!Y.declaresKey($))delete G[$]}return G};return HZ[Z]=X},lQ=(Y,Z)=>{let G=`(data${Z.defaultable.some((_)=>_.defaultValueMorph.length===2)||Z.sequence?.defaultValueMorphs.some((_)=>_.length===2)?", ctx":""})`;return Y.block(`${G} => `,(_)=>{for(let $=0;$<Z.defaultable.length;$++){let{serializedKey:W,defaultValueMorphRef:H}=Z.defaultable[$];_.if(`!(${W} in data)`,(Q)=>Q.line(`${H}${G}`))}if(Z.sequence?.defaultables)_.for(`i < ${Z.sequence.defaultables.length}`,($)=>$.set("data[i]",5),`data.length - ${Z.sequence.prefixLength}`);if(Z.undeclared==="delete")_.forIn("data",($)=>$.if(`!(${Z._compileDeclaresKey($)})`,(W)=>W.line("delete data[k]")));return _.return("data")})},JZ={implementation:uQ,Node:tG},oQ=(Y)=>{if(y(Y,"root")&&Y.hasKind("unit"))Y=Y.unit;if(typeof Y==="number")Y=`${Y}`;return Y},iQ=(Y,Z)=>`${Y} is not allowed as an array index on ${Z}. Use the 'nonNegativeIntegerString' keyword instead.`,Z6=(Y,Z,X)=>{let[G,_]=RX(Y.branches,(W)=>W.hasKind("unit"));if(!G.length)return{index:X.node("index",{signature:Y,value:Z})};let $={};for(let W of G){let H=X.node("required",{key:W.unit,value:Z});$[H.kind]=Z0($[H.kind],H)}if(_.length)$.index=X.node("index",{signature:_,value:Z});return $},nQ=(Y)=>y(Y,"root")?Y.expression:i(Y),rG=(Y,Z)=>`Key${Z.length===1?"":"s"} ${Z.map(nQ).join(", ")} ${Z.length===1?"does":"do"} not exist on ${Y}`;var _2={...wG,alias:s2.implementation,domain:Y6.implementation,unit:XZ.implementation,proto:t2.implementation,union:ZZ.implementation,morph:eY.implementation,intersection:aY.implementation,divisor:yY.implementation,pattern:oY.implementation,predicate:bY.implementation,required:_Z.implementation,optional:i2.implementation,index:GZ.implementation,sequence:$Z.implementation,structure:JZ.implementation};I.defaultConfig=jX(Object.assign(o(_2,(Y,Z)=>[Y,Z.defaults]),{jitless:hX(),clone:vX,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:w0.defaultConfig}));I.resolvedConfig=p2(I.defaultConfig,I.config);var CG={...NG,alias:s2.Node,domain:Y6.Node,unit:XZ.Node,proto:t2.Node,union:ZZ.Node,morph:eY.Node,intersection:aY.Node,divisor:yY.Node,pattern:oY.Node,predicate:bY.Node,required:_Z.Node,optional:i2.Node,index:GZ.Node,sequence:$Z.Node,structure:JZ.Node};class H2 extends MY{get[Y1](){return"module"}}var QZ=(Y,Z)=>new H2(o(Y,(X,G)=>[X,y(G,"module")?QZ(G,Z):Z.bindReference(G)]));var rQ=(Y)=>U0(Y)?Y:("branches"in Y)&&U0(Y.branches)?Y.branches:void 0,sQ=(Y,Z)=>A(`Node of kind ${Z} is not valid as a ${Y} definition`),aG=(Y)=>`#${Y} duplicates public alias ${Y}`,zZ={};I.ambient??={};var eG,Z9="function $",tQ=(Y)=>X9(Y,G9(Y)),X9=(Y,Z)=>{let X=Z.write(Z9,4),G=Z.compile()();for(let _ of Y){if(_.precompilation)continue;if(_.traverseAllows=G[`${_.id}Allows`].bind(G),_.isRoot()&&!_.allowsRequiresContext)_.allows=_.traverseAllows;if(_.traverseApply=G[`${_.id}Apply`].bind(G),G[`${_.id}Optimistic`])_.traverseOptimistic=G[`${_.id}Optimistic`].bind(G);_.precompilation=X}},G9=(Y)=>new d8().return(Y.reduce((Z,X)=>{let G=new g2({kind:"Allows"}).indent();X.compile(G);let _=G.write(`${X.id}Allows`),$=new g2({kind:"Apply"}).indent();X.compile($);let W=$.write(`${X.id}Apply`),H=`${Z}${_},
|
|
44
|
-
${
|
|
45
|
-
`;if(!
|
|
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
|
+
Left: ${X}
|
|
41
|
+
Right: ${Y}`,TQ=(X,Y)=>`The intersection of two ordered unions is indeterminate:
|
|
42
|
+
Left: ${X}
|
|
43
|
+
Right: ${Y}`;var CQ=l({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(X)=>X instanceof Date?X.toISOString():A1(X)}},normalize:(X)=>X,defaults:{description:(X)=>c(X.unit),problem:({expected:X,actual:Y})=>`${X===Y?`must be reference equal to ${X} (serialized to the same value)`:`must be ${X} (was ${Y})`}`},intersections:{unit:(X,Y)=>C.init("unit",X,Y),...o1("unit",(X,Y)=>{if(Y.allows(X.unit))return X;let Z=Y.hasKind("intersection")?Y.basis:Y;if(Z){let _=Z.hasKind("domain")?Z:N.intrinsic.object;if(X.domain!==_.domain){let G=X.domain==="undefined"||X.domain==="null"||X.domain==="boolean"?X.domain:N.intrinsic[X.domain];return C.init("domain",G,_)}}return C.init("assignability",X,Y.hasKind("intersection")?Y.children.find((_)=>!_.allows(X.unit)):Y)})}});class l_ extends v4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=c_(this.unit,this.serializedValue);compiledNegation=c_(this.unit,this.serializedValue,"negated");expression=c(this.unit);domain=x0(this.unit);get defaultShortDescription(){return this.domain==="object"?G1.object:this.description}innerToJsonSchema(X){return this.unit===null?{type:"null"}:N.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:X.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(X)=>X instanceof Date&&X.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(X)=>Number.isNaN(X):(X)=>X===this.unit}var eX={implementation:CQ,Node:l_},c_=(X,Y,Z)=>{if(X instanceof Date){let _=`data instanceof Date && data.toISOString() === ${Y}`;return Z?`!(${_})`:_}if(Number.isNaN(X))return`${Z?"!":""}Number.isNaN(data)`;return`data ${Z?"!":"="}== ${Y}`};var qQ=l({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(X,Y)=>{let Z=Y.$.parseSchema(X);if(!Z.extends(N.intrinsic.key))return w(SQ(Z.expression));let _=Z.branches.filter((G)=>G.hasKind("unit"));if(_.length)return w(jQ(_.map((G)=>c(G.unit))));return Z}},value:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)}},normalize:(X)=>X,defaults:{description:(X)=>`[${X.signature.expression}]: ${X.value.description}`},intersections:{index:(X,Y,Z)=>{if(X.signature.equals(Y.signature)){let _=O0(X.value,Y.value,Z),G=_ instanceof C?N.intrinsic.never.internal:_;return Z.$.node("index",{signature:X.signature,value:G})}if(X.signature.extends(Y.signature)&&X.value.subsumes(Y.value))return Y;if(Y.signature.extends(X.signature)&&Y.value.subsumes(X.value))return X;return null}}});class o_ extends R1{impliedBasis=N.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=s(this.value.flatRefs.map((X)=>f1([this.signature,...X.path],X.node)),f1([this.signature],this.value));traverseAllows=(X,Y)=>q4(X).every((Z)=>{if(this.signature.traverseAllows(Z[0],Y))return $1(Z[0],()=>this.value.traverseAllows(Z[1],Y),Y);return!0});traverseApply=(X,Y)=>{for(let Z of q4(X))if(this.signature.traverseAllows(Z[0],Y))$1(Z[0],()=>this.value.traverseApply(Z[1],Y),Y)};_transform(X,Y){Y.path.push(this.signature);let Z=super._transform(X,Y);return Y.path.pop(),Z}compile(){}}var XY={implementation:qQ,Node:o_},jQ=(X)=>`Index keys ${X.join(", ")} should be specified as named props.`,SQ=(X)=>`Indexed key definition '${X}' must be a string or symbol`;var PQ=l({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X)}},normalize:(X)=>X,defaults:{description:(X)=>`${X.compiledKey}: ${X.value.description}`,expected:(X)=>X.missingValueDescription,actual:()=>"missing"},intersections:{required:c8,optional:c8}});class i_ extends l8{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=D4(this.errorContext)}var YY={implementation:PQ,Node:i_};var vQ=l({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>Y.$.parseSchema(Z))}},optionals:{child:!0,parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>Y.$.parseSchema(Z))}},defaultables:{child:(X)=>X.map((Y)=>Y[0]),parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>{let _=Y.$.parseSchema(Z[0]);return i8(_,Z[1],null),[_,Z[1]]})},serialize:(X)=>X.map((Y)=>[Y[0].collapsibleJson,A1(Y[1])])},variadic:{child:!0,parse:(X,Y)=>Y.$.parseSchema(X,Y)},minVariadicLength:{parse:(X)=>X===0?void 0:X},postfix:{child:!0,parse:(X,Y)=>{if(X.length===0)return;return X.map((Z)=>Y.$.parseSchema(Z))}}},normalize:(X)=>{if(typeof X==="string")return{variadic:X};if("variadic"in X||"prefix"in X||"defaultables"in X||"optionals"in X||"postfix"in X||"minVariadicLength"in X){if(X.postfix?.length){if(!X.variadic)return w(kQ);if(X.optionals?.length||X.defaultables?.length)return w(_Y)}if(X.minVariadicLength&&!X.variadic)return w("minVariadicLength may not be specified without a variadic element");return X}return{variadic:X}},reduce:(X,Y)=>{let Z=X.minVariadicLength??0,_=X.prefix?.slice()??[],G=X.defaultables?.slice()??[],W=X.optionals?.slice()??[],$=X.postfix?.slice()??[];if(X.variadic){while(W.at(-1)?.equals(X.variadic))W.pop();if(W.length===0&&G.length===0)while(_.at(-1)?.equals(X.variadic))_.pop(),Z++;while($[0]?.equals(X.variadic))$.shift(),Z++}else if(W.length===0&&G.length===0)_.push(...$.splice(0));if(Z!==X.minVariadicLength||X.prefix&&X.prefix.length!==_.length)return Y.node("sequence",{...X,prefix:_,defaultables:G,optionals:W,postfix:$,minVariadicLength:Z},{prereduced:!0})},defaults:{description:(X)=>{if(X.isVariadicOnly)return`${X.variadic.nestableExpression}[]`;return`[${X.tuple.map((Z)=>Z.kind==="defaultables"?`${Z.node.nestableExpression} = ${c(Z.default)}`:Z.kind==="optionals"?`${Z.node.nestableExpression}?`:Z.kind==="variadic"?`...${Z.node.nestableExpression}[]`:Z.node.expression).join(", ")}]`}},intersections:{sequence:(X,Y,Z)=>{let _=t8({l:X.tuple,r:Y.tuple,disjoint:new C,result:[],fixedVariants:[],ctx:Z}),G=_.disjoint.length===0?[_,..._.fixedVariants]:_.fixedVariants;return G.length===0?_.disjoint:G.length===1?Z.$.node("sequence",n_(G[0].result)):Z.$.node("union",G.map((W)=>({proto:Array,sequence:n_(W.result)})))}}});class r_ extends R1{impliedBasis=N.intrinsic.Array.internal;tuple=hQ(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((X)=>{if(X.kind==="defaultables"||X.kind==="optionals")return this.defaultablesAndOptionals.push(X.node),!0;return X.kind==="prefix"});variadicOrPostfix=s1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return SX(this.flatRefs,this.prevariadic.flatMap((X,Y)=>s(X.node.flatRefs.map((Z)=>f1([`${Y}`,...Z.path],Z.node)),f1([`${Y}`],X.node)))),SX(this.flatRefs,this.variadicOrPostfix.flatMap((X)=>s(X.flatRefs.map((Y)=>f1([N.intrinsic.nonNegativeIntegerString.internal,...Y.path],Y.node)),f1([N.intrinsic.nonNegativeIntegerString.internal],X)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=fQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?N0(this.defaultValueMorphs):void 0;elementAtIndex(X,Y){if(Y<this.prevariadic.length)return this.tuple[Y];let Z=X.length-this.postfixLength;if(Y>=Z)return{kind:"postfix",node:this.postfix[Y-Z]};return{kind:"variadic",node:this.variadic??e(`Unexpected attempt to access index ${Y} on ${this}`)}}traverseAllows=(X,Y)=>{for(let Z=0;Z<X.length;Z++)if(!this.elementAtIndex(X,Z).node.traverseAllows(X[Z],Y))return!1;return!0};traverseApply=(X,Y)=>{let Z=0;for(;Z<X.length;Z++)$1(Z,()=>this.elementAtIndex(X,Z).node.traverseApply(X[Z],Y),Y)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(X){if(this.prefix)for(let[Y,Z]of this.prefix.entries())X.traverseKey(`${Y}`,`data[${Y}]`,Z);for(let[Y,Z]of this.defaultablesAndOptionals.entries()){let _=`${Y+this.prefixLength}`;X.if(`${_} >= ${X.data}.length`,()=>X.traversalKind==="Allows"?X.return(!0):X.return()),X.traverseKey(_,`data[${_}]`,Z)}if(this.variadic){if(this.postfix)X.const("firstPostfixIndex",`${X.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(X.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>X.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Y,Z]of this.postfix.entries()){let _=`firstPostfixIndex + ${Y}`;X.traverseKey(_,`data[${_}]`,Z)}}if(X.traversalKind==="Allows")X.return(!0)}_transform(X,Y){Y.path.push(N.intrinsic.nonNegativeIntegerString.internal);let Z=super._transform(X,Y);return Y.path.pop(),Z}expression=this.description;reduceJsonSchema(X,Y){if(this.prevariadic.length)X.prefixItems=this.prevariadic.map((Z)=>{let _=Z.node.toJsonSchemaRecurse(Y);if(Z.kind==="defaultables"){let G=typeof Z.default==="function"?Z.default():Z.default;_.default=N.intrinsic.jsonData.allows(G)?G:Y.fallback.defaultValue({code:"defaultValue",base:_,value:G})}return _});if(this.minLength)X.minItems=this.minLength;if(this.variadic){let Z=Object.assign(X,{items:this.variadic.toJsonSchemaRecurse(Y)});if(this.maxLength)Z.maxItems=this.maxLength;if(this.postfix){let _=this.postfix.map((G)=>G.toJsonSchemaRecurse(Y));X=Y.fallback.arrayPostfix({code:"arrayPostfix",base:Z,elements:_})}}else X.items=!1,delete X.maxItems;return X}}var xQ={},fQ=(X)=>{if(!X.defaultables)return[];let Y=[],Z="[",_=X.prefixLength+X.defaultablesLength-1;for(let G=X.prefixLength;G<=_;G++){let[W,$]=X.defaultables[G-X.prefixLength];Y.push(nX(G,W,$)),Z+=`${G}: ${W.id} = ${A1($)}, `}return Z+="]",xQ[Z]??=Y},ZY={implementation:vQ,Node:r_},hQ=(X)=>{let Y=[];if(X.prefix)for(let Z of X.prefix)Y.push({kind:"prefix",node:Z});if(X.defaultables)for(let[Z,_]of X.defaultables)Y.push({kind:"defaultables",node:Z,default:_});if(X.optionals)for(let Z of X.optionals)Y.push({kind:"optionals",node:Z});if(X.variadic)Y.push({kind:"variadic",node:X.variadic});if(X.postfix)for(let Z of X.postfix)Y.push({kind:"postfix",node:Z});return Y},n_=(X)=>X.reduce((Y,Z)=>{if(Z.kind==="variadic")Y.variadic=Z.node;else if(Z.kind==="defaultables")Y.defaultables=s(Y.defaultables,[[Z.node,Z.default]]);else Y[Z.kind]=s(Y[Z.kind],Z.node);return Y},{}),_Y="A postfix required element cannot follow an optional or defaultable element",kQ="A postfix element requires a variadic element",t8=(X)=>{let[Y,...Z]=X.l,[_,...G]=X.r;if(!Y||!_)return X;let W=Z.at(-1)?.kind==="postfix",$=G.at(-1)?.kind==="postfix",H=Y.kind==="prefix"||_.kind==="prefix"?"prefix":Y.kind==="postfix"||_.kind==="postfix"?"postfix":Y.kind==="variadic"&&_.kind==="variadic"?"variadic":W||$?"prefix":Y.kind==="defaultables"||_.kind==="defaultables"?"defaultables":"optionals";if(Y.kind==="prefix"&&_.kind==="variadic"&&$){let F=t8({...X,fixedVariants:[],r:G.map((O)=>({...O,kind:"prefix"}))});if(F.disjoint.length===0)X.fixedVariants.push(F)}else if(_.kind==="prefix"&&Y.kind==="variadic"&&W){let F=t8({...X,fixedVariants:[],l:Z.map((O)=>({...O,kind:"prefix"}))});if(F.disjoint.length===0)X.fixedVariants.push(F)}let Q=O0(Y.node,_.node,X.ctx);if(Q instanceof C)if(H==="prefix"||H==="postfix")X.disjoint.push(...Q.withPrefixKey(H==="prefix"?X.result.length:`-${Z.length+1}`,"required")),X.result=[...X.result,{kind:H,node:N.intrinsic.never.internal}];else if(H==="optionals"||H==="defaultables")return X;else return t8({...X,fixedVariants:[],l:Z.map((F)=>({...F,kind:"prefix"})),r:Z.map((F)=>({...F,kind:"prefix"}))});else if(H==="defaultables"){if(Y.kind==="defaultables"&&_.kind==="defaultables"&&Y.default!==_.default)w(iX(Y.default,_.default));X.result=[...X.result,{kind:H,node:Q,default:Y.kind==="defaultables"?Y.default:_.kind==="defaultables"?_.default:e(`Unexpected defaultable intersection from ${Y.kind} and ${_.kind} elements.`)}]}else X.result=[...X.result,{kind:H,node:Q}];let J=X.l.length,z=X.r.length;if(Y.kind!=="variadic"||J>=z&&(_.kind==="variadic"||z===1))X.l=Z;if(_.kind!=="variadic"||z>=J&&(Y.kind==="variadic"||J===1))X.r=G;return t8(X)};var a_=(X)=>(Y)=>{if(Y.props.length||Y.index){let Z=Y.index?.map((G)=>G[X])??[];for(let G of Y.props)Z.push(G[X]);if(Y.undeclared)Z.push(`+ (undeclared): ${Y.undeclared}`);let _=`{ ${Z.join(", ")} }`;return Y.sequence?`${_} & ${Y.sequence.description}`:_}return Y.sequence?.description??"{}"},bQ=a_("description"),yQ=a_("expression"),s_=(X,Y,Z)=>{let _=X.required?"required":"optional";if(!Y.signature.allows(X.key))return null;let G=H1(X.value,Y.value,Z);if(G instanceof C)return _==="optional"?Z.node("optional",{key:X.key,value:N.intrinsic.never.internal}):G.withPrefixKey(X.key,X.kind);return null},gQ=l({kind:"structure",hasAssociatedError:!1,normalize:(X)=>X,applyConfig:(X,Y)=>{if(!X.undeclared&&Y.onUndeclaredKey!=="ignore")return{...X,undeclared:Y.onUndeclaredKey};return X},keys:{required:{child:!0,parse:i0("required"),reduceIo:(X,Y,Z)=>{Y.required=s(Y.required,Z.map((_)=>_[X]));return}},optional:{child:!0,parse:i0("optional"),reduceIo:(X,Y,Z)=>{if(X==="in"){Y.optional=Z.map((_)=>_.in);return}for(let _ of Z)Y[_.outProp.kind]=s(Y[_.outProp.kind],_.outProp.out)}},index:{child:!0,parse:i0("index")},sequence:{child:!0,parse:i0("sequence")},undeclared:{parse:(X)=>X==="ignore"?void 0:X,reduceIo:(X,Y,Z)=>{if(Z!=="delete")return;if(X==="in")delete Y.undeclared;else Y.undeclared="reject"}}},defaults:{description:bQ},intersections:{structure:(X,Y,Z)=>{let _={...X.inner},G={...Y.inner},W=new C;if(X.undeclared){let Q=X.keyof();for(let J of Y.requiredKeys)if(!Q.allows(J))W.add("presence",N.intrinsic.never.internal,Y.propsByKey[J].value,{path:[J]});if(G.optional)G.optional=G.optional.filter((J)=>Q.allows(J.key));if(G.index)G.index=G.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let z=H1(Q,J.signature,Z.$);if(z instanceof C)return[];let F=X6(z,J.value,Z.$);if(F.required)G.required=s1(G.required,F.required);if(F.optional)G.optional=s1(G.optional,F.optional);return F.index??[]})}if(Y.undeclared){let Q=Y.keyof();for(let J of X.requiredKeys)if(!Q.allows(J))W.add("presence",X.propsByKey[J].value,N.intrinsic.never.internal,{path:[J]});if(_.optional)_.optional=_.optional.filter((J)=>Q.allows(J.key));if(_.index)_.index=_.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let z=H1(Q,J.signature,Z.$);if(z instanceof C)return[];let F=X6(z,J.value,Z.$);if(F.required)_.required=s1(_.required,F.required);if(F.optional)_.optional=s1(_.optional,F.optional);return F.index??[]})}let $={};if(X.undeclared||Y.undeclared)$.undeclared=X.undeclared==="reject"||Y.undeclared==="reject"?"reject":"delete";let H=X8({kind:"structure",baseInner:$,l:Y8(_),r:Y8(G),roots:[],ctx:Z});if(H instanceof C)W.push(...H);if(W.length)return W;return H}},reduce:(X,Y)=>{if(X.index){if(!(X.required||X.optional))return;let Z=!1,_=X.required??[],G=X.optional??[],W=[...G];for(let $ of X.index){for(let H of _){let Q=s_(H,$,Y);if(Q instanceof C)return Q}for(let[H,Q]of G.entries()){let J=s_(Q,$,Y);if(J instanceof C)return J;if(J===null)continue;W[H]=J,Z=!0}}if(Z)return Y.node("structure",{...X,optional:W},{prereduced:!0})}}});class e_ extends R1{impliedBasis=N.intrinsic.object.internal;impliedSiblings=this.children.flatMap((X)=>X.impliedSiblings??[]);props=s1(this.required,this.optional);propsByKey=d(this.props,(X,Y)=>[Y.key,Y]);propsByKeyReference=N0(this.propsByKey);expression=yQ(this);requiredKeys=this.required?.map((X)=>X.key)??[];optionalKeys=this.optional?.map((X)=>X.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let X=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Y}of this.index)X=X.concat(Y.branches);return this._keyof=this.$.node("union",X)}map(X){return this.$.node("structure",this.props.flatMap(X).reduce((Y,Z)=>{let _=this.propsByKey[Z.key];if(E0(Z)){if(Z.kind!=="required"&&Z.kind!=="optional")return w(`Map result must have kind "required" or "optional" (was ${Z.kind})`);return Y[Z.kind]=s(Y[Z.kind],Z),Y}let G=Z.kind??_?.kind??"required",W=d(Z,($,H)=>($ in o8.implementation.keys)?[$,H]:[]);return Y[G]=s(Y[G],this.$.node(G,W)),Y},{}))}assertHasKeys(X){let Y=X.filter((Z)=>!n8(Z,this.keyof()));if(Y.length)return w(t_(this.expression,Y))}get(X,...Y){let Z,_=!1,G=dQ(X);if((typeof G==="string"||typeof G==="symbol")&&this.propsByKey[G])Z=this.propsByKey[G].value,_=this.propsByKey[G].required;if(this.index){for(let $ of this.index)if(n8(G,$.signature))Z=Z?.and($.value)??$.value}if(this.sequence&&n8(G,N.intrinsic.nonNegativeIntegerString))if(f(G,"root")){if(this.sequence.variadic)Z=Z?.and(this.sequence.element)??this.sequence.element}else{let $=Number.parseInt(G);if($<this.sequence.prevariadic.length){let H=this.sequence.prevariadic[$].node;Z=Z?.and(H)??H,_||=$<this.sequence.prefixLength}else if(this.sequence.variadic){let H=this.$.node("union",this.sequence.variadicOrPostfix);Z=Z?.and(H)??H}}if(!Z){if(this.sequence?.variadic&&f(G,"root")&&G.extends(N.intrinsic.number))return w(cQ(G.expression,this.sequence.expression));return w(t_(this.expression,[G]))}let W=Z.get(...Y);return _?W:W.or(N.intrinsic.undefined)}pick(...X){return this.assertHasKeys(X),this.$.node("structure",this.filterKeys("pick",X))}omit(...X){return this.assertHasKeys(X),this.$.node("structure",this.filterKeys("omit",X))}optionalize(){let{required:X,...Y}=this.inner;return this.$.node("structure",{...Y,optional:this.props.map((Z)=>Z.hasKind("required")?this.$.node("optional",Z.inner):Z)})}require(){let{optional:X,...Y}=this.inner;return this.$.node("structure",{...Y,required:this.props.map((Z)=>Z.hasKind("optional")?{key:Z.key,value:Z.value}:Z)})}merge(X){let Y=this.filterKeys("omit",[X.keyof()]);if(X.required)Y.required=s(Y.required,X.required);if(X.optional)Y.optional=s(Y.optional,X.optional);if(X.index)Y.index=s(Y.index,X.index);if(X.sequence)Y.sequence=X.sequence;if(X.undeclared)Y.undeclared=X.undeclared;else delete Y.undeclared;return this.$.node("structure",Y)}filterKeys(X,Y){let Z=d2(this.inner),_=(G)=>{let W=Y.some(($)=>n8(G,$));return X==="pick"?W:!W};if(Z.required)Z.required=Z.required.filter((G)=>_(G.key));if(Z.optional)Z.optional=Z.optional.filter((G)=>_(G.key));if(Z.index)Z.index=Z.index.filter((G)=>_(G.signature));return Z}traverseAllows=(X,Y)=>this._traverse("Allows",X,Y);traverseApply=(X,Y)=>this._traverse("Apply",X,Y);_traverse=(X,Y,Z)=>{let _=Z?.currentErrorCount??0;for(let G=0;G<this.props.length;G++)if(X==="Allows"){if(!this.props[G].traverseAllows(Y,Z))return!1}else if(this.props[G].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>_)return!1;if(this.sequence){if(X==="Allows"){if(!this.sequence.traverseAllows(Y,Z))return!1}else if(this.sequence.traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>_)return!1}if(this.index||this.undeclared==="reject"){let G=Object.keys(Y);G.push(...Object.getOwnPropertySymbols(Y));for(let W=0;W<G.length;W++){let $=G[W];if(this.index){for(let H of this.index)if(H.signature.traverseAllows($,Z)){if(X==="Allows"){if(!$1($,()=>H.value.traverseAllows(Y[$],Z),Z))return!1}else if($1($,()=>H.value.traverseApply(Y[$],Z),Z),Z.failFast&&Z.currentErrorCount>_)return!1}}if(this.undeclared==="reject"&&!this.declaresKey($)){if(X==="Allows")return!1;if(Z.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[$],meta:this.meta}),Z.failFast)return!1}}}if(this.structuralMorph&&Z&&!Z.hasError())Z.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((X)=>X.hasDefault())??[])}declaresKey=(X)=>(X in this.propsByKey)||this.index?.some((Y)=>Y.signature.allows(X))||this.sequence!==void 0&&N.intrinsic.nonNegativeIntegerString.allows(X);_compileDeclaresKey(X){let Y=[];if(this.props.length)Y.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let Z of this.index)Y.push(X.invoke(Z.signature,{kind:"Allows",arg:"k"}));if(this.sequence)Y.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return Y.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",mQ(this))}structuralMorphRef=this.structuralMorph&&N0(this.structuralMorph);compile(X){if(X.traversalKind==="Apply")X.initializeErrorCount();for(let Y of this.props)if(X.check(Y),X.traversalKind==="Apply")X.returnIfFailFast();if(this.sequence){if(X.check(this.sequence),X.traversalKind==="Apply")X.returnIfFailFast()}if(this.index||this.undeclared==="reject")X.const("keys","Object.keys(data)"),X.line("keys.push(...Object.getOwnPropertySymbols(data))"),X.for("i < keys.length",()=>this.compileExhaustiveEntry(X));if(X.traversalKind==="Allows")return X.return(!0);if(this.structuralMorphRef)X.if("ctx && !ctx.hasError()",()=>{return X.line("ctx.queueMorphs(["),uQ(X,this),X.line("])")})}compileExhaustiveEntry(X){if(X.const("k","keys[i]"),this.index)for(let Y of this.index)X.if(`${X.invoke(Y.signature,{arg:"k",kind:"Allows"})}`,()=>X.traverseKey("k","data[k]",Y.value));if(this.undeclared==="reject")X.if(`!(${this._compileDeclaresKey(X)})`,()=>{if(X.traversalKind==="Allows")return X.return(!1);return X.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>X.return())});return X}reduceJsonSchema(X,Y){switch(X.type){case"object":return this.reduceObjectJsonSchema(X,Y);case"array":let Z=this.sequence?.reduceJsonSchema(X,Y)??X;if(this.props.length||this.index)return Y.fallback.arrayObject({code:"arrayObject",base:Z,object:this.reduceObjectJsonSchema({type:"object"},Y)});return Z;default:return M0.throwInternalOperandError("structure",X)}}reduceObjectJsonSchema(X,Y){if(this.props.length){X.properties={};for(let Z of this.props){let _=Z.value.toJsonSchemaRecurse(Y);if(typeof Z.key==="symbol"){Y.fallback.symbolKey({code:"symbolKey",base:X,key:Z.key,value:_,optional:Z.optional});continue}if(Z.hasDefault()){let G=typeof Z.default==="function"?Z.default():Z.default;_.default=N.intrinsic.jsonData.allows(G)?G:Y.fallback.defaultValue({code:"defaultValue",base:_,value:G})}X.properties[Z.key]=_}if(this.requiredKeys.length&&X.properties)X.required=this.requiredKeys.filter((Z)=>typeof Z==="string"&&(Z in X.properties))}if(this.index)for(let Z of this.index){let _=Z.value.toJsonSchemaRecurse(Y);if(Z.signature.equals(N.intrinsic.string)){X.additionalProperties=_;continue}for(let G of Z.signature.branches){if(!G.extends(N.intrinsic.string)){X=Y.fallback.symbolKey({code:"symbolKey",base:X,key:null,value:_,optional:!1});continue}let W={type:"string"};if(G.hasKind("morph"))W=Y.fallback.morph({code:"morph",base:G.in.toJsonSchemaRecurse(Y),out:G.out.toJsonSchemaRecurse(Y)});if(!G.hasKind("intersection"))return e(`Unexpected index branch kind ${G.kind}.`);let{pattern:$}=G.inner;if($){let H=Object.assign(W,{pattern:$[0].rule});for(let Q=1;Q<$.length;Q++)W=Y.fallback.patternIntersection({code:"patternIntersection",base:H,pattern:$[Q].rule});X.patternProperties??={},X.patternProperties[H.pattern]=_}}}if(this.undeclared&&!X.additionalProperties)X.additionalProperties=!1;return X}}var GY={},pQ=(X)=>{let Y="";for(let Z=0;Z<X.defaultable.length;Z++)Y+=X.defaultable[Z].defaultValueMorphRef;if(X.sequence?.defaultValueMorphsReference)Y+=X.sequence?.defaultValueMorphsReference;if(X.undeclared==="delete"){if(Y+="delete !(",X.required)for(let Z of X.required)Y+=Z.compiledKey+" | ";if(X.optional)for(let Z of X.optional)Y+=Z.compiledKey+" | ";if(X.index)for(let Z of X.index)Y+=Z.signature.id+" | ";if(X.sequence)if(X.sequence.maxLength===null)Y+=k.nonNegativeIntegerString.id;else for(let Z=0;Z<X.sequence.tuple.length;Z++)Y+=Z+" | ";Y+=")"}return Y},mQ=(X)=>{let Y=pQ(X);if(!Y)return;if(GY[Y])return GY[Y];let Z=(_,G)=>{for(let W=0;W<X.defaultable.length;W++)if(!(X.defaultable[W].key in _))X.defaultable[W].defaultValueMorph(_,G);if(X.sequence?.defaultables)for(let W=_.length-X.sequence.prefixLength;W<X.sequence.defaultables.length;W++)X.sequence.defaultValueMorphs[W](_,G);if(X.undeclared==="delete"){for(let W in _)if(!X.declaresKey(W))delete _[W]}return _};return GY[Y]=Z},uQ=(X,Y)=>{let _=`(data${Y.defaultable.some((G)=>G.defaultValueMorph.length===2)||Y.sequence?.defaultValueMorphs.some((G)=>G.length===2)?", ctx":""})`;return X.block(`${_} => `,(G)=>{for(let W=0;W<Y.defaultable.length;W++){let{serializedKey:$,defaultValueMorphRef:H}=Y.defaultable[W];G.if(`!(${$} in data)`,(Q)=>Q.line(`${H}${_}`))}if(Y.sequence?.defaultables)G.for(`i < ${Y.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${Y.sequence.prefixLength}`);if(Y.undeclared==="delete")G.forIn("data",(W)=>W.if(`!(${Y._compileDeclaresKey(W)})`,($)=>$.line("delete data[k]")));return G.return("data")})},WY={implementation:gQ,Node:e_},dQ=(X)=>{if(f(X,"root")&&X.hasKind("unit"))X=X.unit;if(typeof X==="number")X=`${X}`;return X},cQ=(X,Y)=>`${X} is not allowed as an array index on ${Y}. Use the 'nonNegativeIntegerString' keyword instead.`,X6=(X,Y,Z)=>{let[_,G]=N5(X.branches,($)=>$.hasKind("unit"));if(!_.length)return{index:Z.node("index",{signature:X,value:Y})};let W={};for(let $ of _){let H=Z.node("required",{key:$.unit,value:Y});W[H.kind]=s(W[H.kind],H)}if(G.length)W.index=Z.node("index",{signature:G,value:Y});return W},lQ=(X)=>f(X,"root")?X.expression:c(X),t_=(X,Y)=>`Key${Y.length===1?"":"s"} ${Y.map(lQ).join(", ")} ${Y.length===1?"does":"do"} not exist on ${X}`;var _8={...I_,alias:r8.implementation,domain:e2.implementation,unit:eX.implementation,proto:s8.implementation,union:aX.implementation,morph:sX.implementation,intersection:rX.implementation,divisor:hX.implementation,pattern:dX.implementation,predicate:fX.implementation,required:YY.implementation,optional:o8.implementation,index:XY.implementation,sequence:ZY.implementation,structure:WY.implementation};N.defaultConfig=P5(Object.assign(d(_8,(X,Y)=>[X,Y.defaults]),{jitless:b5(),clone:f5,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:M0.defaultConfig}));N.resolvedConfig=g8(N.defaultConfig,N.config);var j_={...K_,alias:r8.Node,domain:e2.Node,unit:eX.Node,proto:s8.Node,union:aX.Node,morph:sX.Node,intersection:rX.Node,divisor:hX.Node,pattern:dX.Node,predicate:fX.Node,required:YY.Node,optional:o8.Node,index:XY.Node,sequence:ZY.Node,structure:WY.Node};class $8 extends VX{get[t0](){return"module"}}var $Y=(X,Y)=>new $8(d(X,(Z,_)=>[Z,f(_,"module")?$Y(_,Y):Y.bindReference(_)]));var oQ=(X)=>Q0(X)?X:("branches"in X)&&Q0(X.branches)?X.branches:void 0,iQ=(X,Y)=>w(`Node of kind ${Y} is not valid as a ${X} definition`),X9=(X)=>`#${X} duplicates public alias ${X}`,HY={};N.ambient??={};var Y9,_9="function $",nQ=(X)=>G9(X,W9(X)),G9=(X,Y)=>{let Z=Y.write(_9,4),_=Y.compile()();for(let G of X){if(G.precompilation)continue;if(G.traverseAllows=_[`${G.id}Allows`].bind(_),G.isRoot()&&!G.allowsRequiresContext)G.allows=G.traverseAllows;if(G.traverseApply=_[`${G.id}Apply`].bind(_),_[`${G.id}Optimistic`])G.traverseOptimistic=_[`${G.id}Optimistic`].bind(_);G.precompilation=Z}},W9=(X)=>new u2().return(X.reduce((Y,Z)=>{let _=new y8({kind:"Allows"}).indent();Z.compile(_);let G=_.write(`${Z.id}Allows`),W=new y8({kind:"Apply"}).indent();Z.compile(W);let $=W.write(`${Z.id}Apply`),H=`${Y}${G},
|
|
44
|
+
${$},
|
|
45
|
+
`;if(!Z.hasKind("union"))return H;let Q=new y8({kind:"Allows",optimistic:!0}).indent();Z.compile(Q);let J=Q.write(`${Z.id}Optimistic`);return`${H}${J},
|
|
46
46
|
`},`{
|
|
47
|
-
`)+"}");class X6{config;resolvedConfig;name;get[Y1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Y,Z){if(this.config=p2(I.config,Z),this.resolvedConfig=p2(I.resolvedConfig,Z),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(zZ).length}`,this.name in zZ)A(`A Scope already named ${this.name} already exists`);zZ[this.name]=this;let X=Object.entries(Y).map((G)=>this.preparseOwnAliasEntry(...G));for(let[G,_]of X){let $=G;if(G[0]==="#"){if($=G.slice(1),$ in this.aliases)A(aG($));this.aliases[$]=_}else{if($ in this.aliases)A(aG(G));this.aliases[$]=_,this.exportedNames.push($)}if(!y(_,"module")&&!y(_,"generic")&&!E4(_)){let W=this.preparseOwnDefinitionFormat(_,{alias:$});this.resolutions[$]=y(W,"root")?this.bindReference(W):this.createParseContext(W).id}}eG??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[eG.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=I.intrinsic?o(I.intrinsic,(G,_)=>G.startsWith("json")?[]:[G,this.bindReference(_)]):{}}cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Y){return Y}generic=(...Y)=>{let Z=this;return(X,G)=>new M4(Y,G?new n8(X):X,Z,Z,G??null)};units=(Y,Z)=>{let X=[];for(let _ of Y)if(!X.includes(_))X.push(_);let G=X.map((_)=>this.node("unit",{unit:_},Z));return this.node("union",G,{...Z,prereduced:!0})};lazyResolutions=[];lazilyResolve(Y,Z){let X=this.node("alias",{reference:Z??"synthetic",resolve:Y},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(Y,Z)=>this.finalize(this.parseSchema(Y,Z));parseSchema=(Y,Z)=>this.node(c2(Y),Y,Z);preparseNode(Y,Z,X){let G=typeof Y==="string"?Y:c2(Z,Y);if(D0(Z)&&Z.kind===G)return Z;if(G==="alias"&&!X?.prereduced){let{reference:W}=s2.implementation.normalize(Z,this);if(W.startsWith("$")){let H=this.resolveRoot(W.slice(1));Z=H,G=H.kind}}else if(G==="union"&&W1(Z,"object")){let W=rQ(Z);if(W?.length===1)Z=W[0],G=c2(Z)}if(D0(Z)&&Z.kind===G)return Z;let $=_2[G].normalize?.(Z,this)??Z;if(D0($))return $.kind===G?$:sQ(G,$.kind);return{...X,$:this,kind:G,def:$,prefix:X.alias??G}}bindReference(Y){let Z;if(D0(Y))Z=Y.$===this?Y:new Y.constructor(Y.attachments,this);else Z=Y.$===this?Y:new M4(Y.params,Y.bodyDef,Y.$,this,Y.hkt);if(!this.resolved)Object.assign(this.referencesById,Z.referencesById);return Z}resolveRoot(Y){return this.maybeResolveRoot(Y)??A(EZ(Y))}maybeResolveRoot(Y){let Z=this.maybeResolve(Y);if(y(Z,"generic"))return;return Z}maybeResolveSubalias(Y){return UZ(this.aliases,Y)??UZ(this.ambient,Y)}get ambient(){return I.ambient}maybeResolve(Y){let Z=this.resolutions[Y];if(Z){if(typeof Z!=="string")return this.bindReference(Z);let G=Z1[Z];if(y(G,"root"))return this.resolutions[Y]=G;if(y(G,"context")){if(G.phase==="resolving")return this.node("alias",{reference:`$${Y}`},{prereduced:!0});if(G.phase==="resolved")return G0(`Unexpected resolved context for was uncached by its scope: ${i(G)}`);G.phase="resolving";let _=this.bindReference(this.parseOwnDefinitionFormat(G.def,G));return G.phase="resolved",Z1[_.id]=_,Z1[G.id]=_,this.resolutions[Y]=_}return G0(`Unexpected nodesById entry for ${Z}: ${i(G)}`)}let X=this.aliases[Y]??this.ambient?.[Y];if(!X)return this.maybeResolveSubalias(Y);if(X=this.normalizeRootScopeValue(X),y(X,"generic"))return this.resolutions[Y]=this.bindReference(X);if(y(X,"module")){if(!X.root)A(W9(Y));return this.resolutions[Y]=this.bindReference(X.root)}return this.resolutions[Y]=this.parse(X,{alias:Y})}createParseContext(Y){let Z=Y.id??iY(Y.prefix);return Z1[Z]=Object.assign(Y,{[Y1]:"context",$:this,id:Z,phase:"unresolved"})}traversal(Y){return new x1(Y,this.resolvedConfig)}import(...Y){return new H2(o(this.export(...Y),(Z,X)=>[`#${Z}`,X]))}precompilation;_exportedResolutions;_exports;export(...Y){if(!this._exports){this._exports={};for(let X of this.exportedNames){let G=this.aliases[X];this._exports[X]=y(G,"module")?QZ(G,this):Y9(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=$9(this,this._exports),this._json=_9(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=G9(this.references);this.precompilation=X.write(Z9,4),X9(this.references,X)}this.resolved=!0}let Z=Y.length?Y:this.exportedNames;return new H2(o(Z,(X,G)=>[G,this._exports[G]]))}resolve(Y){return this.export()[Y]}node=(Y,Z,X={})=>{let G=this.preparseNode(Y,Z,X);if(D0(G))return this.bindReference(G);let _=this.createParseContext(G),$=nY(_),W=this.bindReference($);return Z1[_.id]=W};parse=(Y,Z={})=>this.finalize(this.parseDefinition(Y,Z));parseDefinition(Y,Z={}){if(y(Y,"root"))return this.bindReference(Y);let X=this.preparseOwnDefinitionFormat(Y,Z);if(y(X,"root"))return this.bindReference(X);let G=this.createParseContext(X);Z1[G.id]=G;let _=this.bindReference(this.parseOwnDefinitionFormat(Y,G));if(_.isCyclic)_=TG(_,G.id);return Z1[G.id]=_,_}finalize(Y){if(Y9(Y),!Y.precompilation&&!this.resolvedConfig.jitless)tQ(Y.references);return Y}}class FZ extends X6{parseOwnDefinitionFormat(Y,Z){return nY(Z)}preparseOwnDefinitionFormat(Y,Z){return this.preparseNode(c2(Y),Y,Z)}preparseOwnAliasEntry(Y,Z){return[Y,Z]}normalizeRootScopeValue(Y){return Y}}var Y9=(Y)=>{let Z=Y.references.filter((X)=>X.hasKind("alias"));for(let X of Z){Object.assign(X.referencesById,X.resolution.referencesById);for(let G of Y.references)if(X.id in G.referencesById)Object.assign(G.referencesById,X.referencesById)}return Y},_9=(Y)=>o(Y,(Z,X)=>[Z,y(X,"root")||y(X,"generic")?X.json:y(X,"module")?_9(X):G0(`Unexpected resolution ${i(X)}`)]),UZ=(Y,Z)=>{let X=Z.indexOf(".");if(X===-1)return;let G=Z.slice(0,X),_=Y[G];if(_===void 0)return;if(!y(_,"module"))return A(aQ(G));let $=Z.slice(X+1),W=_[$];if(W===void 0)return UZ(_,$);if(y(W,"root")||y(W,"generic"))return W;if(y(W,"module"))return W.root??A(W9(Z));G0(`Unexpected resolution for alias '${Z}': ${i(W)}`)},G6=(Y,Z)=>new FZ(Y,Z),e2=new FZ({});var $9=(Y,Z)=>{let X={};for(let G in Z){let _=Z[G];if(y(_,"module")){let $=$9(Y,_),W=o($,(H,Q)=>[`${G}.${H}`,Q]);Object.assign(X,W)}else if(y(_,"root")||y(_,"generic"))X[G]=_;else G0(`Unexpected scope resolution ${i(_)}`)}return X},EZ=(Y)=>`'${Y}' is unresolvable`,aQ=(Y)=>`'${Y}' must reference a module to be accessed using dot syntax`,W9=(Y)=>`Reference to submodule '${Y}' must specify an alias`;e2.export();var{schema:H0,node:J2,defineSchema:cR,generic:K1}=e2;var VZ="^(?:0|[1-9]\\d*)$",eQ=new RegExp(VZ),iR=T0(eQ);var H9=G6({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();I.intrinsic={...H9};var J9=G6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:VZ}},{prereducedAliases:!0}).export();Object.assign(I.intrinsic,J9);var Yz=G6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),u={...H9,...J9,...Yz,emptyStructure:J2("structure",{},{prereduced:!0})};I.intrinsic={...u};var z9=(Y)=>typeof Y==="string"&&Y[0]==="d"&&(Y[1]==="'"||Y[1]==='"')&&Y.at(-1)===Y[1],Q9=(Y)=>Y.toString()!=="Invalid Date",U9=(Y)=>Y.slice(2,-1),OZ=(Y)=>`'${Y}' could not be parsed by the Date constructor`,F9=(Y,Z)=>Zz(Y,Z),Zz=(Y,Z)=>{let X=new Date(Y);if(Q9(X))return X;let G=cX(Y);if(G!==void 0){let _=new Date(G);if(Q9(_))return _}return Z?A(Z===!0?OZ(Y):Z):void 0};var DZ=(Y,Z)=>{let X=Y.scanner.shiftUntil(Xz[V9[Z]]);if(Y.scanner.lookahead==="")return Y.error(_z(X,Z));if(Y.scanner.shift(),Z==="/"){try{new RegExp(X)}catch(G){A(String(G))}Y.root=Y.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(g0(Z,LZ))Y.root=Y.ctx.$.node("unit",{unit:X});else{let G=F9(X,OZ(X));Y.root=Y.ctx.$.node("unit",{meta:X,unit:G})}},LZ={"'":1,'"':1},E9={"/":1,"'":1,'"':1},V9={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},Xz={"'":(Y)=>Y.lookahead==="'",'"':(Y)=>Y.lookahead==='"',"/":(Y)=>Y.lookahead==="/"},Gz={'"':"double-quote","'":"single-quote","/":"forward slash"},_z=(Y,Z)=>`${Z}${Y} requires a closing ${Gz[V9[Z]]}`;var O9=(Y)=>`Private type references should not include '#'. Use '${Y}' instead.`,_6="Optional definitions like 'string?' are only valid as properties in an object or tuple",$6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var D9={">":!0,">=":!0},L9={"<":!0,"<=":!0};var Q2={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},M9=(Y)=>`Unmatched )${Y===""?"":` before ${Y}`}`,W6=(Y)=>`Missing ${Y}`,A9=(Y,Z)=>`Left bounds are only valid when paired with right bounds (try ...${Z}${Y})`,H6=(Y)=>`Left-bounded expressions must specify their limits using < or <= (was ${Y})`,R9=(Y,Z,X,G)=>`An expression may have at most one left bound (parsed ${Y}${Q2[Z]}, ${X}${Q2[G]})`;var w9=(Y,Z,X)=>N9(Y,Z,X,[]),N9=(Y,Z,X,G)=>{let _=X.parseUntilFinalizer();if(G.push(_.root),_.finalizer===">"){if(G.length!==Z.params.length)return X.error(MZ(Y,Z.names,G.map(($)=>$.expression)));return G}if(_.finalizer===",")return N9(Y,Z,X,G);return _.error(W6(">"))},MZ=(Y,Z,X)=>`${Y}<${Z.join(", ")}> requires exactly ${Z.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var AZ=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator();if(Z==="keyof")Y.addPrefix("keyof");else Y.root=Wz(Y,Z)},$z=(Y,Z,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(MZ(Y,Z.names,[]));let _=w9(Y,Z,X);return Z(..._)},Wz=(Y,Z)=>Hz(Y,Z)??Jz(Y,Z)??Y.error(Z===""?Y.scanner.lookahead==="#"?O9(Y.shiftedByOne().scanner.shiftUntilNextTerminator()):RZ(Y):EZ(Z)),Hz=(Y,Z)=>{if(Y.ctx.args?.[Z]){let G=Y.ctx.args[Z];if(typeof G!=="string")return G;return Y.ctx.$.node("alias",{reference:G},{prereduced:!0})}let X=Y.ctx.$.maybeResolve(Z);if(y(X,"root"))return X;if(X===void 0)return;if(y(X,"generic"))return $z(Z,X,Y);return A(`Unexpected resolution ${i(X)}`)},Jz=(Y,Z)=>{let X=lX(Z);if(X!==void 0)return Y.ctx.$.node("unit",{unit:X});let G=iX(Z);if(G!==void 0)return Y.ctx.$.node("unit",{unit:G})},RZ=(Y)=>{let Z=Y.previousOperator();return Z?wZ(Z,Y.scanner.unscanned):Qz(Y.scanner.unscanned)},wZ=(Y,Z="")=>`Token '${Y}' requires a right operand${Z?` before '${Z}'`:""}`,Qz=(Y)=>`Expected an expression${Y?` before '${Y}'`:""}`;var NZ=(Y)=>Y.scanner.lookahead===""?Y.error(RZ(Y)):Y.scanner.lookahead==="("?Y.shiftedByOne().reduceGroupOpen():Y.scanner.lookaheadIsIn(E9)?DZ(Y,Y.scanner.shift()):Y.scanner.lookaheadIsIn(V4)?NZ(Y.shiftedByOne()):Y.scanner.lookahead==="d"?Y.scanner.nextLookahead in LZ?DZ(Y,`${Y.scanner.shift()}${Y.scanner.shift()}`):AZ(Y):AZ(Y);class G4 extends CY{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in G4.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...V4};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(Y,Z)=>Y===">"?Z[0]==="="?Z[1]==="=":Z.trimStart()===""||g0(Z.trimStart()[0],G4.terminatingChars):Y==="="?Z[0]!=="=":Y===","||Y==="?"}var K9=(Y,Z)=>{let X=zz(Y,Z);if(Y.root.hasKind("unit")){if(typeof Y.root.unit==="number"){Y.reduceLeftBound(Y.root.unit,X),Y.unsetRoot();return}if(Y.root.unit instanceof Date){let G=`d'${Y.root.description??Y.root.unit.toISOString()}'`;Y.unsetRoot(),Y.reduceLeftBound(G,X);return}}return Fz(Y,X)},B9={"<":1,">":1,"=":1},zz=(Y,Z)=>Y.scanner.lookaheadIs("=")?`${Z}${Y.scanner.shift()}`:Z;var I9=(Y,Z,X,G)=>{if(X.extends(I.intrinsic.number)){if(typeof Z!=="number")return A(IZ(Y,Z,G));return Y==="=="?["min","max"]:Y[0]===">"?["min"]:["max"]}if(X.extends(I.intrinsic.lengthBoundable)){if(typeof Z!=="number")return A(IZ(Y,Z,G));return Y==="=="?["exactLength"]:Y[0]===">"?["minLength"]:["maxLength"]}if(X.extends(I.intrinsic.Date))return Y==="=="?["after","before"]:Y[0]===">"?["after"]:["before"];return A(EG(X.expression))},Uz=(Y)=>({rule:z9(Y.limit)?U9(Y.limit):Y.limit,exclusive:Y.comparator.length===1}),Fz=(Y,Z)=>{let X=Y.unsetRoot(),G=Y.scanner.location;Y.parseOperand();let _=Y.unsetRoot(),$=Y.scanner.sliceChars(G,Y.scanner.location);if(Y.root=X,!_.hasKind("unit")||typeof _.unit!=="number"&&!(_.unit instanceof Date))return Y.error(IZ(Z,$,"right"));let W=_.unit,H=Z.length===1,Q=I9(Z,typeof W==="number"?W:$,X,"right");for(let z of Q)Y.constrainRoot(z,Z==="=="?{rule:W}:{rule:W,exclusive:H});if(!Y.branches.leftBound)return;if(!g0(Z,L9))return Y.error(H6(Z));let J=I9(Y.branches.leftBound.comparator,Y.branches.leftBound.limit,X,"left");Y.constrainRoot(J[0],Uz(Y.branches.leftBound)),Y.branches.leftBound=null},IZ=(Y,Z,X)=>`Comparator ${X==="left"?Q2[Y]:Y} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Z})`;var T9=(Y)=>{Y.scanner.shiftUntilNonWhitespace();let Z=Y.scanner.shiftUntilNextTerminator();Y.root=Y.root.brand(Z)};var q9=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator(),X=oX(Z,{errorOnFail:C9(Z)});if(X===0)Y.error(C9(0));Y.root=Y.root.constrain("divisor",X)},C9=(Y)=>`% operator must be followed by a non-zero integer literal (was ${Y})`;var KZ=(Y)=>{let Z=Y.scanner.shift();return Z===""?Y.finalize(""):Z==="["?Y.scanner.shift()==="]"?Y.setRoot(Y.root.array()):Y.error(Ez):Z==="|"?Y.scanner.lookahead===">"?Y.shiftedByOne().pushRootToBranch("|>"):Y.pushRootToBranch(Z):Z==="&"?Y.pushRootToBranch(Z):Z===")"?Y.finalizeGroup():G4.lookaheadIsFinalizing(Z,Y.scanner.unscanned)?Y.finalize(Z):g0(Z,B9)?K9(Y,Z):Z==="%"?q9(Y):Z==="#"?T9(Y):(Z in V4)?KZ(Y):Y.error(J6(Z))},J6=(Y,Z="")=>`'${Y}' is not allowed here${Z&&` (should be ${Z})`}`,Ez="Missing expected ']'";var j9=(Y)=>{let Z=Y.unsetRoot();Y.parseOperand();let X=Y.unsetRoot();if(!X.hasKind("unit"))return Y.error(Vz(X.expression));let G=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Z,"=",G]},Vz=(Y)=>`Default value '${Y}' must a literal value`;var BZ=(Y,Z)=>{let X=Z.$.maybeResolveRoot(Y);if(X)return X;if(Y.endsWith("[]")){let $=Z.$.maybeResolveRoot(Y.slice(0,-2));if($)return $.array()}let G=new z2(new G4(Y),Z),_=Oz(G);if(G.finalizer===">")A(J6(">"));return _},Oz=(Y)=>{Y.parseOperand();let Z=Y8(Y).root;if(!Z)return G0(`Root was unexpectedly unset after parsing string '${Y.scanner.scanned}'`);if(Y.finalizer==="=")Z=j9(Y);else if(Y.finalizer==="?")Z=[Z,"?"];if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.lookahead)A(J6(Y.scanner.lookahead));return Z},Y8=(Y)=>{while(Y.finalizer===void 0)Dz(Y);return Y},Dz=(Y)=>Y.hasRoot()?Y.parseOperator():Y.parseOperand();class z2{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Y,Z){this.scanner=Y,this.ctx=Z}error(Y){return A(Y)}hasRoot(){return this.root!==void 0}setRoot(Y){this.root=Y}unsetRoot(){let Y=this.root;return this.root=void 0,Y}constrainRoot(...Y){this.root=this.root.constrain(Y[0],Y[1])}finalize(Y){if(this.groups.length)return this.error(W6(")"));this.finalizeBranches(),this.finalizer=Y}reduceLeftBound(Y,Z){let X=Q2[Z];if(!g0(X,D9))return this.error(H6(Z));if(this.branches.leftBound)return this.error(R9(this.branches.leftBound.limit,this.branches.leftBound.comparator,Y,X));this.branches.leftBound={comparator:X,limit:Y}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let Y=this.groups.pop();if(!Y)return this.error(M9(this.scanner.unscanned));this.branches=Y}addPrefix(Y){this.branches.prefixes.push(Y)}applyPrefixes(){while(this.branches.prefixes.length){let Y=this.branches.prefixes.pop();this.root=Y==="keyof"?this.root.keyof():G0(`Unexpected prefix '${Y}'`)}}pushRootToBranch(Y){this.assertRangeUnset(),this.applyPrefixes();let Z=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(Z)??Z,Y==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Y==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return Y8(new z2(this.scanner,this.ctx))}parseOperator(){return KZ(this)}parseOperand(){return NZ(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(A9(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var Lz="An empty string is not a valid generic parameter name",Q6=(Y,Z,X)=>{Y.shiftUntilNonWhitespace();let G=Y.shiftUntilNextTerminator();if(G===""){if(Y.lookahead===""&&Z.length)return Z;return A(Lz)}return Y.shiftUntilNonWhitespace(),Mz(Y,G,Z,X)},P9="extends ",Mz=(Y,Z,X,G)=>{if(Y.shiftUntilNonWhitespace(),Y.unscanned.startsWith(P9))Y.jumpForward(P9.length);else{if(Y.lookahead===",")Y.shift();return X.push(Z),Q6(Y,X,G)}let _=Y8(new z2(Y,G));return X.push([Z,_.root]),Q6(Y,X,G)};class TZ extends v1{$;constructor(Y){super((...Z)=>new Z8(Y)(...Z),{bind:Y});this.$=Y}in(Y){return new Z8(this.$,Y===void 0?void 0:this.$.parse(Y))}at(Y,Z){return new Z8(this.$).at(Y,Z)}case(Y,Z){return new Z8(this.$).case(Y,Z)}}class Z8 extends v1{$;in;key;branches=[];constructor(Y,Z){super((X)=>this.caseEntries(Object.entries(X).map(([G,_])=>G==="default"?[G,_]:[this.$.parse(G),_])));this.$=Y,this.in=Z}at(Y,Z){if(this.key)A(Rz);if(this.branches.length)A(Az);return this.key=Y,Z?this.match(Z):this}case(Y,Z){return this.caseEntry(this.$.parse(Y),Z)}caseEntry(Y,Z){let G=(this.key?this.$.parse({[this.key]:Y}):Y).pipe(Z);return this.branches.push(G),this}match(Y){return this(Y)}strings(Y){return this.caseEntries(Object.entries(Y).map(([Z,X])=>Z==="default"?[Z,X]:[this.$.node("unit",{unit:Z}),X]))}caseEntries(Y){for(let Z=0;Z<Y.length;Z++){let[X,G]=Y[Z];if(X==="default"){if(Z!==Y.length-1)A("default may only be specified as the last key of a switch definition");return this.default(G)}if(typeof G!=="function")return A(`Value for case "${X}" must be a function (was ${y0(G)})`);this.caseEntry(X,G)}return this}default(Y){if(typeof Y==="function")this.case(u.unknown,Y);let Z={branches:this.branches,ordered:!0};if(Y==="never"||Y==="assert")Z.meta={onFail:S9};let X=this.$.node("union",Z);if(!this.in)return this.$.finalize(X);let G=this.in.pipe(X);if(Y==="never"||Y==="assert")G=G.configureReferences({onFail:S9},"self");return this.$.finalize(G)}}var S9=(Y)=>Y.throw(),Az="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",Rz="At most one key matcher may be specified per expression";var z6=(Y,Z)=>{if(U0(Y)){if(Y[1]==="=")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"=",Y[2]];if(Y[1]==="?")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"?"]}return U6(Y,Z)},v9="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",x9="Only required keys may specify default values, e.g. { value: 'number = 0' }";var f9=(Y,Z)=>{let X,G={},_=q4(Y);for(let[W,H]of _){let Q=Iz(W);if(Q.kind==="spread"){if(!l1(G))return A(Nz);let L=Z.$.parseOwnDefinitionFormat(H,Z);if(L.equals(u.object))continue;if(!L.hasKind("intersection")||!L.basis?.equals(u.object))return A(Kz(L.expression));X=L.structure;continue}if(Q.kind==="undeclared"){if(H!=="reject"&&H!=="delete"&&H!=="ignore")A(wz(H));G.undeclared=H;continue}let J=z6(H,Z),z=Q;if(Q.kind==="required"){if(!U0(J))CZ(G,"required",{key:Q.normalized,value:J},Z);else CZ(G,"optional",J[1]==="="?{key:Q.normalized,value:J[0],default:J[2]}:{key:Q.normalized,value:J[0]},Z);continue}if(U0(J)){if(J[1]==="?")A(v9);if(J[1]==="=")A(x9)}if(Q.kind==="optional"){CZ(G,"optional",{key:Q.normalized,value:J},Z);continue}let F=Z.$.parseOwnDefinitionFormat(z.normalized,Z),O=Z6(F,J,Z.$);if(O.index)G.index=Z0(G.index,O.index);if(O.required)G.required=Z0(G.required,O.required)}let $=Z.$.node("structure",G);return Z.$.parseSchema({domain:"object",structure:X?.merge($)??$})},CZ=(Y,Z,X,G)=>{Y[Z]=Z0(Y[Z],G.$.node(Z,X))},wz=(Y)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${i(Y)})`,Nz="Spread operator may only be used as the first key in an object",Iz=(Y)=>typeof Y==="symbol"?{kind:"required",normalized:Y}:Y.at(-1)==="?"?Y.at(-2)===x2?{kind:"required",normalized:`${Y.slice(0,-2)}?`}:{kind:"optional",normalized:Y.slice(0,-1)}:Y[0]==="["&&Y.at(-1)==="]"?{kind:"index",normalized:Y.slice(1,-1)}:Y[0]===x2&&Y[1]==="["&&Y.at(-1)==="]"?{kind:"required",normalized:Y.slice(1)}:Y==="..."?{kind:"spread"}:Y==="+"?{kind:"undeclared"}:{kind:"required",normalized:Y==="\\..."?"...":Y==="\\+"?"+":Y},Kz=(Y)=>`Spread operand must resolve to an object literal type (was ${Y})`;var k9=(Y,Z)=>fz(Y)?p9[Y[0]](Y,Z):vz(Y)?g9[Y[1]](Y,Z):null,Bz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[1],Z).keyof(),qZ=(Y,Z)=>{if(Y[2]===void 0)return A(wZ(Y[1],""));let X=Z.$.parseOwnDefinitionFormat(Y[0],Z),G=Z.$.parseOwnDefinitionFormat(Y[2],Z);if(Y[1]==="|")return Z.$.node("union",{branches:[X,G]});let _=Y[1]==="&"?z1(X,G,Z.$):d2(X,G,Z.$);if(_ instanceof S)return _.throw();return _},Tz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).array(),Cz=(Y,Z)=>{if(typeof Y[2]!=="function")return A(b9("=>",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).pipe(Y[2])},b9=(Y,Z)=>`${Y===":"?"Narrow":"Morph"} expression requires a function following '${Y}' (was ${typeof Z})`,qz=(Y,Z)=>{if(typeof Y[2]!=="function")return A(b9(":",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).constrain("predicate",Y[2])},jz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).configureReferences(Y[2],"shallow"),y9=(Y)=>Y,Pz=y9({"[]":Tz,"?":()=>A(_6)}),Sz=y9({"|":qZ,"&":qZ,":":qz,"=>":Cz,"|>":qZ,"@":jz,"=":()=>A($6)}),g9={...Pz,...Sz},vz=(Y)=>g9[Y[1]]!==void 0,xz=(Y)=>Y,p9=xz({keyof:Bz,instanceof:(Y,Z)=>{if(typeof Y[1]!=="function")return A(h9(S2(Y[1])));let X=Y.slice(1).map((G)=>typeof G==="function"?Z.$.node("proto",{proto:G}):A(h9(S2(G))));return X.length===1?X[0]:Z.$.node("union",{branches:X})},"===":(Y,Z)=>Z.$.units(Y.slice(1))}),fz=(Y)=>p9[Y[0]]!==void 0,h9=(Y)=>`Expected a constructor following 'instanceof' operator (was ${Y})`;var d9=(Y,Z)=>{let X=[{}],G=0;while(G<Y.length){let _=!1;if(Y[G]==="..."&&G<Y.length-1)_=!0,G++;let $=z6(Y[G],Z),[W,H,Q]=!U0($)?[$]:$;if(G++,_){if(!W.extends(I.intrinsic.Array))return A(bz(W.expression));X=X.flatMap((J)=>W.distribute((z)=>kz(c8(J),z)))}else X=X.map((J)=>{if(H==="?")return c9(J,W);if(H==="=")return hz(J,W,Q);return jZ(J,W)})}return Z.$.parseSchema(X.map((_)=>l1(_)?{proto:Array,exactLength:0}:{proto:Array,sequence:_}))},jZ=(Y,Z)=>{if(Y.defaultables||Y.optionals)return A(Y.variadic?WZ:yz);if(Y.variadic)Y.postfix=Z0(Y.postfix,Z);else Y.prefix=Z0(Y.prefix,Z);return Y},c9=(Y,Z)=>{if(Y.variadic)return A(l9);return Y.optionals=Z0(Y.optionals,Z),Y},hz=(Y,Z,X)=>{if(Y.variadic)return A(l9);if(Y.optionals)return A(gz);return Y.defaultables=Z0(Y.defaultables,[[Z,X]]),Y},m9=(Y,Z)=>{if(Y.postfix)A(u9);if(Y.variadic){if(!Y.variadic.equals(Z))A(u9)}else Y.variadic=Z.internal;return Y},kz=(Y,Z)=>{let X=Z.select({method:"find",kind:"sequence"});if(!X)return m9(Y,I.intrinsic.unknown);if(X.prefix)for(let G of X.prefix)jZ(Y,G);if(X.optionals)for(let G of X.optionals)c9(Y,G);if(X.variadic)m9(Y,X.variadic);if(X.postfix)for(let G of X.postfix)jZ(Y,G);return Y},bz=(Y)=>`Spread element must be an array (was ${Y})`,u9="A tuple may have at most one variadic element",yz="A required element may not follow an optional element",l9="An optional element may not follow a variadic element";var gz="A defaultable element may not follow an optional element without a default";var pz={},U6=(Y,Z)=>{if(typeof Y==="string"){if(Z.args&&Object.keys(Z.args).some((G)=>Y.includes(G)))return BZ(Y,Z);let X=pz[Z.$.name]??={};return X[Y]??=BZ(Y,Z)}return W1(Y,"object")?mz(Y,Z):A(PZ(y0(Y)))},mz=(Y,Z)=>{let X=P2(Y);switch(X){case void 0:if(y(Y,"root"))return Y;return f9(Y,Z);case"Array":return uz(Y,Z);case"RegExp":return Z.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0});case"Function":{let G=E4(Y)?Y():Y;if(y(G,"root"))return G;return A(PZ("Function"))}default:return A(PZ(X??i(Y)))}},uz=(Y,Z)=>k9(Y,Z)??d9(Y,Z),PZ=(Y)=>`Type definitions must be strings or objects (was ${Y})`;class SZ extends v1{constructor(Y){let Z=Object.assign({errors:J1,hkt:r0,$:Y,raw:Y.parse,module:Y.constructor.module,scope:Y.constructor.scope,define:Y.define,match:Y.match,generic:Y.generic,schema:Y.schema,keywords:Y.ambient,unit:Y.unit,enumerated:Y.enumerated,instanceOf:Y.instanceOf,valueOf:Y.valueOf,or:Y.or,and:Y.and,merge:Y.merge,pipe:Y.pipe},Y.ambientAttachments);super((...X)=>{if(X.length===1)return Y.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0].at(-1)===">"){let G=X[0].slice(1,-1),_=Y.parseGenericParams(G,{});return new M4(_,X[1],Y,Y,null)}return Y.parse(X)},{bind:Y,attach:Z})}}var U2=I;class F6 extends X6{get ambientAttachments(){if(!U2.typeAttachments)return;return this.cacheGetter("ambientAttachments",o(U2.typeAttachments,(Y,Z)=>[Y,this.bindReference(Z)]))}preparseOwnAliasEntry(Y,Z){let X=Y.indexOf("<");if(X===-1){if(y(Z,"module")||y(Z,"generic"))return[Y,Z];let $=this.name==="ark"?Y:Y==="root"?this.name:`${this.name}.${Y}`,W=this.resolvedConfig.keywords?.[$];if(W)Z=[Z,"@",W];return[Y,Z]}if(Y.at(-1)!==">")A("'>' must be the last character of a generic declaration in a scope");let G=Y.slice(0,X),_=Y.slice(X+1,-1);return[G,()=>{let $=this.parseGenericParams(_,{alias:G});return zG($,Z,this)}]}parseGenericParams(Y,Z){return Q6(new G4(Y),[],this.createParseContext({...Z,def:Y,prefix:"generic"}))}normalizeRootScopeValue(Y){if(E4(Y)&&!y(Y,"generic"))return Y();return Y}preparseOwnDefinitionFormat(Y,Z){return{...Z,def:Y,prefix:Z.alias??"type"}}parseOwnDefinitionFormat(Y,Z){if(!(Z.alias&&(Z.alias in this.aliases))&&!Z.args)Z.args={this:Z.id};let G=U6(Y,Z);if(U0(G)){if(G[1]==="=")return A($6);if(G[1]==="?")return A(_6)}return G}unit=(Y)=>this.units([Y]);valueOf=(Y)=>this.units(PX(Y));enumerated=(...Y)=>this.units(Y);instanceOf=(Y)=>this.node("proto",{proto:Y},{prereduced:!0});or=(...Y)=>this.schema(Y.map((Z)=>this.parse(Z)));and=(...Y)=>Y.reduce((Z,X)=>Z.and(this.parse(X)),this.intrinsic.unknown);merge=(...Y)=>Y.reduce((Z,X)=>Z.merge(this.parse(X)),this.intrinsic.object);pipe=(...Y)=>this.intrinsic.unknown.pipe(...Y);match=new TZ(this);declare=()=>({type:this.type});define(Y){return Y}type=new SZ(this);static scope=(Y,Z={})=>new F6(Y,Z);static module=(Y,Z={})=>this.scope(Y,Z).export()}var vZ=Object.assign(F6.scope,{define:(Y)=>Y}),e=F6;class o9 extends r0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var dz=K1(["base",u.object],["props",u.object])((Y)=>Y.base.merge(Y.props),o9),i9=e.module({Key:u.key,Merge:dz});class n9 extends r0{}var cz=K1("element")((Y)=>{let Z=Y.element.exclude(u.Array),X=Z.array();return Z.rawOr(X).pipe(F4).distribute((G)=>G.assertHasKind("morph").declareOut(X),H0)},n9),r9=e.module({root:u.Array,readonly:"root",index:u.nonNegativeIntegerString,liftFrom:cz},{name:"Array"});var xZ=H0(["string",P4.FileConstructor]),lz=xZ.rawOr(xZ.array()),s9=H0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:lz}}),t9=e.module({root:["instanceof",FormData],value:xZ,parsed:s9,parse:H0({in:FormData,morphs:(Y)=>{let Z={};for(let[X,G]of Y)if(X in Z){let _=Z[X];if(typeof _==="string"||_ instanceof P4.FileConstructor)Z[X]=[_,G];else _.push(G)}else Z[X]=G;return Z},declaredOut:s9})},{name:"FormData"});var a9=e.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var oz={Boolean:1,Number:1,String:1},e9=e.module({...o({...AY,...wY},(Y,Z)=>(Y in oz)?[]:[Y,["instanceof",Z]]),Array:r9,TypedArray:a9,FormData:t9});var iz=H0({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),nz=H0({domain:"number",divisor:1}),E6=e.module({root:u.number,integer:nz,epoch:iz,safe:H0({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var N0=(Y,Z,X)=>{let G={domain:"string",pattern:{rule:Y.source,flags:Y.flags,meta:Z}};if(X)G.meta={format:X};return J2("intersection",G)},Y_=N0(f2,"a well-formed integer string"),F_=e.module({root:Y_,parse:H0({in:Y_,morphs:(Y,Z)=>{let X=Number.parseInt(Y);return Number.isSafeInteger(X)?X:Z.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:u.integer})},{name:"string.integer"}),rz=N0(/^[\dA-Fa-f]+$/,"hex characters only"),sz=e.module({root:N0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:N0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),Z_=N0(/^[A-Z].*$/,"capitalized"),tz=e.module({root:H0({in:"string",morphs:(Y)=>Y.charAt(0).toUpperCase()+Y.slice(1),declaredOut:Z_}),preformatted:Z_},{name:"string.capitalize"}),az=(Y)=>{let Z=Y.replaceAll(/[ -]+/g,""),X=0,G,_,$=!1;for(let W=Z.length-1;W>=0;W--){if(G=Z.substring(W,W+1),_=Number.parseInt(G,10),$)_*=2,X+=_>=10?_%10+1:_;else X+=_;$=!$}return!!(X%10===0?Z:!1)},ez=/^(?: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}))$/,YU=H0({domain:"string",pattern:{meta:"a credit card number",rule:ez.source},predicate:{meta:"a credit card number",predicate:az}});var ZU=/^([+-]?\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 XU=(Y)=>!Number.isNaN(new Date(Y).valueOf()),X_=H0({domain:"string",predicate:{meta:"a parsable date",predicate:XU}}).assertHasKind("intersection"),G_=F_.root.internal.narrow((Y,Z)=>{let X=Number.parseInt(Y),G=E6.epoch(X);if(G instanceof J1)return Z.errors.merge(G),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),GU=e.module({root:G_,parse:H0({in:G_,morphs:(Y)=>new Date(Y),declaredOut:u.Date})},{name:"string.date.epoch"}),__=N0(ZU,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),_U=e.module({root:__,parse:H0({in:__,morphs:(Y)=>new Date(Y),declaredOut:u.Date})},{name:"string.date.iso"}),$U=e.module({root:X_,parse:H0({declaredIn:X_,in:"string",morphs:(Y,Z)=>{let X=new Date(Y);if(Number.isNaN(X.valueOf()))return Z.error("a parsable date");return X},declaredOut:u.Date}),iso:_U,epoch:GU},{name:"string.date"}),WU=N0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),$_="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A4=`(${$_}[.]){3}${$_}`,HU=new RegExp(`^${A4}$`),x0="(?:[0-9a-fA-F]{1,4})",JU=new RegExp(`^((?:${x0}:){7}(?:${x0}|:)|(?:${x0}:){6}(?:${A4}|:${x0}|:)|(?:${x0}:){5}(?::${A4}|(:${x0}){1,2}|:)|(?:${x0}:){4}(?:(:${x0}){0,1}:${A4}|(:${x0}){1,3}|:)|(?:${x0}:){3}(?:(:${x0}){0,2}:${A4}|(:${x0}){1,4}|:)|(?:${x0}:){2}(?:(:${x0}){0,3}:${A4}|(:${x0}){1,5}|:)|(?:${x0}:){1}(?:(:${x0}){0,4}:${A4}|(:${x0}){1,6}|:)|(?::((?::${x0}){0,5}:${A4}|(?::${x0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),QU=e.module({root:["v4 | v6","@","an IP address"],v4:N0(HU,"an IPv4 address","ipv4"),v6:N0(JU,"an IPv6 address","ipv6")},{name:"string.ip"}),F2="a JSON string",E_=(Y)=>{if(!(Y instanceof SyntaxError))throw Y;return`must be ${F2} (${Y})`},zU=H0({meta:F2,domain:"string",predicate:{meta:F2,predicate:(Y,Z)=>{try{return JSON.parse(Y),!0}catch(X){return Z.reject({code:"predicate",expected:F2,problem:E_(X)})}}}}),UU=(Y,Z)=>{if(Y.length===0)return Z.error({code:"predicate",expected:F2,actual:"empty"});try{return JSON.parse(Y)}catch(X){return Z.error({code:"predicate",expected:F2,problem:E_(X)})}},FU=e.module({root:zU,parse:H0({meta:"safe JSON string parser",in:"string",morphs:UU,declaredOut:u.jsonObject})},{name:"string.json"}),W_=N0(/^[a-z]*$/,"only lowercase letters"),EU=e.module({root:H0({in:"string",morphs:(Y)=>Y.toLowerCase(),declaredOut:W_}),preformatted:W_},{name:"string.lower"}),V_=["NFC","NFD","NFKC","NFKD"],X8=o(V_,(Y,Z)=>[Z,H0({domain:"string",predicate:(X)=>X.normalize(Z)===X,meta:`${Z}-normalized unicode`})]),V6=o(V_,(Y,Z)=>[Z,H0({in:"string",morphs:(X)=>X.normalize(Z),declaredOut:X8[Z]})]),VU=e.module({root:V6.NFC,preformatted:X8.NFC},{name:"string.normalize.NFC"}),OU=e.module({root:V6.NFD,preformatted:X8.NFD},{name:"string.normalize.NFD"}),DU=e.module({root:V6.NFKC,preformatted:X8.NFKC},{name:"string.normalize.NFKC"}),LU=e.module({root:V6.NFKD,preformatted:X8.NFKD},{name:"string.normalize.NFKD"}),MU=e.module({root:"NFC",NFC:VU,NFD:OU,NFKC:DU,NFKD:LU},{name:"string.normalize"}),H_=N0(m8,"a well-formed numeric string"),AU=e.module({root:H_,parse:H0({in:H_,morphs:(Y)=>Number.parseFloat(Y),declaredOut:u.number})},{name:"string.numeric"}),J_="a regex pattern",RU=H0({domain:"string",predicate:{meta:J_,predicate:(Y,Z)=>{try{return new RegExp(Y),!0}catch(X){return Z.reject({code:"predicate",expected:J_,problem:String(X)})}}},meta:{format:"regex"}}),wU=/^(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-]+)*))?$/,NU=N0(wU,"a semantic version (see https://semver.org/)"),Q_=N0(/^\S.*\S$|^\S?$/,"trimmed"),IU=e.module({root:H0({in:"string",morphs:(Y)=>Y.trim(),declaredOut:Q_}),preformatted:Q_},{name:"string.trim"}),z_=N0(/^[A-Z]*$/,"only uppercase letters"),KU=e.module({root:H0({in:"string",morphs:(Y)=>Y.toUpperCase(),declaredOut:z_}),preformatted:z_},{name:"string.upper"}),BU=(Y)=>{if(URL.canParse)return URL.canParse(Y);try{return new URL(Y),!0}catch{return!1}},U_=H0({domain:"string",predicate:{meta:"a URL string",predicate:BU},meta:{format:"uri"}}),TU=e.module({root:U_,parse:H0({declaredIn:U_,in:"string",morphs:(Y,Z)=>{try{return new URL(Y)}catch{return Z.error("a URL string")}},declaredOut:H0(URL)})},{name:"string.url"}),CU=e.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:N0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:N0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:N0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:N0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:N0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:N0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:N0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:N0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),O_=e.module({root:u.string,alpha:N0(/^[A-Za-z]*$/,"only letters"),alphanumeric:N0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:rz,base64:sz,capitalize:tz,creditCard:YU,date:$U,digits:N0(/^\d*$/,"only digits 0-9"),email:WU,integer:F_,ip:QU,json:FU,lower:EU,normalize:MU,numeric:AU,regex:RU,semver:NU,trim:IU,upper:KU,url:TU,uuid:CU},{name:"string"});var D_=e.module({bigint:u.bigint,boolean:u.boolean,false:u.false,never:u.never,null:u.null,number:u.number,object:u.object,string:u.string,symbol:u.symbol,true:u.true,unknown:u.unknown,undefined:u.undefined}),L_=e.module({root:u.unknown,any:u.unknown},{name:"unknown"}),qU=e.module({root:u.jsonObject,stringify:J2("morph",{in:u.jsonObject,morphs:(Y)=>JSON.stringify(Y),declaredOut:u.string})},{name:"object.json"}),M_=e.module({root:u.object,json:qU},{name:"object"});class A_ extends r0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var jU=K1(["K",u.key],"V")((Y)=>({domain:"object",index:{signature:Y.K,value:Y.V}}),A_);class R_ extends r0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var PU=K1(["T",u.object],["K",u.key])((Y)=>Y.T.pick(Y.K),R_);class w_ extends r0{description='omit a set of properties from an object like `Omit(User, "age")`'}var SU=K1(["T",u.object],["K",u.key])((Y)=>Y.T.omit(Y.K),w_);class N_ extends r0{description="make all named properties of an object optional like `Partial(User)`"}var vU=K1(["T",u.object])((Y)=>Y.T.partial(),N_);class I_ extends r0{description="make all named properties of an object required like `Required(User)`"}var xU=K1(["T",u.object])((Y)=>Y.T.required(),I_);class K_ extends r0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var fU=K1("T","U")((Y)=>Y.T.exclude(Y.U),K_);class B_ extends r0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var hU=K1("T","U")((Y)=>Y.T.extract(Y.U),B_),T_=e.module({Exclude:fU,Extract:hU,Omit:SU,Partial:vU,Pick:PU,Record:jU,Required:xU});var R4=vZ({...D_,...T_,...e9,...i9,string:O_,number:E6,object:M_,unknown:L_},{prereducedAliases:!0,name:"ark"}),p0=R4.export();Object.assign(U2.ambient,p0);U2.typeAttachments={string:p0.string.root,number:p0.number.root,bigint:p0.bigint,boolean:p0.boolean,symbol:p0.symbol,undefined:p0.undefined,null:p0.null,object:p0.object.root,unknown:p0.unknown.root,false:p0.false,true:p0.true,never:p0.never,arrayIndex:p0.Array.index,Key:p0.Key,Record:p0.Record,Array:p0.Array.root,Date:p0.Date};var U1=Object.assign(R4.type,U2.typeAttachments),kU=R4.match,bU=R4.generic,OK=R4.schema,yU=R4.define,gU=R4.declare;function E2(Y){return w6(F1.STORE,Y,void 0)}function V2(Y){return O2(F1.STORE,Y)}function hZ(...Y){return h1(F1.STORE,...Y)}function O6(Y,Z){return h_(F1.STORE,Y,Z)}function C_(Y){return k_(Y,F1.STORE)}var _4={atom_family:"atom family",atom:"atom",continuity:"continuity",key:"key",mutable_atom_family:"atom family [m]",mutable_atom:"atom [m]",readonly_held_selector_family:"selector family [h]",readonly_held_selector:"selector [h]",readonly_pure_selector_family:"selector family",readonly_pure_selector:"selector",state:"state",timeline:"timeline",transaction:"transaction",unknown:"unknown",writable_held_selector_family:"selector family [wh]",writable_held_selector:"selector [wh]",writable_pure_selector_family:"selector family [w]",writable_pure_selector:"selector [w]"};var fZ=(Y)=>(Z,X,G,_,...$)=>{console[Y](`${Z} ${_4[X]} \`${G}\` ${_}`,...$)},pU={error:fZ("error"),info:fZ("info"),warn:fZ("warn")},q_=class{logLevel;filter;logger;constructor(Y,Z,X=pU){this.logLevel=Y,this.filter=Z,this.logger=X}error=(...Y)=>{if(this.logLevel!==null){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.error(...Y);else if(Z)this.logger.error(...Z)}};info=(...Y)=>{if(this.logLevel==="info"){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.info(...Y);else if(Z)this.logger.info(...Z)}};warn=(...Y)=>{if(this.logLevel!=="error"&&this.logLevel!==null){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.warn(...Y);else if(Z)this.logger.warn(...Z)}}};var j_=class{store;deallocateTX;claimTX;constructor(Y=F1.STORE){this.store=Y,this.deallocateTX=S_(Y),this.claimTX=v_(Y),P_(Y,"root")}allocate(Y,Z,X){A6(this.store,Y,Z,X)}deallocate(Y){M6(this.store,this.deallocateTX,kZ())(Y)}claim(Y,Z,X){G8(this.store,Y,Z,X)}};function D6(Y){return bZ(F1.STORE,Y)}function L6(Y){return _8(F1.STORE,Y)}function X1(Y){return JSON.parse(Y)}var Q0=(Y)=>JSON.stringify(Y),pK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var b_=class Y extends Set{mode="record";subject=new _0;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(Z,X=0){super(Z);if(Z instanceof Y)this.parent=Z,this.cacheUpdateNumber=Z.cacheUpdateNumber;if(X)this.cacheLimit=X,this.cache=Array(X),this.subscribe("auto cache",(G)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=G})}READONLY_VIEW=this;toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(Z){let X=new Y(Z.members,Z.cacheLimit);return X.cache=Z.cache,X.cacheIdx=Z.cacheIdx,X.cacheUpdateNumber=Z.cacheUpdateNumber,X}add(Z){let X=super.add(Z);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${Q0(Z)}`);return X}clear(){let Z=this.mode==="record"?[...this]:null;if(super.clear(),Z)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(Z)}`)}delete(Z){let X=super.delete(Z);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${Q0(Z)}`);return X}parent=null;child=null;transactionUpdates=null;transaction(Z){this.mode="transaction",this.transactionUpdates=[],this.child=new Y(this);let X=this.child._subscribe("transaction",(G)=>{this.transactionUpdates?.push(G)});try{if(Z(this.child)){for(let G of this.transactionUpdates)this.doStep(G);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(G){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",G),G}finally{X(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(Z,X){return this.subject.subscribe(Z,X)}subscribe(Z,X){return this.subject.subscribe(Z,(G)=>{X(`${this.cacheUpdateNumber}=${G}`)})}emit(Z){this.subject.next(Z)}doStep(Z){let X=Z.indexOf(":"),G=Z.substring(0,X),_=Z.substring(X+1);switch(G){case"add":this.add(JSON.parse(_));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(_));break;case"tx":for(let $ of _.split(";"))this.doStep($)}}getUpdateNumber(Z){let X=Z.indexOf("=");return Number(Z.substring(0,X))}do(Z){let X=Z.indexOf("="),G=Number(Z.substring(0,X)),_=G-this.cacheUpdateNumber;if(_>0||Number.isNaN(_)){if(_===1||Number.isNaN(_)){this.mode="playback";let $=Z.substring(X+1);return this.doStep($),this.mode="record",this.cacheUpdateNumber=G,null}return this.cacheUpdateNumber+1}if(Math.abs(_)<this.cacheLimit){let $=this.cacheIdx+_;if(this.cache[$]===Z)return null;this.mode="playback";let W=!1;while(!W){this.cacheIdx%=this.cacheLimit;let Q=this.cache[this.cacheIdx];if(this.cacheIdx--,!Q)return"OUT_OF_RANGE";this.undo(Q),W=this.cacheIdx===$-1}let H=Z.substring(X+1);return this.doStep(H),this.mode="record",this.cacheUpdateNumber=G,null}return"OUT_OF_RANGE"}undoStep(Z){let X=Z.indexOf(":"),G=Z.substring(0,X),_=Z.substring(X+1);switch(G){case"add":this.delete(JSON.parse(_));break;case"del":this.add(JSON.parse(_));break;case"clear":{let $=JSON.parse(_);for(let W of $)this.add(W);break}case"tx":{let $=_.split(";");for(let W=$.length-1;W>=0;W--)this.undoStep($[W])}}}undo(Z){let X=Z.indexOf("=");if(Number(Z.substring(0,X))===this.cacheUpdateNumber){this.mode="playback";let G=Z.substring(X+1);return this.undoStep(G),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}};function kZ(Y=Math.random){return Y().toString(36).slice(2)}function Y0(Y){while(Y.child!==null)Y=Y.child;return Y}function uU(Y){while(Y.parent!==null)Y=Y.parent;return Y}var dU=/^\[object (?:Async|Generator|AsyncGenerator)?Function\]$/;function H8(Y){let Z=Object.prototype.toString.call(Y);return dU.test(Z)}function mZ(Y,Z){if(H8(Y))return Y(Z);return Y}var uZ=class extends Promise{fate;resolve;reject;done=!1;constructor(Y){let Z,X;super((G,_)=>{Z=G,X=_});this.resolve=Z,this.reject=X,this.use(Y instanceof Promise?Y:new Promise(Y))}pass(Y,Z){if(Y===this.fate)this.resolve(Z),this.done=!0}fail(Y,Z){if(Y===this.fate)this.reject(Z),this.done=!0}use(Y){if(this===Y)return;if(Y instanceof Promise){let Z=Y;this.fate=Z,Z.then((X)=>{this.pass(Z,X)},(X)=>{this.fail(Z,X)})}else this.resolve(Y),this.fate=void 0}},_0=class{Subscriber;subscribers=new Map;subscribe(Y,Z){return this.subscribers.set(Y,Z),()=>{this.unsubscribe(Y)}}unsubscribe(Y){this.subscribers.delete(Y)}next(Y){let Z=this.subscribers.values();for(let X of Z)X(Y)}},cU=class extends _0{state;constructor(Y){super();this.state=Y}next(Y){this.state=Y,super.next(Y)}},lU=class Y{_buffer;_index=0;constructor(Z){let X;if(typeof Z==="number")X=Z;else X=Z.length;this._buffer=Array.from({length:X})}get buffer(){return this._buffer}get index(){return this._index}add(Z){this._buffer[this._index]=Z,this._index=(this._index+1)%this._buffer.length}copy(){let Z=new Y([...this._buffer]);return Z._index=this._index,Z}};function y1(Y){let Z={key:Y.key,type:Y.type};if("family"in Y)Z.family=Y.family;return Z}var b1=class extends Map{deleted=new Set;changed=new Set;source;constructor(Y){super();this.source=Y}get(Y){if(super.has(Y))return super.get(Y);if(!this.deleted.has(Y)&&this.source.has(Y))return this.source.get(Y)}set(Y,Z){if(this.deleted.delete(Y),this.source.has(Y))this.changed.add(Y);return super.set(Y,Z)}hasOwn(Y){return super.has(Y)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){if(this.source.has(Y))this.deleted.add(Y),this.changed.delete(Y);return super.delete(Y)}clear(){this.deleted=new Set(this.source.keys()),this.changed.clear(),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let[Y,Z]of this.source)if(!this.deleted.has(Y)&&!this.changed.has(Y))yield[Y,Z]}*entries(){yield*this[Symbol.iterator]()}*keys(){yield*super.keys();for(let Y of this.source.keys())if(!this.deleted.has(Y)&&!this.changed.has(Y))yield Y}*values(){for(let[,Y]of this[Symbol.iterator]())yield Y}forEach(Y){for(let[Z,X]of this[Symbol.iterator]())Y(X,Z,this)}get size(){return super.size+this.source.size-this.changed.size-this.deleted.size}},u_=class extends Set{deleted=new Set;source;constructor(Y){super();this.source=Y}add(Y){if(this.source.has(Y))return this.deleted.delete(Y),this;return super.add(Y)}hasOwn(Y){return super.has(Y)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){if(this.source.has(Y))return this.deleted.add(Y),!0;return super.delete(Y)}clear(){this.deleted=new Set(this.source),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let Y of this.source)if(!this.deleted.has(Y))yield Y}*iterateOwn(){yield*super[Symbol.iterator]()}get size(){return super.size+this.source.size-this.deleted.size}},oU=class extends Map{deleted=new Set;source;constructor(Y){super();this.source=Y}get(Y){if(super.has(Y))return super.get(Y);if(!this.deleted.has(Y)&&this.source.has(Y)){let Z=this.source.get(Y),X=new u_(Z);return super.set(Y,X),X}}set(Y,Z){return this.deleted.delete(Y),super.set(Y,Z)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){return this.deleted.add(Y),super.delete(Y)}},$4=class Y{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(Z,X)=>`${Z}:${X}`;warn;getRelatedKeys(Z){return this.relations.get(Z)}addRelation(Z,X){let G=this.relations.get(Z),_=this.relations.get(X);if(G)G.add(X);else G=new Set([X]),this.relations.set(Z,G);if(_)_.add(Z);else _=new Set([Z]),this.relations.set(X,_)}deleteRelation(Z,X){let G=this.relations.get(Z);if(G){if(G.delete(X),G.size===0)this.relations.delete(Z);let _=this.relations.get(X);if(_){if(_.delete(Z),_.size===0)this.relations.delete(X)}}}replaceRelationsUnsafely(Z,X){this.relations.set(Z,new Set(X));for(let G of X){let _=new Set().add(Z);this.relations.set(G,_)}}replaceRelationsSafely(Z,X){let G=this.relations.get(Z),_=this.isAType?.(Z)?Z:void 0,$=_===void 0?Z:void 0;if(G)for(let W of G){_??=W,$??=W;let H=this.relations.get(W);if(H){if(H.size===1)this.relations.delete(W);else H.delete(Z);this.contents.delete(this.makeContentKey(_,$))}}this.relations.set(Z,new Set(X));for(let W of X){let H=this.relations.get(W);if(H)H.add(Z);else H=new Set().add(Z),this.relations.set(W,H)}}getContentInternal(Z){return this.contents.get(Z)}setContent(Z,X){this.contents.set(Z,X)}deleteContent(Z){this.contents.delete(Z)}constructor(Z,X){if(this.a=Z.between[0],this.b=Z.between[1],this.cardinality=Z.cardinality,this.isAType=X?.isAType??null,this.isBType=X?.isBType??null,this.isContent=X?.isContent??null,X?.makeContentKey)this.makeContentKey=X.makeContentKey;if(!X?.externalStore){let G=X?.source;if(G===void 0)this.relations=new Map(Z.relations?.map(([_,$])=>[_,new Set($)])),this.contents=new Map(Z.contents);if(G)this.relations=new oU(G.relations),this.contents=new b1(G.contents)}if(X?.externalStore){let G=X.externalStore;if(this.has=(_,$)=>G.has(_,$),this.addRelation=(_,$)=>{G.addRelation(_,$)},this.deleteRelation=(_,$)=>{G.deleteRelation(_,$)},this.replaceRelationsSafely=(_,$)=>{G.replaceRelationsSafely(_,$)},this.replaceRelationsUnsafely=(_,$)=>{G.replaceRelationsUnsafely(_,$)},this.getRelatedKeys=(_)=>G.getRelatedKeys(_),G.getContent)this.getContentInternal=(_)=>{return G.getContent(_)},this.setContent=(_,$)=>{G.setContent(_,$)},this.deleteContent=(_)=>{G.deleteContent(_)};for(let[_,$]of Z.relations??[]){let W=this.isAType?.(_)?_:void 0,H=W===void 0?_:void 0;for(let Q of $)W??=Q,H??=Q,this.addRelation(W,H)}for(let[_,$]of Z.contents??[])this.setContent(_,$)}if(X?.warn)this.warn=X.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([Z,X])=>[Z,[...X]]),contents:[...this.contents.entries()]}}set(...Z){let X,G,_;switch(Z.length){case 1:{let $=Z[0];X=$[this.a],G=$[this.b],_=void 0;break}case 2:{let $=Z[0];if(typeof $==="string")[X,G]=Z;else X=$[this.a],G=$[this.b],_=Z[1];break}default:X=Z[0],G=Z[1],_=Z[2];break}switch(this.cardinality){case"1:1":{let $=this.getRelatedKey(X);if($&&$!==G)this.delete(X,$)}case"1:n":{let $=this.getRelatedKey(G);if($&&$!==X)this.delete($,G)}break;case"n:n":}if(_){let $=this.makeContentKey(X,G);this.setContent($,_)}return this.addRelation(X,G),this}delete(Z,X){X=typeof X==="string"?X:Z[this.b];let G=typeof Z==="string"?Z:Z[this.a];if(G===void 0&&typeof X==="string"){let _=this.getRelatedKeys(X);if(_)for(let $ of _)this.delete($,X)}else if(typeof G==="string"&&X===void 0){let _=this.getRelatedKeys(G);if(_)for(let $ of _)this.delete(G,$)}else if(typeof G==="string"&&typeof X==="string"){this.deleteRelation(G,X);let _=this.makeContentKey(G,X);this.deleteContent(_)}return this}getRelatedKey(Z){let X=this.getRelatedKeys(Z);if(X){if(X.size>1)this.warn?.(`${X.size} related keys were found for key "${Z}": (${[...X].map((_)=>`"${_}"`).join(", ")}). Only one related key was expected.`);let G;for(let _ of X){G=_;break}return G}}replaceRelations(Z,X,G){let _=!Array.isArray(X),$=_?Object.keys(X):X;if(G?.reckless)this.replaceRelationsUnsafely(Z,$);else this.replaceRelationsSafely(Z,$);if(_)for(let W of $){let H=this.makeContentKey(Z,W),Q=X[W];this.setContent(H,Q)}return this}getContent(Z,X){let G=this.makeContentKey(Z,X);return this.getContentInternal(G)}getRelationEntries(Z){let X=Z[this.a],G=Z[this.b];if(X!==void 0&&G===void 0){let _=this.getRelatedKeys(X);if(_)return[..._].map(($)=>{return[$,this.getContent(X,$)]})}if(X===void 0&&G!==void 0){let _=this.getRelatedKeys(G);if(_)return[..._].map(($)=>{return[$,this.getContent($,G)]})}return[]}has(Z,X){if(X)return this.getRelatedKeys(Z)?.has(X)??!1;return this.relations.has(Z)}overlay(){let Z={source:this,makeContentKey:this.makeContentKey};if(this.isAType)Z.isAType=this.isAType;if(this.isBType)Z.isBType=this.isBType;if(this.isContent)Z.isContent=this.isContent;if(this.warn)Z.warn=this.warn;return new Y({between:[this.a,this.b],cardinality:this.cardinality},Z)}incorporate(Z){let{relations:X,contents:G}=Z;for(let[_,$]of X)if($ instanceof u_){let{source:W}=$;for(let H of $.iterateOwn())W.add(H)}else this.relations.set(_,$);for(let _ of X.deleted)this.relations.delete(_);for(let[_,$]of G)this.contents.set(_,$);for(let _ of G.deleted)this.contents.delete(_)}};function L2(Y){return Y.startsWith("\uD83D\uDD0D ")}var iU=(Y)=>{Y.logger.info("\uD83E\uDE82","transaction",Y.transactionMeta.update.token.key,"Aborting transaction"),Y.parent.child=null};function M6(Y,Z,X){return(...G)=>{return P0(Y,Z).run(G,X)}}function nU(Y,Z,X){let{token:G,update:{newValue:_,oldValue:$}}=Z;k1(Y,G,X==="newValue"?_:$)}function rU(Y){let{stack:Z}=Y;if(Z)return`
|
|
48
|
-
`+
|
|
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
|
+
`+Y.split(`
|
|
49
49
|
`)?.slice(1)?.join(`
|
|
50
|
-
`);return""}function
|
|
51
|
-
${
|
|
52
|
-
${
|
|
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 ${
|
|
55
|
-
${
|
|
56
|
-
${F.trace}`:`No previous disposal trace for ${
|
|
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
|
+
${G} was most recently disposed
|
|
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.`),
|
|
59
|
-
${_.trace}`:"(no previous disposal trace found)"),X.type){case"mutable_atom_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=new X.class;return Y.defaults.set(X.key,$),$.READONLY_VIEW}case"atom_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=X.default,W=$(G);return Y.defaults.set(X.key,W),W}case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=X.default(G);return Y.defaults.set(X.key,$),$}}}function N6(Y,Z){let{type:X,key:G,catch:_}=Z;switch(X){case"readonly_pure_selector":case"writable_pure_selector":{let $;Y.logger.info("\uD83E\uDDEE",X,G,"computing value");try{if($=Z.getFrom(Y),$ instanceof Promise)return $.catch((W)=>{if(Y.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return W}throw W})}catch(W){if(Y.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return B1(Y,Z,W)}throw W}return B1(Y,Z,$)}case"atom":{let $;if(H8(Z.default))try{if($=Z.default(),$ instanceof Promise)$=$.catch((W)=>{if(Y.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return W}throw W})}catch(W){if(Y.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return $=B1(Y,Z,W),Y.logger.info("\u2728",Z.type,G,"computed default",$),$}throw W}else $=Z.default,Y.logger.info("\u2728",Z.type,G,"using static default",$);return B1(Y,Z,$)}}}function h4(Y,Z,X){if(Y.valueMap.has(Z.key))return RF(Y,Z,X);Y.logger.info("\u2754",Z.type,Z.key,"value not found in cache");let{key:G}=Z;switch(Z.type){case"readonly_held_selector":case"writable_held_selector":return Y.logger.info("\uD83E\uDDEE",Z.type,G,"computing value"),Z.getFrom(Y);case"writable_pure_selector":case"readonly_pure_selector":case"atom":return N6(Y,Z);case"mutable_atom":{let _=new Z.class;return Y.logger.info("\u2728",Z.type,G,"created new instance",_),B1(Y,Z,_)}}}function oZ(Y,Z){return P0(Y,{key:Z.family.key,type:`${Z.type}_family`})}var y_={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"},J8=Symbol("MUST_CREATE"),JF=Symbol("DO_NOT_CREATE");function Q8(Y,Z,X,G){let _=Q0(G),$=Z.molecules.get(_);if(!$&&Z.config.lifespan==="immortal"){let{type:H,key:Q}=X;Z.logger.warn("\uD83D\uDCA3","key",_,"was used to mint a counterfeit token for",H,`"${Q}"`);let J=`${Q}(${_})`,z=y_[H];return{counterfeit:!0,key:J,type:z,family:{key:Q,subKey:_}}}let W;if(Y===J8){if(Z.logger.info("\uD83D\uDC6A",X.type,X.key,"adds member",typeof G==="string"?`\`${G}\``:G),W=X.create(G),$)Z.moleculeData.set(_,X.key)}else{let{type:H,key:Q}=X,J=`${Q}(${_})`,z=y_[H];return{key:J,type:z,family:{key:Q,subKey:_}}}return W}function iZ(Y,...Z){let X,G,_,$,W;if(Z.length===1){if(W=Z[0],"family"in W){let Q=oZ(Y,W);if(_=P0(Y,Q),$=X1(W.family.subKey),X=z8(Y,Q,$),"counterfeit"in W)return{token:W,family:_,subKey:$,isNew:!1};if(!X)G=Q8(J8,Y,Q,$),W=G;else W=X}}else if(_=P0(Y,Z[0]),$=Z[1],X=z8(Y,_,$),!X)G=Q8(J8,Y,_,$),W=G;else W=X;let H="counterfeit"in W;if(Boolean(G)&&H===!1&&_){let Q;switch(W.type){case"readonly_pure_selector":case"readonly_held_selector":Q="readable";break;case"atom":case"mutable_atom":case"writable_pure_selector":case"writable_held_selector":Q="writable";break}let J={type:"state_creation",subType:Q,token:W,timestamp:Date.now()};_.subject.next(J);let z=Y0(Y);if(W.family){if(D2(z))switch(W.type){case"atom":case"mutable_atom":Y.on.atomCreation.next(W);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":Y.on.selectorCreation.next(W);break}else if(E1(z)&&z.on.transactionApplying.state===null)z.transactionMeta.update.subEvents.push(J)}}return{token:W,family:_,subKey:$,isNew:Boolean(G)}}function h1(Y,...Z){let{token:X,family:G,subKey:_}=iZ(Y,...Z);if("counterfeit"in X&&G&&_)return o_(Y,X,G,_);let $=P0(Y,X);return h4(Y,$)}function z8(Y,Z,X){let G=Q0(X),_=`${Z.key}(${G})`,$=Y0(Y),W;switch(Z.type){case"atom_family":case"mutable_atom_family":W=$.atoms.get(_);break;case"writable_held_selector_family":case"writable_pure_selector_family":W=$.writableSelectors.get(_);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":W=$.readonlySelectors.get(_);break}if(W)return y1(W);return W}function j0(Y,Z,X){let G=P0(Y,Z),_=z8(Y,Z,X);if(_)return _;return Q8(JF,Y,G,X)}function f4(Y,Z,X){let G=Z.key,_="readonly_pure_selector_family",$={key:G,type:"readonly_pure_selector_family"},W=Y.families.get(G);if(W)Y.logger.error("\u2757","readonly_pure_selector_family",G,`Overwriting an existing ${_4[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new _0,J={...$,create:(z)=>{let F=Q0(z),O={key:G,subKey:F},L=`${G}(${F})`,w=Y0(Y),R={key:L,get:Z.get(z)};if(Z.catch)R.catch=Z.catch;return sZ(w,R,O)},internalRoles:X,subject:H,install:(z)=>f4(z,Z),default:(z)=>{return Z.get(z)({get:(...F)=>h1(Y,...F),find:(...F)=>j0(Y,...F),json:(F)=>k4(Y,F)})}};return Y.families.set(G,J),$}function O2(Y,Z,X){let G={key:Z.key,type:"atom_family"},_=Y.families.get(Z.key);if(_)Y.logger.error("\u2757","atom_family",Z.key,`Overwriting an existing ${_4[_.type]} "${_.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new _0,H={...G,create:(Q)=>{let J=Q0(Q),z={key:Z.key,subKey:J},F=`${Z.key}(${J})`,O=Y0(Y),L=Z.default,w={key:F,default:H8(L)?()=>L(Q):L};if(Z.effects)w.effects=Z.effects(Q);if(Z.catch)w.catch=Z.catch;return x4(O,w,z)},default:Z.default,subject:$,install:(Q)=>O2(Q,Z),internalRoles:X};if(Y.families.set(Z.key,H),H8(Z.default)===!1)Y.defaults.set(Z.key,Z.default);return G}function i_(Y,Z,X){let G=Z.key,_="readonly_held_selector_family",$={key:G,type:"readonly_held_selector_family"},W=Y.families.get(G);if(W)Y.logger.error("\u2757","readonly_held_selector_family",G,`Overwriting an existing ${_4[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new _0,J={...$,create:(z)=>{let F=Q0(z),O={key:G,subKey:F},L=`${G}(${F})`,w=Y0(Y);return rZ(w,{key:L,const:Z.const(z),get:Z.get(z)},O)},internalRoles:X,subject:H,install:(z)=>i_(z,Z),default:Z.const};return Y.families.set(G,J),$}function n_(Y,Z,X){let G=Z.key,_="writable_held_selector_family",$={key:G,type:"writable_held_selector_family"},W=Y.families.get(G);if(W)Y.logger.error("\u2757","writable_held_selector_family",G,`Overwriting an existing ${_4[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new _0,J={...$,create:(z)=>{let F=Q0(z),O={key:G,subKey:F},L=`${G}(${F})`,w=Y0(Y);return tZ(w,{key:L,const:Z.const(z),get:Z.get(z),set:Z.set(z)},O)},internalRoles:X,subject:H,install:(z)=>n_(z,Z),default:Z.const};return Y.families.set(G,J),$}function nZ(Y,Z,X){let G=Z.key,_="writable_pure_selector_family",$={key:G,type:"writable_pure_selector_family"},W=Y.families.get(G);if(W)Y.logger.error("\u2757","writable_pure_selector_family",G,`Overwriting an existing ${_4[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new _0,J={...$,create:(z)=>{let F=Q0(z),O={key:G,subKey:F},L=`${G}(${F})`,w=Y0(Y),R={key:L,get:Z.get(z),set:Z.set(z)};if(Z.catch)R.catch=Z.catch;return aZ(w,R,O)},internalRoles:X,subject:H,install:(z)=>nZ(z,Z),default:(z)=>{return Z.get(z)({get:(...F)=>h1(Y,...F),find:(...F)=>j0(Y,...F),json:(F)=>k4(Y,F)})}};return Y.families.set(G,J),$}function bZ(Y,Z){let X="set"in Z,G="const"in Z;if(G&&X)return n_(Y,Z,void 0);if(G)return i_(Y,Z,void 0);if(X)return nZ(Y,Z);return f4(Y,Z)}function $8(Y,...Z){let X;if(Z.length===1)X=Z[0];else{let G=Z[0],_=Z[1];X=j0(Y,G,_)}try{P0(Y,X)}catch(G){Y.logger.error("\u274C",X.type,X.key,`could not be disposed because it was not found in the store "${Y.config.name}".`);return}switch(X.type){case"atom":case"mutable_atom":X7(Y,X);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":DF(Y,X);break}}function r_(Y,Z){if(Y.operation.open){let X=performance.now();return Y.logger.info("\uD83D\uDEAB",Z.type,Z.key,`deferring setState at T-${X} until setState for "${Y.operation.token.key}" is done`),X}return Y.operation={open:!0,done:new Set,prev:new Map,timestamp:Date.now(),token:Z,subEvents:[]},Y.logger.info("\u2B55",Z.type,Z.key,`operation start in store "${Y.config.name}"${E1(Y)?` ${Y.transactionMeta.phase} "${Y.transactionMeta.update.token.key}"`:""}`),Y}function s_(Y){if(Y.operation.open)Y.logger.info("\uD83D\uDD34",Y.operation.token.type,Y.operation.token.key,`operation done in store "${Y.config.name}"`);Y.operation={open:!1},Y.on.operationClose.next(Y.operation)}var t_=(Y,Z)=>{if(!Y.operation.open)return Y.logger.error("\uD83D\uDC1E","unknown",Z,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return Y.operation.done.has(Z)},B6=(Y,Z)=>{if(!Y.operation.open){Y.logger.error("\uD83D\uDC1E","unknown",Z,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}Y.operation.done.add(Z)};function dZ(Y,Z,{oldValue:X,newValue:G},_,$){let W=y1(Z);if(_&&$){Z.subject.next({newValue:G});let F={checkpoint:!0,type:"state_creation",subType:"writable",token:W,timestamp:Date.now(),value:G};Y.operation.subEvents.push(F),$.subject.next(F);let O=Y0(Y);if(W.family){if(D2(O))switch(W.type){case"atom":case"mutable_atom":Y.on.atomCreation.next(W);break;case"writable_pure_selector":case"writable_held_selector":Y.on.selectorCreation.next(W);break}else if(E1(O)&&O.on.transactionApplying.state===null)O.transactionMeta.update.subEvents.push(F)}return}let{key:H,subject:Q,type:J}=Z,z={oldValue:pZ(X)?X.READONLY_VIEW:X,newValue:pZ(G)?G.READONLY_VIEW:G};if(D2(Y)){switch(J){case"mutable_atom":Y.logger.info("\uD83D\uDCE2",J,H,"is now (",G,") subscribers:",Q.subscribers.keys());break;case"atom":case"writable_pure_selector":case"writable_held_selector":Y.logger.info("\uD83D\uDCE2",J,H,"went (",X,"->",G,") subscribers:",Q.subscribers.keys())}Q.next(z)}if(E1(Y)&&(J==="mutable_atom"||J==="atom")){if(Y.on.transactionApplying.state===null){if(pZ(G))return;let{timestamp:F}=Y.operation,O={type:"atom_update",token:W,timestamp:F,update:z};Y.transactionMeta.update.subEvents.push(O),Y.logger.info("\uD83D\uDCC1","atom",H,"stowed (",X,"->",G,")");return}if(X5(Z,"tracker:signal")){let F=H.slice(1),O=Y.atoms.get(F);if(h4(Y,O,"mut").do(z.newValue)===null===!0)Z5(Y,O)}}}var cZ=(Y,Z,X)=>{let G=h4(Y,Z,"mut"),_=mZ(X,G);return Y.logger.info("\u2B50","atom",Z.key,"setting value",_),_=B1(Y,Z,_),B6(Y,Z.key),Z5(Y,Z),{oldValue:G,newValue:_}};function gZ(Y,Z){switch(Z.type){case"mutable_atom":return cZ(Y,Z,new Z.class);case"atom":{let X;if(H8(Z.default))X=N6(Y,Z);else X=Z.default;return cZ(Y,Z,X)}}}function QF(Y,Z){let X;switch(Z.type){case"atom":case"mutable_atom":X=gZ(Y,Z);break;case"writable_held_selector":{let G=U8(Y,Z.key);for(let $ of G.values()){let W=gZ(Y,$);dZ(Y,Z,W,!1)}let _=Z.getFrom(Y);X={oldValue:_,newValue:_}}break;case"writable_pure_selector":{let G=N6(Y,Z),_=U8(Y,Z.key);for(let W of _.values()){let H=gZ(Y,W);dZ(Y,Z,H,!1)}let $=N6(Y,Z);X={oldValue:G,newValue:$}}break}return X}function k1(Y,...Z){E8(I6,Y,...Z)}var lZ=Symbol("RESET");function R6(Y,...Z){let X=[...Z,lZ];k1(Y,...X)}function zF(Y,Z,X){let G,_,$,{type:W,key:H}=Z;switch(Z.type){case"writable_pure_selector":G=h4(Y,Z,"mut"),_=mZ(X,G),_=B1(Y,Z,_);break;case"writable_held_selector":$=Z.const,mZ(X,$),G=$,_=$}return Y.logger.info("\u2B50",W,H,"setting to",_),B6(Y,H),Z.setSelf(_),{oldValue:G,newValue:_}}var UF=(Y,Z,X)=>{let G;switch(Z.type){case"atom":case"mutable_atom":G=cZ(Y,Z,X);break;case"writable_pure_selector":case"writable_held_selector":G=zF(Y,Z,X);break}return G},I6=Symbol("OWN_OP"),a_=Symbol("JOIN_OP");function E8(Y,Z,...X){let G,_,$,W,H,Q;if(X.length===2){if($=X[0],Q=X[1],"family"in $)if(W=oZ(Z,$),H=X1($.family.subKey),G=z8(Z,W,H),!G)$=_=Q8(J8,Z,W,H);else $=G}else if(W=P0(Z,X[0]),H=X[1],Q=X[2],G=z8(Z,W,H),!G)$=_=Q8(J8,Z,W,H);else $=G;let J=Q===lZ?"reset":"set",z;if(Y===I6){let L=r_(Z,$);if(typeof L==="number"){let w=L,R=Z.on.operationClose.subscribe(`waiting to ${J} "${$.key}" at T-${w}`,function(){R(),Z.logger.info("\uD83D\uDFE2",$.type,$.key,"resuming deferred",J,`from T-${w}`),E8(Y,Z,$,Q)});return}z=L}else z=Z;if("counterfeit"in $&&"family"in $){let L=$.family.subKey,w=Z.disposalTraces.buffer.find((R)=>R?.key===L);Z.logger.error("\u274C",$.type,$.key,"could not be",J,"because key",L,"is not allocated.",w?`this key was previously disposed:${w.trace}`:"(no previous disposal trace found)");return}let F=P0(z,$),O;if(Q===lZ)O=QF(z,F);else O=UF(z,F,Q);if(dZ(z,F,O,Boolean(_),W),Y===I6)s_(z)}var e_=(Y,Z)=>Y0(Y).atoms.has(Z),FF=(Y,Z)=>Y0(Y).writableSelectors.has(Z),EF=(Y,Z)=>Y0(Y).readonlySelectors.has(Z),VF=(Y,Z)=>e_(Y,Z)||FF(Y,Z)||EF(Y,Z);function g_(Y,Z){return Y0(Y).selectorGraph.getRelationEntries({downstreamSelectorKey:Z}).filter(([X,{source:G}])=>G!==Z).map(([X,{source:G}])=>G).filter((X)=>VF(Y,X))}function U8(Y,Z,X=new Set){let G=g_(Y,Z),_=new Map;while(G.length>0){let $=G.pop();if(X.has($))continue;if(X.add($),e_(Y,$)){let W=Y.atoms.get($);_.set(W.key,W)}else G.push(...g_(Y,$))}return _}function OF(Y,Z,X,G,_){let $=Y0(Y),{type:W,key:H}=G;if(W==="atom"||W==="mutable_atom")$.selectorAtoms.set({selectorKey:X,atomKey:H}),Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atom "${H}"`);else{let Q=U8(Y,H,_);Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atoms: [ ${[...Q.values()].map((J)=>`"${J.key}"`).join(", ")} ]`);for(let{key:J}of Q.values())$.selectorAtoms=$.selectorAtoms.set({selectorKey:X,atomKey:J})}_.add(H)}function T6(Y,Z,X,G){return{get:(..._)=>{let $=Y0(Y),{token:W,family:H,subKey:Q}=iZ(Y,..._),J;if("counterfeit"in W&&H&&Q)J=o_(Y,W,H,Q);else{let z=P0(Y,W);J=h4(Y,z)}return Y.logger.info("\uD83D\uDD0C",Z,X,`registers dependency ( "${W.key}" =`,J,")"),$.selectorGraph.set({upstreamSelectorKey:W.key,downstreamSelectorKey:X},{source:W.key}),OF(Y,Z,X,W,G),J},set:(..._)=>{let $=Y0(Y);E8(a_,$,..._)},find:(..._)=>j0(Y,..._),json:(_)=>k4(Y,_)}}function rZ(Y,Z,X){let G=Y0(Y),_=new _0,$=new Set,{key:W,const:H}=Z,Q="readonly_held_selector";Y.logger.info("\uD83D\uDD28","readonly_held_selector",W,"is being created");let{get:J,find:z,json:F}=T6(G,"readonly_held_selector",W,$),L={...Z,type:"readonly_held_selector",subject:_,getFrom:(R)=>{let b=R.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[x,{source:h}]of b)if(h!==W)R.selectorGraph.delete(x,W);return R.selectorAtoms.delete(W),Z.get({get:J,find:z,json:F},H),B1(R,L,H),Y.logger.info("\u2728","readonly_held_selector",W,"=",H),$.clear(),H},install:(R)=>rZ(R,Z,X)};if(X)L.family=X;G.readonlySelectors.set(W,L);let w={key:W,type:"readonly_held_selector"};if(X)w.family=X;return w}function sZ(Y,Z,X){let G=Y0(Y),_=new _0,$=new Set,W=Z.key,H="readonly_pure_selector";Y.logger.info("\uD83D\uDD28","readonly_pure_selector",W,"is being created");let{get:Q,find:J,json:z}=T6(G,"readonly_pure_selector",W,$),O={...Z,type:"readonly_pure_selector",subject:_,getFrom:()=>{let w=Y0(Y),R=w.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[h,{source:g}]of R)if(g!==W)w.selectorGraph.delete(h,W);w.selectorAtoms.delete(W);let b=Z.get({get:Q,find:J,json:z}),x=B1(w,O,b);return Y.logger.info("\u2728","readonly_pure_selector",W,"=",x),$.clear(),x},install:(w)=>sZ(w,Z,X)};if(X)O.family=X;G.readonlySelectors.set(W,O);let L={key:W,type:"readonly_pure_selector"};if(X)L.family=X;return L}function tZ(Y,Z,X){let G=Y0(Y),_=new _0,$=new Set,{key:W,const:H}=Z,Q="writable_held_selector";Y.logger.info("\uD83D\uDD28","writable_held_selector",W,"is being created");let J=T6(G,"writable_held_selector",W,$),{find:z,get:F,json:O}=J,L={find:z,get:F,json:O},b={...Z,type:"writable_held_selector",subject:_,getFrom:(h)=>{let g=h.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[B,{source:K}]of g)if(K!==W)h.selectorGraph.delete(B,W);return h.selectorAtoms.delete(W),Z.get(L,H),B1(h,b,H),Y.logger.info("\u2728","writable_held_selector",W,"=",H),$.clear(),H},setSelf:()=>{Z.set(J,H)},install:(h)=>tZ(h,Z,X)};if(X)b.family=X;G.writableSelectors.set(W,b);let x={key:W,type:"writable_held_selector"};if(X)x.family=X;return x}function aZ(Y,Z,X){let G=Y0(Y),_=new _0,$=new Set,W=Z.key,H="writable_pure_selector";Y.logger.info("\uD83D\uDD28","writable_pure_selector",W,"is being created");let Q=T6(G,"writable_pure_selector",W,$),{find:J,get:z,json:F}=Q,O={find:J,get:z,json:F},R={...Z,type:"writable_pure_selector",subject:_,getFrom:(x)=>{let h=x.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[K,{source:C}]of h)if(C!==W)x.selectorGraph.delete(K,W);x.selectorAtoms.delete(W);let g=Z.get(O),B=B1(x,R,g);return Y.logger.info("\u2728","writable_pure_selector",W,"=",B),$.clear(),B},setSelf:(x)=>{Z.set(Q,x)},install:(x)=>aZ(x,Z,X)};if(X)R.family=X;G.writableSelectors.set(W,R);let b={key:W,type:"writable_pure_selector"};if(X)b.family=X;return b}function f_(Y,Z){let X="set"in Z,G="const"in Z;if(G&&X){let $=tZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}if(G){let $=rZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}if(X){let $=aZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}let _=sZ(Y,Z,void 0);return Y.on.selectorCreation.next(_),_}function DF(Y,Z){let X=Y0(Y),{key:G,type:_,family:$}=Z;if(!$)Y.logger.error("\u274C",_,G,"Standalone selectors cannot be disposed.");else{if(X.molecules.get($.subKey))X.moleculeData.delete($.subKey,$.key);let W;switch(Z.type){case"writable_held_selector":X.writableSelectors.delete(G),W={key:$.key,type:"writable_held_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"writable_pure_selector":X.writableSelectors.delete(G),W={key:$.key,type:"writable_pure_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"readonly_held_selector":X.readonlySelectors.delete(G),W={key:$.key,type:"readonly_held_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"readonly_pure_selector":X.readonlySelectors.delete(G),W={key:$.key,type:"readonly_pure_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break}if(X.valueMap.delete(G),X.selectorAtoms.delete(G),X.selectorGraph.delete(G),X.moleculeData.delete($.key,$.subKey),Y.logger.info("\uD83D\uDD25",Z.type,G,"deleted"),E1(X)&&X.transactionMeta.phase==="building")X.transactionMeta.update.subEvents.push({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});else Y.on.selectorDisposal.next(Z)}}var LF=(Y,Z)=>{let X=Y0(Y);if(X.operation.open)return X.operation.prev.get(Z.key);return X.valueMap.get(Z.key)},p_=(Y,Z,X)=>{return X.subject.subscribe(`${Z.type}:${Z.key}`,(G)=>{Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"root",X.key,"went",G.oldValue,"->",G.newValue);let _=LF(Y,Z),$=h4(Y,Z);Y.logger.info("\u2728",Z.type,Z.key,"went",_,"->",$),Z.subject.next({newValue:$,oldValue:_})})};function F8(Y,Z,X,G){function _(F){if(Y.operation.open){if($?.type==="atom"&&X5($,"tracker:signal")&&"*"+Y.operation.token.key===Z.key&&"inboundTracker"in G)return;let O=Y.on.operationClose.subscribe(`state subscription ${X}`,()=>{O(),G(F)})}else G(F)}iZ(Y,Z);let $=P0(Y,Z);Y.logger.info("\uD83D\uDC40",$.type,$.key,`Adding subscription "${X}"`);let W=$.type==="writable_pure_selector"||$.type==="readonly_pure_selector",H=new Map,Q=_;if(W){h4(Y,$);for(let[F,O]of U8(Y,$.key))H.set(F,p_(Y,$,O));Q=function(O){let L=U8(Y,$.key);for(let[w,R]of H)if(L.get(w))L.delete(w);else R(),H.delete(w);for(let[w,R]of L)H.set(w,p_(Y,$,R));_(O)}}let J=$.subject.subscribe(X,Q);return()=>{Y.logger.info("\uD83D\uDE48",$.type,$.key,`Removing subscription "${X}"`),J();for(let F of H.values())F()}}var MF=(Y,Z,X,G)=>{let _=P0(Y,Z);Y.logger.info("\uD83D\uDC40","timeline",Z.key,`Adding subscription "${X}"`);let $=_.subject.subscribe(X,G);return()=>{Y.logger.info("\uD83D\uDE48","timeline",Z.key,`Removing subscription "${X}" from timeline`),$()}};var eZ=class{initializeSignalAtom(Y,Z){let X=`*${Y.key}`;Z.atoms.delete(X),Z.valueMap.delete(X);let G=Y.family?{key:`*${Y.family.key}`,subKey:Y.family.subKey}:void 0,_=x4(Z,{key:X,default:null},G,["tracker:signal"]);if(Z.parent?.valueMap.has(X)){let $=Z.parent.valueMap.get(X);Z.valueMap.set(X,$)}return _}unsubscribeFromInnerValue;unsubscribeFromState;captureSignalsFromCore(Y,Z,X){let G=Y.key,_=X.config.name,$=E1(X)?X.transactionMeta.update.token.key:"main",W=`tracker-from-core:${_}:${$}:${G}`,H=(Q)=>{E8(a_,X,Z,Q)};this.unsubscribeFromInnerValue=h1(X,Y).subscribe(W,H),this.unsubscribeFromState=F8(X,Y,W,function(J){if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe(W,H)}.bind(this))}supplySignalsToCore(Y,Z,X){let G=Y.key,_=X.config.name,$=E1(X)?X.transactionMeta.update.token.key:"main",W=`tracker-to-core:${_}:${$}:${G}`;F8(X,Z,W,Object.assign(function({newValue:Q,oldValue:J}){let z=X.timelineTopics.getRelatedKey(Z.key);if(z&&X.timelines.get(z)?.timeTraveling){let F=MF(X,{key:z,type:"timeline"},W,function(L){F(),k1(X,Y,(w)=>{if(L==="redo"&&Q)w.do(Q);else if(L==="undo"&&J)w.undo(J);return w})});return}k1(X,Y,(F)=>(F.do(Q),F))},{inboundTracker:!0}))}mutableAtomToken;latestSignalToken;[Symbol.dispose];constructor(Y,Z){let X=Y0(Z),G=this.initializeSignalAtom(Y,X);this.mutableAtomToken=Y,this.latestSignalToken=G,this.captureSignalsFromCore(Y,G,X),this.supplySignalsToCore(Y,G,X),X.trackers.set(Y.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(Y.key)}}};function w6(Y,Z,X){Y.logger.info("\uD83D\uDD28","atom",Z.key,`creating in store "${Y.config.name}"`);let G=Y0(Y),{key:_}=Z,$=G.atoms.get(_),W="mutable_atom";if($&&$.type===W)return Y.logger.error("\u274C",W,_,"Tried to create atom, but it already exists in the store."),y1($);let H=new _0,Q={...Z,type:W,install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",_,`installing in store "${z.config.name}"`),w6(z,Z,X)},subject:H};if(X)Q.family=X;G.atoms.set(Q.key,Q);let J=y1(Q);if(Z.effects){let z=0,F=[];for(let O of Z.effects){let L=O({resetSelf:()=>{R6(Y,J)},setSelf:(w)=>{k1(Y,J,w)},onSet:(w)=>F8(Y,J,`effect[${z}]`,w)});if(L)F.push(L);++z}Q.cleanup=()=>{for(let O of F)O()}}if(new eZ(J,Y),!X)f_(Y,{key:`${_}:JSON`,get:({get:z})=>z(J).toJSON(),set:({set:z},F)=>{z(J,Z.class.fromJSON(F))}});return Y.on.atomCreation.next(J),J}var AF=class{trackers=new Map;latestSignalAtoms;mutableAtoms;constructor(Y,Z){let X=O2(Z,{key:`*${Y.key}`,default:null},["mutable","updates"]);this.latestSignalAtoms=P0(Z,X),this.mutableAtoms=Y;let G=(_)=>{let{type:$,token:W}=_;if(W.family){let H=X1(W.family.subKey);switch($){case"state_creation":this.trackers.set(H,new eZ(W,Z));break;case"state_disposal":{let Q=this.trackers.get(H);if(Q)Q[Symbol.dispose](),this.trackers.delete(H)}}}};this.mutableAtoms.subject.subscribe(`store=${Z.config.name}::tracker-atom-family`,G)}};function yZ(Y,Z,X){let G={key:Z.key,type:"mutable_atom_family"},_=Y.families.get(Z.key);if(_)Y.logger.error("\u2757","mutable_atom_family",Z.key,`Overwriting an existing ${_4[_.type]} "${_.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new _0,H={...G,create:(Q)=>{let J=Q0(Q),z={key:Z.key,subKey:J},F=`${Z.key}(${J})`,O=Y0(Y),L={key:F,class:Z.class};if(Z.effects)L.effects=Z.effects(Q);return w6(O,L,z)},class:Z.class,subject:$,install:(Q)=>yZ(Q,Z),internalRoles:X};return Y.families.set(Z.key,H),nZ(Y,{key:`${Z.key}:JSON`,get:(Q)=>({get:J})=>J(G,Q).toJSON(),set:(Q)=>({set:J},z)=>{J(G,Q,Z.class.fromJSON(z))}},["mutable","json"]),new AF(H,Y),G}var m_=(Y,Z)=>{let X=Y0(Z),G=`${Y.key}:JSON`;return X.families.get(G)},k4=(Y,Z)=>{if(Z.family){let X=Y0(Y),G={key:`${Z.family.key}:JSON`,type:"writable_pure_selector_family"},_=P0(X,G),$=X1(Z.family.subKey);return j0(Y,_,$)}return{type:"writable_pure_selector",key:`${Z.key}:JSON`}};var Y5=(Y)=>{let Z={type:"atom",key:`*${Y.key}`};if(Y.family)Z.family={key:`*${Y.family.key}`,subKey:Y.family.subKey};return Z};function pZ(Y){return typeof Y==="object"&&Y!==null&&"do"in Y&&"undo"in Y&&"subscribe"in Y&&"READONLY_VIEW"in Y&&"toJSON"in Y}function B1(Y,Z,X){let{key:G,subject:_,type:$}=Z,W=Y.valueMap.get(G);if(W instanceof uZ&&!W.done){let H=W;if(X instanceof Promise)return H.use(X),H;return Y.valueMap.set(G,X),X}if(X instanceof Promise){let H=new uZ(X);return Y.valueMap.set(G,H),H.then(function(J){if(Y.valueMap.get(G)===H){switch(r_(Y,Z),B1(Y,Z,J),$){case"atom":Z5(Y,Z);break;case"readonly_pure_selector":case"writable_pure_selector":Z7(Y,G);break}s_(Y),_.next({newValue:J,oldValue:H})}}).catch((Q)=>{Y.logger.error("\uD83D\uDCA5",Z.type,G,"rejected:",Q)}),H}return Y.logger.info("\uD83D\uDCDD",Z.type,Z.key,"writing to cache",X),Y.valueMap.set(G,X),X}function RF(Y,Z,X){Y.logger.info("\uD83D\uDCD6",Z.type,Z.key,"reading cached value");let G=Y.valueMap.get(Z.key);if(X==="mut"&&Z.type==="mutable_atom"&&E1(Y)){let _=Z,{parent:$}=Y;if(Y.valueMap.hasOwn(_.key))return G;let W=$.valueMap.get(_.key);Y.logger.info("\uD83D\uDCC3","atom",_.key,"copying");let H=W.toJSON(),Q=_.class.fromJSON(H);Y.valueMap.set(_.key,Q),new eZ(_,$),G=Q}return G}function Y7(Y,Z){let X=Y.valueMap.get(Z);if(X instanceof uZ){let G=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if(G)G.getFrom(Y);return}if(Y.operation.open)Y.operation.prev.set(Z,X);Y.valueMap.delete(Z),Y.logger.info("\uD83D\uDDD1","state",Z,"evicted")}function Z5(Y,Z){let X=Y0(Y),{key:G,type:_}=Z,$=X.selectorAtoms.getRelatedKeys(G);if(X.logger.info("\uD83E\uDDF9",_,G,$?`evicting ${$.size} states downstream:`:"no downstream states",$??"to evict"),$){if(X.operation.open)X.logger.info("\uD83E\uDDF9",_,G,`[ ${[...X.operation.done].join(", ")} ] already done`);for(let W of $){if(t_(X,W))continue;Y7(X,W),B6(X,W)}}}function Z7(Y,Z){let X=Y0(Y),G=X.selectorGraph.getRelationEntries({upstreamSelectorKey:Z}).filter(([_,{source:$}])=>$===Z);for(let[_]of G){if(t_(X,_))continue;Y7(X,_),B6(X,_),Z7(Y,_)}}function x4(Y,Z,X,G){let{key:$}=Z;Y.logger.info("\uD83D\uDD28","atom",$,"is being created");let W=Y0(Y),H=W.atoms.get($);if(H&&H.type==="atom")return Y.logger.error("\u274C","atom",$,"Tried to create atom, but it already exists in the store."),y1(H);let Q=new _0,J={...Z,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",$,`installing in store "${F.config.name}"`),x4(F,Z,X)},subject:Q};if(X)J.family=X;if(G)J.internalRoles=G;W.atoms.set($,J);let z=y1(J);if(Z.effects){let F=0,O=[];for(let L of Z.effects){let w=L({resetSelf:()=>{R6(Y,z)},setSelf:(R)=>{k1(Y,z,R)},onSet:(R)=>F8(Y,z,`effect[${F}]`,R)});if(w)O.push(w);++F}J.cleanup=()=>{for(let L of O)L()}}return Y.on.atomCreation.next(z),z}function X5(Y,Z){if("internalRoles"in Y===!1)return!1;return Y.internalRoles.includes(Z)}function X7(Y,Z){let X=Y0(Y),{key:G,family:_}=Z,$=P0(X,Z);if(!_)Y.logger.error("\u274C","atom",G,"Standalone atoms cannot be disposed.");else{$.cleanup?.();let W=Y.valueMap.get($.key),H=oZ(Y,Z),Q=P0(Y,H).subject,J={type:"state_disposal",subType:"atom",token:Z,value:W,timestamp:Date.now()};Q.next(J);let z=E1(X);if(X.atoms.delete(G),X.valueMap.delete(G),X.selectorAtoms.delete(G),X.atomsThatAreDefault.delete(G),X.moleculeData.delete(_.key,_.subKey),Y.timelineTopics.delete(G),Z.type==="mutable_atom"){let F=Y5(Z);X7(Y,F),Y.trackers.delete(G)}if(Y.logger.info("\uD83D\uDD25","atom",G,"deleted"),z&&X.transactionMeta.phase==="building"){let F=X.transactionMeta.update.subEvents.at(-1),O=F?.type==="molecule_disposal"&&F.values.some(([w])=>w===$.family?.key),L=X5($,"tracker:signal");if(!O&&!L)X.transactionMeta.update.subEvents.push(J)}else Y.on.atomDisposal.next(Z)}}function K0(Y){return Y[0].toUpperCase()+Y.slice(1)}var G7=class{toolkit;options;defaultContent;relations;states;core;transact(Y,Z){let X=this.toolkit;this.toolkit=Y,Z(this),this.toolkit=X}store;realm;[Symbol.dispose](){}constructor(Y,Z,X=F1.STORE){this.store=X,this.realm=new j_(X),this.options=Y,this.defaultContent=Z,this.store.miscResources.set(`join:${Y.key}`,this),this.realm.allocate("root",Y.key),this.toolkit={get:(...B)=>h1(X,...B),set:(...B)=>{k1(X,...B)},find:(...B)=>j0(X,...B),json:(B)=>k4(X,B)};let G=Y.between[0],_=Y.between[1],$=yZ(X,{key:`${Y.key}/relatedKeys`,class:b_},["join","relations"]);this.core={relatedKeysAtoms:$};let W=({get:B},K)=>B($,K),H=({set:B},K,C)=>{if(!this.store.molecules.has(Q0(K)))this.realm.allocate(Y.key,K);B($,K,(q)=>q.add(C)),B($,C,(q)=>q.add(K))},Q=({set:B},K,C)=>{B($,K,(N)=>{return N.delete(C),N}),B($,C,(N)=>{return N.delete(K),N});let[q,c]=[K,C].sort(),n=`${q}:${c}`;this.store.moleculeJoins.delete(n)},J=(B,K,C)=>{let{find:q,get:c,set:n}=B,N=q($,K),s=c(N);for(let p of s){if(C.includes(p))continue;n($,p,(t)=>{return t.delete(K),t})}n(N,(p)=>{return p.transaction((t)=>{t.clear();for(let I0 of C){let h0=W(B,I0),$1=h0.has(K);if(this.relations.cardinality==="1:n"){let r1=[];for(let T of h0){if(T===K)continue;let m=W(B,T);if(m.delete(I0),m.size===0)r1.push(T)}if(!$1&&h0.size>0)h0.clear();for(let T of r1){let[m,$0]=[I0,T].sort(),V0=`${m}:${$0}`;X.moleculeJoins.delete(V0)}}if(!$1)h0.add(K);t.add(I0)}return!0}),p})},z=(B,K,C)=>{let{set:q}=B;q($,K,(c)=>{return c.transaction((n)=>{for(let N of C)n.add(N);return!0}),c});for(let c of C)q($,c,(n)=>{return n.add(K),n});return!0},F=(B,K,C)=>{let q=W(B,K);return C?q.has(C):q.size>0},O={getRelatedKeys:(B)=>W(this.toolkit,B),addRelation:(B,K)=>{this.store.moleculeJoins.set(`"${B}"`,Y.key),this.store.moleculeJoins.set(`"${K}"`,Y.key),H(this.toolkit,B,K)},deleteRelation:(B,K)=>{Q(this.toolkit,B,K)},replaceRelationsSafely:(B,K)=>{J(this.toolkit,B,K)},replaceRelationsUnsafely:(B,K)=>{z(this.toolkit,B,K)},has:(B,K)=>F(this.toolkit,B,K)},L,w;if(Z){w=O2(X,{key:`${Y.key}/content`,default:Z},["join","content"]);let B=({get:C},q)=>C(w,q),K=({set:C},q,c)=>{C(w,q,c)};L=Object.assign(O,{getContent:(C)=>{return B(this.toolkit,C)},setContent:(C,q)=>{K(this.toolkit,C,q)},deleteContent:(C)=>{}})}else L=O;let R=new $4(Y,{externalStore:L,isAType:Y.isAType,isBType:Y.isBType,makeContentKey:(...B)=>{let[K,C]=B,[q,c]=B.sort(),n=`${q}:${c}`,N=X.molecules.get(Q0(K)),s=X.molecules.get(Q0(C));if(!N)this.realm.allocate(Y.key,K);if(!s)this.realm.allocate(Y.key,C);return this.realm.allocate(K,n,"all"),this.realm.claim(C,n),this.store.moleculeJoins.set(n,Y.key),n}}),b=()=>f4(X,{key:`${Y.key}/singleRelatedKey`,get:(B)=>({get:K})=>{let C=K($,B);for(let q of C)return q;return null}},["join","keys"]),x=()=>{return f4(X,{key:`${Y.key}/multipleRelatedKeys`,get:(B)=>({get:K})=>{let C=m_($,X);return K(C,B).members}},["join","keys"])},h=()=>f4(X,{key:`${Y.key}/singleRelatedEntry`,get:(B)=>({get:K})=>{let C=K($,B);for(let q of C){let c=R.isAType?.(B)?B:void 0,n=c===void 0?B:void 0;c??=q,n??=q;let N=R.makeContentKey(c,n),s=K(w,N);return[q,s]}return null}},["join","entries"]),g=()=>f4(X,{key:`${Y.key}/multipleRelatedEntries`,get:(B)=>({get:K})=>{let C=m_($,X);return K(C,B).members.map((q)=>{let c=R.isAType?.(B)?B:void 0,n=c===void 0?B:void 0;c??=q,n??=q;let N=R.makeContentKey(c,n),s=K(w,N);return[q,s]})}},["join","entries"]);switch(Y.cardinality){case"1:1":{let B=b(),K=`${G}KeyOf${K0(_)}`,C=`${_}KeyOf${K0(G)}`,q={[K]:B,[C]:B},c;if(Z){let n=h(),N=`${G}EntryOf${K0(_)}`,s=`${_}EntryOf${K0(G)}`,p={[N]:n,[s]:n};c=Object.assign(q,p)}else c=q;this.relations=R,this.states=c;break}case"1:n":{let B=b(),K=x(),C=`${G}KeyOf${K0(_)}`,q=`${_}KeysOf${K0(G)}`,c={[C]:B,[q]:K},n;if(Z){let N=h(),s=g(),p=`${G}EntryOf${K0(_)}`,t=`${_}EntriesOf${K0(G)}`,I0={[p]:N,[t]:s};n=Object.assign(c,I0)}else n=c;this.relations=R,this.states=n;break}case"n:n":{let B=x(),K=`${G}KeysOf${K0(_)}`,C=`${_}KeysOf${K0(G)}`,q={[K]:B,[C]:B},c;if(Z){let n=g(),N=`${G}EntriesOf${K0(_)}`,s=`${_}EntriesOf${K0(G)}`,p={[N]:n,[s]:n};c=Object.assign(q,p)}else c=q;this.relations=R,this.states=c}}}};function h_(Y,Z,X){return Y.joins.set(Z.key,new G7(Z,X,Y)),{key:Z.key,type:"join",a:Z.between[0],b:Z.between[1],cardinality:Z.cardinality}}function G5(Y,Z){let X=Z.joins.get(Y.key);if(X===void 0){let G=F1.STORE.joins.get(Y.key);if(G===void 0)throw Error(`Join "${Y.key}" not found in store "${Z.config.name}"`);let _=uU(Z);X=new G7(G.options,G.defaultContent,_),Z.joins.set(Y.key,X)}return X}function W8(Y,Z,X){let G=G5(Y,X),_=Y0(X);if(E1(_)){let{toolkit:$}=_.transactionMeta;G.transact($,({relations:W})=>{Z(W)})}else Z(G.relations)}function mU(Y,Z,X){let G=G5(Y,X),_;switch(Y.cardinality){case"1:1":{let $=`${Y.a}KeyOf${K0(Y.b)}`,W=`${Y.b}KeyOf${K0(Y.a)}`;_={get[$](){let Q=G.states[$];return j0(X,Q,Z)},get[W](){let Q=G.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntryOf${K0(Y.b)}`;if(H in G.states){let Q=`${Y.b}EntryOf${K0(Y.a)}`;Object.assign(_,{get[H](){let J=G.states[H];return j0(X,J,Z)},get[Q](){let J=G.states[Q];return j0(X,J,Z)}})}break}case"1:n":{let $=`${Y.a}KeyOf${K0(Y.b)}`,W=`${Y.b}KeysOf${K0(Y.a)}`;_={get[$](){let Q=G.states[$];return j0(X,Q,Z)},get[W](){let Q=G.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntryOf${K0(Y.b)}`;if(H in G.states){let Q=`${Y.b}EntriesOf${K0(Y.a)}`;Object.assign(_,{get[H](){let J=G.states[H];return j0(X,J,Z)},get[Q](){let J=G.states[Q];return j0(X,J,Z)}})}break}case"n:n":{let $=`${Y.a}KeysOf${K0(Y.b)}`,W=`${Y.b}KeysOf${K0(Y.a)}`;_={get[$](){let Q=G.states[$];return j0(X,Q,Z)},get[W](){let Q=G.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntriesOf${K0(Y.b)}`;if(H in G.states){let Q=`${Y.b}EntriesOf${K0(Y.a)}`;Object.assign(_,{get[H](){let J=G.states[H];return j0(X,J,Z)},get[Q](){let J=G.states[Q];return j0(X,J,Z)}})}}}return _}function k_(Y,Z){return G5(Y,Z).core.relatedKeysAtoms}function _7(Y){let Z={},X=0;for(let G of Y)Z[G]=X,Z[X]=G,++X;return Z}var $7="\x01",W7="\x02",H7="\x03",J7="\x04",_5=(Y)=>{switch(typeof Y){case"string":return H7+Y;case"number":return J7+Y;case"boolean":return $7+ +Y;case"object":return W7}},$5=(Y)=>{switch(Y[0]){case H7:return Y.slice(1);case J7:return+Y.slice(1);case $7:return Y.slice(1)==="1";case W7:return null}};var wF=(Y)=>{return x4(Y,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Z=new Map;for(let[X,G]of Y.atoms){if(L2(X))continue;let _=y1(G);if(G.family){let $=Z.get(G.family.key);if(!$||!("familyMembers"in $))$={key:G.family.key,familyMembers:new Map},Z.set(G.family.key,$);$.familyMembers.set(G.family.subKey,_)}else Z.set(X,_)}return Z},effects:[({setSelf:Z})=>{Y.on.atomCreation.subscribe("introspection",(X)=>{if(L2(X.key))return;Z((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W===void 0||!("familyMembers"in W))W={key:_,familyMembers:new Map},G.set(_,W);W.familyMembers.set($,X)}else G.set(X.key,X);return new Map(G)})}),Y.on.atomDisposal.subscribe("introspection",(X)=>{Z((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)G.delete(_)}}return new Map(G)})})}]},void 0)},NF=(Y)=>{return x4(Y,{key:"\uD83D\uDD0D Selector Token Index",default:()=>{let Z=new Map;for(let X of[Y.readonlySelectors,Y.writableSelectors])for(let[G,_]of X){if(L2(G))continue;let $=y1(_);if(_.family){let W=Z.get(_.family.key);if(!W||!("familyMembers"in W))W={key:_.family.key,familyMembers:new Map},Z.set(_.family.key,W);W.familyMembers.set(_.family.subKey,$)}else Z.set(G,$)}return Z},effects:[({setSelf:Z})=>{Y.on.selectorCreation.subscribe("introspection",(X)=>{if(L2(X.key))return;Z((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W===void 0||!("familyMembers"in W))W={key:_,familyMembers:new Map},G.set(_,W);W.familyMembers.set($,X)}else G.set(X.key,X);return new Map(G)})}),Y.on.selectorDisposal.subscribe("introspection",(X)=>{Z((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)G.delete(_)}}else G.delete(X.key);return new Map(G)})})}]},void 0)};var W5=class{supported;constructor(Y){this.supported=Y}refine(Y){for(let[Z,X]of Object.entries(this.supported))try{if(X(Y)===!0&&X!==Boolean)return{type:Z,data:Y}}catch(G){try{if(Y instanceof X)return{type:Z,data:Y}}catch(_){}}return null}},z7=new W5({number:(Y)=>typeof Y==="number",string:(Y)=>typeof Y==="string",boolean:(Y)=>typeof Y==="boolean",null:(Y)=>Y===null});function U7(Y){if(!Y)return!1;return Object.getPrototypeOf(Y)===Object.prototype}var F7=new W5({object:U7,array:(Y)=>Array.isArray(Y)}),IF=new W5({...z7.supported,...F7.supported}),C6=(Y)=>{if(Y===void 0)return"undefined";let Z=IF.refine(Y);if(Z)return Z.type;return Object.getPrototypeOf(Y).constructor.name};var JB=class Y{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Z=F1.STORE){this.store=Z,this.atomIndex=wF(this.store),this.selectorIndex=NF(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(Z=Y.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw Error("This Auditor has been disposed");let X=hZ(this.atomIndex),G=hZ(this.selectorIndex),_=[...X.values()].filter((Q)=>("familyMembers"in Q)),$=[...G.values()].filter((Q)=>("familyMembers"in Q)),W=performance.now(),H=[];if(Z.atomFamilies)for(let Q of _){let J=Q.familyMembers.values();for(let z of J){let F=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,O=W-F;H.push([z,O])}}if(Z.selectorFamilies)for(let Q of $){let J=Q.familyMembers.values();for(let z of J){let F=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,O=W-F;H.push([z,O])}}return H}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},Q7=(Y,Z)=>{let X=(G,_)=>{let W=((Q,J)=>{let z=Z(Q,J);if(z)return z;return null})(G,_);if(W?.jobComplete??W?.pathComplete)return W;let H=Array.isArray(_)?_.map((Q,J)=>[J,Q]):U7(_)?Object.entries(_):[];for(let[Q,J]of H){let z=X([...G,Q],J);if(z?.jobComplete)return z}return{}};X([],Y)};function KF(Y,Z){return{summary:`${Y<Z?"+":"-"}${Math.abs(Y-Z)} (${Y} \u2192 ${Z})`}}function BF(Y,Z){return{summary:`${Y.length<Z.length?"+":"-"}${Math.abs(Y.length-Z.length)} ("${Y}" \u2192 "${Z}")`}}function TF(Y,Z){return{summary:`${Y} \u2192 ${Z}`}}function E7(Y,Z,X){let G="",_=[],$=[],W=[];return Q7(Y,(H,Q)=>{let J;for(J of H){let z=Z[J];if(z===void 0)$.push([J,JSON.stringify(Q)]);else{let F=X(Q,z);if(F.summary!=="No Change")W.push([J,F])}}}),Q7(Z,(H,Q)=>{let J;for(J of H)if(Y[J]===void 0)_.push([J,JSON.stringify(Q)])}),G=`\uFF5E${W.length} \uFF0B${_.length} \uFF0D${$.length}`,{summary:G,added:_,removed:$,changed:W}}function CF(Y,Z,X){return E7(Y,Z,X)}var qF=class{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(Y,Z,X){this.leafRefinery=Y,this.treeRefinery=Z,this.leafDiffers={},this.treeDiffers={};for(let G of Object.keys(Y.supported)){let _=X[G];this.leafDiffers[G]=_}for(let G of Object.keys(Z.supported)){let _=X[G];this.treeDiffers[G]=_}}diff(Y,Z){if(Y===Z)return{summary:"No Change"};let X=this.leafRefinery.refine(Y)??this.treeRefinery.refine(Y),G=this.leafRefinery.refine(Z)??this.treeRefinery.refine(Z);if(X!==null&&G!==null){if(X.type===G.type){if(X.type in this.leafDiffers)return this.leafDiffers[X.type](X.data,G.data);if(X.type in this.treeDiffers)return this.treeDiffers[X.type](X.data,G.data,(W,H)=>this.diff(W,H))}}let _=C6(Y),$=C6(Z);if(_===$)return{summary:`${_} \u2192 ${$}`};return{summary:`Type change: ${_} \u2192 ${$}`}}},QB=new qF(z7,F7,{number:KF,string:BF,boolean:TF,null:()=>({summary:"No Change"}),object:E7,array:CF});var V7=_7(["add","delete","clear"]),b4=class Y extends Set{mode="record";subject=new _0;constructor(Z){super(Z);if(Z instanceof Y);}READONLY_VIEW=this;toJSON(){return[...this]}static fromJSON(Z){return new Y(Z)}add(Z){let X=super.add(Z);if(this.mode==="record")this.emit({type:"add",value:Z});return X}clear(){let Z=this.mode==="record"?[...this]:null;if(super.clear(),Z)this.emit({type:"clear",values:Z})}delete(Z){let X=super.delete(Z);if(this.mode==="record")this.emit({type:"delete",value:Z});return X}subscribe(Z,X){return this.subject.subscribe(Z,X)}emit(Z){this.subject.next(Y.packUpdate(Z))}do(Z){this.mode="playback";let X=Y.unpackUpdate(Z);switch(X.type){case"add":this.add(X.value);break;case"delete":this.delete(X.value);break;case"clear":this.clear()}return this.mode="record",null}undo(Z){let X=Y.unpackUpdate(Z);switch(this.mode="playback",X.type){case"add":this.delete(X.value);break;case"delete":this.add(X.value);break;case"clear":{let G=X.values;for(let _ of G)this.add(_)}}return this.mode="record",null}static packUpdate(Z){let X=V7[Z.type]+"\x1F";if(Z.type==="clear")return X+Z.values.map(_5).join("\x1E");return X+_5(Z.value)}static unpackUpdate(Z){let[X,G]=Z.split("\x1F"),_=V7[X];if(_==="clear")return{type:"clear",values:G.split("\x1E").map($5)};return{type:_,value:$5(G)}}};var jF=V2({key:"mutex",default:!1}),PF=class extends Map{set(Y,Z){if(this.has(Y))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:Y,value:Z}),this;return super.set(Y,Z)}},LB=class Y{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Z){this.key=Z}static existing=new PF;static create(Z,X){let G=new Y(Z),{type:_,globals:$,actions:W,perspectives:H}=X(G),Q={type:_,key:Z,globals:$,actions:W,perspectives:H};return Y.existing.set(Z,Q),Q}add(...Z){switch(Z[0].type){case"atom":case"mutable_atom":this.globals.push(...Z);break;case"transaction":this.actions.push(...Z);break;case"atom_family":case"mutable_atom_family":{let[X,G]=Z;this.perspectives.push({type:"realtime_perspective",resourceAtoms:X,viewAtoms:G})}break}return this}};var MB=E2({key:"usersInRoomIndex",class:b4}),O7=E2({key:"roomIndex",class:b4}),SF={enteredAtEpoch:0},V8=O6({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(Y)=>typeof Y==="string",isBType:(Y)=>typeof Y==="string"},SF),AB=D6({key:"usersInMyRoomView",get:(Y)=>({find:Z})=>{let X=C_(V8);return[Z(X,Y)]}});var jB=V2({key:"redactor",default:{occlude:(Y)=>Y}}),PB=V2({key:"unacknowledgedUpdates",default:()=>[]});var H5=class{listeners;globalListeners;handleEvent(...Y){let[Z,...X]=Y;for(let _ of this.globalListeners)_(Z,...X);let G=this.listeners.get(Z);if(G)for(let _ of G)_(...X)}id="no_id_retrieved";emit;constructor(Y){this.emit=Y,this.listeners=new Map,this.globalListeners=new Set}on(Y,Z){let X=this.listeners.get(Y);if(X)X.add(Z);else this.listeners.set(Y,new Set([Z]));return this}onAny(Y){return this.globalListeners.add(Y),this}off(Y,Z){let X=this.listeners.get(Y);if(X)if(Z)X.delete(Z);else this.listeners.delete(Y);return this}offAny(Y){return this.globalListeners.delete(Y),this}},SB=class extends H5{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";proc;key;logger;handleLog(Y){if(Array.isArray(Y)){let[Z,...X]=Y;switch(Z){case"i":this.logger.info(...X);break;case"w":this.logger.warn(...X);break;case"e":this.logger.error(...X);break}}}constructor(Y,Z,X){super((G,..._)=>{let $=JSON.stringify([G,..._])+"\x03",W=(H)=>{if(H.code==="EPIPE")console.error("EPIPE error during write",this.proc.stdin);this.proc.stdin.removeListener("error",W)};return this.proc.stdin.once("error",W),this.proc.stdin.write($),this});if(this.proc=Y,this.key=Z,this.logger=X??{info:(...G)=>{console.info(this.id,this.key,...G)},warn:(...G)=>{console.warn(this.id,this.key,...G)},error:(...G)=>{console.error(this.id,this.key,...G)}},this.proc.stdout.on("data",(G)=>{let _=G.toString();if(_==="ALIVE"){this.logger.info(_);return}let $=_.split("\x03"),W=$[0];$[0]=this.incompleteData+W;let H=0;for(let Q of $){if(Q==="")continue;try{let J=X1(Q);this.handleEvent(...J),this.incompleteData=""}catch(J){if(J instanceof Error)console.error(["\u274C Malformed data received from child process","",Q,"",J.message].join(`
|
|
60
|
-
\u274C `));try{if(H===0){this.incompleteData=Q;let z=X1(
|
|
61
|
-
\u274C `))}}++H}}),this.proc.stderr.on("data",(
|
|
62
|
-
\u274C `));try{if(
|
|
63
|
-
\u274C `))}}
|
|
64
|
-
\u274C `));try{if(
|
|
65
|
-
\u274C `))}}++_}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),this.proc.exit(0)}),this.proc.pid)this.id=this.proc.pid?.toString();this.on("user-joins",(Z)=>{this.logger.info("\uD83D\uDC64","user",Z,"joined");let X=`user::${Z}`,G=new vF(X);this.relays.set(Z,G),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let _ of this.relayServices){let $=_(G,X);if($)G.disposalFunctions.push($)}this.on(X,(..._)=>{G.in.next(_)}),G.out.subscribe("socket",(_)=>{this.emit(..._)})}),this.on("user-leaves",(Z)=>{let X=this.relays.get(Z);if(this.off(`relay:${Z}`),X)X.dispose(),this.relays.delete(Z)}),this.proc.stdout.write("ALIVE")}receiveRelay(Y){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(Y)}};var D7=new Map;var vB=L6({key:"joinRoom",do:(Y,Z,X,G)=>{let _={enteredAtEpoch:G};return W8(V8,($)=>{$.set({room:Z,user:X},_)},Y.env().store),_}}),xB=L6({key:"leaveRoom",do:({env:Y},Z,X)=>{W8(V8,(G)=>{G.delete({room:Z,user:X})},Y().store)}}),fB=L6({key:"destroyRoom",do:({set:Y,env:Z},X)=>{W8(V8,(_)=>{_.delete({room:X})},Z().store),Y(O7,(_)=>(_.delete(X),_));let G=D7.get(X);if(G)G.emit("exit"),D7.delete(X)}}),hB=V2({key:"sockets",default:null}),kB=E2({key:"socketsIndex",class:b4}),bB=E2({key:"usersIndex",class:b4}),yB=O6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(Y)=>Y.startsWith("user::"),isBType:(Y)=>Y.startsWith("socket::")}),gB=D6({key:"userMutualSituationalAwarenessIndexes",get:(Y)=>()=>{return[Y]}});var{file:rW,serve:nE}=globalThis.Bun;import{readFileSync as R7}from"fs";import{createServer as kF}from"http";import{createServer as bF}from"https";import{resolve as Q5}from"path";function M7(Y,Z){if(Y instanceof Promise)throw Error(Z)}function xF(Y,Z){let X={},G=[];for(let _ in Y){let $=Y[_]["~standard"].validate(Z[_]);if(M7($,`Validation must be synchronous, but ${_} returned a Promise.`),$.issues){G.push(...$.issues.map((W)=>({...W,message:W.message,path:[_,...W.path??[]]})));continue}X[_]=$.value}if(G.length)return{issues:G};return{value:X}}function J5(Y){let Z=Y.runtimeEnvStrict??Y.runtimeEnv??process.env;if(Y.emptyStringAsUndefined??!1){for(let[h,g]of Object.entries(Z))if(g==="")delete Z[h]}if(!!Y.skipValidation)return Z;let _=typeof Y.client==="object"?Y.client:{},$=typeof Y.server==="object"?Y.server:{},W=typeof Y.shared==="object"?Y.shared:{},H=Y.isServer??(typeof window>"u"||("Deno"in window)),Q=H?{...$,...W,..._}:{..._,...W},J=Y.createFinalSchema?.(Q,H)["~standard"].validate(Z)??xF(Q,Z);M7(J,"Validation must be synchronous");let z=Y.onValidationError??((h)=>{throw console.error("\u274C Invalid environment variables:",h),Error("Invalid environment variables")}),F=Y.onInvalidAccess??(()=>{throw Error("\u274C Attempted to access a server-side environment variable on the client")});if(J.issues)return z(J.issues);let O=(h)=>{if(!Y.clientPrefix)return!0;return!h.startsWith(Y.clientPrefix)&&!(h in W)},L=(h)=>{return H||!O(h)},w=(h)=>{return h==="__esModule"||h==="$$typeof"},R=(Y.extends??[]).reduce((h,g)=>{return Object.assign(h,g)},{}),b=Object.assign(R,J.value);return new Proxy(b,{get(h,g){if(typeof g!=="string")return;if(w(g))return;if(!L(g))return F(g);return Reflect.get(h,g)}})}var fF="__vite_start_time"in globalThis,hF=typeof window<"u",sB="vitest"in globalThis,W4=U1("string"),A7=U1('"true" | "false" | undefined'),g1=J5({isServer:!fF&&!hF,server:{CI:U1("string | undefined").pipe(Boolean),POSTGRES_USER:W4,POSTGRES_PASSWORD:W4,POSTGRES_DATABASE:W4,POSTGRES_HOST:W4,POSTGRES_PORT:W4.pipe((Y)=>Number.parseInt(Y,10)),BACKEND_PORT:W4.pipe((Y)=>Number.parseInt(Y,10)),RUN_WORKERS_FROM_SOURCE:A7.pipe((Y)=>Y==="true"),FRONTEND_PORT:W4.pipe((Y)=>Number.parseInt(Y,10)),FRONTEND_ORIGINS:W4.pipe.try((Y)=>JSON.parse(Y),U1("string[]")),API_KEY_OPENAI:U1("string | undefined"),API_KEY_RESEND:U1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:W4,VITE_DEV_FRONTEND_HOST:U1("string | undefined"),VITE_DEV_HTTPS:A7.pipe((Y)=>Y==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var w7=Q5(import.meta.dirname,"../dev"),q6=g1.VITE_DEV_HTTPS?{cert:R7(Q5(w7,"./cert.pem"),"utf-8"),key:R7(Q5(w7,"./key.pem"),"utf-8")}:void 0;function GT(Y){if(q6)return bF(q6,Y);return kF({},Y)}import mE from"path";var E=Symbol.for("drizzle:entityKind");function M(Y,Z){if(!Y||typeof Y!=="object")return!1;if(Y instanceof Z)return!0;if(!Object.prototype.hasOwnProperty.call(Z,E))throw Error(`Class "${Z.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let X=Object.getPrototypeOf(Y).constructor;if(X)while(X){if(E in X&&X[E]===Z[E])return!0;X=Object.getPrototypeOf(X)}return!1}class F0{constructor(Y,Z){this.table=Y,this.config=Z,this.name=Z.name,this.keyAsName=Z.keyAsName,this.notNull=Z.notNull,this.default=Z.default,this.defaultFn=Z.defaultFn,this.onUpdateFn=Z.onUpdateFn,this.hasDefault=Z.hasDefault,this.primary=Z.primaryKey,this.isUnique=Z.isUnique,this.uniqueName=Z.uniqueName,this.uniqueType=Z.uniqueType,this.dataType=Z.dataType,this.columnType=Z.columnType,this.generated=Z.generated,this.generatedIdentity=Z.generatedIdentity}static[E]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(Y){return Y}mapToDriverValue(Y){return Y}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class z5{static[E]="ColumnBuilder";config;constructor(Y,Z,X){this.config={name:Y,keyAsName:Y==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:Z,columnType:X,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(Y){return this.config.default=Y,this.config.hasDefault=!0,this}$defaultFn(Y){return this.config.defaultFn=Y,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(Y){return this.config.onUpdateFn=Y,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(Y){if(this.config.name!=="")return;this.config.name=Y}}var p1=Symbol.for("drizzle:Name");class U5{static[E]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(Y,Z){if(this.reference=()=>{let{name:X,columns:G,foreignColumns:_}=Y();return{name:X,columns:G,foreignTable:_[0].table,foreignColumns:_}},Z)this._onUpdate=Z.onUpdate,this._onDelete=Z.onDelete}onUpdate(Y){return this._onUpdate=Y===void 0?"no action":Y,this}onDelete(Y){return this._onDelete=Y===void 0?"no action":Y,this}build(Y){return new N7(Y,this)}}class N7{constructor(Y,Z){this.table=Y,this.reference=Z.reference,this.onUpdate=Z._onUpdate,this.onDelete=Z._onDelete}static[E]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:Y,columns:Z,foreignColumns:X}=this.reference(),G=Z.map((W)=>W.name),_=X.map((W)=>W.name),$=[this.table[p1],...G,X[0].table[p1],..._];return Y??`${$.join("_")}_fk`}}function j6(Y,...Z){return Y(...Z)}function I7(Y,Z){return`${Y[p1]}_${Z.join("_")}_unique`}function K7(Y,Z,X){for(let G=Z;G<Y.length;G++){let _=Y[G];if(_==="\\"){G++;continue}if(_==='"')return[Y.slice(Z,G).replace(/\\/g,""),G+1];if(X)continue;if(_===","||_==="}")return[Y.slice(Z,G).replace(/\\/g,""),G]}return[Y.slice(Z).replace(/\\/g,""),Y.length]}function B7(Y,Z=0){let X=[],G=Z,_=!1;while(G<Y.length){let $=Y[G];if($===","){if(_||G===Z)X.push("");_=!0,G++;continue}if(_=!1,$==="\\"){G+=2;continue}if($==='"'){let[Q,J]=K7(Y,G+1,!0);X.push(Q),G=J;continue}if($==="}")return[X,G+1];if($==="{"){let[Q,J]=B7(Y,G+1);X.push(Q),G=J;continue}let[W,H]=K7(Y,G,!1);X.push(W),G=H}return[X,G]}function T7(Y){let[Z]=B7(Y,1);return Z}function F5(Y){return`{${Y.map((Z)=>{if(Array.isArray(Z))return F5(Z);if(typeof Z==="string")return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Z}`}).join(",")}}`}class k extends z5{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(Y){return new q7(this.config.name,this,Y)}references(Y,Z={}){return this.foreignKeyConfigs.push({ref:Y,actions:Z}),this}unique(Y,Z){return this.config.isUnique=!0,this.config.uniqueName=Y,this.config.uniqueType=Z?.nulls,this}generatedAlwaysAs(Y){return this.config.generated={as:Y,type:"always",mode:"stored"},this}buildForeignKeys(Y,Z){return this.foreignKeyConfigs.map(({ref:X,actions:G})=>{return j6((_,$)=>{let W=new U5(()=>{let H=_();return{columns:[Y],foreignColumns:[H]}});if($.onUpdate)W.onUpdate($.onUpdate);if($.onDelete)W.onDelete($.onDelete);return W.build(Z)},X,G)})}buildExtraConfigColumn(Y){return new C7(Y,this.config)}}class j extends F0{constructor(Y,Z){if(!Z.uniqueName)Z.uniqueName=I7(Y,[Z.name]);super(Y,Z);this.table=Y}static[E]="PgColumn"}class C7 extends j{static[E]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(Y){return this.indexConfig.opClass=Y,this}}class O8{static[E]="IndexedColumn";constructor(Y,Z,X,G){this.name=Y,this.keyAsName=Z,this.type=X,this.indexConfig=G}name;keyAsName;type;indexConfig}class q7 extends k{static[E]="PgArrayBuilder";constructor(Y,Z,X){super(Y,"array","PgArray");this.config.baseBuilder=Z,this.config.size=X}build(Y){let Z=this.config.baseBuilder.build(Y);return new E5(Y,this.config,Z)}}class E5 extends j{constructor(Y,Z,X,G){super(Y,Z);this.baseColumn=X,this.range=G,this.size=Z.size}size;static[E]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(Y){if(typeof Y==="string")Y=T7(Y);return Y.map((Z)=>this.baseColumn.mapFromDriverValue(Z))}mapToDriverValue(Y,Z=!1){let X=Y.map((G)=>G===null?null:M(this.baseColumn,E5)?this.baseColumn.mapToDriverValue(G,!0):this.baseColumn.mapToDriverValue(G));if(Z)return X;return F5(X)}}class j7 extends k{static[E]="PgEnumObjectColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumObjectColumn");this.config.enum=Z}build(Y){return new P7(Y,this.config)}}class P7 extends j{static[E]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}var P6=Symbol.for("drizzle:isPgEnum");function S7(Y){return!!Y&&typeof Y==="function"&&P6 in Y&&Y[P6]===!0}class v7 extends k{static[E]="PgEnumColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumColumn");this.config.enum=Z}build(Y){return new x7(Y,this.config)}}class x7 extends j{static[E]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}function D8(Y,Z){return Array.isArray(Z)?yF(Y,[...Z],void 0):gF(Y,Z,void 0)}function yF(Y,Z,X){let G=Object.assign((_)=>new v7(_??"",G),{enumName:Y,enumValues:Z,schema:X,[P6]:!0});return G}function gF(Y,Z,X){let G=Object.assign((_)=>new j7(_??"",G),{enumName:Y,enumValues:Object.values(Z),schema:X,[P6]:!0});return G}class S0{static[E]="Subquery";constructor(Y,Z,X,G=!1,_=[]){this._={brand:"Subquery",sql:Y,selectedFields:Z,alias:X,isWith:G,usedTables:_}}}class L8 extends S0{static[E]="WithSubquery"}var f7="0.44.5";var V5,O5,E0={startActiveSpan(Y,Z){if(!V5)return Z();if(!O5)O5=V5.trace.getTracer("drizzle-orm",f7);return j6((X,G)=>G.startActiveSpan(Y,(_)=>{try{return Z(_)}catch($){throw _.setStatus({code:X.SpanStatusCode.ERROR,message:$ instanceof Error?$.message:"Unknown error"}),$}finally{_.end()}}),V5,O5)}};var M0=Symbol.for("drizzle:ViewBaseConfig");var y4=Symbol.for("drizzle:Schema"),S6=Symbol.for("drizzle:Columns"),h7=Symbol.for("drizzle:ExtraConfigColumns"),D5=Symbol.for("drizzle:OriginalName"),L5=Symbol.for("drizzle:BaseName"),M8=Symbol.for("drizzle:IsAlias"),k7=Symbol.for("drizzle:ExtraConfigBuilder"),pF=Symbol.for("drizzle:IsDrizzleTable");class P{static[E]="Table";static Symbol={Name:p1,Schema:y4,OriginalName:D5,Columns:S6,ExtraConfigColumns:h7,BaseName:L5,IsAlias:M8,ExtraConfigBuilder:k7};[p1];[D5];[y4];[S6];[h7];[L5];[M8]=!1;[pF]=!0;[k7]=void 0;constructor(Y,Z,X){this[p1]=this[D5]=Y,this[y4]=Z,this[L5]=X}}function d0(Y){return Y[p1]}function g4(Y){return`${Y[y4]??"public"}.${Y[p1]}`}function M5(Y){return Y!==null&&Y!==void 0&&typeof Y.getSQL==="function"}function mF(Y){let Z={sql:"",params:[]};for(let X of Y)if(Z.sql+=X.sql,Z.params.push(...X.params),X.typings?.length){if(!Z.typings)Z.typings=[];Z.typings.push(...X.typings)}return Z}class m0{static[E]="StringChunk";value;constructor(Y){this.value=Array.isArray(Y)?Y:[Y]}getSQL(){return new f([this])}}class f{constructor(Y){this.queryChunks=Y;for(let Z of Y)if(M(Z,P)){let X=Z[P.Symbol.Schema];this.usedTables.push(X===void 0?Z[P.Symbol.Name]:X+"."+Z[P.Symbol.Name])}}static[E]="SQL";decoder=y7;shouldInlineParams=!1;usedTables=[];append(Y){return this.queryChunks.push(...Y.queryChunks),this}toQuery(Y){return E0.startActiveSpan("drizzle.buildSQL",(Z)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,Y);return Z?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams(Y,Z){let X=Object.assign({},Z,{inlineParams:Z.inlineParams||this.shouldInlineParams,paramStartIndex:Z.paramStartIndex||{value:0}}),{casing:G,escapeName:_,escapeParam:$,prepareTyping:W,inlineParams:H,paramStartIndex:Q}=X;return mF(Y.map((J)=>{if(M(J,m0))return{sql:J.value.join(""),params:[]};if(M(J,v6))return{sql:_(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let z=[new m0("(")];for(let[F,O]of J.entries())if(z.push(O),F<J.length-1)z.push(new m0(", "));return z.push(new m0(")")),this.buildQueryFromSourceParams(z,X)}if(M(J,f))return this.buildQueryFromSourceParams(J.queryChunks,{...X,inlineParams:H||J.shouldInlineParams});if(M(J,P)){let z=J[P.Symbol.Schema],F=J[P.Symbol.Name];return{sql:z===void 0||J[M8]?_(F):_(z)+"."+_(F),params:[]}}if(M(J,F0)){let z=G.getColumnCasing(J);if(Z.invokeSource==="indexes")return{sql:_(z),params:[]};let F=J.table[P.Symbol.Schema];return{sql:J.table[M8]||F===void 0?_(J.table[P.Symbol.Name])+"."+_(z):_(F)+"."+_(J.table[P.Symbol.Name])+"."+_(z),params:[]}}if(M(J,V1)){let z=J[M0].schema,F=J[M0].name;return{sql:z===void 0||J[M0].isAlias?_(F):_(z)+"."+_(F),params:[]}}if(M(J,A1)){if(M(J.value,w4))return{sql:$(Q.value++,J),params:[J],typings:["none"]};let z=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(M(z,f))return this.buildQueryFromSourceParams([z],X);if(H)return{sql:this.mapInlineParam(z,X),params:[]};let F=["none"];if(W)F=[W(J.encoder)];return{sql:$(Q.value++,z),params:[z],typings:F}}if(M(J,w4))return{sql:$(Q.value++,J),params:[J],typings:["none"]};if(M(J,f.Aliased)&&J.fieldAlias!==void 0)return{sql:_(J.fieldAlias),params:[]};if(M(J,S0)){if(J._.isWith)return{sql:_(J._.alias),params:[]};return this.buildQueryFromSourceParams([new m0("("),J._.sql,new m0(") "),new v6(J._.alias)],X)}if(S7(J)){if(J.schema)return{sql:_(J.schema)+"."+_(J.enumName),params:[]};return{sql:_(J.enumName),params:[]}}if(M5(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],X);return this.buildQueryFromSourceParams([new m0("("),J.getSQL(),new m0(")")],X)}if(H)return{sql:this.mapInlineParam(J,X),params:[]};return{sql:$(Q.value++,J),params:[J],typings:["none"]}}))}mapInlineParam(Y,{escapeString:Z}){if(Y===null)return"null";if(typeof Y==="number"||typeof Y==="boolean")return Y.toString();if(typeof Y==="string")return Z(Y);if(typeof Y==="object"){let X=Y.toString();if(X==="[object Object]")return Z(JSON.stringify(Y));return Z(X)}throw Error("Unexpected param value: "+Y)}getSQL(){return this}as(Y){if(Y===void 0)return this;return new f.Aliased(this,Y)}mapWith(Y){return this.decoder=typeof Y==="function"?{mapFromDriverValue:Y}:Y,this}inlineParams(){return this.shouldInlineParams=!0,this}if(Y){return Y?this:void 0}}class v6{constructor(Y){this.value=Y}static[E]="Name";brand;getSQL(){return new f([this])}}function b7(Y){return typeof Y==="object"&&Y!==null&&"mapToDriverValue"in Y&&typeof Y.mapToDriverValue==="function"}var y7={mapFromDriverValue:(Y)=>Y},g7={mapToDriverValue:(Y)=>Y},oT={...y7,...g7};class A1{constructor(Y,Z=g7){this.value=Y,this.encoder=Z}static[E]="Param";brand;getSQL(){return new f([this])}}function V(Y,...Z){let X=[];if(Z.length>0||Y.length>0&&Y[0]!=="")X.push(new m0(Y[0]));for(let[G,_]of Z.entries())X.push(_,new m0(Y[G+1]));return new f(X)}((Y)=>{function Z(){return new f([])}Y.empty=Z;function X(Q){return new f(Q)}Y.fromList=X;function G(Q){return new f([new m0(Q)])}Y.raw=G;function _(Q,J){let z=[];for(let[F,O]of Q.entries()){if(F>0&&J!==void 0)z.push(J);z.push(O)}return new f(z)}Y.join=_;function $(Q){return new v6(Q)}Y.identifier=$;function W(Q){return new w4(Q)}Y.placeholder=W;function H(Q,J){return new A1(Q,J)}Y.param=H})(V||(V={}));((Y)=>{class Z{constructor(X,G){this.sql=X,this.fieldAlias=G}static[E]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Z(this.sql,this.fieldAlias)}}Y.Aliased=Z})(f||(f={}));class w4{constructor(Y){this.name=Y}static[E]="Placeholder";getSQL(){return new f([this])}}function A5(Y,Z){return Y.map((X)=>{if(M(X,w4)){if(!(X.name in Z))throw Error(`No value for placeholder "${X.name}" was provided`);return Z[X.name]}if(M(X,A1)&&M(X.value,w4)){if(!(X.value.name in Z))throw Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue(Z[X.value.name])}return X})}var uF=Symbol.for("drizzle:IsDrizzleView");class V1{static[E]="View";[M0];[uF]=!0;constructor({name:Y,schema:Z,selectedFields:X,query:G}){this[M0]={name:Y,originalName:Y,schema:Z,selectedFields:X,query:G,isExisting:!G,isAlias:!1}}getSQL(){return new f([this])}}F0.prototype.getSQL=function(){return new f([this])};P.prototype.getSQL=function(){return new f([this])};S0.prototype.getSQL=function(){return new f([this])};class M2{constructor(Y){this.table=Y}static[E]="ColumnAliasProxyHandler";get(Y,Z){if(Z==="table")return this.table;return Y[Z]}}class A8{constructor(Y,Z){this.alias=Y,this.replaceOriginalName=Z}static[E]="TableAliasProxyHandler";get(Y,Z){if(Z===P.Symbol.IsAlias)return!0;if(Z===P.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Z===P.Symbol.OriginalName)return this.alias;if(Z===M0)return{...Y[M0],name:this.alias,isAlias:!0};if(Z===P.Symbol.Columns){let G=Y[P.Symbol.Columns];if(!G)return G;let _={};return Object.keys(G).map(($)=>{_[$]=new Proxy(G[$],new M2(new Proxy(Y,this)))}),_}let X=Y[Z];if(M(X,F0))return new Proxy(X,new M2(new Proxy(Y,this)));return X}}function x6(Y,Z){return new Proxy(Y,new A8(Z,!1))}function i1(Y,Z){return new Proxy(Y,new M2(new Proxy(Y.table,new A8(Z,!1))))}function R5(Y,Z){return new f.Aliased(R8(Y.sql,Z),Y.fieldAlias)}function R8(Y,Z){return V.join(Y.queryChunks.map((X)=>{if(M(X,F0))return i1(X,Z);if(M(X,f))return R8(X,Z);if(M(X,f.Aliased))return R5(X,Z);return X}))}class f6 extends Error{static[E]="DrizzleError";constructor({message:Y,cause:Z}){super(Y);this.name="DrizzleError",this.cause=Z}}class H4 extends Error{constructor(Y,Z,X){super(`Failed query: ${Y}
|
|
66
|
-
params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrace(this,H4),X)this.cause=X}}class w5 extends f6{static[E]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class p7{static[E]="ConsoleLogWriter";write(Y){console.log(Y)}}class N5{static[E]="DefaultLogger";writer;constructor(Y){this.writer=Y?.writer??new p7}logQuery(Y,Z){let X=Z.map((_)=>{try{return JSON.stringify(_)}catch{return String(_)}}),G=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${Y}${G}`)}}class I5{static[E]="NoopLogger";logQuery(){}}class G1{static[E]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(Y){return this.then(void 0,Y)}finally(Y){return this.then((Z)=>{return Y?.(),Z},(Z)=>{throw Y?.(),Z})}then(Y,Z){return this.execute().then(Y,Z)}}function m7(Y,Z,X){let G={},_=Y.reduce(($,{path:W,field:H},Q)=>{let J;if(M(H,F0))J=H;else if(M(H,f))J=H.decoder;else J=H.sql.decoder;let z=$;for(let[F,O]of W.entries())if(F<W.length-1){if(!(O in z))z[O]={};z=z[O]}else{let L=Z[Q],w=z[O]=L===null?null:J.mapFromDriverValue(L);if(X&&M(H,F0)&&W.length===2){let R=W[0];if(!(R in G))G[R]=w===null?d0(H.table):!1;else if(typeof G[R]==="string"&&G[R]!==d0(H.table))G[R]=!1}}return $},{});if(X&&Object.keys(G).length>0){for(let[$,W]of Object.entries(G))if(typeof W==="string"&&!X[W])_[$]=null}return _}function T1(Y,Z){return Object.entries(Y).reduce((X,[G,_])=>{if(typeof G!=="string")return X;let $=Z?[...Z,G]:[G];if(M(_,F0)||M(_,f)||M(_,f.Aliased))X.push({path:$,field:_});else if(M(_,P))X.push(...T1(_[P.Symbol.Columns],$));else X.push(...T1(_,$));return X},[])}function w8(Y,Z){let X=Object.keys(Y),G=Object.keys(Z);if(X.length!==G.length)return!1;for(let[_,$]of X.entries())if($!==G[_])return!1;return!0}function h6(Y,Z){let X=Object.entries(Z).filter(([,G])=>G!==void 0).map(([G,_])=>{if(M(_,f)||M(_,F0))return[G,_];else return[G,new A1(_,Y[P.Symbol.Columns][G])]});if(X.length===0)throw Error("No values to set");return Object.fromEntries(X)}function u7(Y,Z){for(let X of Z)for(let G of Object.getOwnPropertyNames(X.prototype)){if(G==="constructor")continue;Object.defineProperty(Y.prototype,G,Object.getOwnPropertyDescriptor(X.prototype,G)||Object.create(null))}}function d7(Y){return Y[P.Symbol.Columns]}function J4(Y){return M(Y,S0)?Y._.alias:M(Y,V1)?Y[M0].name:M(Y,f)?void 0:Y[P.Symbol.IsAlias]?Y[P.Symbol.Name]:Y[P.Symbol.BaseName]}function X0(Y,Z){return{name:typeof Y==="string"&&Y.length>0?Y:"",config:typeof Y==="object"?Y:Z}}function c7(Y){if(typeof Y!=="object"||Y===null)return!1;if(Y.constructor.name!=="Object")return!1;if("logger"in Y){let Z=typeof Y.logger;if(Z!=="boolean"&&(Z!=="object"||typeof Y.logger.logQuery!=="function")&&Z!=="undefined")return!1;return!0}if("schema"in Y){let Z=typeof Y.schema;if(Z!=="object"&&Z!=="undefined")return!1;return!0}if("casing"in Y){let Z=typeof Y.casing;if(Z!=="string"&&Z!=="undefined")return!1;return!0}if("mode"in Y){if(Y.mode!=="default"||Y.mode!=="planetscale"||Y.mode!==void 0)return!1;return!0}if("connection"in Y){let Z=typeof Y.connection;if(Z!=="string"&&Z!=="object"&&Z!=="undefined")return!1;return!0}if("client"in Y){let Z=typeof Y.client;if(Z!=="object"&&Z!=="function"&&Z!=="undefined")return!1;return!0}if(Object.keys(Y).length===0)return!0;return!1}class N4 extends k{static[E]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(Y){if(Y){let{name:Z,...X}=Y;this.config.generatedIdentity={type:"always",sequenceName:Z,sequenceOptions:X}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(Y){if(Y){let{name:Z,...X}=Y;this.config.generatedIdentity={type:"byDefault",sequenceName:Z,sequenceOptions:X}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class l7 extends N4{static[E]="PgBigInt53Builder";constructor(Y){super(Y,"number","PgBigInt53")}build(Y){return new o7(Y,this.config)}}class o7 extends j{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class i7 extends N4{static[E]="PgBigInt64Builder";constructor(Y){super(Y,"bigint","PgBigInt64")}build(Y){return new n7(Y,this.config)}}class n7 extends j{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(Y){return BigInt(Y)}}function r7(Y,Z){let{name:X,config:G}=X0(Y,Z);if(G.mode==="number")return new l7(X);return new i7(X)}class s7 extends k{static[E]="PgBigSerial53Builder";constructor(Y){super(Y,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new t7(Y,this.config)}}class t7 extends j{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class a7 extends k{static[E]="PgBigSerial64Builder";constructor(Y){super(Y,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(Y){return new e7(Y,this.config)}}class e7 extends j{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(Y){return BigInt(Y)}}function Y$(Y,Z){let{name:X,config:G}=X0(Y,Z);if(G.mode==="number")return new s7(X);return new a7(X)}class Z$ extends k{static[E]="PgBooleanBuilder";constructor(Y){super(Y,"boolean","PgBoolean")}build(Y){return new X$(Y,this.config)}}class X$ extends j{static[E]="PgBoolean";getSQLType(){return"boolean"}}function N8(Y){return new Z$(Y??"")}class G$ extends k{static[E]="PgCharBuilder";constructor(Y,Z){super(Y,"string","PgChar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new _$(Y,this.config)}}class _$ extends j{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function $$(Y,Z={}){let{name:X,config:G}=X0(Y,Z);return new G$(X,G)}class W$ extends k{static[E]="PgCidrBuilder";constructor(Y){super(Y,"string","PgCidr")}build(Y){return new H$(Y,this.config)}}class H$ extends j{static[E]="PgCidr";getSQLType(){return"cidr"}}function J$(Y){return new W$(Y??"")}class Q$ extends k{static[E]="PgCustomColumnBuilder";constructor(Y,Z,X){super(Y,"custom","PgCustomColumn");this.config.fieldConfig=Z,this.config.customTypeParams=X}build(Y){return new z$(Y,this.config)}}class z$ extends j{static[E]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(Y,Z){super(Y,Z);this.sqlName=Z.customTypeParams.dataType(Z.fieldConfig),this.mapTo=Z.customTypeParams.toDriver,this.mapFrom=Z.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(Y){return typeof this.mapFrom==="function"?this.mapFrom(Y):Y}mapToDriverValue(Y){return typeof this.mapTo==="function"?this.mapTo(Y):Y}}function U$(Y){return(Z,X)=>{let{name:G,config:_}=X0(Z,X);return new Q$(G,_,Y)}}class Q4 extends k{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(V`now()`)}}class F$ extends Q4{static[E]="PgDateBuilder";constructor(Y){super(Y,"date","PgDate")}build(Y){return new k6(Y,this.config)}}class k6 extends j{static[E]="PgDate";getSQLType(){return"date"}mapFromDriverValue(Y){return new Date(Y)}mapToDriverValue(Y){return Y.toISOString()}}class E$ extends Q4{static[E]="PgDateStringBuilder";constructor(Y){super(Y,"string","PgDateString")}build(Y){return new b6(Y,this.config)}}class b6 extends j{static[E]="PgDateString";getSQLType(){return"date"}}function V$(Y,Z){let{name:X,config:G}=X0(Y,Z);if(G?.mode==="date")return new F$(X);return new E$(X)}class O$ extends k{static[E]="PgDoublePrecisionBuilder";constructor(Y){super(Y,"number","PgDoublePrecision")}build(Y){return new D$(Y,this.config)}}class D$ extends j{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function L$(Y){return new O$(Y??"")}class M$ extends k{static[E]="PgInetBuilder";constructor(Y){super(Y,"string","PgInet")}build(Y){return new A$(Y,this.config)}}class A$ extends j{static[E]="PgInet";getSQLType(){return"inet"}}function R$(Y){return new M$(Y??"")}class w$ extends N4{static[E]="PgIntegerBuilder";constructor(Y){super(Y,"number","PgInteger")}build(Y){return new N$(Y,this.config)}}class N$ extends j{static[E]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseInt(Y);return Y}}function I8(Y){return new w$(Y??"")}class I$ extends k{static[E]="PgIntervalBuilder";constructor(Y,Z){super(Y,"string","PgInterval");this.config.intervalConfig=Z}build(Y){return new K$(Y,this.config)}}class K$ extends j{static[E]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let Y=this.fields?` ${this.fields}`:"",Z=this.precision?`(${this.precision})`:"";return`interval${Y}${Z}`}}function B$(Y,Z={}){let{name:X,config:G}=X0(Y,Z);return new I$(X,G)}class T$ extends k{static[E]="PgJsonBuilder";constructor(Y){super(Y,"json","PgJson")}build(Y){return new y6(Y,this.config)}}class y6 extends j{static[E]="PgJson";constructor(Y,Z){super(Y,Z)}getSQLType(){return"json"}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}}function C$(Y){return new T$(Y??"")}class q$ extends k{static[E]="PgJsonbBuilder";constructor(Y){super(Y,"json","PgJsonb")}build(Y){return new g6(Y,this.config)}}class g6 extends j{static[E]="PgJsonb";constructor(Y,Z){super(Y,Z)}getSQLType(){return"jsonb"}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}}function j$(Y){return new q$(Y??"")}class P$ extends k{static[E]="PgLineBuilder";constructor(Y){super(Y,"array","PgLine")}build(Y){return new S$(Y,this.config)}}class S$ extends j{static[E]="PgLine";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,G]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X),Number.parseFloat(G)]}mapToDriverValue(Y){return`{${Y[0]},${Y[1]},${Y[2]}}`}}class v$ extends k{static[E]="PgLineABCBuilder";constructor(Y){super(Y,"json","PgLineABC")}build(Y){return new x$(Y,this.config)}}class x$ extends j{static[E]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,G]=Y.slice(1,-1).split(",");return{a:Number.parseFloat(Z),b:Number.parseFloat(X),c:Number.parseFloat(G)}}mapToDriverValue(Y){return`{${Y.a},${Y.b},${Y.c}}`}}function f$(Y,Z){let{name:X,config:G}=X0(Y,Z);if(!G?.mode||G.mode==="tuple")return new P$(X);return new v$(X)}class h$ extends k{static[E]="PgMacaddrBuilder";constructor(Y){super(Y,"string","PgMacaddr")}build(Y){return new k$(Y,this.config)}}class k$ extends j{static[E]="PgMacaddr";getSQLType(){return"macaddr"}}function b$(Y){return new h$(Y??"")}class y$ extends k{static[E]="PgMacaddr8Builder";constructor(Y){super(Y,"string","PgMacaddr8")}build(Y){return new g$(Y,this.config)}}class g$ extends j{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}}function p$(Y){return new y$(Y??"")}class m$ extends k{static[E]="PgNumericBuilder";constructor(Y,Z,X){super(Y,"string","PgNumeric");this.config.precision=Z,this.config.scale=X}build(Y){return new p6(Y,this.config)}}class p6 extends j{static[E]="PgNumeric";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.scale}mapFromDriverValue(Y){if(typeof Y==="string")return Y;return String(Y)}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class u$ extends k{static[E]="PgNumericNumberBuilder";constructor(Y,Z,X){super(Y,"number","PgNumericNumber");this.config.precision=Z,this.config.scale=X}build(Y){return new d$(Y,this.config)}}class d$ extends j{static[E]="PgNumericNumber";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.scale}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class c$ extends k{static[E]="PgNumericBigIntBuilder";constructor(Y,Z,X){super(Y,"bigint","PgNumericBigInt");this.config.precision=Z,this.config.scale=X}build(Y){return new l$(Y,this.config)}}class l$ extends j{static[E]="PgNumericBigInt";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function o$(Y,Z){let{name:X,config:G}=X0(Y,Z),_=G?.mode;return _==="number"?new u$(X,G?.precision,G?.scale):_==="bigint"?new c$(X,G?.precision,G?.scale):new m$(X,G?.precision,G?.scale)}class i$ extends k{static[E]="PgPointTupleBuilder";constructor(Y){super(Y,"array","PgPointTuple")}build(Y){return new n$(Y,this.config)}}class n$ extends j{static[E]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(Y){if(typeof Y==="string"){let[Z,X]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X)]}return[Y.x,Y.y]}mapToDriverValue(Y){return`(${Y[0]},${Y[1]})`}}class r$ extends k{static[E]="PgPointObjectBuilder";constructor(Y){super(Y,"json","PgPointObject")}build(Y){return new s$(Y,this.config)}}class s$ extends j{static[E]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(Y){if(typeof Y==="string"){let[Z,X]=Y.slice(1,-1).split(",");return{x:Number.parseFloat(Z),y:Number.parseFloat(X)}}return Y}mapToDriverValue(Y){return`(${Y.x},${Y.y})`}}function t$(Y,Z){let{name:X,config:G}=X0(Y,Z);if(!G?.mode||G.mode==="tuple")return new i$(X);return new r$(X)}function dF(Y){let Z=[];for(let X=0;X<Y.length;X+=2)Z.push(Number.parseInt(Y.slice(X,X+2),16));return new Uint8Array(Z)}function a$(Y,Z){let X=new ArrayBuffer(8),G=new DataView(X);for(let _=0;_<8;_++)G.setUint8(_,Y[Z+_]);return G.getFloat64(0,!0)}function K5(Y){let Z=dF(Y),X=0,G=Z[X];X+=1;let _=new DataView(Z.buffer),$=_.getUint32(X,G===1);X+=4;let W;if($&536870912)W=_.getUint32(X,G===1),X+=4;if(($&65535)===1){let H=a$(Z,X);X+=8;let Q=a$(Z,X);return X+=8,[H,Q]}throw Error("Unsupported geometry type")}class e$ extends k{static[E]="PgGeometryBuilder";constructor(Y){super(Y,"array","PgGeometry")}build(Y){return new Y3(Y,this.config)}}class Y3 extends j{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){return K5(Y)}mapToDriverValue(Y){return`point(${Y[0]} ${Y[1]})`}}class Z3 extends k{static[E]="PgGeometryObjectBuilder";constructor(Y){super(Y,"json","PgGeometryObject")}build(Y){return new X3(Y,this.config)}}class X3 extends j{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){let Z=K5(Y);return{x:Z[0],y:Z[1]}}mapToDriverValue(Y){return`point(${Y.x} ${Y.y})`}}function G3(Y,Z){let{name:X,config:G}=X0(Y,Z);if(!G?.mode||G.mode==="tuple")return new e$(X);return new Z3(X)}class _3 extends k{static[E]="PgRealBuilder";constructor(Y,Z){super(Y,"number","PgReal");this.config.length=Z}build(Y){return new $3(Y,this.config)}}class $3 extends j{static[E]="PgReal";constructor(Y,Z){super(Y,Z)}getSQLType(){return"real"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function W3(Y){return new _3(Y??"")}class H3 extends k{static[E]="PgSerialBuilder";constructor(Y){super(Y,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new J3(Y,this.config)}}class J3 extends j{static[E]="PgSerial";getSQLType(){return"serial"}}function Q3(Y){return new H3(Y??"")}class z3 extends N4{static[E]="PgSmallIntBuilder";constructor(Y){super(Y,"number","PgSmallInt")}build(Y){return new U3(Y,this.config)}}class U3 extends j{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number(Y);return Y}}function F3(Y){return new z3(Y??"")}class E3 extends k{static[E]="PgSmallSerialBuilder";constructor(Y){super(Y,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new V3(Y,this.config)}}class V3 extends j{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}}function O3(Y){return new E3(Y??"")}class D3 extends k{static[E]="PgTextBuilder";constructor(Y,Z){super(Y,"string","PgText");this.config.enumValues=Z.enum}build(Y){return new L3(Y,this.config)}}class L3 extends j{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function M3(Y,Z={}){let{name:X,config:G}=X0(Y,Z);return new D3(X,G)}class A3 extends Q4{constructor(Y,Z,X){super(Y,"string","PgTime");this.withTimezone=Z,this.precision=X,this.config.withTimezone=Z,this.config.precision=X}static[E]="PgTimeBuilder";build(Y){return new m6(Y,this.config)}}class m6 extends j{static[E]="PgTime";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function R3(Y,Z={}){let{name:X,config:G}=X0(Y,Z);return new A3(X,G.withTimezone??!1,G.precision)}class w3 extends Q4{static[E]="PgTimestampBuilder";constructor(Y,Z,X){super(Y,"date","PgTimestamp");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new u6(Y,this.config)}}class u6 extends j{static[E]="PgTimestamp";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(Y)=>{return new Date(this.withTimezone?Y:Y+"+0000")};mapToDriverValue=(Y)=>{return Y.toISOString()}}class N3 extends Q4{static[E]="PgTimestampStringBuilder";constructor(Y,Z,X){super(Y,"string","PgTimestampString");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new d6(Y,this.config)}}class d6 extends j{static[E]="PgTimestampString";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function I3(Y,Z={}){let{name:X,config:G}=X0(Y,Z);if(G?.mode==="string")return new N3(X,G.withTimezone??!1,G.precision);return new w3(X,G?.withTimezone??!1,G?.precision)}class K3 extends k{static[E]="PgUUIDBuilder";constructor(Y){super(Y,"string","PgUUID")}defaultRandom(){return this.default(V`gen_random_uuid()`)}build(Y){return new c6(Y,this.config)}}class c6 extends j{static[E]="PgUUID";getSQLType(){return"uuid"}}function C1(Y){return new K3(Y??"")}class B3 extends k{static[E]="PgVarcharBuilder";constructor(Y,Z){super(Y,"string","PgVarchar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new T3(Y,this.config)}}class T3 extends j{static[E]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function t0(Y,Z={}){let{name:X,config:G}=X0(Y,Z);return new B3(X,G)}class C3 extends k{static[E]="PgBinaryVectorBuilder";constructor(Y,Z){super(Y,"string","PgBinaryVector");this.config.dimensions=Z.dimensions}build(Y){return new q3(Y,this.config)}}class q3 extends j{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function j3(Y,Z){let{name:X,config:G}=X0(Y,Z);return new C3(X,G)}class P3 extends k{static[E]="PgHalfVectorBuilder";constructor(Y,Z){super(Y,"array","PgHalfVector");this.config.dimensions=Z.dimensions}build(Y){return new S3(Y,this.config)}}class S3 extends j{static[E]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){return Y.slice(1,-1).split(",").map((Z)=>Number.parseFloat(Z))}}function v3(Y,Z){let{name:X,config:G}=X0(Y,Z);return new P3(X,G)}class x3 extends k{static[E]="PgSparseVectorBuilder";constructor(Y,Z){super(Y,"string","PgSparseVector");this.config.dimensions=Z.dimensions}build(Y){return new f3(Y,this.config)}}class f3 extends j{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function h3(Y,Z){let{name:X,config:G}=X0(Y,Z);return new x3(X,G)}class k3 extends k{static[E]="PgVectorBuilder";constructor(Y,Z){super(Y,"array","PgVector");this.config.dimensions=Z.dimensions}build(Y){return new b3(Y,this.config)}}class b3 extends j{static[E]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){return Y.slice(1,-1).split(",").map((Z)=>Number.parseFloat(Z))}}function y3(Y,Z){let{name:X,config:G}=X0(Y,Z);return new k3(X,G)}function g3(){return{bigint:r7,bigserial:Y$,boolean:N8,char:$$,cidr:J$,customType:U$,date:V$,doublePrecision:L$,inet:R$,integer:I8,interval:B$,json:C$,jsonb:j$,line:f$,macaddr:b$,macaddr8:p$,numeric:o$,point:t$,geometry:G3,real:W3,serial:Q3,smallint:F3,smallserial:O3,text:M3,time:R3,timestamp:I3,uuid:C1,varchar:t0,bit:j3,halfvec:v3,sparsevec:h3,vector:y3}}var B5=Symbol.for("drizzle:PgInlineForeignKeys"),p3=Symbol.for("drizzle:EnableRLS");class u0 extends P{static[E]="PgTable";static Symbol=Object.assign({},P.Symbol,{InlineForeignKeys:B5,EnableRLS:p3});[B5]=[];[p3]=!1;[P.Symbol.ExtraConfigBuilder]=void 0;[P.Symbol.ExtraConfigColumns]={}}function cF(Y,Z,X,G,_=Y){let $=new u0(Y,G,_),W=typeof Z==="function"?Z(g3()):Z,H=Object.fromEntries(Object.entries(W).map(([z,F])=>{let O=F;O.setName(z);let L=O.build($);return $[B5].push(...O.buildForeignKeys(L,$)),[z,L]})),Q=Object.fromEntries(Object.entries(W).map(([z,F])=>{let O=F;O.setName(z);let L=O.buildExtraConfigColumn($);return[z,L]})),J=Object.assign($,H);if(J[P.Symbol.Columns]=H,J[P.Symbol.ExtraConfigColumns]=Q,X)J[u0.Symbol.ExtraConfigBuilder]=X;return Object.assign(J,{enableRLS:()=>{return J[u0.Symbol.EnableRLS]=!0,J}})}var I4=(Y,Z,X)=>{return cF(Y,Z,X,void 0)};function m3(...Y){if(Y[0].columns)return new K8(Y[0].columns,Y[0].name);return new K8(Y)}class K8{static[E]="PgPrimaryKeyBuilder";columns;name;constructor(Y,Z){this.columns=Y,this.name=Z}build(Y){return new u3(Y,this.columns,this.name)}}class u3{constructor(Y,Z,X){this.table=Y,this.columns=Z,this.name=X}static[E]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[u0.Symbol.Name]}_${this.columns.map((Y)=>Y.name).join("_")}_pk`}}function O1(Y,Z){if(b7(Z)&&!M5(Y)&&!M(Y,A1)&&!M(Y,w4)&&!M(Y,F0)&&!M(Y,P)&&!M(Y,V1))return new A1(Y,Z);return Y}var l6=(Y,Z)=>{return V`${Y} = ${O1(Z,Y)}`},d3=(Y,Z)=>{return V`${Y} <> ${O1(Z,Y)}`};function B8(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new f(Z);return new f([new m0("("),V.join(Z,new m0(" and ")),new m0(")")])}function c3(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new f(Z);return new f([new m0("("),V.join(Z,new m0(" or ")),new m0(")")])}function l3(Y){return V`not ${Y}`}var o3=(Y,Z)=>{return V`${Y} > ${O1(Z,Y)}`},i3=(Y,Z)=>{return V`${Y} >= ${O1(Z,Y)}`},n3=(Y,Z)=>{return V`${Y} < ${O1(Z,Y)}`},r3=(Y,Z)=>{return V`${Y} <= ${O1(Z,Y)}`};function s3(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return V`false`;return V`${Y} in ${Z.map((X)=>O1(X,Y))}`}return V`${Y} in ${O1(Z,Y)}`}function t3(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return V`true`;return V`${Y} not in ${Z.map((X)=>O1(X,Y))}`}return V`${Y} not in ${O1(Z,Y)}`}function a3(Y){return V`${Y} is null`}function e3(Y){return V`${Y} is not null`}function YW(Y){return V`exists ${Y}`}function ZW(Y){return V`not exists ${Y}`}function XW(Y,Z,X){return V`${Y} between ${O1(Z,Y)} and ${O1(X,Y)}`}function GW(Y,Z,X){return V`${Y} not between ${O1(Z,Y)} and ${O1(X,Y)}`}function _W(Y,Z){return V`${Y} like ${Z}`}function $W(Y,Z){return V`${Y} not like ${Z}`}function WW(Y,Z){return V`${Y} ilike ${Z}`}function HW(Y,Z){return V`${Y} not ilike ${Z}`}function JW(Y){return V`${Y} asc`}function QW(Y){return V`${Y} desc`}class T5{constructor(Y,Z,X){this.sourceTable=Y,this.referencedTable=Z,this.relationName=X,this.referencedTableName=Z[P.Symbol.Name]}static[E]="Relation";referencedTableName;fieldName}class zW{constructor(Y,Z){this.table=Y,this.config=Z}static[E]="Relations"}class K4 extends T5{constructor(Y,Z,X,G){super(Y,Z,X?.relationName);this.config=X,this.isNullable=G}static[E]="One";withFieldName(Y){let Z=new K4(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Z.fieldName=Y,Z}}class T8 extends T5{constructor(Y,Z,X){super(Y,Z,X?.relationName);this.config=X}static[E]="Many";withFieldName(Y){let Z=new T8(this.sourceTable,this.referencedTable,this.config);return Z.fieldName=Y,Z}}function UW(){return{and:B8,between:XW,eq:l6,exists:YW,gt:o3,gte:i3,ilike:WW,inArray:s3,isNull:a3,isNotNull:e3,like:_W,lt:n3,lte:r3,ne:d3,not:l3,notBetween:GW,notExists:ZW,notLike:$W,notIlike:HW,notInArray:t3,or:c3,sql:V}}function FW(){return{sql:V,asc:JW,desc:QW}}function EW(Y,Z){if(Object.keys(Y).length===1&&"default"in Y&&!M(Y.default,P))Y=Y.default;let X={},G={},_={};for(let[$,W]of Object.entries(Y))if(M(W,P)){let H=g4(W),Q=G[H];X[H]=$,_[$]={tsName:$,dbName:W[P.Symbol.Name],schema:W[P.Symbol.Schema],columns:W[P.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let z of Object.values(W[P.Symbol.Columns]))if(z.primary)_[$].primaryKey.push(z);let J=W[P.Symbol.ExtraConfigBuilder]?.(W[P.Symbol.ExtraConfigColumns]);if(J){for(let z of Object.values(J))if(M(z,K8))_[$].primaryKey.push(...z.columns)}}else if(M(W,zW)){let H=g4(W.table),Q=X[H],J=W.config(Z(W.table)),z;for(let[F,O]of Object.entries(J))if(Q){let L=_[Q];if(L.relations[F]=O,z)L.primaryKey.push(...z)}else{if(!(H in G))G[H]={relations:{},primaryKey:z};G[H].relations[F]=O}}return{tables:_,tableNamesMap:X}}function lF(Y){return function(X,G){return new K4(Y,X,G,G?.fields.reduce((_,$)=>_&&$.notNull,!0)??!1)}}function oF(Y){return function(X,G){return new T8(Y,X,G)}}function VW(Y,Z,X){if(M(X,K4)&&X.config)return{fields:X.config.fields,references:X.config.references};let G=Z[g4(X.referencedTable)];if(!G)throw Error(`Table "${X.referencedTable[P.Symbol.Name]}" not found in schema`);let _=Y[G];if(!_)throw Error(`Table "${G}" not found in schema`);let $=X.sourceTable,W=Z[g4($)];if(!W)throw Error(`Table "${$[P.Symbol.Name]}" not found in schema`);let H=[];for(let Q of Object.values(_.relations))if(X.relationName&&X!==Q&&Q.relationName===X.relationName||!X.relationName&&Q.referencedTable===X.sourceTable)H.push(Q);if(H.length>1)throw X.relationName?Error(`There are multiple relations with name "${X.relationName}" in table "${G}"`):Error(`There are multiple relations between "${G}" and "${X.sourceTable[P.Symbol.Name]}". Please specify relation name`);if(H[0]&&M(H[0],K4)&&H[0].config)return{fields:H[0].config.references,references:H[0].config.fields};throw Error(`There is not enough information to infer relation "${W}.${X.fieldName}"`)}function OW(Y){return{one:lF(Y),many:oF(Y)}}function o6(Y,Z,X,G,_=($)=>$){let $={};for(let[W,H]of G.entries())if(H.isJson){let Q=Z.relations[H.tsKey],J=X[W],z=typeof J==="string"?JSON.parse(J):J;$[H.tsKey]=M(Q,K4)?z&&o6(Y,Y[H.relationTableTsKey],z,H.selection,_):z.map((F)=>o6(Y,Y[H.relationTableTsKey],F,H.selection,_))}else{let Q=_(X[W]),J=H.field,z;if(M(J,F0))z=J;else if(M(J,f))z=J.decoder;else z=J.sql.decoder;$[H.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return $}import DE from"os";import LE from"fs";var i6=new Map,C5=new Map,q5=Symbol("OriginError"),A2={};class q1 extends Promise{constructor(Y,Z,X,G,_={}){let $,W;super((H,Q)=>{$=H,W=Q});this.tagged=Array.isArray(Y.raw),this.strings=Y,this.args=Z,this.handler=X,this.canceller=G,this.options=_,this.state=null,this.statement=null,this.resolve=(H)=>(this.active=!1,$(H)),this.reject=(H)=>(this.active=!1,W(H)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[q5]=this.handler.debug?Error():this.tagged&&iF(this.strings)}get origin(){return(this.handler.debug?this[q5].stack:this.tagged&&C5.has(this.strings)?C5.get(this.strings):C5.set(this.strings,this[q5].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(Y=1,Z){if(this.options.simple=!1,typeof Y==="function")Z=Y,Y=1;if(this.cursorRows=Y,typeof Z==="function")return this.cursorFn=Z,this;let X;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};X&&X();let G=new Promise((_,$)=>{this.cursorFn=(W)=>{return _({value:W,done:!1}),new Promise((H)=>X=H)},this.resolve=()=>(this.active=!1,_({done:!0})),this.reject=(W)=>(this.active=!1,$(W))});return this.execute(),G},return(){return X&&X(A2),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw Error(".stream has been renamed to .forEach")}forEach(Y){return this.forEachFn=Y,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function iF(Y){if(i6.has(Y))return i6.get(Y);let Z=Error.stackTraceLimit;return Error.stackTraceLimit=4,i6.set(Y,Error()),Error.stackTraceLimit=Z,i6.get(Y)}class R2 extends Error{constructor(Y){super(Y.message);this.name=this.constructor.name,Object.assign(this,Y)}}var f0={connection:DW,postgres:LW,generic:MW,notSupported:AW};function DW(Y,Z,X){let{host:G,port:_}=X||Z,$=Object.assign(Error("write "+Y+" "+(Z.path||G+":"+_)),{code:Y,errno:Y,address:Z.path||G},Z.path?{}:{port:_});return Error.captureStackTrace($,DW),$}function LW(Y){let Z=new R2(Y);return Error.captureStackTrace(Z,LW),Z}function MW(Y,Z){let X=Object.assign(Error(Y+": "+Z),{code:Y});return Error.captureStackTrace(X,MW),X}function AW(Y){let Z=Object.assign(Error(Y+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:Y});return Error.captureStackTrace(Z,AW),Z}var nF={string:{to:25,from:null,serialize:(Y)=>""+Y},number:{to:0,from:[21,23,26,700,701],serialize:(Y)=>""+Y,parse:(Y)=>+Y},json:{to:114,from:[114,3802],serialize:(Y)=>JSON.stringify(Y),parse:(Y)=>JSON.parse(Y)},boolean:{to:16,from:16,serialize:(Y)=>Y===!0?"t":"f",parse:(Y)=>Y==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(Y)=>(Y instanceof Date?Y:new Date(Y)).toISOString(),parse:(Y)=>new Date(Y)},bytea:{to:17,from:17,serialize:(Y)=>"\\x"+Buffer.from(Y).toString("hex"),parse:(Y)=>Buffer.from(Y.slice(2),"hex")}};class s6{then(){j5()}catch(){j5()}finally(){j5()}}class P8 extends s6{constructor(Y){super();this.value=e6(Y)}}class n1 extends s6{constructor(Y,Z,X){super();this.value=Y,this.type=Z,this.array=X}}class t6 extends s6{constructor(Y,Z){super();this.first=Y,this.rest=Z}build(Y,Z,X,G){let _=rF.map(([$,W])=>({fn:W,i:Y.search($)})).sort(($,W)=>$.i-W.i).pop();return _.i===-1?f5(this.first,G):_.fn(this.first,this.rest,Z,X,G)}}function a6(Y,Z,X,G){let _=Y instanceof n1?Y.value:Y;if(_===void 0){if(Y instanceof n1?Y.value=G.transform.undefined:_=Y=G.transform.undefined,_===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(Y instanceof n1?(Z.push(Y.value),Y.array?Y.array[Y.type||r6(Y.value)]||Y.type||IW(Y.value):Y.type):(Z.push(Y),r6(Y)))}var wW=BW(nF);function v5(Y,Z,X,G,_,$){for(let W=1;W<Y.strings.length;W++)Z+=x5(Z,X,G,_,$)+Y.strings[W],X=Y.args[W];return Z}function x5(Y,Z,X,G,_){return Z instanceof t6?Z.build(Y,X,G,_):Z instanceof q1?S5(Z,X,G,_):Z instanceof P8?Z.value:Z&&Z[0]instanceof q1?Z.reduce(($,W)=>$+" "+S5(W,X,G,_),""):a6(Z,X,G,_)}function S5(Y,Z,X,G){return Y.fragment=!0,v5(Y,Y.strings[0],Y.args[0],Z,X,G)}function NW(Y,Z,X,G,_){return Y.map(($)=>"("+G.map((W)=>x5("values",$[W],Z,X,_)).join(",")+")").join(",")}function RW(Y,Z,X,G,_){let $=Array.isArray(Y[0]),W=Z.length?Z.flat():Object.keys($?Y[0]:Y);return NW($?Y:[Y],X,G,W,_)}function n6(Y,Z,X,G,_){if(typeof Y==="string"&&(Y=[Y].concat(Z)),Array.isArray(Y))return f5(Y,_);let $;return(Z.length?Z.flat():Object.keys(Y)).map((H)=>{return $=Y[H],($ instanceof q1?S5($,X,G,_):$ instanceof P8?$.value:a6($,X,G,_))+" as "+e6(_.transform.column.to?_.transform.column.to(H):H)}).join(",")}var rF=Object.entries({values:RW,in:(...Y)=>{let Z=RW(...Y);return Z==="()"?"(null)":Z},select:n6,as:n6,returning:n6,"\\(":n6,update(Y,Z,X,G,_){return(Z.length?Z.flat():Object.keys(Y)).map(($)=>e6(_.transform.column.to?_.transform.column.to($):$)+"="+x5("values",Y[$],X,G,_))},insert(Y,Z,X,G,_){let $=Z.length?Z.flat():Object.keys(Array.isArray(Y)?Y[0]:Y);return"("+f5($,_)+")values"+NW(Array.isArray(Y)?Y:[Y],X,G,$,_)}}).map(([Y,Z])=>[new RegExp("((?:^|[\\s(])"+Y+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Z]);function j5(){throw f0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:sF,parsers:tF}=wW;function IW(Y){if(Array.isArray(Y))return IW(Y[0]);return typeof Y==="string"?1009:0}var KW=function(Y){let Z=BW(Y||{});return{serializers:Object.assign({},sF,Z.serializers),parsers:Object.assign({},tF,Z.parsers)}};function BW(Y){return Object.keys(Y).reduce((Z,X)=>{if(Y[X].from&&[].concat(Y[X].from).forEach((G)=>Z.parsers[G]=Y[X].parse),Y[X].serialize)Z.serializers[Y[X].to]=Y[X].serialize,Y[X].from&&[].concat(Y[X].from).forEach((G)=>Z.serializers[G]=Y[X].serialize);return Z},{parsers:{},serializers:{}})}function f5(Y,{transform:{column:Z}}){return Y.map((X)=>e6(Z.to?Z.to(X):X)).join(",")}var e6=function(Z){return'"'+Z.replace(/"/g,'""').replace(/\./g,'"."')+'"'},r6=function Y(Z){return Z instanceof n1?Z.type:Z instanceof Date?1184:Z instanceof Uint8Array?17:Z===!0||Z===!1?16:typeof Z==="bigint"?20:Array.isArray(Z)?Y(Z[0]):0},aF=/\\/g,eF=/"/g;function YE(Y){return Y.replace(aF,"\\\\").replace(eF,"\\\"")}var TW=function Y(Z,X,G,_){if(Array.isArray(Z)===!1)return Z;if(!Z.length)return"{}";let $=Z[0],W=_===1020?";":",";if(Array.isArray($)&&!$.type)return"{"+Z.map((H)=>Y(H,X,G,_)).join(W)+"}";return"{"+Z.map((H)=>{if(H===void 0){if(H=G.transform.undefined,H===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return H===null?"null":'"'+YE(X?X(H.type?H.value:H):""+H)+'"'}).join(W)+"}"},P5={i:0,char:null,str:"",quoted:!1,last:0},CW=function(Z,X,G){return P5.i=P5.last=0,qW(P5,Z,X,G)};function qW(Y,Z,X,G){let _=[],$=G===1020?";":",";for(;Y.i<Z.length;Y.i++){if(Y.char=Z[Y.i],Y.quoted)if(Y.char==="\\")Y.str+=Z[++Y.i];else if(Y.char==='"')_.push(X?X(Y.str):Y.str),Y.str="",Y.quoted=Z[Y.i+1]==='"',Y.last=Y.i+2;else Y.str+=Y.char;else if(Y.char==='"')Y.quoted=!0;else if(Y.char==="{")Y.last=++Y.i,_.push(qW(Y,Z,X,G));else if(Y.char==="}"){Y.quoted=!1,Y.last<Y.i&&_.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;break}else if(Y.char===$&&Y.p!=="}"&&Y.p!=='"')_.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;Y.p=Y.char}return Y.last<Y.i&&_.push(X?X(Z.slice(Y.last,Y.i+1)):Z.slice(Y.last,Y.i+1)),_}var p4=(Y)=>{let Z=Y[0];for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},m4=(Y)=>{let Z=Y[0].toUpperCase();for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},u4=(Y)=>Y.replace(/_/g,"-"),C8=(Y)=>Y.replace(/([A-Z])/g,"_$1").toLowerCase(),q8=(Y)=>(Y.slice(0,1)+Y.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),j8=(Y)=>Y.replace(/-/g,"_");function h5(Y){return function Z(X,G){return typeof X==="object"&&X!==null&&(G.type===114||G.type===3802)?Array.isArray(X)?X.map((_)=>Z(_,G)):Object.entries(X).reduce((_,[$,W])=>Object.assign(_,{[Y($)]:Z(W,G)}),{}):X}}p4.column={from:p4};p4.value={from:h5(p4)};C8.column={to:C8};var k5={...p4};k5.column.to=C8;m4.column={from:m4};m4.value={from:h5(m4)};q8.column={to:q8};var b5={...m4};b5.column.to=q8;u4.column={from:u4};u4.value={from:h5(u4)};j8.column={to:j8};var y5={...u4};y5.column.to=j8;import jW from"net";import _E from"tls";import S8 from"crypto";import g5 from"stream";import{performance as PW}from"perf_hooks";class d4 extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var R1=ZE;function ZE(Y=[]){let Z=Y.slice(),X=0;return{get length(){return Z.length-X},remove:(G)=>{let _=Z.indexOf(G);return _===-1?null:(Z.splice(_,1),G)},push:(G)=>(Z.push(G),G),shift:()=>{let G=Z[X++];if(X===Z.length)X=0,Z=[];else Z[X-1]=void 0;return G}}}var a0=Buffer.allocUnsafe(256),XE="BCcDdEFfHPpQSX".split("").reduce((Y,Z)=>{let X=Z.charCodeAt(0);return Y[Z]=()=>{return a0[0]=X,z0.i=5,z0},Y},{}),z0=Object.assign(GE,XE,{N:String.fromCharCode(0),i:0,inc(Y){return z0.i+=Y,z0},str(Y){let Z=Buffer.byteLength(Y);return YY(Z),z0.i+=a0.write(Y,z0.i,Z,"utf8"),z0},i16(Y){return YY(2),a0.writeUInt16BE(Y,z0.i),z0.i+=2,z0},i32(Y,Z){if(Z||Z===0)return a0.writeUInt32BE(Y,Z),z0;return YY(4),a0.writeUInt32BE(Y,z0.i),z0.i+=4,z0},z(Y){return YY(Y),a0.fill(0,z0.i,z0.i+Y),z0.i+=Y,z0},raw(Y){return a0=Buffer.concat([a0.subarray(0,z0.i),Y]),z0.i=a0.length,z0},end(Y=1){a0.writeUInt32BE(z0.i-Y,Y);let Z=a0.subarray(0,z0.i);return z0.i=0,a0=Buffer.allocUnsafe(256),Z}}),d=z0;function YY(Y){if(a0.length-z0.i<Y){let Z=a0,X=Z.length;a0=Buffer.allocUnsafe(X+(X>>1)+Y),Z.copy(a0)}}function GE(){return z0.i=0,z0}var u5=xW,$E=1,B4=d().S().end(),SW=d().H().end(),WE=d().i32(8).i32(80877103).end(8),HE=Buffer.concat([d().E().str(d.N).i32(0).end(),B4]),JE=d().D().str("S").str(d.N).end(),w2=()=>{},QE=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),zE={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 xW(Y,Z={},{onopen:X=w2,onend:G=w2,onclose:_=w2}={}){let{ssl:$,max:W,user:H,host:Q,port:J,database:z,parsers:F,transform:O,onnotice:L,onnotify:w,onparameter:R,max_pipeline:b,keep_alive:x,backoff:h,target_session_attrs:g}=Y,B=R1(),K=$E++,C={pid:null,secret:null},q=m5(VY,Y.idle_timeout),c=m5(VY,Y.max_lifetime),n=m5(XH,Y.connect_timeout),N=null,s,p=new d4,t=Buffer.alloc(0),I0=Y.fetch_types,h0={},$1={},r1=Math.random().toString(36).slice(2),T=1,m=0,$0=0,V0=0,k0=0,a=0,J0=0,v0=0,B0=null,A0=null,o0=!1,O0=null,j1=null,c0=null,z4=null,b0=null,R0=null,P1=null,u1=null,v=null,B2=null,i0={queue:Z.closed,idleTimer:q,connect(U){c0=U,OX()},terminate:C2,execute:T2,cancel:aW,end:VY,count:0,id:K};return Z.closed&&Z.closed.push(i0),i0;async function tW(){let U;try{U=Y.socket?await Promise.resolve(Y.socket(Y)):new jW.Socket}catch(D){i4(D);return}return U.on("error",i4),U.on("close",DX),U.on("drain",EX),U}async function aW({pid:U,secret:D},l,W0){try{s=d().i32(16).i32(80877102).i32(U).i32(D).end(16),await VX(),N.once("error",W0),N.once("close",l)}catch(C0){W0(C0)}}function T2(U){if(o0)return g8(U,f0.connection("CONNECTION_DESTROYED",Y));if(U.cancelled)return;try{return U.state=C,v?B.push(U):(v=U,v.active=!0),ZH(U),l0(eW(U))&&!U.describeFirst&&!U.cursorFn&&B.length<b&&(!U.options.onexecute||U.options.onexecute(i0))}catch(D){return B.length===0&&l0(B4),d1(D),!0}}function eW(U){if(U.parameters.length>=65534)throw f0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return U.options.simple?d().Q().str(U.statement.string+d.N).end():U.describeFirst?Buffer.concat([zX(U),SW]):U.prepare?U.prepared?y8(U):Buffer.concat([zX(U),y8(U)]):YH(U)}function zX(U){return Buffer.concat([MX(U.statement.string,U.parameters,U.statement.types,U.statement.name),pH("S",U.statement.name)])}function y8(U){return Buffer.concat([gH(U.parameters,U.statement.types,U.statement.name,U.cursorName),U.cursorFn?AX("",U.cursorRows):HE])}function YH(U){return Buffer.concat([MX(U.statement.string,U.parameters,U.statement.types),JE,y8(U)])}function ZH(U){let D=[],l=[],W0=v5(U,U.strings[0],U.args[0],D,l,Y);!U.tagged&&U.args.forEach((C0)=>a6(C0,D,l,Y)),U.prepare=Y.prepare&&("prepare"in U.options?U.options.prepare:!0),U.string=W0,U.signature=U.prepare&&l+W0,U.onlyDescribe&&delete $1[U.signature],U.parameters=U.parameters||D,U.prepared=U.prepare&&U.signature in $1,U.describeFirst=U.onlyDescribe||D.length&&!U.prepared,U.statement=U.prepared?$1[U.signature]:{string:W0,types:l,name:U.prepare?r1+T++:""},typeof Y.debug==="function"&&Y.debug(K,W0,D,l)}function l0(U,D){if(R0=R0?Buffer.concat([R0,U]):Buffer.from(U),D||R0.length>=1024)return UX(D);return A0===null&&(A0=setImmediate(UX)),!0}function UX(U){let D=N.write(R0,U);return A0!==null&&clearImmediate(A0),R0=A0=null,D}function XH(){d1(f0.connection("CONNECT_TIMEOUT",Y,N)),N.destroy()}async function FX(){if(l0(WE),!await new Promise((D)=>N.once("data",(l)=>D(l[0]===83)))&&$==="prefer")return o4();N.removeAllListeners(),N=_E.connect({socket:N,servername:jW.isIP(N.host)?void 0:N.host,...$==="require"||$==="allow"||$==="prefer"?{rejectUnauthorized:!1}:$==="verify-full"?{}:typeof $==="object"?$:{}}),N.on("secureConnect",o4),N.on("error",i4),N.on("close",DX),N.on("drain",EX)}function EX(){!v&&X(i0)}function EY(U){if(O0){if(O0.push(U),$0-=U.length,$0>0)return}t=O0?Buffer.concat(O0,a-$0):t.length===0?U:Buffer.concat([t,U],t.length+U.length);while(t.length>4){if(a=t.readUInt32BE(1),a>=t.length){$0=a-t.length,O0=[t];break}try{GH(t.subarray(0,a+1))}catch(D){v&&(v.cursorFn||v.describeFirst)&&l0(B4),d1(D)}t=t.subarray(a+1),$0=0,O0=null}}async function VX(){if(o0=!1,h0={},N||(N=await tW()),!N)return;if(n.start(),Y.socket)return $?FX():o4();if(N.on("connect",$?FX:o4),Y.path)return N.connect(Y.path);N.ssl=$,N.connect(J[V0],Q[V0]),N.host=Q[V0],N.port=J[V0],V0=(V0+1)%J.length}function OX(){setTimeout(VX,m?m+J0-PW.now():0)}function o4(){try{$1={},I0=Y.fetch_types,r1=Math.random().toString(36).slice(2),T=1,c.start(),N.on("data",EY),x&&N.setKeepAlive&&N.setKeepAlive(!0,1000*x);let U=uH();l0(U)}catch(U){i4(U)}}function i4(U){if(i0.queue===Z.connecting&&Y.host[k0+1])return;d1(U);while(B.length)g8(B.shift(),U)}function d1(U){b0&&(b0.destroy(U),b0=null),v&&g8(v,U),c0&&(g8(c0,U),c0=null)}function g8(U,D){if(U.reserve)return U.reject(D);if(!D||typeof D!=="object")D=Error(D);"query"in D||"parameters"in D||Object.defineProperties(D,{stack:{value:D.stack+U.origin.replace(/.*\n/,`
|
|
67
|
-
`),enumerable:
|
|
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
|
+
\u274C `));try{if(H===0){this.incompleteData=Q;let z=X1($);this.handleEvent(...z),this.incompleteData=""}else this.incompleteData+=Q}catch(z){if(z instanceof Error)console.error(["\u274C Malformed data received from child process","",$,"",z.message].join(`
|
|
61
|
+
\u274C `))}}++H}}),this.proc.stderr.on("data",(_)=>{let G=_.toString().split("\x03"),W=G[0];G[0]=this.incompleteData+W;let $=0;for(let H of G){if(H==="")continue;try{let Q=X1(H);this.handleLog(Q),this.incompleteData=""}catch(Q){if(Q instanceof Error)console.error(["\u274C Malformed log received from child process","",H,"",Q.message].join(`
|
|
62
|
+
\u274C `));try{if($===0){this.incompleteData=H;let J=X1(W);this.handleLog(J),this.incompleteData=""}else this.incompleteData+=H}catch(J){if(J instanceof Error)console.error(["\u274C Malformed log received from child process...","",W,"",J.message].join(`
|
|
63
|
+
\u274C `))}}++$}}),X.pid)this.id=X.pid.toString()}},jU=class extends QZ{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(X){super((...Y)=>{return this.out.next(Y),this});this.id=X,this.in=new Y0,this.out=new Y0,this.in.subscribe("socket",(Y)=>{this.handleEvent(...Y)})}dispose(){for(let X of this.disposalFunctions)X()}},O7=class extends QZ{incompleteData="";unprocessedEvents=[];relays;relayServices;proc;id="#####";log(...X){this.proc.stderr.write(j0(X.map((Y)=>Y instanceof G4?`{ ${Y.toJSON().join(" | ")} }`:Y))+"\x03")}logger={info:(...X)=>{this.log("i",...X)},warn:(...X)=>{this.log("w",...X)},error:(...X)=>{this.log("e",...X)}};constructor(X){super((Y,...Z)=>{let _=JSON.stringify([Y,...Z]);return this.proc.stdout.write(_+"\x03"),this});if(this.proc=X,this.proc.stdin.resume(),this.relays=new Map,this.relayServices=[],this.proc.stdin.on("data",(Y)=>{let Z=Y.toString().split("\x03"),_=Z[0];Z[0]=this.incompleteData+_;let G=0;for(let W of Z){if(W==="")continue;try{let $=X1(W);this.logger.info("\uD83C\uDFB0","received",$),this.handleEvent(...$),this.incompleteData=""}catch($){if($ instanceof Error)this.logger.error(["received malformed data from parent process:","",W,"",$.message].join(`
|
|
64
|
+
\u274C `));try{if(G===0){this.incompleteData=W;let H=X1(_);this.logger.info("\uD83C\uDFB0","received",H),this.handleEvent(...H),this.incompleteData=""}else this.incompleteData+=W}catch(H){if(H instanceof Error)this.logger.error(["received malformed data from parent process:","",_,"",H.message].join(`
|
|
65
|
+
\u274C `))}}++G}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),this.proc.exit(0)}),this.proc.pid)this.id=this.proc.pid?.toString();this.on("user-joins",(Y)=>{this.logger.info("\uD83D\uDC64","user",Y,"joined");let Z=`user::${Y}`,_=new jU(Z);this.relays.set(Y,_),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let G of this.relayServices){let W=G(_,Z);if(W)_.disposalFunctions.push(W)}this.on(Z,(...G)=>{_.in.next(G)}),_.out.subscribe("socket",(G)=>{this.emit(...G)})}),this.on("user-leaves",(Y)=>{let Z=this.relays.get(Y);if(this.off(`relay:${Y}`),Z)Z.dispose(),this.relays.delete(Y)}),this.proc.stdout.write("ALIVE")}receiveRelay(X){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(X)}};var E7=new Map;var jB=D6({key:"joinRoom",do:(X,Y,Z,_)=>{let G={enteredAtEpoch:_};return W2(E2,(W)=>{W.set({room:Y,user:Z})},X.env().store),G}}),SB=D6({key:"leaveRoom",do:({env:X},Y,Z)=>{W2(E2,(_)=>{_.delete({room:Y,user:Z})},X().store)}}),PB=D6({key:"destroyRoom",do:({set:X,env:Y},Z)=>{W2(E2,(G)=>{G.delete({room:Z})},Y().store),X(U7,(G)=>(G.delete(Z),G));let _=E7.get(Z);if(_)_.emit("exit"),E7.delete(Z)}}),vB=E8({key:"sockets",default:null}),xB=U8({key:"socketsIndex",class:G4}),fB=U8({key:"usersIndex",class:G4}),hB=O6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(X)=>X.startsWith("user::"),isBType:(X)=>X.startsWith("socket::")}),kB=V6({key:"userMutualSituationalAwarenessIndexes",get:(X)=>()=>{return[X]}});var{file:o$,serve:lE}=globalThis.Bun;import{readFileSync as L7}from"fs";import{createServer as xU}from"http";import{createServer as fU}from"https";import{resolve as FZ}from"path";function V7(X,Y){if(X instanceof Promise)throw Error(Y)}function SU(X,Y){let Z={},_=[];for(let G in X){let W=X[G]["~standard"].validate(Y[G]);if(V7(W,`Validation must be synchronous, but ${G} returned a Promise.`),W.issues){_.push(...W.issues.map(($)=>({...$,message:$.message,path:[G,...$.path??[]]})));continue}Z[G]=W.value}if(_.length)return{issues:_};return{value:Z}}function zZ(X){let Y=X.runtimeEnvStrict??X.runtimeEnv??process.env;if(X.emptyStringAsUndefined??!1){for(let[P,h]of Object.entries(Y))if(h==="")delete Y[P]}if(!!X.skipValidation)return Y;let G=typeof X.client==="object"?X.client:{},W=typeof X.server==="object"?X.server:{},$=typeof X.shared==="object"?X.shared:{},H=X.isServer??(typeof window>"u"||("Deno"in window)),Q=H?{...W,...$,...G}:{...G,...$},J=X.createFinalSchema?.(Q,H)["~standard"].validate(Y)??SU(Q,Y);V7(J,"Validation must be synchronous");let z=X.onValidationError??((P)=>{throw console.error("\u274C Invalid environment variables:",P),Error("Invalid environment variables")}),F=X.onInvalidAccess??(()=>{throw Error("\u274C Attempted to access a server-side environment variable on the client")});if(J.issues)return z(J.issues);let O=(P)=>{if(!X.clientPrefix)return!0;return!P.startsWith(X.clientPrefix)&&!(P in $)},D=(P)=>{return H||!O(P)},A=(P)=>{return P==="__esModule"||P==="$$typeof"},R=(X.extends??[]).reduce((P,h)=>{return Object.assign(P,h)},{}),v=Object.assign(R,J.value);return new Proxy(v,{get(P,h){if(typeof h!=="string")return;if(A(h))return;if(!D(h))return F(h);return Reflect.get(P,h)}})}var PU="__vite_start_time"in globalThis,vU=typeof window<"u",iB="vitest"in globalThis,$4=J1("string"),D7=J1('"true" | "false" | undefined'),g1=zZ({isServer:!PU&&!vU,server:{CI:J1("string | undefined").pipe(Boolean),POSTGRES_USER:$4,POSTGRES_PASSWORD:$4,POSTGRES_DATABASE:$4,POSTGRES_HOST:$4,POSTGRES_PORT:$4.pipe((X)=>Number.parseInt(X,10)),BACKEND_PORT:$4.pipe((X)=>Number.parseInt(X,10)),RUN_WORKERS_FROM_SOURCE:D7.pipe((X)=>X==="true"),FRONTEND_PORT:$4.pipe((X)=>Number.parseInt(X,10)),FRONTEND_ORIGINS:$4.pipe.try((X)=>JSON.parse(X),J1("string[]")),API_KEY_OPENAI:J1("string | undefined"),API_KEY_RESEND:J1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:$4,VITE_DEV_FRONTEND_HOST:J1("string | undefined"),VITE_DEV_HTTPS:D7.pipe((X)=>X==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var M7=FZ(import.meta.dirname,"../dev"),B6=g1.VITE_DEV_HTTPS?{cert:L7(FZ(M7,"./cert.pem"),"utf-8"),key:L7(FZ(M7,"./key.pem"),"utf-8")}:void 0;function XT(X){if(B6)return fU(B6,X);return xU({},X)}import yE from"path";var E=Symbol.for("drizzle:entityKind");function M(X,Y){if(!X||typeof X!=="object")return!1;if(X instanceof Y)return!0;if(!Object.prototype.hasOwnProperty.call(Y,E))throw Error(`Class "${Y.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let Z=Object.getPrototypeOf(X).constructor;if(Z)while(Z){if(E in Z&&Z[E]===Y[E])return!0;Z=Object.getPrototypeOf(Z)}return!1}class z0{constructor(X,Y){this.table=X,this.config=Y,this.name=Y.name,this.keyAsName=Y.keyAsName,this.notNull=Y.notNull,this.default=Y.default,this.defaultFn=Y.defaultFn,this.onUpdateFn=Y.onUpdateFn,this.hasDefault=Y.hasDefault,this.primary=Y.primaryKey,this.isUnique=Y.isUnique,this.uniqueName=Y.uniqueName,this.uniqueType=Y.uniqueType,this.dataType=Y.dataType,this.columnType=Y.columnType,this.generated=Y.generated,this.generatedIdentity=Y.generatedIdentity}static[E]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(X){return X}mapToDriverValue(X){return X}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class UZ{static[E]="ColumnBuilder";config;constructor(X,Y,Z){this.config={name:X,keyAsName:X==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:Y,columnType:Z,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(X){return this.config.default=X,this.config.hasDefault=!0,this}$defaultFn(X){return this.config.defaultFn=X,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(X){return this.config.onUpdateFn=X,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(X){if(this.config.name!=="")return;this.config.name=X}}var p1=Symbol.for("drizzle:Name");class EZ{static[E]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(X,Y){if(this.reference=()=>{let{name:Z,columns:_,foreignColumns:G}=X();return{name:Z,columns:_,foreignTable:G[0].table,foreignColumns:G}},Y)this._onUpdate=Y.onUpdate,this._onDelete=Y.onDelete}onUpdate(X){return this._onUpdate=X===void 0?"no action":X,this}onDelete(X){return this._onDelete=X===void 0?"no action":X,this}build(X){return new A7(X,this)}}class A7{constructor(X,Y){this.table=X,this.reference=Y.reference,this.onUpdate=Y._onUpdate,this.onDelete=Y._onDelete}static[E]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:X,columns:Y,foreignColumns:Z}=this.reference(),_=Y.map(($)=>$.name),G=Z.map(($)=>$.name),W=[this.table[p1],..._,Z[0].table[p1],...G];return X??`${W.join("_")}_fk`}}function T6(X,...Y){return X(...Y)}function R7(X,Y){return`${X[p1]}_${Y.join("_")}_unique`}function w7(X,Y,Z){for(let _=Y;_<X.length;_++){let G=X[_];if(G==="\\"){_++;continue}if(G==='"')return[X.slice(Y,_).replace(/\\/g,""),_+1];if(Z)continue;if(G===","||G==="}")return[X.slice(Y,_).replace(/\\/g,""),_]}return[X.slice(Y).replace(/\\/g,""),X.length]}function N7(X,Y=0){let Z=[],_=Y,G=!1;while(_<X.length){let W=X[_];if(W===","){if(G||_===Y)Z.push("");G=!0,_++;continue}if(G=!1,W==="\\"){_+=2;continue}if(W==='"'){let[Q,J]=w7(X,_+1,!0);Z.push(Q),_=J;continue}if(W==="}")return[Z,_+1];if(W==="{"){let[Q,J]=N7(X,_+1);Z.push(Q),_=J;continue}let[$,H]=w7(X,_,!1);Z.push($),_=H}return[Z,_]}function I7(X){let[Y]=N7(X,1);return Y}function OZ(X){return`{${X.map((Y)=>{if(Array.isArray(Y))return OZ(Y);if(typeof Y==="string")return`"${Y.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Y}`}).join(",")}}`}class x extends UZ{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(X){return new B7(this.config.name,this,X)}references(X,Y={}){return this.foreignKeyConfigs.push({ref:X,actions:Y}),this}unique(X,Y){return this.config.isUnique=!0,this.config.uniqueName=X,this.config.uniqueType=Y?.nulls,this}generatedAlwaysAs(X){return this.config.generated={as:X,type:"always",mode:"stored"},this}buildForeignKeys(X,Y){return this.foreignKeyConfigs.map(({ref:Z,actions:_})=>{return T6((G,W)=>{let $=new EZ(()=>{let H=G();return{columns:[X],foreignColumns:[H]}});if(W.onUpdate)$.onUpdate(W.onUpdate);if(W.onDelete)$.onDelete(W.onDelete);return $.build(Y)},Z,_)})}buildExtraConfigColumn(X){return new K7(X,this.config)}}class B extends z0{constructor(X,Y){if(!Y.uniqueName)Y.uniqueName=R7(X,[Y.name]);super(X,Y);this.table=X}static[E]="PgColumn"}class K7 extends B{static[E]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(X){return this.indexConfig.opClass=X,this}}class O2{static[E]="IndexedColumn";constructor(X,Y,Z,_){this.name=X,this.keyAsName=Y,this.type=Z,this.indexConfig=_}name;keyAsName;type;indexConfig}class B7 extends x{static[E]="PgArrayBuilder";constructor(X,Y,Z){super(X,"array","PgArray");this.config.baseBuilder=Y,this.config.size=Z}build(X){let Y=this.config.baseBuilder.build(X);return new VZ(X,this.config,Y)}}class VZ extends B{constructor(X,Y,Z,_){super(X,Y);this.baseColumn=Z,this.range=_,this.size=Y.size}size;static[E]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(X){if(typeof X==="string")X=I7(X);return X.map((Y)=>this.baseColumn.mapFromDriverValue(Y))}mapToDriverValue(X,Y=!1){let Z=X.map((_)=>_===null?null:M(this.baseColumn,VZ)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Y)return Z;return OZ(Z)}}class T7 extends x{static[E]="PgEnumObjectColumnBuilder";constructor(X,Y){super(X,"string","PgEnumObjectColumn");this.config.enum=Y}build(X){return new C7(X,this.config)}}class C7 extends B{static[E]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(X,Y){super(X,Y);this.enum=Y.enum}getSQLType(){return this.enum.enumName}}var C6=Symbol.for("drizzle:isPgEnum");function q7(X){return!!X&&typeof X==="function"&&C6 in X&&X[C6]===!0}class j7 extends x{static[E]="PgEnumColumnBuilder";constructor(X,Y){super(X,"string","PgEnumColumn");this.config.enum=Y}build(X){return new S7(X,this.config)}}class S7 extends B{static[E]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(X,Y){super(X,Y);this.enum=Y.enum}getSQLType(){return this.enum.enumName}}function V2(X,Y){return Array.isArray(Y)?hU(X,[...Y],void 0):kU(X,Y,void 0)}function hU(X,Y,Z){let _=Object.assign((G)=>new j7(G??"",_),{enumName:X,enumValues:Y,schema:Z,[C6]:!0});return _}function kU(X,Y,Z){let _=Object.assign((G)=>new T7(G??"",_),{enumName:X,enumValues:Object.values(Y),schema:Z,[C6]:!0});return _}class T0{static[E]="Subquery";constructor(X,Y,Z,_=!1,G=[]){this._={brand:"Subquery",sql:X,selectedFields:Y,alias:Z,isWith:_,usedTables:G}}}class D2 extends T0{static[E]="WithSubquery"}var P7="0.44.5";var DZ,LZ,F0={startActiveSpan(X,Y){if(!DZ)return Y();if(!LZ)LZ=DZ.trace.getTracer("drizzle-orm",P7);return T6((Z,_)=>_.startActiveSpan(X,(G)=>{try{return Y(G)}catch(W){throw G.setStatus({code:Z.SpanStatusCode.ERROR,message:W instanceof Error?W.message:"Unknown error"}),W}finally{G.end()}}),DZ,LZ)}};var V0=Symbol.for("drizzle:ViewBaseConfig");var k4=Symbol.for("drizzle:Schema"),q6=Symbol.for("drizzle:Columns"),v7=Symbol.for("drizzle:ExtraConfigColumns"),MZ=Symbol.for("drizzle:OriginalName"),AZ=Symbol.for("drizzle:BaseName"),L2=Symbol.for("drizzle:IsAlias"),x7=Symbol.for("drizzle:ExtraConfigBuilder"),bU=Symbol.for("drizzle:IsDrizzleTable");class T{static[E]="Table";static Symbol={Name:p1,Schema:k4,OriginalName:MZ,Columns:q6,ExtraConfigColumns:v7,BaseName:AZ,IsAlias:L2,ExtraConfigBuilder:x7};[p1];[MZ];[k4];[q6];[v7];[AZ];[L2]=!1;[bU]=!0;[x7]=void 0;constructor(X,Y,Z){this[p1]=this[MZ]=X,this[k4]=Y,this[AZ]=Z}}function y0(X){return X[p1]}function b4(X){return`${X[k4]??"public"}.${X[p1]}`}function RZ(X){return X!==null&&X!==void 0&&typeof X.getSQL==="function"}function yU(X){let Y={sql:"",params:[]};for(let Z of X)if(Y.sql+=Z.sql,Y.params.push(...Z.params),Z.typings?.length){if(!Y.typings)Y.typings=[];Y.typings.push(...Z.typings)}return Y}class k0{static[E]="StringChunk";value;constructor(X){this.value=Array.isArray(X)?X:[X]}getSQL(){return new S([this])}}class S{constructor(X){this.queryChunks=X;for(let Y of X)if(M(Y,T)){let Z=Y[T.Symbol.Schema];this.usedTables.push(Z===void 0?Y[T.Symbol.Name]:Z+"."+Y[T.Symbol.Name])}}static[E]="SQL";decoder=h7;shouldInlineParams=!1;usedTables=[];append(X){return this.queryChunks.push(...X.queryChunks),this}toQuery(X){return F0.startActiveSpan("drizzle.buildSQL",(Y)=>{let Z=this.buildQueryFromSourceParams(this.queryChunks,X);return Y?.setAttributes({"drizzle.query.text":Z.sql,"drizzle.query.params":JSON.stringify(Z.params)}),Z})}buildQueryFromSourceParams(X,Y){let Z=Object.assign({},Y,{inlineParams:Y.inlineParams||this.shouldInlineParams,paramStartIndex:Y.paramStartIndex||{value:0}}),{casing:_,escapeName:G,escapeParam:W,prepareTyping:$,inlineParams:H,paramStartIndex:Q}=Z;return yU(X.map((J)=>{if(M(J,k0))return{sql:J.value.join(""),params:[]};if(M(J,j6))return{sql:G(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let z=[new k0("(")];for(let[F,O]of J.entries())if(z.push(O),F<J.length-1)z.push(new k0(", "));return z.push(new k0(")")),this.buildQueryFromSourceParams(z,Z)}if(M(J,S))return this.buildQueryFromSourceParams(J.queryChunks,{...Z,inlineParams:H||J.shouldInlineParams});if(M(J,T)){let z=J[T.Symbol.Schema],F=J[T.Symbol.Name];return{sql:z===void 0||J[L2]?G(F):G(z)+"."+G(F),params:[]}}if(M(J,z0)){let z=_.getColumnCasing(J);if(Y.invokeSource==="indexes")return{sql:G(z),params:[]};let F=J.table[T.Symbol.Schema];return{sql:J.table[L2]||F===void 0?G(J.table[T.Symbol.Name])+"."+G(z):G(F)+"."+G(J.table[T.Symbol.Name])+"."+G(z),params:[]}}if(M(J,z1)){let z=J[V0].schema,F=J[V0].name;return{sql:z===void 0||J[V0].isAlias?G(F):G(z)+"."+G(F),params:[]}}if(M(J,L1)){if(M(J.value,w4))return{sql:W(Q.value++,J),params:[J],typings:["none"]};let z=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(M(z,S))return this.buildQueryFromSourceParams([z],Z);if(H)return{sql:this.mapInlineParam(z,Z),params:[]};let F=["none"];if($)F=[$(J.encoder)];return{sql:W(Q.value++,z),params:[z],typings:F}}if(M(J,w4))return{sql:W(Q.value++,J),params:[J],typings:["none"]};if(M(J,S.Aliased)&&J.fieldAlias!==void 0)return{sql:G(J.fieldAlias),params:[]};if(M(J,T0)){if(J._.isWith)return{sql:G(J._.alias),params:[]};return this.buildQueryFromSourceParams([new k0("("),J._.sql,new k0(") "),new j6(J._.alias)],Z)}if(q7(J)){if(J.schema)return{sql:G(J.schema)+"."+G(J.enumName),params:[]};return{sql:G(J.enumName),params:[]}}if(RZ(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],Z);return this.buildQueryFromSourceParams([new k0("("),J.getSQL(),new k0(")")],Z)}if(H)return{sql:this.mapInlineParam(J,Z),params:[]};return{sql:W(Q.value++,J),params:[J],typings:["none"]}}))}mapInlineParam(X,{escapeString:Y}){if(X===null)return"null";if(typeof X==="number"||typeof X==="boolean")return X.toString();if(typeof X==="string")return Y(X);if(typeof X==="object"){let Z=X.toString();if(Z==="[object Object]")return Y(JSON.stringify(X));return Y(Z)}throw Error("Unexpected param value: "+X)}getSQL(){return this}as(X){if(X===void 0)return this;return new S.Aliased(this,X)}mapWith(X){return this.decoder=typeof X==="function"?{mapFromDriverValue:X}:X,this}inlineParams(){return this.shouldInlineParams=!0,this}if(X){return X?this:void 0}}class j6{constructor(X){this.value=X}static[E]="Name";brand;getSQL(){return new S([this])}}function f7(X){return typeof X==="object"&&X!==null&&"mapToDriverValue"in X&&typeof X.mapToDriverValue==="function"}var h7={mapFromDriverValue:(X)=>X},k7={mapToDriverValue:(X)=>X},dT={...h7,...k7};class L1{constructor(X,Y=k7){this.value=X,this.encoder=Y}static[E]="Param";brand;getSQL(){return new S([this])}}function V(X,...Y){let Z=[];if(Y.length>0||X.length>0&&X[0]!=="")Z.push(new k0(X[0]));for(let[_,G]of Y.entries())Z.push(G,new k0(X[_+1]));return new S(Z)}((X)=>{function Y(){return new S([])}X.empty=Y;function Z(Q){return new S(Q)}X.fromList=Z;function _(Q){return new S([new k0(Q)])}X.raw=_;function G(Q,J){let z=[];for(let[F,O]of Q.entries()){if(F>0&&J!==void 0)z.push(J);z.push(O)}return new S(z)}X.join=G;function W(Q){return new j6(Q)}X.identifier=W;function $(Q){return new w4(Q)}X.placeholder=$;function H(Q,J){return new L1(Q,J)}X.param=H})(V||(V={}));((X)=>{class Y{constructor(Z,_){this.sql=Z,this.fieldAlias=_}static[E]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Y(this.sql,this.fieldAlias)}}X.Aliased=Y})(S||(S={}));class w4{constructor(X){this.name=X}static[E]="Placeholder";getSQL(){return new S([this])}}function wZ(X,Y){return X.map((Z)=>{if(M(Z,w4)){if(!(Z.name in Y))throw Error(`No value for placeholder "${Z.name}" was provided`);return Y[Z.name]}if(M(Z,L1)&&M(Z.value,w4)){if(!(Z.value.name in Y))throw Error(`No value for placeholder "${Z.value.name}" was provided`);return Z.encoder.mapToDriverValue(Y[Z.value.name])}return Z})}var gU=Symbol.for("drizzle:IsDrizzleView");class z1{static[E]="View";[V0];[gU]=!0;constructor({name:X,schema:Y,selectedFields:Z,query:_}){this[V0]={name:X,originalName:X,schema:Y,selectedFields:Z,query:_,isExisting:!_,isAlias:!1}}getSQL(){return new S([this])}}z0.prototype.getSQL=function(){return new S([this])};T.prototype.getSQL=function(){return new S([this])};T0.prototype.getSQL=function(){return new S([this])};class L8{constructor(X){this.table=X}static[E]="ColumnAliasProxyHandler";get(X,Y){if(Y==="table")return this.table;return X[Y]}}class M2{constructor(X,Y){this.alias=X,this.replaceOriginalName=Y}static[E]="TableAliasProxyHandler";get(X,Y){if(Y===T.Symbol.IsAlias)return!0;if(Y===T.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Y===T.Symbol.OriginalName)return this.alias;if(Y===V0)return{...X[V0],name:this.alias,isAlias:!0};if(Y===T.Symbol.Columns){let _=X[T.Symbol.Columns];if(!_)return _;let G={};return Object.keys(_).map((W)=>{G[W]=new Proxy(_[W],new L8(new Proxy(X,this)))}),G}let Z=X[Y];if(M(Z,z0))return new Proxy(Z,new L8(new Proxy(X,this)));return Z}}function S6(X,Y){return new Proxy(X,new M2(Y,!1))}function i1(X,Y){return new Proxy(X,new L8(new Proxy(X.table,new M2(Y,!1))))}function NZ(X,Y){return new S.Aliased(A2(X.sql,Y),X.fieldAlias)}function A2(X,Y){return V.join(X.queryChunks.map((Z)=>{if(M(Z,z0))return i1(Z,Y);if(M(Z,S))return A2(Z,Y);if(M(Z,S.Aliased))return NZ(Z,Y);return Z}))}class P6 extends Error{static[E]="DrizzleError";constructor({message:X,cause:Y}){super(X);this.name="DrizzleError",this.cause=Y}}class H4 extends Error{constructor(X,Y,Z){super(`Failed query: ${X}
|
|
66
|
+
params: ${Y}`);if(this.query=X,this.params=Y,this.cause=Z,Error.captureStackTrace(this,H4),Z)this.cause=Z}}class IZ extends P6{static[E]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class b7{static[E]="ConsoleLogWriter";write(X){console.log(X)}}class KZ{static[E]="DefaultLogger";writer;constructor(X){this.writer=X?.writer??new b7}logQuery(X,Y){let Z=Y.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),_=Z.length?` -- params: [${Z.join(", ")}]`:"";this.writer.write(`Query: ${X}${_}`)}}class BZ{static[E]="NoopLogger";logQuery(){}}class Y1{static[E]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(X){return this.then(void 0,X)}finally(X){return this.then((Y)=>{return X?.(),Y},(Y)=>{throw X?.(),Y})}then(X,Y){return this.execute().then(X,Y)}}function y7(X,Y,Z){let _={},G=X.reduce((W,{path:$,field:H},Q)=>{let J;if(M(H,z0))J=H;else if(M(H,S))J=H.decoder;else J=H.sql.decoder;let z=W;for(let[F,O]of $.entries())if(F<$.length-1){if(!(O in z))z[O]={};z=z[O]}else{let D=Y[Q],A=z[O]=D===null?null:J.mapFromDriverValue(D);if(Z&&M(H,z0)&&$.length===2){let R=$[0];if(!(R in _))_[R]=A===null?y0(H.table):!1;else if(typeof _[R]==="string"&&_[R]!==y0(H.table))_[R]=!1}}return W},{});if(Z&&Object.keys(_).length>0){for(let[W,$]of Object.entries(_))if(typeof $==="string"&&!Z[$])G[W]=null}return G}function B1(X,Y){return Object.entries(X).reduce((Z,[_,G])=>{if(typeof _!=="string")return Z;let W=Y?[...Y,_]:[_];if(M(G,z0)||M(G,S)||M(G,S.Aliased))Z.push({path:W,field:G});else if(M(G,T))Z.push(...B1(G[T.Symbol.Columns],W));else Z.push(...B1(G,W));return Z},[])}function R2(X,Y){let Z=Object.keys(X),_=Object.keys(Y);if(Z.length!==_.length)return!1;for(let[G,W]of Z.entries())if(W!==_[G])return!1;return!0}function v6(X,Y){let Z=Object.entries(Y).filter(([,_])=>_!==void 0).map(([_,G])=>{if(M(G,S)||M(G,z0))return[_,G];else return[_,new L1(G,X[T.Symbol.Columns][_])]});if(Z.length===0)throw Error("No values to set");return Object.fromEntries(Z)}function g7(X,Y){for(let Z of Y)for(let _ of Object.getOwnPropertyNames(Z.prototype)){if(_==="constructor")continue;Object.defineProperty(X.prototype,_,Object.getOwnPropertyDescriptor(Z.prototype,_)||Object.create(null))}}function p7(X){return X[T.Symbol.Columns]}function J4(X){return M(X,T0)?X._.alias:M(X,z1)?X[V0].name:M(X,S)?void 0:X[T.Symbol.IsAlias]?X[T.Symbol.Name]:X[T.Symbol.BaseName]}function a(X,Y){return{name:typeof X==="string"&&X.length>0?X:"",config:typeof X==="object"?X:Y}}function m7(X){if(typeof X!=="object"||X===null)return!1;if(X.constructor.name!=="Object")return!1;if("logger"in X){let Y=typeof X.logger;if(Y!=="boolean"&&(Y!=="object"||typeof X.logger.logQuery!=="function")&&Y!=="undefined")return!1;return!0}if("schema"in X){let Y=typeof X.schema;if(Y!=="object"&&Y!=="undefined")return!1;return!0}if("casing"in X){let Y=typeof X.casing;if(Y!=="string"&&Y!=="undefined")return!1;return!0}if("mode"in X){if(X.mode!=="default"||X.mode!=="planetscale"||X.mode!==void 0)return!1;return!0}if("connection"in X){let Y=typeof X.connection;if(Y!=="string"&&Y!=="object"&&Y!=="undefined")return!1;return!0}if("client"in X){let Y=typeof X.client;if(Y!=="object"&&Y!=="function"&&Y!=="undefined")return!1;return!0}if(Object.keys(X).length===0)return!0;return!1}class N4 extends x{static[E]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(X){if(X){let{name:Y,...Z}=X;this.config.generatedIdentity={type:"always",sequenceName:Y,sequenceOptions:Z}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(X){if(X){let{name:Y,...Z}=X;this.config.generatedIdentity={type:"byDefault",sequenceName:Y,sequenceOptions:Z}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class u7 extends N4{static[E]="PgBigInt53Builder";constructor(X){super(X,"number","PgBigInt53")}build(X){return new d7(X,this.config)}}class d7 extends B{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}}class c7 extends N4{static[E]="PgBigInt64Builder";constructor(X){super(X,"bigint","PgBigInt64")}build(X){return new l7(X,this.config)}}class l7 extends B{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(X){return BigInt(X)}}function o7(X,Y){let{name:Z,config:_}=a(X,Y);if(_.mode==="number")return new u7(Z);return new c7(Z)}class i7 extends x{static[E]="PgBigSerial53Builder";constructor(X){super(X,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new n7(X,this.config)}}class n7 extends B{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}}class r7 extends x{static[E]="PgBigSerial64Builder";constructor(X){super(X,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(X){return new s7(X,this.config)}}class s7 extends B{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(X){return BigInt(X)}}function t7(X,Y){let{name:Z,config:_}=a(X,Y);if(_.mode==="number")return new i7(Z);return new r7(Z)}class a7 extends x{static[E]="PgBooleanBuilder";constructor(X){super(X,"boolean","PgBoolean")}build(X){return new e7(X,this.config)}}class e7 extends B{static[E]="PgBoolean";getSQLType(){return"boolean"}}function w2(X){return new a7(X??"")}class X3 extends x{static[E]="PgCharBuilder";constructor(X,Y){super(X,"string","PgChar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(X){return new Y3(X,this.config)}}class Y3 extends B{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function Z3(X,Y={}){let{name:Z,config:_}=a(X,Y);return new X3(Z,_)}class _3 extends x{static[E]="PgCidrBuilder";constructor(X){super(X,"string","PgCidr")}build(X){return new G3(X,this.config)}}class G3 extends B{static[E]="PgCidr";getSQLType(){return"cidr"}}function W3(X){return new _3(X??"")}class $3 extends x{static[E]="PgCustomColumnBuilder";constructor(X,Y,Z){super(X,"custom","PgCustomColumn");this.config.fieldConfig=Y,this.config.customTypeParams=Z}build(X){return new H3(X,this.config)}}class H3 extends B{static[E]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(X,Y){super(X,Y);this.sqlName=Y.customTypeParams.dataType(Y.fieldConfig),this.mapTo=Y.customTypeParams.toDriver,this.mapFrom=Y.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(X){return typeof this.mapFrom==="function"?this.mapFrom(X):X}mapToDriverValue(X){return typeof this.mapTo==="function"?this.mapTo(X):X}}function J3(X){return(Y,Z)=>{let{name:_,config:G}=a(Y,Z);return new $3(_,G,X)}}class Q4 extends x{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(V`now()`)}}class Q3 extends Q4{static[E]="PgDateBuilder";constructor(X){super(X,"date","PgDate")}build(X){return new x6(X,this.config)}}class x6 extends B{static[E]="PgDate";getSQLType(){return"date"}mapFromDriverValue(X){return new Date(X)}mapToDriverValue(X){return X.toISOString()}}class z3 extends Q4{static[E]="PgDateStringBuilder";constructor(X){super(X,"string","PgDateString")}build(X){return new f6(X,this.config)}}class f6 extends B{static[E]="PgDateString";getSQLType(){return"date"}}function F3(X,Y){let{name:Z,config:_}=a(X,Y);if(_?.mode==="date")return new Q3(Z);return new z3(Z)}class U3 extends x{static[E]="PgDoublePrecisionBuilder";constructor(X){super(X,"number","PgDoublePrecision")}build(X){return new E3(X,this.config)}}class E3 extends B{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(X){if(typeof X==="string")return Number.parseFloat(X);return X}}function O3(X){return new U3(X??"")}class V3 extends x{static[E]="PgInetBuilder";constructor(X){super(X,"string","PgInet")}build(X){return new D3(X,this.config)}}class D3 extends B{static[E]="PgInet";getSQLType(){return"inet"}}function L3(X){return new V3(X??"")}class M3 extends N4{static[E]="PgIntegerBuilder";constructor(X){super(X,"number","PgInteger")}build(X){return new A3(X,this.config)}}class A3 extends B{static[E]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(X){if(typeof X==="string")return Number.parseInt(X);return X}}function N2(X){return new M3(X??"")}class R3 extends x{static[E]="PgIntervalBuilder";constructor(X,Y){super(X,"string","PgInterval");this.config.intervalConfig=Y}build(X){return new w3(X,this.config)}}class w3 extends B{static[E]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let X=this.fields?` ${this.fields}`:"",Y=this.precision?`(${this.precision})`:"";return`interval${X}${Y}`}}function N3(X,Y={}){let{name:Z,config:_}=a(X,Y);return new R3(Z,_)}class I3 extends x{static[E]="PgJsonBuilder";constructor(X){super(X,"json","PgJson")}build(X){return new h6(X,this.config)}}class h6 extends B{static[E]="PgJson";constructor(X,Y){super(X,Y)}getSQLType(){return"json"}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){if(typeof X==="string")try{return JSON.parse(X)}catch{return X}return X}}function K3(X){return new I3(X??"")}class B3 extends x{static[E]="PgJsonbBuilder";constructor(X){super(X,"json","PgJsonb")}build(X){return new k6(X,this.config)}}class k6 extends B{static[E]="PgJsonb";constructor(X,Y){super(X,Y)}getSQLType(){return"jsonb"}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){if(typeof X==="string")try{return JSON.parse(X)}catch{return X}return X}}function T3(X){return new B3(X??"")}class C3 extends x{static[E]="PgLineBuilder";constructor(X){super(X,"array","PgLine")}build(X){return new q3(X,this.config)}}class q3 extends B{static[E]="PgLine";getSQLType(){return"line"}mapFromDriverValue(X){let[Y,Z,_]=X.slice(1,-1).split(",");return[Number.parseFloat(Y),Number.parseFloat(Z),Number.parseFloat(_)]}mapToDriverValue(X){return`{${X[0]},${X[1]},${X[2]}}`}}class j3 extends x{static[E]="PgLineABCBuilder";constructor(X){super(X,"json","PgLineABC")}build(X){return new S3(X,this.config)}}class S3 extends B{static[E]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(X){let[Y,Z,_]=X.slice(1,-1).split(",");return{a:Number.parseFloat(Y),b:Number.parseFloat(Z),c:Number.parseFloat(_)}}mapToDriverValue(X){return`{${X.a},${X.b},${X.c}}`}}function P3(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new C3(Z);return new j3(Z)}class v3 extends x{static[E]="PgMacaddrBuilder";constructor(X){super(X,"string","PgMacaddr")}build(X){return new x3(X,this.config)}}class x3 extends B{static[E]="PgMacaddr";getSQLType(){return"macaddr"}}function f3(X){return new v3(X??"")}class h3 extends x{static[E]="PgMacaddr8Builder";constructor(X){super(X,"string","PgMacaddr8")}build(X){return new k3(X,this.config)}}class k3 extends B{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}}function b3(X){return new h3(X??"")}class y3 extends x{static[E]="PgNumericBuilder";constructor(X,Y,Z){super(X,"string","PgNumeric");this.config.precision=Y,this.config.scale=Z}build(X){return new b6(X,this.config)}}class b6 extends B{static[E]="PgNumeric";precision;scale;constructor(X,Y){super(X,Y);this.precision=Y.precision,this.scale=Y.scale}mapFromDriverValue(X){if(typeof X==="string")return X;return String(X)}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class g3 extends x{static[E]="PgNumericNumberBuilder";constructor(X,Y,Z){super(X,"number","PgNumericNumber");this.config.precision=Y,this.config.scale=Z}build(X){return new p3(X,this.config)}}class p3 extends B{static[E]="PgNumericNumber";precision;scale;constructor(X,Y){super(X,Y);this.precision=Y.precision,this.scale=Y.scale}mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class m3 extends x{static[E]="PgNumericBigIntBuilder";constructor(X,Y,Z){super(X,"bigint","PgNumericBigInt");this.config.precision=Y,this.config.scale=Z}build(X){return new u3(X,this.config)}}class u3 extends B{static[E]="PgNumericBigInt";precision;scale;constructor(X,Y){super(X,Y);this.precision=Y.precision,this.scale=Y.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function d3(X,Y){let{name:Z,config:_}=a(X,Y),G=_?.mode;return G==="number"?new g3(Z,_?.precision,_?.scale):G==="bigint"?new m3(Z,_?.precision,_?.scale):new y3(Z,_?.precision,_?.scale)}class c3 extends x{static[E]="PgPointTupleBuilder";constructor(X){super(X,"array","PgPointTuple")}build(X){return new l3(X,this.config)}}class l3 extends B{static[E]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(X){if(typeof X==="string"){let[Y,Z]=X.slice(1,-1).split(",");return[Number.parseFloat(Y),Number.parseFloat(Z)]}return[X.x,X.y]}mapToDriverValue(X){return`(${X[0]},${X[1]})`}}class o3 extends x{static[E]="PgPointObjectBuilder";constructor(X){super(X,"json","PgPointObject")}build(X){return new i3(X,this.config)}}class i3 extends B{static[E]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(X){if(typeof X==="string"){let[Y,Z]=X.slice(1,-1).split(",");return{x:Number.parseFloat(Y),y:Number.parseFloat(Z)}}return X}mapToDriverValue(X){return`(${X.x},${X.y})`}}function n3(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new c3(Z);return new o3(Z)}function pU(X){let Y=[];for(let Z=0;Z<X.length;Z+=2)Y.push(Number.parseInt(X.slice(Z,Z+2),16));return new Uint8Array(Y)}function r3(X,Y){let Z=new ArrayBuffer(8),_=new DataView(Z);for(let G=0;G<8;G++)_.setUint8(G,X[Y+G]);return _.getFloat64(0,!0)}function TZ(X){let Y=pU(X),Z=0,_=Y[Z];Z+=1;let G=new DataView(Y.buffer),W=G.getUint32(Z,_===1);Z+=4;let $;if(W&536870912)$=G.getUint32(Z,_===1),Z+=4;if((W&65535)===1){let H=r3(Y,Z);Z+=8;let Q=r3(Y,Z);return Z+=8,[H,Q]}throw Error("Unsupported geometry type")}class s3 extends x{static[E]="PgGeometryBuilder";constructor(X){super(X,"array","PgGeometry")}build(X){return new t3(X,this.config)}}class t3 extends B{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(X){return TZ(X)}mapToDriverValue(X){return`point(${X[0]} ${X[1]})`}}class a3 extends x{static[E]="PgGeometryObjectBuilder";constructor(X){super(X,"json","PgGeometryObject")}build(X){return new e3(X,this.config)}}class e3 extends B{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(X){let Y=TZ(X);return{x:Y[0],y:Y[1]}}mapToDriverValue(X){return`point(${X.x} ${X.y})`}}function XW(X,Y){let{name:Z,config:_}=a(X,Y);if(!_?.mode||_.mode==="tuple")return new s3(Z);return new a3(Z)}class YW extends x{static[E]="PgRealBuilder";constructor(X,Y){super(X,"number","PgReal");this.config.length=Y}build(X){return new ZW(X,this.config)}}class ZW extends B{static[E]="PgReal";constructor(X,Y){super(X,Y)}getSQLType(){return"real"}mapFromDriverValue=(X)=>{if(typeof X==="string")return Number.parseFloat(X);return X}}function _W(X){return new YW(X??"")}class GW extends x{static[E]="PgSerialBuilder";constructor(X){super(X,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new WW(X,this.config)}}class WW extends B{static[E]="PgSerial";getSQLType(){return"serial"}}function $W(X){return new GW(X??"")}class HW extends N4{static[E]="PgSmallIntBuilder";constructor(X){super(X,"number","PgSmallInt")}build(X){return new JW(X,this.config)}}class JW extends B{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(X)=>{if(typeof X==="string")return Number(X);return X}}function QW(X){return new HW(X??"")}class zW extends x{static[E]="PgSmallSerialBuilder";constructor(X){super(X,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(X){return new FW(X,this.config)}}class FW extends B{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}}function UW(X){return new zW(X??"")}class EW extends x{static[E]="PgTextBuilder";constructor(X,Y){super(X,"string","PgText");this.config.enumValues=Y.enum}build(X){return new OW(X,this.config)}}class OW extends B{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function VW(X,Y={}){let{name:Z,config:_}=a(X,Y);return new EW(Z,_)}class DW extends Q4{constructor(X,Y,Z){super(X,"string","PgTime");this.withTimezone=Y,this.precision=Z,this.config.withTimezone=Y,this.config.precision=Z}static[E]="PgTimeBuilder";build(X){return new y6(X,this.config)}}class y6 extends B{static[E]="PgTime";withTimezone;precision;constructor(X,Y){super(X,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function LW(X,Y={}){let{name:Z,config:_}=a(X,Y);return new DW(Z,_.withTimezone??!1,_.precision)}class MW extends Q4{static[E]="PgTimestampBuilder";constructor(X,Y,Z){super(X,"date","PgTimestamp");this.config.withTimezone=Y,this.config.precision=Z}build(X){return new g6(X,this.config)}}class g6 extends B{static[E]="PgTimestamp";withTimezone;precision;constructor(X,Y){super(X,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(X)=>{return new Date(this.withTimezone?X:X+"+0000")};mapToDriverValue=(X)=>{return X.toISOString()}}class AW extends Q4{static[E]="PgTimestampStringBuilder";constructor(X,Y,Z){super(X,"string","PgTimestampString");this.config.withTimezone=Y,this.config.precision=Z}build(X){return new p6(X,this.config)}}class p6 extends B{static[E]="PgTimestampString";withTimezone;precision;constructor(X,Y){super(X,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function RW(X,Y={}){let{name:Z,config:_}=a(X,Y);if(_?.mode==="string")return new AW(Z,_.withTimezone??!1,_.precision);return new MW(Z,_?.withTimezone??!1,_?.precision)}class wW extends x{static[E]="PgUUIDBuilder";constructor(X){super(X,"string","PgUUID")}defaultRandom(){return this.default(V`gen_random_uuid()`)}build(X){return new m6(X,this.config)}}class m6 extends B{static[E]="PgUUID";getSQLType(){return"uuid"}}function T1(X){return new wW(X??"")}class NW extends x{static[E]="PgVarcharBuilder";constructor(X,Y){super(X,"string","PgVarchar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(X){return new IW(X,this.config)}}class IW extends B{static[E]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function n0(X,Y={}){let{name:Z,config:_}=a(X,Y);return new NW(Z,_)}class KW extends x{static[E]="PgBinaryVectorBuilder";constructor(X,Y){super(X,"string","PgBinaryVector");this.config.dimensions=Y.dimensions}build(X){return new BW(X,this.config)}}class BW extends B{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function TW(X,Y){let{name:Z,config:_}=a(X,Y);return new KW(Z,_)}class CW extends x{static[E]="PgHalfVectorBuilder";constructor(X,Y){super(X,"array","PgHalfVector");this.config.dimensions=Y.dimensions}build(X){return new qW(X,this.config)}}class qW extends B{static[E]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){return X.slice(1,-1).split(",").map((Y)=>Number.parseFloat(Y))}}function jW(X,Y){let{name:Z,config:_}=a(X,Y);return new CW(Z,_)}class SW extends x{static[E]="PgSparseVectorBuilder";constructor(X,Y){super(X,"string","PgSparseVector");this.config.dimensions=Y.dimensions}build(X){return new PW(X,this.config)}}class PW extends B{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function vW(X,Y){let{name:Z,config:_}=a(X,Y);return new SW(Z,_)}class xW extends x{static[E]="PgVectorBuilder";constructor(X,Y){super(X,"array","PgVector");this.config.dimensions=Y.dimensions}build(X){return new fW(X,this.config)}}class fW extends B{static[E]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(X){return JSON.stringify(X)}mapFromDriverValue(X){return X.slice(1,-1).split(",").map((Y)=>Number.parseFloat(Y))}}function hW(X,Y){let{name:Z,config:_}=a(X,Y);return new xW(Z,_)}function kW(){return{bigint:o7,bigserial:t7,boolean:w2,char:Z3,cidr:W3,customType:J3,date:F3,doublePrecision:O3,inet:L3,integer:N2,interval:N3,json:K3,jsonb:T3,line:P3,macaddr:f3,macaddr8:b3,numeric:d3,point:n3,geometry:XW,real:_W,serial:$W,smallint:QW,smallserial:UW,text:VW,time:LW,timestamp:RW,uuid:T1,varchar:n0,bit:TW,halfvec:jW,sparsevec:vW,vector:hW}}var CZ=Symbol.for("drizzle:PgInlineForeignKeys"),bW=Symbol.for("drizzle:EnableRLS");class b0 extends T{static[E]="PgTable";static Symbol=Object.assign({},T.Symbol,{InlineForeignKeys:CZ,EnableRLS:bW});[CZ]=[];[bW]=!1;[T.Symbol.ExtraConfigBuilder]=void 0;[T.Symbol.ExtraConfigColumns]={}}function mU(X,Y,Z,_,G=X){let W=new b0(X,_,G),$=typeof Y==="function"?Y(kW()):Y,H=Object.fromEntries(Object.entries($).map(([z,F])=>{let O=F;O.setName(z);let D=O.build(W);return W[CZ].push(...O.buildForeignKeys(D,W)),[z,D]})),Q=Object.fromEntries(Object.entries($).map(([z,F])=>{let O=F;O.setName(z);let D=O.buildExtraConfigColumn(W);return[z,D]})),J=Object.assign(W,H);if(J[T.Symbol.Columns]=H,J[T.Symbol.ExtraConfigColumns]=Q,Z)J[b0.Symbol.ExtraConfigBuilder]=Z;return Object.assign(J,{enableRLS:()=>{return J[b0.Symbol.EnableRLS]=!0,J}})}var I4=(X,Y,Z)=>{return mU(X,Y,Z,void 0)};function yW(...X){if(X[0].columns)return new I2(X[0].columns,X[0].name);return new I2(X)}class I2{static[E]="PgPrimaryKeyBuilder";columns;name;constructor(X,Y){this.columns=X,this.name=Y}build(X){return new gW(X,this.columns,this.name)}}class gW{constructor(X,Y,Z){this.table=X,this.columns=Y,this.name=Z}static[E]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[b0.Symbol.Name]}_${this.columns.map((X)=>X.name).join("_")}_pk`}}function F1(X,Y){if(f7(Y)&&!RZ(X)&&!M(X,L1)&&!M(X,w4)&&!M(X,z0)&&!M(X,T)&&!M(X,z1))return new L1(X,Y);return X}var u6=(X,Y)=>{return V`${X} = ${F1(Y,X)}`},pW=(X,Y)=>{return V`${X} <> ${F1(Y,X)}`};function K2(...X){let Y=X.filter((Z)=>Z!==void 0);if(Y.length===0)return;if(Y.length===1)return new S(Y);return new S([new k0("("),V.join(Y,new k0(" and ")),new k0(")")])}function mW(...X){let Y=X.filter((Z)=>Z!==void 0);if(Y.length===0)return;if(Y.length===1)return new S(Y);return new S([new k0("("),V.join(Y,new k0(" or ")),new k0(")")])}function uW(X){return V`not ${X}`}var dW=(X,Y)=>{return V`${X} > ${F1(Y,X)}`},cW=(X,Y)=>{return V`${X} >= ${F1(Y,X)}`},lW=(X,Y)=>{return V`${X} < ${F1(Y,X)}`},oW=(X,Y)=>{return V`${X} <= ${F1(Y,X)}`};function iW(X,Y){if(Array.isArray(Y)){if(Y.length===0)return V`false`;return V`${X} in ${Y.map((Z)=>F1(Z,X))}`}return V`${X} in ${F1(Y,X)}`}function nW(X,Y){if(Array.isArray(Y)){if(Y.length===0)return V`true`;return V`${X} not in ${Y.map((Z)=>F1(Z,X))}`}return V`${X} not in ${F1(Y,X)}`}function rW(X){return V`${X} is null`}function sW(X){return V`${X} is not null`}function tW(X){return V`exists ${X}`}function aW(X){return V`not exists ${X}`}function eW(X,Y,Z){return V`${X} between ${F1(Y,X)} and ${F1(Z,X)}`}function X$(X,Y,Z){return V`${X} not between ${F1(Y,X)} and ${F1(Z,X)}`}function Y$(X,Y){return V`${X} like ${Y}`}function Z$(X,Y){return V`${X} not like ${Y}`}function _$(X,Y){return V`${X} ilike ${Y}`}function G$(X,Y){return V`${X} not ilike ${Y}`}function W$(X){return V`${X} asc`}function $$(X){return V`${X} desc`}class qZ{constructor(X,Y,Z){this.sourceTable=X,this.referencedTable=Y,this.relationName=Z,this.referencedTableName=Y[T.Symbol.Name]}static[E]="Relation";referencedTableName;fieldName}class H${constructor(X,Y){this.table=X,this.config=Y}static[E]="Relations"}class K4 extends qZ{constructor(X,Y,Z,_){super(X,Y,Z?.relationName);this.config=Z,this.isNullable=_}static[E]="One";withFieldName(X){let Y=new K4(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Y.fieldName=X,Y}}class B2 extends qZ{constructor(X,Y,Z){super(X,Y,Z?.relationName);this.config=Z}static[E]="Many";withFieldName(X){let Y=new B2(this.sourceTable,this.referencedTable,this.config);return Y.fieldName=X,Y}}function J$(){return{and:K2,between:eW,eq:u6,exists:tW,gt:dW,gte:cW,ilike:_$,inArray:iW,isNull:rW,isNotNull:sW,like:Y$,lt:lW,lte:oW,ne:pW,not:uW,notBetween:X$,notExists:aW,notLike:Z$,notIlike:G$,notInArray:nW,or:mW,sql:V}}function Q$(){return{sql:V,asc:W$,desc:$$}}function z$(X,Y){if(Object.keys(X).length===1&&"default"in X&&!M(X.default,T))X=X.default;let Z={},_={},G={};for(let[W,$]of Object.entries(X))if(M($,T)){let H=b4($),Q=_[H];Z[H]=W,G[W]={tsName:W,dbName:$[T.Symbol.Name],schema:$[T.Symbol.Schema],columns:$[T.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let z of Object.values($[T.Symbol.Columns]))if(z.primary)G[W].primaryKey.push(z);let J=$[T.Symbol.ExtraConfigBuilder]?.($[T.Symbol.ExtraConfigColumns]);if(J){for(let z of Object.values(J))if(M(z,I2))G[W].primaryKey.push(...z.columns)}}else if(M($,H$)){let H=b4($.table),Q=Z[H],J=$.config(Y($.table)),z;for(let[F,O]of Object.entries(J))if(Q){let D=G[Q];if(D.relations[F]=O,z)D.primaryKey.push(...z)}else{if(!(H in _))_[H]={relations:{},primaryKey:z};_[H].relations[F]=O}}return{tables:G,tableNamesMap:Z}}function uU(X){return function(Z,_){return new K4(X,Z,_,_?.fields.reduce((G,W)=>G&&W.notNull,!0)??!1)}}function dU(X){return function(Z,_){return new B2(X,Z,_)}}function F$(X,Y,Z){if(M(Z,K4)&&Z.config)return{fields:Z.config.fields,references:Z.config.references};let _=Y[b4(Z.referencedTable)];if(!_)throw Error(`Table "${Z.referencedTable[T.Symbol.Name]}" not found in schema`);let G=X[_];if(!G)throw Error(`Table "${_}" not found in schema`);let W=Z.sourceTable,$=Y[b4(W)];if(!$)throw Error(`Table "${W[T.Symbol.Name]}" not found in schema`);let H=[];for(let Q of Object.values(G.relations))if(Z.relationName&&Z!==Q&&Q.relationName===Z.relationName||!Z.relationName&&Q.referencedTable===Z.sourceTable)H.push(Q);if(H.length>1)throw Z.relationName?Error(`There are multiple relations with name "${Z.relationName}" in table "${_}"`):Error(`There are multiple relations between "${_}" and "${Z.sourceTable[T.Symbol.Name]}". Please specify relation name`);if(H[0]&&M(H[0],K4)&&H[0].config)return{fields:H[0].config.references,references:H[0].config.fields};throw Error(`There is not enough information to infer relation "${$}.${Z.fieldName}"`)}function U$(X){return{one:uU(X),many:dU(X)}}function d6(X,Y,Z,_,G=(W)=>W){let W={};for(let[$,H]of _.entries())if(H.isJson){let Q=Y.relations[H.tsKey],J=Z[$],z=typeof J==="string"?JSON.parse(J):J;W[H.tsKey]=M(Q,K4)?z&&d6(X,X[H.relationTableTsKey],z,H.selection,G):z.map((F)=>d6(X,X[H.relationTableTsKey],F,H.selection,G))}else{let Q=G(Z[$]),J=H.field,z;if(M(J,z0))z=J;else if(M(J,S))z=J.decoder;else z=J.sql.decoder;W[H.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return W}import EE from"os";import OE from"fs";var c6=new Map,jZ=new Map,SZ=Symbol("OriginError"),M8={};class C1 extends Promise{constructor(X,Y,Z,_,G={}){let W,$;super((H,Q)=>{W=H,$=Q});this.tagged=Array.isArray(X.raw),this.strings=X,this.args=Y,this.handler=Z,this.canceller=_,this.options=G,this.state=null,this.statement=null,this.resolve=(H)=>(this.active=!1,W(H)),this.reject=(H)=>(this.active=!1,$(H)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[SZ]=this.handler.debug?Error():this.tagged&&cU(this.strings)}get origin(){return(this.handler.debug?this[SZ].stack:this.tagged&&jZ.has(this.strings)?jZ.get(this.strings):jZ.set(this.strings,this[SZ].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(X=1,Y){if(this.options.simple=!1,typeof X==="function")Y=X,X=1;if(this.cursorRows=X,typeof Y==="function")return this.cursorFn=Y,this;let Z;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};Z&&Z();let _=new Promise((G,W)=>{this.cursorFn=($)=>{return G({value:$,done:!1}),new Promise((H)=>Z=H)},this.resolve=()=>(this.active=!1,G({done:!0})),this.reject=($)=>(this.active=!1,W($))});return this.execute(),_},return(){return Z&&Z(M8),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw Error(".stream has been renamed to .forEach")}forEach(X){return this.forEachFn=X,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function cU(X){if(c6.has(X))return c6.get(X);let Y=Error.stackTraceLimit;return Error.stackTraceLimit=4,c6.set(X,Error()),Error.stackTraceLimit=Y,c6.get(X)}class A8 extends Error{constructor(X){super(X.message);this.name=this.constructor.name,Object.assign(this,X)}}var S0={connection:E$,postgres:O$,generic:V$,notSupported:D$};function E$(X,Y,Z){let{host:_,port:G}=Z||Y,W=Object.assign(Error("write "+X+" "+(Y.path||_+":"+G)),{code:X,errno:X,address:Y.path||_},Y.path?{}:{port:G});return Error.captureStackTrace(W,E$),W}function O$(X){let Y=new A8(X);return Error.captureStackTrace(Y,O$),Y}function V$(X,Y){let Z=Object.assign(Error(X+": "+Y),{code:X});return Error.captureStackTrace(Z,V$),Z}function D$(X){let Y=Object.assign(Error(X+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:X});return Error.captureStackTrace(Y,D$),Y}var lU={string:{to:25,from:null,serialize:(X)=>""+X},number:{to:0,from:[21,23,26,700,701],serialize:(X)=>""+X,parse:(X)=>+X},json:{to:114,from:[114,3802],serialize:(X)=>JSON.stringify(X),parse:(X)=>JSON.parse(X)},boolean:{to:16,from:16,serialize:(X)=>X===!0?"t":"f",parse:(X)=>X==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(X)=>(X instanceof Date?X:new Date(X)).toISOString(),parse:(X)=>new Date(X)},bytea:{to:17,from:17,serialize:(X)=>"\\x"+Buffer.from(X).toString("hex"),parse:(X)=>Buffer.from(X.slice(2),"hex")}};class i6{then(){PZ()}catch(){PZ()}finally(){PZ()}}class j2 extends i6{constructor(X){super();this.value=s6(X)}}class n1 extends i6{constructor(X,Y,Z){super();this.value=X,this.type=Y,this.array=Z}}class n6 extends i6{constructor(X,Y){super();this.first=X,this.rest=Y}build(X,Y,Z,_){let G=oU.map(([W,$])=>({fn:$,i:X.search(W)})).sort((W,$)=>W.i-$.i).pop();return G.i===-1?kZ(this.first,_):G.fn(this.first,this.rest,Y,Z,_)}}function r6(X,Y,Z,_){let G=X instanceof n1?X.value:X;if(G===void 0){if(X instanceof n1?X.value=_.transform.undefined:G=X=_.transform.undefined,G===void 0)throw S0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+Z.push(X instanceof n1?(Y.push(X.value),X.array?X.array[X.type||o6(X.value)]||X.type||R$(X.value):X.type):(Y.push(X),o6(X)))}var M$=N$(lU);function fZ(X,Y,Z,_,G,W){for(let $=1;$<X.strings.length;$++)Y+=hZ(Y,Z,_,G,W)+X.strings[$],Z=X.args[$];return Y}function hZ(X,Y,Z,_,G){return Y instanceof n6?Y.build(X,Z,_,G):Y instanceof C1?xZ(Y,Z,_,G):Y instanceof j2?Y.value:Y&&Y[0]instanceof C1?Y.reduce((W,$)=>W+" "+xZ($,Z,_,G),""):r6(Y,Z,_,G)}function xZ(X,Y,Z,_){return X.fragment=!0,fZ(X,X.strings[0],X.args[0],Y,Z,_)}function A$(X,Y,Z,_,G){return X.map((W)=>"("+_.map(($)=>hZ("values",W[$],Y,Z,G)).join(",")+")").join(",")}function L$(X,Y,Z,_,G){let W=Array.isArray(X[0]),$=Y.length?Y.flat():Object.keys(W?X[0]:X);return A$(W?X:[X],Z,_,$,G)}function l6(X,Y,Z,_,G){if(typeof X==="string"&&(X=[X].concat(Y)),Array.isArray(X))return kZ(X,G);let W;return(Y.length?Y.flat():Object.keys(X)).map((H)=>{return W=X[H],(W instanceof C1?xZ(W,Z,_,G):W instanceof j2?W.value:r6(W,Z,_,G))+" as "+s6(G.transform.column.to?G.transform.column.to(H):H)}).join(",")}var oU=Object.entries({values:L$,in:(...X)=>{let Y=L$(...X);return Y==="()"?"(null)":Y},select:l6,as:l6,returning:l6,"\\(":l6,update(X,Y,Z,_,G){return(Y.length?Y.flat():Object.keys(X)).map((W)=>s6(G.transform.column.to?G.transform.column.to(W):W)+"="+hZ("values",X[W],Z,_,G))},insert(X,Y,Z,_,G){let W=Y.length?Y.flat():Object.keys(Array.isArray(X)?X[0]:X);return"("+kZ(W,G)+")values"+A$(Array.isArray(X)?X:[X],Z,_,W,G)}}).map(([X,Y])=>[new RegExp("((?:^|[\\s(])"+X+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Y]);function PZ(){throw S0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:iU,parsers:nU}=M$;function R$(X){if(Array.isArray(X))return R$(X[0]);return typeof X==="string"?1009:0}var w$=function(X){let Y=N$(X||{});return{serializers:Object.assign({},iU,Y.serializers),parsers:Object.assign({},nU,Y.parsers)}};function N$(X){return Object.keys(X).reduce((Y,Z)=>{if(X[Z].from&&[].concat(X[Z].from).forEach((_)=>Y.parsers[_]=X[Z].parse),X[Z].serialize)Y.serializers[X[Z].to]=X[Z].serialize,X[Z].from&&[].concat(X[Z].from).forEach((_)=>Y.serializers[_]=X[Z].serialize);return Y},{parsers:{},serializers:{}})}function kZ(X,{transform:{column:Y}}){return X.map((Z)=>s6(Y.to?Y.to(Z):Z)).join(",")}var s6=function(Y){return'"'+Y.replace(/"/g,'""').replace(/\./g,'"."')+'"'},o6=function X(Y){return Y instanceof n1?Y.type:Y instanceof Date?1184:Y instanceof Uint8Array?17:Y===!0||Y===!1?16:typeof Y==="bigint"?20:Array.isArray(Y)?X(Y[0]):0},rU=/\\/g,sU=/"/g;function tU(X){return X.replace(rU,"\\\\").replace(sU,"\\\"")}var I$=function X(Y,Z,_,G){if(Array.isArray(Y)===!1)return Y;if(!Y.length)return"{}";let W=Y[0],$=G===1020?";":",";if(Array.isArray(W)&&!W.type)return"{"+Y.map((H)=>X(H,Z,_,G)).join($)+"}";return"{"+Y.map((H)=>{if(H===void 0){if(H=_.transform.undefined,H===void 0)throw S0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return H===null?"null":'"'+tU(Z?Z(H.type?H.value:H):""+H)+'"'}).join($)+"}"},vZ={i:0,char:null,str:"",quoted:!1,last:0},K$=function(Y,Z,_){return vZ.i=vZ.last=0,B$(vZ,Y,Z,_)};function B$(X,Y,Z,_){let G=[],W=_===1020?";":",";for(;X.i<Y.length;X.i++){if(X.char=Y[X.i],X.quoted)if(X.char==="\\")X.str+=Y[++X.i];else if(X.char==='"')G.push(Z?Z(X.str):X.str),X.str="",X.quoted=Y[X.i+1]==='"',X.last=X.i+2;else X.str+=X.char;else if(X.char==='"')X.quoted=!0;else if(X.char==="{")X.last=++X.i,G.push(B$(X,Y,Z,_));else if(X.char==="}"){X.quoted=!1,X.last<X.i&&G.push(Z?Z(Y.slice(X.last,X.i)):Y.slice(X.last,X.i)),X.last=X.i+1;break}else if(X.char===W&&X.p!=="}"&&X.p!=='"')G.push(Z?Z(Y.slice(X.last,X.i)):Y.slice(X.last,X.i)),X.last=X.i+1;X.p=X.char}return X.last<X.i&&G.push(Z?Z(Y.slice(X.last,X.i+1)):Y.slice(X.last,X.i+1)),G}var y4=(X)=>{let Y=X[0];for(let Z=1;Z<X.length;Z++)Y+=X[Z]==="_"?X[++Z].toUpperCase():X[Z];return Y},g4=(X)=>{let Y=X[0].toUpperCase();for(let Z=1;Z<X.length;Z++)Y+=X[Z]==="_"?X[++Z].toUpperCase():X[Z];return Y},p4=(X)=>X.replace(/_/g,"-"),T2=(X)=>X.replace(/([A-Z])/g,"_$1").toLowerCase(),C2=(X)=>(X.slice(0,1)+X.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),q2=(X)=>X.replace(/-/g,"_");function bZ(X){return function Y(Z,_){return typeof Z==="object"&&Z!==null&&(_.type===114||_.type===3802)?Array.isArray(Z)?Z.map((G)=>Y(G,_)):Object.entries(Z).reduce((G,[W,$])=>Object.assign(G,{[X(W)]:Y($,_)}),{}):Z}}y4.column={from:y4};y4.value={from:bZ(y4)};T2.column={to:T2};var yZ={...y4};yZ.column.to=T2;g4.column={from:g4};g4.value={from:bZ(g4)};C2.column={to:C2};var gZ={...g4};gZ.column.to=C2;p4.column={from:p4};p4.value={from:bZ(p4)};q2.column={to:q2};var pZ={...p4};pZ.column.to=q2;import T$ from"net";import YE from"tls";import S2 from"crypto";import mZ from"stream";import{performance as C$}from"perf_hooks";class m4 extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var M1=aU;function aU(X=[]){let Y=X.slice(),Z=0;return{get length(){return Y.length-Z},remove:(_)=>{let G=Y.indexOf(_);return G===-1?null:(Y.splice(G,1),_)},push:(_)=>(Y.push(_),_),shift:()=>{let _=Y[Z++];if(Z===Y.length)Z=0,Y=[];else Y[Z-1]=void 0;return _}}}var r0=Buffer.allocUnsafe(256),eU="BCcDdEFfHPpQSX".split("").reduce((X,Y)=>{let Z=Y.charCodeAt(0);return X[Y]=()=>{return r0[0]=Z,H0.i=5,H0},X},{}),H0=Object.assign(XE,eU,{N:String.fromCharCode(0),i:0,inc(X){return H0.i+=X,H0},str(X){let Y=Buffer.byteLength(X);return t6(Y),H0.i+=r0.write(X,H0.i,Y,"utf8"),H0},i16(X){return t6(2),r0.writeUInt16BE(X,H0.i),H0.i+=2,H0},i32(X,Y){if(Y||Y===0)return r0.writeUInt32BE(X,Y),H0;return t6(4),r0.writeUInt32BE(X,H0.i),H0.i+=4,H0},z(X){return t6(X),r0.fill(0,H0.i,H0.i+X),H0.i+=X,H0},raw(X){return r0=Buffer.concat([r0.subarray(0,H0.i),X]),H0.i=r0.length,H0},end(X=1){r0.writeUInt32BE(H0.i-X,X);let Y=r0.subarray(0,H0.i);return H0.i=0,r0=Buffer.allocUnsafe(256),Y}}),b=H0;function t6(X){if(r0.length-H0.i<X){let Y=r0,Z=Y.length;r0=Buffer.allocUnsafe(Z+(Z>>1)+X),Y.copy(r0)}}function XE(){return H0.i=0,H0}var cZ=S$,ZE=1,B4=b().S().end(),q$=b().H().end(),_E=b().i32(8).i32(80877103).end(8),GE=Buffer.concat([b().E().str(b.N).i32(0).end(),B4]),WE=b().D().str("S").str(b.N).end(),R8=()=>{},$E=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),HE={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function S$(X,Y={},{onopen:Z=R8,onend:_=R8,onclose:G=R8}={}){let{ssl:W,max:$,user:H,host:Q,port:J,database:z,parsers:F,transform:O,onnotice:D,onnotify:A,onparameter:R,max_pipeline:v,keep_alive:j,backoff:P,target_session_attrs:h}=X,i=M1(),p=ZE++,y={pid:null,secret:null},m=dZ(FX,X.idle_timeout),_0=dZ(FX,X.max_lifetime),u0=dZ(e$,X.connect_timeout),K=null,J0,o=new m4,X0=Buffer.alloc(0),g0=X.fetch_types,E1={},q1={},c4=Math.random().toString(36).slice(2),I=1,u=0,W0=0,R0=0,P0=0,n=0,$0=0,C0=0,w0=null,D0=null,d0=!1,U0=null,j1=null,p0=null,z4=null,v0=null,L0=null,S1=null,u1=null,q=null,K8=null,c0={queue:Y.closed,idleTimer:m,connect(U){p0=U,L5()},terminate:T8,execute:B8,cancel:r$,end:FX,count:0,id:p};return Y.closed&&Y.closed.push(c0),c0;async function n$(){let U;try{U=X.socket?await Promise.resolve(X.socket(X)):new T$.Socket}catch(L){o4(L);return}return U.on("error",o4),U.on("close",M5),U.on("drain",V5),U}async function r$({pid:U,secret:L},g,Z0){try{J0=b().i32(16).i32(80877102).i32(U).i32(L).end(16),await D5(),K.once("error",Z0),K.once("close",g)}catch(I0){Z0(I0)}}function B8(U){if(d0)return y2(U,S0.connection("CONNECTION_DESTROYED",X));if(U.cancelled)return;try{return U.state=y,q?i.push(U):(q=U,q.active=!0),a$(U),m0(s$(U))&&!U.describeFirst&&!U.cursorFn&&i.length<v&&(!U.options.onexecute||U.options.onexecute(c0))}catch(L){return i.length===0&&m0(B4),d1(L),!0}}function s$(U){if(U.parameters.length>=65534)throw S0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return U.options.simple?b().Q().str(U.statement.string+b.N).end():U.describeFirst?Buffer.concat([U5(U),q$]):U.prepare?U.prepared?b2(U):Buffer.concat([U5(U),b2(U)]):t$(U)}function U5(U){return Buffer.concat([R5(U.statement.string,U.parameters,U.statement.types,U.statement.name),bH("S",U.statement.name)])}function b2(U){return Buffer.concat([kH(U.parameters,U.statement.types,U.statement.name,U.cursorName),U.cursorFn?w5("",U.cursorRows):GE])}function t$(U){return Buffer.concat([R5(U.statement.string,U.parameters,U.statement.types),WE,b2(U)])}function a$(U){let L=[],g=[],Z0=fZ(U,U.strings[0],U.args[0],L,g,X);!U.tagged&&U.args.forEach((I0)=>r6(I0,L,g,X)),U.prepare=X.prepare&&("prepare"in U.options?U.options.prepare:!0),U.string=Z0,U.signature=U.prepare&&g+Z0,U.onlyDescribe&&delete q1[U.signature],U.parameters=U.parameters||L,U.prepared=U.prepare&&U.signature in q1,U.describeFirst=U.onlyDescribe||L.length&&!U.prepared,U.statement=U.prepared?q1[U.signature]:{string:Z0,types:g,name:U.prepare?c4+I++:""},typeof X.debug==="function"&&X.debug(p,Z0,L,g)}function m0(U,L){if(L0=L0?Buffer.concat([L0,U]):Buffer.from(U),L||L0.length>=1024)return E5(L);return D0===null&&(D0=setImmediate(E5)),!0}function E5(U){let L=K.write(L0,U);return D0!==null&&clearImmediate(D0),L0=D0=null,L}function e$(){d1(S0.connection("CONNECT_TIMEOUT",X,K)),K.destroy()}async function O5(){if(m0(_E),!await new Promise((L)=>K.once("data",(g)=>L(g[0]===83)))&&W==="prefer")return l4();K.removeAllListeners(),K=YE.connect({socket:K,servername:T$.isIP(K.host)?void 0:K.host,...W==="require"||W==="allow"||W==="prefer"?{rejectUnauthorized:!1}:W==="verify-full"?{}:typeof W==="object"?W:{}}),K.on("secureConnect",l4),K.on("error",o4),K.on("close",M5),K.on("drain",V5)}function V5(){!q&&Z(c0)}function zX(U){if(U0){if(U0.push(U),W0-=U.length,W0>0)return}X0=U0?Buffer.concat(U0,n-W0):X0.length===0?U:Buffer.concat([X0,U],X0.length+U.length);while(X0.length>4){if(n=X0.readUInt32BE(1),n>=X0.length){W0=n-X0.length,U0=[X0];break}try{XH(X0.subarray(0,n+1))}catch(L){q&&(q.cursorFn||q.describeFirst)&&m0(B4),d1(L)}X0=X0.subarray(n+1),W0=0,U0=null}}async function D5(){if(d0=!1,E1={},K||(K=await n$()),!K)return;if(u0.start(),X.socket)return W?O5():l4();if(K.on("connect",W?O5:l4),X.path)return K.connect(X.path);K.ssl=W,K.connect(J[R0],Q[R0]),K.host=Q[R0],K.port=J[R0],R0=(R0+1)%J.length}function L5(){setTimeout(D5,u?u+$0-C$.now():0)}function l4(){try{q1={},g0=X.fetch_types,c4=Math.random().toString(36).slice(2),I=1,_0.start(),K.on("data",zX),j&&K.setKeepAlive&&K.setKeepAlive(!0,1000*j);let U=gH();m0(U)}catch(U){o4(U)}}function o4(U){if(c0.queue===Y.connecting&&X.host[P0+1])return;d1(U);while(i.length)y2(i.shift(),U)}function d1(U){v0&&(v0.destroy(U),v0=null),q&&y2(q,U),p0&&(y2(p0,U),p0=null)}function y2(U,L){if(U.reserve)return U.reject(L);if(!L||typeof L!=="object")L=Error(L);"query"in L||"parameters"in L||Object.defineProperties(L,{stack:{value:L.stack+U.origin.replace(/.*\n/,`
|
|
67
|
+
`),enumerable:X.debug},query:{value:U.string,enumerable:X.debug},parameters:{value:U.parameters,enumerable:X.debug},args:{value:U.args,enumerable:X.debug},types:{value:U.statement&&U.statement.types,enumerable:X.debug}}),U.reject(L)}function FX(){return z4||(!c0.reserved&&_(c0),!c0.reserved&&!p0&&!q&&i.length===0?(T8(),new Promise((U)=>K&&K.readyState!=="closed"?K.once("close",U):U())):z4=new Promise((U)=>S1=U))}function T8(){if(d0=!0,v0||q||p0||i.length)o4(S0.connection("CONNECTION_DESTROYED",X));if(clearImmediate(D0),K)K.removeListener("data",zX),K.removeListener("connect",l4),K.readyState==="open"&&K.end(b().X().end());S1&&(S1(),z4=S1=null)}async function M5(U){if(X0=Buffer.alloc(0),W0=0,U0=null,clearImmediate(D0),K.removeListener("data",zX),K.removeListener("connect",l4),m.cancel(),_0.cancel(),u0.cancel(),K.removeAllListeners(),K=null,p0)return L5();!U&&(q||i.length)&&o4(S0.connection("CONNECTION_CLOSED",X,K)),u=C$.now(),U&&X.shared.retries++,$0=(typeof P==="function"?P(X.shared.retries):P)*1000,G(c0,S0.connection("CONNECTION_CLOSED",X,K))}function XH(U,L=U[0]){(L===68?YH:L===100?qH:L===65?NH:L===83?ZH:L===90?_H:L===67?GH:L===50?A5:L===49?WH:L===116?$H:L===84?HH:L===82?JH:L===110?OH:L===75?VH:L===69?RH:L===115?IH:L===51?KH:L===71?BH:L===78?SH:L===72?TH:L===99?jH:L===73?PH:L===86?vH:L===118?xH:L===87?CH:fH)(U)}function YH(U){let L=7,g,Z0,I0,l0=q.isRaw?Array(q.statement.columns.length):{};for(let s0=0;s0<q.statement.columns.length;s0++)Z0=q.statement.columns[s0],g=U.readInt32BE(L),L+=4,I0=g===-1?null:q.isRaw===!0?U.subarray(L,L+=g):Z0.parser===void 0?U.toString("utf8",L,L+=g):Z0.parser.array===!0?Z0.parser(U.toString("utf8",L+1,L+=g)):Z0.parser(U.toString("utf8",L,L+=g)),q.isRaw?l0[s0]=q.isRaw===!0?I0:O.value.from?O.value.from(I0,Z0):I0:l0[Z0.name]=O.value.from?O.value.from(I0,Z0):I0;q.forEachFn?q.forEachFn(O.row.from?O.row.from(l0):l0,o):o[C0++]=O.row.from?O.row.from(l0):l0}function ZH(U){let[L,g]=U.toString("utf8",5,U.length-1).split(b.N);if(E1[L]=g,X.parameters[L]!==g)X.parameters[L]=g,R&&R(L,g)}function _H(U){if(q&&q.options.simple&&q.resolve(j1||o),q=j1=null,o=new m4,u0.cancel(),p0){if(h){if(!E1.in_hot_standby||!E1.default_transaction_read_only)return AH();else if(MH(h,E1))return T8()}if(g0)return p0.reserve&&(p0=null),DH();p0&&!p0.reserve&&B8(p0),X.shared.retries=P0=0,p0=null;return}while(i.length&&(q=i.shift())&&(q.active=!0,q.cancelled))S$(X).cancel(q.state,q.cancelled.resolve,q.cancelled.reject);if(q)return;c0.reserved?!c0.reserved.release&&U[5]===73?z4?T8():(c0.reserved=null,Z(c0)):c0.reserved():z4?T8():Z(c0)}function GH(U){C0=0;for(let L=U.length-1;L>0;L--){if(U[L]===32&&U[L+1]<58&&o.count===null)o.count=+U.toString("utf8",L+1,U.length-1);if(U[L-1]>=65){o.command=U.toString("utf8",5,L),o.state=y;break}}if(K8&&(K8(),K8=null),o.command==="BEGIN"&&$!==1&&!c0.reserved)return d1(S0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(q.options.simple)return A5();if(q.cursorFn)o.count&&q.cursorFn(o),m0(B4);q.resolve(o)}function WH(){q.parsing=!1}function A5(){!o.statement&&(o.statement=q.statement),o.columns=q.statement.columns}function $H(U){let L=U.readUInt16BE(5);for(let g=0;g<L;++g)!q.statement.types[g]&&(q.statement.types[g]=U.readUInt32BE(7+g*4));q.prepare&&(q1[q.signature]=q.statement),q.describeFirst&&!q.onlyDescribe&&(m0(b2(q)),q.describeFirst=!1)}function HH(U){if(o.command)j1=j1||[o],j1.push(o=new m4),o.count=null,q.statement.columns=null;let L=U.readUInt16BE(5),g=7,Z0;q.statement.columns=Array(L);for(let I0=0;I0<L;++I0){Z0=g;while(U[g++]!==0);let l0=U.readUInt32BE(g),s0=U.readUInt16BE(g+4),F4=U.readUInt32BE(g+6);q.statement.columns[I0]={name:O.column.from?O.column.from(U.toString("utf8",Z0,g-1)):U.toString("utf8",Z0,g-1),parser:F[F4],table:l0,number:s0,type:F4},g+=18}if(o.statement=q.statement,q.onlyDescribe)return q.resolve(q.statement),m0(B4)}async function JH(U,L=U.readUInt32BE(5)){(L===3?QH:L===5?zH:L===10?FH:L===11?UH:L===12?EH:L!==0?hH:R8)(U,L)}async function QH(){let U=await UX();m0(b().p().str(U).z(1).end())}async function zH(U){let L="md5"+await j$(Buffer.concat([Buffer.from(await j$(await UX()+H)),U.subarray(9)]));m0(b().p().str(L).z(1).end())}async function FH(){u1=(await S2.randomBytes(18)).toString("base64"),b().p().str("SCRAM-SHA-256"+b.N);let U=b.i;m0(b.inc(4).str("n,,n=*,r="+u1).i32(b.i-U-4,U).end())}async function UH(U){let L=U.toString("utf8",9).split(",").reduce((s0,F4)=>(s0[F4[0]]=F4.slice(2),s0),{}),g=await S2.pbkdf2Sync(await UX(),Buffer.from(L.s,"base64"),parseInt(L.i),32,"sha256"),Z0=await a6(g,"Client Key"),I0="n=*,r="+u1+",r="+L.r+",s="+L.s+",i="+L.i+",c=biws,r="+L.r;w0=(await a6(await a6(g,"Server Key"),I0)).toString("base64");let l0="c=biws,r="+L.r+",p="+QE(Z0,Buffer.from(await a6(await JE(Z0),I0))).toString("base64");m0(b().p().str(l0).end())}function EH(U){if(U.toString("utf8",9).split(b.N,1)[0].slice(2)===w0)return;d1(S0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),K.destroy()}function UX(){return Promise.resolve(typeof X.pass==="function"?X.pass():X.pass)}function OH(){if(o.statement=q.statement,o.statement.columns=[],q.onlyDescribe)return q.resolve(q.statement),m0(B4)}function VH(U){y.pid=U.readUInt32BE(5),y.secret=U.readUInt32BE(9)}async function DH(){g0=!1,(await new C1([`
|
|
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
|
-
`],[],
|
|
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
|
-
`],[],
|
|
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: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrac
|
|
|
84
84
|
tell.location
|
|
85
85
|
from (select lo_tell64($1) as location) tell
|
|
86
86
|
) seek
|
|
87
|
-
`};return G(Q),new Promise(async(F)=>W=F);async function J({highWaterMark:F=16384,start:O=0,end:L=1/0}={}){let w=L-O;return O&&await Q.seek(O),new hW.Readable({highWaterMark:F,async read(R){let b=R>w?R-w:R;w-=R;let[{data:x}]=await Q.read(b);if(this.push(x),x.length<R)this.push(null)}})}async function z({highWaterMark:F=16384,start:O=0}={}){return O&&await Q.seek(O),new hW.Writable({highWaterMark:F,write(L,w,R){Q.write(L).then(()=>R(),R)}})}}).catch(_)})}Object.assign(GY,{PostgresError:R2,toPascal:m4,pascal:b5,toCamel:p4,camel:k5,toKebab:u4,kebab:y5,fromPascal:q8,fromCamel:C8,fromKebab:j8,BigInt:{to:20,from:[20],parse:(Y)=>BigInt(Y),serialize:(Y)=>Y.toString()}});var N2=GY;function GY(Y,Z){let X=ME(Y,Z),G=X.no_subscribe||d5(GY,{...X}),_=!1,$=R1(),W=R1(),H=R1(),Q=R1(),J=R1(),z=R1(),F=R1(),O=R1(),L={connecting:W,reserved:H,closed:Q,ended:J,open:z,busy:F,full:O},w=[...Array(X.max)].map(()=>u5(X,L,{onopen:$1,onend:h0,onclose:r1})),R=b(c);return Object.assign(R,{get parameters(){return X.parameters},largeObject:c5.bind(null,R),subscribe:G,CLOSE:A2,END:A2,PostgresError:R2,options:X,reserve:g,listen:x,begin:B,close:p,end:s}),R;function b(T){return T.debug=X.debug,Object.entries(X.types).reduce((a,[J0,v0])=>{return a[J0]=(B0)=>new n1(B0,v0.to),a},m),Object.assign($0,{types:m,typed:m,unsafe:V0,notify:h,array:q,json:C,file:k0}),$0;function m(a,J0){return new n1(a,J0)}function $0(a,...J0){return a&&Array.isArray(a.raw)?new q1(a,J0,T,N):typeof a==="string"&&!J0.length?new P8(X.transform.column.to?X.transform.column.to(a):a):new t6(a,J0)}function V0(a,J0=[],v0={}){return arguments.length===2&&!Array.isArray(J0)&&(v0=J0,J0=[]),new q1([a],J0,T,N,{prepare:!1,...v0,simple:"simple"in v0?v0.simple:J0.length===0})}function k0(a,J0=[],v0={}){return arguments.length===2&&!Array.isArray(J0)&&(v0=J0,J0=[]),new q1([],J0,(A0)=>{LE.readFile(a,"utf8",(o0,O0)=>{if(o0)return A0.reject(o0);A0.strings=[O0],T(A0)})},N,{...v0,simple:"simple"in v0?v0.simple:J0.length===0})}}async function x(T,m,$0){let V0={fn:m,onlisten:$0},k0=x.sql||(x.sql=GY({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(x.channels).forEach(([A0,{listeners:o0}])=>{delete x.channels[A0],Promise.all(o0.map((O0)=>x(A0,O0.fn,O0.onlisten).catch(()=>{})))})},onnotify(A0,o0){A0 in x.channels&&x.channels[A0].listeners.forEach((O0)=>O0.fn(o0))}})),a=x.channels||(x.channels={});if(T in a){a[T].listeners.push(V0);let A0=await a[T].result;return V0.onlisten&&V0.onlisten(),{state:A0.state,unlisten:B0}}a[T]={result:k0`listen ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`,listeners:[V0]};let v0=await a[T].result;return V0.onlisten&&V0.onlisten(),{state:v0.state,unlisten:B0};async function B0(){if(T in a===!1)return;if(a[T].listeners=a[T].listeners.filter((A0)=>A0!==V0),a[T].listeners.length)return;return delete a[T],k0`unlisten ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`}}async function h(T,m){return await R`select pg_notify(${T}, ${""+m})`}async function g(){let T=R1(),m=z.length?z.shift():await new Promise((k0,a)=>{let J0={reserve:k0,reject:a};$.push(J0),Q.length&&I0(Q.shift(),J0)});K(m,H),m.reserved=()=>T.length?m.execute(T.shift()):K(m,H),m.reserved.release=!0;let $0=b(V0);return $0.release=()=>{m.reserved=null,$1(m)},$0;function V0(k0){m.queue===O?T.push(k0):m.execute(k0)||K(m,O)}}async function B(T,m){!m&&(m=T,T="");let $0=R1(),V0=0,k0,a=null;try{return await R.unsafe("begin "+T.replace(/[^a-z ]/ig,""),[],{onexecute:v0}).execute(),await Promise.race([J0(k0,m),new Promise((B0,A0)=>k0.onclose=A0)])}catch(B0){throw B0}async function J0(B0,A0,o0){let O0=b(b0);O0.savepoint=z4,O0.prepare=(R0)=>a=R0.replace(/[^a-z0-9$-_. ]/gi);let j1,c0;o0&&await O0`savepoint ${O0(o0)}`;try{if(c0=await new Promise((R0,P1)=>{let u1=A0(O0);Promise.resolve(Array.isArray(u1)?Promise.all(u1):u1).then(R0,P1)}),j1)throw j1}catch(R0){throw await(o0?O0`rollback to ${O0(o0)}`:O0`rollback`),R0 instanceof R2&&R0.code==="25P02"&&j1||R0}if(!o0)a?await O0`prepare transaction '${O0.unsafe(a)}'`:await O0`commit`;return c0;function z4(R0,P1){if(R0&&Array.isArray(R0.raw))return z4((u1)=>u1.apply(u1,arguments));return arguments.length===1&&(P1=R0,R0=null),J0(B0,P1,"s"+V0+++(R0?"_"+R0:""))}function b0(R0){R0.catch((P1)=>j1||(j1=P1)),B0.queue===O?$0.push(R0):B0.execute(R0)||K(B0,O)}}function v0(B0){k0=B0,K(B0,H),B0.reserved=()=>$0.length?B0.execute($0.shift()):K(B0,H)}}function K(T,m){return T.queue.remove(T),m.push(T),T.queue=m,m===z?T.idleTimer.start():T.idleTimer.cancel(),T}function C(T){return new n1(T,3802)}function q(T,m){if(!Array.isArray(T))return q(Array.from(arguments));return new n1(T,m||(T.length?r6(T)||25:0),X.shared.typeArrayMap)}function c(T){if(_)return T.reject(f0.connection("CONNECTION_ENDED",X,X));if(z.length)return n(z.shift(),T);if(Q.length)return I0(Q.shift(),T);F.length?n(F.shift(),T):$.push(T)}function n(T,m){return T.execute(m)?K(T,F):K(T,O)}function N(T){return new Promise((m,$0)=>{T.state?T.active?u5(X).cancel(T.state,m,$0):T.cancelled={resolve:m,reject:$0}:($.remove(T),T.cancelled=!0,T.reject(f0.generic("57014","canceling statement due to user request")),m())})}async function s({timeout:T=null}={}){if(_)return _;await 1;let m;return _=Promise.race([new Promise(($0)=>T!==null&&(m=setTimeout(t,T*1000,$0))),Promise.all(w.map(($0)=>$0.end()).concat(x.sql?x.sql.end({timeout:0}):[],G.sql?G.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(m))}async function p(){await Promise.all(w.map((T)=>T.end()))}async function t(T){await Promise.all(w.map((m)=>m.terminate()));while($.length)$.shift().reject(f0.connection("CONNECTION_DESTROYED",X));T()}function I0(T,m){return K(T,W),T.connect(m),T}function h0(T){K(T,J)}function $1(T){if($.length===0)return K(T,z);let m=Math.ceil($.length/(W.length+1)),$0=!0;while($0&&$.length&&m-- >0){let V0=$.shift();if(V0.reserve)return V0.reserve(T);$0=T.execute(V0)}$0?K(T,F):K(T,O)}function r1(T,m){K(T,Q),T.reserved=null,T.onclose&&(T.onclose(m),T.onclose=null),X.onclose&&X.onclose(T.id),$.length&&I0(T,$.shift())}}function ME(Y,Z){if(Y&&Y.shared)return Y;let X=process.env,G=(!Y||typeof Y==="string"?Z:Y)||{},{url:_,multihost:$}=IE(Y),W=[..._.searchParams].reduce((O,[L,w])=>(O[L]=w,O),{}),H=G.hostname||G.host||$||_.hostname||X.PGHOST||"localhost",Q=G.port||_.port||X.PGPORT||5432,J=G.user||G.username||_.username||X.PGUSERNAME||X.PGUSER||KE();G.no_prepare&&(G.prepare=!1),W.sslmode&&(W.ssl=W.sslmode,delete W.sslmode),"timeout"in G&&(console.log("The timeout option is deprecated, use idle_timeout instead"),G.idle_timeout=G.timeout),W.sslrootcert==="system"&&(W.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],F={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:wE,max_pipeline:100,backoff:RE,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(H)?H:H.split(",").map((O)=>O.split(":")[0]),port:Array.isArray(Q)?Q:H.split(",").map((O)=>parseInt(O.split(":")[1]||Q)),path:G.path||H.indexOf("/")>-1&&H+"/.s.PGSQL."+Q,database:G.database||G.db||(_.pathname||"").slice(1)||X.PGDATABASE||J,user:J,pass:G.pass||G.password||_.password||X.PGPASSWORD||"",...Object.entries(F).reduce((O,[L,w])=>{let R=L in G?G[L]:(L in W)?W[L]==="disable"||W[L]==="false"?!1:W[L]:X["PG"+L.toUpperCase()]||w;return O[L]=typeof R==="string"&&z.includes(L)?+R:R,O},{}),connection:{application_name:X.PGAPPNAME||"postgres.js",...G.connection,...Object.entries(W).reduce((O,[L,w])=>((L in F)||(O[L]=w),O),{})},types:G.types||{},target_session_attrs:AE(G,_,X),onnotice:G.onnotice,onnotify:G.onnotify,onclose:G.onclose,onparameter:G.onparameter,socket:G.socket,transform:NE(G.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...KW(G.types)}}function AE(Y,Z,X){let G=Y.target_session_attrs||Z.searchParams.get("target_session_attrs")||X.PGTARGETSESSIONATTRS;if(!G||["read-write","read-only","primary","standby","prefer-standby"].includes(G))return G;throw Error("target_session_attrs "+G+" is not supported")}function RE(Y){return(0.5+Math.random()/2)*Math.min(3**Y/100,20)}function wE(){return 60*(30+Math.random()*30)}function NE(Y){return{undefined:Y.undefined,column:{from:typeof Y.column==="function"?Y.column:Y.column&&Y.column.from,to:Y.column&&Y.column.to},value:{from:typeof Y.value==="function"?Y.value:Y.value&&Y.value.from,to:Y.value&&Y.value.to},row:{from:typeof Y.row==="function"?Y.row:Y.row&&Y.row.from,to:Y.row&&Y.row.to}}}function IE(Y){if(!Y||typeof Y!=="string")return{url:{searchParams:new Map}};let Z=Y;Z=Z.slice(Z.indexOf("://")+3).split(/[?/]/)[0],Z=decodeURIComponent(Z.slice(Z.indexOf("@")+1));let X=new URL(Y.replace(Z,Z.split(",")[0]));return{url:{username:decodeURIComponent(X.username),password:decodeURIComponent(X.password),host:X.host,hostname:X.hostname,port:X.port,pathname:X.pathname,searchParams:X.searchParams},multihost:Z.indexOf(",")>-1&&Z}}function KE(){try{return DE.userInfo().username}catch(Y){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class q0{static[E]="SelectionProxyHandler";config;constructor(Y){this.config={...Y}}get(Y,Z){if(Z==="_")return{...Y._,selectedFields:new Proxy(Y._.selectedFields,this)};if(Z===M0)return{...Y[M0],selectedFields:new Proxy(Y[M0].selectedFields,this)};if(typeof Z==="symbol")return Y[Z];let G=(M(Y,S0)?Y._.selectedFields:M(Y,V1)?Y[M0].selectedFields:Y)[Z];if(M(G,f.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!G.isSelectionField)return G.sql;let _=G.clone();return _.isSelectionField=!0,_}if(M(G,f)){if(this.config.sqlBehavior==="sql")return G;throw Error(`You tried to reference "${Z}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(M(G,F0)){if(this.config.alias)return new Proxy(G,new M2(new Proxy(G.table,new A8(this.config.alias,this.config.replaceOriginalName??!1))));return G}if(typeof G!=="object"||G===null)return G;return new Proxy(G,new q0(this.config))}}class kW{constructor(Y,Z){this.unique=Y,this.name=Z}static[E]="PgIndexBuilderOn";on(...Y){return new _Y(Y.map((Z)=>{if(M(Z,f))return Z;Z=Z;let X=new O8(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=JSON.parse(JSON.stringify(Z.defaultConfig)),X}),this.unique,!1,this.name)}onOnly(...Y){return new _Y(Y.map((Z)=>{if(M(Z,f))return Z;Z=Z;let X=new O8(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=Z.defaultConfig,X}),this.unique,!0,this.name)}using(Y,...Z){return new _Y(Z.map((X)=>{if(M(X,f))return X;X=X;let G=new O8(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),G}),this.unique,!0,this.name,Y)}}class _Y{static[E]="PgIndexBuilder";config;constructor(Y,Z,X,G,_="btree"){this.config={name:G,columns:Y,unique:Z,only:X,method:_}}concurrently(){return this.config.concurrently=!0,this}with(Y){return this.config.with=Y,this}where(Y){return this.config.where=Y,this}build(Y){return new bW(this.config,Y)}}class bW{static[E]="PgIndex";config;constructor(Y,Z){this.config={...Y,table:Z}}}function l5(Y){return new kW(!0,Y)}function BE(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function TE(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,G,_)=>{let $=_===0?G.toLowerCase():`${G[0].toUpperCase()}${G.slice(1)}`;return X+$},"")}function CE(Y){return Y}class o5{static[E]="CasingCache";cache={};cachedTables={};convert;constructor(Y){this.convert=Y==="snake_case"?BE:Y==="camelCase"?TE:CE}getColumnCasing(Y){if(!Y.keyAsName)return Y.name;let Z=Y.table[P.Symbol.Schema]??"public",X=Y.table[P.Symbol.OriginalName],G=`${Z}.${X}.${Y.name}`;if(!this.cache[G])this.cacheTable(Y.table);return this.cache[G]}cacheTable(Y){let Z=Y[P.Symbol.Schema]??"public",X=Y[P.Symbol.OriginalName],G=`${Z}.${X}`;if(!this.cachedTables[G]){for(let _ of Object.values(Y[P.Symbol.Columns])){let $=`${G}.${_.name}`;this.cache[$]=this.convert(_.name)}this.cachedTables[G]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class v8 extends V1{static[E]="PgViewBase"}class c4{static[E]="PgDialect";casing;constructor(Y){this.casing=new o5(Y?.casing)}async migrate(Y,Z,X){let G=typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",_=typeof X==="string"?"drizzle":X.migrationsSchema??"drizzle",$=V`
|
|
88
|
-
CREATE TABLE IF NOT EXISTS ${V.identifier(
|
|
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
|
+
CREATE TABLE IF NOT EXISTS ${V.identifier(G)}.${V.identifier(_)} (
|
|
89
89
|
id SERIAL PRIMARY KEY,
|
|
90
90
|
hash text NOT NULL,
|
|
91
91
|
created_at bigint
|
|
92
92
|
)
|
|
93
|
-
`;await Z.execute(V`CREATE SCHEMA IF NOT EXISTS ${V.identifier(_)}`),await Z.execute($);let H=(await Z.all(V`select id, hash, created_at from ${V.identifier(_)}.${V.identifier(G)} order by created_at desc limit 1`))[0];await Z.transaction(async(Q)=>{for await(let J of Y)if(!H||Number(H.created_at)<J.folderMillis){for(let z of J.sql)await Q.execute(V.raw(z));await Q.execute(V`insert into ${V.identifier(_)}.${V.identifier(G)} ("hash", "created_at") values(${J.hash}, ${J.folderMillis})`)}})}escapeName(Y){return`"${Y}"`}escapeParam(Y){return`$${Y+1}`}escapeString(Y){return`'${Y.replace(/'/g,"''")}'`}buildWithCTE(Y){if(!Y?.length)return;let Z=[V`with `];for(let[X,G]of Y.entries())if(Z.push(V`${V.identifier(G._.alias)} as (${G._.sql})`),X<Y.length-1)Z.push(V`, `);return Z.push(V` `),V.join(Z)}buildDeleteQuery({table:Y,where:Z,returning:X,withList:G}){let _=this.buildWithCTE(G),$=X?V` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,W=Z?V` where ${Z}`:void 0;return V`${_}delete from ${Y}${W}${$}`}buildUpdateSet(Y,Z){let X=Y[P.Symbol.Columns],G=Object.keys(X).filter(($)=>Z[$]!==void 0||X[$]?.onUpdateFn!==void 0),_=G.length;return V.join(G.flatMap(($,W)=>{let H=X[$],Q=Z[$]??V.param(H.onUpdateFn(),H),J=V`${V.identifier(this.casing.getColumnCasing(H))} = ${Q}`;if(W<_-1)return[J,V.raw(", ")];return[J]}))}buildUpdateQuery({table:Y,set:Z,where:X,returning:G,withList:_,from:$,joins:W}){let H=this.buildWithCTE(_),Q=Y[u0.Symbol.Name],J=Y[u0.Symbol.Schema],z=Y[u0.Symbol.OriginalName],F=Q===z?void 0:Q,O=V`${J?V`${V.identifier(J)}.`:void 0}${V.identifier(z)}${F&&V` ${V.identifier(F)}`}`,L=this.buildUpdateSet(Y,Z),w=$&&V.join([V.raw(" from "),this.buildFromTable($)]),R=this.buildJoins(W),b=G?V` returning ${this.buildSelection(G,{isSingleTable:!$})}`:void 0,x=X?V` where ${X}`:void 0;return V`${H}update ${O} set ${L}${w}${R}${x}${b}`}buildSelection(Y,{isSingleTable:Z=!1}={}){let X=Y.length,G=Y.flatMap(({field:_},$)=>{let W=[];if(M(_,f.Aliased)&&_.isSelectionField)W.push(V.identifier(_.fieldAlias));else if(M(_,f.Aliased)||M(_,f)){let H=M(_,f.Aliased)?_.sql:_;if(Z)W.push(new f(H.queryChunks.map((Q)=>{if(M(Q,j))return V.identifier(this.casing.getColumnCasing(Q));return Q})));else W.push(H);if(M(_,f.Aliased))W.push(V` as ${V.identifier(_.fieldAlias)}`)}else if(M(_,F0))if(Z)W.push(V.identifier(this.casing.getColumnCasing(_)));else W.push(_);if($<X-1)W.push(V`, `);return W});return V.join(G)}buildJoins(Y){if(!Y||Y.length===0)return;let Z=[];for(let[X,G]of Y.entries()){if(X===0)Z.push(V` `);let _=G.table,$=G.lateral?V` lateral`:void 0,W=G.on?V` on ${G.on}`:void 0;if(M(_,u0)){let H=_[u0.Symbol.Name],Q=_[u0.Symbol.Schema],J=_[u0.Symbol.OriginalName],z=H===J?void 0:G.alias;Z.push(V`${V.raw(G.joinType)} join${$} ${Q?V`${V.identifier(Q)}.`:void 0}${V.identifier(J)}${z&&V` ${V.identifier(z)}`}${W}`)}else if(M(_,V1)){let H=_[M0].name,Q=_[M0].schema,J=_[M0].originalName,z=H===J?void 0:G.alias;Z.push(V`${V.raw(G.joinType)} join${$} ${Q?V`${V.identifier(Q)}.`:void 0}${V.identifier(J)}${z&&V` ${V.identifier(z)}`}${W}`)}else Z.push(V`${V.raw(G.joinType)} join${$} ${_}${W}`);if(X<Y.length-1)Z.push(V` `)}return V.join(Z)}buildFromTable(Y){if(M(Y,P)&&Y[P.Symbol.IsAlias]){let Z=V`${V.identifier(Y[P.Symbol.OriginalName])}`;if(Y[P.Symbol.Schema])Z=V`${V.identifier(Y[P.Symbol.Schema])}.${Z}`;return V`${Z} ${V.identifier(Y[P.Symbol.Name])}`}return Y}buildSelectQuery({withList:Y,fields:Z,fieldsFlat:X,where:G,having:_,table:$,joins:W,orderBy:H,groupBy:Q,limit:J,offset:z,lockingClause:F,distinct:O,setOperators:L}){let w=X??T1(Z);for(let t of w)if(M(t.field,F0)&&d0(t.field.table)!==(M($,S0)?$._.alias:M($,v8)?$[M0].name:M($,f)?void 0:d0($))&&!((I0)=>W?.some(({alias:h0})=>h0===(I0[P.Symbol.IsAlias]?d0(I0):I0[P.Symbol.BaseName])))(t.field.table)){let I0=d0(t.field.table);throw Error(`Your "${t.path.join("->")}" field references a column "${I0}"."${t.field.name}", but the table "${I0}" is not part of the query! Did you forget to join it?`)}let R=!W||W.length===0,b=this.buildWithCTE(Y),x;if(O)x=O===!0?V` distinct`:V` distinct on (${V.join(O.on,V`, `)})`;let h=this.buildSelection(w,{isSingleTable:R}),g=this.buildFromTable($),B=this.buildJoins(W),K=G?V` where ${G}`:void 0,C=_?V` having ${_}`:void 0,q;if(H&&H.length>0)q=V` order by ${V.join(H,V`, `)}`;let c;if(Q&&Q.length>0)c=V` group by ${V.join(Q,V`, `)}`;let n=typeof J==="object"||typeof J==="number"&&J>=0?V` limit ${J}`:void 0,N=z?V` offset ${z}`:void 0,s=V.empty();if(F){let t=V` for ${V.raw(F.strength)}`;if(F.config.of)t.append(V` of ${V.join(Array.isArray(F.config.of)?F.config.of:[F.config.of],V`, `)}`);if(F.config.noWait)t.append(V` nowait`);else if(F.config.skipLocked)t.append(V` skip locked`);s.append(t)}let p=V`${b}select${x} ${h} from ${g}${B}${K}${c}${C}${q}${n}${N}${s}`;if(L.length>0)return this.buildSetOperations(p,L);return p}buildSetOperations(Y,Z){let[X,...G]=Z;if(!X)throw Error("Cannot pass undefined values to any set operator");if(G.length===0)return this.buildSetOperationQuery({leftSelect:Y,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:Y,setOperator:X}),G)}buildSetOperationQuery({leftSelect:Y,setOperator:{type:Z,isAll:X,rightSelect:G,limit:_,orderBy:$,offset:W}}){let H=V`(${Y.getSQL()}) `,Q=V`(${G.getSQL()})`,J;if($&&$.length>0){let L=[];for(let w of $)if(M(w,j))L.push(V.identifier(w.name));else if(M(w,f)){for(let R=0;R<w.queryChunks.length;R++){let b=w.queryChunks[R];if(M(b,j))w.queryChunks[R]=V.identifier(b.name)}L.push(V`${w}`)}else L.push(V`${w}`);J=V` order by ${V.join(L,V`, `)} `}let z=typeof _==="object"||typeof _==="number"&&_>=0?V` limit ${_}`:void 0,F=V.raw(`${Z} ${X?"all ":""}`),O=W?V` offset ${W}`:void 0;return V`${H}${F}${Q}${J}${z}${O}`}buildInsertQuery({table:Y,values:Z,onConflict:X,returning:G,withList:_,select:$,overridingSystemValue_:W}){let H=[],Q=Y[P.Symbol.Columns],J=Object.entries(Q).filter(([b,x])=>!x.shouldDisableInsert()),z=J.map(([,b])=>V.identifier(this.casing.getColumnCasing(b)));if($){let b=Z;if(M(b,f))H.push(b);else H.push(b.getSQL())}else{let b=Z;H.push(V.raw("values "));for(let[x,h]of b.entries()){let g=[];for(let[B,K]of J){let C=h[B];if(C===void 0||M(C,A1)&&C.value===void 0)if(K.defaultFn!==void 0){let q=K.defaultFn(),c=M(q,f)?q:V.param(q,K);g.push(c)}else if(!K.default&&K.onUpdateFn!==void 0){let q=K.onUpdateFn(),c=M(q,f)?q:V.param(q,K);g.push(c)}else g.push(V`default`);else g.push(C)}if(H.push(g),x<b.length-1)H.push(V`, `)}}let F=this.buildWithCTE(_),O=V.join(H),L=G?V` returning ${this.buildSelection(G,{isSingleTable:!0})}`:void 0,w=X?V` on conflict ${X}`:void 0,R=W===!0?V`overriding system value `:void 0;return V`${F}insert into ${Y} ${z} ${R}${O}${w}${L}`}buildRefreshMaterializedViewQuery({view:Y,concurrently:Z,withNoData:X}){let G=Z?V` concurrently`:void 0,_=X?V` with no data`:void 0;return V`refresh materialized view${G} ${Y}${_}`}prepareTyping(Y){if(M(Y,g6)||M(Y,y6))return"json";else if(M(Y,p6))return"decimal";else if(M(Y,m6))return"time";else if(M(Y,u6)||M(Y,d6))return"timestamp";else if(M(Y,k6)||M(Y,b6))return"date";else if(M(Y,c6))return"uuid";else return"none"}sqlToQuery(Y,Z){return Y.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:Z})}buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:G,tableConfig:_,queryConfig:$,tableAlias:W,nestedQueryRelation:H,joinOn:Q}){let J=[],z,F,O=[],L,w=[];if($===!0)J=Object.entries(_.columns).map(([x,h])=>({dbKey:h.name,tsKey:x,field:i1(h,W),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let b=Object.fromEntries(Object.entries(_.columns).map(([C,q])=>[C,i1(q,W)]));if($.where){let C=typeof $.where==="function"?$.where(b,UW()):$.where;L=C&&R8(C,W)}let x=[],h=[];if($.columns){let C=!1;for(let[q,c]of Object.entries($.columns)){if(c===void 0)continue;if(q in _.columns){if(!C&&c===!0)C=!0;h.push(q)}}if(h.length>0)h=C?h.filter((q)=>$.columns?.[q]===!0):Object.keys(_.columns).filter((q)=>!h.includes(q))}else h=Object.keys(_.columns);for(let C of h){let q=_.columns[C];x.push({tsKey:C,value:q})}let g=[];if($.with)g=Object.entries($.with).filter((C)=>!!C[1]).map(([C,q])=>({tsKey:C,queryConfig:q,relation:_.relations[C]}));let B;if($.extras){B=typeof $.extras==="function"?$.extras(b,{sql:V}):$.extras;for(let[C,q]of Object.entries(B))x.push({tsKey:C,value:R5(q,W)})}for(let{tsKey:C,value:q}of x)J.push({dbKey:M(q,f.Aliased)?q.fieldAlias:_.columns[C].name,tsKey:C,field:M(q,F0)?i1(q,W):q,relationTableTsKey:void 0,isJson:!1,selection:[]});let K=typeof $.orderBy==="function"?$.orderBy(b,FW()):$.orderBy??[];if(!Array.isArray(K))K=[K];O=K.map((C)=>{if(M(C,F0))return i1(C,W);return R8(C,W)}),z=$.limit,F=$.offset;for(let{tsKey:C,queryConfig:q,relation:c}of g){let n=VW(Z,X,c),N=g4(c.referencedTable),s=X[N],p=`${W}_${C}`,t=B8(...n.fields.map(($1,r1)=>l6(i1(n.references[r1],p),i1($1,W)))),I0=this.buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:Y[s],tableConfig:Z[s],queryConfig:M(c,K4)?q===!0?{limit:1}:{...q,limit:1}:q,tableAlias:p,joinOn:t,nestedQueryRelation:c}),h0=V`${V.identifier(p)}.${V.identifier("data")}`.as(C);w.push({on:V`true`,table:new S0(I0.sql,{},p),alias:p,joinType:"left",lateral:!0}),J.push({dbKey:C,tsKey:C,field:h0,relationTableTsKey:s,isJson:!0,selection:I0.selection})}}if(J.length===0)throw new f6({message:`No fields selected for table "${_.tsName}" ("${W}")`});let R;if(L=B8(Q,L),H){let b=V`json_build_array(${V.join(J.map(({field:g,tsKey:B,isJson:K})=>K?V`${V.identifier(`${W}_${B}`)}.${V.identifier("data")}`:M(g,f.Aliased)?g.sql:g),V`, `)})`;if(M(H,T8))b=V`coalesce(json_agg(${b}${O.length>0?V` order by ${V.join(O,V`, `)}`:void 0}), '[]'::json)`;let x=[{dbKey:"data",tsKey:"data",field:b.as("data"),isJson:!0,relationTableTsKey:_.tsName,selection:J}];if(z!==void 0||F!==void 0||O.length>0)R=this.buildSelectQuery({table:x6(G,W),fields:{},fieldsFlat:[{path:[],field:V.raw("*")}],where:L,limit:z,offset:F,orderBy:O,setOperators:[]}),L=void 0,z=void 0,F=void 0,O=[];else R=x6(G,W);R=this.buildSelectQuery({table:M(R,u0)?R:new S0(R,{},W),fields:{},fieldsFlat:x.map(({field:g})=>({path:[],field:M(g,F0)?i1(g,W):g})),joins:w,where:L,limit:z,offset:F,orderBy:O,setOperators:[]})}else R=this.buildSelectQuery({table:x6(G,W),fields:{},fieldsFlat:J.map(({field:b})=>({path:[],field:M(b,F0)?i1(b,W):b})),joins:w,where:L,limit:z,offset:F,orderBy:O,setOperators:[]});return{tableTsKey:_.tsName,sql:R,selection:J}}}class i5{static[E]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class _1{static[E]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(Y){if(this.fields=Y.fields,this.session=Y.session,this.dialect=Y.dialect,Y.withList)this.withList=Y.withList;this.distinct=Y.distinct}authToken;setToken(Y){return this.authToken=Y,this}from(Y){let Z=!!this.fields,X=Y,G;if(this.fields)G=this.fields;else if(M(X,S0))G=Object.fromEntries(Object.keys(X._.selectedFields).map((_)=>[_,X[_]]));else if(M(X,v8))G=X[M0].selectedFields;else if(M(X,f))G={};else G=d7(X);return new n5({table:X,fields:G,isPartialSelect:Z,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class yW extends i5{static[E]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:Y,fields:Z,isPartialSelect:X,session:G,dialect:_,withList:$,distinct:W}){super();this.config={withList:$,table:Y,fields:{...Z},distinct:W,setOperators:[]},this.isPartialSelect=X,this.session=G,this.dialect=_,this._={selectedFields:Z,config:this.config},this.tableName=J4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let H of m1(Y))this.usedTables.add(H)}getUsedTables(){return[...this.usedTables]}createJoin(Y,Z){return(X,G)=>{let _=this.tableName,$=J4(X);for(let W of m1(X))this.usedTables.add(W);if(typeof $==="string"&&this.config.joins?.some((W)=>W.alias===$))throw Error(`Alias "${$}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof _==="string")this.config.fields={[_]:this.config.fields};if(typeof $==="string"&&!M(X,f)){let W=M(X,S0)?X._.selectedFields:M(X,V1)?X[M0].selectedFields:X[P.Symbol.Columns];this.config.fields[$]=W}}if(typeof G==="function")G=G(new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:G,table:X,joinType:Y,alias:$,lateral:Z}),typeof $==="string")switch(Y){case"left":{this.joinsNotNullableMap[$]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([W])=>[W,!1])),this.joinsNotNullableMap[$]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[$]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([W])=>[W,!1])),this.joinsNotNullableMap[$]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(Y,Z){return(X)=>{let G=typeof X==="function"?X(qE()):X;if(!w8(this.getSelectedFields(),G.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:Y,isAll:Z,rightSelect:G}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(Y){return this.config.setOperators.push(...Y),this}where(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=Y,this}having(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=Y,this}groupBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(Z)?Z:[Z]}else this.config.groupBy=Y;return this}orderBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray(Z)?Z:[Z];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=X;else this.config.orderBy=X}else{let Z=Y;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Z;else this.config.orderBy=Z}return this}limit(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=Y;else this.config.limit=Y;return this}offset(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=Y;else this.config.offset=Y;return this}for(Y,Z={}){return this.config.lockingClause={strength:Y,config:Z},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}as(Y){let Z=[];if(Z.push(...m1(this.config.table)),this.config.joins)for(let X of this.config.joins)Z.push(...m1(X.table));return new Proxy(new S0(this.getSQL(),this.config.fields,Y,!1,[...new Set(Z)]),new q0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new q0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(Y){return this.cacheConfig=Y===void 0?{config:{},enable:!0,autoInvalidate:!0}:Y===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...Y},this}}class n5 extends yW{static[E]="PgSelect";_prepare(Y){let{session:Z,config:X,dialect:G,joinsNotNullableMap:_,authToken:$,cacheConfig:W,usedTables:H}=this;if(!Z)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:Q}=X;return E0.startActiveSpan("drizzle.prepareQuery",()=>{let J=T1(Q),z=Z.prepareQuery(G.sqlToQuery(this.getSQL()),J,Y,!0,void 0,{type:"select",tables:[...H]},W);return z.joinsNotNullableMap=_,z.setToken($)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}u7(n5,[G1]);function I2(Y,Z){return(X,G,..._)=>{let $=[G,..._].map((W)=>({type:Y,isAll:Z,rightSelect:W}));for(let W of $)if(!w8(X.getSelectedFields(),W.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return X.addSetOperators($)}}var qE=()=>({union:jE,unionAll:PE,intersect:SE,intersectAll:vE,except:xE,exceptAll:fE}),jE=I2("union",!1),PE=I2("union",!0),SE=I2("intersect",!1),vE=I2("intersect",!0),xE=I2("except",!1),fE=I2("except",!0);class x8{static[E]="PgQueryBuilder";dialect;dialectConfig;constructor(Y){this.dialect=M(Y,c4)?Y:void 0,this.dialectConfig=M(Y,c4)?void 0:Y}$with=(Y,Z)=>{let X=this;return{as:(_)=>{if(typeof _==="function")_=_(X);return new Proxy(new L8(_.getSQL(),Z??("getSelectedFields"in _?_.getSelectedFields()??{}:{}),Y,!0),new q0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...Y){let Z=this;function X($){return new _1({fields:$??void 0,session:void 0,dialect:Z.getDialect(),withList:Y})}function G($){return new _1({fields:$??void 0,session:void 0,dialect:Z.getDialect(),distinct:!0})}function _($,W){return new _1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),distinct:{on:$}})}return{select:X,selectDistinct:G,selectDistinctOn:_}}select(Y){return new _1({fields:Y??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(Y){return new _1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(Y,Z){return new _1({fields:Z??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:Y}})}getDialect(){if(!this.dialect)this.dialect=new c4(this.dialectConfig);return this.dialect}}function m1(Y){if(M(Y,u0))return[Y[y4]?`${Y[y4]}.${Y[P.Symbol.BaseName]}`:Y[P.Symbol.BaseName]];if(M(Y,S0))return Y._.usedTables??[];if(M(Y,f))return Y.usedTables??[];return[]}class $Y extends G1{constructor(Y,Z,X,G){super();this.session=Z,this.dialect=X,this.config={table:Y,withList:G}}static[E]="PgDelete";config;cacheConfig;where(Y){return this.config.where=Y,this}returning(Y=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=T1(Y),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"delete",tables:m1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new q0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class WY{constructor(Y,Z,X,G,_){this.table=Y,this.session=Z,this.dialect=X,this.withList=G,this.overridingSystemValue_=_}static[E]="PgInsertBuilder";authToken;setToken(Y){return this.authToken=Y,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(Y){if(Y=Array.isArray(Y)?Y:[Y],Y.length===0)throw Error("values() must be called with at least one value");let Z=Y.map((X)=>{let G={},_=this.table[P.Symbol.Columns];for(let $ of Object.keys(X)){let W=X[$];G[$]=M(W,f)?W:new A1(W,_[$])}return G});return new r5(this.table,Z,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(Y){let Z=typeof Y==="function"?Y(new x8):Y;if(!M(Z,f)&&!w8(this.table[S6],Z._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new r5(this.table,Z,this.session,this.dialect,this.withList,!0)}}class r5 extends G1{constructor(Y,Z,X,G,_,$,W){super();this.session=X,this.dialect=G,this.config={table:Y,values:Z,withList:_,select:$,overridingSystemValue_:W}}static[E]="PgInsert";config;cacheConfig;returning(Y=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=T1(Y),this}onConflictDoNothing(Y={}){if(Y.target===void 0)this.config.onConflict=V`do nothing`;else{let Z="";Z=Array.isArray(Y.target)?Y.target.map((G)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(G))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target));let X=Y.where?V` where ${Y.where}`:void 0;this.config.onConflict=V`(${V.raw(Z)})${X} do nothing`}return this}onConflictDoUpdate(Y){if(Y.where&&(Y.targetWhere||Y.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let Z=Y.where?V` where ${Y.where}`:void 0,X=Y.targetWhere?V` where ${Y.targetWhere}`:void 0,G=Y.setWhere?V` where ${Y.setWhere}`:void 0,_=this.dialect.buildUpdateSet(this.config.table,h6(this.config.table,Y.set)),$="";return $=Array.isArray(Y.target)?Y.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target)),this.config.onConflict=V`(${V.raw($)})${X} do update set ${_}${Z}${G}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:m1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new q0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class s5 extends G1{constructor(Y,Z,X){super();this.session=Z,this.dialect=X,this.config={view:Y}}static[E]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,Y,!0)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}class HY{constructor(Y,Z,X,G){this.table=Y,this.session=Z,this.dialect=X,this.withList=G}static[E]="PgUpdateBuilder";authToken;setToken(Y){return this.authToken=Y,this}set(Y){return new gW(this.table,h6(this.table,Y),this.session,this.dialect,this.withList).setToken(this.authToken)}}class gW extends G1{constructor(Y,Z,X,G,_){super();this.session=X,this.dialect=G,this.config={set:Z,table:Y,withList:_,joins:[]},this.tableName=J4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[E]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(Y){let Z=Y,X=J4(Z);if(typeof X==="string")this.joinsNotNullableMap[X]=!0;return this.config.from=Z,this}getTableLikeFields(Y){if(M(Y,u0))return Y[P.Symbol.Columns];else if(M(Y,S0))return Y._.selectedFields;return Y[M0].selectedFields}createJoin(Y){return(Z,X)=>{let G=J4(Z);if(typeof G==="string"&&this.config.joins.some((_)=>_.alias===G))throw Error(`Alias "${G}" is already used in this query`);if(typeof X==="function"){let _=this.config.from&&!M(this.config.from,f)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[P.Symbol.Columns],new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),_&&new Proxy(_,new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:X,table:Z,joinType:Y,alias:G}),typeof G==="string")switch(Y){case"left":{this.joinsNotNullableMap[G]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([_])=>[_,!1])),this.joinsNotNullableMap[G]=!0;break}case"inner":{this.joinsNotNullableMap[G]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([_])=>[_,!1])),this.joinsNotNullableMap[G]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(Y){return this.config.where=Y,this}returning(Y){if(!Y){if(Y=Object.assign({},this.config.table[P.Symbol.Columns]),this.config.from){let Z=J4(this.config.from);if(typeof Z==="string"&&this.config.from&&!M(this.config.from,f)){let X=this.getTableLikeFields(this.config.from);Y[Z]=X}for(let X of this.config.joins){let G=J4(X.table);if(typeof G==="string"&&!M(X.table,f)){let _=this.getTableLikeFields(X.table);Y[G]=_}}}}return this.config.returningFields=Y,this.config.returning=T1(Y),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){let Z=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:m1(this.config.table)},this.cacheConfig);return Z.joinsNotNullableMap=this.joinsNotNullableMap,Z}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return this._prepare().execute(Y,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new q0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class f8 extends f{constructor(Y){super(f8.buildEmbeddedCount(Y.source,Y.filters).queryChunks);this.params=Y,this.mapWith(Number),this.session=Y.session,this.sql=f8.buildCount(Y.source,Y.filters)}sql;token;static[E]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(Y,Z){return V`(select count(*) from ${Y}${V.raw(" where ").if(Z)}${Z})`}static buildCount(Y,Z){return V`select count(*) as count from ${Y}${V.raw(" where ").if(Z)}${Z};`}setToken(Y){return this.token=Y,this}then(Y,Z){return Promise.resolve(this.session.count(this.sql,this.token)).then(Y,Z)}catch(Y){return this.then(void 0,Y)}finally(Y){return this.then((Z)=>{return Y?.(),Z},(Z)=>{throw Y?.(),Z})}}class a5{constructor(Y,Z,X,G,_,$,W){this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=G,this.tableConfig=_,this.dialect=$,this.session=W}static[E]="PgRelationalQueryBuilder";findMany(Y){return new t5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?Y:{},"many")}findFirst(Y){return new t5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?{...Y,limit:1}:{limit:1},"first")}}class t5 extends G1{constructor(Y,Z,X,G,_,$,W,H,Q){super();this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=G,this.tableConfig=_,this.dialect=$,this.session=W,this.config=H,this.mode=Q}static[E]="PgRelationalQuery";_prepare(Y){return E0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Z,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,Y,!0,(G,_)=>{let $=G.map((W)=>o6(this.schema,this.tableConfig,W,Z.selection,_));if(this.mode==="first")return $[0];return $})})}prepare(Y){return this._prepare(Y)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let Y=this._getQuery(),Z=this.dialect.sqlToQuery(Y.sql);return{query:Y,builtQuery:Z}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(Y){return this.authToken=Y,this}execute(){return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class e5 extends G1{constructor(Y,Z,X,G){super();this.execute=Y,this.sql=Z,this.query=X,this.mapBatchResult=G}static[E]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(Y,Z){return Z?this.mapBatchResult(Y):Y}_prepare(){return this}isResponseInArrayMode(){return!1}}class h8{constructor(Y,Z,X){if(this.dialect=Y,this.session=Z,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap,session:Z}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:Z},this.query={},this._.schema)for(let[G,_]of Object.entries(this._.schema))this.query[G]=new a5(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[G],_,Y,Z);this.$cache={invalidate:async(G)=>{}}}static[E]="PgDatabase";query;$with=(Y,Z)=>{let X=this;return{as:(_)=>{if(typeof _==="function")_=_(new x8(X.dialect));return new Proxy(new L8(_.getSQL(),Z??("getSelectedFields"in _?_.getSelectedFields()??{}:{}),Y,!0),new q0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(Y,Z){return new f8({source:Y,filters:Z,session:this.session})}$cache;with(...Y){let Z=this;function X(Q){return new _1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y})}function G(Q){return new _1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:!0})}function _(Q,J){return new _1({fields:J??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:{on:Q}})}function $(Q){return new HY(Q,Z.session,Z.dialect,Y)}function W(Q){return new WY(Q,Z.session,Z.dialect,Y)}function H(Q){return new $Y(Q,Z.session,Z.dialect,Y)}return{select:X,selectDistinct:G,selectDistinctOn:_,update:$,insert:W,delete:H}}select(Y){return new _1({fields:Y??void 0,session:this.session,dialect:this.dialect})}selectDistinct(Y){return new _1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(Y,Z){return new _1({fields:Z??void 0,session:this.session,dialect:this.dialect,distinct:{on:Y}})}update(Y){return new HY(Y,this.session,this.dialect)}insert(Y){return new WY(Y,this.session,this.dialect)}delete(Y){return new $Y(Y,this.session,this.dialect)}refreshMaterializedView(Y){return new s5(Y,this.session,this.dialect)}authToken;execute(Y){let Z=typeof Y==="string"?V.raw(Y):Y.getSQL(),X=this.dialect.sqlToQuery(Z),G=this.session.prepareQuery(X,void 0,void 0,!1);return new e5(()=>G.execute(void 0,this.authToken),Z,X,(_)=>G.mapResult(_,!0))}transaction(Y,Z){return this.session.transaction(Y,Z)}}class pW{static[E]="Cache"}class k8 extends pW{strategy(){return"all"}static[E]="NoopCache";async get(Y){return}async put(Y,Z,X,G){}async onMutate(Y){}}async function YX(Y,Z){let X=`${Y}-${JSON.stringify(Z)}`,_=new TextEncoder().encode(X),$=await crypto.subtle.digest("SHA-256",_);return[...new Uint8Array($)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}class ZX{constructor(Y,Z,X,G){if(this.query=Y,this.cache=Z,this.queryMetadata=X,this.cacheConfig=G,Z&&Z.strategy()==="all"&&G===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(Y,Z){return Y}setToken(Y){return this.authToken=Y,this}static[E]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(Y,Z,X){if(this.cache===void 0||M(this.cache,k8)||this.queryMetadata===void 0)try{return await X()}catch(G){throw new H4(Y,Z,G)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await X()}catch(G){throw new H4(Y,Z,G)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[G]=await Promise.all([X(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return G}catch(G){throw new H4(Y,Z,G)}if(!this.cacheConfig)try{return await X()}catch(G){throw new H4(Y,Z,G)}if(this.queryMetadata.type==="select"){let G=await this.cache.get(this.cacheConfig.tag??await YX(Y,Z),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(G===void 0){let _;try{_=await X()}catch($){throw new H4(Y,Z,$)}return await this.cache.put(this.cacheConfig.tag??await YX(Y,Z),_,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),_}return G}try{return await X()}catch(G){throw new H4(Y,Z,G)}}}class XX{constructor(Y){this.dialect=Y}static[E]="PgSession";execute(Y,Z){return E0.startActiveSpan("drizzle.operation",()=>{return E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(Y),void 0,void 0,!1)}).setToken(Z).execute(void 0,Z)})}all(Y){return this.prepareQuery(this.dialect.sqlToQuery(Y),void 0,void 0,!1).all()}async count(Y,Z){let X=await this.execute(Y,Z);return Number(X[0].count)}}class GX extends h8{constructor(Y,Z,X,G=0){super(Y,Z,X);this.schema=X,this.nestedIndex=G}static[E]="PgTransaction";rollback(){throw new w5}getTransactionConfigSQL(Y){let Z=[];if(Y.isolationLevel)Z.push(`isolation level ${Y.isolationLevel}`);if(Y.accessMode)Z.push(Y.accessMode);if(typeof Y.deferrable==="boolean")Z.push(Y.deferrable?"deferrable":"not deferrable");return V.raw(Z.join(" "))}setTransaction(Y){return this.session.execute(V`set transaction ${this.getTransactionConfigSQL(Y)}`)}}class mW extends ZX{constructor(Y,Z,X,G,_,$,W,H,Q,J){super({sql:Z,params:X},_,$,W);this.client=Y,this.queryString=Z,this.params=X,this.logger=G,this.fields=H,this._isResponseInArrayMode=Q,this.customResultMapper=J}static[E]="PostgresJsPreparedQuery";async execute(Y={}){return E0.startActiveSpan("drizzle.execute",async(Z)=>{let X=A5(this.params,Y);Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X);let{fields:G,queryString:_,client:$,joinsNotNullableMap:W,customResultMapper:H}=this;if(!G&&!H)return E0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(_,X,async()=>{return await $.unsafe(_,X)})});let Q=await E0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":_,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(_,X,async()=>{return await $.unsafe(_,X).values()})});return E0.startActiveSpan("drizzle.mapResponse",()=>{return H?H(Q):Q.map((J)=>m7(G,J,W))})})}all(Y={}){return E0.startActiveSpan("drizzle.execute",async(Z)=>{let X=A5(this.params,Y);return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),E0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(this.queryString,X,async()=>{return this.client.unsafe(this.queryString,X)})})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class b8 extends XX{constructor(Y,Z,X,G={}){super(Z);this.client=Y,this.schema=X,this.options=G,this.logger=G.logger??new I5,this.cache=G.cache??new k8}static[E]="PostgresJsSession";logger;cache;prepareQuery(Y,Z,X,G,_,$,W){return new mW(this.client,Y.sql,Y.params,this.logger,this.cache,$,W,Z,G,_)}query(Y,Z){return this.logger.logQuery(Y,Z),this.client.unsafe(Y,Z).values()}queryObjects(Y,Z){return this.client.unsafe(Y,Z)}transaction(Y,Z){return this.client.begin(async(X)=>{let G=new b8(X,this.dialect,this.schema,this.options),_=new _X(this.dialect,G,this.schema);if(Z)await _.setTransaction(Z);return Y(_)})}}class _X extends GX{constructor(Y,Z,X,G=0){super(Y,Z,X,G);this.session=Z}static[E]="PostgresJsTransaction";transaction(Y){return this.session.client.savepoint((Z)=>{let X=new b8(Z,this.dialect,this.schema,this.session.options),G=new _X(this.dialect,X,this.schema);return Y(G)})}}class uW extends h8{static[E]="PostgresJsDatabase"}function K2(Y,Z={}){let X=(Q)=>Q;for(let Q of["1184","1082","1083","1114","1182","1185","1115","1231"])Y.options.parsers[Q]=X,Y.options.serializers[Q]=X;Y.options.serializers["114"]=X,Y.options.serializers["3802"]=X;let G=new c4({casing:Z.casing}),_;if(Z.logger===!0)_=new N5;else if(Z.logger!==!1)_=Z.logger;let $;if(Z.schema){let Q=EW(Z.schema,OW);$={fullSchema:Z.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let W=new b8(Y,G,$,{logger:_,cache:Z.cache}),H=new uW(G,W,$);if(H.$client=Y,H.$cache=Z.cache,H.$cache)H.$cache.invalidate=Z.cache?.onMutate;return H}function JY(...Y){if(typeof Y[0]==="string"){let Z=N2(Y[0]);return K2(Z,Y[1])}if(c7(Y[0])){let{connection:Z,client:X,...G}=Y[0];if(X)return K2(X,G);if(typeof Z==="object"&&Z.url!==void 0){let{url:$,...W}=Z,H=N2($,W);return K2(H,G)}let _=N2(Z);return K2(_,G)}return K2(Y[0],Y[1])}((Y)=>{function Z(X){return K2({options:{parsers:{},serializers:{}}},X)}Y.mock=Z})(JY||(JY={}));var WX={};iH(WX,{users:()=>l4,untrackedUserColumnNames:()=>hE,twoFactorMethod:()=>iW,trackedUserColumnName:()=>kE,trackableUserColumnNames:()=>lW,signInHistory:()=>yE,role:()=>cW,players:()=>$X,passwordResetAttempts:()=>gE,games:()=>zY,banishedIps:()=>pE,accountActions:()=>bE,accountAction:()=>oW});function T4(){return t0({length:24}).$type()}function dW(Y){return V`lower(${Y})`}var QY=V`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,cW=D8("role",["admin","user"]),l4=I4("users",{id:C1().primaryKey().defaultRandom(),username:t0({length:16}).notNull(),emailOffered:t0({length:254}).notNull(),emailVerified:t0({length:254}),password:t0({length:254}),createdAtIso:T4().notNull().default(QY),createdIp:t0({length:45}).notNull(),isActive:N8().notNull().default(!1),verifiedAtIso:T4(),userRole:cW().default("user")},(Y)=>[l5("usernameUniqueIndex").on(dW(Y.username)),l5("emailVerifiedUniqueIndex").on(dW(Y.emailVerified))]),hE=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],lW=["username","emailOffered","emailVerified","password","userRole"],kE=D8("trackedUserColumnName",lW),oW=D8("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),bE=I4("accountActions",{userId:C1().references(()=>l4.id).primaryKey(),action:oW().notNull(),code:t0({length:254}).notNull(),wrongCodeCount:I8().notNull().default(0),expiresAtIso:T4().notNull()}),zY=I4("games",{id:C1().primaryKey().defaultRandom()}),$X=I4("players",{userId:C1().notNull().references(()=>l4.id,{onDelete:"cascade"}),gameId:C1().notNull().references(()=>zY.id,{onDelete:"cascade"}),score:I8().notNull()},(Y)=>[m3({name:"players_userId_gameId_pk",columns:[Y.userId,Y.gameId]})]),yE=I4("signInHistory",{id:C1().primaryKey().defaultRandom(),userId:C1().references(()=>l4.id,{onDelete:"cascade"}),signInTimeIso:T4().notNull().default(QY),ipAddress:t0({length:45}).notNull(),userAgent:t0({length:1024}),successful:N8().notNull().default(!1)}),iW=D8("twoFactorMethod",["email","phone"]),gE=I4("passwordResetAttempts",{id:C1().primaryKey().defaultRandom(),userId:C1().notNull().references(()=>l4.id,{onDelete:"cascade"}),requestedIp:t0({length:45}).notNull(),requestedAtIso:T4().notNull().default(QY),succeededIp:t0({length:45}),succeededAtIso:T4(),verificationMethod:iW().notNull()}),pE=I4("banishedIps",{ip:t0({length:45}).primaryKey(),reason:t0({length:2048}).notNull(),banishedAtIso:T4().notNull().default(QY),banishedUntilIso:T4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class HX{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(mE.resolve(__dirname,"notify_update.sql"));let Y=[d0(l4),d0(zY),d0($X)];await this.sql`SELECT create_notify_triggers(${this.sql.array(Y)})`,await this.sql.listen("table_update",(Z)=>{let X=Z.split(","),G=X[0],_=X[1],$=`${G}("${_}")`;if(this.observers.has($))this.observers.get($).next($)})}constructor(Y=!1,Z={host:g1.POSTGRES_HOST,port:g1.POSTGRES_PORT,user:g1.POSTGRES_USER,password:g1.POSTGRES_PASSWORD,database:g1.POSTGRES_DATABASE}){this.options=Z,this.sql=N2(Z),this.drizzle=JY(this.sql,{schema:WX,logger:Y})}observe(Y,Z){if(!this.observers.has(Y))this.observers.set(Y,new _0);this.observers.get(Y).subscribe("SINGLETON",Z)}}var UY={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 uE(Y){return Number.parseInt(Y,10)}var dE=U1(UY),cE=dE.keyof().pipe((Y)=>uE(Y)),nW=U1([cE,"string"]);var QX=new L7(process),{logger:D1}=QX;Object.assign(console,D1,{log:D1.info});D1.info("ready");var JX=sW(import.meta.dir,"..","app"),Of=new HX({logQuery(Y,Z){D1.info("\uD83D\uDCDD query",Y,Z)}});nE({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...q6??void 0,async fetch(Y){try{let Z=new Date,X=new URL(Y.url);if(D1.info(Y.method,X.pathname),X.pathname==="/")return new Response(Bun.file(sW(JX,"index.html")));if(X.pathname==="/index.html")return Response.redirect("/");let G=oE(JX,X.pathname),_=iE(G);if(!_.startsWith(JX))throw[403,"Access Denied"];if(!await rW(_).exists())return Response.redirect("/");return new Response(rW(_))}catch(Z){let X=nW(Z);if(X instanceof U1.errors===!1){let[G,_]=X,W=`${UY[G]}. ${_}`;return D1.info(`\u274C ${G}: ${W}`),new Response(W,{status:G})}if(Z instanceof Error)D1.error(Z.message);else{let G=C6(Z);D1.error("frontend server threw",G)}return new Response(UY[500],{status:500})}}});function FY(){D1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{D1.info("\u2757 received SIGINT; exiting gracefully"),FY()});process.on("SIGTERM",()=>{D1.info("\u2757 received SIGTERM; exiting gracefully"),FY()});process.on("exit",()=>{D1.info("\u2757 received exit; exiting gracefully"),FY()});QX.on("timeToStop",()=>{D1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),FY()});var{version:rE}=await Bun.file(lE.resolve(import.meta.dir,"../package.json")).json();D1.info(`\uD83D\uDEEB frontend v${rE} running at http://localhost:${g1.FRONTEND_PORT}/`);QX.emit("alive");
|
|
93
|
+
`;await Y.execute(V`CREATE SCHEMA IF NOT EXISTS ${V.identifier(G)}`),await Y.execute(W);let H=(await Y.all(V`select id, hash, created_at from ${V.identifier(G)}.${V.identifier(_)} order by created_at desc limit 1`))[0];await Y.transaction(async(Q)=>{for await(let J of X)if(!H||Number(H.created_at)<J.folderMillis){for(let z of J.sql)await Q.execute(V.raw(z));await Q.execute(V`insert into ${V.identifier(G)}.${V.identifier(_)} ("hash", "created_at") values(${J.hash}, ${J.folderMillis})`)}})}escapeName(X){return`"${X}"`}escapeParam(X){return`$${X+1}`}escapeString(X){return`'${X.replace(/'/g,"''")}'`}buildWithCTE(X){if(!X?.length)return;let Y=[V`with `];for(let[Z,_]of X.entries())if(Y.push(V`${V.identifier(_._.alias)} as (${_._.sql})`),Z<X.length-1)Y.push(V`, `);return Y.push(V` `),V.join(Y)}buildDeleteQuery({table:X,where:Y,returning:Z,withList:_}){let G=this.buildWithCTE(_),W=Z?V` returning ${this.buildSelection(Z,{isSingleTable:!0})}`:void 0,$=Y?V` where ${Y}`:void 0;return V`${G}delete from ${X}${$}${W}`}buildUpdateSet(X,Y){let Z=X[T.Symbol.Columns],_=Object.keys(Z).filter((W)=>Y[W]!==void 0||Z[W]?.onUpdateFn!==void 0),G=_.length;return V.join(_.flatMap((W,$)=>{let H=Z[W],Q=Y[W]??V.param(H.onUpdateFn(),H),J=V`${V.identifier(this.casing.getColumnCasing(H))} = ${Q}`;if($<G-1)return[J,V.raw(", ")];return[J]}))}buildUpdateQuery({table:X,set:Y,where:Z,returning:_,withList:G,from:W,joins:$}){let H=this.buildWithCTE(G),Q=X[b0.Symbol.Name],J=X[b0.Symbol.Schema],z=X[b0.Symbol.OriginalName],F=Q===z?void 0:Q,O=V`${J?V`${V.identifier(J)}.`:void 0}${V.identifier(z)}${F&&V` ${V.identifier(F)}`}`,D=this.buildUpdateSet(X,Y),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");
|