tempest.games 0.2.17 → 0.2.19
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-DikmBhXT.js +109 -0
- package/app/index.html +1 -1
- package/bin/backend.bun.js +234 -234
- package/bin/backend.worker.game.bun.js +14 -3
- package/bin/backend.worker.tribunal.bun.js +123 -110
- package/bin/frontend.bun.js +61 -50
- package/bin/setup-db.bun.js +55 -55
- package/package.json +20 -20
- package/app/assets/index-DV2ldfnq.js +0 -109
package/bin/frontend.bun.js
CHANGED
|
@@ -1,65 +1,76 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
Message: ${
|
|
5
|
-
Source: (${
|
|
6
|
-
${
|
|
7
|
-
}`)}}};class
|
|
8
|
-
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},
|
|
9
|
-
`+
|
|
10
|
-
${
|
|
11
|
-
${
|
|
12
|
-
${
|
|
3
|
+
var NJ=Object.create;var{getPrototypeOf:RJ,defineProperty:HZ,getOwnPropertyNames:IJ}=Object;var BJ=Object.prototype.hasOwnProperty;var fO=(Y,Z,X)=>{X=Y!=null?NJ(RJ(Y)):{};let _=Z||!Y||!Y.__esModule?HZ(X,"default",{value:Y,enumerable:!0}):X;for(let G of IJ(Y))if(!BJ.call(_,G))HZ(_,G,{get:()=>Y[G],enumerable:!0});return _};var bO=(Y,Z)=>()=>(Z||Y((Z={exports:{}}).exports,Z),Z.exports);var TJ=(Y,Z)=>{for(var X in Z)HZ(Y,X,{get:Z[X],enumerable:!0,configurable:!0,set:(_)=>Z[X]=()=>_})};var kO=(Y,Z)=>()=>(Y&&(Z=Y(Y=0)),Z);var gO=import.meta.require;import PO,{join as SO,normalize as vO,resolve as qH}from"path";var U4=(Y)=>Array.isArray(Y)?Y:[Y],Q_=(Y,Z)=>{let X=[[],[]];for(let _ of Y)if(Z(_))X[0].push(_);else X[1].push(_);return X},k6=Array,a1=(Y,Z)=>Y.includes(Z),z_=(Y,Z=0)=>[...new Array(Y)].map((X,_)=>_+Z),Z0=(Y,Z,X)=>{if(Y===void 0)return Z===void 0?[]:Array.isArray(Z)?Z:[Z];if(X?.prepend)if(Array.isArray(Z))Y.unshift(...Z);else Y.unshift(Z);else if(Array.isArray(Z))Y.push(...Z);else Y.push(Z);return Y},t1=(Y,Z)=>{if(Z===void 0||Z===null)return Y??[];if(Y===void 0||Y===null)return U4(Z);return Y.concat(Z)},F_=(...Y)=>Y.reduce(t1,[]),d1=(Y,Z,X)=>{if(Y===void 0)return Array.isArray(Z)?Z:[Z];let _=X?.isEqual??((G,W)=>G===W);for(let G of U4(Z))if(!Y.some((W)=>_(W,G)))Y.push(G);return Y},U_=(Y,Z)=>Y.reduce((X,_)=>{let G=_[Z];return X[G]=Z0(X[G],_),X},{}),e1=(Y,Z,X)=>Y.length===Z.length&&Y.every(X?.isEqual?(_,G)=>X.isEqual(_,Z[G]):(_,G)=>_===Z[G]);var $1=(Y,Z)=>g0(Y)===Z,g0=(Y)=>{let Z=typeof Y;return Z==="object"?Y===null?"null":"object":Z==="function"?"object":Z},Q1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},O_={...Q1,function:"a function"};class E_ extends Error{}var _0=(Y)=>q4(Y,E_),q4=(Y,Z=Error)=>{throw new Z(Y)};class j8 extends Error{name="ParseError"}var w=(Y)=>q4(Y,j8),x1=(Y)=>` ${Y}`;var o=(Y,Z)=>{let X={},_=Array.isArray(Y),G=!1;for(let[W,H]of Object.entries(Y).entries()){let J=_?Z(W,H[1]):Z(...H,W);G||=typeof J[0]==="number";let Q=Array.isArray(J[0])||J.length===0?J:[J];for(let[$,z]of Q)if(typeof $==="object")X[$.group]=Z0(X[$.group],z);else X[$]=z}return G?Object.values(X):X};var JZ=Object.entries;var y0=(Y,Z)=>(Y in Z),n4=(Y,Z)=>(Z in Y);class $Z{constructor(Y){Object.assign(this,Y)}}var L_=class{};class P8 extends L_{}var CJ=(Y,Z)=>{let X={},_={},G;for(G in Y)if(G in Z)X[G]=Y[G];else _[G]=Y[G];return[X,_]};var D_=(Y,Z)=>CJ(Y,Z)[1],c1=(Y)=>Object.keys(Y).length===0,j4=(Y)=>[...Object.entries(Y),...Object.getOwnPropertySymbols(Y).map((Z)=>[Z,Y[Z]])],V_=(Y,Z)=>Object.defineProperties(Y,Object.getOwnPropertyDescriptors(Z)),M_=(Y)=>{let Z=Object.keys(Y).sort(),X={};for(let _=0;_<Z.length;_++)X[Z[_]]=Y[Z[_]];return X};var A1=x1("represents an uninitialized value"),A_=(Y)=>Object.values(Y).filter((Z)=>{if(typeof Z==="number")return!0;return typeof Y[Z]!=="number"});var QZ={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},zZ=globalThis.File??Blob,FZ={ArrayBuffer,Blob,File:zZ,FormData,Headers,Request,Response,URL},KJ={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},P4={...QZ,...FZ,...KJ,String,Number,Boolean},S8=(Y)=>{let Z=Object.getPrototypeOf(Y);while(Z?.constructor&&(!y0(Z.constructor.name,P4)||!(Y instanceof P4[Z.constructor.name])))Z=Object.getPrototypeOf(Z);let X=Z?.constructor?.name;if(X===void 0||X==="Object")return;return X},v8=(Y)=>typeof Y==="object"&&Y!==null?S8(Y)??"object":g0(Y);var O0=Array.isArray,qJ={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"},jJ={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"},PJ={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"},w_={...qJ,...jJ,...PJ},x8=(Y)=>{let Z=Object(Y).name??null;return Z&&y0(Z,P4)&&P4[Z]===Y?Z:null};var UZ=(Y,Z)=>{let X=Y.prototype;while(X!==null){if(X===Z.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var N_=(Y)=>R_(Y,new Map),R_=(Y,Z)=>{if(typeof Y!=="object"||Y===null)return Y;if(Z?.has(Y))return Z.get(Y);let X=x8(Y.constructor);if(X==="Date")return new Date(Y.getTime());if(X&&X!=="Array")return Y;let _=Array.isArray(Y)?Y.slice():Object.create(Object.getPrototypeOf(Y)),G=Object.getOwnPropertyDescriptors(Y);if(Z){Z.set(Y,_);for(let W in G){let H=G[W];if("get"in H||"set"in H)continue;H.value=R_(H.value,Z)}}return Object.defineProperties(_,G),_};var SJ=(Y)=>{let Z=A1;return()=>Z===A1?Z=Y():Z},O4=(Y)=>typeof Y==="function"&&Y.length===0;var I_=class extends Function{constructor(...Y){let Z=Y.slice(0,-1),X=Y.at(-1);try{super(...Z,X)}catch(_){return _0(`Encountered an unexpected error while compiling your definition:
|
|
4
|
+
Message: ${_}
|
|
5
|
+
Source: (${Y.slice(0,-1)}) => {
|
|
6
|
+
${Y.at(-1)}
|
|
7
|
+
}`)}}};class h1{constructor(Y,...[Z]){return Object.assign(Object.setPrototypeOf(Y.bind(Z?.bind??this),this.constructor.prototype),Z?.attach)}}var B_=SJ(()=>{try{return new Function("return false")()}catch{return!0}});var WE=x1("brand");var T_=x1("arkInferred");var $E=x1("args");class a0{constructor(){}}var vJ=()=>{try{return((new Error().stack?.split(`
|
|
8
|
+
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},xJ=globalThis.process?.env??{},C_={fileName:vJ,env:xJ};var K_=(Y)=>Y[0].toUpperCase()+Y.slice(1);var OZ=(Y)=>new RegExp(hJ(Y),typeof Y==="string"?"":Y.flags);var hJ=(Y)=>{return`^(?:${typeof Y==="string"?Y:Y.source})$`};var Y4={negativeLookahead:(Y)=>`(?!${Y})`,nonCapturingGroup:(Y)=>`(?:${Y})`},h8="\\",E4={" ":1,"\n":1,"\t":1};var fJ=/^-0\.?0*$/.source,j_=/[1-9]\d*/.source,bJ=/\.\d+/.source,kJ=/\.\d*[1-9]/.source,P_=(Y)=>OZ(Y4.negativeLookahead(fJ)+Y4.nonCapturingGroup("-?"+Y4.nonCapturingGroup(Y4.nonCapturingGroup("0|"+j_)+Y4.nonCapturingGroup(Y.decimalPattern)+"?")+(Y.allowDecimalOnly?"|"+Y.decimalPattern:"")+"?")),q_=P_({decimalPattern:kJ,allowDecimalOnly:!1}),gJ=q_.test.bind(q_),g6=P_({decimalPattern:bJ,allowDecimalOnly:!0}),LE=g6.test.bind(g6),yJ=/^-?\d*\.?\d*$/,pJ=(Y)=>Y.length!==0&&yJ.test(Y),f8=OZ(Y4.negativeLookahead("^-0$")+"-?"+Y4.nonCapturingGroup(Y4.nonCapturingGroup("0|"+j_))),mJ=f8.test.bind(f8),EZ=/^-?\d+$/,uJ=EZ.test.bind(EZ),S_={number:"a number",bigint:"a bigint",integer:"an integer"},v_=(Y,Z)=>`'${Y}' was parsed as ${S_[Z]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,dJ=(Y,Z)=>Z==="number"?gJ(Y):mJ(Y),cJ=(Y,Z)=>Z==="number"?Number(Y):Number.parseInt(Y),lJ=(Y,Z)=>Z==="number"?pJ(Y):uJ(Y),x_=(Y,Z)=>LZ(Y,"number",Z),h_=(Y,Z)=>LZ(Y,"number",{...Z,strict:!0}),f_=(Y,Z)=>LZ(Y,"integer",Z),LZ=(Y,Z,X)=>{let _=cJ(Y,Z);if(!Number.isNaN(_)){if(lJ(Y,Z)){if(X?.strict)return dJ(Y,Z)?_:w(v_(Y,Z));return _}}return X?.errorOnFail?w(X?.errorOnFail===!0?`Failed to parse ${S_[Z]} from '${Y}'`:X?.errorOnFail):void 0},b_=(Y)=>{if(Y[Y.length-1]!=="n")return;let Z=Y.slice(0,-1),X;try{X=BigInt(Z)}catch{return}if(f8.test(Z))return X;if(EZ.test(Z))return w(v_(Y,"bigint"))};var iJ="0.46.0",oJ={version:iJ,filename:C_.fileName(),FileConstructor:zZ},S4=oJ,k_=new Map,DZ=Object.create(null),b8=(Y)=>{let Z=k_.get(Y);if(Z)return Z;let X=nJ(Y);if(DZ[X])X=`${X}${DZ[X]++}`;else DZ[X]=1;return S4[X]=Y,k_.set(Y,X),X},L4=(Y)=>/^[$A-Z_a-z][\w$]*$/.test(Y),nJ=(Y)=>{switch(typeof Y){case"object":{if(Y===null)break;let Z=S8(Y)??"object";return Z[0].toLowerCase()+Z.slice(1)}case"function":return L4(Y.name)?Y.name:"fn";case"symbol":return Y.description&&L4(Y.description)?Y.description:"symbol"}return _0(`Unexpected attempt to register serializable value of type ${g0(Y)}`)};var k8=(Y)=>typeof Y==="string"?JSON.stringify(Y):typeof Y==="bigint"?`${Y}n`:`${Y}`;var g_=(Y,Z={})=>g8(Y,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...Z},[]);var n=(Y,Z)=>{switch(g0(Y)){case"object":let X=Y,_=X.constructor.name;return _==="Object"||_==="Array"?Z?.quoteKeys===!1?y6(X,Z?.indent??0,""):JSON.stringify(g8(X,r4,[]),null,Z?.indent):y6(X,Z?.indent??0,"");case"symbol":return r4.onSymbol(Y);default:return k8(Y)}},y6=(Y,Z,X)=>{if(typeof Y==="function")return r4.onFunction(Y);if(typeof Y!=="object"||Y===null)return k8(Y);let _=X+" ".repeat(Z);if(Array.isArray(Y)){if(Y.length===0)return"[]";let W=Y.map((H)=>y6(H,Z,_)).join(`,
|
|
9
|
+
`+_);return Z?`[
|
|
10
|
+
${_}${W}
|
|
11
|
+
${X}]`:`[${W}]`}let G=Y.constructor.name;if(G==="Object"){let W=j4(Y).map(([H,J])=>{let Q=typeof H==="symbol"?r4.onSymbol(H):L4(H)?H:JSON.stringify(H),$=y6(J,Z,_);return`${_}${Q}: ${$}`});if(W.length===0)return"{}";return Z?`{
|
|
12
|
+
${W.join(`,
|
|
13
13
|
`)}
|
|
14
|
-
${
|
|
15
|
-
`,this}const(
|
|
16
|
-
`).map((
|
|
17
|
-
`):this.body} }`}compile(){return new
|
|
18
|
-
`)}_add(
|
|
19
|
-
`+
|
|
20
|
-
`));Object.defineProperty(this,"arkErrors",{value:
|
|
14
|
+
${X}}`:`{${W.join(", ")}}`}if(Y instanceof Date)return v4(Y);if("expression"in Y&&typeof Y.expression==="string")return Y.expression;return G},r4={onCycle:()=>"(cycle)",onSymbol:(Y)=>`Symbol(${b8(Y)})`,onFunction:(Y)=>`Function(${b8(Y)})`},g8=(Y,Z,X)=>{switch(g0(Y)){case"object":{let _=Y;if("toJSON"in _&&typeof _.toJSON==="function")return _.toJSON();if(typeof _==="function")return r4.onFunction(_);if(X.includes(_))return"(cycle)";let G=[...X,_];if(Array.isArray(_))return _.map((H)=>g8(H,Z,G));if(_ instanceof Date)return _.toDateString();let W={};for(let H in _)W[H]=g8(_[H],Z,G);for(let H of Object.getOwnPropertySymbols(_))W[Z.onSymbol?.(H)??H.toString()]=g8(_[H],Z,G);return W}case"symbol":return r4.onSymbol(Y);case"bigint":return Z.onBigInt?.(Y)??`${Y}n`;case"undefined":return Z.onUndefined??"undefined";case"string":return Y.replaceAll("\\","\\\\");default:return Y}},v4=(Y)=>{let Z=Y.getFullYear(),X=Y.getMonth(),_=Y.getDate(),G=Y.getHours(),W=Y.getMinutes(),H=Y.getSeconds(),J=Y.getMilliseconds();if(X===0&&_===1&&G===0&&W===0&&H===0&&J===0)return`${Z}`;let Q=`${rJ[X]} ${_}, ${Z}`;if(G===0&&W===0&&H===0&&J===0)return Q;let $=Y.toLocaleTimeString(),z=$.endsWith(" AM")||$.endsWith(" PM")?$.slice(-3):"";if(z)$=$.slice(0,-z.length);if(J)$+=`.${aJ(J,3)}`;else if(sJ.test($))$=$.slice(0,-3);return`${$+z}, ${Q}`},rJ=["January","February","March","April","May","June","July","August","September","October","November","December"],sJ=/:\d\d:00$/,aJ=(Y,Z)=>String(Y).padStart(Z,"0");var y_=(Y,Z,...[X])=>{let _=X?.stringifySymbol??n,G=Y;switch(typeof Z){case"string":G=L4(Z)?Y===""?Z:`${Y}.${Z}`:`${Y}[${JSON.stringify(Z)}]`;break;case"number":G=`${Y}[${Z}]`;break;case"symbol":G=`${Y}[${_(Z)}]`;break;default:if(X?.stringifyNonKey)G=`${Y}[${X.stringifyNonKey(Z)}]`;else w(`${n(Z)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return G},Z4=(Y,...Z)=>Y.reduce((X,_)=>y_(X,_,...Z),"");class y8 extends k6{cache={};constructor(...Y){super();this.push(...Y)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let Y=0;Y<this.length;Y++)this.cache.json.push(typeof this[Y]==="symbol"?n(this[Y]):this[Y]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=Z4(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Y="",Z=[Y];for(let X of this)Y=y_(Y,X),Z.push(Y);return this.cache.stringifyAncestors=Z}}class VZ{chars;i;def;constructor(Y){this.def=Y,this.chars=[...Y],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(Y){let Z="";while(this.lookahead){if(Y(this,Z))if(Z[Z.length-1]===h8)Z=Z.slice(0,-1);else break;Z+=this.shift()}return Z}shiftUntilLookahead(Y){return typeof Y==="string"?this.shiftUntil((Z)=>Z.lookahead===Y):this.shiftUntil((Z)=>(Z.lookahead in Y))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in E4))}jumpToIndex(Y){this.i=Y<0?this.length+Y:Y}jumpForward(Y){this.i+=Y}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(Y,Z){return this.chars.slice(Y,Z).join("")}lookaheadIs(Y){return this.lookahead===Y}lookaheadIsIn(Y){return this.lookahead in Y}}var pE=x1("implementedTraits");var MZ="$ark",tJ=2;while(MZ in globalThis)MZ=`$ark${tJ++}`;var p_=MZ;globalThis[p_]=S4;var B=S4,eJ=(Y)=>`${p_}.${Y}`,K0=(Y)=>eJ(b8(Y));class p6 extends P8{argNames;body="";constructor(...Y){super();this.argNames=Y;for(let Z of Y){if(Z in this)throw new Error(`Arg name '${Z}' would overwrite an existing property on FunctionBody`);this[Z]=Z}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(Y,Z=!1){return AZ(Y,Z)}index(Y,Z=!1){return m_(`${Y}`,Z)}line(Y){return this.body+=`${" ".repeat(this.indentation)}${Y}
|
|
15
|
+
`,this}const(Y,Z){return this.line(`const ${Y} = ${Z}`),this}let(Y,Z){return this.line(`let ${Y} = ${Z}`)}set(Y,Z){return this.line(`${Y} = ${Z}`)}if(Y,Z){return this.block(`if (${Y})`,Z)}elseIf(Y,Z){return this.block(`else if (${Y})`,Z)}else(Y){return this.block("else",Y)}for(Y,Z,X=0){return this.block(`for (let i = ${X}; ${Y}; i++)`,Z)}forIn(Y,Z){return this.block(`for (const k in ${Y})`,Z)}block(Y,Z,X=""){return this.line(`${Y} {`),this.indent(),Z(this),this.dedent(),this.line(`}${X}`)}return(Y=""){return this.line(`return ${Y}`)}write(Y="anonymous",Z=0){return`${Y}(${this.argNames.join(", ")}) { ${Z?this.body.split(`
|
|
16
|
+
`).map((X)=>" ".repeat(Z)+`${X}`).join(`
|
|
17
|
+
`):this.body} }`}compile(){return new I_(...this.argNames,this.body)}}var X4=(Y)=>$1(Y,"object")||typeof Y==="symbol"?K0(Y):k8(Y),AZ=(Y,Z=!1)=>{if(typeof Y==="string"&&L4(Y))return`${Z?"?":""}.${Y}`;return m_(Y$(Y),Z)},Y$=(Y)=>typeof Y==="symbol"?K0(Y):JSON.stringify(Y),m_=(Y,Z=!1)=>`${Z?"?.":""}[${Y}]`;class p8 extends p6{traversalKind;optimistic;constructor(Y){super("data","ctx");this.traversalKind=Y.kind,this.optimistic=Y.optimistic===!0}invoke(Y,Z){let X=Z?.arg??this.data,_=typeof Y==="string"?!0:this.requiresContextFor(Y),G=typeof Y==="string"?Y:Y.id;if(_)return`${this.referenceToId(G,Z)}(${X}, ${this.ctx})`;return`${this.referenceToId(G,Z)}(${X})`}referenceToId(Y,Z){let X=Z?.kind??this.traversalKind,_=`this.${Y}${X}`;return Z?.bind?`${_}.bind(${Z?.bind})`:_}requiresContextFor(Y){return this.traversalKind==="Apply"||Y.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(Y,Z,X){let _=this.requiresContextFor(X);if(_)this.line(`${this.ctx}.path.push(${Y})`);if(this.check(X,{arg:Z}),_)this.line(`${this.ctx}.path.pop()`);return this}check(Y,Z){return this.traversalKind==="Allows"?this.if(`!${this.invoke(Y,Z)}`,()=>this.return(!1)):this.line(this.invoke(Y,Z))}}var m6=(Y)=>o(Y,(Z,X)=>[Z,O0(X)?[...X]:X]),X1=x1("arkKind"),y=(Y,Z)=>Y?.[X1]===Z,V0=(Y)=>y(Y,"root")||y(Y,"constraint");var u_=["unit","proto","domain"],s4=["required","optional","index","sequence"],wZ=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],u6=[...wZ,...s4,"structure","predicate"],a4=["alias","union","morph","unit","intersection","proto","domain"],Z$=[...a4,...u6],d6=o(u6,(Y,Z)=>[Z,1]),d_=o([...s4,"undeclared"],(Y,Z)=>[Z,1]),c_=o(Z$,(Y,Z)=>[Z,Y]),t4=(Y)=>typeof Y==="string"&&(Y in c_);var e4=(Y)=>c_[Y],c6=(Y)=>a4.slice(e4(Y)+1),IL=[...c6("union"),"alias"],BL=[...c6("morph"),"alias"],B1=(Y)=>{if(typeof Y==="string"||typeof Y==="boolean"||Y===null)return Y;if(typeof Y==="number"){if(Number.isNaN(Y))return"NaN";if(Y===Number.POSITIVE_INFINITY)return"Infinity";if(Y===Number.NEGATIVE_INFINITY)return"-Infinity";return Y}return X4(Y)},D4=(Y)=>{let Z="{ ";for(let[X,_]of Object.entries(Y))Z+=`${X}: ${X4(_)}, `;return Z+" }"},r=(Y)=>{let Z=Y;if(Z.hasAssociatedError)Z.defaults.expected??=(X)=>("description"in X)?X.description:Z.defaults.description(X),Z.defaults.actual??=(X)=>n(X),Z.defaults.problem??=(X)=>`must be ${X.expected}${X.actual?` (was ${X.actual})`:""}`,Z.defaults.message??=(X)=>{if(X.path.length===0)return X.problem;let _=`${X.propString} ${X.problem}`;if(_[0]==="[")return`value at ${_}`;return _};return Z};class l_ extends Error{name="ToJsonSchemaError";code;context;constructor(Y,Z){super(n(Z,{quoteKeys:!1,indent:4}));this.code=Y,this.context=Z}hasCode(Y){return this.code===Y}}var X$={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Y)=>R0.throw("arrayObject",Y),arrayPostfix:(Y)=>R0.throw("arrayPostfix",Y),defaultValue:(Y)=>R0.throw("defaultValue",Y),domain:(Y)=>R0.throw("domain",Y),morph:(Y)=>R0.throw("morph",Y),patternIntersection:(Y)=>R0.throw("patternIntersection",Y),predicate:(Y)=>R0.throw("predicate",Y),proto:(Y)=>R0.throw("proto",Y),symbolKey:(Y)=>R0.throw("symbolKey",Y),unit:(Y)=>R0.throw("unit",Y),date:(Y)=>R0.throw("date",Y)}},R0={Error:l_,throw:(...Y)=>{throw new R0.Error(...Y)},throwInternalOperandError:(Y,Z)=>_0(`Unexpected JSON Schema input for ${Y}: ${n(Z)}`),defaultConfig:X$};B.config??={};var m8=(Y,Z)=>{if(!Z)return Y;let X={...Y},_;for(_ in Z){let G={...Y.keywords};if(_==="keywords"){for(let W in Z[_]){let H=Z.keywords[W];if(H===void 0)continue;G[W]=typeof H==="string"?{description:H}:H}X.keywords=G}else if(_==="toJsonSchema")X[_]=NZ(Y.toJsonSchema,Z.toJsonSchema);else if(t4(_))X[_]={...Y[_],...Z[_]};else X[_]=Z[_]}return X},NZ=(Y,Z)=>{if(!Y)return Z??{};if(!Z)return Y;let X={...Y},_;for(_ in Z)if(_==="fallback")X.fallback=_$(Y.fallback,Z.fallback);else X[_]=Z[_];return X},_$=(Y,Z)=>{Y=i_(Y),Z=i_(Z);let X={},_;for(_ in R0.defaultConfig.fallback)X[_]=Z[_]??Z.default??Y[_]??Y.default??R0.defaultConfig.fallback[_];return X},i_=(Y)=>typeof Y==="function"?{default:Y}:Y??{};class V4 extends P8{[X1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Y,relativePath:Z,...X},_){super();this.input=X,this.ctx=_,V_(this,X);let G=_.data;if(X.code==="union")X.errors=X.errors.flatMap((H)=>{let J=H.hasCode("union")?H.errors:[H];if(!Y&&!Z)return J;return J.map((Q)=>Q.transform(($)=>({...$,path:F_(Y,$.path,Z)})))});this.nodeConfig=_.config[this.code];let W=[...X.path??_.path];if(Z)W.push(...Z);if(Y)W.unshift(...Y);this.path=new y8(...W),this.data="data"in X?X.data:G}transform(Y){return new V4(Y({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(Y){return this.code===Y}get propString(){return Z4(this.path)}get expected(){if(this.input.expected)return this.input.expected;let Y=this.meta?.expected??this.nodeConfig.expected;return typeof Y==="function"?Y(this.input):Y}get actual(){if(this.input.actual)return this.input.actual;let Y=this.meta?.actual??this.nodeConfig.actual;return typeof Y==="function"?Y(this.data):Y}get problem(){if(this.input.problem)return this.input.problem;let Y=this.meta?.problem??this.nodeConfig.problem;return typeof Y==="function"?Y(this):Y}get message(){if(this.input.message)return this.input.message;let Y=this.meta?.message??this.nodeConfig.message;return typeof Y==="function"?Y(this):Y}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class z1 extends k6{[X1]="errors";ctx;constructor(Y){super();this.ctx=Y}byPath=Object.create(null);get flatByPath(){return o(this.byPath,(Y,Z)=>[Y,Z.flat])}get flatProblemsByPath(){return o(this.byPath,(Y,Z)=>[Y,Z.flat.map((X)=>X.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new RZ(this)}add(Y){if(this.includes(Y))return;this._add(Y)}transform(Y){let Z=new z1(this.ctx);for(let X of this)Z.add(Y(X));return Z}merge(Y){for(let Z of Y){if(this.includes(Z))continue;this._add(new V4({...Z,path:[...this.ctx.path,...Z.path]},this.ctx))}}affectsPath(Y){if(this.length===0)return!1;return Y.stringifyAncestors().some((Z)=>(Z in this.byPath))||Y.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((Y)=>Y.toJSON())]}toString(){return this.join(`
|
|
18
|
+
`)}_add(Y){let Z=this.byPath[Y.propString];if(Z){if(Z.hasCode("union")&&Z.errors.length===0)return;let X=Y.hasCode("union")&&Y.errors.length===0?Y:new V4({code:"intersection",errors:Z.hasCode("intersection")?[...Z.errors,Y]:[Z,Y]},this.ctx),_=this.indexOf(Z);this.mutable[_===-1?this.length:_]=X,this.byPath[Y.propString]=X,this.addAncestorPaths(Y)}else this.byPath[Y.propString]=Y,this.addAncestorPaths(Y),this.mutable.push(Y);this.count++}addAncestorPaths(Y){for(let Z of Y.path.stringifyAncestors())this.byAncestorPath[Z]=Z0(this.byAncestorPath[Z],Y)}}class RZ extends Error{name="TraversalError";constructor(Y){if(Y.length===1)super(Y.summary);else super(`
|
|
19
|
+
`+Y.map((Z)=>` \u2022 ${G$(Z)}`).join(`
|
|
20
|
+
`));Object.defineProperty(this,"arkErrors",{value:Y,enumerable:!1})}}var G$=(Y)=>Y.toString().split(`
|
|
21
21
|
`).join(`
|
|
22
|
-
`);class f_{path=[];errors=new F_(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(T,_){this.root=T,this.config=_}get data(){let T=this.root;for(let _ of this.path)T=T?.[_];return T}get propString(){return t_(this.path)}reject(T){return this.error(T),!1}mustBe(T){return this.error(T),!1}error(T){let _=typeof T==="object"?T.code?T:{...T,code:"predicate"}:{code:"predicate",expected:T};return this.errorFromContext(_)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(T){let _={path:new BF(...this.path),morphs:T};if(this.currentBranch)this.currentBranch.queuedMorphs.push(_);else this.queuedMorphs.push(_)}finalize(T){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 T?T(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(T){return this.errorFromContext(T)}errorFromContext(T){let _=new X0(T,this);if(this.currentBranch)this.currentBranch.error=_;else this.errors.add(_);return _}applyQueuedMorphs(){while(this.queuedMorphs.length){let T=this.queuedMorphs;this.queuedMorphs=[];for(let{path:_,morphs:F}of T){if(this.errors.affectsPath(_))continue;this.applyMorphsAtPath(_,F)}}}applyMorphsAtPath(T,_){let F=T.at(-1),W;if(F!==void 0){W=this.root;for(let J=0;J<T.length-1;J++)W=W[T[J]]}this.path=[...T];for(let J of _){let Y=OT(J),$=J(W===void 0?this.root:W[F],this);if($ instanceof X0){this.errors.add($);break}if($ instanceof F_){if(!Y)this.errors.merge($);break}if(W===void 0)this.root=$;else W[F]=$;this.applyQueuedMorphs()}}}var W_=(T,_,F)=>{if(!F)return _();F.path.push(T);let W=_();return F.path.pop(),W};class qF extends k_{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(T,_){super((W,J,Y=this.onFail)=>{if(J)return this.traverseApply(W,J),J.hasError()?J.errors:J.data;return this.rootApply(W,Y)},{attach:T});this.attachments=T,this.$=_,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((W,J)=>qA(W,J.shallowReferences),[this]);let F=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let W=0;W<this.children.length;W++){if(this.includesTransform||=this.children[W].includesTransform,this.includesContextualPredicate||=this.children[W].includesContextualPredicate,this.isCyclic||=this.children[W].isCyclic,!F){let J=this.children[W].flatRefs;for(let Y=0;Y<J.length;Y++){let $=J[Y];if(!this.flatRefs.some((Z)=>SJ(Z,$))){this.flatRefs.push($);for(let Z of $.node.branches)if(Z.hasKind("morph")||Z.hasKind("intersection")&&Z.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:$.path,propString:$.propString,node:Z})}}}Object.assign(this.referencesById,this.children[W].referencesById)}this.flatRefs.sort((W,J)=>W.path.length>J.path.length?1:W.path.length<J.path.length?-1:W.propString>J.propString?1:W.propString<J.propString?-1:W.node.expression<J.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((W)=>W.length===1||W.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((W)=>W.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(W)=>this.traverseAllows(W,new f_(W,this.$.resolvedConfig)):(W)=>this.traverseAllows(W)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(_,F)=>{if(this.allows(_))return _;let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"contextual":return(_,F)=>{let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let T=this.$.resolvedConfig.clone;return(_,F)=>{if(this.allows(_))return this.contextFreeMorph(T&&(typeof _==="object"&&_!==null||typeof _==="function")?T(_):_);let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,e(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=PA(this.metaJson);cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=d0(this.kind);precompilation;assert=(T,_)=>this(T,_,(F)=>F.throw());traverse(T,_){return this(T,_,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(T){if(!this.includesTransform)return this;let _={};for(let[F,W]of this.innerEntries){let J=this.impl.keys[F];if(J.reduceIo)J.reduceIo(T,_,W);else if(J.child){let Y=W;_[F]=XT(Y)?Y.map(($)=>$[T]):Y[T]}else _[F]=W}return this.$.node(this.kind,_)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(T){let _=OT(T)?T:this.$.parseDefinition(T);return this.innerHash===_.innerHash}ifEquals(T){return this.equals(T)?this:void 0}hasKind(T){return this.kind===T}assertHasKind(T){if(this.kind!==T)D0(`${this.kind} node was not of asserted kind ${T}`);return this}hasKindIn(...T){return T.includes(this.kind)}assertHasKindIn(...T){if(!u_(T,this.kind))D0(`${this.kind} node was not one of asserted kinds ${T}`);return this}isBasis(){return u_(EJ,this.kind)}isConstraint(){return u_(PW,this.kind)}isStructural(){return u_(o0,this.kind)}isRefinement(){return u_(A4,this.kind)}isRoot(){return u_(u0,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(T){return this.hasKind("unit")&&this.allows(T)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(T){let _=PF.normalize(T);return this._select(_)}_select(T){let _=PF.applyBoundary[T.boundary??"references"](this);if(T.kind)_=_.filter((F)=>F.kind===T.kind);if(T.where)_=_.filter(T.where);return PF.applyMethod[T.method??"filter"](_,this,T)}transform(T,_){return this._transform(T,this._createTransformContext(_))}_createTransformContext(T){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:T?.prereduced??!1},undeclaredKeyHandling:void 0,...T}}_transform(T,_){let F=_.bindScope??this.$;if(_.seen[this.id])return this.$.lazilyResolve(_.seen[this.id]);if(_.shouldTransform?.(this,_)===!1)return this;let W;if(_.seen[this.id]=()=>W,this.hasKind("structure")&&this.undeclared!==_.undeclaredKeyHandling)_={..._,undeclaredKeyHandling:this.undeclared};let J=c(this.inner,(X,O)=>{if(!this.impl.keys[X].child)return[X,O];let M=O;if(!XT(M)){let V=M._transform(T,_);return V?[X,V]:[]}if(M.length===0)return[X,O];let Q=M.flatMap((V)=>{return V._transform(T,_)??[]});return Q.length?[X,Q]:[]});delete _.seen[this.id];let Y=Object.assign(J,{meta:this.meta}),$=_.selected&&!_.selected.includes(this)?Y:T(this.kind,Y,_);if($===null)return null;if(OT($))return W=$;let Z=Object.keys($);if((Z.length===0||Z.length===1&&Z[0]==="meta")&&!h_(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in $))return _.undeclaredKeyHandling?{...$,value:z.intrinsic.unknown}:null;if(this.kind==="morph")$.in??=z.intrinsic.unknown;return W=F.node(this.kind,$,_.parseOptions)}configureReferences(T,_="references"){let F=PF.normalize(_),W=typeof T==="string"?(Z,G)=>({...G,meta:{...G.meta,description:T}}):typeof T==="function"?(Z,G)=>({...G,meta:T(G.meta)}):(Z,G)=>({...G,meta:{...G.meta,...T}});if(F.boundary==="self")return this.$.node(this.kind,W(this.kind,{...this.inner,meta:this.meta}));let J=this._select(F),Y=J&&W0(J),$=F.boundary==="child"?(Z,G)=>G.root.children.includes(Z):F.boundary==="shallow"?(Z)=>Z.kind!=="structure":()=>!0;return this.$.finalize(this.transform(W,{shouldTransform:$,selected:Y}))}}var PF={applyBoundary:{self:(T)=>[T],child:(T)=>[...T.children],shallow:(T)=>[...T.shallowReferences],references:(T)=>[...T.references]},applyMethod:{filter:(T)=>T,assertFilter:(T,_,F)=>{if(T.length===0)D0(DJ(_,F));return T},find:(T)=>T[0],assertFind:(T,_,F)=>{if(T.length===0)D0(DJ(_,F));return T[0]}},normalize:(T)=>typeof T==="function"?{boundary:"references",method:"filter",where:T}:typeof T==="string"?qT(T,PF.applyBoundary)?{method:"filter",boundary:T}:{boundary:"references",method:"filter",kind:T}:{boundary:"references",method:"filter",...T}},DJ=(T,_)=>`${T} had no references matching ${d(_)}.`,kA=(T)=>t_(T,{stringifyNonKey:(_)=>_.expression}),fA=/"(\$ark\.[^"]+)"/g,PA=(T)=>JSON.stringify(T).replaceAll(fA,"$1"),P_=(T,_)=>({path:T,node:_,propString:kA(T)}),SJ=(T,_)=>T.propString===_.propString&&T.node.equals(_.node),U4=(T,_)=>b_(T,_,{isEqual:SJ}),qA=(T,_)=>b_(T,_,{isEqual:(F,W)=>F.equals(W)});class N extends Array{static init(T,_,F,W){return new N({kind:T,l:_,r:F,path:W?.path??[],optional:W?.optional??!1})}add(T,_,F,W){return this.push({kind:T,l:_,r:F,path:W?.path??[],optional:W?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:T,l:_,r:F}=this[0],W=t_(T);return w4(`Intersection${W&&` at ${W}`} of ${IJ(_,F)}`)}return`The following intersections result in unsatisfiable types:
|
|
23
|
-
\u2022 ${this.map(({path:
|
|
24
|
-
\u2022 `)}`}throw(){return E(this.describeReasons())}invert(){let T=this.map((_)=>({..._,l:_.r,r:_.l}));if(!(T instanceof N))return new N(...T);return T}withPrefixKey(T,_){return this.map((F)=>({...F,path:[T,...F.path],optional:F.optional||_==="optional"}))}toNeverIfDisjoint(){return z.intrinsic.never}}var IJ=(T,_)=>`${M4(T)} and ${M4(_)}`,M4=(T)=>OT(T)?T.expression:XT(T)?T.map(M4).join(" | ")||"never":String(T),w4=(T)=>`${T} results in an unsatisfiable type`;var l0={},J_=(T,_,F)=>UT(T,_,{$:F,invert:!1,pipe:!1}),jF=(T,_,F)=>UT(T,_,{$:F,invert:!1,pipe:!0}),UT=(T,_,F)=>{let W=F.pipe?"|>":"&",J=`${T.hash}${W}${_.hash}`;if(l0[J]!==void 0)return l0[J];if(!F.pipe){let Z=`${_.hash}${W}${T.hash}`;if(l0[Z]!==void 0){let G=l0[Z],X=G instanceof N?G.invert():G;return l0[J]=X,X}}let Y=!F.pipe||!T.includesTransform&&!_.includesTransform;if(Y&&T.equals(_))return T;let $=Y?Q4(T,_,F):T.hasKindIn(...u0)?jA(T,_,F):Q4(T,_,F);if(OT($)){if(T.equals($))$=T;else if(_.equals($))$=_}return l0[J]=$,$},Q4=(T,_,F)=>{let W=T.precedence<_.precedence?T.kind:_.kind,J=T.impl.intersections[_.kind]??_.impl.intersections[T.kind];if(J===void 0)return null;else if(W===T.kind)return J(T,_,F);else{let Y=J(_,T,{...F,invert:!F.invert});if(Y instanceof N)Y=Y.invert();return Y}},jA=(T,_,F)=>T.includesTransform||_.includesTransform?F.invert?NJ(_,T,F):NJ(T,_,F):Q4(T,_,F),NJ=(T,_,F)=>T.distribute((W)=>yA(W,_,F),(W)=>{let J=W.filter(OT);if(J.length===0)return N.init("union",T.branches,_.branches);if(J.length<T.branches.length||!T.branches.every((Z,G)=>Z.in.equals(J[G].in)))return F.$.parseSchema(J);let Y;if(J.length===1){let Z=J[0];if(!Y)return Z;return F.$.node("morph",{...Z.inner,in:Z.in.configure(Y,"self")})}let $={branches:J};if(Y)$.meta=Y;return F.$.parseSchema($)}),yA=(T,_,F)=>{if(T.hasKind("morph")){let J=[...T.morphs];if(T.lastMorphIfNode){let Y=UT(T.lastMorphIfNode,_,F);if(Y instanceof N)return Y;J[J.length-1]=Y}else J.push(_);return F.$.node("morph",{morphs:J,in:T.inner.in})}if(_.hasKind("morph")){let J=UT(T,_.in,F);if(J instanceof N)return J;return F.$.node("morph",{morphs:[_],in:J})}return F.$.node("morph",{morphs:[_],in:T})};class z_ extends qF{constructor(T,_){super(T,_);Object.defineProperty(this,iT,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(T){return J_(this,T,this.$)}}class n_ extends z_{traverseApply=(T,_)=>{if(!this.traverseAllows(T,_))_.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Z0(this.errorContext)}}var cT=(T)=>(_,F)=>{if(XT(_)){if(_.length===0)return;let J=_.map((Y)=>F.$.node(T,Y));if(T==="predicate")return J;return J.sort((Y,$)=>Y.hash<$.hash?-1:1)}let W=F.$.node(T,_);return W.hasOpenIntersection()?[W]:W},t0=(T)=>{let _=T.r.shift();if(!_){let W=T.l.length===0&&T.kind==="structure"?z.intrinsic.unknown.internal:T.ctx.$.node(T.kind,Object.assign(T.baseInner,vA(T.l)),{prereduced:!0});for(let J of T.roots){if(W instanceof N)return W;W=UT(J,W,T.ctx)}return W}let F=!1;for(let W=0;W<T.l.length;W++){let J=UT(T.l[W],_,T.ctx);if(J===null)continue;if(J instanceof N)return J;if(!F){if(J.isRoot())return T.roots.push(J),T.l.splice(W),t0(T);T.l[W]=J,F=!0}else if(!T.l.includes(J))return e(`Unexpectedly encountered multiple distinct intersection results for refinement ${J}`)}if(!F)T.l.push(_);if(T.kind==="intersection"){if(_.impliedSiblings)for(let W of _.impliedSiblings)b_(T.r,W)}return t0(T)},i0=(T)=>{return Object.entries(T).flatMap(([F,W])=>(F in qW)?W:[]).sort((F,W)=>F.precedence<W.precedence?-1:F.precedence>W.precedence?1:F.kind==="predicate"&&W.kind==="predicate"?0:F.hash<W.hash?-1:1)},vA=(T)=>{let _={};for(let F of T)if(F.hasOpenIntersection())_[F.kind]=s(_[F.kind],F);else{if(_[F.kind])return e(`Unexpected intersection of closed refinements of kind ${F.kind}`);_[F.kind]=F}return _},CJ=(...T)=>E(BJ(...T)),BJ=(T,_,F)=>{let W=F.hasKind("morph")?"a morph":F.isUnknown()?"unknown":F.exclude(_).defaultShortDescription;return`${WJ(T)} operand must be ${_.description} (was ${W})`};var kJ=(T,_,F)=>new G0(T,_,F,F,null);class yW extends k_{}class G0 extends k_{[iT]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(T,_,F,W,J){super((...Y)=>{let $=c(this.names,(Z,G)=>{let X=this.arg$.parse(Y[Z]);if(!X.extends(this.constraints[Z]))E(xA(G,this.constraints[Z].expression,X.expression));return[G,X]});if(this.defIsLazy()){let Z=this.bodyDef($);return this.$.parse(Z)}return this.$.parse(_,{args:$})});this.paramDefs=T,this.bodyDef=_,this.$=F,this.arg$=W,this.hkt=J,this.description=J?new J().description??`a generic type for ${J.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof yW}cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get json(){return this.cacheGetter("json",{params:this.params.map((T)=>T[1].isUnknown()?T[0]:[T[0],T[1].json]),body:MJ(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((T)=>typeof T==="string"?[T,z.intrinsic.unknown]:[T[0],this.$.parse(T[1])]))}get names(){return this.cacheGetter("names",this.params.map((T)=>T[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((T)=>T[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var xA=(T,_,F)=>`${T} must be assignable to ${_} (was ${F})`;var bA=l({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(T)=>typeof T==="function"?{predicate:T}:T,defaults:{description:(T)=>`valid according to ${T.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class fJ extends z_{serializedPredicate=VT(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=Z0(this.errorContext);traverseApply=(T,_)=>{if(!this.predicate(T,_.external)&&!_.hasError())_.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows"){T.return(this.compiledCondition);return}T.if(`${this.compiledNegation} && !ctx.hasError()`,()=>T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(T,_){return _.fallback.predicate({code:"predicate",base:T,predicate:this.predicate})}}var R4={implementation:bA,Node:fJ};var hA=l({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(T)=>Number.isInteger(T)?T:E(pA(T))}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>T.rule===1?"an integer":T.rule===2?"even":`a multiple of ${T.rule}`},intersections:{divisor:(T,_,F)=>F.$.node("divisor",{rule:Math.abs(T.rule*_.rule/gA(T.rule,_.rule))})},obviatesBasisDescription:!0});class PJ extends n_{traverseAllows=(T)=>T%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=z.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(T){if(T.type="integer",this.rule===1)return T;return T.multipleOf=this.rule,T}}var E4={implementation:hA,Node:PJ};var pA=(T)=>`divisor must be an integer (was ${T})`,gA=(T,_)=>{let F,W=T,J=_;while(J!==0)F=J,J=W%J,W=F;return W};class U_ extends n_{boundOperandKind=cA[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=dA(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${mA[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?lA(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(T){return(this.limitKind==="upper"?this.numericLimit<T.numericLimit:this.numericLimit>T.numericLimit)||this.numericLimit===T.numericLimit&&this.exclusive===!0&&!T.exclusive}overlapsRange(T){if(this.isStricterThan(T))return!1;if(this.numericLimit===T.numericLimit&&(this.exclusive||T.exclusive))return!1;return!0}overlapIsUnit(T){return this.numericLimit===T.numericLimit&&!this.exclusive&&!T.exclusive}}var mA={"<":">=","<=":">",">":"<=",">=":"<"},oA={min:"max",minLength:"maxLength",after:"before"},vW={parse:(T)=>T||void 0},xW=(T)=>(_)=>{if(typeof _==="number")return{rule:_};let{exclusive:F,...W}=_;return F?{...W,rule:T==="minLength"?W.rule+1:W.rule-1}:W},bW=(T)=>(_)=>{if(typeof _==="number"||typeof _==="string"||_ instanceof Date)return{rule:_};let{exclusive:F,...W}=_;if(!F)return W;let J=typeof W.rule==="number"?W.rule:typeof W.rule==="string"?new Date(W.rule).valueOf():W.rule.valueOf();return F?{...W,rule:T==="after"?J+1:J-1}:W},hW=(T)=>typeof T==="string"||typeof T==="number"?new Date(T):T,uA=(T,_)=>`${T} bound must be a positive integer (was ${_})`,n0=(T)=>(_)=>{if(!Number.isInteger(_)||_<0)E(uA(T,_));return _},cA={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},dA=(T,_)=>`${qT(T,oA)?">":"<"}${_?"":"="}`,lA=(T)=>typeof T==="string"?T:new Date(T).toLocaleString(),qJ=(T)=>`Bounded expression ${T} must be exactly one of number, string, Array, or Date`;var tA=l({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:hW,serialize:(T)=>T.toISOString()}},normalize:bW("after"),defaults:{description:(T)=>`${T.collapsibleLimitString} or later`,actual:C0},intersections:{after:(T,_)=>T.isStricterThan(_)?T:_}});class jJ extends U_{impliedBasis=z.intrinsic.Date.internal;collapsibleLimitString=C0(this.rule);traverseAllows=(T)=>T>=this.rule;reduceJsonSchema(T,_){return _.fallback.date({code:"date",base:T,after:this.rule})}}var z4={implementation:tA,Node:jJ};var iA=l({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:hW,serialize:(T)=>T.toISOString()}},normalize:bW("before"),defaults:{description:(T)=>`${T.collapsibleLimitString} or earlier`,actual:C0},intersections:{before:(T,_)=>T.isStricterThan(_)?T:_,after:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("unit",{unit:T.rule}):null:N.init("range",T,_)}});class yJ extends U_{collapsibleLimitString=C0(this.rule);traverseAllows=(T)=>T<=this.rule;impliedBasis=z.intrinsic.Date.internal;reduceJsonSchema(T,_){return _.fallback.date({code:"date",base:T,before:this.rule})}}var K4={implementation:iA,Node:yJ};var nA=l({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:n0("exactLength")}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>`exactly length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{exactLength:(T,_,F)=>N.init("unit",F.$.node("unit",{unit:T.rule}),F.$.node("unit",{unit:_.rule}),{path:["length"]}),minLength:(T,_)=>T.rule>=_.rule?T:N.init("range",T,_),maxLength:(T,_)=>T.rule<=_.rule?T:N.init("range",T,_)}});class vJ extends n_{traverseAllows=(T)=>T.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=z.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T.maxLength=this.rule,T;case"array":return T.minItems=this.rule,T.maxItems=this.rule,T;default:return RT.throwInternalOperandError("exactLength",T)}}}var V4={implementation:nA,Node:vJ};var rA=l({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:vW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"negative":"non-positive";return`${T.exclusive?"less than":"at most"} ${T.rule}`}},intersections:{max:(T,_)=>T.isStricterThan(_)?T:_,min:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("unit",{unit:T.rule}):null:N.init("range",T,_)},obviatesBasisDescription:!0});class xJ extends U_{impliedBasis=z.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T<this.rule:(T)=>T<=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMaximum=this.rule;else T.maximum=this.rule;return T}}var L4={implementation:rA,Node:xJ};var sA=l({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:n0("maxLength")}},reduce:(T,_)=>T.rule===0?_.node("exactLength",T):void 0,normalize:xW("maxLength"),defaults:{description:(T)=>`at most length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{maxLength:(T,_)=>T.isStricterThan(_)?T:_,minLength:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("exactLength",{rule:T.rule}):null:N.init("range",T,_)}});class bJ extends U_{impliedBasis=z.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length<=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.maxLength=this.rule,T;case"array":return T.maxItems=this.rule,T;default:return RT.throwInternalOperandError("maxLength",T)}}}var D4={implementation:sA,Node:bJ};var aA=l({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:vW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"positive":"non-negative";return`${T.exclusive?"more than":"at least"} ${T.rule}`}},intersections:{min:(T,_)=>T.isStricterThan(_)?T:_},obviatesBasisDescription:!0});class hJ extends U_{impliedBasis=z.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T>this.rule:(T)=>T>=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMinimum=this.rule;else T.minimum=this.rule;return T}}var S4={implementation:aA,Node:hJ};var eA=l({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:n0("minLength")}},reduce:(T)=>T.rule===0?z.intrinsic.unknown:void 0,normalize:xW("minLength"),defaults:{description:(T)=>T.rule===1?"non-empty":`at least length ${T.rule}`,actual:(T)=>T.length===0?"":`${T.length}`},intersections:{minLength:(T,_)=>T.isStricterThan(_)?T:_}});class pJ extends U_{impliedBasis=z.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length>=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T;case"array":return T.minItems=this.rule,T;default:return RT.throwInternalOperandError("minLength",T)}}}var I4={implementation:eA,Node:pJ};var gJ={min:S4.implementation,max:L4.implementation,minLength:I4.implementation,maxLength:D4.implementation,exactLength:V4.implementation,after:z4.implementation,before:K4.implementation},mJ={min:S4.Node,max:L4.Node,minLength:I4.Node,maxLength:D4.Node,exactLength:V4.Node,after:z4.Node,before:K4.Node};var TH=l({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(T)=>typeof T==="string"?{rule:T}:T instanceof RegExp?T.flags?{rule:T.source,flags:T.flags}:{rule:T.source}:T,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(T)=>`matched by ${T.rule}`},intersections:{pattern:()=>null}});class oJ extends n_{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=z.intrinsic.string.internal;reduceJsonSchema(T,_){if(T.pattern)return _.fallback.patternIntersection({code:"patternIntersection",base:T,pattern:this.rule});return T.pattern=this.rule,T}}var N4={implementation:TH,Node:oJ};var yF=(T,_)=>{let F=_H(T);if(_&&!_.includes(F))return E(`Root of kind ${F} should be one of ${_}`);return F},_H=(T)=>{if(P(T,"root"))return T.kind;if(typeof T==="string")return T[0]==="$"?"alias":(T in __)?"domain":"proto";if(typeof T==="function")return"proto";if(typeof T!=="object"||T===null)return E(uJ(T));if("morphs"in T)return"morph";if("branches"in T||XT(T))return"union";if("unit"in T)return"unit";if("reference"in T)return"alias";let _=Object.keys(T);if(_.length===0||_.some((F)=>(F in qW)))return"intersection";if("proto"in T)return"proto";if("domain"in T)return"domain";return E(uJ(T))},uJ=(T)=>`${d(T)} is not a valid type schema`,cJ={},FH=(T)=>XT(T)?T.map((_)=>_.collapsibleJson):T.collapsibleJson,nT={};z.nodesByRegisteredId=nT;var C4=(T)=>{return cJ[T]??=0,`${T}${++cJ[T]}`},B4=(T)=>{let _=r0[T.kind],F=_.applyConfig?.(T.def,T.$.resolvedConfig)??T.def,W={},{meta:J,...Y}=F,$=J===void 0?{}:typeof J==="string"?{description:J}:J,Z=s1(Y).sort(([X],[O])=>c0(X)?c0(O)?d0(X)-d0(O):1:c0(O)?-1:X<O?-1:1).filter(([X,O])=>{if(X.startsWith("meta.")){let M=X.slice(5);return $[M]=O,!1}return!0});for(let X of Z){let O=X[0],M=_.keys[O];if(!M)return E(`Key ${O} is not valid on ${T.kind} schema`);let Q=M.parse?M.parse(X[1],T):X[1];if(Q!==O_&&(Q!==void 0||M.preserveUndefined))W[O]=Q}if(_.reduce&&!T.prereduced){let X=_.reduce(W,T.$);if(X){if(X instanceof N)return X.throw();return WH(X,$)}}return k4({id:T.id,kind:T.kind,inner:W,meta:$,$:T.$})},k4=({id:T,kind:_,inner:F,meta:W,$:J,ignoreCache:Y})=>{let $=r0[_],Z=s1(F),G=[],X={};for(let[q,j]of Z){let y=$.keys[q],u=y.serialize??(y.child?FH:E_);if(X[q]=u(j),y.child===!0){let h=j;if(XT(h))G.push(...h);else G.push(h)}else if(typeof y.child==="function")G.push(...y.child(j))}if($.finalizeInnerJson)X=$.finalizeInnerJson(X);let O={...X},M={};if(!h_(W))M=c(W,(q,j)=>[q,q==="examples"?j:E_(j)]),O.meta=pW(M,"description",!0);X=pW(X,$.collapsibleKey,!1);let Q=JSON.stringify({kind:_,...X});O=pW(O,$.collapsibleKey,!1);let V=pW(O,$.collapsibleKey,!0),B=JSON.stringify({kind:_,...O});if(J.nodesByHash[B]&&!Y)return J.nodesByHash[B];let K={id:T,kind:_,impl:$,inner:F,innerEntries:Z,innerJson:X,innerHash:Q,meta:W,metaJson:M,json:O,hash:B,collapsibleJson:V,children:G};if(_!=="intersection"){for(let q in F)if(q!=="in"&&q!=="out")K[q]=F[q]}let v=new lJ[_](K,J);return J.nodesByHash[B]=v},dJ=(T,_)=>{if(T.id===_)return T;if(OT(nT[_]))e(`Unexpected attempt to overwrite node id ${_}`);return k4({id:_,kind:T.kind,inner:T.inner,meta:T.meta,$:T.$,ignoreCache:!0})},WH=(T,_,F)=>{if(F&&OT(nT[F]))e(`Unexpected attempt to overwrite node id ${F}`);return k4({id:F??C4(_.alias??T.kind),kind:T.kind,inner:T.inner,meta:_,$:T.$})},pW=(T,_,F)=>{let W=Object.keys(T);if(W.length===1&&W[0]===_){let J=T[_];if(F)return J;if(T_(J,"object")&&(Object.keys(J).length===1||Array.isArray(J)))return J}return T};var vF=(T,_,F)=>{if(T.key!==_.key)return null;let W=T.key,J=UT(T.value,_.value,F),Y=T.required||_.required?"required":"optional";if(J instanceof N)if(Y==="optional")J=z.intrinsic.never.internal;else return J.withPrefixKey(T.key,T.required&&_.required?"required":"optional");if(Y==="required")return F.$.node("required",{key:W,value:J});let $=T.hasDefault()?_.hasDefault()?T.default===_.default?T.default:E(f4(T.default,_.default)):T.default:_.hasDefault()?_.default:O_;return F.$.node("optional",{key:W,value:J,default:$})};class xF extends z_{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=z.intrinsic.object.internal;serializedKey=i_(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=s(this.value.flatRefs.map((T)=>P_([this.key,...T.path],T.node)),P_([this.key],this.value));_transform(T,_){_.path.push(this.key);let F=super._transform(T,_);return _.path.pop(),F}hasDefault(){return"default"in this.inner}traverseAllows=(T,_)=>{if(this.key in T)return W_(this.key,()=>this.value.traverseAllows(T[this.key],_),_);return this.optional};traverseApply=(T,_)=>{if(this.key in T)W_(this.key,()=>this.value.traverseApply(T[this.key],_),_);else if(this.hasKind("required"))_.errorFromNodeContext(this.errorContext)};compile(T){if(T.if(`${this.serializedKey} in data`,()=>T.traverseKey(this.serializedKey,`data${T.prop(this.key)}`,this.value)),this.hasKind("required"))T.else(()=>T.traversalKind==="Apply"?T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):T.return(!1));if(T.traversalKind==="Allows")T.return(!0)}}var f4=(T,_)=>`Invalid intersection of default values ${d(T)} & ${d(_)}`;var JH=l({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)},default:{preserveUndefined:!0}},normalize:(T)=>T,reduce:(T,_)=>{if(_.resolvedConfig.exactOptionalPropertyTypes===!1){if(!T.value.allows(void 0))return _.node("optional",{...T,value:T.value.or(x.undefined)},{prereduced:!0})}},defaults:{description:(T)=>`${T.compiledKey}?: ${T.value.description}`},intersections:{optional:vF}});class tJ extends xF{constructor(...T){super(...T);if("default"in this.inner)hF(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:T,..._}=this.inner;return this.cacheGetter("outProp",this.$.node("required",_,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${d(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=$H(this);defaultValueMorphRef=this.defaultValueMorph&&VT(this.defaultValueMorph)}var bF={implementation:JH,Node:tJ},YH={},$H=(T)=>{if(!T.hasDefault())return;let _=`{${T.compiledKey}: ${T.value.id} = ${E_(T.default)}}`;return YH[_]??=P4(T.key,T.value,T.default)},P4=(T,_,F)=>{if(typeof F==="function")return _.includesTransform?(J,Y)=>{return W_(T,()=>_(J[T]=F(),Y),Y),J}:(J)=>{return J[T]=F(),J};let W=_.includesTransform?_.assert(F):F;return T_(W,"object")?(J,Y)=>{return W_(T,()=>_(J[T]=F,Y),Y),J}:(J)=>{return J[T]=W,J}},hF=(T,_,F)=>{let W=J0(_);if(T_(_,"object")&&!W)E(ZH(F));let J=T.in(W?_():_);if(J instanceof F_){if(F===null)E(`Default ${J.summary}`);let Y=J.transform(($)=>$.transform((Z)=>({...Z,prefixPath:[F]})));E(`Default for ${Y.summary}`)}return _},ZH=(T)=>{return`Non-primitive default ${T===null?"":typeof T==="number"?`for value at [${T}] `:`for ${i_(T)} `}must be specified as a function like () => ({my: 'object'})`};class K_ extends qF{constructor(T,_){super(T,_);Object.defineProperty(this,iT,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(T)=>{let _=this(T);if(_ instanceof F_)return _;return{value:_}}}}as(){return this}brand(T){if(T==="")return E(XH);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(T,_){let F=this.branches.map(T);return _?.(F)??F}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(T={}){let _=H4(this.$.resolvedConfig.toJsonSchema,T);_.useRefs||=this.isCyclic;let F=typeof _.dialect==="string"?{$schema:_.dialect}:{};if(Object.assign(F,this.toJsonSchemaRecurse(_)),_.useRefs)F.$defs=c(this.references,(W,J)=>J.isRoot()&&!J.alwaysExpandJsonSchema?[J.id,J.toResolvedJsonSchema(_)]:[]);return F}toJsonSchemaRecurse(T){if(T.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(T)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(T){let _=this.innerToJsonSchema(T);return Object.assign(_,this.metaJson)}intersect(T){let _=this.$.parseDefinition(T),F=this.rawIntersect(_);if(F instanceof N)return F;return this.$.finalize(F)}rawIntersect(T){return J_(this,T,this.$)}toNeverIfDisjoint(){return this}and(T){let _=this.intersect(T);return _ instanceof N?_.throw():_}rawAnd(T){let _=this.rawIntersect(T);return _ instanceof N?_.throw():_}or(T){let _=this.$.parseDefinition(T);return this.$.finalize(this.rawOr(_))}rawOr(T){let _=[...this.branches,...T.branches];return this.$.node("union",_)}map(T){return this.$.schema(this.applyStructuralOperation("map",[T]))}pick(...T){return this.$.schema(this.applyStructuralOperation("pick",T))}omit(...T){return this.$.schema(this.applyStructuralOperation("omit",T))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.applyStructuralOperation("keyof",[]).reduce((_,F)=>_.intersect(F).toNeverIfDisjoint(),z.intrinsic.unknown.internal);if(T.branches.length===0)E(w4(`keyof ${this.expression}`));return this._keyof=this.$.finalize(T)}get props(){if(this.branches.length!==1)return E(GH(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(T){let _=this.$.parseDefinition(T);return this.$.schema(_.distribute((F)=>this.applyStructuralOperation("merge",[iJ(F)??E(nJ("merge",F.expression))])))}applyStructuralOperation(T,_){return this.distribute((F)=>{if(F.equals(z.intrinsic.object)&&T!=="merge")return F;let W=iJ(F);if(!W)E(nJ(T,F.expression));if(T==="keyof")return W.keyof();if(T==="get")return W.get(..._);if(T==="props")return W.props;let J=T==="required"?"require":T==="partial"?"optionalize":T;return this.$.node("intersection",{...F.inner,structure:W[J](..._)})})}get(...T){if(T[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",T))}extract(T){let _=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>F.extends(_)))}exclude(T){let _=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>!F.extends(_)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(T){return!(this.intersect(T)instanceof N)}extends(T){let _=this.intersect(T);return!(_ instanceof N)&&this.equals(_)}ifExtends(T){return this.extends(T)?this:void 0}subsumes(T){return this.$.parseDefinition(T).extends(this)}configure(T,_="shallow"){return this.configureReferences(T,_)}describe(T,_="shallow"){return this.configure({description:T},_)}optional(){return[this,"?"]}default(T){return hF(this,T,null),[this,"=",T]}from(T){return this.assert(T)}_pipe(...T){let _=T.reduce((F,W)=>F.rawPipeOnce(W),this);return this.$.finalize(_)}tryPipe(...T){let _=T.reduce((F,W)=>F.rawPipeOnce(P(W,"root")?W:(J,Y)=>{try{return W(J,Y)}catch($){return Y.error({code:"predicate",predicate:W,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 f1{path=[];errors=new z1(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 Z4(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 y8(...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 V4(Y,this);if(this.currentBranch)this.currentBranch.error=Z;else this.errors.add(Z);return Z}applyQueuedMorphs(){while(this.queuedMorphs.length){let Y=this.queuedMorphs;this.queuedMorphs=[];for(let{path:Z,morphs:X}of Y){if(this.errors.affectsPath(Z))continue;this.applyMorphsAtPath(Z,X)}}}applyMorphsAtPath(Y,Z){let X=Y.at(-1),_;if(X!==void 0){_=this.root;for(let G=0;G<Y.length-1;G++)_=_[Y[G]]}this.path=[...Y];for(let G of Z){let W=V0(G),H=G(_===void 0?this.root:_[X],this);if(H instanceof V4){this.errors.add(H);break}if(H instanceof z1){if(!W)this.errors.merge(H);break}if(_===void 0)this.root=H;else _[X]=H;this.applyQueuedMorphs()}}}var F1=(Y,Z,X)=>{if(!X)return Z();X.path.push(Y);let _=Z();return X.path.pop(),_};class d8 extends h1{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Y,Z){super((_,G,W=this.onFail)=>{if(G)return this.traverseApply(_,G),G.hasError()?G.errors:G.data;return this.rootApply(_,W)},{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)=>$$(_,G.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let _=0;_<this.children.length;_++){if(this.includesTransform||=this.children[_].includesTransform,this.includesContextualPredicate||=this.children[_].includesContextualPredicate,this.isCyclic||=this.children[_].isCyclic,!X){let G=this.children[_].flatRefs;for(let W=0;W<G.length;W++){let H=G[W];if(!this.flatRefs.some((J)=>n_(J,H))){this.flatRefs.push(H);for(let J of H.node.branches)if(J.hasKind("morph")||J.hasKind("intersection")&&J.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:H.path,propString:H.propString,node:J})}}}Object.assign(this.referencesById,this.children[_].referencesById)}this.flatRefs.sort((_,G)=>_.path.length>G.path.length?1:_.path.length<G.path.length?-1:_.propString>G.propString?1:_.propString<G.propString?-1:_.node.expression<G.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((_)=>_.length===1||_.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((_)=>_.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(_)=>this.traverseAllows(_,new f1(_,this.$.resolvedConfig)):(_)=>this.traverseAllows(_)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Z,X)=>{if(this.allows(Z))return Z;let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"contextual":return(Z,X)=>{let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Y=this.$.resolvedConfig.clone;return(Z,X)=>{if(this.allows(Z))return this.contextFreeMorph(Y&&(typeof Z==="object"&&Z!==null||typeof Z==="function")?Y(Z):Z);let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,_0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=J$(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,_]of this.innerEntries){let G=this.impl.keys[X];if(G.reduceIo)G.reduceIo(Y,Z,_);else if(G.child){let W=_;Z[X]=O0(W)?W.map((H)=>H[Y]):W[Y]}else Z[X]=_}return this.$.node(this.kind,Z)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Y){let Z=V0(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)q4(`${this.kind} node was not of asserted kind ${Y}`);return this}hasKindIn(...Y){return Y.includes(this.kind)}assertHasKindIn(...Y){if(!a1(Y,this.kind))q4(`${this.kind} node was not one of asserted kinds ${Y}`);return this}isBasis(){return a1(u_,this.kind)}isConstraint(){return a1(u6,this.kind)}isStructural(){return a1(s4,this.kind)}isRefinement(){return a1(wZ,this.kind)}isRoot(){return a1(a4,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=u8.normalize(Y);return this._select(Z)}_select(Y){let Z=u8.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 u8.applyMethod[Y.method??"filter"](Z,this,Y)}transform(Y,Z){return this._transform(Y,this._createTransformContext(Z))}_createTransformContext(Y){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Y?.prereduced??!1},undeclaredKeyHandling:void 0,...Y}}_transform(Y,Z){let X=Z.bindScope??this.$;if(Z.seen[this.id])return this.$.lazilyResolve(Z.seen[this.id]);if(Z.shouldTransform?.(this,Z)===!1)return this;let _;if(Z.seen[this.id]=()=>_,this.hasKind("structure")&&this.undeclared!==Z.undeclaredKeyHandling)Z={...Z,undeclaredKeyHandling:this.undeclared};let G=o(this.inner,($,z)=>{if(!this.impl.keys[$].child)return[$,z];let O=z;if(!O0(O)){let V=O._transform(Y,Z);return V?[$,V]:[]}if(O.length===0)return[$,z];let L=O.flatMap((V)=>{return V._transform(Y,Z)??[]});return L.length?[$,L]:[]});delete Z.seen[this.id];let W=Object.assign(G,{meta:this.meta}),H=Z.selected&&!Z.selected.includes(this)?W:Y(this.kind,W,Z);if(H===null)return null;if(V0(H))return _=H;let J=Object.keys(H);if((J.length===0||J.length===1&&J[0]==="meta")&&!c1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in H))return Z.undeclaredKeyHandling?{...H,value:B.intrinsic.unknown}:null;if(this.kind==="morph")H.in??=B.intrinsic.unknown;return _=X.node(this.kind,H,Z.parseOptions)}configureReferences(Y,Z="references"){let X=u8.normalize(Z),_=typeof Y==="string"?(J,Q)=>({...Q,meta:{...Q.meta,description:Y}}):typeof Y==="function"?(J,Q)=>({...Q,meta:Y(Q.meta)}):(J,Q)=>({...Q,meta:{...Q.meta,...Y}});if(X.boundary==="self")return this.$.node(this.kind,_(this.kind,{...this.inner,meta:this.meta}));let G=this._select(X),W=G&&U4(G),H=X.boundary==="child"?(J,Q)=>Q.root.children.includes(J):X.boundary==="shallow"?(J)=>J.kind!=="structure":()=>!0;return this.$.finalize(this.transform(_,{shouldTransform:H,selected:W}))}}var u8={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)q4(o_(Z,X));return Y},find:(Y)=>Y[0],assertFind:(Y,Z,X)=>{if(Y.length===0)q4(o_(Z,X));return Y[0]}},normalize:(Y)=>typeof Y==="function"?{boundary:"references",method:"filter",where:Y}:typeof Y==="string"?y0(Y,u8.applyBoundary)?{method:"filter",boundary:Y}:{boundary:"references",method:"filter",kind:Y}:{boundary:"references",method:"filter",...Y}},o_=(Y,Z)=>`${Y} had no references matching ${n(Z)}.`,W$=(Y)=>Z4(Y,{stringifyNonKey:(Z)=>Z.expression}),H$=/"(\$ark\.[^"]+)"/g,J$=(Y)=>JSON.stringify(Y).replaceAll(H$,"$1"),b1=(Y,Z)=>({path:Y,node:Z,propString:W$(Y)}),n_=(Y,Z)=>Y.propString===Z.propString&&Y.node.equals(Z.node),IZ=(Y,Z)=>d1(Y,Z,{isEqual:n_}),$$=(Y,Z)=>d1(Y,Z,{isEqual:(X,_)=>X.equals(_)});class S extends Array{static init(Y,Z,X,_){return new S({kind:Y,l:Z,r:X,path:_?.path??[],optional:_?.optional??!1})}add(Y,Z,X,_){return this.push({kind:Y,l:Z,r:X,path:_?.path??[],optional:_?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Y,l:Z,r:X}=this[0],_=Z4(Y);return TZ(`Intersection${_&&` at ${_}`} of ${r_(Z,X)}`)}return`The following intersections result in unsatisfiable types:
|
|
23
|
+
\u2022 ${this.map(({path:Y,l:Z,r:X})=>`${Y}: ${r_(Z,X)}`).join(`
|
|
24
|
+
\u2022 `)}`}throw(){return w(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 B.intrinsic.never}}var r_=(Y,Z)=>`${BZ(Y)} and ${BZ(Z)}`,BZ=(Y)=>V0(Y)?Y.expression:O0(Y)?Y.map(BZ).join(" | ")||"never":String(Y),TZ=(Y)=>`${Y} results in an unsatisfiable type`;var Y8={},U1=(Y,Z,X)=>M0(Y,Z,{$:X,invert:!1,pipe:!1}),c8=(Y,Z,X)=>M0(Y,Z,{$:X,invert:!1,pipe:!0}),M0=(Y,Z,X)=>{let _=X.pipe?"|>":"&",G=`${Y.hash}${_}${Z.hash}`;if(Y8[G]!==void 0)return Y8[G];if(!X.pipe){let J=`${Z.hash}${_}${Y.hash}`;if(Y8[J]!==void 0){let Q=Y8[J],$=Q instanceof S?Q.invert():Q;return Y8[G]=$,$}}let W=!X.pipe||!Y.includesTransform&&!Z.includesTransform;if(W&&Y.equals(Z))return Y;let H=W?CZ(Y,Z,X):Y.hasKindIn(...a4)?Q$(Y,Z,X):CZ(Y,Z,X);if(V0(H)){if(Y.equals(H))H=Y;else if(Z.equals(H))H=Z}return Y8[G]=H,H},CZ=(Y,Z,X)=>{let _=Y.precedence<Z.precedence?Y.kind:Z.kind,G=Y.impl.intersections[Z.kind]??Z.impl.intersections[Y.kind];if(G===void 0)return null;else if(_===Y.kind)return G(Y,Z,X);else{let W=G(Z,Y,{...X,invert:!X.invert});if(W instanceof S)W=W.invert();return W}},Q$=(Y,Z,X)=>Y.includesTransform||Z.includesTransform?X.invert?s_(Z,Y,X):s_(Y,Z,X):CZ(Y,Z,X),s_=(Y,Z,X)=>Y.distribute((_)=>z$(_,Z,X),(_)=>{let G=_.filter(V0);if(G.length===0)return S.init("union",Y.branches,Z.branches);if(G.length<Y.branches.length||!Y.branches.every((J,Q)=>J.in.equals(G[Q].in)))return X.$.parseSchema(G);let W;if(G.length===1){let J=G[0];if(!W)return J;return X.$.node("morph",{...J.inner,in:J.in.configure(W,"self")})}let H={branches:G};if(W)H.meta=W;return X.$.parseSchema(H)}),z$=(Y,Z,X)=>{if(Y.hasKind("morph")){let G=[...Y.morphs];if(Y.lastMorphIfNode){let W=M0(Y.lastMorphIfNode,Z,X);if(W instanceof S)return W;G[G.length-1]=W}else G.push(Z);return X.$.node("morph",{morphs:G,in:Y.inner.in})}if(Z.hasKind("morph")){let G=M0(Y,Z.in,X);if(G instanceof S)return G;return X.$.node("morph",{morphs:[Z],in:G})}return X.$.node("morph",{morphs:[Z],in:Y})};class T1 extends d8{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,X1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Y){return U1(this,Y,this.$)}}class _4 extends T1{traverseApply=(Y,Z)=>{if(!this.traverseAllows(Y,Z))Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.traversalKind==="Allows")Y.return(this.compiledCondition);else Y.if(this.compiledNegation,()=>Y.line(`${Y.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return D4(this.errorContext)}}var t0=(Y)=>(Z,X)=>{if(O0(Z)){if(Z.length===0)return;let G=Z.map((W)=>X.$.node(Y,W));if(Y==="predicate")return G;return G.sort((W,H)=>W.hash<H.hash?-1:1)}let _=X.$.node(Y,Z);return _.hasOpenIntersection()?[_]:_},Z8=(Y)=>{let Z=Y.r.shift();if(!Z){let _=Y.l.length===0&&Y.kind==="structure"?B.intrinsic.unknown.internal:Y.ctx.$.node(Y.kind,Object.assign(Y.baseInner,F$(Y.l)),{prereduced:!0});for(let G of Y.roots){if(_ instanceof S)return _;_=M0(G,_,Y.ctx)}return _}let X=!1;for(let _=0;_<Y.l.length;_++){let G=M0(Y.l[_],Z,Y.ctx);if(G===null)continue;if(G instanceof S)return G;if(!X){if(G.isRoot())return Y.roots.push(G),Y.l.splice(_),Z8(Y);Y.l[_]=G,X=!0}else if(!Y.l.includes(G))return _0(`Unexpectedly encountered multiple distinct intersection results for refinement ${G}`)}if(!X)Y.l.push(Z);if(Y.kind==="intersection"){if(Z.impliedSiblings)for(let _ of Z.impliedSiblings)d1(Y.r,_)}return Z8(Y)},X8=(Y)=>{return Object.entries(Y).flatMap(([X,_])=>(X in d6)?_:[]).sort((X,_)=>X.precedence<_.precedence?-1:X.precedence>_.precedence?1:X.kind==="predicate"&&_.kind==="predicate"?0:X.hash<_.hash?-1:1)},F$=(Y)=>{let Z={};for(let X of Y)if(X.hasOpenIntersection())Z[X.kind]=Z0(Z[X.kind],X);else{if(Z[X.kind])return _0(`Unexpected intersection of closed refinements of kind ${X.kind}`);Z[X.kind]=X}return Z},a_=(...Y)=>w(t_(...Y)),t_=(Y,Z,X)=>{let _=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Z).defaultShortDescription;return`${K_(Y)} operand must be ${Z.description} (was ${_})`};var e_=(Y,Z,X)=>new M4(Y,Z,X,X,null);class l6 extends h1{}class M4 extends h1{[X1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Y,Z,X,_,G){super((...W)=>{let H=o(this.names,(J,Q)=>{let $=this.arg$.parse(W[J]);if(!$.extends(this.constraints[J]))w(U$(Q,this.constraints[J].expression,$.expression));return[Q,$]});if(this.defIsLazy()){let J=this.bodyDef(H);return this.$.parse(J)}return this.$.parse(Z,{args:H})});this.paramDefs=Y,this.bodyDef=Z,this.$=X,this.arg$=_,this.hkt=G,this.description=G?new G().description??`a generic type for ${G.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof l6}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:g_(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Y)=>typeof Y==="string"?[Y,B.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 U$=(Y,Z,X)=>`${Y} must be assignable to ${Z} (was ${X})`;var O$=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 YG extends T1{serializedPredicate=K0(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 KZ={implementation:O$,Node:YG};var E$=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Y)=>Number.isInteger(Y)?Y:w(L$(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/D$(Y.rule,Z.rule))})},obviatesBasisDescription:!0});class ZG extends _4{traverseAllows=(Y)=>Y%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=B.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Y){if(Y.type="integer",this.rule===1)return Y;return Y.multipleOf=this.rule,Y}}var qZ={implementation:E$,Node:ZG};var L$=(Y)=>`divisor must be an integer (was ${Y})`,D$=(Y,Z)=>{let X,_=Y,G=Z;while(G!==0)X=G,G=_%G,_=X;return _};class w1 extends _4{boundOperandKind=w$[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=N$(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${V$[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?R$(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 V$={"<":">=","<=":">",">":"<=",">=":"<"},M$={min:"max",minLength:"maxLength",after:"before"},i6={parse:(Y)=>Y||void 0},o6=(Y)=>(Z)=>{if(typeof Z==="number")return{rule:Z};let{exclusive:X,..._}=Z;return X?{..._,rule:Y==="minLength"?_.rule+1:_.rule-1}:_},n6=(Y)=>(Z)=>{if(typeof Z==="number"||typeof Z==="string"||Z instanceof Date)return{rule:Z};let{exclusive:X,..._}=Z;if(!X)return _;let G=typeof _.rule==="number"?_.rule:typeof _.rule==="string"?new Date(_.rule).valueOf():_.rule.valueOf();return X?{..._,rule:Y==="after"?G+1:G-1}:_},r6=(Y)=>typeof Y==="string"||typeof Y==="number"?new Date(Y):Y,A$=(Y,Z)=>`${Y} bound must be a positive integer (was ${Z})`,_8=(Y)=>(Z)=>{if(!Number.isInteger(Z)||Z<0)w(A$(Y,Z));return Z},w$={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},N$=(Y,Z)=>`${y0(Y,M$)?">":"<"}${Z?"":"="}`,R$=(Y)=>typeof Y==="string"?Y:new Date(Y).toLocaleString(),XG=(Y)=>`Bounded expression ${Y} must be exactly one of number, string, Array, or Date`;var I$=r({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:r6,serialize:(Y)=>Y.toISOString()}},normalize:n6("after"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or later`,actual:v4},intersections:{after:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class _G extends w1{impliedBasis=B.intrinsic.Date.internal;collapsibleLimitString=v4(this.rule);traverseAllows=(Y)=>Y>=this.rule;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,after:this.rule})}}var jZ={implementation:I$,Node:_G};var B$=r({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:r6,serialize:(Y)=>Y.toISOString()}},normalize:n6("before"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or earlier`,actual:v4},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 GG extends w1{collapsibleLimitString=v4(this.rule);traverseAllows=(Y)=>Y<=this.rule;impliedBasis=B.intrinsic.Date.internal;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,before:this.rule})}}var PZ={implementation:B$,Node:GG};var T$=r({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:_8("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 WG extends _4{traverseAllows=(Y)=>Y.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=B.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y.maxLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y.maxItems=this.rule,Y;default:return R0.throwInternalOperandError("exactLength",Y)}}}var SZ={implementation:T$,Node:WG};var C$=r({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:i6},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 HG extends w1{impliedBasis=B.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 vZ={implementation:C$,Node:HG};var K$=r({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_8("maxLength")}},reduce:(Y,Z)=>Y.rule===0?Z.node("exactLength",Y):void 0,normalize:o6("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 JG extends w1{impliedBasis=B.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length<=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.maxLength=this.rule,Y;case"array":return Y.maxItems=this.rule,Y;default:return R0.throwInternalOperandError("maxLength",Y)}}}var xZ={implementation:K$,Node:JG};var q$=r({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:i6},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 $G extends w1{impliedBasis=B.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 hZ={implementation:q$,Node:$G};var j$=r({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_8("minLength")}},reduce:(Y)=>Y.rule===0?B.intrinsic.unknown:void 0,normalize:o6("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 QG extends w1{impliedBasis=B.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length>=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y;default:return R0.throwInternalOperandError("minLength",Y)}}}var fZ={implementation:j$,Node:QG};var zG={min:hZ.implementation,max:vZ.implementation,minLength:fZ.implementation,maxLength:xZ.implementation,exactLength:SZ.implementation,after:jZ.implementation,before:PZ.implementation},FG={min:hZ.Node,max:vZ.Node,minLength:fZ.Node,maxLength:xZ.Node,exactLength:SZ.Node,after:jZ.Node,before:PZ.Node};var P$=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 UG extends _4{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=B.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 bZ={implementation:P$,Node:UG};var l8=(Y,Z)=>{let X=S$(Y);if(Z&&!Z.includes(X))return w(`Root of kind ${X} should be one of ${Z}`);return X},S$=(Y)=>{if(y(Y,"root"))return Y.kind;if(typeof Y==="string")return Y[0]==="$"?"alias":(Y in Q1)?"domain":"proto";if(typeof Y==="function")return"proto";if(typeof Y!=="object"||Y===null)return w(OG(Y));if("morphs"in Y)return"morph";if("branches"in Y||O0(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 d6)))return"intersection";if("proto"in Y)return"proto";if("domain"in Y)return"domain";return w(OG(Y))},OG=(Y)=>`${n(Y)} is not a valid type schema`,EG={},v$=(Y)=>O0(Y)?Y.map((Z)=>Z.collapsibleJson):Y.collapsibleJson,_1={};B.nodesByRegisteredId=_1;var kZ=(Y)=>{return EG[Y]??=0,`${Y}${++EG[Y]}`},gZ=(Y)=>{let Z=G8[Y.kind],X=Z.applyConfig?.(Y.def,Y.$.resolvedConfig)??Y.def,_={},{meta:G,...W}=X,H=G===void 0?{}:typeof G==="string"?{description:G}:G,J=JZ(W).sort(([$],[z])=>t4($)?t4(z)?e4($)-e4(z):1:t4(z)?-1:$<z?-1:1).filter(([$,z])=>{if($.startsWith("meta.")){let O=$.slice(5);return H[O]=z,!1}return!0});for(let $ of J){let z=$[0],O=Z.keys[z];if(!O)return w(`Key ${z} is not valid on ${Y.kind} schema`);let L=O.parse?O.parse($[1],Y):$[1];if(L!==A1&&(L!==void 0||O.preserveUndefined))_[z]=L}if(Z.reduce&&!Y.prereduced){let $=Z.reduce(_,Y.$);if($){if($ instanceof S)return $.throw();return x$($,H)}}return yZ({id:Y.id,kind:Y.kind,inner:_,meta:H,$:Y.$})},yZ=({id:Y,kind:Z,inner:X,meta:_,$:G,ignoreCache:W})=>{let H=G8[Z],J=JZ(X),Q=[],$={};for(let[b,k]of J){let g=H.keys[b],N=g.serialize??(g.child?v$:B1);if($[b]=N(k),g.child===!0){let I=k;if(O0(I))Q.push(...I);else Q.push(I)}else if(typeof g.child==="function")Q.push(...g.child(k))}if(H.finalizeInnerJson)$=H.finalizeInnerJson($);let z={...$},O={};if(!c1(_))O=o(_,(b,k)=>[b,b==="examples"?k:B1(k)]),z.meta=s6(O,"description",!0);$=s6($,H.collapsibleKey,!1);let L=JSON.stringify({kind:Z,...$});z=s6(z,H.collapsibleKey,!1);let V=s6(z,H.collapsibleKey,!0),R=JSON.stringify({kind:Z,...z});if(G.nodesByHash[R]&&!W)return G.nodesByHash[R];let A={id:Y,kind:Z,impl:H,inner:X,innerEntries:J,innerJson:$,innerHash:L,meta:_,metaJson:O,json:z,hash:R,collapsibleJson:V,children:Q};if(Z!=="intersection"){for(let b in X)if(b!=="in"&&b!=="out")A[b]=X[b]}let f=new DG[Z](A,G);return G.nodesByHash[R]=f},LG=(Y,Z)=>{if(Y.id===Z)return Y;if(V0(_1[Z]))_0(`Unexpected attempt to overwrite node id ${Z}`);return yZ({id:Z,kind:Y.kind,inner:Y.inner,meta:Y.meta,$:Y.$,ignoreCache:!0})},x$=(Y,Z,X)=>{if(X&&V0(_1[X]))_0(`Unexpected attempt to overwrite node id ${X}`);return yZ({id:X??kZ(Z.alias??Y.kind),kind:Y.kind,inner:Y.inner,meta:Z,$:Y.$})},s6=(Y,Z,X)=>{let _=Object.keys(Y);if(_.length===1&&_[0]===Z){let G=Y[Z];if(X)return G;if($1(G,"object")&&(Object.keys(G).length===1||Array.isArray(G)))return G}return Y};var i8=(Y,Z,X)=>{if(Y.key!==Z.key)return null;let _=Y.key,G=M0(Y.value,Z.value,X),W=Y.required||Z.required?"required":"optional";if(G instanceof S)if(W==="optional")G=B.intrinsic.never.internal;else return G.withPrefixKey(Y.key,Y.required&&Z.required?"required":"optional");if(W==="required")return X.$.node("required",{key:_,value:G});let H=Y.hasDefault()?Z.hasDefault()?Y.default===Z.default?Y.default:w(pZ(Y.default,Z.default)):Y.default:Z.hasDefault()?Z.default:A1;return X.$.node("optional",{key:_,value:G,default:H})};class o8 extends T1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=B.intrinsic.object.internal;serializedKey=X4(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=Z0(this.value.flatRefs.map((Y)=>b1([this.key,...Y.path],Y.node)),b1([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 F1(this.key,()=>this.value.traverseAllows(Y[this.key],Z),Z);return this.optional};traverseApply=(Y,Z)=>{if(this.key in Y)F1(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 pZ=(Y,Z)=>`Invalid intersection of default values ${n(Y)} & ${n(Z)}`;var h$=r({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},default:{preserveUndefined:!0}},normalize:(Y)=>Y,reduce:(Y,Z)=>{if(Z.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Y.value.allows(void 0))return Z.node("optional",{...Y,value:Y.value.or(d.undefined)},{prereduced:!0})}},defaults:{description:(Y)=>`${Y.compiledKey}?: ${Y.value.description}`},intersections:{optional:i8}});class VG extends o8{constructor(...Y){super(...Y);if("default"in this.inner)r8(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} = ${n(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=b$(this);defaultValueMorphRef=this.defaultValueMorph&&K0(this.defaultValueMorph)}var n8={implementation:h$,Node:VG},f$={},b$=(Y)=>{if(!Y.hasDefault())return;let Z=`{${Y.compiledKey}: ${Y.value.id} = ${B1(Y.default)}}`;return f$[Z]??=mZ(Y.key,Y.value,Y.default)},mZ=(Y,Z,X)=>{if(typeof X==="function")return Z.includesTransform?(G,W)=>{return F1(Y,()=>Z(G[Y]=X(),W),W),G}:(G)=>{return G[Y]=X(),G};let _=Z.includesTransform?Z.assert(X):X;return $1(_,"object")?(G,W)=>{return F1(Y,()=>Z(G[Y]=X,W),W),G}:(G)=>{return G[Y]=_,G}},r8=(Y,Z,X)=>{let _=O4(Z);if($1(Z,"object")&&!_)w(k$(X));let G=Y.in(_?Z():Z);if(G instanceof z1){if(X===null)w(`Default ${G.summary}`);let W=G.transform((H)=>H.transform((J)=>({...J,prefixPath:[X]})));w(`Default for ${W.summary}`)}return Z},k$=(Y)=>{return`Non-primitive default ${Y===null?"":typeof Y==="number"?`for value at [${Y}] `:`for ${X4(Y)} `}must be specified as a function like () => ({my: 'object'})`};class C1 extends d8{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,X1,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Y)=>{let Z=this(Y);if(Z instanceof z1)return Z;return{value:Z}}}}as(){return this}brand(Y){if(Y==="")return w(g$);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=NZ(this.$.resolvedConfig.toJsonSchema,Y);Z.useRefs||=this.isCyclic;let X=typeof Z.dialect==="string"?{$schema:Z.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse(Z)),Z.useRefs)X.$defs=o(this.references,(_,G)=>G.isRoot()&&!G.alwaysExpandJsonSchema?[G.id,G.toResolvedJsonSchema(Z)]:[]);return X}toJsonSchemaRecurse(Y){if(Y.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(Y)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Y){let Z=this.innerToJsonSchema(Y);return Object.assign(Z,this.metaJson)}intersect(Y){let Z=this.$.parseDefinition(Y),X=this.rawIntersect(Z);if(X instanceof S)return X;return this.$.finalize(X)}rawIntersect(Y){return U1(this,Y,this.$)}toNeverIfDisjoint(){return this}and(Y){let Z=this.intersect(Y);return Z instanceof 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(),B.intrinsic.unknown.internal);if(Y.branches.length===0)w(TZ(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Y)}get props(){if(this.branches.length!==1)return w(y$(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(Z.distribute((X)=>this.applyStructuralOperation("merge",[MG(X)??w(AG("merge",X.expression))])))}applyStructuralOperation(Y,Z){return this.distribute((X)=>{if(X.equals(B.intrinsic.object)&&Y!=="merge")return X;let _=MG(X);if(!_)w(AG(Y,X.expression));if(Y==="keyof")return _.keyof();if(Y==="get")return _.get(...Z);if(Y==="props")return _.props;let G=Y==="required"?"require":Y==="partial"?"optionalize":Y;return this.$.node("intersection",{...X.inner,structure:_[G](...Z)})})}get(...Y){if(Y[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Y))}extract(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>X.extends(Z)))}exclude(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>!X.extends(Z)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Y){return!(this.intersect(Y)instanceof 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 r8(this,Y,null),[this,"=",Y]}from(Y){return this.assert(Y)}_pipe(...Y){let Z=Y.reduce((X,_)=>X.rawPipeOnce(_),this);return this.$.finalize(Z)}tryPipe(...Y){let Z=Y.reduce((X,_)=>X.rawPipeOnce(y(_,"root")?_:(G,W)=>{try{return _(G,W)}catch(H){return W.error({code:"predicate",predicate:_,actual:`aborted due to error:
|
|
25
|
+
${H}
|
|
26
|
+
`})}}),this);return this.$.finalize(Z)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Y){return this.$.finalize(this.toNode(this.$.parseDefinition(Y)))}toNode(Y){let Z=c8(this,Y,this.$);if(Z instanceof S)return Z.throw();return Z}rawPipeOnce(Y){if(y(Y,"root"))return this.toNode(Y);return this.distribute((Z)=>Z.hasKind("morph")?this.$.node("morph",{in:Z.inner.in,morphs:[...Z.morphs,Y]}):this.$.node("morph",{in:Z,morphs:[Y]}),this.$.parseSchema)}narrow(Y){return this.constrainOut("predicate",Y)}constrain(Y,Z){return this._constrain("root",Y,Z)}constrainIn(Y,Z){return this._constrain("in",Y,Z)}constrainOut(Y,Z){return this._constrain("out",Y,Z)}_constrain(Y,Z,X){let _=this.$.node(Z,X);if(_.isRoot())return _.isUnknown()?this:_0(`Unexpected constraint node ${_}`);let G=Y==="root"?this:this[Y];if(G.hasKind("morph")||_.impliedBasis&&!G.extends(_.impliedBasis))return a_(Z,_.impliedBasis,this);let W=this.$.node("intersection",{[_.kind]:_}),H=Y==="out"?c8(this,W,this.$):U1(this,W,this.$);if(H instanceof S)H.throw();return this.$.finalize(H)}onUndeclaredKey(Y){let Z=typeof Y==="string"?Y:Y.rule,X=typeof Y==="string"?!1:Y.deep;return this.$.finalize(this.transform((_,G)=>_==="structure"?Z==="ignore"?D_(G,{undeclared:1}):{...G,undeclared:Z}:G,X?void 0:{shouldTransform:(_)=>!a1(s4,_.kind)}))}hasEqualMorphs(Y){if(!this.includesTransform&&!Y.includesTransform)return!0;if(!e1(this.shallowMorphs,Y.shallowMorphs))return!1;if(!e1(this.flatMorphs,Y.flatMorphs,{isEqual:(Z,X)=>Z.propString===X.propString&&(Z.node.hasKind("morph")&&X.node.hasKind("morph")?Z.node.hasEqualMorphs(X.node):Z.node.hasKind("intersection")&&X.node.hasKind("intersection")?Z.node.structure?.structuralMorphRef===X.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(Y){return this.onUndeclaredKey({rule:Y,deep:!0})}filter(Y){return this.constrainIn("predicate",Y)}divisibleBy(Y){return this.constrain("divisor",Y)}matching(Y){return this.constrain("pattern",Y)}atLeast(Y){return this.constrain("min",Y)}atMost(Y){return this.constrain("max",Y)}moreThan(Y){return this.constrain("min",W8(Y))}lessThan(Y){return this.constrain("max",W8(Y))}atLeastLength(Y){return this.constrain("minLength",Y)}atMostLength(Y){return this.constrain("maxLength",Y)}moreThanLength(Y){return this.constrain("minLength",W8(Y))}lessThanLength(Y){return this.constrain("maxLength",W8(Y))}exactlyLength(Y){return this.constrain("exactLength",Y)}atOrAfter(Y){return this.constrain("after",Y)}atOrBefore(Y){return this.constrain("before",Y)}laterThan(Y){return this.constrain("after",W8(Y))}earlierThan(Y){return this.constrain("before",W8(Y))}}var g$="Expected a non-empty brand name after #",W8=(Y)=>typeof Y==="object"&&!(Y instanceof Date)?{...Y,exclusive:!0}:{rule:Y,exclusive:!0},s8=(Y,Z)=>y(Z,"root")?y(Y,"root")?Y.extends(Z):Z.allows(Y):y(Y,"root")?Y.hasUnit(Z):Z===Y,MG=(Y)=>{if(Y.hasKind("morph"))return null;if(Y.hasKind("intersection"))return Y.inner.structure??(Y.basis?.domain==="object"?Y.$.bindReference(B.intrinsic.emptyStructure):null);if(Y.isBasis()&&Y.domain==="object")return Y.$.bindReference(B.intrinsic.emptyStructure);return null},y$=(Y)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
27
|
+
${Y}`,AG=(Y,Z)=>`${Y} operand must be an object (was ${Z})`;var l1=(Y,Z)=>o(c6(Y),(X,_)=>[_,Z]);var p$=(Y)=>typeof Y==="string"?{reference:Y}:Y,wG=(Y)=>Y instanceof S?B.intrinsic.never.internal:Y,m$=r({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Y)=>Y.startsWith("$")?Y:`$ark.${Y}`},resolve:{}},normalize:p$,defaults:{description:(Y)=>Y.reference},intersections:{alias:(Y,Z,X)=>X.$.lazilyResolve(()=>wG(M0(Y.resolution,Z.resolution,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.reference}`),...l1("alias",(Y,Z,X)=>{if(Z.isUnknown())return Y;if(Z.isNever())return Z;if(Z.isBasis()&&!Z.overlaps(B.intrinsic.object))return S.init("assignability",B.intrinsic.object,Z);return X.$.lazilyResolve(()=>wG(M0(Y.resolution,Z,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.id}`)})}});class NG extends C1{expression=this.reference;structure=void 0;get resolution(){let Y=this._resolve();return _1[this.id]=Y}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let Y=this.reference,Z=_1[Y],X=[];while(y(Z,"context")){if(X.includes(Z.id))return w(u$(Z.id,X));X.push(Z.id),Z=_1[Z.id]}if(!y(Z,"root"))return _0(`Unexpected resolution for reference ${this.reference}
|
|
28
|
+
Seen: [${X.join("->")}]
|
|
29
|
+
Resolution: ${n(Z)}`);return Z}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Y=this.reference.slice(1),Z=this.$.resolutions[Y];if(typeof Z==="string")return Z;if(y(Z,"root"))return Z.id;return _0(`Unexpected resolution for reference ${this.reference}: ${n(Z)}`)}get defaultShortDescription(){return Q1.object}innerToJsonSchema(Y){return this.resolution.toJsonSchemaRecurse(Y)}traverseAllows=(Y,Z)=>{let X=Z.seen[this.reference];if(X?.includes(Y))return!0;return Z.seen[this.reference]=Z0(X,Y),this.resolution.traverseAllows(Y,Z)};traverseApply=(Y,Z)=>{let X=Z.seen[this.reference];if(X?.includes(Y))return;Z.seen[this.reference]=Z0(X,Y),this.resolution.traverseApply(Y,Z)};compile(Y){let Z=this.resolutionId;Y.if(`ctx.seen.${Z} && ctx.seen.${Z}.includes(data)`,()=>Y.return(!0)),Y.if(`!ctx.seen.${Z}`,()=>Y.line(`ctx.seen.${Z} = []`)),Y.line(`ctx.seen.${Z}.push(data)`),Y.return(Y.invoke(Z))}}var u$=(Y,Z)=>`Alias '${Y}' has a shallow resolution cycle: ${[...Z,Y].join("->")}`,a8={implementation:m$,Node:NG};class x4 extends C1{traverseApply=(Y,Z)=>{if(!this.traverseAllows(Y,Z))Z.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return D4(this.errorContext)}compile(Y){if(Y.traversalKind==="Allows")Y.return(this.compiledCondition);else Y.if(this.compiledNegation,()=>Y.line(`${Y.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var d$=r({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Y)=>typeof Y==="string"?{domain:Y}:n4(Y,"numberAllowsNaN")&&Y.domain!=="number"?w(a6.writeBadAllowNanMessage(Y.domain)):Y,applyConfig:(Y,Z)=>Y.numberAllowsNaN===void 0&&Y.domain==="number"&&Z.numberAllowsNaN?{...Y,numberAllowsNaN:!0}:Y,defaults:{description:(Y)=>Q1[Y.domain],actual:(Y)=>Number.isNaN(Y)?"NaN":Q1[g0(Y)]},intersections:{domain:(Y,Z)=>Y.domain==="number"&&Z.domain==="number"?Y.numberAllowsNaN?Z:Y:S.init("domain",Y,Z)}});class RG extends x4{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Y)=>typeof Y==="number"&&!Number.isNaN(Y):(Y)=>g0(Y)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return Q1[this.domain]}innerToJsonSchema(Y){if(this.domain==="bigint"||this.domain==="symbol")return Y.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var a6={implementation:d$,Node:RG,writeBadAllowNanMessage:(Y)=>`numberAllowsNaN may only be specified with domain "number" (was ${Y})`};var c$=r({kind:"intersection",hasAssociatedError:!0,normalize:(Y)=>{if(V0(Y))return Y;let{structure:Z,...X}=Y,_=!!Z,G=Z??{},W=o(X,(H,J)=>{if(y0(H,d_)){if(_)w(`Flattened structure key ${H} cannot be specified alongside a root 'structure' key.`);return G[H]=J,[]}return[H,J]});if(y(G,"constraint")||!c1(G))W.structure=G;return W},finalizeInnerJson:({structure:Y,...Z})=>$1(Y,"object")?{...Y,...Z}:Z,keys:{domain:{child:!0,parse:(Y,Z)=>Z.$.node("domain",Y)},proto:{child:!0,parse:(Y,Z)=>Z.$.node("proto",Y)},structure:{child:!0,parse:(Y,Z)=>Z.$.node("structure",Y),serialize:(Y)=>{if(!Y.sequence?.minLength)return Y.collapsibleJson;let{sequence:Z,...X}=Y.collapsibleJson,{minVariadicLength:_,...G}=Z,W=G.variadic&&Object.keys(G).length===1?G.variadic:G;return{...X,sequence:W}}},divisor:{child:!0,parse:t0("divisor")},max:{child:!0,parse:t0("max")},min:{child:!0,parse:t0("min")},maxLength:{child:!0,parse:t0("maxLength")},minLength:{child:!0,parse:t0("minLength")},exactLength:{child:!0,parse:t0("exactLength")},before:{child:!0,parse:t0("before")},after:{child:!0,parse:t0("after")},pattern:{child:!0,parse:t0("pattern")},predicate:{child:!0,parse:t0("predicate")}},reduce:(Y,Z)=>IG({},Y,{$:Z,invert:!1,pipe:!1}),defaults:{description:(Y)=>{if(Y.children.length===0)return"unknown";if(Y.structure)return Y.structure.description;let Z=[];if(Y.basis&&!Y.refinements.some((X)=>X.impl.obviatesBasisDescription))Z.push(Y.basis.description);if(Y.refinements.length){let X=Y.refinements.toSorted((_,G)=>_.kind==="min"&&G.kind==="max"?-1:0).map((_)=>_.description);Z.push(...X)}if(Y.inner.predicate)Z.push(...Y.inner.predicate.map((X)=>X.description));return Z.join(" and ")},expected:(Y)=>` \u25E6 ${Y.errors.map((Z)=>Z.expected).join(`
|
|
30
|
+
\u25E6 `)}`,problem:(Y)=>`(${Y.actual}) must be...
|
|
31
|
+
${Y.expected}`},intersections:{intersection:(Y,Z,X)=>IG(Y.inner,Z.inner,X),...l1("intersection",(Y,Z,X)=>{if(Y.children.length===0)return Z;let{domain:_,proto:G,...W}=Y.inner,H=G??_,J=H?M0(H,Z,X):Z;return J instanceof S?J:Y?.basis?.equals(J)?Y:Y.$.node("intersection",{...W,[J.kind]:J},{prereduced:!0})})}});class BG extends C1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((Y)=>Y.isRefinement());structure=this.inner.structure;expression=l$(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(Y){return this.children.reduce((Z,X)=>X.isBasis()?X.toJsonSchemaRecurse(Y):X.reduceJsonSchema(Z,Y),{})}traverseAllows=(Y,Z)=>this.children.every((X)=>X.traverseAllows(Y,Z));traverseApply=(Y,Z)=>{let X=Z.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.refinements.length){for(let _=0;_<this.refinements.length-1;_++)if(this.refinements[_].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>X)return;if(this.refinements.at(-1).traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.structure){if(this.structure.traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.inner.predicate){for(let _=0;_<this.inner.predicate.length-1;_++)if(this.inner.predicate[_].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>X)return;this.inner.predicate.at(-1).traverseApply(Y,Z)}};compile(Y){if(Y.traversalKind==="Allows"){for(let Z of this.children)Y.check(Z);Y.return(!0);return}if(Y.initializeErrorCount(),this.basis){if(Y.check(this.basis),this.children.length>1)Y.returnIfFail()}if(this.refinements.length){for(let Z=0;Z<this.refinements.length-1;Z++)Y.check(this.refinements[Z]),Y.returnIfFailFast();if(Y.check(this.refinements.at(-1)),this.structure||this.inner.predicate)Y.returnIfFail()}if(this.structure){if(Y.check(this.structure),this.inner.predicate)Y.returnIfFail()}if(this.inner.predicate){for(let Z=0;Z<this.inner.predicate.length-1;Z++)Y.check(this.inner.predicate[Z]),Y.returnIfFail();Y.check(this.inner.predicate.at(-1))}}}var uZ={implementation:c$,Node:BG},l$=(Y)=>{let Z=Y.structure?.expression||`${Y.basis&&!Y.refinements.some((X)=>X.impl.obviatesBasisExpression)?Y.basis.nestableExpression+" ":""}${Y.refinements.map((X)=>X.expression).join(" & ")}`||"unknown";if(Z==="Array == 0")Z="[]";return Z},IG=(Y,Z,X)=>{let _={},G=Y.proto??Y.domain,W=Z.proto??Z.domain,H=G?W?M0(G,W,X):G:W;if(H instanceof S)return H;if(H)_[H.kind]=H;return Z8({kind:"intersection",baseInner:_,l:X8(Y),r:X8(Z),roots:[],ctx:X})};var i$=r({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},morphs:{parse:U4,serialize:(Y)=>Y.map((Z)=>y(Z,"root")?Z.json:K0(Z))},declaredIn:{child:!1,serialize:(Y)=>Y.json},declaredOut:{child:!1,serialize:(Y)=>Y.json}},normalize:(Y)=>Y,defaults:{description:(Y)=>`a morph from ${Y.in.description} to ${Y.out?.description??"unknown"}`},intersections:{morph:(Y,Z,X)=>{if(!Y.hasEqualMorphs(Z))return w(o$(Y.expression,Z.expression));let _=M0(Y.in,Z.in,X);if(_ instanceof S)return _;let G={morphs:Y.morphs};if(Y.declaredIn||Z.declaredIn){let W=M0(Y.in,Z.in,X);if(W instanceof S)return W.throw();else G.declaredIn=W}if(Y.declaredOut||Z.declaredOut){let W=M0(Y.out,Z.out,X);if(W instanceof S)return W.throw();else G.declaredOut=W}return _.distribute((W)=>X.$.node("morph",{...G,in:W}),X.$.parseSchema)},...l1("morph",(Y,Z,X)=>{let _=Y.inner.in?M0(Y.inner.in,Z,X):Z;return _ instanceof S?_:_.equals(Y.inner.in)?Y:X.$.node("morph",{...Y.inner,in:_})})}});class TG extends C1{serializedMorphs=this.morphs.map(K0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=y(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??B.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??B.intrinsic.unknown.internal}declareIn(Y){return this.$.node("morph",{...this.inner,declaredIn:Y})}declareOut(Y){return this.$.node("morph",{...this.inner,declaredOut:Y})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(Y){return Y.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(Y),out:this.introspectableOut?.toJsonSchemaRecurse(Y)??null})}compile(Y){if(Y.traversalKind==="Allows"){if(!this.introspectableIn)return;Y.return(Y.invoke(this.introspectableIn));return}if(this.introspectableIn)Y.line(Y.invoke(this.introspectableIn));Y.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(Y,Z)=>!this.introspectableIn||this.introspectableIn.traverseAllows(Y,Z);traverseApply=(Y,Z)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(Y,Z);Z.queueMorphs(this.morphs)};hasEqualMorphs(Y){return e1(this.morphs,Y.morphs,{isEqual:(Z,X)=>Z===X||y(Z,"root")&&y(X,"root")&&Z.equals(X)})}}var dZ={implementation:i$,Node:TG},o$=(Y,Z)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
32
|
+
Left: ${Y}
|
|
33
|
+
Right: ${Z}`;var n$=r({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Y)=>x8(Y)??B1(Y)},dateAllowsInvalid:{}},normalize:(Y)=>{let Z=typeof Y==="string"?{proto:P4[Y]}:typeof Y==="function"?V0(Y)?Y:{proto:Y}:typeof Y.proto==="string"?{...Y,proto:P4[Y.proto]}:Y;if(typeof Z.proto!=="function")w(t8.writeInvalidSchemaMessage(Z.proto));if(n4(Z,"dateAllowsInvalid")&&Z.proto!==Date)w(t8.writeBadInvalidDateMessage(Z.proto));return Z},applyConfig:(Y,Z)=>{if(Y.dateAllowsInvalid===void 0&&Y.proto===Date&&Z.dateAllowsInvalid)return{...Y,dateAllowsInvalid:!0};return Y},defaults:{description:(Y)=>Y.builtinName?w_[Y.builtinName]:`an instance of ${Y.proto.name}`,actual:(Y)=>Y instanceof Date&&Y.toString()==="Invalid Date"?"an invalid Date":v8(Y)},intersections:{proto:(Y,Z)=>Y.proto===Date&&Z.proto===Date?Y.dateAllowsInvalid?Z:Y:UZ(Y.proto,Z.proto)?Y:UZ(Z.proto,Y.proto)?Z:S.init("proto",Y,Z),domain:(Y,Z)=>Z.domain==="object"?Y:S.init("domain",B.intrinsic.object.internal,Z)}});class CG extends x4{builtinName=x8(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(Y)=>Y instanceof Date&&Y.toString()!=="Invalid Date":(Y)=>Y instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(Y){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return Y.fallback.date?.({code:"date",base:{}})??Y.fallback.proto({code:"proto",base:{},proto:this.proto});default:return Y.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var t8={implementation:n$,Node:CG,writeBadInvalidDateMessage:(Y)=>`dateAllowsInvalid may only be specified with constructor Date (was ${Y.name})`,writeInvalidSchemaMessage:(Y)=>`instanceOf operand must be a function (was ${g0(Y)})`};var r$=r({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Y,Z)=>{let X=[];for(let _ of Y){let G=y(_,"root")?_.branches:Z.$.parseSchema(_).branches;for(let W of G)if(W.hasKind("morph")){let H=X.findIndex((J)=>J.hasKind("morph")&&J.hasEqualMorphs(W));if(H===-1)X.push(W);else{let J=X[H];X[H]=Z.$.node("morph",{...J.inner,in:J.in.rawOr(W.in)})}}else X.push(W)}if(!Z.def.ordered)X.sort((_,G)=>_.hash<G.hash?-1:1);return X}}},normalize:(Y)=>O0(Y)?{branches:Y}:Y,reduce:(Y,Z)=>{let X=WQ(Y);if(X.length===1)return X[0];if(X.length===Y.branches.length)return;return Z.node("union",{...Y,branches:X},{prereduced:!0})},defaults:{description:(Y)=>Y.distribute((Z)=>Z.description,H8),expected:(Y)=>{let Z=U_(Y.errors,"propString"),X=Object.entries(Z).map(([_,G])=>{let W=[];for(let Q of G)d1(W,Q.expected);let H=H8(W),J=G.every((Q)=>Q.actual===G[0].actual)?G[0].actual:n(G[0].data);return`${_&&`${_} `}must be ${H}${J&&` (was ${J})`}`});return H8(X)},problem:(Y)=>Y.expected,message:(Y)=>Y.problem},intersections:{union:(Y,Z,X)=>{if(Y.isNever!==Z.isNever)return S.init("presence",Y,Z);let _;if(Y.ordered){if(Z.ordered)w(JQ(Y.expression,Z.expression));if(_=cZ(Z.branches,Y.branches,X),_ instanceof S)_.invert()}else _=cZ(Y.branches,Z.branches,X);if(_ instanceof S)return _;return X.$.parseSchema(Y.ordered||Z.ordered?{branches:_,ordered:!0}:{branches:_})},...l1("union",(Y,Z,X)=>{let _=cZ(Y.branches,[Z],X);if(_ instanceof S)return _;if(_.length===1)return _[0];return X.$.parseSchema(Y.ordered?{branches:_,ordered:!0}:{branches:_})})}});class jG extends C1{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let Y=[],Z=-1;for(let X of this.branches){if(X.hasKind("unit")&&X.domain==="boolean"){if(Z===-1)Z=Y.length,Y.push(X);else Y[Z]=B.intrinsic.boolean;continue}Y.push(X)}return Y}unitBranches=this.branches.filter((Y)=>Y.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?XQ(this.discriminant):null;expression=this.distribute((Y)=>Y.nestableExpression,GQ);createBranchedOptimisticRootApply(){return(Y,Z)=>{let X=this.traverseOptimistic(Y);if(X!==A1)return X;let _=new f1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)}}get shallowMorphs(){return this.branches.reduce((Y,Z)=>d1(Y,Z.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Y)=>Y.defaultShortDescription,H8)}innerToJsonSchema(Y){if(this.branchGroups.length===1&&this.branchGroups[0].equals(B.intrinsic.boolean))return{type:"boolean"};let Z=this.branchGroups.map((X)=>X.toJsonSchemaRecurse(Y));if(Z.every((X)=>Object.keys(X).length===1&&n4(X,"const")))return{enum:Z.map((X)=>X.const)};return{anyOf:Z}}traverseAllows=(Y,Z)=>this.branches.some((X)=>X.traverseAllows(Y,Z));traverseApply=(Y,Z)=>{let X=[];for(let _=0;_<this.branches.length;_++){if(Z.pushBranch(),this.branches[_].traverseApply(Y,Z),!Z.hasError()){if(this.branches[_].includesTransform)return Z.queuedMorphs.push(...Z.popBranch().queuedMorphs);return Z.popBranch()}X.push(Z.popBranch().error)}Z.errorFromNodeContext({code:"union",errors:X,meta:this.meta})};traverseOptimistic=(Y)=>{for(let Z=0;Z<this.branches.length;Z++){let X=this.branches[Z];if(X.traverseAllows(Y)){if(X.contextFreeMorph)return X.contextFreeMorph(Y);return Y}}return A1};compile(Y){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(Y);let Z=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")Z=`typeof ${Z} === "object" ? ${Z} === null ? "null" : "object" : typeof ${Z} === "function" ? "object" : typeof ${Z}`;let X=this.discriminant.cases,_=Object.keys(X),{optimistic:G}=Y;if(Y.optimistic=!1,Y.block(`switch(${Z})`,()=>{for(let $ in X){let z=X[$],O=$==="default"?$:`case ${$}`;Y.line(`${O}: return ${z===!0?G?Y.data:z:G?`${Y.invoke(z)} ? ${z.contextFreeMorph?`${K0(z.contextFreeMorph)}(${Y.data})`:Y.data} : "${A1}"`:Y.invoke(z)}`)}return Y}),Y.traversalKind==="Allows"){Y.return(G?`"${A1}"`:!1);return}let W=H8(this.discriminant.kind==="domain"?_.map(($)=>{let z=$.slice(1,-1);return z==="function"?Q1.object:Q1[z]}):_),H=this.discriminant.path.map(($)=>typeof $==="symbol"?K0($):JSON.stringify($)),J=JSON.stringify(W),Q=this.discriminant.kind==="domain"?`${YQ}[${Z}]`:`${ZQ}(${Z})`;Y.line(`ctx.errorFromNodeContext({
|
|
34
34
|
code: "predicate",
|
|
35
|
-
expected: ${
|
|
36
|
-
actual: ${
|
|
37
|
-
relativePath: [${
|
|
35
|
+
expected: ${J},
|
|
36
|
+
actual: ${Q},
|
|
37
|
+
relativePath: [${H}],
|
|
38
38
|
meta: ${this.compiledMeta}
|
|
39
|
-
})`)}compileIndiscriminable(
|
|
40
|
-
Left: ${
|
|
41
|
-
Right: ${
|
|
42
|
-
Left: ${
|
|
43
|
-
Right: ${_}`;var qH=l({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(T)=>T instanceof Date?T.toISOString():E_(T)}},normalize:(T)=>T,defaults:{description:(T)=>d(T.unit),problem:({expected:T,actual:_})=>`${T===_?`must be reference equal to ${T} (serialized to the same value)`:`must be ${T} (was ${_})`}`},intersections:{unit:(T,_)=>N.init("unit",T,_),...p_("unit",(T,_)=>{if(_.allows(T.unit))return T;let F=_.hasKind("intersection")?_.basis:_;if(F){let W=F.hasKind("domain")?F:z.intrinsic.object;if(T.domain!==W.domain){let J=T.domain==="undefined"||T.domain==="null"||T.domain==="boolean"?T.domain:z.intrinsic[T.domain];return N.init("domain",J,W)}}return N.init("assignability",T,_.hasKind("intersection")?_.children.find((W)=>!W.allows(T.unit)):_)})}});class X6 extends B0{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=Z6(this.unit,this.serializedValue);compiledNegation=Z6(this.unit,this.serializedValue,"negated");expression=d(this.unit);domain=PT(this.unit);get defaultShortDescription(){return this.domain==="object"?__.object:this.description}innerToJsonSchema(T){return this.unit===null?{type:"null"}:z.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:T.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(T)=>T instanceof Date&&T.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(T)=>Number.isNaN(T):(T)=>T===this.unit}var x4={implementation:qH,Node:X6},Z6=(T,_,F)=>{if(T instanceof Date){let W=`data instanceof Date && data.toISOString() === ${_}`;return F?`!(${W})`:W}if(Number.isNaN(T))return`${F?"!":""}Number.isNaN(data)`;return`data ${F?"!":"="}== ${_}`};var jH=l({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(T,_)=>{let F=_.$.parseSchema(T);if(!F.extends(z.intrinsic.key))return E(vH(F.expression));let W=F.branches.filter((J)=>J.hasKind("unit"));if(W.length)return E(yH(W.map((J)=>d(J.unit))));return F}},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`[${T.signature.expression}]: ${T.value.description}`},intersections:{index:(T,_,F)=>{if(T.signature.equals(_.signature)){let W=UT(T.value,_.value,F),J=W instanceof N?z.intrinsic.never.internal:W;return F.$.node("index",{signature:T.signature,value:J})}if(T.signature.extends(_.signature)&&T.value.subsumes(_.value))return _;if(_.signature.extends(T.signature)&&_.value.subsumes(T.value))return T;return null}}});class G6 extends z_{impliedBasis=z.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=s(this.value.flatRefs.map((T)=>P_([this.signature,...T.path],T.node)),P_([this.signature],this.value));traverseAllows=(T,_)=>S0(T).every((F)=>{if(this.signature.traverseAllows(F[0],_))return W_(F[0],()=>this.value.traverseAllows(F[1],_),_);return!0});traverseApply=(T,_)=>{for(let F of S0(T))if(this.signature.traverseAllows(F[0],_))W_(F[0],()=>this.value.traverseApply(F[1],_),_)};_transform(T,_){_.path.push(this.signature);let F=super._transform(T,_);return _.path.pop(),F}compile(){}}var b4={implementation:jH,Node:G6},yH=(T)=>`Index keys ${T.join(", ")} should be specified as named props.`,vH=(T)=>`Indexed key definition '${T}' must be a string or symbol`;var xH=l({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`${T.compiledKey}: ${T.value.description}`,expected:(T)=>T.missingValueDescription,actual:()=>"missing"},intersections:{required:vF,optional:vF}});class A6 extends xF{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=Z0(this.errorContext)}var h4={implementation:xH,Node:A6};var bH=l({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}},optionals:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}},defaultables:{child:(T)=>T.map((_)=>_[0]),parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>{let W=_.$.parseSchema(F[0]);return hF(W,F[1],null),[W,F[1]]})},serialize:(T)=>T.map((_)=>[_[0].collapsibleJson,E_(_[1])])},variadic:{child:!0,parse:(T,_)=>_.$.parseSchema(T,_)},minVariadicLength:{parse:(T)=>T===0?void 0:T},postfix:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}}},normalize:(T)=>{if(typeof T==="string")return{variadic:T};if("variadic"in T||"prefix"in T||"defaultables"in T||"optionals"in T||"postfix"in T||"minVariadicLength"in T){if(T.postfix?.length){if(!T.variadic)return E(mH);if(T.optionals?.length||T.defaultables?.length)return E(g4)}if(T.minVariadicLength&&!T.variadic)return E("minVariadicLength may not be specified without a variadic element");return T}return{variadic:T}},reduce:(T,_)=>{let F=T.minVariadicLength??0,W=T.prefix?.slice()??[],J=T.defaultables?.slice()??[],Y=T.optionals?.slice()??[],$=T.postfix?.slice()??[];if(T.variadic){while(Y.at(-1)?.equals(T.variadic))Y.pop();if(Y.length===0&&J.length===0)while(W.at(-1)?.equals(T.variadic))W.pop(),F++;while($[0]?.equals(T.variadic))$.shift(),F++}else if(Y.length===0&&J.length===0)W.push(...$.splice(0));if(F!==T.minVariadicLength||T.prefix&&T.prefix.length!==W.length)return _.node("sequence",{...T,prefix:W,defaultables:J,optionals:Y,postfix:$,minVariadicLength:F},{prereduced:!0})},defaults:{description:(T)=>{if(T.isVariadicOnly)return`${T.variadic.nestableExpression}[]`;return`[${T.tuple.map((F)=>F.kind==="defaultables"?`${F.node.nestableExpression} = ${d(F.default)}`:F.kind==="optionals"?`${F.node.nestableExpression}?`:F.kind==="variadic"?`...${F.node.nestableExpression}[]`:F.node.expression).join(", ")}]`}},intersections:{sequence:(T,_,F)=>{let W=oF({l:T.tuple,r:_.tuple,disjoint:new N,result:[],fixedVariants:[],ctx:F}),J=W.disjoint.length===0?[W,...W.fixedVariants]:W.fixedVariants;return J.length===0?W.disjoint:J.length===1?F.$.node("sequence",H6(J[0].result)):F.$.node("union",J.map((Y)=>({proto:Array,sequence:H6(Y.result)})))}}});class O6 extends z_{impliedBasis=z.intrinsic.Array.internal;tuple=gH(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((T)=>{if(T.kind==="defaultables"||T.kind==="optionals")return this.defaultablesAndOptionals.push(T.node),!0;return T.kind==="prefix"});variadicOrPostfix=c_(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return U4(this.flatRefs,this.prevariadic.flatMap((T,_)=>s(T.node.flatRefs.map((F)=>P_([`${_}`,...F.path],F.node)),P_([`${_}`],T.node)))),U4(this.flatRefs,this.variadicOrPostfix.flatMap((T)=>s(T.flatRefs.map((_)=>P_([z.intrinsic.nonNegativeIntegerString.internal,..._.path],_.node)),P_([z.intrinsic.nonNegativeIntegerString.internal],T)))),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=pH(this);defaultValueMorphsReference=this.defaultValueMorphs.length?VT(this.defaultValueMorphs):void 0;elementAtIndex(T,_){if(_<this.prevariadic.length)return this.tuple[_];let F=T.length-this.postfixLength;if(_>=F)return{kind:"postfix",node:this.postfix[_-F]};return{kind:"variadic",node:this.variadic??e(`Unexpected attempt to access index ${_} on ${this}`)}}traverseAllows=(T,_)=>{for(let F=0;F<T.length;F++)if(!this.elementAtIndex(T,F).node.traverseAllows(T[F],_))return!1;return!0};traverseApply=(T,_)=>{let F=0;for(;F<T.length;F++)W_(F,()=>this.elementAtIndex(T,F).node.traverseApply(T[F],_),_)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(T){if(this.prefix)for(let[_,F]of this.prefix.entries())T.traverseKey(`${_}`,`data[${_}]`,F);for(let[_,F]of this.defaultablesAndOptionals.entries()){let W=`${_+this.prefixLength}`;T.if(`${W} >= ${T.data}.length`,()=>T.traversalKind==="Allows"?T.return(!0):T.return()),T.traverseKey(W,`data[${W}]`,F)}if(this.variadic){if(this.postfix)T.const("firstPostfixIndex",`${T.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(T.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>T.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[_,F]of this.postfix.entries()){let W=`firstPostfixIndex + ${_}`;T.traverseKey(W,`data[${W}]`,F)}}if(T.traversalKind==="Allows")T.return(!0)}_transform(T,_){_.path.push(z.intrinsic.nonNegativeIntegerString.internal);let F=super._transform(T,_);return _.path.pop(),F}expression=this.description;reduceJsonSchema(T,_){if(this.prevariadic.length)T.prefixItems=this.prevariadic.map((F)=>{let W=F.node.toJsonSchemaRecurse(_);if(F.kind==="defaultables"){let J=typeof F.default==="function"?F.default():F.default;W.default=z.intrinsic.jsonData.allows(J)?J:_.fallback.defaultValue({code:"defaultValue",base:W,value:J})}return W});if(this.minLength)T.minItems=this.minLength;if(this.variadic){let F=Object.assign(T,{items:this.variadic.toJsonSchemaRecurse(_)});if(this.maxLength)F.maxItems=this.maxLength;if(this.postfix){let W=this.postfix.map((J)=>J.toJsonSchemaRecurse(_));T=_.fallback.arrayPostfix({code:"arrayPostfix",base:F,elements:W})}}else T.items=!1,delete T.maxItems;return T}}var hH={},pH=(T)=>{if(!T.defaultables)return[];let _=[],F="[",W=T.prefixLength+T.defaultablesLength-1;for(let J=T.prefixLength;J<=W;J++){let[Y,$]=T.defaultables[J-T.prefixLength];_.push(P4(J,Y,$)),F+=`${J}: ${Y.id} = ${E_($)}, `}return F+="]",hH[F]??=_},p4={implementation:bH,Node:O6},gH=(T)=>{let _=[];if(T.prefix)for(let F of T.prefix)_.push({kind:"prefix",node:F});if(T.defaultables)for(let[F,W]of T.defaultables)_.push({kind:"defaultables",node:F,default:W});if(T.optionals)for(let F of T.optionals)_.push({kind:"optionals",node:F});if(T.variadic)_.push({kind:"variadic",node:T.variadic});if(T.postfix)for(let F of T.postfix)_.push({kind:"postfix",node:F});return _},H6=(T)=>T.reduce((_,F)=>{if(F.kind==="variadic")_.variadic=F.node;else if(F.kind==="defaultables")_.defaultables=s(_.defaultables,[[F.node,F.default]]);else _[F.kind]=s(_[F.kind],F.node);return _},{}),g4="A postfix required element cannot follow an optional or defaultable element",mH="A postfix element requires a variadic element",oF=(T)=>{let[_,...F]=T.l,[W,...J]=T.r;if(!_||!W)return T;let Y=F.at(-1)?.kind==="postfix",$=J.at(-1)?.kind==="postfix",Z=_.kind==="prefix"||W.kind==="prefix"?"prefix":_.kind==="postfix"||W.kind==="postfix"?"postfix":_.kind==="variadic"&&W.kind==="variadic"?"variadic":Y||$?"prefix":_.kind==="defaultables"||W.kind==="defaultables"?"defaultables":"optionals";if(_.kind==="prefix"&&W.kind==="variadic"&&$){let M=oF({...T,fixedVariants:[],r:J.map((Q)=>({...Q,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}else if(W.kind==="prefix"&&_.kind==="variadic"&&Y){let M=oF({...T,fixedVariants:[],l:F.map((Q)=>({...Q,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}let G=UT(_.node,W.node,T.ctx);if(G instanceof N)if(Z==="prefix"||Z==="postfix")T.disjoint.push(...G.withPrefixKey(Z==="prefix"?T.result.length:`-${F.length+1}`,"required")),T.result=[...T.result,{kind:Z,node:z.intrinsic.never.internal}];else if(Z==="optionals"||Z==="defaultables")return T;else return oF({...T,fixedVariants:[],l:F.map((M)=>({...M,kind:"prefix"})),r:F.map((M)=>({...M,kind:"prefix"}))});else if(Z==="defaultables"){if(_.kind==="defaultables"&&W.kind==="defaultables"&&_.default!==W.default)E(f4(_.default,W.default));T.result=[...T.result,{kind:Z,node:G,default:_.kind==="defaultables"?_.default:W.kind==="defaultables"?W.default:e(`Unexpected defaultable intersection from ${_.kind} and ${W.kind} elements.`)}]}else T.result=[...T.result,{kind:Z,node:G}];let X=T.l.length,O=T.r.length;if(_.kind!=="variadic"||X>=O&&(W.kind==="variadic"||O===1))T.l=F;if(W.kind!=="variadic"||O>=X&&(_.kind==="variadic"||X===1))T.r=J;return oF(T)};var w6=(T)=>(_)=>{if(_.props.length||_.index){let F=_.index?.map((J)=>J[T])??[];for(let J of _.props)F.push(J[T]);if(_.undeclared)F.push(`+ (undeclared): ${_.undeclared}`);let W=`{ ${F.join(", ")} }`;return _.sequence?`${W} & ${_.sequence.description}`:W}return _.sequence?.description??"{}"},oH=w6("description"),uH=w6("expression"),U6=(T,_,F)=>{let W=T.required?"required":"optional";if(!_.signature.allows(T.key))return null;let J=J_(T.value,_.value,F);if(J instanceof N)return W==="optional"?F.node("optional",{key:T.key,value:z.intrinsic.never.internal}):J.withPrefixKey(T.key,T.kind);return null},cH=l({kind:"structure",hasAssociatedError:!1,normalize:(T)=>T,applyConfig:(T,_)=>{if(!T.undeclared&&_.onUndeclaredKey!=="ignore")return{...T,undeclared:_.onUndeclaredKey};return T},keys:{required:{child:!0,parse:cT("required"),reduceIo:(T,_,F)=>{_.required=s(_.required,F.map((W)=>W[T]));return}},optional:{child:!0,parse:cT("optional"),reduceIo:(T,_,F)=>{if(T==="in"){_.optional=F.map((W)=>W.in);return}for(let W of F)_[W.outProp.kind]=s(_[W.outProp.kind],W.outProp.out)}},index:{child:!0,parse:cT("index")},sequence:{child:!0,parse:cT("sequence")},undeclared:{parse:(T)=>T==="ignore"?void 0:T,reduceIo:(T,_,F)=>{if(F!=="delete")return;if(T==="in")delete _.undeclared;else _.undeclared="reject"}}},defaults:{description:oH},intersections:{structure:(T,_,F)=>{let W={...T.inner},J={..._.inner},Y=new N;if(T.undeclared){let G=T.keyof();for(let X of _.requiredKeys)if(!G.allows(X))Y.add("presence",z.intrinsic.never.internal,_.propsByKey[X].value,{path:[X]});if(J.optional)J.optional=J.optional.filter((X)=>G.allows(X.key));if(J.index)J.index=J.index.flatMap((X)=>{if(X.signature.extends(G))return X;let O=J_(G,X.signature,F.$);if(O instanceof N)return[];let M=mW(O,X.value,F.$);if(M.required)J.required=c_(J.required,M.required);if(M.optional)J.optional=c_(J.optional,M.optional);return M.index??[]})}if(_.undeclared){let G=_.keyof();for(let X of T.requiredKeys)if(!G.allows(X))Y.add("presence",T.propsByKey[X].value,z.intrinsic.never.internal,{path:[X]});if(W.optional)W.optional=W.optional.filter((X)=>G.allows(X.key));if(W.index)W.index=W.index.flatMap((X)=>{if(X.signature.extends(G))return X;let O=J_(G,X.signature,F.$);if(O instanceof N)return[];let M=mW(O,X.value,F.$);if(M.required)W.required=c_(W.required,M.required);if(M.optional)W.optional=c_(W.optional,M.optional);return M.index??[]})}let $={};if(T.undeclared||_.undeclared)$.undeclared=T.undeclared==="reject"||_.undeclared==="reject"?"reject":"delete";let Z=t0({kind:"structure",baseInner:$,l:i0(W),r:i0(J),roots:[],ctx:F});if(Z instanceof N)Y.push(...Z);if(Y.length)return Y;return Z}},reduce:(T,_)=>{if(T.index){if(!(T.required||T.optional))return;let F=!1,W=T.required??[],J=T.optional??[],Y=[...J];for(let $ of T.index){for(let Z of W){let G=U6(Z,$,_);if(G instanceof N)return G}for(let[Z,G]of J.entries()){let X=U6(G,$,_);if(X instanceof N)return X;if(X===null)continue;Y[Z]=X,F=!0}}if(F)return _.node("structure",{...T,optional:Y},{prereduced:!0})}}});class Q6 extends z_{impliedBasis=z.intrinsic.object.internal;impliedSiblings=this.children.flatMap((T)=>T.impliedSiblings??[]);props=c_(this.required,this.optional);propsByKey=c(this.props,(T,_)=>[_.key,_]);propsByKeyReference=VT(this.propsByKey);expression=uH(this);requiredKeys=this.required?.map((T)=>T.key)??[];optionalKeys=this.optional?.map((T)=>T.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:_}of this.index)T=T.concat(_.branches);return this._keyof=this.$.node("union",T)}map(T){return this.$.node("structure",this.props.flatMap(T).reduce((_,F)=>{let W=this.propsByKey[F.key];if(OT(F)){if(F.kind!=="required"&&F.kind!=="optional")return E(`Map result must have kind "required" or "optional" (was ${F.kind})`);return _[F.kind]=s(_[F.kind],F),_}let J=F.kind??W?.kind??"required",Y=c(F,($,Z)=>($ in bF.implementation.keys)?[$,Z]:[]);return _[J]=s(_[J],this.$.node(J,Y)),_},{}))}assertHasKeys(T){let _=T.filter((F)=>!pF(F,this.keyof()));if(_.length)return E(M6(this.expression,_))}get(T,..._){let F,W=!1,J=iH(T);if((typeof J==="string"||typeof J==="symbol")&&this.propsByKey[J])F=this.propsByKey[J].value,W=this.propsByKey[J].required;if(this.index){for(let $ of this.index)if(pF(J,$.signature))F=F?.and($.value)??$.value}if(this.sequence&&pF(J,z.intrinsic.nonNegativeIntegerString))if(P(J,"root")){if(this.sequence.variadic)F=F?.and(this.sequence.element)??this.sequence.element}else{let $=Number.parseInt(J);if($<this.sequence.prevariadic.length){let Z=this.sequence.prevariadic[$].node;F=F?.and(Z)??Z,W||=$<this.sequence.prefixLength}else if(this.sequence.variadic){let Z=this.$.node("union",this.sequence.variadicOrPostfix);F=F?.and(Z)??Z}}if(!F){if(this.sequence?.variadic&&P(J,"root")&&J.extends(z.intrinsic.number))return E(nH(J.expression,this.sequence.expression));return E(M6(this.expression,[J]))}let Y=F.get(..._);return W?Y:Y.or(z.intrinsic.undefined)}pick(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("pick",T))}omit(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("omit",T))}optionalize(){let{required:T,..._}=this.inner;return this.$.node("structure",{..._,optional:this.props.map((F)=>F.hasKind("required")?this.$.node("optional",F.inner):F)})}require(){let{optional:T,..._}=this.inner;return this.$.node("structure",{..._,required:this.props.map((F)=>F.hasKind("optional")?{key:F.key,value:F.value}:F)})}merge(T){let _=this.filterKeys("omit",[T.keyof()]);if(T.required)_.required=s(_.required,T.required);if(T.optional)_.optional=s(_.optional,T.optional);if(T.index)_.index=s(_.index,T.index);if(T.sequence)_.sequence=T.sequence;if(T.undeclared)_.undeclared=T.undeclared;else delete _.undeclared;return this.$.node("structure",_)}filterKeys(T,_){let F=fW(this.inner),W=(J)=>{let Y=_.some(($)=>pF(J,$));return T==="pick"?Y:!Y};if(F.required)F.required=F.required.filter((J)=>W(J.key));if(F.optional)F.optional=F.optional.filter((J)=>W(J.key));if(F.index)F.index=F.index.filter((J)=>W(J.signature));return F}traverseAllows=(T,_)=>this._traverse("Allows",T,_);traverseApply=(T,_)=>this._traverse("Apply",T,_);_traverse=(T,_,F)=>{let W=F?.currentErrorCount??0;for(let J=0;J<this.props.length;J++)if(T==="Allows"){if(!this.props[J].traverseAllows(_,F))return!1}else if(this.props[J].traverseApply(_,F),F.failFast&&F.currentErrorCount>W)return!1;if(this.sequence){if(T==="Allows"){if(!this.sequence.traverseAllows(_,F))return!1}else if(this.sequence.traverseApply(_,F),F.failFast&&F.currentErrorCount>W)return!1}if(this.index||this.undeclared==="reject"){let J=Object.keys(_);J.push(...Object.getOwnPropertySymbols(_));for(let Y=0;Y<J.length;Y++){let $=J[Y];if(this.index){for(let Z of this.index)if(Z.signature.traverseAllows($,F)){if(T==="Allows"){if(!W_($,()=>Z.value.traverseAllows(_[$],F),F))return!1}else if(W_($,()=>Z.value.traverseApply(_[$],F),F),F.failFast&&F.currentErrorCount>W)return!1}}if(this.undeclared==="reject"&&!this.declaresKey($)){if(T==="Allows")return!1;if(F.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[$],meta:this.meta}),F.failFast)return!1}}}if(this.structuralMorph&&F&&!F.hasError())F.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((T)=>T.hasDefault())??[])}declaresKey=(T)=>(T in this.propsByKey)||this.index?.some((_)=>_.signature.allows(T))||this.sequence!==void 0&&z.intrinsic.nonNegativeIntegerString.allows(T);_compileDeclaresKey(T){let _=[];if(this.props.length)_.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let F of this.index)_.push(T.invoke(F.signature,{kind:"Allows",arg:"k"}));if(this.sequence)_.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return _.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",lH(this))}structuralMorphRef=this.structuralMorph&&VT(this.structuralMorph);compile(T){if(T.traversalKind==="Apply")T.initializeErrorCount();for(let _ of this.props)if(T.check(_),T.traversalKind==="Apply")T.returnIfFailFast();if(this.sequence){if(T.check(this.sequence),T.traversalKind==="Apply")T.returnIfFailFast()}if(this.index||this.undeclared==="reject")T.const("keys","Object.keys(data)"),T.line("keys.push(...Object.getOwnPropertySymbols(data))"),T.for("i < keys.length",()=>this.compileExhaustiveEntry(T));if(T.traversalKind==="Allows")return T.return(!0);if(this.structuralMorphRef)T.if("ctx && !ctx.hasError()",()=>{return T.line("ctx.queueMorphs(["),tH(T,this),T.line("])")})}compileExhaustiveEntry(T){if(T.const("k","keys[i]"),this.index)for(let _ of this.index)T.if(`${T.invoke(_.signature,{arg:"k",kind:"Allows"})}`,()=>T.traverseKey("k","data[k]",_.value));if(this.undeclared==="reject")T.if(`!(${this._compileDeclaresKey(T)})`,()=>{if(T.traversalKind==="Allows")return T.return(!1);return T.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>T.return())});return T}reduceJsonSchema(T,_){switch(T.type){case"object":return this.reduceObjectJsonSchema(T,_);case"array":let F=this.sequence?.reduceJsonSchema(T,_)??T;if(this.props.length||this.index)return _.fallback.arrayObject({code:"arrayObject",base:F,object:this.reduceObjectJsonSchema({type:"object"},_)});return F;default:return RT.throwInternalOperandError("structure",T)}}reduceObjectJsonSchema(T,_){if(this.props.length){T.properties={};for(let F of this.props){let W=F.value.toJsonSchemaRecurse(_);if(typeof F.key==="symbol"){_.fallback.symbolKey({code:"symbolKey",base:T,key:F.key,value:W,optional:F.optional});continue}if(F.hasDefault()){let J=typeof F.default==="function"?F.default():F.default;W.default=z.intrinsic.jsonData.allows(J)?J:_.fallback.defaultValue({code:"defaultValue",base:W,value:J})}T.properties[F.key]=W}if(this.requiredKeys.length&&T.properties)T.required=this.requiredKeys.filter((F)=>typeof F==="string"&&(F in T.properties))}if(this.index)for(let F of this.index){let W=F.value.toJsonSchemaRecurse(_);if(F.signature.equals(z.intrinsic.string)){T.additionalProperties=W;continue}for(let J of F.signature.branches){if(!J.extends(z.intrinsic.string)){T=_.fallback.symbolKey({code:"symbolKey",base:T,key:null,value:W,optional:!1});continue}let Y={type:"string"};if(J.hasKind("morph"))Y=_.fallback.morph({code:"morph",base:J.in.toJsonSchemaRecurse(_),out:J.out.toJsonSchemaRecurse(_)});if(!J.hasKind("intersection"))return e(`Unexpected index branch kind ${J.kind}.`);let{pattern:$}=J.inner;if($){let Z=Object.assign(Y,{pattern:$[0].rule});for(let G=1;G<$.length;G++)Y=_.fallback.patternIntersection({code:"patternIntersection",base:Z,pattern:$[G].rule});T.patternProperties??={},T.patternProperties[Z.pattern]=W}}}if(this.undeclared&&!T.additionalProperties)T.additionalProperties=!1;return T}}var m4={},dH=(T)=>{let _="";for(let F=0;F<T.defaultable.length;F++)_+=T.defaultable[F].defaultValueMorphRef;if(T.sequence?.defaultValueMorphsReference)_+=T.sequence?.defaultValueMorphsReference;if(T.undeclared==="delete"){if(_+="delete !(",T.required)for(let F of T.required)_+=F.compiledKey+" | ";if(T.optional)for(let F of T.optional)_+=F.compiledKey+" | ";if(T.index)for(let F of T.index)_+=F.signature.id+" | ";if(T.sequence)if(T.sequence.maxLength===null)_+=x.nonNegativeIntegerString.id;else for(let F=0;F<T.sequence.tuple.length;F++)_+=F+" | ";_+=")"}return _},lH=(T)=>{let _=dH(T);if(!_)return;if(m4[_])return m4[_];let F=(W,J)=>{for(let Y=0;Y<T.defaultable.length;Y++)if(!(T.defaultable[Y].key in W))T.defaultable[Y].defaultValueMorph(W,J);if(T.sequence?.defaultables)for(let Y=W.length-T.sequence.prefixLength;Y<T.sequence.defaultables.length;Y++)T.sequence.defaultValueMorphs[Y](W,J);if(T.undeclared==="delete"){for(let Y in W)if(!T.declaresKey(Y))delete W[Y]}return W};return m4[_]=F},tH=(T,_)=>{let W=`(data${_.defaultable.some((J)=>J.defaultValueMorph.length===2)||_.sequence?.defaultValueMorphs.some((J)=>J.length===2)?", ctx":""})`;return T.block(`${W} => `,(J)=>{for(let Y=0;Y<_.defaultable.length;Y++){let{serializedKey:$,defaultValueMorphRef:Z}=_.defaultable[Y];J.if(`!(${$} in data)`,(G)=>G.line(`${Z}${W}`))}if(_.sequence?.defaultables)J.for(`i < ${_.sequence.defaultables.length}`,(Y)=>Y.set("data[i]",5),`data.length - ${_.sequence.prefixLength}`);if(_.undeclared==="delete")J.forIn("data",(Y)=>Y.if(`!(${_._compileDeclaresKey(Y)})`,($)=>$.line("delete data[k]")));return J.return("data")})},o4={implementation:cH,Node:Q6},iH=(T)=>{if(P(T,"root")&&T.hasKind("unit"))T=T.unit;if(typeof T==="number")T=`${T}`;return T},nH=(T,_)=>`${T} is not allowed as an array index on ${_}. Use the 'nonNegativeIntegerString' keyword instead.`,mW=(T,_,F)=>{let[W,J]=p8(T.branches,($)=>$.hasKind("unit"));if(!W.length)return{index:F.node("index",{signature:T,value:_})};let Y={};for(let $ of W){let Z=F.node("required",{key:$.unit,value:_});Y[Z.kind]=s(Y[Z.kind],Z)}if(J.length)Y.index=F.node("index",{signature:J,value:_});return Y},rH=(T)=>P(T,"root")?T.expression:d(T),M6=(T,_)=>`Key${_.length===1?"":"s"} ${_.map(rH).join(", ")} ${_.length===1?"does":"do"} not exist on ${T}`;var r0={...gJ,alias:gF.implementation,domain:gW.implementation,unit:x4.implementation,proto:mF.implementation,union:v4.implementation,morph:j4.implementation,intersection:q4.implementation,divisor:E4.implementation,pattern:N4.implementation,predicate:R4.implementation,required:h4.implementation,optional:bF.implementation,index:b4.implementation,sequence:p4.implementation,structure:o4.implementation};z.defaultConfig=i8(Object.assign(c(r0,(T,_)=>[T,_.defaults]),{jitless:TJ(),clone:s8,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:RT.defaultConfig}));z.resolvedConfig=fF(z.defaultConfig,z.config);var lJ={...mJ,alias:gF.Node,domain:gW.Node,unit:x4.Node,proto:mF.Node,union:v4.Node,morph:j4.Node,intersection:q4.Node,divisor:E4.Node,pattern:N4.Node,predicate:R4.Node,required:h4.Node,optional:bF.Node,index:b4.Node,sequence:p4.Node,structure:o4.Node};class e0 extends a1{get[iT](){return"module"}}var u4=(T,_)=>new e0(c(T,(F,W)=>[F,P(W,"module")?u4(W,_):_.bindReference(W)]));var sH=(T)=>XT(T)?T:("branches"in T)&&XT(T.branches)?T.branches:void 0,aH=(T,_)=>E(`Node of kind ${_} is not valid as a ${T} definition`),R6=(T)=>`#${T} duplicates public alias ${T}`,c4={};z.ambient??={};var E6,K6="function $",eH=(T)=>V6(T,L6(T)),V6=(T,_)=>{let F=_.write(K6,4),W=_.compile()();for(let J of T){if(J.precompilation)continue;if(J.traverseAllows=W[`${J.id}Allows`].bind(W),J.isRoot()&&!J.allowsRequiresContext)J.allows=J.traverseAllows;if(J.traverseApply=W[`${J.id}Apply`].bind(W),W[`${J.id}Optimistic`])J.traverseOptimistic=W[`${J.id}Optimistic`].bind(W);J.precompilation=F}},L6=(T)=>new kW().return(T.reduce((_,F)=>{let W=new kF({kind:"Allows"}).indent();F.compile(W);let J=W.write(`${F.id}Allows`),Y=new kF({kind:"Apply"}).indent();F.compile(Y);let $=Y.write(`${F.id}Apply`),Z=`${_}${J},
|
|
44
|
-
${
|
|
45
|
-
`;if(!
|
|
39
|
+
})`)}compileIndiscriminable(Y){if(Y.traversalKind==="Apply"){Y.const("errors","[]");for(let Z of this.branches)Y.line("ctx.pushBranch()").line(Y.invoke(Z)).if("!ctx.hasError()",()=>Y.return(Z.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Y.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:Z}=Y;Y.optimistic=!1;for(let X of this.branches)Y.if(`${Y.invoke(X)}`,()=>Y.return(Z?X.contextFreeMorph?`${K0(X.contextFreeMorph)}(${Y.data})`:Y.data:!0));Y.return(Z?`"${A1}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let G=o(this.unitBranches,(W,H)=>[`${H.in.serializedValue}`,H.hasKind("morph")?H:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:G}}let Y=[];for(let G=0;G<this.branches.length-1;G++){let W=this.branches[G];for(let H=G+1;H<this.branches.length;H++){let J=this.branches[H],Q=U1(W.in,J.in,W.$);if(!(Q instanceof S))continue;for(let $ of Q){if(!$.kind||$.optional)continue;let z,O;if($.kind==="domain"){let{l:V,r:R}=$;z=`"${typeof V==="string"?V:V.domain}"`,O=`"${typeof R==="string"?R:R.domain}"`}else if($.kind==="unit")z=$.l.serializedValue,O=$.r.serializedValue;else continue;let L=Y.find((V)=>e1(V.path,$.path)&&V.kind===$.kind);if(!L)Y.push({kind:$.kind,cases:{[z]:{branchIndices:[G],condition:$.l},[O]:{branchIndices:[H],condition:$.r}},path:$.path});else{if(L.cases[z])L.cases[z].branchIndices=d1(L.cases[z].branchIndices,G);else L.cases[z]??={branchIndices:[G],condition:$.l};if(L.cases[O])L.cases[O].branchIndices=d1(L.cases[O].branchIndices,H);else L.cases[O]??={branchIndices:[H],condition:$.r}}}}}let Z=this.ordered?t$(Y,this.branches):Y;if(!Z.length)return null;let X=s$(Z,this),_={};for(let G in X.best.cases){let W=a$(X,G);if(W===null){_[G]=!0;continue}if(W.length===this.branches.length)return null;if(this.ordered)W.sort((Q,$)=>Q.originalIndex-$.originalIndex);let H=W.map((Q)=>Q.branch),J=H.length===1?H[0]:this.$.node("union",this.ordered?{branches:H,ordered:!0}:H);Object.assign(this.referencesById,J.referencesById),_[G]=J}if(X.defaultEntries.length){let G=X.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(X.location,{cases:_})}}var s$=(Y,Z)=>{let X=Y.sort((W,H)=>Object.keys(H.cases).length-Object.keys(W.cases).length)[0],_={kind:X.kind,path:X.path,optionallyChainedPropString:PG(X.path)},G=Z.branches.map((W,H)=>({originalIndex:H,branch:W}));return{best:X,location:_,defaultEntries:G,node:Z}},a$=(Y,Z)=>{let X=Y.best.cases[Z],_=e$(X.condition,Y.location.path,Y.node.$),G=[],W=[];for(let H=0;H<Y.defaultEntries.length;H++){let J=Y.defaultEntries[H];if(X.branchIndices.includes(J.originalIndex)){let Q=KG(Y.node.branches[J.originalIndex],Y.location);if(Q===null)G=null;else G?.push({originalIndex:J.originalIndex,branch:Q})}else if(J.branch.hasKind("alias")&&_.hasKind("domain")&&_.domain==="object")G?.push(J);else{if(J.branch.in.overlaps(_)){let Q=KG(J.branch,Y.location);G?.push({originalIndex:J.originalIndex,branch:Q})}W.push(J)}}return Y.defaultEntries=W,G},t$=(Y,Z)=>{return Y.filter((_)=>{let G=Object.values(_.cases).map((W)=>W.branchIndices);for(let W=0;W<G.length-1;W++){let H=G[W];for(let J=W+1;J<G.length;J++){let Q=G[J];for(let $ of H)for(let z of Q)if($>z){if(Z[$].overlaps(Z[z]))return!1}}}return!0})},e$=(Y,Z,X)=>{let _=Y==="undefined"?X.node("unit",{unit:void 0}):Y==="null"?X.node("unit",{unit:null}):Y==="boolean"?X.units([!0,!1]):Y;for(let G=Z.length-1;G>=0;G--){let W=Z[G];_=X.node("intersection",typeof W==="number"?{proto:"Array",sequence:[...z_(W).map((H)=>({})),_]}:{domain:"object",required:[{key:W,value:_}]})}return _},PG=(Y)=>Y.reduce((Z,X)=>Z+AZ(X,!0),"data"),YQ=K0(O_),ZQ=K0(n),lZ={implementation:r$,Node:jG},XQ=(Y)=>({kind:Y.kind,path:Y.path.map((Z)=>typeof Z==="string"?Z:X4(Z)),cases:o(Y.cases,(Z,X)=>[Z,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),_Q={delimiter:" | ",finalDelimiter:" | "},GQ=(Y)=>H8(Y,_Q),H8=(Y,Z)=>{let X=Z?.delimiter??", ",_=Z?.finalDelimiter??" or ";if(Y.length===0)return"never";if(Y.length===1)return Y[0];if(Y.length===2&&Y[0]==="false"&&Y[1]==="true"||Y[0]==="true"&&Y[1]==="false")return"boolean";let G={},W=Y.filter((J)=>G[J]?!1:G[J]=!0),H=W.pop();return`${W.join(X)}${W.length?_:""}${H}`},cZ=(Y,Z,X)=>{let _=Z.map(()=>[]);for(let W=0;W<Y.length;W++){let H={};for(let J=0;J<Z.length;J++){if(_[J]===null)continue;if(Y[W].equals(Z[J])){_[J]=null,H={};break}let Q=M0(Y[W],Z[J],X);if(Q instanceof S)continue;if(Q.equals(Y[W])){_[J].push(Y[W]),H={};break}if(Q.equals(Z[J]))_[J]=null;else H[J]=Q}for(let J in H)_[J][W]=H[J]}let G=_.flatMap((W,H)=>W?.flatMap((J)=>J.branches)??Z[H]);return G.length===0?S.init("union",Y,Z):G},WQ=({branches:Y,ordered:Z})=>{if(Y.length<2)return Y;let X=Y.map(()=>!0);for(let _=0;_<Y.length;_++)for(let G=_+1;G<Y.length&&X[_]&&X[G];G++){if(Y[_].equals(Y[G])){X[G]=!1;continue}let W=U1(Y[_].in,Y[G].in,Y[0].$);if(W instanceof S)continue;if(!Z)HQ(Y[_],Y[G]);if(W.equals(Y[_].in))X[_]=!!Z;else if(W.equals(Y[G].in))X[G]=!1}return Y.filter((_,G)=>X[G])},HQ=(Y,Z)=>{if(!Y.includesTransform&&!Z.includesTransform)return;if(!e1(Y.shallowMorphs,Z.shallowMorphs))w(qG(Y.expression,Z.expression));if(!e1(Y.flatMorphs,Z.flatMorphs,{isEqual:(X,_)=>X.propString===_.propString&&(X.node.hasKind("morph")&&_.node.hasKind("morph")?X.node.hasEqualMorphs(_.node):X.node.hasKind("intersection")&&_.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===_.node.structure?.structuralMorphRef:!1)}))w(qG(Y.expression,Z.expression))},KG=(Y,Z)=>Y.transform((X,_)=>{if(X==="domain"||X==="unit")return null;return _},{shouldTransform:(X,_)=>{let G=PG(_.path);if(!Z.optionallyChainedPropString.startsWith(G))return!1;if(X.hasKind("domain")&&X.domain==="object")return!0;if((X.hasKind("domain")||Z.kind==="unit")&&G===Z.optionallyChainedPropString)return!0;return X.children.length!==0&&X.kind!=="index"}}),qG=(Y,Z)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
40
|
+
Left: ${Y}
|
|
41
|
+
Right: ${Z}`,JQ=(Y,Z)=>`The intersection of two ordered unions is indeterminate:
|
|
42
|
+
Left: ${Y}
|
|
43
|
+
Right: ${Z}`;var $Q=r({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Y)=>Y instanceof Date?Y.toISOString():B1(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>n(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),...l1("unit",(Y,Z)=>{if(Z.allows(Y.unit))return Y;let X=Z.hasKind("intersection")?Z.basis:Z;if(X){let _=X.hasKind("domain")?X:B.intrinsic.object;if(Y.domain!==_.domain){let G=Y.domain==="undefined"||Y.domain==="null"||Y.domain==="boolean"?Y.domain:B.intrinsic[Y.domain];return S.init("domain",G,_)}}return S.init("assignability",Y,Z.hasKind("intersection")?Z.children.find((_)=>!_.allows(Y.unit)):Z)})}});class vG extends x4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=SG(this.unit,this.serializedValue);compiledNegation=SG(this.unit,this.serializedValue,"negated");expression=n(this.unit);domain=g0(this.unit);get defaultShortDescription(){return this.domain==="object"?Q1.object:this.description}innerToJsonSchema(Y){return this.unit===null?{type:"null"}:B.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 iZ={implementation:$Q,Node:vG},SG=(Y,Z,X)=>{if(Y instanceof Date){let _=`data instanceof Date && data.toISOString() === ${Z}`;return X?`!(${_})`:_}if(Number.isNaN(Y))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${Z}`};var QQ=r({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Y,Z)=>{let X=Z.$.parseSchema(Y);if(!X.extends(B.intrinsic.key))return w(FQ(X.expression));let _=X.branches.filter((G)=>G.hasKind("unit"));if(_.length)return w(zQ(_.map((G)=>n(G.unit))));return X}},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>`[${Y.signature.expression}]: ${Y.value.description}`},intersections:{index:(Y,Z,X)=>{if(Y.signature.equals(Z.signature)){let _=M0(Y.value,Z.value,X),G=_ instanceof S?B.intrinsic.never.internal:_;return X.$.node("index",{signature:Y.signature,value:G})}if(Y.signature.extends(Z.signature)&&Y.value.subsumes(Z.value))return Z;if(Z.signature.extends(Y.signature)&&Z.value.subsumes(Y.value))return Y;return null}}});class xG extends T1{impliedBasis=B.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=Z0(this.value.flatRefs.map((Y)=>b1([this.signature,...Y.path],Y.node)),b1([this.signature],this.value));traverseAllows=(Y,Z)=>j4(Y).every((X)=>{if(this.signature.traverseAllows(X[0],Z))return F1(X[0],()=>this.value.traverseAllows(X[1],Z),Z);return!0});traverseApply=(Y,Z)=>{for(let X of j4(Y))if(this.signature.traverseAllows(X[0],Z))F1(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 oZ={implementation:QQ,Node:xG},zQ=(Y)=>`Index keys ${Y.join(", ")} should be specified as named props.`,FQ=(Y)=>`Indexed key definition '${Y}' must be a string or symbol`;var UQ=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:i8,optional:i8}});class hG extends o8{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 nZ={implementation:UQ,Node:hG};var OQ=r({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},optionals:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},defaultables:{child:(Y)=>Y.map((Z)=>Z[0]),parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>{let _=Z.$.parseSchema(X[0]);return r8(_,X[1],null),[_,X[1]]})},serialize:(Y)=>Y.map((Z)=>[Z[0].collapsibleJson,B1(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 w(VQ);if(Y.optionals?.length||Y.defaultables?.length)return w(sZ)}if(Y.minVariadicLength&&!Y.variadic)return w("minVariadicLength may not be specified without a variadic element");return Y}return{variadic:Y}},reduce:(Y,Z)=>{let X=Y.minVariadicLength??0,_=Y.prefix?.slice()??[],G=Y.defaultables?.slice()??[],W=Y.optionals?.slice()??[],H=Y.postfix?.slice()??[];if(Y.variadic){while(W.at(-1)?.equals(Y.variadic))W.pop();if(W.length===0&&G.length===0)while(_.at(-1)?.equals(Y.variadic))_.pop(),X++;while(H[0]?.equals(Y.variadic))H.shift(),X++}else if(W.length===0&&G.length===0)_.push(...H.splice(0));if(X!==Y.minVariadicLength||Y.prefix&&Y.prefix.length!==_.length)return Z.node("sequence",{...Y,prefix:_,defaultables:G,optionals:W,postfix:H,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} = ${n(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(Y,Z,X)=>{let _=e8({l:Y.tuple,r:Z.tuple,disjoint:new S,result:[],fixedVariants:[],ctx:X}),G=_.disjoint.length===0?[_,..._.fixedVariants]:_.fixedVariants;return G.length===0?_.disjoint:G.length===1?X.$.node("sequence",fG(G[0].result)):X.$.node("union",G.map((W)=>({proto:Array,sequence:fG(W.result)})))}}});class bG extends T1{impliedBasis=B.intrinsic.Array.internal;tuple=DQ(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 IZ(this.flatRefs,this.prevariadic.flatMap((Y,Z)=>Z0(Y.node.flatRefs.map((X)=>b1([`${Z}`,...X.path],X.node)),b1([`${Z}`],Y.node)))),IZ(this.flatRefs,this.variadicOrPostfix.flatMap((Y)=>Z0(Y.flatRefs.map((Z)=>b1([B.intrinsic.nonNegativeIntegerString.internal,...Z.path],Z.node)),b1([B.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=LQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?K0(this.defaultValueMorphs):void 0;elementAtIndex(Y,Z){if(Z<this.prevariadic.length)return this.tuple[Z];let X=Y.length-this.postfixLength;if(Z>=X)return{kind:"postfix",node:this.postfix[Z-X]};return{kind:"variadic",node:this.variadic??_0(`Unexpected attempt to access index ${Z} on ${this}`)}}traverseAllows=(Y,Z)=>{for(let X=0;X<Y.length;X++)if(!this.elementAtIndex(Y,X).node.traverseAllows(Y[X],Z))return!1;return!0};traverseApply=(Y,Z)=>{let X=0;for(;X<Y.length;X++)F1(X,()=>this.elementAtIndex(Y,X).node.traverseApply(Y[X],Z),Z)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Y){if(this.prefix)for(let[Z,X]of this.prefix.entries())Y.traverseKey(`${Z}`,`data[${Z}]`,X);for(let[Z,X]of this.defaultablesAndOptionals.entries()){let _=`${Z+this.prefixLength}`;Y.if(`${_} >= ${Y.data}.length`,()=>Y.traversalKind==="Allows"?Y.return(!0):Y.return()),Y.traverseKey(_,`data[${_}]`,X)}if(this.variadic){if(this.postfix)Y.const("firstPostfixIndex",`${Y.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Y.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Y.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Z,X]of this.postfix.entries()){let _=`firstPostfixIndex + ${Z}`;Y.traverseKey(_,`data[${_}]`,X)}}if(Y.traversalKind==="Allows")Y.return(!0)}_transform(Y,Z){Z.path.push(B.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(Y,Z);return Z.path.pop(),X}expression=this.description;reduceJsonSchema(Y,Z){if(this.prevariadic.length)Y.prefixItems=this.prevariadic.map((X)=>{let _=X.node.toJsonSchemaRecurse(Z);if(X.kind==="defaultables"){let G=typeof X.default==="function"?X.default():X.default;_.default=B.intrinsic.jsonData.allows(G)?G:Z.fallback.defaultValue({code:"defaultValue",base:_,value:G})}return _});if(this.minLength)Y.minItems=this.minLength;if(this.variadic){let X=Object.assign(Y,{items:this.variadic.toJsonSchemaRecurse(Z)});if(this.maxLength)X.maxItems=this.maxLength;if(this.postfix){let _=this.postfix.map((G)=>G.toJsonSchemaRecurse(Z));Y=Z.fallback.arrayPostfix({code:"arrayPostfix",base:X,elements:_})}}else Y.items=!1,delete Y.maxItems;return Y}}var EQ={},LQ=(Y)=>{if(!Y.defaultables)return[];let Z=[],X="[",_=Y.prefixLength+Y.defaultablesLength-1;for(let G=Y.prefixLength;G<=_;G++){let[W,H]=Y.defaultables[G-Y.prefixLength];Z.push(mZ(G,W,H)),X+=`${G}: ${W.id} = ${B1(H)}, `}return X+="]",EQ[X]??=Z},rZ={implementation:OQ,Node:bG},DQ=(Y)=>{let Z=[];if(Y.prefix)for(let X of Y.prefix)Z.push({kind:"prefix",node:X});if(Y.defaultables)for(let[X,_]of Y.defaultables)Z.push({kind:"defaultables",node:X,default:_});if(Y.optionals)for(let X of Y.optionals)Z.push({kind:"optionals",node:X});if(Y.variadic)Z.push({kind:"variadic",node:Y.variadic});if(Y.postfix)for(let X of Y.postfix)Z.push({kind:"postfix",node:X});return Z},fG=(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},{}),sZ="A postfix required element cannot follow an optional or defaultable element",VQ="A postfix element requires a variadic element",e8=(Y)=>{let[Z,...X]=Y.l,[_,...G]=Y.r;if(!Z||!_)return Y;let W=X.at(-1)?.kind==="postfix",H=G.at(-1)?.kind==="postfix",J=Z.kind==="prefix"||_.kind==="prefix"?"prefix":Z.kind==="postfix"||_.kind==="postfix"?"postfix":Z.kind==="variadic"&&_.kind==="variadic"?"variadic":W||H?"prefix":Z.kind==="defaultables"||_.kind==="defaultables"?"defaultables":"optionals";if(Z.kind==="prefix"&&_.kind==="variadic"&&H){let O=e8({...Y,fixedVariants:[],r:G.map((L)=>({...L,kind:"prefix"}))});if(O.disjoint.length===0)Y.fixedVariants.push(O)}else if(_.kind==="prefix"&&Z.kind==="variadic"&&W){let O=e8({...Y,fixedVariants:[],l:X.map((L)=>({...L,kind:"prefix"}))});if(O.disjoint.length===0)Y.fixedVariants.push(O)}let Q=M0(Z.node,_.node,Y.ctx);if(Q instanceof S)if(J==="prefix"||J==="postfix")Y.disjoint.push(...Q.withPrefixKey(J==="prefix"?Y.result.length:`-${X.length+1}`,"required")),Y.result=[...Y.result,{kind:J,node:B.intrinsic.never.internal}];else if(J==="optionals"||J==="defaultables")return Y;else return e8({...Y,fixedVariants:[],l:X.map((O)=>({...O,kind:"prefix"})),r:X.map((O)=>({...O,kind:"prefix"}))});else if(J==="defaultables"){if(Z.kind==="defaultables"&&_.kind==="defaultables"&&Z.default!==_.default)w(pZ(Z.default,_.default));Y.result=[...Y.result,{kind:J,node:Q,default:Z.kind==="defaultables"?Z.default:_.kind==="defaultables"?_.default:_0(`Unexpected defaultable intersection from ${Z.kind} and ${_.kind} elements.`)}]}else Y.result=[...Y.result,{kind:J,node:Q}];let $=Y.l.length,z=Y.r.length;if(Z.kind!=="variadic"||$>=z&&(_.kind==="variadic"||z===1))Y.l=X;if(_.kind!=="variadic"||z>=$&&(Z.kind==="variadic"||$===1))Y.r=G;return e8(Y)};var yG=(Y)=>(Z)=>{if(Z.props.length||Z.index){let X=Z.index?.map((G)=>G[Y])??[];for(let G of Z.props)X.push(G[Y]);if(Z.undeclared)X.push(`+ (undeclared): ${Z.undeclared}`);let _=`{ ${X.join(", ")} }`;return Z.sequence?`${_} & ${Z.sequence.description}`:_}return Z.sequence?.description??"{}"},MQ=yG("description"),AQ=yG("expression"),kG=(Y,Z,X)=>{let _=Y.required?"required":"optional";if(!Z.signature.allows(Y.key))return null;let G=U1(Y.value,Z.value,X);if(G instanceof S)return _==="optional"?X.node("optional",{key:Y.key,value:B.intrinsic.never.internal}):G.withPrefixKey(Y.key,Y.kind);return null},wQ=r({kind:"structure",hasAssociatedError:!1,normalize:(Y)=>Y,applyConfig:(Y,Z)=>{if(!Y.undeclared&&Z.onUndeclaredKey!=="ignore")return{...Y,undeclared:Z.onUndeclaredKey};return Y},keys:{required:{child:!0,parse:t0("required"),reduceIo:(Y,Z,X)=>{Z.required=Z0(Z.required,X.map((_)=>_[Y]));return}},optional:{child:!0,parse:t0("optional"),reduceIo:(Y,Z,X)=>{if(Y==="in"){Z.optional=X.map((_)=>_.in);return}for(let _ of X)Z[_.outProp.kind]=Z0(Z[_.outProp.kind],_.outProp.out)}},index:{child:!0,parse:t0("index")},sequence:{child:!0,parse:t0("sequence")},undeclared:{parse:(Y)=>Y==="ignore"?void 0:Y,reduceIo:(Y,Z,X)=>{if(X!=="delete")return;if(Y==="in")delete Z.undeclared;else Z.undeclared="reject"}}},defaults:{description:MQ},intersections:{structure:(Y,Z,X)=>{let _={...Y.inner},G={...Z.inner},W=new S;if(Y.undeclared){let Q=Y.keyof();for(let $ of Z.requiredKeys)if(!Q.allows($))W.add("presence",B.intrinsic.never.internal,Z.propsByKey[$].value,{path:[$]});if(G.optional)G.optional=G.optional.filter(($)=>Q.allows($.key));if(G.index)G.index=G.index.flatMap(($)=>{if($.signature.extends(Q))return $;let z=U1(Q,$.signature,X.$);if(z instanceof S)return[];let O=t6(z,$.value,X.$);if(O.required)G.required=t1(G.required,O.required);if(O.optional)G.optional=t1(G.optional,O.optional);return O.index??[]})}if(Z.undeclared){let Q=Z.keyof();for(let $ of Y.requiredKeys)if(!Q.allows($))W.add("presence",Y.propsByKey[$].value,B.intrinsic.never.internal,{path:[$]});if(_.optional)_.optional=_.optional.filter(($)=>Q.allows($.key));if(_.index)_.index=_.index.flatMap(($)=>{if($.signature.extends(Q))return $;let z=U1(Q,$.signature,X.$);if(z instanceof S)return[];let O=t6(z,$.value,X.$);if(O.required)_.required=t1(_.required,O.required);if(O.optional)_.optional=t1(_.optional,O.optional);return O.index??[]})}let H={};if(Y.undeclared||Z.undeclared)H.undeclared=Y.undeclared==="reject"||Z.undeclared==="reject"?"reject":"delete";let J=Z8({kind:"structure",baseInner:H,l:X8(_),r:X8(G),roots:[],ctx:X});if(J instanceof S)W.push(...J);if(W.length)return W;return J}},reduce:(Y,Z)=>{if(Y.index){if(!(Y.required||Y.optional))return;let X=!1,_=Y.required??[],G=Y.optional??[],W=[...G];for(let H of Y.index){for(let J of _){let Q=kG(J,H,Z);if(Q instanceof S)return Q}for(let[J,Q]of G.entries()){let $=kG(Q,H,Z);if($ instanceof S)return $;if($===null)continue;W[J]=$,X=!0}}if(X)return Z.node("structure",{...Y,optional:W},{prereduced:!0})}}});class pG extends T1{impliedBasis=B.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=K0(this.propsByKey);expression=AQ(this);requiredKeys=this.required?.map((Y)=>Y.key)??[];optionalKeys=this.optional?.map((Y)=>Y.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Y=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Z}of this.index)Y=Y.concat(Z.branches);return this._keyof=this.$.node("union",Y)}map(Y){return this.$.node("structure",this.props.flatMap(Y).reduce((Z,X)=>{let _=this.propsByKey[X.key];if(V0(X)){if(X.kind!=="required"&&X.kind!=="optional")return w(`Map result must have kind "required" or "optional" (was ${X.kind})`);return Z[X.kind]=Z0(Z[X.kind],X),Z}let G=X.kind??_?.kind??"required",W=o(X,(H,J)=>(H in n8.implementation.keys)?[H,J]:[]);return Z[G]=Z0(Z[G],this.$.node(G,W)),Z},{}))}assertHasKeys(Y){let Z=Y.filter((X)=>!s8(X,this.keyof()));if(Z.length)return w(gG(this.expression,Z))}get(Y,...Z){let X,_=!1,G=BQ(Y);if((typeof G==="string"||typeof G==="symbol")&&this.propsByKey[G])X=this.propsByKey[G].value,_=this.propsByKey[G].required;if(this.index){for(let H of this.index)if(s8(G,H.signature))X=X?.and(H.value)??H.value}if(this.sequence&&s8(G,B.intrinsic.nonNegativeIntegerString))if(y(G,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let H=Number.parseInt(G);if(H<this.sequence.prevariadic.length){let J=this.sequence.prevariadic[H].node;X=X?.and(J)??J,_||=H<this.sequence.prefixLength}else if(this.sequence.variadic){let J=this.$.node("union",this.sequence.variadicOrPostfix);X=X?.and(J)??J}}if(!X){if(this.sequence?.variadic&&y(G,"root")&&G.extends(B.intrinsic.number))return w(TQ(G.expression,this.sequence.expression));return w(gG(this.expression,[G]))}let W=X.get(...Z);return _?W:W.or(B.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=m6(this.inner),_=(G)=>{let W=Z.some((H)=>s8(G,H));return Y==="pick"?W:!W};if(X.required)X.required=X.required.filter((G)=>_(G.key));if(X.optional)X.optional=X.optional.filter((G)=>_(G.key));if(X.index)X.index=X.index.filter((G)=>_(G.signature));return X}traverseAllows=(Y,Z)=>this._traverse("Allows",Y,Z);traverseApply=(Y,Z)=>this._traverse("Apply",Y,Z);_traverse=(Y,Z,X)=>{let _=X?.currentErrorCount??0;for(let G=0;G<this.props.length;G++)if(Y==="Allows"){if(!this.props[G].traverseAllows(Z,X))return!1}else if(this.props[G].traverseApply(Z,X),X.failFast&&X.currentErrorCount>_)return!1;if(this.sequence){if(Y==="Allows"){if(!this.sequence.traverseAllows(Z,X))return!1}else if(this.sequence.traverseApply(Z,X),X.failFast&&X.currentErrorCount>_)return!1}if(this.index||this.undeclared==="reject"){let G=Object.keys(Z);G.push(...Object.getOwnPropertySymbols(Z));for(let W=0;W<G.length;W++){let H=G[W];if(this.index){for(let J of this.index)if(J.signature.traverseAllows(H,X)){if(Y==="Allows"){if(!F1(H,()=>J.value.traverseAllows(Z[H],X),X))return!1}else if(F1(H,()=>J.value.traverseApply(Z[H],X),X),X.failFast&&X.currentErrorCount>_)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(H)){if(Y==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[H],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&&B.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",RQ(this))}structuralMorphRef=this.structuralMorph&&K0(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(["),IQ(Y,this),Y.line("])")})}compileExhaustiveEntry(Y){if(Y.const("k","keys[i]"),this.index)for(let Z of this.index)Y.if(`${Y.invoke(Z.signature,{arg:"k",kind:"Allows"})}`,()=>Y.traverseKey("k","data[k]",Z.value));if(this.undeclared==="reject")Y.if(`!(${this._compileDeclaresKey(Y)})`,()=>{if(Y.traversalKind==="Allows")return Y.return(!1);return Y.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Y.return())});return Y}reduceJsonSchema(Y,Z){switch(Y.type){case"object":return this.reduceObjectJsonSchema(Y,Z);case"array":let X=this.sequence?.reduceJsonSchema(Y,Z)??Y;if(this.props.length||this.index)return Z.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},Z)});return X;default:return R0.throwInternalOperandError("structure",Y)}}reduceObjectJsonSchema(Y,Z){if(this.props.length){Y.properties={};for(let X of this.props){let _=X.value.toJsonSchemaRecurse(Z);if(typeof X.key==="symbol"){Z.fallback.symbolKey({code:"symbolKey",base:Y,key:X.key,value:_,optional:X.optional});continue}if(X.hasDefault()){let G=typeof X.default==="function"?X.default():X.default;_.default=B.intrinsic.jsonData.allows(G)?G:Z.fallback.defaultValue({code:"defaultValue",base:_,value:G})}Y.properties[X.key]=_}if(this.requiredKeys.length&&Y.properties)Y.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in Y.properties))}if(this.index)for(let X of this.index){let _=X.value.toJsonSchemaRecurse(Z);if(X.signature.equals(B.intrinsic.string)){Y.additionalProperties=_;continue}for(let G of X.signature.branches){if(!G.extends(B.intrinsic.string)){Y=Z.fallback.symbolKey({code:"symbolKey",base:Y,key:null,value:_,optional:!1});continue}let W={type:"string"};if(G.hasKind("morph"))W=Z.fallback.morph({code:"morph",base:G.in.toJsonSchemaRecurse(Z),out:G.out.toJsonSchemaRecurse(Z)});if(!G.hasKind("intersection"))return _0(`Unexpected index branch kind ${G.kind}.`);let{pattern:H}=G.inner;if(H){let J=Object.assign(W,{pattern:H[0].rule});for(let Q=1;Q<H.length;Q++)W=Z.fallback.patternIntersection({code:"patternIntersection",base:J,pattern:H[Q].rule});Y.patternProperties??={},Y.patternProperties[J.pattern]=_}}}if(this.undeclared&&!Y.additionalProperties)Y.additionalProperties=!1;return Y}}var aZ={},NQ=(Y)=>{let Z="";for(let X=0;X<Y.defaultable.length;X++)Z+=Y.defaultable[X].defaultValueMorphRef;if(Y.sequence?.defaultValueMorphsReference)Z+=Y.sequence?.defaultValueMorphsReference;if(Y.undeclared==="delete"){if(Z+="delete !(",Y.required)for(let X of Y.required)Z+=X.compiledKey+" | ";if(Y.optional)for(let X of Y.optional)Z+=X.compiledKey+" | ";if(Y.index)for(let X of Y.index)Z+=X.signature.id+" | ";if(Y.sequence)if(Y.sequence.maxLength===null)Z+=d.nonNegativeIntegerString.id;else for(let X=0;X<Y.sequence.tuple.length;X++)Z+=X+" | ";Z+=")"}return Z},RQ=(Y)=>{let Z=NQ(Y);if(!Z)return;if(aZ[Z])return aZ[Z];let X=(_,G)=>{for(let W=0;W<Y.defaultable.length;W++)if(!(Y.defaultable[W].key in _))Y.defaultable[W].defaultValueMorph(_,G);if(Y.sequence?.defaultables)for(let W=_.length-Y.sequence.prefixLength;W<Y.sequence.defaultables.length;W++)Y.sequence.defaultValueMorphs[W](_,G);if(Y.undeclared==="delete"){for(let W in _)if(!Y.declaresKey(W))delete _[W]}return _};return aZ[Z]=X},IQ=(Y,Z)=>{let _=`(data${Z.defaultable.some((G)=>G.defaultValueMorph.length===2)||Z.sequence?.defaultValueMorphs.some((G)=>G.length===2)?", ctx":""})`;return Y.block(`${_} => `,(G)=>{for(let W=0;W<Z.defaultable.length;W++){let{serializedKey:H,defaultValueMorphRef:J}=Z.defaultable[W];G.if(`!(${H} in data)`,(Q)=>Q.line(`${J}${_}`))}if(Z.sequence?.defaultables)G.for(`i < ${Z.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${Z.sequence.prefixLength}`);if(Z.undeclared==="delete")G.forIn("data",(W)=>W.if(`!(${Z._compileDeclaresKey(W)})`,(H)=>H.line("delete data[k]")));return G.return("data")})},tZ={implementation:wQ,Node:pG},BQ=(Y)=>{if(y(Y,"root")&&Y.hasKind("unit"))Y=Y.unit;if(typeof Y==="number")Y=`${Y}`;return Y},TQ=(Y,Z)=>`${Y} is not allowed as an array index on ${Z}. Use the 'nonNegativeIntegerString' keyword instead.`,t6=(Y,Z,X)=>{let[_,G]=Q_(Y.branches,(H)=>H.hasKind("unit"));if(!_.length)return{index:X.node("index",{signature:Y,value:Z})};let W={};for(let H of _){let J=X.node("required",{key:H.unit,value:Z});W[J.kind]=Z0(W[J.kind],J)}if(G.length)W.index=X.node("index",{signature:G,value:Z});return W},CQ=(Y)=>y(Y,"root")?Y.expression:n(Y),gG=(Y,Z)=>`Key${Z.length===1?"":"s"} ${Z.map(CQ).join(", ")} ${Z.length===1?"does":"do"} not exist on ${Y}`;var G8={...zG,alias:a8.implementation,domain:a6.implementation,unit:iZ.implementation,proto:t8.implementation,union:lZ.implementation,morph:dZ.implementation,intersection:uZ.implementation,divisor:qZ.implementation,pattern:bZ.implementation,predicate:KZ.implementation,required:nZ.implementation,optional:n8.implementation,index:oZ.implementation,sequence:rZ.implementation,structure:tZ.implementation};B.defaultConfig=M_(Object.assign(o(G8,(Y,Z)=>[Y,Z.defaults]),{jitless:B_(),clone:N_,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:R0.defaultConfig}));B.resolvedConfig=m8(B.defaultConfig,B.config);var DG={...FG,alias:a8.Node,domain:a6.Node,unit:iZ.Node,proto:t8.Node,union:lZ.Node,morph:dZ.Node,intersection:uZ.Node,divisor:qZ.Node,pattern:bZ.Node,predicate:KZ.Node,required:nZ.Node,optional:n8.Node,index:oZ.Node,sequence:rZ.Node,structure:tZ.Node};class J8 extends $Z{get[X1](){return"module"}}var eZ=(Y,Z)=>new J8(o(Y,(X,_)=>[X,y(_,"module")?eZ(_,Z):Z.bindReference(_)]));var KQ=(Y)=>O0(Y)?Y:("branches"in Y)&&O0(Y.branches)?Y.branches:void 0,qQ=(Y,Z)=>w(`Node of kind ${Z} is not valid as a ${Y} definition`),mG=(Y)=>`#${Y} duplicates public alias ${Y}`,Y5={};B.ambient??={};var uG,cG="function $",jQ=(Y)=>lG(Y,iG(Y)),lG=(Y,Z)=>{let X=Z.write(cG,4),_=Z.compile()();for(let G of Y){if(G.precompilation)continue;if(G.traverseAllows=_[`${G.id}Allows`].bind(_),G.isRoot()&&!G.allowsRequiresContext)G.allows=G.traverseAllows;if(G.traverseApply=_[`${G.id}Apply`].bind(_),_[`${G.id}Optimistic`])G.traverseOptimistic=_[`${G.id}Optimistic`].bind(_);G.precompilation=X}},iG=(Y)=>new p6().return(Y.reduce((Z,X)=>{let _=new p8({kind:"Allows"}).indent();X.compile(_);let G=_.write(`${X.id}Allows`),W=new p8({kind:"Apply"}).indent();X.compile(W);let H=W.write(`${X.id}Apply`),J=`${Z}${G},
|
|
44
|
+
${H},
|
|
45
|
+
`;if(!X.hasKind("union"))return J;let Q=new p8({kind:"Allows",optimistic:!0}).indent();X.compile(Q);let $=Q.write(`${X.id}Optimistic`);return`${J}${$},
|
|
46
46
|
`},`{
|
|
47
|
-
`)+"}");class oW{config;resolvedConfig;name;get[iT](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(T,_){if(this.config=fF(z.config,_),this.resolvedConfig=fF(z.resolvedConfig,_),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(c4).length}`,this.name in c4)E(`A Scope already named ${this.name} already exists`);c4[this.name]=this;let F=Object.entries(T).map((W)=>this.preparseOwnAliasEntry(...W));for(let[W,J]of F){let Y=W;if(W[0]==="#"){if(Y=W.slice(1),Y in this.aliases)E(R6(Y));this.aliases[Y]=J}else{if(Y in this.aliases)E(R6(W));this.aliases[Y]=J,this.exportedNames.push(Y)}if(!P(J,"module")&&!P(J,"generic")&&!J0(J)){let $=this.preparseOwnDefinitionFormat(J,{alias:Y});this.resolutions[Y]=P($,"root")?this.bindReference($):this.createParseContext($).id}}E6??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[E6.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=z.intrinsic?c(z.intrinsic,(W,J)=>W.startsWith("json")?[]:[W,this.bindReference(J)]):{}}cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(T){return T}generic=(...T)=>{let _=this;return(F,W)=>new G0(T,W?new yW(F):F,_,_,W??null)};units=(T,_)=>{let F=[];for(let J of T)if(!F.includes(J))F.push(J);let W=F.map((J)=>this.node("unit",{unit:J},_));return this.node("union",W,{..._,prereduced:!0})};lazyResolutions=[];lazilyResolve(T,_){let F=this.node("alias",{reference:_??"synthetic",resolve:T},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(F);return F}schema=(T,_)=>this.finalize(this.parseSchema(T,_));parseSchema=(T,_)=>this.node(yF(T),T,_);preparseNode(T,_,F){let W=typeof T==="string"?T:yF(_,T);if(OT(_)&&_.kind===W)return _;if(W==="alias"&&!F?.prereduced){let{reference:$}=gF.implementation.normalize(_,this);if($.startsWith("$")){let Z=this.resolveRoot($.slice(1));_=Z,W=Z.kind}}else if(W==="union"&&T_(_,"object")){let $=sH(_);if($?.length===1)_=$[0],W=yF(_)}if(OT(_)&&_.kind===W)return _;let Y=r0[W].normalize?.(_,this)??_;if(OT(Y))return Y.kind===W?Y:aH(W,Y.kind);return{...F,$:this,kind:W,def:Y,prefix:F.alias??W}}bindReference(T){let _;if(OT(T))_=T.$===this?T:new T.constructor(T.attachments,this);else _=T.$===this?T:new G0(T.params,T.bodyDef,T.$,this,T.hkt);if(!this.resolved)Object.assign(this.referencesById,_.referencesById);return _}resolveRoot(T){return this.maybeResolveRoot(T)??E(t4(T))}maybeResolveRoot(T){let _=this.maybeResolve(T);if(P(_,"generic"))return;return _}maybeResolveSubalias(T){return d4(this.aliases,T)??d4(this.ambient,T)}get ambient(){return z.ambient}maybeResolve(T){let _=this.resolutions[T];if(_){if(typeof _!=="string")return this.bindReference(_);let W=nT[_];if(P(W,"root"))return this.resolutions[T]=W;if(P(W,"context")){if(W.phase==="resolving")return this.node("alias",{reference:`$${T}`},{prereduced:!0});if(W.phase==="resolved")return e(`Unexpected resolved context for was uncached by its scope: ${d(W)}`);W.phase="resolving";let J=this.bindReference(this.parseOwnDefinitionFormat(W.def,W));return W.phase="resolved",nT[J.id]=J,nT[W.id]=J,this.resolutions[T]=J}return e(`Unexpected nodesById entry for ${_}: ${d(W)}`)}let F=this.aliases[T]??this.ambient?.[T];if(!F)return this.maybeResolveSubalias(T);if(F=this.normalizeRootScopeValue(F),P(F,"generic"))return this.resolutions[T]=this.bindReference(F);if(P(F,"module")){if(!F.root)E(I6(T));return this.resolutions[T]=this.bindReference(F.root)}return this.resolutions[T]=this.parse(F,{alias:T})}createParseContext(T){let _=T.id??C4(T.prefix);return nT[_]=Object.assign(T,{[iT]:"context",$:this,id:_,phase:"unresolved"})}traversal(T){return new f_(T,this.resolvedConfig)}import(...T){return new e0(c(this.export(...T),(_,F)=>[`#${_}`,F]))}precompilation;_exportedResolutions;_exports;export(...T){if(!this._exports){this._exports={};for(let F of this.exportedNames){let W=this.aliases[F];this._exports[F]=P(W,"module")?u4(W,this):z6(this.maybeResolve(F))}for(let F of this.lazyResolutions)F.resolution;if(this._exportedResolutions=S6(this,this._exports),this._json=D6(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let F=L6(this.references);this.precompilation=F.write(K6,4),V6(this.references,F)}this.resolved=!0}let _=T.length?T:this.exportedNames;return new e0(c(_,(F,W)=>[W,this._exports[W]]))}resolve(T){return this.export()[T]}node=(T,_,F={})=>{let W=this.preparseNode(T,_,F);if(OT(W))return this.bindReference(W);let J=this.createParseContext(W),Y=B4(J),$=this.bindReference(Y);return nT[J.id]=$};parse=(T,_={})=>this.finalize(this.parseDefinition(T,_));parseDefinition(T,_={}){if(P(T,"root"))return this.bindReference(T);let F=this.preparseOwnDefinitionFormat(T,_);if(P(F,"root"))return this.bindReference(F);let W=this.createParseContext(F);nT[W.id]=W;let J=this.bindReference(this.parseOwnDefinitionFormat(T,W));if(J.isCyclic)J=dJ(J,W.id);return nT[W.id]=J,J}finalize(T){if(z6(T),!T.precompilation&&!this.resolvedConfig.jitless)eH(T.references);return T}}class l4 extends oW{parseOwnDefinitionFormat(T,_){return B4(_)}preparseOwnDefinitionFormat(T,_){return this.preparseNode(yF(T),T,_)}preparseOwnAliasEntry(T,_){return[T,_]}normalizeRootScopeValue(T){return T}}var z6=(T)=>{let _=T.references.filter((F)=>F.hasKind("alias"));for(let F of _){Object.assign(F.referencesById,F.resolution.referencesById);for(let W of T.references)if(F.id in W.referencesById)Object.assign(W.referencesById,F.referencesById)}return T},D6=(T)=>c(T,(_,F)=>[_,P(F,"root")||P(F,"generic")?F.json:P(F,"module")?D6(F):e(`Unexpected resolution ${d(F)}`)]),d4=(T,_)=>{let F=_.indexOf(".");if(F===-1)return;let W=_.slice(0,F),J=T[W];if(J===void 0)return;if(!P(J,"module"))return E(T9(W));let Y=_.slice(F+1),$=J[Y];if($===void 0)return d4(J,Y);if(P($,"root")||P($,"generic"))return $;if(P($,"module"))return $.root??E(I6(_));e(`Unexpected resolution for alias '${_}': ${d($)}`)},uW=(T,_)=>new l4(T,_),uF=new l4({});var S6=(T,_)=>{let F={};for(let W in _){let J=_[W];if(P(J,"module")){let Y=S6(T,J),$=c(Y,(Z,G)=>[`${W}.${Z}`,G]);Object.assign(F,$)}else if(P(J,"root")||P(J,"generic"))F[W]=J;else e(`Unexpected scope resolution ${d(J)}`)}return F},t4=(T)=>`'${T}' is unresolvable`,T9=(T)=>`'${T}' must reference a module to be accessed using dot syntax`,I6=(T)=>`Reference to submodule '${T}' must specify an alias`;uF.export();var{schema:WT,node:TF,defineSchema:Zz,generic:V_}=uF;var i4="^(?:0|[1-9]\\d*)$",_9=new RegExp(i4),Az=VT(_9);var N6=uW({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();z.intrinsic={...N6};var C6=uW({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:i4}},{prereducedAliases:!0}).export();Object.assign(z.intrinsic,C6);var F9=uW({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),x={...N6,...C6,...F9,emptyStructure:TF("structure",{},{prereduced:!0})};z.intrinsic={...x};var k6=(T)=>typeof T==="string"&&T[0]==="d"&&(T[1]==="'"||T[1]==='"')&&T.at(-1)===T[1],B6=(T)=>T.toString()!=="Invalid Date",f6=(T)=>T.slice(2,-1),n4=(T)=>`'${T}' could not be parsed by the Date constructor`,P6=(T,_)=>W9(T,_),W9=(T,_)=>{let F=new Date(T);if(B6(F))return F;let W=GJ(T);if(W!==void 0){let J=new Date(W);if(B6(J))return J}return _?E(_===!0?n4(T):_):void 0};var r4=(T,_)=>{let F=T.scanner.shiftUntil(J9[j6[_]]);if(T.scanner.lookahead==="")return T.error($9(F,_));if(T.scanner.shift(),_==="/"){try{new RegExp(F)}catch(W){E(String(W))}T.root=T.ctx.$.node("intersection",{domain:"string",pattern:F},{prereduced:!0})}else if(qT(_,s4))T.root=T.ctx.$.node("unit",{unit:F});else{let W=P6(F,n4(F));T.root=T.ctx.$.node("unit",{meta:F,unit:W})}},s4={"'":1,'"':1},q6={"/":1,"'":1,'"':1},j6={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},J9={"'":(T)=>T.lookahead==="'",'"':(T)=>T.lookahead==='"',"/":(T)=>T.lookahead==="/"},Y9={'"':"double-quote","'":"single-quote","/":"forward slash"},$9=(T,_)=>`${_}${T} requires a closing ${Y9[j6[_]]}`;var y6=(T)=>`Private type references should not include '#'. Use '${T}' instead.`,cW="Optional definitions like 'string?' are only valid as properties in an object or tuple",dW="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var v6={">":!0,">=":!0},x6={"<":!0,"<=":!0};var _F={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},b6=(T)=>`Unmatched )${T===""?"":` before ${T}`}`,lW=(T)=>`Missing ${T}`,h6=(T,_)=>`Left bounds are only valid when paired with right bounds (try ...${_}${T})`,tW=(T)=>`Left-bounded expressions must specify their limits using < or <= (was ${T})`,p6=(T,_,F,W)=>`An expression may have at most one left bound (parsed ${T}${_F[_]}, ${F}${_F[W]})`;var g6=(T,_,F)=>m6(T,_,F,[]),m6=(T,_,F,W)=>{let J=F.parseUntilFinalizer();if(W.push(J.root),J.finalizer===">"){if(W.length!==_.params.length)return F.error(a4(T,_.names,W.map((Y)=>Y.expression)));return W}if(J.finalizer===",")return m6(T,_,F,W);return J.error(lW(">"))},a4=(T,_,F)=>`${T}<${_.join(", ")}> requires exactly ${_.length} args (got ${F.length}${F.length===0?"":`: ${F.join(", ")}`})`;var e4=(T)=>{let _=T.scanner.shiftUntilNextTerminator();if(_==="keyof")T.addPrefix("keyof");else T.root=X9(T,_)},Z9=(T,_,F)=>{if(F.scanner.shiftUntilNonWhitespace(),F.scanner.shift()!=="<")return F.error(a4(T,_.names,[]));let J=g6(T,_,F);return _(...J)},X9=(T,_)=>G9(T,_)??A9(T,_)??T.error(_===""?T.scanner.lookahead==="#"?y6(T.shiftedByOne().scanner.shiftUntilNextTerminator()):T2(T):t4(_)),G9=(T,_)=>{if(T.ctx.args?.[_]){let W=T.ctx.args[_];if(typeof W!=="string")return W;return T.ctx.$.node("alias",{reference:W},{prereduced:!0})}let F=T.ctx.$.maybeResolve(_);if(P(F,"root"))return F;if(F===void 0)return;if(P(F,"generic"))return Z9(_,F,T);return E(`Unexpected resolution ${d(F)}`)},A9=(T,_)=>{let F=AJ(_);if(F!==void 0)return T.ctx.$.node("unit",{unit:F});let W=OJ(_);if(W!==void 0)return T.ctx.$.node("unit",{unit:W})},T2=(T)=>{let _=T.previousOperator();return _?_2(_,T.scanner.unscanned):H9(T.scanner.unscanned)},_2=(T,_="")=>`Token '${T}' requires a right operand${_?` before '${_}'`:""}`,H9=(T)=>`Expected an expression${T?` before '${T}'`:""}`;var F2=(T)=>T.scanner.lookahead===""?T.error(T2(T)):T.scanner.lookahead==="("?T.shiftedByOne().reduceGroupOpen():T.scanner.lookaheadIsIn(q6)?r4(T,T.scanner.shift()):T.scanner.lookaheadIsIn(Y0)?F2(T.shiftedByOne()):T.scanner.lookahead==="d"?T.scanner.nextLookahead in s4?r4(T,`${T.scanner.shift()}${T.scanner.shift()}`):e4(T):e4(T);class r_ extends Z4{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in r_.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...Y0};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(T,_)=>T===">"?_[0]==="="?_[1]==="=":_.trimStart()===""||qT(_.trimStart()[0],r_.terminatingChars):T==="="?_[0]!=="=":T===","||T==="?"}var u6=(T,_)=>{let F=O9(T,_);if(T.root.hasKind("unit")){if(typeof T.root.unit==="number"){T.reduceLeftBound(T.root.unit,F),T.unsetRoot();return}if(T.root.unit instanceof Date){let W=`d'${T.root.description??T.root.unit.toISOString()}'`;T.unsetRoot(),T.reduceLeftBound(W,F);return}}return M9(T,F)},c6={"<":1,">":1,"=":1},O9=(T,_)=>T.scanner.lookaheadIs("=")?`${_}${T.scanner.shift()}`:_;var o6=(T,_,F,W)=>{if(F.extends(z.intrinsic.number)){if(typeof _!=="number")return E(W2(T,_,W));return T==="=="?["min","max"]:T[0]===">"?["min"]:["max"]}if(F.extends(z.intrinsic.lengthBoundable)){if(typeof _!=="number")return E(W2(T,_,W));return T==="=="?["exactLength"]:T[0]===">"?["minLength"]:["maxLength"]}if(F.extends(z.intrinsic.Date))return T==="=="?["after","before"]:T[0]===">"?["after"]:["before"];return E(qJ(F.expression))},U9=(T)=>({rule:k6(T.limit)?f6(T.limit):T.limit,exclusive:T.comparator.length===1}),M9=(T,_)=>{let F=T.unsetRoot(),W=T.scanner.location;T.parseOperand();let J=T.unsetRoot(),Y=T.scanner.sliceChars(W,T.scanner.location);if(T.root=F,!J.hasKind("unit")||typeof J.unit!=="number"&&!(J.unit instanceof Date))return T.error(W2(_,Y,"right"));let $=J.unit,Z=_.length===1,G=o6(_,typeof $==="number"?$:Y,F,"right");for(let O of G)T.constrainRoot(O,_==="=="?{rule:$}:{rule:$,exclusive:Z});if(!T.branches.leftBound)return;if(!qT(_,x6))return T.error(tW(_));let X=o6(T.branches.leftBound.comparator,T.branches.leftBound.limit,F,"left");T.constrainRoot(X[0],U9(T.branches.leftBound)),T.branches.leftBound=null},W2=(T,_,F)=>`Comparator ${F==="left"?_F[T]:T} must be ${F==="left"?"preceded":"followed"} by a corresponding literal (was ${_})`;var d6=(T)=>{T.scanner.shiftUntilNonWhitespace();let _=T.scanner.shiftUntilNextTerminator();T.root=T.root.brand(_)};var t6=(T)=>{let _=T.scanner.shiftUntilNextTerminator(),F=HJ(_,{errorOnFail:l6(_)});if(F===0)T.error(l6(0));T.root=T.root.constrain("divisor",F)},l6=(T)=>`% operator must be followed by a non-zero integer literal (was ${T})`;var J2=(T)=>{let _=T.scanner.shift();return _===""?T.finalize(""):_==="["?T.scanner.shift()==="]"?T.setRoot(T.root.array()):T.error(w9):_==="|"?T.scanner.lookahead===">"?T.shiftedByOne().pushRootToBranch("|>"):T.pushRootToBranch(_):_==="&"?T.pushRootToBranch(_):_===")"?T.finalizeGroup():r_.lookaheadIsFinalizing(_,T.scanner.unscanned)?T.finalize(_):qT(_,c6)?u6(T,_):_==="%"?t6(T):_==="#"?d6(T):(_ in Y0)?J2(T):T.error(iW(_))},iW=(T,_="")=>`'${T}' is not allowed here${_&&` (should be ${_})`}`,w9="Missing expected ']'";var i6=(T)=>{let _=T.unsetRoot();T.parseOperand();let F=T.unsetRoot();if(!F.hasKind("unit"))return T.error(Q9(F.expression));let W=F.unit instanceof Date?()=>new Date(F.unit):F.unit;return[_,"=",W]},Q9=(T)=>`Default value '${T}' must a literal value`;var Y2=(T,_)=>{let F=_.$.maybeResolveRoot(T);if(F)return F;if(T.endsWith("[]")){let Y=_.$.maybeResolveRoot(T.slice(0,-2));if(Y)return Y.array()}let W=new FF(new r_(T),_),J=R9(W);if(W.finalizer===">")E(iW(">"));return J},R9=(T)=>{T.parseOperand();let _=cF(T).root;if(!_)return e(`Root was unexpectedly unset after parsing string '${T.scanner.scanned}'`);if(T.finalizer==="=")_=i6(T);else if(T.finalizer==="?")_=[_,"?"];if(T.scanner.shiftUntilNonWhitespace(),T.scanner.lookahead)E(iW(T.scanner.lookahead));return _},cF=(T)=>{while(T.finalizer===void 0)E9(T);return T},E9=(T)=>T.hasRoot()?T.parseOperator():T.parseOperand();class FF{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(T,_){this.scanner=T,this.ctx=_}error(T){return E(T)}hasRoot(){return this.root!==void 0}setRoot(T){this.root=T}unsetRoot(){let T=this.root;return this.root=void 0,T}constrainRoot(...T){this.root=this.root.constrain(T[0],T[1])}finalize(T){if(this.groups.length)return this.error(lW(")"));this.finalizeBranches(),this.finalizer=T}reduceLeftBound(T,_){let F=_F[_];if(!qT(F,v6))return this.error(tW(_));if(this.branches.leftBound)return this.error(p6(this.branches.leftBound.limit,this.branches.leftBound.comparator,T,F));this.branches.leftBound={comparator:F,limit:T}}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 T=this.groups.pop();if(!T)return this.error(b6(this.scanner.unscanned));this.branches=T}addPrefix(T){this.branches.prefixes.push(T)}applyPrefixes(){while(this.branches.prefixes.length){let T=this.branches.prefixes.pop();this.root=T==="keyof"?this.root.keyof():e(`Unexpected prefix '${T}'`)}}pushRootToBranch(T){this.assertRangeUnset(),this.applyPrefixes();let _=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(_)??_,T==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,T==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return cF(new FF(this.scanner,this.ctx))}parseOperator(){return J2(this)}parseOperand(){return F2(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(h6(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 z9="An empty string is not a valid generic parameter name",nW=(T,_,F)=>{T.shiftUntilNonWhitespace();let W=T.shiftUntilNextTerminator();if(W===""){if(T.lookahead===""&&_.length)return _;return E(z9)}return T.shiftUntilNonWhitespace(),K9(T,W,_,F)},n6="extends ",K9=(T,_,F,W)=>{if(T.shiftUntilNonWhitespace(),T.unscanned.startsWith(n6))T.jumpForward(n6.length);else{if(T.lookahead===",")T.shift();return F.push(_),nW(T,F,W)}let J=cF(new FF(T,W));return F.push([_,J.root]),nW(T,F,W)};class $2 extends k_{$;constructor(T){super((..._)=>new dF(T)(..._),{bind:T});this.$=T}in(T){return new dF(this.$,T===void 0?void 0:this.$.parse(T))}at(T,_){return new dF(this.$).at(T,_)}case(T,_){return new dF(this.$).case(T,_)}}class dF extends k_{$;in;key;branches=[];constructor(T,_){super((F)=>this.caseEntries(Object.entries(F).map(([W,J])=>W==="default"?[W,J]:[this.$.parse(W),J])));this.$=T,this.in=_}at(T,_){if(this.key)E(L9);if(this.branches.length)E(V9);return this.key=T,_?this.match(_):this}case(T,_){return this.caseEntry(this.$.parse(T),_)}caseEntry(T,_){let W=(this.key?this.$.parse({[this.key]:T}):T).pipe(_);return this.branches.push(W),this}match(T){return this(T)}strings(T){return this.caseEntries(Object.entries(T).map(([_,F])=>_==="default"?[_,F]:[this.$.node("unit",{unit:_}),F]))}caseEntries(T){for(let _=0;_<T.length;_++){let[F,W]=T[_];if(F==="default"){if(_!==T.length-1)E("default may only be specified as the last key of a switch definition");return this.default(W)}if(typeof W!=="function")return E(`Value for case "${F}" must be a function (was ${PT(W)})`);this.caseEntry(F,W)}return this}default(T){if(typeof T==="function")this.case(x.unknown,T);let _={branches:this.branches,ordered:!0};if(T==="never"||T==="assert")_.meta={onFail:r6};let F=this.$.node("union",_);if(!this.in)return this.$.finalize(F);let W=this.in.pipe(F);if(T==="never"||T==="assert")W=W.configureReferences({onFail:r6},"self");return this.$.finalize(W)}}var r6=(T)=>T.throw(),V9="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",L9="At most one key matcher may be specified per expression";var rW=(T,_)=>{if(XT(T)){if(T[1]==="=")return[_.$.parseOwnDefinitionFormat(T[0],_),"=",T[2]];if(T[1]==="?")return[_.$.parseOwnDefinitionFormat(T[0],_),"?"]}return sW(T,_)},s6="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",a6="Only required keys may specify default values, e.g. { value: 'number = 0' }";var e6=(T,_)=>{let F,W={},J=S0(T);for(let[$,Z]of J){let G=I9($);if(G.kind==="spread"){if(!h_(W))return E(S9);let V=_.$.parseOwnDefinitionFormat(Z,_);if(V.equals(x.object))continue;if(!V.hasKind("intersection")||!V.basis?.equals(x.object))return E(N9(V.expression));F=V.structure;continue}if(G.kind==="undeclared"){if(Z!=="reject"&&Z!=="delete"&&Z!=="ignore")E(D9(Z));W.undeclared=Z;continue}let X=rW(Z,_),O=G;if(G.kind==="required"){if(!XT(X))Z2(W,"required",{key:G.normalized,value:X},_);else Z2(W,"optional",X[1]==="="?{key:G.normalized,value:X[0],default:X[2]}:{key:G.normalized,value:X[0]},_);continue}if(XT(X)){if(X[1]==="?")E(s6);if(X[1]==="=")E(a6)}if(G.kind==="optional"){Z2(W,"optional",{key:G.normalized,value:X},_);continue}let M=_.$.parseOwnDefinitionFormat(O.normalized,_),Q=mW(M,X,_.$);if(Q.index)W.index=s(W.index,Q.index);if(Q.required)W.required=s(W.required,Q.required)}let Y=_.$.node("structure",W);return _.$.parseSchema({domain:"object",structure:F?.merge(Y)??Y})},Z2=(T,_,F,W)=>{T[_]=s(T[_],W.$.node(_,F))},D9=(T)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${d(T)})`,S9="Spread operator may only be used as the first key in an object",I9=(T)=>typeof T==="symbol"?{kind:"required",normalized:T}:T.at(-1)==="?"?T.at(-2)===DF?{kind:"required",normalized:`${T.slice(0,-2)}?`}:{kind:"optional",normalized:T.slice(0,-1)}:T[0]==="["&&T.at(-1)==="]"?{kind:"index",normalized:T.slice(1,-1)}:T[0]===DF&&T[1]==="["&&T.at(-1)==="]"?{kind:"required",normalized:T.slice(1)}:T==="..."?{kind:"spread"}:T==="+"?{kind:"undeclared"}:{kind:"required",normalized:T==="\\..."?"...":T==="\\+"?"+":T},N9=(T)=>`Spread operand must resolve to an object literal type (was ${T})`;var _Y=(T,_)=>x9(T)?YY[T[0]](T,_):y9(T)?JY[T[1]](T,_):null,C9=(T,_)=>_.$.parseOwnDefinitionFormat(T[1],_).keyof(),X2=(T,_)=>{if(T[2]===void 0)return E(_2(T[1],""));let F=_.$.parseOwnDefinitionFormat(T[0],_),W=_.$.parseOwnDefinitionFormat(T[2],_);if(T[1]==="|")return _.$.node("union",{branches:[F,W]});let J=T[1]==="&"?J_(F,W,_.$):jF(F,W,_.$);if(J instanceof N)return J.throw();return J},B9=(T,_)=>_.$.parseOwnDefinitionFormat(T[0],_).array(),k9=(T,_)=>{if(typeof T[2]!=="function")return E(FY("=>",T[2]));return _.$.parseOwnDefinitionFormat(T[0],_).pipe(T[2])},FY=(T,_)=>`${T===":"?"Narrow":"Morph"} expression requires a function following '${T}' (was ${typeof _})`,f9=(T,_)=>{if(typeof T[2]!=="function")return E(FY(":",T[2]));return _.$.parseOwnDefinitionFormat(T[0],_).constrain("predicate",T[2])},P9=(T,_)=>_.$.parseOwnDefinitionFormat(T[0],_).configureReferences(T[2],"shallow"),WY=(T)=>T,q9=WY({"[]":B9,"?":()=>E(cW)}),j9=WY({"|":X2,"&":X2,":":f9,"=>":k9,"|>":X2,"@":P9,"=":()=>E(dW)}),JY={...q9,...j9},y9=(T)=>JY[T[1]]!==void 0,v9=(T)=>T,YY=v9({keyof:C9,instanceof:(T,_)=>{if(typeof T[1]!=="function")return E(TY(VF(T[1])));let F=T.slice(1).map((W)=>typeof W==="function"?_.$.node("proto",{proto:W}):E(TY(VF(W))));return F.length===1?F[0]:_.$.node("union",{branches:F})},"===":(T,_)=>_.$.units(T.slice(1))}),x9=(T)=>YY[T[0]]!==void 0,TY=(T)=>`Expected a constructor following 'instanceof' operator (was ${T})`;var XY=(T,_)=>{let F=[{}],W=0;while(W<T.length){let J=!1;if(T[W]==="..."&&W<T.length-1)J=!0,W++;let Y=rW(T[W],_),[$,Z,G]=!XT(Y)?[Y]:Y;if(W++,J){if(!$.extends(z.intrinsic.Array))return E(p9($.expression));F=F.flatMap((X)=>$.distribute((O)=>h9(fW(X),O)))}else F=F.map((X)=>{if(Z==="?")return GY(X,$);if(Z==="=")return b9(X,$,G);return G2(X,$)})}return _.$.parseSchema(F.map((J)=>h_(J)?{proto:Array,exactLength:0}:{proto:Array,sequence:J}))},G2=(T,_)=>{if(T.defaultables||T.optionals)return E(T.variadic?g4:g9);if(T.variadic)T.postfix=s(T.postfix,_);else T.prefix=s(T.prefix,_);return T},GY=(T,_)=>{if(T.variadic)return E(AY);return T.optionals=s(T.optionals,_),T},b9=(T,_,F)=>{if(T.variadic)return E(AY);if(T.optionals)return E(m9);return T.defaultables=s(T.defaultables,[[_,F]]),T},$Y=(T,_)=>{if(T.postfix)E(ZY);if(T.variadic){if(!T.variadic.equals(_))E(ZY)}else T.variadic=_.internal;return T},h9=(T,_)=>{let F=_.select({method:"find",kind:"sequence"});if(!F)return $Y(T,z.intrinsic.unknown);if(F.prefix)for(let W of F.prefix)G2(T,W);if(F.optionals)for(let W of F.optionals)GY(T,W);if(F.variadic)$Y(T,F.variadic);if(F.postfix)for(let W of F.postfix)G2(T,W);return T},p9=(T)=>`Spread element must be an array (was ${T})`,ZY="A tuple may have at most one variadic element",g9="A required element may not follow an optional element",AY="An optional element may not follow a variadic element";var m9="A defaultable element may not follow an optional element without a default";var o9={},sW=(T,_)=>{if(typeof T==="string"){if(_.args&&Object.keys(_.args).some((W)=>T.includes(W)))return Y2(T,_);let F=o9[_.$.name]??={};return F[T]??=Y2(T,_)}return T_(T,"object")?u9(T,_):E(A2(PT(T)))},u9=(T,_)=>{let F=KF(T);switch(F){case void 0:if(P(T,"root"))return T;return e6(T,_);case"Array":return c9(T,_);case"RegExp":return _.$.node("intersection",{domain:"string",pattern:T},{prereduced:!0});case"Function":{let W=J0(T)?T():T;if(P(W,"root"))return W;return E(A2("Function"))}default:return E(A2(F??d(T)))}},c9=(T,_)=>_Y(T,_)??XY(T,_),A2=(T)=>`Type definitions must be strings or objects (was ${T})`;class H2 extends k_{constructor(T){let _=Object.assign({errors:F_,hkt:uT,$:T,raw:T.parse,module:T.constructor.module,scope:T.constructor.scope,define:T.define,match:T.match,generic:T.generic,schema:T.schema,keywords:T.ambient,unit:T.unit,enumerated:T.enumerated,instanceOf:T.instanceOf,valueOf:T.valueOf,or:T.or,and:T.and,merge:T.merge,pipe:T.pipe},T.ambientAttachments);super((...F)=>{if(F.length===1)return T.parse(F[0]);if(F.length===2&&typeof F[0]==="string"&&F[0][0]==="<"&&F[0].at(-1)===">"){let W=F[0].slice(1,-1),J=T.parseGenericParams(W,{});return new G0(J,F[1],T,T,null)}return T.parse(F)},{bind:T,attach:_})}}var WF=z;class aW extends oW{get ambientAttachments(){if(!WF.typeAttachments)return;return this.cacheGetter("ambientAttachments",c(WF.typeAttachments,(T,_)=>[T,this.bindReference(_)]))}preparseOwnAliasEntry(T,_){let F=T.indexOf("<");if(F===-1){if(P(_,"module")||P(_,"generic"))return[T,_];let Y=this.name==="ark"?T:T==="root"?this.name:`${this.name}.${T}`,$=this.resolvedConfig.keywords?.[Y];if($)_=[_,"@",$];return[T,_]}if(T.at(-1)!==">")E("'>' must be the last character of a generic declaration in a scope");let W=T.slice(0,F),J=T.slice(F+1,-1);return[W,()=>{let Y=this.parseGenericParams(J,{alias:W});return kJ(Y,_,this)}]}parseGenericParams(T,_){return nW(new r_(T),[],this.createParseContext({..._,def:T,prefix:"generic"}))}normalizeRootScopeValue(T){if(J0(T)&&!P(T,"generic"))return T();return T}preparseOwnDefinitionFormat(T,_){return{..._,def:T,prefix:_.alias??"type"}}parseOwnDefinitionFormat(T,_){if(!(_.alias&&(_.alias in this.aliases))&&!_.args)_.args={this:_.id};let W=sW(T,_);if(XT(W)){if(W[1]==="=")return E(dW);if(W[1]==="?")return E(cW)}return W}unit=(T)=>this.units([T]);valueOf=(T)=>this.units(n8(T));enumerated=(...T)=>this.units(T);instanceOf=(T)=>this.node("proto",{proto:T},{prereduced:!0});or=(...T)=>this.schema(T.map((_)=>this.parse(_)));and=(...T)=>T.reduce((_,F)=>_.and(this.parse(F)),this.intrinsic.unknown);merge=(...T)=>T.reduce((_,F)=>_.merge(this.parse(F)),this.intrinsic.object);pipe=(...T)=>this.intrinsic.unknown.pipe(...T);match=new $2(this);declare=()=>({type:this.type});define(T){return T}type=new H2(this);static scope=(T,_={})=>new aW(T,_);static module=(T,_={})=>this.scope(T,_).export()}var O2=Object.assign(aW.scope,{define:(T)=>T}),r=aW;class HY extends uT{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var d9=V_(["base",x.object],["props",x.object])((T)=>T.base.merge(T.props),HY),OY=r.module({Key:x.key,Merge:d9});class UY extends uT{}var l9=V_("element")((T)=>{let _=T.element.exclude(x.Array),F=_.array();return _.rawOr(F).pipe(W0).distribute((W)=>W.assertHasKind("morph").declareOut(F),WT)},UY),MY=r.module({root:x.Array,readonly:"root",index:x.nonNegativeIntegerString,liftFrom:l9},{name:"Array"});var U2=WT(["string",N0.FileConstructor]),t9=U2.rawOr(U2.array()),wY=WT({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:t9}}),QY=r.module({root:["instanceof",FormData],value:U2,parsed:wY,parse:WT({in:FormData,morphs:(T)=>{let _={};for(let[F,W]of T)if(F in _){let J=_[F];if(typeof J==="string"||J instanceof N0.FileConstructor)_[F]=[J,W];else J.push(W)}else _[F]=W;return _},declaredOut:wY})},{name:"FormData"});var RY=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 i9={Boolean:1,Number:1,String:1},EY=r.module({...c({...e1,..._4},(T,_)=>(T in i9)?[]:[T,["instanceof",_]]),Array:MY,TypedArray:RY,FormData:QY});var n9=WT({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"}),r9=WT({domain:"number",divisor:1}),eW=r.module({root:x.number,integer:r9,epoch:n9,safe:WT({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 ET=(T,_,F)=>{let W={domain:"string",pattern:{rule:T.source,flags:T.flags,meta:_}};if(F)W.meta={format:F};return TF("intersection",W)},zY=ET(SF,"a well-formed integer string"),PY=r.module({root:zY,parse:WT({in:zY,morphs:(T,_)=>{let F=Number.parseInt(T);return Number.isSafeInteger(F)?F:_.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:x.integer})},{name:"string.integer"}),s9=ET(/^[\dA-Fa-f]+$/,"hex characters only"),a9=r.module({root:ET(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:ET(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),KY=ET(/^[A-Z].*$/,"capitalized"),e9=r.module({root:WT({in:"string",morphs:(T)=>T.charAt(0).toUpperCase()+T.slice(1),declaredOut:KY}),preformatted:KY},{name:"string.capitalize"}),T7=(T)=>{let _=T.replaceAll(/[ -]+/g,""),F=0,W,J,Y=!1;for(let $=_.length-1;$>=0;$--){if(W=_.substring($,$+1),J=Number.parseInt(W,10),Y)J*=2,F+=J>=10?J%10+1:J;else F+=J;Y=!Y}return!!(F%10===0?_:!1)},_7=/^(?: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}))$/,F7=WT({domain:"string",pattern:{meta:"a credit card number",rule:_7.source},predicate:{meta:"a credit card number",predicate:T7}});var W7=/^([+-]?\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 J7=(T)=>!Number.isNaN(new Date(T).valueOf()),VY=WT({domain:"string",predicate:{meta:"a parsable date",predicate:J7}}).assertHasKind("intersection"),LY=PY.root.internal.narrow((T,_)=>{let F=Number.parseInt(T),W=eW.epoch(F);if(W instanceof F_)return _.errors.merge(W),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),Y7=r.module({root:LY,parse:WT({in:LY,morphs:(T)=>new Date(T),declaredOut:x.Date})},{name:"string.date.epoch"}),DY=ET(W7,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),$7=r.module({root:DY,parse:WT({in:DY,morphs:(T)=>new Date(T),declaredOut:x.Date})},{name:"string.date.iso"}),Z7=r.module({root:VY,parse:WT({declaredIn:VY,in:"string",morphs:(T,_)=>{let F=new Date(T);if(Number.isNaN(F.valueOf()))return _.error("a parsable date");return F},declaredOut:x.Date}),iso:$7,epoch:Y7},{name:"string.date"}),X7=ET(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),SY="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A0=`(${SY}[.]){3}${SY}`,G7=new RegExp(`^${A0}$`),CT="(?:[0-9a-fA-F]{1,4})",A7=new RegExp(`^((?:${CT}:){7}(?:${CT}|:)|(?:${CT}:){6}(?:${A0}|:${CT}|:)|(?:${CT}:){5}(?::${A0}|(:${CT}){1,2}|:)|(?:${CT}:){4}(?:(:${CT}){0,1}:${A0}|(:${CT}){1,3}|:)|(?:${CT}:){3}(?:(:${CT}){0,2}:${A0}|(:${CT}){1,4}|:)|(?:${CT}:){2}(?:(:${CT}){0,3}:${A0}|(:${CT}){1,5}|:)|(?:${CT}:){1}(?:(:${CT}){0,4}:${A0}|(:${CT}){1,6}|:)|(?::((?::${CT}){0,5}:${A0}|(?::${CT}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),H7=r.module({root:["v4 | v6","@","an IP address"],v4:ET(G7,"an IPv4 address","ipv4"),v6:ET(A7,"an IPv6 address","ipv6")},{name:"string.ip"}),JF="a JSON string",qY=(T)=>{if(!(T instanceof SyntaxError))throw T;return`must be ${JF} (${T})`},O7=WT({meta:JF,domain:"string",predicate:{meta:JF,predicate:(T,_)=>{try{return JSON.parse(T),!0}catch(F){return _.reject({code:"predicate",expected:JF,problem:qY(F)})}}}}),U7=(T,_)=>{if(T.length===0)return _.error({code:"predicate",expected:JF,actual:"empty"});try{return JSON.parse(T)}catch(F){return _.error({code:"predicate",expected:JF,problem:qY(F)})}},M7=r.module({root:O7,parse:WT({meta:"safe JSON string parser",in:"string",morphs:U7,declaredOut:x.jsonObject})},{name:"string.json"}),IY=ET(/^[a-z]*$/,"only lowercase letters"),w7=r.module({root:WT({in:"string",morphs:(T)=>T.toLowerCase(),declaredOut:IY}),preformatted:IY},{name:"string.lower"}),jY=["NFC","NFD","NFKC","NFKD"],lF=c(jY,(T,_)=>[_,WT({domain:"string",predicate:(F)=>F.normalize(_)===F,meta:`${_}-normalized unicode`})]),T1=c(jY,(T,_)=>[_,WT({in:"string",morphs:(F)=>F.normalize(_),declaredOut:lF[_]})]),Q7=r.module({root:T1.NFC,preformatted:lF.NFC},{name:"string.normalize.NFC"}),R7=r.module({root:T1.NFD,preformatted:lF.NFD},{name:"string.normalize.NFD"}),E7=r.module({root:T1.NFKC,preformatted:lF.NFKC},{name:"string.normalize.NFKC"}),z7=r.module({root:T1.NFKD,preformatted:lF.NFKD},{name:"string.normalize.NFKD"}),K7=r.module({root:"NFC",NFC:Q7,NFD:R7,NFKC:E7,NFKD:z7},{name:"string.normalize"}),NY=ET(CW,"a well-formed numeric string"),V7=r.module({root:NY,parse:WT({in:NY,morphs:(T)=>Number.parseFloat(T),declaredOut:x.number})},{name:"string.numeric"}),CY="a regex pattern",L7=WT({domain:"string",predicate:{meta:CY,predicate:(T,_)=>{try{return new RegExp(T),!0}catch(F){return _.reject({code:"predicate",expected:CY,problem:String(F)})}}},meta:{format:"regex"}}),D7=/^(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-]+)*))?$/,S7=ET(D7,"a semantic version (see https://semver.org/)"),BY=ET(/^\S.*\S$|^\S?$/,"trimmed"),I7=r.module({root:WT({in:"string",morphs:(T)=>T.trim(),declaredOut:BY}),preformatted:BY},{name:"string.trim"}),kY=ET(/^[A-Z]*$/,"only uppercase letters"),N7=r.module({root:WT({in:"string",morphs:(T)=>T.toUpperCase(),declaredOut:kY}),preformatted:kY},{name:"string.upper"}),C7=(T)=>{if(URL.canParse)return URL.canParse(T);try{return new URL(T),!0}catch{return!1}},fY=WT({domain:"string",predicate:{meta:"a URL string",predicate:C7},meta:{format:"uri"}}),B7=r.module({root:fY,parse:WT({declaredIn:fY,in:"string",morphs:(T,_)=>{try{return new URL(T)}catch{return _.error("a URL string")}},declaredOut:WT(URL)})},{name:"string.url"}),k7=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:ET(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:ET(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:ET(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:ET(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:ET(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:ET(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:ET(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:ET(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),yY=r.module({root:x.string,alpha:ET(/^[A-Za-z]*$/,"only letters"),alphanumeric:ET(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:s9,base64:a9,capitalize:e9,creditCard:F7,date:Z7,digits:ET(/^\d*$/,"only digits 0-9"),email:X7,integer:PY,ip:H7,json:M7,lower:w7,normalize:K7,numeric:V7,regex:L7,semver:S7,trim:I7,upper:N7,url:B7,uuid:k7},{name:"string"});var vY=r.module({bigint:x.bigint,boolean:x.boolean,false:x.false,never:x.never,null:x.null,number:x.number,object:x.object,string:x.string,symbol:x.symbol,true:x.true,unknown:x.unknown,undefined:x.undefined}),xY=r.module({root:x.unknown,any:x.unknown},{name:"unknown"}),f7=r.module({root:x.jsonObject,stringify:TF("morph",{in:x.jsonObject,morphs:(T)=>JSON.stringify(T),declaredOut:x.string})},{name:"object.json"}),bY=r.module({root:x.object,json:f7},{name:"object"});class hY extends uT{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var P7=V_(["K",x.key],"V")((T)=>({domain:"object",index:{signature:T.K,value:T.V}}),hY);class pY extends uT{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var q7=V_(["T",x.object],["K",x.key])((T)=>T.T.pick(T.K),pY);class gY extends uT{description='omit a set of properties from an object like `Omit(User, "age")`'}var j7=V_(["T",x.object],["K",x.key])((T)=>T.T.omit(T.K),gY);class mY extends uT{description="make all named properties of an object optional like `Partial(User)`"}var y7=V_(["T",x.object])((T)=>T.T.partial(),mY);class oY extends uT{description="make all named properties of an object required like `Required(User)`"}var v7=V_(["T",x.object])((T)=>T.T.required(),oY);class uY extends uT{description='exclude branches of a union like `Exclude("boolean", "true")`'}var x7=V_("T","U")((T)=>T.T.exclude(T.U),uY);class cY extends uT{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var b7=V_("T","U")((T)=>T.T.extract(T.U),cY),dY=r.module({Exclude:x7,Extract:b7,Omit:j7,Partial:y7,Pick:q7,Record:P7,Required:v7});var H0=O2({...vY,...dY,...EY,...OY,string:yY,number:eW,object:bY,unknown:xY},{prereducedAliases:!0,name:"ark"}),jT=H0.export();Object.assign(WF.ambient,jT);WF.typeAttachments={string:jT.string.root,number:jT.number.root,bigint:jT.bigint,boolean:jT.boolean,symbol:jT.symbol,undefined:jT.undefined,null:jT.null,object:jT.object.root,unknown:jT.unknown.root,false:jT.false,true:jT.true,never:jT.never,arrayIndex:jT.Array.index,Key:jT.Key,Record:jT.Record,Array:jT.Array.root,Date:jT.Date};var Y_=Object.assign(H0.type,WF.typeAttachments),h7=H0.match,p7=H0.generic,qL=H0.schema,g7=H0.define,m7=H0.declare;class tF extends Promise{fate;resolve;reject;done=!1;constructor(T){let _,F;super((W,J)=>{_=W,F=J});this.resolve=_,this.reject=F,this.use(T instanceof Promise?T:new Promise(T))}pass(T,_){if(T===this.fate)this.resolve(_),this.done=!0}fail(T,_){if(T===this.fate)this.reject(_),this.done=!0}use(T){if(T instanceof Promise){let _=T;this.fate=_,_.then((F)=>{this.pass(_,F)},(F)=>{this.fail(_,F)})}else this.resolve(T),this.fate=void 0}}var rL=(T,_,F=tY.STORE)=>{return lY(F,{key:`${T.key}:JSON`,get:({get:W})=>_.toJson(W(T)),set:({set:W},J)=>{W(T,_.fromJson(J))}})};function eL(T,_,F){return M2(T,{key:`${_.key}:JSON`,get:(J)=>({get:Y})=>{let $=Y(_,J);return F.toJson($)},set:(J)=>({set:Y},$)=>{Y(_,J,F.fromJson($))}},["mutable","json"])}var iF=(T)=>JSON.parse(T),rT=(T)=>JSON.stringify(T),_D=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function m(T){while(T.child!==null)T=T.child;return T}class _1{_buffer;_index=0;constructor(T){let _;if(typeof T==="number")_=T;else _=T.length;this._buffer=Array.from({length:_})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new _1([...this._buffer]);return T._index=this._index,T}}var o7={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"};function iY(T,_){let F=rT(_),W=`${T.key}(${F})`,J=o7[T.type],Y={key:W,type:J};return Object.assign(Y,{family:{key:T.key,subKey:F}}),Object.assign(Y,{counterfeit:!0}),Y}function nF(T){let _={key:T.key,type:T.type};if("family"in T)_.family=T.family;return _}var w2=(T)=>(_,F,W,J,...Y)=>{console[T](`${_} ${F} "${W}" ${J}`,...Y)},u7={error:w2("error"),info:w2("info"),warn:w2("warn")};class Q2{logLevel;filter;logger;constructor(T,_,F=u7){this.logLevel=T,this.filter=_,this.logger=F}error=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel!==null){if(_===!0)this.logger.error(...T);else if(_!==!1)this.logger.error(..._)}};info=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel==="info"){if(_===!0)this.logger.info(...T);else if(_!==!1)this.logger.info(..._)}};warn=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel!=="error"&&this.logLevel!==null){if(_===!0)this.logger.warn(...T);else if(_!==!1)this.logger.warn(..._)}}}class g_{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,_)=>`${T}:${_}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,_){let F=this.relations.get(T),W=this.relations.get(_);if(F)F.add(_);else F=new Set([_]),this.relations.set(T,F);if(W)W.add(T);else W=new Set([T]),this.relations.set(_,W)}deleteRelation(T,_){let F=this.relations.get(T);if(F){if(F.delete(_),F.size===0)this.relations.delete(T);let W=this.relations.get(_);if(W){if(W.delete(T),W.size===0)this.relations.delete(_)}}}replaceRelationsUnsafely(T,_){this.relations.set(T,new Set(_));for(let F of _){let W=new Set().add(T);this.relations.set(F,W)}}replaceRelationsSafely(T,_){let F=this.relations.get(T),W=this.isAType?.(T)?T:void 0,J=W===void 0?T:void 0;if(F)for(let Y of F){W??=Y,J??=Y;let $=this.relations.get(Y);if($){if($.size===1)this.relations.delete(Y);else $.delete(T);this.contents.delete(this.makeContentKey(W,J))}}this.relations.set(T,new Set(_));for(let Y of _){let $=this.relations.get(Y);if($)$.add(T);else $=new Set().add(T),this.relations.set(Y,$)}}getContentInternal(T){return this.contents.get(T)}setContent(T,_){this.contents.set(T,_)}deleteContent(T){this.contents.delete(T)}constructor(T,_){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!_?.externalStore)this.relations=new Map(T.relations?.map(([F,W])=>[F,new Set(W)])),this.contents=new Map(T.contents);if(this.isAType=_?.isAType??null,this.isBType=_?.isBType??null,this.isContent=_?.isContent??null,_?.makeContentKey)this.makeContentKey=_.makeContentKey;if(_?.externalStore){let F=_.externalStore;if(this.has=(W,J)=>F.has(W,J),this.addRelation=(W,J)=>{F.addRelation(W,J)},this.deleteRelation=(W,J)=>{F.deleteRelation(W,J)},this.replaceRelationsSafely=(W,J)=>{F.replaceRelationsSafely(W,J)},this.replaceRelationsUnsafely=(W,J)=>{F.replaceRelationsUnsafely(W,J)},this.getRelatedKeys=(W)=>F.getRelatedKeys(W),F.getContent)this.getContentInternal=(W)=>{return F.getContent(W)},this.setContent=(W,J)=>{F.setContent(W,J)},this.deleteContent=(W)=>{F.deleteContent(W)};for(let[W,J]of T.relations??[]){let Y=this.isAType?.(W)?W:void 0,$=Y===void 0?W:void 0;for(let Z of J)Y??=Z,$??=Z,this.addRelation(Y,$)}for(let[W,J]of T.contents??[])this.setContent(W,J)}if(_?.warn)this.warn=_.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,_])=>[T,[..._]]),contents:[...this.contents.entries()]}}set(...T){let _,F,W;switch(T.length){case 1:{let J=T[0];_=J[this.a],F=J[this.b],W=void 0;break}case 2:{let J=T[0];if(typeof J==="string")[_,F]=T;else _=J[this.a],F=J[this.b],W=T[1];break}default:{_=T[0],F=T[1],W=T[2];break}}switch(this.cardinality){case"1:1":{let J=this.getRelatedKey(_);if(J&&J!==F)this.delete(_,J)}case"1:n":{let J=this.getRelatedKey(F);if(J&&J!==_)this.delete(J,F)}break;case"n:n":}if(W){let J=this.makeContentKey(_,F);this.setContent(J,W)}return this.addRelation(_,F),this}delete(T,_){_=typeof _==="string"?_:T[this.b];let F=typeof T==="string"?T:T[this.a];if(F===void 0&&typeof _==="string"){let W=this.getRelatedKeys(_);if(W)for(let J of W)this.delete(J,_)}if(typeof F==="string"&&_===void 0){let W=this.getRelatedKeys(F);if(W)for(let J of W)this.delete(F,J)}if(typeof F==="string"&&typeof _==="string"){this.deleteRelation(F,_);let W=this.makeContentKey(F,_);this.deleteContent(W)}return this}getRelatedKey(T){let _=this.getRelatedKeys(T);if(_){if(_.size>1)this.warn?.(`${_.size} related keys were found for key "${T}": (${[..._].map((W)=>`"${W}"`).join(", ")}). Only one related key was expected.`);let F;for(let W of _){F=W;break}return F}}replaceRelations(T,_,F){let W=!Array.isArray(_),J=W?Object.keys(_):_;if(F?.reckless)this.replaceRelationsUnsafely(T,J);else this.replaceRelationsSafely(T,J);if(W)for(let Y of J){let $=this.makeContentKey(T,Y),Z=_[Y];this.setContent($,Z)}return this}getContent(T,_){let F=this.makeContentKey(T,_);return this.getContentInternal(F)}getRelationEntries(T){let _=T[this.a],F=T[this.b];if(_!==void 0&&F===void 0){let W=this.getRelatedKeys(_);if(W)return[...W].map((J)=>{return[J,this.getContent(_,J)]})}if(_===void 0&&F!==void 0){let W=this.getRelatedKeys(F);if(W)return[...W].map((J)=>{return[J,this.getContent(J,F)]})}return[]}has(T,_){if(_)return this.getRelatedKeys(T)?.has(_)??!1;return this.relations.has(T)}}class FT{Subscriber;subscribers=new Map;subscribe(T,_){return this.subscribers.set(T,_),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let _=this.subscribers.values();for(let F of _)F(T)}}class R2 extends FT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function O0(T){return"epoch"in T.transactionMeta}function M_(T){return"phase"in T.transactionMeta}function nY(T){return T[0].toUpperCase()+T.slice(1)}function F1(T){return T.type.split("_").map(nY).join(" ")}class rF extends Error{constructor(T,_){super(`${F1(T)} ${rT(T.key)} not found in store "${_.config.name}".`)}}var YF=(T)=>(_)=>T instanceof Function?T(_):T;var U0=(T,_)=>{if(T.valueMap.has(_.key))return T.logger.info("\uD83D\uDCD6",_.type,_.key,"reading cached value"),rY(_,T);switch(_.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return T.logger.info("\uD83E\uDDEE",_.type,_.key,"computing value"),_.get();case"atom":case"mutable_atom":{let F=_.default,W;if(F instanceof Function)W=F();else W=F;return T.logger.info("\uD83D\uDC81","atom",_.key,"could not find cached value; using default",W),W}}};var sY=(T,_)=>{if(T.operation.open){let F=performance.now();return T.logger.info("\u2757",_.type,_.key,`deferring setState at T-${F} until setState for "${T.operation.token.key}" is done`),F}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:_},T.logger.info("\u2B55",_.type,_.key,`operation start in store "${T.config.name}"${!M_(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},aY=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},eY=(T,_)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",_,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(_)},M0=(T,_)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",_,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(_)};var T$=(T,_,F)=>{switch(_.type){case"mutable_atom":T.logger.info("\uD83D\uDCE2",_.type,_.key,"is now (",F.newValue,") subscribers:",_.subject.subscribers);break;case"atom":case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":T.logger.info("\uD83D\uDCE2",_.type,_.key,"went (",F.oldValue,"->",F.newValue,") subscribers:",_.subject.subscribers)}_.subject.next(F)};var E2=(T,_)=>{let F=m(T),W=F.selectorAtoms.getRelatedKeys(_.key);if(F.logger.info("\uD83E\uDDF9",_.type,_.key,W?`evicting ${W.size} states downstream:`:"no downstream states",W??"to evict"),W){if(F.operation.open)F.logger.info("\uD83E\uDDF9",_.type,_.key,`[ ${[...F.operation.done].join(", ")} ] already done`);for(let J of W){if(eY(F,J))continue;_$(J,F),M0(F,J)}}};var F$=(T,_,F)=>{let W=U0(T,_),J=W;if(_.type==="mutable_atom"&&M_(T)){let{parent:$}=T;J=sF(T,_,$)}if(J=YF(F)(J),T.logger.info("\uD83D\uDCDD","atom",_.key,"set to",J),J=sT(T,_.key,J,_.subject),J$(T,_.key))Y$(T,_.key);M0(T,_.key),E2(T,_);let Y={oldValue:W,newValue:J};if(!M_(T)){T$(T,_,Y);return}if(T.on.transactionApplying.state===null){let{key:$}=_;if(W$(Y.newValue))return;let Z={type:"atom_update",key:$,...Y};if(_.family)Z.family=_.family;T.transactionMeta.update.updates.push(Z),T.logger.info("\uD83D\uDCC1","atom",$,"stowed (",Y.oldValue,"->",Y.newValue,")")}else if(_.key.startsWith("*")){let $=_.key.slice(1),Z=T.atoms.get($),G=T.valueMap.get($);if(Z.type==="mutable_atom"&&M_(T)){let{parent:O}=T;G=sF(T,Z,O)}if(G.do(Y.newValue)===null)E2(T,Z)}};var W1=(T,_,F)=>{switch(_.type){case"atom":case"mutable_atom":F$(T,_,F);break;case"writable_pure_selector":case"writable_held_selector":_.set(F);break}};var J1=(T,_)=>m(T).atoms.has(_),c7=(T,_)=>m(T).writableSelectors.has(_),d7=(T,_)=>m(T).readonlySelectors.has(_),$$=(T,_)=>J1(T,_)||c7(T,_)||d7(T,_);var Y1=(T,_)=>{return m(T).selectorGraph.getRelationEntries({downstreamSelectorKey:_}).filter(([W,{source:J}])=>J!==_).map(([W,{source:J}])=>J).filter((W)=>$$(T,W))};var z2=(T,_,F)=>{let W=[],J=Y1(T,_);while(J.length>0){let Y=J.shift();if(F.has(Y))continue;if(F.add(Y),!J1(T,Y))J.push(...Y1(T,Y));else if(!W.includes(Y))W.push(Y)}return W},Z$=(T,_)=>{let F=T.key,W=Y1(_,F),J=new Set;return W.flatMap((Y)=>J1(_,Y)?Y:z2(_,Y,J))};var X$=(T,_,F,W,J)=>{let Y=m(T),{type:$,key:Z}=W;if($==="atom"||$==="mutable_atom")Y.selectorAtoms.set({selectorKey:F,atomKey:Z}),T.logger.info("\uD83D\uDD0D",_,F,`discovers root atom "${Z}"`);else{let G=z2(T,Z,J);T.logger.info("\uD83D\uDD0D",_,F,`discovers root atoms: [ ${G.map((X)=>`"${X}"`).join(", ")} ]`);for(let X of G)Y.selectorAtoms=Y.selectorAtoms.set({selectorKey:F,atomKey:X})}J.add(Z)};var w0=(T,_,F,W)=>({get:(...J)=>{let Y=m(T),$;if(J.length===2){let[O,M]=J;$=w_(T,O,M)}else[$]=J;let Z=$_(T,$),G=U0(T,Z),X=$.key;return T.logger.info("\uD83D\uDD0C",_,F,`registers dependency ( "${X}" =`,G,")"),Y.selectorGraph.set({upstreamSelectorKey:X,downstreamSelectorKey:F},{source:$.key}),X$(T,_,F,$,W),G},set:(...J)=>{let Y,$;if(J.length===2)Y=J[0],$=J[1];else{let X=J[0],O=J[1];$=J[2],Y=w_(T,X,O)}let Z=m(T),G=$_(Z,Y);W1(Z,G,$)},find:(...J)=>w_(T,...J),json:(J)=>$F(T,J)});var K2=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,{key:$,const:Z}=_,G="readonly_held_selector",{get:X,find:O,json:M}=w0(W,"readonly_held_selector",$,Y),V={..._,type:"readonly_held_selector",subject:J,install:(K)=>K2(K,_,F),get:()=>{return _.get({get:X,find:O,json:M},Z),sT(m(T),$,Z,J),Y.clear(),Z},...F&&{family:F}};W.readonlySelectors.set($,V),T.logger.info("\u2728","readonly_held_selector",$,"=",Z);let B={key:$,type:"readonly_held_selector"};if(F)B.family=F;return B};var V2=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,$=_.key,Z="readonly_pure_selector",{get:G,find:X,json:O}=w0(W,"readonly_pure_selector",$,Y),M=()=>{let K=_.get({get:G,find:X,json:O});return sT(m(T),$,K,J),Y.clear(),K},Q={..._,type:"readonly_pure_selector",subject:J,install:(K)=>V2(K,_,F),get:M,...F&&{family:F}};W.readonlySelectors.set($,Q);let V=M();T.logger.info("\u2728","readonly_pure_selector",$,"=",V);let B={key:$,type:"readonly_pure_selector"};if(F)B.family=F;return B};var L2=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,{key:$,const:Z}=_,G="writable_held_selector",X=w0(W,"writable_held_selector",$,Y),{find:O,get:M,json:Q}=X,V={find:O,get:M,json:Q},B=(y=_.get,u=m(T))=>{return y(V,Z),sT(u,$,Z,J),Y.clear(),Z},v={..._,type:"writable_held_selector",subject:J,install:(y)=>L2(y,_,F),get:B,set:(y)=>{let u=m(T),h=B(_.get,u),p=YF(y)(h);if(T.logger.info("\uD83D\uDCDD","writable_held_selector",$,"set (",h,"->",p,")"),sT(u,$,p,J),M0(u,$),O0(u))J.next({newValue:p,oldValue:h});_.set(X,p)},...F&&{family:F}};W.writableSelectors.set($,v);let q=B();T.logger.info("\u2728","writable_held_selector",$,"=",q);let j={key:$,type:"writable_held_selector"};if(F)j.family=F;return j};var aF=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,$=_.key,Z="writable_pure_selector",G=w0(W,"writable_pure_selector",$,Y),{find:X,get:O,json:M}=G,Q={find:X,get:O,json:M},V=(j=_.get,y=m(T))=>{let u=j(Q);return sT(y,$,u,J),Y.clear(),u},K={..._,type:"writable_pure_selector",subject:J,install:(j)=>aF(j,_,F),get:V,set:(j)=>{let y=m(T),u=V(_.get,y),h=YF(j)(u);if(T.logger.info("\uD83D\uDCDD","writable_pure_selector",$,"set (",u,"->",h,")"),sT(y,_.key,h,J),M0(y,_.key),O0(y))J.next({newValue:h,oldValue:u});_.set(G,h)},...F&&{family:F}};W.writableSelectors.set($,K);let v=V();T.logger.info("\u2728",K.type,K.key,"=",v);let q={key:$,type:"writable_pure_selector"};if(F)q.family=F;return q};function lY(T,_){let F="set"in _,W="const"in _;if(W&&F){let Y=L2(T,_,void 0);return T.on.selectorCreation.next(Y),Y}if(W){let Y=K2(T,_,void 0);return T.on.selectorCreation.next(Y),Y}if(F){let Y=aF(T,_,void 0);return T.on.selectorCreation.next(Y),Y}let J=V2(T,_,void 0);return T.on.selectorCreation.next(J),J}function M2(T,_,F){let W=_.key,J="writable_pure_selector_family",Y={key:W,type:"writable_pure_selector_family"},$=T.families.get(W);if($)T.logger.error("\u2757","writable_pure_selector_family",W,`Overwriting an existing ${F1($)} "${$.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let Z=new FT,X=Object.assign((O)=>{let M=rT(O),Q={key:W,subKey:M},V=`${W}(${M})`,B=m(T),K=aF(B,{key:V,get:_.get(O),set:_.set(O)},Q);return Z.next({type:"state_creation",token:K}),K},Y,{internalRoles:F,subject:Z,install:(O)=>M2(O,_),default:(O)=>{return _.get(O)({get:(...Q)=>eF(T,...Q),find:(...Q)=>w_(T,...Q),json:(Q)=>$F(T,Q)})}});return T.families.set(W,X),Y}function G$(T,_,F){let W=T.families.get(_.key);if(W===void 0)throw new rF(_,T);let J=W(F),Y=m(T);if(J.family){if(O0(Y))switch(J.type){case"atom":case"mutable_atom":T.on.atomCreation.next(J);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":T.on.selectorCreation.next(J);break}else if(M_(Y)&&Y.on.transactionApplying.state===null)Y.transactionMeta.update.updates.push({type:"state_creation",token:J})}return J}function A$(T,_,F){let W=rT(F),J=`${_.key}(${W})`,Y=m(T),$;switch(_.type){case"atom_family":case"mutable_atom_family":$=Y.atoms.get(J);break;case"writable_held_selector_family":case"writable_pure_selector_family":$=Y.writableSelectors.get(J);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":$=Y.readonlySelectors.get(J);break}if($)return nF($);return $}function w_(T,_,F){let W=A$(T,_,F);if(W)return W;let J=rT(F),Y=T.molecules.get(J);if(!Y&&T.config.lifespan==="immortal"){let $=iY(_,F);return T.logger.error("\u274C",$.type,$.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),$}if(W=G$(T,_,F),Y)m(T).moleculeData.set(J,_.key);return W}function H$(T,_){if(_.family){let F=T.families.get(_.family.key);if(F)return F}}function Q0(T,..._){let F,W,J,Y;if(_.length===2){if(F=_[0],Y=_[1],W=H$(T,F)??null,W)J=F.family?iF(F.family.subKey):null,F=w_(T,W,J)}else W=_[0],J=_[1],Y=_[2],F=w_(T,W,J);if("counterfeit"in F&&"family"in F){let G=F.family.subKey,X=T.disposalTraces.buffer.find((O)=>O?.key===G);T.logger.error("\u274C",F.type,F.key,`could not be set because it was not found in the store "${T.config.name}".`,X?`This state was previously disposed:
|
|
48
|
-
${
|
|
49
|
-
${$.trace}`:"No previous disposal trace was found."),W.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(W.key);case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(T.defaults.has(W.key))return T.defaults.get(F.family.key);let Z=$_(T,W).default(Y);return T.defaults.set(W.key,Z),Z}}}return U0(T,$_(T,F))}class O${parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new g_({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new g_({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new g_({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new g_({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new _1(100);molecules=new Map;moleculeJoins=new g_({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new g_({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new g_({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new FT,atomDisposal:new FT,selectorCreation:new FT,selectorDisposal:new FT,timelineCreation:new FT,transactionCreation:new FT,transactionApplying:new R2(null),operationClose:new FT,moleculeCreation:new FT,moleculeDisposal:new FT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Q2("warn",(T,_,F)=>!M$(F))];logger={error:(...T)=>{for(let _ of this.loggers)_.error(...T)},info:(...T)=>{for(let _ of this.loggers)_.info(...T)},warn:(...T)=>{for(let _ of this.loggers)_.warn(...T)}};constructor(T,_=null){if(this.config={..._?.config,...T},_!==null){if(this.valueMap=new Map(_?.valueMap),this.operation={..._?.operation},O0(_))this.transactionMeta={epoch:new Map(_?.transactionMeta.epoch),actionContinuities:new g_(_?.transactionMeta.actionContinuities.toJSON())};for(let[,W]of _.families){if(W.internalRoles?.includes("mutable")||W.internalRoles?.includes("join"))continue;W.install(this)}let F=new Set;for(let[,W]of _.atoms){if(F.has(W.key))continue;if(W.install(this),W.type==="mutable_atom"){let J=$F(_,W),Y=U$(W);F.add(J.key),F.add(Y.key)}}for(let[,W]of _.readonlySelectors)W.install(this);for(let[,W]of _.writableSelectors){if(F.has(W.key))continue;W.install(this)}for(let[,W]of _.transactions)W.install(this);for(let[,W]of _.timelines)W.install(this)}}}var tY={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new O$({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function $_(T,_){let F,W=T;while(W!==null){switch(_.type){case"atom":case"mutable_atom":F=W.atoms.get(_.key);break;case"writable_pure_selector":case"writable_held_selector":F=W.writableSelectors.get(_.key);break;case"readonly_pure_selector":case"readonly_held_selector":F=W.readonlySelectors.get(_.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":F=W.families.get(_.key);break;case"timeline":F=W.timelines.get(_.key);break;case"transaction":F=W.transactions.get(_.key);break}if(F)return F;W=W.child}throw new rF(_,T)}var w$=(T,_)=>{let F=m(T);if(F.operation.open)return F.operation.prev.get(_.key);return F.valueMap.get(_.key)};var D2=(T,_)=>{let F=m(T);return Z$(_,T).map((J)=>{let Y=F.atoms.get(J);if(Y===void 0)throw new Error(`Atom "${J}", a dependency of selector "${_.key}", not found in store "${T.config.name}".`);return Y.subject.subscribe(`${_.type}:${_.key}`,($)=>{T.logger.info("\uD83D\uDCE2",_.type,_.key,"root",J,"went",$.oldValue,"->",$.newValue);let Z=w$(F,_),G=U0(F,_);T.logger.info("\u2728",_.type,_.key,"went",Z,"->",G),_.subject.next({newValue:G,oldValue:Z})})})};function TW(T,_,F,W){function J(M){if(T.operation.open){let Q=T.on.operationClose.subscribe(`state subscription ${F}`,()=>{Q(),W(M)})}else W(M)}let Y=$_(T,_);T.logger.info("\uD83D\uDC40",Y.type,Y.key,`Adding subscription "${F}"`);let $=Y.type==="writable_pure_selector"||Y.type==="readonly_pure_selector",Z=null,G=J;if($)Z=D2(T,Y),G=(M)=>{if(Z)Z.length=0,Z.push(...D2(T,Y));J(M)};let X=Y.subject.subscribe(F,G);return()=>{if(T.logger.info("\uD83D\uDE48",Y.type,Y.key,`Removing subscription "${F}"`),X(),Z)for(let M of Z)M()}}var Q$=(T,_,F,W)=>{let J=$_(T,_);T.logger.info("\uD83D\uDC40","timeline",_.key,`Adding subscription "${F}"`);let Y=J.subject.subscribe(F,W);return()=>{T.logger.info("\uD83D\uDE48","timeline",_.key,`Removing subscription "${F}" from timeline`),Y()}};class S2{initializeState(T,_){let F=`*${T.key}`;_.atoms.delete(F),_.valueMap.delete(F);let W=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,J=I2(_,{key:F,default:null},W);if(_.parent?.valueMap.has(F)){let Y=_.parent.valueMap.get(F);_.valueMap.set(F,Y)}return J}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,_,F){let W=`tracker:${F.config.name}:${M_(F)?F.transactionMeta.update.key:"main"}:${T.key}`,J=eF(F,T);this.unsubscribeFromInnerValue=J.subscribe(W,(Y)=>{Q0(F,_,Y)}),this.unsubscribeFromState=TW(F,T,W,(Y)=>{if(Y.newValue!==Y.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=Y.newValue.subscribe(W,($)=>{Q0(F,_,$)})})}updateCore(T,_,F){let W=`tracker:${F.config.name}:${M_(F)?F.transactionMeta.update.key:"main"}:${T.key}`;TW(F,_,W,({newValue:J,oldValue:Y})=>{let $=F.timelineTopics.getRelatedKey(_.key);if($){if(F.timelines.get($)?.timeTraveling){let X=Q$(F,{key:$,type:"timeline"},W,(O)=>{X(),Q0(F,T,(M)=>{if(O==="redo"&&J)M.do(J);else if(O==="undo"&&Y)M.undo(Y);return M})});return}}let Z=F.on.operationClose.subscribe(W,()=>{Z();let G=eF(F,T),X=J===null?-1:G.getUpdateNumber(J),O=X-G.cacheUpdateNumber;if(J&&O===1)Q0(F,T,(M)=>(M.do(J),M));else F.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${G.cacheUpdateNumber+1}, but got ${X}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(T,_){this.mutableState=T;let F=m(_);this.latestUpdateState=this.initializeState(T,F),this.observeCore(T,this.latestUpdateState,F),this.updateCore(T,this.latestUpdateState,F),F.trackers.set(T.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),F.trackers.delete(T.key)}}}var $F=(T,_)=>{if(_.family){let W=m(T),Y={key:`${_.family.key}:JSON`,type:"writable_pure_selector_family"},$=$_(W,Y),Z=JSON.parse(_.family.subKey);return w_(T,$,Z)}return{type:"writable_pure_selector",key:`${_.key}:JSON`}};var U$=(T)=>{let F={type:"atom",key:`*${T.key}`};if(T.family)F.family={key:`*${T.family.key}`,subKey:T.family.subKey};return F};function W$(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function sF(T,_,F){let W=F.valueMap.get(_.key),J=T.valueMap.get(_.key);if(W!==J)return J;if(W===void 0)return _.default();F.logger.info("\uD83D\uDCC3","atom",_.key,"copying");let Y=_.toJson(W),$=_.fromJson(Y);return T.valueMap.set(_.key,$),new S2(_,F),$}function sT(T,_,F,W){let J=T.valueMap.get(_);if(J instanceof tF)J.use(F);if(F instanceof Promise){let Y=new tF(F);return T.valueMap.set(_,Y),Y.then(($)=>{sT(T,_,$,W),W.next({newValue:$,oldValue:Y})}).catch(($)=>{T.logger.error("\uD83D\uDCA5","state",_,"rejected:",$)}),Y}return T.valueMap.set(_,F),F}var rY=(T,_)=>{let F=_.valueMap.get(T.key);if(T.type==="mutable_atom"&&M_(_)){let{parent:W}=_;F=sF(_,T,W)}return F},_$=(T,_)=>{let F=_.valueMap.get(T);if(F instanceof tF){let W=F,J=_.writableSelectors.get(T)??_.readonlySelectors.get(T);if(J)W.use(J.get());return}if(_.operation.open)_.operation.prev.set(T,F);_.valueMap.delete(T),_.logger.info("\uD83D\uDDD1","state",T,"evicted")};var J$=(T,_)=>{return m(T).atomsThatAreDefault.has(_)},R$=(T,_)=>{let F=m(T);F.atomsThatAreDefault=new Set(F.atomsThatAreDefault).add(_)},Y$=(T,_)=>{let F=m(T);F.atomsThatAreDefault=new Set(m(T).atomsThatAreDefault),F.atomsThatAreDefault.delete(_)};function I2(T,_,F){let{key:J,default:Y}=_;T.logger.info("\uD83D\uDD28","atom",J,`creating in store "${T.config.name}"`);let $=m(T),Z=$.atoms.get(J);if(Z&&Z.type==="atom")return T.logger.error("\u274C","atom",J,"Tried to create atom, but it already exists in the store."),nF(Z);let G=new FT,X={..._,type:"atom",install:(Q)=>{return Q.logger.info("\uD83D\uDEE0\uFE0F","atom",J,`installing in store "${Q.config.name}"`),I2(Q,_,F)},subject:G};if(F)X.family=F;let O=Y;if(Y instanceof Function)O=Y();$.atoms.set(J,X),R$(T,J),sT($,J,O,G);let M=nF(X);if(_.effects){let Q=0,V=[];for(let B of _.effects){let K=B({setSelf:(v)=>{Q0(T,M,v)},onSet:(v)=>TW(T,M,`effect[${Q}]`,v)});if(K)V.push(K);++Q}X.cleanup=()=>{for(let B of V)B()}}return M}class ZF extends Set{mode="record";subject=new FT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,_=0){super(T);if(T instanceof ZF)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(_)this.cacheLimit=_,this.cache=new Array(_),this.subscribe("auto cache",(F)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=F})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let _=new ZF(T.members,T.cacheLimit);return _.cache=T.cache,_.cacheIdx=T.cacheIdx,_.cacheUpdateNumber=T.cacheUpdateNumber,_}add(T){let _=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${rT(T)}`);return _}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let _=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${rT(T)}`);return _}parent=null;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new ZF(this);let _=this.child._subscribe("transaction",(F)=>{this.transactionUpdates?.push(F)});try{if(T(this.child)){for(let W of this.transactionUpdates)this.doStep(W);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(F){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",F),F}finally{_(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,_){return this.subject.subscribe(T,_)}subscribe(T,_){return this.subject.subscribe(T,(F)=>{_(`${this.cacheUpdateNumber}=${F}`)})}emit(T){this.subject.next(T)}doStep(T){let _=T.indexOf(":"),F=T.substring(0,_),W=T.substring(_+1);switch(F){case"add":this.add(JSON.parse(W));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(W));break;case"tx":for(let J of W.split(";"))this.doStep(J)}}getUpdateNumber(T){let _=T.indexOf("=");return Number(T.substring(0,_))}do(T){let _=T.indexOf("="),F=Number(T.substring(0,_)),W=F-this.cacheUpdateNumber;if(W>0){if(W===1){this.mode="playback";let Y=T.substring(_+1);return this.doStep(Y),this.mode="record",this.cacheUpdateNumber=F,null}return this.cacheUpdateNumber+1}if(Math.abs(W)<this.cacheLimit){let Y=this.cacheIdx+W;if(this.cache[Y]===T)return null;this.mode="playback";let Z=!1;while(!Z){this.cacheIdx%=this.cacheLimit;let X=this.cache[this.cacheIdx];if(this.cacheIdx--,!X)return"OUT_OF_RANGE";this.undo(X),Z=this.cacheIdx===Y-1}let G=T.substring(_+1);return this.doStep(G),this.mode="record",this.cacheUpdateNumber=F,null}return"OUT_OF_RANGE"}undoStep(T){let _=T.indexOf(":"),F=T.substring(0,_),W=T.substring(_+1);switch(F){case"add":this.delete(JSON.parse(W));break;case"del":this.add(JSON.parse(W));break;case"clear":{let J=JSON.parse(W);for(let Y of J)this.add(Y);break}case"tx":{let J=W.split(";");for(let Y=J.length-1;Y>=0;Y--)this.undoStep(J[Y])}}}undo(T){let _=T.indexOf("=");if(Number(T.substring(0,_))===this.cacheUpdateNumber){this.mode="playback";let W=T.substring(_+1);return this.undoStep(W),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function M$(T){return T.startsWith("\uD83D\uDD0D ")}class $1{supported;constructor(T){this.supported=T}refine(T){for(let[_,F]of Object.entries(this.supported))try{if(F(T)===!0&&F!==Boolean)return{type:_,data:T}}catch(W){try{if(T instanceof F)return{type:_,data:T}}catch(J){}}return null}}var l7=new $1({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function t7(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var i7=new $1({object:t7,array:(T)=>Array.isArray(T)}),n7=new $1({...l7.supported,...i7.supported}),E$=(T)=>{if(T===void 0)return"undefined";let _=n7.refine(T);if(_)return _.type;return Object.getPrototypeOf(T).constructor.name};class Z1{listeners;globalListeners;handleEvent(T,..._){for(let W of this.globalListeners)W(T,..._);let F=this.listeners.get(T);if(F)for(let W of F)W(..._)}id="no_id_retrieved";emit;constructor(T){this.emit=T,this.listeners=new Map,this.globalListeners=new Set}on(T,_){let F=this.listeners.get(T);if(F)F.add(_);else this.listeners.set(T,new Set([_]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,_){let F=this.listeners.get(T);if(F)if(_)F.delete(_);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class z$ extends Z1{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((..._)=>{return this.out.next(_),this});this.id=T,this.in=new FT,this.out=new FT,this.in.subscribe("socket",(_)=>{this.handleEvent(..._)})}dispose(){for(let T of this.disposalFunctions)T()}}class N2 extends Z1{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(rT(T.map((_)=>_ instanceof ZF?`{ ${_.toJSON().members.join(" | ")} }`:_))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,..._)=>{let F=JSON.stringify([T,..._]);return this.process.stdout.write(F+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let _=T.toString();this.unprocessedEvents.push(..._.split("\x03"));let F=this.unprocessedEvents.shift();this.incompleteData+=F??"";try{let W=iF(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",W),this.handleEvent(...W);while(this.unprocessedEvents.length>0){let J=this.unprocessedEvents.shift();if(J){if(this.unprocessedEvents.length===0)this.incompleteData=J;let Y=iF(J);this.handleEvent(...Y)}}this.incompleteData=""}catch(W){if(W instanceof Error)this.logger.error("\u2757",W.message,W.cause,W.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let _=new z$(`user:${T}`);this.relays.set(T,_),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let F of this.relayServices){let W=F(_);if(W)_.disposalFunctions.push(W)}this.on(`user:${T}`,(...F)=>{_.in.next(F)}),_.out.subscribe("socket",(F)=>{this.emit(...F)})}),this.on("user-leaves",(T)=>{let _=this.relays.get(T);if(this.off(`relay:${T}`),_)_.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var{file:s5,serve:HO}=globalThis.Bun;import{readFileSync as L$}from"fs";import{createServer as e7}from"http";import{createServer as T3}from"https";import{resolve as B2}from"path";function K$(T,_){if(T instanceof Promise)throw new Error(_)}function r7(T,_){let F={},W=[];for(let J in T){let Y=T[J]["~standard"].validate(_[J]);if(K$(Y,`Validation must be synchronous, but ${J} returned a Promise.`),Y.issues){W.push(...Y.issues.map(($)=>({...$,message:$.message,path:[J,...$.path??[]]})));continue}F[J]=Y.value}if(W.length)return{issues:W};return{value:F}}function C2(T){let _=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[j,y]of Object.entries(_))if(y==="")delete _[j]}if(!!T.skipValidation)return _;let J=typeof T.client==="object"?T.client:{},Y=typeof T.server==="object"?T.server:{},$=typeof T.shared==="object"?T.shared:{},Z=T.isServer??(typeof window==="undefined"||("Deno"in window)),G=Z?{...Y,...$,...J}:{...J,...$},X=T.createFinalSchema?.(G,Z)["~standard"].validate(_)??r7(G,_);K$(X,"Validation must be synchronous");let O=T.onValidationError??((j)=>{throw console.error("\u274C Invalid environment variables:",j),new Error("Invalid environment variables")}),M=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(X.issues)return O(X.issues);let Q=(j)=>{if(!T.clientPrefix)return!0;return!j.startsWith(T.clientPrefix)&&!(j in $)},V=(j)=>{return Z||!Q(j)},B=(j)=>{return j==="__esModule"||j==="$$typeof"},K=(T.extends??[]).reduce((j,y)=>{return Object.assign(j,y)},{}),v=Object.assign(K,X.value);return new Proxy(v,{get(j,y){if(typeof y!=="string")return;if(B(y))return;if(!V(y))return M(y);return Reflect.get(j,y)}})}var s7="__vite_start_time"in globalThis,a7=typeof window!=="undefined",BN="vitest"in globalThis,s_=Y_("string"),V$=Y_('"true" | "false" | undefined'),q_=C2({isServer:!s7&&!a7,server:{CI:Y_("string | undefined").pipe(Boolean),POSTGRES_USER:s_,POSTGRES_PASSWORD:s_,POSTGRES_DATABASE:s_,POSTGRES_HOST:s_,POSTGRES_PORT:s_.pipe((T)=>Number.parseInt(T,10)),BACKEND_PORT:s_.pipe((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:V$.pipe((T)=>T==="true"),FRONTEND_PORT:s_.pipe((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:s_.pipe.try((T)=>JSON.parse(T),Y_("string[]")),API_KEY_OPENAI:Y_("string | undefined"),API_KEY_RESEND:Y_("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:s_,VITE_DEV_FRONTEND_HOST:Y_("string | undefined"),VITE_DEV_HTTPS:V$.pipe((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var D$=B2(import.meta.dirname,"../dev"),X1=q_.VITE_DEV_HTTPS?{cert:L$(B2(D$,"./cert.pem"),"utf-8"),key:L$(B2(D$,"./key.pem"),"utf-8")}:void 0;function vN(T){if(X1)return T3(X1,T);return e7({},T)}import JO from"path";var H=Symbol.for("drizzle:entityKind"),bN=Symbol.for("drizzle:hasOwnEntityKind");function R(T,_){if(!T||typeof T!=="object")return!1;if(T instanceof _)return!0;if(!Object.prototype.hasOwnProperty.call(_,H))throw new Error(`Class "${_.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 F=Object.getPrototypeOf(T).constructor;if(F)while(F){if(H in F&&F[H]===_[H])return!0;F=Object.getPrototypeOf(F)}return!1}class GT{constructor(T,_){this.table=T,this.config=_,this.name=_.name,this.keyAsName=_.keyAsName,this.notNull=_.notNull,this.default=_.default,this.defaultFn=_.defaultFn,this.onUpdateFn=_.onUpdateFn,this.hasDefault=_.hasDefault,this.primary=_.primaryKey,this.isUnique=_.isUnique,this.uniqueName=_.uniqueName,this.uniqueType=_.uniqueType,this.dataType=_.dataType,this.columnType=_.columnType,this.generated=_.generated,this.generatedIdentity=_.generatedIdentity}static[H]="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(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class k2{static[H]="ColumnBuilder";config;constructor(T,_,F){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:_,columnType:F,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var j_=Symbol.for("drizzle:Name");class f2{static[H]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,_){if(this.reference=()=>{let{name:F,columns:W,foreignColumns:J}=T();return{name:F,columns:W,foreignTable:J[0].table,foreignColumns:J}},_)this._onUpdate=_.onUpdate,this._onDelete=_.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new S$(T,this)}}class S${constructor(T,_){this.table=T,this.reference=_.reference,this.onUpdate=_._onUpdate,this.onDelete=_._onDelete}static[H]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:_,foreignColumns:F}=this.reference(),W=_.map(($)=>$.name),J=F.map(($)=>$.name),Y=[this.table[j_],...W,F[0].table[j_],...J];return T??`${Y.join("_")}_fk`}}function G1(T,..._){return T(..._)}function I$(T,_){return`${T[j_]}_${_.join("_")}_unique`}function N$(T,_,F){for(let W=_;W<T.length;W++){let J=T[W];if(J==="\\"){W++;continue}if(J==='"')return[T.slice(_,W).replace(/\\/g,""),W+1];if(F)continue;if(J===","||J==="}")return[T.slice(_,W).replace(/\\/g,""),W]}return[T.slice(_).replace(/\\/g,""),T.length]}function C$(T,_=0){let F=[],W=_,J=!1;while(W<T.length){let Y=T[W];if(Y===","){if(J||W===_)F.push("");J=!0,W++;continue}if(J=!1,Y==="\\"){W+=2;continue}if(Y==='"'){let[G,X]=N$(T,W+1,!0);F.push(G),W=X;continue}if(Y==="}")return[F,W+1];if(Y==="{"){let[G,X]=C$(T,W+1);F.push(G),W=X;continue}let[$,Z]=N$(T,W,!1);F.push($),W=Z}return[F,W]}function B$(T){let[_]=C$(T,1);return _}function P2(T){return`{${T.map((_)=>{if(Array.isArray(_))return P2(_);if(typeof _==="string")return`"${_.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${_}`}).join(",")}}`}class f extends k2{foreignKeyConfigs=[];static[H]="PgColumnBuilder";array(T){return new f$(this.config.name,this,T)}references(T,_={}){return this.foreignKeyConfigs.push({ref:T,actions:_}),this}unique(T,_){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=_?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,_){return this.foreignKeyConfigs.map(({ref:F,actions:W})=>{return G1((J,Y)=>{let $=new f2(()=>{let Z=J();return{columns:[T],foreignColumns:[Z]}});if(Y.onUpdate)$.onUpdate(Y.onUpdate);if(Y.onDelete)$.onDelete(Y.onDelete);return $.build(_)},F,W)})}buildExtraConfigColumn(T){return new k$(T,this.config)}}class S extends GT{constructor(T,_){if(!_.uniqueName)_.uniqueName=I$(T,[_.name]);super(T,_);this.table=T}static[H]="PgColumn"}class k$ extends S{static[H]="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(T){return this.indexConfig.opClass=T,this}}class _W{static[H]="IndexedColumn";constructor(T,_,F,W){this.name=T,this.keyAsName=_,this.type=F,this.indexConfig=W}name;keyAsName;type;indexConfig}class f$ extends f{static[H]="PgArrayBuilder";constructor(T,_,F){super(T,"array","PgArray");this.config.baseBuilder=_,this.config.size=F}build(T){let _=this.config.baseBuilder.build(T);return new q2(T,this.config,_)}}class q2 extends S{constructor(T,_,F,W){super(T,_);this.baseColumn=F,this.range=W,this.size=_.size}size;static[H]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=B$(T);return T.map((_)=>this.baseColumn.mapFromDriverValue(_))}mapToDriverValue(T,_=!1){let F=T.map((W)=>W===null?null:R(this.baseColumn,q2)?this.baseColumn.mapToDriverValue(W,!0):this.baseColumn.mapToDriverValue(W));if(_)return F;return P2(F)}}class P$ extends f{static[H]="PgEnumObjectColumnBuilder";constructor(T,_){super(T,"string","PgEnumObjectColumn");this.config.enum=_}build(T){return new q$(T,this.config)}}class q$ extends S{static[H]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(T,_){super(T,_);this.enum=_.enum}getSQLType(){return this.enum.enumName}}var A1=Symbol.for("drizzle:isPgEnum");function j$(T){return!!T&&typeof T==="function"&&A1 in T&&T[A1]===!0}class y$ extends f{static[H]="PgEnumColumnBuilder";constructor(T,_){super(T,"string","PgEnumColumn");this.config.enum=_}build(T){return new v$(T,this.config)}}class v$ extends S{static[H]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,_){super(T,_);this.enum=_.enum}getSQLType(){return this.enum.enumName}}function FW(T,_){return Array.isArray(_)?_3(T,[..._],void 0):F3(T,_,void 0)}function _3(T,_,F){let W=Object.assign((J)=>new y$(J??"",W),{enumName:T,enumValues:_,schema:F,[A1]:!0});return W}function F3(T,_,F){let W=Object.assign((J)=>new P$(J??"",W),{enumName:T,enumValues:Object.values(_),schema:F,[A1]:!0});return W}class IT{static[H]="Subquery";constructor(T,_,F,W=!1,J=[]){this._={brand:"Subquery",sql:T,selectedFields:_,alias:F,isWith:W,usedTables:J}}}class WW extends IT{static[H]="WithSubquery"}var x$="0.44.2";var j2,y2,AT={startActiveSpan(T,_){if(!j2)return _();if(!y2)y2=j2.trace.getTracer("drizzle-orm",x$);return G1((F,W)=>W.startActiveSpan(T,(J)=>{try{return _(J)}catch(Y){throw J.setStatus({code:F.SpanStatusCode.ERROR,message:Y instanceof Error?Y.message:"Unknown error"}),Y}finally{J.end()}}),j2,y2)}};var MT=Symbol.for("drizzle:ViewBaseConfig");var k0=Symbol.for("drizzle:Schema"),H1=Symbol.for("drizzle:Columns"),b$=Symbol.for("drizzle:ExtraConfigColumns"),v2=Symbol.for("drizzle:OriginalName"),x2=Symbol.for("drizzle:BaseName"),JW=Symbol.for("drizzle:IsAlias"),h$=Symbol.for("drizzle:ExtraConfigBuilder"),W3=Symbol.for("drizzle:IsDrizzleTable");class I{static[H]="Table";static Symbol={Name:j_,Schema:k0,OriginalName:v2,Columns:H1,ExtraConfigColumns:b$,BaseName:x2,IsAlias:JW,ExtraConfigBuilder:h$};[j_];[v2];[k0];[H1];[b$];[x2];[JW]=!1;[W3]=!0;[h$]=void 0;constructor(T,_,F){this[j_]=this[v2]=T,this[k0]=_,this[x2]=F}}function xT(T){return T[j_]}function f0(T){return`${T[k0]??"public"}.${T[j_]}`}function b2(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function J3(T){let _={sql:"",params:[]};for(let F of T)if(_.sql+=F.sql,_.params.push(...F.params),F.typings?.length){if(!_.typings)_.typings=[];_.typings.push(...F.typings)}return _}class yT{static[H]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new k([this])}}class k{constructor(T){this.queryChunks=T;for(let _ of T)if(R(_,I)){let F=_[I.Symbol.Schema];this.usedTables.push(F===void 0?_[I.Symbol.Name]:F+"."+_[I.Symbol.Name])}}static[H]="SQL";decoder=g$;shouldInlineParams=!1;usedTables=[];append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return AT.startActiveSpan("drizzle.buildSQL",(_)=>{let F=this.buildQueryFromSourceParams(this.queryChunks,T);return _?.setAttributes({"drizzle.query.text":F.sql,"drizzle.query.params":JSON.stringify(F.params)}),F})}buildQueryFromSourceParams(T,_){let F=Object.assign({},_,{inlineParams:_.inlineParams||this.shouldInlineParams,paramStartIndex:_.paramStartIndex||{value:0}}),{casing:W,escapeName:J,escapeParam:Y,prepareTyping:$,inlineParams:Z,paramStartIndex:G}=F;return J3(T.map((X)=>{if(R(X,yT))return{sql:X.value.join(""),params:[]};if(R(X,O1))return{sql:J(X.value),params:[]};if(X===void 0)return{sql:"",params:[]};if(Array.isArray(X)){let O=[new yT("(")];for(let[M,Q]of X.entries())if(O.push(Q),M<X.length-1)O.push(new yT(", "));return O.push(new yT(")")),this.buildQueryFromSourceParams(O,F)}if(R(X,k))return this.buildQueryFromSourceParams(X.queryChunks,{...F,inlineParams:Z||X.shouldInlineParams});if(R(X,I)){let O=X[I.Symbol.Schema],M=X[I.Symbol.Name];return{sql:O===void 0||X[JW]?J(M):J(O)+"."+J(M),params:[]}}if(R(X,GT)){let O=W.getColumnCasing(X);if(_.invokeSource==="indexes")return{sql:J(O),params:[]};let M=X.table[I.Symbol.Schema];return{sql:X.table[JW]||M===void 0?J(X.table[I.Symbol.Name])+"."+J(O):J(M)+"."+J(X.table[I.Symbol.Name])+"."+J(O),params:[]}}if(R(X,Z_)){let O=X[MT].schema,M=X[MT].name;return{sql:O===void 0||X[MT].isAlias?J(M):J(O)+"."+J(M),params:[]}}if(R(X,Q_)){if(R(X.value,R0))return{sql:Y(G.value++,X),params:[X],typings:["none"]};let O=X.value===null?null:X.encoder.mapToDriverValue(X.value);if(R(O,k))return this.buildQueryFromSourceParams([O],F);if(Z)return{sql:this.mapInlineParam(O,F),params:[]};let M=["none"];if($)M=[$(X.encoder)];return{sql:Y(G.value++,O),params:[O],typings:M}}if(R(X,R0))return{sql:Y(G.value++,X),params:[X],typings:["none"]};if(R(X,k.Aliased)&&X.fieldAlias!==void 0)return{sql:J(X.fieldAlias),params:[]};if(R(X,IT)){if(X._.isWith)return{sql:J(X._.alias),params:[]};return this.buildQueryFromSourceParams([new yT("("),X._.sql,new yT(") "),new O1(X._.alias)],F)}if(j$(X)){if(X.schema)return{sql:J(X.schema)+"."+J(X.enumName),params:[]};return{sql:J(X.enumName),params:[]}}if(b2(X)){if(X.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([X.getSQL()],F);return this.buildQueryFromSourceParams([new yT("("),X.getSQL(),new yT(")")],F)}if(Z)return{sql:this.mapInlineParam(X,F),params:[]};return{sql:Y(G.value++,X),params:[X],typings:["none"]}}))}mapInlineParam(T,{escapeString:_}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return _(T);if(typeof T==="object"){let F=T.toString();if(F==="[object Object]")return _(JSON.stringify(T));return _(F)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new k.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class O1{constructor(T){this.value=T}static[H]="Name";brand;getSQL(){return new k([this])}}function p$(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var g$={mapFromDriverValue:(T)=>T},m$={mapToDriverValue:(T)=>T},IC={...g$,...m$};class Q_{constructor(T,_=m$){this.value=T,this.encoder=_}static[H]="Param";brand;getSQL(){return new k([this])}}function U(T,..._){let F=[];if(_.length>0||T.length>0&&T[0]!=="")F.push(new yT(T[0]));for(let[W,J]of _.entries())F.push(J,new yT(T[W+1]));return new k(F)}((T)=>{function _(){return new k([])}T.empty=_;function F(G){return new k(G)}T.fromList=F;function W(G){return new k([new yT(G)])}T.raw=W;function J(G,X){let O=[];for(let[M,Q]of G.entries()){if(M>0&&X!==void 0)O.push(X);O.push(Q)}return new k(O)}T.join=J;function Y(G){return new O1(G)}T.identifier=Y;function $(G){return new R0(G)}T.placeholder=$;function Z(G,X){return new Q_(G,X)}T.param=Z})(U||(U={}));((T)=>{class _{constructor(F,W){this.sql=F,this.fieldAlias=W}static[H]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new _(this.sql,this.fieldAlias)}}T.Aliased=_})(k||(k={}));class R0{constructor(T){this.name=T}static[H]="Placeholder";getSQL(){return new k([this])}}function h2(T,_){return T.map((F)=>{if(R(F,R0)){if(!(F.name in _))throw new Error(`No value for placeholder "${F.name}" was provided`);return _[F.name]}if(R(F,Q_)&&R(F.value,R0)){if(!(F.value.name in _))throw new Error(`No value for placeholder "${F.value.name}" was provided`);return F.encoder.mapToDriverValue(_[F.value.name])}return F})}var Y3=Symbol.for("drizzle:IsDrizzleView");class Z_{static[H]="View";[MT];[Y3]=!0;constructor({name:T,schema:_,selectedFields:F,query:W}){this[MT]={name:T,originalName:T,schema:_,selectedFields:F,query:W,isExisting:!W,isAlias:!1}}getSQL(){return new k([this])}}GT.prototype.getSQL=function(){return new k([this])};I.prototype.getSQL=function(){return new k([this])};IT.prototype.getSQL=function(){return new k([this])};class XF{constructor(T){this.table=T}static[H]="ColumnAliasProxyHandler";get(T,_){if(_==="table")return this.table;return T[_]}}class YW{constructor(T,_){this.alias=T,this.replaceOriginalName=_}static[H]="TableAliasProxyHandler";get(T,_){if(_===I.Symbol.IsAlias)return!0;if(_===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&_===I.Symbol.OriginalName)return this.alias;if(_===MT)return{...T[MT],name:this.alias,isAlias:!0};if(_===I.Symbol.Columns){let W=T[I.Symbol.Columns];if(!W)return W;let J={};return Object.keys(W).map((Y)=>{J[Y]=new Proxy(W[Y],new XF(new Proxy(T,this)))}),J}let F=T[_];if(R(F,GT))return new Proxy(F,new XF(new Proxy(T,this)));return F}}function U1(T,_){return new Proxy(T,new YW(_,!1))}function m_(T,_){return new Proxy(T,new XF(new Proxy(T.table,new YW(_,!1))))}function p2(T,_){return new k.Aliased($W(T.sql,_),T.fieldAlias)}function $W(T,_){return U.join(T.queryChunks.map((F)=>{if(R(F,GT))return m_(F,_);if(R(F,k))return $W(F,_);if(R(F,k.Aliased))return p2(F,_);return F}))}class M1 extends Error{static[H]="DrizzleError";constructor({message:T,cause:_}){super(T);this.name="DrizzleError",this.cause=_}}class g2 extends M1{static[H]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class o${static[H]="ConsoleLogWriter";write(T){console.log(T)}}class m2{static[H]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new o$}logQuery(T,_){let F=_.map((J)=>{try{return JSON.stringify(J)}catch{return String(J)}}),W=F.length?` -- params: [${F.join(", ")}]`:"";this.writer.write(`Query: ${T}${W}`)}}class o2{static[H]="NoopLogger";logQuery(){}}class aT{static[H]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((_)=>{return T?.(),_},(_)=>{throw T?.(),_})}then(T,_){return this.execute().then(T,_)}}function u$(T,_,F){let W={},J=T.reduce((Y,{path:$,field:Z},G)=>{let X;if(R(Z,GT))X=Z;else if(R(Z,k))X=Z.decoder;else X=Z.sql.decoder;let O=Y;for(let[M,Q]of $.entries())if(M<$.length-1){if(!(Q in O))O[Q]={};O=O[Q]}else{let V=_[G],B=O[Q]=V===null?null:X.mapFromDriverValue(V);if(F&&R(Z,GT)&&$.length===2){let K=$[0];if(!(K in W))W[K]=B===null?xT(Z.table):!1;else if(typeof W[K]==="string"&&W[K]!==xT(Z.table))W[K]=!1}}return Y},{});if(F&&Object.keys(W).length>0){for(let[Y,$]of Object.entries(W))if(typeof $==="string"&&!F[$])J[Y]=null}return J}function L_(T,_){return Object.entries(T).reduce((F,[W,J])=>{if(typeof W!=="string")return F;let Y=_?[..._,W]:[W];if(R(J,GT)||R(J,k)||R(J,k.Aliased))F.push({path:Y,field:J});else if(R(J,I))F.push(...L_(J[I.Symbol.Columns],Y));else F.push(...L_(J,Y));return F},[])}function ZW(T,_){let F=Object.keys(T),W=Object.keys(_);if(F.length!==W.length)return!1;for(let[J,Y]of F.entries())if(Y!==W[J])return!1;return!0}function w1(T,_){let F=Object.entries(_).filter(([,W])=>W!==void 0).map(([W,J])=>{if(R(J,k)||R(J,GT))return[W,J];else return[W,new Q_(J,T[I.Symbol.Columns][W])]});if(F.length===0)throw new Error("No values to set");return Object.fromEntries(F)}function c$(T,_){for(let F of _)for(let W of Object.getOwnPropertyNames(F.prototype)){if(W==="constructor")continue;Object.defineProperty(T.prototype,W,Object.getOwnPropertyDescriptor(F.prototype,W)||Object.create(null))}}function d$(T){return T[I.Symbol.Columns]}function a_(T){return R(T,IT)?T._.alias:R(T,Z_)?T[MT].name:R(T,k)?void 0:T[I.Symbol.IsAlias]?T[I.Symbol.Name]:T[I.Symbol.BaseName]}function a(T,_){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:_}}function l$(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let _=typeof T.logger;if(_!=="boolean"&&(_!=="object"||typeof T.logger.logQuery!=="function")&&_!=="undefined")return!1;return!0}if("schema"in T){let _=typeof T.schema;if(_!=="object"&&_!=="undefined")return!1;return!0}if("casing"in T){let _=typeof T.casing;if(_!=="string"&&_!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let _=typeof T.connection;if(_!=="string"&&_!=="object"&&_!=="undefined")return!1;return!0}if("client"in T){let _=typeof T.client;if(_!=="object"&&_!=="function"&&_!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class E0 extends f{static[H]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:_,...F}=T;this.config.generatedIdentity={type:"always",sequenceName:_,sequenceOptions:F}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:_,...F}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:_,sequenceOptions:F}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class t$ extends E0{static[H]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new i$(T,this.config)}}class i$ extends S{static[H]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class n$ extends E0{static[H]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new r$(T,this.config)}}class r$ extends S{static[H]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function s$(T,_){let{name:F,config:W}=a(T,_);if(W.mode==="number")return new t$(F);return new n$(F)}class a$ extends f{static[H]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new e$(T,this.config)}}class e$ extends S{static[H]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class TZ extends f{static[H]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new _Z(T,this.config)}}class _Z extends S{static[H]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function FZ(T,_){let{name:F,config:W}=a(T,_);if(W.mode==="number")return new a$(F);return new TZ(F)}class WZ extends f{static[H]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new JZ(T,this.config)}}class JZ extends S{static[H]="PgBoolean";getSQLType(){return"boolean"}}function XW(T){return new WZ(T??"")}class YZ extends f{static[H]="PgCharBuilder";constructor(T,_){super(T,"string","PgChar");this.config.length=_.length,this.config.enumValues=_.enum}build(T){return new $Z(T,this.config)}}class $Z extends S{static[H]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function ZZ(T,_={}){let{name:F,config:W}=a(T,_);return new YZ(F,W)}class XZ extends f{static[H]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new GZ(T,this.config)}}class GZ extends S{static[H]="PgCidr";getSQLType(){return"cidr"}}function AZ(T){return new XZ(T??"")}class HZ extends f{static[H]="PgCustomColumnBuilder";constructor(T,_,F){super(T,"custom","PgCustomColumn");this.config.fieldConfig=_,this.config.customTypeParams=F}build(T){return new OZ(T,this.config)}}class OZ extends S{static[H]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,_){super(T,_);this.sqlName=_.customTypeParams.dataType(_.fieldConfig),this.mapTo=_.customTypeParams.toDriver,this.mapFrom=_.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function UZ(T){return(_,F)=>{let{name:W,config:J}=a(_,F);return new HZ(W,J,T)}}class e_ extends f{static[H]="PgDateColumnBaseBuilder";defaultNow(){return this.default(U`now()`)}}class MZ extends e_{static[H]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new Q1(T,this.config)}}class Q1 extends S{static[H]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class wZ extends e_{static[H]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new R1(T,this.config)}}class R1 extends S{static[H]="PgDateString";getSQLType(){return"date"}}function QZ(T,_){let{name:F,config:W}=a(T,_);if(W?.mode==="date")return new MZ(F);return new wZ(F)}class RZ extends f{static[H]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new EZ(T,this.config)}}class EZ extends S{static[H]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function zZ(T){return new RZ(T??"")}class KZ extends f{static[H]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new VZ(T,this.config)}}class VZ extends S{static[H]="PgInet";getSQLType(){return"inet"}}function LZ(T){return new KZ(T??"")}class DZ extends E0{static[H]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new SZ(T,this.config)}}class SZ extends S{static[H]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function GW(T){return new DZ(T??"")}class IZ extends f{static[H]="PgIntervalBuilder";constructor(T,_){super(T,"string","PgInterval");this.config.intervalConfig=_}build(T){return new NZ(T,this.config)}}class NZ extends S{static[H]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",_=this.precision?`(${this.precision})`:"";return`interval${T}${_}`}}function CZ(T,_={}){let{name:F,config:W}=a(T,_);return new IZ(F,W)}class BZ extends f{static[H]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new E1(T,this.config)}}class E1 extends S{static[H]="PgJson";constructor(T,_){super(T,_)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function kZ(T){return new BZ(T??"")}class fZ extends f{static[H]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new z1(T,this.config)}}class z1 extends S{static[H]="PgJsonb";constructor(T,_){super(T,_)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function PZ(T){return new fZ(T??"")}class qZ extends f{static[H]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new jZ(T,this.config)}}class jZ extends S{static[H]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[_,F,W]=T.slice(1,-1).split(",");return[Number.parseFloat(_),Number.parseFloat(F),Number.parseFloat(W)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class yZ extends f{static[H]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new vZ(T,this.config)}}class vZ extends S{static[H]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[_,F,W]=T.slice(1,-1).split(",");return{a:Number.parseFloat(_),b:Number.parseFloat(F),c:Number.parseFloat(W)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function xZ(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new qZ(F);return new yZ(F)}class bZ extends f{static[H]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new hZ(T,this.config)}}class hZ extends S{static[H]="PgMacaddr";getSQLType(){return"macaddr"}}function pZ(T){return new bZ(T??"")}class gZ extends f{static[H]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new mZ(T,this.config)}}class mZ extends S{static[H]="PgMacaddr8";getSQLType(){return"macaddr8"}}function oZ(T){return new gZ(T??"")}class uZ extends f{static[H]="PgNumericBuilder";constructor(T,_,F){super(T,"string","PgNumeric");this.config.precision=_,this.config.scale=F}build(T){return new K1(T,this.config)}}class K1 extends S{static[H]="PgNumeric";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue(T){if(typeof T==="string")return T;return String(T)}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 cZ extends f{static[H]="PgNumericNumberBuilder";constructor(T,_,F){super(T,"number","PgNumericNumber");this.config.precision=_,this.config.scale=F}build(T){return new dZ(T,this.config)}}class dZ extends S{static[H]="PgNumericNumber";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}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 lZ extends f{static[H]="PgNumericBigIntBuilder";constructor(T,_,F){super(T,"bigint","PgNumericBigInt");this.config.precision=_,this.config.scale=F}build(T){return new tZ(T,this.config)}}class tZ extends S{static[H]="PgNumericBigInt";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.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 iZ(T,_){let{name:F,config:W}=a(T,_),J=W?.mode;return J==="number"?new cZ(F,W?.precision,W?.scale):J==="bigint"?new lZ(F,W?.precision,W?.scale):new uZ(F,W?.precision,W?.scale)}class nZ extends f{static[H]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new rZ(T,this.config)}}class rZ extends S{static[H]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[_,F]=T.slice(1,-1).split(",");return[Number.parseFloat(_),Number.parseFloat(F)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class sZ extends f{static[H]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new aZ(T,this.config)}}class aZ extends S{static[H]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[_,F]=T.slice(1,-1).split(",");return{x:Number.parseFloat(_),y:Number.parseFloat(F)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function eZ(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new nZ(F);return new sZ(F)}function $3(T){let _=[];for(let F=0;F<T.length;F+=2)_.push(Number.parseInt(T.slice(F,F+2),16));return new Uint8Array(_)}function TX(T,_){let F=new ArrayBuffer(8),W=new DataView(F);for(let J=0;J<8;J++)W.setUint8(J,T[_+J]);return W.getFloat64(0,!0)}function u2(T){let _=$3(T),F=0,W=_[F];F+=1;let J=new DataView(_.buffer),Y=J.getUint32(F,W===1);F+=4;let $;if(Y&536870912)$=J.getUint32(F,W===1),F+=4;if((Y&65535)===1){let Z=TX(_,F);F+=8;let G=TX(_,F);return F+=8,[Z,G]}throw new Error("Unsupported geometry type")}class _X extends f{static[H]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new FX(T,this.config)}}class FX extends S{static[H]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return u2(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class WX extends f{static[H]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new JX(T,this.config)}}class JX extends S{static[H]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let _=u2(T);return{x:_[0],y:_[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function YX(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new _X(F);return new WX(F)}class $X extends f{static[H]="PgRealBuilder";constructor(T,_){super(T,"number","PgReal");this.config.length=_}build(T){return new ZX(T,this.config)}}class ZX extends S{static[H]="PgReal";constructor(T,_){super(T,_)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function XX(T){return new $X(T??"")}class GX extends f{static[H]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new AX(T,this.config)}}class AX extends S{static[H]="PgSerial";getSQLType(){return"serial"}}function HX(T){return new GX(T??"")}class OX extends E0{static[H]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new UX(T,this.config)}}class UX extends S{static[H]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function MX(T){return new OX(T??"")}class wX extends f{static[H]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new QX(T,this.config)}}class QX extends S{static[H]="PgSmallSerial";getSQLType(){return"smallserial"}}function RX(T){return new wX(T??"")}class EX extends f{static[H]="PgTextBuilder";constructor(T,_){super(T,"string","PgText");this.config.enumValues=_.enum}build(T){return new zX(T,this.config)}}class zX extends S{static[H]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function KX(T,_={}){let{name:F,config:W}=a(T,_);return new EX(F,W)}class VX extends e_{constructor(T,_,F){super(T,"string","PgTime");this.withTimezone=_,this.precision=F,this.config.withTimezone=_,this.config.precision=F}static[H]="PgTimeBuilder";build(T){return new V1(T,this.config)}}class V1 extends S{static[H]="PgTime";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function LX(T,_={}){let{name:F,config:W}=a(T,_);return new VX(F,W.withTimezone??!1,W.precision)}class DX extends e_{static[H]="PgTimestampBuilder";constructor(T,_,F){super(T,"date","PgTimestamp");this.config.withTimezone=_,this.config.precision=F}build(T){return new L1(T,this.config)}}class L1 extends S{static[H]="PgTimestamp";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class SX extends e_{static[H]="PgTimestampStringBuilder";constructor(T,_,F){super(T,"string","PgTimestampString");this.config.withTimezone=_,this.config.precision=F}build(T){return new D1(T,this.config)}}class D1 extends S{static[H]="PgTimestampString";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function IX(T,_={}){let{name:F,config:W}=a(T,_);if(W?.mode==="string")return new SX(F,W.withTimezone??!1,W.precision);return new DX(F,W?.withTimezone??!1,W?.precision)}class NX extends f{static[H]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(U`gen_random_uuid()`)}build(T){return new S1(T,this.config)}}class S1 extends S{static[H]="PgUUID";getSQLType(){return"uuid"}}function D_(T){return new NX(T??"")}class CX extends f{static[H]="PgVarcharBuilder";constructor(T,_){super(T,"string","PgVarchar");this.config.length=_.length,this.config.enumValues=_.enum}build(T){return new BX(T,this.config)}}class BX extends S{static[H]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function dT(T,_={}){let{name:F,config:W}=a(T,_);return new CX(F,W)}class kX extends f{static[H]="PgBinaryVectorBuilder";constructor(T,_){super(T,"string","PgBinaryVector");this.config.dimensions=_.dimensions}build(T){return new fX(T,this.config)}}class fX extends S{static[H]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function PX(T,_){let{name:F,config:W}=a(T,_);return new kX(F,W)}class qX extends f{static[H]="PgHalfVectorBuilder";constructor(T,_){super(T,"array","PgHalfVector");this.config.dimensions=_.dimensions}build(T){return new jX(T,this.config)}}class jX extends S{static[H]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((_)=>Number.parseFloat(_))}}function yX(T,_){let{name:F,config:W}=a(T,_);return new qX(F,W)}class vX extends f{static[H]="PgSparseVectorBuilder";constructor(T,_){super(T,"string","PgSparseVector");this.config.dimensions=_.dimensions}build(T){return new xX(T,this.config)}}class xX extends S{static[H]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function bX(T,_){let{name:F,config:W}=a(T,_);return new vX(F,W)}class hX extends f{static[H]="PgVectorBuilder";constructor(T,_){super(T,"array","PgVector");this.config.dimensions=_.dimensions}build(T){return new pX(T,this.config)}}class pX extends S{static[H]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((_)=>Number.parseFloat(_))}}function gX(T,_){let{name:F,config:W}=a(T,_);return new hX(F,W)}function mX(){return{bigint:s$,bigserial:FZ,boolean:XW,char:ZZ,cidr:AZ,customType:UZ,date:QZ,doublePrecision:zZ,inet:LZ,integer:GW,interval:CZ,json:kZ,jsonb:PZ,line:xZ,macaddr:pZ,macaddr8:oZ,numeric:iZ,point:eZ,geometry:YX,real:XX,serial:HX,smallint:MX,smallserial:RX,text:KX,time:LX,timestamp:IX,uuid:D_,varchar:dT,bit:PX,halfvec:yX,sparsevec:bX,vector:gX}}var c2=Symbol.for("drizzle:PgInlineForeignKeys"),oX=Symbol.for("drizzle:EnableRLS");class vT extends I{static[H]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:c2,EnableRLS:oX});[c2]=[];[oX]=!1;[I.Symbol.ExtraConfigBuilder]=void 0;[I.Symbol.ExtraConfigColumns]={}}function Z3(T,_,F,W,J=T){let Y=new vT(T,W,J),$=typeof _==="function"?_(mX()):_,Z=Object.fromEntries(Object.entries($).map(([O,M])=>{let Q=M;Q.setName(O);let V=Q.build(Y);return Y[c2].push(...Q.buildForeignKeys(V,Y)),[O,V]})),G=Object.fromEntries(Object.entries($).map(([O,M])=>{let Q=M;Q.setName(O);let V=Q.buildExtraConfigColumn(Y);return[O,V]})),X=Object.assign(Y,Z);if(X[I.Symbol.Columns]=Z,X[I.Symbol.ExtraConfigColumns]=G,F)X[vT.Symbol.ExtraConfigBuilder]=F;return Object.assign(X,{enableRLS:()=>{return X[vT.Symbol.EnableRLS]=!0,X}})}var z0=(T,_,F)=>{return Z3(T,_,F,void 0)};function uX(...T){if(T[0].columns)return new AW(T[0].columns,T[0].name);return new AW(T)}class AW{static[H]="PgPrimaryKeyBuilder";columns;name;constructor(T,_){this.columns=T,this.name=_}build(T){return new cX(T,this.columns,this.name)}}class cX{constructor(T,_,F){this.table=T,this.columns=_,this.name=F}static[H]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[vT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}function X_(T,_){if(p$(_)&&!b2(T)&&!R(T,Q_)&&!R(T,R0)&&!R(T,GT)&&!R(T,I)&&!R(T,Z_))return new Q_(T,_);return T}var I1=(T,_)=>{return U`${T} = ${X_(_,T)}`},dX=(T,_)=>{return U`${T} <> ${X_(_,T)}`};function HW(...T){let _=T.filter((F)=>F!==void 0);if(_.length===0)return;if(_.length===1)return new k(_);return new k([new yT("("),U.join(_,new yT(" and ")),new yT(")")])}function lX(...T){let _=T.filter((F)=>F!==void 0);if(_.length===0)return;if(_.length===1)return new k(_);return new k([new yT("("),U.join(_,new yT(" or ")),new yT(")")])}function tX(T){return U`not ${T}`}var iX=(T,_)=>{return U`${T} > ${X_(_,T)}`},nX=(T,_)=>{return U`${T} >= ${X_(_,T)}`},rX=(T,_)=>{return U`${T} < ${X_(_,T)}`},sX=(T,_)=>{return U`${T} <= ${X_(_,T)}`};function aX(T,_){if(Array.isArray(_)){if(_.length===0)return U`false`;return U`${T} in ${_.map((F)=>X_(F,T))}`}return U`${T} in ${X_(_,T)}`}function eX(T,_){if(Array.isArray(_)){if(_.length===0)return U`true`;return U`${T} not in ${_.map((F)=>X_(F,T))}`}return U`${T} not in ${X_(_,T)}`}function T5(T){return U`${T} is null`}function _5(T){return U`${T} is not null`}function F5(T){return U`exists ${T}`}function W5(T){return U`not exists ${T}`}function J5(T,_,F){return U`${T} between ${X_(_,T)} and ${X_(F,T)}`}function Y5(T,_,F){return U`${T} not between ${X_(_,T)} and ${X_(F,T)}`}function $5(T,_){return U`${T} like ${_}`}function Z5(T,_){return U`${T} not like ${_}`}function X5(T,_){return U`${T} ilike ${_}`}function G5(T,_){return U`${T} not ilike ${_}`}function A5(T){return U`${T} asc`}function H5(T){return U`${T} desc`}class d2{constructor(T,_,F){this.sourceTable=T,this.referencedTable=_,this.relationName=F,this.referencedTableName=_[I.Symbol.Name]}static[H]="Relation";referencedTableName;fieldName}class O5{constructor(T,_){this.table=T,this.config=_}static[H]="Relations"}class K0 extends d2{constructor(T,_,F,W){super(T,_,F?.relationName);this.config=F,this.isNullable=W}static[H]="One";withFieldName(T){let _=new K0(this.sourceTable,this.referencedTable,this.config,this.isNullable);return _.fieldName=T,_}}class OW extends d2{constructor(T,_,F){super(T,_,F?.relationName);this.config=F}static[H]="Many";withFieldName(T){let _=new OW(this.sourceTable,this.referencedTable,this.config);return _.fieldName=T,_}}function U5(){return{and:HW,between:J5,eq:I1,exists:F5,gt:iX,gte:nX,ilike:X5,inArray:aX,isNull:T5,isNotNull:_5,like:$5,lt:rX,lte:sX,ne:dX,not:tX,notBetween:Y5,notExists:W5,notLike:Z5,notIlike:G5,notInArray:eX,or:lX,sql:U}}function M5(){return{sql:U,asc:A5,desc:H5}}function w5(T,_){if(Object.keys(T).length===1&&"default"in T&&!R(T.default,I))T=T.default;let F={},W={},J={};for(let[Y,$]of Object.entries(T))if(R($,I)){let Z=f0($),G=W[Z];F[Z]=Y,J[Y]={tsName:Y,dbName:$[I.Symbol.Name],schema:$[I.Symbol.Schema],columns:$[I.Symbol.Columns],relations:G?.relations??{},primaryKey:G?.primaryKey??[]};for(let O of Object.values($[I.Symbol.Columns]))if(O.primary)J[Y].primaryKey.push(O);let X=$[I.Symbol.ExtraConfigBuilder]?.($[I.Symbol.ExtraConfigColumns]);if(X){for(let O of Object.values(X))if(R(O,AW))J[Y].primaryKey.push(...O.columns)}}else if(R($,O5)){let Z=f0($.table),G=F[Z],X=$.config(_($.table)),O;for(let[M,Q]of Object.entries(X))if(G){let V=J[G];if(V.relations[M]=Q,O)V.primaryKey.push(...O)}else{if(!(Z in W))W[Z]={relations:{},primaryKey:O};W[Z].relations[M]=Q}}return{tables:J,tableNamesMap:F}}function X3(T){return function _(F,W){return new K0(T,F,W,W?.fields.reduce((J,Y)=>J&&Y.notNull,!0)??!1)}}function G3(T){return function _(F,W){return new OW(T,F,W)}}function Q5(T,_,F){if(R(F,K0)&&F.config)return{fields:F.config.fields,references:F.config.references};let W=_[f0(F.referencedTable)];if(!W)throw new Error(`Table "${F.referencedTable[I.Symbol.Name]}" not found in schema`);let J=T[W];if(!J)throw new Error(`Table "${W}" not found in schema`);let Y=F.sourceTable,$=_[f0(Y)];if(!$)throw new Error(`Table "${Y[I.Symbol.Name]}" not found in schema`);let Z=[];for(let G of Object.values(J.relations))if(F.relationName&&F!==G&&G.relationName===F.relationName||!F.relationName&&G.referencedTable===F.sourceTable)Z.push(G);if(Z.length>1)throw F.relationName?new Error(`There are multiple relations with name "${F.relationName}" in table "${W}"`):new Error(`There are multiple relations between "${W}" and "${F.sourceTable[I.Symbol.Name]}". Please specify relation name`);if(Z[0]&&R(Z[0],K0)&&Z[0].config)return{fields:Z[0].config.references,references:Z[0].config.fields};throw new Error(`There is not enough information to infer relation "${$}.${F.fieldName}"`)}function R5(T){return{one:X3(T),many:G3(T)}}function N1(T,_,F,W,J=(Y)=>Y){let Y={};for(let[$,Z]of W.entries())if(Z.isJson){let G=_.relations[Z.tsKey],X=F[$],O=typeof X==="string"?JSON.parse(X):X;Y[Z.tsKey]=R(G,K0)?O&&N1(T,T[Z.relationTableTsKey],O,Z.selection,J):O.map((M)=>N1(T,T[Z.relationTableTsKey],M,Z.selection,J))}else{let G=J(F[$]),X=Z.field,O;if(R(X,GT))O=X;else if(R(X,k))O=X.decoder;else O=X.sql.decoder;Y[Z.tsKey]=G===null?null:O.mapFromDriverValue(G)}return Y}import j3 from"os";import y3 from"fs";var C1=new Map,l2=new Map,t2=Symbol("OriginError"),GF={};class S_ extends Promise{constructor(T,_,F,W,J={}){let Y,$;super((Z,G)=>{Y=Z,$=G});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=_,this.handler=F,this.canceller=W,this.options=J,this.state=null,this.statement=null,this.resolve=(Z)=>(this.active=!1,Y(Z)),this.reject=(Z)=>(this.active=!1,$(Z)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[t2]=this.handler.debug?new Error:this.tagged&&A3(this.strings)}get origin(){return(this.handler.debug?this[t2].stack:this.tagged&&l2.has(this.strings)?l2.get(this.strings):l2.set(this.strings,this[t2].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(T=1,_){if(this.options.simple=!1,typeof T==="function")_=T,T=1;if(this.cursorRows=T,typeof _==="function")return this.cursorFn=_,this;let F;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};F&&F();let W=new Promise((J,Y)=>{this.cursorFn=($)=>{return J({value:$,done:!1}),new Promise((Z)=>F=Z)},this.resolve=()=>(this.active=!1,J({done:!0})),this.reject=($)=>(this.active=!1,Y($))});return this.execute(),W},return(){return F&&F(GF),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,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 A3(T){if(C1.has(T))return C1.get(T);let _=Error.stackTraceLimit;return Error.stackTraceLimit=4,C1.set(T,new Error),Error.stackTraceLimit=_,C1.get(T)}class AF extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var BT={connection:E5,postgres:z5,generic:K5,notSupported:V5};function E5(T,_,F){let{host:W,port:J}=F||_,Y=Object.assign(new Error("write "+T+" "+(_.path||W+":"+J)),{code:T,errno:T,address:_.path||W},_.path?{}:{port:J});return Error.captureStackTrace(Y,E5),Y}function z5(T){let _=new AF(T);return Error.captureStackTrace(_,z5),_}function K5(T,_){let F=Object.assign(new Error(T+": "+_),{code:T});return Error.captureStackTrace(F,K5),F}function V5(T){let _=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(_,V5),_}var H3={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class f1{then(){i2()}catch(){i2()}finally(){i2()}}class QW extends f1{constructor(T){super();this.value=j1(T)}}class o_ extends f1{constructor(T,_,F){super();this.value=T,this.type=_,this.array=F}}class P1 extends f1{constructor(T,_){super();this.first=T,this.rest=_}build(T,_,F,W){let J=O3.map(([Y,$])=>({fn:$,i:T.search(Y)})).sort((Y,$)=>Y.i-$.i).pop();return J.i===-1?e2(this.first,W):J.fn(this.first,this.rest,_,F,W)}}function q1(T,_,F,W){let J=T instanceof o_?T.value:T;if(J===void 0){if(T instanceof o_?T.value=W.transform.undefined:J=T=W.transform.undefined,J===void 0)throw BT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+F.push(T instanceof o_?(_.push(T.value),T.array?T.array[T.type||k1(T.value)]||T.type||I5(T.value):T.type):(_.push(T),k1(T)))}var D5=C5(H3);function s2(T,_,F,W,J,Y){for(let $=1;$<T.strings.length;$++)_+=a2(_,F,W,J,Y)+T.strings[$],F=T.args[$];return _}function a2(T,_,F,W,J){return _ instanceof P1?_.build(T,F,W,J):_ instanceof S_?r2(_,F,W,J):_ instanceof QW?_.value:_&&_[0]instanceof S_?_.reduce((Y,$)=>Y+" "+r2($,F,W,J),""):q1(_,F,W,J)}function r2(T,_,F,W){return T.fragment=!0,s2(T,T.strings[0],T.args[0],_,F,W)}function S5(T,_,F,W,J){return T.map((Y)=>"("+W.map(($)=>a2("values",Y[$],_,F,J)).join(",")+")").join(",")}function L5(T,_,F,W,J){let Y=Array.isArray(T[0]),$=_.length?_.flat():Object.keys(Y?T[0]:T);return S5(Y?T:[T],F,W,$,J)}function B1(T,_,F,W,J){if(typeof T==="string"&&(T=[T].concat(_)),Array.isArray(T))return e2(T,J);let Y;return(_.length?_.flat():Object.keys(T)).map((Z)=>{return Y=T[Z],(Y instanceof S_?r2(Y,F,W,J):Y instanceof QW?Y.value:q1(Y,F,W,J))+" as "+j1(J.transform.column.to?J.transform.column.to(Z):Z)}).join(",")}var O3=Object.entries({values:L5,in:(...T)=>{let _=L5(...T);return _==="()"?"(null)":_},select:B1,as:B1,returning:B1,"\\(":B1,update(T,_,F,W,J){return(_.length?_.flat():Object.keys(T)).map((Y)=>j1(J.transform.column.to?J.transform.column.to(Y):Y)+"="+a2("values",T[Y],F,W,J))},insert(T,_,F,W,J){let Y=_.length?_.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+e2(Y,J)+")values"+S5(Array.isArray(T)?T:[T],F,W,Y,J)}}).map(([T,_])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),_]);function i2(){throw BT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:U3,parsers:M3}=D5;function I5(T){if(Array.isArray(T))return I5(T[0]);return typeof T==="string"?1009:0}var N5=function(T){let _=C5(T||{});return{serializers:Object.assign({},U3,_.serializers),parsers:Object.assign({},M3,_.parsers)}};function C5(T){return Object.keys(T).reduce((_,F)=>{if(T[F].from&&[].concat(T[F].from).forEach((W)=>_.parsers[W]=T[F].parse),T[F].serialize)_.serializers[T[F].to]=T[F].serialize,T[F].from&&[].concat(T[F].from).forEach((W)=>_.serializers[W]=T[F].serialize);return _},{parsers:{},serializers:{}})}function e2(T,{transform:{column:_}}){return T.map((F)=>j1(_.to?_.to(F):F)).join(",")}var j1=function T(_){return'"'+_.replace(/"/g,'""').replace(/\./g,'"."')+'"'},k1=function T(_){return _ instanceof o_?_.type:_ instanceof Date?1184:_ instanceof Uint8Array?17:_===!0||_===!1?16:typeof _==="bigint"?20:Array.isArray(_)?T(_[0]):0},w3=/\\/g,Q3=/"/g;function R3(T){return T.replace(w3,"\\\\").replace(Q3,"\\\"")}var B5=function T(_,F,W,J){if(Array.isArray(_)===!1)return _;if(!_.length)return"{}";let Y=_[0],$=J===1020?";":",";if(Array.isArray(Y)&&!Y.type)return"{"+_.map((Z)=>T(Z,F,W,J)).join($)+"}";return"{"+_.map((Z)=>{if(Z===void 0){if(Z=W.transform.undefined,Z===void 0)throw BT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return Z===null?"null":'"'+R3(F?F(Z.type?Z.value:Z):""+Z)+'"'}).join($)+"}"},n2={i:0,char:null,str:"",quoted:!1,last:0},k5=function T(_,F,W){return n2.i=n2.last=0,f5(n2,_,F,W)};function f5(T,_,F,W){let J=[],Y=W===1020?";":",";for(;T.i<_.length;T.i++){if(T.char=_[T.i],T.quoted)if(T.char==="\\")T.str+=_[++T.i];else if(T.char==='"')J.push(F?F(T.str):T.str),T.str="",T.quoted=_[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,J.push(f5(T,_,F,W));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&J.push(F?F(_.slice(T.last,T.i)):_.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===Y&&T.p!=="}"&&T.p!=='"')J.push(F?F(_.slice(T.last,T.i)):_.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&J.push(F?F(_.slice(T.last,T.i+1)):_.slice(T.last,T.i+1)),J}var P0=(T)=>{let _=T[0];for(let F=1;F<T.length;F++)_+=T[F]==="_"?T[++F].toUpperCase():T[F];return _},q0=(T)=>{let _=T[0].toUpperCase();for(let F=1;F<T.length;F++)_+=T[F]==="_"?T[++F].toUpperCase():T[F];return _},j0=(T)=>T.replace(/_/g,"-"),UW=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),MW=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),wW=(T)=>T.replace(/-/g,"_");function T8(T){return function _(F,W){return typeof F==="object"&&F!==null&&(W.type===114||W.type===3802)?Array.isArray(F)?F.map((J)=>_(J,W)):Object.entries(F).reduce((J,[Y,$])=>Object.assign(J,{[T(Y)]:_($,W)}),{}):F}}P0.column={from:P0};P0.value={from:T8(P0)};UW.column={to:UW};var _8={...P0};_8.column.to=UW;q0.column={from:q0};q0.value={from:T8(q0)};MW.column={to:MW};var F8={...q0};F8.column.to=MW;j0.column={from:j0};j0.value={from:T8(j0)};wW.column={to:wW};var W8={...j0};W8.column.to=wW;import P5 from"net";import V3 from"tls";import RW from"crypto";import J8 from"stream";import{performance as q5}from"perf_hooks";class y0 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 R_=E3;function E3(T=[]){let _=T.slice(),F=0;return{get length(){return _.length-F},remove:(W)=>{let J=_.indexOf(W);return J===-1?null:(_.splice(J,1),W)},push:(W)=>(_.push(W),W),shift:()=>{let W=_[F++];if(F===_.length)F=0,_=[];else _[F-1]=void 0;return W}}}var lT=Buffer.allocUnsafe(256),z3="BCcDdEFfHPpQSX".split("").reduce((T,_)=>{let F=_.charCodeAt(0);return T[_]=()=>{return lT[0]=F,$T.i=5,$T},T},{}),$T=Object.assign(K3,z3,{N:String.fromCharCode(0),i:0,inc(T){return $T.i+=T,$T},str(T){let _=Buffer.byteLength(T);return y1(_),$T.i+=lT.write(T,$T.i,_,"utf8"),$T},i16(T){return y1(2),lT.writeUInt16BE(T,$T.i),$T.i+=2,$T},i32(T,_){if(_||_===0)return lT.writeUInt32BE(T,_),$T;return y1(4),lT.writeUInt32BE(T,$T.i),$T.i+=4,$T},z(T){return y1(T),lT.fill(0,$T.i,$T.i+T),$T.i+=T,$T},raw(T){return lT=Buffer.concat([lT.subarray(0,$T.i),T]),$T.i=lT.length,$T},end(T=1){lT.writeUInt32BE($T.i-T,T);let _=lT.subarray(0,$T.i);return $T.i=0,lT=Buffer.allocUnsafe(256),_}}),b=$T;function y1(T){if(lT.length-$T.i<T){let _=lT,F=_.length;lT=Buffer.allocUnsafe(F+(F>>1)+T),_.copy(lT)}}function K3(){return $T.i=0,$T}var Z8=v5,L3=1,V0=b().S().end(),j5=b().H().end(),D3=b().i32(8).i32(80877103).end(8),S3=Buffer.concat([b().E().str(b.N).i32(0).end(),V0]),I3=b().D().str("S").str(b.N).end(),HF=()=>{},N3=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),C3={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 v5(T,_={},{onopen:F=HF,onend:W=HF,onclose:J=HF}={}){let{ssl:Y,max:$,user:Z,host:G,port:X,database:O,parsers:M,transform:Q,onnotice:V,onnotify:B,onparameter:K,max_pipeline:v,keep_alive:q,backoff:j,target_session_attrs:y}=T,u=R_(),h=L3++,p={pid:null,secret:null},t=$8(i1,T.idle_timeout),ST=$8(i1,T.max_lifetime),A_=$8(JG,T.connect_timeout),D=null,ZT,i=new y0,TT=Buffer.alloc(0),bT=T.fetch_types,H_={},I_={},b0=Math.random().toString(36).slice(2),L=1,o=0,JT=0,zT=0,kT=0,n=0,YT=0,NT=0,KT=null,wT=null,gT=!1,HT=null,N_=null,hT=null,_0=null,fT=null,QT=null,C_=null,v_=null,C=null,wF=null,mT={queue:_.closed,idleTimer:t,connect(A){hT=A,y8()},terminate:RF,execute:QF,cancel:TG,end:i1,count:0,id:h};return _.closed&&_.closed.push(mT),mT;async function e5(){let A;try{A=T.socket?await Promise.resolve(T.socket(T)):new P5.Socket}catch(w){p0(w);return}return A.on("error",p0),A.on("close",v8),A.on("drain",q8),A}async function TG({pid:A,secret:w},g,_T){try{ZT=b().i32(16).i32(80877102).i32(A).i32(w).end(16),await j8(),D.once("error",_T),D.once("close",g)}catch(LT){_T(LT)}}function QF(A){if(gT)return IW(A,BT.connection("CONNECTION_DESTROYED",T));if(A.cancelled)return;try{return A.state=p,C?u.push(A):(C=A,C.active=!0),WG(A),pT(_G(A))&&!A.describeFirst&&!A.cursorFn&&u.length<v&&(!A.options.onexecute||A.options.onexecute(mT))}catch(w){return u.length===0&&pT(V0),x_(w),!0}}function _G(A){if(A.parameters.length>=65534)throw BT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return A.options.simple?b().Q().str(A.statement.string+b.N).end():A.describeFirst?Buffer.concat([k8(A),j5]):A.prepare?A.prepared?SW(A):Buffer.concat([k8(A),SW(A)]):FG(A)}function k8(A){return Buffer.concat([b8(A.statement.string,A.parameters,A.statement.types,A.statement.name),oG("S",A.statement.name)])}function SW(A){return Buffer.concat([mG(A.parameters,A.statement.types,A.statement.name,A.cursorName),A.cursorFn?h8("",A.cursorRows):S3])}function FG(A){return Buffer.concat([b8(A.statement.string,A.parameters,A.statement.types),I3,SW(A)])}function WG(A){let w=[],g=[],_T=s2(A,A.strings[0],A.args[0],w,g,T);!A.tagged&&A.args.forEach((LT)=>q1(LT,w,g,T)),A.prepare=T.prepare&&("prepare"in A.options?A.options.prepare:!0),A.string=_T,A.signature=A.prepare&&g+_T,A.onlyDescribe&&delete I_[A.signature],A.parameters=A.parameters||w,A.prepared=A.prepare&&A.signature in I_,A.describeFirst=A.onlyDescribe||w.length&&!A.prepared,A.statement=A.prepared?I_[A.signature]:{string:_T,types:g,name:A.prepare?b0+L++:""},typeof T.debug==="function"&&T.debug(h,_T,w,g)}function pT(A,w){if(QT=QT?Buffer.concat([QT,A]):Buffer.from(A),w||QT.length>=1024)return f8(w);return wT===null&&(wT=setImmediate(f8)),!0}function f8(A){let w=D.write(QT,A);return wT!==null&&clearImmediate(wT),QT=wT=null,w}function JG(){x_(BT.connection("CONNECT_TIMEOUT",T,D)),D.destroy()}async function P8(){if(pT(D3),!await new Promise((w)=>D.once("data",(g)=>w(g[0]===83)))&&Y==="prefer")return h0();D.removeAllListeners(),D=V3.connect({socket:D,servername:P5.isIP(D.host)?void 0:D.host,...Y==="require"||Y==="allow"||Y==="prefer"?{rejectUnauthorized:!1}:Y==="verify-full"?{}:typeof Y==="object"?Y:{}}),D.on("secureConnect",h0),D.on("error",p0),D.on("close",v8),D.on("drain",q8)}function q8(){!C&&F(mT)}function t1(A){if(HT){if(HT.push(A),JT-=A.length,JT>0)return}TT=HT?Buffer.concat(HT,n-JT):TT.length===0?A:Buffer.concat([TT,A],TT.length+A.length);while(TT.length>4){if(n=TT.readUInt32BE(1),n>=TT.length){JT=n-TT.length,HT=[TT];break}try{YG(TT.subarray(0,n+1))}catch(w){C&&(C.cursorFn||C.describeFirst)&&pT(V0),x_(w)}TT=TT.subarray(n+1),JT=0,HT=null}}async function j8(){if(gT=!1,H_={},D||(D=await e5()),!D)return;if(A_.start(),T.socket)return Y?P8():h0();if(D.on("connect",Y?P8:h0),T.path)return D.connect(T.path);D.ssl=Y,D.connect(X[zT],G[zT]),D.host=G[zT],D.port=X[zT],zT=(zT+1)%X.length}function y8(){setTimeout(j8,o?o+YT-q5.now():0)}function h0(){try{I_={},bT=T.fetch_types,b0=Math.random().toString(36).slice(2),L=1,ST.start(),D.on("data",t1),q&&D.setKeepAlive&&D.setKeepAlive(!0,1000*q);let A=cG();pT(A)}catch(A){p0(A)}}function p0(A){if(mT.queue===_.connecting&&T.host[kT+1])return;x_(A);while(u.length)IW(u.shift(),A)}function x_(A){fT&&(fT.destroy(A),fT=null),C&&IW(C,A),hT&&(IW(hT,A),hT=null)}function IW(A,w){if(A.reserve)return A.reject(w);if(!w||typeof w!=="object")w=new Error(w);"query"in w||"parameters"in w||Object.defineProperties(w,{stack:{value:w.stack+A.origin.replace(/.*\n/,`
|
|
50
|
-
`)
|
|
47
|
+
`)+"}");class e6{config;resolvedConfig;name;get[X1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Y,Z){if(this.config=m8(B.config,Z),this.resolvedConfig=m8(B.resolvedConfig,Z),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Y5).length}`,this.name in Y5)w(`A Scope already named ${this.name} already exists`);Y5[this.name]=this;let X=Object.entries(Y).map((_)=>this.preparseOwnAliasEntry(..._));for(let[_,G]of X){let W=_;if(_[0]==="#"){if(W=_.slice(1),W in this.aliases)w(mG(W));this.aliases[W]=G}else{if(W in this.aliases)w(mG(_));this.aliases[W]=G,this.exportedNames.push(W)}if(!y(G,"module")&&!y(G,"generic")&&!O4(G)){let H=this.preparseOwnDefinitionFormat(G,{alias:W});this.resolutions[W]=y(H,"root")?this.bindReference(H):this.createParseContext(H).id}}uG??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[uG.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=B.intrinsic?o(B.intrinsic,(_,G)=>_.startsWith("json")?[]:[_,this.bindReference(G)]):{}}cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Y){return Y}generic=(...Y)=>{let Z=this;return(X,_)=>new M4(Y,_?new l6(X):X,Z,Z,_??null)};units=(Y,Z)=>{let X=[];for(let G of Y)if(!X.includes(G))X.push(G);let _=X.map((G)=>this.node("unit",{unit:G},Z));return this.node("union",_,{...Z,prereduced:!0})};lazyResolutions=[];lazilyResolve(Y,Z){let X=this.node("alias",{reference:Z??"synthetic",resolve:Y},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(Y,Z)=>this.finalize(this.parseSchema(Y,Z));parseSchema=(Y,Z)=>this.node(l8(Y),Y,Z);preparseNode(Y,Z,X){let _=typeof Y==="string"?Y:l8(Z,Y);if(V0(Z)&&Z.kind===_)return Z;if(_==="alias"&&!X?.prereduced){let{reference:H}=a8.implementation.normalize(Z,this);if(H.startsWith("$")){let J=this.resolveRoot(H.slice(1));Z=J,_=J.kind}}else if(_==="union"&&$1(Z,"object")){let H=KQ(Z);if(H?.length===1)Z=H[0],_=l8(Z)}if(V0(Z)&&Z.kind===_)return Z;let W=G8[_].normalize?.(Z,this)??Z;if(V0(W))return W.kind===_?W:qQ(_,W.kind);return{...X,$:this,kind:_,def:W,prefix:X.alias??_}}bindReference(Y){let Z;if(V0(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)??w(_5(Y))}maybeResolveRoot(Y){let Z=this.maybeResolve(Y);if(y(Z,"generic"))return;return Z}maybeResolveSubalias(Y){return Z5(this.aliases,Y)??Z5(this.ambient,Y)}get ambient(){return B.ambient}maybeResolve(Y){let Z=this.resolutions[Y];if(Z){if(typeof Z!=="string")return this.bindReference(Z);let _=_1[Z];if(y(_,"root"))return this.resolutions[Y]=_;if(y(_,"context")){if(_.phase==="resolving")return this.node("alias",{reference:`$${Y}`},{prereduced:!0});if(_.phase==="resolved")return _0(`Unexpected resolved context for was uncached by its scope: ${n(_)}`);_.phase="resolving";let G=this.bindReference(this.parseOwnDefinitionFormat(_.def,_));return _.phase="resolved",_1[G.id]=G,_1[_.id]=G,this.resolutions[Y]=G}return _0(`Unexpected nodesById entry for ${Z}: ${n(_)}`)}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)w(rG(Y));return this.resolutions[Y]=this.bindReference(X.root)}return this.resolutions[Y]=this.parse(X,{alias:Y})}createParseContext(Y){let Z=Y.id??kZ(Y.prefix);return _1[Z]=Object.assign(Y,{[X1]:"context",$:this,id:Z,phase:"unresolved"})}traversal(Y){return new f1(Y,this.resolvedConfig)}import(...Y){return new J8(o(this.export(...Y),(Z,X)=>[`#${Z}`,X]))}precompilation;_exportedResolutions;_exports;export(...Y){if(!this._exports){this._exports={};for(let X of this.exportedNames){let _=this.aliases[X];this._exports[X]=y(_,"module")?eZ(_,this):dG(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=nG(this,this._exports),this._json=oG(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=iG(this.references);this.precompilation=X.write(cG,4),lG(this.references,X)}this.resolved=!0}let Z=Y.length?Y:this.exportedNames;return new J8(o(Z,(X,_)=>[_,this._exports[_]]))}resolve(Y){return this.export()[Y]}node=(Y,Z,X={})=>{let _=this.preparseNode(Y,Z,X);if(V0(_))return this.bindReference(_);let G=this.createParseContext(_),W=gZ(G),H=this.bindReference(W);return _1[G.id]=H};parse=(Y,Z={})=>this.finalize(this.parseDefinition(Y,Z));parseDefinition(Y,Z={}){if(y(Y,"root"))return this.bindReference(Y);let X=this.preparseOwnDefinitionFormat(Y,Z);if(y(X,"root"))return this.bindReference(X);let _=this.createParseContext(X);_1[_.id]=_;let G=this.bindReference(this.parseOwnDefinitionFormat(Y,_));if(G.isCyclic)G=LG(G,_.id);return _1[_.id]=G,G}finalize(Y){if(dG(Y),!Y.precompilation&&!this.resolvedConfig.jitless)jQ(Y.references);return Y}}class X5 extends e6{parseOwnDefinitionFormat(Y,Z){return gZ(Z)}preparseOwnDefinitionFormat(Y,Z){return this.preparseNode(l8(Y),Y,Z)}preparseOwnAliasEntry(Y,Z){return[Y,Z]}normalizeRootScopeValue(Y){return Y}}var dG=(Y)=>{let Z=Y.references.filter((X)=>X.hasKind("alias"));for(let X of Z){Object.assign(X.referencesById,X.resolution.referencesById);for(let _ of Y.references)if(X.id in _.referencesById)Object.assign(_.referencesById,X.referencesById)}return Y},oG=(Y)=>o(Y,(Z,X)=>[Z,y(X,"root")||y(X,"generic")?X.json:y(X,"module")?oG(X):_0(`Unexpected resolution ${n(X)}`)]),Z5=(Y,Z)=>{let X=Z.indexOf(".");if(X===-1)return;let _=Z.slice(0,X),G=Y[_];if(G===void 0)return;if(!y(G,"module"))return w(PQ(_));let W=Z.slice(X+1),H=G[W];if(H===void 0)return Z5(G,W);if(y(H,"root")||y(H,"generic"))return H;if(y(H,"module"))return H.root??w(rG(Z));_0(`Unexpected resolution for alias '${Z}': ${n(H)}`)},YY=(Y,Z)=>new X5(Y,Z),Y6=new X5({});var nG=(Y,Z)=>{let X={};for(let _ in Z){let G=Z[_];if(y(G,"module")){let W=nG(Y,G),H=o(W,(J,Q)=>[`${_}.${J}`,Q]);Object.assign(X,H)}else if(y(G,"root")||y(G,"generic"))X[_]=G;else _0(`Unexpected scope resolution ${n(G)}`)}return X},_5=(Y)=>`'${Y}' is unresolvable`,PQ=(Y)=>`'${Y}' must reference a module to be accessed using dot syntax`,rG=(Y)=>`Reference to submodule '${Y}' must specify an alias`;Y6.export();var{schema:J0,node:$8,defineSchema:jw,generic:K1}=Y6;var G5="^(?:0|[1-9]\\d*)$",SQ=new RegExp(G5),vw=K0(SQ);var sG=YY({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();B.intrinsic={...sG};var aG=YY({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:G5}},{prereducedAliases:!0}).export();Object.assign(B.intrinsic,aG);var vQ=YY({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),d={...sG,...aG,...vQ,emptyStructure:$8("structure",{},{prereduced:!0})};B.intrinsic={...d};var eG=(Y)=>typeof Y==="string"&&Y[0]==="d"&&(Y[1]==="'"||Y[1]==='"')&&Y.at(-1)===Y[1],tG=(Y)=>Y.toString()!=="Invalid Date",Y9=(Y)=>Y.slice(2,-1),W5=(Y)=>`'${Y}' could not be parsed by the Date constructor`,Z9=(Y,Z)=>xQ(Y,Z),xQ=(Y,Z)=>{let X=new Date(Y);if(tG(X))return X;let _=x_(Y);if(_!==void 0){let G=new Date(_);if(tG(G))return G}return Z?w(Z===!0?W5(Y):Z):void 0};var H5=(Y,Z)=>{let X=Y.scanner.shiftUntil(hQ[_9[Z]]);if(Y.scanner.lookahead==="")return Y.error(bQ(X,Z));if(Y.scanner.shift(),Z==="/"){try{new RegExp(X)}catch(_){w(String(_))}Y.root=Y.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(y0(Z,J5))Y.root=Y.ctx.$.node("unit",{unit:X});else{let _=Z9(X,W5(X));Y.root=Y.ctx.$.node("unit",{meta:X,unit:_})}},J5={"'":1,'"':1},X9={"/":1,"'":1,'"':1},_9={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},hQ={"'":(Y)=>Y.lookahead==="'",'"':(Y)=>Y.lookahead==='"',"/":(Y)=>Y.lookahead==="/"},fQ={'"':"double-quote","'":"single-quote","/":"forward slash"},bQ=(Y,Z)=>`${Z}${Y} requires a closing ${fQ[_9[Z]]}`;var G9=(Y)=>`Private type references should not include '#'. Use '${Y}' instead.`,ZY="Optional definitions like 'string?' are only valid as properties in an object or tuple",XY="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var W9={">":!0,">=":!0},H9={"<":!0,"<=":!0};var Q8={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},J9=(Y)=>`Unmatched )${Y===""?"":` before ${Y}`}`,_Y=(Y)=>`Missing ${Y}`,$9=(Y,Z)=>`Left bounds are only valid when paired with right bounds (try ...${Z}${Y})`,GY=(Y)=>`Left-bounded expressions must specify their limits using < or <= (was ${Y})`,Q9=(Y,Z,X,_)=>`An expression may have at most one left bound (parsed ${Y}${Q8[Z]}, ${X}${Q8[_]})`;var z9=(Y,Z,X)=>F9(Y,Z,X,[]),F9=(Y,Z,X,_)=>{let G=X.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Z.params.length)return X.error($5(Y,Z.names,_.map((W)=>W.expression)));return _}if(G.finalizer===",")return F9(Y,Z,X,_);return G.error(_Y(">"))},$5=(Y,Z,X)=>`${Y}<${Z.join(", ")}> requires exactly ${Z.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var Q5=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator();if(Z==="keyof")Y.addPrefix("keyof");else Y.root=gQ(Y,Z)},kQ=(Y,Z,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error($5(Y,Z.names,[]));let G=z9(Y,Z,X);return Z(...G)},gQ=(Y,Z)=>yQ(Y,Z)??pQ(Y,Z)??Y.error(Z===""?Y.scanner.lookahead==="#"?G9(Y.shiftedByOne().scanner.shiftUntilNextTerminator()):z5(Y):_5(Z)),yQ=(Y,Z)=>{if(Y.ctx.args?.[Z]){let _=Y.ctx.args[Z];if(typeof _!=="string")return _;return Y.ctx.$.node("alias",{reference:_},{prereduced:!0})}let X=Y.ctx.$.maybeResolve(Z);if(y(X,"root"))return X;if(X===void 0)return;if(y(X,"generic"))return kQ(Z,X,Y);return w(`Unexpected resolution ${n(X)}`)},pQ=(Y,Z)=>{let X=h_(Z);if(X!==void 0)return Y.ctx.$.node("unit",{unit:X});let _=b_(Z);if(_!==void 0)return Y.ctx.$.node("unit",{unit:_})},z5=(Y)=>{let Z=Y.previousOperator();return Z?F5(Z,Y.scanner.unscanned):mQ(Y.scanner.unscanned)},F5=(Y,Z="")=>`Token '${Y}' requires a right operand${Z?` before '${Z}'`:""}`,mQ=(Y)=>`Expected an expression${Y?` before '${Y}'`:""}`;var U5=(Y)=>Y.scanner.lookahead===""?Y.error(z5(Y)):Y.scanner.lookahead==="("?Y.shiftedByOne().reduceGroupOpen():Y.scanner.lookaheadIsIn(X9)?H5(Y,Y.scanner.shift()):Y.scanner.lookaheadIsIn(E4)?U5(Y.shiftedByOne()):Y.scanner.lookahead==="d"?Y.scanner.nextLookahead in J5?H5(Y,`${Y.scanner.shift()}${Y.scanner.shift()}`):Q5(Y):Q5(Y);class G4 extends VZ{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,...E4};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(Y,Z)=>Y===">"?Z[0]==="="?Z[1]==="=":Z.trimStart()===""||y0(Z.trimStart()[0],G4.terminatingChars):Y==="="?Z[0]!=="=":Y===","||Y==="?"}var O9=(Y,Z)=>{let X=uQ(Y,Z);if(Y.root.hasKind("unit")){if(typeof Y.root.unit==="number"){Y.reduceLeftBound(Y.root.unit,X),Y.unsetRoot();return}if(Y.root.unit instanceof Date){let _=`d'${Y.root.description??Y.root.unit.toISOString()}'`;Y.unsetRoot(),Y.reduceLeftBound(_,X);return}}return cQ(Y,X)},E9={"<":1,">":1,"=":1},uQ=(Y,Z)=>Y.scanner.lookaheadIs("=")?`${Z}${Y.scanner.shift()}`:Z;var U9=(Y,Z,X,_)=>{if(X.extends(B.intrinsic.number)){if(typeof Z!=="number")return w(O5(Y,Z,_));return Y==="=="?["min","max"]:Y[0]===">"?["min"]:["max"]}if(X.extends(B.intrinsic.lengthBoundable)){if(typeof Z!=="number")return w(O5(Y,Z,_));return Y==="=="?["exactLength"]:Y[0]===">"?["minLength"]:["maxLength"]}if(X.extends(B.intrinsic.Date))return Y==="=="?["after","before"]:Y[0]===">"?["after"]:["before"];return w(XG(X.expression))},dQ=(Y)=>({rule:eG(Y.limit)?Y9(Y.limit):Y.limit,exclusive:Y.comparator.length===1}),cQ=(Y,Z)=>{let X=Y.unsetRoot(),_=Y.scanner.location;Y.parseOperand();let G=Y.unsetRoot(),W=Y.scanner.sliceChars(_,Y.scanner.location);if(Y.root=X,!G.hasKind("unit")||typeof G.unit!=="number"&&!(G.unit instanceof Date))return Y.error(O5(Z,W,"right"));let H=G.unit,J=Z.length===1,Q=U9(Z,typeof H==="number"?H:W,X,"right");for(let z of Q)Y.constrainRoot(z,Z==="=="?{rule:H}:{rule:H,exclusive:J});if(!Y.branches.leftBound)return;if(!y0(Z,H9))return Y.error(GY(Z));let $=U9(Y.branches.leftBound.comparator,Y.branches.leftBound.limit,X,"left");Y.constrainRoot($[0],dQ(Y.branches.leftBound)),Y.branches.leftBound=null},O5=(Y,Z,X)=>`Comparator ${X==="left"?Q8[Y]:Y} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Z})`;var L9=(Y)=>{Y.scanner.shiftUntilNonWhitespace();let Z=Y.scanner.shiftUntilNextTerminator();Y.root=Y.root.brand(Z)};var V9=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator(),X=f_(Z,{errorOnFail:D9(Z)});if(X===0)Y.error(D9(0));Y.root=Y.root.constrain("divisor",X)},D9=(Y)=>`% operator must be followed by a non-zero integer literal (was ${Y})`;var E5=(Y)=>{let Z=Y.scanner.shift();return Z===""?Y.finalize(""):Z==="["?Y.scanner.shift()==="]"?Y.setRoot(Y.root.array()):Y.error(lQ):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):y0(Z,E9)?O9(Y,Z):Z==="%"?V9(Y):Z==="#"?L9(Y):(Z in E4)?E5(Y):Y.error(WY(Z))},WY=(Y,Z="")=>`'${Y}' is not allowed here${Z&&` (should be ${Z})`}`,lQ="Missing expected ']'";var M9=(Y)=>{let Z=Y.unsetRoot();Y.parseOperand();let X=Y.unsetRoot();if(!X.hasKind("unit"))return Y.error(iQ(X.expression));let _=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Z,"=",_]},iQ=(Y)=>`Default value '${Y}' must a literal value`;var L5=(Y,Z)=>{let X=Z.$.maybeResolveRoot(Y);if(X)return X;if(Y.endsWith("[]")){let W=Z.$.maybeResolveRoot(Y.slice(0,-2));if(W)return W.array()}let _=new z8(new G4(Y),Z),G=oQ(_);if(_.finalizer===">")w(WY(">"));return G},oQ=(Y)=>{Y.parseOperand();let Z=Z6(Y).root;if(!Z)return _0(`Root was unexpectedly unset after parsing string '${Y.scanner.scanned}'`);if(Y.finalizer==="=")Z=M9(Y);else if(Y.finalizer==="?")Z=[Z,"?"];if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.lookahead)w(WY(Y.scanner.lookahead));return Z},Z6=(Y)=>{while(Y.finalizer===void 0)nQ(Y);return Y},nQ=(Y)=>Y.hasRoot()?Y.parseOperator():Y.parseOperand();class z8{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 w(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(_Y(")"));this.finalizeBranches(),this.finalizer=Y}reduceLeftBound(Y,Z){let X=Q8[Z];if(!y0(X,W9))return this.error(GY(Z));if(this.branches.leftBound)return this.error(Q9(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(J9(this.scanner.unscanned));this.branches=Y}addPrefix(Y){this.branches.prefixes.push(Y)}applyPrefixes(){while(this.branches.prefixes.length){let Y=this.branches.prefixes.pop();this.root=Y==="keyof"?this.root.keyof():_0(`Unexpected prefix '${Y}'`)}}pushRootToBranch(Y){this.assertRangeUnset(),this.applyPrefixes();let Z=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(Z)??Z,Y==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Y==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return Z6(new z8(this.scanner,this.ctx))}parseOperator(){return E5(this)}parseOperand(){return U5(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error($9(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 rQ="An empty string is not a valid generic parameter name",HY=(Y,Z,X)=>{Y.shiftUntilNonWhitespace();let _=Y.shiftUntilNextTerminator();if(_===""){if(Y.lookahead===""&&Z.length)return Z;return w(rQ)}return Y.shiftUntilNonWhitespace(),sQ(Y,_,Z,X)},A9="extends ",sQ=(Y,Z,X,_)=>{if(Y.shiftUntilNonWhitespace(),Y.unscanned.startsWith(A9))Y.jumpForward(A9.length);else{if(Y.lookahead===",")Y.shift();return X.push(Z),HY(Y,X,_)}let G=Z6(new z8(Y,_));return X.push([Z,G.root]),HY(Y,X,_)};class D5 extends h1{$;constructor(Y){super((...Z)=>new X6(Y)(...Z),{bind:Y});this.$=Y}in(Y){return new X6(this.$,Y===void 0?void 0:this.$.parse(Y))}at(Y,Z){return new X6(this.$).at(Y,Z)}case(Y,Z){return new X6(this.$).case(Y,Z)}}class X6 extends h1{$;in;key;branches=[];constructor(Y,Z){super((X)=>this.caseEntries(Object.entries(X).map(([_,G])=>_==="default"?[_,G]:[this.$.parse(_),G])));this.$=Y,this.in=Z}at(Y,Z){if(this.key)w(tQ);if(this.branches.length)w(aQ);return this.key=Y,Z?this.match(Z):this}case(Y,Z){return this.caseEntry(this.$.parse(Y),Z)}caseEntry(Y,Z){let _=(this.key?this.$.parse({[this.key]:Y}):Y).pipe(Z);return this.branches.push(_),this}match(Y){return this(Y)}strings(Y){return this.caseEntries(Object.entries(Y).map(([Z,X])=>Z==="default"?[Z,X]:[this.$.node("unit",{unit:Z}),X]))}caseEntries(Y){for(let Z=0;Z<Y.length;Z++){let[X,_]=Y[Z];if(X==="default"){if(Z!==Y.length-1)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 "${X}" must be a function (was ${g0(_)})`);this.caseEntry(X,_)}return this}default(Y){if(typeof Y==="function")this.case(d.unknown,Y);let Z={branches:this.branches,ordered:!0};if(Y==="never"||Y==="assert")Z.meta={onFail:w9};let X=this.$.node("union",Z);if(!this.in)return this.$.finalize(X);let _=this.in.pipe(X);if(Y==="never"||Y==="assert")_=_.configureReferences({onFail:w9},"self");return this.$.finalize(_)}}var w9=(Y)=>Y.throw(),aQ="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",tQ="At most one key matcher may be specified per expression";var JY=(Y,Z)=>{if(O0(Y)){if(Y[1]==="=")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"=",Y[2]];if(Y[1]==="?")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"?"]}return $Y(Y,Z)},N9="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",R9="Only required keys may specify default values, e.g. { value: 'number = 0' }";var I9=(Y,Z)=>{let X,_={},G=j4(Y);for(let[H,J]of G){let Q=Zz(H);if(Q.kind==="spread"){if(!c1(_))return w(Yz);let V=Z.$.parseOwnDefinitionFormat(J,Z);if(V.equals(d.object))continue;if(!V.hasKind("intersection")||!V.basis?.equals(d.object))return w(Xz(V.expression));X=V.structure;continue}if(Q.kind==="undeclared"){if(J!=="reject"&&J!=="delete"&&J!=="ignore")w(eQ(J));_.undeclared=J;continue}let $=JY(J,Z),z=Q;if(Q.kind==="required"){if(!O0($))V5(_,"required",{key:Q.normalized,value:$},Z);else V5(_,"optional",$[1]==="="?{key:Q.normalized,value:$[0],default:$[2]}:{key:Q.normalized,value:$[0]},Z);continue}if(O0($)){if($[1]==="?")w(N9);if($[1]==="=")w(R9)}if(Q.kind==="optional"){V5(_,"optional",{key:Q.normalized,value:$},Z);continue}let O=Z.$.parseOwnDefinitionFormat(z.normalized,Z),L=t6(O,$,Z.$);if(L.index)_.index=Z0(_.index,L.index);if(L.required)_.required=Z0(_.required,L.required)}let W=Z.$.node("structure",_);return Z.$.parseSchema({domain:"object",structure:X?.merge(W)??W})},V5=(Y,Z,X,_)=>{Y[Z]=Z0(Y[Z],_.$.node(Z,X))},eQ=(Y)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${n(Y)})`,Yz="Spread operator may only be used as the first key in an object",Zz=(Y)=>typeof Y==="symbol"?{kind:"required",normalized:Y}:Y.at(-1)==="?"?Y.at(-2)===h8?{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]===h8&&Y[1]==="["&&Y.at(-1)==="]"?{kind:"required",normalized:Y.slice(1)}:Y==="..."?{kind:"spread"}:Y==="+"?{kind:"undeclared"}:{kind:"required",normalized:Y==="\\..."?"...":Y==="\\+"?"+":Y},Xz=(Y)=>`Spread operand must resolve to an object literal type (was ${Y})`;var T9=(Y,Z)=>Uz(Y)?j9[Y[0]](Y,Z):zz(Y)?q9[Y[1]](Y,Z):null,_z=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[1],Z).keyof(),M5=(Y,Z)=>{if(Y[2]===void 0)return w(F5(Y[1],""));let X=Z.$.parseOwnDefinitionFormat(Y[0],Z),_=Z.$.parseOwnDefinitionFormat(Y[2],Z);if(Y[1]==="|")return Z.$.node("union",{branches:[X,_]});let G=Y[1]==="&"?U1(X,_,Z.$):c8(X,_,Z.$);if(G instanceof S)return G.throw();return G},Gz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).array(),Wz=(Y,Z)=>{if(typeof Y[2]!=="function")return w(C9("=>",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).pipe(Y[2])},C9=(Y,Z)=>`${Y===":"?"Narrow":"Morph"} expression requires a function following '${Y}' (was ${typeof Z})`,Hz=(Y,Z)=>{if(typeof Y[2]!=="function")return w(C9(":",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).constrain("predicate",Y[2])},Jz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).configureReferences(Y[2],"shallow"),K9=(Y)=>Y,$z=K9({"[]":Gz,"?":()=>w(ZY)}),Qz=K9({"|":M5,"&":M5,":":Hz,"=>":Wz,"|>":M5,"@":Jz,"=":()=>w(XY)}),q9={...$z,...Qz},zz=(Y)=>q9[Y[1]]!==void 0,Fz=(Y)=>Y,j9=Fz({keyof:_z,instanceof:(Y,Z)=>{if(typeof Y[1]!=="function")return w(B9(v8(Y[1])));let X=Y.slice(1).map((_)=>typeof _==="function"?Z.$.node("proto",{proto:_}):w(B9(v8(_))));return X.length===1?X[0]:Z.$.node("union",{branches:X})},"===":(Y,Z)=>Z.$.units(Y.slice(1))}),Uz=(Y)=>j9[Y[0]]!==void 0,B9=(Y)=>`Expected a constructor following 'instanceof' operator (was ${Y})`;var v9=(Y,Z)=>{let X=[{}],_=0;while(_<Y.length){let G=!1;if(Y[_]==="..."&&_<Y.length-1)G=!0,_++;let W=JY(Y[_],Z),[H,J,Q]=!O0(W)?[W]:W;if(_++,G){if(!H.extends(B.intrinsic.Array))return w(Lz(H.expression));X=X.flatMap(($)=>H.distribute((z)=>Ez(m6($),z)))}else X=X.map(($)=>{if(J==="?")return x9($,H);if(J==="=")return Oz($,H,Q);return A5($,H)})}return Z.$.parseSchema(X.map((G)=>c1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},A5=(Y,Z)=>{if(Y.defaultables||Y.optionals)return w(Y.variadic?sZ:Dz);if(Y.variadic)Y.postfix=Z0(Y.postfix,Z);else Y.prefix=Z0(Y.prefix,Z);return Y},x9=(Y,Z)=>{if(Y.variadic)return w(h9);return Y.optionals=Z0(Y.optionals,Z),Y},Oz=(Y,Z,X)=>{if(Y.variadic)return w(h9);if(Y.optionals)return w(Vz);return Y.defaultables=Z0(Y.defaultables,[[Z,X]]),Y},P9=(Y,Z)=>{if(Y.postfix)w(S9);if(Y.variadic){if(!Y.variadic.equals(Z))w(S9)}else Y.variadic=Z.internal;return Y},Ez=(Y,Z)=>{let X=Z.select({method:"find",kind:"sequence"});if(!X)return P9(Y,B.intrinsic.unknown);if(X.prefix)for(let _ of X.prefix)A5(Y,_);if(X.optionals)for(let _ of X.optionals)x9(Y,_);if(X.variadic)P9(Y,X.variadic);if(X.postfix)for(let _ of X.postfix)A5(Y,_);return Y},Lz=(Y)=>`Spread element must be an array (was ${Y})`,S9="A tuple may have at most one variadic element",Dz="A required element may not follow an optional element",h9="An optional element may not follow a variadic element";var Vz="A defaultable element may not follow an optional element without a default";var Mz={},$Y=(Y,Z)=>{if(typeof Y==="string"){if(Z.args&&Object.keys(Z.args).some((_)=>Y.includes(_)))return L5(Y,Z);let X=Mz[Z.$.name]??={};return X[Y]??=L5(Y,Z)}return $1(Y,"object")?Az(Y,Z):w(w5(g0(Y)))},Az=(Y,Z)=>{let X=S8(Y);switch(X){case void 0:if(y(Y,"root"))return Y;return I9(Y,Z);case"Array":return wz(Y,Z);case"RegExp":return Z.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0});case"Function":{let _=O4(Y)?Y():Y;if(y(_,"root"))return _;return w(w5("Function"))}default:return w(w5(X??n(Y)))}},wz=(Y,Z)=>T9(Y,Z)??v9(Y,Z),w5=(Y)=>`Type definitions must be strings or objects (was ${Y})`;class N5 extends h1{constructor(Y){let Z=Object.assign({errors:z1,hkt:a0,$:Y,raw:Y.parse,module:Y.constructor.module,scope:Y.constructor.scope,define:Y.define,match:Y.match,generic:Y.generic,schema:Y.schema,keywords:Y.ambient,unit:Y.unit,enumerated:Y.enumerated,instanceOf:Y.instanceOf,valueOf:Y.valueOf,or:Y.or,and:Y.and,merge:Y.merge,pipe:Y.pipe},Y.ambientAttachments);super((...X)=>{if(X.length===1)return Y.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0].at(-1)===">"){let _=X[0].slice(1,-1),G=Y.parseGenericParams(_,{});return new M4(G,X[1],Y,Y,null)}return Y.parse(X)},{bind:Y,attach:Z})}}var F8=B;class QY extends e6{get ambientAttachments(){if(!F8.typeAttachments)return;return this.cacheGetter("ambientAttachments",o(F8.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 W=this.name==="ark"?Y:Y==="root"?this.name:`${this.name}.${Y}`,H=this.resolvedConfig.keywords?.[W];if(H)Z=[Z,"@",H];return[Y,Z]}if(Y.at(-1)!==">")w("'>' must be the last character of a generic declaration in a scope");let _=Y.slice(0,X),G=Y.slice(X+1,-1);return[_,()=>{let W=this.parseGenericParams(G,{alias:_});return e_(W,Z,this)}]}parseGenericParams(Y,Z){return HY(new G4(Y),[],this.createParseContext({...Z,def:Y,prefix:"generic"}))}normalizeRootScopeValue(Y){if(O4(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 _=$Y(Y,Z);if(O0(_)){if(_[1]==="=")return w(XY);if(_[1]==="?")return w(ZY)}return _}unit=(Y)=>this.units([Y]);valueOf=(Y)=>this.units(A_(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 D5(this);declare=()=>({type:this.type});define(Y){return Y}type=new N5(this);static scope=(Y,Z={})=>new QY(Y,Z);static module=(Y,Z={})=>this.scope(Y,Z).export()}var R5=Object.assign(QY.scope,{define:(Y)=>Y}),Y0=QY;class f9 extends a0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var Nz=K1(["base",d.object],["props",d.object])((Y)=>Y.base.merge(Y.props),f9),b9=Y0.module({Key:d.key,Merge:Nz});class k9 extends a0{}var Rz=K1("element")((Y)=>{let Z=Y.element.exclude(d.Array),X=Z.array();return Z.rawOr(X).pipe(U4).distribute((_)=>_.assertHasKind("morph").declareOut(X),J0)},k9),g9=Y0.module({root:d.Array,readonly:"root",index:d.nonNegativeIntegerString,liftFrom:Rz},{name:"Array"});var I5=J0(["string",S4.FileConstructor]),Iz=I5.rawOr(I5.array()),y9=J0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:Iz}}),p9=Y0.module({root:["instanceof",FormData],value:I5,parsed:y9,parse:J0({in:FormData,morphs:(Y)=>{let Z={};for(let[X,_]of Y)if(X in Z){let G=Z[X];if(typeof G==="string"||G instanceof S4.FileConstructor)Z[X]=[G,_];else G.push(_)}else Z[X]=_;return Z},declaredOut:y9})},{name:"FormData"});var m9=Y0.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var Bz={Boolean:1,Number:1,String:1},u9=Y0.module({...o({...QZ,...FZ},(Y,Z)=>(Y in Bz)?[]:[Y,["instanceof",Z]]),Array:g9,TypedArray:m9,FormData:p9});var Tz=J0({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"}),Cz=J0({domain:"number",divisor:1}),zY=Y0.module({root:d.number,integer:Cz,epoch:Tz,safe:J0({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var I0=(Y,Z,X)=>{let _={domain:"string",pattern:{rule:Y.source,flags:Y.flags,meta:Z}};if(X)_.meta={format:X};return $8("intersection",_)},d9=I0(f8,"a well-formed integer string"),Z7=Y0.module({root:d9,parse:J0({in:d9,morphs:(Y,Z)=>{let X=Number.parseInt(Y);return Number.isSafeInteger(X)?X:Z.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:d.integer})},{name:"string.integer"}),Kz=I0(/^[\dA-Fa-f]+$/,"hex characters only"),qz=Y0.module({root:I0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:I0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),c9=I0(/^[A-Z].*$/,"capitalized"),jz=Y0.module({root:J0({in:"string",morphs:(Y)=>Y.charAt(0).toUpperCase()+Y.slice(1),declaredOut:c9}),preformatted:c9},{name:"string.capitalize"}),Pz=(Y)=>{let Z=Y.replaceAll(/[ -]+/g,""),X=0,_,G,W=!1;for(let H=Z.length-1;H>=0;H--){if(_=Z.substring(H,H+1),G=Number.parseInt(_,10),W)G*=2,X+=G>=10?G%10+1:G;else X+=G;W=!W}return!!(X%10===0?Z:!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}))$/,vz=J0({domain:"string",pattern:{meta:"a credit card number",rule:Sz.source},predicate:{meta:"a credit card number",predicate:Pz}});var xz=/^([+-]?\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 hz=(Y)=>!Number.isNaN(new Date(Y).valueOf()),l9=J0({domain:"string",predicate:{meta:"a parsable date",predicate:hz}}).assertHasKind("intersection"),i9=Z7.root.internal.narrow((Y,Z)=>{let X=Number.parseInt(Y),_=zY.epoch(X);if(_ instanceof z1)return Z.errors.merge(_),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),fz=Y0.module({root:i9,parse:J0({in:i9,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.epoch"}),o9=I0(xz,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),bz=Y0.module({root:o9,parse:J0({in:o9,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.iso"}),kz=Y0.module({root:l9,parse:J0({declaredIn:l9,in:"string",morphs:(Y,Z)=>{let X=new Date(Y);if(Number.isNaN(X.valueOf()))return Z.error("a parsable date");return X},declaredOut:d.Date}),iso:bz,epoch:fz},{name:"string.date"}),gz=I0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),n9="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A4=`(${n9}[.]){3}${n9}`,yz=new RegExp(`^${A4}$`),v0="(?:[0-9a-fA-F]{1,4})",pz=new RegExp(`^((?:${v0}:){7}(?:${v0}|:)|(?:${v0}:){6}(?:${A4}|:${v0}|:)|(?:${v0}:){5}(?::${A4}|(:${v0}){1,2}|:)|(?:${v0}:){4}(?:(:${v0}){0,1}:${A4}|(:${v0}){1,3}|:)|(?:${v0}:){3}(?:(:${v0}){0,2}:${A4}|(:${v0}){1,4}|:)|(?:${v0}:){2}(?:(:${v0}){0,3}:${A4}|(:${v0}){1,5}|:)|(?:${v0}:){1}(?:(:${v0}){0,4}:${A4}|(:${v0}){1,6}|:)|(?::((?::${v0}){0,5}:${A4}|(?::${v0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),mz=Y0.module({root:["v4 | v6","@","an IP address"],v4:I0(yz,"an IPv4 address","ipv4"),v6:I0(pz,"an IPv6 address","ipv6")},{name:"string.ip"}),U8="a JSON string",X7=(Y)=>{if(!(Y instanceof SyntaxError))throw Y;return`must be ${U8} (${Y})`},uz=J0({meta:U8,domain:"string",predicate:{meta:U8,predicate:(Y,Z)=>{try{return JSON.parse(Y),!0}catch(X){return Z.reject({code:"predicate",expected:U8,problem:X7(X)})}}}}),dz=(Y,Z)=>{if(Y.length===0)return Z.error({code:"predicate",expected:U8,actual:"empty"});try{return JSON.parse(Y)}catch(X){return Z.error({code:"predicate",expected:U8,problem:X7(X)})}},cz=Y0.module({root:uz,parse:J0({meta:"safe JSON string parser",in:"string",morphs:dz,declaredOut:d.jsonObject})},{name:"string.json"}),r9=I0(/^[a-z]*$/,"only lowercase letters"),lz=Y0.module({root:J0({in:"string",morphs:(Y)=>Y.toLowerCase(),declaredOut:r9}),preformatted:r9},{name:"string.lower"}),_7=["NFC","NFD","NFKC","NFKD"],_6=o(_7,(Y,Z)=>[Z,J0({domain:"string",predicate:(X)=>X.normalize(Z)===X,meta:`${Z}-normalized unicode`})]),FY=o(_7,(Y,Z)=>[Z,J0({in:"string",morphs:(X)=>X.normalize(Z),declaredOut:_6[Z]})]),iz=Y0.module({root:FY.NFC,preformatted:_6.NFC},{name:"string.normalize.NFC"}),oz=Y0.module({root:FY.NFD,preformatted:_6.NFD},{name:"string.normalize.NFD"}),nz=Y0.module({root:FY.NFKC,preformatted:_6.NFKC},{name:"string.normalize.NFKC"}),rz=Y0.module({root:FY.NFKD,preformatted:_6.NFKD},{name:"string.normalize.NFKD"}),sz=Y0.module({root:"NFC",NFC:iz,NFD:oz,NFKC:nz,NFKD:rz},{name:"string.normalize"}),s9=I0(g6,"a well-formed numeric string"),az=Y0.module({root:s9,parse:J0({in:s9,morphs:(Y)=>Number.parseFloat(Y),declaredOut:d.number})},{name:"string.numeric"}),a9="a regex pattern",tz=J0({domain:"string",predicate:{meta:a9,predicate:(Y,Z)=>{try{return new RegExp(Y),!0}catch(X){return Z.reject({code:"predicate",expected:a9,problem:String(X)})}}},meta:{format:"regex"}}),ez=/^(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-]+)*))?$/,YF=I0(ez,"a semantic version (see https://semver.org/)"),t9=I0(/^\S.*\S$|^\S?$/,"trimmed"),ZF=Y0.module({root:J0({in:"string",morphs:(Y)=>Y.trim(),declaredOut:t9}),preformatted:t9},{name:"string.trim"}),e9=I0(/^[A-Z]*$/,"only uppercase letters"),XF=Y0.module({root:J0({in:"string",morphs:(Y)=>Y.toUpperCase(),declaredOut:e9}),preformatted:e9},{name:"string.upper"}),_F=(Y)=>{if(URL.canParse)return URL.canParse(Y);try{return new URL(Y),!0}catch{return!1}},Y7=J0({domain:"string",predicate:{meta:"a URL string",predicate:_F},meta:{format:"uri"}}),GF=Y0.module({root:Y7,parse:J0({declaredIn:Y7,in:"string",morphs:(Y,Z)=>{try{return new URL(Y)}catch{return Z.error("a URL string")}},declaredOut:J0(URL)})},{name:"string.url"}),WF=Y0.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:I0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:I0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:I0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:I0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:I0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:I0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:I0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:I0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),G7=Y0.module({root:d.string,alpha:I0(/^[A-Za-z]*$/,"only letters"),alphanumeric:I0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:Kz,base64:qz,capitalize:jz,creditCard:vz,date:kz,digits:I0(/^\d*$/,"only digits 0-9"),email:gz,integer:Z7,ip:mz,json:cz,lower:lz,normalize:sz,numeric:az,regex:tz,semver:YF,trim:ZF,upper:XF,url:GF,uuid:WF},{name:"string"});var W7=Y0.module({bigint:d.bigint,boolean:d.boolean,false:d.false,never:d.never,null:d.null,number:d.number,object:d.object,string:d.string,symbol:d.symbol,true:d.true,unknown:d.unknown,undefined:d.undefined}),H7=Y0.module({root:d.unknown,any:d.unknown},{name:"unknown"}),HF=Y0.module({root:d.jsonObject,stringify:$8("morph",{in:d.jsonObject,morphs:(Y)=>JSON.stringify(Y),declaredOut:d.string})},{name:"object.json"}),J7=Y0.module({root:d.object,json:HF},{name:"object"});class $7 extends a0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var JF=K1(["K",d.key],"V")((Y)=>({domain:"object",index:{signature:Y.K,value:Y.V}}),$7);class Q7 extends a0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var $F=K1(["T",d.object],["K",d.key])((Y)=>Y.T.pick(Y.K),Q7);class z7 extends a0{description='omit a set of properties from an object like `Omit(User, "age")`'}var QF=K1(["T",d.object],["K",d.key])((Y)=>Y.T.omit(Y.K),z7);class F7 extends a0{description="make all named properties of an object optional like `Partial(User)`"}var zF=K1(["T",d.object])((Y)=>Y.T.partial(),F7);class U7 extends a0{description="make all named properties of an object required like `Required(User)`"}var FF=K1(["T",d.object])((Y)=>Y.T.required(),U7);class O7 extends a0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var UF=K1("T","U")((Y)=>Y.T.exclude(Y.U),O7);class E7 extends a0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var OF=K1("T","U")((Y)=>Y.T.extract(Y.U),E7),L7=Y0.module({Exclude:UF,Extract:OF,Omit:QF,Partial:zF,Pick:$F,Record:JF,Required:FF});var w4=R5({...W7,...L7,...u9,...b9,string:G7,number:zY,object:J7,unknown:H7},{prereducedAliases:!0,name:"ark"}),p0=w4.export();Object.assign(F8.ambient,p0);F8.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 O1=Object.assign(w4.type,F8.typeAttachments),EF=w4.match,LF=w4.generic,YB=w4.schema,DF=w4.define,VF=w4.declare;var D7=(Y,Z,X=x0.STORE)=>{return O8(X,{key:`${Y.key}:JSON`,get:({get:_})=>Z.toJson(_(Y)),set:({set:_},G)=>{_(Y,Z.fromJson(G))}})};function V7(Y,Z,X){return UY(Y,{key:`${Z.key}:JSON`,get:(G)=>({get:W})=>{let H=W(Z,G);return X.toJson(H)},set:(G)=>({set:W},H)=>{W(Z,G,X.fromJson(H))}},["mutable","json"])}var E1=(Y)=>JSON.parse(Y),z0=(Y)=>JSON.stringify(Y),VB=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function E8(Y){return C7(x0.STORE,Y)}function G6(Y){return R7(x0.STORE,Y)}function T5(...Y){if(Y.length===2)return k1(x0.STORE,...Y);return k1(x0.STORE,...Y)}function OY(Y,Z,X=x0.STORE){return X.joins.set(Y.key,new j5(Y,Z,X)),{key:Y.key,type:"join",a:Y.between[0],b:Y.between[1],cardinality:Y.cardinality}}function M7(Y){return q7(Y,x0.STORE)}var B5=(Y)=>(Z,X,_,G,...W)=>{console[Y](`${Z} ${X} "${_}" ${G}`,...W)},MF={error:B5("error"),info:B5("info"),warn:B5("warn")},A7=class{logLevel;filter;logger;constructor(Y,Z,X=MF){this.logLevel=Y,this.filter=Z,this.logger=X}error=(...Y)=>{let Z=this.filter?.(...Y)??!0;if(this.logLevel!==null){if(Z===!0)this.logger.error(...Y);else if(Z!==!1)this.logger.error(...Z)}};info=(...Y)=>{let Z=this.filter?.(...Y)??!0;if(this.logLevel==="info"){if(Z===!0)this.logger.info(...Y);else if(Z!==!1)this.logger.info(...Z)}};warn=(...Y)=>{let Z=this.filter?.(...Y)??!0;if(this.logLevel!=="error"&&this.logLevel!==null){if(Z===!0)this.logger.warn(...Y);else if(Z!==!1)this.logger.warn(...Z)}}},wB=Symbol.for("claim"),AF=class{store;constructor(Y=x0.STORE){this.store=Y,I7("root",Y)}allocate(Y,Z,X){return D8(this.store,Y,Z,X)}fuse(Y,Z,X){return B7(this.store,Y,Z,X)}deallocate(Y){V8(this.store,Y)}claim(Y,Z,X){return H6(this.store,Y,Z,X)}},w7=class{store;realm;constructor(Y=x0.STORE){this.store=Y,this.realm=new AF(Y)}allocate(Y,Z,X){D8(this.store,Y,Z,X)}deallocate(Y){V8(this.store,Y)}claim(Y,Z,X){H6(this.store,Y,Z,X)}};function EY(Y){return K5(x0.STORE,Y)}function W6(Y){return q5(x0.STORE,Y)}var L1=class Y extends Set{mode="record";subject=new H0;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(Z,X=0){super(Z);if(Z instanceof Y)this.parent=Z,this.cacheUpdateNumber=Z.cacheUpdateNumber;if(X)this.cacheLimit=X,this.cache=new Array(X),this.subscribe("auto cache",(_)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=_})}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:${z0(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:${z0(Z)}`);return X}parent=null;child=null;transactionUpdates=null;transaction(Z){this.mode="transaction",this.transactionUpdates=[],this.child=new Y(this);let X=this.child._subscribe("transaction",(_)=>{this.transactionUpdates?.push(_)});try{if(Z(this.child)){for(let G of this.transactionUpdates)this.doStep(G);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(_){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",_),_}finally{X(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(Z,X){return this.subject.subscribe(Z,X)}subscribe(Z,X){return this.subject.subscribe(Z,(_)=>{X(`${this.cacheUpdateNumber}=${_}`)})}emit(Z){this.subject.next(Z)}doStep(Z){let X=Z.indexOf(":"),_=Z.substring(0,X),G=Z.substring(X+1);switch(_){case"add":this.add(JSON.parse(G));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(G));break;case"tx":for(let W of G.split(";"))this.doStep(W)}}getUpdateNumber(Z){let X=Z.indexOf("=");return Number(Z.substring(0,X))}do(Z){let X=Z.indexOf("="),_=Number(Z.substring(0,X)),G=_-this.cacheUpdateNumber;if(G>0){if(G===1){this.mode="playback";let H=Z.substring(X+1);return this.doStep(H),this.mode="record",this.cacheUpdateNumber=_,null}return this.cacheUpdateNumber+1}if(Math.abs(G)<this.cacheLimit){let H=this.cacheIdx+G;if(this.cache[H]===Z)return null;this.mode="playback";let Q=!1;while(!Q){this.cacheIdx%=this.cacheLimit;let z=this.cache[this.cacheIdx];if(this.cacheIdx--,!z)return"OUT_OF_RANGE";this.undo(z),Q=this.cacheIdx===H-1}let $=Z.substring(X+1);return this.doStep($),this.mode="record",this.cacheUpdateNumber=_,null}return"OUT_OF_RANGE"}undoStep(Z){let X=Z.indexOf(":"),_=Z.substring(0,X),G=Z.substring(X+1);switch(_){case"add":this.delete(JSON.parse(G));break;case"del":this.add(JSON.parse(G));break;case"clear":{let W=JSON.parse(G);for(let H of W)this.add(H);break}case"tx":{let W=G.split(";");for(let H=W.length-1;H>=0;H--)this.undoStep(W[H])}}}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 N7(Y=Math.random){return Y().toString(36).slice(2)}var P5=class extends Promise{fate;resolve;reject;done=!1;constructor(Y){let Z,X;super((_,G)=>{Z=_,X=G});this.resolve=Z,this.reject=X,this.use(Y instanceof Promise?Y:new Promise(Y))}pass(Y,Z){if(Y===this.fate)this.resolve(Z),this.done=!0}fail(Y,Z){if(Y===this.fate)this.reject(Z),this.done=!0}use(Y){if(Y instanceof Promise){let Z=Y;this.fate=Z,Z.then((X)=>{this.pass(Z,X)},(X)=>{this.fail(Z,X)})}else this.resolve(Y),this.fate=void 0}};function i(Y){while(Y.child!==null)Y=Y.child;return Y}var NF=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}},RF={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"};function IF(Y,Z){let X=z0(Z),_=`${Y.key}(${X})`,G=RF[Y.type],W={key:_,type:G};return Object.assign(W,{family:{key:Y.key,subKey:X}}),Object.assign(W,{counterfeit:!0}),W}function W4(Y){let Z={key:Y.key,type:Y.type};if("family"in Y)Z.family=Y.family;return Z}var G1=class{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 X=this.relations.get(Y),_=this.relations.get(Z);if(X)X.add(Z);else X=new Set([Z]),this.relations.set(Y,X);if(_)_.add(Y);else _=new Set([Y]),this.relations.set(Z,_)}deleteRelation(Y,Z){let X=this.relations.get(Y);if(X){if(X.delete(Z),X.size===0)this.relations.delete(Y);let _=this.relations.get(Z);if(_){if(_.delete(Y),_.size===0)this.relations.delete(Z)}}}replaceRelationsUnsafely(Y,Z){this.relations.set(Y,new Set(Z));for(let X of Z){let _=new Set().add(Y);this.relations.set(X,_)}}replaceRelationsSafely(Y,Z){let X=this.relations.get(Y),_=this.isAType?.(Y)?Y:void 0,G=_===void 0?Y:void 0;if(X)for(let W of X){_??=W,G??=W;let H=this.relations.get(W);if(H){if(H.size===1)this.relations.delete(W);else H.delete(Y);this.contents.delete(this.makeContentKey(_,G))}}this.relations.set(Y,new Set(Z));for(let W of Z){let H=this.relations.get(W);if(H)H.add(Y);else H=new Set().add(Y),this.relations.set(W,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,!Z?.externalStore)this.relations=new Map(Y.relations?.map(([X,_])=>[X,new Set(_)])),this.contents=new Map(Y.contents);if(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 X=Z.externalStore;if(this.has=(_,G)=>X.has(_,G),this.addRelation=(_,G)=>{X.addRelation(_,G)},this.deleteRelation=(_,G)=>{X.deleteRelation(_,G)},this.replaceRelationsSafely=(_,G)=>{X.replaceRelationsSafely(_,G)},this.replaceRelationsUnsafely=(_,G)=>{X.replaceRelationsUnsafely(_,G)},this.getRelatedKeys=(_)=>X.getRelatedKeys(_),X.getContent)this.getContentInternal=(_)=>{return X.getContent(_)},this.setContent=(_,G)=>{X.setContent(_,G)},this.deleteContent=(_)=>{X.deleteContent(_)};for(let[_,G]of Y.relations??[]){let W=this.isAType?.(_)?_:void 0,H=W===void 0?_:void 0;for(let J of G)W??=J,H??=J,this.addRelation(W,H)}for(let[_,G]of Y.contents??[])this.setContent(_,G)}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,X,_;switch(Y.length){case 1:{let G=Y[0];Z=G[this.a],X=G[this.b],_=void 0;break}case 2:{let G=Y[0];if(typeof G==="string")[Z,X]=Y;else Z=G[this.a],X=G[this.b],_=Y[1];break}default:{Z=Y[0],X=Y[1],_=Y[2];break}}switch(this.cardinality){case"1:1":{let G=this.getRelatedKey(Z);if(G&&G!==X)this.delete(Z,G)}case"1:n":{let G=this.getRelatedKey(X);if(G&&G!==Z)this.delete(G,X)}break;case"n:n":}if(_){let G=this.makeContentKey(Z,X);this.setContent(G,_)}return this.addRelation(Z,X),this}delete(Y,Z){Z=typeof Z==="string"?Z:Y[this.b];let X=typeof Y==="string"?Y:Y[this.a];if(X===void 0&&typeof Z==="string"){let _=this.getRelatedKeys(Z);if(_)for(let G of _)this.delete(G,Z)}if(typeof X==="string"&&Z===void 0){let _=this.getRelatedKeys(X);if(_)for(let G of _)this.delete(X,G)}if(typeof X==="string"&&typeof Z==="string"){this.deleteRelation(X,Z);let _=this.makeContentKey(X,Z);this.deleteContent(_)}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((_)=>`"${_}"`).join(", ")}). Only one related key was expected.`);let X;for(let _ of Z){X=_;break}return X}}replaceRelations(Y,Z,X){let _=!Array.isArray(Z),G=_?Object.keys(Z):Z;if(X?.reckless)this.replaceRelationsUnsafely(Y,G);else this.replaceRelationsSafely(Y,G);if(_)for(let W of G){let H=this.makeContentKey(Y,W),J=Z[W];this.setContent(H,J)}return this}getContent(Y,Z){let X=this.makeContentKey(Y,Z);return this.getContentInternal(X)}getRelationEntries(Y){let Z=Y[this.a],X=Y[this.b];if(Z!==void 0&&X===void 0){let _=this.getRelatedKeys(Z);if(_)return[..._].map((G)=>{return[G,this.getContent(Z,G)]})}if(Z===void 0&&X!==void 0){let _=this.getRelatedKeys(X);if(_)return[..._].map((G)=>{return[G,this.getContent(G,X)]})}return[]}has(Y,Z){if(Z)return this.getRelatedKeys(Y)?.has(Z)??!1;return this.relations.has(Y)}},H0=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)}},BF=class extends H0{state;constructor(Y){super();this.state=Y}next(Y){this.state=Y,super.next(Y)}};function N4(Y){return"epoch"in Y.transactionMeta}function o0(Y){return"phase"in Y.transactionMeta}var TF=(Y)=>{let Z=i(Y);if(!o0(Z)){Y.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}Y.logger.info("\uD83E\uDE82","transaction",Z.transactionMeta.update.key,"Aborting transaction"),Z.parent.child=null};function B0(Y){return Y[0].toUpperCase()+Y.slice(1)}function f4(Y){return Y.type.split("_").map(B0).join(" ")}var b5=class extends Error{constructor(Y,Z){super(`${f4(Y)} ${z0(Y.key)} not found in store "${Z.config.name}".`)}};function C5(Y,Z,X){return(..._)=>{let G=m0(Y,Z);if(G)return G.run(_,X);throw new b5(Z,Y)}}var k5=(Y)=>(Z)=>Y instanceof Function?Y(Z):Y,LY=(Y,Z)=>{if(Y.valueMap.has(Z.key))return Y.logger.info("\uD83D\uDCD6",Z.type,Z.key,"reading cached value"),ZU(Z,Y);switch(Z.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return Y.logger.info("\uD83E\uDDEE",Z.type,Z.key,"computing value"),Z.get();case"atom":case"mutable_atom":{let X=Z.default,_;if(X instanceof Function)_=X();else _=X;return Y.logger.info("\uD83D\uDC81","atom",Z.key,"could not find cached value; using default",_),_}}},S5=(Y,Z)=>{if(Y.operation.open){let X=performance.now();return Y.logger.info("\u2757",Z.type,Z.key,`deferring setState at T-${X} until setState for "${Y.operation.token.key}" is done`),X}Y.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:Z},Y.logger.info("\u2B55",Z.type,Z.key,`operation start in store "${Y.config.name}"${!o0(Y)?"":` ${Y.transactionMeta.phase} "${Y.transactionMeta.update.key}"`}`)},v5=(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)},v7=(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)},Q6=(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)},CF=(Y,Z,X)=>{switch(Z.type){case"mutable_atom":Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"is now (",X.newValue,") subscribers:",Z.subject.subscribers);break;case"atom":case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"went (",X.oldValue,"->",X.newValue,") subscribers:",Z.subject.subscribers)}Z.subject.next(X)};function x5(Y,Z){let X=i(Y),_=X.selectorAtoms.getRelatedKeys(Z.key);if(X.logger.info("\uD83E\uDDF9",Z.type,Z.key,_?`evicting ${_.size} states downstream:`:"no downstream states",_??"to evict"),_){if(X.operation.open)X.logger.info("\uD83E\uDDF9",Z.type,Z.key,`[ ${[...X.operation.done].join(", ")} ] already done`);for(let G of _){if(v7(X,G))continue;p7(G,X),Q6(X,G)}}}function KF(Y,Z){let X=i(Y),_=X.selectorGraph.getRelationEntries({upstreamSelectorKey:Z.key}).filter(([G,{source:W}])=>W===Z.key);for(let[G]of _){if(v7(X,G))continue;p7(G,X),Q6(X,G)}}var qF=(Y,Z,X)=>{let _=LY(Y,Z),G=_;if(Z.type==="mutable_atom"&&o0(Y)){let{parent:H}=Y;G=f5(Y,Z,H)}if(G=k5(X)(G),Y.logger.info("\uD83D\uDCDD","atom",Z.key,"set to",G),G=o1(Y,Z.key,G,Z.subject),XU(Y,Z.key))_U(Y,Z.key);Q6(Y,Z.key),x5(Y,Z);let W={oldValue:_,newValue:G};if(!o0(Y)){CF(Y,Z,W);return}if(Y.on.transactionApplying.state===null){let{key:H}=Z;if(YU(W.newValue))return;let J={type:"atom_update",key:H,...W};if(Z.family)J.family=Z.family;Y.transactionMeta.update.updates.push(J),Y.logger.info("\uD83D\uDCC1","atom",H,"stowed (",W.oldValue,"->",W.newValue,")")}else if(Z.key.startsWith("*")){let H=Z.key.slice(1),J=Y.atoms.get(H),Q=Y.valueMap.get(H);if(J.type==="mutable_atom"&&o0(Y)){let{parent:z}=Y;Q=f5(Y,J,z)}if(Q.do(W.newValue)===null)x5(Y,J)}},x7=(Y,Z,X)=>{switch(Z.type){case"atom":case"mutable_atom":qF(Y,Z,X);break;case"writable_pure_selector":case"writable_held_selector":Z.set(X);break}};function z6(Y,Z,X){let _={key:Z.key,type:"atom_family"},G=Y.families.get(Z.key);if(G)Y.logger.error("\u2757","atom_family",Z.key,`Overwriting an existing ${f4(G)} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let W=new H0,J=Object.assign((Q)=>{let $=z0(Q),z={key:Z.key,subKey:$},O=`${Z.key}(${$})`,L=i(Y),V=Z.default,R={key:O,default:V instanceof Function?V(Q):V};if(Z.effects)R.effects=Z.effects(Q);let A=k4(L,R,z);return W.next({type:"state_creation",token:A}),A},_,{subject:W,install:(Q)=>z6(Q,Z),internalRoles:X});return Y.families.set(Z.key,J),Y.defaults.set(Z.key,Z.default),_}function R7(Y,Z){if("mutable"in Z)return l5(Y,Z);return z6(Y,Z)}var g5=(Y,Z)=>i(Y).atoms.has(Z),jF=(Y,Z)=>i(Y).writableSelectors.has(Z),PF=(Y,Z)=>i(Y).readonlySelectors.has(Z),SF=(Y,Z)=>g5(Y,Z)||jF(Y,Z)||PF(Y,Z),h5=(Y,Z)=>{return i(Y).selectorGraph.getRelationEntries({downstreamSelectorKey:Z}).filter(([_,{source:G}])=>G!==Z).map(([_,{source:G}])=>G).filter((_)=>SF(Y,_))},h7=(Y,Z,X)=>{let _=[],G=h5(Y,Z);while(G.length>0){let W=G.shift();if(X.has(W))continue;if(X.add(W),!g5(Y,W))G.push(...h5(Y,W));else if(!_.includes(W))_.push(W)}return _},vF=(Y,Z)=>{let X=Y.key,_=h5(Z,X),G=new Set;return _.flatMap((W)=>g5(Z,W)?W:h7(Z,W,G))},xF=(Y,Z,X,_,G)=>{let W=i(Y),{type:H,key:J}=_;if(H==="atom"||H==="mutable_atom")W.selectorAtoms.set({selectorKey:X,atomKey:J}),Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atom "${J}"`);else{let Q=h7(Y,J,G);Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atoms: [ ${Q.map(($)=>`"${$}"`).join(", ")} ]`);for(let $ of Q)W.selectorAtoms=W.selectorAtoms.set({selectorKey:X,atomKey:$})}G.add(J)},DY=(Y,Z,X,_)=>({get:(...G)=>{let W=i(Y),H;if(G.length===2){let[z,O]=G;H=Q0(Y,z,O)}else[H]=G;let J=m0(Y,H),Q=LY(Y,J),$=H.key;return Y.logger.info("\uD83D\uDD0C",Z,X,`registers dependency ( "${$}" =`,Q,")"),W.selectorGraph.set({upstreamSelectorKey:$,downstreamSelectorKey:X},{source:H.key}),xF(Y,Z,X,H,_),Q},set:(...G)=>{let W,H;if(G.length===2)W=G[0],H=G[1];else{let $=G[0],z=G[1];H=G[2],W=Q0(Y,$,z)}let J=i(Y),Q=m0(J,W);x7(J,Q,H)},find:(...G)=>Q0(Y,...G),json:(G)=>b4(Y,G)}),y5=(Y,Z,X)=>{let _=i(Y),G=new H0,W=new Set,{key:H,const:J}=Z,Q="readonly_held_selector",{get:$,find:z,json:O}=DY(_,"readonly_held_selector",H,W),V={...Z,type:"readonly_held_selector",subject:G,install:(A)=>y5(A,Z,X),get:()=>{return Z.get({get:$,find:z,json:O},J),o1(i(Y),H,J,G),W.clear(),J},...X&&{family:X}};_.readonlySelectors.set(H,V),Y.logger.info("\u2728","readonly_held_selector",H,"=",J);let R={key:H,type:"readonly_held_selector"};if(X)R.family=X;return R},p5=(Y,Z,X)=>{let _=i(Y),G=new H0,W=new Set,H=Z.key,J="readonly_pure_selector",{get:Q,find:$,json:z}=DY(_,"readonly_pure_selector",H,W),O=()=>{let A=Z.get({get:Q,find:$,json:z});return o1(i(Y),H,A,G),W.clear(),A},L={...Z,type:"readonly_pure_selector",subject:G,install:(A)=>p5(A,Z,X),get:O,...X&&{family:X}};_.readonlySelectors.set(H,L);let V=O();Y.logger.info("\u2728","readonly_pure_selector",H,"=",V);let R={key:H,type:"readonly_pure_selector"};if(X)R.family=X;return R},m5=(Y,Z,X)=>{let _=i(Y),G=new H0,W=new Set,{key:H,const:J}=Z,Q="writable_held_selector",$=DY(_,"writable_held_selector",H,W),{find:z,get:O,json:L}=$,V={find:z,get:O,json:L},R=(g=Z.get,N=i(Y))=>{return g(V,J),o1(N,H,J,G),W.clear(),J},f={...Z,type:"writable_held_selector",subject:G,install:(g)=>m5(g,Z,X),get:R,set:(g)=>{let N=i(Y),I=R(Z.get,N),q=k5(g)(I);if(Y.logger.info("\uD83D\uDCDD","writable_held_selector",H,"set (",I,"->",q,")"),o1(N,H,q,G),Q6(N,H),N4(N))G.next({newValue:q,oldValue:I});Z.set($,q)},...X&&{family:X}};_.writableSelectors.set(H,f);let b=R();Y.logger.info("\u2728","writable_held_selector",H,"=",b);let k={key:H,type:"writable_held_selector"};if(X)k.family=X;return k},u5=(Y,Z,X)=>{let _=i(Y),G=new H0,W=new Set,H=Z.key,J="writable_pure_selector",Q=DY(_,"writable_pure_selector",H,W),{find:$,get:z,json:O}=Q,L={find:$,get:z,json:O},V=(k=Z.get,g=i(Y))=>{let N=k(L);return o1(g,H,N,G),W.clear(),N},A={...Z,type:"writable_pure_selector",subject:G,install:(k)=>u5(k,Z,X),get:V,set:(k)=>{let g=i(Y),N=V(Z.get,g),I=k5(k)(N);if(Y.logger.info("\uD83D\uDCDD","writable_pure_selector",H,"set (",N,"->",I,")"),o1(g,Z.key,I,G),Q6(g,Z.key),N4(g))G.next({newValue:I,oldValue:N});Z.set(Q,I)},...X&&{family:X}};_.writableSelectors.set(H,A);let f=V();Y.logger.info("\u2728",A.type,A.key,"=",f);let b={key:H,type:"writable_pure_selector"};if(X)b.family=X;return b};function O8(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X){let W=m5(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}if(_){let W=y5(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}if(X){let W=u5(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}let G=p5(Y,Z,void 0);return Y.on.selectorCreation.next(G),G}function hF(Y,Z){let X=i(Y),{key:_,type:G}=Z,W=m0(X,Z);if(!W.family)Y.logger.error("\u274C",G,_,"Standalone selectors cannot be disposed.");else{if(X.molecules.get(W.family.subKey))X.moleculeData.delete(W.family.subKey,W.family.key);let J;switch(Z.type){case"writable_held_selector":X.writableSelectors.delete(_),J={key:W.family.key,type:"writable_held_selector_family"},m0(Y,J).subject.next({type:"state_disposal",subType:"selector",token:Z});break;case"writable_pure_selector":X.writableSelectors.delete(_),J={key:W.family.key,type:"writable_pure_selector_family"},m0(Y,J).subject.next({type:"state_disposal",subType:"selector",token:Z});break;case"readonly_held_selector":X.readonlySelectors.delete(_),J={key:W.family.key,type:"readonly_held_selector_family"},m0(Y,J).subject.next({type:"state_disposal",subType:"selector",token:Z});break;case"readonly_pure_selector":X.readonlySelectors.delete(_),J={key:W.family.key,type:"readonly_pure_selector_family"},m0(Y,J).subject.next({type:"state_disposal",subType:"selector",token:Z});break}if(X.valueMap.delete(_),X.selectorAtoms.delete(_),X.selectorGraph.delete(_),Y.logger.info("\uD83D\uDD25",Z.type,_,"deleted"),o0(X)&&X.transactionMeta.phase==="building")X.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:Z});else Y.on.selectorDisposal.next(Z)}}function h4(Y,Z,X){let _=Z.key,G="readonly_pure_selector_family",W={key:_,type:"readonly_pure_selector_family"},H=Y.families.get(_);if(H)Y.logger.error("\u2757","readonly_pure_selector_family",_,`Overwriting an existing ${f4(H)} "${H.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new H0,$=Object.assign((z)=>{let O=z0(z),L={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=p5(R,{key:V,get:Z.get(z)},L);return J.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:J,install:(z)=>h4(z,Z),default:(z)=>{return Z.get(z)({get:(...L)=>k1(Y,...L),find:(...L)=>Q0(Y,...L),json:(L)=>b4(Y,L)})}});return Y.families.set(_,$),W}function f7(Y,Z,X){let _=Z.key,G="readonly_held_selector_family",W={key:_,type:"readonly_held_selector_family"},H=Y.families.get(_);if(H)Y.logger.error("\u2757","readonly_held_selector_family",_,`Overwriting an existing ${f4(H)} "${H.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new H0,$=Object.assign((z)=>{let O=z0(z),L={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=y5(R,{key:V,const:Z.const(z),get:Z.get(z)},L);return J.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:J,install:(z)=>f7(z,Z),default:Z.const});return Y.families.set(_,$),W}function b7(Y,Z,X){let _=Z.key,G="writable_held_selector_family",W={key:_,type:"writable_held_selector_family"},H=Y.families.get(_);if(H)Y.logger.error("\u2757","writable_held_selector_family",_,`Overwriting an existing ${f4(H)} "${H.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new H0,$=Object.assign((z)=>{let O=z0(z),L={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=m5(R,{key:V,const:Z.const(z),get:Z.get(z),set:Z.set(z)},L);return J.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:J,install:(z)=>b7(z,Z),default:Z.const});return Y.families.set(_,$),W}function UY(Y,Z,X){let _=Z.key,G="writable_pure_selector_family",W={key:_,type:"writable_pure_selector_family"},H=Y.families.get(_);if(H)Y.logger.error("\u2757","writable_pure_selector_family",_,`Overwriting an existing ${f4(H)} "${H.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new H0,$=Object.assign((z)=>{let O=z0(z),L={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=u5(R,{key:V,get:Z.get(z),set:Z.set(z)},L);return J.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:J,install:(z)=>UY(z,Z),default:(z)=>{return Z.get(z)({get:(...L)=>k1(Y,...L),find:(...L)=>Q0(Y,...L),json:(L)=>b4(Y,L)})}});return Y.families.set(_,$),W}function K5(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X)return b7(Y,Z,void 0);if(_)return f7(Y,Z,void 0);if(X)return UY(Y,Z);return h4(Y,Z)}function fF(Y,Z,X){let _=Y.families.get(Z.key);if(_===void 0)throw new b5(Z,Y);let G=_(X),W=i(Y);if(G.family){if(N4(W))switch(G.type){case"atom":case"mutable_atom":Y.on.atomCreation.next(G);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":Y.on.selectorCreation.next(G);break}else if(o0(W)&&W.on.transactionApplying.state===null)W.transactionMeta.update.updates.push({type:"state_creation",token:G})}return G}function bF(Y,Z,X){let _=z0(X),G=`${Z.key}(${_})`,W=i(Y),H;switch(Z.type){case"atom_family":case"mutable_atom_family":H=W.atoms.get(G);break;case"writable_held_selector_family":case"writable_pure_selector_family":H=W.writableSelectors.get(G);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":H=W.readonlySelectors.get(G);break}if(H)return W4(H);return H}function Q0(Y,Z,X){let _=bF(Y,Z,X);if(_)return _;let G=z0(X),W=Y.molecules.get(G);if(!W&&Y.config.lifespan==="immortal"){let H=IF(Z,X);return Y.logger.error("\u274C",H.type,H.key,`was not found in store "${Y.config.name}"; returned a counterfeit token.`),H}if(_=fF(Y,Z,X),W)i(Y).moleculeData.set(G,Z.key);return _}function L8(Y,...Z){let X;if(Z.length===1)X=Z[0];else{let _=Z[0],G=Z[1];X=Q0(Y,_,G)}try{m0(Y,X)}catch(_){Y.logger.error("\u274C",X.type,X.key,`could not be disposed because it was not found in the store "${Y.config.name}".`);return}switch(X.type){case"atom":case"mutable_atom":u7(Y,X);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":hF(Y,X);break}}function kF(Y,Z){if(Z.family){let X=Y.families.get(Z.family.key);if(X)return X}}function N1(Y,...Z){let X,_,G,W;if(Z.length===2){if(X=Z[0],W=Z[1],_=kF(Y,X)??null,_)G=X.family?E1(X.family.subKey):null,X=Q0(Y,_,G)}else _=Z[0],G=Z[1],W=Z[2],X=Q0(Y,_,G);if("counterfeit"in X&&"family"in X){let Q=X.family.subKey,$=Y.disposalTraces.buffer.find((z)=>z?.key===Q);Y.logger.error("\u274C",X.type,X.key,`could not be set because it was not found in the store "${Y.config.name}".`,$?`This state was previously disposed:
|
|
48
|
+
${$.trace}`:"No previous disposal trace was found.");return}let H=S5(Y,X);if(H){let Q=Y.on.operationClose.subscribe(`waiting to set "${X.key}" at T-${H}`,()=>{Q(),Y.logger.info("\uD83D\uDFE2",X.type,X.key,`resuming deferred setState from T-${H}`),N1(Y,X,W)});return}let J=m0(Y,X);x7(Y,J,W),v5(Y)}function gF(Y,Z,X){let{key:_,newValue:G,oldValue:W}=Z,H=Y==="newValue"?G:W,J={key:_,type:"atom"};if(Z.family)Object.assign(J,{family:Z.family});N1(X,J,H)}function yF(Y){let{stack:Z}=Y;if(Z)return`
|
|
49
|
+
`+Z.split(`
|
|
50
|
+
`)?.slice(1)?.join(`
|
|
51
|
+
`);return""}function I7(Y,Z=x0.STORE){let X={key:Y,stringKey:z0(Y),dependsOn:"any"};return Z.molecules.set(z0(Y),X),Y}function D8(Y,Z,X,_="any"){let G=Z,W=z0(X),H=[],J=i(Y);if(Array.isArray(G))for(let z of G){let O=z0(z);if(J.molecules.get(O))Y.moleculeGraph.set(O,W,{source:O});else H.push(O)}else{let z=z0(G);if(J.molecules.get(z))Y.moleculeGraph.set(z,W,{source:z});else H.push(z)}if(H.length===0)J.molecules.set(W,{key:X,stringKey:W,dependsOn:_});let Q={type:"molecule_creation",key:X,provenance:G};if(o0(J)&&J.transactionMeta.phase==="building")J.transactionMeta.update.updates.push(Q);else J.on.moleculeCreation.next(Q);for(let z of H){let O=Y.disposalTraces.buffer.find((L)=>L?.key===z);Y.logger.error("\u274C","molecule",X,"allocation failed:",`Could not allocate to ${z} in store "${Y.config.name}".`,O?`
|
|
52
|
+
${z} was most recently disposed
|
|
53
|
+
${O.trace}`:`No previous disposal trace for ${z} was found.`)}return X}function B7(Y,Z,X,_){let G=`T$--${Z}==${X}++${_}`;return D8(Y,[X,_],G,"all"),G}function V8(Y,Z){let X=z0(Z),_=Y.molecules.get(X);if(!_){let V=Y.disposalTraces.buffer.find((R)=>R?.key===X);Y.logger.error("\u274C","molecule",Z,"deallocation failed:",`Could not find allocation for ${X} in store "${Y.config.name}".`,V?`
|
|
54
|
+
This state was most recently deallocated
|
|
55
|
+
${V.trace}`:`No previous disposal trace for ${X} was found.`);return}let G=Y.moleculeJoins.getRelatedKeys(_.key);if(G)for(let V of G){let R=Y.joins.get(V);if(R)R.relations.delete(_.key),R.molecules.delete(_.stringKey)}Y.moleculeJoins.delete(_.stringKey);let W=[],H=[],J={type:"molecule_disposal",key:_.key,values:H,provenance:W},Q=i(Y);Q.molecules.delete(X);let $=o0(Q)&&Q.transactionMeta.phase==="building";if($)Q.transactionMeta.update.updates.push(J);let z=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:_.stringKey});if(z)for(let[V,{source:R}]of z)if(R===_.stringKey){let A=E1(V);V8(Y,A)}else W.push(R);let O=Q.moleculeData.getRelatedKeys(_.stringKey);if(O)for(let V of O){let R=Q.families.get(V),A=Q0(Y,R,_.key);H.push([R.key,A]),L8(Y,A)}if(Q.moleculeGraph.delete(_.stringKey),Q.moleculeJoins.delete(_.stringKey),Q.moleculeData.delete(_.stringKey),!$)Q.on.moleculeDisposal.next(J);Q.molecules.delete(_.stringKey);let L=yF(new Error);Y.disposalTraces.add({key:X,trace:L})}function H6(Y,Z,X,_){let G=z0(X),W=i(Y),H=W.molecules.get(G);if(!H){let L=Y.disposalTraces.buffer.find((V)=>V?.key===G);return Y.logger.error("\u274C","molecule",X,"claim failed:",`Could not allocate to ${G} in store "${Y.config.name}".`,L?`
|
|
56
|
+
${G} was most recently disposed
|
|
57
|
+
${L.trace}`:`No previous disposal trace for ${G} was found.`),X}let J=z0(Z),Q=W.molecules.get(J);if(!Q){let L=Y.disposalTraces.buffer.find((V)=>V?.key===J);return Y.logger.error("\u274C","molecule",X,"claim failed:",`Could not allocate to ${J} in store "${Y.config.name}".`,L?`
|
|
58
|
+
${J} was most recently disposed
|
|
59
|
+
${L.trace}`:`No previous disposal trace for ${J} was found.`),X}let $=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:H.stringKey}).filter(([,{source:L}])=>L!==G).map(([L])=>E1(L));if(_)W.moleculeGraph.delete(G);W.moleculeGraph.set({upstreamMoleculeKey:Q.stringKey,downstreamMoleculeKey:H.stringKey},{source:Q.stringKey});let z={type:"molecule_transfer",key:H.key,from:$,to:[Q.key]};if(o0(W)&&W.transactionMeta.phase==="building")W.transactionMeta.update.updates.push(z);return X}function pF(Y,Z,X){switch(Z){case"newValue":{k7(Y,X);break}case"oldValue":{L8(X,Y.token);break}}}function mF(Y,Z,X){switch(Z){case"newValue":{L8(X,Y.token);break}case"oldValue":{if(k7(Y,X),Y.subType==="atom")X.valueMap.set(Y.token.key,Y.value);break}}}function k7(Y,Z){let{family:X}=Y.token;if(X){let _=Z.families.get(X.key);if(_)Q0(Z,_,E1(X.subKey))}}function uF(Y,Z,X){switch(Z){case"newValue":D8(X,Y.provenance,Y.key);break;case"oldValue":V8(X,Y.key);break}}function dF(Y,Z,X){switch(Z){case"newValue":V8(X,Y.key);break;case"oldValue":{let _=Y.provenance.map(E1);D8(X,_,Y.key);for(let[G,W]of Y.values){let H=X.families.get(G);if(H){Q0(X,H,Y.key);let J=`${G}(${z0(Y.key)})`;X.valueMap.set(J,W)}}}break}}function cF(Y,Z,X){switch(Z){case"newValue":{let _=Y.to.length===1?Y.to[0]:Y.to;H6(X,_,Y.key,"exclusive")}break;case"oldValue":{let _=Y.from.length===1?Y.from[0]:Y.from;H6(X,_,Y.key,"exclusive")}break}}function g7(Y,Z,X){let _=Y==="newValue"?Z.updates:[...Z.updates].reverse();for(let G of _)switch(G.type){case"atom_update":case"selector_update":gF(Y,G,X);break;case"state_creation":pF(G,Y,X);break;case"state_disposal":mF(G,Y,X);break;case"molecule_creation":uF(G,Y,X);break;case"molecule_disposal":dF(G,Y,X);break;case"molecule_transfer":cF(G,Y,X);break;case"transaction_update":g7(Y,G,X);break}}function y7(Y,Z){return Y.transactionMeta.actionContinuities.getRelatedKey(Z)}function lF(Y,Z){return Y.transactionMeta.epoch.get(Z)}function iF(Y,Z){if(!N4(Y))return;let _=y7(Y,Z);if(_===void 0)return;return lF(Y,_)}function oF(Y,Z,X){if(!N4(Y))return;let G=y7(Y,Z);if(G!==void 0)Y.transactionMeta.epoch.set(G,X)}var nF=(Y,Z)=>{let X=i(Z),{parent:_}=X;if(_===null||!o0(X)||X.transactionMeta?.phase!=="building"){Z.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}X.transactionMeta.phase="applying",X.transactionMeta.update.output=Y,_.child=null,_.on.transactionApplying.next(X.transactionMeta);let{updates:G}=X.transactionMeta.update;if(Z.logger.info("\uD83D\uDEC4","transaction",X.transactionMeta.update.key,`Applying transaction with ${G.length} updates:`,G),g7("newValue",X.transactionMeta.update,_),N4(_))oF(_,X.transactionMeta.update.key,X.transactionMeta.update.epoch),m0(Z,{key:X.transactionMeta.update.key,type:"transaction"})?.subject.next(X.transactionMeta.update),Z.logger.info("\uD83D\uDEEC","transaction",X.transactionMeta.update.key,"Finished applying transaction.");else if(o0(_))_.transactionMeta.update.updates.push(X.transactionMeta.update);_.on.transactionApplying.next(null)};function rF(Y){return{store:Y}}function k1(Y,...Z){let X,_,G;if(Z.length===1)X=Z[0];else _=Z[0],G=Z[1],X=Q0(Y,_,G);if("counterfeit"in X&&"family"in X){_=Y.families.get(X.family.key);let W=X.family.subKey,H=Y.disposalTraces.buffer.find((J)=>J?.key===W);switch(Y.logger.error("\u274C",X.type,X.key,`could not be retrieved because it was not found in the store "${Y.config.name}".`,H?`This state was previously disposed:
|
|
60
|
+
${H.trace}`:"No previous disposal trace was found."),_.type){case"atom_family":case"mutable_atom_family":return Y.defaults.get(_.key);case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(Y.defaults.has(_.key))return Y.defaults.get(X.family.key);let J=m0(Y,_).default(W);return Y.defaults.set(_.key,J),J}}}return LY(Y,m0(Y,X))}var i1=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))return this.source.get(Y);return}set(Y,Z){return this.deleted.delete(Y),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){return this.deleted.add(Y),super.delete(Y)}},sF=(Y,Z,X,_)=>{let G=i(Y),W={parent:G,child:null,on:G.on,loggers:G.loggers,logger:G.logger,config:G.config,atoms:new i1(G.atoms),atomsThatAreDefault:new Set(G.atomsThatAreDefault),families:new i1(G.families),joins:new i1(G.joins),operation:{open:!1},readonlySelectors:new i1(G.readonlySelectors),timelines:new i1(G.timelines),timelineTopics:new G1(G.timelineTopics.toJSON()),trackers:new Map,transactions:new i1(G.transactions),selectorAtoms:new G1(G.selectorAtoms.toJSON()),selectorGraph:new G1(G.selectorGraph.toJSON(),{makeContentKey:(...$)=>$.sort().join(":")}),writableSelectors:new i1(G.writableSelectors),valueMap:new i1(G.valueMap),defaults:G.defaults,disposalTraces:Y.disposalTraces.copy(),molecules:new i1(G.molecules),moleculeGraph:new G1(G.moleculeGraph.toJSON(),{makeContentKey:G.moleculeGraph.makeContentKey}),moleculeData:new G1(G.moleculeData.toJSON(),{makeContentKey:G.moleculeData.makeContentKey}),moleculeJoins:new G1(G.moleculeJoins.toJSON(),{makeContentKey:G.moleculeJoins.makeContentKey}),miscResources:new i1(G.miscResources)},H=iF(Y,Z),J={phase:"building",update:{type:"transaction_update",key:Z,id:_,epoch:H===void 0?NaN:H+1,updates:[],params:X,output:void 0},toolkit:{get:(...$)=>k1(Q,...$),set:(...$)=>{N1(Q,...$)},run:($,z=N7())=>C5(Q,$,z),find:(...$)=>Q0(Y,...$),json:($)=>b4(Q,$),dispose:(...$)=>{L8(Q,...$)},env:()=>rF(Q)}},Q=Object.assign(W,{transactionMeta:J});return G.child=Q,Y.logger.info("\uD83D\uDEEB","transaction",Z,"Building transaction with params:",X),Q};function q5(Y,Z){let X={key:Z.key,type:"transaction",run:(W,H)=>{let J=sF(Y,Z.key,W,H);try{let Q=i(Y),{toolkit:$}=J.transactionMeta,z=Z.do($,...W);return nF(z,Q),z}catch(Q){throw TF(_),Y.logger.warn("\uD83D\uDCA5","transaction",Z.key,"caught:",Q),Q}},install:(W)=>q5(W,Z),subject:new H0},_=i(Y);_.transactions.set(X.key,X);let G=W4(X);return Y.on.transactionCreation.next(G),G}var T7=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 G1({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new G1({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new G1({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new G1({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new NF(100);molecules=new Map;moleculeJoins=new G1({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeGraph=new G1({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeData=new G1({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});miscResources=new Map;on={atomCreation:new H0,atomDisposal:new H0,selectorCreation:new H0,selectorDisposal:new H0,timelineCreation:new H0,transactionCreation:new H0,transactionApplying:new BF(null),operationClose:new H0,moleculeCreation:new H0,moleculeDisposal:new H0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new A7("warn",(Y,Z,X)=>!M8(X))];logger={error:(...Y)=>{for(let Z of this.loggers)Z.error(...Y)},info:(...Y)=>{for(let Z of this.loggers)Z.info(...Y)},warn:(...Y)=>{for(let Z of this.loggers)Z.warn(...Y)}};constructor(Y,Z=null){if(this.config={...Z?.config,...Y},Z!==null){if(this.valueMap=new Map(Z?.valueMap),this.operation={...Z?.operation},N4(Z))this.transactionMeta={epoch:new Map(Z?.transactionMeta.epoch),actionContinuities:new G1(Z?.transactionMeta.actionContinuities.toJSON())};for(let[,_]of Z.families){if(_.internalRoles?.includes("mutable")||_.internalRoles?.includes("join"))continue;_.install(this)}let X=new Set;for(let[,_]of Z.atoms){if(X.has(_.key))continue;if(_.install(this),_.type==="mutable_atom"){let G=b4(Z,_),W=i5(_);X.add(G.key),X.add(W.key)}}for(let[,_]of Z.readonlySelectors)_.install(this);for(let[,_]of Z.writableSelectors){if(X.has(_.key))continue;_.install(this)}for(let[,_]of Z.transactions)_.install(this);for(let[,_]of Z.timelines)_.install(this)}}},x0={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new T7({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function m0(Y,Z){let X,_=Y;while(_!==null){switch(Z.type){case"atom":case"mutable_atom":X=_.atoms.get(Z.key);break;case"writable_pure_selector":case"writable_held_selector":X=_.writableSelectors.get(Z.key);break;case"readonly_pure_selector":case"readonly_held_selector":X=_.readonlySelectors.get(Z.key);break;case"atom_family":case"mutable_atom_family":case"writable_pure_selector_family":case"readonly_pure_selector_family":case"writable_held_selector_family":case"readonly_held_selector_family":X=_.families.get(Z.key);break;case"timeline":X=_.timelines.get(Z.key);break;case"transaction":X=_.transactions.get(Z.key);break}if(X)return X;_=_.child}throw new b5(Z,Y)}var aF=(Y,Z)=>{let X=i(Y);if(X.operation.open)return X.operation.prev.get(Z.key);return X.valueMap.get(Z.key)};var P7=(Y,Z)=>{let X=i(Y);return vF(Z,Y).map((G)=>{let W=X.atoms.get(G);if(W===void 0)throw new Error(`Atom "${G}", a dependency of selector "${Z.key}", not found in store "${Y.config.name}".`);return W.subject.subscribe(`${Z.type}:${Z.key}`,(H)=>{Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"root",G,"went",H.oldValue,"->",H.newValue);let J=aF(X,Z),Q=LY(X,Z);Y.logger.info("\u2728",Z.type,Z.key,"went",J,"->",Q),Z.subject.next({newValue:Q,oldValue:J})})})};function $6(Y,Z,X,_){function G(O){if(Y.operation.open){let L=Y.on.operationClose.subscribe(`state subscription ${X}`,()=>{L(),_(O)})}else _(O)}let W=m0(Y,Z);Y.logger.info("\uD83D\uDC40",W.type,W.key,`Adding subscription "${X}"`);let H=W.type==="writable_pure_selector"||W.type==="readonly_pure_selector",J=null,Q=G;if(H)J=P7(Y,W),Q=(O)=>{if(J)J.length=0,J.push(...P7(Y,W));G(O)};let $=W.subject.subscribe(X,Q);return()=>{if(Y.logger.info("\uD83D\uDE48",W.type,W.key,`Removing subscription "${X}"`),$(),J)for(let O of J)O()}}var tF=(Y,Z,X,_)=>{let G=m0(Y,Z);Y.logger.info("\uD83D\uDC40","timeline",Z.key,`Adding subscription "${X}"`);let W=G.subject.subscribe(X,_);return()=>{Y.logger.info("\uD83D\uDE48","timeline",Z.key,`Removing subscription "${X}" from timeline`),W()}};var d5=class{initializeState(Y,Z){let X=`*${Y.key}`;Z.atoms.delete(X),Z.valueMap.delete(X);let _=Y.family?{key:`*${Y.family.key}`,subKey:Y.family.subKey}:void 0,G=k4(Z,{key:X,default:null},_);if(Z.parent?.valueMap.has(X)){let W=Z.parent.valueMap.get(X);Z.valueMap.set(X,W)}return G}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(Y,Z,X){let _=`tracker:${X.config.name}:${o0(X)?X.transactionMeta.update.key:"main"}:${Y.key}`,G=k1(X,Y);this.unsubscribeFromInnerValue=G.subscribe(_,(W)=>{N1(X,Z,W)}),this.unsubscribeFromState=$6(X,Y,_,(W)=>{if(W.newValue!==W.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=W.newValue.subscribe(_,(H)=>{N1(X,Z,H)})})}updateCore(Y,Z,X){let _=`tracker:${X.config.name}:${o0(X)?X.transactionMeta.update.key:"main"}:${Y.key}`;$6(X,Z,_,({newValue:G,oldValue:W})=>{let H=X.timelineTopics.getRelatedKey(Z.key);if(H){if(X.timelines.get(H)?.timeTraveling){let $=tF(X,{key:H,type:"timeline"},_,(z)=>{$(),N1(X,Y,(O)=>{if(z==="redo"&&G)O.do(G);else if(z==="undo"&&W)O.undo(W);return O})});return}}let J=X.on.operationClose.subscribe(_,()=>{J();let Q=k1(X,Y),$=G===null?-1:Q.getUpdateNumber(G),z=$-Q.cacheUpdateNumber;if(G&&z===1)N1(X,Y,(O)=>(O.do(G),O));else X.logger.info("\u274C","mutable_atom",Y.key,`could not be updated. Expected update number ${Q.cacheUpdateNumber+1}, but got ${$}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(Y,Z){this.mutableState=Y;let X=i(Z);this.latestUpdateState=this.initializeState(Y,X),this.observeCore(Y,this.latestUpdateState,X),this.updateCore(Y,this.latestUpdateState,X),X.trackers.set(Y.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(Y.key)}}};function c5(Y,Z,X){Y.logger.info("\uD83D\uDD28","atom",Z.key,`creating in store "${Y.config.name}"`);let _=i(Y),{key:G,default:W}=Z,H=_.atoms.get(G),J="mutable_atom";if(H&&H.type===J)return Y.logger.error("\u274C",J,G,"Tried to create atom, but it already exists in the store."),W4(H);let Q=new H0,$={...Z,type:J,install:(L)=>{return L.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${L.config.name}"`),c5(L,Z,X)},subject:Q};if(X)$.family=X;let z=W();_.atoms.set($.key,$),m7(Y,G),o1(_,G,z,Q);let O=W4($);if(Z.effects){let L=0,V=[];for(let R of Z.effects){let A=R({setSelf:(f)=>{N1(Y,O,f)},onSet:(f)=>$6(Y,O,`effect[${L}]`,f)});if(A)V.push(A);++L}$.cleanup=()=>{for(let R of V)R()}}if(new d5(O,Y),!X)D7(O,Z,Y);return O}var eF=class{trackers=new Map;latestUpdateAtoms;mutableAtoms;constructor(Y,Z){let X=z6(Z,{key:`*${Y.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=m0(Z,X),this.mutableAtoms=Y,this.mutableAtoms.subject.subscribe(`store=${Z.config.name}::tracker-atom-family`,(_)=>{let{type:G,token:W}=_;if(W.family){let H=E1(W.family.subKey);switch(G){case"state_creation":this.trackers.set(H,new d5(W,Z));break;case"state_disposal":{let J=this.trackers.get(H);if(J)J[Symbol.dispose](),this.trackers.delete(H)}break}}})}};function l5(Y,Z,X){let _={key:Z.key,type:"mutable_atom_family"},G=Y.families.get(Z.key);if(G)Y.logger.error("\u2757","mutable_atom_family",Z.key,`Overwriting an existing ${f4(G)} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let W=new H0,J=Object.assign((Q)=>{let $=z0(Q),z={key:Z.key,subKey:$},O=`${Z.key}(${$})`,L=i(Y),V={key:O,default:()=>Z.default(Q),toJson:Z.toJson,fromJson:Z.fromJson,mutable:!0};if(Z.effects)V.effects=Z.effects(Q);let R=c5(L,V,z);return W.next({type:"state_creation",token:R}),R},_,{subject:W,install:(Q)=>l5(Q,Z),toJson:Z.toJson,fromJson:Z.fromJson,internalRoles:X});return Y.families.set(Z.key,J),V7(Y,J,Z),new eF(J,Y),_}var S7=(Y,Z)=>{let X=i(Z),_=`${Y.key}:JSON`;return X.families.get(_)},b4=(Y,Z)=>{if(Z.family){let _=i(Y),W={key:`${Z.family.key}:JSON`,type:"writable_pure_selector_family"},H=m0(_,W),J=JSON.parse(Z.family.subKey);return Q0(Y,H,J)}return{type:"writable_pure_selector",key:`${Z.key}:JSON`}};var i5=(Y)=>{let X={type:"atom",key:`*${Y.key}`};if(Y.family)X.family={key:`*${Y.family.key}`,subKey:Y.family.subKey};return X};function YU(Y){return typeof Y==="object"&&Y!==null&&"do"in Y&&"undo"in Y&&"subscribe"in Y}function f5(Y,Z,X){let _=X.valueMap.get(Z.key),G=Y.valueMap.get(Z.key);if(_!==G)return G;if(_===void 0)return Z.default();X.logger.info("\uD83D\uDCC3","atom",Z.key,"copying");let W=Z.toJson(_),H=Z.fromJson(W);return Y.valueMap.set(Z.key,H),new d5(Z,X),H}function o1(Y,Z,X,_){let G=Y.valueMap.get(Z);if(G instanceof P5){let W=G;if(X instanceof Promise)return W;return Y.valueMap.set(Z,X),X}if(X instanceof Promise){let W=new P5(X);return Y.valueMap.set(Z,W),W.then((H)=>{if(Y.valueMap.get(Z)===W){o1(Y,Z,H,_);let Q=Y.atoms.get(Z);if(Q)S5(Y,Q),x5(Y,Q),v5(Y);else{let $=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if($)S5(Y,$),KF(Y,$),v5(Y)}_.next({newValue:H,oldValue:W})}}).catch((H)=>{Y.logger.error("\uD83D\uDCA5","state",Z,"rejected:",H)}),W}return Y.valueMap.set(Z,X),X}var ZU=(Y,Z)=>{let X=Z.valueMap.get(Y.key);if(Y.type==="mutable_atom"&&o0(Z)){let{parent:_}=Z;X=f5(Z,Y,_)}return X},p7=(Y,Z)=>{let X=Z.valueMap.get(Y);if(X instanceof P5){let _=X,G=Z.writableSelectors.get(Y)??Z.readonlySelectors.get(Y);if(G)_.use(G.get());return}if(Z.operation.open)Z.operation.prev.set(Y,X);Z.valueMap.delete(Y),Z.logger.info("\uD83D\uDDD1","state",Y,"evicted")},XU=(Y,Z)=>{return i(Y).atomsThatAreDefault.has(Z)},m7=(Y,Z)=>{let X=i(Y);X.atomsThatAreDefault=new Set(X.atomsThatAreDefault).add(Z)},_U=(Y,Z)=>{let X=i(Y);X.atomsThatAreDefault=new Set(i(Y).atomsThatAreDefault),X.atomsThatAreDefault.delete(Z)};function k4(Y,Z,X){let{key:G,default:W}=Z;Y.logger.info("\uD83D\uDD28","atom",G,`creating in store "${Y.config.name}"`);let H=i(Y),J=H.atoms.get(G);if(J&&J.type==="atom")return Y.logger.error("\u274C","atom",G,"Tried to create atom, but it already exists in the store."),W4(J);let Q=new H0,$={...Z,type:"atom",install:(L)=>{return L.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${L.config.name}"`),k4(L,Z,X)},subject:Q};if(X)$.family=X;let z=W;if(W instanceof Function)z=W();H.atoms.set(G,$),m7(Y,G),o1(H,G,z,Q);let O=W4($);if(Z.effects){let L=0,V=[];for(let R of Z.effects){let A=R({setSelf:(f)=>{N1(Y,O,f)},onSet:(f)=>$6(Y,O,`effect[${L}]`,f)});if(A)V.push(A);++L}$.cleanup=()=>{for(let R of V)R()}}return O}function C7(Y,Z){if("mutable"in Z){let G=c5(Y,Z,void 0);return Y.on.atomCreation.next(G),G}let _=k4(Y,Z,void 0);return Y.on.atomCreation.next(_),_}function u7(Y,Z){let X=i(Y),{key:_,family:G}=Z,W=m0(X,Z);if(!G)Y.logger.error("\u274C","atom",_,"Standalone atoms cannot be disposed.");else{W.cleanup?.();let H=Y.valueMap.get(W.key),J=m0(Y,{key:G.key,type:"atom_family"}),Q={type:"state_disposal",subType:"atom",token:Z,value:H};J.subject.next(Q);let $=o0(X);if(X.atoms.delete(_),X.valueMap.delete(_),X.selectorAtoms.delete(_),X.atomsThatAreDefault.delete(_),Y.timelineTopics.delete(_),Z.type==="mutable_atom"){let z=i5(Z);u7(Y,z),Y.trackers.delete(_)}if(Y.logger.info("\uD83D\uDD25","atom",_,"deleted"),$&&X.transactionMeta.phase==="building"){let z=X.transactionMeta.update.updates.at(-1);if(!(z?.type==="molecule_disposal"&&z.values.some(([V])=>V===W.family?.key)))X.transactionMeta.update.updates.push(Q)}else Y.on.atomDisposal.next(Z)}}var j5=class{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(Y,Z){let X=this.toolkit;this.toolkit=Y,Z(this),this.toolkit=X}store;realm;[Symbol.dispose](){}constructor(Y,Z,X=x0.STORE){this.store=X,this.realm=new w7(X),this.options=Y,this.defaultContent=Z,this.store.miscResources.set(`join:${Y.key}`,this),this.realm.allocate("root",Y.key),this.toolkit={get:(...N)=>k1(X,...N),set:(...N)=>{N1(X,...N)},find:(...N)=>Q0(X,...N),json:(N)=>b4(X,N)};let _=Y.between[0],G=Y.between[1],W=l5(X,{key:`${Y.key}/relatedKeys`,default:()=>new L1,mutable:!0,fromJson:(N)=>L1.fromJSON(N),toJson:(N)=>N.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:W};let H=({get:N},I)=>N(W,I),J=({set:N},I,q)=>{if(!this.store.molecules.has(z0(I)))this.realm.allocate(Y.key,I);N(W,I,(K)=>K.add(q)),N(W,q,(K)=>K.add(I))},Q=({set:N},I,q)=>{N(W,I,(K)=>{return K.delete(q),K}),N(W,q,(K)=>{return K.delete(I),K})},$=(N,I,q)=>{let{find:K,get:p,set:s}=N,T=K(W,I),t=p(T);for(let m of t){if(q.includes(m))continue;s(W,m,(U0)=>{return U0.delete(I),U0})}s(T,(m)=>{return m.transaction((e)=>{e.clear();for(let U0 of q){let f0=H(N,U0),J1=f0.has(I);if(this.relations.cardinality==="1:n"){let s1=[];for(let C of f0){if(C===I)continue;let u=H(N,C);if(u.delete(U0),u.size===0)s1.push(C)}if(!J1&&f0.size>0)f0.clear();for(let C of s1){let u=[U0,C].sort(),G0=`"${u[0]}:${u[1]}"`;this.molecules.delete(G0)}}if(!J1)f0.add(I);e.add(U0)}return!0}),m})},z=(N,I,q)=>{let{set:K}=N;K(W,I,(p)=>{return p.transaction((s)=>{for(let T of q)s.add(T);return!0}),p});for(let p of q)K(W,p,(s)=>{return s.add(I),s});return!0},O=(N,I,q)=>{let K=H(N,I);return q?K.has(q):K.size>0},L={getRelatedKeys:(N)=>H(this.toolkit,N),addRelation:(N,I)=>{this.store.moleculeJoins.set(N,Y.key),this.store.moleculeJoins.set(I,Y.key),J(this.toolkit,N,I)},deleteRelation:(N,I)=>{Q(this.toolkit,N,I)},replaceRelationsSafely:(N,I)=>{$(this.toolkit,N,I)},replaceRelationsUnsafely:(N,I)=>{z(this.toolkit,N,I)},has:(N,I)=>O(this.toolkit,N,I)},V,R;if(Z){R=z6(X,{key:`${Y.key}/content`,default:Z},["join","content"]);let N=({get:K},p)=>K(R,p),I=({set:K},p,s)=>{K(R,p,s)};V=Object.assign(L,{getContent:(K)=>{return N(this.toolkit,K)},setContent:(K,p)=>{I(this.toolkit,K,p)},deleteContent:(K)=>{this.realm.deallocate(K)}})}else V=L;let A=new G1(Y,{externalStore:V,isAType:Y.isAType,isBType:Y.isBType,makeContentKey:(...N)=>{let[I,q]=N,K=N.sort(),p=`${K[0]}:${K[1]}`,s=X.molecules.get(z0(I)),T=X.molecules.get(z0(q));if(!s)this.realm.allocate(Y.key,I);if(!T)this.realm.allocate(Y.key,q);return this.realm.allocate(I,p,"all"),this.realm.claim(q,p),this.store.moleculeJoins.set(p,Y.key),p}}),f=()=>h4(X,{key:`${Y.key}/singleRelatedKey`,get:(N)=>({get:I})=>{let q=I(W,N);for(let K of q)return K;return null}},["join","keys"]),b=()=>{return h4(X,{key:`${Y.key}/multipleRelatedKeys`,get:(N)=>({get:I})=>{let q=S7(W,X);return I(q,N).members}},["join","keys"])},k=()=>h4(X,{key:`${Y.key}/singleRelatedEntry`,get:(N)=>({get:I})=>{let q=I(W,N);for(let K of q){let p=A.isAType?.(N)?N:void 0,s=p===void 0?N:void 0;p??=K,s??=K;let T=A.makeContentKey(p,s),t=I(R,T);return[K,t]}return null}},["join","entries"]),g=()=>h4(X,{key:`${Y.key}/multipleRelatedEntries`,get:(N)=>({get:I})=>{let q=S7(W,X);return I(q,N).members.map((p)=>{let s=A.isAType?.(N)?N:void 0,T=s===void 0?N:void 0;s??=p,T??=p;let t=A.makeContentKey(s,T),m=I(R,t);return[p,m]})}},["join","entries"]);switch(Y.cardinality){case"1:1":{let N=f(),I=`${_}KeyOf${B0(G)}`,q=`${G}KeyOf${B0(_)}`,K={[I]:N,[q]:N},p;if(Z){let s=k(),T=`${_}EntryOf${B0(G)}`,t=`${G}EntryOf${B0(_)}`,m={[T]:s,[t]:s};p=Object.assign(K,m)}else p=K;this.relations=A,this.states=p;break}case"1:n":{let N=f(),I=b(),q=`${_}KeyOf${B0(G)}`,K=`${G}KeysOf${B0(_)}`,p={[q]:N,[K]:I},s;if(Z){let T=k(),t=g(),m=`${_}EntryOf${B0(G)}`,e=`${G}EntriesOf${B0(_)}`,U0={[m]:T,[e]:t};s=Object.assign(p,U0)}else s=p;this.relations=A,this.states=s;break}case"n:n":{let N=b(),I=`${_}KeysOf${B0(G)}`,q=`${G}KeysOf${B0(_)}`,K={[I]:N,[q]:N},p;if(Z){let s=g(),T=`${_}EntriesOf${B0(G)}`,t=`${G}EntriesOf${B0(_)}`,m={[T]:s,[t]:s};p=Object.assign(K,m)}else p=K;this.relations=A,this.states=p}}}};function o5(Y,Z){let X=Z.joins.get(Y.key);if(X===void 0){let G=x0.STORE.joins.get(Y.key);if(G===void 0)throw new Error(`Join "${Y.key}" not found in store "${Z.config.name}"`);X=new j5(G.options,G.defaultContent,Z),Z.joins.set(Y.key,X)}return X}function J6(Y,Z,X){let _=o5(Y,X),G=i(X);if(o0(G)){let{toolkit:W}=G.transactionMeta;_.transact(W,({relations:H})=>{Z(H)})}else Z(_.relations)}function K7(Y,Z,X){let _=o5(Y,X),G;switch(Y.cardinality){case"1:1":{let W=`${Y.a}KeyOf${B0(Y.b)}`,H=`${Y.b}KeyOf${B0(Y.a)}`;G={get[W](){let Q=_.states[W];return Q0(X,Q,Z)},get[H](){let Q=_.states[H];return Q0(X,Q,Z)}};let J=`${Y.a}EntryOf${B0(Y.b)}`;if(J in _.states){let Q=`${Y.b}EntryOf${B0(Y.a)}`;Object.assign(G,{get[J](){let $=_.states[J];return Q0(X,$,Z)},get[Q](){let $=_.states[Q];return Q0(X,$,Z)}})}break}case"1:n":{let W=`${Y.a}KeyOf${B0(Y.b)}`,H=`${Y.b}KeysOf${B0(Y.a)}`;G={get[W](){let Q=_.states[W];return Q0(X,Q,Z)},get[H](){let Q=_.states[H];return Q0(X,Q,Z)}};let J=`${Y.a}EntryOf${B0(Y.b)}`;if(J in _.states){let Q=`${Y.b}EntriesOf${B0(Y.a)}`;Object.assign(G,{get[J](){let $=_.states[J];return Q0(X,$,Z)},get[Q](){let $=_.states[Q];return Q0(X,$,Z)}})}break}case"n:n":{let W=`${Y.a}KeysOf${B0(Y.b)}`,H=`${Y.b}KeysOf${B0(Y.a)}`;G={get[W](){let Q=_.states[W];return Q0(X,Q,Z)},get[H](){let Q=_.states[H];return Q0(X,Q,Z)}};let J=`${Y.a}EntriesOf${B0(Y.b)}`;if(J in _.states){let Q=`${Y.b}EntriesOf${B0(Y.a)}`;Object.assign(G,{get[J](){let $=_.states[J];return Q0(X,$,Z)},get[Q](){let $=_.states[Q];return Q0(X,$,Z)}})}}}return G}function q7(Y,Z){return o5(Y,Z).core.relatedKeysAtoms}function M8(Y){return Y.startsWith("\uD83D\uDD0D ")}var GU=(Y)=>{let Z=k4(Y,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let X=new Map;for(let[_,G]of Y.atoms){if(M8(_))continue;let W=W4(G);if(G.family){let H=X.get(G.family.key);if(!H||!("familyMembers"in H))H={key:G.family.key,familyMembers:new Map},X.set(G.family.key,H);H.familyMembers.set(G.family.subKey,W)}else X.set(_,W)}return X},effects:[({setSelf:X})=>{Y.on.atomCreation.subscribe("introspection",(_)=>{if(M8(_.key))return;X((G)=>{if(_.family){let{key:W,subKey:H}=_.family,J=G.get(W);if(J===void 0||!("familyMembers"in J))J={key:W,familyMembers:new Map},G.set(W,J);J.familyMembers.set(H,_)}else G.set(_.key,_);return G})}),Y.on.atomDisposal.subscribe("introspection",(_)=>{X((G)=>{if(_.family){let{key:W,subKey:H}=_.family,J=G.get(W);if(J&&"familyMembers"in J){if(J.familyMembers.delete(H),J.familyMembers.size===0)G.delete(W)}}else G.delete(_.key);return G})})}]},void 0);return O8(Y,{key:"\uD83D\uDD0D Atom Token Index",get:({get:X})=>X(Z)})},WU=(Y)=>{let Z=k4(Y,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let X=new Map;for(let _ of[Y.readonlySelectors,Y.writableSelectors])for(let[G,W]of _){if(M8(G))continue;let H=W4(W);if(W.family){let J=X.get(W.family.key);if(!J||!("familyMembers"in J))J={key:W.family.key,familyMembers:new Map},X.set(W.family.key,J);J.familyMembers.set(W.family.subKey,H)}else X.set(G,H)}return X},effects:[({setSelf:X})=>{Y.on.selectorCreation.subscribe("introspection",(_)=>{if(M8(_.key))return;X((G)=>{if(_.family){let{key:W,subKey:H}=_.family,J=G.get(W);if(J===void 0||!("familyMembers"in J))J={key:W,familyMembers:new Map},G.set(W,J);J.familyMembers.set(H,_)}else G.set(_.key,_);return G})}),Y.on.selectorDisposal.subscribe("introspection",(_)=>{X((G)=>{if(_.family){let{key:W,subKey:H}=_.family,J=G.get(W);if(J&&"familyMembers"in J){if(J.familyMembers.delete(H),J.familyMembers.size===0)G.delete(W)}}else G.delete(_.key);return G})})}]},void 0);return O8(Y,{key:"\uD83D\uDD0D Selector Token Index",get:({get:X})=>X(Z)})};var n5=class{supported;constructor(Y){this.supported=Y}refine(Y){for(let[Z,X]of Object.entries(this.supported))try{if(X(Y)===!0&&X!==Boolean)return{type:Z,data:Y}}catch(_){try{if(Y instanceof X)return{type:Z,data:Y}}catch(G){}}return null}},c7=new n5({number:(Y)=>typeof Y==="number",string:(Y)=>typeof Y==="string",boolean:(Y)=>typeof Y==="boolean",null:(Y)=>Y===null});function l7(Y){if(!Y)return!1;return Object.getPrototypeOf(Y)===Object.prototype}var i7=new n5({object:l7,array:(Y)=>Array.isArray(Y)}),HU=new n5({...c7.supported,...i7.supported}),VY=(Y)=>{if(Y===void 0)return"undefined";let Z=HU.refine(Y);if(Z)return Z.type;return Object.getPrototypeOf(Y).constructor.name};var iB=class Y{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Z=x0.STORE){this.store=Z,this.atomIndex=GU(this.store),this.selectorIndex=WU(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(Z=Y.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let X=T5(this.atomIndex),_=T5(this.selectorIndex),G=[...X.values()].filter((Q)=>("familyMembers"in Q)),W=[..._.values()].filter((Q)=>("familyMembers"in Q)),H=performance.now(),J=[];if(Z.atomFamilies)for(let Q of G){let $=Q.familyMembers.values();for(let z of $){let L=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,V=H-L;J.push([z,V])}}if(Z.selectorFamilies)for(let Q of W){let $=Q.familyMembers.values();for(let z of $){let L=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,V=H-L;J.push([z,V])}}return J}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},d7=(Y,Z)=>{let X=(_,G)=>{let H=((Q,$)=>{let z=Z(Q,$);if(z)return z;return null})(_,G);if(H?.jobComplete??H?.pathComplete)return H;let J=Array.isArray(G)?G.map((Q,$)=>[$,Q]):l7(G)?Object.entries(G):[];for(let[Q,$]of J){let z=X([..._,Q],$);if(z?.jobComplete)return z}return{}};X([],Y)};function JU(Y,Z){return{summary:`${Y<Z?"+":"-"}${Math.abs(Y-Z)} (${Y} \u2192 ${Z})`}}function $U(Y,Z){return{summary:`${Y.length<Z.length?"+":"-"}${Math.abs(Y.length-Z.length)} ("${Y}" \u2192 "${Z}")`}}function QU(Y,Z){return{summary:`${Y} \u2192 ${Z}`}}function o7(Y,Z,X){let _="",G=[],W=[],H=[];return d7(Y,(J,Q)=>{let $;for($ of J){let z=Z[$];if(z===void 0)W.push([$,JSON.stringify(Q)]);else{let O=X(Q,z);if(O.summary!=="No Change")H.push([$,O])}}}),d7(Z,(J,Q)=>{let $;for($ of J)if(Y[$]===void 0)G.push([$,JSON.stringify(Q)])}),_=`\uFF5E${H.length} \uFF0B${G.length} \uFF0D${W.length}`,{summary:_,added:G,removed:W,changed:H}}function zU(Y,Z,X){return o7(Y,Z,X)}var FU=class{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(Y,Z,X){this.leafRefinery=Y,this.treeRefinery=Z,this.leafDiffers={},this.treeDiffers={};for(let _ of Object.keys(Y.supported)){let G=X[_];this.leafDiffers[_]=G}for(let _ of Object.keys(Z.supported)){let G=X[_];this.treeDiffers[_]=G}}diff(Y,Z){if(Y===Z)return{summary:"No Change"};let X=this.leafRefinery.refine(Y)??this.treeRefinery.refine(Y),_=this.leafRefinery.refine(Z)??this.treeRefinery.refine(Z);if(X!==null&&_!==null){if(X.type===_.type){if(X.type in this.leafDiffers)return this.leafDiffers[X.type](X.data,_.data);if(X.type in this.treeDiffers)return this.treeDiffers[X.type](X.data,_.data,(J,Q)=>this.diff(J,Q))}}let G=VY(Y),W=VY(Z);if(G===W)return{summary:`${G} \u2192 ${W}`};return{summary:`Type change: ${G} \u2192 ${W}`}}},oB=new FU(c7,i7,{number:JU,string:$U,boolean:QU,null:()=>({summary:"No Change"}),object:o7,array:zU});var UU=class extends Map{set(Y,Z){if(this.has(Y))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:Y,value:Z}),this;return super.set(Y,Z)}clear(){throw new Error("Cannot clear an InvariantMap")}},eB=class Y{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Z){this.key=Z}static existing=new UU;static create(Z,X){let _=new Y(Z),{type:G,globals:W,actions:H,perspectives:J}=X(_),Q={type:G,key:Z,globals:W,actions:H,perspectives:J};return Y.existing.set(Z,Q),Q}add(...Z){switch(Z[0].type){case"atom":case"mutable_atom":this.globals.push(...Z);break;case"transaction":this.actions.push(...Z);break;case"atom_family":case"mutable_atom_family":{let[_,G]=Z;this.perspectives.push({type:"realtime_perspective",resourceAtoms:_,viewAtoms:G})}break}return this}};var YT=E8({key:"usersInRoomIndex",mutable:!0,default:()=>new L1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>L1.fromJSON(Y)}),r5=E8({key:"roomIndex",default:()=>new L1,mutable:!0,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>L1.fromJSON(Y)}),OU={enteredAtEpoch:0},F6=OY({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(Y)=>typeof Y==="string",isBType:(Y)=>typeof Y==="string"},OU),ZT=EY({key:"usersInMyRoomView",get:(Y)=>({find:Z})=>{let X=M7(F6);return[Z(X,Y)]}});import{spawn as EU}from"child_process";var s5=class{listeners;globalListeners;handleEvent(Y,...Z){for(let _ of this.globalListeners)_(Y,...Z);let X=this.listeners.get(Y);if(X)for(let _ of X)_(...Z)}id="no_id_retrieved";emit;constructor(Y){this.emit=Y,this.listeners=new Map,this.globalListeners=new Set}on(Y,Z){let X=this.listeners.get(Y);if(X)X.add(Z);else this.listeners.set(Y,new Set([Z]));return this}onAny(Y){return this.globalListeners.add(Y),this}off(Y,Z){let X=this.listeners.get(Y);if(X)if(Z)X.delete(Z);else this.listeners.delete(Y);return this}offAny(Y){return this.globalListeners.delete(Y),this}},LU=class extends s5{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(Y){if(Array.isArray(Y)){let[Z,...X]=Y;switch(Z){case"i":this.logger.info(...X);break;case"w":this.logger.warn(...X);break;case"e":this.logger.error(...X);break;default:return}}}constructor(Y,Z,X){super((_,...G)=>{let W=JSON.stringify([_,...G])+"\x03",H=(J)=>{if(J.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",H)};return this.process.stdin.once("error",H),this.process.stdin.write(W),this});if(this.process=Y,this.key=Z,this.logger=X??{info:(..._)=>{console.info(this.id,this.key,..._)},warn:(..._)=>{console.warn(this.id,this.key,..._)},error:(..._)=>{console.error(this.id,this.key,..._)}},this.process.stdout.on("data",(_)=>{let G=_.toString();if(G==="ALIVE")return;this.unprocessedEvents.push(...G.split("\x03"));let W=this.unprocessedEvents.shift();this.incompleteData+=W??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let H=E1(this.incompleteData);this.handleEvent(...H);while(this.unprocessedEvents.length>0){let J=this.unprocessedEvents.shift();if(J){if(this.unprocessedEvents.length===0)this.incompleteData=J;H=E1(J),this.handleEvent(...H)}}this.incompleteData=""}catch(H){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(H)}}),this.process.stderr.on("data",(_)=>{let G=_.toString();this.unprocessedLogs.push(...G.split("\x03"));let W=this.unprocessedLogs.shift();this.incompleteLog+=W??"";try{let H=E1(this.incompleteLog);this.handleLog(H);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)H=E1(this.incompleteLog),this.handleLog(H)}catch(H){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(H),console.error("\u274C\u274C\u274C\uFE0F")}}),Y.pid)this.id=Y.pid.toString()}},DU=class extends s5{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(Y){super((...Z)=>{return this.out.next(Z),this});this.id=Y,this.in=new H0,this.out=new H0,this.in.subscribe("socket",(Z)=>{this.handleEvent(...Z)})}dispose(){for(let Y of this.disposalFunctions)Y()}},n7=class extends s5{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...Y){this.process.stderr.write(z0(Y.map((Z)=>Z instanceof L1?`{ ${Z.toJSON().members.join(" | ")} }`:Z))+"\x03")}logger={info:(...Y)=>{this.log("i",...Y)},warn:(...Y)=>{this.log("w",...Y)},error:(...Y)=>{this.log("e",...Y)}};constructor(){super((Y,...Z)=>{let X=JSON.stringify([Y,...Z]);return this.process.stdout.write(X+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(Y)=>{let Z=Y.toString();this.unprocessedEvents.push(...Z.split("\x03"));let X=this.unprocessedEvents.shift();this.incompleteData+=X??"";try{let _=E1(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",_),this.handleEvent(..._);while(this.unprocessedEvents.length>0){let G=this.unprocessedEvents.shift();if(G){if(this.unprocessedEvents.length===0)this.incompleteData=G;let W=E1(G);this.handleEvent(...W)}}this.incompleteData=""}catch(_){if(_ instanceof Error)this.logger.error("\u2757",_.message,_.cause,_.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(Y)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${Y}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(Y)=>{this.logger.info("\uD83D\uDC64","user",Y,"joined");let Z=new DU(`user:${Y}`);this.relays.set(Y,Z),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let X of this.relayServices){let _=X(Z);if(_)Z.disposalFunctions.push(_)}this.on(`user:${Y}`,(...X)=>{Z.in.next(X)}),Z.out.subscribe("socket",(X)=>{this.emit(...X)})}),this.on("user-leaves",(Y)=>{let Z=this.relays.get(Y);if(this.off(`relay:${Y}`),Z)Z.dispose(),this.relays.delete(Y)}),process.stdout.write("ALIVE")}relay(Y){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(Y)}},r7=G6({key:"roomArguments",default:["echo",["Hello World!"]]}),VU=EY({key:"room",get:(Y)=>async({get:Z,find:X})=>{let _=X(r7,Y),G=Z(_),[W,H]=G,J=await new Promise((Q)=>{let $=EU(W,H,{env:process.env}),z=(O)=>{if(O.toString()==="ALIVE")$.stdout.off("data",z),Q($)};$.stdout.on("data",z)});return new LU(J,Y)}}),FT=W6({key:"createRoom",do:({get:Y,set:Z,find:X},_,G,W)=>{let H=W?[G,W]:[G],J=X(r7,_);Z(J,H),Z(r5,(z)=>z.add(_));let Q=X(VU,_);return Y(Q)}}),UT=W6({key:"joinRoom",do:(Y,Z,X,_)=>{let G={enteredAtEpoch:_};return J6(F6,(W)=>{W.set({room:Z,user:X},G)},Y.env().store),G}}),OT=W6({key:"leaveRoom",do:(Y,Z,X)=>{J6(F6,(_)=>{_.delete({room:Z,user:X})},Y.env().store)}}),ET=W6({key:"destroyRoom",do:(Y,Z)=>{J6(F6,(X)=>{X.delete({room:Z})},Y.env().store),Y.set(r5,(X)=>(X.delete(Z),X))}});var LT=G6({key:"redactor",default:{occlude:(Y)=>Y}}),DT=G6({key:"unacknowledgedUpdates",default:()=>[]}),VT=G6({key:"sockets",default:null}),MT=E8({key:"socketsIndex",mutable:!0,default:()=>new L1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>L1.fromJSON(Y)}),AT=E8({key:"usersIndex",mutable:!0,default:()=>new L1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>L1.fromJSON(Y)}),wT=OY({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(Y)=>Y.startsWith("user::"),isBType:(Y)=>Y.startsWith("socket::")});var{file:KH,serve:xO}=globalThis.Bun;import{readFileSync as t7}from"fs";import{createServer as NU}from"http";import{createServer as RU}from"https";import{resolve as t5}from"path";function s7(Y,Z){if(Y instanceof Promise)throw new Error(Z)}function MU(Y,Z){let X={},_=[];for(let G in Y){let W=Y[G]["~standard"].validate(Z[G]);if(s7(W,`Validation must be synchronous, but ${G} returned a Promise.`),W.issues){_.push(...W.issues.map((H)=>({...H,message:H.message,path:[G,...H.path??[]]})));continue}X[G]=W.value}if(_.length)return{issues:_};return{value:X}}function a5(Y){let Z=Y.runtimeEnvStrict??Y.runtimeEnv??process.env;if(Y.emptyStringAsUndefined??!1){for(let[k,g]of Object.entries(Z))if(g==="")delete Z[k]}if(!!Y.skipValidation)return Z;let G=typeof Y.client==="object"?Y.client:{},W=typeof Y.server==="object"?Y.server:{},H=typeof Y.shared==="object"?Y.shared:{},J=Y.isServer??(typeof window==="undefined"||("Deno"in window)),Q=J?{...W,...H,...G}:{...G,...H},$=Y.createFinalSchema?.(Q,J)["~standard"].validate(Z)??MU(Q,Z);s7($,"Validation must be synchronous");let z=Y.onValidationError??((k)=>{throw console.error("\u274C Invalid environment variables:",k),new Error("Invalid environment variables")}),O=Y.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if($.issues)return z($.issues);let L=(k)=>{if(!Y.clientPrefix)return!0;return!k.startsWith(Y.clientPrefix)&&!(k in H)},V=(k)=>{return J||!L(k)},R=(k)=>{return k==="__esModule"||k==="$$typeof"},A=(Y.extends??[]).reduce((k,g)=>{return Object.assign(k,g)},{}),f=Object.assign(A,$.value);return new Proxy(f,{get(k,g){if(typeof g!=="string")return;if(R(g))return;if(!V(g))return O(g);return Reflect.get(k,g)}})}var AU="__vite_start_time"in globalThis,wU=typeof window!=="undefined",ST="vitest"in globalThis,H4=O1("string"),a7=O1('"true" | "false" | undefined'),g1=a5({isServer:!AU&&!wU,server:{CI:O1("string | undefined").pipe(Boolean),POSTGRES_USER:H4,POSTGRES_PASSWORD:H4,POSTGRES_DATABASE:H4,POSTGRES_HOST:H4,POSTGRES_PORT:H4.pipe((Y)=>Number.parseInt(Y,10)),BACKEND_PORT:H4.pipe((Y)=>Number.parseInt(Y,10)),RUN_WORKERS_FROM_SOURCE:a7.pipe((Y)=>Y==="true"),FRONTEND_PORT:H4.pipe((Y)=>Number.parseInt(Y,10)),FRONTEND_ORIGINS:H4.pipe.try((Y)=>JSON.parse(Y),O1("string[]")),API_KEY_OPENAI:O1("string | undefined"),API_KEY_RESEND:O1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:H4,VITE_DEV_FRONTEND_HOST:O1("string | undefined"),VITE_DEV_HTTPS:a7.pipe((Y)=>Y==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var e7=t5(import.meta.dirname,"../dev"),MY=g1.VITE_DEV_HTTPS?{cert:t7(t5(e7,"./cert.pem"),"utf-8"),key:t7(t5(e7,"./key.pem"),"utf-8")}:void 0;function gT(Y){if(MY)return RU(MY,Y);return NU({},Y)}import CO from"path";var U=Symbol.for("drizzle:entityKind"),pT=Symbol.for("drizzle:hasOwnEntityKind");function M(Y,Z){if(!Y||typeof Y!=="object")return!1;if(Y instanceof Z)return!0;if(!Object.prototype.hasOwnProperty.call(Z,U))throw new Error(`Class "${Z.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let X=Object.getPrototypeOf(Y).constructor;if(X)while(X){if(U in X&&X[U]===Z[U])return!0;X=Object.getPrototypeOf(X)}return!1}class E0{constructor(Y,Z){this.table=Y,this.config=Z,this.name=Z.name,this.keyAsName=Z.keyAsName,this.notNull=Z.notNull,this.default=Z.default,this.defaultFn=Z.defaultFn,this.onUpdateFn=Z.onUpdateFn,this.hasDefault=Z.hasDefault,this.primary=Z.primaryKey,this.isUnique=Z.isUnique,this.uniqueName=Z.uniqueName,this.uniqueType=Z.uniqueType,this.dataType=Z.dataType,this.columnType=Z.columnType,this.generated=Z.generated,this.generatedIdentity=Z.generatedIdentity}static[U]="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 e5{static[U]="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 y1=Symbol.for("drizzle:Name");class YX{static[U]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(Y,Z){if(this.reference=()=>{let{name:X,columns:_,foreignColumns:G}=Y();return{name:X,columns:_,foreignTable:G[0].table,foreignColumns:G}},Z)this._onUpdate=Z.onUpdate,this._onDelete=Z.onDelete}onUpdate(Y){return this._onUpdate=Y===void 0?"no action":Y,this}onDelete(Y){return this._onDelete=Y===void 0?"no action":Y,this}build(Y){return new Y3(Y,this)}}class Y3{constructor(Y,Z){this.table=Y,this.reference=Z.reference,this.onUpdate=Z._onUpdate,this.onDelete=Z._onDelete}static[U]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:Y,columns:Z,foreignColumns:X}=this.reference(),_=Z.map((H)=>H.name),G=X.map((H)=>H.name),W=[this.table[y1],..._,X[0].table[y1],...G];return Y??`${W.join("_")}_fk`}}function AY(Y,...Z){return Y(...Z)}function Z3(Y,Z){return`${Y[y1]}_${Z.join("_")}_unique`}function X3(Y,Z,X){for(let _=Z;_<Y.length;_++){let G=Y[_];if(G==="\\"){_++;continue}if(G==='"')return[Y.slice(Z,_).replace(/\\/g,""),_+1];if(X)continue;if(G===","||G==="}")return[Y.slice(Z,_).replace(/\\/g,""),_]}return[Y.slice(Z).replace(/\\/g,""),Y.length]}function _3(Y,Z=0){let X=[],_=Z,G=!1;while(_<Y.length){let W=Y[_];if(W===","){if(G||_===Z)X.push("");G=!0,_++;continue}if(G=!1,W==="\\"){_+=2;continue}if(W==='"'){let[Q,$]=X3(Y,_+1,!0);X.push(Q),_=$;continue}if(W==="}")return[X,_+1];if(W==="{"){let[Q,$]=_3(Y,_+1);X.push(Q),_=$;continue}let[H,J]=X3(Y,_,!1);X.push(H),_=J}return[X,_]}function G3(Y){let[Z]=_3(Y,1);return Z}function ZX(Y){return`{${Y.map((Z)=>{if(Array.isArray(Z))return ZX(Z);if(typeof Z==="string")return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Z}`}).join(",")}}`}class h extends e5{foreignKeyConfigs=[];static[U]="PgColumnBuilder";array(Y){return new H3(this.config.name,this,Y)}references(Y,Z={}){return this.foreignKeyConfigs.push({ref:Y,actions:Z}),this}unique(Y,Z){return this.config.isUnique=!0,this.config.uniqueName=Y,this.config.uniqueType=Z?.nulls,this}generatedAlwaysAs(Y){return this.config.generated={as:Y,type:"always",mode:"stored"},this}buildForeignKeys(Y,Z){return this.foreignKeyConfigs.map(({ref:X,actions:_})=>{return AY((G,W)=>{let H=new YX(()=>{let J=G();return{columns:[Y],foreignColumns:[J]}});if(W.onUpdate)H.onUpdate(W.onUpdate);if(W.onDelete)H.onDelete(W.onDelete);return H.build(Z)},X,_)})}buildExtraConfigColumn(Y){return new W3(Y,this.config)}}class j extends E0{constructor(Y,Z){if(!Z.uniqueName)Z.uniqueName=Z3(Y,[Z.name]);super(Y,Z);this.table=Y}static[U]="PgColumn"}class W3 extends j{static[U]="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 U6{static[U]="IndexedColumn";constructor(Y,Z,X,_){this.name=Y,this.keyAsName=Z,this.type=X,this.indexConfig=_}name;keyAsName;type;indexConfig}class H3 extends h{static[U]="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 XX(Y,this.config,Z)}}class XX extends j{constructor(Y,Z,X,_){super(Y,Z);this.baseColumn=X,this.range=_,this.size=Z.size}size;static[U]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(Y){if(typeof Y==="string")Y=G3(Y);return Y.map((Z)=>this.baseColumn.mapFromDriverValue(Z))}mapToDriverValue(Y,Z=!1){let X=Y.map((_)=>_===null?null:M(this.baseColumn,XX)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Z)return X;return ZX(X)}}class J3 extends h{static[U]="PgEnumObjectColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumObjectColumn");this.config.enum=Z}build(Y){return new $3(Y,this.config)}}class $3 extends j{static[U]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}var wY=Symbol.for("drizzle:isPgEnum");function Q3(Y){return!!Y&&typeof Y==="function"&&wY in Y&&Y[wY]===!0}class z3 extends h{static[U]="PgEnumColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumColumn");this.config.enum=Z}build(Y){return new F3(Y,this.config)}}class F3 extends j{static[U]="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 O6(Y,Z){return Array.isArray(Z)?IU(Y,[...Z],void 0):BU(Y,Z,void 0)}function IU(Y,Z,X){let _=Object.assign((G)=>new z3(G??"",_),{enumName:Y,enumValues:Z,schema:X,[wY]:!0});return _}function BU(Y,Z,X){let _=Object.assign((G)=>new J3(G??"",_),{enumName:Y,enumValues:Object.values(Z),schema:X,[wY]:!0});return _}class P0{static[U]="Subquery";constructor(Y,Z,X,_=!1,G=[]){this._={brand:"Subquery",sql:Y,selectedFields:Z,alias:X,isWith:_,usedTables:G}}}class E6 extends P0{static[U]="WithSubquery"}var U3="0.44.3";var _X,GX,L0={startActiveSpan(Y,Z){if(!_X)return Z();if(!GX)GX=_X.trace.getTracer("drizzle-orm",U3);return AY((X,_)=>_.startActiveSpan(Y,(G)=>{try{return Z(G)}catch(W){throw G.setStatus({code:X.SpanStatusCode.ERROR,message:W instanceof Error?W.message:"Unknown error"}),W}finally{G.end()}}),_X,GX)}};var A0=Symbol.for("drizzle:ViewBaseConfig");var g4=Symbol.for("drizzle:Schema"),NY=Symbol.for("drizzle:Columns"),O3=Symbol.for("drizzle:ExtraConfigColumns"),WX=Symbol.for("drizzle:OriginalName"),HX=Symbol.for("drizzle:BaseName"),L6=Symbol.for("drizzle:IsAlias"),E3=Symbol.for("drizzle:ExtraConfigBuilder"),TU=Symbol.for("drizzle:IsDrizzleTable");class P{static[U]="Table";static Symbol={Name:y1,Schema:g4,OriginalName:WX,Columns:NY,ExtraConfigColumns:O3,BaseName:HX,IsAlias:L6,ExtraConfigBuilder:E3};[y1];[WX];[g4];[NY];[O3];[HX];[L6]=!1;[TU]=!0;[E3]=void 0;constructor(Y,Z,X){this[y1]=this[WX]=Y,this[g4]=Z,this[HX]=X}}function c0(Y){return Y[y1]}function y4(Y){return`${Y[g4]??"public"}.${Y[y1]}`}function JX(Y){return Y!==null&&Y!==void 0&&typeof Y.getSQL==="function"}function CU(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 u0{static[U]="StringChunk";value;constructor(Y){this.value=Array.isArray(Y)?Y:[Y]}getSQL(){return new x([this])}}class x{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[U]="SQL";decoder=D3;shouldInlineParams=!1;usedTables=[];append(Y){return this.queryChunks.push(...Y.queryChunks),this}toQuery(Y){return L0.startActiveSpan("drizzle.buildSQL",(Z)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,Y);return Z?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams(Y,Z){let X=Object.assign({},Z,{inlineParams:Z.inlineParams||this.shouldInlineParams,paramStartIndex:Z.paramStartIndex||{value:0}}),{casing:_,escapeName:G,escapeParam:W,prepareTyping:H,inlineParams:J,paramStartIndex:Q}=X;return CU(Y.map(($)=>{if(M($,u0))return{sql:$.value.join(""),params:[]};if(M($,RY))return{sql:G($.value),params:[]};if($===void 0)return{sql:"",params:[]};if(Array.isArray($)){let z=[new u0("(")];for(let[O,L]of $.entries())if(z.push(L),O<$.length-1)z.push(new u0(", "));return z.push(new u0(")")),this.buildQueryFromSourceParams(z,X)}if(M($,x))return this.buildQueryFromSourceParams($.queryChunks,{...X,inlineParams:J||$.shouldInlineParams});if(M($,P)){let z=$[P.Symbol.Schema],O=$[P.Symbol.Name];return{sql:z===void 0||$[L6]?G(O):G(z)+"."+G(O),params:[]}}if(M($,E0)){let z=_.getColumnCasing($);if(Z.invokeSource==="indexes")return{sql:G(z),params:[]};let O=$.table[P.Symbol.Schema];return{sql:$.table[L6]||O===void 0?G($.table[P.Symbol.Name])+"."+G(z):G(O)+"."+G($.table[P.Symbol.Name])+"."+G(z),params:[]}}if(M($,D1)){let z=$[A0].schema,O=$[A0].name;return{sql:z===void 0||$[A0].isAlias?G(O):G(z)+"."+G(O),params:[]}}if(M($,R1)){if(M($.value,R4))return{sql:W(Q.value++,$),params:[$],typings:["none"]};let z=$.value===null?null:$.encoder.mapToDriverValue($.value);if(M(z,x))return this.buildQueryFromSourceParams([z],X);if(J)return{sql:this.mapInlineParam(z,X),params:[]};let O=["none"];if(H)O=[H($.encoder)];return{sql:W(Q.value++,z),params:[z],typings:O}}if(M($,R4))return{sql:W(Q.value++,$),params:[$],typings:["none"]};if(M($,x.Aliased)&&$.fieldAlias!==void 0)return{sql:G($.fieldAlias),params:[]};if(M($,P0)){if($._.isWith)return{sql:G($._.alias),params:[]};return this.buildQueryFromSourceParams([new u0("("),$._.sql,new u0(") "),new RY($._.alias)],X)}if(Q3($)){if($.schema)return{sql:G($.schema)+"."+G($.enumName),params:[]};return{sql:G($.enumName),params:[]}}if(JX($)){if($.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([$.getSQL()],X);return this.buildQueryFromSourceParams([new u0("("),$.getSQL(),new u0(")")],X)}if(J)return{sql:this.mapInlineParam($,X),params:[]};return{sql:W(Q.value++,$),params:[$],typings:["none"]}}))}mapInlineParam(Y,{escapeString:Z}){if(Y===null)return"null";if(typeof Y==="number"||typeof Y==="boolean")return Y.toString();if(typeof Y==="string")return Z(Y);if(typeof Y==="object"){let X=Y.toString();if(X==="[object Object]")return Z(JSON.stringify(Y));return Z(X)}throw new Error("Unexpected param value: "+Y)}getSQL(){return this}as(Y){if(Y===void 0)return this;return new x.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 RY{constructor(Y){this.value=Y}static[U]="Name";brand;getSQL(){return new x([this])}}function L3(Y){return typeof Y==="object"&&Y!==null&&"mapToDriverValue"in Y&&typeof Y.mapToDriverValue==="function"}var D3={mapFromDriverValue:(Y)=>Y},V3={mapToDriverValue:(Y)=>Y},qC={...D3,...V3};class R1{constructor(Y,Z=V3){this.value=Y,this.encoder=Z}static[U]="Param";brand;getSQL(){return new x([this])}}function E(Y,...Z){let X=[];if(Z.length>0||Y.length>0&&Y[0]!=="")X.push(new u0(Y[0]));for(let[_,G]of Z.entries())X.push(G,new u0(Y[_+1]));return new x(X)}((Y)=>{function Z(){return new x([])}Y.empty=Z;function X(Q){return new x(Q)}Y.fromList=X;function _(Q){return new x([new u0(Q)])}Y.raw=_;function G(Q,$){let z=[];for(let[O,L]of Q.entries()){if(O>0&&$!==void 0)z.push($);z.push(L)}return new x(z)}Y.join=G;function W(Q){return new RY(Q)}Y.identifier=W;function H(Q){return new R4(Q)}Y.placeholder=H;function J(Q,$){return new R1(Q,$)}Y.param=J})(E||(E={}));((Y)=>{class Z{constructor(X,_){this.sql=X,this.fieldAlias=_}static[U]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Z(this.sql,this.fieldAlias)}}Y.Aliased=Z})(x||(x={}));class R4{constructor(Y){this.name=Y}static[U]="Placeholder";getSQL(){return new x([this])}}function $X(Y,Z){return Y.map((X)=>{if(M(X,R4)){if(!(X.name in Z))throw new Error(`No value for placeholder "${X.name}" was provided`);return Z[X.name]}if(M(X,R1)&&M(X.value,R4)){if(!(X.value.name in Z))throw new Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue(Z[X.value.name])}return X})}var KU=Symbol.for("drizzle:IsDrizzleView");class D1{static[U]="View";[A0];[KU]=!0;constructor({name:Y,schema:Z,selectedFields:X,query:_}){this[A0]={name:Y,originalName:Y,schema:Z,selectedFields:X,query:_,isExisting:!_,isAlias:!1}}getSQL(){return new x([this])}}E0.prototype.getSQL=function(){return new x([this])};P.prototype.getSQL=function(){return new x([this])};P0.prototype.getSQL=function(){return new x([this])};class A8{constructor(Y){this.table=Y}static[U]="ColumnAliasProxyHandler";get(Y,Z){if(Z==="table")return this.table;return Y[Z]}}class D6{constructor(Y,Z){this.alias=Y,this.replaceOriginalName=Z}static[U]="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===A0)return{...Y[A0],name:this.alias,isAlias:!0};if(Z===P.Symbol.Columns){let _=Y[P.Symbol.Columns];if(!_)return _;let G={};return Object.keys(_).map((W)=>{G[W]=new Proxy(_[W],new A8(new Proxy(Y,this)))}),G}let X=Y[Z];if(M(X,E0))return new Proxy(X,new A8(new Proxy(Y,this)));return X}}function IY(Y,Z){return new Proxy(Y,new D6(Z,!1))}function n1(Y,Z){return new Proxy(Y,new A8(new Proxy(Y.table,new D6(Z,!1))))}function QX(Y,Z){return new x.Aliased(V6(Y.sql,Z),Y.fieldAlias)}function V6(Y,Z){return E.join(Y.queryChunks.map((X)=>{if(M(X,E0))return n1(X,Z);if(M(X,x))return V6(X,Z);if(M(X,x.Aliased))return QX(X,Z);return X}))}class BY extends Error{static[U]="DrizzleError";constructor({message:Y,cause:Z}){super(Y);this.name="DrizzleError",this.cause=Z}}class zX extends BY{static[U]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class M3{static[U]="ConsoleLogWriter";write(Y){console.log(Y)}}class FX{static[U]="DefaultLogger";writer;constructor(Y){this.writer=Y?.writer??new M3}logQuery(Y,Z){let X=Z.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),_=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${Y}${_}`)}}class UX{static[U]="NoopLogger";logQuery(){}}class W1{static[U]="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 A3(Y,Z,X){let _={},G=Y.reduce((W,{path:H,field:J},Q)=>{let $;if(M(J,E0))$=J;else if(M(J,x))$=J.decoder;else $=J.sql.decoder;let z=W;for(let[O,L]of H.entries())if(O<H.length-1){if(!(L in z))z[L]={};z=z[L]}else{let V=Z[Q],R=z[L]=V===null?null:$.mapFromDriverValue(V);if(X&&M(J,E0)&&H.length===2){let A=H[0];if(!(A in _))_[A]=R===null?c0(J.table):!1;else if(typeof _[A]==="string"&&_[A]!==c0(J.table))_[A]=!1}}return W},{});if(X&&Object.keys(_).length>0){for(let[W,H]of Object.entries(_))if(typeof H==="string"&&!X[H])G[W]=null}return G}function q1(Y,Z){return Object.entries(Y).reduce((X,[_,G])=>{if(typeof _!=="string")return X;let W=Z?[...Z,_]:[_];if(M(G,E0)||M(G,x)||M(G,x.Aliased))X.push({path:W,field:G});else if(M(G,P))X.push(...q1(G[P.Symbol.Columns],W));else X.push(...q1(G,W));return X},[])}function M6(Y,Z){let X=Object.keys(Y),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let[G,W]of X.entries())if(W!==_[G])return!1;return!0}function TY(Y,Z){let X=Object.entries(Z).filter(([,_])=>_!==void 0).map(([_,G])=>{if(M(G,x)||M(G,E0))return[_,G];else return[_,new R1(G,Y[P.Symbol.Columns][_])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function w3(Y,Z){for(let X of Z)for(let _ of Object.getOwnPropertyNames(X.prototype)){if(_==="constructor")continue;Object.defineProperty(Y.prototype,_,Object.getOwnPropertyDescriptor(X.prototype,_)||Object.create(null))}}function N3(Y){return Y[P.Symbol.Columns]}function J4(Y){return M(Y,P0)?Y._.alias:M(Y,D1)?Y[A0].name:M(Y,x)?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 R3(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 I4 extends h{static[U]="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 I3 extends I4{static[U]="PgBigInt53Builder";constructor(Y){super(Y,"number","PgBigInt53")}build(Y){return new B3(Y,this.config)}}class B3 extends j{static[U]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class T3 extends I4{static[U]="PgBigInt64Builder";constructor(Y){super(Y,"bigint","PgBigInt64")}build(Y){return new C3(Y,this.config)}}class C3 extends j{static[U]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(Y){return BigInt(Y)}}function K3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new I3(X);return new T3(X)}class q3 extends h{static[U]="PgBigSerial53Builder";constructor(Y){super(Y,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new j3(Y,this.config)}}class j3 extends j{static[U]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class P3 extends h{static[U]="PgBigSerial64Builder";constructor(Y){super(Y,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(Y){return new S3(Y,this.config)}}class S3 extends j{static[U]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(Y){return BigInt(Y)}}function v3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new q3(X);return new P3(X)}class x3 extends h{static[U]="PgBooleanBuilder";constructor(Y){super(Y,"boolean","PgBoolean")}build(Y){return new h3(Y,this.config)}}class h3 extends j{static[U]="PgBoolean";getSQLType(){return"boolean"}}function A6(Y){return new x3(Y??"")}class f3 extends h{static[U]="PgCharBuilder";constructor(Y,Z){super(Y,"string","PgChar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new b3(Y,this.config)}}class b3 extends j{static[U]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function k3(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new f3(X,_)}class g3 extends h{static[U]="PgCidrBuilder";constructor(Y){super(Y,"string","PgCidr")}build(Y){return new y3(Y,this.config)}}class y3 extends j{static[U]="PgCidr";getSQLType(){return"cidr"}}function p3(Y){return new g3(Y??"")}class m3 extends h{static[U]="PgCustomColumnBuilder";constructor(Y,Z,X){super(Y,"custom","PgCustomColumn");this.config.fieldConfig=Z,this.config.customTypeParams=X}build(Y){return new u3(Y,this.config)}}class u3 extends j{static[U]="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 d3(Y){return(Z,X)=>{let{name:_,config:G}=X0(Z,X);return new m3(_,G,Y)}}class $4 extends h{static[U]="PgDateColumnBaseBuilder";defaultNow(){return this.default(E`now()`)}}class c3 extends $4{static[U]="PgDateBuilder";constructor(Y){super(Y,"date","PgDate")}build(Y){return new CY(Y,this.config)}}class CY extends j{static[U]="PgDate";getSQLType(){return"date"}mapFromDriverValue(Y){return new Date(Y)}mapToDriverValue(Y){return Y.toISOString()}}class l3 extends $4{static[U]="PgDateStringBuilder";constructor(Y){super(Y,"string","PgDateString")}build(Y){return new KY(Y,this.config)}}class KY extends j{static[U]="PgDateString";getSQLType(){return"date"}}function i3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="date")return new c3(X);return new l3(X)}class o3 extends h{static[U]="PgDoublePrecisionBuilder";constructor(Y){super(Y,"number","PgDoublePrecision")}build(Y){return new n3(Y,this.config)}}class n3 extends j{static[U]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function r3(Y){return new o3(Y??"")}class s3 extends h{static[U]="PgInetBuilder";constructor(Y){super(Y,"string","PgInet")}build(Y){return new a3(Y,this.config)}}class a3 extends j{static[U]="PgInet";getSQLType(){return"inet"}}function t3(Y){return new s3(Y??"")}class e3 extends I4{static[U]="PgIntegerBuilder";constructor(Y){super(Y,"number","PgInteger")}build(Y){return new Y2(Y,this.config)}}class Y2 extends j{static[U]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseInt(Y);return Y}}function w6(Y){return new e3(Y??"")}class Z2 extends h{static[U]="PgIntervalBuilder";constructor(Y,Z){super(Y,"string","PgInterval");this.config.intervalConfig=Z}build(Y){return new X2(Y,this.config)}}class X2 extends j{static[U]="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 _2(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new Z2(X,_)}class G2 extends h{static[U]="PgJsonBuilder";constructor(Y){super(Y,"json","PgJson")}build(Y){return new qY(Y,this.config)}}class qY extends j{static[U]="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 W2(Y){return new G2(Y??"")}class H2 extends h{static[U]="PgJsonbBuilder";constructor(Y){super(Y,"json","PgJsonb")}build(Y){return new jY(Y,this.config)}}class jY extends j{static[U]="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 J2(Y){return new H2(Y??"")}class $2 extends h{static[U]="PgLineBuilder";constructor(Y){super(Y,"array","PgLine")}build(Y){return new Q2(Y,this.config)}}class Q2 extends j{static[U]="PgLine";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,_]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X),Number.parseFloat(_)]}mapToDriverValue(Y){return`{${Y[0]},${Y[1]},${Y[2]}}`}}class z2 extends h{static[U]="PgLineABCBuilder";constructor(Y){super(Y,"json","PgLineABC")}build(Y){return new F2(Y,this.config)}}class F2 extends j{static[U]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,_]=Y.slice(1,-1).split(",");return{a:Number.parseFloat(Z),b:Number.parseFloat(X),c:Number.parseFloat(_)}}mapToDriverValue(Y){return`{${Y.a},${Y.b},${Y.c}}`}}function U2(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new $2(X);return new z2(X)}class O2 extends h{static[U]="PgMacaddrBuilder";constructor(Y){super(Y,"string","PgMacaddr")}build(Y){return new E2(Y,this.config)}}class E2 extends j{static[U]="PgMacaddr";getSQLType(){return"macaddr"}}function L2(Y){return new O2(Y??"")}class D2 extends h{static[U]="PgMacaddr8Builder";constructor(Y){super(Y,"string","PgMacaddr8")}build(Y){return new V2(Y,this.config)}}class V2 extends j{static[U]="PgMacaddr8";getSQLType(){return"macaddr8"}}function M2(Y){return new D2(Y??"")}class A2 extends h{static[U]="PgNumericBuilder";constructor(Y,Z,X){super(Y,"string","PgNumeric");this.config.precision=Z,this.config.scale=X}build(Y){return new PY(Y,this.config)}}class PY extends j{static[U]="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 w2 extends h{static[U]="PgNumericNumberBuilder";constructor(Y,Z,X){super(Y,"number","PgNumericNumber");this.config.precision=Z,this.config.scale=X}build(Y){return new N2(Y,this.config)}}class N2 extends j{static[U]="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 R2 extends h{static[U]="PgNumericBigIntBuilder";constructor(Y,Z,X){super(Y,"bigint","PgNumericBigInt");this.config.precision=Z,this.config.scale=X}build(Y){return new I2(Y,this.config)}}class I2 extends j{static[U]="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 B2(Y,Z){let{name:X,config:_}=X0(Y,Z),G=_?.mode;return G==="number"?new w2(X,_?.precision,_?.scale):G==="bigint"?new R2(X,_?.precision,_?.scale):new A2(X,_?.precision,_?.scale)}class T2 extends h{static[U]="PgPointTupleBuilder";constructor(Y){super(Y,"array","PgPointTuple")}build(Y){return new C2(Y,this.config)}}class C2 extends j{static[U]="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 K2 extends h{static[U]="PgPointObjectBuilder";constructor(Y){super(Y,"json","PgPointObject")}build(Y){return new q2(Y,this.config)}}class q2 extends j{static[U]="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 j2(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new T2(X);return new K2(X)}function qU(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 P2(Y,Z){let X=new ArrayBuffer(8),_=new DataView(X);for(let G=0;G<8;G++)_.setUint8(G,Y[Z+G]);return _.getFloat64(0,!0)}function OX(Y){let Z=qU(Y),X=0,_=Z[X];X+=1;let G=new DataView(Z.buffer),W=G.getUint32(X,_===1);X+=4;let H;if(W&536870912)H=G.getUint32(X,_===1),X+=4;if((W&65535)===1){let J=P2(Z,X);X+=8;let Q=P2(Z,X);return X+=8,[J,Q]}throw new Error("Unsupported geometry type")}class S2 extends h{static[U]="PgGeometryBuilder";constructor(Y){super(Y,"array","PgGeometry")}build(Y){return new v2(Y,this.config)}}class v2 extends j{static[U]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){return OX(Y)}mapToDriverValue(Y){return`point(${Y[0]} ${Y[1]})`}}class x2 extends h{static[U]="PgGeometryObjectBuilder";constructor(Y){super(Y,"json","PgGeometryObject")}build(Y){return new h2(Y,this.config)}}class h2 extends j{static[U]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){let Z=OX(Y);return{x:Z[0],y:Z[1]}}mapToDriverValue(Y){return`point(${Y.x} ${Y.y})`}}function f2(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new S2(X);return new x2(X)}class b2 extends h{static[U]="PgRealBuilder";constructor(Y,Z){super(Y,"number","PgReal");this.config.length=Z}build(Y){return new k2(Y,this.config)}}class k2 extends j{static[U]="PgReal";constructor(Y,Z){super(Y,Z)}getSQLType(){return"real"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function g2(Y){return new b2(Y??"")}class y2 extends h{static[U]="PgSerialBuilder";constructor(Y){super(Y,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new p2(Y,this.config)}}class p2 extends j{static[U]="PgSerial";getSQLType(){return"serial"}}function m2(Y){return new y2(Y??"")}class u2 extends I4{static[U]="PgSmallIntBuilder";constructor(Y){super(Y,"number","PgSmallInt")}build(Y){return new d2(Y,this.config)}}class d2 extends j{static[U]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number(Y);return Y}}function c2(Y){return new u2(Y??"")}class l2 extends h{static[U]="PgSmallSerialBuilder";constructor(Y){super(Y,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new i2(Y,this.config)}}class i2 extends j{static[U]="PgSmallSerial";getSQLType(){return"smallserial"}}function o2(Y){return new l2(Y??"")}class n2 extends h{static[U]="PgTextBuilder";constructor(Y,Z){super(Y,"string","PgText");this.config.enumValues=Z.enum}build(Y){return new r2(Y,this.config)}}class r2 extends j{static[U]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function s2(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new n2(X,_)}class a2 extends $4{constructor(Y,Z,X){super(Y,"string","PgTime");this.withTimezone=Z,this.precision=X,this.config.withTimezone=Z,this.config.precision=X}static[U]="PgTimeBuilder";build(Y){return new SY(Y,this.config)}}class SY extends j{static[U]="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 t2(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new a2(X,_.withTimezone??!1,_.precision)}class e2 extends $4{static[U]="PgTimestampBuilder";constructor(Y,Z,X){super(Y,"date","PgTimestamp");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new vY(Y,this.config)}}class vY extends j{static[U]="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 YW extends $4{static[U]="PgTimestampStringBuilder";constructor(Y,Z,X){super(Y,"string","PgTimestampString");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new xY(Y,this.config)}}class xY extends j{static[U]="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 ZW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="string")return new YW(X,_.withTimezone??!1,_.precision);return new e2(X,_?.withTimezone??!1,_?.precision)}class XW extends h{static[U]="PgUUIDBuilder";constructor(Y){super(Y,"string","PgUUID")}defaultRandom(){return this.default(E`gen_random_uuid()`)}build(Y){return new hY(Y,this.config)}}class hY extends j{static[U]="PgUUID";getSQLType(){return"uuid"}}function j1(Y){return new XW(Y??"")}class _W extends h{static[U]="PgVarcharBuilder";constructor(Y,Z){super(Y,"string","PgVarchar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new GW(Y,this.config)}}class GW extends j{static[U]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function e0(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new _W(X,_)}class WW extends h{static[U]="PgBinaryVectorBuilder";constructor(Y,Z){super(Y,"string","PgBinaryVector");this.config.dimensions=Z.dimensions}build(Y){return new HW(Y,this.config)}}class HW extends j{static[U]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function JW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new WW(X,_)}class $W extends h{static[U]="PgHalfVectorBuilder";constructor(Y,Z){super(Y,"array","PgHalfVector");this.config.dimensions=Z.dimensions}build(Y){return new QW(Y,this.config)}}class QW extends j{static[U]="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 zW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new $W(X,_)}class FW extends h{static[U]="PgSparseVectorBuilder";constructor(Y,Z){super(Y,"string","PgSparseVector");this.config.dimensions=Z.dimensions}build(Y){return new UW(Y,this.config)}}class UW extends j{static[U]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function OW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new FW(X,_)}class EW extends h{static[U]="PgVectorBuilder";constructor(Y,Z){super(Y,"array","PgVector");this.config.dimensions=Z.dimensions}build(Y){return new LW(Y,this.config)}}class LW extends j{static[U]="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 DW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new EW(X,_)}function VW(){return{bigint:K3,bigserial:v3,boolean:A6,char:k3,cidr:p3,customType:d3,date:i3,doublePrecision:r3,inet:t3,integer:w6,interval:_2,json:W2,jsonb:J2,line:U2,macaddr:L2,macaddr8:M2,numeric:B2,point:j2,geometry:f2,real:g2,serial:m2,smallint:c2,smallserial:o2,text:s2,time:t2,timestamp:ZW,uuid:j1,varchar:e0,bit:JW,halfvec:zW,sparsevec:OW,vector:DW}}var EX=Symbol.for("drizzle:PgInlineForeignKeys"),MW=Symbol.for("drizzle:EnableRLS");class d0 extends P{static[U]="PgTable";static Symbol=Object.assign({},P.Symbol,{InlineForeignKeys:EX,EnableRLS:MW});[EX]=[];[MW]=!1;[P.Symbol.ExtraConfigBuilder]=void 0;[P.Symbol.ExtraConfigColumns]={}}function jU(Y,Z,X,_,G=Y){let W=new d0(Y,_,G),H=typeof Z==="function"?Z(VW()):Z,J=Object.fromEntries(Object.entries(H).map(([z,O])=>{let L=O;L.setName(z);let V=L.build(W);return W[EX].push(...L.buildForeignKeys(V,W)),[z,V]})),Q=Object.fromEntries(Object.entries(H).map(([z,O])=>{let L=O;L.setName(z);let V=L.buildExtraConfigColumn(W);return[z,V]})),$=Object.assign(W,J);if($[P.Symbol.Columns]=J,$[P.Symbol.ExtraConfigColumns]=Q,X)$[d0.Symbol.ExtraConfigBuilder]=X;return Object.assign($,{enableRLS:()=>{return $[d0.Symbol.EnableRLS]=!0,$}})}var B4=(Y,Z,X)=>{return jU(Y,Z,X,void 0)};function AW(...Y){if(Y[0].columns)return new N6(Y[0].columns,Y[0].name);return new N6(Y)}class N6{static[U]="PgPrimaryKeyBuilder";columns;name;constructor(Y,Z){this.columns=Y,this.name=Z}build(Y){return new wW(Y,this.columns,this.name)}}class wW{constructor(Y,Z,X){this.table=Y,this.columns=Z,this.name=X}static[U]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[d0.Symbol.Name]}_${this.columns.map((Y)=>Y.name).join("_")}_pk`}}function V1(Y,Z){if(L3(Z)&&!JX(Y)&&!M(Y,R1)&&!M(Y,R4)&&!M(Y,E0)&&!M(Y,P)&&!M(Y,D1))return new R1(Y,Z);return Y}var fY=(Y,Z)=>{return E`${Y} = ${V1(Z,Y)}`},NW=(Y,Z)=>{return E`${Y} <> ${V1(Z,Y)}`};function R6(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new x(Z);return new x([new u0("("),E.join(Z,new u0(" and ")),new u0(")")])}function RW(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new x(Z);return new x([new u0("("),E.join(Z,new u0(" or ")),new u0(")")])}function IW(Y){return E`not ${Y}`}var BW=(Y,Z)=>{return E`${Y} > ${V1(Z,Y)}`},TW=(Y,Z)=>{return E`${Y} >= ${V1(Z,Y)}`},CW=(Y,Z)=>{return E`${Y} < ${V1(Z,Y)}`},KW=(Y,Z)=>{return E`${Y} <= ${V1(Z,Y)}`};function qW(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return E`false`;return E`${Y} in ${Z.map((X)=>V1(X,Y))}`}return E`${Y} in ${V1(Z,Y)}`}function jW(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return E`true`;return E`${Y} not in ${Z.map((X)=>V1(X,Y))}`}return E`${Y} not in ${V1(Z,Y)}`}function PW(Y){return E`${Y} is null`}function SW(Y){return E`${Y} is not null`}function vW(Y){return E`exists ${Y}`}function xW(Y){return E`not exists ${Y}`}function hW(Y,Z,X){return E`${Y} between ${V1(Z,Y)} and ${V1(X,Y)}`}function fW(Y,Z,X){return E`${Y} not between ${V1(Z,Y)} and ${V1(X,Y)}`}function bW(Y,Z){return E`${Y} like ${Z}`}function kW(Y,Z){return E`${Y} not like ${Z}`}function gW(Y,Z){return E`${Y} ilike ${Z}`}function yW(Y,Z){return E`${Y} not ilike ${Z}`}function pW(Y){return E`${Y} asc`}function mW(Y){return E`${Y} desc`}class LX{constructor(Y,Z,X){this.sourceTable=Y,this.referencedTable=Z,this.relationName=X,this.referencedTableName=Z[P.Symbol.Name]}static[U]="Relation";referencedTableName;fieldName}class uW{constructor(Y,Z){this.table=Y,this.config=Z}static[U]="Relations"}class T4 extends LX{constructor(Y,Z,X,_){super(Y,Z,X?.relationName);this.config=X,this.isNullable=_}static[U]="One";withFieldName(Y){let Z=new T4(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Z.fieldName=Y,Z}}class I6 extends LX{constructor(Y,Z,X){super(Y,Z,X?.relationName);this.config=X}static[U]="Many";withFieldName(Y){let Z=new I6(this.sourceTable,this.referencedTable,this.config);return Z.fieldName=Y,Z}}function dW(){return{and:R6,between:hW,eq:fY,exists:vW,gt:BW,gte:TW,ilike:gW,inArray:qW,isNull:PW,isNotNull:SW,like:bW,lt:CW,lte:KW,ne:NW,not:IW,notBetween:fW,notExists:xW,notLike:kW,notIlike:yW,notInArray:jW,or:RW,sql:E}}function cW(){return{sql:E,asc:pW,desc:mW}}function lW(Y,Z){if(Object.keys(Y).length===1&&"default"in Y&&!M(Y.default,P))Y=Y.default;let X={},_={},G={};for(let[W,H]of Object.entries(Y))if(M(H,P)){let J=y4(H),Q=_[J];X[J]=W,G[W]={tsName:W,dbName:H[P.Symbol.Name],schema:H[P.Symbol.Schema],columns:H[P.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let z of Object.values(H[P.Symbol.Columns]))if(z.primary)G[W].primaryKey.push(z);let $=H[P.Symbol.ExtraConfigBuilder]?.(H[P.Symbol.ExtraConfigColumns]);if($){for(let z of Object.values($))if(M(z,N6))G[W].primaryKey.push(...z.columns)}}else if(M(H,uW)){let J=y4(H.table),Q=X[J],$=H.config(Z(H.table)),z;for(let[O,L]of Object.entries($))if(Q){let V=G[Q];if(V.relations[O]=L,z)V.primaryKey.push(...z)}else{if(!(J in _))_[J]={relations:{},primaryKey:z};_[J].relations[O]=L}}return{tables:G,tableNamesMap:X}}function PU(Y){return function Z(X,_){return new T4(Y,X,_,_?.fields.reduce((G,W)=>G&&W.notNull,!0)??!1)}}function SU(Y){return function Z(X,_){return new I6(Y,X,_)}}function iW(Y,Z,X){if(M(X,T4)&&X.config)return{fields:X.config.fields,references:X.config.references};let _=Z[y4(X.referencedTable)];if(!_)throw new Error(`Table "${X.referencedTable[P.Symbol.Name]}" not found in schema`);let G=Y[_];if(!G)throw new Error(`Table "${_}" not found in schema`);let W=X.sourceTable,H=Z[y4(W)];if(!H)throw new Error(`Table "${W[P.Symbol.Name]}" not found in schema`);let J=[];for(let Q of Object.values(G.relations))if(X.relationName&&X!==Q&&Q.relationName===X.relationName||!X.relationName&&Q.referencedTable===X.sourceTable)J.push(Q);if(J.length>1)throw X.relationName?new Error(`There are multiple relations with name "${X.relationName}" in table "${_}"`):new Error(`There are multiple relations between "${_}" and "${X.sourceTable[P.Symbol.Name]}". Please specify relation name`);if(J[0]&&M(J[0],T4)&&J[0].config)return{fields:J[0].config.references,references:J[0].config.fields};throw new Error(`There is not enough information to infer relation "${H}.${X.fieldName}"`)}function oW(Y){return{one:PU(Y),many:SU(Y)}}function bY(Y,Z,X,_,G=(W)=>W){let W={};for(let[H,J]of _.entries())if(J.isJson){let Q=Z.relations[J.tsKey],$=X[H],z=typeof $==="string"?JSON.parse($):$;W[J.tsKey]=M(Q,T4)?z&&bY(Y,Y[J.relationTableTsKey],z,J.selection,G):z.map((O)=>bY(Y,Y[J.relationTableTsKey],O,J.selection,G))}else{let Q=G(X[H]),$=J.field,z;if(M($,E0))z=$;else if(M($,x))z=$.decoder;else z=$.sql.decoder;W[J.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return W}import ZO from"os";import XO from"fs";var kY=new Map,DX=new Map,VX=Symbol("OriginError"),w8={};class P1 extends Promise{constructor(Y,Z,X,_,G={}){let W,H;super((J,Q)=>{W=J,H=Q});this.tagged=Array.isArray(Y.raw),this.strings=Y,this.args=Z,this.handler=X,this.canceller=_,this.options=G,this.state=null,this.statement=null,this.resolve=(J)=>(this.active=!1,W(J)),this.reject=(J)=>(this.active=!1,H(J)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[VX]=this.handler.debug?new Error:this.tagged&&vU(this.strings)}get origin(){return(this.handler.debug?this[VX].stack:this.tagged&&DX.has(this.strings)?DX.get(this.strings):DX.set(this.strings,this[VX].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(Y=1,Z){if(this.options.simple=!1,typeof Y==="function")Z=Y,Y=1;if(this.cursorRows=Y,typeof Z==="function")return this.cursorFn=Z,this;let X;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};X&&X();let _=new Promise((G,W)=>{this.cursorFn=(H)=>{return G({value:H,done:!1}),new Promise((J)=>X=J)},this.resolve=()=>(this.active=!1,G({done:!0})),this.reject=(H)=>(this.active=!1,W(H))});return this.execute(),_},return(){return X&&X(w8),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(Y){return this.forEachFn=Y,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function vU(Y){if(kY.has(Y))return kY.get(Y);let Z=Error.stackTraceLimit;return Error.stackTraceLimit=4,kY.set(Y,new Error),Error.stackTraceLimit=Z,kY.get(Y)}class N8 extends Error{constructor(Y){super(Y.message);this.name=this.constructor.name,Object.assign(this,Y)}}var h0={connection:nW,postgres:rW,generic:sW,notSupported:aW};function nW(Y,Z,X){let{host:_,port:G}=X||Z,W=Object.assign(new Error("write "+Y+" "+(Z.path||_+":"+G)),{code:Y,errno:Y,address:Z.path||_},Z.path?{}:{port:G});return Error.captureStackTrace(W,nW),W}function rW(Y){let Z=new N8(Y);return Error.captureStackTrace(Z,rW),Z}function sW(Y,Z){let X=Object.assign(new Error(Y+": "+Z),{code:Y});return Error.captureStackTrace(X,sW),X}function aW(Y){let Z=Object.assign(new Error(Y+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:Y});return Error.captureStackTrace(Z,aW),Z}var xU={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 pY{then(){MX()}catch(){MX()}finally(){MX()}}class K6 extends pY{constructor(Y){super();this.value=dY(Y)}}class r1 extends pY{constructor(Y,Z,X){super();this.value=Y,this.type=Z,this.array=X}}class mY extends pY{constructor(Y,Z){super();this.first=Y,this.rest=Z}build(Y,Z,X,_){let G=hU.map(([W,H])=>({fn:H,i:Y.search(W)})).sort((W,H)=>W.i-H.i).pop();return G.i===-1?IX(this.first,_):G.fn(this.first,this.rest,Z,X,_)}}function uY(Y,Z,X,_){let G=Y instanceof r1?Y.value:Y;if(G===void 0){if(Y instanceof r1?Y.value=_.transform.undefined:G=Y=_.transform.undefined,G===void 0)throw h0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(Y instanceof r1?(Z.push(Y.value),Y.array?Y.array[Y.type||yY(Y.value)]||Y.type||ZH(Y.value):Y.type):(Z.push(Y),yY(Y)))}var eW=_H(xU);function NX(Y,Z,X,_,G,W){for(let H=1;H<Y.strings.length;H++)Z+=RX(Z,X,_,G,W)+Y.strings[H],X=Y.args[H];return Z}function RX(Y,Z,X,_,G){return Z instanceof mY?Z.build(Y,X,_,G):Z instanceof P1?wX(Z,X,_,G):Z instanceof K6?Z.value:Z&&Z[0]instanceof P1?Z.reduce((W,H)=>W+" "+wX(H,X,_,G),""):uY(Z,X,_,G)}function wX(Y,Z,X,_){return Y.fragment=!0,NX(Y,Y.strings[0],Y.args[0],Z,X,_)}function YH(Y,Z,X,_,G){return Y.map((W)=>"("+_.map((H)=>RX("values",W[H],Z,X,G)).join(",")+")").join(",")}function tW(Y,Z,X,_,G){let W=Array.isArray(Y[0]),H=Z.length?Z.flat():Object.keys(W?Y[0]:Y);return YH(W?Y:[Y],X,_,H,G)}function gY(Y,Z,X,_,G){if(typeof Y==="string"&&(Y=[Y].concat(Z)),Array.isArray(Y))return IX(Y,G);let W;return(Z.length?Z.flat():Object.keys(Y)).map((J)=>{return W=Y[J],(W instanceof P1?wX(W,X,_,G):W instanceof K6?W.value:uY(W,X,_,G))+" as "+dY(G.transform.column.to?G.transform.column.to(J):J)}).join(",")}var hU=Object.entries({values:tW,in:(...Y)=>{let Z=tW(...Y);return Z==="()"?"(null)":Z},select:gY,as:gY,returning:gY,"\\(":gY,update(Y,Z,X,_,G){return(Z.length?Z.flat():Object.keys(Y)).map((W)=>dY(G.transform.column.to?G.transform.column.to(W):W)+"="+RX("values",Y[W],X,_,G))},insert(Y,Z,X,_,G){let W=Z.length?Z.flat():Object.keys(Array.isArray(Y)?Y[0]:Y);return"("+IX(W,G)+")values"+YH(Array.isArray(Y)?Y:[Y],X,_,W,G)}}).map(([Y,Z])=>[new RegExp("((?:^|[\\s(])"+Y+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Z]);function MX(){throw h0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:fU,parsers:bU}=eW;function ZH(Y){if(Array.isArray(Y))return ZH(Y[0]);return typeof Y==="string"?1009:0}var XH=function(Y){let Z=_H(Y||{});return{serializers:Object.assign({},fU,Z.serializers),parsers:Object.assign({},bU,Z.parsers)}};function _H(Y){return Object.keys(Y).reduce((Z,X)=>{if(Y[X].from&&[].concat(Y[X].from).forEach((_)=>Z.parsers[_]=Y[X].parse),Y[X].serialize)Z.serializers[Y[X].to]=Y[X].serialize,Y[X].from&&[].concat(Y[X].from).forEach((_)=>Z.serializers[_]=Y[X].serialize);return Z},{parsers:{},serializers:{}})}function IX(Y,{transform:{column:Z}}){return Y.map((X)=>dY(Z.to?Z.to(X):X)).join(",")}var dY=function Y(Z){return'"'+Z.replace(/"/g,'""').replace(/\./g,'"."')+'"'},yY=function Y(Z){return Z instanceof r1?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},kU=/\\/g,gU=/"/g;function yU(Y){return Y.replace(kU,"\\\\").replace(gU,"\\\"")}var GH=function Y(Z,X,_,G){if(Array.isArray(Z)===!1)return Z;if(!Z.length)return"{}";let W=Z[0],H=G===1020?";":",";if(Array.isArray(W)&&!W.type)return"{"+Z.map((J)=>Y(J,X,_,G)).join(H)+"}";return"{"+Z.map((J)=>{if(J===void 0){if(J=_.transform.undefined,J===void 0)throw h0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return J===null?"null":'"'+yU(X?X(J.type?J.value:J):""+J)+'"'}).join(H)+"}"},AX={i:0,char:null,str:"",quoted:!1,last:0},WH=function Y(Z,X,_){return AX.i=AX.last=0,HH(AX,Z,X,_)};function HH(Y,Z,X,_){let G=[],W=_===1020?";":",";for(;Y.i<Z.length;Y.i++){if(Y.char=Z[Y.i],Y.quoted)if(Y.char==="\\")Y.str+=Z[++Y.i];else if(Y.char==='"')G.push(X?X(Y.str):Y.str),Y.str="",Y.quoted=Z[Y.i+1]==='"',Y.last=Y.i+2;else Y.str+=Y.char;else if(Y.char==='"')Y.quoted=!0;else if(Y.char==="{")Y.last=++Y.i,G.push(HH(Y,Z,X,_));else if(Y.char==="}"){Y.quoted=!1,Y.last<Y.i&&G.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;break}else if(Y.char===W&&Y.p!=="}"&&Y.p!=='"')G.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;Y.p=Y.char}return Y.last<Y.i&&G.push(X?X(Z.slice(Y.last,Y.i+1)):Z.slice(Y.last,Y.i+1)),G}var 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,"-"),B6=(Y)=>Y.replace(/([A-Z])/g,"_$1").toLowerCase(),T6=(Y)=>(Y.slice(0,1)+Y.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),C6=(Y)=>Y.replace(/-/g,"_");function BX(Y){return function Z(X,_){return typeof X==="object"&&X!==null&&(_.type===114||_.type===3802)?Array.isArray(X)?X.map((G)=>Z(G,_)):Object.entries(X).reduce((G,[W,H])=>Object.assign(G,{[Y(W)]:Z(H,_)}),{}):X}}p4.column={from:p4};p4.value={from:BX(p4)};B6.column={to:B6};var TX={...p4};TX.column.to=B6;m4.column={from:m4};m4.value={from:BX(m4)};T6.column={to:T6};var CX={...m4};CX.column.to=T6;u4.column={from:u4};u4.value={from:BX(u4)};C6.column={to:C6};var KX={...u4};KX.column.to=C6;import JH from"net";import dU from"tls";import q6 from"crypto";import qX from"stream";import{performance as $H}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 I1=pU;function pU(Y=[]){let Z=Y.slice(),X=0;return{get length(){return Z.length-X},remove:(_)=>{let G=Z.indexOf(_);return G===-1?null:(Z.splice(G,1),_)},push:(_)=>(Z.push(_),_),shift:()=>{let _=Z[X++];if(X===Z.length)X=0,Z=[];else Z[X-1]=void 0;return _}}}var Y1=Buffer.allocUnsafe(256),mU="BCcDdEFfHPpQSX".split("").reduce((Y,Z)=>{let X=Z.charCodeAt(0);return Y[Z]=()=>{return Y1[0]=X,F0.i=5,F0},Y},{}),F0=Object.assign(uU,mU,{N:String.fromCharCode(0),i:0,inc(Y){return F0.i+=Y,F0},str(Y){let Z=Buffer.byteLength(Y);return cY(Z),F0.i+=Y1.write(Y,F0.i,Z,"utf8"),F0},i16(Y){return cY(2),Y1.writeUInt16BE(Y,F0.i),F0.i+=2,F0},i32(Y,Z){if(Z||Z===0)return Y1.writeUInt32BE(Y,Z),F0;return cY(4),Y1.writeUInt32BE(Y,F0.i),F0.i+=4,F0},z(Y){return cY(Y),Y1.fill(0,F0.i,F0.i+Y),F0.i+=Y,F0},raw(Y){return Y1=Buffer.concat([Y1.subarray(0,F0.i),Y]),F0.i=Y1.length,F0},end(Y=1){Y1.writeUInt32BE(F0.i-Y,Y);let Z=Y1.subarray(0,F0.i);return F0.i=0,Y1=Buffer.allocUnsafe(256),Z}}),c=F0;function cY(Y){if(Y1.length-F0.i<Y){let Z=Y1,X=Z.length;Y1=Buffer.allocUnsafe(X+(X>>1)+Y),Z.copy(Y1)}}function uU(){return F0.i=0,F0}var SX=FH,cU=1,C4=c().S().end(),QH=c().H().end(),lU=c().i32(8).i32(80877103).end(8),iU=Buffer.concat([c().E().str(c.N).i32(0).end(),C4]),oU=c().D().str("S").str(c.N).end(),R8=()=>{},nU=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),rU={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 FH(Y,Z={},{onopen:X=R8,onend:_=R8,onclose:G=R8}={}){let{ssl:W,max:H,user:J,host:Q,port:$,database:z,parsers:O,transform:L,onnotice:V,onnotify:R,onparameter:A,max_pipeline:f,keep_alive:b,backoff:k,target_session_attrs:g}=Y,N=I1(),I=cU++,q={pid:null,secret:null},K=PX(GZ,Y.idle_timeout),p=PX(GZ,Y.max_lifetime),s=PX(hH,Y.connect_timeout),T=null,t,m=new d4,e=Buffer.alloc(0),U0=Y.fetch_types,f0={},J1={},s1=Math.random().toString(36).slice(2),C=1,u=0,G0=0,T0=0,b0=0,a=0,$0=0,S0=0,C0=null,w0=null,n0=!1,D0=null,S1=null,l0=null,z4=null,k0=null,N0=null,v1=null,m1=null,v=null,C8=null,r0={queue:Z.closed,idleTimer:K,connect(F){l0=F,G_()},terminate:q8,execute:K8,cancel:PH,end:GZ,count:0,id:I};return Z.closed&&Z.closed.push(r0),r0;async function jH(){let F;try{F=Y.socket?await Promise.resolve(Y.socket(Y)):new JH.Socket}catch(D){o4(D);return}return F.on("error",o4),F.on("close",W_),F.on("drain",X_),F}async function PH({pid:F,secret:D},l,W0){try{t=c().i32(16).i32(80877102).i32(F).i32(D).end(16),await __(),T.once("error",W0),T.once("close",l)}catch(q0){W0(q0)}}function K8(F){if(n0)return b6(F,h0.connection("CONNECTION_DESTROYED",Y));if(F.cancelled)return;try{return F.state=q,v?N.push(F):(v=F,v.active=!0),xH(F),i0(SH(F))&&!F.describeFirst&&!F.cursorFn&&N.length<f&&(!F.options.onexecute||F.options.onexecute(r0))}catch(D){return N.length===0&&i0(C4),u1(D),!0}}function SH(F){if(F.parameters.length>=65534)throw h0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return F.options.simple?c().Q().str(F.statement.string+c.N).end():F.describeFirst?Buffer.concat([eX(F),QH]):F.prepare?F.prepared?f6(F):Buffer.concat([eX(F),f6(F)]):vH(F)}function eX(F){return Buffer.concat([J_(F.statement.string,F.parameters,F.statement.types,F.statement.name),MJ("S",F.statement.name)])}function f6(F){return Buffer.concat([VJ(F.parameters,F.statement.types,F.statement.name,F.cursorName),F.cursorFn?$_("",F.cursorRows):iU])}function vH(F){return Buffer.concat([J_(F.statement.string,F.parameters,F.statement.types),oU,f6(F)])}function xH(F){let D=[],l=[],W0=NX(F,F.strings[0],F.args[0],D,l,Y);!F.tagged&&F.args.forEach((q0)=>uY(q0,D,l,Y)),F.prepare=Y.prepare&&("prepare"in F.options?F.options.prepare:!0),F.string=W0,F.signature=F.prepare&&l+W0,F.onlyDescribe&&delete J1[F.signature],F.parameters=F.parameters||D,F.prepared=F.prepare&&F.signature in J1,F.describeFirst=F.onlyDescribe||D.length&&!F.prepared,F.statement=F.prepared?J1[F.signature]:{string:W0,types:l,name:F.prepare?s1+C++:""},typeof Y.debug==="function"&&Y.debug(I,W0,D,l)}function i0(F,D){if(N0=N0?Buffer.concat([N0,F]):Buffer.from(F),D||N0.length>=1024)return Y_(D);return w0===null&&(w0=setImmediate(Y_)),!0}function Y_(F){let D=T.write(N0,F);return w0!==null&&clearImmediate(w0),N0=w0=null,D}function hH(){u1(h0.connection("CONNECT_TIMEOUT",Y,T)),T.destroy()}async function Z_(){if(i0(lU),!await new Promise((D)=>T.once("data",(l)=>D(l[0]===83)))&&W==="prefer")return i4();T.removeAllListeners(),T=dU.connect({socket:T,servername:JH.isIP(T.host)?void 0:T.host,...W==="require"||W==="allow"||W==="prefer"?{rejectUnauthorized:!1}:W==="verify-full"?{}:typeof W==="object"?W:{}}),T.on("secureConnect",i4),T.on("error",o4),T.on("close",W_),T.on("drain",X_)}function X_(){!v&&X(r0)}function _Z(F){if(D0){if(D0.push(F),G0-=F.length,G0>0)return}e=D0?Buffer.concat(D0,a-G0):e.length===0?F:Buffer.concat([e,F],e.length+F.length);while(e.length>4){if(a=e.readUInt32BE(1),a>=e.length){G0=a-e.length,D0=[e];break}try{fH(e.subarray(0,a+1))}catch(D){v&&(v.cursorFn||v.describeFirst)&&i0(C4),u1(D)}e=e.subarray(a+1),G0=0,D0=null}}async function __(){if(n0=!1,f0={},T||(T=await jH()),!T)return;if(s.start(),Y.socket)return W?Z_():i4();if(T.on("connect",W?Z_:i4),Y.path)return T.connect(Y.path);T.ssl=W,T.connect($[T0],Q[T0]),T.host=Q[T0],T.port=$[T0],T0=(T0+1)%$.length}function G_(){setTimeout(__,u?u+$0-$H.now():0)}function i4(){try{J1={},U0=Y.fetch_types,s1=Math.random().toString(36).slice(2),C=1,p.start(),T.on("data",_Z),b&&T.setKeepAlive&&T.setKeepAlive(!0,1000*b);let F=wJ();i0(F)}catch(F){o4(F)}}function o4(F){if(r0.queue===Z.connecting&&Y.host[b0+1])return;u1(F);while(N.length)b6(N.shift(),F)}function u1(F){k0&&(k0.destroy(F),k0=null),v&&b6(v,F),l0&&(b6(l0,F),l0=null)}function b6(F,D){if(F.reserve)return F.reject(D);if(!D||typeof D!=="object")D=new Error(D);"query"in D||"parameters"in D||Object.defineProperties(D,{stack:{value:D.stack+F.origin.replace(/.*\n/,`
|
|
61
|
+
`),enumerable:Y.debug},query:{value:F.string,enumerable:Y.debug},parameters:{value:F.parameters,enumerable:Y.debug},args:{value:F.args,enumerable:Y.debug},types:{value:F.statement&&F.statement.types,enumerable:Y.debug}}),F.reject(D)}function GZ(){return z4||(!r0.reserved&&_(r0),!r0.reserved&&!l0&&!v&&N.length===0?(q8(),new Promise((F)=>T&&T.readyState!=="closed"?T.once("close",F):F())):z4=new Promise((F)=>v1=F))}function q8(){if(n0=!0,k0||v||l0||N.length)o4(h0.connection("CONNECTION_DESTROYED",Y));if(clearImmediate(w0),T)T.removeListener("data",_Z),T.removeListener("connect",i4),T.readyState==="open"&&T.end(c().X().end());v1&&(v1(),z4=v1=null)}async function W_(F){if(e=Buffer.alloc(0),G0=0,D0=null,clearImmediate(w0),T.removeListener("data",_Z),T.removeListener("connect",i4),K.cancel(),p.cancel(),s.cancel(),T.removeAllListeners(),T=null,l0)return G_();!F&&(v||N.length)&&o4(h0.connection("CONNECTION_CLOSED",Y,T)),u=$H.now(),F&&Y.shared.retries++,$0=(typeof k==="function"?k(Y.shared.retries):k)*1000,G(r0,h0.connection("CONNECTION_CLOSED",Y,T))}function fH(F,D=F[0]){(D===68?bH:D===100?QJ:D===65?_J:D===83?kH:D===90?gH:D===67?yH:D===50?H_:D===49?pH:D===116?mH:D===84?uH:D===82?dH:D===110?rH:D===75?sH:D===69?ZJ:D===115?GJ:D===51?WJ:D===71?HJ:D===78?FJ:D===72?JJ:D===99?zJ:D===73?UJ:D===86?OJ:D===118?EJ:D===87?$J:LJ)(F)}function bH(F){let D=7,l,W0,q0,s0=v.isRaw?new Array(v.statement.columns.length):{};for(let Z1=0;Z1<v.statement.columns.length;Z1++)W0=v.statement.columns[Z1],l=F.readInt32BE(D),D+=4,q0=l===-1?null:v.isRaw===!0?F.subarray(D,D+=l):W0.parser===void 0?F.toString("utf8",D,D+=l):W0.parser.array===!0?W0.parser(F.toString("utf8",D+1,D+=l)):W0.parser(F.toString("utf8",D,D+=l)),v.isRaw?s0[Z1]=v.isRaw===!0?q0:L.value.from?L.value.from(q0,W0):q0:s0[W0.name]=L.value.from?L.value.from(q0,W0):q0;v.forEachFn?v.forEachFn(L.row.from?L.row.from(s0):s0,m):m[S0++]=L.row.from?L.row.from(s0):s0}function kH(F){let[D,l]=F.toString("utf8",5,F.length-1).split(c.N);if(f0[D]=l,Y.parameters[D]!==l)Y.parameters[D]=l,A&&A(D,l)}function gH(F){if(v&&v.options.simple&&v.resolve(S1||m),v=S1=null,m=new d4,s.cancel(),l0){if(g){if(!f0.in_hot_standby||!f0.default_transaction_read_only)return YJ();else if(eH(g,f0))return q8()}if(U0)return l0.reserve&&(l0=null),aH();l0&&!l0.reserve&&K8(l0),Y.shared.retries=b0=0,l0=null;return}while(N.length&&(v=N.shift())&&(v.active=!0,v.cancelled))FH(Y).cancel(v.state,v.cancelled.resolve,v.cancelled.reject);if(v)return;r0.reserved?!r0.reserved.release&&F[5]===73?z4?q8():(r0.reserved=null,X(r0)):r0.reserved():z4?q8():X(r0)}function yH(F){S0=0;for(let D=F.length-1;D>0;D--){if(F[D]===32&&F[D+1]<58&&m.count===null)m.count=+F.toString("utf8",D+1,F.length-1);if(F[D-1]>=65){m.command=F.toString("utf8",5,D),m.state=q;break}}if(C8&&(C8(),C8=null),m.command==="BEGIN"&&H!==1&&!r0.reserved)return u1(h0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(v.options.simple)return H_();if(v.cursorFn)m.count&&v.cursorFn(m),i0(C4);v.resolve(m)}function pH(){v.parsing=!1}function H_(){!m.statement&&(m.statement=v.statement),m.columns=v.statement.columns}function mH(F){let D=F.readUInt16BE(5);for(let l=0;l<D;++l)!v.statement.types[l]&&(v.statement.types[l]=F.readUInt32BE(7+l*4));v.prepare&&(J1[v.signature]=v.statement),v.describeFirst&&!v.onlyDescribe&&(i0(f6(v)),v.describeFirst=!1)}function uH(F){if(m.command)S1=S1||[m],S1.push(m=new d4),m.count=null,v.statement.columns=null;let D=F.readUInt16BE(5),l=7,W0;v.statement.columns=Array(D);for(let q0=0;q0<D;++q0){W0=l;while(F[l++]!==0);let s0=F.readUInt32BE(l),Z1=F.readUInt16BE(l+4),F4=F.readUInt32BE(l+6);v.statement.columns[q0]={name:L.column.from?L.column.from(F.toString("utf8",W0,l-1)):F.toString("utf8",W0,l-1),parser:O[F4],table:s0,number:Z1,type:F4},l+=18}if(m.statement=v.statement,v.onlyDescribe)return v.resolve(v.statement),i0(C4)}async function dH(F,D=F.readUInt32BE(5)){(D===3?cH:D===5?lH:D===10?iH:D===11?oH:D===12?nH:D!==0?DJ:R8)(F,D)}async function cH(){let F=await WZ();i0(c().p().str(F).z(1).end())}async function lH(F){let D="md5"+await zH(Buffer.concat([Buffer.from(await zH(await WZ()+J)),F.subarray(9)]));i0(c().p().str(D).z(1).end())}async function iH(){m1=(await q6.randomBytes(18)).toString("base64"),c().p().str("SCRAM-SHA-256"+c.N);let F=c.i;i0(c.inc(4).str("n,,n=*,r="+m1).i32(c.i-F-4,F).end())}async function oH(F){let D=F.toString("utf8",9).split(",").reduce((Z1,F4)=>(Z1[F4[0]]=F4.slice(2),Z1),{}),l=await q6.pbkdf2Sync(await WZ(),Buffer.from(D.s,"base64"),parseInt(D.i),32,"sha256"),W0=await lY(l,"Client Key"),q0="n=*,r="+m1+",r="+D.r+",s="+D.s+",i="+D.i+",c=biws,r="+D.r;C0=(await lY(await lY(l,"Server Key"),q0)).toString("base64");let s0="c=biws,r="+D.r+",p="+aU(W0,Buffer.from(await lY(await sU(W0),q0))).toString("base64");i0(c().p().str(s0).end())}function nH(F){if(F.toString("utf8",9).split(c.N,1)[0].slice(2)===C0)return;u1(h0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),T.destroy()}function WZ(){return Promise.resolve(typeof Y.pass==="function"?Y.pass():Y.pass)}function rH(){if(m.statement=v.statement,m.statement.columns=[],v.onlyDescribe)return v.resolve(v.statement),i0(C4)}function sH(F){q.pid=F.readUInt32BE(5),q.secret=F.readUInt32BE(9)}async function aH(){U0=!1,(await new P1([`
|
|
51
62
|
select b.oid, b.typarray
|
|
52
63
|
from pg_catalog.pg_type a
|
|
53
64
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
54
65
|
where a.typcategory = 'A'
|
|
55
66
|
group by b.oid, b.typarray
|
|
56
67
|
order by b.oid
|
|
57
|
-
`],[],
|
|
68
|
+
`],[],K8)).forEach(({oid:D,typarray:l})=>tH(D,l))}function tH(F,D){if(!!Y.parsers[D]&&!!Y.serializers[D])return;let l=Y.parsers[F];Y.shared.typeArrayMap[F]=D,Y.parsers[D]=(W0)=>WH(W0,l,D),Y.parsers[D].array=!0,Y.serializers[D]=(W0)=>GH(W0,Y.serializers[F],Y,D)}function eH(F,D){return F==="read-write"&&D.default_transaction_read_only==="on"||F==="read-only"&&D.default_transaction_read_only==="off"||F==="primary"&&D.in_hot_standby==="on"||F==="standby"&&D.in_hot_standby==="off"||F==="prefer-standby"&&D.in_hot_standby==="off"&&Y.host[b0]}function YJ(){let F=new P1([`
|
|
58
69
|
show transaction_read_only;
|
|
59
70
|
select pg_catalog.pg_is_in_recovery()
|
|
60
|
-
`],[],
|
|
71
|
+
`],[],K8,null,{simple:!0});F.resolve=([[D],[l]])=>{f0.default_transaction_read_only=D.transaction_read_only,f0.in_hot_standby=l.pg_is_in_recovery?"on":"off"},F.execute()}function ZJ(F){v&&(v.cursorFn||v.describeFirst)&&i0(C4);let D=h0.postgres(jX(F));v&&v.retried?u1(v.retried):v&&v.prepared&&nU.has(D.routine)?XJ(v,D):u1(D)}function XJ(F,D){delete J1[F.signature],F.retried=D,K8(F)}function _J(F){if(!R)return;let D=9;while(F[D++]!==0);R(F.toString("utf8",9,D-1),F.toString("utf8",D,F.length-1))}async function GJ(){try{let F=await Promise.resolve(v.cursorFn(m));S0=0,F===w8?i0(AJ(v.portal)):(m=new d4,i0($_("",v.cursorRows)))}catch(F){i0(C4),v.reject(F)}}function WJ(){m.count&&v.cursorFn(m),v.resolve(m)}function HJ(){k0=new qX.Writable({autoDestroy:!0,write(F,D,l){T.write(c().d().raw(F).end(),l)},destroy(F,D){D(F),T.write(c().f().str(F+c.N).end()),k0=null},final(F){T.write(c().c().end()),C8=F}}),v.resolve(k0)}function JJ(){k0=new qX.Readable({read(){T.resume()}}),v.resolve(k0)}function $J(){k0=new qX.Duplex({autoDestroy:!0,read(){T.resume()},write(F,D,l){T.write(c().d().raw(F).end(),l)},destroy(F,D){D(F),T.write(c().f().str(F+c.N).end()),k0=null},final(F){T.write(c().c().end()),C8=F}}),v.resolve(k0)}function QJ(F){k0&&(k0.push(F.subarray(5))||T.pause())}function zJ(){k0&&k0.push(null),k0=null}function FJ(F){V?V(jX(F)):console.log(jX(F))}function UJ(){}function OJ(){u1(h0.notSupported("FunctionCallResponse"))}function EJ(){u1(h0.notSupported("NegotiateProtocolVersion"))}function LJ(F){console.error("Postgres.js : Unknown Message:",F[0])}function DJ(F,D){console.error("Postgres.js : Unknown Auth:",D)}function VJ(F,D,l="",W0=""){let q0,s0;return c().B().str(W0+c.N).str(l+c.N).i16(0).i16(F.length),F.forEach((Z1,F4)=>{if(Z1===null)return c.i32(4294967295);s0=D[F4],F[F4]=Z1=s0 in Y.serializers?Y.serializers[s0](Z1):""+Z1,q0=c.i,c.inc(4).str(Z1).i32(c.i-q0-4,q0)}),c.i16(0),c.end()}function J_(F,D,l,W0=""){return c().P().str(W0+c.N).str(F+c.N).i16(D.length),D.forEach((q0,s0)=>c.i32(l[s0]||0)),c.end()}function MJ(F,D=""){return c().D().str(F).str(D+c.N).end()}function $_(F="",D=0){return Buffer.concat([c().E().str(F+c.N).i32(D).end(),QH])}function AJ(F=""){return Buffer.concat([c().C().str("P").str(F+c.N).end(),c().S().end()])}function wJ(){return t||c().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:J,database:z,client_encoding:"UTF8"},Y.connection)).filter(([,F])=>F).map(([F,D])=>F+c.N+D).join(c.N)).z(2).end(0)}}function jX(Y){let Z={},X=5;for(let _=5;_<Y.length-1;_++)if(Y[_]===0)Z[rU[Y[X]]]=Y.toString("utf8",X+1,_),X=_+1;return Z}function zH(Y){return q6.createHash("md5").update(Y).digest("hex")}function lY(Y,Z){return q6.createHmac("sha256",Y).update(Z).digest()}function sU(Y){return q6.createHash("sha256").update(Y).digest()}function aU(Y,Z){let X=Math.max(Y.length,Z.length),_=Buffer.allocUnsafe(X);for(let G=0;G<X;G++)_[G]=Y[G]^Z[G];return _}function PX(Y,Z){if(Z=typeof Z==="function"?Z():Z,!Z)return{cancel:R8,start:R8};let X;return{cancel(){X&&(clearTimeout(X),X=null)},start(){X&&clearTimeout(X),X=setTimeout(_,Z*1000,arguments)}};function _(G){Y.apply(null,G),X=null}}var UH=()=>{};function vX(Y,Z){let X=new Map,_="postgresjs_"+Math.random().toString(36).slice(2),G={},W,H,J=!1,Q=O.sql=Y({...Z,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...Z.connection,replication:"database"},onclose:async function(){if(J)return;H=null,G.pid=G.secret=void 0,L(await V(Q,_,Z.publications)),X.forEach((A)=>A.forEach(({onsubscribe:f})=>f()))},no_subscribe:!0}),$=Q.end,z=Q.close;return Q.end=async()=>{return J=!0,H&&await new Promise((A)=>(H.once("close",A),H.end())),$()},Q.close=async()=>{return H&&await new Promise((A)=>(H.once("close",A),H.end())),z()},O;async function O(A,f,b=UH,k=UH){if(A=YO(A),!W)W=V(Q,_,Z.publications);let g={fn:f,onsubscribe:b},N=X.has(A)?X.get(A).add(g):X.set(A,new Set([g])).get(A),I=()=>{N.delete(g),N.size===0&&X.delete(A)};return W.then((q)=>{return L(q),b(),H&&H.on("error",k),{unsubscribe:I,state:G,sql:Q}})}function L(A){H=A.stream,G.pid=A.state.pid,G.secret=A.state.secret}async function V(A,f,b){if(!b)throw new Error("Missing publication names");let k=await A.unsafe(`CREATE_REPLICATION_SLOT ${f} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[g]=k,N=await A.unsafe(`START_REPLICATION SLOT ${f} LOGICAL ${g.consistent_point} (proto_version '1', publication_names '${b}')`).writable(),I={lsn:Buffer.concat(g.consistent_point.split("/").map((T)=>Buffer.from(("00000000"+T).slice(-8),"hex")))};return N.on("data",K),N.on("error",q),N.on("close",A.close),{stream:N,state:k.state};function q(T){console.error("Unexpected error during logical streaming - reconnecting",T)}function K(T){if(T[0]===119)eU(T.subarray(25),I,A.options.parsers,p,Z.transform);else if(T[0]===107&&T[17])I.lsn=T.subarray(1,9),s()}function p(T,t){let m=t.relation.schema+"."+t.relation.table;R("*",T,t),R("*:"+m,T,t),t.relation.keys.length&&R("*:"+m+"="+t.relation.keys.map((e)=>T[e.name]),T,t),R(t.command,T,t),R(t.command+":"+m,T,t),t.relation.keys.length&&R(t.command+":"+m+"="+t.relation.keys.map((e)=>T[e.name]),T,t)}function s(){let T=Buffer.alloc(34);T[0]=114,T.fill(I.lsn,1),T.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),N.write(T)}}function R(A,f,b){X.has(A)&&X.get(A).forEach(({fn:k})=>k(f,b,A))}}function tU(Y){return new Date(Date.UTC(2000,0,1)+Number(Y/BigInt(1000)))}function eU(Y,Z,X,_,G){let W=(H,[J,Q])=>(H[J.charCodeAt(0)]=Q,H);Object.entries({R:(H)=>{let J=1,Q=Z[H.readUInt32BE(J)]={schema:H.toString("utf8",J+=4,J=H.indexOf(0,J))||"pg_catalog",table:H.toString("utf8",J+1,J=H.indexOf(0,J+1)),columns:Array(H.readUInt16BE(J+=2)),keys:[]};J+=2;let $=0,z;while(J<H.length)z=Q.columns[$++]={key:H[J++],name:G.column.from?G.column.from(H.toString("utf8",J,J=H.indexOf(0,J))):H.toString("utf8",J,J=H.indexOf(0,J)),type:H.readUInt32BE(J+=1),parser:X[H.readUInt32BE(J)],atttypmod:H.readUInt32BE(J+=4)},z.key&&Q.keys.push(z),J+=4},Y:()=>{},O:()=>{},B:(H)=>{Z.date=tU(H.readBigInt64BE(9)),Z.lsn=H.subarray(1,9)},I:(H)=>{let J=1,Q=Z[H.readUInt32BE(J)],{row:$}=iY(H,Q.columns,J+=7,G);_($,{command:"insert",relation:Q})},D:(H)=>{let J=1,Q=Z[H.readUInt32BE(J)];J+=4;let $=H[J]===75;_($||H[J]===79?iY(H,Q.columns,J+=3,G).row:null,{command:"delete",relation:Q,key:$})},U:(H)=>{let J=1,Q=Z[H.readUInt32BE(J)];J+=4;let $=H[J]===75,z=$||H[J]===79?iY(H,Q.columns,J+=3,G):null;z&&(J=z.i);let{row:O}=iY(H,Q.columns,J+3,G);_(O,{command:"update",relation:Q,key:$,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce(W,{})[Y[0]](Y)}function iY(Y,Z,X,_){let G,W,H,J=_.raw?new Array(Z.length):{};for(let Q=0;Q<Z.length;Q++)G=Y[X++],W=Z[Q],H=G===110?null:G===117?void 0:W.parser===void 0?Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X)):W.parser.array===!0?W.parser(Y.toString("utf8",X+5,X+=4+Y.readUInt32BE(X))):W.parser(Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X))),_.raw?J[Q]=_.raw===!0?H:_.value.from?_.value.from(H,W):H:J[W.name]=_.value.from?_.value.from(H,W):H;return{i:X,row:_.row.from?_.row.from(J):J}}function YO(Y){let Z=Y.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!Z)throw new Error("Malformed subscribe pattern: "+Y);let[,X,_,G]=Z;return(X||"*")+(_?":"+(_.indexOf(".")===-1?"public."+_:_):"")+(G?"="+G:"")}import OH from"stream";function xX(Y,Z,X=393216){return new Promise(async(_,G)=>{await Y.begin(async(W)=>{let H;!Z&&([{oid:Z}]=await W`select lo_creat(-1) as oid`);let[{fd:J}]=await W`select lo_open(${Z}, ${X}) as fd`,Q={writable:z,readable:$,close:()=>W`select lo_close(${J})`.then(H),tell:()=>W`select lo_tell64(${J})`,read:(O)=>W`select loread(${J}, ${O}) as data`,write:(O)=>W`select lowrite(${J}, ${O})`,truncate:(O)=>W`select lo_truncate64(${J}, ${O})`,seek:(O,L=0)=>W`select lo_lseek64(${J}, ${O}, ${L})`,size:()=>W`
|
|
61
72
|
select
|
|
62
|
-
lo_lseek64(${
|
|
73
|
+
lo_lseek64(${J}, location, 0) as position,
|
|
63
74
|
seek.size
|
|
64
75
|
from (
|
|
65
76
|
select
|
|
@@ -67,11 +78,11 @@ ${$.trace}`:"No previous disposal trace was found."),W.type){case"atom_family":c
|
|
|
67
78
|
tell.location
|
|
68
79
|
from (select lo_tell64($1) as location) tell
|
|
69
80
|
) seek
|
|
70
|
-
`};return W(G),new Promise(async(M)=>$=M);async function X({highWaterMark:M=16384,start:Q=0,end:V=1/0}={}){let B=V-Q;return Q&&await G.seek(Q),new b5.Readable({highWaterMark:M,async read(K){let v=K>B?K-B:K;B-=K;let[{data:q}]=await G.read(v);if(this.push(q),q.length<K)this.push(null)}})}async function O({highWaterMark:M=16384,start:Q=0}={}){return Q&&await G.seek(Q),new b5.Writable({highWaterMark:M,write(V,B,K){G.write(V).then(()=>K(),K)}})}}).catch(J)})}Object.assign(b1,{PostgresError:AF,toPascal:q0,pascal:F8,toCamel:P0,camel:_8,toKebab:j0,kebab:W8,fromPascal:MW,fromCamel:UW,fromKebab:wW,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var OF=b1;function b1(T,_){let F=v3(T,_),W=F.no_subscribe||X8(b1,{...F}),J=!1,Y=R_(),$=R_(),Z=R_(),G=R_(),X=R_(),O=R_(),M=R_(),Q=R_(),V={connecting:$,reserved:Z,closed:G,ended:X,open:O,busy:M,full:Q},B=[...Array(F.max)].map(()=>Z8(F,V,{onopen:I_,onend:H_,onclose:b0})),K=v(ST);return Object.assign(K,{get parameters(){return F.parameters},largeObject:G8.bind(null,K),subscribe:W,CLOSE:GF,END:GF,PostgresError:AF,options:F,reserve:y,listen:q,begin:u,close:i,end:ZT}),K;function v(L){return L.debug=F.debug,Object.entries(F.types).reduce((n,[YT,NT])=>{return n[YT]=(KT)=>new o_(KT,NT.to),n},o),Object.assign(JT,{types:o,typed:o,unsafe:zT,notify:j,array:t,json:p,file:kT}),JT;function o(n,YT){return new o_(n,YT)}function JT(n,...YT){return n&&Array.isArray(n.raw)?new S_(n,YT,L,D):typeof n==="string"&&!YT.length?new QW(F.transform.column.to?F.transform.column.to(n):n):new P1(n,YT)}function zT(n,YT=[],NT={}){return arguments.length===2&&!Array.isArray(YT)&&(NT=YT,YT=[]),new S_([n],YT,L,D,{prepare:!1,...NT,simple:"simple"in NT?NT.simple:YT.length===0})}function kT(n,YT=[],NT={}){return arguments.length===2&&!Array.isArray(YT)&&(NT=YT,YT=[]),new S_([],YT,(wT)=>{y3.readFile(n,"utf8",(gT,HT)=>{if(gT)return wT.reject(gT);wT.strings=[HT],L(wT)})},D,{...NT,simple:"simple"in NT?NT.simple:YT.length===0})}}async function q(L,o,JT){let zT={fn:o,onlisten:JT},kT=q.sql||(q.sql=b1({...F,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(q.channels).forEach(([wT,{listeners:gT}])=>{delete q.channels[wT],Promise.all(gT.map((HT)=>q(wT,HT.fn,HT.onlisten).catch(()=>{})))})},onnotify(wT,gT){wT in q.channels&&q.channels[wT].listeners.forEach((HT)=>HT.fn(gT))}})),n=q.channels||(q.channels={});if(L in n){n[L].listeners.push(zT);let wT=await n[L].result;return zT.onlisten&&zT.onlisten(),{state:wT.state,unlisten:KT}}n[L]={result:kT`listen ${kT.unsafe('"'+L.replace(/"/g,'""')+'"')}`,listeners:[zT]};let NT=await n[L].result;return zT.onlisten&&zT.onlisten(),{state:NT.state,unlisten:KT};async function KT(){if(L in n===!1)return;if(n[L].listeners=n[L].listeners.filter((wT)=>wT!==zT),n[L].listeners.length)return;return delete n[L],kT`unlisten ${kT.unsafe('"'+L.replace(/"/g,'""')+'"')}`}}async function j(L,o){return await K`select pg_notify(${L}, ${""+o})`}async function y(){let L=R_(),o=O.length?O.shift():await new Promise((kT,n)=>{let YT={reserve:kT,reject:n};Y.push(YT),G.length&&bT(G.shift(),YT)});h(o,Z),o.reserved=()=>L.length?o.execute(L.shift()):h(o,Z),o.reserved.release=!0;let JT=v(zT);return JT.release=()=>{o.reserved=null,I_(o)},JT;function zT(kT){o.queue===Q?L.push(kT):o.execute(kT)||h(o,Q)}}async function u(L,o){!o&&(o=L,L="");let JT=R_(),zT=0,kT,n=null;try{return await K.unsafe("begin "+L.replace(/[^a-z ]/ig,""),[],{onexecute:NT}).execute(),await Promise.race([YT(kT,o),new Promise((KT,wT)=>kT.onclose=wT)])}catch(KT){throw KT}async function YT(KT,wT,gT){let HT=v(fT);HT.savepoint=_0,HT.prepare=(QT)=>n=QT.replace(/[^a-z0-9$-_. ]/gi);let N_,hT;gT&&await HT`savepoint ${HT(gT)}`;try{if(hT=await new Promise((QT,C_)=>{let v_=wT(HT);Promise.resolve(Array.isArray(v_)?Promise.all(v_):v_).then(QT,C_)}),N_)throw N_}catch(QT){throw await(gT?HT`rollback to ${HT(gT)}`:HT`rollback`),QT instanceof AF&&QT.code==="25P02"&&N_||QT}if(!gT)n?await HT`prepare transaction '${HT.unsafe(n)}'`:await HT`commit`;return hT;function _0(QT,C_){if(QT&&Array.isArray(QT.raw))return _0((v_)=>v_.apply(v_,arguments));return arguments.length===1&&(C_=QT,QT=null),YT(KT,C_,"s"+zT+++(QT?"_"+QT:""))}function fT(QT){QT.catch((C_)=>N_||(N_=C_)),KT.queue===Q?JT.push(QT):KT.execute(QT)||h(KT,Q)}}function NT(KT){kT=KT,h(KT,Z),KT.reserved=()=>JT.length?KT.execute(JT.shift()):h(KT,Z)}}function h(L,o){return L.queue.remove(L),o.push(L),L.queue=o,o===O?L.idleTimer.start():L.idleTimer.cancel(),L}function p(L){return new o_(L,3802)}function t(L,o){if(!Array.isArray(L))return t(Array.from(arguments));return new o_(L,o||(L.length?k1(L)||25:0),F.shared.typeArrayMap)}function ST(L){if(J)return L.reject(BT.connection("CONNECTION_ENDED",F,F));if(O.length)return A_(O.shift(),L);if(G.length)return bT(G.shift(),L);M.length?A_(M.shift(),L):Y.push(L)}function A_(L,o){return L.execute(o)?h(L,M):h(L,Q)}function D(L){return new Promise((o,JT)=>{L.state?L.active?Z8(F).cancel(L.state,o,JT):L.cancelled={resolve:o,reject:JT}:(Y.remove(L),L.cancelled=!0,L.reject(BT.generic("57014","canceling statement due to user request")),o())})}async function ZT({timeout:L=null}={}){if(J)return J;await 1;let o;return J=Promise.race([new Promise((JT)=>L!==null&&(o=setTimeout(TT,L*1000,JT))),Promise.all(B.map((JT)=>JT.end()).concat(q.sql?q.sql.end({timeout:0}):[],W.sql?W.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(o))}async function i(){await Promise.all(B.map((L)=>L.end()))}async function TT(L){await Promise.all(B.map((o)=>o.terminate()));while(Y.length)Y.shift().reject(BT.connection("CONNECTION_DESTROYED",F));L()}function bT(L,o){return h(L,$),L.connect(o),L}function H_(L){h(L,X)}function I_(L){if(Y.length===0)return h(L,O);let o=Math.ceil(Y.length/($.length+1)),JT=!0;while(JT&&Y.length&&o-- >0){let zT=Y.shift();if(zT.reserve)return zT.reserve(L);JT=L.execute(zT)}JT?h(L,M):h(L,Q)}function b0(L,o){h(L,G),L.reserved=null,L.onclose&&(L.onclose(o),L.onclose=null),F.onclose&&F.onclose(L.id),Y.length&&bT(L,Y.shift())}}function v3(T,_){if(T&&T.shared)return T;let F=process.env,W=(!T||typeof T==="string"?_:T)||{},{url:J,multihost:Y}=g3(T),$=[...J.searchParams].reduce((Q,[V,B])=>(Q[V]=B,Q),{}),Z=W.hostname||W.host||Y||J.hostname||F.PGHOST||"localhost",G=W.port||J.port||F.PGPORT||5432,X=W.user||W.username||J.username||F.PGUSERNAME||F.PGUSER||m3();W.no_prepare&&(W.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in W&&(console.log("The timeout option is deprecated, use idle_timeout instead"),W.idle_timeout=W.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let O=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],M={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:h3,max_pipeline:100,backoff:b3,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(Z)?Z:Z.split(",").map((Q)=>Q.split(":")[0]),port:Array.isArray(G)?G:Z.split(",").map((Q)=>parseInt(Q.split(":")[1]||G)),path:W.path||Z.indexOf("/")>-1&&Z+"/.s.PGSQL."+G,database:W.database||W.db||(J.pathname||"").slice(1)||F.PGDATABASE||X,user:X,pass:W.pass||W.password||J.password||F.PGPASSWORD||"",...Object.entries(M).reduce((Q,[V,B])=>{let K=V in W?W[V]:(V in $)?$[V]==="disable"||$[V]==="false"?!1:$[V]:F["PG"+V.toUpperCase()]||B;return Q[V]=typeof K==="string"&&O.includes(V)?+K:K,Q},{}),connection:{application_name:F.PGAPPNAME||"postgres.js",...W.connection,...Object.entries($).reduce((Q,[V,B])=>((V in M)||(Q[V]=B),Q),{})},types:W.types||{},target_session_attrs:x3(W,J,F),onnotice:W.onnotice,onnotify:W.onnotify,onclose:W.onclose,onparameter:W.onparameter,socket:W.socket,transform:p3(W.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...N5(W.types)}}function x3(T,_,F){let W=T.target_session_attrs||_.searchParams.get("target_session_attrs")||F.PGTARGETSESSIONATTRS;if(!W||["read-write","read-only","primary","standby","prefer-standby"].includes(W))return W;throw new Error("target_session_attrs "+W+" is not supported")}function b3(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function h3(){return 60*(30+Math.random()*30)}function p3(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function g3(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let _=T;_=_.slice(_.indexOf("://")+3).split(/[?/]/)[0],_=decodeURIComponent(_.slice(_.indexOf("@")+1));let F=new URL(T.replace(_,_.split(",")[0]));return{url:{username:decodeURIComponent(F.username),password:decodeURIComponent(F.password),host:F.host,hostname:F.hostname,port:F.port,pathname:F.pathname,searchParams:F.searchParams},multihost:_.indexOf(",")>-1&&_}}function m3(){try{return j3.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class DT{static[H]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,_){if(_==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(_===MT)return{...T[MT],selectedFields:new Proxy(T[MT].selectedFields,this)};if(typeof _==="symbol")return T[_];let W=(R(T,IT)?T._.selectedFields:R(T,Z_)?T[MT].selectedFields:T)[_];if(R(W,k.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!W.isSelectionField)return W.sql;let J=W.clone();return J.isSelectionField=!0,J}if(R(W,k)){if(this.config.sqlBehavior==="sql")return W;throw new Error(`You tried to reference "${_}" 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(R(W,GT)){if(this.config.alias)return new Proxy(W,new XF(new Proxy(W.table,new YW(this.config.alias,this.config.replaceOriginalName??!1))));return W}if(typeof W!=="object"||W===null)return W;return new Proxy(W,new DT(this.config))}}class h5{constructor(T,_){this.unique=T,this.name=_}static[H]="PgIndexBuilderOn";on(...T){return new h1(T.map((_)=>{if(R(_,k))return _;_=_;let F=new _W(_.name,!!_.keyAsName,_.columnType,_.indexConfig);return _.indexConfig=JSON.parse(JSON.stringify(_.defaultConfig)),F}),this.unique,!1,this.name)}onOnly(...T){return new h1(T.map((_)=>{if(R(_,k))return _;_=_;let F=new _W(_.name,!!_.keyAsName,_.columnType,_.indexConfig);return _.indexConfig=_.defaultConfig,F}),this.unique,!0,this.name)}using(T,..._){return new h1(_.map((F)=>{if(R(F,k))return F;F=F;let W=new _W(F.name,!!F.keyAsName,F.columnType,F.indexConfig);return F.indexConfig=JSON.parse(JSON.stringify(F.defaultConfig)),W}),this.unique,!0,this.name,T)}}class h1{static[H]="PgIndexBuilder";config;constructor(T,_,F,W,J="btree"){this.config={name:W,columns:T,unique:_,only:F,method:J}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new p5(this.config,T)}}class p5{static[H]="PgIndex";config;constructor(T,_){this.config={...T,table:_}}}function A8(T){return new h5(!0,T)}function o3(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((F)=>F.toLowerCase()).join("_")}function u3(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((F,W,J)=>{let Y=J===0?W.toLowerCase():`${W[0].toUpperCase()}${W.slice(1)}`;return F+Y},"")}function c3(T){return T}class H8{static[H]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?o3:T==="camelCase"?u3:c3}getColumnCasing(T){if(!T.keyAsName)return T.name;let _=T.table[I.Symbol.Schema]??"public",F=T.table[I.Symbol.OriginalName],W=`${_}.${F}.${T.name}`;if(!this.cache[W])this.cacheTable(T.table);return this.cache[W]}cacheTable(T){let _=T[I.Symbol.Schema]??"public",F=T[I.Symbol.OriginalName],W=`${_}.${F}`;if(!this.cachedTables[W]){for(let J of Object.values(T[I.Symbol.Columns])){let Y=`${W}.${J.name}`;this.cache[Y]=this.convert(J.name)}this.cachedTables[W]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class EW extends Z_{static[H]="PgViewBase"}class v0{static[H]="PgDialect";casing;constructor(T){this.casing=new H8(T?.casing)}async migrate(T,_,F){let W=typeof F==="string"?"__drizzle_migrations":F.migrationsTable??"__drizzle_migrations",J=typeof F==="string"?"drizzle":F.migrationsSchema??"drizzle",Y=U`
|
|
71
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
81
|
+
`};return _(Q),new Promise(async(O)=>H=O);async function $({highWaterMark:O=16384,start:L=0,end:V=1/0}={}){let R=V-L;return L&&await Q.seek(L),new OH.Readable({highWaterMark:O,async read(A){let f=A>R?A-R:A;R-=A;let[{data:b}]=await Q.read(f);if(this.push(b),b.length<A)this.push(null)}})}async function z({highWaterMark:O=16384,start:L=0}={}){return L&&await Q.seek(L),new OH.Writable({highWaterMark:O,write(V,R,A){Q.write(V).then(()=>A(),A)}})}}).catch(G)})}Object.assign(oY,{PostgresError:N8,toPascal:m4,pascal:CX,toCamel:p4,camel:TX,toKebab:u4,kebab:KX,fromPascal:T6,fromCamel:B6,fromKebab:C6,BigInt:{to:20,from:[20],parse:(Y)=>BigInt(Y),serialize:(Y)=>Y.toString()}});var I8=oY;function oY(Y,Z){let X=_O(Y,Z),_=X.no_subscribe||vX(oY,{...X}),G=!1,W=I1(),H=I1(),J=I1(),Q=I1(),$=I1(),z=I1(),O=I1(),L=I1(),V={connecting:H,reserved:J,closed:Q,ended:$,open:z,busy:O,full:L},R=[...Array(X.max)].map(()=>SX(X,V,{onopen:J1,onend:f0,onclose:s1})),A=f(p);return Object.assign(A,{get parameters(){return X.parameters},largeObject:xX.bind(null,A),subscribe:_,CLOSE:w8,END:w8,PostgresError:N8,options:X,reserve:g,listen:b,begin:N,close:m,end:t}),A;function f(C){return C.debug=X.debug,Object.entries(X.types).reduce((a,[$0,S0])=>{return a[$0]=(C0)=>new r1(C0,S0.to),a},u),Object.assign(G0,{types:u,typed:u,unsafe:T0,notify:k,array:K,json:q,file:b0}),G0;function u(a,$0){return new r1(a,$0)}function G0(a,...$0){return a&&Array.isArray(a.raw)?new P1(a,$0,C,T):typeof a==="string"&&!$0.length?new K6(X.transform.column.to?X.transform.column.to(a):a):new mY(a,$0)}function T0(a,$0=[],S0={}){return arguments.length===2&&!Array.isArray($0)&&(S0=$0,$0=[]),new P1([a],$0,C,T,{prepare:!1,...S0,simple:"simple"in S0?S0.simple:$0.length===0})}function b0(a,$0=[],S0={}){return arguments.length===2&&!Array.isArray($0)&&(S0=$0,$0=[]),new P1([],$0,(w0)=>{XO.readFile(a,"utf8",(n0,D0)=>{if(n0)return w0.reject(n0);w0.strings=[D0],C(w0)})},T,{...S0,simple:"simple"in S0?S0.simple:$0.length===0})}}async function b(C,u,G0){let T0={fn:u,onlisten:G0},b0=b.sql||(b.sql=oY({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(b.channels).forEach(([w0,{listeners:n0}])=>{delete b.channels[w0],Promise.all(n0.map((D0)=>b(w0,D0.fn,D0.onlisten).catch(()=>{})))})},onnotify(w0,n0){w0 in b.channels&&b.channels[w0].listeners.forEach((D0)=>D0.fn(n0))}})),a=b.channels||(b.channels={});if(C in a){a[C].listeners.push(T0);let w0=await a[C].result;return T0.onlisten&&T0.onlisten(),{state:w0.state,unlisten:C0}}a[C]={result:b0`listen ${b0.unsafe('"'+C.replace(/"/g,'""')+'"')}`,listeners:[T0]};let S0=await a[C].result;return T0.onlisten&&T0.onlisten(),{state:S0.state,unlisten:C0};async function C0(){if(C in a===!1)return;if(a[C].listeners=a[C].listeners.filter((w0)=>w0!==T0),a[C].listeners.length)return;return delete a[C],b0`unlisten ${b0.unsafe('"'+C.replace(/"/g,'""')+'"')}`}}async function k(C,u){return await A`select pg_notify(${C}, ${""+u})`}async function g(){let C=I1(),u=z.length?z.shift():await new Promise((b0,a)=>{let $0={reserve:b0,reject:a};W.push($0),Q.length&&U0(Q.shift(),$0)});I(u,J),u.reserved=()=>C.length?u.execute(C.shift()):I(u,J),u.reserved.release=!0;let G0=f(T0);return G0.release=()=>{u.reserved=null,J1(u)},G0;function T0(b0){u.queue===L?C.push(b0):u.execute(b0)||I(u,L)}}async function N(C,u){!u&&(u=C,C="");let G0=I1(),T0=0,b0,a=null;try{return await A.unsafe("begin "+C.replace(/[^a-z ]/ig,""),[],{onexecute:S0}).execute(),await Promise.race([$0(b0,u),new Promise((C0,w0)=>b0.onclose=w0)])}catch(C0){throw C0}async function $0(C0,w0,n0){let D0=f(k0);D0.savepoint=z4,D0.prepare=(N0)=>a=N0.replace(/[^a-z0-9$-_. ]/gi);let S1,l0;n0&&await D0`savepoint ${D0(n0)}`;try{if(l0=await new Promise((N0,v1)=>{let m1=w0(D0);Promise.resolve(Array.isArray(m1)?Promise.all(m1):m1).then(N0,v1)}),S1)throw S1}catch(N0){throw await(n0?D0`rollback to ${D0(n0)}`:D0`rollback`),N0 instanceof N8&&N0.code==="25P02"&&S1||N0}if(!n0)a?await D0`prepare transaction '${D0.unsafe(a)}'`:await D0`commit`;return l0;function z4(N0,v1){if(N0&&Array.isArray(N0.raw))return z4((m1)=>m1.apply(m1,arguments));return arguments.length===1&&(v1=N0,N0=null),$0(C0,v1,"s"+T0+++(N0?"_"+N0:""))}function k0(N0){N0.catch((v1)=>S1||(S1=v1)),C0.queue===L?G0.push(N0):C0.execute(N0)||I(C0,L)}}function S0(C0){b0=C0,I(C0,J),C0.reserved=()=>G0.length?C0.execute(G0.shift()):I(C0,J)}}function I(C,u){return C.queue.remove(C),u.push(C),C.queue=u,u===z?C.idleTimer.start():C.idleTimer.cancel(),C}function q(C){return new r1(C,3802)}function K(C,u){if(!Array.isArray(C))return K(Array.from(arguments));return new r1(C,u||(C.length?yY(C)||25:0),X.shared.typeArrayMap)}function p(C){if(G)return C.reject(h0.connection("CONNECTION_ENDED",X,X));if(z.length)return s(z.shift(),C);if(Q.length)return U0(Q.shift(),C);O.length?s(O.shift(),C):W.push(C)}function s(C,u){return C.execute(u)?I(C,O):I(C,L)}function T(C){return new Promise((u,G0)=>{C.state?C.active?SX(X).cancel(C.state,u,G0):C.cancelled={resolve:u,reject:G0}:(W.remove(C),C.cancelled=!0,C.reject(h0.generic("57014","canceling statement due to user request")),u())})}async function t({timeout:C=null}={}){if(G)return G;await 1;let u;return G=Promise.race([new Promise((G0)=>C!==null&&(u=setTimeout(e,C*1000,G0))),Promise.all(R.map((G0)=>G0.end()).concat(b.sql?b.sql.end({timeout:0}):[],_.sql?_.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(u))}async function m(){await Promise.all(R.map((C)=>C.end()))}async function e(C){await Promise.all(R.map((u)=>u.terminate()));while(W.length)W.shift().reject(h0.connection("CONNECTION_DESTROYED",X));C()}function U0(C,u){return I(C,H),C.connect(u),C}function f0(C){I(C,$)}function J1(C){if(W.length===0)return I(C,z);let u=Math.ceil(W.length/(H.length+1)),G0=!0;while(G0&&W.length&&u-- >0){let T0=W.shift();if(T0.reserve)return T0.reserve(C);G0=C.execute(T0)}G0?I(C,O):I(C,L)}function s1(C,u){I(C,Q),C.reserved=null,C.onclose&&(C.onclose(u),C.onclose=null),X.onclose&&X.onclose(C.id),W.length&&U0(C,W.shift())}}function _O(Y,Z){if(Y&&Y.shared)return Y;let X=process.env,_=(!Y||typeof Y==="string"?Z:Y)||{},{url:G,multihost:W}=$O(Y),H=[...G.searchParams].reduce((L,[V,R])=>(L[V]=R,L),{}),J=_.hostname||_.host||W||G.hostname||X.PGHOST||"localhost",Q=_.port||G.port||X.PGPORT||5432,$=_.user||_.username||G.username||X.PGUSERNAME||X.PGUSER||QO();_.no_prepare&&(_.prepare=!1),H.sslmode&&(H.ssl=H.sslmode,delete H.sslmode),"timeout"in _&&(console.log("The timeout option is deprecated, use idle_timeout instead"),_.idle_timeout=_.timeout),H.sslrootcert==="system"&&(H.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],O={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:HO,max_pipeline:100,backoff:WO,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(J)?J:J.split(",").map((L)=>L.split(":")[0]),port:Array.isArray(Q)?Q:J.split(",").map((L)=>parseInt(L.split(":")[1]||Q)),path:_.path||J.indexOf("/")>-1&&J+"/.s.PGSQL."+Q,database:_.database||_.db||(G.pathname||"").slice(1)||X.PGDATABASE||$,user:$,pass:_.pass||_.password||G.password||X.PGPASSWORD||"",...Object.entries(O).reduce((L,[V,R])=>{let A=V in _?_[V]:(V in H)?H[V]==="disable"||H[V]==="false"?!1:H[V]:X["PG"+V.toUpperCase()]||R;return L[V]=typeof A==="string"&&z.includes(V)?+A:A,L},{}),connection:{application_name:X.PGAPPNAME||"postgres.js",..._.connection,...Object.entries(H).reduce((L,[V,R])=>((V in O)||(L[V]=R),L),{})},types:_.types||{},target_session_attrs:GO(_,G,X),onnotice:_.onnotice,onnotify:_.onnotify,onclose:_.onclose,onparameter:_.onparameter,socket:_.socket,transform:JO(_.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...XH(_.types)}}function GO(Y,Z,X){let _=Y.target_session_attrs||Z.searchParams.get("target_session_attrs")||X.PGTARGETSESSIONATTRS;if(!_||["read-write","read-only","primary","standby","prefer-standby"].includes(_))return _;throw new Error("target_session_attrs "+_+" is not supported")}function WO(Y){return(0.5+Math.random()/2)*Math.min(3**Y/100,20)}function HO(){return 60*(30+Math.random()*30)}function JO(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 $O(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 QO(){try{return ZO.userInfo().username}catch(Y){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class j0{static[U]="SelectionProxyHandler";config;constructor(Y){this.config={...Y}}get(Y,Z){if(Z==="_")return{...Y._,selectedFields:new Proxy(Y._.selectedFields,this)};if(Z===A0)return{...Y[A0],selectedFields:new Proxy(Y[A0].selectedFields,this)};if(typeof Z==="symbol")return Y[Z];let _=(M(Y,P0)?Y._.selectedFields:M(Y,D1)?Y[A0].selectedFields:Y)[Z];if(M(_,x.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!_.isSelectionField)return _.sql;let G=_.clone();return G.isSelectionField=!0,G}if(M(_,x)){if(this.config.sqlBehavior==="sql")return _;throw new Error(`You tried to reference "${Z}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(M(_,E0)){if(this.config.alias)return new Proxy(_,new A8(new Proxy(_.table,new D6(this.config.alias,this.config.replaceOriginalName??!1))));return _}if(typeof _!=="object"||_===null)return _;return new Proxy(_,new j0(this.config))}}class EH{constructor(Y,Z){this.unique=Y,this.name=Z}static[U]="PgIndexBuilderOn";on(...Y){return new nY(Y.map((Z)=>{if(M(Z,x))return Z;Z=Z;let X=new U6(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 nY(Y.map((Z)=>{if(M(Z,x))return Z;Z=Z;let X=new U6(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=Z.defaultConfig,X}),this.unique,!0,this.name)}using(Y,...Z){return new nY(Z.map((X)=>{if(M(X,x))return X;X=X;let _=new U6(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),_}),this.unique,!0,this.name,Y)}}class nY{static[U]="PgIndexBuilder";config;constructor(Y,Z,X,_,G="btree"){this.config={name:_,columns:Y,unique:Z,only:X,method:G}}concurrently(){return this.config.concurrently=!0,this}with(Y){return this.config.with=Y,this}where(Y){return this.config.where=Y,this}build(Y){return new LH(this.config,Y)}}class LH{static[U]="PgIndex";config;constructor(Y,Z){this.config={...Y,table:Z}}}function hX(Y){return new EH(!0,Y)}function zO(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function FO(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,_,G)=>{let W=G===0?_.toLowerCase():`${_[0].toUpperCase()}${_.slice(1)}`;return X+W},"")}function UO(Y){return Y}class fX{static[U]="CasingCache";cache={};cachedTables={};convert;constructor(Y){this.convert=Y==="snake_case"?zO:Y==="camelCase"?FO:UO}getColumnCasing(Y){if(!Y.keyAsName)return Y.name;let Z=Y.table[P.Symbol.Schema]??"public",X=Y.table[P.Symbol.OriginalName],_=`${Z}.${X}.${Y.name}`;if(!this.cache[_])this.cacheTable(Y.table);return this.cache[_]}cacheTable(Y){let Z=Y[P.Symbol.Schema]??"public",X=Y[P.Symbol.OriginalName],_=`${Z}.${X}`;if(!this.cachedTables[_]){for(let G of Object.values(Y[P.Symbol.Columns])){let W=`${_}.${G.name}`;this.cache[W]=this.convert(G.name)}this.cachedTables[_]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class j6 extends D1{static[U]="PgViewBase"}class c4{static[U]="PgDialect";casing;constructor(Y){this.casing=new fX(Y?.casing)}async migrate(Y,Z,X){let _=typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",G=typeof X==="string"?"drizzle":X.migrationsSchema??"drizzle",W=E`
|
|
82
|
+
CREATE TABLE IF NOT EXISTS ${E.identifier(G)}.${E.identifier(_)} (
|
|
72
83
|
id SERIAL PRIMARY KEY,
|
|
73
84
|
hash text NOT NULL,
|
|
74
85
|
created_at bigint
|
|
75
86
|
)
|
|
76
|
-
`;await _.execute(U`CREATE SCHEMA IF NOT EXISTS ${U.identifier(J)}`),await _.execute(Y);let Z=(await _.all(U`select id, hash, created_at from ${U.identifier(J)}.${U.identifier(W)} order by created_at desc limit 1`))[0];await _.transaction(async(G)=>{for await(let X of T)if(!Z||Number(Z.created_at)<X.folderMillis){for(let O of X.sql)await G.execute(U.raw(O));await G.execute(U`insert into ${U.identifier(J)}.${U.identifier(W)} ("hash", "created_at") values(${X.hash}, ${X.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let _=[U`with `];for(let[F,W]of T.entries())if(_.push(U`${U.identifier(W._.alias)} as (${W._.sql})`),F<T.length-1)_.push(U`, `);return _.push(U` `),U.join(_)}buildDeleteQuery({table:T,where:_,returning:F,withList:W}){let J=this.buildWithCTE(W),Y=F?U` returning ${this.buildSelection(F,{isSingleTable:!0})}`:void 0,$=_?U` where ${_}`:void 0;return U`${J}delete from ${T}${$}${Y}`}buildUpdateSet(T,_){let F=T[I.Symbol.Columns],W=Object.keys(F).filter((Y)=>_[Y]!==void 0||F[Y]?.onUpdateFn!==void 0),J=W.length;return U.join(W.flatMap((Y,$)=>{let Z=F[Y],G=_[Y]??U.param(Z.onUpdateFn(),Z),X=U`${U.identifier(this.casing.getColumnCasing(Z))} = ${G}`;if($<J-1)return[X,U.raw(", ")];return[X]}))}buildUpdateQuery({table:T,set:_,where:F,returning:W,withList:J,from:Y,joins:$}){let Z=this.buildWithCTE(J),G=T[vT.Symbol.Name],X=T[vT.Symbol.Schema],O=T[vT.Symbol.OriginalName],M=G===O?void 0:G,Q=U`${X?U`${U.identifier(X)}.`:void 0}${U.identifier(O)}${M&&U` ${U.identifier(M)}`}`,V=this.buildUpdateSet(T,_),B=Y&&U.join([U.raw(" from "),this.buildFromTable(Y)]),K=this.buildJoins($),v=W?U` returning ${this.buildSelection(W,{isSingleTable:!Y})}`:void 0,q=F?U` where ${F}`:void 0;return U`${Z}update ${Q} set ${V}${B}${K}${q}${v}`}buildSelection(T,{isSingleTable:_=!1}={}){let F=T.length,W=T.flatMap(({field:J},Y)=>{let $=[];if(R(J,k.Aliased)&&J.isSelectionField)$.push(U.identifier(J.fieldAlias));else if(R(J,k.Aliased)||R(J,k)){let Z=R(J,k.Aliased)?J.sql:J;if(_)$.push(new k(Z.queryChunks.map((G)=>{if(R(G,S))return U.identifier(this.casing.getColumnCasing(G));return G})));else $.push(Z);if(R(J,k.Aliased))$.push(U` as ${U.identifier(J.fieldAlias)}`)}else if(R(J,GT))if(_)$.push(U.identifier(this.casing.getColumnCasing(J)));else $.push(J);if(Y<F-1)$.push(U`, `);return $});return U.join(W)}buildJoins(T){if(!T||T.length===0)return;let _=[];for(let[F,W]of T.entries()){if(F===0)_.push(U` `);let J=W.table,Y=W.lateral?U` lateral`:void 0,$=W.on?U` on ${W.on}`:void 0;if(R(J,vT)){let Z=J[vT.Symbol.Name],G=J[vT.Symbol.Schema],X=J[vT.Symbol.OriginalName],O=Z===X?void 0:W.alias;_.push(U`${U.raw(W.joinType)} join${Y} ${G?U`${U.identifier(G)}.`:void 0}${U.identifier(X)}${O&&U` ${U.identifier(O)}`}${$}`)}else if(R(J,Z_)){let Z=J[MT].name,G=J[MT].schema,X=J[MT].originalName,O=Z===X?void 0:W.alias;_.push(U`${U.raw(W.joinType)} join${Y} ${G?U`${U.identifier(G)}.`:void 0}${U.identifier(X)}${O&&U` ${U.identifier(O)}`}${$}`)}else _.push(U`${U.raw(W.joinType)} join${Y} ${J}${$}`);if(F<T.length-1)_.push(U` `)}return U.join(_)}buildFromTable(T){if(R(T,I)&&T[I.Symbol.IsAlias]){let _=U`${U.identifier(T[I.Symbol.OriginalName])}`;if(T[I.Symbol.Schema])_=U`${U.identifier(T[I.Symbol.Schema])}.${_}`;return U`${_} ${U.identifier(T[I.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:_,fieldsFlat:F,where:W,having:J,table:Y,joins:$,orderBy:Z,groupBy:G,limit:X,offset:O,lockingClause:M,distinct:Q,setOperators:V}){let B=F??L_(_);for(let TT of B)if(R(TT.field,GT)&&xT(TT.field.table)!==(R(Y,IT)?Y._.alias:R(Y,EW)?Y[MT].name:R(Y,k)?void 0:xT(Y))&&!((bT)=>$?.some(({alias:H_})=>H_===(bT[I.Symbol.IsAlias]?xT(bT):bT[I.Symbol.BaseName])))(TT.field.table)){let bT=xT(TT.field.table);throw new Error(`Your "${TT.path.join("->")}" field references a column "${bT}"."${TT.field.name}", but the table "${bT}" is not part of the query! Did you forget to join it?`)}let K=!$||$.length===0,v=this.buildWithCTE(T),q;if(Q)q=Q===!0?U` distinct`:U` distinct on (${U.join(Q.on,U`, `)})`;let j=this.buildSelection(B,{isSingleTable:K}),y=this.buildFromTable(Y),u=this.buildJoins($),h=W?U` where ${W}`:void 0,p=J?U` having ${J}`:void 0,t;if(Z&&Z.length>0)t=U` order by ${U.join(Z,U`, `)}`;let ST;if(G&&G.length>0)ST=U` group by ${U.join(G,U`, `)}`;let A_=typeof X==="object"||typeof X==="number"&&X>=0?U` limit ${X}`:void 0,D=O?U` offset ${O}`:void 0,ZT=U.empty();if(M){let TT=U` for ${U.raw(M.strength)}`;if(M.config.of)TT.append(U` of ${U.join(Array.isArray(M.config.of)?M.config.of:[M.config.of],U`, `)}`);if(M.config.noWait)TT.append(U` nowait`);else if(M.config.skipLocked)TT.append(U` skip locked`);ZT.append(TT)}let i=U`${v}select${q} ${j} from ${y}${u}${h}${ST}${p}${t}${A_}${D}${ZT}`;if(V.length>0)return this.buildSetOperations(i,V);return i}buildSetOperations(T,_){let[F,...W]=_;if(!F)throw new Error("Cannot pass undefined values to any set operator");if(W.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:F});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:F}),W)}buildSetOperationQuery({leftSelect:T,setOperator:{type:_,isAll:F,rightSelect:W,limit:J,orderBy:Y,offset:$}}){let Z=U`(${T.getSQL()}) `,G=U`(${W.getSQL()})`,X;if(Y&&Y.length>0){let V=[];for(let B of Y)if(R(B,S))V.push(U.identifier(B.name));else if(R(B,k)){for(let K=0;K<B.queryChunks.length;K++){let v=B.queryChunks[K];if(R(v,S))B.queryChunks[K]=U.identifier(v.name)}V.push(U`${B}`)}else V.push(U`${B}`);X=U` order by ${U.join(V,U`, `)} `}let O=typeof J==="object"||typeof J==="number"&&J>=0?U` limit ${J}`:void 0,M=U.raw(`${_} ${F?"all ":""}`),Q=$?U` offset ${$}`:void 0;return U`${Z}${M}${G}${X}${O}${Q}`}buildInsertQuery({table:T,values:_,onConflict:F,returning:W,withList:J,select:Y,overridingSystemValue_:$}){let Z=[],G=T[I.Symbol.Columns],X=Object.entries(G).filter(([v,q])=>!q.shouldDisableInsert()),O=X.map(([,v])=>U.identifier(this.casing.getColumnCasing(v)));if(Y){let v=_;if(R(v,k))Z.push(v);else Z.push(v.getSQL())}else{let v=_;Z.push(U.raw("values "));for(let[q,j]of v.entries()){let y=[];for(let[u,h]of X){let p=j[u];if(p===void 0||R(p,Q_)&&p.value===void 0)if(h.defaultFn!==void 0){let t=h.defaultFn(),ST=R(t,k)?t:U.param(t,h);y.push(ST)}else if(!h.default&&h.onUpdateFn!==void 0){let t=h.onUpdateFn(),ST=R(t,k)?t:U.param(t,h);y.push(ST)}else y.push(U`default`);else y.push(p)}if(Z.push(y),q<v.length-1)Z.push(U`, `)}}let M=this.buildWithCTE(J),Q=U.join(Z),V=W?U` returning ${this.buildSelection(W,{isSingleTable:!0})}`:void 0,B=F?U` on conflict ${F}`:void 0,K=$===!0?U`overriding system value `:void 0;return U`${M}insert into ${T} ${O} ${K}${Q}${B}${V}`}buildRefreshMaterializedViewQuery({view:T,concurrently:_,withNoData:F}){let W=_?U` concurrently`:void 0,J=F?U` with no data`:void 0;return U`refresh materialized view${W} ${T}${J}`}prepareTyping(T){if(R(T,z1)||R(T,E1))return"json";else if(R(T,K1))return"decimal";else if(R(T,V1))return"time";else if(R(T,L1)||R(T,D1))return"timestamp";else if(R(T,Q1)||R(T,R1))return"date";else if(R(T,S1))return"uuid";else return"none"}sqlToQuery(T,_){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:_})}buildRelationalQueryWithoutPK({fullSchema:T,schema:_,tableNamesMap:F,table:W,tableConfig:J,queryConfig:Y,tableAlias:$,nestedQueryRelation:Z,joinOn:G}){let X=[],O,M,Q=[],V,B=[];if(Y===!0)X=Object.entries(J.columns).map(([q,j])=>({dbKey:j.name,tsKey:q,field:m_(j,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let v=Object.fromEntries(Object.entries(J.columns).map(([p,t])=>[p,m_(t,$)]));if(Y.where){let p=typeof Y.where==="function"?Y.where(v,U5()):Y.where;V=p&&$W(p,$)}let q=[],j=[];if(Y.columns){let p=!1;for(let[t,ST]of Object.entries(Y.columns)){if(ST===void 0)continue;if(t in J.columns){if(!p&&ST===!0)p=!0;j.push(t)}}if(j.length>0)j=p?j.filter((t)=>Y.columns?.[t]===!0):Object.keys(J.columns).filter((t)=>!j.includes(t))}else j=Object.keys(J.columns);for(let p of j){let t=J.columns[p];q.push({tsKey:p,value:t})}let y=[];if(Y.with)y=Object.entries(Y.with).filter((p)=>!!p[1]).map(([p,t])=>({tsKey:p,queryConfig:t,relation:J.relations[p]}));let u;if(Y.extras){u=typeof Y.extras==="function"?Y.extras(v,{sql:U}):Y.extras;for(let[p,t]of Object.entries(u))q.push({tsKey:p,value:p2(t,$)})}for(let{tsKey:p,value:t}of q)X.push({dbKey:R(t,k.Aliased)?t.fieldAlias:J.columns[p].name,tsKey:p,field:R(t,GT)?m_(t,$):t,relationTableTsKey:void 0,isJson:!1,selection:[]});let h=typeof Y.orderBy==="function"?Y.orderBy(v,M5()):Y.orderBy??[];if(!Array.isArray(h))h=[h];Q=h.map((p)=>{if(R(p,GT))return m_(p,$);return $W(p,$)}),O=Y.limit,M=Y.offset;for(let{tsKey:p,queryConfig:t,relation:ST}of y){let A_=Q5(_,F,ST),D=f0(ST.referencedTable),ZT=F[D],i=`${$}_${p}`,TT=HW(...A_.fields.map((I_,b0)=>I1(m_(A_.references[b0],i),m_(I_,$)))),bT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:_,tableNamesMap:F,table:T[ZT],tableConfig:_[ZT],queryConfig:R(ST,K0)?t===!0?{limit:1}:{...t,limit:1}:t,tableAlias:i,joinOn:TT,nestedQueryRelation:ST}),H_=U`${U.identifier(i)}.${U.identifier("data")}`.as(p);B.push({on:U`true`,table:new IT(bT.sql,{},i),alias:i,joinType:"left",lateral:!0}),X.push({dbKey:p,tsKey:p,field:H_,relationTableTsKey:ZT,isJson:!0,selection:bT.selection})}}if(X.length===0)throw new M1({message:`No fields selected for table "${J.tsName}" ("${$}")`});let K;if(V=HW(G,V),Z){let v=U`json_build_array(${U.join(X.map(({field:y,tsKey:u,isJson:h})=>h?U`${U.identifier(`${$}_${u}`)}.${U.identifier("data")}`:R(y,k.Aliased)?y.sql:y),U`, `)})`;if(R(Z,OW))v=U`coalesce(json_agg(${v}${Q.length>0?U` order by ${U.join(Q,U`, `)}`:void 0}), '[]'::json)`;let q=[{dbKey:"data",tsKey:"data",field:v.as("data"),isJson:!0,relationTableTsKey:J.tsName,selection:X}];if(O!==void 0||M!==void 0||Q.length>0)K=this.buildSelectQuery({table:U1(W,$),fields:{},fieldsFlat:[{path:[],field:U.raw("*")}],where:V,limit:O,offset:M,orderBy:Q,setOperators:[]}),V=void 0,O=void 0,M=void 0,Q=[];else K=U1(W,$);K=this.buildSelectQuery({table:R(K,vT)?K:new IT(K,{},$),fields:{},fieldsFlat:q.map(({field:y})=>({path:[],field:R(y,GT)?m_(y,$):y})),joins:B,where:V,limit:O,offset:M,orderBy:Q,setOperators:[]})}else K=this.buildSelectQuery({table:U1(W,$),fields:{},fieldsFlat:X.map(({field:v})=>({path:[],field:R(v,GT)?m_(v,$):v})),joins:B,where:V,limit:O,offset:M,orderBy:Q,setOperators:[]});return{tableTsKey:J.tsName,sql:K,selection:X}}}class O8{static[H]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class eT{static[H]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let _=!!this.fields,F=T,W;if(this.fields)W=this.fields;else if(R(F,IT))W=Object.fromEntries(Object.keys(F._.selectedFields).map((J)=>[J,F[J]]));else if(R(F,EW))W=F[MT].selectedFields;else if(R(F,k))W={};else W=d$(F);return new U8({table:F,fields:W,isPartialSelect:_,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class g5 extends O8{static[H]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:T,fields:_,isPartialSelect:F,session:W,dialect:J,withList:Y,distinct:$}){super();this.config={withList:Y,table:T,fields:{..._},distinct:$,setOperators:[]},this.isPartialSelect=F,this.session=W,this.dialect=J,this._={selectedFields:_,config:this.config},this.tableName=a_(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let Z of y_(T))this.usedTables.add(Z)}getUsedTables(){return[...this.usedTables]}createJoin(T,_){return(F,W)=>{let J=this.tableName,Y=a_(F);for(let $ of y_(F))this.usedTables.add($);if(typeof Y==="string"&&this.config.joins?.some(($)=>$.alias===Y))throw new Error(`Alias "${Y}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof J==="string")this.config.fields={[J]:this.config.fields};if(typeof Y==="string"&&!R(F,k)){let $=R(F,IT)?F._.selectedFields:R(F,Z_)?F[MT].selectedFields:F[I.Symbol.Columns];this.config.fields[Y]=$}}if(typeof W==="function")W=W(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:W,table:F,joinType:T,alias:Y,lateral:_}),typeof Y==="string")switch(T){case"left":{this.joinsNotNullableMap[Y]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[Y]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[Y]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[Y]=!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(T,_){return(F)=>{let W=typeof F==="function"?F(d3()):F;if(!ZW(this.getSelectedFields(),W.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:_,rightSelect:W}),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(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let _=T[0](new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(_)?_:[_]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let _=T[0](new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),F=Array.isArray(_)?_:[_];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=F;else this.config.orderBy=F}else{let _=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=_;else this.config.orderBy=_}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,_={}){return this.config.lockingClause={strength:T,config:_},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}as(T){let _=[];if(_.push(...y_(this.config.table)),this.config.joins)for(let F of this.config.joins)_.push(...y_(F.table));return new Proxy(new IT(this.getSQL(),this.config.fields,T,!1,[...new Set(_)]),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new DT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(T){return this.cacheConfig=T===void 0?{config:{},enable:!0,autoInvalidate:!0}:T===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...T},this}}class U8 extends g5{static[H]="PgSelect";_prepare(T){let{session:_,config:F,dialect:W,joinsNotNullableMap:J,authToken:Y,cacheConfig:$,usedTables:Z}=this;if(!_)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:G}=F;return AT.startActiveSpan("drizzle.prepareQuery",()=>{let X=L_(G),O=_.prepareQuery(W.sqlToQuery(this.getSQL()),X,T,!0,void 0,{type:"select",tables:[...Z]},$);return O.joinsNotNullableMap=J,O.setToken(Y)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}c$(U8,[aT]);function UF(T,_){return(F,W,...J)=>{let Y=[W,...J].map(($)=>({type:T,isAll:_,rightSelect:$}));for(let $ of Y)if(!ZW(F.getSelectedFields(),$.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return F.addSetOperators(Y)}}var d3=()=>({union:l3,unionAll:t3,intersect:i3,intersectAll:n3,except:r3,exceptAll:s3}),l3=UF("union",!1),t3=UF("union",!0),i3=UF("intersect",!1),n3=UF("intersect",!0),r3=UF("except",!1),s3=UF("except",!0);class zW{static[H]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=R(T,v0)?T:void 0,this.dialectConfig=R(T,v0)?void 0:T}$with=(T,_)=>{let F=this;return{as:(J)=>{if(typeof J==="function")J=J(F);return new Proxy(new WW(J.getSQL(),_??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let _=this;function F(Y){return new eT({fields:Y??void 0,session:void 0,dialect:_.getDialect(),withList:T})}function W(Y){return new eT({fields:Y??void 0,session:void 0,dialect:_.getDialect(),distinct:!0})}function J(Y,$){return new eT({fields:$??void 0,session:void 0,dialect:_.getDialect(),distinct:{on:Y}})}return{select:F,selectDistinct:W,selectDistinctOn:J}}select(T){return new eT({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new eT({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,_){return new eT({fields:_??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new v0(this.dialectConfig);return this.dialect}}function y_(T){if(R(T,vT))return[T[k0]?`${T[k0]}.${T[I.Symbol.BaseName]}`:T[I.Symbol.BaseName]];if(R(T,IT))return T._.usedTables??[];if(R(T,k))return T.usedTables??[];return[]}class p1 extends aT{constructor(T,_,F,W){super();this.session=_,this.dialect=F,this.config={table:T,withList:W}}static[H]="PgDelete";config;cacheConfig;where(T){return this.config.where=T,this}returning(T=this.config.table[I.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=L_(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"delete",tables:y_(this.config.table)},this.cacheConfig)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class g1{constructor(T,_,F,W,J){this.table=T,this.session=_,this.dialect=F,this.withList=W,this.overridingSystemValue_=J}static[H]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let _=T.map((F)=>{let W={},J=this.table[I.Symbol.Columns];for(let Y of Object.keys(F)){let $=F[Y];W[Y]=R($,k)?$:new Q_($,J[Y])}return W});return new M8(this.table,_,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let _=typeof T==="function"?T(new zW):T;if(!R(_,k)&&!ZW(this.table[H1],_._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new M8(this.table,_,this.session,this.dialect,this.withList,!0)}}class M8 extends aT{constructor(T,_,F,W,J,Y,$){super();this.session=F,this.dialect=W,this.config={table:T,values:_,withList:J,select:Y,overridingSystemValue_:$}}static[H]="PgInsert";config;cacheConfig;returning(T=this.config.table[I.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=L_(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=U`do nothing`;else{let _="";_=Array.isArray(T.target)?T.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let F=T.where?U` where ${T.where}`:void 0;this.config.onConflict=U`(${U.raw(_)})${F} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let _=T.where?U` where ${T.where}`:void 0,F=T.targetWhere?U` where ${T.targetWhere}`:void 0,W=T.setWhere?U` where ${T.setWhere}`:void 0,J=this.dialect.buildUpdateSet(this.config.table,w1(this.config.table,T.set)),Y="";return Y=Array.isArray(T.target)?T.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=U`(${U.raw(Y)})${F} do update set ${J}${_}${W}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"insert",tables:y_(this.config.table)},this.cacheConfig)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class w8 extends aT{constructor(T,_,F){super();this.session=_,this.dialect=F,this.config={view:T}}static[H]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class m1{constructor(T,_,F,W){this.table=T,this.session=_,this.dialect=F,this.withList=W}static[H]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new m5(this.table,w1(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class m5 extends aT{constructor(T,_,F,W,J){super();this.session=F,this.dialect=W,this.config={set:_,table:T,withList:J,joins:[]},this.tableName=a_(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[H]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(T){let _=T,F=a_(_);if(typeof F==="string")this.joinsNotNullableMap[F]=!0;return this.config.from=_,this}getTableLikeFields(T){if(R(T,vT))return T[I.Symbol.Columns];else if(R(T,IT))return T._.selectedFields;return T[MT].selectedFields}createJoin(T){return(_,F)=>{let W=a_(_);if(typeof W==="string"&&this.config.joins.some((J)=>J.alias===W))throw new Error(`Alias "${W}" is already used in this query`);if(typeof F==="function"){let J=this.config.from&&!R(this.config.from,k)?this.getTableLikeFields(this.config.from):void 0;F=F(new Proxy(this.config.table[I.Symbol.Columns],new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),J&&new Proxy(J,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:F,table:_,joinType:T,alias:W}),typeof W==="string")switch(T){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!0;break}case"inner":{this.joinsNotNullableMap[W]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[I.Symbol.Columns]),this.config.from){let _=a_(this.config.from);if(typeof _==="string"&&this.config.from&&!R(this.config.from,k)){let F=this.getTableLikeFields(this.config.from);T[_]=F}for(let F of this.config.joins){let W=a_(F.table);if(typeof W==="string"&&!R(F.table,k)){let J=this.getTableLikeFields(F.table);T[W]=J}}}}return this.config.returningFields=T,this.config.returning=L_(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){let _=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"insert",tables:y_(this.config.table)},this.cacheConfig);return _.joinsNotNullableMap=this.joinsNotNullableMap,_}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class KW extends k{constructor(T){super(KW.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=KW.buildCount(T.source,T.filters)}sql;token;static[H]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,_){return U`(select count(*) from ${T}${U.raw(" where ").if(_)}${_})`}static buildCount(T,_){return U`select count(*) as count from ${T}${U.raw(" where ").if(_)}${_};`}setToken(T){return this.token=T,this}then(T,_){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,_)}catch(T){return this.then(void 0,T)}finally(T){return this.then((_)=>{return T?.(),_},(_)=>{throw T?.(),_})}}class R8{constructor(T,_,F,W,J,Y,$){this.fullSchema=T,this.schema=_,this.tableNamesMap=F,this.table=W,this.tableConfig=J,this.dialect=Y,this.session=$}static[H]="PgRelationalQueryBuilder";findMany(T){return new Q8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new Q8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class Q8 extends aT{constructor(T,_,F,W,J,Y,$,Z,G){super();this.fullSchema=T,this.schema=_,this.tableNamesMap=F,this.table=W,this.tableConfig=J,this.dialect=Y,this.session=$,this.config=Z,this.mode=G}static[H]="PgRelationalQuery";_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:_,builtQuery:F}=this._toSQL();return this.session.prepareQuery(F,void 0,T,!0,(W,J)=>{let Y=W.map(($)=>N1(this.schema,this.tableConfig,$,_.selection,J));if(this.mode==="first")return Y[0];return Y})})}prepare(T){return this._prepare(T)}_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 T=this._getQuery(),_=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:_}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class E8 extends aT{constructor(T,_,F,W){super();this.execute=T,this.sql=_,this.query=F,this.mapBatchResult=W}static[H]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,_){return _?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class VW{constructor(T,_,F){if(this.dialect=T,this.session=_,this._=F?{schema:F.schema,fullSchema:F.fullSchema,tableNamesMap:F.tableNamesMap,session:_}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:_},this.query={},this._.schema)for(let[W,J]of Object.entries(this._.schema))this.query[W]=new R8(F.fullSchema,this._.schema,this._.tableNamesMap,F.fullSchema[W],J,T,_);this.$cache={invalidate:async(W)=>{}}}static[H]="PgDatabase";query;$with=(T,_)=>{let F=this;return{as:(J)=>{if(typeof J==="function")J=J(new zW(F.dialect));return new Proxy(new WW(J.getSQL(),_??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,_){return new KW({source:T,filters:_,session:this.session})}$cache;with(...T){let _=this;function F(G){return new eT({fields:G??void 0,session:_.session,dialect:_.dialect,withList:T})}function W(G){return new eT({fields:G??void 0,session:_.session,dialect:_.dialect,withList:T,distinct:!0})}function J(G,X){return new eT({fields:X??void 0,session:_.session,dialect:_.dialect,withList:T,distinct:{on:G}})}function Y(G){return new m1(G,_.session,_.dialect,T)}function $(G){return new g1(G,_.session,_.dialect,T)}function Z(G){return new p1(G,_.session,_.dialect,T)}return{select:F,selectDistinct:W,selectDistinctOn:J,update:Y,insert:$,delete:Z}}select(T){return new eT({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new eT({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,_){return new eT({fields:_??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new m1(T,this.session,this.dialect)}insert(T){return new g1(T,this.session,this.dialect)}delete(T){return new p1(T,this.session,this.dialect)}refreshMaterializedView(T){return new w8(T,this.session,this.dialect)}authToken;execute(T){let _=typeof T==="string"?U.raw(T):T.getSQL(),F=this.dialect.sqlToQuery(_),W=this.session.prepareQuery(F,void 0,void 0,!1);return new E8(()=>W.execute(void 0,this.authToken),_,F,(J)=>W.mapResult(J,!0))}transaction(T,_){return this.session.transaction(T,_)}}class o5{static[H]="Cache"}class LW extends o5{strategy(){return"all"}static[H]="NoopCache";async get(T){return}async put(T,_,F,W){}async onMutate(T){}}async function z8(T,_){let F=`${T}-${JSON.stringify(_)}`,J=new TextEncoder().encode(F),Y=await crypto.subtle.digest("SHA-256",J);return[...new Uint8Array(Y)].map((G)=>G.toString(16).padStart(2,"0")).join("")}class T0 extends Error{constructor(T,_,F){super(`Failed query: ${T}
|
|
77
|
-
params: ${_}`);if(this.query=T,this.params=_,this.cause=F,Error.captureStackTrace(this,T0),F)this.cause=F}}class K8{constructor(T,_,F,W){if(this.query=T,this.cache=_,this.queryMetadata=F,this.cacheConfig=W,_&&_.strategy()==="all"&&W===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(T,_){return T}setToken(T){return this.authToken=T,this}static[H]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(T,_,F){if(this.cache===void 0||R(this.cache,LW)||this.queryMetadata===void 0)try{return await F()}catch(W){throw new T0(T,_,W)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await F()}catch(W){throw new T0(T,_,W)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[W]=await Promise.all([F(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return W}catch(W){throw new T0(T,_,W)}if(!this.cacheConfig)try{return await F()}catch(W){throw new T0(T,_,W)}if(this.queryMetadata.type==="select"){let W=await this.cache.get(this.cacheConfig.tag??await z8(T,_),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(W===void 0){let J;try{J=await F()}catch(Y){throw new T0(T,_,Y)}return await this.cache.put(this.cacheConfig.tag??await z8(T,_),J,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),J}return W}try{return await F()}catch(W){throw new T0(T,_,W)}}}class V8{constructor(T){this.dialect=T}static[H]="PgSession";execute(T,_){return AT.startActiveSpan("drizzle.operation",()=>{return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(_).execute(void 0,_)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,_){let F=await this.execute(T,_);return Number(F[0].count)}}class L8 extends VW{constructor(T,_,F,W=0){super(T,_,F);this.schema=F,this.nestedIndex=W}static[H]="PgTransaction";rollback(){throw new g2}getTransactionConfigSQL(T){let _=[];if(T.isolationLevel)_.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)_.push(T.accessMode);if(typeof T.deferrable==="boolean")_.push(T.deferrable?"deferrable":"not deferrable");return U.raw(_.join(" "))}setTransaction(T){return this.session.execute(U`set transaction ${this.getTransactionConfigSQL(T)}`)}}class u5 extends K8{constructor(T,_,F,W,J,Y,$,Z,G,X){super({sql:_,params:F},J,Y,$);this.client=T,this.queryString=_,this.params=F,this.logger=W,this.fields=Z,this._isResponseInArrayMode=G,this.customResultMapper=X}static[H]="PostgresJsPreparedQuery";async execute(T={}){return AT.startActiveSpan("drizzle.execute",async(_)=>{let F=h2(this.params,T);_?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F);let{fields:W,queryString:J,client:Y,joinsNotNullableMap:$,customResultMapper:Z}=this;if(!W&&!Z)return AT.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(J,F,async()=>{return await Y.unsafe(J,F)})});let G=await AT.startActiveSpan("drizzle.driver.execute",()=>{return _?.setAttributes({"drizzle.query.text":J,"drizzle.query.params":JSON.stringify(F)}),this.queryWithCache(J,F,async()=>{return await Y.unsafe(J,F).values()})});return AT.startActiveSpan("drizzle.mapResponse",()=>{return Z?Z(G):G.map((X)=>u$(W,X,$))})})}all(T={}){return AT.startActiveSpan("drizzle.execute",async(_)=>{let F=h2(this.params,T);return _?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F),AT.startActiveSpan("drizzle.driver.execute",()=>{return _?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.queryWithCache(this.queryString,F,async()=>{return this.client.unsafe(this.queryString,F)})})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class DW extends V8{constructor(T,_,F,W={}){super(_);this.client=T,this.schema=F,this.options=W,this.logger=W.logger??new o2,this.cache=W.cache??new LW}static[H]="PostgresJsSession";logger;cache;prepareQuery(T,_,F,W,J,Y,$){return new u5(this.client,T.sql,T.params,this.logger,this.cache,Y,$,_,W,J)}query(T,_){return this.logger.logQuery(T,_),this.client.unsafe(T,_).values()}queryObjects(T,_){return this.client.unsafe(T,_)}transaction(T,_){return this.client.begin(async(F)=>{let W=new DW(F,this.dialect,this.schema,this.options),J=new D8(this.dialect,W,this.schema);if(_)await J.setTransaction(_);return T(J)})}}class D8 extends L8{constructor(T,_,F,W=0){super(T,_,F,W);this.session=_}static[H]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((_)=>{let F=new DW(_,this.dialect,this.schema,this.session.options),W=new D8(this.dialect,F,this.schema);return T(W)})}}class c5 extends VW{static[H]="PostgresJsDatabase"}function MF(T,_={}){let F=(G)=>G;for(let G of["1184","1082","1083","1114","1182","1185","1115","1231"])T.options.parsers[G]=F,T.options.serializers[G]=F;T.options.serializers["114"]=F,T.options.serializers["3802"]=F;let W=new v0({casing:_.casing}),J;if(_.logger===!0)J=new m2;else if(_.logger!==!1)J=_.logger;let Y;if(_.schema){let G=w5(_.schema,R5);Y={fullSchema:_.schema,schema:G.tables,tableNamesMap:G.tableNamesMap}}let $=new DW(T,W,Y,{logger:J,cache:_.cache}),Z=new c5(W,$,Y);if(Z.$client=T,Z.$cache=_.cache,Z.$cache)Z.$cache.invalidate=_.cache?.onMutate;return Z}function o1(...T){if(typeof T[0]==="string"){let _=OF(T[0]);return MF(_,T[1])}if(l$(T[0])){let{connection:_,client:F,...W}=T[0];if(F)return MF(F,W);if(typeof _==="object"&&_.url!==void 0){let{url:Y,...$}=_,Z=OF(Y,$);return MF(Z,W)}let J=OF(_);return MF(J,W)}return MF(T[0],T[1])}((T)=>{function _(F){return MF({options:{parsers:{},serializers:{}}},F)}T.mock=_})(o1||(o1={}));var I8={};nG(I8,{users:()=>x0,untrackedUserColumnNames:()=>a3,twoFactorMethod:()=>n5,trackedUserColumnName:()=>e3,trackableUserColumnNames:()=>t5,signInHistory:()=>_O,role:()=>l5,players:()=>S8,passwordResetAttempts:()=>FO,games:()=>c1,banishedIps:()=>WO,accountActions:()=>TO,accountAction:()=>i5});function L0(){return dT({length:24}).$type()}function d5(T){return U`lower(${T})`}var u1=U`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,l5=FW("role",["admin","user"]),x0=z0("users",{id:D_().primaryKey().defaultRandom(),username:dT({length:16}).notNull(),emailOffered:dT({length:254}).notNull(),emailVerified:dT({length:254}),password:dT({length:254}),createdAtIso:L0().notNull().default(u1),createdIp:dT({length:45}).notNull(),isActive:XW().notNull().default(!1),verifiedAtIso:L0(),userRole:l5().default("user")},(T)=>[A8("usernameUniqueIndex").on(d5(T.username)),A8("emailVerifiedUniqueIndex").on(d5(T.emailVerified))]),a3=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],t5=["username","emailOffered","emailVerified","password","userRole"],e3=FW("trackedUserColumnName",t5),i5=FW("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),TO=z0("accountActions",{userId:D_().references(()=>x0.id).primaryKey(),action:i5().notNull(),code:dT({length:254}).notNull(),wrongCodeCount:GW().notNull().default(0),expiresAtIso:L0().notNull()}),c1=z0("games",{id:D_().primaryKey().defaultRandom()}),S8=z0("players",{userId:D_().notNull().references(()=>x0.id,{onDelete:"cascade"}),gameId:D_().notNull().references(()=>c1.id,{onDelete:"cascade"}),score:GW().notNull()},(T)=>[uX({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),_O=z0("signInHistory",{id:D_().primaryKey().defaultRandom(),userId:D_().references(()=>x0.id,{onDelete:"cascade"}),signInTimeIso:L0().notNull().default(u1),ipAddress:dT({length:45}).notNull(),userAgent:dT({length:1024}),successful:XW().notNull().default(!1)}),n5=FW("twoFactorMethod",["email","phone"]),FO=z0("passwordResetAttempts",{id:D_().primaryKey().defaultRandom(),userId:D_().notNull().references(()=>x0.id,{onDelete:"cascade"}),requestedIp:dT({length:45}).notNull(),requestedAtIso:L0().notNull().default(u1),succeededIp:dT({length:45}),succeededAtIso:L0(),verificationMethod:n5().notNull()}),WO=z0("banishedIps",{ip:dT({length:45}).primaryKey(),reason:dT({length:2048}).notNull(),banishedAtIso:L0().notNull().default(u1),banishedUntilIso:L0()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class N8{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(JO.resolve(__dirname,"notify_update.sql"));let T=[xT(x0),xT(c1),xT(S8)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(_)=>{let F=_.split(","),W=F[0],J=F[1],Y=`${W}("${J}")`;if(this.observers.has(Y))this.observers.get(Y).next(Y)})}constructor(T=!1,_={host:q_.POSTGRES_HOST,port:q_.POSTGRES_PORT,user:q_.POSTGRES_USER,password:q_.POSTGRES_PASSWORD,database:q_.POSTGRES_DATABASE}){this.options=_,this.sql=OF(_),this.drizzle=o1(this.sql,{schema:I8,logger:T})}observe(T,_){if(!this.observers.has(T))this.observers.set(T,new FT);this.observers.get(T).subscribe("SINGLETON",_)}}var d1={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 YO(T){return Number.parseInt(T,10)}var $O=Y_(d1),ZO=$O.keyof().pipe((T)=>YO(T)),r5=Y_([ZO,"string"]);var B8=new N2,{logger:G_}=B8;Object.assign(console,G_,{log:G_.info});G_.info("ready");var C8=a5(import.meta.dir,"..","app"),sy=new N8({logQuery(T,_){G_.info("\uD83D\uDCDD query",T,_)}});HO({hostname:"0.0.0.0",port:q_.FRONTEND_PORT??3333,...X1??void 0,async fetch(T){try{let _=new Date,F=new URL(T.url);if(G_.info(T.method,F.pathname),F.pathname==="/")return new Response(Bun.file(a5(C8,"index.html")));if(F.pathname==="/index.html")return Response.redirect("/");let W=GO(C8,F.pathname),J=AO(W);if(!J.startsWith(C8))throw[403,"Access Denied"];if(!await s5(J).exists())return Response.redirect("/");return new Response(s5(J))}catch(_){let F=r5(_);if(F instanceof Y_.errors===!1){let[W,J]=F,$=`${d1[W]}. ${J}`;return G_.info(`\u274C ${W}: ${$}`),new Response($,{status:W})}if(_ instanceof Error)G_.error(_.message);else{let W=E$(_);G_.error("frontend server threw",W)}return new Response(d1[500],{status:500})}}});function l1(){G_.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{G_.info("\u2757 received SIGINT; exiting gracefully"),l1()});process.on("SIGTERM",()=>{G_.info("\u2757 received SIGTERM; exiting gracefully"),l1()});process.on("exit",()=>{G_.info("\u2757 received exit; exiting gracefully"),l1()});B8.on("timeToStop",()=>{G_.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),l1()});var{version:OO}=await Bun.file(XO.resolve(import.meta.dir,"../package.json")).json();G_.info(`\uD83D\uDEEB frontend v${OO} running at http://localhost:${q_.FRONTEND_PORT}/`);B8.emit("alive");
|
|
87
|
+
`;await Z.execute(E`CREATE SCHEMA IF NOT EXISTS ${E.identifier(G)}`),await Z.execute(W);let J=(await Z.all(E`select id, hash, created_at from ${E.identifier(G)}.${E.identifier(_)} order by created_at desc limit 1`))[0];await Z.transaction(async(Q)=>{for await(let $ of Y)if(!J||Number(J.created_at)<$.folderMillis){for(let z of $.sql)await Q.execute(E.raw(z));await Q.execute(E`insert into ${E.identifier(G)}.${E.identifier(_)} ("hash", "created_at") values(${$.hash}, ${$.folderMillis})`)}})}escapeName(Y){return`"${Y}"`}escapeParam(Y){return`$${Y+1}`}escapeString(Y){return`'${Y.replace(/'/g,"''")}'`}buildWithCTE(Y){if(!Y?.length)return;let Z=[E`with `];for(let[X,_]of Y.entries())if(Z.push(E`${E.identifier(_._.alias)} as (${_._.sql})`),X<Y.length-1)Z.push(E`, `);return Z.push(E` `),E.join(Z)}buildDeleteQuery({table:Y,where:Z,returning:X,withList:_}){let G=this.buildWithCTE(_),W=X?E` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,H=Z?E` where ${Z}`:void 0;return E`${G}delete from ${Y}${H}${W}`}buildUpdateSet(Y,Z){let X=Y[P.Symbol.Columns],_=Object.keys(X).filter((W)=>Z[W]!==void 0||X[W]?.onUpdateFn!==void 0),G=_.length;return E.join(_.flatMap((W,H)=>{let J=X[W],Q=Z[W]??E.param(J.onUpdateFn(),J),$=E`${E.identifier(this.casing.getColumnCasing(J))} = ${Q}`;if(H<G-1)return[$,E.raw(", ")];return[$]}))}buildUpdateQuery({table:Y,set:Z,where:X,returning:_,withList:G,from:W,joins:H}){let J=this.buildWithCTE(G),Q=Y[d0.Symbol.Name],$=Y[d0.Symbol.Schema],z=Y[d0.Symbol.OriginalName],O=Q===z?void 0:Q,L=E`${$?E`${E.identifier($)}.`:void 0}${E.identifier(z)}${O&&E` ${E.identifier(O)}`}`,V=this.buildUpdateSet(Y,Z),R=W&&E.join([E.raw(" from "),this.buildFromTable(W)]),A=this.buildJoins(H),f=_?E` returning ${this.buildSelection(_,{isSingleTable:!W})}`:void 0,b=X?E` where ${X}`:void 0;return E`${J}update ${L} set ${V}${R}${A}${b}${f}`}buildSelection(Y,{isSingleTable:Z=!1}={}){let X=Y.length,_=Y.flatMap(({field:G},W)=>{let H=[];if(M(G,x.Aliased)&&G.isSelectionField)H.push(E.identifier(G.fieldAlias));else if(M(G,x.Aliased)||M(G,x)){let J=M(G,x.Aliased)?G.sql:G;if(Z)H.push(new x(J.queryChunks.map((Q)=>{if(M(Q,j))return E.identifier(this.casing.getColumnCasing(Q));return Q})));else H.push(J);if(M(G,x.Aliased))H.push(E` as ${E.identifier(G.fieldAlias)}`)}else if(M(G,E0))if(Z)H.push(E.identifier(this.casing.getColumnCasing(G)));else H.push(G);if(W<X-1)H.push(E`, `);return H});return E.join(_)}buildJoins(Y){if(!Y||Y.length===0)return;let Z=[];for(let[X,_]of Y.entries()){if(X===0)Z.push(E` `);let G=_.table,W=_.lateral?E` lateral`:void 0,H=_.on?E` on ${_.on}`:void 0;if(M(G,d0)){let J=G[d0.Symbol.Name],Q=G[d0.Symbol.Schema],$=G[d0.Symbol.OriginalName],z=J===$?void 0:_.alias;Z.push(E`${E.raw(_.joinType)} join${W} ${Q?E`${E.identifier(Q)}.`:void 0}${E.identifier($)}${z&&E` ${E.identifier(z)}`}${H}`)}else if(M(G,D1)){let J=G[A0].name,Q=G[A0].schema,$=G[A0].originalName,z=J===$?void 0:_.alias;Z.push(E`${E.raw(_.joinType)} join${W} ${Q?E`${E.identifier(Q)}.`:void 0}${E.identifier($)}${z&&E` ${E.identifier(z)}`}${H}`)}else Z.push(E`${E.raw(_.joinType)} join${W} ${G}${H}`);if(X<Y.length-1)Z.push(E` `)}return E.join(Z)}buildFromTable(Y){if(M(Y,P)&&Y[P.Symbol.IsAlias]){let Z=E`${E.identifier(Y[P.Symbol.OriginalName])}`;if(Y[P.Symbol.Schema])Z=E`${E.identifier(Y[P.Symbol.Schema])}.${Z}`;return E`${Z} ${E.identifier(Y[P.Symbol.Name])}`}return Y}buildSelectQuery({withList:Y,fields:Z,fieldsFlat:X,where:_,having:G,table:W,joins:H,orderBy:J,groupBy:Q,limit:$,offset:z,lockingClause:O,distinct:L,setOperators:V}){let R=X??q1(Z);for(let e of R)if(M(e.field,E0)&&c0(e.field.table)!==(M(W,P0)?W._.alias:M(W,j6)?W[A0].name:M(W,x)?void 0:c0(W))&&!((U0)=>H?.some(({alias:f0})=>f0===(U0[P.Symbol.IsAlias]?c0(U0):U0[P.Symbol.BaseName])))(e.field.table)){let U0=c0(e.field.table);throw new Error(`Your "${e.path.join("->")}" field references a column "${U0}"."${e.field.name}", but the table "${U0}" is not part of the query! Did you forget to join it?`)}let A=!H||H.length===0,f=this.buildWithCTE(Y),b;if(L)b=L===!0?E` distinct`:E` distinct on (${E.join(L.on,E`, `)})`;let k=this.buildSelection(R,{isSingleTable:A}),g=this.buildFromTable(W),N=this.buildJoins(H),I=_?E` where ${_}`:void 0,q=G?E` having ${G}`:void 0,K;if(J&&J.length>0)K=E` order by ${E.join(J,E`, `)}`;let p;if(Q&&Q.length>0)p=E` group by ${E.join(Q,E`, `)}`;let s=typeof $==="object"||typeof $==="number"&&$>=0?E` limit ${$}`:void 0,T=z?E` offset ${z}`:void 0,t=E.empty();if(O){let e=E` for ${E.raw(O.strength)}`;if(O.config.of)e.append(E` of ${E.join(Array.isArray(O.config.of)?O.config.of:[O.config.of],E`, `)}`);if(O.config.noWait)e.append(E` nowait`);else if(O.config.skipLocked)e.append(E` skip locked`);t.append(e)}let m=E`${f}select${b} ${k} from ${g}${N}${I}${p}${q}${K}${s}${T}${t}`;if(V.length>0)return this.buildSetOperations(m,V);return m}buildSetOperations(Y,Z){let[X,..._]=Z;if(!X)throw new Error("Cannot pass undefined values to any set operator");if(_.length===0)return this.buildSetOperationQuery({leftSelect:Y,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:Y,setOperator:X}),_)}buildSetOperationQuery({leftSelect:Y,setOperator:{type:Z,isAll:X,rightSelect:_,limit:G,orderBy:W,offset:H}}){let J=E`(${Y.getSQL()}) `,Q=E`(${_.getSQL()})`,$;if(W&&W.length>0){let V=[];for(let R of W)if(M(R,j))V.push(E.identifier(R.name));else if(M(R,x)){for(let A=0;A<R.queryChunks.length;A++){let f=R.queryChunks[A];if(M(f,j))R.queryChunks[A]=E.identifier(f.name)}V.push(E`${R}`)}else V.push(E`${R}`);$=E` order by ${E.join(V,E`, `)} `}let z=typeof G==="object"||typeof G==="number"&&G>=0?E` limit ${G}`:void 0,O=E.raw(`${Z} ${X?"all ":""}`),L=H?E` offset ${H}`:void 0;return E`${J}${O}${Q}${$}${z}${L}`}buildInsertQuery({table:Y,values:Z,onConflict:X,returning:_,withList:G,select:W,overridingSystemValue_:H}){let J=[],Q=Y[P.Symbol.Columns],$=Object.entries(Q).filter(([f,b])=>!b.shouldDisableInsert()),z=$.map(([,f])=>E.identifier(this.casing.getColumnCasing(f)));if(W){let f=Z;if(M(f,x))J.push(f);else J.push(f.getSQL())}else{let f=Z;J.push(E.raw("values "));for(let[b,k]of f.entries()){let g=[];for(let[N,I]of $){let q=k[N];if(q===void 0||M(q,R1)&&q.value===void 0)if(I.defaultFn!==void 0){let K=I.defaultFn(),p=M(K,x)?K:E.param(K,I);g.push(p)}else if(!I.default&&I.onUpdateFn!==void 0){let K=I.onUpdateFn(),p=M(K,x)?K:E.param(K,I);g.push(p)}else g.push(E`default`);else g.push(q)}if(J.push(g),b<f.length-1)J.push(E`, `)}}let O=this.buildWithCTE(G),L=E.join(J),V=_?E` returning ${this.buildSelection(_,{isSingleTable:!0})}`:void 0,R=X?E` on conflict ${X}`:void 0,A=H===!0?E`overriding system value `:void 0;return E`${O}insert into ${Y} ${z} ${A}${L}${R}${V}`}buildRefreshMaterializedViewQuery({view:Y,concurrently:Z,withNoData:X}){let _=Z?E` concurrently`:void 0,G=X?E` with no data`:void 0;return E`refresh materialized view${_} ${Y}${G}`}prepareTyping(Y){if(M(Y,jY)||M(Y,qY))return"json";else if(M(Y,PY))return"decimal";else if(M(Y,SY))return"time";else if(M(Y,vY)||M(Y,xY))return"timestamp";else if(M(Y,CY)||M(Y,KY))return"date";else if(M(Y,hY))return"uuid";else return"none"}sqlToQuery(Y,Z){return Y.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:Z})}buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:_,tableConfig:G,queryConfig:W,tableAlias:H,nestedQueryRelation:J,joinOn:Q}){let $=[],z,O,L=[],V,R=[];if(W===!0)$=Object.entries(G.columns).map(([b,k])=>({dbKey:k.name,tsKey:b,field:n1(k,H),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let f=Object.fromEntries(Object.entries(G.columns).map(([q,K])=>[q,n1(K,H)]));if(W.where){let q=typeof W.where==="function"?W.where(f,dW()):W.where;V=q&&V6(q,H)}let b=[],k=[];if(W.columns){let q=!1;for(let[K,p]of Object.entries(W.columns)){if(p===void 0)continue;if(K in G.columns){if(!q&&p===!0)q=!0;k.push(K)}}if(k.length>0)k=q?k.filter((K)=>W.columns?.[K]===!0):Object.keys(G.columns).filter((K)=>!k.includes(K))}else k=Object.keys(G.columns);for(let q of k){let K=G.columns[q];b.push({tsKey:q,value:K})}let g=[];if(W.with)g=Object.entries(W.with).filter((q)=>!!q[1]).map(([q,K])=>({tsKey:q,queryConfig:K,relation:G.relations[q]}));let N;if(W.extras){N=typeof W.extras==="function"?W.extras(f,{sql:E}):W.extras;for(let[q,K]of Object.entries(N))b.push({tsKey:q,value:QX(K,H)})}for(let{tsKey:q,value:K}of b)$.push({dbKey:M(K,x.Aliased)?K.fieldAlias:G.columns[q].name,tsKey:q,field:M(K,E0)?n1(K,H):K,relationTableTsKey:void 0,isJson:!1,selection:[]});let I=typeof W.orderBy==="function"?W.orderBy(f,cW()):W.orderBy??[];if(!Array.isArray(I))I=[I];L=I.map((q)=>{if(M(q,E0))return n1(q,H);return V6(q,H)}),z=W.limit,O=W.offset;for(let{tsKey:q,queryConfig:K,relation:p}of g){let s=iW(Z,X,p),T=y4(p.referencedTable),t=X[T],m=`${H}_${q}`,e=R6(...s.fields.map((J1,s1)=>fY(n1(s.references[s1],m),n1(J1,H)))),U0=this.buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:Y[t],tableConfig:Z[t],queryConfig:M(p,T4)?K===!0?{limit:1}:{...K,limit:1}:K,tableAlias:m,joinOn:e,nestedQueryRelation:p}),f0=E`${E.identifier(m)}.${E.identifier("data")}`.as(q);R.push({on:E`true`,table:new P0(U0.sql,{},m),alias:m,joinType:"left",lateral:!0}),$.push({dbKey:q,tsKey:q,field:f0,relationTableTsKey:t,isJson:!0,selection:U0.selection})}}if($.length===0)throw new BY({message:`No fields selected for table "${G.tsName}" ("${H}")`});let A;if(V=R6(Q,V),J){let f=E`json_build_array(${E.join($.map(({field:g,tsKey:N,isJson:I})=>I?E`${E.identifier(`${H}_${N}`)}.${E.identifier("data")}`:M(g,x.Aliased)?g.sql:g),E`, `)})`;if(M(J,I6))f=E`coalesce(json_agg(${f}${L.length>0?E` order by ${E.join(L,E`, `)}`:void 0}), '[]'::json)`;let b=[{dbKey:"data",tsKey:"data",field:f.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:$}];if(z!==void 0||O!==void 0||L.length>0)A=this.buildSelectQuery({table:IY(_,H),fields:{},fieldsFlat:[{path:[],field:E.raw("*")}],where:V,limit:z,offset:O,orderBy:L,setOperators:[]}),V=void 0,z=void 0,O=void 0,L=[];else A=IY(_,H);A=this.buildSelectQuery({table:M(A,d0)?A:new P0(A,{},H),fields:{},fieldsFlat:b.map(({field:g})=>({path:[],field:M(g,E0)?n1(g,H):g})),joins:R,where:V,limit:z,offset:O,orderBy:L,setOperators:[]})}else A=this.buildSelectQuery({table:IY(_,H),fields:{},fieldsFlat:$.map(({field:f})=>({path:[],field:M(f,E0)?n1(f,H):f})),joins:R,where:V,limit:z,offset:O,orderBy:L,setOperators:[]});return{tableTsKey:G.tsName,sql:A,selection:$}}}class bX{static[U]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class H1{static[U]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(Y){if(this.fields=Y.fields,this.session=Y.session,this.dialect=Y.dialect,Y.withList)this.withList=Y.withList;this.distinct=Y.distinct}authToken;setToken(Y){return this.authToken=Y,this}from(Y){let Z=!!this.fields,X=Y,_;if(this.fields)_=this.fields;else if(M(X,P0))_=Object.fromEntries(Object.keys(X._.selectedFields).map((G)=>[G,X[G]]));else if(M(X,j6))_=X[A0].selectedFields;else if(M(X,x))_={};else _=N3(X);return new kX({table:X,fields:_,isPartialSelect:Z,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class DH extends bX{static[U]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:Y,fields:Z,isPartialSelect:X,session:_,dialect:G,withList:W,distinct:H}){super();this.config={withList:W,table:Y,fields:{...Z},distinct:H,setOperators:[]},this.isPartialSelect=X,this.session=_,this.dialect=G,this._={selectedFields:Z,config:this.config},this.tableName=J4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let J of p1(Y))this.usedTables.add(J)}getUsedTables(){return[...this.usedTables]}createJoin(Y,Z){return(X,_)=>{let G=this.tableName,W=J4(X);for(let H of p1(X))this.usedTables.add(H);if(typeof W==="string"&&this.config.joins?.some((H)=>H.alias===W))throw new 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(X,x)){let H=M(X,P0)?X._.selectedFields:M(X,D1)?X[A0].selectedFields:X[P.Symbol.Columns];this.config.fields[W]=H}}if(typeof _==="function")_=_(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:_,table:X,joinType:Y,alias:W,lateral:Z}),typeof W==="string")switch(Y){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([H])=>[H,!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(([H])=>[H,!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(Y,Z){return(X)=>{let _=typeof X==="function"?X(OO()):X;if(!M6(this.getSelectedFields(),_.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:Y,isAll:Z,rightSelect:_}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(Y){return this.config.setOperators.push(...Y),this}where(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=Y,this}having(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=Y,this}groupBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(Z)?Z:[Z]}else this.config.groupBy=Y;return this}orderBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray(Z)?Z:[Z];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=X;else this.config.orderBy=X}else{let Z=Y;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Z;else this.config.orderBy=Z}return this}limit(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=Y;else this.config.limit=Y;return this}offset(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=Y;else this.config.offset=Y;return this}for(Y,Z={}){return this.config.lockingClause={strength:Y,config:Z},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}as(Y){let Z=[];if(Z.push(...p1(this.config.table)),this.config.joins)for(let X of this.config.joins)Z.push(...p1(X.table));return new Proxy(new P0(this.getSQL(),this.config.fields,Y,!1,[...new Set(Z)]),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new j0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(Y){return this.cacheConfig=Y===void 0?{config:{},enable:!0,autoInvalidate:!0}:Y===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...Y},this}}class kX extends DH{static[U]="PgSelect";_prepare(Y){let{session:Z,config:X,dialect:_,joinsNotNullableMap:G,authToken:W,cacheConfig:H,usedTables:J}=this;if(!Z)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:Q}=X;return L0.startActiveSpan("drizzle.prepareQuery",()=>{let $=q1(Q),z=Z.prepareQuery(_.sqlToQuery(this.getSQL()),$,Y,!0,void 0,{type:"select",tables:[...J]},H);return z.joinsNotNullableMap=G,z.setToken(W)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return L0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}w3(kX,[W1]);function B8(Y,Z){return(X,_,...G)=>{let W=[_,...G].map((H)=>({type:Y,isAll:Z,rightSelect:H}));for(let H of W)if(!M6(X.getSelectedFields(),H.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return X.addSetOperators(W)}}var OO=()=>({union:EO,unionAll:LO,intersect:DO,intersectAll:VO,except:MO,exceptAll:AO}),EO=B8("union",!1),LO=B8("union",!0),DO=B8("intersect",!1),VO=B8("intersect",!0),MO=B8("except",!1),AO=B8("except",!0);class P6{static[U]="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:(G)=>{if(typeof G==="function")G=G(X);return new Proxy(new E6(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...Y){let Z=this;function X(W){return new H1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),withList:Y})}function _(W){return new H1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),distinct:!0})}function G(W,H){return new H1({fields:H??void 0,session:void 0,dialect:Z.getDialect(),distinct:{on:W}})}return{select:X,selectDistinct:_,selectDistinctOn:G}}select(Y){return new H1({fields:Y??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(Y){return new H1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(Y,Z){return new H1({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 p1(Y){if(M(Y,d0))return[Y[g4]?`${Y[g4]}.${Y[P.Symbol.BaseName]}`:Y[P.Symbol.BaseName]];if(M(Y,P0))return Y._.usedTables??[];if(M(Y,x))return Y.usedTables??[];return[]}class rY extends W1{constructor(Y,Z,X,_){super();this.session=Z,this.dialect=X,this.config={table:Y,withList:_}}static[U]="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=q1(Y),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return L0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"delete",tables:p1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return L0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:c0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class sY{constructor(Y,Z,X,_,G){this.table=Y,this.session=Z,this.dialect=X,this.withList=_,this.overridingSystemValue_=G}static[U]="PgInsertBuilder";authToken;setToken(Y){return this.authToken=Y,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(Y){if(Y=Array.isArray(Y)?Y:[Y],Y.length===0)throw new Error("values() must be called with at least one value");let Z=Y.map((X)=>{let _={},G=this.table[P.Symbol.Columns];for(let W of Object.keys(X)){let H=X[W];_[W]=M(H,x)?H:new R1(H,G[W])}return _});return new gX(this.table,Z,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(Y){let Z=typeof Y==="function"?Y(new P6):Y;if(!M(Z,x)&&!M6(this.table[NY],Z._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new gX(this.table,Z,this.session,this.dialect,this.withList,!0)}}class gX extends W1{constructor(Y,Z,X,_,G,W,H){super();this.session=X,this.dialect=_,this.config={table:Y,values:Z,withList:G,select:W,overridingSystemValue_:H}}static[U]="PgInsert";config;cacheConfig;returning(Y=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=q1(Y),this}onConflictDoNothing(Y={}){if(Y.target===void 0)this.config.onConflict=E`do nothing`;else{let Z="";Z=Array.isArray(Y.target)?Y.target.map((_)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(_))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target));let X=Y.where?E` where ${Y.where}`:void 0;this.config.onConflict=E`(${E.raw(Z)})${X} do nothing`}return this}onConflictDoUpdate(Y){if(Y.where&&(Y.targetWhere||Y.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let Z=Y.where?E` where ${Y.where}`:void 0,X=Y.targetWhere?E` where ${Y.targetWhere}`:void 0,_=Y.setWhere?E` where ${Y.setWhere}`:void 0,G=this.dialect.buildUpdateSet(this.config.table,TY(this.config.table,Y.set)),W="";return W=Array.isArray(Y.target)?Y.target.map((H)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(H))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target)),this.config.onConflict=E`(${E.raw(W)})${X} do update set ${G}${Z}${_}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return L0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:p1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return L0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:c0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class yX extends W1{constructor(Y,Z,X){super();this.session=Z,this.dialect=X,this.config={view:Y}}static[U]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return L0.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 L0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}class aY{constructor(Y,Z,X,_){this.table=Y,this.session=Z,this.dialect=X,this.withList=_}static[U]="PgUpdateBuilder";authToken;setToken(Y){return this.authToken=Y,this}set(Y){return new VH(this.table,TY(this.table,Y),this.session,this.dialect,this.withList).setToken(this.authToken)}}class VH extends W1{constructor(Y,Z,X,_,G){super();this.session=X,this.dialect=_,this.config={set:Z,table:Y,withList:G,joins:[]},this.tableName=J4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[U]="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,d0))return Y[P.Symbol.Columns];else if(M(Y,P0))return Y._.selectedFields;return Y[A0].selectedFields}createJoin(Y){return(Z,X)=>{let _=J4(Z);if(typeof _==="string"&&this.config.joins.some((G)=>G.alias===_))throw new Error(`Alias "${_}" is already used in this query`);if(typeof X==="function"){let G=this.config.from&&!M(this.config.from,x)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[P.Symbol.Columns],new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:X,table:Z,joinType:Y,alias:_}),typeof _==="string")switch(Y){case"left":{this.joinsNotNullableMap[_]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!0;break}case"inner":{this.joinsNotNullableMap[_]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(Y){return this.config.where=Y,this}returning(Y){if(!Y){if(Y=Object.assign({},this.config.table[P.Symbol.Columns]),this.config.from){let Z=J4(this.config.from);if(typeof Z==="string"&&this.config.from&&!M(this.config.from,x)){let X=this.getTableLikeFields(this.config.from);Y[Z]=X}for(let X of this.config.joins){let _=J4(X.table);if(typeof _==="string"&&!M(X.table,x)){let G=this.getTableLikeFields(X.table);Y[_]=G}}}}return this.config.returningFields=Y,this.config.returning=q1(Y),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){let Z=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:p1(this.config.table)},this.cacheConfig);return Z.joinsNotNullableMap=this.joinsNotNullableMap,Z}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return this._prepare().execute(Y,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:c0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class S6 extends x{constructor(Y){super(S6.buildEmbeddedCount(Y.source,Y.filters).queryChunks);this.params=Y,this.mapWith(Number),this.session=Y.session,this.sql=S6.buildCount(Y.source,Y.filters)}sql;token;static[U]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(Y,Z){return E`(select count(*) from ${Y}${E.raw(" where ").if(Z)}${Z})`}static buildCount(Y,Z){return E`select count(*) as count from ${Y}${E.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 mX{constructor(Y,Z,X,_,G,W,H){this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=_,this.tableConfig=G,this.dialect=W,this.session=H}static[U]="PgRelationalQueryBuilder";findMany(Y){return new pX(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?Y:{},"many")}findFirst(Y){return new pX(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?{...Y,limit:1}:{limit:1},"first")}}class pX extends W1{constructor(Y,Z,X,_,G,W,H,J,Q){super();this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=_,this.tableConfig=G,this.dialect=W,this.session=H,this.config=J,this.mode=Q}static[U]="PgRelationalQuery";_prepare(Y){return L0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Z,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,Y,!0,(_,G)=>{let W=_.map((H)=>bY(this.schema,this.tableConfig,H,Z.selection,G));if(this.mode==="first")return W[0];return W})})}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 L0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class uX extends W1{constructor(Y,Z,X,_){super();this.execute=Y,this.sql=Z,this.query=X,this.mapBatchResult=_}static[U]="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 v6{constructor(Y,Z,X){if(this.dialect=Y,this.session=Z,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap,session:Z}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:Z},this.query={},this._.schema)for(let[_,G]of Object.entries(this._.schema))this.query[_]=new mX(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[_],G,Y,Z);this.$cache={invalidate:async(_)=>{}}}static[U]="PgDatabase";query;$with=(Y,Z)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(new P6(X.dialect));return new Proxy(new E6(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(Y,Z){return new S6({source:Y,filters:Z,session:this.session})}$cache;with(...Y){let Z=this;function X(Q){return new H1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y})}function _(Q){return new H1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:!0})}function G(Q,$){return new H1({fields:$??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:{on:Q}})}function W(Q){return new aY(Q,Z.session,Z.dialect,Y)}function H(Q){return new sY(Q,Z.session,Z.dialect,Y)}function J(Q){return new rY(Q,Z.session,Z.dialect,Y)}return{select:X,selectDistinct:_,selectDistinctOn:G,update:W,insert:H,delete:J}}select(Y){return new H1({fields:Y??void 0,session:this.session,dialect:this.dialect})}selectDistinct(Y){return new H1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(Y,Z){return new H1({fields:Z??void 0,session:this.session,dialect:this.dialect,distinct:{on:Y}})}update(Y){return new aY(Y,this.session,this.dialect)}insert(Y){return new sY(Y,this.session,this.dialect)}delete(Y){return new rY(Y,this.session,this.dialect)}refreshMaterializedView(Y){return new yX(Y,this.session,this.dialect)}authToken;execute(Y){let Z=typeof Y==="string"?E.raw(Y):Y.getSQL(),X=this.dialect.sqlToQuery(Z),_=this.session.prepareQuery(X,void 0,void 0,!1);return new uX(()=>_.execute(void 0,this.authToken),Z,X,(G)=>_.mapResult(G,!0))}transaction(Y,Z){return this.session.transaction(Y,Z)}}class MH{static[U]="Cache"}class x6 extends MH{strategy(){return"all"}static[U]="NoopCache";async get(Y){return}async put(Y,Z,X,_){}async onMutate(Y){}}async function dX(Y,Z){let X=`${Y}-${JSON.stringify(Z)}`,G=new TextEncoder().encode(X),W=await crypto.subtle.digest("SHA-256",G);return[...new Uint8Array(W)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}class Q4 extends Error{constructor(Y,Z,X){super(`Failed query: ${Y}
|
|
88
|
+
params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrace(this,Q4),X)this.cause=X}}class cX{constructor(Y,Z,X,_){if(this.query=Y,this.cache=Z,this.queryMetadata=X,this.cacheConfig=_,Z&&Z.strategy()==="all"&&_===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(Y,Z){return Y}setToken(Y){return this.authToken=Y,this}static[U]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(Y,Z,X){if(this.cache===void 0||M(this.cache,x6)||this.queryMetadata===void 0)try{return await X()}catch(_){throw new Q4(Y,Z,_)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await X()}catch(_){throw new Q4(Y,Z,_)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[_]=await Promise.all([X(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return _}catch(_){throw new Q4(Y,Z,_)}if(!this.cacheConfig)try{return await X()}catch(_){throw new Q4(Y,Z,_)}if(this.queryMetadata.type==="select"){let _=await this.cache.get(this.cacheConfig.tag??await dX(Y,Z),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(_===void 0){let G;try{G=await X()}catch(W){throw new Q4(Y,Z,W)}return await this.cache.put(this.cacheConfig.tag??await dX(Y,Z),G,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),G}return _}try{return await X()}catch(_){throw new Q4(Y,Z,_)}}}class lX{constructor(Y){this.dialect=Y}static[U]="PgSession";execute(Y,Z){return L0.startActiveSpan("drizzle.operation",()=>{return L0.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 iX extends v6{constructor(Y,Z,X,_=0){super(Y,Z,X);this.schema=X,this.nestedIndex=_}static[U]="PgTransaction";rollback(){throw new zX}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 E.raw(Z.join(" "))}setTransaction(Y){return this.session.execute(E`set transaction ${this.getTransactionConfigSQL(Y)}`)}}class AH extends cX{constructor(Y,Z,X,_,G,W,H,J,Q,$){super({sql:Z,params:X},G,W,H);this.client=Y,this.queryString=Z,this.params=X,this.logger=_,this.fields=J,this._isResponseInArrayMode=Q,this.customResultMapper=$}static[U]="PostgresJsPreparedQuery";async execute(Y={}){return L0.startActiveSpan("drizzle.execute",async(Z)=>{let X=$X(this.params,Y);Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X);let{fields:_,queryString:G,client:W,joinsNotNullableMap:H,customResultMapper:J}=this;if(!_&&!J)return L0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(G,X,async()=>{return await W.unsafe(G,X)})});let Q=await L0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":G,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(G,X,async()=>{return await W.unsafe(G,X).values()})});return L0.startActiveSpan("drizzle.mapResponse",()=>{return J?J(Q):Q.map(($)=>A3(_,$,H))})})}all(Y={}){return L0.startActiveSpan("drizzle.execute",async(Z)=>{let X=$X(this.params,Y);return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),L0.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 h6 extends lX{constructor(Y,Z,X,_={}){super(Z);this.client=Y,this.schema=X,this.options=_,this.logger=_.logger??new UX,this.cache=_.cache??new x6}static[U]="PostgresJsSession";logger;cache;prepareQuery(Y,Z,X,_,G,W,H){return new AH(this.client,Y.sql,Y.params,this.logger,this.cache,W,H,Z,_,G)}query(Y,Z){return this.logger.logQuery(Y,Z),this.client.unsafe(Y,Z).values()}queryObjects(Y,Z){return this.client.unsafe(Y,Z)}transaction(Y,Z){return this.client.begin(async(X)=>{let _=new h6(X,this.dialect,this.schema,this.options),G=new oX(this.dialect,_,this.schema);if(Z)await G.setTransaction(Z);return Y(G)})}}class oX extends iX{constructor(Y,Z,X,_=0){super(Y,Z,X,_);this.session=Z}static[U]="PostgresJsTransaction";transaction(Y){return this.session.client.savepoint((Z)=>{let X=new h6(Z,this.dialect,this.schema,this.session.options),_=new oX(this.dialect,X,this.schema);return Y(_)})}}class wH extends v6{static[U]="PostgresJsDatabase"}function T8(Y,Z={}){let X=(Q)=>Q;for(let Q of["1184","1082","1083","1114","1182","1185","1115","1231"])Y.options.parsers[Q]=X,Y.options.serializers[Q]=X;Y.options.serializers["114"]=X,Y.options.serializers["3802"]=X;let _=new c4({casing:Z.casing}),G;if(Z.logger===!0)G=new FX;else if(Z.logger!==!1)G=Z.logger;let W;if(Z.schema){let Q=lW(Z.schema,oW);W={fullSchema:Z.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let H=new h6(Y,_,W,{logger:G,cache:Z.cache}),J=new wH(_,H,W);if(J.$client=Y,J.$cache=Z.cache,J.$cache)J.$cache.invalidate=Z.cache?.onMutate;return J}function tY(...Y){if(typeof Y[0]==="string"){let Z=I8(Y[0]);return T8(Z,Y[1])}if(R3(Y[0])){let{connection:Z,client:X,..._}=Y[0];if(X)return T8(X,_);if(typeof Z==="object"&&Z.url!==void 0){let{url:W,...H}=Z,J=I8(W,H);return T8(J,_)}let G=I8(Z);return T8(G,_)}return T8(Y[0],Y[1])}((Y)=>{function Z(X){return T8({options:{parsers:{},serializers:{}}},X)}Y.mock=Z})(tY||(tY={}));var rX={};TJ(rX,{users:()=>l4,untrackedUserColumnNames:()=>wO,twoFactorMethod:()=>TH,trackedUserColumnName:()=>NO,trackableUserColumnNames:()=>IH,signInHistory:()=>IO,role:()=>RH,players:()=>nX,passwordResetAttempts:()=>BO,games:()=>YZ,banishedIps:()=>TO,accountActions:()=>RO,accountAction:()=>BH});function K4(){return e0({length:24}).$type()}function NH(Y){return E`lower(${Y})`}var eY=E`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,RH=O6("role",["admin","user"]),l4=B4("users",{id:j1().primaryKey().defaultRandom(),username:e0({length:16}).notNull(),emailOffered:e0({length:254}).notNull(),emailVerified:e0({length:254}),password:e0({length:254}),createdAtIso:K4().notNull().default(eY),createdIp:e0({length:45}).notNull(),isActive:A6().notNull().default(!1),verifiedAtIso:K4(),userRole:RH().default("user")},(Y)=>[hX("usernameUniqueIndex").on(NH(Y.username)),hX("emailVerifiedUniqueIndex").on(NH(Y.emailVerified))]),wO=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],IH=["username","emailOffered","emailVerified","password","userRole"],NO=O6("trackedUserColumnName",IH),BH=O6("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),RO=B4("accountActions",{userId:j1().references(()=>l4.id).primaryKey(),action:BH().notNull(),code:e0({length:254}).notNull(),wrongCodeCount:w6().notNull().default(0),expiresAtIso:K4().notNull()}),YZ=B4("games",{id:j1().primaryKey().defaultRandom()}),nX=B4("players",{userId:j1().notNull().references(()=>l4.id,{onDelete:"cascade"}),gameId:j1().notNull().references(()=>YZ.id,{onDelete:"cascade"}),score:w6().notNull()},(Y)=>[AW({name:"players_userId_gameId_pk",columns:[Y.userId,Y.gameId]})]),IO=B4("signInHistory",{id:j1().primaryKey().defaultRandom(),userId:j1().references(()=>l4.id,{onDelete:"cascade"}),signInTimeIso:K4().notNull().default(eY),ipAddress:e0({length:45}).notNull(),userAgent:e0({length:1024}),successful:A6().notNull().default(!1)}),TH=O6("twoFactorMethod",["email","phone"]),BO=B4("passwordResetAttempts",{id:j1().primaryKey().defaultRandom(),userId:j1().notNull().references(()=>l4.id,{onDelete:"cascade"}),requestedIp:e0({length:45}).notNull(),requestedAtIso:K4().notNull().default(eY),succeededIp:e0({length:45}),succeededAtIso:K4(),verificationMethod:TH().notNull()}),TO=B4("banishedIps",{ip:e0({length:45}).primaryKey(),reason:e0({length:2048}).notNull(),banishedAtIso:K4().notNull().default(eY),banishedUntilIso:K4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class sX{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(CO.resolve(__dirname,"notify_update.sql"));let Y=[c0(l4),c0(YZ),c0(nX)];await this.sql`SELECT create_notify_triggers(${this.sql.array(Y)})`,await this.sql.listen("table_update",(Z)=>{let X=Z.split(","),_=X[0],G=X[1],W=`${_}("${G}")`;if(this.observers.has(W))this.observers.get(W).next(W)})}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=I8(Z),this.drizzle=tY(this.sql,{schema:rX,logger:Y})}observe(Y,Z){if(!this.observers.has(Y))this.observers.set(Y,new H0);this.observers.get(Y).subscribe("SINGLETON",Z)}}var ZZ={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 KO(Y){return Number.parseInt(Y,10)}var qO=O1(ZZ),jO=qO.keyof().pipe((Y)=>KO(Y)),CH=O1([jO,"string"]);var tX=new n7,{logger:M1}=tX;Object.assign(console,M1,{log:M1.info});M1.info("ready");var aX=qH(import.meta.dir,"..","app"),ex=new sX({logQuery(Y,Z){M1.info("\uD83D\uDCDD query",Y,Z)}});xO({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...MY??void 0,async fetch(Y){try{let Z=new Date,X=new URL(Y.url);if(M1.info(Y.method,X.pathname),X.pathname==="/")return new Response(Bun.file(qH(aX,"index.html")));if(X.pathname==="/index.html")return Response.redirect("/");let _=SO(aX,X.pathname),G=vO(_);if(!G.startsWith(aX))throw[403,"Access Denied"];if(!await KH(G).exists())return Response.redirect("/");return new Response(KH(G))}catch(Z){let X=CH(Z);if(X instanceof O1.errors===!1){let[_,G]=X,H=`${ZZ[_]}. ${G}`;return M1.info(`\u274C ${_}: ${H}`),new Response(H,{status:_})}if(Z instanceof Error)M1.error(Z.message);else{let _=VY(Z);M1.error("frontend server threw",_)}return new Response(ZZ[500],{status:500})}}});function XZ(){M1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{M1.info("\u2757 received SIGINT; exiting gracefully"),XZ()});process.on("SIGTERM",()=>{M1.info("\u2757 received SIGTERM; exiting gracefully"),XZ()});process.on("exit",()=>{M1.info("\u2757 received exit; exiting gracefully"),XZ()});tX.on("timeToStop",()=>{M1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),XZ()});var{version:hO}=await Bun.file(PO.resolve(import.meta.dir,"../package.json")).json();M1.info(`\uD83D\uDEEB frontend v${hO} running at http://localhost:${g1.FRONTEND_PORT}/`);tX.emit("alive");
|