tempest.games 0.2.30 → 0.2.32
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 +14 -0
- package/app/assets/{index-B5TrbPgh.js → index-PdakLVWK.js} +34 -34
- package/app/index.html +1 -1
- package/bin/backend.bun.js +163 -163
- package/bin/backend.worker.game.bun.js +10 -10
- package/bin/backend.worker.tribunal.bun.js +82 -82
- package/bin/frontend.bun.js +36 -36
- package/bin/setup-db.bun.js +1 -1
- package/package.json +8 -8
package/bin/frontend.bun.js
CHANGED
|
@@ -1,76 +1,76 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var TJ=Object.create;var{getPrototypeOf:
|
|
3
|
+
var TJ=Object.create;var{getPrototypeOf:KJ,defineProperty:$Z,getOwnPropertyNames:qJ}=Object;var jJ=Object.prototype.hasOwnProperty;var bO=(Y,Z,X)=>{X=Y!=null?TJ(KJ(Y)):{};let _=Z||!Y||!Y.__esModule?$Z(X,"default",{value:Y,enumerable:!0}):X;for(let G of qJ(Y))if(!jJ.call(_,G))$Z(_,G,{get:()=>Y[G],enumerable:!0});return _};var kO=(Y,Z)=>()=>(Z||Y((Z={exports:{}}).exports,Z),Z.exports);var PJ=(Y,Z)=>{for(var X in Z)$Z(Y,X,{get:Z[X],enumerable:!0,configurable:!0,set:(_)=>Z[X]=()=>_})};var gO=(Y,Z)=>()=>(Y&&(Z=Y(Y=0)),Z);var yO=import.meta.require;import SO,{join as vO,normalize as xO,resolve as xH}from"path";var U4=(Y)=>Array.isArray(Y)?Y:[Y],z_=(Y,Z)=>{let X=[[],[]];for(let _ of Y)if(Z(_))X[0].push(_);else X[1].push(_);return X},g6=Array,s1=(Y,Z)=>Y.includes(Z),F_=(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},a1=(Y,Z)=>{if(Z===void 0||Z===null)return Y??[];if(Y===void 0||Y===null)return U4(Z);return Y.concat(Z)},U_=(...Y)=>Y.reduce(a1,[]),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},O_=(Y,Z)=>Y.reduce((X,_)=>{let G=_[Z];return X[G]=Z0(X[G],_),X},{}),t1=(Y,Z,X)=>Y.length===Z.length&&Y.every(X?.isEqual?(_,G)=>X.isEqual(_,Z[G]):(_,G)=>_===Z[G]);var $1=(Y,Z)=>y0(Y)===Z,y0=(Y)=>{let Z=typeof Y;return Z==="object"?Y===null?"null":"object":Z==="function"?"object":Z},z1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},E_={...z1,function:"a function"};class D_ extends Error{}var _0=(Y)=>q4(Y,D_),q4=(Y,Z=Error)=>{throw new Z(Y)};class P8 extends Error{name="ParseError"}var w=(Y)=>q4(Y,P8),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 $=Array.isArray(J[0])||J.length===0?J:[J];for(let[Q,z]of $)if(typeof Q==="object")X[Q.group]=Z0(X[Q.group],z);else X[Q]=z}return G?Object.values(X):X};var zZ=Object.entries;var p0=(Y,Z)=>(Y in Z),n4=(Y,Z)=>(Z in Y);class FZ{constructor(Y){Object.assign(this,Y)}}var L_=class{};class S8 extends L_{}var SJ=(Y,Z)=>{let X={},_={},G;for(G in Y)if(G in Z)X[G]=Y[G];else _[G]=Y[G];return[X,_]};var V_=(Y,Z)=>SJ(Y,Z)[1],c1=(Y)=>Object.keys(Y).length===0,j4=(Y)=>[...Object.entries(Y),...Object.getOwnPropertySymbols(Y).map((Z)=>[Z,Y[Z]])],M_=(Y,Z)=>Object.defineProperties(Y,Object.getOwnPropertyDescriptors(Z)),A_=(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"),w_=(Y)=>Object.values(Y).filter((Z)=>{if(typeof Z==="number")return!0;return typeof Y[Z]!=="number"});var UZ={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},OZ=globalThis.File??Blob,EZ={ArrayBuffer,Blob,File:OZ,FormData,Headers,Request,Response,URL},vJ={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},P4={...UZ,...EZ,...vJ,String,Number,Boolean},v8=(Y)=>{let Z=Object.getPrototypeOf(Y);while(Z?.constructor&&(!p0(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},x8=(Y)=>typeof Y==="object"&&Y!==null?v8(Y)??"object":y0(Y);var O0=Array.isArray,xJ={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},hJ={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"},fJ={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"},R_={...xJ,...hJ,...fJ},h8=(Y)=>{let Z=Object(Y).name??null;return Z&&p0(Z,P4)&&P4[Z]===Y?Z:null};var DZ=(Y,Z)=>{let X=Y.prototype;while(X!==null){if(X===Z.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var N_=(Y)=>I_(Y,new Map),I_=(Y,Z)=>{if(typeof Y!=="object"||Y===null)return Y;if(Z?.has(Y))return Z.get(Y);let X=h8(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=I_(H.value,Z)}}return Object.defineProperties(_,G),_};var bJ=(Y)=>{let Z=A1;return()=>Z===A1?Z=Y():Z},O4=(Y)=>typeof Y==="function"&&Y.length===0;var B_=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
4
|
Message: ${_}
|
|
5
5
|
Source: (${Y.slice(0,-1)}) => {
|
|
6
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
|
|
8
|
-
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},
|
|
7
|
+
}`)}}};class h1{constructor(Y,...[Z]){return Object.assign(Object.setPrototypeOf(Y.bind(Z?.bind??this),this.constructor.prototype),Z?.attach)}}var C_=bJ(()=>{try{return new Function("return false")()}catch{return!0}});var HE=x1("brand");var T_=x1("arkInferred");var $E=x1("args");class a0{constructor(){}}var kJ=()=>{try{return((new Error().stack?.split(`
|
|
8
|
+
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},gJ=globalThis.process?.env??{},K_={fileName:kJ,env:gJ};var q_=(Y)=>Y[0].toUpperCase()+Y.slice(1);var LZ=(Y)=>new RegExp(yJ(Y),typeof Y==="string"?"":Y.flags);var yJ=(Y)=>{return`^(?:${typeof Y==="string"?Y:Y.source})$`};var e1={negativeLookahead:(Y)=>`(?!${Y})`,nonCapturingGroup:(Y)=>`(?:${Y})`},f8="\\",E4={" ":1,"\n":1,"\t":1};var pJ=/^-0\.?0*$/.source,P_=/[1-9]\d*/.source,mJ=/\.\d+/.source,uJ=/\.\d*[1-9]/.source,S_=(Y)=>LZ(e1.negativeLookahead(pJ)+e1.nonCapturingGroup("-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+P_)+e1.nonCapturingGroup(Y.decimalPattern)+"?")+(Y.allowDecimalOnly?"|"+Y.decimalPattern:"")+"?")),j_=S_({decimalPattern:uJ,allowDecimalOnly:!1}),dJ=j_.test.bind(j_),y6=S_({decimalPattern:mJ,allowDecimalOnly:!0}),LE=y6.test.bind(y6),cJ=/^-?\d*\.?\d*$/,lJ=(Y)=>Y.length!==0&&cJ.test(Y),b8=LZ(e1.negativeLookahead("^-0$")+"-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+P_))),iJ=b8.test.bind(b8),VZ=/^-?\d+$/,oJ=VZ.test.bind(VZ),v_={number:"a number",bigint:"a bigint",integer:"an integer"},x_=(Y,Z)=>`'${Y}' was parsed as ${v_[Z]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,nJ=(Y,Z)=>Z==="number"?dJ(Y):iJ(Y),rJ=(Y,Z)=>Z==="number"?Number(Y):Number.parseInt(Y),sJ=(Y,Z)=>Z==="number"?lJ(Y):oJ(Y),h_=(Y,Z)=>MZ(Y,"number",Z),f_=(Y,Z)=>MZ(Y,"number",{...Z,strict:!0}),b_=(Y,Z)=>MZ(Y,"integer",Z),MZ=(Y,Z,X)=>{let _=rJ(Y,Z);if(!Number.isNaN(_)){if(sJ(Y,Z)){if(X?.strict)return nJ(Y,Z)?_:w(x_(Y,Z));return _}}return X?.errorOnFail?w(X?.errorOnFail===!0?`Failed to parse ${v_[Z]} from '${Y}'`:X?.errorOnFail):void 0},k_=(Y)=>{if(Y[Y.length-1]!=="n")return;let Z=Y.slice(0,-1),X;try{X=BigInt(Z)}catch{return}if(b8.test(Z))return X;if(VZ.test(Z))return w(x_(Y,"bigint"))};var aJ="0.46.0",tJ={version:aJ,filename:K_.fileName(),FileConstructor:OZ},S4=tJ,g_=new Map,AZ=Object.create(null),k8=(Y)=>{let Z=g_.get(Y);if(Z)return Z;let X=eJ(Y);if(AZ[X])X=`${X}${AZ[X]++}`;else AZ[X]=1;return S4[X]=Y,g_.set(Y,X),X},D4=(Y)=>/^[$A-Z_a-z][\w$]*$/.test(Y),eJ=(Y)=>{switch(typeof Y){case"object":{if(Y===null)break;let Z=v8(Y)??"object";return Z[0].toLowerCase()+Z.slice(1)}case"function":return D4(Y.name)?Y.name:"fn";case"symbol":return Y.description&&D4(Y.description)?Y.description:"symbol"}return _0(`Unexpected attempt to register serializable value of type ${y0(Y)}`)};var g8=(Y)=>typeof Y==="string"?JSON.stringify(Y):typeof Y==="bigint"?`${Y}n`:`${Y}`;var y_=(Y,Z={})=>y8(Y,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...Z},[]);var n=(Y,Z)=>{switch(y0(Y)){case"object":let X=Y,_=X.constructor.name;return _==="Object"||_==="Array"?Z?.quoteKeys===!1?p6(X,Z?.indent??0,""):JSON.stringify(y8(X,r4,[]),null,Z?.indent):p6(X,Z?.indent??0,"");case"symbol":return r4.onSymbol(Y);default:return g8(Y)}},p6=(Y,Z,X)=>{if(typeof Y==="function")return r4.onFunction(Y);if(typeof Y!=="object"||Y===null)return g8(Y);let _=X+" ".repeat(Z);if(Array.isArray(Y)){if(Y.length===0)return"[]";let W=Y.map((H)=>p6(H,Z,_)).join(`,
|
|
9
9
|
`+_);return Z?`[
|
|
10
10
|
${_}${W}
|
|
11
|
-
${X}]`:`[${W}]`}let G=Y.constructor.name;if(G==="Object"){let W=j4(Y).map(([H,J])=>{let
|
|
11
|
+
${X}]`:`[${W}]`}let G=Y.constructor.name;if(G==="Object"){let W=j4(Y).map(([H,J])=>{let $=typeof H==="symbol"?r4.onSymbol(H):D4(H)?H:JSON.stringify(H),Q=p6(J,Z,_);return`${_}${$}: ${Q}`});if(W.length===0)return"{}";return Z?`{
|
|
12
12
|
${W.join(`,
|
|
13
13
|
`)}
|
|
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(${
|
|
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(${k8(Y)})`,onFunction:(Y)=>`Function(${k8(Y)})`},y8=(Y,Z,X)=>{switch(y0(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)=>y8(H,Z,G));if(_ instanceof Date)return _.toDateString();let W={};for(let H in _)W[H]=y8(_[H],Z,G);for(let H of Object.getOwnPropertySymbols(_))W[Z.onSymbol?.(H)??H.toString()]=y8(_[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 $=`${YQ[X]} ${_}, ${Z}`;if(G===0&&W===0&&H===0&&J===0)return $;let Q=Y.toLocaleTimeString(),z=Q.endsWith(" AM")||Q.endsWith(" PM")?Q.slice(-3):"";if(z)Q=Q.slice(0,-z.length);if(J)Q+=`.${XQ(J,3)}`;else if(ZQ.test(Q))Q=Q.slice(0,-3);return`${Q+z}, ${$}`},YQ=["January","February","March","April","May","June","July","August","September","October","November","December"],ZQ=/:\d\d:00$/,XQ=(Y,Z)=>String(Y).padStart(Z,"0");var p_=(Y,Z,...[X])=>{let _=X?.stringifySymbol??n,G=Y;switch(typeof Z){case"string":G=D4(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},Y4=(Y,...Z)=>Y.reduce((X,_)=>p_(X,_,...Z),"");class p8 extends g6{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=Y4(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Y="",Z=[Y];for(let X of this)Y=p_(Y,X),Z.push(Y);return this.cache.stringifyAncestors=Z}}class wZ{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]===f8)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 mE=x1("implementedTraits");var RZ="$ark",_Q=2;while(RZ in globalThis)RZ=`$ark${_Q++}`;var m_=RZ;globalThis[m_]=S4;var B=S4,GQ=(Y)=>`${m_}.${Y}`,K0=(Y)=>GQ(k8(Y));class m6 extends S8{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 NZ(Y,Z)}index(Y,Z=!1){return u_(`${Y}`,Z)}line(Y){return this.body+=`${" ".repeat(this.indentation)}${Y}
|
|
15
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
16
|
`).map((X)=>" ".repeat(Z)+`${X}`).join(`
|
|
17
|
-
`):this.body} }`}compile(){return new B_(...this.argNames,this.body)}}var
|
|
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
|
|
19
|
-
`+Y.map((Z)=>` \u2022 ${
|
|
20
|
-
`));Object.defineProperty(this,"arkErrors",{value:Y,enumerable:!1})}}var
|
|
17
|
+
`):this.body} }`}compile(){return new B_(...this.argNames,this.body)}}var Z4=(Y)=>$1(Y,"object")||typeof Y==="symbol"?K0(Y):g8(Y),NZ=(Y,Z=!1)=>{if(typeof Y==="string"&&D4(Y))return`${Z?"?":""}.${Y}`;return u_(WQ(Y),Z)},WQ=(Y)=>typeof Y==="symbol"?K0(Y):JSON.stringify(Y),u_=(Y,Z=!1)=>`${Z?"?.":""}[${Y}]`;class m8 extends m6{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 u6=(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 d_=["unit","proto","domain"],s4=["required","optional","index","sequence"],IZ=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],d6=[...IZ,...s4,"structure","predicate"],a4=["alias","union","morph","unit","intersection","proto","domain"],HQ=[...a4,...d6],c6=o(d6,(Y,Z)=>[Z,1]),c_=o([...s4,"undeclared"],(Y,Z)=>[Z,1]),l_=o(HQ,(Y,Z)=>[Z,Y]),t4=(Y)=>typeof Y==="string"&&(Y in l_);var e4=(Y)=>l_[Y],l6=(Y)=>a4.slice(e4(Y)+1),BD=[...l6("union"),"alias"],CD=[...l6("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 Z4(Y)},L4=(Y)=>{let Z="{ ";for(let[X,_]of Object.entries(Y))Z+=`${X}: ${Z4(_)}, `;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 i_ 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 JQ={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Y)=>N0.throw("arrayObject",Y),arrayPostfix:(Y)=>N0.throw("arrayPostfix",Y),defaultValue:(Y)=>N0.throw("defaultValue",Y),domain:(Y)=>N0.throw("domain",Y),morph:(Y)=>N0.throw("morph",Y),patternIntersection:(Y)=>N0.throw("patternIntersection",Y),predicate:(Y)=>N0.throw("predicate",Y),proto:(Y)=>N0.throw("proto",Y),symbolKey:(Y)=>N0.throw("symbolKey",Y),unit:(Y)=>N0.throw("unit",Y),date:(Y)=>N0.throw("date",Y)}},N0={Error:i_,throw:(...Y)=>{throw new N0.Error(...Y)},throwInternalOperandError:(Y,Z)=>_0(`Unexpected JSON Schema input for ${Y}: ${n(Z)}`),defaultConfig:JQ};B.config??={};var u8=(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[_]=BZ(Y.toJsonSchema,Z.toJsonSchema);else if(t4(_))X[_]={...Y[_],...Z[_]};else X[_]=Z[_]}return X},BZ=(Y,Z)=>{if(!Y)return Z??{};if(!Z)return Y;let X={...Y},_;for(_ in Z)if(_==="fallback")X.fallback=QQ(Y.fallback,Z.fallback);else X[_]=Z[_];return X},QQ=(Y,Z)=>{Y=o_(Y),Z=o_(Z);let X={},_;for(_ in N0.defaultConfig.fallback)X[_]=Z[_]??Z.default??Y[_]??Y.default??N0.defaultConfig.fallback[_];return X},o_=(Y)=>typeof Y==="function"?{default:Y}:Y??{};class V4 extends S8{[X1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Y,relativePath:Z,...X},_){super();this.input=X,this.ctx=_,M_(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(($)=>$.transform((Q)=>({...Q,path:U_(Y,Q.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 p8(...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 Y4(this.path)}get expected(){if(this.input.expected)return this.input.expected;let Y=this.meta?.expected??this.nodeConfig.expected;return typeof Y==="function"?Y(this.input):Y}get actual(){if(this.input.actual)return this.input.actual;let Y=this.meta?.actual??this.nodeConfig.actual;return typeof Y==="function"?Y(this.data):Y}get problem(){if(this.input.problem)return this.input.problem;let Y=this.meta?.problem??this.nodeConfig.problem;return typeof Y==="function"?Y(this):Y}get message(){if(this.input.message)return this.input.message;let Y=this.meta?.message??this.nodeConfig.message;return typeof Y==="function"?Y(this):Y}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class F1 extends g6{[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 CZ(this)}add(Y){if(this.includes(Y))return;this._add(Y)}transform(Y){let Z=new F1(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 CZ extends Error{name="TraversalError";constructor(Y){if(Y.length===1)super(Y.summary);else super(`
|
|
19
|
+
`+Y.map((Z)=>` \u2022 ${$Q(Z)}`).join(`
|
|
20
|
+
`));Object.defineProperty(this,"arkErrors",{value:Y,enumerable:!1})}}var $Q=(Y)=>Y.toString().split(`
|
|
21
21
|
`).join(`
|
|
22
|
-
`);class f1{path=[];errors=new F1(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 F1){if(!W)this.errors.merge(H);break}if(_===void 0)this.root=H;else _[X]=H;this.applyQueuedMorphs()}}}var U1=(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)=>U$(_,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)=>r_(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=F$(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)K4(`${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))K4(`${this.kind} node was not one of asserted kinds ${Y}`);return this}isBasis(){return a1(d_,this.kind)}isConstraint(){return a1(u6,this.kind)}isStructural(){return a1(s4,this.kind)}isRefinement(){return a1(NZ,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)K4(n_(Z,X));return Y},find:(Y)=>Y[0],assertFind:(Y,Z,X)=>{if(Y.length===0)K4(n_(Z,X));return Y[0]}},normalize:(Y)=>typeof Y==="function"?{boundary:"references",method:"filter",where:Y}:typeof Y==="string"?p0(Y,u8.applyBoundary)?{method:"filter",boundary:Y}:{boundary:"references",method:"filter",kind:Y}:{boundary:"references",method:"filter",...Y}},n_=(Y,Z)=>`${Y} had no references matching ${n(Z)}.`,Q$=(Y)=>Z4(Y,{stringifyNonKey:(Z)=>Z.expression}),z$=/"(\$ark\.[^"]+)"/g,F$=(Y)=>JSON.stringify(Y).replaceAll(z$,"$1"),b1=(Y,Z)=>({path:Y,node:Z,propString:Q$(Y)}),r_=(Y,Z)=>Y.propString===Z.propString&&Y.node.equals(Z.node),TZ=(Y,Z)=>d1(Y,Z,{isEqual:r_}),U$=(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 qZ(`Intersection${_&&` at ${_}`} of ${s_(Z,X)}`)}return`The following intersections result in unsatisfiable types:
|
|
22
|
+
`);class f1{path=[];errors=new F1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Y,Z){this.root=Y,this.config=Z}get data(){let Y=this.root;for(let Z of this.path)Y=Y?.[Z];return Y}get propString(){return Y4(this.path)}reject(Y){return this.error(Y),!1}mustBe(Y){return this.error(Y),!1}error(Y){let Z=typeof Y==="object"?Y.code?Y:{...Y,code:"predicate"}:{code:"predicate",expected:Y};return this.errorFromContext(Z)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(Y){let Z={path:new p8(...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 F1){if(!W)this.errors.merge(H);break}if(_===void 0)this.root=H;else _[X]=H;this.applyQueuedMorphs()}}}var U1=(Y,Z,X)=>{if(!X)return Z();X.path.push(Y);let _=Z();return X.path.pop(),_};class c8 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)=>OQ(_,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)=>r_(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=UQ(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(!s1(Y,this.kind))q4(`${this.kind} node was not one of asserted kinds ${Y}`);return this}isBasis(){return s1(d_,this.kind)}isConstraint(){return s1(d6,this.kind)}isStructural(){return s1(s4,this.kind)}isRefinement(){return s1(IZ,this.kind)}isRoot(){return s1(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=d8.normalize(Y);return this._select(Z)}_select(Y){let Z=d8.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 d8.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,(Q,z)=>{if(!this.impl.keys[Q].child)return[Q,z];let O=z;if(!O0(O)){let V=O._transform(Y,Z);return V?[Q,V]:[]}if(O.length===0)return[Q,z];let D=O.flatMap((V)=>{return V._transform(Y,Z)??[]});return D.length?[Q,D]:[]});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=d8.normalize(Z),_=typeof Y==="string"?(J,$)=>({...$,meta:{...$.meta,description:Y}}):typeof Y==="function"?(J,$)=>({...$,meta:Y($.meta)}):(J,$)=>({...$,meta:{...$.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,$)=>$.root.children.includes(J):X.boundary==="shallow"?(J)=>J.kind!=="structure":()=>!0;return this.$.finalize(this.transform(_,{shouldTransform:H,selected:W}))}}var d8={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(n_(Z,X));return Y},find:(Y)=>Y[0],assertFind:(Y,Z,X)=>{if(Y.length===0)q4(n_(Z,X));return Y[0]}},normalize:(Y)=>typeof Y==="function"?{boundary:"references",method:"filter",where:Y}:typeof Y==="string"?p0(Y,d8.applyBoundary)?{method:"filter",boundary:Y}:{boundary:"references",method:"filter",kind:Y}:{boundary:"references",method:"filter",...Y}},n_=(Y,Z)=>`${Y} had no references matching ${n(Z)}.`,zQ=(Y)=>Y4(Y,{stringifyNonKey:(Z)=>Z.expression}),FQ=/"(\$ark\.[^"]+)"/g,UQ=(Y)=>JSON.stringify(Y).replaceAll(FQ,"$1"),b1=(Y,Z)=>({path:Y,node:Z,propString:zQ(Y)}),r_=(Y,Z)=>Y.propString===Z.propString&&Y.node.equals(Z.node),TZ=(Y,Z)=>d1(Y,Z,{isEqual:r_}),OQ=(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],_=Y4(Y);return qZ(`Intersection${_&&` at ${_}`} of ${s_(Z,X)}`)}return`The following intersections result in unsatisfiable types:
|
|
23
23
|
\u2022 ${this.map(({path:Y,l:Z,r:X})=>`${Y}: ${s_(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 s_=(Y,Z)=>`${CZ(Y)} and ${CZ(Z)}`,CZ=(Y)=>V0(Y)?Y.expression:O0(Y)?Y.map(CZ).join(" | ")||"never":String(Y),qZ=(Y)=>`${Y} results in an unsatisfiable type`;var Y8={},O1=(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?KZ(Y,Z,X):Y.hasKindIn(...a4)?O$(Y,Z,X):KZ(Y,Z,X);if(V0(H)){if(Y.equals(H))H=Y;else if(Z.equals(H))H=Z}return Y8[G]=H,H},KZ=(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}},O$=(Y,Z,X)=>Y.includesTransform||Z.includesTransform?X.invert?a_(Z,Y,X):a_(Y,Z,X):KZ(Y,Z,X),a_=(Y,Z,X)=>Y.distribute((_)=>E$(_,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)}),E$=(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 O1(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,L$(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)},L$=(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},t_=(...Y)=>w(e_(...Y)),e_=(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 YG=(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(D$(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:y_(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 D$=(Y,Z,X)=>`${Y} must be assignable to ${Z} (was ${X})`;var V$=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 ZG extends T1{serializedPredicate=q0(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 jZ={implementation:V$,Node:ZG};var M$=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Y)=>Number.isInteger(Y)?Y:w(A$(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/w$(Y.rule,Z.rule))})},obviatesBasisDescription:!0});class XG 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 PZ={implementation:M$,Node:XG};var A$=(Y)=>`divisor must be an integer (was ${Y})`,w$=(Y,Z)=>{let X,_=Y,G=Z;while(G!==0)X=G,G=_%G,_=X;return _};class w1 extends _4{boundOperandKind=B$[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=T$(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${R$[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?C$(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 R$={"<":">=","<=":">",">":"<=",">=":"<"},N$={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,I$=(Y,Z)=>`${Y} bound must be a positive integer (was ${Z})`,_8=(Y)=>(Z)=>{if(!Number.isInteger(Z)||Z<0)w(I$(Y,Z));return Z},B$={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},T$=(Y,Z)=>`${p0(Y,N$)?">":"<"}${Z?"":"="}`,C$=(Y)=>typeof Y==="string"?Y:new Date(Y).toLocaleString(),_G=(Y)=>`Bounded expression ${Y} must be exactly one of number, string, Array, or Date`;var q$=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 GG 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 SZ={implementation:q$,Node:GG};var K$=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 WG 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 vZ={implementation:K$,Node:WG};var j$=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 HG 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 N0.throwInternalOperandError("exactLength",Y)}}}var xZ={implementation:j$,Node:HG};var P$=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 JG 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 hZ={implementation:P$,Node:JG};var S$=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 $G 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 N0.throwInternalOperandError("maxLength",Y)}}}var fZ={implementation:S$,Node:$G};var v$=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 QG 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 bZ={implementation:v$,Node:QG};var x$=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 zG 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 N0.throwInternalOperandError("minLength",Y)}}}var kZ={implementation:x$,Node:zG};var FG={min:bZ.implementation,max:hZ.implementation,minLength:kZ.implementation,maxLength:fZ.implementation,exactLength:xZ.implementation,after:SZ.implementation,before:vZ.implementation},UG={min:bZ.Node,max:hZ.Node,minLength:kZ.Node,maxLength:fZ.Node,exactLength:xZ.Node,after:SZ.Node,before:vZ.Node};var h$=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 OG 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 gZ={implementation:h$,Node:OG};var l8=(Y,Z)=>{let X=f$(Y);if(Z&&!Z.includes(X))return w(`Root of kind ${X} should be one of ${Z}`);return X},f$=(Y)=>{if(y(Y,"root"))return Y.kind;if(typeof Y==="string")return Y[0]==="$"?"alias":(Y in z1)?"domain":"proto";if(typeof Y==="function")return"proto";if(typeof Y!=="object"||Y===null)return w(EG(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(EG(Y))},EG=(Y)=>`${n(Y)} is not a valid type schema`,LG={},b$=(Y)=>O0(Y)?Y.map((Z)=>Z.collapsibleJson):Y.collapsibleJson,_1={};B.nodesByRegisteredId=_1;var yZ=(Y)=>{return LG[Y]??=0,`${Y}${++LG[Y]}`},pZ=(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=QZ(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 k$($,H)}}return mZ({id:Y.id,kind:Y.kind,inner:_,meta:H,$:Y.$})},mZ=({id:Y,kind:Z,inner:X,meta:_,$:G,ignoreCache:W})=>{let H=G8[Z],J=QZ(X),Q=[],$={};for(let[b,k]of J){let g=H.keys[b],R=g.serialize??(g.child?b$:B1);if($[b]=R(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),N=JSON.stringify({kind:Z,...z});if(G.nodesByHash[N]&&!W)return G.nodesByHash[N];let A={id:Y,kind:Z,impl:H,inner:X,innerEntries:J,innerJson:$,innerHash:L,meta:_,metaJson:O,json:z,hash:N,collapsibleJson:V,children:Q};if(Z!=="intersection"){for(let b in X)if(b!=="in"&&b!=="out")A[b]=X[b]}let f=new VG[Z](A,G);return G.nodesByHash[N]=f},DG=(Y,Z)=>{if(Y.id===Z)return Y;if(V0(_1[Z]))_0(`Unexpected attempt to overwrite node id ${Z}`);return mZ({id:Z,kind:Y.kind,inner:Y.inner,meta:Y.meta,$:Y.$,ignoreCache:!0})},k$=(Y,Z,X)=>{if(X&&V0(_1[X]))_0(`Unexpected attempt to overwrite node id ${X}`);return mZ({id:X??yZ(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(Q1(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(uZ(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 U1(this.key,()=>this.value.traverseAllows(Y[this.key],Z),Z);return this.optional};traverseApply=(Y,Z)=>{if(this.key in Y)U1(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 uZ=(Y,Z)=>`Invalid intersection of default values ${n(Y)} & ${n(Z)}`;var g$=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 MG 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=p$(this);defaultValueMorphRef=this.defaultValueMorph&&q0(this.defaultValueMorph)}var n8={implementation:g$,Node:MG},y$={},p$=(Y)=>{if(!Y.hasDefault())return;let Z=`{${Y.compiledKey}: ${Y.value.id} = ${B1(Y.default)}}`;return y$[Z]??=dZ(Y.key,Y.value,Y.default)},dZ=(Y,Z,X)=>{if(typeof X==="function")return Z.includesTransform?(G,W)=>{return U1(Y,()=>Z(G[Y]=X(),W),W),G}:(G)=>{return G[Y]=X(),G};let _=Z.includesTransform?Z.assert(X):X;return Q1(_,"object")?(G,W)=>{return U1(Y,()=>Z(G[Y]=X,W),W),G}:(G)=>{return G[Y]=_,G}},r8=(Y,Z,X)=>{let _=O4(Z);if(Q1(Z,"object")&&!_)w(m$(X));let G=Y.in(_?Z():Z);if(G instanceof F1){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},m$=(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 F1)return Z;return{value:Z}}}}as(){return this}brand(Y){if(Y==="")return w(u$);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=IZ(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 O1(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(qZ(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Y)}get props(){if(this.branches.length!==1)return w(d$(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(Z.distribute((X)=>this.applyStructuralOperation("merge",[AG(X)??w(wG("merge",X.expression))])))}applyStructuralOperation(Y,Z){return this.distribute((X)=>{if(X.equals(B.intrinsic.object)&&Y!=="merge")return X;let _=AG(X);if(!_)w(wG(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:
|
|
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 s_=(Y,Z)=>`${KZ(Y)} and ${KZ(Z)}`,KZ=(Y)=>V0(Y)?Y.expression:O0(Y)?Y.map(KZ).join(" | ")||"never":String(Y),qZ=(Y)=>`${Y} results in an unsatisfiable type`;var Y8={},O1=(Y,Z,X)=>M0(Y,Z,{$:X,invert:!1,pipe:!1}),l8=(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 $=Y8[J],Q=$ instanceof S?$.invert():$;return Y8[G]=Q,Q}}let W=!X.pipe||!Y.includesTransform&&!Z.includesTransform;if(W&&Y.equals(Z))return Y;let H=W?jZ(Y,Z,X):Y.hasKindIn(...a4)?EQ(Y,Z,X):jZ(Y,Z,X);if(V0(H)){if(Y.equals(H))H=Y;else if(Z.equals(H))H=Z}return Y8[G]=H,H},jZ=(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}},EQ=(Y,Z,X)=>Y.includesTransform||Z.includesTransform?X.invert?a_(Z,Y,X):a_(Y,Z,X):jZ(Y,Z,X),a_=(Y,Z,X)=>Y.distribute((_)=>DQ(_,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,$)=>J.in.equals(G[$].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)}),DQ=(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 C1 extends c8{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,X1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Y){return O1(this,Y,this.$)}}class X4 extends C1{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 L4(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,LQ(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 c6)?_:[]).sort((X,_)=>X.precedence<_.precedence?-1:X.precedence>_.precedence?1:X.kind==="predicate"&&_.kind==="predicate"?0:X.hash<_.hash?-1:1)},LQ=(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},t_=(...Y)=>w(e_(...Y)),e_=(Y,Z,X)=>{let _=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Z).defaultShortDescription;return`${q_(Y)} operand must be ${Z.description} (was ${_})`};var YG=(Y,Z,X)=>new M4(Y,Z,X,X,null);class i6 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,$)=>{let Q=this.arg$.parse(W[J]);if(!Q.extends(this.constraints[J]))w(VQ($,this.constraints[J].expression,Q.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 i6}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:y_(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 VQ=(Y,Z,X)=>`${Y} must be assignable to ${Z} (was ${X})`;var MQ=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 ZG extends C1{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=L4(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 PZ={implementation:MQ,Node:ZG};var AQ=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Y)=>Number.isInteger(Y)?Y:w(wQ(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/RQ(Y.rule,Z.rule))})},obviatesBasisDescription:!0});class XG extends X4{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 SZ={implementation:AQ,Node:XG};var wQ=(Y)=>`divisor must be an integer (was ${Y})`,RQ=(Y,Z)=>{let X,_=Y,G=Z;while(G!==0)X=G,G=_%G,_=X;return _};class w1 extends X4{boundOperandKind=CQ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=TQ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${NQ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?KQ(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 NQ={"<":">=","<=":">",">":"<=",">=":"<"},IQ={min:"max",minLength:"maxLength",after:"before"},o6={parse:(Y)=>Y||void 0},n6=(Y)=>(Z)=>{if(typeof Z==="number")return{rule:Z};let{exclusive:X,..._}=Z;return X?{..._,rule:Y==="minLength"?_.rule+1:_.rule-1}:_},r6=(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}:_},s6=(Y)=>typeof Y==="string"||typeof Y==="number"?new Date(Y):Y,BQ=(Y,Z)=>`${Y} bound must be a positive integer (was ${Z})`,_8=(Y)=>(Z)=>{if(!Number.isInteger(Z)||Z<0)w(BQ(Y,Z));return Z},CQ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},TQ=(Y,Z)=>`${p0(Y,IQ)?">":"<"}${Z?"":"="}`,KQ=(Y)=>typeof Y==="string"?Y:new Date(Y).toLocaleString(),_G=(Y)=>`Bounded expression ${Y} must be exactly one of number, string, Array, or Date`;var qQ=r({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:s6,serialize:(Y)=>Y.toISOString()}},normalize:r6("after"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or later`,actual:v4},intersections:{after:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class GG 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 vZ={implementation:qQ,Node:GG};var jQ=r({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:s6,serialize:(Y)=>Y.toISOString()}},normalize:r6("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 WG 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 xZ={implementation:jQ,Node:WG};var PQ=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 HG extends X4{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 N0.throwInternalOperandError("exactLength",Y)}}}var hZ={implementation:PQ,Node:HG};var SQ=r({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:o6},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 JG 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 fZ={implementation:SQ,Node:JG};var vQ=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:n6("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 QG 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 N0.throwInternalOperandError("maxLength",Y)}}}var bZ={implementation:vQ,Node:QG};var xQ=r({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:o6},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 kZ={implementation:xQ,Node:$G};var hQ=r({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_8("minLength")}},reduce:(Y)=>Y.rule===0?B.intrinsic.unknown:void 0,normalize:n6("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 zG 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 N0.throwInternalOperandError("minLength",Y)}}}var gZ={implementation:hQ,Node:zG};var FG={min:kZ.implementation,max:fZ.implementation,minLength:gZ.implementation,maxLength:bZ.implementation,exactLength:hZ.implementation,after:vZ.implementation,before:xZ.implementation},UG={min:kZ.Node,max:fZ.Node,minLength:gZ.Node,maxLength:bZ.Node,exactLength:hZ.Node,after:vZ.Node,before:xZ.Node};var fQ=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 OG extends X4{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=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 yZ={implementation:fQ,Node:OG};var i8=(Y,Z)=>{let X=bQ(Y);if(Z&&!Z.includes(X))return w(`Root of kind ${X} should be one of ${Z}`);return X},bQ=(Y)=>{if(y(Y,"root"))return Y.kind;if(typeof Y==="string")return Y[0]==="$"?"alias":(Y in z1)?"domain":"proto";if(typeof Y==="function")return"proto";if(typeof Y!=="object"||Y===null)return w(EG(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 c6)))return"intersection";if("proto"in Y)return"proto";if("domain"in Y)return"domain";return w(EG(Y))},EG=(Y)=>`${n(Y)} is not a valid type schema`,DG={},kQ=(Y)=>O0(Y)?Y.map((Z)=>Z.collapsibleJson):Y.collapsibleJson,_1={};B.nodesByRegisteredId=_1;var pZ=(Y)=>{return DG[Y]??=0,`${Y}${++DG[Y]}`},mZ=(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=zZ(W).sort(([Q],[z])=>t4(Q)?t4(z)?e4(Q)-e4(z):1:t4(z)?-1:Q<z?-1:1).filter(([Q,z])=>{if(Q.startsWith("meta.")){let O=Q.slice(5);return H[O]=z,!1}return!0});for(let Q of J){let z=Q[0],O=Z.keys[z];if(!O)return w(`Key ${z} is not valid on ${Y.kind} schema`);let D=O.parse?O.parse(Q[1],Y):Q[1];if(D!==A1&&(D!==void 0||O.preserveUndefined))_[z]=D}if(Z.reduce&&!Y.prereduced){let Q=Z.reduce(_,Y.$);if(Q){if(Q instanceof S)return Q.throw();return gQ(Q,H)}}return uZ({id:Y.id,kind:Y.kind,inner:_,meta:H,$:Y.$})},uZ=({id:Y,kind:Z,inner:X,meta:_,$:G,ignoreCache:W})=>{let H=G8[Z],J=zZ(X),$=[],Q={};for(let[b,f]of J){let h=H.keys[b],I=h.serialize??(h.child?kQ:B1);if(Q[b]=I(f),h.child===!0){let N=f;if(O0(N))$.push(...N);else $.push(N)}else if(typeof h.child==="function")$.push(...h.child(f))}if(H.finalizeInnerJson)Q=H.finalizeInnerJson(Q);let z={...Q},O={};if(!c1(_))O=o(_,(b,f)=>[b,b==="examples"?f:B1(f)]),z.meta=a6(O,"description",!0);Q=a6(Q,H.collapsibleKey,!1);let D=JSON.stringify({kind:Z,...Q});z=a6(z,H.collapsibleKey,!1);let V=a6(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:Q,innerHash:D,meta:_,metaJson:O,json:z,hash:R,collapsibleJson:V,children:$};if(Z!=="intersection"){for(let b in X)if(b!=="in"&&b!=="out")A[b]=X[b]}let g=new VG[Z](A,G);return G.nodesByHash[R]=g},LG=(Y,Z)=>{if(Y.id===Z)return Y;if(V0(_1[Z]))_0(`Unexpected attempt to overwrite node id ${Z}`);return uZ({id:Z,kind:Y.kind,inner:Y.inner,meta:Y.meta,$:Y.$,ignoreCache:!0})},gQ=(Y,Z,X)=>{if(X&&V0(_1[X]))_0(`Unexpected attempt to overwrite node id ${X}`);return uZ({id:X??pZ(Z.alias??Y.kind),kind:Y.kind,inner:Y.inner,meta:Z,$:Y.$})},a6=(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 o8=(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(dZ(Y.default,Z.default)):Y.default:Z.hasDefault()?Z.default:A1;return X.$.node("optional",{key:_,value:G,default:H})};class n8 extends C1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=B.intrinsic.object.internal;serializedKey=Z4(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 U1(this.key,()=>this.value.traverseAllows(Y[this.key],Z),Z);return this.optional};traverseApply=(Y,Z)=>{if(this.key in Y)U1(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 dZ=(Y,Z)=>`Invalid intersection of default values ${n(Y)} & ${n(Z)}`;var yQ=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:o8}});class MG extends n8{constructor(...Y){super(...Y);if("default"in this.inner)s8(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=mQ(this);defaultValueMorphRef=this.defaultValueMorph&&K0(this.defaultValueMorph)}var r8={implementation:yQ,Node:MG},pQ={},mQ=(Y)=>{if(!Y.hasDefault())return;let Z=`{${Y.compiledKey}: ${Y.value.id} = ${B1(Y.default)}}`;return pQ[Z]??=cZ(Y.key,Y.value,Y.default)},cZ=(Y,Z,X)=>{if(typeof X==="function")return Z.includesTransform?(G,W)=>{return U1(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 U1(Y,()=>Z(G[Y]=X,W),W),G}:(G)=>{return G[Y]=_,G}},s8=(Y,Z,X)=>{let _=O4(Z);if($1(Z,"object")&&!_)w(uQ(X));let G=Y.in(_?Z():Z);if(G instanceof F1){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},uQ=(Y)=>{return`Non-primitive default ${Y===null?"":typeof Y==="number"?`for value at [${Y}] `:`for ${Z4(Y)} `}must be specified as a function like () => ({my: 'object'})`};class T1 extends c8{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 F1)return Z;return{value:Z}}}}as(){return this}brand(Y){if(Y==="")return w(dQ);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=BZ(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 O1(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(qZ(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Y)}get props(){if(this.branches.length!==1)return w(cQ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(Z.distribute((X)=>this.applyStructuralOperation("merge",[AG(X)??w(wG("merge",X.expression))])))}applyStructuralOperation(Y,Z){return this.distribute((X)=>{if(X.equals(B.intrinsic.object)&&Y!=="merge")return X;let _=AG(X);if(!_)w(wG(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 s8(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
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=
|
|
27
|
-
${Y}`,wG=(Y,Z)=>`${Y} operand must be an object (was ${Z})`;var l1=(Y,Z)=>o(
|
|
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=l8(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 t_(Z,_.impliedBasis,this);let W=this.$.node("intersection",{[_.kind]:_}),H=Y==="out"?l8(this,W,this.$):O1(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"?V_(G,{undeclared:1}):{...G,undeclared:Z}:G,X?void 0:{shouldTransform:(_)=>!s1(s4,_.kind)}))}hasEqualMorphs(Y){if(!this.includesTransform&&!Y.includesTransform)return!0;if(!t1(this.shallowMorphs,Y.shallowMorphs))return!1;if(!t1(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 dQ="Expected a non-empty brand name after #",W8=(Y)=>typeof Y==="object"&&!(Y instanceof Date)?{...Y,exclusive:!0}:{rule:Y,exclusive:!0},a8=(Y,Z)=>y(Z,"root")?y(Y,"root")?Y.extends(Z):Z.allows(Y):y(Y,"root")?Y.hasUnit(Z):Z===Y,AG=(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},cQ=(Y)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
27
|
+
${Y}`,wG=(Y,Z)=>`${Y} operand must be an object (was ${Z})`;var l1=(Y,Z)=>o(l6(Y),(X,_)=>[_,Z]);var lQ=(Y)=>typeof Y==="string"?{reference:Y}:Y,RG=(Y)=>Y instanceof S?B.intrinsic.never.internal:Y,iQ=r({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Y)=>Y.startsWith("$")?Y:`$ark.${Y}`},resolve:{}},normalize:lQ,defaults:{description:(Y)=>Y.reference},intersections:{alias:(Y,Z,X)=>X.$.lazilyResolve(()=>RG(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(()=>RG(M0(Y.resolution,Z,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.id}`)})}});class NG extends T1{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(oQ(Z.id,X));X.push(Z.id),Z=_1[Z.id]}if(!y(Z,"root"))return _0(`Unexpected resolution for reference ${this.reference}
|
|
28
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 z1.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
|
|
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 z1.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 oQ=(Y,Z)=>`Alias '${Y}' has a shallow resolution cycle: ${[...Z,Y].join("->")}`,t8={implementation:iQ,Node:NG};class x4 extends T1{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 L4(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 nQ=r({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Y)=>typeof Y==="string"?{domain:Y}:n4(Y,"numberAllowsNaN")&&Y.domain!=="number"?w(t6.writeBadAllowNanMessage(Y.domain)):Y,applyConfig:(Y,Z)=>Y.numberAllowsNaN===void 0&&Y.domain==="number"&&Z.numberAllowsNaN?{...Y,numberAllowsNaN:!0}:Y,defaults:{description:(Y)=>z1[Y.domain],actual:(Y)=>Number.isNaN(Y)?"NaN":z1[y0(Y)]},intersections:{domain:(Y,Z)=>Y.domain==="number"&&Z.domain==="number"?Y.numberAllowsNaN?Z:Y:S.init("domain",Y,Z)}});class IG extends x4{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Y)=>typeof Y==="number"&&!Number.isNaN(Y):(Y)=>y0(Y)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return z1[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 t6={implementation:nQ,Node:IG,writeBadAllowNanMessage:(Y)=>`numberAllowsNaN may only be specified with domain "number" (was ${Y})`};var rQ=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(p0(H,c_)){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)=>BG({},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
30
|
\u25E6 `)}`,problem:(Y)=>`(${Y.actual}) must be...
|
|
31
|
-
${Y.expected}`},intersections:{intersection:(Y,Z,X)=>BG(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
|
|
31
|
+
${Y.expected}`},intersections:{intersection:(Y,Z,X)=>BG(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 CG extends T1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((Y)=>Y.isRefinement());structure=this.inner.structure;expression=sQ(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 lZ={implementation:rQ,Node:CG},sQ=(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},BG=(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 aQ=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(tQ(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 T1{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 t1(this.morphs,Y.morphs,{isEqual:(Z,X)=>Z===X||y(Z,"root")&&y(X,"root")&&Z.equals(X)})}}var iZ={implementation:aQ,Node:TG},tQ=(Y,Z)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
32
32
|
Left: ${Y}
|
|
33
|
-
Right: ${Z}`;var
|
|
33
|
+
Right: ${Z}`;var eQ=r({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Y)=>h8(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(e8.writeInvalidSchemaMessage(Z.proto));if(n4(Z,"dateAllowsInvalid")&&Z.proto!==Date)w(e8.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?R_[Y.builtinName]:`an instance of ${Y.proto.name}`,actual:(Y)=>Y instanceof Date&&Y.toString()==="Invalid Date"?"an invalid Date":x8(Y)},intersections:{proto:(Y,Z)=>Y.proto===Date&&Z.proto===Date?Y.dateAllowsInvalid?Z:Y:DZ(Y.proto,Z.proto)?Y:DZ(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 KG extends x4{builtinName=h8(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 e8={implementation:eQ,Node:KG,writeBadInvalidDateMessage:(Y)=>`dateAllowsInvalid may only be specified with constructor Date (was ${Y.name})`,writeInvalidSchemaMessage:(Y)=>`instanceOf operand must be a function (was ${y0(Y)})`};var Y$=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=z$(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=O_(Y.errors,"propString"),X=Object.entries(Z).map(([_,G])=>{let W=[];for(let $ of G)d1(W,$.expected);let H=H8(W),J=G.every(($)=>$.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(U$(Y.expression,Z.expression));if(_=oZ(Z.branches,Y.branches,X),_ instanceof S)_.invert()}else _=oZ(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 _=oZ(Y.branches,[Z],X);if(_ instanceof S)return _;if(_.length===1)return _[0];return X.$.parseSchema(Y.ordered?{branches:_,ordered:!0}:{branches:_})})}});class PG extends T1{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?J$(this.discriminant):null;expression=this.distribute((Y)=>Y.nestableExpression,$$);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 Q in X){let z=X[Q],O=Q==="default"?Q:`case ${Q}`;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((Q)=>{let z=Q.slice(1,-1);return z==="function"?z1.object:z1[z]}):_),H=this.discriminant.path.map((Q)=>typeof Q==="symbol"?K0(Q):JSON.stringify(Q)),J=JSON.stringify(W),$=this.discriminant.kind==="domain"?`${W$}[${Z}]`:`${H$}(${Z})`;Y.line(`ctx.errorFromNodeContext({
|
|
34
34
|
code: "predicate",
|
|
35
35
|
expected: ${J},
|
|
36
|
-
actual: ${
|
|
36
|
+
actual: ${$},
|
|
37
37
|
relativePath: [${H}],
|
|
38
38
|
meta: ${this.compiledMeta}
|
|
39
|
-
})`)}compileIndiscriminable(Y){if(Y.traversalKind==="Apply"){Y.const("errors","[]");for(let Z of this.branches)Y.line("ctx.pushBranch()").line(Y.invoke(Z)).if("!ctx.hasError()",()=>Y.return(Z.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Y.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:Z}=Y;Y.optimistic=!1;for(let X of this.branches)Y.if(`${Y.invoke(X)}`,()=>Y.return(Z?X.contextFreeMorph?`${
|
|
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],$=O1(W.in,J.in,W.$);if(!($ instanceof S))continue;for(let Q of $){if(!Q.kind||Q.optional)continue;let z,O;if(Q.kind==="domain"){let{l:V,r:R}=Q;z=`"${typeof V==="string"?V:V.domain}"`,O=`"${typeof R==="string"?R:R.domain}"`}else if(Q.kind==="unit")z=Q.l.serializedValue,O=Q.r.serializedValue;else continue;let D=Y.find((V)=>t1(V.path,Q.path)&&V.kind===Q.kind);if(!D)Y.push({kind:Q.kind,cases:{[z]:{branchIndices:[G],condition:Q.l},[O]:{branchIndices:[H],condition:Q.r}},path:Q.path});else{if(D.cases[z])D.cases[z].branchIndices=d1(D.cases[z].branchIndices,G);else D.cases[z]??={branchIndices:[G],condition:Q.l};if(D.cases[O])D.cases[O].branchIndices=d1(D.cases[O].branchIndices,H);else D.cases[O]??={branchIndices:[H],condition:Q.r}}}}}let Z=this.ordered?_$(Y,this.branches):Y;if(!Z.length)return null;let X=Z$(Z,this),_={};for(let G in X.best.cases){let W=X$(X,G);if(W===null){_[G]=!0;continue}if(W.length===this.branches.length)return null;if(this.ordered)W.sort(($,Q)=>$.originalIndex-Q.originalIndex);let H=W.map(($)=>$.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 Z$=(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:SG(X.path)},G=Z.branches.map((W,H)=>({originalIndex:H,branch:W}));return{best:X,location:_,defaultEntries:G,node:Z}},X$=(Y,Z)=>{let X=Y.best.cases[Z],_=G$(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 $=qG(Y.node.branches[J.originalIndex],Y.location);if($===null)G=null;else G?.push({originalIndex:J.originalIndex,branch:$})}else if(J.branch.hasKind("alias")&&_.hasKind("domain")&&_.domain==="object")G?.push(J);else{if(J.branch.in.overlaps(_)){let $=qG(J.branch,Y.location);G?.push({originalIndex:J.originalIndex,branch:$})}W.push(J)}}return Y.defaultEntries=W,G},_$=(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 $=G[J];for(let Q of H)for(let z of $)if(Q>z){if(Z[Q].overlaps(Z[z]))return!1}}}return!0})},G$=(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:[...F_(W).map((H)=>({})),_]}:{domain:"object",required:[{key:W,value:_}]})}return _},SG=(Y)=>Y.reduce((Z,X)=>Z+NZ(X,!0),"data"),W$=K0(E_),H$=K0(n),nZ={implementation:Y$,Node:PG},J$=(Y)=>({kind:Y.kind,path:Y.path.map((Z)=>typeof Z==="string"?Z:Z4(Z)),cases:o(Y.cases,(Z,X)=>[Z,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),Q$={delimiter:" | ",finalDelimiter:" | "},$$=(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}`},oZ=(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 $=M0(Y[W],Z[J],X);if($ instanceof S)continue;if($.equals(Y[W])){_[J].push(Y[W]),H={};break}if($.equals(Z[J]))_[J]=null;else H[J]=$}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},z$=({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=O1(Y[_].in,Y[G].in,Y[0].$);if(W instanceof S)continue;if(!Z)F$(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])},F$=(Y,Z)=>{if(!Y.includesTransform&&!Z.includesTransform)return;if(!t1(Y.shallowMorphs,Z.shallowMorphs))w(jG(Y.expression,Z.expression));if(!t1(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(jG(Y.expression,Z.expression))},qG=(Y,Z)=>Y.transform((X,_)=>{if(X==="domain"||X==="unit")return null;return _},{shouldTransform:(X,_)=>{let G=SG(_.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"}}),jG=(Y,Z)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
40
40
|
Left: ${Y}
|
|
41
|
-
Right: ${Z}`,
|
|
41
|
+
Right: ${Z}`,U$=(Y,Z)=>`The intersection of two ordered unions is indeterminate:
|
|
42
42
|
Left: ${Y}
|
|
43
|
-
Right: ${Z}`;var UQ=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 xG extends x4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=vG(this.unit,this.serializedValue);compiledNegation=vG(this.unit,this.serializedValue,"negated");expression=n(this.unit);domain=y0(this.unit);get defaultShortDescription(){return this.domain==="object"?z1.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 nZ={implementation:UQ,Node:xG},vG=(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 OQ=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(LQ(X.expression));let _=X.branches.filter((G)=>G.hasKind("unit"));if(_.length)return w(EQ(_.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 hG 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 U1(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))U1(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 rZ={implementation:OQ,Node:hG},EQ=(Y)=>`Index keys ${Y.join(", ")} should be specified as named props.`,LQ=(Y)=>`Indexed key definition '${Y}' must be a string or symbol`;var DQ=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 fG 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 sZ={implementation:DQ,Node:fG};var VQ=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(RQ);if(Y.optionals?.length||Y.defaultables?.length)return w(tZ)}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",bG(G[0].result)):X.$.node("union",G.map((W)=>({proto:Array,sequence:bG(W.result)})))}}});class kG extends T1{impliedBasis=B.intrinsic.Array.internal;tuple=wQ(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 TZ(this.flatRefs,this.prevariadic.flatMap((Y,Z)=>Z0(Y.node.flatRefs.map((X)=>b1([`${Z}`,...X.path],X.node)),b1([`${Z}`],Y.node)))),TZ(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=AQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?q0(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++)U1(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 MQ={},AQ=(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(dZ(G,W,H)),X+=`${G}: ${W.id} = ${B1(H)}, `}return X+="]",MQ[X]??=Z},aZ={implementation:VQ,Node:kG},wQ=(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},bG=(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},{}),tZ="A postfix required element cannot follow an optional or defaultable element",RQ="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(uZ(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 pG=(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??"{}"},NQ=pG("description"),IQ=pG("expression"),gG=(Y,Z,X)=>{let _=Y.required?"required":"optional";if(!Z.signature.allows(Y.key))return null;let G=O1(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},BQ=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:NQ},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=O1(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=O1(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=gG(J,H,Z);if(Q instanceof S)return Q}for(let[J,Q]of G.entries()){let $=gG(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 mG 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=q0(this.propsByKey);expression=IQ(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(yG(this.expression,Z))}get(Y,...Z){let X,_=!1,G=KQ(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(jQ(G.expression,this.sequence.expression));return w(yG(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(!U1(H,()=>J.value.traverseAllows(Z[H],X),X))return!1}else if(U1(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",CQ(this))}structuralMorphRef=this.structuralMorph&&q0(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(["),qQ(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 N0.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 eZ={},TQ=(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},CQ=(Y)=>{let Z=TQ(Y);if(!Z)return;if(eZ[Z])return eZ[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 eZ[Z]=X},qQ=(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")})},Y5={implementation:BQ,Node:mG},KQ=(Y)=>{if(y(Y,"root")&&Y.hasKind("unit"))Y=Y.unit;if(typeof Y==="number")Y=`${Y}`;return Y},jQ=(Y,Z)=>`${Y} is not allowed as an array index on ${Z}. Use the 'nonNegativeIntegerString' keyword instead.`,t6=(Y,Z,X)=>{let[_,G]=z_(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},PQ=(Y)=>y(Y,"root")?Y.expression:n(Y),yG=(Y,Z)=>`Key${Z.length===1?"":"s"} ${Z.map(PQ).join(", ")} ${Z.length===1?"does":"do"} not exist on ${Y}`;var G8={...FG,alias:a8.implementation,domain:a6.implementation,unit:nZ.implementation,proto:t8.implementation,union:oZ.implementation,morph:lZ.implementation,intersection:cZ.implementation,divisor:PZ.implementation,pattern:gZ.implementation,predicate:jZ.implementation,required:sZ.implementation,optional:n8.implementation,index:rZ.implementation,sequence:aZ.implementation,structure:Y5.implementation};B.defaultConfig=A_(Object.assign(o(G8,(Y,Z)=>[Y,Z.defaults]),{jitless:T_(),clone:N_,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:N0.defaultConfig}));B.resolvedConfig=m8(B.defaultConfig,B.config);var VG={...UG,alias:a8.Node,domain:a6.Node,unit:nZ.Node,proto:t8.Node,union:oZ.Node,morph:lZ.Node,intersection:cZ.Node,divisor:PZ.Node,pattern:gZ.Node,predicate:jZ.Node,required:sZ.Node,optional:n8.Node,index:rZ.Node,sequence:aZ.Node,structure:Y5.Node};class J8 extends zZ{get[X1](){return"module"}}var Z5=(Y,Z)=>new J8(o(Y,(X,_)=>[X,y(_,"module")?Z5(_,Z):Z.bindReference(_)]));var SQ=(Y)=>O0(Y)?Y:("branches"in Y)&&O0(Y.branches)?Y.branches:void 0,vQ=(Y,Z)=>w(`Node of kind ${Z} is not valid as a ${Y} definition`),uG=(Y)=>`#${Y} duplicates public alias ${Y}`,X5={};B.ambient??={};var dG,lG="function $",xQ=(Y)=>iG(Y,oG(Y)),iG=(Y,Z)=>{let X=Z.write(lG,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}},oG=(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},
|
|
43
|
+
Right: ${Z}`;var O$=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 xG extends x4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=vG(this.unit,this.serializedValue);compiledNegation=vG(this.unit,this.serializedValue,"negated");expression=n(this.unit);domain=y0(this.unit);get defaultShortDescription(){return this.domain==="object"?z1.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 rZ={implementation:O$,Node:xG},vG=(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 E$=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(L$(X.expression));let _=X.branches.filter((G)=>G.hasKind("unit"));if(_.length)return w(D$(_.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 hG extends C1{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 U1(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))U1(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 sZ={implementation:E$,Node:hG},D$=(Y)=>`Index keys ${Y.join(", ")} should be specified as named props.`,L$=(Y)=>`Indexed key definition '${Y}' must be a string or symbol`;var V$=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:o8,optional:o8}});class fG extends n8{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=L4(this.errorContext)}var aZ={implementation:V$,Node:fG};var M$=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 s8(_,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(N$);if(Y.optionals?.length||Y.defaultables?.length)return w(eZ)}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 _=Y6({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",bG(G[0].result)):X.$.node("union",G.map((W)=>({proto:Array,sequence:bG(W.result)})))}}});class kG extends C1{impliedBasis=B.intrinsic.Array.internal;tuple=R$(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=a1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return TZ(this.flatRefs,this.prevariadic.flatMap((Y,Z)=>Z0(Y.node.flatRefs.map((X)=>b1([`${Z}`,...X.path],X.node)),b1([`${Z}`],Y.node)))),TZ(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=w$(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++)U1(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 A$={},w$=(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(cZ(G,W,H)),X+=`${G}: ${W.id} = ${B1(H)}, `}return X+="]",A$[X]??=Z},tZ={implementation:M$,Node:kG},R$=(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},bG=(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},{}),eZ="A postfix required element cannot follow an optional or defaultable element",N$="A postfix element requires a variadic element",Y6=(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=Y6({...Y,fixedVariants:[],r:G.map((D)=>({...D,kind:"prefix"}))});if(O.disjoint.length===0)Y.fixedVariants.push(O)}else if(_.kind==="prefix"&&Z.kind==="variadic"&&W){let O=Y6({...Y,fixedVariants:[],l:X.map((D)=>({...D,kind:"prefix"}))});if(O.disjoint.length===0)Y.fixedVariants.push(O)}let $=M0(Z.node,_.node,Y.ctx);if($ instanceof S)if(J==="prefix"||J==="postfix")Y.disjoint.push(...$.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 Y6({...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(dZ(Z.default,_.default));Y.result=[...Y.result,{kind:J,node:$,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:$}];let Q=Y.l.length,z=Y.r.length;if(Z.kind!=="variadic"||Q>=z&&(_.kind==="variadic"||z===1))Y.l=X;if(_.kind!=="variadic"||z>=Q&&(Z.kind==="variadic"||Q===1))Y.r=G;return Y6(Y)};var pG=(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??"{}"},I$=pG("description"),B$=pG("expression"),gG=(Y,Z,X)=>{let _=Y.required?"required":"optional";if(!Z.signature.allows(Y.key))return null;let G=O1(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},C$=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:I$},intersections:{structure:(Y,Z,X)=>{let _={...Y.inner},G={...Z.inner},W=new S;if(Y.undeclared){let $=Y.keyof();for(let Q of Z.requiredKeys)if(!$.allows(Q))W.add("presence",B.intrinsic.never.internal,Z.propsByKey[Q].value,{path:[Q]});if(G.optional)G.optional=G.optional.filter((Q)=>$.allows(Q.key));if(G.index)G.index=G.index.flatMap((Q)=>{if(Q.signature.extends($))return Q;let z=O1($,Q.signature,X.$);if(z instanceof S)return[];let O=e6(z,Q.value,X.$);if(O.required)G.required=a1(G.required,O.required);if(O.optional)G.optional=a1(G.optional,O.optional);return O.index??[]})}if(Z.undeclared){let $=Z.keyof();for(let Q of Y.requiredKeys)if(!$.allows(Q))W.add("presence",Y.propsByKey[Q].value,B.intrinsic.never.internal,{path:[Q]});if(_.optional)_.optional=_.optional.filter((Q)=>$.allows(Q.key));if(_.index)_.index=_.index.flatMap((Q)=>{if(Q.signature.extends($))return Q;let z=O1($,Q.signature,X.$);if(z instanceof S)return[];let O=e6(z,Q.value,X.$);if(O.required)_.required=a1(_.required,O.required);if(O.optional)_.optional=a1(_.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 $=gG(J,H,Z);if($ instanceof S)return $}for(let[J,$]of G.entries()){let Q=gG($,H,Z);if(Q instanceof S)return Q;if(Q===null)continue;W[J]=Q,X=!0}}if(X)return Z.node("structure",{...Y,optional:W},{prereduced:!0})}}});class mG extends C1{impliedBasis=B.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Y)=>Y.impliedSiblings??[]);props=a1(this.required,this.optional);propsByKey=o(this.props,(Y,Z)=>[Z.key,Z]);propsByKeyReference=K0(this.propsByKey);expression=B$(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 r8.implementation.keys)?[H,J]:[]);return Z[G]=Z0(Z[G],this.$.node(G,W)),Z},{}))}assertHasKeys(Y){let Z=Y.filter((X)=>!a8(X,this.keyof()));if(Z.length)return w(yG(this.expression,Z))}get(Y,...Z){let X,_=!1,G=j$(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(a8(G,H.signature))X=X?.and(H.value)??H.value}if(this.sequence&&a8(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(P$(G.expression,this.sequence.expression));return w(yG(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=u6(this.inner),_=(G)=>{let W=Z.some((H)=>a8(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(!U1(H,()=>J.value.traverseAllows(Z[H],X),X))return!1}else if(U1(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",K$(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(["),q$(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 N0.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 $=1;$<H.length;$++)W=Z.fallback.patternIntersection({code:"patternIntersection",base:J,pattern:H[$].rule});Y.patternProperties??={},Y.patternProperties[J.pattern]=_}}}if(this.undeclared&&!Y.additionalProperties)Y.additionalProperties=!1;return Y}}var Y5={},T$=(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},K$=(Y)=>{let Z=T$(Y);if(!Z)return;if(Y5[Z])return Y5[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 Y5[Z]=X},q$=(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)`,($)=>$.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")})},Z5={implementation:C$,Node:mG},j$=(Y)=>{if(y(Y,"root")&&Y.hasKind("unit"))Y=Y.unit;if(typeof Y==="number")Y=`${Y}`;return Y},P$=(Y,Z)=>`${Y} is not allowed as an array index on ${Z}. Use the 'nonNegativeIntegerString' keyword instead.`,e6=(Y,Z,X)=>{let[_,G]=z_(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},S$=(Y)=>y(Y,"root")?Y.expression:n(Y),yG=(Y,Z)=>`Key${Z.length===1?"":"s"} ${Z.map(S$).join(", ")} ${Z.length===1?"does":"do"} not exist on ${Y}`;var G8={...FG,alias:t8.implementation,domain:t6.implementation,unit:rZ.implementation,proto:e8.implementation,union:nZ.implementation,morph:iZ.implementation,intersection:lZ.implementation,divisor:SZ.implementation,pattern:yZ.implementation,predicate:PZ.implementation,required:aZ.implementation,optional:r8.implementation,index:sZ.implementation,sequence:tZ.implementation,structure:Z5.implementation};B.defaultConfig=A_(Object.assign(o(G8,(Y,Z)=>[Y,Z.defaults]),{jitless:C_(),clone:N_,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:N0.defaultConfig}));B.resolvedConfig=u8(B.defaultConfig,B.config);var VG={...UG,alias:t8.Node,domain:t6.Node,unit:rZ.Node,proto:e8.Node,union:nZ.Node,morph:iZ.Node,intersection:lZ.Node,divisor:SZ.Node,pattern:yZ.Node,predicate:PZ.Node,required:aZ.Node,optional:r8.Node,index:sZ.Node,sequence:tZ.Node,structure:Z5.Node};class J8 extends FZ{get[X1](){return"module"}}var X5=(Y,Z)=>new J8(o(Y,(X,_)=>[X,y(_,"module")?X5(_,Z):Z.bindReference(_)]));var v$=(Y)=>O0(Y)?Y:("branches"in Y)&&O0(Y.branches)?Y.branches:void 0,x$=(Y,Z)=>w(`Node of kind ${Z} is not valid as a ${Y} definition`),uG=(Y)=>`#${Y} duplicates public alias ${Y}`,_5={};B.ambient??={};var dG,lG="function $",h$=(Y)=>iG(Y,oG(Y)),iG=(Y,Z)=>{let X=Z.write(lG,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}},oG=(Y)=>new m6().return(Y.reduce((Z,X)=>{let _=new m8({kind:"Allows"}).indent();X.compile(_);let G=_.write(`${X.id}Allows`),W=new m8({kind:"Apply"}).indent();X.compile(W);let H=W.write(`${X.id}Apply`),J=`${Z}${G},
|
|
44
44
|
${H},
|
|
45
|
-
`;if(!X.hasKind("union"))return J;let
|
|
45
|
+
`;if(!X.hasKind("union"))return J;let $=new m8({kind:"Allows",optimistic:!0}).indent();X.compile($);let Q=$.write(`${X.id}Optimistic`);return`${J}${Q},
|
|
46
46
|
`},`{
|
|
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(X5).length}`,this.name in X5)w(`A Scope already named ${this.name} already exists`);X5[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(uG(W));this.aliases[W]=G}else{if(W in this.aliases)w(uG(_));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}}dG??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[dG.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"&&Q1(Z,"object")){let H=SQ(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:vQ(_,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(W5(Y))}maybeResolveRoot(Y){let Z=this.maybeResolve(Y);if(y(Z,"generic"))return;return Z}maybeResolveSubalias(Y){return _5(this.aliases,Y)??_5(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(sG(Y));return this.resolutions[Y]=this.bindReference(X.root)}return this.resolutions[Y]=this.parse(X,{alias:Y})}createParseContext(Y){let Z=Y.id??yZ(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")?Z5(_,this):cG(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=rG(this,this._exports),this._json=nG(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=oG(this.references);this.precompilation=X.write(lG,4),iG(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=pZ(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=DG(G,_.id);return _1[_.id]=G,G}finalize(Y){if(cG(Y),!Y.precompilation&&!this.resolvedConfig.jitless)xQ(Y.references);return Y}}class G5 extends e6{parseOwnDefinitionFormat(Y,Z){return pZ(Z)}preparseOwnDefinitionFormat(Y,Z){return this.preparseNode(l8(Y),Y,Z)}preparseOwnAliasEntry(Y,Z){return[Y,Z]}normalizeRootScopeValue(Y){return Y}}var cG=(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},nG=(Y)=>o(Y,(Z,X)=>[Z,y(X,"root")||y(X,"generic")?X.json:y(X,"module")?nG(X):_0(`Unexpected resolution ${n(X)}`)]),_5=(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(hQ(_));let W=Z.slice(X+1),H=G[W];if(H===void 0)return _5(G,W);if(y(H,"root")||y(H,"generic"))return H;if(y(H,"module"))return H.root??w(sG(Z));_0(`Unexpected resolution for alias '${Z}': ${n(H)}`)},YY=(Y,Z)=>new G5(Y,Z),Y6=new G5({});var rG=(Y,Z)=>{let X={};for(let _ in Z){let G=Z[_];if(y(G,"module")){let W=rG(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},W5=(Y)=>`'${Y}' is unresolvable`,hQ=(Y)=>`'${Y}' must reference a module to be accessed using dot syntax`,sG=(Y)=>`Reference to submodule '${Y}' must specify an alias`;Y6.export();var{schema:$0,node:$8,defineSchema:jw,generic:q1}=Y6;var H5="^(?:0|[1-9]\\d*)$",fQ=new RegExp(H5),vw=q0(fQ);var aG=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={...aG};var tG=YY({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:H5}},{prereducedAliases:!0}).export();Object.assign(B.intrinsic,tG);var bQ=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={...aG,...tG,...bQ,emptyStructure:$8("structure",{},{prereduced:!0})};B.intrinsic={...d};var Y9=(Y)=>typeof Y==="string"&&Y[0]==="d"&&(Y[1]==="'"||Y[1]==='"')&&Y.at(-1)===Y[1],eG=(Y)=>Y.toString()!=="Invalid Date",Z9=(Y)=>Y.slice(2,-1),J5=(Y)=>`'${Y}' could not be parsed by the Date constructor`,X9=(Y,Z)=>kQ(Y,Z),kQ=(Y,Z)=>{let X=new Date(Y);if(eG(X))return X;let _=h_(Y);if(_!==void 0){let G=new Date(_);if(eG(G))return G}return Z?w(Z===!0?J5(Y):Z):void 0};var $5=(Y,Z)=>{let X=Y.scanner.shiftUntil(gQ[G9[Z]]);if(Y.scanner.lookahead==="")return Y.error(pQ(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(p0(Z,Q5))Y.root=Y.ctx.$.node("unit",{unit:X});else{let _=X9(X,J5(X));Y.root=Y.ctx.$.node("unit",{meta:X,unit:_})}},Q5={"'":1,'"':1},_9={"/":1,"'":1,'"':1},G9={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},gQ={"'":(Y)=>Y.lookahead==="'",'"':(Y)=>Y.lookahead==='"',"/":(Y)=>Y.lookahead==="/"},yQ={'"':"double-quote","'":"single-quote","/":"forward slash"},pQ=(Y,Z)=>`${Z}${Y} requires a closing ${yQ[G9[Z]]}`;var W9=(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 H9={">":!0,">=":!0},J9={"<":!0,"<=":!0};var Q8={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},$9=(Y)=>`Unmatched )${Y===""?"":` before ${Y}`}`,_Y=(Y)=>`Missing ${Y}`,Q9=(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})`,z9=(Y,Z,X,_)=>`An expression may have at most one left bound (parsed ${Y}${Q8[Z]}, ${X}${Q8[_]})`;var F9=(Y,Z,X)=>U9(Y,Z,X,[]),U9=(Y,Z,X,_)=>{let G=X.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Z.params.length)return X.error(z5(Y,Z.names,_.map((W)=>W.expression)));return _}if(G.finalizer===",")return U9(Y,Z,X,_);return G.error(_Y(">"))},z5=(Y,Z,X)=>`${Y}<${Z.join(", ")}> requires exactly ${Z.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var F5=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator();if(Z==="keyof")Y.addPrefix("keyof");else Y.root=uQ(Y,Z)},mQ=(Y,Z,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(z5(Y,Z.names,[]));let G=F9(Y,Z,X);return Z(...G)},uQ=(Y,Z)=>dQ(Y,Z)??cQ(Y,Z)??Y.error(Z===""?Y.scanner.lookahead==="#"?W9(Y.shiftedByOne().scanner.shiftUntilNextTerminator()):U5(Y):W5(Z)),dQ=(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 mQ(Z,X,Y);return w(`Unexpected resolution ${n(X)}`)},cQ=(Y,Z)=>{let X=f_(Z);if(X!==void 0)return Y.ctx.$.node("unit",{unit:X});let _=k_(Z);if(_!==void 0)return Y.ctx.$.node("unit",{unit:_})},U5=(Y)=>{let Z=Y.previousOperator();return Z?O5(Z,Y.scanner.unscanned):lQ(Y.scanner.unscanned)},O5=(Y,Z="")=>`Token '${Y}' requires a right operand${Z?` before '${Z}'`:""}`,lQ=(Y)=>`Expected an expression${Y?` before '${Y}'`:""}`;var E5=(Y)=>Y.scanner.lookahead===""?Y.error(U5(Y)):Y.scanner.lookahead==="("?Y.shiftedByOne().reduceGroupOpen():Y.scanner.lookaheadIsIn(_9)?$5(Y,Y.scanner.shift()):Y.scanner.lookaheadIsIn(E4)?E5(Y.shiftedByOne()):Y.scanner.lookahead==="d"?Y.scanner.nextLookahead in Q5?$5(Y,`${Y.scanner.shift()}${Y.scanner.shift()}`):F5(Y):F5(Y);class G4 extends AZ{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()===""||p0(Z.trimStart()[0],G4.terminatingChars):Y==="="?Z[0]!=="=":Y===","||Y==="?"}var E9=(Y,Z)=>{let X=iQ(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 nQ(Y,X)},L9={"<":1,">":1,"=":1},iQ=(Y,Z)=>Y.scanner.lookaheadIs("=")?`${Z}${Y.scanner.shift()}`:Z;var O9=(Y,Z,X,_)=>{if(X.extends(B.intrinsic.number)){if(typeof Z!=="number")return w(L5(Y,Z,_));return Y==="=="?["min","max"]:Y[0]===">"?["min"]:["max"]}if(X.extends(B.intrinsic.lengthBoundable)){if(typeof Z!=="number")return w(L5(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(_G(X.expression))},oQ=(Y)=>({rule:Y9(Y.limit)?Z9(Y.limit):Y.limit,exclusive:Y.comparator.length===1}),nQ=(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(L5(Z,W,"right"));let H=G.unit,J=Z.length===1,Q=O9(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(!p0(Z,J9))return Y.error(GY(Z));let $=O9(Y.branches.leftBound.comparator,Y.branches.leftBound.limit,X,"left");Y.constrainRoot($[0],oQ(Y.branches.leftBound)),Y.branches.leftBound=null},L5=(Y,Z,X)=>`Comparator ${X==="left"?Q8[Y]:Y} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Z})`;var D9=(Y)=>{Y.scanner.shiftUntilNonWhitespace();let Z=Y.scanner.shiftUntilNextTerminator();Y.root=Y.root.brand(Z)};var M9=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator(),X=b_(Z,{errorOnFail:V9(Z)});if(X===0)Y.error(V9(0));Y.root=Y.root.constrain("divisor",X)},V9=(Y)=>`% operator must be followed by a non-zero integer literal (was ${Y})`;var D5=(Y)=>{let Z=Y.scanner.shift();return Z===""?Y.finalize(""):Z==="["?Y.scanner.shift()==="]"?Y.setRoot(Y.root.array()):Y.error(rQ):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):p0(Z,L9)?E9(Y,Z):Z==="%"?M9(Y):Z==="#"?D9(Y):(Z in E4)?D5(Y):Y.error(WY(Z))},WY=(Y,Z="")=>`'${Y}' is not allowed here${Z&&` (should be ${Z})`}`,rQ="Missing expected ']'";var A9=(Y)=>{let Z=Y.unsetRoot();Y.parseOperand();let X=Y.unsetRoot();if(!X.hasKind("unit"))return Y.error(sQ(X.expression));let _=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Z,"=",_]},sQ=(Y)=>`Default value '${Y}' must a literal value`;var V5=(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=aQ(_);if(_.finalizer===">")w(WY(">"));return G},aQ=(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=A9(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)tQ(Y);return Y},tQ=(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(!p0(X,H9))return this.error(GY(Z));if(this.branches.leftBound)return this.error(z9(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($9(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 D5(this)}parseOperand(){return E5(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Q9(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 eQ="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(eQ)}return Y.shiftUntilNonWhitespace(),Yz(Y,_,Z,X)},w9="extends ",Yz=(Y,Z,X,_)=>{if(Y.shiftUntilNonWhitespace(),Y.unscanned.startsWith(w9))Y.jumpForward(w9.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 M5 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(Xz);if(this.branches.length)w(Zz);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 ${y0(_)})`);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:R9};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:R9},"self");return this.$.finalize(_)}}var R9=(Y)=>Y.throw(),Zz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",Xz="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', '?'] }",I9="Only required keys may specify default values, e.g. { value: 'number = 0' }";var B9=(Y,Z)=>{let X,_={},G=j4(Y);for(let[H,J]of G){let Q=Wz(H);if(Q.kind==="spread"){if(!c1(_))return w(Gz);let V=Z.$.parseOwnDefinitionFormat(J,Z);if(V.equals(d.object))continue;if(!V.hasKind("intersection")||!V.basis?.equals(d.object))return w(Hz(V.expression));X=V.structure;continue}if(Q.kind==="undeclared"){if(J!=="reject"&&J!=="delete"&&J!=="ignore")w(_z(J));_.undeclared=J;continue}let $=JY(J,Z),z=Q;if(Q.kind==="required"){if(!O0($))A5(_,"required",{key:Q.normalized,value:$},Z);else A5(_,"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(I9)}if(Q.kind==="optional"){A5(_,"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})},A5=(Y,Z,X,_)=>{Y[Z]=Z0(Y[Z],_.$.node(Z,X))},_z=(Y)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${n(Y)})`,Gz="Spread operator may only be used as the first key in an object",Wz=(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},Hz=(Y)=>`Spread operand must resolve to an object literal type (was ${Y})`;var C9=(Y,Z)=>Dz(Y)?P9[Y[0]](Y,Z):Ez(Y)?j9[Y[1]](Y,Z):null,Jz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[1],Z).keyof(),w5=(Y,Z)=>{if(Y[2]===void 0)return w(O5(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]==="&"?O1(X,_,Z.$):c8(X,_,Z.$);if(G instanceof S)return G.throw();return G},$z=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).array(),Qz=(Y,Z)=>{if(typeof Y[2]!=="function")return w(q9("=>",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).pipe(Y[2])},q9=(Y,Z)=>`${Y===":"?"Narrow":"Morph"} expression requires a function following '${Y}' (was ${typeof Z})`,zz=(Y,Z)=>{if(typeof Y[2]!=="function")return w(q9(":",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).constrain("predicate",Y[2])},Fz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).configureReferences(Y[2],"shallow"),K9=(Y)=>Y,Uz=K9({"[]":$z,"?":()=>w(ZY)}),Oz=K9({"|":w5,"&":w5,":":zz,"=>":Qz,"|>":w5,"@":Fz,"=":()=>w(XY)}),j9={...Uz,...Oz},Ez=(Y)=>j9[Y[1]]!==void 0,Lz=(Y)=>Y,P9=Lz({keyof:Jz,instanceof:(Y,Z)=>{if(typeof Y[1]!=="function")return w(T9(v8(Y[1])));let X=Y.slice(1).map((_)=>typeof _==="function"?Z.$.node("proto",{proto:_}):w(T9(v8(_))));return X.length===1?X[0]:Z.$.node("union",{branches:X})},"===":(Y,Z)=>Z.$.units(Y.slice(1))}),Dz=(Y)=>P9[Y[0]]!==void 0,T9=(Y)=>`Expected a constructor following 'instanceof' operator (was ${Y})`;var x9=(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(Az(H.expression));X=X.flatMap(($)=>H.distribute((z)=>Mz(m6($),z)))}else X=X.map(($)=>{if(J==="?")return h9($,H);if(J==="=")return Vz($,H,Q);return R5($,H)})}return Z.$.parseSchema(X.map((G)=>c1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},R5=(Y,Z)=>{if(Y.defaultables||Y.optionals)return w(Y.variadic?tZ:wz);if(Y.variadic)Y.postfix=Z0(Y.postfix,Z);else Y.prefix=Z0(Y.prefix,Z);return Y},h9=(Y,Z)=>{if(Y.variadic)return w(f9);return Y.optionals=Z0(Y.optionals,Z),Y},Vz=(Y,Z,X)=>{if(Y.variadic)return w(f9);if(Y.optionals)return w(Rz);return Y.defaultables=Z0(Y.defaultables,[[Z,X]]),Y},S9=(Y,Z)=>{if(Y.postfix)w(v9);if(Y.variadic){if(!Y.variadic.equals(Z))w(v9)}else Y.variadic=Z.internal;return Y},Mz=(Y,Z)=>{let X=Z.select({method:"find",kind:"sequence"});if(!X)return S9(Y,B.intrinsic.unknown);if(X.prefix)for(let _ of X.prefix)R5(Y,_);if(X.optionals)for(let _ of X.optionals)h9(Y,_);if(X.variadic)S9(Y,X.variadic);if(X.postfix)for(let _ of X.postfix)R5(Y,_);return Y},Az=(Y)=>`Spread element must be an array (was ${Y})`,v9="A tuple may have at most one variadic element",wz="A required element may not follow an optional element",f9="An optional element may not follow a variadic element";var Rz="A defaultable element may not follow an optional element without a default";var Nz={},$Y=(Y,Z)=>{if(typeof Y==="string"){if(Z.args&&Object.keys(Z.args).some((_)=>Y.includes(_)))return V5(Y,Z);let X=Nz[Z.$.name]??={};return X[Y]??=V5(Y,Z)}return Q1(Y,"object")?Iz(Y,Z):w(N5(y0(Y)))},Iz=(Y,Z)=>{let X=S8(Y);switch(X){case void 0:if(y(Y,"root"))return Y;return B9(Y,Z);case"Array":return Bz(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(N5("Function"))}default:return w(N5(X??n(Y)))}},Bz=(Y,Z)=>C9(Y,Z)??x9(Y,Z),N5=(Y)=>`Type definitions must be strings or objects (was ${Y})`;class I5 extends h1{constructor(Y){let Z=Object.assign({errors:F1,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 YG(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(w_(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 M5(this);declare=()=>({type:this.type});define(Y){return Y}type=new I5(this);static scope=(Y,Z={})=>new QY(Y,Z);static module=(Y,Z={})=>this.scope(Y,Z).export()}var B5=Object.assign(QY.scope,{define:(Y)=>Y}),Y0=QY;class b9 extends a0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var Tz=q1(["base",d.object],["props",d.object])((Y)=>Y.base.merge(Y.props),b9),k9=Y0.module({Key:d.key,Merge:Tz});class g9 extends a0{}var Cz=q1("element")((Y)=>{let Z=Y.element.exclude(d.Array),X=Z.array();return Z.rawOr(X).pipe(U4).distribute((_)=>_.assertHasKind("morph").declareOut(X),$0)},g9),y9=Y0.module({root:d.Array,readonly:"root",index:d.nonNegativeIntegerString,liftFrom:Cz},{name:"Array"});var T5=$0(["string",S4.FileConstructor]),qz=T5.rawOr(T5.array()),p9=$0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:qz}}),m9=Y0.module({root:["instanceof",FormData],value:T5,parsed:p9,parse:$0({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:p9})},{name:"FormData"});var u9=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 Kz={Boolean:1,Number:1,String:1},d9=Y0.module({...o({...FZ,...OZ},(Y,Z)=>(Y in Kz)?[]:[Y,["instanceof",Z]]),Array:y9,TypedArray:u9,FormData:m9});var jz=$0({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"}),Pz=$0({domain:"number",divisor:1}),zY=Y0.module({root:d.number,integer:Pz,epoch:jz,safe:$0({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",_)},c9=I0(f8,"a well-formed integer string"),X7=Y0.module({root:c9,parse:$0({in:c9,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"}),Sz=I0(/^[\dA-Fa-f]+$/,"hex characters only"),vz=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"}),l9=I0(/^[A-Z].*$/,"capitalized"),xz=Y0.module({root:$0({in:"string",morphs:(Y)=>Y.charAt(0).toUpperCase()+Y.slice(1),declaredOut:l9}),preformatted:l9},{name:"string.capitalize"}),hz=(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)},fz=/^(?: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}))$/,bz=$0({domain:"string",pattern:{meta:"a credit card number",rule:fz.source},predicate:{meta:"a credit card number",predicate:hz}});var kz=/^([+-]?\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 gz=(Y)=>!Number.isNaN(new Date(Y).valueOf()),i9=$0({domain:"string",predicate:{meta:"a parsable date",predicate:gz}}).assertHasKind("intersection"),o9=X7.root.internal.narrow((Y,Z)=>{let X=Number.parseInt(Y),_=zY.epoch(X);if(_ instanceof F1)return Z.errors.merge(_),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),yz=Y0.module({root:o9,parse:$0({in:o9,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.epoch"}),n9=I0(kz,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),pz=Y0.module({root:n9,parse:$0({in:n9,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.iso"}),mz=Y0.module({root:i9,parse:$0({declaredIn:i9,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:pz,epoch:yz},{name:"string.date"}),uz=I0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),r9="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A4=`(${r9}[.]){3}${r9}`,dz=new RegExp(`^${A4}$`),v0="(?:[0-9a-fA-F]{1,4})",cz=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,})?$`),lz=Y0.module({root:["v4 | v6","@","an IP address"],v4:I0(dz,"an IPv4 address","ipv4"),v6:I0(cz,"an IPv6 address","ipv6")},{name:"string.ip"}),U8="a JSON string",_7=(Y)=>{if(!(Y instanceof SyntaxError))throw Y;return`must be ${U8} (${Y})`},iz=$0({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:_7(X)})}}}}),oz=(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:_7(X)})}},nz=Y0.module({root:iz,parse:$0({meta:"safe JSON string parser",in:"string",morphs:oz,declaredOut:d.jsonObject})},{name:"string.json"}),s9=I0(/^[a-z]*$/,"only lowercase letters"),rz=Y0.module({root:$0({in:"string",morphs:(Y)=>Y.toLowerCase(),declaredOut:s9}),preformatted:s9},{name:"string.lower"}),G7=["NFC","NFD","NFKC","NFKD"],_6=o(G7,(Y,Z)=>[Z,$0({domain:"string",predicate:(X)=>X.normalize(Z)===X,meta:`${Z}-normalized unicode`})]),FY=o(G7,(Y,Z)=>[Z,$0({in:"string",morphs:(X)=>X.normalize(Z),declaredOut:_6[Z]})]),sz=Y0.module({root:FY.NFC,preformatted:_6.NFC},{name:"string.normalize.NFC"}),az=Y0.module({root:FY.NFD,preformatted:_6.NFD},{name:"string.normalize.NFD"}),tz=Y0.module({root:FY.NFKC,preformatted:_6.NFKC},{name:"string.normalize.NFKC"}),ez=Y0.module({root:FY.NFKD,preformatted:_6.NFKD},{name:"string.normalize.NFKD"}),YF=Y0.module({root:"NFC",NFC:sz,NFD:az,NFKC:tz,NFKD:ez},{name:"string.normalize"}),a9=I0(g6,"a well-formed numeric string"),ZF=Y0.module({root:a9,parse:$0({in:a9,morphs:(Y)=>Number.parseFloat(Y),declaredOut:d.number})},{name:"string.numeric"}),t9="a regex pattern",XF=$0({domain:"string",predicate:{meta:t9,predicate:(Y,Z)=>{try{return new RegExp(Y),!0}catch(X){return Z.reject({code:"predicate",expected:t9,problem:String(X)})}}},meta:{format:"regex"}}),_F=/^(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-]+)*))?$/,GF=I0(_F,"a semantic version (see https://semver.org/)"),e9=I0(/^\S.*\S$|^\S?$/,"trimmed"),WF=Y0.module({root:$0({in:"string",morphs:(Y)=>Y.trim(),declaredOut:e9}),preformatted:e9},{name:"string.trim"}),Y7=I0(/^[A-Z]*$/,"only uppercase letters"),HF=Y0.module({root:$0({in:"string",morphs:(Y)=>Y.toUpperCase(),declaredOut:Y7}),preformatted:Y7},{name:"string.upper"}),JF=(Y)=>{if(URL.canParse)return URL.canParse(Y);try{return new URL(Y),!0}catch{return!1}},Z7=$0({domain:"string",predicate:{meta:"a URL string",predicate:JF},meta:{format:"uri"}}),$F=Y0.module({root:Z7,parse:$0({declaredIn:Z7,in:"string",morphs:(Y,Z)=>{try{return new URL(Y)}catch{return Z.error("a URL string")}},declaredOut:$0(URL)})},{name:"string.url"}),QF=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"}),W7=Y0.module({root:d.string,alpha:I0(/^[A-Za-z]*$/,"only letters"),alphanumeric:I0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:Sz,base64:vz,capitalize:xz,creditCard:bz,date:mz,digits:I0(/^\d*$/,"only digits 0-9"),email:uz,integer:X7,ip:lz,json:nz,lower:rz,normalize:YF,numeric:ZF,regex:XF,semver:GF,trim:WF,upper:HF,url:$F,uuid:QF},{name:"string"});var H7=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}),J7=Y0.module({root:d.unknown,any:d.unknown},{name:"unknown"}),zF=Y0.module({root:d.jsonObject,stringify:$8("morph",{in:d.jsonObject,morphs:(Y)=>JSON.stringify(Y),declaredOut:d.string})},{name:"object.json"}),$7=Y0.module({root:d.object,json:zF},{name:"object"});class Q7 extends a0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var FF=q1(["K",d.key],"V")((Y)=>({domain:"object",index:{signature:Y.K,value:Y.V}}),Q7);class z7 extends a0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var UF=q1(["T",d.object],["K",d.key])((Y)=>Y.T.pick(Y.K),z7);class F7 extends a0{description='omit a set of properties from an object like `Omit(User, "age")`'}var OF=q1(["T",d.object],["K",d.key])((Y)=>Y.T.omit(Y.K),F7);class U7 extends a0{description="make all named properties of an object optional like `Partial(User)`"}var EF=q1(["T",d.object])((Y)=>Y.T.partial(),U7);class O7 extends a0{description="make all named properties of an object required like `Required(User)`"}var LF=q1(["T",d.object])((Y)=>Y.T.required(),O7);class E7 extends a0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var DF=q1("T","U")((Y)=>Y.T.exclude(Y.U),E7);class L7 extends a0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var VF=q1("T","U")((Y)=>Y.T.extract(Y.U),L7),D7=Y0.module({Exclude:DF,Extract:VF,Omit:OF,Partial:EF,Pick:UF,Record:FF,Required:LF});var w4=B5({...H7,...D7,...d9,...k9,string:W7,number:zY,object:$7,unknown:J7},{prereducedAliases:!0,name:"ark"}),m0=w4.export();Object.assign(F8.ambient,m0);F8.typeAttachments={string:m0.string.root,number:m0.number.root,bigint:m0.bigint,boolean:m0.boolean,symbol:m0.symbol,undefined:m0.undefined,null:m0.null,object:m0.object.root,unknown:m0.unknown.root,false:m0.false,true:m0.true,never:m0.never,arrayIndex:m0.Array.index,Key:m0.Key,Record:m0.Record,Array:m0.Array.root,Date:m0.Date};var E1=Object.assign(w4.type,F8.typeAttachments),MF=w4.match,AF=w4.generic,YB=w4.schema,wF=w4.define,RF=w4.declare;var V7=(Y,Z,X=x0.STORE)=>{return C5(X,{key:`${Y.key}:JSON`,get:({get:_})=>Z.toJson(_(Y)),set:({set:_},G)=>{_(Y,Z.fromJson(G))}})};function M7(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 G1=(Y)=>JSON.parse(Y),z0=(Y)=>JSON.stringify(Y),VB=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function O8(Y){return q7(x0.STORE,Y)}function G6(Y){return I7(x0.STORE,Y)}function K5(...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 v5(Y,Z,X)),{key:Y.key,type:"join",a:Y.between[0],b:Y.between[1],cardinality:Y.cardinality}}function A7(Y){return j7(Y,x0.STORE)}var q5=(Y)=>(Z,X,_,G,...W)=>{console[Y](`${Z} ${X} "${_}" ${G}`,...W)},NF={error:q5("error"),info:q5("info"),warn:q5("warn")},w7=class{logLevel;filter;logger;constructor(Y,Z,X=NF){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)}}};var IF=class{store;constructor(Y=x0.STORE){this.store=Y,B7("root",Y)}allocate(Y,Z,X){return D8(this.store,Y,Z,X)}fuse(Y,Z,X){return T7(this.store,Y,Z,X)}deallocate(Y){V8(this.store,Y)}claim(Y,Z,X){return H6(this.store,Y,Z,X)}},R7=class{store;realm;constructor(Y=x0.STORE){this.store=Y,this.realm=new IF(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 P5(x0.STORE,Y)}function W6(Y){return S5(x0.STORE,Y)}var L1=class Y extends Set{mode="record";subject=new J0;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 x5=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 TF=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}},CF={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 qF(Y,Z){let X=z0(Z),_=`${Y.key}(${X})`,G=CF[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 W1=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)}},J0=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)}},KF=class extends J0{state;constructor(Y){super();this.state=Y}next(Y){this.state=Y,super.next(Y)}};function R4(Y){return"epoch"in Y.transactionMeta}function o0(Y){return"phase"in Y.transactionMeta}var jF=(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 k5=class extends Error{constructor(Y,Z){super(`${f4(Y)} ${z0(Y.key)} not found in store "${Z.config.name}".`)}};function j5(Y,Z,X){return(..._)=>{let G=h0(Y,Z);if(G)return G.run(_,X);throw new k5(Z,Y)}}var g5=(Y)=>(Z)=>Y instanceof Function?Y(Z):Y,VY=(Y,Z)=>{if(Y.valueMap.has(Z.key))return Y.logger.info("\uD83D\uDCD6",Z.type,Z.key,"reading cached value"),_U(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",_),_}}},LY=(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}"`}`)},DY=(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)},h7=(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)},PF=(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 h5(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(h7(X,G))continue;l7(G,X),Q6(X,G)}}}function SF(Y,Z){let X=i(Y),_=X.selectorGraph.getRelationEntries({upstreamSelectorKey:Z.key}).filter(([G,{source:W}])=>W===Z.key);for(let[G]of _){if(h7(X,G))continue;l7(G,X),Q6(X,G)}}var f7=(Y,Z,X)=>{let _=VY(Y,Z),G=_;if(Z.type==="mutable_atom"&&o0(Y)){let{parent:H}=Y;G=b5(Y,Z,H)}G=g5(X)(G),Y.logger.info("\uD83D\uDCDD","atom",Z.key,"set to",G),G=o1(Y,Z.key,G,Z.subject),Q6(Y,Z.key),h5(Y,Z);let W={oldValue:_,newValue:G};if(!o0(Y)){PF(Y,Z,W);return}if(Y.on.transactionApplying.state===null){let{key:H}=Z;if(XU(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=b5(Y,J,z)}if(Q.do(W.newValue)===null)h5(Y,J)}};function S7(Y,Z){let X=Z.default;if(X instanceof Function)X=X();f7(Y,Z,X)}function vF(Y,Z){switch(Z.type){case"atom":case"mutable_atom":S7(Y,Z);break;case"writable_pure_selector":case"writable_held_selector":{let X=k7(Z,Y);for(let _ of X)S7(Y,_)}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 J0,J=Object.assign((Q)=>{let $=z0(Q),z={key:Z.key,subKey:$},O=`${Z.key}(${$})`,L=i(Y),V=Z.default,N={key:O,default:V instanceof Function?()=>V(Q):V};if(Z.effects)N.effects=Z.effects(Q);let A=k4(L,N,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 I7(Y,Z){if("mutable"in Z)return i5(Y,Z);return z6(Y,Z)}var y5=(Y,Z)=>i(Y).atoms.has(Z),xF=(Y,Z)=>i(Y).writableSelectors.has(Z),hF=(Y,Z)=>i(Y).readonlySelectors.has(Z),fF=(Y,Z)=>y5(Y,Z)||xF(Y,Z)||hF(Y,Z),f5=(Y,Z)=>{return i(Y).selectorGraph.getRelationEntries({downstreamSelectorKey:Z}).filter(([_,{source:G}])=>G!==Z).map(([_,{source:G}])=>G).filter((_)=>fF(Y,_))},b7=(Y,Z,X)=>{let _=[],G=f5(Y,Z);while(G.length>0){let W=G.shift();if(X.has(W))continue;if(X.add(W),!y5(Y,W))G.push(...f5(Y,W));else if(!_.includes(W))_.push(W)}return _},k7=(Y,Z)=>{let X=Y.key,_=f5(Z,X),G=new Set;return _.flatMap((W)=>y5(Z,W)?W:b7(Z,W,G)).map((W)=>Z.atoms.get(W))},bF=(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=b7(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)},MY=(Y,Z,X,_)=>({get:(...G)=>{let W=i(Y),H;if(G.length===2){let[z,O]=G;H=H0(Y,z,O)}else[H]=G;let J=h0(Y,H),Q=VY(Y,J),$=H.key;return Y.logger.info("\uD83D\uDD0C",Z,X,`registers dependency ( "${$}" =`,Q,")"),W.selectorGraph.set({upstreamSelectorKey:$,downstreamSelectorKey:X},{source:H.key}),bF(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=H0(Y,$,z)}let J=i(Y),Q=h0(J,W);m7(J,Q,H)},find:(...G)=>H0(Y,...G),json:(G)=>b4(Y,G)}),p5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,{key:H,const:J}=Z,Q="readonly_held_selector",{get:$,find:z,json:O}=MY(_,"readonly_held_selector",H,W),V={...Z,type:"readonly_held_selector",subject:G,install:(A)=>p5(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 N={key:H,type:"readonly_held_selector"};if(X)N.family=X;return N},m5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,H=Z.key,J="readonly_pure_selector",{get:Q,find:$,json:z}=MY(_,"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)=>m5(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 N={key:H,type:"readonly_pure_selector"};if(X)N.family=X;return N},u5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,{key:H,const:J}=Z,Q="writable_held_selector",$=MY(_,"writable_held_selector",H,W),{find:z,get:O,json:L}=$,V={find:z,get:O,json:L},N=(g=Z.get,R=i(Y))=>{return g(V,J),o1(R,H,J,G),W.clear(),J},f={...Z,type:"writable_held_selector",subject:G,install:(g)=>u5(g,Z,X),get:N,set:(g)=>{let R=i(Y),I=N(Z.get,R),K=g5(g)(I);if(Y.logger.info("\uD83D\uDCDD","writable_held_selector",H,"set (",I,"->",K,")"),o1(R,H,K,G),Q6(R,H),R4(R))G.next({newValue:K,oldValue:I});Z.set($,K)},...X&&{family:X}};_.writableSelectors.set(H,f);let b=N();Y.logger.info("\u2728","writable_held_selector",H,"=",b);let k={key:H,type:"writable_held_selector"};if(X)k.family=X;return k},d5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,H=Z.key,J="writable_pure_selector",Q=MY(_,"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 R=k(L);return o1(g,H,R,G),W.clear(),R},A={...Z,type:"writable_pure_selector",subject:G,install:(k)=>d5(k,Z,X),get:V,set:(k)=>{let g=i(Y),R=V(Z.get,g),I=g5(k)(R);if(Y.logger.info("\uD83D\uDCDD","writable_pure_selector",H,"set (",R,"->",I,")"),o1(g,Z.key,I,G),Q6(g,Z.key),R4(g))G.next({newValue:I,oldValue:R});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 C5(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X){let W=u5(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}if(_){let W=p5(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}if(X){let W=d5(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}let G=m5(Y,Z,void 0);return Y.on.selectorCreation.next(G),G}function kF(Y,Z){let X=i(Y),{key:_,type:G}=Z,W=h0(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"},h0(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"},h0(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"},h0(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"},h0(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 J0,$=Object.assign((z)=>{let O=z0(z),L={key:_,subKey:O},V=`${_}(${O})`,N=i(Y),A=m5(N,{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)=>H0(Y,...L),json:(L)=>b4(Y,L)})}});return Y.families.set(_,$),W}function g7(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 J0,$=Object.assign((z)=>{let O=z0(z),L={key:_,subKey:O},V=`${_}(${O})`,N=i(Y),A=p5(N,{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)=>g7(z,Z),default:Z.const});return Y.families.set(_,$),W}function y7(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 J0,$=Object.assign((z)=>{let O=z0(z),L={key:_,subKey:O},V=`${_}(${O})`,N=i(Y),A=u5(N,{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)=>y7(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 J0,$=Object.assign((z)=>{let O=z0(z),L={key:_,subKey:O},V=`${_}(${O})`,N=i(Y),A=d5(N,{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)=>H0(Y,...L),json:(L)=>b4(Y,L)})}});return Y.families.set(_,$),W}function P5(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X)return y7(Y,Z,void 0);if(_)return g7(Y,Z,void 0);if(X)return UY(Y,Z);return h4(Y,Z)}function gF(Y,Z,X){let _=Y.families.get(Z.key);if(_===void 0)throw new k5(Z,Y);let G=_(X),W=i(Y);if(G.family){if(R4(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 yF(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 H0(Y,Z,X){let _=yF(Y,Z,X);if(_)return _;let G=z0(X),W=Y.molecules.get(G);if(!W&&Y.config.lifespan==="immortal"){let H=qF(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(_=gF(Y,Z,X),W)i(Y).moleculeData.set(G,Z.key);return _}function E8(Y,...Z){let X;if(Z.length===1)X=Z[0];else{let _=Z[0],G=Z[1];X=H0(Y,_,G)}try{h0(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":i7(Y,X);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":kF(Y,X);break}}function p7(Y,Z){if(Z.family){let X=Y.families.get(Z.family.key);if(X)return X}}function L8(Y,...Z){let X,_,G;if(Z.length===1){if(X=Z[0],_=p7(Y,X)??null,_)G=X.family?G1(X.family.subKey):null,X=H0(Y,_,G)}else _=Z[0],G=Z[1],X=H0(Y,_,G);if("counterfeit"in X&&"family"in X){let J=X.family.subKey,Q=Y.disposalTraces.buffer.find(($)=>$?.key===J);Y.logger.error("\u274C",X.type,X.key,`could not be reset because it was not found in the store "${Y.config.name}".`,Q?`This state was previously disposed:
|
|
48
|
-
${
|
|
49
|
-
${
|
|
47
|
+
`)+"}");class YY{config;resolvedConfig;name;get[X1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Y,Z){if(this.config=u8(B.config,Z),this.resolvedConfig=u8(B.resolvedConfig,Z),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(_5).length}`,this.name in _5)w(`A Scope already named ${this.name} already exists`);_5[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(uG(W));this.aliases[W]=G}else{if(W in this.aliases)w(uG(_));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}}dG??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[dG.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 i6(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(i8(Y),Y,Z);preparseNode(Y,Z,X){let _=typeof Y==="string"?Y:i8(Z,Y);if(V0(Z)&&Z.kind===_)return Z;if(_==="alias"&&!X?.prereduced){let{reference:H}=t8.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=v$(Z);if(H?.length===1)Z=H[0],_=i8(Z)}if(V0(Z)&&Z.kind===_)return Z;let W=G8[_].normalize?.(Z,this)??Z;if(V0(W))return W.kind===_?W:x$(_,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(H5(Y))}maybeResolveRoot(Y){let Z=this.maybeResolve(Y);if(y(Z,"generic"))return;return Z}maybeResolveSubalias(Y){return G5(this.aliases,Y)??G5(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(sG(Y));return this.resolutions[Y]=this.bindReference(X.root)}return this.resolutions[Y]=this.parse(X,{alias:Y})}createParseContext(Y){let Z=Y.id??pZ(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")?X5(_,this):cG(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=rG(this,this._exports),this._json=nG(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=oG(this.references);this.precompilation=X.write(lG,4),iG(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=mZ(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(cG(Y),!Y.precompilation&&!this.resolvedConfig.jitless)h$(Y.references);return Y}}class W5 extends YY{parseOwnDefinitionFormat(Y,Z){return mZ(Z)}preparseOwnDefinitionFormat(Y,Z){return this.preparseNode(i8(Y),Y,Z)}preparseOwnAliasEntry(Y,Z){return[Y,Z]}normalizeRootScopeValue(Y){return Y}}var cG=(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},nG=(Y)=>o(Y,(Z,X)=>[Z,y(X,"root")||y(X,"generic")?X.json:y(X,"module")?nG(X):_0(`Unexpected resolution ${n(X)}`)]),G5=(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(f$(_));let W=Z.slice(X+1),H=G[W];if(H===void 0)return G5(G,W);if(y(H,"root")||y(H,"generic"))return H;if(y(H,"module"))return H.root??w(sG(Z));_0(`Unexpected resolution for alias '${Z}': ${n(H)}`)},ZY=(Y,Z)=>new W5(Y,Z),Z6=new W5({});var rG=(Y,Z)=>{let X={};for(let _ in Z){let G=Z[_];if(y(G,"module")){let W=rG(Y,G),H=o(W,(J,$)=>[`${_}.${J}`,$]);Object.assign(X,H)}else if(y(G,"root")||y(G,"generic"))X[_]=G;else _0(`Unexpected scope resolution ${n(G)}`)}return X},H5=(Y)=>`'${Y}' is unresolvable`,f$=(Y)=>`'${Y}' must reference a module to be accessed using dot syntax`,sG=(Y)=>`Reference to submodule '${Y}' must specify an alias`;Z6.export();var{schema:Q0,node:Q8,defineSchema:Pw,generic:K1}=Z6;var J5="^(?:0|[1-9]\\d*)$",b$=new RegExp(J5),xw=K0(b$);var aG=ZY({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={...aG};var tG=ZY({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:J5}},{prereducedAliases:!0}).export();Object.assign(B.intrinsic,tG);var k$=ZY({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),d={...aG,...tG,...k$,emptyStructure:Q8("structure",{},{prereduced:!0})};B.intrinsic={...d};var Y9=(Y)=>typeof Y==="string"&&Y[0]==="d"&&(Y[1]==="'"||Y[1]==='"')&&Y.at(-1)===Y[1],eG=(Y)=>Y.toString()!=="Invalid Date",Z9=(Y)=>Y.slice(2,-1),Q5=(Y)=>`'${Y}' could not be parsed by the Date constructor`,X9=(Y,Z)=>g$(Y,Z),g$=(Y,Z)=>{let X=new Date(Y);if(eG(X))return X;let _=h_(Y);if(_!==void 0){let G=new Date(_);if(eG(G))return G}return Z?w(Z===!0?Q5(Y):Z):void 0};var $5=(Y,Z)=>{let X=Y.scanner.shiftUntil(y$[G9[Z]]);if(Y.scanner.lookahead==="")return Y.error(m$(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(p0(Z,z5))Y.root=Y.ctx.$.node("unit",{unit:X});else{let _=X9(X,Q5(X));Y.root=Y.ctx.$.node("unit",{meta:X,unit:_})}},z5={"'":1,'"':1},_9={"/":1,"'":1,'"':1},G9={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},y$={"'":(Y)=>Y.lookahead==="'",'"':(Y)=>Y.lookahead==='"',"/":(Y)=>Y.lookahead==="/"},p$={'"':"double-quote","'":"single-quote","/":"forward slash"},m$=(Y,Z)=>`${Z}${Y} requires a closing ${p$[G9[Z]]}`;var W9=(Y)=>`Private type references should not include '#'. Use '${Y}' instead.`,XY="Optional definitions like 'string?' are only valid as properties in an object or tuple",_Y="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var H9={">":!0,">=":!0},J9={"<":!0,"<=":!0};var $8={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Q9=(Y)=>`Unmatched )${Y===""?"":` before ${Y}`}`,GY=(Y)=>`Missing ${Y}`,$9=(Y,Z)=>`Left bounds are only valid when paired with right bounds (try ...${Z}${Y})`,WY=(Y)=>`Left-bounded expressions must specify their limits using < or <= (was ${Y})`,z9=(Y,Z,X,_)=>`An expression may have at most one left bound (parsed ${Y}${$8[Z]}, ${X}${$8[_]})`;var F9=(Y,Z,X)=>U9(Y,Z,X,[]),U9=(Y,Z,X,_)=>{let G=X.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Z.params.length)return X.error(F5(Y,Z.names,_.map((W)=>W.expression)));return _}if(G.finalizer===",")return U9(Y,Z,X,_);return G.error(GY(">"))},F5=(Y,Z,X)=>`${Y}<${Z.join(", ")}> requires exactly ${Z.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var U5=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator();if(Z==="keyof")Y.addPrefix("keyof");else Y.root=d$(Y,Z)},u$=(Y,Z,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(F5(Y,Z.names,[]));let G=F9(Y,Z,X);return Z(...G)},d$=(Y,Z)=>c$(Y,Z)??l$(Y,Z)??Y.error(Z===""?Y.scanner.lookahead==="#"?W9(Y.shiftedByOne().scanner.shiftUntilNextTerminator()):O5(Y):H5(Z)),c$=(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 u$(Z,X,Y);return w(`Unexpected resolution ${n(X)}`)},l$=(Y,Z)=>{let X=f_(Z);if(X!==void 0)return Y.ctx.$.node("unit",{unit:X});let _=k_(Z);if(_!==void 0)return Y.ctx.$.node("unit",{unit:_})},O5=(Y)=>{let Z=Y.previousOperator();return Z?E5(Z,Y.scanner.unscanned):i$(Y.scanner.unscanned)},E5=(Y,Z="")=>`Token '${Y}' requires a right operand${Z?` before '${Z}'`:""}`,i$=(Y)=>`Expected an expression${Y?` before '${Y}'`:""}`;var D5=(Y)=>Y.scanner.lookahead===""?Y.error(O5(Y)):Y.scanner.lookahead==="("?Y.shiftedByOne().reduceGroupOpen():Y.scanner.lookaheadIsIn(_9)?$5(Y,Y.scanner.shift()):Y.scanner.lookaheadIsIn(E4)?D5(Y.shiftedByOne()):Y.scanner.lookahead==="d"?Y.scanner.nextLookahead in z5?$5(Y,`${Y.scanner.shift()}${Y.scanner.shift()}`):U5(Y):U5(Y);class _4 extends wZ{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in _4.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()===""||p0(Z.trimStart()[0],_4.terminatingChars):Y==="="?Z[0]!=="=":Y===","||Y==="?"}var E9=(Y,Z)=>{let X=o$(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 r$(Y,X)},D9={"<":1,">":1,"=":1},o$=(Y,Z)=>Y.scanner.lookaheadIs("=")?`${Z}${Y.scanner.shift()}`:Z;var O9=(Y,Z,X,_)=>{if(X.extends(B.intrinsic.number)){if(typeof Z!=="number")return w(L5(Y,Z,_));return Y==="=="?["min","max"]:Y[0]===">"?["min"]:["max"]}if(X.extends(B.intrinsic.lengthBoundable)){if(typeof Z!=="number")return w(L5(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(_G(X.expression))},n$=(Y)=>({rule:Y9(Y.limit)?Z9(Y.limit):Y.limit,exclusive:Y.comparator.length===1}),r$=(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(L5(Z,W,"right"));let H=G.unit,J=Z.length===1,$=O9(Z,typeof H==="number"?H:W,X,"right");for(let z of $)Y.constrainRoot(z,Z==="=="?{rule:H}:{rule:H,exclusive:J});if(!Y.branches.leftBound)return;if(!p0(Z,J9))return Y.error(WY(Z));let Q=O9(Y.branches.leftBound.comparator,Y.branches.leftBound.limit,X,"left");Y.constrainRoot(Q[0],n$(Y.branches.leftBound)),Y.branches.leftBound=null},L5=(Y,Z,X)=>`Comparator ${X==="left"?$8[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 M9=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator(),X=b_(Z,{errorOnFail:V9(Z)});if(X===0)Y.error(V9(0));Y.root=Y.root.constrain("divisor",X)},V9=(Y)=>`% operator must be followed by a non-zero integer literal (was ${Y})`;var V5=(Y)=>{let Z=Y.scanner.shift();return Z===""?Y.finalize(""):Z==="["?Y.scanner.shift()==="]"?Y.setRoot(Y.root.array()):Y.error(s$):Z==="|"?Y.scanner.lookahead===">"?Y.shiftedByOne().pushRootToBranch("|>"):Y.pushRootToBranch(Z):Z==="&"?Y.pushRootToBranch(Z):Z===")"?Y.finalizeGroup():_4.lookaheadIsFinalizing(Z,Y.scanner.unscanned)?Y.finalize(Z):p0(Z,D9)?E9(Y,Z):Z==="%"?M9(Y):Z==="#"?L9(Y):(Z in E4)?V5(Y):Y.error(HY(Z))},HY=(Y,Z="")=>`'${Y}' is not allowed here${Z&&` (should be ${Z})`}`,s$="Missing expected ']'";var A9=(Y)=>{let Z=Y.unsetRoot();Y.parseOperand();let X=Y.unsetRoot();if(!X.hasKind("unit"))return Y.error(a$(X.expression));let _=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Z,"=",_]},a$=(Y)=>`Default value '${Y}' must a literal value`;var M5=(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 _4(Y),Z),G=t$(_);if(_.finalizer===">")w(HY(">"));return G},t$=(Y)=>{Y.parseOperand();let Z=X6(Y).root;if(!Z)return _0(`Root was unexpectedly unset after parsing string '${Y.scanner.scanned}'`);if(Y.finalizer==="=")Z=A9(Y);else if(Y.finalizer==="?")Z=[Z,"?"];if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.lookahead)w(HY(Y.scanner.lookahead));return Z},X6=(Y)=>{while(Y.finalizer===void 0)e$(Y);return Y},e$=(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(GY(")"));this.finalizeBranches(),this.finalizer=Y}reduceLeftBound(Y,Z){let X=$8[Z];if(!p0(X,H9))return this.error(WY(Z));if(this.branches.leftBound)return this.error(z9(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(Q9(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 X6(new z8(this.scanner,this.ctx))}parseOperator(){return V5(this)}parseOperand(){return D5(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 Yz="An empty string is not a valid generic parameter name",JY=(Y,Z,X)=>{Y.shiftUntilNonWhitespace();let _=Y.shiftUntilNextTerminator();if(_===""){if(Y.lookahead===""&&Z.length)return Z;return w(Yz)}return Y.shiftUntilNonWhitespace(),Zz(Y,_,Z,X)},w9="extends ",Zz=(Y,Z,X,_)=>{if(Y.shiftUntilNonWhitespace(),Y.unscanned.startsWith(w9))Y.jumpForward(w9.length);else{if(Y.lookahead===",")Y.shift();return X.push(Z),JY(Y,X,_)}let G=X6(new z8(Y,_));return X.push([Z,G.root]),JY(Y,X,_)};class A5 extends h1{$;constructor(Y){super((...Z)=>new _6(Y)(...Z),{bind:Y});this.$=Y}in(Y){return new _6(this.$,Y===void 0?void 0:this.$.parse(Y))}at(Y,Z){return new _6(this.$).at(Y,Z)}case(Y,Z){return new _6(this.$).case(Y,Z)}}class _6 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(_z);if(this.branches.length)w(Xz);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 ${y0(_)})`);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:R9};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:R9},"self");return this.$.finalize(_)}}var R9=(Y)=>Y.throw(),Xz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",_z="At most one key matcher may be specified per expression";var QY=(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', '?'] }",I9="Only required keys may specify default values, e.g. { value: 'number = 0' }";var B9=(Y,Z)=>{let X,_={},G=j4(Y);for(let[H,J]of G){let $=Hz(H);if($.kind==="spread"){if(!c1(_))return w(Wz);let V=Z.$.parseOwnDefinitionFormat(J,Z);if(V.equals(d.object))continue;if(!V.hasKind("intersection")||!V.basis?.equals(d.object))return w(Jz(V.expression));X=V.structure;continue}if($.kind==="undeclared"){if(J!=="reject"&&J!=="delete"&&J!=="ignore")w(Gz(J));_.undeclared=J;continue}let Q=QY(J,Z),z=$;if($.kind==="required"){if(!O0(Q))w5(_,"required",{key:$.normalized,value:Q},Z);else w5(_,"optional",Q[1]==="="?{key:$.normalized,value:Q[0],default:Q[2]}:{key:$.normalized,value:Q[0]},Z);continue}if(O0(Q)){if(Q[1]==="?")w(N9);if(Q[1]==="=")w(I9)}if($.kind==="optional"){w5(_,"optional",{key:$.normalized,value:Q},Z);continue}let O=Z.$.parseOwnDefinitionFormat(z.normalized,Z),D=e6(O,Q,Z.$);if(D.index)_.index=Z0(_.index,D.index);if(D.required)_.required=Z0(_.required,D.required)}let W=Z.$.node("structure",_);return Z.$.parseSchema({domain:"object",structure:X?.merge(W)??W})},w5=(Y,Z,X,_)=>{Y[Z]=Z0(Y[Z],_.$.node(Z,X))},Gz=(Y)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${n(Y)})`,Wz="Spread operator may only be used as the first key in an object",Hz=(Y)=>typeof Y==="symbol"?{kind:"required",normalized:Y}:Y.at(-1)==="?"?Y.at(-2)===f8?{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]===f8&&Y[1]==="["&&Y.at(-1)==="]"?{kind:"required",normalized:Y.slice(1)}:Y==="..."?{kind:"spread"}:Y==="+"?{kind:"undeclared"}:{kind:"required",normalized:Y==="\\..."?"...":Y==="\\+"?"+":Y},Jz=(Y)=>`Spread operand must resolve to an object literal type (was ${Y})`;var T9=(Y,Z)=>Vz(Y)?P9[Y[0]](Y,Z):Dz(Y)?j9[Y[1]](Y,Z):null,Qz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[1],Z).keyof(),R5=(Y,Z)=>{if(Y[2]===void 0)return w(E5(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]==="&"?O1(X,_,Z.$):l8(X,_,Z.$);if(G instanceof S)return G.throw();return G},$z=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).array(),zz=(Y,Z)=>{if(typeof Y[2]!=="function")return w(K9("=>",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).pipe(Y[2])},K9=(Y,Z)=>`${Y===":"?"Narrow":"Morph"} expression requires a function following '${Y}' (was ${typeof Z})`,Fz=(Y,Z)=>{if(typeof Y[2]!=="function")return w(K9(":",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).constrain("predicate",Y[2])},Uz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).configureReferences(Y[2],"shallow"),q9=(Y)=>Y,Oz=q9({"[]":$z,"?":()=>w(XY)}),Ez=q9({"|":R5,"&":R5,":":Fz,"=>":zz,"|>":R5,"@":Uz,"=":()=>w(_Y)}),j9={...Oz,...Ez},Dz=(Y)=>j9[Y[1]]!==void 0,Lz=(Y)=>Y,P9=Lz({keyof:Qz,instanceof:(Y,Z)=>{if(typeof Y[1]!=="function")return w(C9(x8(Y[1])));let X=Y.slice(1).map((_)=>typeof _==="function"?Z.$.node("proto",{proto:_}):w(C9(x8(_))));return X.length===1?X[0]:Z.$.node("union",{branches:X})},"===":(Y,Z)=>Z.$.units(Y.slice(1))}),Vz=(Y)=>P9[Y[0]]!==void 0,C9=(Y)=>`Expected a constructor following 'instanceof' operator (was ${Y})`;var x9=(Y,Z)=>{let X=[{}],_=0;while(_<Y.length){let G=!1;if(Y[_]==="..."&&_<Y.length-1)G=!0,_++;let W=QY(Y[_],Z),[H,J,$]=!O0(W)?[W]:W;if(_++,G){if(!H.extends(B.intrinsic.Array))return w(wz(H.expression));X=X.flatMap((Q)=>H.distribute((z)=>Az(u6(Q),z)))}else X=X.map((Q)=>{if(J==="?")return h9(Q,H);if(J==="=")return Mz(Q,H,$);return N5(Q,H)})}return Z.$.parseSchema(X.map((G)=>c1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},N5=(Y,Z)=>{if(Y.defaultables||Y.optionals)return w(Y.variadic?eZ:Rz);if(Y.variadic)Y.postfix=Z0(Y.postfix,Z);else Y.prefix=Z0(Y.prefix,Z);return Y},h9=(Y,Z)=>{if(Y.variadic)return w(f9);return Y.optionals=Z0(Y.optionals,Z),Y},Mz=(Y,Z,X)=>{if(Y.variadic)return w(f9);if(Y.optionals)return w(Nz);return Y.defaultables=Z0(Y.defaultables,[[Z,X]]),Y},S9=(Y,Z)=>{if(Y.postfix)w(v9);if(Y.variadic){if(!Y.variadic.equals(Z))w(v9)}else Y.variadic=Z.internal;return Y},Az=(Y,Z)=>{let X=Z.select({method:"find",kind:"sequence"});if(!X)return S9(Y,B.intrinsic.unknown);if(X.prefix)for(let _ of X.prefix)N5(Y,_);if(X.optionals)for(let _ of X.optionals)h9(Y,_);if(X.variadic)S9(Y,X.variadic);if(X.postfix)for(let _ of X.postfix)N5(Y,_);return Y},wz=(Y)=>`Spread element must be an array (was ${Y})`,v9="A tuple may have at most one variadic element",Rz="A required element may not follow an optional element",f9="An optional element may not follow a variadic element";var Nz="A defaultable element may not follow an optional element without a default";var Iz={},$Y=(Y,Z)=>{if(typeof Y==="string"){if(Z.args&&Object.keys(Z.args).some((_)=>Y.includes(_)))return M5(Y,Z);let X=Iz[Z.$.name]??={};return X[Y]??=M5(Y,Z)}return $1(Y,"object")?Bz(Y,Z):w(I5(y0(Y)))},Bz=(Y,Z)=>{let X=v8(Y);switch(X){case void 0:if(y(Y,"root"))return Y;return B9(Y,Z);case"Array":return Cz(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(I5("Function"))}default:return w(I5(X??n(Y)))}},Cz=(Y,Z)=>T9(Y,Z)??x9(Y,Z),I5=(Y)=>`Type definitions must be strings or objects (was ${Y})`;class B5 extends h1{constructor(Y){let Z=Object.assign({errors:F1,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 zY extends YY{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 YG(W,Z,this)}]}parseGenericParams(Y,Z){return JY(new _4(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(_Y);if(_[1]==="?")return w(XY)}return _}unit=(Y)=>this.units([Y]);valueOf=(Y)=>this.units(w_(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 A5(this);declare=()=>({type:this.type});define(Y){return Y}type=new B5(this);static scope=(Y,Z={})=>new zY(Y,Z);static module=(Y,Z={})=>this.scope(Y,Z).export()}var C5=Object.assign(zY.scope,{define:(Y)=>Y}),Y0=zY;class b9 extends a0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var Tz=K1(["base",d.object],["props",d.object])((Y)=>Y.base.merge(Y.props),b9),k9=Y0.module({Key:d.key,Merge:Tz});class g9 extends a0{}var Kz=K1("element")((Y)=>{let Z=Y.element.exclude(d.Array),X=Z.array();return Z.rawOr(X).pipe(U4).distribute((_)=>_.assertHasKind("morph").declareOut(X),Q0)},g9),y9=Y0.module({root:d.Array,readonly:"root",index:d.nonNegativeIntegerString,liftFrom:Kz},{name:"Array"});var T5=Q0(["string",S4.FileConstructor]),qz=T5.rawOr(T5.array()),p9=Q0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:qz}}),m9=Y0.module({root:["instanceof",FormData],value:T5,parsed:p9,parse:Q0({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:p9})},{name:"FormData"});var u9=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 jz={Boolean:1,Number:1,String:1},d9=Y0.module({...o({...UZ,...EZ},(Y,Z)=>(Y in jz)?[]:[Y,["instanceof",Z]]),Array:y9,TypedArray:u9,FormData:m9});var Pz=Q0({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"}),Sz=Q0({domain:"number",divisor:1}),FY=Y0.module({root:d.number,integer:Sz,epoch:Pz,safe:Q0({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 Q8("intersection",_)},c9=I0(b8,"a well-formed integer string"),X7=Y0.module({root:c9,parse:Q0({in:c9,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"}),vz=I0(/^[\dA-Fa-f]+$/,"hex characters only"),xz=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"}),l9=I0(/^[A-Z].*$/,"capitalized"),hz=Y0.module({root:Q0({in:"string",morphs:(Y)=>Y.charAt(0).toUpperCase()+Y.slice(1),declaredOut:l9}),preformatted:l9},{name:"string.capitalize"}),fz=(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)},bz=/^(?: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}))$/,kz=Q0({domain:"string",pattern:{meta:"a credit card number",rule:bz.source},predicate:{meta:"a credit card number",predicate:fz}});var gz=/^([+-]?\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 yz=(Y)=>!Number.isNaN(new Date(Y).valueOf()),i9=Q0({domain:"string",predicate:{meta:"a parsable date",predicate:yz}}).assertHasKind("intersection"),o9=X7.root.internal.narrow((Y,Z)=>{let X=Number.parseInt(Y),_=FY.epoch(X);if(_ instanceof F1)return Z.errors.merge(_),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),pz=Y0.module({root:o9,parse:Q0({in:o9,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.epoch"}),n9=I0(gz,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),mz=Y0.module({root:n9,parse:Q0({in:n9,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.iso"}),uz=Y0.module({root:i9,parse:Q0({declaredIn:i9,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:mz,epoch:pz},{name:"string.date"}),dz=I0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),r9="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A4=`(${r9}[.]){3}${r9}`,cz=new RegExp(`^${A4}$`),v0="(?:[0-9a-fA-F]{1,4})",lz=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,})?$`),iz=Y0.module({root:["v4 | v6","@","an IP address"],v4:I0(cz,"an IPv4 address","ipv4"),v6:I0(lz,"an IPv6 address","ipv6")},{name:"string.ip"}),U8="a JSON string",_7=(Y)=>{if(!(Y instanceof SyntaxError))throw Y;return`must be ${U8} (${Y})`},oz=Q0({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:_7(X)})}}}}),nz=(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:_7(X)})}},rz=Y0.module({root:oz,parse:Q0({meta:"safe JSON string parser",in:"string",morphs:nz,declaredOut:d.jsonObject})},{name:"string.json"}),s9=I0(/^[a-z]*$/,"only lowercase letters"),sz=Y0.module({root:Q0({in:"string",morphs:(Y)=>Y.toLowerCase(),declaredOut:s9}),preformatted:s9},{name:"string.lower"}),G7=["NFC","NFD","NFKC","NFKD"],G6=o(G7,(Y,Z)=>[Z,Q0({domain:"string",predicate:(X)=>X.normalize(Z)===X,meta:`${Z}-normalized unicode`})]),UY=o(G7,(Y,Z)=>[Z,Q0({in:"string",morphs:(X)=>X.normalize(Z),declaredOut:G6[Z]})]),az=Y0.module({root:UY.NFC,preformatted:G6.NFC},{name:"string.normalize.NFC"}),tz=Y0.module({root:UY.NFD,preformatted:G6.NFD},{name:"string.normalize.NFD"}),ez=Y0.module({root:UY.NFKC,preformatted:G6.NFKC},{name:"string.normalize.NFKC"}),YF=Y0.module({root:UY.NFKD,preformatted:G6.NFKD},{name:"string.normalize.NFKD"}),ZF=Y0.module({root:"NFC",NFC:az,NFD:tz,NFKC:ez,NFKD:YF},{name:"string.normalize"}),a9=I0(y6,"a well-formed numeric string"),XF=Y0.module({root:a9,parse:Q0({in:a9,morphs:(Y)=>Number.parseFloat(Y),declaredOut:d.number})},{name:"string.numeric"}),t9="a regex pattern",_F=Q0({domain:"string",predicate:{meta:t9,predicate:(Y,Z)=>{try{return new RegExp(Y),!0}catch(X){return Z.reject({code:"predicate",expected:t9,problem:String(X)})}}},meta:{format:"regex"}}),GF=/^(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-]+)*))?$/,WF=I0(GF,"a semantic version (see https://semver.org/)"),e9=I0(/^\S.*\S$|^\S?$/,"trimmed"),HF=Y0.module({root:Q0({in:"string",morphs:(Y)=>Y.trim(),declaredOut:e9}),preformatted:e9},{name:"string.trim"}),Y7=I0(/^[A-Z]*$/,"only uppercase letters"),JF=Y0.module({root:Q0({in:"string",morphs:(Y)=>Y.toUpperCase(),declaredOut:Y7}),preformatted:Y7},{name:"string.upper"}),QF=(Y)=>{if(URL.canParse)return URL.canParse(Y);try{return new URL(Y),!0}catch{return!1}},Z7=Q0({domain:"string",predicate:{meta:"a URL string",predicate:QF},meta:{format:"uri"}}),$F=Y0.module({root:Z7,parse:Q0({declaredIn:Z7,in:"string",morphs:(Y,Z)=>{try{return new URL(Y)}catch{return Z.error("a URL string")}},declaredOut:Q0(URL)})},{name:"string.url"}),zF=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"}),W7=Y0.module({root:d.string,alpha:I0(/^[A-Za-z]*$/,"only letters"),alphanumeric:I0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:vz,base64:xz,capitalize:hz,creditCard:kz,date:uz,digits:I0(/^\d*$/,"only digits 0-9"),email:dz,integer:X7,ip:iz,json:rz,lower:sz,normalize:ZF,numeric:XF,regex:_F,semver:WF,trim:HF,upper:JF,url:$F,uuid:zF},{name:"string"});var H7=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}),J7=Y0.module({root:d.unknown,any:d.unknown},{name:"unknown"}),FF=Y0.module({root:d.jsonObject,stringify:Q8("morph",{in:d.jsonObject,morphs:(Y)=>JSON.stringify(Y),declaredOut:d.string})},{name:"object.json"}),Q7=Y0.module({root:d.object,json:FF},{name:"object"});class $7 extends a0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var UF=K1(["K",d.key],"V")((Y)=>({domain:"object",index:{signature:Y.K,value:Y.V}}),$7);class z7 extends a0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var OF=K1(["T",d.object],["K",d.key])((Y)=>Y.T.pick(Y.K),z7);class F7 extends a0{description='omit a set of properties from an object like `Omit(User, "age")`'}var EF=K1(["T",d.object],["K",d.key])((Y)=>Y.T.omit(Y.K),F7);class U7 extends a0{description="make all named properties of an object optional like `Partial(User)`"}var DF=K1(["T",d.object])((Y)=>Y.T.partial(),U7);class O7 extends a0{description="make all named properties of an object required like `Required(User)`"}var LF=K1(["T",d.object])((Y)=>Y.T.required(),O7);class E7 extends a0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var VF=K1("T","U")((Y)=>Y.T.exclude(Y.U),E7);class D7 extends a0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var MF=K1("T","U")((Y)=>Y.T.extract(Y.U),D7),L7=Y0.module({Exclude:VF,Extract:MF,Omit:EF,Partial:DF,Pick:OF,Record:UF,Required:LF});var w4=C5({...H7,...L7,...d9,...k9,string:W7,number:FY,object:Q7,unknown:J7},{prereducedAliases:!0,name:"ark"}),m0=w4.export();Object.assign(F8.ambient,m0);F8.typeAttachments={string:m0.string.root,number:m0.number.root,bigint:m0.bigint,boolean:m0.boolean,symbol:m0.symbol,undefined:m0.undefined,null:m0.null,object:m0.object.root,unknown:m0.unknown.root,false:m0.false,true:m0.true,never:m0.never,arrayIndex:m0.Array.index,Key:m0.Key,Record:m0.Record,Array:m0.Array.root,Date:m0.Date};var E1=Object.assign(w4.type,F8.typeAttachments),AF=w4.match,wF=w4.generic,ZB=w4.schema,RF=w4.define,NF=w4.declare;var V7=(Y,Z,X=x0.STORE)=>{return K5(X,{key:`${Y.key}:JSON`,get:({get:_})=>Z.toJson(_(Y)),set:({set:_},G)=>{_(Y,Z.fromJson(G))}})};function M7(Y,Z,X){return OY(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 G1=(Y)=>JSON.parse(Y),z0=(Y)=>JSON.stringify(Y),MB=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function O8(Y){return T7(x0.STORE,Y)}function W6(Y){return N7(x0.STORE,Y)}function j5(...Y){if(Y.length===2)return k1(x0.STORE,...Y);return k1(x0.STORE,...Y)}function EY(Y,Z){return K7(x0.STORE,Y,Z)}function A7(Y){return j7(Y,x0.STORE)}var q5=(Y)=>(Z,X,_,G,...W)=>{console[Y](`${Z} ${X} "${_}" ${G}`,...W)},IF={error:q5("error"),info:q5("info"),warn:q5("warn")},w7=class{logLevel;filter;logger;constructor(Y,Z,X=IF){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)}}};var BF=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){L8(this.store,Y)}claim(Y,Z,X){return J6(this.store,Y,Z,X)}},R7=class{store;realm;constructor(Y=x0.STORE){this.store=Y,this.realm=new BF(Y)}allocate(Y,Z,X){D8(this.store,Y,Z,X)}deallocate(Y){L8(this.store,Y)}claim(Y,Z,X){J6(this.store,Y,Z,X)}};function DY(Y){return x5(x0.STORE,Y)}function H6(Y){return v5(x0.STORE,Y)}var D1=class Y extends Set{mode="record";subject=new J0;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 $=!1;while(!$){this.cacheIdx%=this.cacheLimit;let z=this.cache[this.cacheIdx];if(this.cacheIdx--,!z)return"OUT_OF_RANGE";this.undo(z),$=this.cacheIdx===H-1}let Q=Z.substring(X+1);return this.doStep(Q),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 P5(Y=Math.random){return Y().toString(36).slice(2)}function i(Y){while(Y.child!==null)Y=Y.child;return Y}var TF=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}},KF={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 qF(Y,Z){let X=z0(Z),_=`${Y.key}(${X})`,G=KF[Y.type],W={key:_,type:G};return Object.assign(W,{family:{key:Y.key,subKey:X}}),Object.assign(W,{counterfeit:!0}),W}function G4(Y){let Z={key:Y.key,type:Y.type};if("family"in Y)Z.family=Y.family;return Z}var W1=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)}},J0=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)}},jF=class extends J0{state;constructor(Y){super();this.state=Y}next(Y){this.state=Y,super.next(Y)}},PF=(Y,Z)=>{let X=i(Y);if(X.operation.open)return X.operation.prev.get(Z.key);return X.valueMap.get(Z.key)};var h5=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(this===Y)return;if(Y instanceof Promise){let Z=Y;this.fate=Z,Z.then((X)=>{this.pass(Z,X)},(X)=>{this.fail(Z,X)})}else this.resolve(Y),this.fate=void 0}};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 R4(Y){return"epoch"in Y.transactionMeta}function o0(Y){return"phase"in Y.transactionMeta}var LY=(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}"`}`)},VY=(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)},f7=(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)},$6=(Y,Z)=>{if(!Y.operation.open){Y.logger.error("\uD83D\uDC1E","unknown",Z,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}Y.operation.done.add(Z)};function b5(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(f7(X,G))continue;b7(X,G),$6(X,G)}}}function SF(Y,Z){let X=i(Y),_=X.selectorGraph.getRelationEntries({upstreamSelectorKey:Z.key}).filter(([G,{source:W}])=>W===Z.key);for(let[G]of _){if(f7(X,G))continue;b7(X,G),$6(X,G)}}function W4(Y,Z,X,_){let G=Y.valueMap.get(Z);if(G instanceof h5&&!G.done){let W=G;if(X instanceof Promise)return W.use(X),W;return Y.valueMap.set(Z,X),X}if(X instanceof Promise){let W=new h5(X);return Y.valueMap.set(Z,W),W.then(function H(J){if(Y.valueMap.get(Z)===W){W4(Y,Z,J,_);let Q=Y.atoms.get(Z);if(Q)LY(Y,Q),b5(Y,Q),VY(Y);else{let z=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if(z)LY(Y,z),SF(Y,z),VY(Y)}_.next({newValue:J,oldValue:W})}}).catch((H)=>{Y.logger.error("\uD83D\uDCA5","state",Z,"rejected:",H)}),W}return Y.valueMap.set(Z,X),X}var vF=(Y,Z)=>{Z.logger.info("\uD83D\uDCD6",Y.type,Y.key,"reading cached value");let X=Z.valueMap.get(Y.key);if(Y.type==="mutable_atom"&&o0(Z)){let{parent:_}=Z;X=f5(Z,Y,_)}return X},b7=(Y,Z)=>{let X=Y.valueMap.get(Z);if(X instanceof h5){let _=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if(_)_.get();return}if(Y.operation.open)Y.operation.prev.set(Z,X);Y.valueMap.delete(Z),Y.logger.info("\uD83D\uDDD1","state",Z,"evicted")},z6=(Y,Z)=>{if(Y.valueMap.has(Z.key))return vF(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;let G=W4(Y,Z.key,_,Z.subject);return Y.logger.info("\uD83D\uDC81","atom",Z.key,"could not find cached value; using default",_),G}}},S7=(Y,Z,X)=>{return X.subject.subscribe(`${Z.type}:${Z.key}`,(_)=>{Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"root",X.key,"went",_.oldValue,"->",_.newValue);let G=PF(Y,Z),W=z6(Y,Z);Y.logger.info("\u2728",Z.type,Z.key,"went",G,"->",W),Z.subject.next({newValue:W,oldValue:G})})};function F6(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 J0,J=Object.assign(($)=>{let Q=z0($),z={key:Z.key,subKey:Q},O=`${Z.key}(${Q})`,D=i(Y),V=Z.default,R={key:O,default:V instanceof Function?()=>V($):V};if(Z.effects)R.effects=Z.effects($);let A=k4(D,R,z);return W.next({type:"state_creation",token:A}),A},_,{subject:W,install:($)=>F6($,Z),internalRoles:X});return Y.families.set(Z.key,J),Y.defaults.set(Z.key,Z.default),_}function N7(Y,Z){if("mutable"in Z)return l5(Y,Z);return F6(Y,Z)}var k5=(Y)=>(Z)=>Y instanceof Function?Y(Z):Y,xF=(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)},k7=(Y,Z,X)=>{let _=z6(Y,Z),G=_;if(Z.type==="mutable_atom"&&o0(Y)){let{parent:H}=Y;G=f5(Y,Z,H)}G=k5(X)(G),Y.logger.info("\uD83D\uDCDD","atom",Z.key,"set to",G),G=W4(Y,Z.key,G,Z.subject),$6(Y,Z.key),b5(Y,Z);let W={oldValue:_,newValue:G};if(!o0(Y)){xF(Y,Z,W);return}if(Y.on.transactionApplying.state===null){let{key:H}=Z;if(GU(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),$=Y.valueMap.get(H);if(J.type==="mutable_atom"&&o0(Y)){let{parent:z}=Y;$=f5(Y,J,z)}if($.do(W.newValue)===null)b5(Y,J)}};function v7(Y,Z){let X=Z.default;if(X instanceof Function)X=X();k7(Y,Z,X)}function hF(Y,Z){switch(Z.type){case"atom":case"mutable_atom":v7(Y,Z);break;case"writable_pure_selector":case"writable_held_selector":{let X=MY(Y,Z.key);for(let _ of X.values())v7(Y,_)}break}}function g7(Y,Z){if(Z.family){let X=Y.families.get(Z.family.key);if(X)return X}}function E8(Y,...Z){let X,_,G;if(Z.length===1){if(X=Z[0],_=g7(Y,X)??null,_)G=X.family?G1(X.family.subKey):null,X=H0(Y,_,G)}else _=Z[0],G=Z[1],X=H0(Y,_,G);if("counterfeit"in X&&"family"in X){let J=X.family.subKey,$=Y.disposalTraces.buffer.find((Q)=>Q?.key===J);Y.logger.error("\u274C",X.type,X.key,`could not be reset 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 W=LY(Y,X);if(W){let J=Y.on.operationClose.subscribe(`waiting to reset "${X.key}" at T-${W}`,()=>{J(),Y.logger.info("\uD83D\uDFE2",X.type,X.key,`resuming deferred resetState from T-${W}`),E8(Y,X)});return}let H=h0(Y,X);hF(Y,H),VY(Y)}var y7=(Y,Z,X)=>{switch(Z.type){case"atom":case"mutable_atom":k7(Y,Z,X);break;case"writable_pure_selector":case"writable_held_selector":Z.set(X);break}};function R1(Y,...Z){let X,_,G,W;if(Z.length===2){if(X=Z[0],W=Z[1],_=g7(Y,X)??null,_)G=X.family?G1(X.family.subKey):null,X=H0(Y,_,G)}else _=Z[0],G=Z[1],W=Z[2],X=H0(Y,_,G);if("counterfeit"in X&&"family"in X){let $=X.family.subKey,Q=Y.disposalTraces.buffer.find((z)=>z?.key===$);Y.logger.error("\u274C",X.type,X.key,`could not be set because it was not found in the store "${Y.config.name}".`,Q?`This state was previously disposed:
|
|
49
|
+
${Q.trace}`:"No previous disposal trace was found.");return}let H=LY(Y,X);if(H){let $=Y.on.operationClose.subscribe(`waiting to set "${X.key}" at T-${H}`,()=>{$(),Y.logger.info("\uD83D\uDFE2",X.type,X.key,`resuming deferred setState from T-${H}`),R1(Y,X,W)});return}let J=h0(Y,X);y7(Y,J,W),VY(Y)}var p7=(Y,Z)=>i(Y).atoms.has(Z),fF=(Y,Z)=>i(Y).writableSelectors.has(Z),bF=(Y,Z)=>i(Y).readonlySelectors.has(Z),kF=(Y,Z)=>p7(Y,Z)||fF(Y,Z)||bF(Y,Z),x7=(Y,Z)=>{return i(Y).selectorGraph.getRelationEntries({downstreamSelectorKey:Z}).filter(([_,{source:G}])=>G!==Z).map(([_,{source:G}])=>G).filter((_)=>kF(Y,_))},MY=(Y,Z,X=new Set)=>{let _=x7(Y,Z),G=new Map;while(_.length>0){let W=_.pop();if(X.has(W))continue;if(X.add(W),p7(Y,W)){let H=Y.atoms.get(W);G.set(H.key,H)}else _.push(...x7(Y,W))}return G},gF=(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 $=MY(Y,J,G);Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atoms: [ ${[...$.values()].map((Q)=>`"${Q.key}"`).join(", ")} ]`);for(let{key:Q}of $.values())W.selectorAtoms=W.selectorAtoms.set({selectorKey:X,atomKey:Q})}G.add(J)},AY=(Y,Z,X,_)=>({get:(...G)=>{let W=i(Y),H;if(G.length===2){let[z,O]=G;H=H0(Y,z,O)}else[H]=G;let J=h0(Y,H),$=z6(Y,J),Q=H.key;return Y.logger.info("\uD83D\uDD0C",Z,X,`registers dependency ( "${Q}" =`,$,")"),W.selectorGraph.set({upstreamSelectorKey:Q,downstreamSelectorKey:X},{source:H.key}),gF(Y,Z,X,H,_),$},set:(...G)=>{let W,H;if(G.length===2)W=G[0],H=G[1];else{let Q=G[0],z=G[1];H=G[2],W=H0(Y,Q,z)}let J=i(Y),$=h0(J,W);y7(J,$,H)},find:(...G)=>H0(Y,...G),json:(G)=>b4(Y,G)}),g5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,{key:H,const:J}=Z,$="readonly_held_selector",{get:Q,find:z,json:O}=AY(_,"readonly_held_selector",H,W),V={...Z,type:"readonly_held_selector",subject:G,install:(A)=>g5(A,Z,X),get:()=>{let A=i(Y),g=A.selectorGraph.getRelationEntries({downstreamSelectorKey:H});for(let[b,{source:f}]of g)if(f!==H)A.selectorGraph.delete(b,H);return A.selectorAtoms.delete(H),Z.get({get:Q,find:z,json:O},J),W4(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},y5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,H=Z.key,J="readonly_pure_selector",{get:$,find:Q,json:z}=AY(_,"readonly_pure_selector",H,W),D={...Z,type:"readonly_pure_selector",subject:G,install:(R)=>y5(R,Z,X),get:()=>{let R=i(Y),A=R.selectorGraph.getRelationEntries({downstreamSelectorKey:H});for(let[f,{source:h}]of A)if(h!==H)R.selectorGraph.delete(f,H);R.selectorAtoms.delete(H);let g=Z.get({get:$,find:Q,json:z}),b=W4(R,H,g,G);return Y.logger.info("\u2728","readonly_pure_selector",H,"=",b),W.clear(),b},...X&&{family:X}};_.readonlySelectors.set(H,D);let V={key:H,type:"readonly_pure_selector"};if(X)V.family=X;return V},yF=(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 p5=class extends Error{constructor(Y,Z){super(`${f4(Y)} ${z0(Y.key)} not found in store "${Z.config.name}".`)}};function S5(Y,Z,X){return(..._)=>{let G=h0(Y,Z);if(G)return G.run(_,X);throw new p5(Z,Y)}}function pF(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});R1(X,J,H)}function mF(Y){let{stack:Z}=Y;if(Z)return`
|
|
50
50
|
`+Z.split(`
|
|
51
51
|
`)?.slice(1)?.join(`
|
|
52
|
-
`);return""}function
|
|
52
|
+
`);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 $={type:"molecule_creation",key:X,provenance:G};if(o0(J)&&J.transactionMeta.phase==="building")J.transactionMeta.update.updates.push($);else J.on.moleculeCreation.next($);for(let z of H){let O=Y.disposalTraces.buffer.find((D)=>D?.key===z);Y.logger.error("\u274C","molecule",X,"allocation failed:",`Could not allocate to ${z} in store "${Y.config.name}".`,O?`
|
|
53
53
|
${z} was most recently disposed
|
|
54
|
-
${O.trace}`:`No previous disposal trace for ${z} was found.`)}return X}function
|
|
54
|
+
${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 L8(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?`
|
|
55
55
|
This state was most recently deallocated
|
|
56
|
-
${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
|
|
56
|
+
${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},$=i(Y);$.molecules.delete(X);let Q=o0($)&&$.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=G1(V);L8(Y,A)}else W.push(R);let O=$.moleculeData.getRelatedKeys(_.stringKey);if(O)for(let V of O){let R=$.families.get(V),A=H0(Y,R,_.key);H.push([R.key,A]),V8(Y,A)}if($.moleculeGraph.delete(_.stringKey),$.moleculeJoins.delete(_.stringKey),$.moleculeData.delete(_.stringKey),!Q)$.on.moleculeDisposal.next(J);$.molecules.delete(_.stringKey);let D=mF(new Error);Y.disposalTraces.add({key:X,trace:D})}function J6(Y,Z,X,_){let G=z0(X),W=i(Y),H=W.molecules.get(G);if(!H){let D=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}".`,D?`
|
|
57
57
|
${G} was most recently disposed
|
|
58
|
-
${
|
|
58
|
+
${D.trace}`:`No previous disposal trace for ${G} was found.`),X}let J=z0(Z),$=W.molecules.get(J);if(!$){let D=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}".`,D?`
|
|
59
59
|
${J} was most recently disposed
|
|
60
|
-
${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])=>G1(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 uF(Y,Z,X){switch(Z){case"newValue":{u7(Y,X);break}case"oldValue":{E8(X,Y.token);break}}}function dF(Y,Z,X){switch(Z){case"newValue":{E8(X,Y.token);break}case"oldValue":{if(u7(Y,X),Y.subType==="atom")X.valueMap.set(Y.token.key,Y.value);break}}}function u7(Y,Z){let{family:X}=Y.token;if(X){let _=Z.families.get(X.key);if(_)H0(Z,_,G1(X.subKey))}}function cF(Y,Z,X){switch(Z){case"newValue":D8(X,Y.provenance,Y.key);break;case"oldValue":V8(X,Y.key);break}}function lF(Y,Z,X){switch(Z){case"newValue":V8(X,Y.key);break;case"oldValue":{let _=Y.provenance.map(G1);D8(X,_,Y.key);for(let[G,W]of Y.values){let H=X.families.get(G);if(H){H0(X,H,Y.key);let J=`${G}(${z0(Y.key)})`;X.valueMap.set(J,W)}}}break}}function iF(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 d7(Y,Z,X){let _=Y==="newValue"?Z.updates:[...Z.updates].reverse();for(let G of _)switch(G.type){case"atom_update":case"selector_update":pF(Y,G,X);break;case"state_creation":uF(G,Y,X);break;case"state_disposal":dF(G,Y,X);break;case"molecule_creation":cF(G,Y,X);break;case"molecule_disposal":lF(G,Y,X);break;case"molecule_transfer":iF(G,Y,X);break;case"transaction_update":d7(Y,G,X);break}}function c7(Y,Z){return Y.transactionMeta.actionContinuities.getRelatedKey(Z)}function oF(Y,Z){return Y.transactionMeta.epoch.get(Z)}function nF(Y,Z){if(!R4(Y))return;let _=c7(Y,Z);if(_===void 0)return;return oF(Y,_)}function rF(Y,Z,X){if(!R4(Y))return;let G=c7(Y,Z);if(G!==void 0)Y.transactionMeta.epoch.set(G,X)}var sF=(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),d7("newValue",X.transactionMeta.update,_),R4(_))rF(_,X.transactionMeta.update.key,X.transactionMeta.update.epoch),h0(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 aF(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=H0(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:
|
|
61
|
-
${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=h0(Y,_).default(W);return Y.defaults.set(_.key,J),J}}}return VY(Y,h0(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)}},tF=(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 W1(G.timelineTopics.toJSON()),trackers:new Map,transactions:new i1(G.transactions),selectorAtoms:new W1(G.selectorAtoms.toJSON()),selectorGraph:new W1(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 W1(G.moleculeGraph.toJSON(),{makeContentKey:G.moleculeGraph.makeContentKey}),moleculeData:new W1(G.moleculeData.toJSON(),{makeContentKey:G.moleculeData.makeContentKey}),moleculeJoins:new W1(G.moleculeJoins.toJSON(),{makeContentKey:G.moleculeJoins.makeContentKey}),miscResources:new i1(G.miscResources)},H=nF(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:(...$)=>{R1(Q,...$)},reset:(...$)=>{L8(Q,...$)},run:($,z=N7())=>j5(Q,$,z),find:(...$)=>H0(Y,...$),json:($)=>b4(Q,$),dispose:(...$)=>{E8(Q,...$)},env:()=>aF(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 S5(Y,Z){let{key:X}=Z,_=Y.transactions.has(X),G={key:X,type:"transaction",run:(J,Q)=>{let $=tF(Y,X,J,Q);try{let z=i(Y),{toolkit:O}=$.transactionMeta,L=Z.do(O,...J);return sF(L,z),L}catch(z){throw jF(W),Y.logger.warn("\uD83D\uDCA5","transaction",X,"caught:",z),z}},install:(J)=>S5(J,Z),subject:new J0},W=i(Y);W.transactions.set(X,G);let H=W4(G);if(!_)Y.on.transactionCreation.next(H);return H}var C7=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 W1({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new W1({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 W1({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new W1({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new TF(100);molecules=new Map;moleculeJoins=new W1({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeGraph=new W1({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeData=new W1({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});miscResources=new Map;on={atomCreation:new J0,atomDisposal:new J0,selectorCreation:new J0,selectorDisposal:new J0,timelineCreation:new J0,transactionCreation:new J0,transactionApplying:new KF(null),operationClose:new J0,moleculeCreation:new J0,moleculeDisposal:new J0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new w7("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},R4(Z))this.transactionMeta={epoch:new Map(Z?.transactionMeta.epoch),actionContinuities:new W1(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=o5(_);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 C7({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function h0(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 k5(Z,Y)}var eF=(Y,Z)=>{let X=i(Y);if(X.operation.open)return X.operation.prev.get(Z.key);return X.valueMap.get(Z.key)};var v7=(Y,Z)=>{let X=i(Y);return k7(Z,Y).map((G)=>{return G.subject.subscribe(`${Z.type}:${Z.key}`,(W)=>{Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"root",G.key,"went",W.oldValue,"->",W.newValue);let H=eF(X,Z),J=VY(X,Z);Y.logger.info("\u2728",Z.type,Z.key,"went",H,"->",J),Z.subject.next({newValue:J,oldValue:H})})})};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=h0(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=v7(Y,W),Q=(O)=>{if(J)J.length=0,J.push(...v7(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 YU=(Y,Z,X,_)=>{let G=h0(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 c5=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)=>{R1(X,Z,W)}),this.unsubscribeFromState=$6(X,Y,_,(W)=>{if(W.newValue!==W.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=W.newValue.subscribe(_,(H)=>{R1(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 $=YU(X,{key:H,type:"timeline"},_,(z)=>{$(),R1(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)R1(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 l5(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 J0,$={...Z,type:J,install:(L)=>{return L.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${L.config.name}"`),l5(L,Z,X)},subject:Q};if(X)$.family=X;let z=W();_.atoms.set($.key,$),o1(_,G,z,Q);let O=W4($);if(Z.effects){let L=0,V=[];for(let N of Z.effects){let A=N({resetSelf:()=>{L8(Y,O)},setSelf:(f)=>{R1(Y,O,f)},onSet:(f)=>$6(Y,O,`effect[${L}]`,f)});if(A)V.push(A);++L}$.cleanup=()=>{for(let N of V)N()}}if(new c5(O,Y),!X)V7(O,Z,Y);return O}var ZU=class{trackers=new Map;latestUpdateAtoms;mutableAtoms;constructor(Y,Z){let X=z6(Z,{key:`*${Y.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=h0(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=G1(W.family.subKey);switch(G){case"state_creation":this.trackers.set(H,new c5(W,Z));break;case"state_disposal":{let J=this.trackers.get(H);if(J)J[Symbol.dispose](),this.trackers.delete(H)}break}}})}};function i5(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 J0,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 N=l5(L,V,z);return W.next({type:"state_creation",token:N}),N},_,{subject:W,install:(Q)=>i5(Q,Z),toJson:Z.toJson,fromJson:Z.fromJson,internalRoles:X});return Y.families.set(Z.key,J),M7(Y,J,Z),new ZU(J,Y),_}var x7=(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=h0(_,W),J=JSON.parse(Z.family.subKey);return H0(Y,H,J)}return{type:"writable_pure_selector",key:`${Z.key}:JSON`}};var o5=(Y)=>{let X={type:"atom",key:`*${Y.key}`};if(Y.family)X.family={key:`*${Y.family.key}`,subKey:Y.family.subKey};return X};function XU(Y){return typeof Y==="object"&&Y!==null&&"do"in Y&&"undo"in Y&&"subscribe"in Y}function b5(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 c5(Z,X),H}function o1(Y,Z,X,_){let G=Y.valueMap.get(Z);if(G instanceof x5){let W=G;if(X instanceof Promise)return W.use(X),W;return Y.valueMap.set(Z,X),X}if(X instanceof Promise){let W=new x5(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)LY(Y,Q),h5(Y,Q),DY(Y);else{let $=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if($)LY(Y,$),SF(Y,$),DY(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 _U=(Y,Z)=>{let X=Z.valueMap.get(Y.key);if(Y.type==="mutable_atom"&&o0(Z)){let{parent:_}=Z;X=b5(Z,Y,_)}return X},l7=(Y,Z)=>{let X=Z.valueMap.get(Y);if(X instanceof x5){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")};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 J0,$={...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,$),o1(H,G,z,Q);let O=W4($);if(Z.effects){let L=0,V=[];for(let N of Z.effects){let A=N({resetSelf:()=>{L8(Y,O)},setSelf:(f)=>{R1(Y,O,f)},onSet:(f)=>$6(Y,O,`effect[${L}]`,f)});if(A)V.push(A);++L}$.cleanup=()=>{for(let N of V)N()}}return O}function q7(Y,Z){if("mutable"in Z){let G=l5(Y,Z,void 0);return Y.on.atomCreation.next(G),G}let _=k4(Y,Z,void 0);return Y.on.atomCreation.next(_),_}function i7(Y,Z){let X=i(Y),{key:_,family:G}=Z,W=h0(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=h0(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=o5(Z);i7(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 v5=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 R7(X),this.options=Y,this.defaultContent=Z,this.store.miscResources.set(`join:${Y.key}`,this),this.realm.allocate("root",Y.key),this.toolkit={get:(...R)=>k1(X,...R),set:(...R)=>{R1(X,...R)},find:(...R)=>H0(X,...R),json:(R)=>b4(X,R)};let _=Y.between[0],G=Y.between[1],W=i5(X,{key:`${Y.key}/relatedKeys`,default:()=>new L1,mutable:!0,fromJson:(R)=>L1.fromJSON(R),toJson:(R)=>R.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:W};let H=({get:R},I)=>R(W,I),J=({set:R},I,K)=>{if(!this.store.molecules.has(z0(I)))this.realm.allocate(Y.key,I);R(W,I,(q)=>q.add(K)),R(W,K,(q)=>q.add(I))},Q=({set:R},I,K)=>{R(W,I,(q)=>{return q.delete(K),q}),R(W,K,(q)=>{return q.delete(I),q})},$=(R,I,K)=>{let{find:q,get:p,set:s}=R,T=q(W,I),t=p(T);for(let m of t){if(K.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 K){let b0=H(R,U0),$1=b0.has(I);if(this.relations.cardinality==="1:n"){let s1=[];for(let C of b0){if(C===I)continue;let u=H(R,C);if(u.delete(U0),u.size===0)s1.push(C)}if(!$1&&b0.size>0)b0.clear();for(let C of s1){let u=[U0,C].sort(),G0=`"${u[0]}:${u[1]}"`;this.molecules.delete(G0)}}if(!$1)b0.add(I);e.add(U0)}return!0}),m})},z=(R,I,K)=>{let{set:q}=R;q(W,I,(p)=>{return p.transaction((s)=>{for(let T of K)s.add(T);return!0}),p});for(let p of K)q(W,p,(s)=>{return s.add(I),s});return!0},O=(R,I,K)=>{let q=H(R,I);return K?q.has(K):q.size>0},L={getRelatedKeys:(R)=>H(this.toolkit,R),addRelation:(R,I)=>{this.store.moleculeJoins.set(R,Y.key),this.store.moleculeJoins.set(I,Y.key),J(this.toolkit,R,I)},deleteRelation:(R,I)=>{Q(this.toolkit,R,I)},replaceRelationsSafely:(R,I)=>{$(this.toolkit,R,I)},replaceRelationsUnsafely:(R,I)=>{z(this.toolkit,R,I)},has:(R,I)=>O(this.toolkit,R,I)},V,N;if(Z){N=z6(X,{key:`${Y.key}/content`,default:Z},["join","content"]);let R=({get:q},p)=>q(N,p),I=({set:q},p,s)=>{q(N,p,s)};V=Object.assign(L,{getContent:(q)=>{return R(this.toolkit,q)},setContent:(q,p)=>{I(this.toolkit,q,p)},deleteContent:(q)=>{this.realm.deallocate(q)}})}else V=L;let A=new W1(Y,{externalStore:V,isAType:Y.isAType,isBType:Y.isBType,makeContentKey:(...R)=>{let[I,K]=R,q=R.sort(),p=`${q[0]}:${q[1]}`,s=X.molecules.get(z0(I)),T=X.molecules.get(z0(K));if(!s)this.realm.allocate(Y.key,I);if(!T)this.realm.allocate(Y.key,K);return this.realm.allocate(I,p,"all"),this.realm.claim(K,p),this.store.moleculeJoins.set(p,Y.key),p}}),f=()=>h4(X,{key:`${Y.key}/singleRelatedKey`,get:(R)=>({get:I})=>{let K=I(W,R);for(let q of K)return q;return null}},["join","keys"]),b=()=>{return h4(X,{key:`${Y.key}/multipleRelatedKeys`,get:(R)=>({get:I})=>{let K=x7(W,X);return I(K,R).members}},["join","keys"])},k=()=>h4(X,{key:`${Y.key}/singleRelatedEntry`,get:(R)=>({get:I})=>{let K=I(W,R);for(let q of K){let p=A.isAType?.(R)?R:void 0,s=p===void 0?R:void 0;p??=q,s??=q;let T=A.makeContentKey(p,s),t=I(N,T);return[q,t]}return null}},["join","entries"]),g=()=>h4(X,{key:`${Y.key}/multipleRelatedEntries`,get:(R)=>({get:I})=>{let K=x7(W,X);return I(K,R).members.map((p)=>{let s=A.isAType?.(R)?R:void 0,T=s===void 0?R:void 0;s??=p,T??=p;let t=A.makeContentKey(s,T),m=I(N,t);return[p,m]})}},["join","entries"]);switch(Y.cardinality){case"1:1":{let R=f(),I=`${_}KeyOf${B0(G)}`,K=`${G}KeyOf${B0(_)}`,q={[I]:R,[K]:R},p;if(Z){let s=k(),T=`${_}EntryOf${B0(G)}`,t=`${G}EntryOf${B0(_)}`,m={[T]:s,[t]:s};p=Object.assign(q,m)}else p=q;this.relations=A,this.states=p;break}case"1:n":{let R=f(),I=b(),K=`${_}KeyOf${B0(G)}`,q=`${G}KeysOf${B0(_)}`,p={[K]:R,[q]: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 R=b(),I=`${_}KeysOf${B0(G)}`,K=`${G}KeysOf${B0(_)}`,q={[I]:R,[K]:R},p;if(Z){let s=g(),T=`${_}EntriesOf${B0(G)}`,t=`${G}EntriesOf${B0(_)}`,m={[T]:s,[t]:s};p=Object.assign(q,m)}else p=q;this.relations=A,this.states=p}}}};function n5(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 v5(G.options,G.defaultContent,Z),Z.joins.set(Y.key,X)}return X}function J6(Y,Z,X){let _=n5(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 _=n5(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 H0(X,Q,Z)},get[H](){let Q=_.states[H];return H0(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 H0(X,$,Z)},get[Q](){let $=_.states[Q];return H0(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 H0(X,Q,Z)},get[H](){let Q=_.states[H];return H0(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 H0(X,$,Z)},get[Q](){let $=_.states[Q];return H0(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 H0(X,Q,Z)},get[H](){let Q=_.states[H];return H0(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 H0(X,$,Z)},get[Q](){let $=_.states[Q];return H0(X,$,Z)}})}}}return G}function j7(Y,Z){return n5(Y,Z).core.relatedKeysAtoms}function M8(Y){return Y.startsWith("\uD83D\uDD0D ")}var GU=(Y)=>{return k4(Y,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Z=new Map;for(let[X,_]of Y.atoms){if(M8(X))continue;let G=W4(_);if(_.family){let W=Z.get(_.family.key);if(!W||!("familyMembers"in W))W={key:_.family.key,familyMembers:new Map},Z.set(_.family.key,W);W.familyMembers.set(_.family.subKey,G)}else Z.set(X,G)}return Z},effects:[({setSelf:Z})=>{Y.on.atomCreation.subscribe("introspection",(X)=>{if(M8(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H===void 0||!("familyMembers"in H))H={key:G,familyMembers:new Map},_.set(G,H);H.familyMembers.set(W,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.atomDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H&&"familyMembers"in H){if(H.familyMembers.delete(W),H.familyMembers.size===0)_.delete(G)}}return new Map(_)})})}]},void 0)},WU=(Y)=>{return k4(Y,{key:"\uD83D\uDD0D Selector Token Index",default:()=>{let Z=new Map;for(let X of[Y.readonlySelectors,Y.writableSelectors])for(let[_,G]of X){if(M8(_))continue;let W=W4(G);if(G.family){let H=Z.get(G.family.key);if(!H||!("familyMembers"in H))H={key:G.family.key,familyMembers:new Map},Z.set(G.family.key,H);H.familyMembers.set(G.family.subKey,W)}else Z.set(_,W)}return Z},effects:[({setSelf:Z})=>{Y.on.selectorCreation.subscribe("introspection",(X)=>{if(M8(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H===void 0||!("familyMembers"in H))H={key:G,familyMembers:new Map},_.set(G,H);H.familyMembers.set(W,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.selectorDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H&&"familyMembers"in H){if(H.familyMembers.delete(W),H.familyMembers.size===0)_.delete(G)}}else _.delete(X.key);return new Map(_)})})}]},void 0)};var r5=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}},n7=new r5({number:(Y)=>typeof Y==="number",string:(Y)=>typeof Y==="string",boolean:(Y)=>typeof Y==="boolean",null:(Y)=>Y===null});function r7(Y){if(!Y)return!1;return Object.getPrototypeOf(Y)===Object.prototype}var s7=new r5({object:r7,array:(Y)=>Array.isArray(Y)}),HU=new r5({...n7.supported,...s7.supported}),AY=(Y)=>{if(Y===void 0)return"undefined";let Z=HU.refine(Y);if(Z)return Z.type;return Object.getPrototypeOf(Y).constructor.name};var lB=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=K5(this.atomIndex),_=K5(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}},o7=(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]):r7(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 a7(Y,Z,X){let _="",G=[],W=[],H=[];return o7(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])}}}),o7(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 a7(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=AY(Y),W=AY(Z);if(G===W)return{summary:`${G} \u2192 ${W}`};return{summary:`Type change: ${G} \u2192 ${W}`}}},iB=new FU(n7,s7,{number:JU,string:$U,boolean:QU,null:()=>({summary:"No Change"}),object:a7,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")}},tB=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 eB=O8({key:"usersInRoomIndex",mutable:!0,default:()=>new L1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>L1.fromJSON(Y)}),s5=O8({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),YT=EY({key:"usersInMyRoomView",get:(Y)=>({find:Z})=>{let X=A7(F6);return[Z(X,Y)]}});import{spawn as EU}from"child_process";var a5=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 a5{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=G1(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=G1(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=G1(this.incompleteLog);this.handleLog(H);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)H=G1(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 a5{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(Y){super((...Z)=>{return this.out.next(Z),this});this.id=Y,this.in=new J0,this.out=new J0,this.in.subscribe("socket",(Z)=>{this.handleEvent(...Z)})}dispose(){for(let Y of this.disposalFunctions)Y()}},t7=class extends a5{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 _=G1(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=G1(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)}},e7=G6({key:"roomArguments",default:["echo",["Hello World!"]]}),VU=EY({key:"room",get:(Y)=>async({get:Z,find:X})=>{let _=X(e7,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)}}),zT=W6({key:"createRoom",do:({get:Y,set:Z,find:X},_,G,W)=>{let H=W?[G,W]:[G],J=X(e7,_);Z(J,H),Z(s5,(z)=>z.add(_));let Q=X(VU,_);return Y(Q)}}),FT=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}}),UT=W6({key:"leaveRoom",do:(Y,Z,X)=>{J6(F6,(_)=>{_.delete({room:Z,user:X})},Y.env().store)}}),OT=W6({key:"destroyRoom",do:(Y,Z)=>{J6(F6,(X)=>{X.delete({room:Z})},Y.env().store),Y.set(s5,(X)=>(X.delete(Z),X))}});var ET=G6({key:"redactor",default:{occlude:(Y)=>Y}}),LT=G6({key:"unacknowledgedUpdates",default:()=>[]}),DT=G6({key:"sockets",default:null}),VT=O8({key:"socketsIndex",mutable:!0,default:()=>new L1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>L1.fromJSON(Y)}),MT=O8({key:"usersIndex",mutable:!0,default:()=>new L1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>L1.fromJSON(Y)}),AT=OY({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(Y)=>Y.startsWith("user::"),isBType:(Y)=>Y.startsWith("socket::")});var{file:SH,serve:xO}=globalThis.Bun;import{readFileSync as X3}from"fs";import{createServer as RU}from"http";import{createServer as NU}from"https";import{resolve as e5}from"path";function Y3(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(Y3(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 t5(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);Y3($,"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)},N=(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(N(g))return;if(!V(g))return O(g);return Reflect.get(k,g)}})}var AU="__vite_start_time"in globalThis,wU=typeof window!=="undefined",PT="vitest"in globalThis,H4=E1("string"),Z3=E1('"true" | "false" | undefined'),g1=t5({isServer:!AU&&!wU,server:{CI:E1("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:Z3.pipe((Y)=>Y==="true"),FRONTEND_PORT:H4.pipe((Y)=>Number.parseInt(Y,10)),FRONTEND_ORIGINS:H4.pipe.try((Y)=>JSON.parse(Y),E1("string[]")),API_KEY_OPENAI:E1("string | undefined"),API_KEY_RESEND:E1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:H4,VITE_DEV_FRONTEND_HOST:E1("string | undefined"),VITE_DEV_HTTPS:Z3.pipe((Y)=>Y==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var _3=e5(import.meta.dirname,"../dev"),wY=g1.VITE_DEV_HTTPS?{cert:X3(e5(_3,"./cert.pem"),"utf-8"),key:X3(e5(_3,"./key.pem"),"utf-8")}:void 0;function kT(Y){if(wY)return NU(wY,Y);return RU({},Y)}import CO from"path";var U=Symbol.for("drizzle:entityKind");function M(Y,Z){if(!Y||typeof Y!=="object")return!1;if(Y instanceof Z)return!0;if(!Object.prototype.hasOwnProperty.call(Z,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 YX{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 ZX{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 G3(Y,this)}}class G3{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 RY(Y,...Z){return Y(...Z)}function W3(Y,Z){return`${Y[y1]}_${Z.join("_")}_unique`}function H3(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 J3(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,$]=H3(Y,_+1,!0);X.push(Q),_=$;continue}if(W==="}")return[X,_+1];if(W==="{"){let[Q,$]=J3(Y,_+1);X.push(Q),_=$;continue}let[H,J]=H3(Y,_,!1);X.push(H),_=J}return[X,_]}function $3(Y){let[Z]=J3(Y,1);return Z}function XX(Y){return`{${Y.map((Z)=>{if(Array.isArray(Z))return XX(Z);if(typeof Z==="string")return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Z}`}).join(",")}}`}class h extends YX{foreignKeyConfigs=[];static[U]="PgColumnBuilder";array(Y){return new z3(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 RY((G,W)=>{let H=new ZX(()=>{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 Q3(Y,this.config)}}class j extends E0{constructor(Y,Z){if(!Z.uniqueName)Z.uniqueName=W3(Y,[Z.name]);super(Y,Z);this.table=Y}static[U]="PgColumn"}class Q3 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 z3 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 _X(Y,this.config,Z)}}class _X 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=$3(Y);return Y.map((Z)=>this.baseColumn.mapFromDriverValue(Z))}mapToDriverValue(Y,Z=!1){let X=Y.map((_)=>_===null?null:M(this.baseColumn,_X)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Z)return X;return XX(X)}}class F3 extends h{static[U]="PgEnumObjectColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumObjectColumn");this.config.enum=Z}build(Y){return new U3(Y,this.config)}}class U3 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 NY=Symbol.for("drizzle:isPgEnum");function O3(Y){return!!Y&&typeof Y==="function"&&NY in Y&&Y[NY]===!0}class E3 extends h{static[U]="PgEnumColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumColumn");this.config.enum=Z}build(Y){return new L3(Y,this.config)}}class L3 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 E3(G??"",_),{enumName:Y,enumValues:Z,schema:X,[NY]:!0});return _}function BU(Y,Z,X){let _=Object.assign((G)=>new F3(G??"",_),{enumName:Y,enumValues:Object.values(Z),schema:X,[NY]:!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 D3="0.44.4";var GX,WX,L0={startActiveSpan(Y,Z){if(!GX)return Z();if(!WX)WX=GX.trace.getTracer("drizzle-orm",D3);return RY((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()}}),GX,WX)}};var A0=Symbol.for("drizzle:ViewBaseConfig");var g4=Symbol.for("drizzle:Schema"),IY=Symbol.for("drizzle:Columns"),V3=Symbol.for("drizzle:ExtraConfigColumns"),HX=Symbol.for("drizzle:OriginalName"),JX=Symbol.for("drizzle:BaseName"),L6=Symbol.for("drizzle:IsAlias"),M3=Symbol.for("drizzle:ExtraConfigBuilder"),TU=Symbol.for("drizzle:IsDrizzleTable");class P{static[U]="Table";static Symbol={Name:y1,Schema:g4,OriginalName:HX,Columns:IY,ExtraConfigColumns:V3,BaseName:JX,IsAlias:L6,ExtraConfigBuilder:M3};[y1];[HX];[g4];[IY];[V3];[JX];[L6]=!1;[TU]=!0;[M3]=void 0;constructor(Y,Z,X){this[y1]=this[HX]=Y,this[g4]=Z,this[JX]=X}}function c0(Y){return Y[y1]}function y4(Y){return`${Y[g4]??"public"}.${Y[y1]}`}function $X(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=w3;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($,BY))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($,N1)){if(M($.value,N4))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($,N4))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 BY($._.alias)],X)}if(O3($)){if($.schema)return{sql:G($.schema)+"."+G($.enumName),params:[]};return{sql:G($.enumName),params:[]}}if($X($)){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 BY{constructor(Y){this.value=Y}static[U]="Name";brand;getSQL(){return new x([this])}}function A3(Y){return typeof Y==="object"&&Y!==null&&"mapToDriverValue"in Y&&typeof Y.mapToDriverValue==="function"}var w3={mapFromDriverValue:(Y)=>Y},R3={mapToDriverValue:(Y)=>Y},CC={...w3,...R3};class N1{constructor(Y,Z=R3){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 BY(Q)}Y.identifier=W;function H(Q){return new N4(Q)}Y.placeholder=H;function J(Q,$){return new N1(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 N4{constructor(Y){this.name=Y}static[U]="Placeholder";getSQL(){return new x([this])}}function QX(Y,Z){return Y.map((X)=>{if(M(X,N4)){if(!(X.name in Z))throw new Error(`No value for placeholder "${X.name}" was provided`);return Z[X.name]}if(M(X,N1)&&M(X.value,N4)){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 qU=Symbol.for("drizzle:IsDrizzleView");class D1{static[U]="View";[A0];[qU]=!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 TY(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 zX(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 zX(X,Z);return X}))}class CY extends Error{static[U]="DrizzleError";constructor({message:Y,cause:Z}){super(Y);this.name="DrizzleError",this.cause=Z}}class J4 extends Error{constructor(Y,Z,X){super(`Failed query: ${Y}
|
|
62
|
-
params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrace(this,J4),X)this.cause=X}}class FX extends CY{static[U]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class N3{static[U]="ConsoleLogWriter";write(Y){console.log(Y)}}class UX{static[U]="DefaultLogger";writer;constructor(Y){this.writer=Y?.writer??new N3}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 OX{static[U]="NoopLogger";logQuery(){}}class H1{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 I3(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],N=z[L]=V===null?null:$.mapFromDriverValue(V);if(X&&M(J,E0)&&H.length===2){let A=H[0];if(!(A in _))_[A]=N===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 K1(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(...K1(G[P.Symbol.Columns],W));else X.push(...K1(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 qY(Y,Z){let X=Object.entries(Z).filter(([,_])=>_!==void 0).map(([_,G])=>{if(M(G,x)||M(G,E0))return[_,G];else return[_,new N1(G,Y[P.Symbol.Columns][_])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function B3(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 T3(Y){return Y[P.Symbol.Columns]}function $4(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 C3(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 q3 extends I4{static[U]="PgBigInt53Builder";constructor(Y){super(Y,"number","PgBigInt53")}build(Y){return new K3(Y,this.config)}}class K3 extends j{static[U]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class j3 extends I4{static[U]="PgBigInt64Builder";constructor(Y){super(Y,"bigint","PgBigInt64")}build(Y){return new P3(Y,this.config)}}class P3 extends j{static[U]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(Y){return BigInt(Y)}}function S3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new q3(X);return new j3(X)}class v3 extends h{static[U]="PgBigSerial53Builder";constructor(Y){super(Y,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new x3(Y,this.config)}}class x3 extends j{static[U]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class h3 extends h{static[U]="PgBigSerial64Builder";constructor(Y){super(Y,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(Y){return new f3(Y,this.config)}}class f3 extends j{static[U]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(Y){return BigInt(Y)}}function b3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new v3(X);return new h3(X)}class k3 extends h{static[U]="PgBooleanBuilder";constructor(Y){super(Y,"boolean","PgBoolean")}build(Y){return new g3(Y,this.config)}}class g3 extends j{static[U]="PgBoolean";getSQLType(){return"boolean"}}function A6(Y){return new k3(Y??"")}class y3 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 p3(Y,this.config)}}class p3 extends j{static[U]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function m3(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new y3(X,_)}class u3 extends h{static[U]="PgCidrBuilder";constructor(Y){super(Y,"string","PgCidr")}build(Y){return new d3(Y,this.config)}}class d3 extends j{static[U]="PgCidr";getSQLType(){return"cidr"}}function c3(Y){return new u3(Y??"")}class l3 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 i3(Y,this.config)}}class i3 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 o3(Y){return(Z,X)=>{let{name:_,config:G}=X0(Z,X);return new l3(_,G,Y)}}class Q4 extends h{static[U]="PgDateColumnBaseBuilder";defaultNow(){return this.default(E`now()`)}}class n3 extends Q4{static[U]="PgDateBuilder";constructor(Y){super(Y,"date","PgDate")}build(Y){return new KY(Y,this.config)}}class KY extends j{static[U]="PgDate";getSQLType(){return"date"}mapFromDriverValue(Y){return new Date(Y)}mapToDriverValue(Y){return Y.toISOString()}}class r3 extends Q4{static[U]="PgDateStringBuilder";constructor(Y){super(Y,"string","PgDateString")}build(Y){return new jY(Y,this.config)}}class jY extends j{static[U]="PgDateString";getSQLType(){return"date"}}function s3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="date")return new n3(X);return new r3(X)}class a3 extends h{static[U]="PgDoublePrecisionBuilder";constructor(Y){super(Y,"number","PgDoublePrecision")}build(Y){return new t3(Y,this.config)}}class t3 extends j{static[U]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function e3(Y){return new a3(Y??"")}class Y2 extends h{static[U]="PgInetBuilder";constructor(Y){super(Y,"string","PgInet")}build(Y){return new Z2(Y,this.config)}}class Z2 extends j{static[U]="PgInet";getSQLType(){return"inet"}}function X2(Y){return new Y2(Y??"")}class _2 extends I4{static[U]="PgIntegerBuilder";constructor(Y){super(Y,"number","PgInteger")}build(Y){return new G2(Y,this.config)}}class G2 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 _2(Y??"")}class W2 extends h{static[U]="PgIntervalBuilder";constructor(Y,Z){super(Y,"string","PgInterval");this.config.intervalConfig=Z}build(Y){return new H2(Y,this.config)}}class H2 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 J2(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new W2(X,_)}class $2 extends h{static[U]="PgJsonBuilder";constructor(Y){super(Y,"json","PgJson")}build(Y){return new PY(Y,this.config)}}class PY 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 Q2(Y){return new $2(Y??"")}class z2 extends h{static[U]="PgJsonbBuilder";constructor(Y){super(Y,"json","PgJsonb")}build(Y){return new SY(Y,this.config)}}class SY 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 F2(Y){return new z2(Y??"")}class U2 extends h{static[U]="PgLineBuilder";constructor(Y){super(Y,"array","PgLine")}build(Y){return new O2(Y,this.config)}}class O2 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 E2 extends h{static[U]="PgLineABCBuilder";constructor(Y){super(Y,"json","PgLineABC")}build(Y){return new L2(Y,this.config)}}class L2 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 D2(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new U2(X);return new E2(X)}class V2 extends h{static[U]="PgMacaddrBuilder";constructor(Y){super(Y,"string","PgMacaddr")}build(Y){return new M2(Y,this.config)}}class M2 extends j{static[U]="PgMacaddr";getSQLType(){return"macaddr"}}function A2(Y){return new V2(Y??"")}class w2 extends h{static[U]="PgMacaddr8Builder";constructor(Y){super(Y,"string","PgMacaddr8")}build(Y){return new R2(Y,this.config)}}class R2 extends j{static[U]="PgMacaddr8";getSQLType(){return"macaddr8"}}function N2(Y){return new w2(Y??"")}class I2 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 vY(Y,this.config)}}class vY 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 B2 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 T2(Y,this.config)}}class T2 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 C2 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 q2(Y,this.config)}}class q2 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 K2(Y,Z){let{name:X,config:_}=X0(Y,Z),G=_?.mode;return G==="number"?new B2(X,_?.precision,_?.scale):G==="bigint"?new C2(X,_?.precision,_?.scale):new I2(X,_?.precision,_?.scale)}class j2 extends h{static[U]="PgPointTupleBuilder";constructor(Y){super(Y,"array","PgPointTuple")}build(Y){return new P2(Y,this.config)}}class P2 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 S2 extends h{static[U]="PgPointObjectBuilder";constructor(Y){super(Y,"json","PgPointObject")}build(Y){return new v2(Y,this.config)}}class v2 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 x2(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new j2(X);return new S2(X)}function KU(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 h2(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 EX(Y){let Z=KU(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=h2(Z,X);X+=8;let Q=h2(Z,X);return X+=8,[J,Q]}throw new Error("Unsupported geometry type")}class f2 extends h{static[U]="PgGeometryBuilder";constructor(Y){super(Y,"array","PgGeometry")}build(Y){return new b2(Y,this.config)}}class b2 extends j{static[U]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){return EX(Y)}mapToDriverValue(Y){return`point(${Y[0]} ${Y[1]})`}}class k2 extends h{static[U]="PgGeometryObjectBuilder";constructor(Y){super(Y,"json","PgGeometryObject")}build(Y){return new g2(Y,this.config)}}class g2 extends j{static[U]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){let Z=EX(Y);return{x:Z[0],y:Z[1]}}mapToDriverValue(Y){return`point(${Y.x} ${Y.y})`}}function y2(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new f2(X);return new k2(X)}class p2 extends h{static[U]="PgRealBuilder";constructor(Y,Z){super(Y,"number","PgReal");this.config.length=Z}build(Y){return new m2(Y,this.config)}}class m2 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 u2(Y){return new p2(Y??"")}class d2 extends h{static[U]="PgSerialBuilder";constructor(Y){super(Y,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new c2(Y,this.config)}}class c2 extends j{static[U]="PgSerial";getSQLType(){return"serial"}}function l2(Y){return new d2(Y??"")}class i2 extends I4{static[U]="PgSmallIntBuilder";constructor(Y){super(Y,"number","PgSmallInt")}build(Y){return new o2(Y,this.config)}}class o2 extends j{static[U]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number(Y);return Y}}function n2(Y){return new i2(Y??"")}class r2 extends h{static[U]="PgSmallSerialBuilder";constructor(Y){super(Y,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new s2(Y,this.config)}}class s2 extends j{static[U]="PgSmallSerial";getSQLType(){return"smallserial"}}function a2(Y){return new r2(Y??"")}class t2 extends h{static[U]="PgTextBuilder";constructor(Y,Z){super(Y,"string","PgText");this.config.enumValues=Z.enum}build(Y){return new e2(Y,this.config)}}class e2 extends j{static[U]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function YW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new t2(X,_)}class ZW extends Q4{constructor(Y,Z,X){super(Y,"string","PgTime");this.withTimezone=Z,this.precision=X,this.config.withTimezone=Z,this.config.precision=X}static[U]="PgTimeBuilder";build(Y){return new xY(Y,this.config)}}class xY 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 XW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new ZW(X,_.withTimezone??!1,_.precision)}class _W extends Q4{static[U]="PgTimestampBuilder";constructor(Y,Z,X){super(Y,"date","PgTimestamp");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new hY(Y,this.config)}}class hY 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 GW extends Q4{static[U]="PgTimestampStringBuilder";constructor(Y,Z,X){super(Y,"string","PgTimestampString");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new fY(Y,this.config)}}class fY 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 WW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="string")return new GW(X,_.withTimezone??!1,_.precision);return new _W(X,_?.withTimezone??!1,_?.precision)}class HW extends h{static[U]="PgUUIDBuilder";constructor(Y){super(Y,"string","PgUUID")}defaultRandom(){return this.default(E`gen_random_uuid()`)}build(Y){return new bY(Y,this.config)}}class bY extends j{static[U]="PgUUID";getSQLType(){return"uuid"}}function j1(Y){return new HW(Y??"")}class JW 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 $W(Y,this.config)}}class $W 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 JW(X,_)}class QW extends h{static[U]="PgBinaryVectorBuilder";constructor(Y,Z){super(Y,"string","PgBinaryVector");this.config.dimensions=Z.dimensions}build(Y){return new zW(Y,this.config)}}class zW extends j{static[U]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function FW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new QW(X,_)}class UW extends h{static[U]="PgHalfVectorBuilder";constructor(Y,Z){super(Y,"array","PgHalfVector");this.config.dimensions=Z.dimensions}build(Y){return new OW(Y,this.config)}}class OW 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 EW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new UW(X,_)}class LW extends h{static[U]="PgSparseVectorBuilder";constructor(Y,Z){super(Y,"string","PgSparseVector");this.config.dimensions=Z.dimensions}build(Y){return new DW(Y,this.config)}}class DW extends j{static[U]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function VW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new LW(X,_)}class MW extends h{static[U]="PgVectorBuilder";constructor(Y,Z){super(Y,"array","PgVector");this.config.dimensions=Z.dimensions}build(Y){return new AW(Y,this.config)}}class AW 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 wW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new MW(X,_)}function RW(){return{bigint:S3,bigserial:b3,boolean:A6,char:m3,cidr:c3,customType:o3,date:s3,doublePrecision:e3,inet:X2,integer:w6,interval:J2,json:Q2,jsonb:F2,line:D2,macaddr:A2,macaddr8:N2,numeric:K2,point:x2,geometry:y2,real:u2,serial:l2,smallint:n2,smallserial:a2,text:YW,time:XW,timestamp:WW,uuid:j1,varchar:e0,bit:FW,halfvec:EW,sparsevec:VW,vector:wW}}var LX=Symbol.for("drizzle:PgInlineForeignKeys"),NW=Symbol.for("drizzle:EnableRLS");class d0 extends P{static[U]="PgTable";static Symbol=Object.assign({},P.Symbol,{InlineForeignKeys:LX,EnableRLS:NW});[LX]=[];[NW]=!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(RW()):Z,J=Object.fromEntries(Object.entries(H).map(([z,O])=>{let L=O;L.setName(z);let V=L.build(W);return W[LX].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 IW(...Y){if(Y[0].columns)return new R6(Y[0].columns,Y[0].name);return new R6(Y)}class R6{static[U]="PgPrimaryKeyBuilder";columns;name;constructor(Y,Z){this.columns=Y,this.name=Z}build(Y){return new BW(Y,this.columns,this.name)}}class BW{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(A3(Z)&&!$X(Y)&&!M(Y,N1)&&!M(Y,N4)&&!M(Y,E0)&&!M(Y,P)&&!M(Y,D1))return new N1(Y,Z);return Y}var kY=(Y,Z)=>{return E`${Y} = ${V1(Z,Y)}`},TW=(Y,Z)=>{return E`${Y} <> ${V1(Z,Y)}`};function N6(...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 CW(...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 qW(Y){return E`not ${Y}`}var KW=(Y,Z)=>{return E`${Y} > ${V1(Z,Y)}`},jW=(Y,Z)=>{return E`${Y} >= ${V1(Z,Y)}`},PW=(Y,Z)=>{return E`${Y} < ${V1(Z,Y)}`},SW=(Y,Z)=>{return E`${Y} <= ${V1(Z,Y)}`};function vW(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 xW(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 hW(Y){return E`${Y} is null`}function fW(Y){return E`${Y} is not null`}function bW(Y){return E`exists ${Y}`}function kW(Y){return E`not exists ${Y}`}function gW(Y,Z,X){return E`${Y} between ${V1(Z,Y)} and ${V1(X,Y)}`}function yW(Y,Z,X){return E`${Y} not between ${V1(Z,Y)} and ${V1(X,Y)}`}function pW(Y,Z){return E`${Y} like ${Z}`}function mW(Y,Z){return E`${Y} not like ${Z}`}function uW(Y,Z){return E`${Y} ilike ${Z}`}function dW(Y,Z){return E`${Y} not ilike ${Z}`}function cW(Y){return E`${Y} asc`}function lW(Y){return E`${Y} desc`}class DX{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 iW{constructor(Y,Z){this.table=Y,this.config=Z}static[U]="Relations"}class T4 extends DX{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 DX{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 oW(){return{and:N6,between:gW,eq:kY,exists:bW,gt:KW,gte:jW,ilike:uW,inArray:vW,isNull:hW,isNotNull:fW,like:pW,lt:PW,lte:SW,ne:TW,not:qW,notBetween:yW,notExists:kW,notLike:mW,notIlike:dW,notInArray:xW,or:CW,sql:E}}function nW(){return{sql:E,asc:cW,desc:lW}}function rW(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,R6))G[W].primaryKey.push(...z.columns)}}else if(M(H,iW)){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 sW(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 aW(Y){return{one:PU(Y),many:SU(Y)}}function gY(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&&gY(Y,Y[J.relationTableTsKey],z,J.selection,G):z.map((O)=>gY(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 yY=new Map,VX=new Map,MX=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[MX]=this.handler.debug?new Error:this.tagged&&vU(this.strings)}get origin(){return(this.handler.debug?this[MX].stack:this.tagged&&VX.has(this.strings)?VX.get(this.strings):VX.set(this.strings,this[MX].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(yY.has(Y))return yY.get(Y);let Z=Error.stackTraceLimit;return Error.stackTraceLimit=4,yY.set(Y,new Error),Error.stackTraceLimit=Z,yY.get(Y)}class R8 extends Error{constructor(Y){super(Y.message);this.name=this.constructor.name,Object.assign(this,Y)}}var f0={connection:tW,postgres:eW,generic:YH,notSupported:ZH};function tW(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,tW),W}function eW(Y){let Z=new R8(Y);return Error.captureStackTrace(Z,eW),Z}function YH(Y,Z){let X=Object.assign(new Error(Y+": "+Z),{code:Y});return Error.captureStackTrace(X,YH),X}function ZH(Y){let Z=Object.assign(new Error(Y+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:Y});return Error.captureStackTrace(Z,ZH),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 uY{then(){AX()}catch(){AX()}finally(){AX()}}class q6 extends uY{constructor(Y){super();this.value=lY(Y)}}class r1 extends uY{constructor(Y,Z,X){super();this.value=Y,this.type=Z,this.array=X}}class dY extends uY{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?BX(this.first,_):G.fn(this.first,this.rest,Z,X,_)}}function cY(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 f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(Y instanceof r1?(Z.push(Y.value),Y.array?Y.array[Y.type||mY(Y.value)]||Y.type||WH(Y.value):Y.type):(Z.push(Y),mY(Y)))}var _H=JH(xU);function NX(Y,Z,X,_,G,W){for(let H=1;H<Y.strings.length;H++)Z+=IX(Z,X,_,G,W)+Y.strings[H],X=Y.args[H];return Z}function IX(Y,Z,X,_,G){return Z instanceof dY?Z.build(Y,X,_,G):Z instanceof P1?RX(Z,X,_,G):Z instanceof q6?Z.value:Z&&Z[0]instanceof P1?Z.reduce((W,H)=>W+" "+RX(H,X,_,G),""):cY(Z,X,_,G)}function RX(Y,Z,X,_){return Y.fragment=!0,NX(Y,Y.strings[0],Y.args[0],Z,X,_)}function GH(Y,Z,X,_,G){return Y.map((W)=>"("+_.map((H)=>IX("values",W[H],Z,X,G)).join(",")+")").join(",")}function XH(Y,Z,X,_,G){let W=Array.isArray(Y[0]),H=Z.length?Z.flat():Object.keys(W?Y[0]:Y);return GH(W?Y:[Y],X,_,H,G)}function pY(Y,Z,X,_,G){if(typeof Y==="string"&&(Y=[Y].concat(Z)),Array.isArray(Y))return BX(Y,G);let W;return(Z.length?Z.flat():Object.keys(Y)).map((J)=>{return W=Y[J],(W instanceof P1?RX(W,X,_,G):W instanceof q6?W.value:cY(W,X,_,G))+" as "+lY(G.transform.column.to?G.transform.column.to(J):J)}).join(",")}var hU=Object.entries({values:XH,in:(...Y)=>{let Z=XH(...Y);return Z==="()"?"(null)":Z},select:pY,as:pY,returning:pY,"\\(":pY,update(Y,Z,X,_,G){return(Z.length?Z.flat():Object.keys(Y)).map((W)=>lY(G.transform.column.to?G.transform.column.to(W):W)+"="+IX("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"("+BX(W,G)+")values"+GH(Array.isArray(Y)?Y:[Y],X,_,W,G)}}).map(([Y,Z])=>[new RegExp("((?:^|[\\s(])"+Y+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Z]);function AX(){throw f0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:fU,parsers:bU}=_H;function WH(Y){if(Array.isArray(Y))return WH(Y[0]);return typeof Y==="string"?1009:0}var HH=function(Y){let Z=JH(Y||{});return{serializers:Object.assign({},fU,Z.serializers),parsers:Object.assign({},bU,Z.parsers)}};function JH(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 BX(Y,{transform:{column:Z}}){return Y.map((X)=>lY(Z.to?Z.to(X):X)).join(",")}var lY=function Y(Z){return'"'+Z.replace(/"/g,'""').replace(/\./g,'"."')+'"'},mY=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 $H=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 f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return J===null?"null":'"'+yU(X?X(J.type?J.value:J):""+J)+'"'}).join(H)+"}"},wX={i:0,char:null,str:"",quoted:!1,last:0},QH=function Y(Z,X,_){return wX.i=wX.last=0,zH(wX,Z,X,_)};function zH(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(zH(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 TX(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:TX(p4)};B6.column={to:B6};var CX={...p4};CX.column.to=B6;m4.column={from:m4};m4.value={from:TX(m4)};T6.column={to:T6};var qX={...m4};qX.column.to=T6;u4.column={from:u4};u4.value={from:TX(u4)};C6.column={to:C6};var KX={...u4};KX.column.to=C6;import FH from"net";import dU from"tls";import K6 from"crypto";import jX from"stream";import{performance as UH}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 iY(Z),F0.i+=Y1.write(Y,F0.i,Z,"utf8"),F0},i16(Y){return iY(2),Y1.writeUInt16BE(Y,F0.i),F0.i+=2,F0},i32(Y,Z){if(Z||Z===0)return Y1.writeUInt32BE(Y,Z),F0;return iY(4),Y1.writeUInt32BE(Y,F0.i),F0.i+=4,F0},z(Y){return iY(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 iY(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 vX=LH,cU=1,C4=c().S().end(),OH=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(),N8=()=>{},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 LH(Y,Z={},{onopen:X=N8,onend:_=N8,onclose:G=N8}={}){let{ssl:W,max:H,user:J,host:Q,port:$,database:z,parsers:O,transform:L,onnotice:V,onnotify:N,onparameter:A,max_pipeline:f,keep_alive:b,backoff:k,target_session_attrs:g}=Y,R=I1(),I=cU++,K={pid:null,secret:null},q=SX(HZ,Y.idle_timeout),p=SX(HZ,Y.max_lifetime),s=SX(gH,Y.connect_timeout),T=null,t,m=new d4,e=Buffer.alloc(0),U0=Y.fetch_types,b0={},$1={},s1=Math.random().toString(36).slice(2),C=1,u=0,G0=0,T0=0,k0=0,a=0,Q0=0,S0=0,C0=null,w0=null,n0=!1,D0=null,S1=null,l0=null,z4=null,g0=null,R0=null,v1=null,m1=null,v=null,C8=null,r0={queue:Z.closed,idleTimer:q,connect(F){l0=F,W_()},terminate:K8,execute:q8,cancel:hH,end:HZ,count:0,id:I};return Z.closed&&Z.closed.push(r0),r0;async function xH(){let F;try{F=Y.socket?await Promise.resolve(Y.socket(Y)):new FH.Socket}catch(D){o4(D);return}return F.on("error",o4),F.on("close",H_),F.on("drain",__),F}async function hH({pid:F,secret:D},l,W0){try{t=c().i32(16).i32(80877102).i32(F).i32(D).end(16),await G_(),T.once("error",W0),T.once("close",l)}catch(K0){W0(K0)}}function q8(F){if(n0)return b6(F,f0.connection("CONNECTION_DESTROYED",Y));if(F.cancelled)return;try{return F.state=K,v?R.push(F):(v=F,v.active=!0),kH(F),i0(fH(F))&&!F.describeFirst&&!F.cursorFn&&R.length<f&&(!F.options.onexecute||F.options.onexecute(r0))}catch(D){return R.length===0&&i0(C4),u1(D),!0}}function fH(F){if(F.parameters.length>=65534)throw f0.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([Y_(F),OH]):F.prepare?F.prepared?f6(F):Buffer.concat([Y_(F),f6(F)]):bH(F)}function Y_(F){return Buffer.concat([$_(F.statement.string,F.parameters,F.statement.types,F.statement.name),NJ("S",F.statement.name)])}function f6(F){return Buffer.concat([RJ(F.parameters,F.statement.types,F.statement.name,F.cursorName),F.cursorFn?Q_("",F.cursorRows):iU])}function bH(F){return Buffer.concat([$_(F.statement.string,F.parameters,F.statement.types),oU,f6(F)])}function kH(F){let D=[],l=[],W0=NX(F,F.strings[0],F.args[0],D,l,Y);!F.tagged&&F.args.forEach((K0)=>cY(K0,D,l,Y)),F.prepare=Y.prepare&&("prepare"in F.options?F.options.prepare:!0),F.string=W0,F.signature=F.prepare&&l+W0,F.onlyDescribe&&delete $1[F.signature],F.parameters=F.parameters||D,F.prepared=F.prepare&&F.signature in $1,F.describeFirst=F.onlyDescribe||D.length&&!F.prepared,F.statement=F.prepared?$1[F.signature]:{string:W0,types:l,name:F.prepare?s1+C++:""},typeof Y.debug==="function"&&Y.debug(I,W0,D,l)}function i0(F,D){if(R0=R0?Buffer.concat([R0,F]):Buffer.from(F),D||R0.length>=1024)return Z_(D);return w0===null&&(w0=setImmediate(Z_)),!0}function Z_(F){let D=T.write(R0,F);return w0!==null&&clearImmediate(w0),R0=w0=null,D}function gH(){u1(f0.connection("CONNECT_TIMEOUT",Y,T)),T.destroy()}async function X_(){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:FH.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",H_),T.on("drain",__)}function __(){!v&&X(r0)}function WZ(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{yH(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 G_(){if(n0=!1,b0={},T||(T=await xH()),!T)return;if(s.start(),Y.socket)return W?X_():i4();if(T.on("connect",W?X_: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 W_(){setTimeout(G_,u?u+Q0-UH.now():0)}function i4(){try{$1={},U0=Y.fetch_types,s1=Math.random().toString(36).slice(2),C=1,p.start(),T.on("data",WZ),b&&T.setKeepAlive&&T.setKeepAlive(!0,1000*b);let F=BJ();i0(F)}catch(F){o4(F)}}function o4(F){if(r0.queue===Z.connecting&&Y.host[k0+1])return;u1(F);while(R.length)b6(R.shift(),F)}function u1(F){g0&&(g0.destroy(F),g0=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/,`
|
|
63
|
-
`),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(
|
|
60
|
+
${D.trace}`:`No previous disposal trace for ${J} was found.`),X}let Q=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:H.stringKey}).filter(([,{source:D}])=>D!==G).map(([D])=>G1(D));if(_)W.moleculeGraph.delete(G);W.moleculeGraph.set({upstreamMoleculeKey:$.stringKey,downstreamMoleculeKey:H.stringKey},{source:$.stringKey});let z={type:"molecule_transfer",key:H.key,from:Q,to:[$.key]};if(o0(W)&&W.transactionMeta.phase==="building")W.transactionMeta.update.updates.push(z);return X}function uF(Y,Z,X){switch(Z){case"newValue":m7(Y,X);break;case"oldValue":V8(X,Y.token);break}}function dF(Y,Z,X){switch(Z){case"newValue":V8(X,Y.token);break;case"oldValue":if(m7(Y,X),Y.subType==="atom")X.valueMap.set(Y.token.key,Y.value);break}}function m7(Y,Z){let{family:X}=Y.token;if(X){let _=Z.families.get(X.key);if(_)H0(Z,_,G1(X.subKey))}}function cF(Y,Z,X){switch(Z){case"newValue":D8(X,Y.provenance,Y.key);break;case"oldValue":L8(X,Y.key);break}}function lF(Y,Z,X){switch(Z){case"newValue":L8(X,Y.key);break;case"oldValue":{let _=Y.provenance.map(G1);D8(X,_,Y.key);for(let[G,W]of Y.values){let H=X.families.get(G);if(H){H0(X,H,Y.key);let J=`${G}(${z0(Y.key)})`;X.valueMap.set(J,W)}}}break}}function iF(Y,Z,X){switch(Z){case"newValue":{let _=Y.to.length===1?Y.to[0]:Y.to;J6(X,_,Y.key,"exclusive")}break;case"oldValue":{let _=Y.from.length===1?Y.from[0]:Y.from;J6(X,_,Y.key,"exclusive")}break}}function u7(Y,Z,X){let _=Y==="newValue"?Z.updates:[...Z.updates].reverse();for(let G of _)switch(G.type){case"atom_update":case"selector_update":pF(Y,G,X);break;case"state_creation":uF(G,Y,X);break;case"state_disposal":dF(G,Y,X);break;case"molecule_creation":cF(G,Y,X);break;case"molecule_disposal":lF(G,Y,X);break;case"molecule_transfer":iF(G,Y,X);break;case"transaction_update":u7(Y,G,X);break}}function d7(Y,Z){return Y.transactionMeta.actionContinuities.getRelatedKey(Z)}function oF(Y,Z){return Y.transactionMeta.epoch.get(Z)}function nF(Y,Z){if(!R4(Y))return;let _=d7(Y,Z);if(_===void 0)return;return oF(Y,_)}function rF(Y,Z,X){if(!R4(Y))return;let G=d7(Y,Z);if(G!==void 0)Y.transactionMeta.epoch.set(G,X)}var sF=(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),u7("newValue",X.transactionMeta.update,_),R4(_))rF(_,X.transactionMeta.update.key,X.transactionMeta.update.epoch),h0(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 aF(Y){return{store:Y}}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)}},tF=(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 W1(G.timelineTopics.toJSON()),trackers:new Map,transactions:new i1(G.transactions),selectorAtoms:new W1(G.selectorAtoms.toJSON()),selectorGraph:new W1(G.selectorGraph.toJSON(),{makeContentKey:(...Q)=>Q.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 W1(G.moleculeGraph.toJSON(),{makeContentKey:G.moleculeGraph.makeContentKey}),moleculeData:new W1(G.moleculeData.toJSON(),{makeContentKey:G.moleculeData.makeContentKey}),moleculeJoins:new W1(G.moleculeJoins.toJSON(),{makeContentKey:G.moleculeJoins.makeContentKey}),miscResources:new i1(G.miscResources)},H=nF(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:(...Q)=>k1($,...Q),set:(...Q)=>{R1($,...Q)},reset:(...Q)=>{E8($,...Q)},run:(Q,z=P5())=>S5($,Q,z),find:(...Q)=>H0(Y,...Q),json:(Q)=>b4($,Q),dispose:(...Q)=>{V8($,...Q)},env:()=>aF($)}},$=Object.assign(W,{transactionMeta:J});return G.child=$,Y.logger.info("\uD83D\uDEEB","transaction",Z,"Building transaction with params:",X),$};function v5(Y,Z){let{key:X}=Z,_=Y.transactions.has(X),G={key:X,type:"transaction",run:(J,$)=>{let Q=tF(Y,X,J,$);try{let z=i(Y),{toolkit:O}=Q.transactionMeta,D=Z.do(O,...J);return sF(D,z),D}catch(z){throw yF(W),Y.logger.warn("\uD83D\uDCA5","transaction",X,"caught:",z),z}},install:(J)=>v5(J,Z),subject:new J0},W=i(Y);W.transactions.set(X,G);let H=G4(G);if(!_)Y.on.transactionCreation.next(H);return H}var m5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,{key:H,const:J}=Z,$="writable_held_selector",Q=AY(_,"writable_held_selector",H,W),{find:z,get:O,json:D}=Q,V={find:z,get:O,json:D},R=(f=Z.get,h=i(Y))=>{let I=h.selectorGraph.getRelationEntries({downstreamSelectorKey:H});for(let[N,{source:q}]of I)if(q!==H)h.selectorGraph.delete(N,H);return h.selectorAtoms.delete(H),f(V,J),W4(h,H,J,G),Y.logger.info("\u2728","writable_held_selector",H,"=",J),W.clear(),J},g={...Z,type:"writable_held_selector",subject:G,install:(f)=>m5(f,Z,X),get:R,set:(f)=>{let h=i(Y),I=R(Z.get,h),N=k5(f)(I);if(Y.logger.info("\uD83D\uDCDD","writable_held_selector",H,"set (",I,"->",N,")"),W4(h,H,N,G),$6(h,H),R4(h))G.next({newValue:N,oldValue:I});Z.set(Q,N)},...X&&{family:X}};_.writableSelectors.set(H,g);let b={key:H,type:"writable_held_selector"};if(X)b.family=X;return b},u5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,H=Z.key,J="writable_pure_selector",$=AY(_,"writable_pure_selector",H,W),{find:Q,get:z,json:O}=$,D={find:Q,get:z,json:O},V=(f=Z.get,h=i(Y))=>{let I=h.selectorGraph.getRelationEntries({downstreamSelectorKey:H});for(let[K,{source:p}]of I)if(p!==H)h.selectorGraph.delete(K,H);h.selectorAtoms.delete(H);let N=f(D),q=W4(h,H,N,G);return Y.logger.info("\u2728","writable_pure_selector",H,"=",q),W.clear(),N},A={...Z,type:"writable_pure_selector",subject:G,install:(f)=>u5(f,Z,X),get:V,set:(f)=>{let h=i(Y),I=V(Z.get,h),N=k5(f)(I);if(Y.logger.info("\uD83D\uDCDD","writable_pure_selector",H,"set (",I,"->",N,")"),W4(h,Z.key,N,G),$6(h,Z.key),R4(h))G.next({newValue:N,oldValue:I});Z.set($,N)},...X&&{family:X}};_.writableSelectors.set(H,A);let g=V();Y.logger.info("\u2728",A.type,A.key,"=",g);let b={key:H,type:"writable_pure_selector"};if(X)b.family=X;return b};function K5(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=g5(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=y5(Y,Z,void 0);return Y.on.selectorCreation.next(G),G}function eF(Y,Z){let X=i(Y),{key:_,type:G}=Z,W=h0(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"},h0(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"},h0(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"},h0(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"},h0(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 J0,Q=Object.assign((z)=>{let O=z0(z),D={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=y5(R,{key:V,get:Z.get(z)},D);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:(...D)=>k1(Y,...D),find:(...D)=>H0(Y,...D),json:(D)=>b4(Y,D)})}});return Y.families.set(_,Q),W}function c7(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 J0,Q=Object.assign((z)=>{let O=z0(z),D={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=g5(R,{key:V,const:Z.const(z),get:Z.get(z)},D);return J.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:J,install:(z)=>c7(z,Z),default:Z.const});return Y.families.set(_,Q),W}function l7(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 J0,Q=Object.assign((z)=>{let O=z0(z),D={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)},D);return J.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:J,install:(z)=>l7(z,Z),default:Z.const});return Y.families.set(_,Q),W}function OY(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 J0,Q=Object.assign((z)=>{let O=z0(z),D={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=u5(R,{key:V,get:Z.get(z),set:Z.set(z)},D);return J.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:J,install:(z)=>OY(z,Z),default:(z)=>{return Z.get(z)({get:(...D)=>k1(Y,...D),find:(...D)=>H0(Y,...D),json:(D)=>b4(Y,D)})}});return Y.families.set(_,Q),W}function x5(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X)return l7(Y,Z,void 0);if(_)return c7(Y,Z,void 0);if(X)return OY(Y,Z);return h4(Y,Z)}function YU(Y,Z,X){let _=Y.families.get(Z.key);if(_===void 0)throw new p5(Z,Y);let G=_(X),W=i(Y);if(G.family){if(R4(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 ZU(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 G4(H);return H}function H0(Y,Z,X){let _=ZU(Y,Z,X);if(_)return _;let G=z0(X),W=Y.molecules.get(G);if(!W&&Y.config.lifespan==="immortal"){let H=qF(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(_=YU(Y,Z,X),W)i(Y).moleculeData.set(G,Z.key);return _}function V8(Y,...Z){let X;if(Z.length===1)X=Z[0];else{let _=Z[0],G=Z[1];X=H0(Y,_,G)}try{h0(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":o7(Y,X);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":eF(Y,X);break}}function k1(Y,...Z){let X,_,G;if(Z.length===1)X=Z[0];else _=Z[0],G=Z[1],X=H0(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:
|
|
61
|
+
${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=h0(Y,_).default(W);return Y.defaults.set(_.key,J),J}}}return z6(Y,h0(Y,X))}function M8(Y,Z,X,_){function G(O){if(Y.operation.open){let D=Y.on.operationClose.subscribe(`state subscription ${X}`,()=>{D(),_(O)})}else _(O)}let W=h0(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=new Map,$=G;if(H){z6(Y,W);for(let[O,D]of MY(Y,W.key))J.set(O,S7(Y,W,D));$=function O(D){let V=MY(Y,W.key);for(let[R,A]of J)if(V.get(R))V.delete(R);else A(),J.delete(R);for(let[R,A]of V)J.set(R,S7(Y,W,A));G(D)}}let Q=W.subject.subscribe(X,$);return()=>{Y.logger.info("\uD83D\uDE48",W.type,W.key,`Removing subscription "${X}"`),Q();for(let O of J.values())O()}}var i7=(Y,Z,X,_)=>{let G=h0(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)=>{R1(X,Z,W)}),this.unsubscribeFromState=M8(X,Y,_,(W)=>{if(W.newValue!==W.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=W.newValue.subscribe(_,(H)=>{R1(X,Z,H)})})}updateCore(Y,Z,X){let _=`tracker:${X.config.name}:${o0(X)?X.transactionMeta.update.key:"main"}:${Y.key}`;M8(X,Z,_,({newValue:G,oldValue:W})=>{let H=X.timelineTopics.getRelatedKey(Z.key);if(H){if(X.timelines.get(H)?.timeTraveling){let Q=i7(X,{key:H,type:"timeline"},_,(z)=>{Q(),R1(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 $=k1(X,Y),Q=G===null?-1:$.getUpdateNumber(G),z=Q-$.cacheUpdateNumber;if(G&&z===1)R1(X,Y,(O)=>(O.do(G),O));else X.logger.info("\u274C","mutable_atom",Y.key,`could not be updated. Expected update number ${$.cacheUpdateNumber+1}, but got ${Q}`)})})}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}=Z,W=_.atoms.get(G),H="mutable_atom";if(W&&W.type===H)return Y.logger.error("\u274C",H,G,"Tried to create atom, but it already exists in the store."),G4(W);let J=new J0,$={...Z,type:H,install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${z.config.name}"`),c5(z,Z,X)},subject:J};if(X)$.family=X;_.atoms.set($.key,$);let Q=G4($);if(Z.effects){let z=0,O=[];for(let D of Z.effects){let V=D({resetSelf:()=>{E8(Y,Q)},setSelf:(R)=>{R1(Y,Q,R)},onSet:(R)=>M8(Y,Q,`effect[${z}]`,R)});if(V)O.push(V);++z}$.cleanup=()=>{for(let D of O)D()}}if(new d5(Q,Y),!X)V7(Q,Z,Y);return Q}var _U=class{trackers=new Map;latestUpdateAtoms;mutableAtoms;constructor(Y,Z){let X=F6(Z,{key:`*${Y.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=h0(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=G1(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 J0,J=Object.assign(($)=>{let Q=z0($),z={key:Z.key,subKey:Q},O=`${Z.key}(${Q})`,D=i(Y),V={key:O,default:()=>Z.default($),toJson:Z.toJson,fromJson:Z.fromJson,mutable:!0};if(Z.effects)V.effects=Z.effects($);let R=c5(D,V,z);return W.next({type:"state_creation",token:R}),R},_,{subject:W,install:($)=>l5($,Z),toJson:Z.toJson,fromJson:Z.fromJson,internalRoles:X});return Y.families.set(Z.key,J),M7(Y,J,Z),new _U(J,Y),_}var h7=(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=h0(_,W),J=JSON.parse(Z.family.subKey);return H0(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 GU(Y){return typeof Y==="object"&&Y!==null&&"do"in Y&&"undo"in Y&&"subscribe"in Y}var C7=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 W1({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new W1({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 W1({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new W1({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new TF(100);molecules=new Map;moleculeJoins=new W1({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeGraph=new W1({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeData=new W1({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});miscResources=new Map;on={atomCreation:new J0,atomDisposal:new J0,selectorCreation:new J0,selectorDisposal:new J0,timelineCreation:new J0,transactionCreation:new J0,transactionApplying:new jF(null),operationClose:new J0,moleculeCreation:new J0,moleculeDisposal:new J0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new w7("warn",(Y,Z,X)=>!A8(X))];logger={error:(...Y)=>{for(let Z of this.loggers)Z.error(...Y)},info:(...Y)=>{for(let Z of this.loggers)Z.info(...Y)},warn:(...Y)=>{for(let Z of this.loggers)Z.warn(...Y)}};constructor(Y,Z=null){if(this.config={...Z?.config,...Y},Z!==null){if(this.operation={...Z?.operation},R4(Z))this.transactionMeta={epoch:new Map(Z?.transactionMeta.epoch),actionContinuities:new W1(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 C7({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function h0(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 p5(Z,Y)}function k4(Y,Z,X){let{key:G}=Z;Y.logger.info("\uD83D\uDD28","atom",G,`creating in store "${Y.config.name}"`);let W=i(Y),H=W.atoms.get(G);if(H&&H.type==="atom")return Y.logger.error("\u274C","atom",G,"Tried to create atom, but it already exists in the store."),G4(H);let J=new J0,$={...Z,type:"atom",install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${z.config.name}"`),k4(z,Z,X)},subject:J};if(X)$.family=X;W.atoms.set(G,$);let Q=G4($);if(Z.effects){let z=0,O=[];for(let D of Z.effects){let V=D({resetSelf:()=>{E8(Y,Q)},setSelf:(R)=>{R1(Y,Q,R)},onSet:(R)=>M8(Y,Q,`effect[${z}]`,R)});if(V)O.push(V);++z}$.cleanup=()=>{for(let D of O)D()}}return Q}function T7(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 o7(Y,Z){let X=i(Y),{key:_,family:G}=Z,W=h0(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=h0(Y,{key:G.key,type:"atom_family"}),$={type:"state_disposal",subType:"atom",token:Z,value:H};J.subject.next($);let Q=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);o7(Y,z),Y.trackers.delete(_)}if(Y.logger.info("\uD83D\uDD25","atom",_,"deleted"),Q&&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($)}else Y.on.atomDisposal.next(Z)}}function K7(Y,Z,X){return Y.joins.set(Z.key,new o5(Z,X,Y)),{key:Z.key,type:"join",a:Z.between[0],b:Z.between[1],cardinality:Z.cardinality}}var o5=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 R7(X),this.options=Y,this.defaultContent=Z,this.store.miscResources.set(`join:${Y.key}`,this),this.realm.allocate("root",Y.key),this.toolkit={get:(...I)=>k1(X,...I),set:(...I)=>{R1(X,...I)},find:(...I)=>H0(X,...I),json:(I)=>b4(X,I)};let _=Y.between[0],G=Y.between[1],W=l5(X,{key:`${Y.key}/relatedKeys`,default:()=>new D1,mutable:!0,fromJson:(I)=>D1.fromJSON(I),toJson:(I)=>I.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:W};let H=({get:I},N)=>I(W,N),J=({set:I},N,q)=>{if(!this.store.molecules.has(z0(N)))this.realm.allocate(Y.key,N);I(W,N,(K)=>K.add(q)),I(W,q,(K)=>K.add(N))},$=({set:I},N,q)=>{I(W,N,(K)=>{return K.delete(q),K}),I(W,q,(K)=>{return K.delete(N),K})},Q=(I,N,q)=>{let{find:K,get:p,set:s}=I,C=K(W,N),t=p(C);for(let m of t){if(q.includes(m))continue;s(W,m,(U0)=>{return U0.delete(N),U0})}s(C,(m)=>{return m.transaction((e)=>{e.clear();for(let U0 of q){let b0=H(I,U0),Q1=b0.has(N);if(this.relations.cardinality==="1:n"){let r1=[];for(let T of b0){if(T===N)continue;let u=H(I,T);if(u.delete(U0),u.size===0)r1.push(T)}if(!Q1&&b0.size>0)b0.clear();for(let T of r1){let u=[U0,T].sort(),G0=`"${u[0]}:${u[1]}"`;this.molecules.delete(G0)}}if(!Q1)b0.add(N);e.add(U0)}return!0}),m})},z=(I,N,q)=>{let{set:K}=I;K(W,N,(p)=>{return p.transaction((s)=>{for(let C of q)s.add(C);return!0}),p});for(let p of q)K(W,p,(s)=>{return s.add(N),s});return!0},O=(I,N,q)=>{let K=H(I,N);return q?K.has(q):K.size>0},D={getRelatedKeys:(I)=>H(this.toolkit,I),addRelation:(I,N)=>{this.store.moleculeJoins.set(I,Y.key),this.store.moleculeJoins.set(N,Y.key),J(this.toolkit,I,N)},deleteRelation:(I,N)=>{$(this.toolkit,I,N)},replaceRelationsSafely:(I,N)=>{Q(this.toolkit,I,N)},replaceRelationsUnsafely:(I,N)=>{z(this.toolkit,I,N)},has:(I,N)=>O(this.toolkit,I,N)},V,R;if(Z){R=F6(X,{key:`${Y.key}/content`,default:Z},["join","content"]);let I=({get:K},p)=>K(R,p),N=({set:K},p,s)=>{K(R,p,s)};V=Object.assign(D,{getContent:(K)=>{return I(this.toolkit,K)},setContent:(K,p)=>{N(this.toolkit,K,p)},deleteContent:(K)=>{this.realm.deallocate(K)}})}else V=D;let A=new W1(Y,{externalStore:V,isAType:Y.isAType,isBType:Y.isBType,makeContentKey:(...I)=>{let[N,q]=I,K=I.sort(),p=`${K[0]}:${K[1]}`,s=X.molecules.get(z0(N)),C=X.molecules.get(z0(q));if(!s)this.realm.allocate(Y.key,N);if(!C)this.realm.allocate(Y.key,q);return this.realm.allocate(N,p,"all"),this.realm.claim(q,p),this.store.moleculeJoins.set(p,Y.key),p}}),g=()=>h4(X,{key:`${Y.key}/singleRelatedKey`,get:(I)=>({get:N})=>{let q=N(W,I);for(let K of q)return K;return null}},["join","keys"]),b=()=>{return h4(X,{key:`${Y.key}/multipleRelatedKeys`,get:(I)=>({get:N})=>{let q=h7(W,X);return N(q,I).members}},["join","keys"])},f=()=>h4(X,{key:`${Y.key}/singleRelatedEntry`,get:(I)=>({get:N})=>{let q=N(W,I);for(let K of q){let p=A.isAType?.(I)?I:void 0,s=p===void 0?I:void 0;p??=K,s??=K;let C=A.makeContentKey(p,s),t=N(R,C);return[K,t]}return null}},["join","entries"]),h=()=>h4(X,{key:`${Y.key}/multipleRelatedEntries`,get:(I)=>({get:N})=>{let q=h7(W,X);return N(q,I).members.map((p)=>{let s=A.isAType?.(I)?I:void 0,C=s===void 0?I:void 0;s??=p,C??=p;let t=A.makeContentKey(s,C),m=N(R,t);return[p,m]})}},["join","entries"]);switch(Y.cardinality){case"1:1":{let I=g(),N=`${_}KeyOf${B0(G)}`,q=`${G}KeyOf${B0(_)}`,K={[N]:I,[q]:I},p;if(Z){let s=f(),C=`${_}EntryOf${B0(G)}`,t=`${G}EntryOf${B0(_)}`,m={[C]:s,[t]:s};p=Object.assign(K,m)}else p=K;this.relations=A,this.states=p;break}case"1:n":{let I=g(),N=b(),q=`${_}KeyOf${B0(G)}`,K=`${G}KeysOf${B0(_)}`,p={[q]:I,[K]:N},s;if(Z){let C=f(),t=h(),m=`${_}EntryOf${B0(G)}`,e=`${G}EntriesOf${B0(_)}`,U0={[m]:C,[e]:t};s=Object.assign(p,U0)}else s=p;this.relations=A,this.states=s;break}case"n:n":{let I=b(),N=`${_}KeysOf${B0(G)}`,q=`${G}KeysOf${B0(_)}`,K={[N]:I,[q]:I},p;if(Z){let s=h(),C=`${_}EntriesOf${B0(G)}`,t=`${G}EntriesOf${B0(_)}`,m={[C]:s,[t]:s};p=Object.assign(K,m)}else p=K;this.relations=A,this.states=p}}}};function n5(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 o5(G.options,G.defaultContent,Z),Z.joins.set(Y.key,X)}return X}function Q6(Y,Z,X){let _=n5(Y,X),G=i(X);if(o0(G)){let{toolkit:W}=G.transactionMeta;_.transact(W,({relations:H})=>{Z(H)})}else Z(_.relations)}function q7(Y,Z,X){let _=n5(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 $=_.states[W];return H0(X,$,Z)},get[H](){let $=_.states[H];return H0(X,$,Z)}};let J=`${Y.a}EntryOf${B0(Y.b)}`;if(J in _.states){let $=`${Y.b}EntryOf${B0(Y.a)}`;Object.assign(G,{get[J](){let Q=_.states[J];return H0(X,Q,Z)},get[$](){let Q=_.states[$];return H0(X,Q,Z)}})}break}case"1:n":{let W=`${Y.a}KeyOf${B0(Y.b)}`,H=`${Y.b}KeysOf${B0(Y.a)}`;G={get[W](){let $=_.states[W];return H0(X,$,Z)},get[H](){let $=_.states[H];return H0(X,$,Z)}};let J=`${Y.a}EntryOf${B0(Y.b)}`;if(J in _.states){let $=`${Y.b}EntriesOf${B0(Y.a)}`;Object.assign(G,{get[J](){let Q=_.states[J];return H0(X,Q,Z)},get[$](){let Q=_.states[$];return H0(X,Q,Z)}})}break}case"n:n":{let W=`${Y.a}KeysOf${B0(Y.b)}`,H=`${Y.b}KeysOf${B0(Y.a)}`;G={get[W](){let $=_.states[W];return H0(X,$,Z)},get[H](){let $=_.states[H];return H0(X,$,Z)}};let J=`${Y.a}EntriesOf${B0(Y.b)}`;if(J in _.states){let $=`${Y.b}EntriesOf${B0(Y.a)}`;Object.assign(G,{get[J](){let Q=_.states[J];return H0(X,Q,Z)},get[$](){let Q=_.states[$];return H0(X,Q,Z)}})}}}return G}function j7(Y,Z){return n5(Y,Z).core.relatedKeysAtoms}function A8(Y){return Y.startsWith("\uD83D\uDD0D ")}var WU=(Y)=>{return k4(Y,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Z=new Map;for(let[X,_]of Y.atoms){if(A8(X))continue;let G=G4(_);if(_.family){let W=Z.get(_.family.key);if(!W||!("familyMembers"in W))W={key:_.family.key,familyMembers:new Map},Z.set(_.family.key,W);W.familyMembers.set(_.family.subKey,G)}else Z.set(X,G)}return Z},effects:[({setSelf:Z})=>{Y.on.atomCreation.subscribe("introspection",(X)=>{if(A8(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H===void 0||!("familyMembers"in H))H={key:G,familyMembers:new Map},_.set(G,H);H.familyMembers.set(W,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.atomDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H&&"familyMembers"in H){if(H.familyMembers.delete(W),H.familyMembers.size===0)_.delete(G)}}return new Map(_)})})}]},void 0)},HU=(Y)=>{return k4(Y,{key:"\uD83D\uDD0D Selector Token Index",default:()=>{let Z=new Map;for(let X of[Y.readonlySelectors,Y.writableSelectors])for(let[_,G]of X){if(A8(_))continue;let W=G4(G);if(G.family){let H=Z.get(G.family.key);if(!H||!("familyMembers"in H))H={key:G.family.key,familyMembers:new Map},Z.set(G.family.key,H);H.familyMembers.set(G.family.subKey,W)}else Z.set(_,W)}return Z},effects:[({setSelf:Z})=>{Y.on.selectorCreation.subscribe("introspection",(X)=>{if(A8(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H===void 0||!("familyMembers"in H))H={key:G,familyMembers:new Map},_.set(G,H);H.familyMembers.set(W,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.selectorDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H&&"familyMembers"in H){if(H.familyMembers.delete(W),H.familyMembers.size===0)_.delete(G)}}else _.delete(X.key);return new Map(_)})})}]},void 0)};var r5=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}},r7=new r5({number:(Y)=>typeof Y==="number",string:(Y)=>typeof Y==="string",boolean:(Y)=>typeof Y==="boolean",null:(Y)=>Y===null});function s7(Y){if(!Y)return!1;return Object.getPrototypeOf(Y)===Object.prototype}var a7=new r5({object:s7,array:(Y)=>Array.isArray(Y)}),JU=new r5({...r7.supported,...a7.supported}),wY=(Y)=>{if(Y===void 0)return"undefined";let Z=JU.refine(Y);if(Z)return Z.type;return Object.getPrototypeOf(Y).constructor.name};var oB=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=WU(this.store),this.selectorIndex=HU(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=j5(this.atomIndex),_=j5(this.selectorIndex),G=[...X.values()].filter(($)=>("familyMembers"in $)),W=[..._.values()].filter(($)=>("familyMembers"in $)),H=performance.now(),J=[];if(Z.atomFamilies)for(let $ of G){let Q=$.familyMembers.values();for(let z of Q){let D=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,V=H-D;J.push([z,V])}}if(Z.selectorFamilies)for(let $ of W){let Q=$.familyMembers.values();for(let z of Q){let D=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,V=H-D;J.push([z,V])}}return J}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},n7=(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,$]):s7(G)?Object.entries(G):[];for(let[$,Q]of J){let z=X([..._,$],Q);if(z?.jobComplete)return z}return{}};X([],Y)};function QU(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 zU(Y,Z){return{summary:`${Y} \u2192 ${Z}`}}function t7(Y,Z,X){let _="",G=[],W=[],H=[];return n7(Y,(J,$)=>{let Q;for(Q of J){let z=Z[Q];if(z===void 0)W.push([Q,JSON.stringify($)]);else{let O=X($,z);if(O.summary!=="No Change")H.push([Q,O])}}}),n7(Z,(J,$)=>{let Q;for(Q of J)if(Y[Q]===void 0)G.push([Q,JSON.stringify($)])}),_=`\uFF5E${H.length} \uFF0B${G.length} \uFF0D${W.length}`,{summary:_,added:G,removed:W,changed:H}}function FU(Y,Z,X){return t7(Y,Z,X)}var UU=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,$)=>this.diff(J,$))}}let G=wY(Y),W=wY(Z);if(G===W)return{summary:`${G} \u2192 ${W}`};return{summary:`Type change: ${G} \u2192 ${W}`}}},nB=new UU(r7,a7,{number:QU,string:$U,boolean:zU,null:()=>({summary:"No Change"}),object:t7,array:FU});var OU=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")}},YC=class Y{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Z){this.key=Z}static existing=new OU;static create(Z,X){let _=new Y(Z),{type:G,globals:W,actions:H,perspectives:J}=X(_),$={type:G,key:Z,globals:W,actions:H,perspectives:J};return Y.existing.set(Z,$),$}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 ZC=O8({key:"usersInRoomIndex",mutable:!0,default:()=>new D1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),s5=O8({key:"roomIndex",default:()=>new D1,mutable:!0,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),EU={enteredAtEpoch:0},U6=EY({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(Y)=>typeof Y==="string",isBType:(Y)=>typeof Y==="string"},EU),XC=DY({key:"usersInMyRoomView",get:(Y)=>({find:Z})=>{let X=A7(U6);return[Z(X,Y)]}});import{spawn as DU}from"child_process";var a5=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 a5{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=G1(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=G1(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=G1(this.incompleteLog);this.handleLog(H);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)H=G1(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()}},VU=class extends a5{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(Y){super((...Z)=>{return this.out.next(Z),this});this.id=Y,this.in=new J0,this.out=new J0,this.in.subscribe("socket",(Z)=>{this.handleEvent(...Z)})}dispose(){for(let Y of this.disposalFunctions)Y()}},e7=class extends a5{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...Y){this.process.stderr.write(z0(Y.map((Z)=>Z instanceof D1?`{ ${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 _=G1(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=G1(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 VU(`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)}},Y3=W6({key:"roomArguments",default:["echo",["Hello World!"]]}),MU=DY({key:"room",get:(Y)=>async({get:Z,find:X})=>{let _=X(Y3,Y),G=Z(_),[W,H]=G,J=await new Promise(($)=>{let Q=DU(W,H,{env:process.env}),z=(O)=>{if(O.toString()==="ALIVE")Q.stdout.off("data",z),$(Q)};Q.stdout.on("data",z)});return new LU(J,Y)}}),FC=H6({key:"createRoom",do:({get:Y,set:Z,find:X},_,G,W)=>{let H=W?[G,W]:[G],J=X(Y3,_);Z(J,H),Z(s5,(z)=>z.add(_));let $=X(MU,_);return Y($)}}),UC=H6({key:"joinRoom",do:(Y,Z,X,_)=>{let G={enteredAtEpoch:_};return Q6(U6,(W)=>{W.set({room:Z,user:X},G)},Y.env().store),G}}),OC=H6({key:"leaveRoom",do:(Y,Z,X)=>{Q6(U6,(_)=>{_.delete({room:Z,user:X})},Y.env().store)}}),EC=H6({key:"destroyRoom",do:(Y,Z)=>{Q6(U6,(X)=>{X.delete({room:Z})},Y.env().store),Y.set(s5,(X)=>(X.delete(Z),X))}});var DC=W6({key:"redactor",default:{occlude:(Y)=>Y}}),LC=W6({key:"unacknowledgedUpdates",default:()=>[]}),VC=W6({key:"sockets",default:null}),MC=O8({key:"socketsIndex",mutable:!0,default:()=>new D1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),AC=O8({key:"usersIndex",mutable:!0,default:()=>new D1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),wC=EY({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(Y)=>Y.startsWith("user::"),isBType:(Y)=>Y.startsWith("socket::")});var{file:vH,serve:hO}=globalThis.Bun;import{readFileSync as _3}from"fs";import{createServer as NU}from"http";import{createServer as IU}from"https";import{resolve as e5}from"path";function Z3(Y,Z){if(Y instanceof Promise)throw new Error(Z)}function AU(Y,Z){let X={},_=[];for(let G in Y){let W=Y[G]["~standard"].validate(Z[G]);if(Z3(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 t5(Y){let Z=Y.runtimeEnvStrict??Y.runtimeEnv??process.env;if(Y.emptyStringAsUndefined??!1){for(let[f,h]of Object.entries(Z))if(h==="")delete Z[f]}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)),$=J?{...W,...H,...G}:{...G,...H},Q=Y.createFinalSchema?.($,J)["~standard"].validate(Z)??AU($,Z);Z3(Q,"Validation must be synchronous");let z=Y.onValidationError??((f)=>{throw console.error("\u274C Invalid environment variables:",f),new Error("Invalid environment variables")}),O=Y.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(Q.issues)return z(Q.issues);let D=(f)=>{if(!Y.clientPrefix)return!0;return!f.startsWith(Y.clientPrefix)&&!(f in H)},V=(f)=>{return J||!D(f)},R=(f)=>{return f==="__esModule"||f==="$$typeof"},A=(Y.extends??[]).reduce((f,h)=>{return Object.assign(f,h)},{}),g=Object.assign(A,Q.value);return new Proxy(g,{get(f,h){if(typeof h!=="string")return;if(R(h))return;if(!V(h))return O(h);return Reflect.get(f,h)}})}var wU="__vite_start_time"in globalThis,RU=typeof window!=="undefined",SC="vitest"in globalThis,H4=E1("string"),X3=E1('"true" | "false" | undefined'),g1=t5({isServer:!wU&&!RU,server:{CI:E1("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:X3.pipe((Y)=>Y==="true"),FRONTEND_PORT:H4.pipe((Y)=>Number.parseInt(Y,10)),FRONTEND_ORIGINS:H4.pipe.try((Y)=>JSON.parse(Y),E1("string[]")),API_KEY_OPENAI:E1("string | undefined"),API_KEY_RESEND:E1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:H4,VITE_DEV_FRONTEND_HOST:E1("string | undefined"),VITE_DEV_HTTPS:X3.pipe((Y)=>Y==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var G3=e5(import.meta.dirname,"../dev"),RY=g1.VITE_DEV_HTTPS?{cert:_3(e5(G3,"./cert.pem"),"utf-8"),key:_3(e5(G3,"./key.pem"),"utf-8")}:void 0;function gC(Y){if(RY)return IU(RY,Y);return NU({},Y)}import KO from"path";var U=Symbol.for("drizzle:entityKind");function M(Y,Z){if(!Y||typeof Y!=="object")return!1;if(Y instanceof Z)return!0;if(!Object.prototype.hasOwnProperty.call(Z,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 YX{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 ZX{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 W3(Y,this)}}class W3{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 NY(Y,...Z){return Y(...Z)}function H3(Y,Z){return`${Y[y1]}_${Z.join("_")}_unique`}function J3(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 Q3(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]=J3(Y,_+1,!0);X.push($),_=Q;continue}if(W==="}")return[X,_+1];if(W==="{"){let[$,Q]=Q3(Y,_+1);X.push($),_=Q;continue}let[H,J]=J3(Y,_,!1);X.push(H),_=J}return[X,_]}function $3(Y){let[Z]=Q3(Y,1);return Z}function XX(Y){return`{${Y.map((Z)=>{if(Array.isArray(Z))return XX(Z);if(typeof Z==="string")return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Z}`}).join(",")}}`}class k extends YX{foreignKeyConfigs=[];static[U]="PgColumnBuilder";array(Y){return new F3(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 NY((G,W)=>{let H=new ZX(()=>{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 z3(Y,this.config)}}class j extends E0{constructor(Y,Z){if(!Z.uniqueName)Z.uniqueName=H3(Y,[Z.name]);super(Y,Z);this.table=Y}static[U]="PgColumn"}class z3 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 O6{static[U]="IndexedColumn";constructor(Y,Z,X,_){this.name=Y,this.keyAsName=Z,this.type=X,this.indexConfig=_}name;keyAsName;type;indexConfig}class F3 extends k{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 _X(Y,this.config,Z)}}class _X 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=$3(Y);return Y.map((Z)=>this.baseColumn.mapFromDriverValue(Z))}mapToDriverValue(Y,Z=!1){let X=Y.map((_)=>_===null?null:M(this.baseColumn,_X)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Z)return X;return XX(X)}}class U3 extends k{static[U]="PgEnumObjectColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumObjectColumn");this.config.enum=Z}build(Y){return new O3(Y,this.config)}}class O3 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 IY=Symbol.for("drizzle:isPgEnum");function E3(Y){return!!Y&&typeof Y==="function"&&IY in Y&&Y[IY]===!0}class D3 extends k{static[U]="PgEnumColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumColumn");this.config.enum=Z}build(Y){return new L3(Y,this.config)}}class L3 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 E6(Y,Z){return Array.isArray(Z)?BU(Y,[...Z],void 0):CU(Y,Z,void 0)}function BU(Y,Z,X){let _=Object.assign((G)=>new D3(G??"",_),{enumName:Y,enumValues:Z,schema:X,[IY]:!0});return _}function CU(Y,Z,X){let _=Object.assign((G)=>new U3(G??"",_),{enumName:Y,enumValues:Object.values(Z),schema:X,[IY]:!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 D6 extends P0{static[U]="WithSubquery"}var V3="0.44.4";var GX,WX,D0={startActiveSpan(Y,Z){if(!GX)return Z();if(!WX)WX=GX.trace.getTracer("drizzle-orm",V3);return NY((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()}}),GX,WX)}};var A0=Symbol.for("drizzle:ViewBaseConfig");var g4=Symbol.for("drizzle:Schema"),BY=Symbol.for("drizzle:Columns"),M3=Symbol.for("drizzle:ExtraConfigColumns"),HX=Symbol.for("drizzle:OriginalName"),JX=Symbol.for("drizzle:BaseName"),L6=Symbol.for("drizzle:IsAlias"),A3=Symbol.for("drizzle:ExtraConfigBuilder"),TU=Symbol.for("drizzle:IsDrizzleTable");class P{static[U]="Table";static Symbol={Name:y1,Schema:g4,OriginalName:HX,Columns:BY,ExtraConfigColumns:M3,BaseName:JX,IsAlias:L6,ExtraConfigBuilder:A3};[y1];[HX];[g4];[BY];[M3];[JX];[L6]=!1;[TU]=!0;[A3]=void 0;constructor(Y,Z,X){this[y1]=this[HX]=Y,this[g4]=Z,this[JX]=X}}function c0(Y){return Y[y1]}function y4(Y){return`${Y[g4]??"public"}.${Y[y1]}`}function QX(Y){return Y!==null&&Y!==void 0&&typeof Y.getSQL==="function"}function KU(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=R3;shouldInlineParams=!1;usedTables=[];append(Y){return this.queryChunks.push(...Y.queryChunks),this}toQuery(Y){return D0.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:$}=X;return KU(Y.map((Q)=>{if(M(Q,u0))return{sql:Q.value.join(""),params:[]};if(M(Q,CY))return{sql:G(Q.value),params:[]};if(Q===void 0)return{sql:"",params:[]};if(Array.isArray(Q)){let z=[new u0("(")];for(let[O,D]of Q.entries())if(z.push(D),O<Q.length-1)z.push(new u0(", "));return z.push(new u0(")")),this.buildQueryFromSourceParams(z,X)}if(M(Q,x))return this.buildQueryFromSourceParams(Q.queryChunks,{...X,inlineParams:J||Q.shouldInlineParams});if(M(Q,P)){let z=Q[P.Symbol.Schema],O=Q[P.Symbol.Name];return{sql:z===void 0||Q[L6]?G(O):G(z)+"."+G(O),params:[]}}if(M(Q,E0)){let z=_.getColumnCasing(Q);if(Z.invokeSource==="indexes")return{sql:G(z),params:[]};let O=Q.table[P.Symbol.Schema];return{sql:Q.table[L6]||O===void 0?G(Q.table[P.Symbol.Name])+"."+G(z):G(O)+"."+G(Q.table[P.Symbol.Name])+"."+G(z),params:[]}}if(M(Q,L1)){let z=Q[A0].schema,O=Q[A0].name;return{sql:z===void 0||Q[A0].isAlias?G(O):G(z)+"."+G(O),params:[]}}if(M(Q,N1)){if(M(Q.value,N4))return{sql:W($.value++,Q),params:[Q],typings:["none"]};let z=Q.value===null?null:Q.encoder.mapToDriverValue(Q.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(Q.encoder)];return{sql:W($.value++,z),params:[z],typings:O}}if(M(Q,N4))return{sql:W($.value++,Q),params:[Q],typings:["none"]};if(M(Q,x.Aliased)&&Q.fieldAlias!==void 0)return{sql:G(Q.fieldAlias),params:[]};if(M(Q,P0)){if(Q._.isWith)return{sql:G(Q._.alias),params:[]};return this.buildQueryFromSourceParams([new u0("("),Q._.sql,new u0(") "),new CY(Q._.alias)],X)}if(E3(Q)){if(Q.schema)return{sql:G(Q.schema)+"."+G(Q.enumName),params:[]};return{sql:G(Q.enumName),params:[]}}if(QX(Q)){if(Q.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([Q.getSQL()],X);return this.buildQueryFromSourceParams([new u0("("),Q.getSQL(),new u0(")")],X)}if(J)return{sql:this.mapInlineParam(Q,X),params:[]};return{sql:W($.value++,Q),params:[Q],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 CY{constructor(Y){this.value=Y}static[U]="Name";brand;getSQL(){return new x([this])}}function w3(Y){return typeof Y==="object"&&Y!==null&&"mapToDriverValue"in Y&&typeof Y.mapToDriverValue==="function"}var R3={mapFromDriverValue:(Y)=>Y},N3={mapToDriverValue:(Y)=>Y},KT={...R3,...N3};class N1{constructor(Y,Z=N3){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($){return new x($)}Y.fromList=X;function _($){return new x([new u0($)])}Y.raw=_;function G($,Q){let z=[];for(let[O,D]of $.entries()){if(O>0&&Q!==void 0)z.push(Q);z.push(D)}return new x(z)}Y.join=G;function W($){return new CY($)}Y.identifier=W;function H($){return new N4($)}Y.placeholder=H;function J($,Q){return new N1($,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 N4{constructor(Y){this.name=Y}static[U]="Placeholder";getSQL(){return new x([this])}}function $X(Y,Z){return Y.map((X)=>{if(M(X,N4)){if(!(X.name in Z))throw new Error(`No value for placeholder "${X.name}" was provided`);return Z[X.name]}if(M(X,N1)&&M(X.value,N4)){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 qU=Symbol.for("drizzle:IsDrizzleView");class L1{static[U]="View";[A0];[qU]=!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 w8{constructor(Y){this.table=Y}static[U]="ColumnAliasProxyHandler";get(Y,Z){if(Z==="table")return this.table;return Y[Z]}}class V6{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 w8(new Proxy(Y,this)))}),G}let X=Y[Z];if(M(X,E0))return new Proxy(X,new w8(new Proxy(Y,this)));return X}}function TY(Y,Z){return new Proxy(Y,new V6(Z,!1))}function o1(Y,Z){return new Proxy(Y,new w8(new Proxy(Y.table,new V6(Z,!1))))}function zX(Y,Z){return new x.Aliased(M6(Y.sql,Z),Y.fieldAlias)}function M6(Y,Z){return E.join(Y.queryChunks.map((X)=>{if(M(X,E0))return o1(X,Z);if(M(X,x))return M6(X,Z);if(M(X,x.Aliased))return zX(X,Z);return X}))}class KY extends Error{static[U]="DrizzleError";constructor({message:Y,cause:Z}){super(Y);this.name="DrizzleError",this.cause=Z}}class J4 extends Error{constructor(Y,Z,X){super(`Failed query: ${Y}
|
|
62
|
+
params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrace(this,J4),X)this.cause=X}}class FX extends KY{static[U]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class I3{static[U]="ConsoleLogWriter";write(Y){console.log(Y)}}class UX{static[U]="DefaultLogger";writer;constructor(Y){this.writer=Y?.writer??new I3}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 OX{static[U]="NoopLogger";logQuery(){}}class H1{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 B3(Y,Z,X){let _={},G=Y.reduce((W,{path:H,field:J},$)=>{let Q;if(M(J,E0))Q=J;else if(M(J,x))Q=J.decoder;else Q=J.sql.decoder;let z=W;for(let[O,D]of H.entries())if(O<H.length-1){if(!(D in z))z[D]={};z=z[D]}else{let V=Z[$],R=z[D]=V===null?null:Q.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 A6(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 qY(Y,Z){let X=Object.entries(Z).filter(([,_])=>_!==void 0).map(([_,G])=>{if(M(G,x)||M(G,E0))return[_,G];else return[_,new N1(G,Y[P.Symbol.Columns][_])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function C3(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 T3(Y){return Y[P.Symbol.Columns]}function Q4(Y){return M(Y,P0)?Y._.alias:M(Y,L1)?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 K3(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 k{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 q3 extends I4{static[U]="PgBigInt53Builder";constructor(Y){super(Y,"number","PgBigInt53")}build(Y){return new j3(Y,this.config)}}class j3 extends j{static[U]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class P3 extends I4{static[U]="PgBigInt64Builder";constructor(Y){super(Y,"bigint","PgBigInt64")}build(Y){return new S3(Y,this.config)}}class S3 extends j{static[U]="PgBigInt64";getSQLType(){return"bigint"}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 k{static[U]="PgBigSerial53Builder";constructor(Y){super(Y,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new h3(Y,this.config)}}class h3 extends j{static[U]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class f3 extends k{static[U]="PgBigSerial64Builder";constructor(Y){super(Y,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(Y){return new b3(Y,this.config)}}class b3 extends j{static[U]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(Y){return BigInt(Y)}}function k3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new x3(X);return new f3(X)}class g3 extends k{static[U]="PgBooleanBuilder";constructor(Y){super(Y,"boolean","PgBoolean")}build(Y){return new y3(Y,this.config)}}class y3 extends j{static[U]="PgBoolean";getSQLType(){return"boolean"}}function w6(Y){return new g3(Y??"")}class p3 extends k{static[U]="PgCharBuilder";constructor(Y,Z){super(Y,"string","PgChar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new m3(Y,this.config)}}class m3 extends j{static[U]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function u3(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new p3(X,_)}class d3 extends k{static[U]="PgCidrBuilder";constructor(Y){super(Y,"string","PgCidr")}build(Y){return new c3(Y,this.config)}}class c3 extends j{static[U]="PgCidr";getSQLType(){return"cidr"}}function l3(Y){return new d3(Y??"")}class i3 extends k{static[U]="PgCustomColumnBuilder";constructor(Y,Z,X){super(Y,"custom","PgCustomColumn");this.config.fieldConfig=Z,this.config.customTypeParams=X}build(Y){return new o3(Y,this.config)}}class o3 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 n3(Y){return(Z,X)=>{let{name:_,config:G}=X0(Z,X);return new i3(_,G,Y)}}class $4 extends k{static[U]="PgDateColumnBaseBuilder";defaultNow(){return this.default(E`now()`)}}class r3 extends $4{static[U]="PgDateBuilder";constructor(Y){super(Y,"date","PgDate")}build(Y){return new jY(Y,this.config)}}class jY extends j{static[U]="PgDate";getSQLType(){return"date"}mapFromDriverValue(Y){return new Date(Y)}mapToDriverValue(Y){return Y.toISOString()}}class s3 extends $4{static[U]="PgDateStringBuilder";constructor(Y){super(Y,"string","PgDateString")}build(Y){return new PY(Y,this.config)}}class PY extends j{static[U]="PgDateString";getSQLType(){return"date"}}function a3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="date")return new r3(X);return new s3(X)}class t3 extends k{static[U]="PgDoublePrecisionBuilder";constructor(Y){super(Y,"number","PgDoublePrecision")}build(Y){return new e3(Y,this.config)}}class e3 extends j{static[U]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function YW(Y){return new t3(Y??"")}class ZW extends k{static[U]="PgInetBuilder";constructor(Y){super(Y,"string","PgInet")}build(Y){return new XW(Y,this.config)}}class XW extends j{static[U]="PgInet";getSQLType(){return"inet"}}function _W(Y){return new ZW(Y??"")}class GW extends I4{static[U]="PgIntegerBuilder";constructor(Y){super(Y,"number","PgInteger")}build(Y){return new WW(Y,this.config)}}class WW extends j{static[U]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseInt(Y);return Y}}function R6(Y){return new GW(Y??"")}class HW extends k{static[U]="PgIntervalBuilder";constructor(Y,Z){super(Y,"string","PgInterval");this.config.intervalConfig=Z}build(Y){return new JW(Y,this.config)}}class JW 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 QW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new HW(X,_)}class $W extends k{static[U]="PgJsonBuilder";constructor(Y){super(Y,"json","PgJson")}build(Y){return new SY(Y,this.config)}}class SY 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 zW(Y){return new $W(Y??"")}class FW extends k{static[U]="PgJsonbBuilder";constructor(Y){super(Y,"json","PgJsonb")}build(Y){return new vY(Y,this.config)}}class vY 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 UW(Y){return new FW(Y??"")}class OW extends k{static[U]="PgLineBuilder";constructor(Y){super(Y,"array","PgLine")}build(Y){return new EW(Y,this.config)}}class EW 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 DW extends k{static[U]="PgLineABCBuilder";constructor(Y){super(Y,"json","PgLineABC")}build(Y){return new LW(Y,this.config)}}class LW 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 VW(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new OW(X);return new DW(X)}class MW extends k{static[U]="PgMacaddrBuilder";constructor(Y){super(Y,"string","PgMacaddr")}build(Y){return new AW(Y,this.config)}}class AW extends j{static[U]="PgMacaddr";getSQLType(){return"macaddr"}}function wW(Y){return new MW(Y??"")}class RW extends k{static[U]="PgMacaddr8Builder";constructor(Y){super(Y,"string","PgMacaddr8")}build(Y){return new NW(Y,this.config)}}class NW extends j{static[U]="PgMacaddr8";getSQLType(){return"macaddr8"}}function IW(Y){return new RW(Y??"")}class BW extends k{static[U]="PgNumericBuilder";constructor(Y,Z,X){super(Y,"string","PgNumeric");this.config.precision=Z,this.config.scale=X}build(Y){return new xY(Y,this.config)}}class xY 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 CW extends k{static[U]="PgNumericNumberBuilder";constructor(Y,Z,X){super(Y,"number","PgNumericNumber");this.config.precision=Z,this.config.scale=X}build(Y){return new TW(Y,this.config)}}class TW 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 KW extends k{static[U]="PgNumericBigIntBuilder";constructor(Y,Z,X){super(Y,"bigint","PgNumericBigInt");this.config.precision=Z,this.config.scale=X}build(Y){return new qW(Y,this.config)}}class qW 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 jW(Y,Z){let{name:X,config:_}=X0(Y,Z),G=_?.mode;return G==="number"?new CW(X,_?.precision,_?.scale):G==="bigint"?new KW(X,_?.precision,_?.scale):new BW(X,_?.precision,_?.scale)}class PW extends k{static[U]="PgPointTupleBuilder";constructor(Y){super(Y,"array","PgPointTuple")}build(Y){return new SW(Y,this.config)}}class SW 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 vW extends k{static[U]="PgPointObjectBuilder";constructor(Y){super(Y,"json","PgPointObject")}build(Y){return new xW(Y,this.config)}}class xW 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 hW(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new PW(X);return new vW(X)}function jU(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 fW(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 EX(Y){let Z=jU(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=fW(Z,X);X+=8;let $=fW(Z,X);return X+=8,[J,$]}throw new Error("Unsupported geometry type")}class bW extends k{static[U]="PgGeometryBuilder";constructor(Y){super(Y,"array","PgGeometry")}build(Y){return new kW(Y,this.config)}}class kW extends j{static[U]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){return EX(Y)}mapToDriverValue(Y){return`point(${Y[0]} ${Y[1]})`}}class gW extends k{static[U]="PgGeometryObjectBuilder";constructor(Y){super(Y,"json","PgGeometryObject")}build(Y){return new yW(Y,this.config)}}class yW extends j{static[U]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){let Z=EX(Y);return{x:Z[0],y:Z[1]}}mapToDriverValue(Y){return`point(${Y.x} ${Y.y})`}}function pW(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new bW(X);return new gW(X)}class mW extends k{static[U]="PgRealBuilder";constructor(Y,Z){super(Y,"number","PgReal");this.config.length=Z}build(Y){return new uW(Y,this.config)}}class uW 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 dW(Y){return new mW(Y??"")}class cW extends k{static[U]="PgSerialBuilder";constructor(Y){super(Y,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new lW(Y,this.config)}}class lW extends j{static[U]="PgSerial";getSQLType(){return"serial"}}function iW(Y){return new cW(Y??"")}class oW extends I4{static[U]="PgSmallIntBuilder";constructor(Y){super(Y,"number","PgSmallInt")}build(Y){return new nW(Y,this.config)}}class nW extends j{static[U]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number(Y);return Y}}function rW(Y){return new oW(Y??"")}class sW extends k{static[U]="PgSmallSerialBuilder";constructor(Y){super(Y,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new aW(Y,this.config)}}class aW extends j{static[U]="PgSmallSerial";getSQLType(){return"smallserial"}}function tW(Y){return new sW(Y??"")}class eW extends k{static[U]="PgTextBuilder";constructor(Y,Z){super(Y,"string","PgText");this.config.enumValues=Z.enum}build(Y){return new Y2(Y,this.config)}}class Y2 extends j{static[U]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function Z2(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new eW(X,_)}class X2 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 hY(Y,this.config)}}class hY 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 _2(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new X2(X,_.withTimezone??!1,_.precision)}class G2 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 fY(Y,this.config)}}class fY 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 W2 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 bY(Y,this.config)}}class bY 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 H2(Y,Z={}){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="string")return new W2(X,_.withTimezone??!1,_.precision);return new G2(X,_?.withTimezone??!1,_?.precision)}class J2 extends k{static[U]="PgUUIDBuilder";constructor(Y){super(Y,"string","PgUUID")}defaultRandom(){return this.default(E`gen_random_uuid()`)}build(Y){return new kY(Y,this.config)}}class kY extends j{static[U]="PgUUID";getSQLType(){return"uuid"}}function j1(Y){return new J2(Y??"")}class Q2 extends k{static[U]="PgVarcharBuilder";constructor(Y,Z){super(Y,"string","PgVarchar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new $2(Y,this.config)}}class $2 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 Q2(X,_)}class z2 extends k{static[U]="PgBinaryVectorBuilder";constructor(Y,Z){super(Y,"string","PgBinaryVector");this.config.dimensions=Z.dimensions}build(Y){return new F2(Y,this.config)}}class F2 extends j{static[U]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function U2(Y,Z){let{name:X,config:_}=X0(Y,Z);return new z2(X,_)}class O2 extends k{static[U]="PgHalfVectorBuilder";constructor(Y,Z){super(Y,"array","PgHalfVector");this.config.dimensions=Z.dimensions}build(Y){return new E2(Y,this.config)}}class E2 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 D2(Y,Z){let{name:X,config:_}=X0(Y,Z);return new O2(X,_)}class L2 extends k{static[U]="PgSparseVectorBuilder";constructor(Y,Z){super(Y,"string","PgSparseVector");this.config.dimensions=Z.dimensions}build(Y){return new V2(Y,this.config)}}class V2 extends j{static[U]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function M2(Y,Z){let{name:X,config:_}=X0(Y,Z);return new L2(X,_)}class A2 extends k{static[U]="PgVectorBuilder";constructor(Y,Z){super(Y,"array","PgVector");this.config.dimensions=Z.dimensions}build(Y){return new w2(Y,this.config)}}class w2 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 R2(Y,Z){let{name:X,config:_}=X0(Y,Z);return new A2(X,_)}function N2(){return{bigint:v3,bigserial:k3,boolean:w6,char:u3,cidr:l3,customType:n3,date:a3,doublePrecision:YW,inet:_W,integer:R6,interval:QW,json:zW,jsonb:UW,line:VW,macaddr:wW,macaddr8:IW,numeric:jW,point:hW,geometry:pW,real:dW,serial:iW,smallint:rW,smallserial:tW,text:Z2,time:_2,timestamp:H2,uuid:j1,varchar:e0,bit:U2,halfvec:D2,sparsevec:M2,vector:R2}}var DX=Symbol.for("drizzle:PgInlineForeignKeys"),I2=Symbol.for("drizzle:EnableRLS");class d0 extends P{static[U]="PgTable";static Symbol=Object.assign({},P.Symbol,{InlineForeignKeys:DX,EnableRLS:I2});[DX]=[];[I2]=!1;[P.Symbol.ExtraConfigBuilder]=void 0;[P.Symbol.ExtraConfigColumns]={}}function PU(Y,Z,X,_,G=Y){let W=new d0(Y,_,G),H=typeof Z==="function"?Z(N2()):Z,J=Object.fromEntries(Object.entries(H).map(([z,O])=>{let D=O;D.setName(z);let V=D.build(W);return W[DX].push(...D.buildForeignKeys(V,W)),[z,V]})),$=Object.fromEntries(Object.entries(H).map(([z,O])=>{let D=O;D.setName(z);let V=D.buildExtraConfigColumn(W);return[z,V]})),Q=Object.assign(W,J);if(Q[P.Symbol.Columns]=J,Q[P.Symbol.ExtraConfigColumns]=$,X)Q[d0.Symbol.ExtraConfigBuilder]=X;return Object.assign(Q,{enableRLS:()=>{return Q[d0.Symbol.EnableRLS]=!0,Q}})}var B4=(Y,Z,X)=>{return PU(Y,Z,X,void 0)};function B2(...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 C2(Y,this.columns,this.name)}}class C2{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(w3(Z)&&!QX(Y)&&!M(Y,N1)&&!M(Y,N4)&&!M(Y,E0)&&!M(Y,P)&&!M(Y,L1))return new N1(Y,Z);return Y}var gY=(Y,Z)=>{return E`${Y} = ${V1(Z,Y)}`},T2=(Y,Z)=>{return E`${Y} <> ${V1(Z,Y)}`};function I6(...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 K2(...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 q2(Y){return E`not ${Y}`}var j2=(Y,Z)=>{return E`${Y} > ${V1(Z,Y)}`},P2=(Y,Z)=>{return E`${Y} >= ${V1(Z,Y)}`},S2=(Y,Z)=>{return E`${Y} < ${V1(Z,Y)}`},v2=(Y,Z)=>{return E`${Y} <= ${V1(Z,Y)}`};function x2(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 h2(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 f2(Y){return E`${Y} is null`}function b2(Y){return E`${Y} is not null`}function k2(Y){return E`exists ${Y}`}function g2(Y){return E`not exists ${Y}`}function y2(Y,Z,X){return E`${Y} between ${V1(Z,Y)} and ${V1(X,Y)}`}function p2(Y,Z,X){return E`${Y} not between ${V1(Z,Y)} and ${V1(X,Y)}`}function m2(Y,Z){return E`${Y} like ${Z}`}function u2(Y,Z){return E`${Y} not like ${Z}`}function d2(Y,Z){return E`${Y} ilike ${Z}`}function c2(Y,Z){return E`${Y} not ilike ${Z}`}function l2(Y){return E`${Y} asc`}function i2(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 o2{constructor(Y,Z){this.table=Y,this.config=Z}static[U]="Relations"}class C4 extends LX{constructor(Y,Z,X,_){super(Y,Z,X?.relationName);this.config=X,this.isNullable=_}static[U]="One";withFieldName(Y){let Z=new C4(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Z.fieldName=Y,Z}}class B6 extends LX{constructor(Y,Z,X){super(Y,Z,X?.relationName);this.config=X}static[U]="Many";withFieldName(Y){let Z=new B6(this.sourceTable,this.referencedTable,this.config);return Z.fieldName=Y,Z}}function n2(){return{and:I6,between:y2,eq:gY,exists:k2,gt:j2,gte:P2,ilike:d2,inArray:x2,isNull:f2,isNotNull:b2,like:m2,lt:S2,lte:v2,ne:T2,not:q2,notBetween:p2,notExists:g2,notLike:u2,notIlike:c2,notInArray:h2,or:K2,sql:E}}function r2(){return{sql:E,asc:l2,desc:i2}}function s2(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),$=_[J];X[J]=W,G[W]={tsName:W,dbName:H[P.Symbol.Name],schema:H[P.Symbol.Schema],columns:H[P.Symbol.Columns],relations:$?.relations??{},primaryKey:$?.primaryKey??[]};for(let z of Object.values(H[P.Symbol.Columns]))if(z.primary)G[W].primaryKey.push(z);let Q=H[P.Symbol.ExtraConfigBuilder]?.(H[P.Symbol.ExtraConfigColumns]);if(Q){for(let z of Object.values(Q))if(M(z,N6))G[W].primaryKey.push(...z.columns)}}else if(M(H,o2)){let J=y4(H.table),$=X[J],Q=H.config(Z(H.table)),z;for(let[O,D]of Object.entries(Q))if($){let V=G[$];if(V.relations[O]=D,z)V.primaryKey.push(...z)}else{if(!(J in _))_[J]={relations:{},primaryKey:z};_[J].relations[O]=D}}return{tables:G,tableNamesMap:X}}function SU(Y){return function Z(X,_){return new C4(Y,X,_,_?.fields.reduce((G,W)=>G&&W.notNull,!0)??!1)}}function vU(Y){return function Z(X,_){return new B6(Y,X,_)}}function a2(Y,Z,X){if(M(X,C4)&&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 $ of Object.values(G.relations))if(X.relationName&&X!==$&&$.relationName===X.relationName||!X.relationName&&$.referencedTable===X.sourceTable)J.push($);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],C4)&&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 t2(Y){return{one:SU(Y),many:vU(Y)}}function yY(Y,Z,X,_,G=(W)=>W){let W={};for(let[H,J]of _.entries())if(J.isJson){let $=Z.relations[J.tsKey],Q=X[H],z=typeof Q==="string"?JSON.parse(Q):Q;W[J.tsKey]=M($,C4)?z&&yY(Y,Y[J.relationTableTsKey],z,J.selection,G):z.map((O)=>yY(Y,Y[J.relationTableTsKey],O,J.selection,G))}else{let $=G(X[H]),Q=J.field,z;if(M(Q,E0))z=Q;else if(M(Q,x))z=Q.decoder;else z=Q.sql.decoder;W[J.tsKey]=$===null?null:z.mapFromDriverValue($)}return W}import XO from"os";import _O from"fs";var pY=new Map,VX=new Map,MX=Symbol("OriginError"),R8={};class P1 extends Promise{constructor(Y,Z,X,_,G={}){let W,H;super((J,$)=>{W=J,H=$});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[MX]=this.handler.debug?new Error:this.tagged&&xU(this.strings)}get origin(){return(this.handler.debug?this[MX].stack:this.tagged&&VX.has(this.strings)?VX.get(this.strings):VX.set(this.strings,this[MX].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(R8),{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 xU(Y){if(pY.has(Y))return pY.get(Y);let Z=Error.stackTraceLimit;return Error.stackTraceLimit=4,pY.set(Y,new Error),Error.stackTraceLimit=Z,pY.get(Y)}class N8 extends Error{constructor(Y){super(Y.message);this.name=this.constructor.name,Object.assign(this,Y)}}var f0={connection:e2,postgres:YH,generic:ZH,notSupported:XH};function e2(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,e2),W}function YH(Y){let Z=new N8(Y);return Error.captureStackTrace(Z,YH),Z}function ZH(Y,Z){let X=Object.assign(new Error(Y+": "+Z),{code:Y});return Error.captureStackTrace(X,ZH),X}function XH(Y){let Z=Object.assign(new Error(Y+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:Y});return Error.captureStackTrace(Z,XH),Z}var hU={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 dY{then(){AX()}catch(){AX()}finally(){AX()}}class q6 extends dY{constructor(Y){super();this.value=iY(Y)}}class n1 extends dY{constructor(Y,Z,X){super();this.value=Y,this.type=Z,this.array=X}}class cY extends dY{constructor(Y,Z){super();this.first=Y,this.rest=Z}build(Y,Z,X,_){let G=fU.map(([W,H])=>({fn:H,i:Y.search(W)})).sort((W,H)=>W.i-H.i).pop();return G.i===-1?BX(this.first,_):G.fn(this.first,this.rest,Z,X,_)}}function lY(Y,Z,X,_){let G=Y instanceof n1?Y.value:Y;if(G===void 0){if(Y instanceof n1?Y.value=_.transform.undefined:G=Y=_.transform.undefined,G===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(Y instanceof n1?(Z.push(Y.value),Y.array?Y.array[Y.type||uY(Y.value)]||Y.type||HH(Y.value):Y.type):(Z.push(Y),uY(Y)))}var GH=QH(hU);function NX(Y,Z,X,_,G,W){for(let H=1;H<Y.strings.length;H++)Z+=IX(Z,X,_,G,W)+Y.strings[H],X=Y.args[H];return Z}function IX(Y,Z,X,_,G){return Z instanceof cY?Z.build(Y,X,_,G):Z instanceof P1?RX(Z,X,_,G):Z instanceof q6?Z.value:Z&&Z[0]instanceof P1?Z.reduce((W,H)=>W+" "+RX(H,X,_,G),""):lY(Z,X,_,G)}function RX(Y,Z,X,_){return Y.fragment=!0,NX(Y,Y.strings[0],Y.args[0],Z,X,_)}function WH(Y,Z,X,_,G){return Y.map((W)=>"("+_.map((H)=>IX("values",W[H],Z,X,G)).join(",")+")").join(",")}function _H(Y,Z,X,_,G){let W=Array.isArray(Y[0]),H=Z.length?Z.flat():Object.keys(W?Y[0]:Y);return WH(W?Y:[Y],X,_,H,G)}function mY(Y,Z,X,_,G){if(typeof Y==="string"&&(Y=[Y].concat(Z)),Array.isArray(Y))return BX(Y,G);let W;return(Z.length?Z.flat():Object.keys(Y)).map((J)=>{return W=Y[J],(W instanceof P1?RX(W,X,_,G):W instanceof q6?W.value:lY(W,X,_,G))+" as "+iY(G.transform.column.to?G.transform.column.to(J):J)}).join(",")}var fU=Object.entries({values:_H,in:(...Y)=>{let Z=_H(...Y);return Z==="()"?"(null)":Z},select:mY,as:mY,returning:mY,"\\(":mY,update(Y,Z,X,_,G){return(Z.length?Z.flat():Object.keys(Y)).map((W)=>iY(G.transform.column.to?G.transform.column.to(W):W)+"="+IX("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"("+BX(W,G)+")values"+WH(Array.isArray(Y)?Y:[Y],X,_,W,G)}}).map(([Y,Z])=>[new RegExp("((?:^|[\\s(])"+Y+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Z]);function AX(){throw f0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:bU,parsers:kU}=GH;function HH(Y){if(Array.isArray(Y))return HH(Y[0]);return typeof Y==="string"?1009:0}var JH=function(Y){let Z=QH(Y||{});return{serializers:Object.assign({},bU,Z.serializers),parsers:Object.assign({},kU,Z.parsers)}};function QH(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 BX(Y,{transform:{column:Z}}){return Y.map((X)=>iY(Z.to?Z.to(X):X)).join(",")}var iY=function Y(Z){return'"'+Z.replace(/"/g,'""').replace(/\./g,'"."')+'"'},uY=function Y(Z){return Z instanceof n1?Z.type:Z instanceof Date?1184:Z instanceof Uint8Array?17:Z===!0||Z===!1?16:typeof Z==="bigint"?20:Array.isArray(Z)?Y(Z[0]):0},gU=/\\/g,yU=/"/g;function pU(Y){return Y.replace(gU,"\\\\").replace(yU,"\\\"")}var $H=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 f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return J===null?"null":'"'+pU(X?X(J.type?J.value:J):""+J)+'"'}).join(H)+"}"},wX={i:0,char:null,str:"",quoted:!1,last:0},zH=function Y(Z,X,_){return wX.i=wX.last=0,FH(wX,Z,X,_)};function FH(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(FH(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,"-"),C6=(Y)=>Y.replace(/([A-Z])/g,"_$1").toLowerCase(),T6=(Y)=>(Y.slice(0,1)+Y.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),K6=(Y)=>Y.replace(/-/g,"_");function CX(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:CX(p4)};C6.column={to:C6};var TX={...p4};TX.column.to=C6;m4.column={from:m4};m4.value={from:CX(m4)};T6.column={to:T6};var KX={...m4};KX.column.to=T6;u4.column={from:u4};u4.value={from:CX(u4)};K6.column={to:K6};var qX={...u4};qX.column.to=K6;import UH from"net";import cU from"tls";import j6 from"crypto";import jX from"stream";import{performance as OH}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=mU;function mU(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),uU="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(dU,uU,{N:String.fromCharCode(0),i:0,inc(Y){return F0.i+=Y,F0},str(Y){let Z=Buffer.byteLength(Y);return oY(Z),F0.i+=Y1.write(Y,F0.i,Z,"utf8"),F0},i16(Y){return oY(2),Y1.writeUInt16BE(Y,F0.i),F0.i+=2,F0},i32(Y,Z){if(Z||Z===0)return Y1.writeUInt32BE(Y,Z),F0;return oY(4),Y1.writeUInt32BE(Y,F0.i),F0.i+=4,F0},z(Y){return oY(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 oY(Y){if(Y1.length-F0.i<Y){let Z=Y1,X=Z.length;Y1=Buffer.allocUnsafe(X+(X>>1)+Y),Z.copy(Y1)}}function dU(){return F0.i=0,F0}var vX=LH,lU=1,T4=c().S().end(),EH=c().H().end(),iU=c().i32(8).i32(80877103).end(8),oU=Buffer.concat([c().E().str(c.N).i32(0).end(),T4]),nU=c().D().str("S").str(c.N).end(),I8=()=>{},rU=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),sU={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 LH(Y,Z={},{onopen:X=I8,onend:_=I8,onclose:G=I8}={}){let{ssl:W,max:H,user:J,host:$,port:Q,database:z,parsers:O,transform:D,onnotice:V,onnotify:R,onparameter:A,max_pipeline:g,keep_alive:b,backoff:f,target_session_attrs:h}=Y,I=I1(),N=lU++,q={pid:null,secret:null},K=SX(JZ,Y.idle_timeout),p=SX(JZ,Y.max_lifetime),s=SX(yH,Y.connect_timeout),C=null,t,m=new d4,e=Buffer.alloc(0),U0=Y.fetch_types,b0={},Q1={},r1=Math.random().toString(36).slice(2),T=1,u=0,G0=0,C0=0,k0=0,a=0,$0=0,S0=0,T0=null,w0=null,n0=!1,L0=null,S1=null,l0=null,z4=null,g0=null,R0=null,v1=null,m1=null,v=null,K8=null,r0={queue:Z.closed,idleTimer:K,connect(F){l0=F,W_()},terminate:j8,execute:q8,cancel:fH,end:JZ,count:0,id:N};return Z.closed&&Z.closed.push(r0),r0;async function hH(){let F;try{F=Y.socket?await Promise.resolve(Y.socket(Y)):new UH.Socket}catch(L){o4(L);return}return F.on("error",o4),F.on("close",H_),F.on("drain",__),F}async function fH({pid:F,secret:L},l,W0){try{t=c().i32(16).i32(80877102).i32(F).i32(L).end(16),await G_(),C.once("error",W0),C.once("close",l)}catch(q0){W0(q0)}}function q8(F){if(n0)return k6(F,f0.connection("CONNECTION_DESTROYED",Y));if(F.cancelled)return;try{return F.state=q,v?I.push(F):(v=F,v.active=!0),gH(F),i0(bH(F))&&!F.describeFirst&&!F.cursorFn&&I.length<g&&(!F.options.onexecute||F.options.onexecute(r0))}catch(L){return I.length===0&&i0(T4),u1(L),!0}}function bH(F){if(F.parameters.length>=65534)throw f0.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([Y_(F),EH]):F.prepare?F.prepared?b6(F):Buffer.concat([Y_(F),b6(F)]):kH(F)}function Y_(F){return Buffer.concat([Q_(F.statement.string,F.parameters,F.statement.types,F.statement.name),IJ("S",F.statement.name)])}function b6(F){return Buffer.concat([NJ(F.parameters,F.statement.types,F.statement.name,F.cursorName),F.cursorFn?$_("",F.cursorRows):oU])}function kH(F){return Buffer.concat([Q_(F.statement.string,F.parameters,F.statement.types),nU,b6(F)])}function gH(F){let L=[],l=[],W0=NX(F,F.strings[0],F.args[0],L,l,Y);!F.tagged&&F.args.forEach((q0)=>lY(q0,L,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 Q1[F.signature],F.parameters=F.parameters||L,F.prepared=F.prepare&&F.signature in Q1,F.describeFirst=F.onlyDescribe||L.length&&!F.prepared,F.statement=F.prepared?Q1[F.signature]:{string:W0,types:l,name:F.prepare?r1+T++:""},typeof Y.debug==="function"&&Y.debug(N,W0,L,l)}function i0(F,L){if(R0=R0?Buffer.concat([R0,F]):Buffer.from(F),L||R0.length>=1024)return Z_(L);return w0===null&&(w0=setImmediate(Z_)),!0}function Z_(F){let L=C.write(R0,F);return w0!==null&&clearImmediate(w0),R0=w0=null,L}function yH(){u1(f0.connection("CONNECT_TIMEOUT",Y,C)),C.destroy()}async function X_(){if(i0(iU),!await new Promise((L)=>C.once("data",(l)=>L(l[0]===83)))&&W==="prefer")return i4();C.removeAllListeners(),C=cU.connect({socket:C,servername:UH.isIP(C.host)?void 0:C.host,...W==="require"||W==="allow"||W==="prefer"?{rejectUnauthorized:!1}:W==="verify-full"?{}:typeof W==="object"?W:{}}),C.on("secureConnect",i4),C.on("error",o4),C.on("close",H_),C.on("drain",__)}function __(){!v&&X(r0)}function HZ(F){if(L0){if(L0.push(F),G0-=F.length,G0>0)return}e=L0?Buffer.concat(L0,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,L0=[e];break}try{pH(e.subarray(0,a+1))}catch(L){v&&(v.cursorFn||v.describeFirst)&&i0(T4),u1(L)}e=e.subarray(a+1),G0=0,L0=null}}async function G_(){if(n0=!1,b0={},C||(C=await hH()),!C)return;if(s.start(),Y.socket)return W?X_():i4();if(C.on("connect",W?X_:i4),Y.path)return C.connect(Y.path);C.ssl=W,C.connect(Q[C0],$[C0]),C.host=$[C0],C.port=Q[C0],C0=(C0+1)%Q.length}function W_(){setTimeout(G_,u?u+$0-OH.now():0)}function i4(){try{Q1={},U0=Y.fetch_types,r1=Math.random().toString(36).slice(2),T=1,p.start(),C.on("data",HZ),b&&C.setKeepAlive&&C.setKeepAlive(!0,1000*b);let F=CJ();i0(F)}catch(F){o4(F)}}function o4(F){if(r0.queue===Z.connecting&&Y.host[k0+1])return;u1(F);while(I.length)k6(I.shift(),F)}function u1(F){g0&&(g0.destroy(F),g0=null),v&&k6(v,F),l0&&(k6(l0,F),l0=null)}function k6(F,L){if(F.reserve)return F.reject(L);if(!L||typeof L!=="object")L=new Error(L);"query"in L||"parameters"in L||Object.defineProperties(L,{stack:{value:L.stack+F.origin.replace(/.*\n/,`
|
|
63
|
+
`),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(L)}function JZ(){return z4||(!r0.reserved&&_(r0),!r0.reserved&&!l0&&!v&&I.length===0?(j8(),new Promise((F)=>C&&C.readyState!=="closed"?C.once("close",F):F())):z4=new Promise((F)=>v1=F))}function j8(){if(n0=!0,g0||v||l0||I.length)o4(f0.connection("CONNECTION_DESTROYED",Y));if(clearImmediate(w0),C)C.removeListener("data",HZ),C.removeListener("connect",i4),C.readyState==="open"&&C.end(c().X().end());v1&&(v1(),z4=v1=null)}async function H_(F){if(e=Buffer.alloc(0),G0=0,L0=null,clearImmediate(w0),C.removeListener("data",HZ),C.removeListener("connect",i4),K.cancel(),p.cancel(),s.cancel(),C.removeAllListeners(),C=null,l0)return W_();!F&&(v||I.length)&&o4(f0.connection("CONNECTION_CLOSED",Y,C)),u=OH.now(),F&&Y.shared.retries++,$0=(typeof f==="function"?f(Y.shared.retries):f)*1000,G(r0,f0.connection("CONNECTION_CLOSED",Y,C))}function pH(F,L=F[0]){(L===68?mH:L===100?EJ:L===65?QJ:L===83?uH:L===90?dH:L===67?cH:L===50?J_:L===49?lH:L===116?iH:L===84?oH:L===82?nH:L===110?YJ:L===75?ZJ:L===69?HJ:L===115?$J:L===51?zJ:L===71?FJ:L===78?LJ:L===72?UJ:L===99?DJ:L===73?VJ:L===86?MJ:L===118?AJ:L===87?OJ:wJ)(F)}function mH(F){let L=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(L),L+=4,q0=l===-1?null:v.isRaw===!0?F.subarray(L,L+=l):W0.parser===void 0?F.toString("utf8",L,L+=l):W0.parser.array===!0?W0.parser(F.toString("utf8",L+1,L+=l)):W0.parser(F.toString("utf8",L,L+=l)),v.isRaw?s0[Z1]=v.isRaw===!0?q0:D.value.from?D.value.from(q0,W0):q0:s0[W0.name]=D.value.from?D.value.from(q0,W0):q0;v.forEachFn?v.forEachFn(D.row.from?D.row.from(s0):s0,m):m[S0++]=D.row.from?D.row.from(s0):s0}function uH(F){let[L,l]=F.toString("utf8",5,F.length-1).split(c.N);if(b0[L]=l,Y.parameters[L]!==l)Y.parameters[L]=l,A&&A(L,l)}function dH(F){if(v&&v.options.simple&&v.resolve(S1||m),v=S1=null,m=new d4,s.cancel(),l0){if(h){if(!b0.in_hot_standby||!b0.default_transaction_read_only)return WJ();else if(GJ(h,b0))return j8()}if(U0)return l0.reserve&&(l0=null),XJ();l0&&!l0.reserve&&q8(l0),Y.shared.retries=k0=0,l0=null;return}while(I.length&&(v=I.shift())&&(v.active=!0,v.cancelled))LH(Y).cancel(v.state,v.cancelled.resolve,v.cancelled.reject);if(v)return;r0.reserved?!r0.reserved.release&&F[5]===73?z4?j8():(r0.reserved=null,X(r0)):r0.reserved():z4?j8():X(r0)}function cH(F){S0=0;for(let L=F.length-1;L>0;L--){if(F[L]===32&&F[L+1]<58&&m.count===null)m.count=+F.toString("utf8",L+1,F.length-1);if(F[L-1]>=65){m.command=F.toString("utf8",5,L),m.state=q;break}}if(K8&&(K8(),K8=null),m.command==="BEGIN"&&H!==1&&!r0.reserved)return u1(f0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(v.options.simple)return J_();if(v.cursorFn)m.count&&v.cursorFn(m),i0(T4);v.resolve(m)}function lH(){v.parsing=!1}function J_(){!m.statement&&(m.statement=v.statement),m.columns=v.statement.columns}function iH(F){let L=F.readUInt16BE(5);for(let l=0;l<L;++l)!v.statement.types[l]&&(v.statement.types[l]=F.readUInt32BE(7+l*4));v.prepare&&(Q1[v.signature]=v.statement),v.describeFirst&&!v.onlyDescribe&&(i0(b6(v)),v.describeFirst=!1)}function oH(F){if(m.command)S1=S1||[m],S1.push(m=new d4),m.count=null,v.statement.columns=null;let L=F.readUInt16BE(5),l=7,W0;v.statement.columns=Array(L);for(let q0=0;q0<L;++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:D.column.from?D.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(T4)}async function nH(F,L=F.readUInt32BE(5)){(L===3?rH:L===5?sH:L===10?aH:L===11?tH:L===12?eH:L!==0?RJ:I8)(F,L)}async function rH(){let F=await QZ();i0(c().p().str(F).z(1).end())}async function sH(F){let L="md5"+await DH(Buffer.concat([Buffer.from(await DH(await QZ()+J)),F.subarray(9)]));i0(c().p().str(L).z(1).end())}async function aH(){m1=(await j6.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 tH(F){let L=F.toString("utf8",9).split(",").reduce((Z1,F4)=>(Z1[F4[0]]=F4.slice(2),Z1),{}),l=await j6.pbkdf2Sync(await QZ(),Buffer.from(L.s,"base64"),parseInt(L.i),32,"sha256"),W0=await nY(l,"Client Key"),q0="n=*,r="+m1+",r="+L.r+",s="+L.s+",i="+L.i+",c=biws,r="+L.r;T0=(await nY(await nY(l,"Server Key"),q0)).toString("base64");let s0="c=biws,r="+L.r+",p="+tU(W0,Buffer.from(await nY(await aU(W0),q0))).toString("base64");i0(c().p().str(s0).end())}function eH(F){if(F.toString("utf8",9).split(c.N,1)[0].slice(2)===T0)return;u1(f0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),C.destroy()}function QZ(){return Promise.resolve(typeof Y.pass==="function"?Y.pass():Y.pass)}function YJ(){if(m.statement=v.statement,m.statement.columns=[],v.onlyDescribe)return v.resolve(v.statement),i0(T4)}function ZJ(F){q.pid=F.readUInt32BE(5),q.secret=F.readUInt32BE(9)}async function XJ(){U0=!1,(await new P1([`
|
|
64
64
|
select b.oid, b.typarray
|
|
65
65
|
from pg_catalog.pg_type a
|
|
66
66
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
67
67
|
where a.typcategory = 'A'
|
|
68
68
|
group by b.oid, b.typarray
|
|
69
69
|
order by b.oid
|
|
70
|
-
`],[],q8)).forEach(({oid:
|
|
70
|
+
`],[],q8)).forEach(({oid:L,typarray:l})=>_J(L,l))}function _J(F,L){if(!!Y.parsers[L]&&!!Y.serializers[L])return;let l=Y.parsers[F];Y.shared.typeArrayMap[F]=L,Y.parsers[L]=(W0)=>zH(W0,l,L),Y.parsers[L].array=!0,Y.serializers[L]=(W0)=>$H(W0,Y.serializers[F],Y,L)}function GJ(F,L){return F==="read-write"&&L.default_transaction_read_only==="on"||F==="read-only"&&L.default_transaction_read_only==="off"||F==="primary"&&L.in_hot_standby==="on"||F==="standby"&&L.in_hot_standby==="off"||F==="prefer-standby"&&L.in_hot_standby==="off"&&Y.host[k0]}function WJ(){let F=new P1([`
|
|
71
71
|
show transaction_read_only;
|
|
72
72
|
select pg_catalog.pg_is_in_recovery()
|
|
73
|
-
`],[],q8,null,{simple:!0});F.resolve=([[
|
|
73
|
+
`],[],q8,null,{simple:!0});F.resolve=([[L],[l]])=>{b0.default_transaction_read_only=L.transaction_read_only,b0.in_hot_standby=l.pg_is_in_recovery?"on":"off"},F.execute()}function HJ(F){v&&(v.cursorFn||v.describeFirst)&&i0(T4);let L=f0.postgres(PX(F));v&&v.retried?u1(v.retried):v&&v.prepared&&rU.has(L.routine)?JJ(v,L):u1(L)}function JJ(F,L){delete Q1[F.signature],F.retried=L,q8(F)}function QJ(F){if(!R)return;let L=9;while(F[L++]!==0);R(F.toString("utf8",9,L-1),F.toString("utf8",L,F.length-1))}async function $J(){try{let F=await Promise.resolve(v.cursorFn(m));S0=0,F===R8?i0(BJ(v.portal)):(m=new d4,i0($_("",v.cursorRows)))}catch(F){i0(T4),v.reject(F)}}function zJ(){m.count&&v.cursorFn(m),v.resolve(m)}function FJ(){g0=new jX.Writable({autoDestroy:!0,write(F,L,l){C.write(c().d().raw(F).end(),l)},destroy(F,L){L(F),C.write(c().f().str(F+c.N).end()),g0=null},final(F){C.write(c().c().end()),K8=F}}),v.resolve(g0)}function UJ(){g0=new jX.Readable({read(){C.resume()}}),v.resolve(g0)}function OJ(){g0=new jX.Duplex({autoDestroy:!0,read(){C.resume()},write(F,L,l){C.write(c().d().raw(F).end(),l)},destroy(F,L){L(F),C.write(c().f().str(F+c.N).end()),g0=null},final(F){C.write(c().c().end()),K8=F}}),v.resolve(g0)}function EJ(F){g0&&(g0.push(F.subarray(5))||C.pause())}function DJ(){g0&&g0.push(null),g0=null}function LJ(F){V?V(PX(F)):console.log(PX(F))}function VJ(){}function MJ(){u1(f0.notSupported("FunctionCallResponse"))}function AJ(){u1(f0.notSupported("NegotiateProtocolVersion"))}function wJ(F){console.error("Postgres.js : Unknown Message:",F[0])}function RJ(F,L){console.error("Postgres.js : Unknown Auth:",L)}function NJ(F,L,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=L[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 Q_(F,L,l,W0=""){return c().P().str(W0+c.N).str(F+c.N).i16(L.length),L.forEach((q0,s0)=>c.i32(l[s0]||0)),c.end()}function IJ(F,L=""){return c().D().str(F).str(L+c.N).end()}function $_(F="",L=0){return Buffer.concat([c().E().str(F+c.N).i32(L).end(),EH])}function BJ(F=""){return Buffer.concat([c().C().str("P").str(F+c.N).end(),c().S().end()])}function CJ(){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,L])=>F+c.N+L).join(c.N)).z(2).end(0)}}function PX(Y){let Z={},X=5;for(let _=5;_<Y.length-1;_++)if(Y[_]===0)Z[sU[Y[X]]]=Y.toString("utf8",X+1,_),X=_+1;return Z}function DH(Y){return j6.createHash("md5").update(Y).digest("hex")}function nY(Y,Z){return j6.createHmac("sha256",Y).update(Z).digest()}function aU(Y){return j6.createHash("sha256").update(Y).digest()}function tU(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 SX(Y,Z){if(Z=typeof Z==="function"?Z():Z,!Z)return{cancel:I8,start:I8};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 VH=()=>{};function xX(Y,Z){let X=new Map,_="postgresjs_"+Math.random().toString(36).slice(2),G={},W,H,J=!1,$=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,D(await V($,_,Z.publications)),X.forEach((A)=>A.forEach(({onsubscribe:g})=>g()))},no_subscribe:!0}),Q=$.end,z=$.close;return $.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,g,b=VH,f=VH){if(A=ZO(A),!W)W=V($,_,Z.publications);let h={fn:g,onsubscribe:b},I=X.has(A)?X.get(A).add(h):X.set(A,new Set([h])).get(A),N=()=>{I.delete(h),I.size===0&&X.delete(A)};return W.then((q)=>{return D(q),b(),H&&H.on("error",f),{unsubscribe:N,state:G,sql:$}})}function D(A){H=A.stream,G.pid=A.state.pid,G.secret=A.state.secret}async function V(A,g,b){if(!b)throw new Error("Missing publication names");let f=await A.unsafe(`CREATE_REPLICATION_SLOT ${g} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[h]=f,I=await A.unsafe(`START_REPLICATION SLOT ${g} LOGICAL ${h.consistent_point} (proto_version '1', publication_names '${b}')`).writable(),N={lsn:Buffer.concat(h.consistent_point.split("/").map((C)=>Buffer.from(("00000000"+C).slice(-8),"hex")))};return I.on("data",K),I.on("error",q),I.on("close",A.close),{stream:I,state:f.state};function q(C){console.error("Unexpected error during logical streaming - reconnecting",C)}function K(C){if(C[0]===119)YO(C.subarray(25),N,A.options.parsers,p,Z.transform);else if(C[0]===107&&C[17])N.lsn=C.subarray(1,9),s()}function p(C,t){let m=t.relation.schema+"."+t.relation.table;R("*",C,t),R("*:"+m,C,t),t.relation.keys.length&&R("*:"+m+"="+t.relation.keys.map((e)=>C[e.name]),C,t),R(t.command,C,t),R(t.command+":"+m,C,t),t.relation.keys.length&&R(t.command+":"+m+"="+t.relation.keys.map((e)=>C[e.name]),C,t)}function s(){let C=Buffer.alloc(34);C[0]=114,C.fill(N.lsn,1),C.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),I.write(C)}}function R(A,g,b){X.has(A)&&X.get(A).forEach(({fn:f})=>f(g,b,A))}}function eU(Y){return new Date(Date.UTC(2000,0,1)+Number(Y/BigInt(1000)))}function YO(Y,Z,X,_,G){let W=(H,[J,$])=>(H[J.charCodeAt(0)]=$,H);Object.entries({R:(H)=>{let J=1,$=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 Q=0,z;while(J<H.length)z=$.columns[Q++]={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&&$.keys.push(z),J+=4},Y:()=>{},O:()=>{},B:(H)=>{Z.date=eU(H.readBigInt64BE(9)),Z.lsn=H.subarray(1,9)},I:(H)=>{let J=1,$=Z[H.readUInt32BE(J)],{row:Q}=rY(H,$.columns,J+=7,G);_(Q,{command:"insert",relation:$})},D:(H)=>{let J=1,$=Z[H.readUInt32BE(J)];J+=4;let Q=H[J]===75;_(Q||H[J]===79?rY(H,$.columns,J+=3,G).row:null,{command:"delete",relation:$,key:Q})},U:(H)=>{let J=1,$=Z[H.readUInt32BE(J)];J+=4;let Q=H[J]===75,z=Q||H[J]===79?rY(H,$.columns,J+=3,G):null;z&&(J=z.i);let{row:O}=rY(H,$.columns,J+3,G);_(O,{command:"update",relation:$,key:Q,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce(W,{})[Y[0]](Y)}function rY(Y,Z,X,_){let G,W,H,J=_.raw?new Array(Z.length):{};for(let $=0;$<Z.length;$++)G=Y[X++],W=Z[$],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[$]=_.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 ZO(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 MH from"stream";function hX(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`,$={writable:z,readable:Q,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,D=0)=>W`select lo_lseek64(${J}, ${O}, ${D})`,size:()=>W`
|
|
74
74
|
select
|
|
75
75
|
lo_lseek64(${J}, location, 0) as position,
|
|
76
76
|
seek.size
|
|
@@ -80,10 +80,10 @@ params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrac
|
|
|
80
80
|
tell.location
|
|
81
81
|
from (select lo_tell64($1) as location) tell
|
|
82
82
|
) seek
|
|
83
|
-
`};return _(Q),new Promise(async(O)=>H=O);async function $({highWaterMark:O=16384,start:L=0,end:V=1/0}={}){let N=V-L;return L&&await Q.seek(L),new VH.Readable({highWaterMark:O,async read(A){let f=A>N?A-N:A;N-=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 VH.Writable({highWaterMark:O,write(V,N,A){Q.write(V).then(()=>A(),A)}})}}).catch(G)})}Object.assign(rY,{PostgresError:R8,toPascal:m4,pascal:qX,toCamel:p4,camel:CX,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=rY;function rY(Y,Z){let X=_O(Y,Z),_=X.no_subscribe||xX(rY,{...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},N=[...Array(X.max)].map(()=>vX(X,V,{onopen:$1,onend:b0,onclose:s1})),A=f(p);return Object.assign(A,{get parameters(){return X.parameters},largeObject:hX.bind(null,A),subscribe:_,CLOSE:w8,END:w8,PostgresError:R8,options:X,reserve:g,listen:b,begin:R,close:m,end:t}),A;function f(C){return C.debug=X.debug,Object.entries(X.types).reduce((a,[Q0,S0])=>{return a[Q0]=(C0)=>new r1(C0,S0.to),a},u),Object.assign(G0,{types:u,typed:u,unsafe:T0,notify:k,array:q,json:K,file:k0}),G0;function u(a,Q0){return new r1(a,Q0)}function G0(a,...Q0){return a&&Array.isArray(a.raw)?new P1(a,Q0,C,T):typeof a==="string"&&!Q0.length?new q6(X.transform.column.to?X.transform.column.to(a):a):new dY(a,Q0)}function T0(a,Q0=[],S0={}){return arguments.length===2&&!Array.isArray(Q0)&&(S0=Q0,Q0=[]),new P1([a],Q0,C,T,{prepare:!1,...S0,simple:"simple"in S0?S0.simple:Q0.length===0})}function k0(a,Q0=[],S0={}){return arguments.length===2&&!Array.isArray(Q0)&&(S0=Q0,Q0=[]),new P1([],Q0,(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:Q0.length===0})}}async function b(C,u,G0){let T0={fn:u,onlisten:G0},k0=b.sql||(b.sql=rY({...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:k0`listen ${k0.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],k0`unlisten ${k0.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((k0,a)=>{let Q0={reserve:k0,reject:a};W.push(Q0),Q.length&&U0(Q.shift(),Q0)});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,$1(u)},G0;function T0(k0){u.queue===L?C.push(k0):u.execute(k0)||I(u,L)}}async function R(C,u){!u&&(u=C,C="");let G0=I1(),T0=0,k0,a=null;try{return await A.unsafe("begin "+C.replace(/[^a-z ]/ig,""),[],{onexecute:S0}).execute(),await Promise.race([Q0(k0,u),new Promise((C0,w0)=>k0.onclose=w0)])}catch(C0){throw C0}async function Q0(C0,w0,n0){let D0=f(g0);D0.savepoint=z4,D0.prepare=(R0)=>a=R0.replace(/[^a-z0-9$-_. ]/gi);let S1,l0;n0&&await D0`savepoint ${D0(n0)}`;try{if(l0=await new Promise((R0,v1)=>{let m1=w0(D0);Promise.resolve(Array.isArray(m1)?Promise.all(m1):m1).then(R0,v1)}),S1)throw S1}catch(R0){throw await(n0?D0`rollback to ${D0(n0)}`:D0`rollback`),R0 instanceof R8&&R0.code==="25P02"&&S1||R0}if(!n0)a?await D0`prepare transaction '${D0.unsafe(a)}'`:await D0`commit`;return l0;function z4(R0,v1){if(R0&&Array.isArray(R0.raw))return z4((m1)=>m1.apply(m1,arguments));return arguments.length===1&&(v1=R0,R0=null),Q0(C0,v1,"s"+T0+++(R0?"_"+R0:""))}function g0(R0){R0.catch((v1)=>S1||(S1=v1)),C0.queue===L?G0.push(R0):C0.execute(R0)||I(C0,L)}}function S0(C0){k0=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 K(C){return new r1(C,3802)}function q(C,u){if(!Array.isArray(C))return q(Array.from(arguments));return new r1(C,u||(C.length?mY(C)||25:0),X.shared.typeArrayMap)}function p(C){if(G)return C.reject(f0.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?vX(X).cancel(C.state,u,G0):C.cancelled={resolve:u,reject:G0}:(W.remove(C),C.cancelled=!0,C.reject(f0.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(N.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(N.map((C)=>C.end()))}async function e(C){await Promise.all(N.map((u)=>u.terminate()));while(W.length)W.shift().reject(f0.connection("CONNECTION_DESTROYED",X));C()}function U0(C,u){return I(C,H),C.connect(u),C}function b0(C){I(C,$)}function $1(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,N])=>(L[V]=N,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,N])=>{let A=V in _?_[V]:(V in H)?H[V]==="disable"||H[V]==="false"?!1:H[V]:X["PG"+V.toUpperCase()]||N;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,N])=>((V in O)||(L[V]=N),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:{}},...HH(_.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 MH{constructor(Y,Z){this.unique=Y,this.name=Z}static[U]="PgIndexBuilderOn";on(...Y){return new sY(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 sY(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 sY(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 sY{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 AH(this.config,Y)}}class AH{static[U]="PgIndex";config;constructor(Y,Z){this.config={...Y,table:Z}}}function fX(Y){return new MH(!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 bX{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 bX(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`
|
|
83
|
+
`};return _($),new Promise(async(O)=>H=O);async function Q({highWaterMark:O=16384,start:D=0,end:V=1/0}={}){let R=V-D;return D&&await $.seek(D),new MH.Readable({highWaterMark:O,async read(A){let g=A>R?A-R:A;R-=A;let[{data:b}]=await $.read(g);if(this.push(b),b.length<A)this.push(null)}})}async function z({highWaterMark:O=16384,start:D=0}={}){return D&&await $.seek(D),new MH.Writable({highWaterMark:O,write(V,R,A){$.write(V).then(()=>A(),A)}})}}).catch(G)})}Object.assign(sY,{PostgresError:N8,toPascal:m4,pascal:KX,toCamel:p4,camel:TX,toKebab:u4,kebab:qX,fromPascal:T6,fromCamel:C6,fromKebab:K6,BigInt:{to:20,from:[20],parse:(Y)=>BigInt(Y),serialize:(Y)=>Y.toString()}});var B8=sY;function sY(Y,Z){let X=GO(Y,Z),_=X.no_subscribe||xX(sY,{...X}),G=!1,W=I1(),H=I1(),J=I1(),$=I1(),Q=I1(),z=I1(),O=I1(),D=I1(),V={connecting:H,reserved:J,closed:$,ended:Q,open:z,busy:O,full:D},R=[...Array(X.max)].map(()=>vX(X,V,{onopen:Q1,onend:b0,onclose:r1})),A=g(p);return Object.assign(A,{get parameters(){return X.parameters},largeObject:hX.bind(null,A),subscribe:_,CLOSE:R8,END:R8,PostgresError:N8,options:X,reserve:h,listen:b,begin:I,close:m,end:t}),A;function g(T){return T.debug=X.debug,Object.entries(X.types).reduce((a,[$0,S0])=>{return a[$0]=(T0)=>new n1(T0,S0.to),a},u),Object.assign(G0,{types:u,typed:u,unsafe:C0,notify:f,array:K,json:q,file:k0}),G0;function u(a,$0){return new n1(a,$0)}function G0(a,...$0){return a&&Array.isArray(a.raw)?new P1(a,$0,T,C):typeof a==="string"&&!$0.length?new q6(X.transform.column.to?X.transform.column.to(a):a):new cY(a,$0)}function C0(a,$0=[],S0={}){return arguments.length===2&&!Array.isArray($0)&&(S0=$0,$0=[]),new P1([a],$0,T,C,{prepare:!1,...S0,simple:"simple"in S0?S0.simple:$0.length===0})}function k0(a,$0=[],S0={}){return arguments.length===2&&!Array.isArray($0)&&(S0=$0,$0=[]),new P1([],$0,(w0)=>{_O.readFile(a,"utf8",(n0,L0)=>{if(n0)return w0.reject(n0);w0.strings=[L0],T(w0)})},C,{...S0,simple:"simple"in S0?S0.simple:$0.length===0})}}async function b(T,u,G0){let C0={fn:u,onlisten:G0},k0=b.sql||(b.sql=sY({...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((L0)=>b(w0,L0.fn,L0.onlisten).catch(()=>{})))})},onnotify(w0,n0){w0 in b.channels&&b.channels[w0].listeners.forEach((L0)=>L0.fn(n0))}})),a=b.channels||(b.channels={});if(T in a){a[T].listeners.push(C0);let w0=await a[T].result;return C0.onlisten&&C0.onlisten(),{state:w0.state,unlisten:T0}}a[T]={result:k0`listen ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`,listeners:[C0]};let S0=await a[T].result;return C0.onlisten&&C0.onlisten(),{state:S0.state,unlisten:T0};async function T0(){if(T in a===!1)return;if(a[T].listeners=a[T].listeners.filter((w0)=>w0!==C0),a[T].listeners.length)return;return delete a[T],k0`unlisten ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`}}async function f(T,u){return await A`select pg_notify(${T}, ${""+u})`}async function h(){let T=I1(),u=z.length?z.shift():await new Promise((k0,a)=>{let $0={reserve:k0,reject:a};W.push($0),$.length&&U0($.shift(),$0)});N(u,J),u.reserved=()=>T.length?u.execute(T.shift()):N(u,J),u.reserved.release=!0;let G0=g(C0);return G0.release=()=>{u.reserved=null,Q1(u)},G0;function C0(k0){u.queue===D?T.push(k0):u.execute(k0)||N(u,D)}}async function I(T,u){!u&&(u=T,T="");let G0=I1(),C0=0,k0,a=null;try{return await A.unsafe("begin "+T.replace(/[^a-z ]/ig,""),[],{onexecute:S0}).execute(),await Promise.race([$0(k0,u),new Promise((T0,w0)=>k0.onclose=w0)])}catch(T0){throw T0}async function $0(T0,w0,n0){let L0=g(g0);L0.savepoint=z4,L0.prepare=(R0)=>a=R0.replace(/[^a-z0-9$-_. ]/gi);let S1,l0;n0&&await L0`savepoint ${L0(n0)}`;try{if(l0=await new Promise((R0,v1)=>{let m1=w0(L0);Promise.resolve(Array.isArray(m1)?Promise.all(m1):m1).then(R0,v1)}),S1)throw S1}catch(R0){throw await(n0?L0`rollback to ${L0(n0)}`:L0`rollback`),R0 instanceof N8&&R0.code==="25P02"&&S1||R0}if(!n0)a?await L0`prepare transaction '${L0.unsafe(a)}'`:await L0`commit`;return l0;function z4(R0,v1){if(R0&&Array.isArray(R0.raw))return z4((m1)=>m1.apply(m1,arguments));return arguments.length===1&&(v1=R0,R0=null),$0(T0,v1,"s"+C0+++(R0?"_"+R0:""))}function g0(R0){R0.catch((v1)=>S1||(S1=v1)),T0.queue===D?G0.push(R0):T0.execute(R0)||N(T0,D)}}function S0(T0){k0=T0,N(T0,J),T0.reserved=()=>G0.length?T0.execute(G0.shift()):N(T0,J)}}function N(T,u){return T.queue.remove(T),u.push(T),T.queue=u,u===z?T.idleTimer.start():T.idleTimer.cancel(),T}function q(T){return new n1(T,3802)}function K(T,u){if(!Array.isArray(T))return K(Array.from(arguments));return new n1(T,u||(T.length?uY(T)||25:0),X.shared.typeArrayMap)}function p(T){if(G)return T.reject(f0.connection("CONNECTION_ENDED",X,X));if(z.length)return s(z.shift(),T);if($.length)return U0($.shift(),T);O.length?s(O.shift(),T):W.push(T)}function s(T,u){return T.execute(u)?N(T,O):N(T,D)}function C(T){return new Promise((u,G0)=>{T.state?T.active?vX(X).cancel(T.state,u,G0):T.cancelled={resolve:u,reject:G0}:(W.remove(T),T.cancelled=!0,T.reject(f0.generic("57014","canceling statement due to user request")),u())})}async function t({timeout:T=null}={}){if(G)return G;await 1;let u;return G=Promise.race([new Promise((G0)=>T!==null&&(u=setTimeout(e,T*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((T)=>T.end()))}async function e(T){await Promise.all(R.map((u)=>u.terminate()));while(W.length)W.shift().reject(f0.connection("CONNECTION_DESTROYED",X));T()}function U0(T,u){return N(T,H),T.connect(u),T}function b0(T){N(T,Q)}function Q1(T){if(W.length===0)return N(T,z);let u=Math.ceil(W.length/(H.length+1)),G0=!0;while(G0&&W.length&&u-- >0){let C0=W.shift();if(C0.reserve)return C0.reserve(T);G0=T.execute(C0)}G0?N(T,O):N(T,D)}function r1(T,u){N(T,$),T.reserved=null,T.onclose&&(T.onclose(u),T.onclose=null),X.onclose&&X.onclose(T.id),W.length&&U0(T,W.shift())}}function GO(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((D,[V,R])=>(D[V]=R,D),{}),J=_.hostname||_.host||W||G.hostname||X.PGHOST||"localhost",$=_.port||G.port||X.PGPORT||5432,Q=_.user||_.username||G.username||X.PGUSERNAME||X.PGUSER||zO();_.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:JO,max_pipeline:100,backoff:HO,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((D)=>D.split(":")[0]),port:Array.isArray($)?$:J.split(",").map((D)=>parseInt(D.split(":")[1]||$)),path:_.path||J.indexOf("/")>-1&&J+"/.s.PGSQL."+$,database:_.database||_.db||(G.pathname||"").slice(1)||X.PGDATABASE||Q,user:Q,pass:_.pass||_.password||G.password||X.PGPASSWORD||"",...Object.entries(O).reduce((D,[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 D[V]=typeof A==="string"&&z.includes(V)?+A:A,D},{}),connection:{application_name:X.PGAPPNAME||"postgres.js",..._.connection,...Object.entries(H).reduce((D,[V,R])=>((V in O)||(D[V]=R),D),{})},types:_.types||{},target_session_attrs:WO(_,G,X),onnotice:_.onnotice,onnotify:_.onnotify,onclose:_.onclose,onparameter:_.onparameter,socket:_.socket,transform:QO(_.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...JH(_.types)}}function WO(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 HO(Y){return(0.5+Math.random()/2)*Math.min(3**Y/100,20)}function JO(){return 60*(30+Math.random()*30)}function QO(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 zO(){try{return XO.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,L1)?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 w8(new Proxy(_.table,new V6(this.config.alias,this.config.replaceOriginalName??!1))));return _}if(typeof _!=="object"||_===null)return _;return new Proxy(_,new j0(this.config))}}class AH{constructor(Y,Z){this.unique=Y,this.name=Z}static[U]="PgIndexBuilderOn";on(...Y){return new aY(Y.map((Z)=>{if(M(Z,x))return Z;Z=Z;let X=new O6(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 aY(Y.map((Z)=>{if(M(Z,x))return Z;Z=Z;let X=new O6(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=Z.defaultConfig,X}),this.unique,!0,this.name)}using(Y,...Z){return new aY(Z.map((X)=>{if(M(X,x))return X;X=X;let _=new O6(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),_}),this.unique,!0,this.name,Y)}}class aY{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 wH(this.config,Y)}}class wH{static[U]="PgIndex";config;constructor(Y,Z){this.config={...Y,table:Z}}}function fX(Y){return new AH(!0,Y)}function FO(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function UO(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 OO(Y){return Y}class bX{static[U]="CasingCache";cache={};cachedTables={};convert;constructor(Y){this.convert=Y==="snake_case"?FO:Y==="camelCase"?UO:OO}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 P6 extends L1{static[U]="PgViewBase"}class c4{static[U]="PgDialect";casing;constructor(Y){this.casing=new bX(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`
|
|
84
84
|
CREATE TABLE IF NOT EXISTS ${E.identifier(G)}.${E.identifier(_)} (
|
|
85
85
|
id SERIAL PRIMARY KEY,
|
|
86
86
|
hash text NOT NULL,
|
|
87
87
|
created_at bigint
|
|
88
88
|
)
|
|
89
|
-
`;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),N=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}${N}${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 N=X??K1(Z);for(let e of N)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:b0})=>b0===(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(N,{isSingleTable:A}),g=this.buildFromTable(W),R=this.buildJoins(H),I=_?E` where ${_}`:void 0,K=G?E` having ${G}`:void 0,q;if(J&&J.length>0)q=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}${R}${I}${p}${K}${q}${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 N of W)if(M(N,j))V.push(E.identifier(N.name));else if(M(N,x)){for(let A=0;A<N.queryChunks.length;A++){let f=N.queryChunks[A];if(M(f,j))N.queryChunks[A]=E.identifier(f.name)}V.push(E`${N}`)}else V.push(E`${N}`);$=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[R,I]of $){let K=k[R];if(K===void 0||M(K,N1)&&K.value===void 0)if(I.defaultFn!==void 0){let q=I.defaultFn(),p=M(q,x)?q:E.param(q,I);g.push(p)}else if(!I.default&&I.onUpdateFn!==void 0){let q=I.onUpdateFn(),p=M(q,x)?q:E.param(q,I);g.push(p)}else g.push(E`default`);else g.push(K)}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,N=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}${N}${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,SY)||M(Y,PY))return"json";else if(M(Y,vY))return"decimal";else if(M(Y,xY))return"time";else if(M(Y,hY)||M(Y,fY))return"timestamp";else if(M(Y,KY)||M(Y,jY))return"date";else if(M(Y,bY))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,N=[];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(([K,q])=>[K,n1(q,H)]));if(W.where){let K=typeof W.where==="function"?W.where(f,oW()):W.where;V=K&&V6(K,H)}let b=[],k=[];if(W.columns){let K=!1;for(let[q,p]of Object.entries(W.columns)){if(p===void 0)continue;if(q in G.columns){if(!K&&p===!0)K=!0;k.push(q)}}if(k.length>0)k=K?k.filter((q)=>W.columns?.[q]===!0):Object.keys(G.columns).filter((q)=>!k.includes(q))}else k=Object.keys(G.columns);for(let K of k){let q=G.columns[K];b.push({tsKey:K,value:q})}let g=[];if(W.with)g=Object.entries(W.with).filter((K)=>!!K[1]).map(([K,q])=>({tsKey:K,queryConfig:q,relation:G.relations[K]}));let R;if(W.extras){R=typeof W.extras==="function"?W.extras(f,{sql:E}):W.extras;for(let[K,q]of Object.entries(R))b.push({tsKey:K,value:zX(q,H)})}for(let{tsKey:K,value:q}of b)$.push({dbKey:M(q,x.Aliased)?q.fieldAlias:G.columns[K].name,tsKey:K,field:M(q,E0)?n1(q,H):q,relationTableTsKey:void 0,isJson:!1,selection:[]});let I=typeof W.orderBy==="function"?W.orderBy(f,nW()):W.orderBy??[];if(!Array.isArray(I))I=[I];L=I.map((K)=>{if(M(K,E0))return n1(K,H);return V6(K,H)}),z=W.limit,O=W.offset;for(let{tsKey:K,queryConfig:q,relation:p}of g){let s=sW(Z,X,p),T=y4(p.referencedTable),t=X[T],m=`${H}_${K}`,e=N6(...s.fields.map(($1,s1)=>kY(n1(s.references[s1],m),n1($1,H)))),U0=this.buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:Y[t],tableConfig:Z[t],queryConfig:M(p,T4)?q===!0?{limit:1}:{...q,limit:1}:q,tableAlias:m,joinOn:e,nestedQueryRelation:p}),b0=E`${E.identifier(m)}.${E.identifier("data")}`.as(K);N.push({on:E`true`,table:new P0(U0.sql,{},m),alias:m,joinType:"left",lateral:!0}),$.push({dbKey:K,tsKey:K,field:b0,relationTableTsKey:t,isJson:!0,selection:U0.selection})}}if($.length===0)throw new CY({message:`No fields selected for table "${G.tsName}" ("${H}")`});let A;if(V=N6(Q,V),J){let f=E`json_build_array(${E.join($.map(({field:g,tsKey:R,isJson:I})=>I?E`${E.identifier(`${H}_${R}`)}.${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:TY(_,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=TY(_,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:N,where:V,limit:z,offset:O,orderBy:L,setOperators:[]})}else A=this.buildSelectQuery({table:TY(_,H),fields:{},fieldsFlat:$.map(({field:f})=>({path:[],field:M(f,E0)?n1(f,H):f})),joins:N,where:V,limit:z,offset:O,orderBy:L,setOperators:[]});return{tableTsKey:G.tsName,sql:A,selection:$}}}class kX{static[U]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class J1{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 _=T3(X);return new gX({table:X,fields:_,isPartialSelect:Z,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class wH extends kX{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=$4(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=$4(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 gX extends wH{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 $=K1(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)})}}B3(gX,[H1]);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 J1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),withList:Y})}function _(W){return new J1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),distinct:!0})}function G(W,H){return new J1({fields:H??void 0,session:void 0,dialect:Z.getDialect(),distinct:{on:W}})}return{select:X,selectDistinct:_,selectDistinctOn:G}}select(Y){return new J1({fields:Y??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(Y){return new J1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(Y,Z){return new J1({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 aY extends H1{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=K1(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 tY{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 N1(H,G[W])}return _});return new yX(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[IY],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 yX(this.table,Z,this.session,this.dialect,this.withList,!0)}}class yX extends H1{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=K1(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,qY(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 pX extends H1{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 eY{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 RH(this.table,qY(this.table,Y),this.session,this.dialect,this.withList).setToken(this.authToken)}}class RH extends H1{constructor(Y,Z,X,_,G){super();this.session=X,this.dialect=_,this.config={set:Z,table:Y,withList:G,joins:[]},this.tableName=$4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[U]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(Y){let Z=Y,X=$4(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 _=$4(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=$4(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 _=$4(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=K1(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 uX{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 mX(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?Y:{},"many")}findFirst(Y){return new mX(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?{...Y,limit:1}:{limit:1},"first")}}class mX extends H1{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)=>gY(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 dX extends H1{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 uX(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 J1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y})}function _(Q){return new J1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:!0})}function G(Q,$){return new J1({fields:$??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:{on:Q}})}function W(Q){return new eY(Q,Z.session,Z.dialect,Y)}function H(Q){return new tY(Q,Z.session,Z.dialect,Y)}function J(Q){return new aY(Q,Z.session,Z.dialect,Y)}return{select:X,selectDistinct:_,selectDistinctOn:G,update:W,insert:H,delete:J}}select(Y){return new J1({fields:Y??void 0,session:this.session,dialect:this.dialect})}selectDistinct(Y){return new J1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(Y,Z){return new J1({fields:Z??void 0,session:this.session,dialect:this.dialect,distinct:{on:Y}})}update(Y){return new eY(Y,this.session,this.dialect)}insert(Y){return new tY(Y,this.session,this.dialect)}delete(Y){return new aY(Y,this.session,this.dialect)}refreshMaterializedView(Y){return new pX(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 dX(()=>_.execute(void 0,this.authToken),Z,X,(G)=>_.mapResult(G,!0))}transaction(Y,Z){return this.session.transaction(Y,Z)}}class NH{static[U]="Cache"}class x6 extends NH{strategy(){return"all"}static[U]="NoopCache";async get(Y){return}async put(Y,Z,X,_){}async onMutate(Y){}}async function cX(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 lX{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 J4(Y,Z,_)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await X()}catch(_){throw new J4(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 J4(Y,Z,_)}if(!this.cacheConfig)try{return await X()}catch(_){throw new J4(Y,Z,_)}if(this.queryMetadata.type==="select"){let _=await this.cache.get(this.cacheConfig.tag??await cX(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 J4(Y,Z,W)}return await this.cache.put(this.cacheConfig.tag??await cX(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 J4(Y,Z,_)}}}class iX{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 oX extends v6{constructor(Y,Z,X,_=0){super(Y,Z,X);this.schema=X,this.nestedIndex=_}static[U]="PgTransaction";rollback(){throw new FX}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 IH extends lX{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=QX(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(($)=>I3(_,$,H))})})}all(Y={}){return L0.startActiveSpan("drizzle.execute",async(Z)=>{let X=QX(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 iX{constructor(Y,Z,X,_={}){super(Z);this.client=Y,this.schema=X,this.options=_,this.logger=_.logger??new OX,this.cache=_.cache??new x6}static[U]="PostgresJsSession";logger;cache;prepareQuery(Y,Z,X,_,G,W,H){return new IH(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 nX(this.dialect,_,this.schema);if(Z)await G.setTransaction(Z);return Y(G)})}}class nX extends oX{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 nX(this.dialect,X,this.schema);return Y(_)})}}class BH 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 UX;else if(Z.logger!==!1)G=Z.logger;let W;if(Z.schema){let Q=rW(Z.schema,aW);W={fullSchema:Z.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let H=new h6(Y,_,W,{logger:G,cache:Z.cache}),J=new BH(_,H,W);if(J.$client=Y,J.$cache=Z.cache,J.$cache)J.$cache.invalidate=Z.cache?.onMutate;return J}function YZ(...Y){if(typeof Y[0]==="string"){let Z=I8(Y[0]);return T8(Z,Y[1])}if(C3(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})(YZ||(YZ={}));var sX={};jJ(sX,{users:()=>l4,untrackedUserColumnNames:()=>wO,twoFactorMethod:()=>jH,trackedUserColumnName:()=>RO,trackableUserColumnNames:()=>qH,signInHistory:()=>IO,role:()=>CH,players:()=>rX,passwordResetAttempts:()=>BO,games:()=>XZ,banishedIps:()=>TO,accountActions:()=>NO,accountAction:()=>KH});function q4(){return e0({length:24}).$type()}function TH(Y){return E`lower(${Y})`}var ZZ=E`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,CH=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:q4().notNull().default(ZZ),createdIp:e0({length:45}).notNull(),isActive:A6().notNull().default(!1),verifiedAtIso:q4(),userRole:CH().default("user")},(Y)=>[fX("usernameUniqueIndex").on(TH(Y.username)),fX("emailVerifiedUniqueIndex").on(TH(Y.emailVerified))]),wO=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],qH=["username","emailOffered","emailVerified","password","userRole"],RO=O6("trackedUserColumnName",qH),KH=O6("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),NO=B4("accountActions",{userId:j1().references(()=>l4.id).primaryKey(),action:KH().notNull(),code:e0({length:254}).notNull(),wrongCodeCount:w6().notNull().default(0),expiresAtIso:q4().notNull()}),XZ=B4("games",{id:j1().primaryKey().defaultRandom()}),rX=B4("players",{userId:j1().notNull().references(()=>l4.id,{onDelete:"cascade"}),gameId:j1().notNull().references(()=>XZ.id,{onDelete:"cascade"}),score:w6().notNull()},(Y)=>[IW({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:q4().notNull().default(ZZ),ipAddress:e0({length:45}).notNull(),userAgent:e0({length:1024}),successful:A6().notNull().default(!1)}),jH=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:q4().notNull().default(ZZ),succeededIp:e0({length:45}),succeededAtIso:q4(),verificationMethod:jH().notNull()}),TO=B4("banishedIps",{ip:e0({length:45}).primaryKey(),reason:e0({length:2048}).notNull(),banishedAtIso:q4().notNull().default(ZZ),banishedUntilIso:q4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class aX{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(CO.resolve(__dirname,"notify_update.sql"));let Y=[c0(l4),c0(XZ),c0(rX)];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=YZ(this.sql,{schema:sX,logger:Y})}observe(Y,Z){if(!this.observers.has(Y))this.observers.set(Y,new J0);this.observers.get(Y).subscribe("SINGLETON",Z)}}var _Z={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 qO(Y){return Number.parseInt(Y,10)}var KO=E1(_Z),jO=KO.keyof().pipe((Y)=>qO(Y)),PH=E1([jO,"string"]);var eX=new t7,{logger:M1}=eX;Object.assign(console,M1,{log:M1.info});M1.info("ready");var tX=vH(import.meta.dir,"..","app"),rx=new aX({logQuery(Y,Z){M1.info("\uD83D\uDCDD query",Y,Z)}});xO({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...wY??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(vH(tX,"index.html")));if(X.pathname==="/index.html")return Response.redirect("/");let _=SO(tX,X.pathname),G=vO(_);if(!G.startsWith(tX))throw[403,"Access Denied"];if(!await SH(G).exists())return Response.redirect("/");return new Response(SH(G))}catch(Z){let X=PH(Z);if(X instanceof E1.errors===!1){let[_,G]=X,H=`${_Z[_]}. ${G}`;return M1.info(`\u274C ${_}: ${H}`),new Response(H,{status:_})}if(Z instanceof Error)M1.error(Z.message);else{let _=AY(Z);M1.error("frontend server threw",_)}return new Response(_Z[500],{status:500})}}});function GZ(){M1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{M1.info("\u2757 received SIGINT; exiting gracefully"),GZ()});process.on("SIGTERM",()=>{M1.info("\u2757 received SIGTERM; exiting gracefully"),GZ()});process.on("exit",()=>{M1.info("\u2757 received exit; exiting gracefully"),GZ()});eX.on("timeToStop",()=>{M1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),GZ()});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}/`);eX.emit("alive");
|
|
89
|
+
`;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($)=>{for await(let Q of Y)if(!J||Number(J.created_at)<Q.folderMillis){for(let z of Q.sql)await $.execute(E.raw(z));await $.execute(E`insert into ${E.identifier(G)}.${E.identifier(_)} ("hash", "created_at") values(${Q.hash}, ${Q.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],$=Z[W]??E.param(J.onUpdateFn(),J),Q=E`${E.identifier(this.casing.getColumnCasing(J))} = ${$}`;if(H<G-1)return[Q,E.raw(", ")];return[Q]}))}buildUpdateQuery({table:Y,set:Z,where:X,returning:_,withList:G,from:W,joins:H}){let J=this.buildWithCTE(G),$=Y[d0.Symbol.Name],Q=Y[d0.Symbol.Schema],z=Y[d0.Symbol.OriginalName],O=$===z?void 0:$,D=E`${Q?E`${E.identifier(Q)}.`: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),g=_?E` returning ${this.buildSelection(_,{isSingleTable:!W})}`:void 0,b=X?E` where ${X}`:void 0;return E`${J}update ${D} set ${V}${R}${A}${b}${g}`}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(($)=>{if(M($,j))return E.identifier(this.casing.getColumnCasing($));return $})));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],$=G[d0.Symbol.Schema],Q=G[d0.Symbol.OriginalName],z=J===Q?void 0:_.alias;Z.push(E`${E.raw(_.joinType)} join${W} ${$?E`${E.identifier($)}.`:void 0}${E.identifier(Q)}${z&&E` ${E.identifier(z)}`}${H}`)}else if(M(G,L1)){let J=G[A0].name,$=G[A0].schema,Q=G[A0].originalName,z=J===Q?void 0:_.alias;Z.push(E`${E.raw(_.joinType)} join${W} ${$?E`${E.identifier($)}.`:void 0}${E.identifier(Q)}${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:$,limit:Q,offset:z,lockingClause:O,distinct:D,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,P6)?W[A0].name:M(W,x)?void 0:c0(W))&&!((U0)=>H?.some(({alias:b0})=>b0===(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,g=this.buildWithCTE(Y),b;if(D)b=D===!0?E` distinct`:E` distinct on (${E.join(D.on,E`, `)})`;let f=this.buildSelection(R,{isSingleTable:A}),h=this.buildFromTable(W),I=this.buildJoins(H),N=_?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($&&$.length>0)p=E` group by ${E.join($,E`, `)}`;let s=typeof Q==="object"||typeof Q==="number"&&Q>=0?E` limit ${Q}`:void 0,C=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`${g}select${b} ${f} from ${h}${I}${N}${p}${q}${K}${s}${C}${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()}) `,$=E`(${_.getSQL()})`,Q;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 g=R.queryChunks[A];if(M(g,j))R.queryChunks[A]=E.identifier(g.name)}V.push(E`${R}`)}else V.push(E`${R}`);Q=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 ":""}`),D=H?E` offset ${H}`:void 0;return E`${J}${O}${$}${Q}${z}${D}`}buildInsertQuery({table:Y,values:Z,onConflict:X,returning:_,withList:G,select:W,overridingSystemValue_:H}){let J=[],$=Y[P.Symbol.Columns],Q=Object.entries($).filter(([g,b])=>!b.shouldDisableInsert()),z=Q.map(([,g])=>E.identifier(this.casing.getColumnCasing(g)));if(W){let g=Z;if(M(g,x))J.push(g);else J.push(g.getSQL())}else{let g=Z;J.push(E.raw("values "));for(let[b,f]of g.entries()){let h=[];for(let[I,N]of Q){let q=f[I];if(q===void 0||M(q,N1)&&q.value===void 0)if(N.defaultFn!==void 0){let K=N.defaultFn(),p=M(K,x)?K:E.param(K,N);h.push(p)}else if(!N.default&&N.onUpdateFn!==void 0){let K=N.onUpdateFn(),p=M(K,x)?K:E.param(K,N);h.push(p)}else h.push(E`default`);else h.push(q)}if(J.push(h),b<g.length-1)J.push(E`, `)}}let O=this.buildWithCTE(G),D=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}${D}${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,vY)||M(Y,SY))return"json";else if(M(Y,xY))return"decimal";else if(M(Y,hY))return"time";else if(M(Y,fY)||M(Y,bY))return"timestamp";else if(M(Y,jY)||M(Y,PY))return"date";else if(M(Y,kY))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:$}){let Q=[],z,O,D=[],V,R=[];if(W===!0)Q=Object.entries(G.columns).map(([b,f])=>({dbKey:f.name,tsKey:b,field:o1(f,H),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let g=Object.fromEntries(Object.entries(G.columns).map(([q,K])=>[q,o1(K,H)]));if(W.where){let q=typeof W.where==="function"?W.where(g,n2()):W.where;V=q&&M6(q,H)}let b=[],f=[];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;f.push(K)}}if(f.length>0)f=q?f.filter((K)=>W.columns?.[K]===!0):Object.keys(G.columns).filter((K)=>!f.includes(K))}else f=Object.keys(G.columns);for(let q of f){let K=G.columns[q];b.push({tsKey:q,value:K})}let h=[];if(W.with)h=Object.entries(W.with).filter((q)=>!!q[1]).map(([q,K])=>({tsKey:q,queryConfig:K,relation:G.relations[q]}));let I;if(W.extras){I=typeof W.extras==="function"?W.extras(g,{sql:E}):W.extras;for(let[q,K]of Object.entries(I))b.push({tsKey:q,value:zX(K,H)})}for(let{tsKey:q,value:K}of b)Q.push({dbKey:M(K,x.Aliased)?K.fieldAlias:G.columns[q].name,tsKey:q,field:M(K,E0)?o1(K,H):K,relationTableTsKey:void 0,isJson:!1,selection:[]});let N=typeof W.orderBy==="function"?W.orderBy(g,r2()):W.orderBy??[];if(!Array.isArray(N))N=[N];D=N.map((q)=>{if(M(q,E0))return o1(q,H);return M6(q,H)}),z=W.limit,O=W.offset;for(let{tsKey:q,queryConfig:K,relation:p}of h){let s=a2(Z,X,p),C=y4(p.referencedTable),t=X[C],m=`${H}_${q}`,e=I6(...s.fields.map((Q1,r1)=>gY(o1(s.references[r1],m),o1(Q1,H)))),U0=this.buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:Y[t],tableConfig:Z[t],queryConfig:M(p,C4)?K===!0?{limit:1}:{...K,limit:1}:K,tableAlias:m,joinOn:e,nestedQueryRelation:p}),b0=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}),Q.push({dbKey:q,tsKey:q,field:b0,relationTableTsKey:t,isJson:!0,selection:U0.selection})}}if(Q.length===0)throw new KY({message:`No fields selected for table "${G.tsName}" ("${H}")`});let A;if(V=I6($,V),J){let g=E`json_build_array(${E.join(Q.map(({field:h,tsKey:I,isJson:N})=>N?E`${E.identifier(`${H}_${I}`)}.${E.identifier("data")}`:M(h,x.Aliased)?h.sql:h),E`, `)})`;if(M(J,B6))g=E`coalesce(json_agg(${g}${D.length>0?E` order by ${E.join(D,E`, `)}`:void 0}), '[]'::json)`;let b=[{dbKey:"data",tsKey:"data",field:g.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:Q}];if(z!==void 0||O!==void 0||D.length>0)A=this.buildSelectQuery({table:TY(_,H),fields:{},fieldsFlat:[{path:[],field:E.raw("*")}],where:V,limit:z,offset:O,orderBy:D,setOperators:[]}),V=void 0,z=void 0,O=void 0,D=[];else A=TY(_,H);A=this.buildSelectQuery({table:M(A,d0)?A:new P0(A,{},H),fields:{},fieldsFlat:b.map(({field:h})=>({path:[],field:M(h,E0)?o1(h,H):h})),joins:R,where:V,limit:z,offset:O,orderBy:D,setOperators:[]})}else A=this.buildSelectQuery({table:TY(_,H),fields:{},fieldsFlat:Q.map(({field:g})=>({path:[],field:M(g,E0)?o1(g,H):g})),joins:R,where:V,limit:z,offset:O,orderBy:D,setOperators:[]});return{tableTsKey:G.tsName,sql:A,selection:Q}}}class kX{static[U]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class J1{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,P6))_=X[A0].selectedFields;else if(M(X,x))_={};else _=T3(X);return new gX({table:X,fields:_,isPartialSelect:Z,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class RH extends kX{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=Q4(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=Q4(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,L1)?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(EO()):X;if(!A6(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 gX extends RH{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:$}=X;return D0.startActiveSpan("drizzle.prepareQuery",()=>{let Q=q1($),z=Z.prepareQuery(_.sqlToQuery(this.getSQL()),Q,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 D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}C3(gX,[H1]);function C8(Y,Z){return(X,_,...G)=>{let W=[_,...G].map((H)=>({type:Y,isAll:Z,rightSelect:H}));for(let H of W)if(!A6(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 EO=()=>({union:DO,unionAll:LO,intersect:VO,intersectAll:MO,except:AO,exceptAll:wO}),DO=C8("union",!1),LO=C8("union",!0),VO=C8("intersect",!1),MO=C8("intersect",!0),AO=C8("except",!1),wO=C8("except",!0);class S6{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 D6(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 J1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),withList:Y})}function _(W){return new J1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),distinct:!0})}function G(W,H){return new J1({fields:H??void 0,session:void 0,dialect:Z.getDialect(),distinct:{on:W}})}return{select:X,selectDistinct:_,selectDistinctOn:G}}select(Y){return new J1({fields:Y??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(Y){return new J1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(Y,Z){return new J1({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 tY extends H1{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 D0.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 D0.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 eY{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 N1(H,G[W])}return _});return new yX(this.table,Z,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(Y){let Z=typeof Y==="function"?Y(new S6):Y;if(!M(Z,x)&&!A6(this.table[BY],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 yX(this.table,Z,this.session,this.dialect,this.withList,!0)}}class yX extends H1{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,qY(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 D0.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 D0.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 pX extends H1{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 D0.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 D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}class YZ{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 NH(this.table,qY(this.table,Y),this.session,this.dialect,this.withList).setToken(this.authToken)}}class NH extends H1{constructor(Y,Z,X,_,G){super();this.session=X,this.dialect=_,this.config={set:Z,table:Y,withList:G,joins:[]},this.tableName=Q4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[U]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(Y){let Z=Y,X=Q4(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 _=Q4(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=Q4(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 _=Q4(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 v6 extends x{constructor(Y){super(v6.buildEmbeddedCount(Y.source,Y.filters).queryChunks);this.params=Y,this.mapWith(Number),this.session=Y.session,this.sql=v6.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 uX{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 mX(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?Y:{},"many")}findFirst(Y){return new mX(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?{...Y,limit:1}:{limit:1},"first")}}class mX extends H1{constructor(Y,Z,X,_,G,W,H,J,$){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=$}static[U]="PgRelationalQuery";_prepare(Y){return D0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Z,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,Y,!0,(_,G)=>{let W=_.map((H)=>yY(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 D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class dX extends H1{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 x6{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 uX(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 S6(X.dialect));return new Proxy(new D6(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(Y,Z){return new v6({source:Y,filters:Z,session:this.session})}$cache;with(...Y){let Z=this;function X($){return new J1({fields:$??void 0,session:Z.session,dialect:Z.dialect,withList:Y})}function _($){return new J1({fields:$??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:!0})}function G($,Q){return new J1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:{on:$}})}function W($){return new YZ($,Z.session,Z.dialect,Y)}function H($){return new eY($,Z.session,Z.dialect,Y)}function J($){return new tY($,Z.session,Z.dialect,Y)}return{select:X,selectDistinct:_,selectDistinctOn:G,update:W,insert:H,delete:J}}select(Y){return new J1({fields:Y??void 0,session:this.session,dialect:this.dialect})}selectDistinct(Y){return new J1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(Y,Z){return new J1({fields:Z??void 0,session:this.session,dialect:this.dialect,distinct:{on:Y}})}update(Y){return new YZ(Y,this.session,this.dialect)}insert(Y){return new eY(Y,this.session,this.dialect)}delete(Y){return new tY(Y,this.session,this.dialect)}refreshMaterializedView(Y){return new pX(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 dX(()=>_.execute(void 0,this.authToken),Z,X,(G)=>_.mapResult(G,!0))}transaction(Y,Z){return this.session.transaction(Y,Z)}}class IH{static[U]="Cache"}class h6 extends IH{strategy(){return"all"}static[U]="NoopCache";async get(Y){return}async put(Y,Z,X,_){}async onMutate(Y){}}async function cX(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(($)=>$.toString(16).padStart(2,"0")).join("")}class lX{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,h6)||this.queryMetadata===void 0)try{return await X()}catch(_){throw new J4(Y,Z,_)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await X()}catch(_){throw new J4(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 J4(Y,Z,_)}if(!this.cacheConfig)try{return await X()}catch(_){throw new J4(Y,Z,_)}if(this.queryMetadata.type==="select"){let _=await this.cache.get(this.cacheConfig.tag??await cX(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 J4(Y,Z,W)}return await this.cache.put(this.cacheConfig.tag??await cX(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 J4(Y,Z,_)}}}class iX{constructor(Y){this.dialect=Y}static[U]="PgSession";execute(Y,Z){return D0.startActiveSpan("drizzle.operation",()=>{return D0.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 oX extends x6{constructor(Y,Z,X,_=0){super(Y,Z,X);this.schema=X,this.nestedIndex=_}static[U]="PgTransaction";rollback(){throw new FX}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 BH extends lX{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=$,this.customResultMapper=Q}static[U]="PostgresJsPreparedQuery";async execute(Y={}){return D0.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 D0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(G,X,async()=>{return await W.unsafe(G,X)})});let $=await D0.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 D0.startActiveSpan("drizzle.mapResponse",()=>{return J?J($):$.map((Q)=>B3(_,Q,H))})})}all(Y={}){return D0.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),D0.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 f6 extends iX{constructor(Y,Z,X,_={}){super(Z);this.client=Y,this.schema=X,this.options=_,this.logger=_.logger??new OX,this.cache=_.cache??new h6}static[U]="PostgresJsSession";logger;cache;prepareQuery(Y,Z,X,_,G,W,H){return new BH(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 f6(X,this.dialect,this.schema,this.options),G=new nX(this.dialect,_,this.schema);if(Z)await G.setTransaction(Z);return Y(G)})}}class nX extends oX{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 f6(Z,this.dialect,this.schema,this.session.options),_=new nX(this.dialect,X,this.schema);return Y(_)})}}class CH extends x6{static[U]="PostgresJsDatabase"}function T8(Y,Z={}){let X=($)=>$;for(let $ of["1184","1082","1083","1114","1182","1185","1115","1231"])Y.options.parsers[$]=X,Y.options.serializers[$]=X;Y.options.serializers["114"]=X,Y.options.serializers["3802"]=X;let _=new c4({casing:Z.casing}),G;if(Z.logger===!0)G=new UX;else if(Z.logger!==!1)G=Z.logger;let W;if(Z.schema){let $=s2(Z.schema,t2);W={fullSchema:Z.schema,schema:$.tables,tableNamesMap:$.tableNamesMap}}let H=new f6(Y,_,W,{logger:G,cache:Z.cache}),J=new CH(_,H,W);if(J.$client=Y,J.$cache=Z.cache,J.$cache)J.$cache.invalidate=Z.cache?.onMutate;return J}function ZZ(...Y){if(typeof Y[0]==="string"){let Z=B8(Y[0]);return T8(Z,Y[1])}if(K3(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=B8(W,H);return T8(J,_)}let G=B8(Z);return T8(G,_)}return T8(Y[0],Y[1])}((Y)=>{function Z(X){return T8({options:{parsers:{},serializers:{}}},X)}Y.mock=Z})(ZZ||(ZZ={}));var sX={};PJ(sX,{users:()=>l4,untrackedUserColumnNames:()=>RO,twoFactorMethod:()=>PH,trackedUserColumnName:()=>NO,trackableUserColumnNames:()=>qH,signInHistory:()=>BO,role:()=>KH,players:()=>rX,passwordResetAttempts:()=>CO,games:()=>_Z,banishedIps:()=>TO,accountActions:()=>IO,accountAction:()=>jH});function K4(){return e0({length:24}).$type()}function TH(Y){return E`lower(${Y})`}var XZ=E`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,KH=E6("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(XZ),createdIp:e0({length:45}).notNull(),isActive:w6().notNull().default(!1),verifiedAtIso:K4(),userRole:KH().default("user")},(Y)=>[fX("usernameUniqueIndex").on(TH(Y.username)),fX("emailVerifiedUniqueIndex").on(TH(Y.emailVerified))]),RO=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],qH=["username","emailOffered","emailVerified","password","userRole"],NO=E6("trackedUserColumnName",qH),jH=E6("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),IO=B4("accountActions",{userId:j1().references(()=>l4.id).primaryKey(),action:jH().notNull(),code:e0({length:254}).notNull(),wrongCodeCount:R6().notNull().default(0),expiresAtIso:K4().notNull()}),_Z=B4("games",{id:j1().primaryKey().defaultRandom()}),rX=B4("players",{userId:j1().notNull().references(()=>l4.id,{onDelete:"cascade"}),gameId:j1().notNull().references(()=>_Z.id,{onDelete:"cascade"}),score:R6().notNull()},(Y)=>[B2({name:"players_userId_gameId_pk",columns:[Y.userId,Y.gameId]})]),BO=B4("signInHistory",{id:j1().primaryKey().defaultRandom(),userId:j1().references(()=>l4.id,{onDelete:"cascade"}),signInTimeIso:K4().notNull().default(XZ),ipAddress:e0({length:45}).notNull(),userAgent:e0({length:1024}),successful:w6().notNull().default(!1)}),PH=E6("twoFactorMethod",["email","phone"]),CO=B4("passwordResetAttempts",{id:j1().primaryKey().defaultRandom(),userId:j1().notNull().references(()=>l4.id,{onDelete:"cascade"}),requestedIp:e0({length:45}).notNull(),requestedAtIso:K4().notNull().default(XZ),succeededIp:e0({length:45}),succeededAtIso:K4(),verificationMethod:PH().notNull()}),TO=B4("banishedIps",{ip:e0({length:45}).primaryKey(),reason:e0({length:2048}).notNull(),banishedAtIso:K4().notNull().default(XZ),banishedUntilIso:K4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class aX{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(KO.resolve(__dirname,"notify_update.sql"));let Y=[c0(l4),c0(_Z),c0(rX)];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=B8(Z),this.drizzle=ZZ(this.sql,{schema:sX,logger:Y})}observe(Y,Z){if(!this.observers.has(Y))this.observers.set(Y,new J0);this.observers.get(Y).subscribe("SINGLETON",Z)}}var GZ={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 qO(Y){return Number.parseInt(Y,10)}var jO=E1(GZ),PO=jO.keyof().pipe((Y)=>qO(Y)),SH=E1([PO,"string"]);var eX=new e7,{logger:M1}=eX;Object.assign(console,M1,{log:M1.info});M1.info("ready");var tX=xH(import.meta.dir,"..","app"),sx=new aX({logQuery(Y,Z){M1.info("\uD83D\uDCDD query",Y,Z)}});hO({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...RY??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(xH(tX,"index.html")));if(X.pathname==="/index.html")return Response.redirect("/");let _=vO(tX,X.pathname),G=xO(_);if(!G.startsWith(tX))throw[403,"Access Denied"];if(!await vH(G).exists())return Response.redirect("/");return new Response(vH(G))}catch(Z){let X=SH(Z);if(X instanceof E1.errors===!1){let[_,G]=X,H=`${GZ[_]}. ${G}`;return M1.info(`\u274C ${_}: ${H}`),new Response(H,{status:_})}if(Z instanceof Error)M1.error(Z.message);else{let _=wY(Z);M1.error("frontend server threw",_)}return new Response(GZ[500],{status:500})}}});function WZ(){M1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{M1.info("\u2757 received SIGINT; exiting gracefully"),WZ()});process.on("SIGTERM",()=>{M1.info("\u2757 received SIGTERM; exiting gracefully"),WZ()});process.on("exit",()=>{M1.info("\u2757 received exit; exiting gracefully"),WZ()});eX.on("timeToStop",()=>{M1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),WZ()});var{version:fO}=await Bun.file(SO.resolve(import.meta.dir,"../package.json")).json();M1.info(`\uD83D\uDEEB frontend v${fO} running at http://localhost:${g1.FRONTEND_PORT}/`);eX.emit("alive");
|