tempest.games 0.2.12 → 0.2.14
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-XXIFAPT4.js +109 -0
- package/app/index.html +1 -1
- package/bin/backend.bun.js +181 -181
- package/bin/backend.worker.tribunal.bun.js +83 -81
- package/bin/frontend.bun.js +19 -19
- package/bin/setup-db.bun.js +55 -55
- package/package.json +29 -34
- package/app/assets/index-BG6T8CzE.js +0 -109
package/bin/frontend.bun.js
CHANGED
|
@@ -1,53 +1,53 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var dG=Object.create;var{getPrototypeOf:lG,defineProperty:r1,getOwnPropertyNames:tG}=Object;var iG=Object.prototype.hasOwnProperty;var UO=(T,_,F)=>{F=T!=null?dG(lG(T)):{};let W=_||!T||!T.__esModule?r1(F,"default",{value:T,enumerable:!0}):F;for(let J of tG(T))if(!iG.call(W,J))r1(W,J,{get:()=>T[J],enumerable:!0});return W};var MO=(T,_)=>()=>(_||T((_={exports:{}}).exports,_),_.exports);var nG=(T,_)=>{for(var F in _)r1(T,F,{get:_[F],enumerable:!0,configurable:!0,set:(W)=>_[F]=()=>W})};var wO=(T,_)=>()=>(T&&(_=T(T=0)),_);var QO=import.meta.require;import XO,{join as GO,normalize as AO,resolve as a5}from"path";var W0=(T)=>Array.isArray(T)?T:[T],p8=(T,_)=>{let F=[[],[]];for(let W of T)if(_(W))F[0].push(W);else F[1].push(W);return F},NW=Array,u_=(T,_)=>T.includes(_),g8=(T,_=0)=>[...new Array(T)].map((F,W)=>W+_),s=(T,_,F)=>{if(T===void 0)return _===void 0?[]:Array.isArray(_)?_:[_];if(F?.prepend)if(Array.isArray(_))T.unshift(..._);else T.unshift(_);else if(Array.isArray(_))T.push(..._);else T.push(_);return T},c_=(T,_)=>{if(_===void 0||_===null)return T??[];if(T===void 0||T===null)return W0(_);return T.concat(_)},m8=(...T)=>T.reduce(c_,[]),b_=(T,_,F)=>{if(T===void 0)return Array.isArray(_)?_:[_];let W=F?.isEqual??((J,Y)=>J===Y);for(let J of W0(_))if(!T.some((Y)=>W(Y,J)))T.push(J);return T},o8=(T,_)=>T.reduce((F,W)=>{let J=W[_];return F[J]=s(F[J],W),F},{}),d_=(T,_,F)=>T.length===_.length&&T.every(F?.isEqual?(W,J)=>F.isEqual(W,_[J]):(W,J)=>W===_[J]);var T_=(T,_)=>PT(T)===_,PT=(T)=>{let _=typeof T;return _==="object"?T===null?"null":"object":_==="function"?"object":_},__={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},u8={...__,function:"a function"};class c8 extends Error{}var e=(T)=>D0(T,c8),D0=(T,_=Error)=>{throw new _(T)};class EF extends Error{name="ParseError"}var E=(T)=>D0(T,EF),B_=(T)=>` ${T}`;var c=(T,_)=>{let F={},W=Array.isArray(T),J=!1;for(let[Y,$]of Object.entries(T).entries()){let Z=W?_(Y,$[1]):_(...$,Y);J||=typeof Z[0]==="number";let G=Array.isArray(Z[0])||Z.length===0?Z:[Z];for(let[X,O]of G)if(typeof X==="object")F[X.group]=s(F[X.group],O);else F[X]=O}return J?Object.values(F):F};var s1=Object.entries;var qT=(T,_)=>(T in _),g0=(T,_)=>(_ in T);class a1{constructor(T){Object.assign(this,T)}}var d8=class{};class zF extends d8{}var rG=(T,_)=>{let F={},W={},J;for(J in T)if(J in _)F[J]=T[J];else W[J]=T[J];return[F,W]};var l8=(T,_)=>rG(T,_)[1],h_=(T)=>Object.keys(T).length===0,S0=(T)=>[...Object.entries(T),...Object.getOwnPropertySymbols(T).map((_)=>[_,T[_]])],t8=(T,_)=>Object.defineProperties(T,Object.getOwnPropertyDescriptors(_)),i8=(T)=>{let _=Object.keys(T).sort(),F={};for(let W=0;W<_.length;W++)F[_[W]]=T[_[W]];return F};var O_=B_("represents an uninitialized value"),n8=(T)=>Object.values(T).filter((_)=>{if(typeof _==="number")return!0;return typeof T[_]!=="number"});var e1={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},T4=globalThis.File??Blob,_4={ArrayBuffer,Blob,File:T4,FormData,Headers,Request,Response,URL},sG={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},I0={...e1,..._4,...sG,String,Number,Boolean},
|
|
3
|
+
var dG=Object.create;var{getPrototypeOf:lG,defineProperty:r1,getOwnPropertyNames:tG}=Object;var iG=Object.prototype.hasOwnProperty;var UO=(T,_,F)=>{F=T!=null?dG(lG(T)):{};let W=_||!T||!T.__esModule?r1(F,"default",{value:T,enumerable:!0}):F;for(let J of tG(T))if(!iG.call(W,J))r1(W,J,{get:()=>T[J],enumerable:!0});return W};var MO=(T,_)=>()=>(_||T((_={exports:{}}).exports,_),_.exports);var nG=(T,_)=>{for(var F in _)r1(T,F,{get:_[F],enumerable:!0,configurable:!0,set:(W)=>_[F]=()=>W})};var wO=(T,_)=>()=>(T&&(_=T(T=0)),_);var QO=import.meta.require;import XO,{join as GO,normalize as AO,resolve as a5}from"path";var W0=(T)=>Array.isArray(T)?T:[T],p8=(T,_)=>{let F=[[],[]];for(let W of T)if(_(W))F[0].push(W);else F[1].push(W);return F},NW=Array,u_=(T,_)=>T.includes(_),g8=(T,_=0)=>[...new Array(T)].map((F,W)=>W+_),s=(T,_,F)=>{if(T===void 0)return _===void 0?[]:Array.isArray(_)?_:[_];if(F?.prepend)if(Array.isArray(_))T.unshift(..._);else T.unshift(_);else if(Array.isArray(_))T.push(..._);else T.push(_);return T},c_=(T,_)=>{if(_===void 0||_===null)return T??[];if(T===void 0||T===null)return W0(_);return T.concat(_)},m8=(...T)=>T.reduce(c_,[]),b_=(T,_,F)=>{if(T===void 0)return Array.isArray(_)?_:[_];let W=F?.isEqual??((J,Y)=>J===Y);for(let J of W0(_))if(!T.some((Y)=>W(Y,J)))T.push(J);return T},o8=(T,_)=>T.reduce((F,W)=>{let J=W[_];return F[J]=s(F[J],W),F},{}),d_=(T,_,F)=>T.length===_.length&&T.every(F?.isEqual?(W,J)=>F.isEqual(W,_[J]):(W,J)=>W===_[J]);var T_=(T,_)=>PT(T)===_,PT=(T)=>{let _=typeof T;return _==="object"?T===null?"null":"object":_==="function"?"object":_},__={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},u8={...__,function:"a function"};class c8 extends Error{}var e=(T)=>D0(T,c8),D0=(T,_=Error)=>{throw new _(T)};class EF extends Error{name="ParseError"}var E=(T)=>D0(T,EF),B_=(T)=>` ${T}`;var c=(T,_)=>{let F={},W=Array.isArray(T),J=!1;for(let[Y,$]of Object.entries(T).entries()){let Z=W?_(Y,$[1]):_(...$,Y);J||=typeof Z[0]==="number";let G=Array.isArray(Z[0])||Z.length===0?Z:[Z];for(let[X,O]of G)if(typeof X==="object")F[X.group]=s(F[X.group],O);else F[X]=O}return J?Object.values(F):F};var s1=Object.entries;var qT=(T,_)=>(T in _),g0=(T,_)=>(_ in T);class a1{constructor(T){Object.assign(this,T)}}var d8=class{};class zF extends d8{}var rG=(T,_)=>{let F={},W={},J;for(J in T)if(J in _)F[J]=T[J];else W[J]=T[J];return[F,W]};var l8=(T,_)=>rG(T,_)[1],h_=(T)=>Object.keys(T).length===0,S0=(T)=>[...Object.entries(T),...Object.getOwnPropertySymbols(T).map((_)=>[_,T[_]])],t8=(T,_)=>Object.defineProperties(T,Object.getOwnPropertyDescriptors(_)),i8=(T)=>{let _=Object.keys(T).sort(),F={};for(let W=0;W<_.length;W++)F[_[W]]=T[_[W]];return F};var O_=B_("represents an uninitialized value"),n8=(T)=>Object.values(T).filter((_)=>{if(typeof _==="number")return!0;return typeof T[_]!=="number"});var e1={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},T4=globalThis.File??Blob,_4={ArrayBuffer,Blob,File:T4,FormData,Headers,Request,Response,URL},sG={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},I0={...e1,..._4,...sG,String,Number,Boolean},KF=(T)=>{let _=Object.getPrototypeOf(T);while(_?.constructor&&(!qT(_.constructor.name,I0)||!(T instanceof I0[_.constructor.name])))_=Object.getPrototypeOf(_);let F=_?.constructor?.name;if(F===void 0||F==="Object")return;return F},VF=(T)=>typeof T==="object"&&T!==null?KF(T)??"object":PT(T);var XT=Array.isArray,aG={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"},eG={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"},TA={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"},r8={...aG,...eG,...TA},LF=(T)=>{let _=Object(T).name??null;return _&&qT(_,I0)&&I0[_]===T?_:null};var F4=(T,_)=>{let F=T.prototype;while(F!==null){if(F===_.prototype)return!0;F=Object.getPrototypeOf(F)}return!1};var s8=(T)=>a8(T,new Map),a8=(T,_)=>{if(typeof T!=="object"||T===null)return T;if(_?.has(T))return _.get(T);let F=LF(T.constructor);if(F==="Date")return new Date(T.getTime());if(F&&F!=="Array")return T;let W=Array.isArray(T)?T.slice():Object.create(Object.getPrototypeOf(T)),J=Object.getOwnPropertyDescriptors(T);if(_){_.set(T,W);for(let Y in J){let $=J[Y];if("get"in $||"set"in $)continue;$.value=a8($.value,_)}}return Object.defineProperties(W,J),W};var _A=(T)=>{let _=O_;return()=>_===O_?_=T():_},J0=(T)=>typeof T==="function"&&T.length===0;var e8=class extends Function{constructor(...T){let _=T.slice(0,-1),F=T.at(-1);try{super(..._,F)}catch(W){return e(`Encountered an unexpected error while compiling your definition:
|
|
4
4
|
Message: ${W}
|
|
5
5
|
Source: (${T.slice(0,-1)}) => {
|
|
6
6
|
${T.at(-1)}
|
|
7
7
|
}`)}}};class k_{constructor(T,...[_]){return Object.assign(Object.setPrototypeOf(T.bind(_?.bind??this),this.constructor.prototype),_?.attach)}}var TJ=_A(()=>{try{return new Function("return false")()}catch{return!0}});var bO=B_("brand");var _J=B_("arkInferred");var gO=B_("args");class uT{constructor(){}}var FA=()=>{try{return((new Error().stack?.split(`
|
|
8
|
-
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},WA=globalThis.process?.env??{},FJ={fileName:FA,env:WA};var WJ=(T)=>T[0].toUpperCase()+T.slice(1);var W4=(T)=>new RegExp(JA(T),typeof T==="string"?"":T.flags);var JA=(T)=>{return`^(?:${typeof T==="string"?T:T.source})$`};var l_={negativeLookahead:(T)=>`(?!${T})`,nonCapturingGroup:(T)=>`(?:${T})`},DF="\\",Y0={" ":1,"\n":1,"\t":1};var YA=/^-0\.?0*$/.source,YJ=/[1-9]\d*/.source,$A=/\.\d+/.source,ZA=/\.\d*[1-9]/.source,$J=(T)=>W4(l_.negativeLookahead(YA)+l_.nonCapturingGroup("-?"+l_.nonCapturingGroup(l_.nonCapturingGroup("0|"+YJ)+l_.nonCapturingGroup(T.decimalPattern)+"?")+(T.allowDecimalOnly?"|"+T.decimalPattern:"")+"?")),JJ=$J({decimalPattern:ZA,allowDecimalOnly:!1}),XA=JJ.test.bind(JJ),CW=$J({decimalPattern:$A,allowDecimalOnly:!0}),tO=CW.test.bind(CW),GA=/^-?\d*\.?\d*$/,AA=(T)=>T.length!==0&&GA.test(T),SF=W4(l_.negativeLookahead("^-0$")+"-?"+l_.nonCapturingGroup(l_.nonCapturingGroup("0|"+YJ))),HA=SF.test.bind(SF),J4=/^-?\d+$/,OA=J4.test.bind(J4),ZJ={number:"a number",bigint:"a bigint",integer:"an integer"},XJ=(T,_)=>`'${T}' was parsed as ${ZJ[_]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,UA=(T,_)=>_==="number"?XA(T):HA(T),MA=(T,_)=>_==="number"?Number(T):Number.parseInt(T),wA=(T,_)=>_==="number"?AA(T):OA(T),GJ=(T,_)=>Y4(T,"number",_),AJ=(T,_)=>Y4(T,"number",{..._,strict:!0}),HJ=(T,_)=>Y4(T,"integer",_),Y4=(T,_,F)=>{let W=MA(T,_);if(!Number.isNaN(W)){if(wA(T,_)){if(F?.strict)return UA(T,_)?W:E(XJ(T,_));return W}}return F?.errorOnFail?E(F?.errorOnFail===!0?`Failed to parse ${ZJ[_]} from '${T}'`:F?.errorOnFail):void 0},OJ=(T)=>{if(T[T.length-1]!=="n")return;let _=T.slice(0,-1),F;try{F=BigInt(_)}catch{return}if(SF.test(_))return F;if(J4.test(_))return E(XJ(T,"bigint"))};var QA="0.46.0",RA={version:QA,filename:FJ.fileName(),FileConstructor:T4},N0=RA,UJ=new Map,$4=Object.create(null),IF=(T)=>{let _=UJ.get(T);if(_)return _;let F=EA(T);if($4[F])F=`${F}${$4[F]++}`;else $4[F]=1;return N0[F]=T,UJ.set(T,F),F},$0=(T)=>/^[$A-Z_a-z][\w$]*$/.test(T),EA=(T)=>{switch(typeof T){case"object":{if(T===null)break;let _=
|
|
8
|
+
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},WA=globalThis.process?.env??{},FJ={fileName:FA,env:WA};var WJ=(T)=>T[0].toUpperCase()+T.slice(1);var W4=(T)=>new RegExp(JA(T),typeof T==="string"?"":T.flags);var JA=(T)=>{return`^(?:${typeof T==="string"?T:T.source})$`};var l_={negativeLookahead:(T)=>`(?!${T})`,nonCapturingGroup:(T)=>`(?:${T})`},DF="\\",Y0={" ":1,"\n":1,"\t":1};var YA=/^-0\.?0*$/.source,YJ=/[1-9]\d*/.source,$A=/\.\d+/.source,ZA=/\.\d*[1-9]/.source,$J=(T)=>W4(l_.negativeLookahead(YA)+l_.nonCapturingGroup("-?"+l_.nonCapturingGroup(l_.nonCapturingGroup("0|"+YJ)+l_.nonCapturingGroup(T.decimalPattern)+"?")+(T.allowDecimalOnly?"|"+T.decimalPattern:"")+"?")),JJ=$J({decimalPattern:ZA,allowDecimalOnly:!1}),XA=JJ.test.bind(JJ),CW=$J({decimalPattern:$A,allowDecimalOnly:!0}),tO=CW.test.bind(CW),GA=/^-?\d*\.?\d*$/,AA=(T)=>T.length!==0&&GA.test(T),SF=W4(l_.negativeLookahead("^-0$")+"-?"+l_.nonCapturingGroup(l_.nonCapturingGroup("0|"+YJ))),HA=SF.test.bind(SF),J4=/^-?\d+$/,OA=J4.test.bind(J4),ZJ={number:"a number",bigint:"a bigint",integer:"an integer"},XJ=(T,_)=>`'${T}' was parsed as ${ZJ[_]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,UA=(T,_)=>_==="number"?XA(T):HA(T),MA=(T,_)=>_==="number"?Number(T):Number.parseInt(T),wA=(T,_)=>_==="number"?AA(T):OA(T),GJ=(T,_)=>Y4(T,"number",_),AJ=(T,_)=>Y4(T,"number",{..._,strict:!0}),HJ=(T,_)=>Y4(T,"integer",_),Y4=(T,_,F)=>{let W=MA(T,_);if(!Number.isNaN(W)){if(wA(T,_)){if(F?.strict)return UA(T,_)?W:E(XJ(T,_));return W}}return F?.errorOnFail?E(F?.errorOnFail===!0?`Failed to parse ${ZJ[_]} from '${T}'`:F?.errorOnFail):void 0},OJ=(T)=>{if(T[T.length-1]!=="n")return;let _=T.slice(0,-1),F;try{F=BigInt(_)}catch{return}if(SF.test(_))return F;if(J4.test(_))return E(XJ(T,"bigint"))};var QA="0.46.0",RA={version:QA,filename:FJ.fileName(),FileConstructor:T4},N0=RA,UJ=new Map,$4=Object.create(null),IF=(T)=>{let _=UJ.get(T);if(_)return _;let F=EA(T);if($4[F])F=`${F}${$4[F]++}`;else $4[F]=1;return N0[F]=T,UJ.set(T,F),F},$0=(T)=>/^[$A-Z_a-z][\w$]*$/.test(T),EA=(T)=>{switch(typeof T){case"object":{if(T===null)break;let _=KF(T)??"object";return _[0].toLowerCase()+_.slice(1)}case"function":return $0(T.name)?T.name:"fn";case"symbol":return T.description&&$0(T.description)?T.description:"symbol"}return e(`Unexpected attempt to register serializable value of type ${PT(T)}`)};var NF=(T)=>typeof T==="string"?JSON.stringify(T):typeof T==="bigint"?`${T}n`:`${T}`;var MJ=(T,_={})=>CF(T,{onUndefined:"$ark.undefined",onBigInt:(F)=>`$ark.bigint-${F}`,..._},[]);var d=(T,_)=>{switch(PT(T)){case"object":let F=T,W=F.constructor.name;return W==="Object"||W==="Array"?_?.quoteKeys===!1?BW(F,_?.indent??0,""):JSON.stringify(CF(F,m0,[]),null,_?.indent):BW(F,_?.indent??0,"");case"symbol":return m0.onSymbol(T);default:return NF(T)}},BW=(T,_,F)=>{if(typeof T==="function")return m0.onFunction(T);if(typeof T!=="object"||T===null)return NF(T);let W=F+" ".repeat(_);if(Array.isArray(T)){if(T.length===0)return"[]";let Y=T.map(($)=>BW($,_,W)).join(`,
|
|
9
9
|
`+W);return _?`[
|
|
10
10
|
${W}${Y}
|
|
11
11
|
${F}]`:`[${Y}]`}let J=T.constructor.name;if(J==="Object"){let Y=S0(T).map(([$,Z])=>{let G=typeof $==="symbol"?m0.onSymbol($):$0($)?$:JSON.stringify($),X=BW(Z,_,W);return`${W}${G}: ${X}`});if(Y.length===0)return"{}";return _?`{
|
|
12
12
|
${Y.join(`,
|
|
13
13
|
`)}
|
|
14
|
-
${F}}`:`{${Y.join(", ")}}`}if(T instanceof Date)return C0(T);if("expression"in T&&typeof T.expression==="string")return T.expression;return J},m0={onCycle:()=>"(cycle)",onSymbol:(T)=>`Symbol(${IF(T)})`,onFunction:(T)=>`Function(${IF(T)})`},CF=(T,_,F)=>{switch(PT(T)){case"object":{let W=T;if("toJSON"in W&&typeof W.toJSON==="function")return W.toJSON();if(typeof W==="function")return m0.onFunction(W);if(F.includes(W))return"(cycle)";let J=[...F,W];if(Array.isArray(W))return W.map(($)=>CF($,_,J));if(W instanceof Date)return W.toDateString();let Y={};for(let $ in W)Y[$]=CF(W[$],_,J);for(let $ of Object.getOwnPropertySymbols(W))Y[_.onSymbol?.($)??$.toString()]=CF(W[$],_,J);return Y}case"symbol":return m0.onSymbol(T);case"bigint":return _.onBigInt?.(T)??`${T}n`;case"undefined":return _.onUndefined??"undefined";case"string":return T.replaceAll("\\","\\\\");default:return T}},C0=(T)=>{let _=T.getFullYear(),F=T.getMonth(),W=T.getDate(),J=T.getHours(),Y=T.getMinutes(),$=T.getSeconds(),Z=T.getMilliseconds();if(F===0&&W===1&&J===0&&Y===0&&$===0&&Z===0)return`${_}`;let G=`${zA[F]} ${W}, ${_}`;if(J===0&&Y===0&&$===0&&Z===0)return G;let X=T.toLocaleTimeString(),O=X.endsWith(" AM")||X.endsWith(" PM")?X.slice(-3):"";if(O)X=X.slice(0,-O.length);if(Z)X+=`.${
|
|
14
|
+
${F}}`:`{${Y.join(", ")}}`}if(T instanceof Date)return C0(T);if("expression"in T&&typeof T.expression==="string")return T.expression;return J},m0={onCycle:()=>"(cycle)",onSymbol:(T)=>`Symbol(${IF(T)})`,onFunction:(T)=>`Function(${IF(T)})`},CF=(T,_,F)=>{switch(PT(T)){case"object":{let W=T;if("toJSON"in W&&typeof W.toJSON==="function")return W.toJSON();if(typeof W==="function")return m0.onFunction(W);if(F.includes(W))return"(cycle)";let J=[...F,W];if(Array.isArray(W))return W.map(($)=>CF($,_,J));if(W instanceof Date)return W.toDateString();let Y={};for(let $ in W)Y[$]=CF(W[$],_,J);for(let $ of Object.getOwnPropertySymbols(W))Y[_.onSymbol?.($)??$.toString()]=CF(W[$],_,J);return Y}case"symbol":return m0.onSymbol(T);case"bigint":return _.onBigInt?.(T)??`${T}n`;case"undefined":return _.onUndefined??"undefined";case"string":return T.replaceAll("\\","\\\\");default:return T}},C0=(T)=>{let _=T.getFullYear(),F=T.getMonth(),W=T.getDate(),J=T.getHours(),Y=T.getMinutes(),$=T.getSeconds(),Z=T.getMilliseconds();if(F===0&&W===1&&J===0&&Y===0&&$===0&&Z===0)return`${_}`;let G=`${zA[F]} ${W}, ${_}`;if(J===0&&Y===0&&$===0&&Z===0)return G;let X=T.toLocaleTimeString(),O=X.endsWith(" AM")||X.endsWith(" PM")?X.slice(-3):"";if(O)X=X.slice(0,-O.length);if(Z)X+=`.${VA(Z,3)}`;else if(KA.test(X))X=X.slice(0,-3);return`${X+O}, ${G}`},zA=["January","February","March","April","May","June","July","August","September","October","November","December"],KA=/:\d\d:00$/,VA=(T,_)=>String(T).padStart(_,"0");var wJ=(T,_,...[F])=>{let W=F?.stringifySymbol??d,J=T;switch(typeof _){case"string":J=$0(_)?T===""?_:`${T}.${_}`:`${T}[${JSON.stringify(_)}]`;break;case"number":J=`${T}[${_}]`;break;case"symbol":J=`${T}[${W(_)}]`;break;default:if(F?.stringifyNonKey)J=`${T}[${F.stringifyNonKey(_)}]`;else E(`${d(_)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return J},t_=(T,..._)=>T.reduce((F,W)=>wJ(F,W,..._),"");class BF extends NW{cache={};constructor(...T){super();this.push(...T)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let T=0;T<this.length;T++)this.cache.json.push(typeof this[T]==="symbol"?d(this[T]):this[T]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=t_(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let T="",_=[T];for(let F of this)T=wJ(T,F),_.push(T);return this.cache.stringifyAncestors=_}}class Z4{chars;i;def;constructor(T){this.def=T,this.chars=[...T],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(T){let _="";while(this.lookahead){if(T(this,_))if(_[_.length-1]===DF)_=_.slice(0,-1);else break;_+=this.shift()}return _}shiftUntilLookahead(T){return typeof T==="string"?this.shiftUntil((_)=>_.lookahead===T):this.shiftUntil((_)=>(_.lookahead in T))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in Y0))}jumpToIndex(T){this.i=T<0?this.length+T:T}jumpForward(T){this.i+=T}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(T,_){return this.chars.slice(T,_).join("")}lookaheadIs(T){return this.lookahead===T}lookaheadIsIn(T){return this.lookahead in T}}var EU=B_("implementedTraits");var X4="$ark",LA=2;while(X4 in globalThis)X4=`$ark${LA++}`;var QJ=X4;globalThis[QJ]=N0;var z=N0,DA=(T)=>`${QJ}.${T}`,VT=(T)=>DA(IF(T));class kW extends zF{argNames;body="";constructor(...T){super();this.argNames=T;for(let _ of T){if(_ in this)throw new Error(`Arg name '${_}' would overwrite an existing property on FunctionBody`);this[_]=_}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(T,_=!1){return G4(T,_)}index(T,_=!1){return RJ(`${T}`,_)}line(T){return this.body+=`${" ".repeat(this.indentation)}${T}
|
|
15
15
|
`,this}const(T,_){return this.line(`const ${T} = ${_}`),this}let(T,_){return this.line(`let ${T} = ${_}`)}set(T,_){return this.line(`${T} = ${_}`)}if(T,_){return this.block(`if (${T})`,_)}elseIf(T,_){return this.block(`else if (${T})`,_)}else(T){return this.block("else",T)}for(T,_,F=0){return this.block(`for (let i = ${F}; ${T}; i++)`,_)}forIn(T,_){return this.block(`for (const k in ${T})`,_)}block(T,_,F=""){return this.line(`${T} {`),this.indent(),_(this),this.dedent(),this.line(`}${F}`)}return(T=""){return this.line(`return ${T}`)}write(T="anonymous",_=0){return`${T}(${this.argNames.join(", ")}) { ${_?this.body.split(`
|
|
16
16
|
`).map((F)=>" ".repeat(_)+`${F}`).join(`
|
|
17
|
-
`):this.body} }`}compile(){return new e8(...this.argNames,this.body)}}var i_=(T)=>T_(T,"object")||typeof T==="symbol"?
|
|
17
|
+
`):this.body} }`}compile(){return new e8(...this.argNames,this.body)}}var i_=(T)=>T_(T,"object")||typeof T==="symbol"?VT(T):NF(T),G4=(T,_=!1)=>{if(typeof T==="string"&&$0(T))return`${_?"?":""}.${T}`;return RJ(SA(T),_)},SA=(T)=>typeof T==="symbol"?VT(T):JSON.stringify(T),RJ=(T,_=!1)=>`${_?"?.":""}[${T}]`;class kF extends kW{traversalKind;optimistic;constructor(T){super("data","ctx");this.traversalKind=T.kind,this.optimistic=T.optimistic===!0}invoke(T,_){let F=_?.arg??this.data,W=typeof T==="string"?!0:this.requiresContextFor(T),J=typeof T==="string"?T:T.id;if(W)return`${this.referenceToId(J,_)}(${F}, ${this.ctx})`;return`${this.referenceToId(J,_)}(${F})`}referenceToId(T,_){let F=_?.kind??this.traversalKind,W=`this.${T}${F}`;return _?.bind?`${W}.bind(${_?.bind})`:W}requiresContextFor(T){return this.traversalKind==="Apply"||T.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(T,_,F){let W=this.requiresContextFor(F);if(W)this.line(`${this.ctx}.path.push(${T})`);if(this.check(F,{arg:_}),W)this.line(`${this.ctx}.path.pop()`);return this}check(T,_){return this.traversalKind==="Allows"?this.if(`!${this.invoke(T,_)}`,()=>this.return(!1)):this.line(this.invoke(T,_))}}var fW=(T)=>c(T,(_,F)=>[_,XT(F)?[...F]:F]),iT=B_("arkKind"),P=(T,_)=>T?.[iT]===_,OT=(T)=>P(T,"root")||P(T,"constraint");var EJ=["unit","proto","domain"],o0=["required","optional","index","sequence"],A4=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],PW=[...A4,...o0,"structure","predicate"],u0=["alias","union","morph","unit","intersection","proto","domain"],IA=[...u0,...PW],qW=c(PW,(T,_)=>[_,1]),zJ=c([...o0,"undeclared"],(T,_)=>[_,1]),KJ=c(IA,(T,_)=>[_,T]),c0=(T)=>typeof T==="string"&&(T in KJ);var d0=(T)=>KJ[T],jW=(T)=>u0.slice(d0(T)+1),_M=[...jW("union"),"alias"],FM=[...jW("morph"),"alias"],E_=(T)=>{if(typeof T==="string"||typeof T==="boolean"||T===null)return T;if(typeof T==="number"){if(Number.isNaN(T))return"NaN";if(T===Number.POSITIVE_INFINITY)return"Infinity";if(T===Number.NEGATIVE_INFINITY)return"-Infinity";return T}return i_(T)},Z0=(T)=>{let _="{ ";for(let[F,W]of Object.entries(T))_+=`${F}: ${i_(W)}, `;return _+" }"},l=(T)=>{let _=T;if(_.hasAssociatedError)_.defaults.expected??=(F)=>("description"in F)?F.description:_.defaults.description(F),_.defaults.actual??=(F)=>d(F),_.defaults.problem??=(F)=>`must be ${F.expected}${F.actual?` (was ${F.actual})`:""}`,_.defaults.message??=(F)=>{if(F.path.length===0)return F.problem;let W=`${F.propString} ${F.problem}`;if(W[0]==="[")return`value at ${W}`;return W};return _};class VJ extends Error{name="ToJsonSchemaError";code;context;constructor(T,_){super(d(_,{quoteKeys:!1,indent:4}));this.code=T,this.context=_}hasCode(T){return this.code===T}}var NA={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(T)=>RT.throw("arrayObject",T),arrayPostfix:(T)=>RT.throw("arrayPostfix",T),defaultValue:(T)=>RT.throw("defaultValue",T),domain:(T)=>RT.throw("domain",T),morph:(T)=>RT.throw("morph",T),patternIntersection:(T)=>RT.throw("patternIntersection",T),predicate:(T)=>RT.throw("predicate",T),proto:(T)=>RT.throw("proto",T),symbolKey:(T)=>RT.throw("symbolKey",T),unit:(T)=>RT.throw("unit",T),date:(T)=>RT.throw("date",T)}},RT={Error:VJ,throw:(...T)=>{throw new RT.Error(...T)},throwInternalOperandError:(T,_)=>e(`Unexpected JSON Schema input for ${T}: ${d(_)}`),defaultConfig:NA};z.config??={};var fF=(T,_)=>{if(!_)return T;let F={...T},W;for(W in _){let J={...T.keywords};if(W==="keywords"){for(let Y in _[W]){let $=_.keywords[Y];if($===void 0)continue;J[Y]=typeof $==="string"?{description:$}:$}F.keywords=J}else if(W==="toJsonSchema")F[W]=H4(T.toJsonSchema,_.toJsonSchema);else if(c0(W))F[W]={...T[W],..._[W]};else F[W]=_[W]}return F},H4=(T,_)=>{if(!T)return _??{};if(!_)return T;let F={...T},W;for(W in _)if(W==="fallback")F.fallback=CA(T.fallback,_.fallback);else F[W]=_[W];return F},CA=(T,_)=>{T=LJ(T),_=LJ(_);let F={},W;for(W in RT.defaultConfig.fallback)F[W]=_[W]??_.default??T[W]??T.default??RT.defaultConfig.fallback[W];return F},LJ=(T)=>typeof T==="function"?{default:T}:T??{};class X0 extends zF{[iT]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:T,relativePath:_,...F},W){super();this.input=F,this.ctx=W,t8(this,F);let J=W.data;if(F.code==="union")F.errors=F.errors.flatMap(($)=>{let Z=$.hasCode("union")?$.errors:[$];if(!T&&!_)return Z;return Z.map((G)=>G.transform((X)=>({...X,path:m8(T,X.path,_)})))});this.nodeConfig=W.config[this.code];let Y=[...F.path??W.path];if(_)Y.push(..._);if(T)Y.unshift(...T);this.path=new BF(...Y),this.data="data"in F?F.data:J}transform(T){return new X0(T({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(T){return this.code===T}get propString(){return t_(this.path)}get expected(){if(this.input.expected)return this.input.expected;let T=this.meta?.expected??this.nodeConfig.expected;return typeof T==="function"?T(this.input):T}get actual(){if(this.input.actual)return this.input.actual;let T=this.meta?.actual??this.nodeConfig.actual;return typeof T==="function"?T(this.data):T}get problem(){if(this.input.problem)return this.input.problem;let T=this.meta?.problem??this.nodeConfig.problem;return typeof T==="function"?T(this):T}get message(){if(this.input.message)return this.input.message;let T=this.meta?.message??this.nodeConfig.message;return typeof T==="function"?T(this):T}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 F_ extends NW{[iT]="errors";ctx;constructor(T){super();this.ctx=T}byPath=Object.create(null);get flatByPath(){return c(this.byPath,(T,_)=>[T,_.flat])}get flatProblemsByPath(){return c(this.byPath,(T,_)=>[T,_.flat.map((F)=>F.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new O4(this)}add(T){if(this.includes(T))return;this._add(T)}transform(T){let _=new F_(this.ctx);for(let F of this)_.add(T(F));return _}merge(T){for(let _ of T){if(this.includes(_))continue;this._add(new X0({..._,path:[...this.ctx.path,..._.path]},this.ctx))}}affectsPath(T){if(this.length===0)return!1;return T.stringifyAncestors().some((_)=>(_ in this.byPath))||T.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((T)=>T.toJSON())]}toString(){return this.join(`
|
|
18
18
|
`)}_add(T){let _=this.byPath[T.propString];if(_){if(_.hasCode("union")&&_.errors.length===0)return;let F=T.hasCode("union")&&T.errors.length===0?T:new X0({code:"intersection",errors:_.hasCode("intersection")?[..._.errors,T]:[_,T]},this.ctx),W=this.indexOf(_);this.mutable[W===-1?this.length:W]=F,this.byPath[T.propString]=F,this.addAncestorPaths(T)}else this.byPath[T.propString]=T,this.addAncestorPaths(T),this.mutable.push(T);this.count++}addAncestorPaths(T){for(let _ of T.path.stringifyAncestors())this.byAncestorPath[_]=s(this.byAncestorPath[_],T)}}class O4 extends Error{name="TraversalError";constructor(T){if(T.length===1)super(T.summary);else super(`
|
|
19
19
|
`+T.map((_)=>` \u2022 ${BA(_)}`).join(`
|
|
20
20
|
`));Object.defineProperty(this,"arkErrors",{value:T,enumerable:!1})}}var BA=(T)=>T.toString().split(`
|
|
21
21
|
`).join(`
|
|
22
|
-
`);class f_{path=[];errors=new F_(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(T,_){this.root=T,this.config=_}get data(){let T=this.root;for(let _ of this.path)T=T?.[_];return T}get propString(){return t_(this.path)}reject(T){return this.error(T),!1}mustBe(T){return this.error(T),!1}error(T){let _=typeof T==="object"?T.code?T:{...T,code:"predicate"}:{code:"predicate",expected:T};return this.errorFromContext(_)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(T){let _={path:new BF(...this.path),morphs:T};if(this.currentBranch)this.currentBranch.queuedMorphs.push(_);else this.queuedMorphs.push(_)}finalize(T){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return T?T(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(T){return this.errorFromContext(T)}errorFromContext(T){let _=new X0(T,this);if(this.currentBranch)this.currentBranch.error=_;else this.errors.add(_);return _}applyQueuedMorphs(){while(this.queuedMorphs.length){let T=this.queuedMorphs;this.queuedMorphs=[];for(let{path:_,morphs:F}of T){if(this.errors.affectsPath(_))continue;this.applyMorphsAtPath(_,F)}}}applyMorphsAtPath(T,_){let F=T.at(-1),W;if(F!==void 0){W=this.root;for(let J=0;J<T.length-1;J++)W=W[T[J]]}this.path=[...T];for(let J of _){let Y=OT(J),$=J(W===void 0?this.root:W[F],this);if($ instanceof X0){this.errors.add($);break}if($ instanceof F_){if(!Y)this.errors.merge($);break}if(W===void 0)this.root=$;else W[F]=$;this.applyQueuedMorphs()}}}var W_=(T,_,F)=>{if(!F)return _();F.path.push(T);let W=_();return F.path.pop(),W};class qF extends k_{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(T,_){super((W,J,Y=this.onFail)=>{if(J)return this.traverseApply(W,J),J.hasError()?J.errors:J.data;return this.rootApply(W,Y)},{attach:T});this.attachments=T,this.$=_,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((W,J)=>qA(W,J.shallowReferences),[this]);let F=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let W=0;W<this.children.length;W++){if(this.includesTransform||=this.children[W].includesTransform,this.includesContextualPredicate||=this.children[W].includesContextualPredicate,this.isCyclic||=this.children[W].isCyclic,!F){let J=this.children[W].flatRefs;for(let Y=0;Y<J.length;Y++){let $=J[Y];if(!this.flatRefs.some((Z)=>SJ(Z,$))){this.flatRefs.push($);for(let Z of $.node.branches)if(Z.hasKind("morph")||Z.hasKind("intersection")&&Z.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:$.path,propString:$.propString,node:Z})}}}Object.assign(this.referencesById,this.children[W].referencesById)}this.flatRefs.sort((W,J)=>W.path.length>J.path.length?1:W.path.length<J.path.length?-1:W.propString>J.propString?1:W.propString<J.propString?-1:W.node.expression<J.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((W)=>W.length===1||W.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((W)=>W.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(W)=>this.traverseAllows(W,new f_(W,this.$.resolvedConfig)):(W)=>this.traverseAllows(W)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(_,F)=>{if(this.allows(_))return _;let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"contextual":return(_,F)=>{let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let T=this.$.resolvedConfig.clone;return(_,F)=>{if(this.allows(_))return this.contextFreeMorph(T&&(typeof _==="object"&&_!==null||typeof _==="function")?T(_):_);let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,e(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=PA(this.metaJson);cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=d0(this.kind);precompilation;assert=(T,_)=>this(T,_,(F)=>F.throw());traverse(T,_){return this(T,_,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(T){if(!this.includesTransform)return this;let _={};for(let[F,W]of this.innerEntries){let J=this.impl.keys[F];if(J.reduceIo)J.reduceIo(T,_,W);else if(J.child){let Y=W;_[F]=XT(Y)?Y.map(($)=>$[T]):Y[T]}else _[F]=W}return this.$.node(this.kind,_)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(T){let _=OT(T)?T:this.$.parseDefinition(T);return this.innerHash===_.innerHash}ifEquals(T){return this.equals(T)?this:void 0}hasKind(T){return this.kind===T}assertHasKind(T){if(this.kind!==T)D0(`${this.kind} node was not of asserted kind ${T}`);return this}hasKindIn(...T){return T.includes(this.kind)}assertHasKindIn(...T){if(!u_(T,this.kind))D0(`${this.kind} node was not one of asserted kinds ${T}`);return this}isBasis(){return u_(EJ,this.kind)}isConstraint(){return u_(PW,this.kind)}isStructural(){return u_(o0,this.kind)}isRefinement(){return u_(A4,this.kind)}isRoot(){return u_(u0,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(T){return this.hasKind("unit")&&this.allows(T)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(T){let _=PF.normalize(T);return this._select(_)}_select(T){let _=PF.applyBoundary[T.boundary??"references"](this);if(T.kind)_=_.filter((F)=>F.kind===T.kind);if(T.where)_=_.filter(T.where);return PF.applyMethod[T.method??"filter"](_,this,T)}transform(T,_){return this._transform(T,this._createTransformContext(_))}_createTransformContext(T){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:T?.prereduced??!1},undeclaredKeyHandling:void 0,...T}}_transform(T,_){let F=_.bindScope??this.$;if(_.seen[this.id])return this.$.lazilyResolve(_.seen[this.id]);if(_.shouldTransform?.(this,_)===!1)return this;let W;if(_.seen[this.id]=()=>W,this.hasKind("structure")&&this.undeclared!==_.undeclaredKeyHandling)_={..._,undeclaredKeyHandling:this.undeclared};let J=c(this.inner,(X,O)=>{if(!this.impl.keys[X].child)return[X,O];let M=O;if(!XT(M)){let K=M._transform(T,_);return K?[X,K]:[]}if(M.length===0)return[X,O];let Q=M.flatMap((K)=>{return K._transform(T,_)??[]});return Q.length?[X,Q]:[]});delete _.seen[this.id];let Y=Object.assign(J,{meta:this.meta}),$=_.selected&&!_.selected.includes(this)?Y:T(this.kind,Y,_);if($===null)return null;if(OT($))return W=$;let Z=Object.keys($);if((Z.length===0||Z.length===1&&Z[0]==="meta")&&!h_(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in $))return _.undeclaredKeyHandling?{...$,value:z.intrinsic.unknown}:null;if(this.kind==="morph")$.in??=z.intrinsic.unknown;return W=F.node(this.kind,$,_.parseOptions)}configureReferences(T,_="references"){let F=PF.normalize(_),W=typeof T==="string"?(Z,G)=>({...G,meta:{...G.meta,description:T}}):typeof T==="function"?(Z,G)=>({...G,meta:T(G.meta)}):(Z,G)=>({...G,meta:{...G.meta,...T}});if(F.boundary==="self")return this.$.node(this.kind,W(this.kind,{...this.inner,meta:this.meta}));let J=this._select(F),Y=J&&W0(J),$=F.boundary==="child"?(Z,G)=>G.root.children.includes(Z):F.boundary==="shallow"?(Z)=>Z.kind!=="structure":()=>!0;return this.$.finalize(this.transform(W,{shouldTransform:$,selected:Y}))}}var PF={applyBoundary:{self:(T)=>[T],child:(T)=>[...T.children],shallow:(T)=>[...T.shallowReferences],references:(T)=>[...T.references]},applyMethod:{filter:(T)=>T,assertFilter:(T,_,F)=>{if(T.length===0)D0(DJ(_,F));return T},find:(T)=>T[0],assertFind:(T,_,F)=>{if(T.length===0)D0(DJ(_,F));return T[0]}},normalize:(T)=>typeof T==="function"?{boundary:"references",method:"filter",where:T}:typeof T==="string"?qT(T,PF.applyBoundary)?{method:"filter",boundary:T}:{boundary:"references",method:"filter",kind:T}:{boundary:"references",method:"filter",...T}},DJ=(T,_)=>`${T} had no references matching ${d(_)}.`,kA=(T)=>t_(T,{stringifyNonKey:(_)=>_.expression}),fA=/"(\$ark\.[^"]+)"/g,PA=(T)=>JSON.stringify(T).replaceAll(fA,"$1"),P_=(T,_)=>({path:T,node:_,propString:kA(T)}),SJ=(T,_)=>T.propString===_.propString&&T.node.equals(_.node),U4=(T,_)=>b_(T,_,{isEqual:SJ}),qA=(T,_)=>b_(T,_,{isEqual:(F,W)=>F.equals(W)});class N extends Array{static init(T,_,F,W){return new N({kind:T,l:_,r:F,path:W?.path??[],optional:W?.optional??!1})}add(T,_,F,W){return this.push({kind:T,l:_,r:F,path:W?.path??[],optional:W?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:T,l:_,r:F}=this[0],W=t_(T);return w4(`Intersection${W&&` at ${W}`} of ${IJ(_,F)}`)}return`The following intersections result in unsatisfiable types:
|
|
22
|
+
`);class f_{path=[];errors=new F_(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(T,_){this.root=T,this.config=_}get data(){let T=this.root;for(let _ of this.path)T=T?.[_];return T}get propString(){return t_(this.path)}reject(T){return this.error(T),!1}mustBe(T){return this.error(T),!1}error(T){let _=typeof T==="object"?T.code?T:{...T,code:"predicate"}:{code:"predicate",expected:T};return this.errorFromContext(_)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(T){let _={path:new BF(...this.path),morphs:T};if(this.currentBranch)this.currentBranch.queuedMorphs.push(_);else this.queuedMorphs.push(_)}finalize(T){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return T?T(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(T){return this.errorFromContext(T)}errorFromContext(T){let _=new X0(T,this);if(this.currentBranch)this.currentBranch.error=_;else this.errors.add(_);return _}applyQueuedMorphs(){while(this.queuedMorphs.length){let T=this.queuedMorphs;this.queuedMorphs=[];for(let{path:_,morphs:F}of T){if(this.errors.affectsPath(_))continue;this.applyMorphsAtPath(_,F)}}}applyMorphsAtPath(T,_){let F=T.at(-1),W;if(F!==void 0){W=this.root;for(let J=0;J<T.length-1;J++)W=W[T[J]]}this.path=[...T];for(let J of _){let Y=OT(J),$=J(W===void 0?this.root:W[F],this);if($ instanceof X0){this.errors.add($);break}if($ instanceof F_){if(!Y)this.errors.merge($);break}if(W===void 0)this.root=$;else W[F]=$;this.applyQueuedMorphs()}}}var W_=(T,_,F)=>{if(!F)return _();F.path.push(T);let W=_();return F.path.pop(),W};class qF extends k_{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(T,_){super((W,J,Y=this.onFail)=>{if(J)return this.traverseApply(W,J),J.hasError()?J.errors:J.data;return this.rootApply(W,Y)},{attach:T});this.attachments=T,this.$=_,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((W,J)=>qA(W,J.shallowReferences),[this]);let F=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let W=0;W<this.children.length;W++){if(this.includesTransform||=this.children[W].includesTransform,this.includesContextualPredicate||=this.children[W].includesContextualPredicate,this.isCyclic||=this.children[W].isCyclic,!F){let J=this.children[W].flatRefs;for(let Y=0;Y<J.length;Y++){let $=J[Y];if(!this.flatRefs.some((Z)=>SJ(Z,$))){this.flatRefs.push($);for(let Z of $.node.branches)if(Z.hasKind("morph")||Z.hasKind("intersection")&&Z.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:$.path,propString:$.propString,node:Z})}}}Object.assign(this.referencesById,this.children[W].referencesById)}this.flatRefs.sort((W,J)=>W.path.length>J.path.length?1:W.path.length<J.path.length?-1:W.propString>J.propString?1:W.propString<J.propString?-1:W.node.expression<J.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((W)=>W.length===1||W.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((W)=>W.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(W)=>this.traverseAllows(W,new f_(W,this.$.resolvedConfig)):(W)=>this.traverseAllows(W)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(_,F)=>{if(this.allows(_))return _;let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"contextual":return(_,F)=>{let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let T=this.$.resolvedConfig.clone;return(_,F)=>{if(this.allows(_))return this.contextFreeMorph(T&&(typeof _==="object"&&_!==null||typeof _==="function")?T(_):_);let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,e(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=PA(this.metaJson);cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=d0(this.kind);precompilation;assert=(T,_)=>this(T,_,(F)=>F.throw());traverse(T,_){return this(T,_,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(T){if(!this.includesTransform)return this;let _={};for(let[F,W]of this.innerEntries){let J=this.impl.keys[F];if(J.reduceIo)J.reduceIo(T,_,W);else if(J.child){let Y=W;_[F]=XT(Y)?Y.map(($)=>$[T]):Y[T]}else _[F]=W}return this.$.node(this.kind,_)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(T){let _=OT(T)?T:this.$.parseDefinition(T);return this.innerHash===_.innerHash}ifEquals(T){return this.equals(T)?this:void 0}hasKind(T){return this.kind===T}assertHasKind(T){if(this.kind!==T)D0(`${this.kind} node was not of asserted kind ${T}`);return this}hasKindIn(...T){return T.includes(this.kind)}assertHasKindIn(...T){if(!u_(T,this.kind))D0(`${this.kind} node was not one of asserted kinds ${T}`);return this}isBasis(){return u_(EJ,this.kind)}isConstraint(){return u_(PW,this.kind)}isStructural(){return u_(o0,this.kind)}isRefinement(){return u_(A4,this.kind)}isRoot(){return u_(u0,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(T){return this.hasKind("unit")&&this.allows(T)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(T){let _=PF.normalize(T);return this._select(_)}_select(T){let _=PF.applyBoundary[T.boundary??"references"](this);if(T.kind)_=_.filter((F)=>F.kind===T.kind);if(T.where)_=_.filter(T.where);return PF.applyMethod[T.method??"filter"](_,this,T)}transform(T,_){return this._transform(T,this._createTransformContext(_))}_createTransformContext(T){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:T?.prereduced??!1},undeclaredKeyHandling:void 0,...T}}_transform(T,_){let F=_.bindScope??this.$;if(_.seen[this.id])return this.$.lazilyResolve(_.seen[this.id]);if(_.shouldTransform?.(this,_)===!1)return this;let W;if(_.seen[this.id]=()=>W,this.hasKind("structure")&&this.undeclared!==_.undeclaredKeyHandling)_={..._,undeclaredKeyHandling:this.undeclared};let J=c(this.inner,(X,O)=>{if(!this.impl.keys[X].child)return[X,O];let M=O;if(!XT(M)){let V=M._transform(T,_);return V?[X,V]:[]}if(M.length===0)return[X,O];let Q=M.flatMap((V)=>{return V._transform(T,_)??[]});return Q.length?[X,Q]:[]});delete _.seen[this.id];let Y=Object.assign(J,{meta:this.meta}),$=_.selected&&!_.selected.includes(this)?Y:T(this.kind,Y,_);if($===null)return null;if(OT($))return W=$;let Z=Object.keys($);if((Z.length===0||Z.length===1&&Z[0]==="meta")&&!h_(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in $))return _.undeclaredKeyHandling?{...$,value:z.intrinsic.unknown}:null;if(this.kind==="morph")$.in??=z.intrinsic.unknown;return W=F.node(this.kind,$,_.parseOptions)}configureReferences(T,_="references"){let F=PF.normalize(_),W=typeof T==="string"?(Z,G)=>({...G,meta:{...G.meta,description:T}}):typeof T==="function"?(Z,G)=>({...G,meta:T(G.meta)}):(Z,G)=>({...G,meta:{...G.meta,...T}});if(F.boundary==="self")return this.$.node(this.kind,W(this.kind,{...this.inner,meta:this.meta}));let J=this._select(F),Y=J&&W0(J),$=F.boundary==="child"?(Z,G)=>G.root.children.includes(Z):F.boundary==="shallow"?(Z)=>Z.kind!=="structure":()=>!0;return this.$.finalize(this.transform(W,{shouldTransform:$,selected:Y}))}}var PF={applyBoundary:{self:(T)=>[T],child:(T)=>[...T.children],shallow:(T)=>[...T.shallowReferences],references:(T)=>[...T.references]},applyMethod:{filter:(T)=>T,assertFilter:(T,_,F)=>{if(T.length===0)D0(DJ(_,F));return T},find:(T)=>T[0],assertFind:(T,_,F)=>{if(T.length===0)D0(DJ(_,F));return T[0]}},normalize:(T)=>typeof T==="function"?{boundary:"references",method:"filter",where:T}:typeof T==="string"?qT(T,PF.applyBoundary)?{method:"filter",boundary:T}:{boundary:"references",method:"filter",kind:T}:{boundary:"references",method:"filter",...T}},DJ=(T,_)=>`${T} had no references matching ${d(_)}.`,kA=(T)=>t_(T,{stringifyNonKey:(_)=>_.expression}),fA=/"(\$ark\.[^"]+)"/g,PA=(T)=>JSON.stringify(T).replaceAll(fA,"$1"),P_=(T,_)=>({path:T,node:_,propString:kA(T)}),SJ=(T,_)=>T.propString===_.propString&&T.node.equals(_.node),U4=(T,_)=>b_(T,_,{isEqual:SJ}),qA=(T,_)=>b_(T,_,{isEqual:(F,W)=>F.equals(W)});class N extends Array{static init(T,_,F,W){return new N({kind:T,l:_,r:F,path:W?.path??[],optional:W?.optional??!1})}add(T,_,F,W){return this.push({kind:T,l:_,r:F,path:W?.path??[],optional:W?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:T,l:_,r:F}=this[0],W=t_(T);return w4(`Intersection${W&&` at ${W}`} of ${IJ(_,F)}`)}return`The following intersections result in unsatisfiable types:
|
|
23
23
|
\u2022 ${this.map(({path:T,l:_,r:F})=>`${T}: ${IJ(_,F)}`).join(`
|
|
24
|
-
\u2022 `)}`}throw(){return E(this.describeReasons())}invert(){let T=this.map((_)=>({..._,l:_.r,r:_.l}));if(!(T instanceof N))return new N(...T);return T}withPrefixKey(T,_){return this.map((F)=>({...F,path:[T,...F.path],optional:F.optional||_==="optional"}))}toNeverIfDisjoint(){return z.intrinsic.never}}var IJ=(T,_)=>`${M4(T)} and ${M4(_)}`,M4=(T)=>OT(T)?T.expression:XT(T)?T.map(M4).join(" | ")||"never":String(T),w4=(T)=>`${T} results in an unsatisfiable type`;var l0={},J_=(T,_,F)=>UT(T,_,{$:F,invert:!1,pipe:!1}),jF=(T,_,F)=>UT(T,_,{$:F,invert:!1,pipe:!0}),UT=(T,_,F)=>{let W=F.pipe?"|>":"&",J=`${T.hash}${W}${_.hash}`;if(l0[J]!==void 0)return l0[J];if(!F.pipe){let Z=`${_.hash}${W}${T.hash}`;if(l0[Z]!==void 0){let G=l0[Z],X=G instanceof N?G.invert():G;return l0[J]=X,X}}let Y=!F.pipe||!T.includesTransform&&!_.includesTransform;if(Y&&T.equals(_))return T;let $=Y?Q4(T,_,F):T.hasKindIn(...u0)?jA(T,_,F):Q4(T,_,F);if(OT($)){if(T.equals($))$=T;else if(_.equals($))$=_}return l0[J]=$,$},Q4=(T,_,F)=>{let W=T.precedence<_.precedence?T.kind:_.kind,J=T.impl.intersections[_.kind]??_.impl.intersections[T.kind];if(J===void 0)return null;else if(W===T.kind)return J(T,_,F);else{let Y=J(_,T,{...F,invert:!F.invert});if(Y instanceof N)Y=Y.invert();return Y}},jA=(T,_,F)=>T.includesTransform||_.includesTransform?F.invert?NJ(_,T,F):NJ(T,_,F):Q4(T,_,F),NJ=(T,_,F)=>T.distribute((W)=>yA(W,_,F),(W)=>{let J=W.filter(OT);if(J.length===0)return N.init("union",T.branches,_.branches);if(J.length<T.branches.length||!T.branches.every((Z,G)=>Z.in.equals(J[G].in)))return F.$.parseSchema(J);let Y;if(J.length===1){let Z=J[0];if(!Y)return Z;return F.$.node("morph",{...Z.inner,in:Z.in.configure(Y,"self")})}let $={branches:J};if(Y)$.meta=Y;return F.$.parseSchema($)}),yA=(T,_,F)=>{if(T.hasKind("morph")){let J=[...T.morphs];if(T.lastMorphIfNode){let Y=UT(T.lastMorphIfNode,_,F);if(Y instanceof N)return Y;J[J.length-1]=Y}else J.push(_);return F.$.node("morph",{morphs:J,in:T.inner.in})}if(_.hasKind("morph")){let J=UT(T,_.in,F);if(J instanceof N)return J;return F.$.node("morph",{morphs:[_],in:J})}return F.$.node("morph",{morphs:[_],in:T})};class z_ extends qF{constructor(T,_){super(T,_);Object.defineProperty(this,iT,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(T){return J_(this,T,this.$)}}class n_ extends z_{traverseApply=(T,_)=>{if(!this.traverseAllows(T,_))_.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Z0(this.errorContext)}}var cT=(T)=>(_,F)=>{if(XT(_)){if(_.length===0)return;let J=_.map((Y)=>F.$.node(T,Y));if(T==="predicate")return J;return J.sort((Y,$)=>Y.hash<$.hash?-1:1)}let W=F.$.node(T,_);return W.hasOpenIntersection()?[W]:W},t0=(T)=>{let _=T.r.shift();if(!_){let W=T.l.length===0&&T.kind==="structure"?z.intrinsic.unknown.internal:T.ctx.$.node(T.kind,Object.assign(T.baseInner,vA(T.l)),{prereduced:!0});for(let J of T.roots){if(W instanceof N)return W;W=UT(J,W,T.ctx)}return W}let F=!1;for(let W=0;W<T.l.length;W++){let J=UT(T.l[W],_,T.ctx);if(J===null)continue;if(J instanceof N)return J;if(!F){if(J.isRoot())return T.roots.push(J),T.l.splice(W),t0(T);T.l[W]=J,F=!0}else if(!T.l.includes(J))return e(`Unexpectedly encountered multiple distinct intersection results for refinement ${J}`)}if(!F)T.l.push(_);if(T.kind==="intersection"){if(_.impliedSiblings)for(let W of _.impliedSiblings)b_(T.r,W)}return t0(T)},i0=(T)=>{return Object.entries(T).flatMap(([F,W])=>(F in qW)?W:[]).sort((F,W)=>F.precedence<W.precedence?-1:F.precedence>W.precedence?1:F.kind==="predicate"&&W.kind==="predicate"?0:F.hash<W.hash?-1:1)},vA=(T)=>{let _={};for(let F of T)if(F.hasOpenIntersection())_[F.kind]=s(_[F.kind],F);else{if(_[F.kind])return e(`Unexpected intersection of closed refinements of kind ${F.kind}`);_[F.kind]=F}return _},CJ=(...T)=>E(BJ(...T)),BJ=(T,_,F)=>{let W=F.hasKind("morph")?"a morph":F.isUnknown()?"unknown":F.exclude(_).defaultShortDescription;return`${WJ(T)} operand must be ${_.description} (was ${W})`};var kJ=(T,_,F)=>new G0(T,_,F,F,null);class yW extends k_{}class G0 extends k_{[iT]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(T,_,F,W,J){super((...Y)=>{let $=c(this.names,(Z,G)=>{let X=this.arg$.parse(Y[Z]);if(!X.extends(this.constraints[Z]))E(xA(G,this.constraints[Z].expression,X.expression));return[G,X]});if(this.defIsLazy()){let Z=this.bodyDef($);return this.$.parse(Z)}return this.$.parse(_,{args:$})});this.paramDefs=T,this.bodyDef=_,this.$=F,this.arg$=W,this.hkt=J,this.description=J?new J().description??`a generic type for ${J.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof yW}cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get json(){return this.cacheGetter("json",{params:this.params.map((T)=>T[1].isUnknown()?T[0]:[T[0],T[1].json]),body:MJ(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((T)=>typeof T==="string"?[T,z.intrinsic.unknown]:[T[0],this.$.parse(T[1])]))}get names(){return this.cacheGetter("names",this.params.map((T)=>T[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((T)=>T[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var xA=(T,_,F)=>`${T} must be assignable to ${_} (was ${F})`;var bA=l({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(T)=>typeof T==="function"?{predicate:T}:T,defaults:{description:(T)=>`valid according to ${T.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class fJ extends z_{serializedPredicate=KT(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=Z0(this.errorContext);traverseApply=(T,_)=>{if(!this.predicate(T,_.external)&&!_.hasError())_.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows"){T.return(this.compiledCondition);return}T.if(`${this.compiledNegation} && !ctx.hasError()`,()=>T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(T,_){return _.fallback.predicate({code:"predicate",base:T,predicate:this.predicate})}}var R4={implementation:bA,Node:fJ};var hA=l({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(T)=>Number.isInteger(T)?T:E(pA(T))}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>T.rule===1?"an integer":T.rule===2?"even":`a multiple of ${T.rule}`},intersections:{divisor:(T,_,F)=>F.$.node("divisor",{rule:Math.abs(T.rule*_.rule/gA(T.rule,_.rule))})},obviatesBasisDescription:!0});class PJ extends n_{traverseAllows=(T)=>T%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=z.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(T){if(T.type="integer",this.rule===1)return T;return T.multipleOf=this.rule,T}}var E4={implementation:hA,Node:PJ};var pA=(T)=>`divisor must be an integer (was ${T})`,gA=(T,_)=>{let F,W=T,J=_;while(J!==0)F=J,J=W%J,W=F;return W};class U_ extends n_{boundOperandKind=cA[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=dA(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${mA[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?lA(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(T){return(this.limitKind==="upper"?this.numericLimit<T.numericLimit:this.numericLimit>T.numericLimit)||this.numericLimit===T.numericLimit&&this.exclusive===!0&&!T.exclusive}overlapsRange(T){if(this.isStricterThan(T))return!1;if(this.numericLimit===T.numericLimit&&(this.exclusive||T.exclusive))return!1;return!0}overlapIsUnit(T){return this.numericLimit===T.numericLimit&&!this.exclusive&&!T.exclusive}}var mA={"<":">=","<=":">",">":"<=",">=":"<"},oA={min:"max",minLength:"maxLength",after:"before"},vW={parse:(T)=>T||void 0},xW=(T)=>(_)=>{if(typeof _==="number")return{rule:_};let{exclusive:F,...W}=_;return F?{...W,rule:T==="minLength"?W.rule+1:W.rule-1}:W},bW=(T)=>(_)=>{if(typeof _==="number"||typeof _==="string"||_ instanceof Date)return{rule:_};let{exclusive:F,...W}=_;if(!F)return W;let J=typeof W.rule==="number"?W.rule:typeof W.rule==="string"?new Date(W.rule).valueOf():W.rule.valueOf();return F?{...W,rule:T==="after"?J+1:J-1}:W},hW=(T)=>typeof T==="string"||typeof T==="number"?new Date(T):T,uA=(T,_)=>`${T} bound must be a positive integer (was ${_})`,n0=(T)=>(_)=>{if(!Number.isInteger(_)||_<0)E(uA(T,_));return _},cA={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},dA=(T,_)=>`${qT(T,oA)?">":"<"}${_?"":"="}`,lA=(T)=>typeof T==="string"?T:new Date(T).toLocaleString(),qJ=(T)=>`Bounded expression ${T} must be exactly one of number, string, Array, or Date`;var tA=l({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:hW,serialize:(T)=>T.toISOString()}},normalize:bW("after"),defaults:{description:(T)=>`${T.collapsibleLimitString} or later`,actual:C0},intersections:{after:(T,_)=>T.isStricterThan(_)?T:_}});class jJ extends U_{impliedBasis=z.intrinsic.Date.internal;collapsibleLimitString=C0(this.rule);traverseAllows=(T)=>T>=this.rule;reduceJsonSchema(T,_){return _.fallback.date({code:"date",base:T,after:this.rule})}}var z4={implementation:tA,Node:jJ};var iA=l({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:hW,serialize:(T)=>T.toISOString()}},normalize:bW("before"),defaults:{description:(T)=>`${T.collapsibleLimitString} or earlier`,actual:C0},intersections:{before:(T,_)=>T.isStricterThan(_)?T:_,after:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("unit",{unit:T.rule}):null:N.init("range",T,_)}});class yJ extends U_{collapsibleLimitString=C0(this.rule);traverseAllows=(T)=>T<=this.rule;impliedBasis=z.intrinsic.Date.internal;reduceJsonSchema(T,_){return _.fallback.date({code:"date",base:T,before:this.rule})}}var V4={implementation:iA,Node:yJ};var nA=l({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:n0("exactLength")}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>`exactly length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{exactLength:(T,_,F)=>N.init("unit",F.$.node("unit",{unit:T.rule}),F.$.node("unit",{unit:_.rule}),{path:["length"]}),minLength:(T,_)=>T.rule>=_.rule?T:N.init("range",T,_),maxLength:(T,_)=>T.rule<=_.rule?T:N.init("range",T,_)}});class vJ extends n_{traverseAllows=(T)=>T.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=z.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T.maxLength=this.rule,T;case"array":return T.minItems=this.rule,T.maxItems=this.rule,T;default:return RT.throwInternalOperandError("exactLength",T)}}}var K4={implementation:nA,Node:vJ};var rA=l({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:vW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"negative":"non-positive";return`${T.exclusive?"less than":"at most"} ${T.rule}`}},intersections:{max:(T,_)=>T.isStricterThan(_)?T:_,min:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("unit",{unit:T.rule}):null:N.init("range",T,_)},obviatesBasisDescription:!0});class xJ extends U_{impliedBasis=z.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T<this.rule:(T)=>T<=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMaximum=this.rule;else T.maximum=this.rule;return T}}var L4={implementation:rA,Node:xJ};var sA=l({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:n0("maxLength")}},reduce:(T,_)=>T.rule===0?_.node("exactLength",T):void 0,normalize:xW("maxLength"),defaults:{description:(T)=>`at most length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{maxLength:(T,_)=>T.isStricterThan(_)?T:_,minLength:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("exactLength",{rule:T.rule}):null:N.init("range",T,_)}});class bJ extends U_{impliedBasis=z.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length<=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.maxLength=this.rule,T;case"array":return T.maxItems=this.rule,T;default:return RT.throwInternalOperandError("maxLength",T)}}}var D4={implementation:sA,Node:bJ};var aA=l({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:vW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"positive":"non-negative";return`${T.exclusive?"more than":"at least"} ${T.rule}`}},intersections:{min:(T,_)=>T.isStricterThan(_)?T:_},obviatesBasisDescription:!0});class hJ extends U_{impliedBasis=z.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T>this.rule:(T)=>T>=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMinimum=this.rule;else T.minimum=this.rule;return T}}var S4={implementation:aA,Node:hJ};var eA=l({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:n0("minLength")}},reduce:(T)=>T.rule===0?z.intrinsic.unknown:void 0,normalize:xW("minLength"),defaults:{description:(T)=>T.rule===1?"non-empty":`at least length ${T.rule}`,actual:(T)=>T.length===0?"":`${T.length}`},intersections:{minLength:(T,_)=>T.isStricterThan(_)?T:_}});class pJ extends U_{impliedBasis=z.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length>=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T;case"array":return T.minItems=this.rule,T;default:return RT.throwInternalOperandError("minLength",T)}}}var I4={implementation:eA,Node:pJ};var gJ={min:S4.implementation,max:L4.implementation,minLength:I4.implementation,maxLength:D4.implementation,exactLength:K4.implementation,after:z4.implementation,before:V4.implementation},mJ={min:S4.Node,max:L4.Node,minLength:I4.Node,maxLength:D4.Node,exactLength:K4.Node,after:z4.Node,before:V4.Node};var TH=l({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(T)=>typeof T==="string"?{rule:T}:T instanceof RegExp?T.flags?{rule:T.source,flags:T.flags}:{rule:T.source}:T,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(T)=>`matched by ${T.rule}`},intersections:{pattern:()=>null}});class oJ extends n_{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=z.intrinsic.string.internal;reduceJsonSchema(T,_){if(T.pattern)return _.fallback.patternIntersection({code:"patternIntersection",base:T,pattern:this.rule});return T.pattern=this.rule,T}}var N4={implementation:TH,Node:oJ};var yF=(T,_)=>{let F=_H(T);if(_&&!_.includes(F))return E(`Root of kind ${F} should be one of ${_}`);return F},_H=(T)=>{if(P(T,"root"))return T.kind;if(typeof T==="string")return T[0]==="$"?"alias":(T in __)?"domain":"proto";if(typeof T==="function")return"proto";if(typeof T!=="object"||T===null)return E(uJ(T));if("morphs"in T)return"morph";if("branches"in T||XT(T))return"union";if("unit"in T)return"unit";if("reference"in T)return"alias";let _=Object.keys(T);if(_.length===0||_.some((F)=>(F in qW)))return"intersection";if("proto"in T)return"proto";if("domain"in T)return"domain";return E(uJ(T))},uJ=(T)=>`${d(T)} is not a valid type schema`,cJ={},FH=(T)=>XT(T)?T.map((_)=>_.collapsibleJson):T.collapsibleJson,nT={};z.nodesByRegisteredId=nT;var C4=(T)=>{return cJ[T]??=0,`${T}${++cJ[T]}`},B4=(T)=>{let _=r0[T.kind],F=_.applyConfig?.(T.def,T.$.resolvedConfig)??T.def,W={},{meta:J,...Y}=F,$=J===void 0?{}:typeof J==="string"?{description:J}:J,Z=s1(Y).sort(([X],[O])=>c0(X)?c0(O)?d0(X)-d0(O):1:c0(O)?-1:X<O?-1:1).filter(([X,O])=>{if(X.startsWith("meta.")){let M=X.slice(5);return $[M]=O,!1}return!0});for(let X of Z){let O=X[0],M=_.keys[O];if(!M)return E(`Key ${O} is not valid on ${T.kind} schema`);let Q=M.parse?M.parse(X[1],T):X[1];if(Q!==O_&&(Q!==void 0||M.preserveUndefined))W[O]=Q}if(_.reduce&&!T.prereduced){let X=_.reduce(W,T.$);if(X){if(X instanceof N)return X.throw();return WH(X,$)}}return k4({id:T.id,kind:T.kind,inner:W,meta:$,$:T.$})},k4=({id:T,kind:_,inner:F,meta:W,$:J,ignoreCache:Y})=>{let $=r0[_],Z=s1(F),G=[],X={};for(let[q,j]of Z){let y=$.keys[q],u=y.serialize??(y.child?FH:E_);if(X[q]=u(j),y.child===!0){let h=j;if(XT(h))G.push(...h);else G.push(h)}else if(typeof y.child==="function")G.push(...y.child(j))}if($.finalizeInnerJson)X=$.finalizeInnerJson(X);let O={...X},M={};if(!h_(W))M=c(W,(q,j)=>[q,q==="examples"?j:E_(j)]),O.meta=pW(M,"description",!0);X=pW(X,$.collapsibleKey,!1);let Q=JSON.stringify({kind:_,...X});O=pW(O,$.collapsibleKey,!1);let K=pW(O,$.collapsibleKey,!0),B=JSON.stringify({kind:_,...O});if(J.nodesByHash[B]&&!Y)return J.nodesByHash[B];let V={id:T,kind:_,impl:$,inner:F,innerEntries:Z,innerJson:X,innerHash:Q,meta:W,metaJson:M,json:O,hash:B,collapsibleJson:K,children:G};if(_!=="intersection"){for(let q in F)if(q!=="in"&&q!=="out")V[q]=F[q]}let v=new lJ[_](V,J);return J.nodesByHash[B]=v},dJ=(T,_)=>{if(T.id===_)return T;if(OT(nT[_]))e(`Unexpected attempt to overwrite node id ${_}`);return k4({id:_,kind:T.kind,inner:T.inner,meta:T.meta,$:T.$,ignoreCache:!0})},WH=(T,_,F)=>{if(F&&OT(nT[F]))e(`Unexpected attempt to overwrite node id ${F}`);return k4({id:F??C4(_.alias??T.kind),kind:T.kind,inner:T.inner,meta:_,$:T.$})},pW=(T,_,F)=>{let W=Object.keys(T);if(W.length===1&&W[0]===_){let J=T[_];if(F)return J;if(T_(J,"object")&&(Object.keys(J).length===1||Array.isArray(J)))return J}return T};var vF=(T,_,F)=>{if(T.key!==_.key)return null;let W=T.key,J=UT(T.value,_.value,F),Y=T.required||_.required?"required":"optional";if(J instanceof N)if(Y==="optional")J=z.intrinsic.never.internal;else return J.withPrefixKey(T.key,T.required&&_.required?"required":"optional");if(Y==="required")return F.$.node("required",{key:W,value:J});let $=T.hasDefault()?_.hasDefault()?T.default===_.default?T.default:E(f4(T.default,_.default)):T.default:_.hasDefault()?_.default:O_;return F.$.node("optional",{key:W,value:J,default:$})};class xF extends z_{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=z.intrinsic.object.internal;serializedKey=i_(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=s(this.value.flatRefs.map((T)=>P_([this.key,...T.path],T.node)),P_([this.key],this.value));_transform(T,_){_.path.push(this.key);let F=super._transform(T,_);return _.path.pop(),F}hasDefault(){return"default"in this.inner}traverseAllows=(T,_)=>{if(this.key in T)return W_(this.key,()=>this.value.traverseAllows(T[this.key],_),_);return this.optional};traverseApply=(T,_)=>{if(this.key in T)W_(this.key,()=>this.value.traverseApply(T[this.key],_),_);else if(this.hasKind("required"))_.errorFromNodeContext(this.errorContext)};compile(T){if(T.if(`${this.serializedKey} in data`,()=>T.traverseKey(this.serializedKey,`data${T.prop(this.key)}`,this.value)),this.hasKind("required"))T.else(()=>T.traversalKind==="Apply"?T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):T.return(!1));if(T.traversalKind==="Allows")T.return(!0)}}var f4=(T,_)=>`Invalid intersection of default values ${d(T)} & ${d(_)}`;var JH=l({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)},default:{preserveUndefined:!0}},normalize:(T)=>T,reduce:(T,_)=>{if(_.resolvedConfig.exactOptionalPropertyTypes===!1){if(!T.value.allows(void 0))return _.node("optional",{...T,value:T.value.or(x.undefined)},{prereduced:!0})}},defaults:{description:(T)=>`${T.compiledKey}?: ${T.value.description}`},intersections:{optional:vF}});class tJ extends xF{constructor(...T){super(...T);if("default"in this.inner)hF(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:T,..._}=this.inner;return this.cacheGetter("outProp",this.$.node("required",_,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${d(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=$H(this);defaultValueMorphRef=this.defaultValueMorph&&KT(this.defaultValueMorph)}var bF={implementation:JH,Node:tJ},YH={},$H=(T)=>{if(!T.hasDefault())return;let _=`{${T.compiledKey}: ${T.value.id} = ${E_(T.default)}}`;return YH[_]??=P4(T.key,T.value,T.default)},P4=(T,_,F)=>{if(typeof F==="function")return _.includesTransform?(J,Y)=>{return W_(T,()=>_(J[T]=F(),Y),Y),J}:(J)=>{return J[T]=F(),J};let W=_.includesTransform?_.assert(F):F;return T_(W,"object")?(J,Y)=>{return W_(T,()=>_(J[T]=F,Y),Y),J}:(J)=>{return J[T]=W,J}},hF=(T,_,F)=>{let W=J0(_);if(T_(_,"object")&&!W)E(ZH(F));let J=T.in(W?_():_);if(J instanceof F_){if(F===null)E(`Default ${J.summary}`);let Y=J.transform(($)=>$.transform((Z)=>({...Z,prefixPath:[F]})));E(`Default for ${Y.summary}`)}return _},ZH=(T)=>{return`Non-primitive default ${T===null?"":typeof T==="number"?`for value at [${T}] `:`for ${i_(T)} `}must be specified as a function like () => ({my: 'object'})`};class V_ extends qF{constructor(T,_){super(T,_);Object.defineProperty(this,iT,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(T)=>{let _=this(T);if(_ instanceof F_)return _;return{value:_}}}}as(){return this}brand(T){if(T==="")return E(XH);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(T,_){let F=this.branches.map(T);return _?.(F)??F}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(T={}){let _=H4(this.$.resolvedConfig.toJsonSchema,T);_.useRefs||=this.isCyclic;let F=typeof _.dialect==="string"?{$schema:_.dialect}:{};if(Object.assign(F,this.toJsonSchemaRecurse(_)),_.useRefs)F.$defs=c(this.references,(W,J)=>J.isRoot()&&!J.alwaysExpandJsonSchema?[J.id,J.toResolvedJsonSchema(_)]:[]);return F}toJsonSchemaRecurse(T){if(T.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(T)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(T){let _=this.innerToJsonSchema(T);return Object.assign(_,this.metaJson)}intersect(T){let _=this.$.parseDefinition(T),F=this.rawIntersect(_);if(F instanceof N)return F;return this.$.finalize(F)}rawIntersect(T){return J_(this,T,this.$)}toNeverIfDisjoint(){return this}and(T){let _=this.intersect(T);return _ instanceof N?_.throw():_}rawAnd(T){let _=this.rawIntersect(T);return _ instanceof N?_.throw():_}or(T){let _=this.$.parseDefinition(T);return this.$.finalize(this.rawOr(_))}rawOr(T){let _=[...this.branches,...T.branches];return this.$.node("union",_)}map(T){return this.$.schema(this.applyStructuralOperation("map",[T]))}pick(...T){return this.$.schema(this.applyStructuralOperation("pick",T))}omit(...T){return this.$.schema(this.applyStructuralOperation("omit",T))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.applyStructuralOperation("keyof",[]).reduce((_,F)=>_.intersect(F).toNeverIfDisjoint(),z.intrinsic.unknown.internal);if(T.branches.length===0)E(w4(`keyof ${this.expression}`));return this._keyof=this.$.finalize(T)}get props(){if(this.branches.length!==1)return E(GH(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(T){let _=this.$.parseDefinition(T);return this.$.schema(_.distribute((F)=>this.applyStructuralOperation("merge",[iJ(F)??E(nJ("merge",F.expression))])))}applyStructuralOperation(T,_){return this.distribute((F)=>{if(F.equals(z.intrinsic.object)&&T!=="merge")return F;let W=iJ(F);if(!W)E(nJ(T,F.expression));if(T==="keyof")return W.keyof();if(T==="get")return W.get(..._);if(T==="props")return W.props;let J=T==="required"?"require":T==="partial"?"optionalize":T;return this.$.node("intersection",{...F.inner,structure:W[J](..._)})})}get(...T){if(T[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",T))}extract(T){let _=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>F.extends(_)))}exclude(T){let _=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>!F.extends(_)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(T){return!(this.intersect(T)instanceof N)}extends(T){let _=this.intersect(T);return!(_ instanceof N)&&this.equals(_)}ifExtends(T){return this.extends(T)?this:void 0}subsumes(T){return this.$.parseDefinition(T).extends(this)}configure(T,_="shallow"){return this.configureReferences(T,_)}describe(T,_="shallow"){return this.configure({description:T},_)}optional(){return[this,"?"]}default(T){return hF(this,T,null),[this,"=",T]}from(T){return this.assert(T)}_pipe(...T){let _=T.reduce((F,W)=>F.rawPipeOnce(W),this);return this.$.finalize(_)}tryPipe(...T){let _=T.reduce((F,W)=>F.rawPipeOnce(P(W,"root")?W:(J,Y)=>{try{return W(J,Y)}catch($){return Y.error({code:"predicate",predicate:W,actual:`aborted due to error:
|
|
24
|
+
\u2022 `)}`}throw(){return E(this.describeReasons())}invert(){let T=this.map((_)=>({..._,l:_.r,r:_.l}));if(!(T instanceof N))return new N(...T);return T}withPrefixKey(T,_){return this.map((F)=>({...F,path:[T,...F.path],optional:F.optional||_==="optional"}))}toNeverIfDisjoint(){return z.intrinsic.never}}var IJ=(T,_)=>`${M4(T)} and ${M4(_)}`,M4=(T)=>OT(T)?T.expression:XT(T)?T.map(M4).join(" | ")||"never":String(T),w4=(T)=>`${T} results in an unsatisfiable type`;var l0={},J_=(T,_,F)=>UT(T,_,{$:F,invert:!1,pipe:!1}),jF=(T,_,F)=>UT(T,_,{$:F,invert:!1,pipe:!0}),UT=(T,_,F)=>{let W=F.pipe?"|>":"&",J=`${T.hash}${W}${_.hash}`;if(l0[J]!==void 0)return l0[J];if(!F.pipe){let Z=`${_.hash}${W}${T.hash}`;if(l0[Z]!==void 0){let G=l0[Z],X=G instanceof N?G.invert():G;return l0[J]=X,X}}let Y=!F.pipe||!T.includesTransform&&!_.includesTransform;if(Y&&T.equals(_))return T;let $=Y?Q4(T,_,F):T.hasKindIn(...u0)?jA(T,_,F):Q4(T,_,F);if(OT($)){if(T.equals($))$=T;else if(_.equals($))$=_}return l0[J]=$,$},Q4=(T,_,F)=>{let W=T.precedence<_.precedence?T.kind:_.kind,J=T.impl.intersections[_.kind]??_.impl.intersections[T.kind];if(J===void 0)return null;else if(W===T.kind)return J(T,_,F);else{let Y=J(_,T,{...F,invert:!F.invert});if(Y instanceof N)Y=Y.invert();return Y}},jA=(T,_,F)=>T.includesTransform||_.includesTransform?F.invert?NJ(_,T,F):NJ(T,_,F):Q4(T,_,F),NJ=(T,_,F)=>T.distribute((W)=>yA(W,_,F),(W)=>{let J=W.filter(OT);if(J.length===0)return N.init("union",T.branches,_.branches);if(J.length<T.branches.length||!T.branches.every((Z,G)=>Z.in.equals(J[G].in)))return F.$.parseSchema(J);let Y;if(J.length===1){let Z=J[0];if(!Y)return Z;return F.$.node("morph",{...Z.inner,in:Z.in.configure(Y,"self")})}let $={branches:J};if(Y)$.meta=Y;return F.$.parseSchema($)}),yA=(T,_,F)=>{if(T.hasKind("morph")){let J=[...T.morphs];if(T.lastMorphIfNode){let Y=UT(T.lastMorphIfNode,_,F);if(Y instanceof N)return Y;J[J.length-1]=Y}else J.push(_);return F.$.node("morph",{morphs:J,in:T.inner.in})}if(_.hasKind("morph")){let J=UT(T,_.in,F);if(J instanceof N)return J;return F.$.node("morph",{morphs:[_],in:J})}return F.$.node("morph",{morphs:[_],in:T})};class z_ extends qF{constructor(T,_){super(T,_);Object.defineProperty(this,iT,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(T){return J_(this,T,this.$)}}class n_ extends z_{traverseApply=(T,_)=>{if(!this.traverseAllows(T,_))_.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Z0(this.errorContext)}}var cT=(T)=>(_,F)=>{if(XT(_)){if(_.length===0)return;let J=_.map((Y)=>F.$.node(T,Y));if(T==="predicate")return J;return J.sort((Y,$)=>Y.hash<$.hash?-1:1)}let W=F.$.node(T,_);return W.hasOpenIntersection()?[W]:W},t0=(T)=>{let _=T.r.shift();if(!_){let W=T.l.length===0&&T.kind==="structure"?z.intrinsic.unknown.internal:T.ctx.$.node(T.kind,Object.assign(T.baseInner,vA(T.l)),{prereduced:!0});for(let J of T.roots){if(W instanceof N)return W;W=UT(J,W,T.ctx)}return W}let F=!1;for(let W=0;W<T.l.length;W++){let J=UT(T.l[W],_,T.ctx);if(J===null)continue;if(J instanceof N)return J;if(!F){if(J.isRoot())return T.roots.push(J),T.l.splice(W),t0(T);T.l[W]=J,F=!0}else if(!T.l.includes(J))return e(`Unexpectedly encountered multiple distinct intersection results for refinement ${J}`)}if(!F)T.l.push(_);if(T.kind==="intersection"){if(_.impliedSiblings)for(let W of _.impliedSiblings)b_(T.r,W)}return t0(T)},i0=(T)=>{return Object.entries(T).flatMap(([F,W])=>(F in qW)?W:[]).sort((F,W)=>F.precedence<W.precedence?-1:F.precedence>W.precedence?1:F.kind==="predicate"&&W.kind==="predicate"?0:F.hash<W.hash?-1:1)},vA=(T)=>{let _={};for(let F of T)if(F.hasOpenIntersection())_[F.kind]=s(_[F.kind],F);else{if(_[F.kind])return e(`Unexpected intersection of closed refinements of kind ${F.kind}`);_[F.kind]=F}return _},CJ=(...T)=>E(BJ(...T)),BJ=(T,_,F)=>{let W=F.hasKind("morph")?"a morph":F.isUnknown()?"unknown":F.exclude(_).defaultShortDescription;return`${WJ(T)} operand must be ${_.description} (was ${W})`};var kJ=(T,_,F)=>new G0(T,_,F,F,null);class yW extends k_{}class G0 extends k_{[iT]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(T,_,F,W,J){super((...Y)=>{let $=c(this.names,(Z,G)=>{let X=this.arg$.parse(Y[Z]);if(!X.extends(this.constraints[Z]))E(xA(G,this.constraints[Z].expression,X.expression));return[G,X]});if(this.defIsLazy()){let Z=this.bodyDef($);return this.$.parse(Z)}return this.$.parse(_,{args:$})});this.paramDefs=T,this.bodyDef=_,this.$=F,this.arg$=W,this.hkt=J,this.description=J?new J().description??`a generic type for ${J.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof yW}cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get json(){return this.cacheGetter("json",{params:this.params.map((T)=>T[1].isUnknown()?T[0]:[T[0],T[1].json]),body:MJ(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((T)=>typeof T==="string"?[T,z.intrinsic.unknown]:[T[0],this.$.parse(T[1])]))}get names(){return this.cacheGetter("names",this.params.map((T)=>T[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((T)=>T[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var xA=(T,_,F)=>`${T} must be assignable to ${_} (was ${F})`;var bA=l({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(T)=>typeof T==="function"?{predicate:T}:T,defaults:{description:(T)=>`valid according to ${T.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class fJ extends z_{serializedPredicate=VT(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=Z0(this.errorContext);traverseApply=(T,_)=>{if(!this.predicate(T,_.external)&&!_.hasError())_.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows"){T.return(this.compiledCondition);return}T.if(`${this.compiledNegation} && !ctx.hasError()`,()=>T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(T,_){return _.fallback.predicate({code:"predicate",base:T,predicate:this.predicate})}}var R4={implementation:bA,Node:fJ};var hA=l({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(T)=>Number.isInteger(T)?T:E(pA(T))}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>T.rule===1?"an integer":T.rule===2?"even":`a multiple of ${T.rule}`},intersections:{divisor:(T,_,F)=>F.$.node("divisor",{rule:Math.abs(T.rule*_.rule/gA(T.rule,_.rule))})},obviatesBasisDescription:!0});class PJ extends n_{traverseAllows=(T)=>T%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=z.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(T){if(T.type="integer",this.rule===1)return T;return T.multipleOf=this.rule,T}}var E4={implementation:hA,Node:PJ};var pA=(T)=>`divisor must be an integer (was ${T})`,gA=(T,_)=>{let F,W=T,J=_;while(J!==0)F=J,J=W%J,W=F;return W};class U_ extends n_{boundOperandKind=cA[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=dA(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${mA[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?lA(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(T){return(this.limitKind==="upper"?this.numericLimit<T.numericLimit:this.numericLimit>T.numericLimit)||this.numericLimit===T.numericLimit&&this.exclusive===!0&&!T.exclusive}overlapsRange(T){if(this.isStricterThan(T))return!1;if(this.numericLimit===T.numericLimit&&(this.exclusive||T.exclusive))return!1;return!0}overlapIsUnit(T){return this.numericLimit===T.numericLimit&&!this.exclusive&&!T.exclusive}}var mA={"<":">=","<=":">",">":"<=",">=":"<"},oA={min:"max",minLength:"maxLength",after:"before"},vW={parse:(T)=>T||void 0},xW=(T)=>(_)=>{if(typeof _==="number")return{rule:_};let{exclusive:F,...W}=_;return F?{...W,rule:T==="minLength"?W.rule+1:W.rule-1}:W},bW=(T)=>(_)=>{if(typeof _==="number"||typeof _==="string"||_ instanceof Date)return{rule:_};let{exclusive:F,...W}=_;if(!F)return W;let J=typeof W.rule==="number"?W.rule:typeof W.rule==="string"?new Date(W.rule).valueOf():W.rule.valueOf();return F?{...W,rule:T==="after"?J+1:J-1}:W},hW=(T)=>typeof T==="string"||typeof T==="number"?new Date(T):T,uA=(T,_)=>`${T} bound must be a positive integer (was ${_})`,n0=(T)=>(_)=>{if(!Number.isInteger(_)||_<0)E(uA(T,_));return _},cA={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},dA=(T,_)=>`${qT(T,oA)?">":"<"}${_?"":"="}`,lA=(T)=>typeof T==="string"?T:new Date(T).toLocaleString(),qJ=(T)=>`Bounded expression ${T} must be exactly one of number, string, Array, or Date`;var tA=l({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:hW,serialize:(T)=>T.toISOString()}},normalize:bW("after"),defaults:{description:(T)=>`${T.collapsibleLimitString} or later`,actual:C0},intersections:{after:(T,_)=>T.isStricterThan(_)?T:_}});class jJ extends U_{impliedBasis=z.intrinsic.Date.internal;collapsibleLimitString=C0(this.rule);traverseAllows=(T)=>T>=this.rule;reduceJsonSchema(T,_){return _.fallback.date({code:"date",base:T,after:this.rule})}}var z4={implementation:tA,Node:jJ};var iA=l({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:hW,serialize:(T)=>T.toISOString()}},normalize:bW("before"),defaults:{description:(T)=>`${T.collapsibleLimitString} or earlier`,actual:C0},intersections:{before:(T,_)=>T.isStricterThan(_)?T:_,after:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("unit",{unit:T.rule}):null:N.init("range",T,_)}});class yJ extends U_{collapsibleLimitString=C0(this.rule);traverseAllows=(T)=>T<=this.rule;impliedBasis=z.intrinsic.Date.internal;reduceJsonSchema(T,_){return _.fallback.date({code:"date",base:T,before:this.rule})}}var K4={implementation:iA,Node:yJ};var nA=l({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:n0("exactLength")}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>`exactly length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{exactLength:(T,_,F)=>N.init("unit",F.$.node("unit",{unit:T.rule}),F.$.node("unit",{unit:_.rule}),{path:["length"]}),minLength:(T,_)=>T.rule>=_.rule?T:N.init("range",T,_),maxLength:(T,_)=>T.rule<=_.rule?T:N.init("range",T,_)}});class vJ extends n_{traverseAllows=(T)=>T.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=z.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T.maxLength=this.rule,T;case"array":return T.minItems=this.rule,T.maxItems=this.rule,T;default:return RT.throwInternalOperandError("exactLength",T)}}}var V4={implementation:nA,Node:vJ};var rA=l({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:vW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"negative":"non-positive";return`${T.exclusive?"less than":"at most"} ${T.rule}`}},intersections:{max:(T,_)=>T.isStricterThan(_)?T:_,min:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("unit",{unit:T.rule}):null:N.init("range",T,_)},obviatesBasisDescription:!0});class xJ extends U_{impliedBasis=z.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T<this.rule:(T)=>T<=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMaximum=this.rule;else T.maximum=this.rule;return T}}var L4={implementation:rA,Node:xJ};var sA=l({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:n0("maxLength")}},reduce:(T,_)=>T.rule===0?_.node("exactLength",T):void 0,normalize:xW("maxLength"),defaults:{description:(T)=>`at most length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{maxLength:(T,_)=>T.isStricterThan(_)?T:_,minLength:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("exactLength",{rule:T.rule}):null:N.init("range",T,_)}});class bJ extends U_{impliedBasis=z.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length<=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.maxLength=this.rule,T;case"array":return T.maxItems=this.rule,T;default:return RT.throwInternalOperandError("maxLength",T)}}}var D4={implementation:sA,Node:bJ};var aA=l({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:vW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"positive":"non-negative";return`${T.exclusive?"more than":"at least"} ${T.rule}`}},intersections:{min:(T,_)=>T.isStricterThan(_)?T:_},obviatesBasisDescription:!0});class hJ extends U_{impliedBasis=z.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T>this.rule:(T)=>T>=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMinimum=this.rule;else T.minimum=this.rule;return T}}var S4={implementation:aA,Node:hJ};var eA=l({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:n0("minLength")}},reduce:(T)=>T.rule===0?z.intrinsic.unknown:void 0,normalize:xW("minLength"),defaults:{description:(T)=>T.rule===1?"non-empty":`at least length ${T.rule}`,actual:(T)=>T.length===0?"":`${T.length}`},intersections:{minLength:(T,_)=>T.isStricterThan(_)?T:_}});class pJ extends U_{impliedBasis=z.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length>=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T;case"array":return T.minItems=this.rule,T;default:return RT.throwInternalOperandError("minLength",T)}}}var I4={implementation:eA,Node:pJ};var gJ={min:S4.implementation,max:L4.implementation,minLength:I4.implementation,maxLength:D4.implementation,exactLength:V4.implementation,after:z4.implementation,before:K4.implementation},mJ={min:S4.Node,max:L4.Node,minLength:I4.Node,maxLength:D4.Node,exactLength:V4.Node,after:z4.Node,before:K4.Node};var TH=l({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(T)=>typeof T==="string"?{rule:T}:T instanceof RegExp?T.flags?{rule:T.source,flags:T.flags}:{rule:T.source}:T,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(T)=>`matched by ${T.rule}`},intersections:{pattern:()=>null}});class oJ extends n_{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=z.intrinsic.string.internal;reduceJsonSchema(T,_){if(T.pattern)return _.fallback.patternIntersection({code:"patternIntersection",base:T,pattern:this.rule});return T.pattern=this.rule,T}}var N4={implementation:TH,Node:oJ};var yF=(T,_)=>{let F=_H(T);if(_&&!_.includes(F))return E(`Root of kind ${F} should be one of ${_}`);return F},_H=(T)=>{if(P(T,"root"))return T.kind;if(typeof T==="string")return T[0]==="$"?"alias":(T in __)?"domain":"proto";if(typeof T==="function")return"proto";if(typeof T!=="object"||T===null)return E(uJ(T));if("morphs"in T)return"morph";if("branches"in T||XT(T))return"union";if("unit"in T)return"unit";if("reference"in T)return"alias";let _=Object.keys(T);if(_.length===0||_.some((F)=>(F in qW)))return"intersection";if("proto"in T)return"proto";if("domain"in T)return"domain";return E(uJ(T))},uJ=(T)=>`${d(T)} is not a valid type schema`,cJ={},FH=(T)=>XT(T)?T.map((_)=>_.collapsibleJson):T.collapsibleJson,nT={};z.nodesByRegisteredId=nT;var C4=(T)=>{return cJ[T]??=0,`${T}${++cJ[T]}`},B4=(T)=>{let _=r0[T.kind],F=_.applyConfig?.(T.def,T.$.resolvedConfig)??T.def,W={},{meta:J,...Y}=F,$=J===void 0?{}:typeof J==="string"?{description:J}:J,Z=s1(Y).sort(([X],[O])=>c0(X)?c0(O)?d0(X)-d0(O):1:c0(O)?-1:X<O?-1:1).filter(([X,O])=>{if(X.startsWith("meta.")){let M=X.slice(5);return $[M]=O,!1}return!0});for(let X of Z){let O=X[0],M=_.keys[O];if(!M)return E(`Key ${O} is not valid on ${T.kind} schema`);let Q=M.parse?M.parse(X[1],T):X[1];if(Q!==O_&&(Q!==void 0||M.preserveUndefined))W[O]=Q}if(_.reduce&&!T.prereduced){let X=_.reduce(W,T.$);if(X){if(X instanceof N)return X.throw();return WH(X,$)}}return k4({id:T.id,kind:T.kind,inner:W,meta:$,$:T.$})},k4=({id:T,kind:_,inner:F,meta:W,$:J,ignoreCache:Y})=>{let $=r0[_],Z=s1(F),G=[],X={};for(let[q,j]of Z){let y=$.keys[q],u=y.serialize??(y.child?FH:E_);if(X[q]=u(j),y.child===!0){let h=j;if(XT(h))G.push(...h);else G.push(h)}else if(typeof y.child==="function")G.push(...y.child(j))}if($.finalizeInnerJson)X=$.finalizeInnerJson(X);let O={...X},M={};if(!h_(W))M=c(W,(q,j)=>[q,q==="examples"?j:E_(j)]),O.meta=pW(M,"description",!0);X=pW(X,$.collapsibleKey,!1);let Q=JSON.stringify({kind:_,...X});O=pW(O,$.collapsibleKey,!1);let V=pW(O,$.collapsibleKey,!0),B=JSON.stringify({kind:_,...O});if(J.nodesByHash[B]&&!Y)return J.nodesByHash[B];let K={id:T,kind:_,impl:$,inner:F,innerEntries:Z,innerJson:X,innerHash:Q,meta:W,metaJson:M,json:O,hash:B,collapsibleJson:V,children:G};if(_!=="intersection"){for(let q in F)if(q!=="in"&&q!=="out")K[q]=F[q]}let v=new lJ[_](K,J);return J.nodesByHash[B]=v},dJ=(T,_)=>{if(T.id===_)return T;if(OT(nT[_]))e(`Unexpected attempt to overwrite node id ${_}`);return k4({id:_,kind:T.kind,inner:T.inner,meta:T.meta,$:T.$,ignoreCache:!0})},WH=(T,_,F)=>{if(F&&OT(nT[F]))e(`Unexpected attempt to overwrite node id ${F}`);return k4({id:F??C4(_.alias??T.kind),kind:T.kind,inner:T.inner,meta:_,$:T.$})},pW=(T,_,F)=>{let W=Object.keys(T);if(W.length===1&&W[0]===_){let J=T[_];if(F)return J;if(T_(J,"object")&&(Object.keys(J).length===1||Array.isArray(J)))return J}return T};var vF=(T,_,F)=>{if(T.key!==_.key)return null;let W=T.key,J=UT(T.value,_.value,F),Y=T.required||_.required?"required":"optional";if(J instanceof N)if(Y==="optional")J=z.intrinsic.never.internal;else return J.withPrefixKey(T.key,T.required&&_.required?"required":"optional");if(Y==="required")return F.$.node("required",{key:W,value:J});let $=T.hasDefault()?_.hasDefault()?T.default===_.default?T.default:E(f4(T.default,_.default)):T.default:_.hasDefault()?_.default:O_;return F.$.node("optional",{key:W,value:J,default:$})};class xF extends z_{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=z.intrinsic.object.internal;serializedKey=i_(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=s(this.value.flatRefs.map((T)=>P_([this.key,...T.path],T.node)),P_([this.key],this.value));_transform(T,_){_.path.push(this.key);let F=super._transform(T,_);return _.path.pop(),F}hasDefault(){return"default"in this.inner}traverseAllows=(T,_)=>{if(this.key in T)return W_(this.key,()=>this.value.traverseAllows(T[this.key],_),_);return this.optional};traverseApply=(T,_)=>{if(this.key in T)W_(this.key,()=>this.value.traverseApply(T[this.key],_),_);else if(this.hasKind("required"))_.errorFromNodeContext(this.errorContext)};compile(T){if(T.if(`${this.serializedKey} in data`,()=>T.traverseKey(this.serializedKey,`data${T.prop(this.key)}`,this.value)),this.hasKind("required"))T.else(()=>T.traversalKind==="Apply"?T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):T.return(!1));if(T.traversalKind==="Allows")T.return(!0)}}var f4=(T,_)=>`Invalid intersection of default values ${d(T)} & ${d(_)}`;var JH=l({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)},default:{preserveUndefined:!0}},normalize:(T)=>T,reduce:(T,_)=>{if(_.resolvedConfig.exactOptionalPropertyTypes===!1){if(!T.value.allows(void 0))return _.node("optional",{...T,value:T.value.or(x.undefined)},{prereduced:!0})}},defaults:{description:(T)=>`${T.compiledKey}?: ${T.value.description}`},intersections:{optional:vF}});class tJ extends xF{constructor(...T){super(...T);if("default"in this.inner)hF(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:T,..._}=this.inner;return this.cacheGetter("outProp",this.$.node("required",_,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${d(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=$H(this);defaultValueMorphRef=this.defaultValueMorph&&VT(this.defaultValueMorph)}var bF={implementation:JH,Node:tJ},YH={},$H=(T)=>{if(!T.hasDefault())return;let _=`{${T.compiledKey}: ${T.value.id} = ${E_(T.default)}}`;return YH[_]??=P4(T.key,T.value,T.default)},P4=(T,_,F)=>{if(typeof F==="function")return _.includesTransform?(J,Y)=>{return W_(T,()=>_(J[T]=F(),Y),Y),J}:(J)=>{return J[T]=F(),J};let W=_.includesTransform?_.assert(F):F;return T_(W,"object")?(J,Y)=>{return W_(T,()=>_(J[T]=F,Y),Y),J}:(J)=>{return J[T]=W,J}},hF=(T,_,F)=>{let W=J0(_);if(T_(_,"object")&&!W)E(ZH(F));let J=T.in(W?_():_);if(J instanceof F_){if(F===null)E(`Default ${J.summary}`);let Y=J.transform(($)=>$.transform((Z)=>({...Z,prefixPath:[F]})));E(`Default for ${Y.summary}`)}return _},ZH=(T)=>{return`Non-primitive default ${T===null?"":typeof T==="number"?`for value at [${T}] `:`for ${i_(T)} `}must be specified as a function like () => ({my: 'object'})`};class K_ extends qF{constructor(T,_){super(T,_);Object.defineProperty(this,iT,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(T)=>{let _=this(T);if(_ instanceof F_)return _;return{value:_}}}}as(){return this}brand(T){if(T==="")return E(XH);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(T,_){let F=this.branches.map(T);return _?.(F)??F}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(T={}){let _=H4(this.$.resolvedConfig.toJsonSchema,T);_.useRefs||=this.isCyclic;let F=typeof _.dialect==="string"?{$schema:_.dialect}:{};if(Object.assign(F,this.toJsonSchemaRecurse(_)),_.useRefs)F.$defs=c(this.references,(W,J)=>J.isRoot()&&!J.alwaysExpandJsonSchema?[J.id,J.toResolvedJsonSchema(_)]:[]);return F}toJsonSchemaRecurse(T){if(T.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(T)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(T){let _=this.innerToJsonSchema(T);return Object.assign(_,this.metaJson)}intersect(T){let _=this.$.parseDefinition(T),F=this.rawIntersect(_);if(F instanceof N)return F;return this.$.finalize(F)}rawIntersect(T){return J_(this,T,this.$)}toNeverIfDisjoint(){return this}and(T){let _=this.intersect(T);return _ instanceof N?_.throw():_}rawAnd(T){let _=this.rawIntersect(T);return _ instanceof N?_.throw():_}or(T){let _=this.$.parseDefinition(T);return this.$.finalize(this.rawOr(_))}rawOr(T){let _=[...this.branches,...T.branches];return this.$.node("union",_)}map(T){return this.$.schema(this.applyStructuralOperation("map",[T]))}pick(...T){return this.$.schema(this.applyStructuralOperation("pick",T))}omit(...T){return this.$.schema(this.applyStructuralOperation("omit",T))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.applyStructuralOperation("keyof",[]).reduce((_,F)=>_.intersect(F).toNeverIfDisjoint(),z.intrinsic.unknown.internal);if(T.branches.length===0)E(w4(`keyof ${this.expression}`));return this._keyof=this.$.finalize(T)}get props(){if(this.branches.length!==1)return E(GH(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(T){let _=this.$.parseDefinition(T);return this.$.schema(_.distribute((F)=>this.applyStructuralOperation("merge",[iJ(F)??E(nJ("merge",F.expression))])))}applyStructuralOperation(T,_){return this.distribute((F)=>{if(F.equals(z.intrinsic.object)&&T!=="merge")return F;let W=iJ(F);if(!W)E(nJ(T,F.expression));if(T==="keyof")return W.keyof();if(T==="get")return W.get(..._);if(T==="props")return W.props;let J=T==="required"?"require":T==="partial"?"optionalize":T;return this.$.node("intersection",{...F.inner,structure:W[J](..._)})})}get(...T){if(T[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",T))}extract(T){let _=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>F.extends(_)))}exclude(T){let _=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>!F.extends(_)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(T){return!(this.intersect(T)instanceof N)}extends(T){let _=this.intersect(T);return!(_ instanceof N)&&this.equals(_)}ifExtends(T){return this.extends(T)?this:void 0}subsumes(T){return this.$.parseDefinition(T).extends(this)}configure(T,_="shallow"){return this.configureReferences(T,_)}describe(T,_="shallow"){return this.configure({description:T},_)}optional(){return[this,"?"]}default(T){return hF(this,T,null),[this,"=",T]}from(T){return this.assert(T)}_pipe(...T){let _=T.reduce((F,W)=>F.rawPipeOnce(W),this);return this.$.finalize(_)}tryPipe(...T){let _=T.reduce((F,W)=>F.rawPipeOnce(P(W,"root")?W:(J,Y)=>{try{return W(J,Y)}catch($){return Y.error({code:"predicate",predicate:W,actual:`aborted due to error:
|
|
25
25
|
${$}
|
|
26
26
|
`})}}),this);return this.$.finalize(_)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(T){return this.$.finalize(this.toNode(this.$.parseDefinition(T)))}toNode(T){let _=jF(this,T,this.$);if(_ instanceof N)return _.throw();return _}rawPipeOnce(T){if(P(T,"root"))return this.toNode(T);return this.distribute((_)=>_.hasKind("morph")?this.$.node("morph",{in:_.inner.in,morphs:[..._.morphs,T]}):this.$.node("morph",{in:_,morphs:[T]}),this.$.parseSchema)}narrow(T){return this.constrainOut("predicate",T)}constrain(T,_){return this._constrain("root",T,_)}constrainIn(T,_){return this._constrain("in",T,_)}constrainOut(T,_){return this._constrain("out",T,_)}_constrain(T,_,F){let W=this.$.node(_,F);if(W.isRoot())return W.isUnknown()?this:e(`Unexpected constraint node ${W}`);let J=T==="root"?this:this[T];if(J.hasKind("morph")||W.impliedBasis&&!J.extends(W.impliedBasis))return CJ(_,W.impliedBasis,this);let Y=this.$.node("intersection",{[W.kind]:W}),$=T==="out"?jF(this,Y,this.$):J_(this,Y,this.$);if($ instanceof N)$.throw();return this.$.finalize($)}onUndeclaredKey(T){let _=typeof T==="string"?T:T.rule,F=typeof T==="string"?!1:T.deep;return this.$.finalize(this.transform((W,J)=>W==="structure"?_==="ignore"?l8(J,{undeclared:1}):{...J,undeclared:_}:J,F?void 0:{shouldTransform:(W)=>!u_(o0,W.kind)}))}hasEqualMorphs(T){if(!this.includesTransform&&!T.includesTransform)return!0;if(!d_(this.shallowMorphs,T.shallowMorphs))return!1;if(!d_(this.flatMorphs,T.flatMorphs,{isEqual:(_,F)=>_.propString===F.propString&&(_.node.hasKind("morph")&&F.node.hasKind("morph")?_.node.hasEqualMorphs(F.node):_.node.hasKind("intersection")&&F.node.hasKind("intersection")?_.node.structure?.structuralMorphRef===F.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(T){return this.onUndeclaredKey({rule:T,deep:!0})}filter(T){return this.constrainIn("predicate",T)}divisibleBy(T){return this.constrain("divisor",T)}matching(T){return this.constrain("pattern",T)}atLeast(T){return this.constrain("min",T)}atMost(T){return this.constrain("max",T)}moreThan(T){return this.constrain("min",s0(T))}lessThan(T){return this.constrain("max",s0(T))}atLeastLength(T){return this.constrain("minLength",T)}atMostLength(T){return this.constrain("maxLength",T)}moreThanLength(T){return this.constrain("minLength",s0(T))}lessThanLength(T){return this.constrain("maxLength",s0(T))}exactlyLength(T){return this.constrain("exactLength",T)}atOrAfter(T){return this.constrain("after",T)}atOrBefore(T){return this.constrain("before",T)}laterThan(T){return this.constrain("after",s0(T))}earlierThan(T){return this.constrain("before",s0(T))}}var XH="Expected a non-empty brand name after #",s0=(T)=>typeof T==="object"&&!(T instanceof Date)?{...T,exclusive:!0}:{rule:T,exclusive:!0},pF=(T,_)=>P(_,"root")?P(T,"root")?T.extends(_):_.allows(T):P(T,"root")?T.hasUnit(_):_===T,iJ=(T)=>{if(T.hasKind("morph"))return null;if(T.hasKind("intersection"))return T.inner.structure??(T.basis?.domain==="object"?T.$.bindReference(z.intrinsic.emptyStructure):null);if(T.isBasis()&&T.domain==="object")return T.$.bindReference(z.intrinsic.emptyStructure);return null},GH=(T)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
27
|
-
${T}`,nJ=(T,_)=>`${T} operand must be an object (was ${_})`;var p_=(T,_)=>c(jW(T),(F,W)=>[W,_]);var AH=(T)=>typeof T==="string"?{reference:T}:T,rJ=(T)=>T instanceof N?z.intrinsic.never.internal:T,HH=l({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(T)=>T.startsWith("$")?T:`$ark.${T}`},resolve:{}},normalize:AH,defaults:{description:(T)=>T.reference},intersections:{alias:(T,_,F)=>F.$.lazilyResolve(()=>rJ(UT(T.resolution,_.resolution,F)),`${T.reference}${F.pipe?"=>":"&"}${_.reference}`),...p_("alias",(T,_,F)=>{if(_.isUnknown())return T;if(_.isNever())return _;if(_.isBasis()&&!_.overlaps(z.intrinsic.object))return N.init("assignability",z.intrinsic.object,_);return F.$.lazilyResolve(()=>rJ(UT(T.resolution,_,F)),`${T.reference}${F.pipe?"=>":"&"}${_.id}`)})}});class sJ extends
|
|
27
|
+
${T}`,nJ=(T,_)=>`${T} operand must be an object (was ${_})`;var p_=(T,_)=>c(jW(T),(F,W)=>[W,_]);var AH=(T)=>typeof T==="string"?{reference:T}:T,rJ=(T)=>T instanceof N?z.intrinsic.never.internal:T,HH=l({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(T)=>T.startsWith("$")?T:`$ark.${T}`},resolve:{}},normalize:AH,defaults:{description:(T)=>T.reference},intersections:{alias:(T,_,F)=>F.$.lazilyResolve(()=>rJ(UT(T.resolution,_.resolution,F)),`${T.reference}${F.pipe?"=>":"&"}${_.reference}`),...p_("alias",(T,_,F)=>{if(_.isUnknown())return T;if(_.isNever())return _;if(_.isBasis()&&!_.overlaps(z.intrinsic.object))return N.init("assignability",z.intrinsic.object,_);return F.$.lazilyResolve(()=>rJ(UT(T.resolution,_,F)),`${T.reference}${F.pipe?"=>":"&"}${_.id}`)})}});class sJ extends K_{expression=this.reference;structure=void 0;get resolution(){let T=this._resolve();return nT[this.id]=T}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let T=this.reference,_=nT[T],F=[];while(P(_,"context")){if(F.includes(_.id))return E(OH(_.id,F));F.push(_.id),_=nT[_.id]}if(!P(_,"root"))return e(`Unexpected resolution for reference ${this.reference}
|
|
28
28
|
Seen: [${F.join("->")}]
|
|
29
|
-
Resolution: ${d(_)}`);return _}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let T=this.reference.slice(1),_=this.$.resolutions[T];if(typeof _==="string")return _;if(P(_,"root"))return _.id;return e(`Unexpected resolution for reference ${this.reference}: ${d(_)}`)}get defaultShortDescription(){return __.object}innerToJsonSchema(T){return this.resolution.toJsonSchemaRecurse(T)}traverseAllows=(T,_)=>{let F=_.seen[this.reference];if(F?.includes(T))return!0;return _.seen[this.reference]=s(F,T),this.resolution.traverseAllows(T,_)};traverseApply=(T,_)=>{let F=_.seen[this.reference];if(F?.includes(T))return;_.seen[this.reference]=s(F,T),this.resolution.traverseApply(T,_)};compile(T){let _=this.resolutionId;T.if(`ctx.seen.${_} && ctx.seen.${_}.includes(data)`,()=>T.return(!0)),T.if(`!ctx.seen.${_}`,()=>T.line(`ctx.seen.${_} = []`)),T.line(`ctx.seen.${_}.push(data)`),T.return(T.invoke(_))}}var OH=(T,_)=>`Alias '${T}' has a shallow resolution cycle: ${[..._,T].join("->")}`,gF={implementation:HH,Node:sJ};class B0 extends
|
|
29
|
+
Resolution: ${d(_)}`);return _}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let T=this.reference.slice(1),_=this.$.resolutions[T];if(typeof _==="string")return _;if(P(_,"root"))return _.id;return e(`Unexpected resolution for reference ${this.reference}: ${d(_)}`)}get defaultShortDescription(){return __.object}innerToJsonSchema(T){return this.resolution.toJsonSchemaRecurse(T)}traverseAllows=(T,_)=>{let F=_.seen[this.reference];if(F?.includes(T))return!0;return _.seen[this.reference]=s(F,T),this.resolution.traverseAllows(T,_)};traverseApply=(T,_)=>{let F=_.seen[this.reference];if(F?.includes(T))return;_.seen[this.reference]=s(F,T),this.resolution.traverseApply(T,_)};compile(T){let _=this.resolutionId;T.if(`ctx.seen.${_} && ctx.seen.${_}.includes(data)`,()=>T.return(!0)),T.if(`!ctx.seen.${_}`,()=>T.line(`ctx.seen.${_} = []`)),T.line(`ctx.seen.${_}.push(data)`),T.return(T.invoke(_))}}var OH=(T,_)=>`Alias '${T}' has a shallow resolution cycle: ${[..._,T].join("->")}`,gF={implementation:HH,Node:sJ};class B0 extends K_{traverseApply=(T,_)=>{if(!this.traverseAllows(T,_))_.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Z0(this.errorContext)}compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var UH=l({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(T)=>typeof T==="string"?{domain:T}:g0(T,"numberAllowsNaN")&&T.domain!=="number"?E(gW.writeBadAllowNanMessage(T.domain)):T,applyConfig:(T,_)=>T.numberAllowsNaN===void 0&&T.domain==="number"&&_.numberAllowsNaN?{...T,numberAllowsNaN:!0}:T,defaults:{description:(T)=>__[T.domain],actual:(T)=>Number.isNaN(T)?"NaN":__[PT(T)]},intersections:{domain:(T,_)=>T.domain==="number"&&_.domain==="number"?T.numberAllowsNaN?_:T:N.init("domain",T,_)}});class aJ extends B0{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(T)=>typeof T==="number"&&!Number.isNaN(T):(T)=>PT(T)===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 __[this.domain]}innerToJsonSchema(T){if(this.domain==="bigint"||this.domain==="symbol")return T.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var gW={implementation:UH,Node:aJ,writeBadAllowNanMessage:(T)=>`numberAllowsNaN may only be specified with domain "number" (was ${T})`};var MH=l({kind:"intersection",hasAssociatedError:!0,normalize:(T)=>{if(OT(T))return T;let{structure:_,...F}=T,W=!!_,J=_??{},Y=c(F,($,Z)=>{if(qT($,zJ)){if(W)E(`Flattened structure key ${$} cannot be specified alongside a root 'structure' key.`);return J[$]=Z,[]}return[$,Z]});if(P(J,"constraint")||!h_(J))Y.structure=J;return Y},finalizeInnerJson:({structure:T,..._})=>T_(T,"object")?{...T,..._}:_,keys:{domain:{child:!0,parse:(T,_)=>_.$.node("domain",T)},proto:{child:!0,parse:(T,_)=>_.$.node("proto",T)},structure:{child:!0,parse:(T,_)=>_.$.node("structure",T),serialize:(T)=>{if(!T.sequence?.minLength)return T.collapsibleJson;let{sequence:_,...F}=T.collapsibleJson,{minVariadicLength:W,...J}=_,Y=J.variadic&&Object.keys(J).length===1?J.variadic:J;return{...F,sequence:Y}}},divisor:{child:!0,parse:cT("divisor")},max:{child:!0,parse:cT("max")},min:{child:!0,parse:cT("min")},maxLength:{child:!0,parse:cT("maxLength")},minLength:{child:!0,parse:cT("minLength")},exactLength:{child:!0,parse:cT("exactLength")},before:{child:!0,parse:cT("before")},after:{child:!0,parse:cT("after")},pattern:{child:!0,parse:cT("pattern")},predicate:{child:!0,parse:cT("predicate")}},reduce:(T,_)=>eJ({},T,{$:_,invert:!1,pipe:!1}),defaults:{description:(T)=>{if(T.children.length===0)return"unknown";if(T.structure)return T.structure.description;let _=[];if(T.basis&&!T.refinements.some((F)=>F.impl.obviatesBasisDescription))_.push(T.basis.description);if(T.refinements.length){let F=T.refinements.toSorted((W,J)=>W.kind==="min"&&J.kind==="max"?-1:0).map((W)=>W.description);_.push(...F)}if(T.inner.predicate)_.push(...T.inner.predicate.map((F)=>F.description));return _.join(" and ")},expected:(T)=>` \u25E6 ${T.errors.map((_)=>_.expected).join(`
|
|
30
30
|
\u25E6 `)}`,problem:(T)=>`(${T.actual}) must be...
|
|
31
|
-
${T.expected}`},intersections:{intersection:(T,_,F)=>eJ(T.inner,_.inner,F),...p_("intersection",(T,_,F)=>{if(T.children.length===0)return _;let{domain:W,proto:J,...Y}=T.inner,$=J??W,Z=$?UT($,_,F):_;return Z instanceof N?Z:T?.basis?.equals(Z)?T:T.$.node("intersection",{...Y,[Z.kind]:Z},{prereduced:!0})})}});class T6 extends
|
|
31
|
+
${T.expected}`},intersections:{intersection:(T,_,F)=>eJ(T.inner,_.inner,F),...p_("intersection",(T,_,F)=>{if(T.children.length===0)return _;let{domain:W,proto:J,...Y}=T.inner,$=J??W,Z=$?UT($,_,F):_;return Z instanceof N?Z:T?.basis?.equals(Z)?T:T.$.node("intersection",{...Y,[Z.kind]:Z},{prereduced:!0})})}});class T6 extends K_{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((T)=>T.isRefinement());structure=this.inner.structure;expression=wH(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(T){return this.children.reduce((_,F)=>F.isBasis()?F.toJsonSchemaRecurse(T):F.reduceJsonSchema(_,T),{})}traverseAllows=(T,_)=>this.children.every((F)=>F.traverseAllows(T,_));traverseApply=(T,_)=>{let F=_.currentErrorCount;if(this.basis){if(this.basis.traverseApply(T,_),_.currentErrorCount>F)return}if(this.refinements.length){for(let W=0;W<this.refinements.length-1;W++)if(this.refinements[W].traverseApply(T,_),_.failFast&&_.currentErrorCount>F)return;if(this.refinements.at(-1).traverseApply(T,_),_.currentErrorCount>F)return}if(this.structure){if(this.structure.traverseApply(T,_),_.currentErrorCount>F)return}if(this.inner.predicate){for(let W=0;W<this.inner.predicate.length-1;W++)if(this.inner.predicate[W].traverseApply(T,_),_.failFast&&_.currentErrorCount>F)return;this.inner.predicate.at(-1).traverseApply(T,_)}};compile(T){if(T.traversalKind==="Allows"){for(let _ of this.children)T.check(_);T.return(!0);return}if(T.initializeErrorCount(),this.basis){if(T.check(this.basis),this.children.length>1)T.returnIfFail()}if(this.refinements.length){for(let _=0;_<this.refinements.length-1;_++)T.check(this.refinements[_]),T.returnIfFailFast();if(T.check(this.refinements.at(-1)),this.structure||this.inner.predicate)T.returnIfFail()}if(this.structure){if(T.check(this.structure),this.inner.predicate)T.returnIfFail()}if(this.inner.predicate){for(let _=0;_<this.inner.predicate.length-1;_++)T.check(this.inner.predicate[_]),T.returnIfFail();T.check(this.inner.predicate.at(-1))}}}var q4={implementation:MH,Node:T6},wH=(T)=>{let _=T.structure?.expression||`${T.basis&&!T.refinements.some((F)=>F.impl.obviatesBasisExpression)?T.basis.nestableExpression+" ":""}${T.refinements.map((F)=>F.expression).join(" & ")}`||"unknown";if(_==="Array == 0")_="[]";return _},eJ=(T,_,F)=>{let W={},J=T.proto??T.domain,Y=_.proto??_.domain,$=J?Y?UT(J,Y,F):J:Y;if($ instanceof N)return $;if($)W[$.kind]=$;return t0({kind:"intersection",baseInner:W,l:i0(T),r:i0(_),roots:[],ctx:F})};var QH=l({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(T,_)=>_.$.parseSchema(T)},morphs:{parse:W0,serialize:(T)=>T.map((_)=>P(_,"root")?_.json:VT(_))},declaredIn:{child:!1,serialize:(T)=>T.json},declaredOut:{child:!1,serialize:(T)=>T.json}},normalize:(T)=>T,defaults:{description:(T)=>`a morph from ${T.in.description} to ${T.out?.description??"unknown"}`},intersections:{morph:(T,_,F)=>{if(!T.hasEqualMorphs(_))return E(RH(T.expression,_.expression));let W=UT(T.in,_.in,F);if(W instanceof N)return W;let J={morphs:T.morphs};if(T.declaredIn||_.declaredIn){let Y=UT(T.in,_.in,F);if(Y instanceof N)return Y.throw();else J.declaredIn=Y}if(T.declaredOut||_.declaredOut){let Y=UT(T.out,_.out,F);if(Y instanceof N)return Y.throw();else J.declaredOut=Y}return W.distribute((Y)=>F.$.node("morph",{...J,in:Y}),F.$.parseSchema)},...p_("morph",(T,_,F)=>{let W=T.inner.in?UT(T.inner.in,_,F):_;return W instanceof N?W:W.equals(T.inner.in)?T:F.$.node("morph",{...T.inner,in:W})})}});class _6 extends K_{serializedMorphs=this.morphs.map(VT);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=P(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??z.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??z.intrinsic.unknown.internal}declareIn(T){return this.$.node("morph",{...this.inner,declaredIn:T})}declareOut(T){return this.$.node("morph",{...this.inner,declaredOut:T})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(T){return T.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(T),out:this.introspectableOut?.toJsonSchemaRecurse(T)??null})}compile(T){if(T.traversalKind==="Allows"){if(!this.introspectableIn)return;T.return(T.invoke(this.introspectableIn));return}if(this.introspectableIn)T.line(T.invoke(this.introspectableIn));T.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(T,_)=>!this.introspectableIn||this.introspectableIn.traverseAllows(T,_);traverseApply=(T,_)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(T,_);_.queueMorphs(this.morphs)};hasEqualMorphs(T){return d_(this.morphs,T.morphs,{isEqual:(_,F)=>_===F||P(_,"root")&&P(F,"root")&&_.equals(F)})}}var j4={implementation:QH,Node:_6},RH=(T,_)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
32
32
|
Left: ${T}
|
|
33
|
-
Right: ${_}`;var EH=l({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(T)=>LF(T)??E_(T)},dateAllowsInvalid:{}},normalize:(T)=>{let _=typeof T==="string"?{proto:I0[T]}:typeof T==="function"?OT(T)?T:{proto:T}:typeof T.proto==="string"?{...T,proto:I0[T.proto]}:T;if(typeof _.proto!=="function")E(mF.writeInvalidSchemaMessage(_.proto));if(g0(_,"dateAllowsInvalid")&&_.proto!==Date)E(mF.writeBadInvalidDateMessage(_.proto));return _},applyConfig:(T,_)=>{if(T.dateAllowsInvalid===void 0&&T.proto===Date&&_.dateAllowsInvalid)return{...T,dateAllowsInvalid:!0};return T},defaults:{description:(T)=>T.builtinName?r8[T.builtinName]:`an instance of ${T.proto.name}`,actual:(T)=>T instanceof Date&&T.toString()==="Invalid Date"?"an invalid Date":
|
|
33
|
+
Right: ${_}`;var EH=l({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(T)=>LF(T)??E_(T)},dateAllowsInvalid:{}},normalize:(T)=>{let _=typeof T==="string"?{proto:I0[T]}:typeof T==="function"?OT(T)?T:{proto:T}:typeof T.proto==="string"?{...T,proto:I0[T.proto]}:T;if(typeof _.proto!=="function")E(mF.writeInvalidSchemaMessage(_.proto));if(g0(_,"dateAllowsInvalid")&&_.proto!==Date)E(mF.writeBadInvalidDateMessage(_.proto));return _},applyConfig:(T,_)=>{if(T.dateAllowsInvalid===void 0&&T.proto===Date&&_.dateAllowsInvalid)return{...T,dateAllowsInvalid:!0};return T},defaults:{description:(T)=>T.builtinName?r8[T.builtinName]:`an instance of ${T.proto.name}`,actual:(T)=>T instanceof Date&&T.toString()==="Invalid Date"?"an invalid Date":VF(T)},intersections:{proto:(T,_)=>T.proto===Date&&_.proto===Date?T.dateAllowsInvalid?_:T:F4(T.proto,_.proto)?T:F4(_.proto,T.proto)?_:N.init("proto",T,_),domain:(T,_)=>_.domain==="object"?T:N.init("domain",z.intrinsic.object.internal,_)}});class F6 extends B0{builtinName=LF(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(T)=>T instanceof Date&&T.toString()!=="Invalid Date":(T)=>T instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(T){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return T.fallback.date?.({code:"date",base:{}})??T.fallback.proto({code:"proto",base:{},proto:this.proto});default:return T.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 mF={implementation:EH,Node:F6,writeBadInvalidDateMessage:(T)=>`dateAllowsInvalid may only be specified with constructor Date (was ${T.name})`,writeInvalidSchemaMessage:(T)=>`instanceOf operand must be a function (was ${PT(T)})`};var zH=l({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(T,_)=>{let F=[];for(let W of T){let J=P(W,"root")?W.branches:_.$.parseSchema(W).branches;for(let Y of J)if(Y.hasKind("morph")){let $=F.findIndex((Z)=>Z.hasKind("morph")&&Z.hasEqualMorphs(Y));if($===-1)F.push(Y);else{let Z=F[$];F[$]=_.$.node("morph",{...Z.inner,in:Z.in.rawOr(Y.in)})}}else F.push(Y)}if(!_.def.ordered)F.sort((W,J)=>W.hash<J.hash?-1:1);return F}}},normalize:(T)=>XT(T)?{branches:T}:T,reduce:(T,_)=>{let F=kH(T);if(F.length===1)return F[0];if(F.length===T.branches.length)return;return _.node("union",{...T,branches:F},{prereduced:!0})},defaults:{description:(T)=>T.distribute((_)=>_.description,a0),expected:(T)=>{let _=o8(T.errors,"propString"),F=Object.entries(_).map(([W,J])=>{let Y=[];for(let G of J)b_(Y,G.expected);let $=a0(Y),Z=J.every((G)=>G.actual===J[0].actual)?J[0].actual:d(J[0].data);return`${W&&`${W} `}must be ${$}${Z&&` (was ${Z})`}`});return a0(F)},problem:(T)=>T.expected,message:(T)=>T.problem},intersections:{union:(T,_,F)=>{if(T.isNever!==_.isNever)return N.init("presence",T,_);let W;if(T.ordered){if(_.ordered)E(PH(T.expression,_.expression));if(W=y4(_.branches,T.branches,F),W instanceof N)W.invert()}else W=y4(T.branches,_.branches,F);if(W instanceof N)return W;return F.$.parseSchema(T.ordered||_.ordered?{branches:W,ordered:!0}:{branches:W})},...p_("union",(T,_,F)=>{let W=y4(T.branches,[_],F);if(W instanceof N)return W;if(W.length===1)return W[0];return F.$.parseSchema(T.ordered?{branches:W,ordered:!0}:{branches:W})})}});class Y6 extends K_{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let T=[],_=-1;for(let F of this.branches){if(F.hasKind("unit")&&F.domain==="boolean"){if(_===-1)_=T.length,T.push(F);else T[_]=z.intrinsic.boolean;continue}T.push(F)}return T}unitBranches=this.branches.filter((T)=>T.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?NH(this.discriminant):null;expression=this.distribute((T)=>T.nestableExpression,BH);createBranchedOptimisticRootApply(){return(T,_)=>{let F=this.traverseOptimistic(T);if(F!==O_)return F;let W=new f_(T,this.$.resolvedConfig);return this.traverseApply(T,W),W.finalize(_)}}get shallowMorphs(){return this.branches.reduce((T,_)=>b_(T,_.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((T)=>T.defaultShortDescription,a0)}innerToJsonSchema(T){if(this.branchGroups.length===1&&this.branchGroups[0].equals(z.intrinsic.boolean))return{type:"boolean"};let _=this.branchGroups.map((F)=>F.toJsonSchemaRecurse(T));if(_.every((F)=>Object.keys(F).length===1&&g0(F,"const")))return{enum:_.map((F)=>F.const)};return{anyOf:_}}traverseAllows=(T,_)=>this.branches.some((F)=>F.traverseAllows(T,_));traverseApply=(T,_)=>{let F=[];for(let W=0;W<this.branches.length;W++){if(_.pushBranch(),this.branches[W].traverseApply(T,_),!_.hasError()){if(this.branches[W].includesTransform)return _.queuedMorphs.push(..._.popBranch().queuedMorphs);return _.popBranch()}F.push(_.popBranch().error)}_.errorFromNodeContext({code:"union",errors:F,meta:this.meta})};traverseOptimistic=(T)=>{for(let _=0;_<this.branches.length;_++){let F=this.branches[_];if(F.traverseAllows(T)){if(F.contextFreeMorph)return F.contextFreeMorph(T);return T}}return O_};compile(T){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(T);let _=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")_=`typeof ${_} === "object" ? ${_} === null ? "null" : "object" : typeof ${_} === "function" ? "object" : typeof ${_}`;let F=this.discriminant.cases,W=Object.keys(F),{optimistic:J}=T;if(T.optimistic=!1,T.block(`switch(${_})`,()=>{for(let X in F){let O=F[X],M=X==="default"?X:`case ${X}`;T.line(`${M}: return ${O===!0?J?T.data:O:J?`${T.invoke(O)} ? ${O.contextFreeMorph?`${VT(O.contextFreeMorph)}(${T.data})`:T.data} : "${O_}"`:T.invoke(O)}`)}return T}),T.traversalKind==="Allows"){T.return(J?`"${O_}"`:!1);return}let Y=a0(this.discriminant.kind==="domain"?W.map((X)=>{let O=X.slice(1,-1);return O==="function"?__.object:__[O]}):W),$=this.discriminant.path.map((X)=>typeof X==="symbol"?VT(X):JSON.stringify(X)),Z=JSON.stringify(Y),G=this.discriminant.kind==="domain"?`${SH}[${_}]`:`${IH}(${_})`;T.line(`ctx.errorFromNodeContext({
|
|
34
34
|
code: "predicate",
|
|
35
35
|
expected: ${Z},
|
|
36
36
|
actual: ${G},
|
|
37
37
|
relativePath: [${$}],
|
|
38
38
|
meta: ${this.compiledMeta}
|
|
39
|
-
})`)}compileIndiscriminable(T){if(T.traversalKind==="Apply"){T.const("errors","[]");for(let _ of this.branches)T.line("ctx.pushBranch()").line(T.invoke(_)).if("!ctx.hasError()",()=>T.return(_.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");T.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:_}=T;T.optimistic=!1;for(let F of this.branches)T.if(`${T.invoke(F)}`,()=>T.return(_?F.contextFreeMorph?`${
|
|
39
|
+
})`)}compileIndiscriminable(T){if(T.traversalKind==="Apply"){T.const("errors","[]");for(let _ of this.branches)T.line("ctx.pushBranch()").line(T.invoke(_)).if("!ctx.hasError()",()=>T.return(_.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");T.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:_}=T;T.optimistic=!1;for(let F of this.branches)T.if(`${T.invoke(F)}`,()=>T.return(_?F.contextFreeMorph?`${VT(F.contextFreeMorph)}(${T.data})`:T.data:!0));T.return(_?`"${O_}"`:!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 J=c(this.unitBranches,(Y,$)=>[`${$.in.serializedValue}`,$.hasKind("morph")?$:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:J}}let T=[];for(let J=0;J<this.branches.length-1;J++){let Y=this.branches[J];for(let $=J+1;$<this.branches.length;$++){let Z=this.branches[$],G=J_(Y.in,Z.in,Y.$);if(!(G instanceof N))continue;for(let X of G){if(!X.kind||X.optional)continue;let O,M;if(X.kind==="domain"){let{l:V,r:B}=X;O=`"${typeof V==="string"?V:V.domain}"`,M=`"${typeof B==="string"?B:B.domain}"`}else if(X.kind==="unit")O=X.l.serializedValue,M=X.r.serializedValue;else continue;let Q=T.find((V)=>d_(V.path,X.path)&&V.kind===X.kind);if(!Q)T.push({kind:X.kind,cases:{[O]:{branchIndices:[J],condition:X.l},[M]:{branchIndices:[$],condition:X.r}},path:X.path});else{if(Q.cases[O])Q.cases[O].branchIndices=b_(Q.cases[O].branchIndices,J);else Q.cases[O]??={branchIndices:[J],condition:X.l};if(Q.cases[M])Q.cases[M].branchIndices=b_(Q.cases[M].branchIndices,$);else Q.cases[M]??={branchIndices:[$],condition:X.r}}}}}let _=this.ordered?LH(T,this.branches):T;if(!_.length)return null;let F=KH(_,this),W={};for(let J in F.best.cases){let Y=VH(F,J);if(Y===null){W[J]=!0;continue}if(Y.length===this.branches.length)return null;if(this.ordered)Y.sort((G,X)=>G.originalIndex-X.originalIndex);let $=Y.map((G)=>G.branch),Z=$.length===1?$[0]:this.$.node("union",this.ordered?{branches:$,ordered:!0}:$);Object.assign(this.referencesById,Z.referencesById),W[J]=Z}if(F.defaultEntries.length){let J=F.defaultEntries.map((Y)=>Y.branch);W.default=this.$.node("union",this.ordered?{branches:J,ordered:!0}:J,{prereduced:!0}),Object.assign(this.referencesById,W.default.referencesById)}return Object.assign(F.location,{cases:W})}}var KH=(T,_)=>{let F=T.sort((Y,$)=>Object.keys($.cases).length-Object.keys(Y.cases).length)[0],W={kind:F.kind,path:F.path,optionallyChainedPropString:$6(F.path)},J=_.branches.map((Y,$)=>({originalIndex:$,branch:Y}));return{best:F,location:W,defaultEntries:J,node:_}},VH=(T,_)=>{let F=T.best.cases[_],W=DH(F.condition,T.location.path,T.node.$),J=[],Y=[];for(let $=0;$<T.defaultEntries.length;$++){let Z=T.defaultEntries[$];if(F.branchIndices.includes(Z.originalIndex)){let G=W6(T.node.branches[Z.originalIndex],T.location);if(G===null)J=null;else J?.push({originalIndex:Z.originalIndex,branch:G})}else if(Z.branch.hasKind("alias")&&W.hasKind("domain")&&W.domain==="object")J?.push(Z);else{if(Z.branch.in.overlaps(W)){let G=W6(Z.branch,T.location);J?.push({originalIndex:Z.originalIndex,branch:G})}Y.push(Z)}}return T.defaultEntries=Y,J},LH=(T,_)=>{return T.filter((W)=>{let J=Object.values(W.cases).map((Y)=>Y.branchIndices);for(let Y=0;Y<J.length-1;Y++){let $=J[Y];for(let Z=Y+1;Z<J.length;Z++){let G=J[Z];for(let X of $)for(let O of G)if(X>O){if(_[X].overlaps(_[O]))return!1}}}return!0})},DH=(T,_,F)=>{let W=T==="undefined"?F.node("unit",{unit:void 0}):T==="null"?F.node("unit",{unit:null}):T==="boolean"?F.units([!0,!1]):T;for(let J=_.length-1;J>=0;J--){let Y=_[J];W=F.node("intersection",typeof Y==="number"?{proto:"Array",sequence:[...g8(Y).map(($)=>({})),W]}:{domain:"object",required:[{key:Y,value:W}]})}return W},$6=(T)=>T.reduce((_,F)=>_+G4(F,!0),"data"),SH=VT(u8),IH=VT(d),v4={implementation:zH,Node:Y6},NH=(T)=>({kind:T.kind,path:T.path.map((_)=>typeof _==="string"?_:i_(_)),cases:c(T.cases,(_,F)=>[_,F===!0?F:F.hasKind("union")&&F.discriminantJson?F.discriminantJson:F.json])}),CH={delimiter:" | ",finalDelimiter:" | "},BH=(T)=>a0(T,CH),a0=(T,_)=>{let F=_?.delimiter??", ",W=_?.finalDelimiter??" or ";if(T.length===0)return"never";if(T.length===1)return T[0];if(T.length===2&&T[0]==="false"&&T[1]==="true"||T[0]==="true"&&T[1]==="false")return"boolean";let J={},Y=T.filter((Z)=>J[Z]?!1:J[Z]=!0),$=Y.pop();return`${Y.join(F)}${Y.length?W:""}${$}`},y4=(T,_,F)=>{let W=_.map(()=>[]);for(let Y=0;Y<T.length;Y++){let $={};for(let Z=0;Z<_.length;Z++){if(W[Z]===null)continue;if(T[Y].equals(_[Z])){W[Z]=null,$={};break}let G=UT(T[Y],_[Z],F);if(G instanceof N)continue;if(G.equals(T[Y])){W[Z].push(T[Y]),$={};break}if(G.equals(_[Z]))W[Z]=null;else $[Z]=G}for(let Z in $)W[Z][Y]=$[Z]}let J=W.flatMap((Y,$)=>Y?.flatMap((Z)=>Z.branches)??_[$]);return J.length===0?N.init("union",T,_):J},kH=({branches:T,ordered:_})=>{if(T.length<2)return T;let F=T.map(()=>!0);for(let W=0;W<T.length;W++)for(let J=W+1;J<T.length&&F[W]&&F[J];J++){if(T[W].equals(T[J])){F[J]=!1;continue}let Y=J_(T[W].in,T[J].in,T[0].$);if(Y instanceof N)continue;if(!_)fH(T[W],T[J]);if(Y.equals(T[W].in))F[W]=!!_;else if(Y.equals(T[J].in))F[J]=!1}return T.filter((W,J)=>F[J])},fH=(T,_)=>{if(!T.includesTransform&&!_.includesTransform)return;if(!d_(T.shallowMorphs,_.shallowMorphs))E(J6(T.expression,_.expression));if(!d_(T.flatMorphs,_.flatMorphs,{isEqual:(F,W)=>F.propString===W.propString&&(F.node.hasKind("morph")&&W.node.hasKind("morph")?F.node.hasEqualMorphs(W.node):F.node.hasKind("intersection")&&W.node.hasKind("intersection")?F.node.structure?.structuralMorphRef===W.node.structure?.structuralMorphRef:!1)}))E(J6(T.expression,_.expression))},W6=(T,_)=>T.transform((F,W)=>{if(F==="domain"||F==="unit")return null;return W},{shouldTransform:(F,W)=>{let J=$6(W.path);if(!_.optionallyChainedPropString.startsWith(J))return!1;if(F.hasKind("domain")&&F.domain==="object")return!0;if((F.hasKind("domain")||_.kind==="unit")&&J===_.optionallyChainedPropString)return!0;return F.children.length!==0&&F.kind!=="index"}}),J6=(T,_)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
40
40
|
Left: ${T}
|
|
41
41
|
Right: ${_}`,PH=(T,_)=>`The intersection of two ordered unions is indeterminate:
|
|
42
42
|
Left: ${T}
|
|
43
|
-
Right: ${_}`;var qH=l({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(T)=>T instanceof Date?T.toISOString():E_(T)}},normalize:(T)=>T,defaults:{description:(T)=>d(T.unit),problem:({expected:T,actual:_})=>`${T===_?`must be reference equal to ${T} (serialized to the same value)`:`must be ${T} (was ${_})`}`},intersections:{unit:(T,_)=>N.init("unit",T,_),...p_("unit",(T,_)=>{if(_.allows(T.unit))return T;let F=_.hasKind("intersection")?_.basis:_;if(F){let W=F.hasKind("domain")?F:z.intrinsic.object;if(T.domain!==W.domain){let J=T.domain==="undefined"||T.domain==="null"||T.domain==="boolean"?T.domain:z.intrinsic[T.domain];return N.init("domain",J,W)}}return N.init("assignability",T,_.hasKind("intersection")?_.children.find((W)=>!W.allows(T.unit)):_)})}});class X6 extends B0{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=Z6(this.unit,this.serializedValue);compiledNegation=Z6(this.unit,this.serializedValue,"negated");expression=d(this.unit);domain=PT(this.unit);get defaultShortDescription(){return this.domain==="object"?__.object:this.description}innerToJsonSchema(T){return this.unit===null?{type:"null"}:z.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:T.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(T)=>T instanceof Date&&T.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(T)=>Number.isNaN(T):(T)=>T===this.unit}var x4={implementation:qH,Node:X6},Z6=(T,_,F)=>{if(T instanceof Date){let W=`data instanceof Date && data.toISOString() === ${_}`;return F?`!(${W})`:W}if(Number.isNaN(T))return`${F?"!":""}Number.isNaN(data)`;return`data ${F?"!":"="}== ${_}`};var jH=l({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(T,_)=>{let F=_.$.parseSchema(T);if(!F.extends(z.intrinsic.key))return E(vH(F.expression));let W=F.branches.filter((J)=>J.hasKind("unit"));if(W.length)return E(yH(W.map((J)=>d(J.unit))));return F}},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`[${T.signature.expression}]: ${T.value.description}`},intersections:{index:(T,_,F)=>{if(T.signature.equals(_.signature)){let W=UT(T.value,_.value,F),J=W instanceof N?z.intrinsic.never.internal:W;return F.$.node("index",{signature:T.signature,value:J})}if(T.signature.extends(_.signature)&&T.value.subsumes(_.value))return _;if(_.signature.extends(T.signature)&&_.value.subsumes(T.value))return T;return null}}});class G6 extends z_{impliedBasis=z.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=s(this.value.flatRefs.map((T)=>P_([this.signature,...T.path],T.node)),P_([this.signature],this.value));traverseAllows=(T,_)=>S0(T).every((F)=>{if(this.signature.traverseAllows(F[0],_))return W_(F[0],()=>this.value.traverseAllows(F[1],_),_);return!0});traverseApply=(T,_)=>{for(let F of S0(T))if(this.signature.traverseAllows(F[0],_))W_(F[0],()=>this.value.traverseApply(F[1],_),_)};_transform(T,_){_.path.push(this.signature);let F=super._transform(T,_);return _.path.pop(),F}compile(){}}var b4={implementation:jH,Node:G6},yH=(T)=>`Index keys ${T.join(", ")} should be specified as named props.`,vH=(T)=>`Indexed key definition '${T}' must be a string or symbol`;var xH=l({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`${T.compiledKey}: ${T.value.description}`,expected:(T)=>T.missingValueDescription,actual:()=>"missing"},intersections:{required:vF,optional:vF}});class A6 extends xF{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=Z0(this.errorContext)}var h4={implementation:xH,Node:A6};var bH=l({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}},optionals:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}},defaultables:{child:(T)=>T.map((_)=>_[0]),parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>{let W=_.$.parseSchema(F[0]);return hF(W,F[1],null),[W,F[1]]})},serialize:(T)=>T.map((_)=>[_[0].collapsibleJson,E_(_[1])])},variadic:{child:!0,parse:(T,_)=>_.$.parseSchema(T,_)},minVariadicLength:{parse:(T)=>T===0?void 0:T},postfix:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}}},normalize:(T)=>{if(typeof T==="string")return{variadic:T};if("variadic"in T||"prefix"in T||"defaultables"in T||"optionals"in T||"postfix"in T||"minVariadicLength"in T){if(T.postfix?.length){if(!T.variadic)return E(mH);if(T.optionals?.length||T.defaultables?.length)return E(g4)}if(T.minVariadicLength&&!T.variadic)return E("minVariadicLength may not be specified without a variadic element");return T}return{variadic:T}},reduce:(T,_)=>{let F=T.minVariadicLength??0,W=T.prefix?.slice()??[],J=T.defaultables?.slice()??[],Y=T.optionals?.slice()??[],$=T.postfix?.slice()??[];if(T.variadic){while(Y.at(-1)?.equals(T.variadic))Y.pop();if(Y.length===0&&J.length===0)while(W.at(-1)?.equals(T.variadic))W.pop(),F++;while($[0]?.equals(T.variadic))$.shift(),F++}else if(Y.length===0&&J.length===0)W.push(...$.splice(0));if(F!==T.minVariadicLength||T.prefix&&T.prefix.length!==W.length)return _.node("sequence",{...T,prefix:W,defaultables:J,optionals:Y,postfix:$,minVariadicLength:F},{prereduced:!0})},defaults:{description:(T)=>{if(T.isVariadicOnly)return`${T.variadic.nestableExpression}[]`;return`[${T.tuple.map((F)=>F.kind==="defaultables"?`${F.node.nestableExpression} = ${d(F.default)}`:F.kind==="optionals"?`${F.node.nestableExpression}?`:F.kind==="variadic"?`...${F.node.nestableExpression}[]`:F.node.expression).join(", ")}]`}},intersections:{sequence:(T,_,F)=>{let W=oF({l:T.tuple,r:_.tuple,disjoint:new N,result:[],fixedVariants:[],ctx:F}),J=W.disjoint.length===0?[W,...W.fixedVariants]:W.fixedVariants;return J.length===0?W.disjoint:J.length===1?F.$.node("sequence",H6(J[0].result)):F.$.node("union",J.map((Y)=>({proto:Array,sequence:H6(Y.result)})))}}});class O6 extends z_{impliedBasis=z.intrinsic.Array.internal;tuple=gH(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((T)=>{if(T.kind==="defaultables"||T.kind==="optionals")return this.defaultablesAndOptionals.push(T.node),!0;return T.kind==="prefix"});variadicOrPostfix=c_(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return U4(this.flatRefs,this.prevariadic.flatMap((T,_)=>s(T.node.flatRefs.map((F)=>P_([`${_}`,...F.path],F.node)),P_([`${_}`],T.node)))),U4(this.flatRefs,this.variadicOrPostfix.flatMap((T)=>s(T.flatRefs.map((_)=>P_([z.intrinsic.nonNegativeIntegerString.internal,..._.path],_.node)),P_([z.intrinsic.nonNegativeIntegerString.internal],T)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=pH(this);defaultValueMorphsReference=this.defaultValueMorphs.length?KT(this.defaultValueMorphs):void 0;elementAtIndex(T,_){if(_<this.prevariadic.length)return this.tuple[_];let F=T.length-this.postfixLength;if(_>=F)return{kind:"postfix",node:this.postfix[_-F]};return{kind:"variadic",node:this.variadic??e(`Unexpected attempt to access index ${_} on ${this}`)}}traverseAllows=(T,_)=>{for(let F=0;F<T.length;F++)if(!this.elementAtIndex(T,F).node.traverseAllows(T[F],_))return!1;return!0};traverseApply=(T,_)=>{let F=0;for(;F<T.length;F++)W_(F,()=>this.elementAtIndex(T,F).node.traverseApply(T[F],_),_)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(T){if(this.prefix)for(let[_,F]of this.prefix.entries())T.traverseKey(`${_}`,`data[${_}]`,F);for(let[_,F]of this.defaultablesAndOptionals.entries()){let W=`${_+this.prefixLength}`;T.if(`${W} >= ${T.data}.length`,()=>T.traversalKind==="Allows"?T.return(!0):T.return()),T.traverseKey(W,`data[${W}]`,F)}if(this.variadic){if(this.postfix)T.const("firstPostfixIndex",`${T.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(T.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>T.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[_,F]of this.postfix.entries()){let W=`firstPostfixIndex + ${_}`;T.traverseKey(W,`data[${W}]`,F)}}if(T.traversalKind==="Allows")T.return(!0)}_transform(T,_){_.path.push(z.intrinsic.nonNegativeIntegerString.internal);let F=super._transform(T,_);return _.path.pop(),F}expression=this.description;reduceJsonSchema(T,_){if(this.prevariadic.length)T.prefixItems=this.prevariadic.map((F)=>{let W=F.node.toJsonSchemaRecurse(_);if(F.kind==="defaultables"){let J=typeof F.default==="function"?F.default():F.default;W.default=z.intrinsic.jsonData.allows(J)?J:_.fallback.defaultValue({code:"defaultValue",base:W,value:J})}return W});if(this.minLength)T.minItems=this.minLength;if(this.variadic){let F=Object.assign(T,{items:this.variadic.toJsonSchemaRecurse(_)});if(this.maxLength)F.maxItems=this.maxLength;if(this.postfix){let W=this.postfix.map((J)=>J.toJsonSchemaRecurse(_));T=_.fallback.arrayPostfix({code:"arrayPostfix",base:F,elements:W})}}else T.items=!1,delete T.maxItems;return T}}var hH={},pH=(T)=>{if(!T.defaultables)return[];let _=[],F="[",W=T.prefixLength+T.defaultablesLength-1;for(let J=T.prefixLength;J<=W;J++){let[Y,$]=T.defaultables[J-T.prefixLength];_.push(P4(J,Y,$)),F+=`${J}: ${Y.id} = ${E_($)}, `}return F+="]",hH[F]??=_},p4={implementation:bH,Node:O6},gH=(T)=>{let _=[];if(T.prefix)for(let F of T.prefix)_.push({kind:"prefix",node:F});if(T.defaultables)for(let[F,W]of T.defaultables)_.push({kind:"defaultables",node:F,default:W});if(T.optionals)for(let F of T.optionals)_.push({kind:"optionals",node:F});if(T.variadic)_.push({kind:"variadic",node:T.variadic});if(T.postfix)for(let F of T.postfix)_.push({kind:"postfix",node:F});return _},H6=(T)=>T.reduce((_,F)=>{if(F.kind==="variadic")_.variadic=F.node;else if(F.kind==="defaultables")_.defaultables=s(_.defaultables,[[F.node,F.default]]);else _[F.kind]=s(_[F.kind],F.node);return _},{}),g4="A postfix required element cannot follow an optional or defaultable element",mH="A postfix element requires a variadic element",oF=(T)=>{let[_,...F]=T.l,[W,...J]=T.r;if(!_||!W)return T;let Y=F.at(-1)?.kind==="postfix",$=J.at(-1)?.kind==="postfix",Z=_.kind==="prefix"||W.kind==="prefix"?"prefix":_.kind==="postfix"||W.kind==="postfix"?"postfix":_.kind==="variadic"&&W.kind==="variadic"?"variadic":Y||$?"prefix":_.kind==="defaultables"||W.kind==="defaultables"?"defaultables":"optionals";if(_.kind==="prefix"&&W.kind==="variadic"&&$){let M=oF({...T,fixedVariants:[],r:J.map((Q)=>({...Q,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}else if(W.kind==="prefix"&&_.kind==="variadic"&&Y){let M=oF({...T,fixedVariants:[],l:F.map((Q)=>({...Q,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}let G=UT(_.node,W.node,T.ctx);if(G instanceof N)if(Z==="prefix"||Z==="postfix")T.disjoint.push(...G.withPrefixKey(Z==="prefix"?T.result.length:`-${F.length+1}`,"required")),T.result=[...T.result,{kind:Z,node:z.intrinsic.never.internal}];else if(Z==="optionals"||Z==="defaultables")return T;else return oF({...T,fixedVariants:[],l:F.map((M)=>({...M,kind:"prefix"})),r:F.map((M)=>({...M,kind:"prefix"}))});else if(Z==="defaultables"){if(_.kind==="defaultables"&&W.kind==="defaultables"&&_.default!==W.default)E(f4(_.default,W.default));T.result=[...T.result,{kind:Z,node:G,default:_.kind==="defaultables"?_.default:W.kind==="defaultables"?W.default:e(`Unexpected defaultable intersection from ${_.kind} and ${W.kind} elements.`)}]}else T.result=[...T.result,{kind:Z,node:G}];let X=T.l.length,O=T.r.length;if(_.kind!=="variadic"||X>=O&&(W.kind==="variadic"||O===1))T.l=F;if(W.kind!=="variadic"||O>=X&&(_.kind==="variadic"||X===1))T.r=J;return oF(T)};var w6=(T)=>(_)=>{if(_.props.length||_.index){let F=_.index?.map((J)=>J[T])??[];for(let J of _.props)F.push(J[T]);if(_.undeclared)F.push(`+ (undeclared): ${_.undeclared}`);let W=`{ ${F.join(", ")} }`;return _.sequence?`${W} & ${_.sequence.description}`:W}return _.sequence?.description??"{}"},oH=w6("description"),uH=w6("expression"),U6=(T,_,F)=>{let W=T.required?"required":"optional";if(!_.signature.allows(T.key))return null;let J=J_(T.value,_.value,F);if(J instanceof N)return W==="optional"?F.node("optional",{key:T.key,value:z.intrinsic.never.internal}):J.withPrefixKey(T.key,T.kind);return null},cH=l({kind:"structure",hasAssociatedError:!1,normalize:(T)=>T,applyConfig:(T,_)=>{if(!T.undeclared&&_.onUndeclaredKey!=="ignore")return{...T,undeclared:_.onUndeclaredKey};return T},keys:{required:{child:!0,parse:cT("required"),reduceIo:(T,_,F)=>{_.required=s(_.required,F.map((W)=>W[T]));return}},optional:{child:!0,parse:cT("optional"),reduceIo:(T,_,F)=>{if(T==="in"){_.optional=F.map((W)=>W.in);return}for(let W of F)_[W.outProp.kind]=s(_[W.outProp.kind],W.outProp.out)}},index:{child:!0,parse:cT("index")},sequence:{child:!0,parse:cT("sequence")},undeclared:{parse:(T)=>T==="ignore"?void 0:T,reduceIo:(T,_,F)=>{if(F!=="delete")return;if(T==="in")delete _.undeclared;else _.undeclared="reject"}}},defaults:{description:oH},intersections:{structure:(T,_,F)=>{let W={...T.inner},J={..._.inner},Y=new N;if(T.undeclared){let G=T.keyof();for(let X of _.requiredKeys)if(!G.allows(X))Y.add("presence",z.intrinsic.never.internal,_.propsByKey[X].value,{path:[X]});if(J.optional)J.optional=J.optional.filter((X)=>G.allows(X.key));if(J.index)J.index=J.index.flatMap((X)=>{if(X.signature.extends(G))return X;let O=J_(G,X.signature,F.$);if(O instanceof N)return[];let M=mW(O,X.value,F.$);if(M.required)J.required=c_(J.required,M.required);if(M.optional)J.optional=c_(J.optional,M.optional);return M.index??[]})}if(_.undeclared){let G=_.keyof();for(let X of T.requiredKeys)if(!G.allows(X))Y.add("presence",T.propsByKey[X].value,z.intrinsic.never.internal,{path:[X]});if(W.optional)W.optional=W.optional.filter((X)=>G.allows(X.key));if(W.index)W.index=W.index.flatMap((X)=>{if(X.signature.extends(G))return X;let O=J_(G,X.signature,F.$);if(O instanceof N)return[];let M=mW(O,X.value,F.$);if(M.required)W.required=c_(W.required,M.required);if(M.optional)W.optional=c_(W.optional,M.optional);return M.index??[]})}let $={};if(T.undeclared||_.undeclared)$.undeclared=T.undeclared==="reject"||_.undeclared==="reject"?"reject":"delete";let Z=t0({kind:"structure",baseInner:$,l:i0(W),r:i0(J),roots:[],ctx:F});if(Z instanceof N)Y.push(...Z);if(Y.length)return Y;return Z}},reduce:(T,_)=>{if(T.index){if(!(T.required||T.optional))return;let F=!1,W=T.required??[],J=T.optional??[],Y=[...J];for(let $ of T.index){for(let Z of W){let G=U6(Z,$,_);if(G instanceof N)return G}for(let[Z,G]of J.entries()){let X=U6(G,$,_);if(X instanceof N)return X;if(X===null)continue;Y[Z]=X,F=!0}}if(F)return _.node("structure",{...T,optional:Y},{prereduced:!0})}}});class Q6 extends z_{impliedBasis=z.intrinsic.object.internal;impliedSiblings=this.children.flatMap((T)=>T.impliedSiblings??[]);props=c_(this.required,this.optional);propsByKey=c(this.props,(T,_)=>[_.key,_]);propsByKeyReference=KT(this.propsByKey);expression=uH(this);requiredKeys=this.required?.map((T)=>T.key)??[];optionalKeys=this.optional?.map((T)=>T.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:_}of this.index)T=T.concat(_.branches);return this._keyof=this.$.node("union",T)}map(T){return this.$.node("structure",this.props.flatMap(T).reduce((_,F)=>{let W=this.propsByKey[F.key];if(OT(F)){if(F.kind!=="required"&&F.kind!=="optional")return E(`Map result must have kind "required" or "optional" (was ${F.kind})`);return _[F.kind]=s(_[F.kind],F),_}let J=F.kind??W?.kind??"required",Y=c(F,($,Z)=>($ in bF.implementation.keys)?[$,Z]:[]);return _[J]=s(_[J],this.$.node(J,Y)),_},{}))}assertHasKeys(T){let _=T.filter((F)=>!pF(F,this.keyof()));if(_.length)return E(M6(this.expression,_))}get(T,..._){let F,W=!1,J=iH(T);if((typeof J==="string"||typeof J==="symbol")&&this.propsByKey[J])F=this.propsByKey[J].value,W=this.propsByKey[J].required;if(this.index){for(let $ of this.index)if(pF(J,$.signature))F=F?.and($.value)??$.value}if(this.sequence&&pF(J,z.intrinsic.nonNegativeIntegerString))if(P(J,"root")){if(this.sequence.variadic)F=F?.and(this.sequence.element)??this.sequence.element}else{let $=Number.parseInt(J);if($<this.sequence.prevariadic.length){let Z=this.sequence.prevariadic[$].node;F=F?.and(Z)??Z,W||=$<this.sequence.prefixLength}else if(this.sequence.variadic){let Z=this.$.node("union",this.sequence.variadicOrPostfix);F=F?.and(Z)??Z}}if(!F){if(this.sequence?.variadic&&P(J,"root")&&J.extends(z.intrinsic.number))return E(nH(J.expression,this.sequence.expression));return E(M6(this.expression,[J]))}let Y=F.get(..._);return W?Y:Y.or(z.intrinsic.undefined)}pick(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("pick",T))}omit(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("omit",T))}optionalize(){let{required:T,..._}=this.inner;return this.$.node("structure",{..._,optional:this.props.map((F)=>F.hasKind("required")?this.$.node("optional",F.inner):F)})}require(){let{optional:T,..._}=this.inner;return this.$.node("structure",{..._,required:this.props.map((F)=>F.hasKind("optional")?{key:F.key,value:F.value}:F)})}merge(T){let _=this.filterKeys("omit",[T.keyof()]);if(T.required)_.required=s(_.required,T.required);if(T.optional)_.optional=s(_.optional,T.optional);if(T.index)_.index=s(_.index,T.index);if(T.sequence)_.sequence=T.sequence;if(T.undeclared)_.undeclared=T.undeclared;else delete _.undeclared;return this.$.node("structure",_)}filterKeys(T,_){let F=fW(this.inner),W=(J)=>{let Y=_.some(($)=>pF(J,$));return T==="pick"?Y:!Y};if(F.required)F.required=F.required.filter((J)=>W(J.key));if(F.optional)F.optional=F.optional.filter((J)=>W(J.key));if(F.index)F.index=F.index.filter((J)=>W(J.signature));return F}traverseAllows=(T,_)=>this._traverse("Allows",T,_);traverseApply=(T,_)=>this._traverse("Apply",T,_);_traverse=(T,_,F)=>{let W=F?.currentErrorCount??0;for(let J=0;J<this.props.length;J++)if(T==="Allows"){if(!this.props[J].traverseAllows(_,F))return!1}else if(this.props[J].traverseApply(_,F),F.failFast&&F.currentErrorCount>W)return!1;if(this.sequence){if(T==="Allows"){if(!this.sequence.traverseAllows(_,F))return!1}else if(this.sequence.traverseApply(_,F),F.failFast&&F.currentErrorCount>W)return!1}if(this.index||this.undeclared==="reject"){let J=Object.keys(_);J.push(...Object.getOwnPropertySymbols(_));for(let Y=0;Y<J.length;Y++){let $=J[Y];if(this.index){for(let Z of this.index)if(Z.signature.traverseAllows($,F)){if(T==="Allows"){if(!W_($,()=>Z.value.traverseAllows(_[$],F),F))return!1}else if(W_($,()=>Z.value.traverseApply(_[$],F),F),F.failFast&&F.currentErrorCount>W)return!1}}if(this.undeclared==="reject"&&!this.declaresKey($)){if(T==="Allows")return!1;if(F.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[$],meta:this.meta}),F.failFast)return!1}}}if(this.structuralMorph&&F&&!F.hasError())F.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((T)=>T.hasDefault())??[])}declaresKey=(T)=>(T in this.propsByKey)||this.index?.some((_)=>_.signature.allows(T))||this.sequence!==void 0&&z.intrinsic.nonNegativeIntegerString.allows(T);_compileDeclaresKey(T){let _=[];if(this.props.length)_.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let F of this.index)_.push(T.invoke(F.signature,{kind:"Allows",arg:"k"}));if(this.sequence)_.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return _.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",lH(this))}structuralMorphRef=this.structuralMorph&&KT(this.structuralMorph);compile(T){if(T.traversalKind==="Apply")T.initializeErrorCount();for(let _ of this.props)if(T.check(_),T.traversalKind==="Apply")T.returnIfFailFast();if(this.sequence){if(T.check(this.sequence),T.traversalKind==="Apply")T.returnIfFailFast()}if(this.index||this.undeclared==="reject")T.const("keys","Object.keys(data)"),T.line("keys.push(...Object.getOwnPropertySymbols(data))"),T.for("i < keys.length",()=>this.compileExhaustiveEntry(T));if(T.traversalKind==="Allows")return T.return(!0);if(this.structuralMorphRef)T.if("ctx && !ctx.hasError()",()=>{return T.line("ctx.queueMorphs(["),tH(T,this),T.line("])")})}compileExhaustiveEntry(T){if(T.const("k","keys[i]"),this.index)for(let _ of this.index)T.if(`${T.invoke(_.signature,{arg:"k",kind:"Allows"})}`,()=>T.traverseKey("k","data[k]",_.value));if(this.undeclared==="reject")T.if(`!(${this._compileDeclaresKey(T)})`,()=>{if(T.traversalKind==="Allows")return T.return(!1);return T.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>T.return())});return T}reduceJsonSchema(T,_){switch(T.type){case"object":return this.reduceObjectJsonSchema(T,_);case"array":let F=this.sequence?.reduceJsonSchema(T,_)??T;if(this.props.length||this.index)return _.fallback.arrayObject({code:"arrayObject",base:F,object:this.reduceObjectJsonSchema({type:"object"},_)});return F;default:return RT.throwInternalOperandError("structure",T)}}reduceObjectJsonSchema(T,_){if(this.props.length){T.properties={};for(let F of this.props){let W=F.value.toJsonSchemaRecurse(_);if(typeof F.key==="symbol"){_.fallback.symbolKey({code:"symbolKey",base:T,key:F.key,value:W,optional:F.optional});continue}if(F.hasDefault()){let J=typeof F.default==="function"?F.default():F.default;W.default=z.intrinsic.jsonData.allows(J)?J:_.fallback.defaultValue({code:"defaultValue",base:W,value:J})}T.properties[F.key]=W}if(this.requiredKeys.length&&T.properties)T.required=this.requiredKeys.filter((F)=>typeof F==="string"&&(F in T.properties))}if(this.index)for(let F of this.index){let W=F.value.toJsonSchemaRecurse(_);if(F.signature.equals(z.intrinsic.string)){T.additionalProperties=W;continue}for(let J of F.signature.branches){if(!J.extends(z.intrinsic.string)){T=_.fallback.symbolKey({code:"symbolKey",base:T,key:null,value:W,optional:!1});continue}let Y={type:"string"};if(J.hasKind("morph"))Y=_.fallback.morph({code:"morph",base:J.in.toJsonSchemaRecurse(_),out:J.out.toJsonSchemaRecurse(_)});if(!J.hasKind("intersection"))return e(`Unexpected index branch kind ${J.kind}.`);let{pattern:$}=J.inner;if($){let Z=Object.assign(Y,{pattern:$[0].rule});for(let G=1;G<$.length;G++)Y=_.fallback.patternIntersection({code:"patternIntersection",base:Z,pattern:$[G].rule});T.patternProperties??={},T.patternProperties[Z.pattern]=W}}}if(this.undeclared&&!T.additionalProperties)T.additionalProperties=!1;return T}}var m4={},dH=(T)=>{let _="";for(let F=0;F<T.defaultable.length;F++)_+=T.defaultable[F].defaultValueMorphRef;if(T.sequence?.defaultValueMorphsReference)_+=T.sequence?.defaultValueMorphsReference;if(T.undeclared==="delete"){if(_+="delete !(",T.required)for(let F of T.required)_+=F.compiledKey+" | ";if(T.optional)for(let F of T.optional)_+=F.compiledKey+" | ";if(T.index)for(let F of T.index)_+=F.signature.id+" | ";if(T.sequence)if(T.sequence.maxLength===null)_+=x.nonNegativeIntegerString.id;else for(let F=0;F<T.sequence.tuple.length;F++)_+=F+" | ";_+=")"}return _},lH=(T)=>{let _=dH(T);if(!_)return;if(m4[_])return m4[_];let F=(W,J)=>{for(let Y=0;Y<T.defaultable.length;Y++)if(!(T.defaultable[Y].key in W))T.defaultable[Y].defaultValueMorph(W,J);if(T.sequence?.defaultables)for(let Y=W.length-T.sequence.prefixLength;Y<T.sequence.defaultables.length;Y++)T.sequence.defaultValueMorphs[Y](W,J);if(T.undeclared==="delete"){for(let Y in W)if(!T.declaresKey(Y))delete W[Y]}return W};return m4[_]=F},tH=(T,_)=>{let W=`(data${_.defaultable.some((J)=>J.defaultValueMorph.length===2)||_.sequence?.defaultValueMorphs.some((J)=>J.length===2)?", ctx":""})`;return T.block(`${W} => `,(J)=>{for(let Y=0;Y<_.defaultable.length;Y++){let{serializedKey:$,defaultValueMorphRef:Z}=_.defaultable[Y];J.if(`!(${$} in data)`,(G)=>G.line(`${Z}${W}`))}if(_.sequence?.defaultables)J.for(`i < ${_.sequence.defaultables.length}`,(Y)=>Y.set("data[i]",5),`data.length - ${_.sequence.prefixLength}`);if(_.undeclared==="delete")J.forIn("data",(Y)=>Y.if(`!(${_._compileDeclaresKey(Y)})`,($)=>$.line("delete data[k]")));return J.return("data")})},o4={implementation:cH,Node:Q6},iH=(T)=>{if(P(T,"root")&&T.hasKind("unit"))T=T.unit;if(typeof T==="number")T=`${T}`;return T},nH=(T,_)=>`${T} is not allowed as an array index on ${_}. Use the 'nonNegativeIntegerString' keyword instead.`,mW=(T,_,F)=>{let[W,J]=p8(T.branches,($)=>$.hasKind("unit"));if(!W.length)return{index:F.node("index",{signature:T,value:_})};let Y={};for(let $ of W){let Z=F.node("required",{key:$.unit,value:_});Y[Z.kind]=s(Y[Z.kind],Z)}if(J.length)Y.index=F.node("index",{signature:J,value:_});return Y},rH=(T)=>P(T,"root")?T.expression:d(T),M6=(T,_)=>`Key${_.length===1?"":"s"} ${_.map(rH).join(", ")} ${_.length===1?"does":"do"} not exist on ${T}`;var r0={...gJ,alias:gF.implementation,domain:gW.implementation,unit:x4.implementation,proto:mF.implementation,union:v4.implementation,morph:j4.implementation,intersection:q4.implementation,divisor:E4.implementation,pattern:N4.implementation,predicate:R4.implementation,required:h4.implementation,optional:bF.implementation,index:b4.implementation,sequence:p4.implementation,structure:o4.implementation};z.defaultConfig=i8(Object.assign(c(r0,(T,_)=>[T,_.defaults]),{jitless:TJ(),clone:s8,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:RT.defaultConfig}));z.resolvedConfig=fF(z.defaultConfig,z.config);var lJ={...mJ,alias:gF.Node,domain:gW.Node,unit:x4.Node,proto:mF.Node,union:v4.Node,morph:j4.Node,intersection:q4.Node,divisor:E4.Node,pattern:N4.Node,predicate:R4.Node,required:h4.Node,optional:bF.Node,index:b4.Node,sequence:p4.Node,structure:o4.Node};class e0 extends a1{get[iT](){return"module"}}var u4=(T,_)=>new e0(c(T,(F,W)=>[F,P(W,"module")?u4(W,_):_.bindReference(W)]));var sH=(T)=>XT(T)?T:("branches"in T)&&XT(T.branches)?T.branches:void 0,aH=(T,_)=>E(`Node of kind ${_} is not valid as a ${T} definition`),R6=(T)=>`#${T} duplicates public alias ${T}`,c4={};z.ambient??={};var E6,V6="function $",eH=(T)=>K6(T,L6(T)),K6=(T,_)=>{let F=_.write(V6,4),W=_.compile()();for(let J of T){if(J.precompilation)continue;if(J.traverseAllows=W[`${J.id}Allows`].bind(W),J.isRoot()&&!J.allowsRequiresContext)J.allows=J.traverseAllows;if(J.traverseApply=W[`${J.id}Apply`].bind(W),W[`${J.id}Optimistic`])J.traverseOptimistic=W[`${J.id}Optimistic`].bind(W);J.precompilation=F}},L6=(T)=>new kW().return(T.reduce((_,F)=>{let W=new kF({kind:"Allows"}).indent();F.compile(W);let J=W.write(`${F.id}Allows`),Y=new kF({kind:"Apply"}).indent();F.compile(Y);let $=Y.write(`${F.id}Apply`),Z=`${_}${J},
|
|
43
|
+
Right: ${_}`;var qH=l({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(T)=>T instanceof Date?T.toISOString():E_(T)}},normalize:(T)=>T,defaults:{description:(T)=>d(T.unit),problem:({expected:T,actual:_})=>`${T===_?`must be reference equal to ${T} (serialized to the same value)`:`must be ${T} (was ${_})`}`},intersections:{unit:(T,_)=>N.init("unit",T,_),...p_("unit",(T,_)=>{if(_.allows(T.unit))return T;let F=_.hasKind("intersection")?_.basis:_;if(F){let W=F.hasKind("domain")?F:z.intrinsic.object;if(T.domain!==W.domain){let J=T.domain==="undefined"||T.domain==="null"||T.domain==="boolean"?T.domain:z.intrinsic[T.domain];return N.init("domain",J,W)}}return N.init("assignability",T,_.hasKind("intersection")?_.children.find((W)=>!W.allows(T.unit)):_)})}});class X6 extends B0{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=Z6(this.unit,this.serializedValue);compiledNegation=Z6(this.unit,this.serializedValue,"negated");expression=d(this.unit);domain=PT(this.unit);get defaultShortDescription(){return this.domain==="object"?__.object:this.description}innerToJsonSchema(T){return this.unit===null?{type:"null"}:z.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:T.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(T)=>T instanceof Date&&T.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(T)=>Number.isNaN(T):(T)=>T===this.unit}var x4={implementation:qH,Node:X6},Z6=(T,_,F)=>{if(T instanceof Date){let W=`data instanceof Date && data.toISOString() === ${_}`;return F?`!(${W})`:W}if(Number.isNaN(T))return`${F?"!":""}Number.isNaN(data)`;return`data ${F?"!":"="}== ${_}`};var jH=l({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(T,_)=>{let F=_.$.parseSchema(T);if(!F.extends(z.intrinsic.key))return E(vH(F.expression));let W=F.branches.filter((J)=>J.hasKind("unit"));if(W.length)return E(yH(W.map((J)=>d(J.unit))));return F}},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`[${T.signature.expression}]: ${T.value.description}`},intersections:{index:(T,_,F)=>{if(T.signature.equals(_.signature)){let W=UT(T.value,_.value,F),J=W instanceof N?z.intrinsic.never.internal:W;return F.$.node("index",{signature:T.signature,value:J})}if(T.signature.extends(_.signature)&&T.value.subsumes(_.value))return _;if(_.signature.extends(T.signature)&&_.value.subsumes(T.value))return T;return null}}});class G6 extends z_{impliedBasis=z.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=s(this.value.flatRefs.map((T)=>P_([this.signature,...T.path],T.node)),P_([this.signature],this.value));traverseAllows=(T,_)=>S0(T).every((F)=>{if(this.signature.traverseAllows(F[0],_))return W_(F[0],()=>this.value.traverseAllows(F[1],_),_);return!0});traverseApply=(T,_)=>{for(let F of S0(T))if(this.signature.traverseAllows(F[0],_))W_(F[0],()=>this.value.traverseApply(F[1],_),_)};_transform(T,_){_.path.push(this.signature);let F=super._transform(T,_);return _.path.pop(),F}compile(){}}var b4={implementation:jH,Node:G6},yH=(T)=>`Index keys ${T.join(", ")} should be specified as named props.`,vH=(T)=>`Indexed key definition '${T}' must be a string or symbol`;var xH=l({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`${T.compiledKey}: ${T.value.description}`,expected:(T)=>T.missingValueDescription,actual:()=>"missing"},intersections:{required:vF,optional:vF}});class A6 extends xF{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=Z0(this.errorContext)}var h4={implementation:xH,Node:A6};var bH=l({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}},optionals:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}},defaultables:{child:(T)=>T.map((_)=>_[0]),parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>{let W=_.$.parseSchema(F[0]);return hF(W,F[1],null),[W,F[1]]})},serialize:(T)=>T.map((_)=>[_[0].collapsibleJson,E_(_[1])])},variadic:{child:!0,parse:(T,_)=>_.$.parseSchema(T,_)},minVariadicLength:{parse:(T)=>T===0?void 0:T},postfix:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}}},normalize:(T)=>{if(typeof T==="string")return{variadic:T};if("variadic"in T||"prefix"in T||"defaultables"in T||"optionals"in T||"postfix"in T||"minVariadicLength"in T){if(T.postfix?.length){if(!T.variadic)return E(mH);if(T.optionals?.length||T.defaultables?.length)return E(g4)}if(T.minVariadicLength&&!T.variadic)return E("minVariadicLength may not be specified without a variadic element");return T}return{variadic:T}},reduce:(T,_)=>{let F=T.minVariadicLength??0,W=T.prefix?.slice()??[],J=T.defaultables?.slice()??[],Y=T.optionals?.slice()??[],$=T.postfix?.slice()??[];if(T.variadic){while(Y.at(-1)?.equals(T.variadic))Y.pop();if(Y.length===0&&J.length===0)while(W.at(-1)?.equals(T.variadic))W.pop(),F++;while($[0]?.equals(T.variadic))$.shift(),F++}else if(Y.length===0&&J.length===0)W.push(...$.splice(0));if(F!==T.minVariadicLength||T.prefix&&T.prefix.length!==W.length)return _.node("sequence",{...T,prefix:W,defaultables:J,optionals:Y,postfix:$,minVariadicLength:F},{prereduced:!0})},defaults:{description:(T)=>{if(T.isVariadicOnly)return`${T.variadic.nestableExpression}[]`;return`[${T.tuple.map((F)=>F.kind==="defaultables"?`${F.node.nestableExpression} = ${d(F.default)}`:F.kind==="optionals"?`${F.node.nestableExpression}?`:F.kind==="variadic"?`...${F.node.nestableExpression}[]`:F.node.expression).join(", ")}]`}},intersections:{sequence:(T,_,F)=>{let W=oF({l:T.tuple,r:_.tuple,disjoint:new N,result:[],fixedVariants:[],ctx:F}),J=W.disjoint.length===0?[W,...W.fixedVariants]:W.fixedVariants;return J.length===0?W.disjoint:J.length===1?F.$.node("sequence",H6(J[0].result)):F.$.node("union",J.map((Y)=>({proto:Array,sequence:H6(Y.result)})))}}});class O6 extends z_{impliedBasis=z.intrinsic.Array.internal;tuple=gH(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((T)=>{if(T.kind==="defaultables"||T.kind==="optionals")return this.defaultablesAndOptionals.push(T.node),!0;return T.kind==="prefix"});variadicOrPostfix=c_(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return U4(this.flatRefs,this.prevariadic.flatMap((T,_)=>s(T.node.flatRefs.map((F)=>P_([`${_}`,...F.path],F.node)),P_([`${_}`],T.node)))),U4(this.flatRefs,this.variadicOrPostfix.flatMap((T)=>s(T.flatRefs.map((_)=>P_([z.intrinsic.nonNegativeIntegerString.internal,..._.path],_.node)),P_([z.intrinsic.nonNegativeIntegerString.internal],T)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=pH(this);defaultValueMorphsReference=this.defaultValueMorphs.length?VT(this.defaultValueMorphs):void 0;elementAtIndex(T,_){if(_<this.prevariadic.length)return this.tuple[_];let F=T.length-this.postfixLength;if(_>=F)return{kind:"postfix",node:this.postfix[_-F]};return{kind:"variadic",node:this.variadic??e(`Unexpected attempt to access index ${_} on ${this}`)}}traverseAllows=(T,_)=>{for(let F=0;F<T.length;F++)if(!this.elementAtIndex(T,F).node.traverseAllows(T[F],_))return!1;return!0};traverseApply=(T,_)=>{let F=0;for(;F<T.length;F++)W_(F,()=>this.elementAtIndex(T,F).node.traverseApply(T[F],_),_)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(T){if(this.prefix)for(let[_,F]of this.prefix.entries())T.traverseKey(`${_}`,`data[${_}]`,F);for(let[_,F]of this.defaultablesAndOptionals.entries()){let W=`${_+this.prefixLength}`;T.if(`${W} >= ${T.data}.length`,()=>T.traversalKind==="Allows"?T.return(!0):T.return()),T.traverseKey(W,`data[${W}]`,F)}if(this.variadic){if(this.postfix)T.const("firstPostfixIndex",`${T.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(T.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>T.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[_,F]of this.postfix.entries()){let W=`firstPostfixIndex + ${_}`;T.traverseKey(W,`data[${W}]`,F)}}if(T.traversalKind==="Allows")T.return(!0)}_transform(T,_){_.path.push(z.intrinsic.nonNegativeIntegerString.internal);let F=super._transform(T,_);return _.path.pop(),F}expression=this.description;reduceJsonSchema(T,_){if(this.prevariadic.length)T.prefixItems=this.prevariadic.map((F)=>{let W=F.node.toJsonSchemaRecurse(_);if(F.kind==="defaultables"){let J=typeof F.default==="function"?F.default():F.default;W.default=z.intrinsic.jsonData.allows(J)?J:_.fallback.defaultValue({code:"defaultValue",base:W,value:J})}return W});if(this.minLength)T.minItems=this.minLength;if(this.variadic){let F=Object.assign(T,{items:this.variadic.toJsonSchemaRecurse(_)});if(this.maxLength)F.maxItems=this.maxLength;if(this.postfix){let W=this.postfix.map((J)=>J.toJsonSchemaRecurse(_));T=_.fallback.arrayPostfix({code:"arrayPostfix",base:F,elements:W})}}else T.items=!1,delete T.maxItems;return T}}var hH={},pH=(T)=>{if(!T.defaultables)return[];let _=[],F="[",W=T.prefixLength+T.defaultablesLength-1;for(let J=T.prefixLength;J<=W;J++){let[Y,$]=T.defaultables[J-T.prefixLength];_.push(P4(J,Y,$)),F+=`${J}: ${Y.id} = ${E_($)}, `}return F+="]",hH[F]??=_},p4={implementation:bH,Node:O6},gH=(T)=>{let _=[];if(T.prefix)for(let F of T.prefix)_.push({kind:"prefix",node:F});if(T.defaultables)for(let[F,W]of T.defaultables)_.push({kind:"defaultables",node:F,default:W});if(T.optionals)for(let F of T.optionals)_.push({kind:"optionals",node:F});if(T.variadic)_.push({kind:"variadic",node:T.variadic});if(T.postfix)for(let F of T.postfix)_.push({kind:"postfix",node:F});return _},H6=(T)=>T.reduce((_,F)=>{if(F.kind==="variadic")_.variadic=F.node;else if(F.kind==="defaultables")_.defaultables=s(_.defaultables,[[F.node,F.default]]);else _[F.kind]=s(_[F.kind],F.node);return _},{}),g4="A postfix required element cannot follow an optional or defaultable element",mH="A postfix element requires a variadic element",oF=(T)=>{let[_,...F]=T.l,[W,...J]=T.r;if(!_||!W)return T;let Y=F.at(-1)?.kind==="postfix",$=J.at(-1)?.kind==="postfix",Z=_.kind==="prefix"||W.kind==="prefix"?"prefix":_.kind==="postfix"||W.kind==="postfix"?"postfix":_.kind==="variadic"&&W.kind==="variadic"?"variadic":Y||$?"prefix":_.kind==="defaultables"||W.kind==="defaultables"?"defaultables":"optionals";if(_.kind==="prefix"&&W.kind==="variadic"&&$){let M=oF({...T,fixedVariants:[],r:J.map((Q)=>({...Q,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}else if(W.kind==="prefix"&&_.kind==="variadic"&&Y){let M=oF({...T,fixedVariants:[],l:F.map((Q)=>({...Q,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}let G=UT(_.node,W.node,T.ctx);if(G instanceof N)if(Z==="prefix"||Z==="postfix")T.disjoint.push(...G.withPrefixKey(Z==="prefix"?T.result.length:`-${F.length+1}`,"required")),T.result=[...T.result,{kind:Z,node:z.intrinsic.never.internal}];else if(Z==="optionals"||Z==="defaultables")return T;else return oF({...T,fixedVariants:[],l:F.map((M)=>({...M,kind:"prefix"})),r:F.map((M)=>({...M,kind:"prefix"}))});else if(Z==="defaultables"){if(_.kind==="defaultables"&&W.kind==="defaultables"&&_.default!==W.default)E(f4(_.default,W.default));T.result=[...T.result,{kind:Z,node:G,default:_.kind==="defaultables"?_.default:W.kind==="defaultables"?W.default:e(`Unexpected defaultable intersection from ${_.kind} and ${W.kind} elements.`)}]}else T.result=[...T.result,{kind:Z,node:G}];let X=T.l.length,O=T.r.length;if(_.kind!=="variadic"||X>=O&&(W.kind==="variadic"||O===1))T.l=F;if(W.kind!=="variadic"||O>=X&&(_.kind==="variadic"||X===1))T.r=J;return oF(T)};var w6=(T)=>(_)=>{if(_.props.length||_.index){let F=_.index?.map((J)=>J[T])??[];for(let J of _.props)F.push(J[T]);if(_.undeclared)F.push(`+ (undeclared): ${_.undeclared}`);let W=`{ ${F.join(", ")} }`;return _.sequence?`${W} & ${_.sequence.description}`:W}return _.sequence?.description??"{}"},oH=w6("description"),uH=w6("expression"),U6=(T,_,F)=>{let W=T.required?"required":"optional";if(!_.signature.allows(T.key))return null;let J=J_(T.value,_.value,F);if(J instanceof N)return W==="optional"?F.node("optional",{key:T.key,value:z.intrinsic.never.internal}):J.withPrefixKey(T.key,T.kind);return null},cH=l({kind:"structure",hasAssociatedError:!1,normalize:(T)=>T,applyConfig:(T,_)=>{if(!T.undeclared&&_.onUndeclaredKey!=="ignore")return{...T,undeclared:_.onUndeclaredKey};return T},keys:{required:{child:!0,parse:cT("required"),reduceIo:(T,_,F)=>{_.required=s(_.required,F.map((W)=>W[T]));return}},optional:{child:!0,parse:cT("optional"),reduceIo:(T,_,F)=>{if(T==="in"){_.optional=F.map((W)=>W.in);return}for(let W of F)_[W.outProp.kind]=s(_[W.outProp.kind],W.outProp.out)}},index:{child:!0,parse:cT("index")},sequence:{child:!0,parse:cT("sequence")},undeclared:{parse:(T)=>T==="ignore"?void 0:T,reduceIo:(T,_,F)=>{if(F!=="delete")return;if(T==="in")delete _.undeclared;else _.undeclared="reject"}}},defaults:{description:oH},intersections:{structure:(T,_,F)=>{let W={...T.inner},J={..._.inner},Y=new N;if(T.undeclared){let G=T.keyof();for(let X of _.requiredKeys)if(!G.allows(X))Y.add("presence",z.intrinsic.never.internal,_.propsByKey[X].value,{path:[X]});if(J.optional)J.optional=J.optional.filter((X)=>G.allows(X.key));if(J.index)J.index=J.index.flatMap((X)=>{if(X.signature.extends(G))return X;let O=J_(G,X.signature,F.$);if(O instanceof N)return[];let M=mW(O,X.value,F.$);if(M.required)J.required=c_(J.required,M.required);if(M.optional)J.optional=c_(J.optional,M.optional);return M.index??[]})}if(_.undeclared){let G=_.keyof();for(let X of T.requiredKeys)if(!G.allows(X))Y.add("presence",T.propsByKey[X].value,z.intrinsic.never.internal,{path:[X]});if(W.optional)W.optional=W.optional.filter((X)=>G.allows(X.key));if(W.index)W.index=W.index.flatMap((X)=>{if(X.signature.extends(G))return X;let O=J_(G,X.signature,F.$);if(O instanceof N)return[];let M=mW(O,X.value,F.$);if(M.required)W.required=c_(W.required,M.required);if(M.optional)W.optional=c_(W.optional,M.optional);return M.index??[]})}let $={};if(T.undeclared||_.undeclared)$.undeclared=T.undeclared==="reject"||_.undeclared==="reject"?"reject":"delete";let Z=t0({kind:"structure",baseInner:$,l:i0(W),r:i0(J),roots:[],ctx:F});if(Z instanceof N)Y.push(...Z);if(Y.length)return Y;return Z}},reduce:(T,_)=>{if(T.index){if(!(T.required||T.optional))return;let F=!1,W=T.required??[],J=T.optional??[],Y=[...J];for(let $ of T.index){for(let Z of W){let G=U6(Z,$,_);if(G instanceof N)return G}for(let[Z,G]of J.entries()){let X=U6(G,$,_);if(X instanceof N)return X;if(X===null)continue;Y[Z]=X,F=!0}}if(F)return _.node("structure",{...T,optional:Y},{prereduced:!0})}}});class Q6 extends z_{impliedBasis=z.intrinsic.object.internal;impliedSiblings=this.children.flatMap((T)=>T.impliedSiblings??[]);props=c_(this.required,this.optional);propsByKey=c(this.props,(T,_)=>[_.key,_]);propsByKeyReference=VT(this.propsByKey);expression=uH(this);requiredKeys=this.required?.map((T)=>T.key)??[];optionalKeys=this.optional?.map((T)=>T.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:_}of this.index)T=T.concat(_.branches);return this._keyof=this.$.node("union",T)}map(T){return this.$.node("structure",this.props.flatMap(T).reduce((_,F)=>{let W=this.propsByKey[F.key];if(OT(F)){if(F.kind!=="required"&&F.kind!=="optional")return E(`Map result must have kind "required" or "optional" (was ${F.kind})`);return _[F.kind]=s(_[F.kind],F),_}let J=F.kind??W?.kind??"required",Y=c(F,($,Z)=>($ in bF.implementation.keys)?[$,Z]:[]);return _[J]=s(_[J],this.$.node(J,Y)),_},{}))}assertHasKeys(T){let _=T.filter((F)=>!pF(F,this.keyof()));if(_.length)return E(M6(this.expression,_))}get(T,..._){let F,W=!1,J=iH(T);if((typeof J==="string"||typeof J==="symbol")&&this.propsByKey[J])F=this.propsByKey[J].value,W=this.propsByKey[J].required;if(this.index){for(let $ of this.index)if(pF(J,$.signature))F=F?.and($.value)??$.value}if(this.sequence&&pF(J,z.intrinsic.nonNegativeIntegerString))if(P(J,"root")){if(this.sequence.variadic)F=F?.and(this.sequence.element)??this.sequence.element}else{let $=Number.parseInt(J);if($<this.sequence.prevariadic.length){let Z=this.sequence.prevariadic[$].node;F=F?.and(Z)??Z,W||=$<this.sequence.prefixLength}else if(this.sequence.variadic){let Z=this.$.node("union",this.sequence.variadicOrPostfix);F=F?.and(Z)??Z}}if(!F){if(this.sequence?.variadic&&P(J,"root")&&J.extends(z.intrinsic.number))return E(nH(J.expression,this.sequence.expression));return E(M6(this.expression,[J]))}let Y=F.get(..._);return W?Y:Y.or(z.intrinsic.undefined)}pick(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("pick",T))}omit(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("omit",T))}optionalize(){let{required:T,..._}=this.inner;return this.$.node("structure",{..._,optional:this.props.map((F)=>F.hasKind("required")?this.$.node("optional",F.inner):F)})}require(){let{optional:T,..._}=this.inner;return this.$.node("structure",{..._,required:this.props.map((F)=>F.hasKind("optional")?{key:F.key,value:F.value}:F)})}merge(T){let _=this.filterKeys("omit",[T.keyof()]);if(T.required)_.required=s(_.required,T.required);if(T.optional)_.optional=s(_.optional,T.optional);if(T.index)_.index=s(_.index,T.index);if(T.sequence)_.sequence=T.sequence;if(T.undeclared)_.undeclared=T.undeclared;else delete _.undeclared;return this.$.node("structure",_)}filterKeys(T,_){let F=fW(this.inner),W=(J)=>{let Y=_.some(($)=>pF(J,$));return T==="pick"?Y:!Y};if(F.required)F.required=F.required.filter((J)=>W(J.key));if(F.optional)F.optional=F.optional.filter((J)=>W(J.key));if(F.index)F.index=F.index.filter((J)=>W(J.signature));return F}traverseAllows=(T,_)=>this._traverse("Allows",T,_);traverseApply=(T,_)=>this._traverse("Apply",T,_);_traverse=(T,_,F)=>{let W=F?.currentErrorCount??0;for(let J=0;J<this.props.length;J++)if(T==="Allows"){if(!this.props[J].traverseAllows(_,F))return!1}else if(this.props[J].traverseApply(_,F),F.failFast&&F.currentErrorCount>W)return!1;if(this.sequence){if(T==="Allows"){if(!this.sequence.traverseAllows(_,F))return!1}else if(this.sequence.traverseApply(_,F),F.failFast&&F.currentErrorCount>W)return!1}if(this.index||this.undeclared==="reject"){let J=Object.keys(_);J.push(...Object.getOwnPropertySymbols(_));for(let Y=0;Y<J.length;Y++){let $=J[Y];if(this.index){for(let Z of this.index)if(Z.signature.traverseAllows($,F)){if(T==="Allows"){if(!W_($,()=>Z.value.traverseAllows(_[$],F),F))return!1}else if(W_($,()=>Z.value.traverseApply(_[$],F),F),F.failFast&&F.currentErrorCount>W)return!1}}if(this.undeclared==="reject"&&!this.declaresKey($)){if(T==="Allows")return!1;if(F.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[$],meta:this.meta}),F.failFast)return!1}}}if(this.structuralMorph&&F&&!F.hasError())F.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((T)=>T.hasDefault())??[])}declaresKey=(T)=>(T in this.propsByKey)||this.index?.some((_)=>_.signature.allows(T))||this.sequence!==void 0&&z.intrinsic.nonNegativeIntegerString.allows(T);_compileDeclaresKey(T){let _=[];if(this.props.length)_.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let F of this.index)_.push(T.invoke(F.signature,{kind:"Allows",arg:"k"}));if(this.sequence)_.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return _.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",lH(this))}structuralMorphRef=this.structuralMorph&&VT(this.structuralMorph);compile(T){if(T.traversalKind==="Apply")T.initializeErrorCount();for(let _ of this.props)if(T.check(_),T.traversalKind==="Apply")T.returnIfFailFast();if(this.sequence){if(T.check(this.sequence),T.traversalKind==="Apply")T.returnIfFailFast()}if(this.index||this.undeclared==="reject")T.const("keys","Object.keys(data)"),T.line("keys.push(...Object.getOwnPropertySymbols(data))"),T.for("i < keys.length",()=>this.compileExhaustiveEntry(T));if(T.traversalKind==="Allows")return T.return(!0);if(this.structuralMorphRef)T.if("ctx && !ctx.hasError()",()=>{return T.line("ctx.queueMorphs(["),tH(T,this),T.line("])")})}compileExhaustiveEntry(T){if(T.const("k","keys[i]"),this.index)for(let _ of this.index)T.if(`${T.invoke(_.signature,{arg:"k",kind:"Allows"})}`,()=>T.traverseKey("k","data[k]",_.value));if(this.undeclared==="reject")T.if(`!(${this._compileDeclaresKey(T)})`,()=>{if(T.traversalKind==="Allows")return T.return(!1);return T.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>T.return())});return T}reduceJsonSchema(T,_){switch(T.type){case"object":return this.reduceObjectJsonSchema(T,_);case"array":let F=this.sequence?.reduceJsonSchema(T,_)??T;if(this.props.length||this.index)return _.fallback.arrayObject({code:"arrayObject",base:F,object:this.reduceObjectJsonSchema({type:"object"},_)});return F;default:return RT.throwInternalOperandError("structure",T)}}reduceObjectJsonSchema(T,_){if(this.props.length){T.properties={};for(let F of this.props){let W=F.value.toJsonSchemaRecurse(_);if(typeof F.key==="symbol"){_.fallback.symbolKey({code:"symbolKey",base:T,key:F.key,value:W,optional:F.optional});continue}if(F.hasDefault()){let J=typeof F.default==="function"?F.default():F.default;W.default=z.intrinsic.jsonData.allows(J)?J:_.fallback.defaultValue({code:"defaultValue",base:W,value:J})}T.properties[F.key]=W}if(this.requiredKeys.length&&T.properties)T.required=this.requiredKeys.filter((F)=>typeof F==="string"&&(F in T.properties))}if(this.index)for(let F of this.index){let W=F.value.toJsonSchemaRecurse(_);if(F.signature.equals(z.intrinsic.string)){T.additionalProperties=W;continue}for(let J of F.signature.branches){if(!J.extends(z.intrinsic.string)){T=_.fallback.symbolKey({code:"symbolKey",base:T,key:null,value:W,optional:!1});continue}let Y={type:"string"};if(J.hasKind("morph"))Y=_.fallback.morph({code:"morph",base:J.in.toJsonSchemaRecurse(_),out:J.out.toJsonSchemaRecurse(_)});if(!J.hasKind("intersection"))return e(`Unexpected index branch kind ${J.kind}.`);let{pattern:$}=J.inner;if($){let Z=Object.assign(Y,{pattern:$[0].rule});for(let G=1;G<$.length;G++)Y=_.fallback.patternIntersection({code:"patternIntersection",base:Z,pattern:$[G].rule});T.patternProperties??={},T.patternProperties[Z.pattern]=W}}}if(this.undeclared&&!T.additionalProperties)T.additionalProperties=!1;return T}}var m4={},dH=(T)=>{let _="";for(let F=0;F<T.defaultable.length;F++)_+=T.defaultable[F].defaultValueMorphRef;if(T.sequence?.defaultValueMorphsReference)_+=T.sequence?.defaultValueMorphsReference;if(T.undeclared==="delete"){if(_+="delete !(",T.required)for(let F of T.required)_+=F.compiledKey+" | ";if(T.optional)for(let F of T.optional)_+=F.compiledKey+" | ";if(T.index)for(let F of T.index)_+=F.signature.id+" | ";if(T.sequence)if(T.sequence.maxLength===null)_+=x.nonNegativeIntegerString.id;else for(let F=0;F<T.sequence.tuple.length;F++)_+=F+" | ";_+=")"}return _},lH=(T)=>{let _=dH(T);if(!_)return;if(m4[_])return m4[_];let F=(W,J)=>{for(let Y=0;Y<T.defaultable.length;Y++)if(!(T.defaultable[Y].key in W))T.defaultable[Y].defaultValueMorph(W,J);if(T.sequence?.defaultables)for(let Y=W.length-T.sequence.prefixLength;Y<T.sequence.defaultables.length;Y++)T.sequence.defaultValueMorphs[Y](W,J);if(T.undeclared==="delete"){for(let Y in W)if(!T.declaresKey(Y))delete W[Y]}return W};return m4[_]=F},tH=(T,_)=>{let W=`(data${_.defaultable.some((J)=>J.defaultValueMorph.length===2)||_.sequence?.defaultValueMorphs.some((J)=>J.length===2)?", ctx":""})`;return T.block(`${W} => `,(J)=>{for(let Y=0;Y<_.defaultable.length;Y++){let{serializedKey:$,defaultValueMorphRef:Z}=_.defaultable[Y];J.if(`!(${$} in data)`,(G)=>G.line(`${Z}${W}`))}if(_.sequence?.defaultables)J.for(`i < ${_.sequence.defaultables.length}`,(Y)=>Y.set("data[i]",5),`data.length - ${_.sequence.prefixLength}`);if(_.undeclared==="delete")J.forIn("data",(Y)=>Y.if(`!(${_._compileDeclaresKey(Y)})`,($)=>$.line("delete data[k]")));return J.return("data")})},o4={implementation:cH,Node:Q6},iH=(T)=>{if(P(T,"root")&&T.hasKind("unit"))T=T.unit;if(typeof T==="number")T=`${T}`;return T},nH=(T,_)=>`${T} is not allowed as an array index on ${_}. Use the 'nonNegativeIntegerString' keyword instead.`,mW=(T,_,F)=>{let[W,J]=p8(T.branches,($)=>$.hasKind("unit"));if(!W.length)return{index:F.node("index",{signature:T,value:_})};let Y={};for(let $ of W){let Z=F.node("required",{key:$.unit,value:_});Y[Z.kind]=s(Y[Z.kind],Z)}if(J.length)Y.index=F.node("index",{signature:J,value:_});return Y},rH=(T)=>P(T,"root")?T.expression:d(T),M6=(T,_)=>`Key${_.length===1?"":"s"} ${_.map(rH).join(", ")} ${_.length===1?"does":"do"} not exist on ${T}`;var r0={...gJ,alias:gF.implementation,domain:gW.implementation,unit:x4.implementation,proto:mF.implementation,union:v4.implementation,morph:j4.implementation,intersection:q4.implementation,divisor:E4.implementation,pattern:N4.implementation,predicate:R4.implementation,required:h4.implementation,optional:bF.implementation,index:b4.implementation,sequence:p4.implementation,structure:o4.implementation};z.defaultConfig=i8(Object.assign(c(r0,(T,_)=>[T,_.defaults]),{jitless:TJ(),clone:s8,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:RT.defaultConfig}));z.resolvedConfig=fF(z.defaultConfig,z.config);var lJ={...mJ,alias:gF.Node,domain:gW.Node,unit:x4.Node,proto:mF.Node,union:v4.Node,morph:j4.Node,intersection:q4.Node,divisor:E4.Node,pattern:N4.Node,predicate:R4.Node,required:h4.Node,optional:bF.Node,index:b4.Node,sequence:p4.Node,structure:o4.Node};class e0 extends a1{get[iT](){return"module"}}var u4=(T,_)=>new e0(c(T,(F,W)=>[F,P(W,"module")?u4(W,_):_.bindReference(W)]));var sH=(T)=>XT(T)?T:("branches"in T)&&XT(T.branches)?T.branches:void 0,aH=(T,_)=>E(`Node of kind ${_} is not valid as a ${T} definition`),R6=(T)=>`#${T} duplicates public alias ${T}`,c4={};z.ambient??={};var E6,K6="function $",eH=(T)=>V6(T,L6(T)),V6=(T,_)=>{let F=_.write(K6,4),W=_.compile()();for(let J of T){if(J.precompilation)continue;if(J.traverseAllows=W[`${J.id}Allows`].bind(W),J.isRoot()&&!J.allowsRequiresContext)J.allows=J.traverseAllows;if(J.traverseApply=W[`${J.id}Apply`].bind(W),W[`${J.id}Optimistic`])J.traverseOptimistic=W[`${J.id}Optimistic`].bind(W);J.precompilation=F}},L6=(T)=>new kW().return(T.reduce((_,F)=>{let W=new kF({kind:"Allows"}).indent();F.compile(W);let J=W.write(`${F.id}Allows`),Y=new kF({kind:"Apply"}).indent();F.compile(Y);let $=Y.write(`${F.id}Apply`),Z=`${_}${J},
|
|
44
44
|
${$},
|
|
45
45
|
`;if(!F.hasKind("union"))return Z;let G=new kF({kind:"Allows",optimistic:!0}).indent();F.compile(G);let X=G.write(`${F.id}Optimistic`);return`${Z}${X},
|
|
46
46
|
`},`{
|
|
47
|
-
`)+"}");class oW{config;resolvedConfig;name;get[iT](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(T,_){if(this.config=fF(z.config,_),this.resolvedConfig=fF(z.resolvedConfig,_),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(c4).length}`,this.name in c4)E(`A Scope already named ${this.name} already exists`);c4[this.name]=this;let F=Object.entries(T).map((W)=>this.preparseOwnAliasEntry(...W));for(let[W,J]of F){let Y=W;if(W[0]==="#"){if(Y=W.slice(1),Y in this.aliases)E(R6(Y));this.aliases[Y]=J}else{if(Y in this.aliases)E(R6(W));this.aliases[Y]=J,this.exportedNames.push(Y)}if(!P(J,"module")&&!P(J,"generic")&&!J0(J)){let $=this.preparseOwnDefinitionFormat(J,{alias:Y});this.resolutions[Y]=P($,"root")?this.bindReference($):this.createParseContext($).id}}E6??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[E6.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=z.intrinsic?c(z.intrinsic,(W,J)=>W.startsWith("json")?[]:[W,this.bindReference(J)]):{}}cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(T){return T}generic=(...T)=>{let _=this;return(F,W)=>new G0(T,W?new yW(F):F,_,_,W??null)};units=(T,_)=>{let F=[];for(let J of T)if(!F.includes(J))F.push(J);let W=F.map((J)=>this.node("unit",{unit:J},_));return this.node("union",W,{..._,prereduced:!0})};lazyResolutions=[];lazilyResolve(T,_){let F=this.node("alias",{reference:_??"synthetic",resolve:T},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(F);return F}schema=(T,_)=>this.finalize(this.parseSchema(T,_));parseSchema=(T,_)=>this.node(yF(T),T,_);preparseNode(T,_,F){let W=typeof T==="string"?T:yF(_,T);if(OT(_)&&_.kind===W)return _;if(W==="alias"&&!F?.prereduced){let{reference:$}=gF.implementation.normalize(_,this);if($.startsWith("$")){let Z=this.resolveRoot($.slice(1));_=Z,W=Z.kind}}else if(W==="union"&&T_(_,"object")){let $=sH(_);if($?.length===1)_=$[0],W=yF(_)}if(OT(_)&&_.kind===W)return _;let Y=r0[W].normalize?.(_,this)??_;if(OT(Y))return Y.kind===W?Y:aH(W,Y.kind);return{...F,$:this,kind:W,def:Y,prefix:F.alias??W}}bindReference(T){let _;if(OT(T))_=T.$===this?T:new T.constructor(T.attachments,this);else _=T.$===this?T:new G0(T.params,T.bodyDef,T.$,this,T.hkt);if(!this.resolved)Object.assign(this.referencesById,_.referencesById);return _}resolveRoot(T){return this.maybeResolveRoot(T)??E(t4(T))}maybeResolveRoot(T){let _=this.maybeResolve(T);if(P(_,"generic"))return;return _}maybeResolveSubalias(T){return d4(this.aliases,T)??d4(this.ambient,T)}get ambient(){return z.ambient}maybeResolve(T){let _=this.resolutions[T];if(_){if(typeof _!=="string")return this.bindReference(_);let W=nT[_];if(P(W,"root"))return this.resolutions[T]=W;if(P(W,"context")){if(W.phase==="resolving")return this.node("alias",{reference:`$${T}`},{prereduced:!0});if(W.phase==="resolved")return e(`Unexpected resolved context for was uncached by its scope: ${d(W)}`);W.phase="resolving";let J=this.bindReference(this.parseOwnDefinitionFormat(W.def,W));return W.phase="resolved",nT[J.id]=J,nT[W.id]=J,this.resolutions[T]=J}return e(`Unexpected nodesById entry for ${_}: ${d(W)}`)}let F=this.aliases[T]??this.ambient?.[T];if(!F)return this.maybeResolveSubalias(T);if(F=this.normalizeRootScopeValue(F),P(F,"generic"))return this.resolutions[T]=this.bindReference(F);if(P(F,"module")){if(!F.root)E(I6(T));return this.resolutions[T]=this.bindReference(F.root)}return this.resolutions[T]=this.parse(F,{alias:T})}createParseContext(T){let _=T.id??C4(T.prefix);return nT[_]=Object.assign(T,{[iT]:"context",$:this,id:_,phase:"unresolved"})}traversal(T){return new f_(T,this.resolvedConfig)}import(...T){return new e0(c(this.export(...T),(_,F)=>[`#${_}`,F]))}precompilation;_exportedResolutions;_exports;export(...T){if(!this._exports){this._exports={};for(let F of this.exportedNames){let W=this.aliases[F];this._exports[F]=P(W,"module")?u4(W,this):z6(this.maybeResolve(F))}for(let F of this.lazyResolutions)F.resolution;if(this._exportedResolutions=S6(this,this._exports),this._json=D6(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let F=L6(this.references);this.precompilation=F.write(V6,4),K6(this.references,F)}this.resolved=!0}let _=T.length?T:this.exportedNames;return new e0(c(_,(F,W)=>[W,this._exports[W]]))}resolve(T){return this.export()[T]}node=(T,_,F={})=>{let W=this.preparseNode(T,_,F);if(OT(W))return this.bindReference(W);let J=this.createParseContext(W),Y=B4(J),$=this.bindReference(Y);return nT[J.id]=$};parse=(T,_={})=>this.finalize(this.parseDefinition(T,_));parseDefinition(T,_={}){if(P(T,"root"))return this.bindReference(T);let F=this.preparseOwnDefinitionFormat(T,_);if(P(F,"root"))return this.bindReference(F);let W=this.createParseContext(F);nT[W.id]=W;let J=this.bindReference(this.parseOwnDefinitionFormat(T,W));if(J.isCyclic)J=dJ(J,W.id);return nT[W.id]=J,J}finalize(T){if(z6(T),!T.precompilation&&!this.resolvedConfig.jitless)eH(T.references);return T}}class l4 extends oW{parseOwnDefinitionFormat(T,_){return B4(_)}preparseOwnDefinitionFormat(T,_){return this.preparseNode(yF(T),T,_)}preparseOwnAliasEntry(T,_){return[T,_]}normalizeRootScopeValue(T){return T}}var z6=(T)=>{let _=T.references.filter((F)=>F.hasKind("alias"));for(let F of _){Object.assign(F.referencesById,F.resolution.referencesById);for(let W of T.references)if(F.id in W.referencesById)Object.assign(W.referencesById,F.referencesById)}return T},D6=(T)=>c(T,(_,F)=>[_,P(F,"root")||P(F,"generic")?F.json:P(F,"module")?D6(F):e(`Unexpected resolution ${d(F)}`)]),d4=(T,_)=>{let F=_.indexOf(".");if(F===-1)return;let W=_.slice(0,F),J=T[W];if(J===void 0)return;if(!P(J,"module"))return E(T9(W));let Y=_.slice(F+1),$=J[Y];if($===void 0)return d4(J,Y);if(P($,"root")||P($,"generic"))return $;if(P($,"module"))return $.root??E(I6(_));e(`Unexpected resolution for alias '${_}': ${d($)}`)},uW=(T,_)=>new l4(T,_),uF=new l4({});var S6=(T,_)=>{let F={};for(let W in _){let J=_[W];if(P(J,"module")){let Y=S6(T,J),$=c(Y,(Z,G)=>[`${W}.${Z}`,G]);Object.assign(F,$)}else if(P(J,"root")||P(J,"generic"))F[W]=J;else e(`Unexpected scope resolution ${d(J)}`)}return F},t4=(T)=>`'${T}' is unresolvable`,T9=(T)=>`'${T}' must reference a module to be accessed using dot syntax`,I6=(T)=>`Reference to submodule '${T}' must specify an alias`;uF.export();var{schema:WT,node:TF,defineSchema:Zz,generic:K_}=uF;var i4="^(?:0|[1-9]\\d*)$",_9=new RegExp(i4),Az=KT(_9);var N6=uW({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();z.intrinsic={...N6};var C6=uW({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:i4}},{prereducedAliases:!0}).export();Object.assign(z.intrinsic,C6);var F9=uW({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),x={...N6,...C6,...F9,emptyStructure:TF("structure",{},{prereduced:!0})};z.intrinsic={...x};var k6=(T)=>typeof T==="string"&&T[0]==="d"&&(T[1]==="'"||T[1]==='"')&&T.at(-1)===T[1],B6=(T)=>T.toString()!=="Invalid Date",f6=(T)=>T.slice(2,-1),n4=(T)=>`'${T}' could not be parsed by the Date constructor`,P6=(T,_)=>W9(T,_),W9=(T,_)=>{let F=new Date(T);if(B6(F))return F;let W=GJ(T);if(W!==void 0){let J=new Date(W);if(B6(J))return J}return _?E(_===!0?n4(T):_):void 0};var r4=(T,_)=>{let F=T.scanner.shiftUntil(J9[j6[_]]);if(T.scanner.lookahead==="")return T.error($9(F,_));if(T.scanner.shift(),_==="/"){try{new RegExp(F)}catch(W){E(String(W))}T.root=T.ctx.$.node("intersection",{domain:"string",pattern:F},{prereduced:!0})}else if(qT(_,s4))T.root=T.ctx.$.node("unit",{unit:F});else{let W=P6(F,n4(F));T.root=T.ctx.$.node("unit",{meta:F,unit:W})}},s4={"'":1,'"':1},q6={"/":1,"'":1,'"':1},j6={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},J9={"'":(T)=>T.lookahead==="'",'"':(T)=>T.lookahead==='"',"/":(T)=>T.lookahead==="/"},Y9={'"':"double-quote","'":"single-quote","/":"forward slash"},$9=(T,_)=>`${_}${T} requires a closing ${Y9[j6[_]]}`;var y6=(T)=>`Private type references should not include '#'. Use '${T}' instead.`,cW="Optional definitions like 'string?' are only valid as properties in an object or tuple",dW="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var v6={">":!0,">=":!0},x6={"<":!0,"<=":!0};var _F={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},b6=(T)=>`Unmatched )${T===""?"":` before ${T}`}`,lW=(T)=>`Missing ${T}`,h6=(T,_)=>`Left bounds are only valid when paired with right bounds (try ...${_}${T})`,tW=(T)=>`Left-bounded expressions must specify their limits using < or <= (was ${T})`,p6=(T,_,F,W)=>`An expression may have at most one left bound (parsed ${T}${_F[_]}, ${F}${_F[W]})`;var g6=(T,_,F)=>m6(T,_,F,[]),m6=(T,_,F,W)=>{let J=F.parseUntilFinalizer();if(W.push(J.root),J.finalizer===">"){if(W.length!==_.params.length)return F.error(a4(T,_.names,W.map((Y)=>Y.expression)));return W}if(J.finalizer===",")return m6(T,_,F,W);return J.error(lW(">"))},a4=(T,_,F)=>`${T}<${_.join(", ")}> requires exactly ${_.length} args (got ${F.length}${F.length===0?"":`: ${F.join(", ")}`})`;var e4=(T)=>{let _=T.scanner.shiftUntilNextTerminator();if(_==="keyof")T.addPrefix("keyof");else T.root=X9(T,_)},Z9=(T,_,F)=>{if(F.scanner.shiftUntilNonWhitespace(),F.scanner.shift()!=="<")return F.error(a4(T,_.names,[]));let J=g6(T,_,F);return _(...J)},X9=(T,_)=>G9(T,_)??A9(T,_)??T.error(_===""?T.scanner.lookahead==="#"?y6(T.shiftedByOne().scanner.shiftUntilNextTerminator()):T2(T):t4(_)),G9=(T,_)=>{if(T.ctx.args?.[_]){let W=T.ctx.args[_];if(typeof W!=="string")return W;return T.ctx.$.node("alias",{reference:W},{prereduced:!0})}let F=T.ctx.$.maybeResolve(_);if(P(F,"root"))return F;if(F===void 0)return;if(P(F,"generic"))return Z9(_,F,T);return E(`Unexpected resolution ${d(F)}`)},A9=(T,_)=>{let F=AJ(_);if(F!==void 0)return T.ctx.$.node("unit",{unit:F});let W=OJ(_);if(W!==void 0)return T.ctx.$.node("unit",{unit:W})},T2=(T)=>{let _=T.previousOperator();return _?_2(_,T.scanner.unscanned):H9(T.scanner.unscanned)},_2=(T,_="")=>`Token '${T}' requires a right operand${_?` before '${_}'`:""}`,H9=(T)=>`Expected an expression${T?` before '${T}'`:""}`;var F2=(T)=>T.scanner.lookahead===""?T.error(T2(T)):T.scanner.lookahead==="("?T.shiftedByOne().reduceGroupOpen():T.scanner.lookaheadIsIn(q6)?r4(T,T.scanner.shift()):T.scanner.lookaheadIsIn(Y0)?F2(T.shiftedByOne()):T.scanner.lookahead==="d"?T.scanner.nextLookahead in s4?r4(T,`${T.scanner.shift()}${T.scanner.shift()}`):e4(T):e4(T);class r_ extends Z4{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in r_.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...Y0};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(T,_)=>T===">"?_[0]==="="?_[1]==="=":_.trimStart()===""||qT(_.trimStart()[0],r_.terminatingChars):T==="="?_[0]!=="=":T===","||T==="?"}var u6=(T,_)=>{let F=O9(T,_);if(T.root.hasKind("unit")){if(typeof T.root.unit==="number"){T.reduceLeftBound(T.root.unit,F),T.unsetRoot();return}if(T.root.unit instanceof Date){let W=`d'${T.root.description??T.root.unit.toISOString()}'`;T.unsetRoot(),T.reduceLeftBound(W,F);return}}return M9(T,F)},c6={"<":1,">":1,"=":1},O9=(T,_)=>T.scanner.lookaheadIs("=")?`${_}${T.scanner.shift()}`:_;var o6=(T,_,F,W)=>{if(F.extends(z.intrinsic.number)){if(typeof _!=="number")return E(W2(T,_,W));return T==="=="?["min","max"]:T[0]===">"?["min"]:["max"]}if(F.extends(z.intrinsic.lengthBoundable)){if(typeof _!=="number")return E(W2(T,_,W));return T==="=="?["exactLength"]:T[0]===">"?["minLength"]:["maxLength"]}if(F.extends(z.intrinsic.Date))return T==="=="?["after","before"]:T[0]===">"?["after"]:["before"];return E(qJ(F.expression))},U9=(T)=>({rule:k6(T.limit)?f6(T.limit):T.limit,exclusive:T.comparator.length===1}),M9=(T,_)=>{let F=T.unsetRoot(),W=T.scanner.location;T.parseOperand();let J=T.unsetRoot(),Y=T.scanner.sliceChars(W,T.scanner.location);if(T.root=F,!J.hasKind("unit")||typeof J.unit!=="number"&&!(J.unit instanceof Date))return T.error(W2(_,Y,"right"));let $=J.unit,Z=_.length===1,G=o6(_,typeof $==="number"?$:Y,F,"right");for(let O of G)T.constrainRoot(O,_==="=="?{rule:$}:{rule:$,exclusive:Z});if(!T.branches.leftBound)return;if(!qT(_,x6))return T.error(tW(_));let X=o6(T.branches.leftBound.comparator,T.branches.leftBound.limit,F,"left");T.constrainRoot(X[0],U9(T.branches.leftBound)),T.branches.leftBound=null},W2=(T,_,F)=>`Comparator ${F==="left"?_F[T]:T} must be ${F==="left"?"preceded":"followed"} by a corresponding literal (was ${_})`;var d6=(T)=>{T.scanner.shiftUntilNonWhitespace();let _=T.scanner.shiftUntilNextTerminator();T.root=T.root.brand(_)};var t6=(T)=>{let _=T.scanner.shiftUntilNextTerminator(),F=HJ(_,{errorOnFail:l6(_)});if(F===0)T.error(l6(0));T.root=T.root.constrain("divisor",F)},l6=(T)=>`% operator must be followed by a non-zero integer literal (was ${T})`;var J2=(T)=>{let _=T.scanner.shift();return _===""?T.finalize(""):_==="["?T.scanner.shift()==="]"?T.setRoot(T.root.array()):T.error(w9):_==="|"?T.scanner.lookahead===">"?T.shiftedByOne().pushRootToBranch("|>"):T.pushRootToBranch(_):_==="&"?T.pushRootToBranch(_):_===")"?T.finalizeGroup():r_.lookaheadIsFinalizing(_,T.scanner.unscanned)?T.finalize(_):qT(_,c6)?u6(T,_):_==="%"?t6(T):_==="#"?d6(T):(_ in Y0)?J2(T):T.error(iW(_))},iW=(T,_="")=>`'${T}' is not allowed here${_&&` (should be ${_})`}`,w9="Missing expected ']'";var i6=(T)=>{let _=T.unsetRoot();T.parseOperand();let F=T.unsetRoot();if(!F.hasKind("unit"))return T.error(Q9(F.expression));let W=F.unit instanceof Date?()=>new Date(F.unit):F.unit;return[_,"=",W]},Q9=(T)=>`Default value '${T}' must a literal value`;var Y2=(T,_)=>{let F=_.$.maybeResolveRoot(T);if(F)return F;if(T.endsWith("[]")){let Y=_.$.maybeResolveRoot(T.slice(0,-2));if(Y)return Y.array()}let W=new FF(new r_(T),_),J=R9(W);if(W.finalizer===">")E(iW(">"));return J},R9=(T)=>{T.parseOperand();let _=cF(T).root;if(!_)return e(`Root was unexpectedly unset after parsing string '${T.scanner.scanned}'`);if(T.finalizer==="=")_=i6(T);else if(T.finalizer==="?")_=[_,"?"];if(T.scanner.shiftUntilNonWhitespace(),T.scanner.lookahead)E(iW(T.scanner.lookahead));return _},cF=(T)=>{while(T.finalizer===void 0)E9(T);return T},E9=(T)=>T.hasRoot()?T.parseOperator():T.parseOperand();class FF{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(T,_){this.scanner=T,this.ctx=_}error(T){return E(T)}hasRoot(){return this.root!==void 0}setRoot(T){this.root=T}unsetRoot(){let T=this.root;return this.root=void 0,T}constrainRoot(...T){this.root=this.root.constrain(T[0],T[1])}finalize(T){if(this.groups.length)return this.error(lW(")"));this.finalizeBranches(),this.finalizer=T}reduceLeftBound(T,_){let F=_F[_];if(!qT(F,v6))return this.error(tW(_));if(this.branches.leftBound)return this.error(p6(this.branches.leftBound.limit,this.branches.leftBound.comparator,T,F));this.branches.leftBound={comparator:F,limit:T}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let T=this.groups.pop();if(!T)return this.error(b6(this.scanner.unscanned));this.branches=T}addPrefix(T){this.branches.prefixes.push(T)}applyPrefixes(){while(this.branches.prefixes.length){let T=this.branches.prefixes.pop();this.root=T==="keyof"?this.root.keyof():e(`Unexpected prefix '${T}'`)}}pushRootToBranch(T){this.assertRangeUnset(),this.applyPrefixes();let _=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(_)??_,T==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,T==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return cF(new FF(this.scanner,this.ctx))}parseOperator(){return J2(this)}parseOperand(){return F2(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(h6(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var z9="An empty string is not a valid generic parameter name",nW=(T,_,F)=>{T.shiftUntilNonWhitespace();let W=T.shiftUntilNextTerminator();if(W===""){if(T.lookahead===""&&_.length)return _;return E(z9)}return T.shiftUntilNonWhitespace(),V9(T,W,_,F)},n6="extends ",V9=(T,_,F,W)=>{if(T.shiftUntilNonWhitespace(),T.unscanned.startsWith(n6))T.jumpForward(n6.length);else{if(T.lookahead===",")T.shift();return F.push(_),nW(T,F,W)}let J=cF(new FF(T,W));return F.push([_,J.root]),nW(T,F,W)};class $2 extends k_{$;constructor(T){super((..._)=>new dF(T)(..._),{bind:T});this.$=T}in(T){return new dF(this.$,T===void 0?void 0:this.$.parse(T))}at(T,_){return new dF(this.$).at(T,_)}case(T,_){return new dF(this.$).case(T,_)}}class dF extends k_{$;in;key;branches=[];constructor(T,_){super((F)=>this.caseEntries(Object.entries(F).map(([W,J])=>W==="default"?[W,J]:[this.$.parse(W),J])));this.$=T,this.in=_}at(T,_){if(this.key)E(L9);if(this.branches.length)E(K9);return this.key=T,_?this.match(_):this}case(T,_){return this.caseEntry(this.$.parse(T),_)}caseEntry(T,_){let W=(this.key?this.$.parse({[this.key]:T}):T).pipe(_);return this.branches.push(W),this}match(T){return this(T)}strings(T){return this.caseEntries(Object.entries(T).map(([_,F])=>_==="default"?[_,F]:[this.$.node("unit",{unit:_}),F]))}caseEntries(T){for(let _=0;_<T.length;_++){let[F,W]=T[_];if(F==="default"){if(_!==T.length-1)E("default may only be specified as the last key of a switch definition");return this.default(W)}if(typeof W!=="function")return E(`Value for case "${F}" must be a function (was ${PT(W)})`);this.caseEntry(F,W)}return this}default(T){if(typeof T==="function")this.case(x.unknown,T);let _={branches:this.branches,ordered:!0};if(T==="never"||T==="assert")_.meta={onFail:r6};let F=this.$.node("union",_);if(!this.in)return this.$.finalize(F);let W=this.in.pipe(F);if(T==="never"||T==="assert")W=W.configureReferences({onFail:r6},"self");return this.$.finalize(W)}}var r6=(T)=>T.throw(),K9="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",L9="At most one key matcher may be specified per expression";var rW=(T,_)=>{if(XT(T)){if(T[1]==="=")return[_.$.parseOwnDefinitionFormat(T[0],_),"=",T[2]];if(T[1]==="?")return[_.$.parseOwnDefinitionFormat(T[0],_),"?"]}return sW(T,_)},s6="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",a6="Only required keys may specify default values, e.g. { value: 'number = 0' }";var e6=(T,_)=>{let F,W={},J=S0(T);for(let[$,Z]of J){let G=I9($);if(G.kind==="spread"){if(!h_(W))return E(S9);let K=_.$.parseOwnDefinitionFormat(Z,_);if(K.equals(x.object))continue;if(!K.hasKind("intersection")||!K.basis?.equals(x.object))return E(N9(K.expression));F=K.structure;continue}if(G.kind==="undeclared"){if(Z!=="reject"&&Z!=="delete"&&Z!=="ignore")E(D9(Z));W.undeclared=Z;continue}let X=rW(Z,_),O=G;if(G.kind==="required"){if(!XT(X))Z2(W,"required",{key:G.normalized,value:X},_);else Z2(W,"optional",X[1]==="="?{key:G.normalized,value:X[0],default:X[2]}:{key:G.normalized,value:X[0]},_);continue}if(XT(X)){if(X[1]==="?")E(s6);if(X[1]==="=")E(a6)}if(G.kind==="optional"){Z2(W,"optional",{key:G.normalized,value:X},_);continue}let M=_.$.parseOwnDefinitionFormat(O.normalized,_),Q=mW(M,X,_.$);if(Q.index)W.index=s(W.index,Q.index);if(Q.required)W.required=s(W.required,Q.required)}let Y=_.$.node("structure",W);return _.$.parseSchema({domain:"object",structure:F?.merge(Y)??Y})},Z2=(T,_,F,W)=>{T[_]=s(T[_],W.$.node(_,F))},D9=(T)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${d(T)})`,S9="Spread operator may only be used as the first key in an object",I9=(T)=>typeof T==="symbol"?{kind:"required",normalized:T}:T.at(-1)==="?"?T.at(-2)===DF?{kind:"required",normalized:`${T.slice(0,-2)}?`}:{kind:"optional",normalized:T.slice(0,-1)}:T[0]==="["&&T.at(-1)==="]"?{kind:"index",normalized:T.slice(1,-1)}:T[0]===DF&&T[1]==="["&&T.at(-1)==="]"?{kind:"required",normalized:T.slice(1)}:T==="..."?{kind:"spread"}:T==="+"?{kind:"undeclared"}:{kind:"required",normalized:T==="\\..."?"...":T==="\\+"?"+":T},N9=(T)=>`Spread operand must resolve to an object literal type (was ${T})`;var _Y=(T,_)=>x9(T)?YY[T[0]](T,_):y9(T)?JY[T[1]](T,_):null,C9=(T,_)=>_.$.parseOwnDefinitionFormat(T[1],_).keyof(),X2=(T,_)=>{if(T[2]===void 0)return E(_2(T[1],""));let F=_.$.parseOwnDefinitionFormat(T[0],_),W=_.$.parseOwnDefinitionFormat(T[2],_);if(T[1]==="|")return _.$.node("union",{branches:[F,W]});let J=T[1]==="&"?J_(F,W,_.$):jF(F,W,_.$);if(J instanceof N)return J.throw();return J},B9=(T,_)=>_.$.parseOwnDefinitionFormat(T[0],_).array(),k9=(T,_)=>{if(typeof T[2]!=="function")return E(FY("=>",T[2]));return _.$.parseOwnDefinitionFormat(T[0],_).pipe(T[2])},FY=(T,_)=>`${T===":"?"Narrow":"Morph"} expression requires a function following '${T}' (was ${typeof _})`,f9=(T,_)=>{if(typeof T[2]!=="function")return E(FY(":",T[2]));return _.$.parseOwnDefinitionFormat(T[0],_).constrain("predicate",T[2])},P9=(T,_)=>_.$.parseOwnDefinitionFormat(T[0],_).configureReferences(T[2],"shallow"),WY=(T)=>T,q9=WY({"[]":B9,"?":()=>E(cW)}),j9=WY({"|":X2,"&":X2,":":f9,"=>":k9,"|>":X2,"@":P9,"=":()=>E(dW)}),JY={...q9,...j9},y9=(T)=>JY[T[1]]!==void 0,v9=(T)=>T,YY=v9({keyof:C9,instanceof:(T,_)=>{if(typeof T[1]!=="function")return E(TY(KF(T[1])));let F=T.slice(1).map((W)=>typeof W==="function"?_.$.node("proto",{proto:W}):E(TY(KF(W))));return F.length===1?F[0]:_.$.node("union",{branches:F})},"===":(T,_)=>_.$.units(T.slice(1))}),x9=(T)=>YY[T[0]]!==void 0,TY=(T)=>`Expected a constructor following 'instanceof' operator (was ${T})`;var XY=(T,_)=>{let F=[{}],W=0;while(W<T.length){let J=!1;if(T[W]==="..."&&W<T.length-1)J=!0,W++;let Y=rW(T[W],_),[$,Z,G]=!XT(Y)?[Y]:Y;if(W++,J){if(!$.extends(z.intrinsic.Array))return E(p9($.expression));F=F.flatMap((X)=>$.distribute((O)=>h9(fW(X),O)))}else F=F.map((X)=>{if(Z==="?")return GY(X,$);if(Z==="=")return b9(X,$,G);return G2(X,$)})}return _.$.parseSchema(F.map((J)=>h_(J)?{proto:Array,exactLength:0}:{proto:Array,sequence:J}))},G2=(T,_)=>{if(T.defaultables||T.optionals)return E(T.variadic?g4:g9);if(T.variadic)T.postfix=s(T.postfix,_);else T.prefix=s(T.prefix,_);return T},GY=(T,_)=>{if(T.variadic)return E(AY);return T.optionals=s(T.optionals,_),T},b9=(T,_,F)=>{if(T.variadic)return E(AY);if(T.optionals)return E(m9);return T.defaultables=s(T.defaultables,[[_,F]]),T},$Y=(T,_)=>{if(T.postfix)E(ZY);if(T.variadic){if(!T.variadic.equals(_))E(ZY)}else T.variadic=_.internal;return T},h9=(T,_)=>{let F=_.select({method:"find",kind:"sequence"});if(!F)return $Y(T,z.intrinsic.unknown);if(F.prefix)for(let W of F.prefix)G2(T,W);if(F.optionals)for(let W of F.optionals)GY(T,W);if(F.variadic)$Y(T,F.variadic);if(F.postfix)for(let W of F.postfix)G2(T,W);return T},p9=(T)=>`Spread element must be an array (was ${T})`,ZY="A tuple may have at most one variadic element",g9="A required element may not follow an optional element",AY="An optional element may not follow a variadic element";var m9="A defaultable element may not follow an optional element without a default";var o9={},sW=(T,_)=>{if(typeof T==="string"){if(_.args&&Object.keys(_.args).some((W)=>T.includes(W)))return Y2(T,_);let F=o9[_.$.name]??={};return F[T]??=Y2(T,_)}return T_(T,"object")?u9(T,_):E(A2(PT(T)))},u9=(T,_)=>{let F=VF(T);switch(F){case void 0:if(P(T,"root"))return T;return e6(T,_);case"Array":return c9(T,_);case"RegExp":return _.$.node("intersection",{domain:"string",pattern:T},{prereduced:!0});case"Function":{let W=J0(T)?T():T;if(P(W,"root"))return W;return E(A2("Function"))}default:return E(A2(F??d(T)))}},c9=(T,_)=>_Y(T,_)??XY(T,_),A2=(T)=>`Type definitions must be strings or objects (was ${T})`;class H2 extends k_{constructor(T){let _=Object.assign({errors:F_,hkt:uT,$:T,raw:T.parse,module:T.constructor.module,scope:T.constructor.scope,define:T.define,match:T.match,generic:T.generic,schema:T.schema,keywords:T.ambient,unit:T.unit,enumerated:T.enumerated,instanceOf:T.instanceOf,valueOf:T.valueOf,or:T.or,and:T.and,merge:T.merge,pipe:T.pipe},T.ambientAttachments);super((...F)=>{if(F.length===1)return T.parse(F[0]);if(F.length===2&&typeof F[0]==="string"&&F[0][0]==="<"&&F[0].at(-1)===">"){let W=F[0].slice(1,-1),J=T.parseGenericParams(W,{});return new G0(J,F[1],T,T,null)}return T.parse(F)},{bind:T,attach:_})}}var WF=z;class aW extends oW{get ambientAttachments(){if(!WF.typeAttachments)return;return this.cacheGetter("ambientAttachments",c(WF.typeAttachments,(T,_)=>[T,this.bindReference(_)]))}preparseOwnAliasEntry(T,_){let F=T.indexOf("<");if(F===-1){if(P(_,"module")||P(_,"generic"))return[T,_];let Y=this.name==="ark"?T:T==="root"?this.name:`${this.name}.${T}`,$=this.resolvedConfig.keywords?.[Y];if($)_=[_,"@",$];return[T,_]}if(T.at(-1)!==">")E("'>' must be the last character of a generic declaration in a scope");let W=T.slice(0,F),J=T.slice(F+1,-1);return[W,()=>{let Y=this.parseGenericParams(J,{alias:W});return kJ(Y,_,this)}]}parseGenericParams(T,_){return nW(new r_(T),[],this.createParseContext({..._,def:T,prefix:"generic"}))}normalizeRootScopeValue(T){if(J0(T)&&!P(T,"generic"))return T();return T}preparseOwnDefinitionFormat(T,_){return{..._,def:T,prefix:_.alias??"type"}}parseOwnDefinitionFormat(T,_){if(!(_.alias&&(_.alias in this.aliases))&&!_.args)_.args={this:_.id};let W=sW(T,_);if(XT(W)){if(W[1]==="=")return E(dW);if(W[1]==="?")return E(cW)}return W}unit=(T)=>this.units([T]);valueOf=(T)=>this.units(n8(T));enumerated=(...T)=>this.units(T);instanceOf=(T)=>this.node("proto",{proto:T},{prereduced:!0});or=(...T)=>this.schema(T.map((_)=>this.parse(_)));and=(...T)=>T.reduce((_,F)=>_.and(this.parse(F)),this.intrinsic.unknown);merge=(...T)=>T.reduce((_,F)=>_.merge(this.parse(F)),this.intrinsic.object);pipe=(...T)=>this.intrinsic.unknown.pipe(...T);match=new $2(this);declare=()=>({type:this.type});define(T){return T}type=new H2(this);static scope=(T,_={})=>new aW(T,_);static module=(T,_={})=>this.scope(T,_).export()}var O2=Object.assign(aW.scope,{define:(T)=>T}),r=aW;class HY extends uT{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var d9=K_(["base",x.object],["props",x.object])((T)=>T.base.merge(T.props),HY),OY=r.module({Key:x.key,Merge:d9});class UY extends uT{}var l9=K_("element")((T)=>{let _=T.element.exclude(x.Array),F=_.array();return _.rawOr(F).pipe(W0).distribute((W)=>W.assertHasKind("morph").declareOut(F),WT)},UY),MY=r.module({root:x.Array,readonly:"root",index:x.nonNegativeIntegerString,liftFrom:l9},{name:"Array"});var U2=WT(["string",N0.FileConstructor]),t9=U2.rawOr(U2.array()),wY=WT({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:t9}}),QY=r.module({root:["instanceof",FormData],value:U2,parsed:wY,parse:WT({in:FormData,morphs:(T)=>{let _={};for(let[F,W]of T)if(F in _){let J=_[F];if(typeof J==="string"||J instanceof N0.FileConstructor)_[F]=[J,W];else J.push(W)}else _[F]=W;return _},declaredOut:wY})},{name:"FormData"});var RY=r.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var i9={Boolean:1,Number:1,String:1},EY=r.module({...c({...e1,..._4},(T,_)=>(T in i9)?[]:[T,["instanceof",_]]),Array:MY,TypedArray:RY,FormData:QY});var n9=WT({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),r9=WT({domain:"number",divisor:1}),eW=r.module({root:x.number,integer:r9,epoch:n9,safe:WT({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var ET=(T,_,F)=>{let W={domain:"string",pattern:{rule:T.source,flags:T.flags,meta:_}};if(F)W.meta={format:F};return TF("intersection",W)},zY=ET(SF,"a well-formed integer string"),PY=r.module({root:zY,parse:WT({in:zY,morphs:(T,_)=>{let F=Number.parseInt(T);return Number.isSafeInteger(F)?F:_.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:x.integer})},{name:"string.integer"}),s9=ET(/^[\dA-Fa-f]+$/,"hex characters only"),a9=r.module({root:ET(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:ET(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),VY=ET(/^[A-Z].*$/,"capitalized"),e9=r.module({root:WT({in:"string",morphs:(T)=>T.charAt(0).toUpperCase()+T.slice(1),declaredOut:VY}),preformatted:VY},{name:"string.capitalize"}),T7=(T)=>{let _=T.replaceAll(/[ -]+/g,""),F=0,W,J,Y=!1;for(let $=_.length-1;$>=0;$--){if(W=_.substring($,$+1),J=Number.parseInt(W,10),Y)J*=2,F+=J>=10?J%10+1:J;else F+=J;Y=!Y}return!!(F%10===0?_:!1)},_7=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,F7=WT({domain:"string",pattern:{meta:"a credit card number",rule:_7.source},predicate:{meta:"a credit card number",predicate:T7}});var W7=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var J7=(T)=>!Number.isNaN(new Date(T).valueOf()),KY=WT({domain:"string",predicate:{meta:"a parsable date",predicate:J7}}).assertHasKind("intersection"),LY=PY.root.internal.narrow((T,_)=>{let F=Number.parseInt(T),W=eW.epoch(F);if(W instanceof F_)return _.errors.merge(W),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),Y7=r.module({root:LY,parse:WT({in:LY,morphs:(T)=>new Date(T),declaredOut:x.Date})},{name:"string.date.epoch"}),DY=ET(W7,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),$7=r.module({root:DY,parse:WT({in:DY,morphs:(T)=>new Date(T),declaredOut:x.Date})},{name:"string.date.iso"}),Z7=r.module({root:KY,parse:WT({declaredIn:KY,in:"string",morphs:(T,_)=>{let F=new Date(T);if(Number.isNaN(F.valueOf()))return _.error("a parsable date");return F},declaredOut:x.Date}),iso:$7,epoch:Y7},{name:"string.date"}),X7=ET(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),SY="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A0=`(${SY}[.]){3}${SY}`,G7=new RegExp(`^${A0}$`),CT="(?:[0-9a-fA-F]{1,4})",A7=new RegExp(`^((?:${CT}:){7}(?:${CT}|:)|(?:${CT}:){6}(?:${A0}|:${CT}|:)|(?:${CT}:){5}(?::${A0}|(:${CT}){1,2}|:)|(?:${CT}:){4}(?:(:${CT}){0,1}:${A0}|(:${CT}){1,3}|:)|(?:${CT}:){3}(?:(:${CT}){0,2}:${A0}|(:${CT}){1,4}|:)|(?:${CT}:){2}(?:(:${CT}){0,3}:${A0}|(:${CT}){1,5}|:)|(?:${CT}:){1}(?:(:${CT}){0,4}:${A0}|(:${CT}){1,6}|:)|(?::((?::${CT}){0,5}:${A0}|(?::${CT}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),H7=r.module({root:["v4 | v6","@","an IP address"],v4:ET(G7,"an IPv4 address","ipv4"),v6:ET(A7,"an IPv6 address","ipv6")},{name:"string.ip"}),JF="a JSON string",qY=(T)=>{if(!(T instanceof SyntaxError))throw T;return`must be ${JF} (${T})`},O7=WT({meta:JF,domain:"string",predicate:{meta:JF,predicate:(T,_)=>{try{return JSON.parse(T),!0}catch(F){return _.reject({code:"predicate",expected:JF,problem:qY(F)})}}}}),U7=(T,_)=>{if(T.length===0)return _.error({code:"predicate",expected:JF,actual:"empty"});try{return JSON.parse(T)}catch(F){return _.error({code:"predicate",expected:JF,problem:qY(F)})}},M7=r.module({root:O7,parse:WT({meta:"safe JSON string parser",in:"string",morphs:U7,declaredOut:x.jsonObject})},{name:"string.json"}),IY=ET(/^[a-z]*$/,"only lowercase letters"),w7=r.module({root:WT({in:"string",morphs:(T)=>T.toLowerCase(),declaredOut:IY}),preformatted:IY},{name:"string.lower"}),jY=["NFC","NFD","NFKC","NFKD"],lF=c(jY,(T,_)=>[_,WT({domain:"string",predicate:(F)=>F.normalize(_)===F,meta:`${_}-normalized unicode`})]),T1=c(jY,(T,_)=>[_,WT({in:"string",morphs:(F)=>F.normalize(_),declaredOut:lF[_]})]),Q7=r.module({root:T1.NFC,preformatted:lF.NFC},{name:"string.normalize.NFC"}),R7=r.module({root:T1.NFD,preformatted:lF.NFD},{name:"string.normalize.NFD"}),E7=r.module({root:T1.NFKC,preformatted:lF.NFKC},{name:"string.normalize.NFKC"}),z7=r.module({root:T1.NFKD,preformatted:lF.NFKD},{name:"string.normalize.NFKD"}),V7=r.module({root:"NFC",NFC:Q7,NFD:R7,NFKC:E7,NFKD:z7},{name:"string.normalize"}),NY=ET(CW,"a well-formed numeric string"),K7=r.module({root:NY,parse:WT({in:NY,morphs:(T)=>Number.parseFloat(T),declaredOut:x.number})},{name:"string.numeric"}),CY="a regex pattern",L7=WT({domain:"string",predicate:{meta:CY,predicate:(T,_)=>{try{return new RegExp(T),!0}catch(F){return _.reject({code:"predicate",expected:CY,problem:String(F)})}}},meta:{format:"regex"}}),D7=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,S7=ET(D7,"a semantic version (see https://semver.org/)"),BY=ET(/^\S.*\S$|^\S?$/,"trimmed"),I7=r.module({root:WT({in:"string",morphs:(T)=>T.trim(),declaredOut:BY}),preformatted:BY},{name:"string.trim"}),kY=ET(/^[A-Z]*$/,"only uppercase letters"),N7=r.module({root:WT({in:"string",morphs:(T)=>T.toUpperCase(),declaredOut:kY}),preformatted:kY},{name:"string.upper"}),C7=(T)=>{if(URL.canParse)return URL.canParse(T);try{return new URL(T),!0}catch{return!1}},fY=WT({domain:"string",predicate:{meta:"a URL string",predicate:C7},meta:{format:"uri"}}),B7=r.module({root:fY,parse:WT({declaredIn:fY,in:"string",morphs:(T,_)=>{try{return new URL(T)}catch{return _.error("a URL string")}},declaredOut:WT(URL)})},{name:"string.url"}),k7=r.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:ET(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:ET(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:ET(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:ET(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:ET(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:ET(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:ET(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:ET(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),yY=r.module({root:x.string,alpha:ET(/^[A-Za-z]*$/,"only letters"),alphanumeric:ET(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:s9,base64:a9,capitalize:e9,creditCard:F7,date:Z7,digits:ET(/^\d*$/,"only digits 0-9"),email:X7,integer:PY,ip:H7,json:M7,lower:w7,normalize:V7,numeric:K7,regex:L7,semver:S7,trim:I7,upper:N7,url:B7,uuid:k7},{name:"string"});var vY=r.module({bigint:x.bigint,boolean:x.boolean,false:x.false,never:x.never,null:x.null,number:x.number,object:x.object,string:x.string,symbol:x.symbol,true:x.true,unknown:x.unknown,undefined:x.undefined}),xY=r.module({root:x.unknown,any:x.unknown},{name:"unknown"}),f7=r.module({root:x.jsonObject,stringify:TF("morph",{in:x.jsonObject,morphs:(T)=>JSON.stringify(T),declaredOut:x.string})},{name:"object.json"}),bY=r.module({root:x.object,json:f7},{name:"object"});class hY extends uT{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var P7=K_(["K",x.key],"V")((T)=>({domain:"object",index:{signature:T.K,value:T.V}}),hY);class pY extends uT{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var q7=K_(["T",x.object],["K",x.key])((T)=>T.T.pick(T.K),pY);class gY extends uT{description='omit a set of properties from an object like `Omit(User, "age")`'}var j7=K_(["T",x.object],["K",x.key])((T)=>T.T.omit(T.K),gY);class mY extends uT{description="make all named properties of an object optional like `Partial(User)`"}var y7=K_(["T",x.object])((T)=>T.T.partial(),mY);class oY extends uT{description="make all named properties of an object required like `Required(User)`"}var v7=K_(["T",x.object])((T)=>T.T.required(),oY);class uY extends uT{description='exclude branches of a union like `Exclude("boolean", "true")`'}var x7=K_("T","U")((T)=>T.T.exclude(T.U),uY);class cY extends uT{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var b7=K_("T","U")((T)=>T.T.extract(T.U),cY),dY=r.module({Exclude:x7,Extract:b7,Omit:j7,Partial:y7,Pick:q7,Record:P7,Required:v7});var H0=O2({...vY,...dY,...EY,...OY,string:yY,number:eW,object:bY,unknown:xY},{prereducedAliases:!0,name:"ark"}),jT=H0.export();Object.assign(WF.ambient,jT);WF.typeAttachments={string:jT.string.root,number:jT.number.root,bigint:jT.bigint,boolean:jT.boolean,symbol:jT.symbol,undefined:jT.undefined,null:jT.null,object:jT.object.root,unknown:jT.unknown.root,false:jT.false,true:jT.true,never:jT.never,arrayIndex:jT.Array.index,Key:jT.Key,Record:jT.Record,Array:jT.Array.root,Date:jT.Date};var Y_=Object.assign(H0.type,WF.typeAttachments),h7=H0.match,p7=H0.generic,qL=H0.schema,g7=H0.define,m7=H0.declare;class tF extends Promise{fate;resolve;reject;done=!1;constructor(T){let _,F;super((W,J)=>{_=W,F=J});this.resolve=_,this.reject=F,this.use(T instanceof Promise?T:new Promise(T))}pass(T,_){if(T===this.fate)this.resolve(_),this.done=!0}fail(T,_){if(T===this.fate)this.reject(_),this.done=!0}use(T){if(T instanceof Promise){let _=T;this.fate=_,_.then((F)=>{this.pass(_,F)},(F)=>{this.fail(_,F)})}else this.resolve(T),this.fate=void 0}}var rL=(T,_,F=tY.STORE)=>{return lY(F,{key:`${T.key}:JSON`,get:({get:W})=>_.toJson(W(T)),set:({set:W},J)=>{W(T,_.fromJson(J))}})};function eL(T,_,F){return M2(T,{key:`${_.key}:JSON`,get:(J)=>({get:Y})=>{let $=Y(_,J);return F.toJson($)},set:(J)=>({set:Y},$)=>{Y(_,J,F.fromJson($))}},["mutable","json"])}var iF=(T)=>JSON.parse(T),rT=(T)=>JSON.stringify(T),_D=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function m(T){while(T.child!==null)T=T.child;return T}class _1{_buffer;_index=0;constructor(T){let _;if(typeof T==="number")_=T;else _=T.length;this._buffer=Array.from({length:_})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new _1([...this._buffer]);return T._index=this._index,T}}var o7={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"};function iY(T,_){let F=rT(_),W=`${T.key}(${F})`,J=o7[T.type],Y={key:W,type:J};return Object.assign(Y,{family:{key:T.key,subKey:F}}),Object.assign(Y,{counterfeit:!0}),Y}function nF(T){let _={key:T.key,type:T.type};if("family"in T)_.family=T.family;return _}var w2=(T)=>(_,F,W,J,...Y)=>{console[T](`${_} ${F} "${W}" ${J}`,...Y)},u7={error:w2("error"),info:w2("info"),warn:w2("warn")};class Q2{logLevel;filter;logger;constructor(T,_,F=u7){this.logLevel=T,this.filter=_,this.logger=F}error=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel!==null){if(_===!0)this.logger.error(...T);else if(_!==!1)this.logger.error(..._)}};info=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel==="info"){if(_===!0)this.logger.info(...T);else if(_!==!1)this.logger.info(..._)}};warn=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel!=="error"&&this.logLevel!==null){if(_===!0)this.logger.warn(...T);else if(_!==!1)this.logger.warn(..._)}}}class g_{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,_)=>`${T}:${_}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,_){let F=this.relations.get(T),W=this.relations.get(_);if(F)F.add(_);else F=new Set([_]),this.relations.set(T,F);if(W)W.add(T);else W=new Set([T]),this.relations.set(_,W)}deleteRelation(T,_){let F=this.relations.get(T);if(F){if(F.delete(_),F.size===0)this.relations.delete(T);let W=this.relations.get(_);if(W){if(W.delete(T),W.size===0)this.relations.delete(_)}}}replaceRelationsUnsafely(T,_){this.relations.set(T,new Set(_));for(let F of _){let W=new Set().add(T);this.relations.set(F,W)}}replaceRelationsSafely(T,_){let F=this.relations.get(T),W=this.isAType?.(T)?T:void 0,J=W===void 0?T:void 0;if(F)for(let Y of F){W??=Y,J??=Y;let $=this.relations.get(Y);if($){if($.size===1)this.relations.delete(Y);else $.delete(T);this.contents.delete(this.makeContentKey(W,J))}}this.relations.set(T,new Set(_));for(let Y of _){let $=this.relations.get(Y);if($)$.add(T);else $=new Set().add(T),this.relations.set(Y,$)}}getContentInternal(T){return this.contents.get(T)}setContent(T,_){this.contents.set(T,_)}deleteContent(T){this.contents.delete(T)}constructor(T,_){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!_?.externalStore)this.relations=new Map(T.relations?.map(([F,W])=>[F,new Set(W)])),this.contents=new Map(T.contents);if(this.isAType=_?.isAType??null,this.isBType=_?.isBType??null,this.isContent=_?.isContent??null,_?.makeContentKey)this.makeContentKey=_.makeContentKey;if(_?.externalStore){let F=_.externalStore;if(this.has=(W,J)=>F.has(W,J),this.addRelation=(W,J)=>{F.addRelation(W,J)},this.deleteRelation=(W,J)=>{F.deleteRelation(W,J)},this.replaceRelationsSafely=(W,J)=>{F.replaceRelationsSafely(W,J)},this.replaceRelationsUnsafely=(W,J)=>{F.replaceRelationsUnsafely(W,J)},this.getRelatedKeys=(W)=>F.getRelatedKeys(W),F.getContent)this.getContentInternal=(W)=>{return F.getContent(W)},this.setContent=(W,J)=>{F.setContent(W,J)},this.deleteContent=(W)=>{F.deleteContent(W)};for(let[W,J]of T.relations??[]){let Y=this.isAType?.(W)?W:void 0,$=Y===void 0?W:void 0;for(let Z of J)Y??=Z,$??=Z,this.addRelation(Y,$)}for(let[W,J]of T.contents??[])this.setContent(W,J)}if(_?.warn)this.warn=_.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,_])=>[T,[..._]]),contents:[...this.contents.entries()]}}set(...T){let _,F,W;switch(T.length){case 1:{let J=T[0];_=J[this.a],F=J[this.b],W=void 0;break}case 2:{let J=T[0];if(typeof J==="string")[_,F]=T;else _=J[this.a],F=J[this.b],W=T[1];break}default:{_=T[0],F=T[1],W=T[2];break}}switch(this.cardinality){case"1:1":{let J=this.getRelatedKey(_);if(J&&J!==F)this.delete(_,J)}case"1:n":{let J=this.getRelatedKey(F);if(J&&J!==_)this.delete(J,F)}break;case"n:n":}if(W){let J=this.makeContentKey(_,F);this.setContent(J,W)}return this.addRelation(_,F),this}delete(T,_){_=typeof _==="string"?_:T[this.b];let F=typeof T==="string"?T:T[this.a];if(F===void 0&&typeof _==="string"){let W=this.getRelatedKeys(_);if(W)for(let J of W)this.delete(J,_)}if(typeof F==="string"&&_===void 0){let W=this.getRelatedKeys(F);if(W)for(let J of W)this.delete(F,J)}if(typeof F==="string"&&typeof _==="string"){this.deleteRelation(F,_);let W=this.makeContentKey(F,_);this.deleteContent(W)}return this}getRelatedKey(T){let _=this.getRelatedKeys(T);if(_){if(_.size>1)this.warn?.(`${_.size} related keys were found for key "${T}": (${[..._].map((W)=>`"${W}"`).join(", ")}). Only one related key was expected.`);let F;for(let W of _){F=W;break}return F}}replaceRelations(T,_,F){let W=!Array.isArray(_),J=W?Object.keys(_):_;if(F?.reckless)this.replaceRelationsUnsafely(T,J);else this.replaceRelationsSafely(T,J);if(W)for(let Y of J){let $=this.makeContentKey(T,Y),Z=_[Y];this.setContent($,Z)}return this}getContent(T,_){let F=this.makeContentKey(T,_);return this.getContentInternal(F)}getRelationEntries(T){let _=T[this.a],F=T[this.b];if(_!==void 0&&F===void 0){let W=this.getRelatedKeys(_);if(W)return[...W].map((J)=>{return[J,this.getContent(_,J)]})}if(_===void 0&&F!==void 0){let W=this.getRelatedKeys(F);if(W)return[...W].map((J)=>{return[J,this.getContent(J,F)]})}return[]}has(T,_){if(_)return this.getRelatedKeys(T)?.has(_)??!1;return this.relations.has(T)}}class FT{Subscriber;subscribers=new Map;subscribe(T,_){return this.subscribers.set(T,_),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let _=this.subscribers.values();for(let F of _)F(T)}}class R2 extends FT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function O0(T){return"epoch"in T.transactionMeta}function M_(T){return"phase"in T.transactionMeta}function nY(T){return T[0].toUpperCase()+T.slice(1)}function F1(T){return T.type.split("_").map(nY).join(" ")}class rF extends Error{constructor(T,_){super(`${F1(T)} ${rT(T.key)} not found in store "${_.config.name}".`)}}var YF=(T)=>(_)=>T instanceof Function?T(_):T;var U0=(T,_)=>{if(T.valueMap.has(_.key))return T.logger.info("\uD83D\uDCD6",_.type,_.key,"reading cached value"),rY(_,T);switch(_.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return T.logger.info("\uD83E\uDDEE",_.type,_.key,"computing value"),_.get();case"atom":case"mutable_atom":{let F=_.default,W;if(F instanceof Function)W=F();else W=F;return T.logger.info("\uD83D\uDC81","atom",_.key,"could not find cached value; using default",W),W}}};var sY=(T,_)=>{if(T.operation.open){let F=performance.now();return T.logger.info("\u2757",_.type,_.key,`deferring setState at T-${F} until setState for "${T.operation.token.key}" is done`),F}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:_},T.logger.info("\u2B55",_.type,_.key,`operation start in store "${T.config.name}"${!M_(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},aY=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},eY=(T,_)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",_,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(_)},M0=(T,_)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",_,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(_)};var T$=(T,_,F)=>{switch(_.type){case"mutable_atom":T.logger.info("\uD83D\uDCE2",_.type,_.key,"is now (",F.newValue,") subscribers:",_.subject.subscribers);break;case"atom":case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":T.logger.info("\uD83D\uDCE2",_.type,_.key,"went (",F.oldValue,"->",F.newValue,") subscribers:",_.subject.subscribers)}_.subject.next(F)};var E2=(T,_)=>{let F=m(T),W=F.selectorAtoms.getRelatedKeys(_.key);if(F.logger.info("\uD83E\uDDF9",_.type,_.key,W?`evicting ${W.size} states downstream:`:"no downstream states",W??"to evict"),W){if(F.operation.open)F.logger.info("\uD83E\uDDF9",_.type,_.key,`[ ${[...F.operation.done].join(", ")} ] already done`);for(let J of W){if(eY(F,J))continue;_$(J,F),M0(F,J)}}};var F$=(T,_,F)=>{let W=U0(T,_),J=W;if(_.type==="mutable_atom"&&M_(T)){let{parent:$}=T;J=sF(T,_,$)}if(J=YF(F)(J),T.logger.info("\uD83D\uDCDD","atom",_.key,"set to",J),J=sT(T,_.key,J,_.subject),J$(T,_.key))Y$(T,_.key);M0(T,_.key),E2(T,_);let Y={oldValue:W,newValue:J};if(!M_(T)){T$(T,_,Y);return}if(T.on.transactionApplying.state===null){let{key:$}=_;if(W$(Y.newValue))return;let Z={type:"atom_update",key:$,...Y};if(_.family)Z.family=_.family;T.transactionMeta.update.updates.push(Z),T.logger.info("\uD83D\uDCC1","atom",$,"stowed (",Y.oldValue,"->",Y.newValue,")")}else if(_.key.startsWith("*")){let $=_.key.slice(1),Z=T.atoms.get($),G=T.valueMap.get($);if(Z.type==="mutable_atom"&&M_(T)){let{parent:O}=T;G=sF(T,Z,O)}if(G.do(Y.newValue)===null)E2(T,Z)}};var W1=(T,_,F)=>{switch(_.type){case"atom":case"mutable_atom":F$(T,_,F);break;case"writable_pure_selector":case"writable_held_selector":_.set(F);break}};var J1=(T,_)=>m(T).atoms.has(_),c7=(T,_)=>m(T).writableSelectors.has(_),d7=(T,_)=>m(T).readonlySelectors.has(_),$$=(T,_)=>J1(T,_)||c7(T,_)||d7(T,_);var Y1=(T,_)=>{return m(T).selectorGraph.getRelationEntries({downstreamSelectorKey:_}).filter(([W,{source:J}])=>J!==_).map(([W,{source:J}])=>J).filter((W)=>$$(T,W))};var z2=(T,_,F)=>{let W=[],J=Y1(T,_);while(J.length>0){let Y=J.shift();if(F.has(Y))continue;if(F.add(Y),!J1(T,Y))J.push(...Y1(T,Y));else if(!W.includes(Y))W.push(Y)}return W},Z$=(T,_)=>{let F=T.key,W=Y1(_,F),J=new Set;return W.flatMap((Y)=>J1(_,Y)?Y:z2(_,Y,J))};var X$=(T,_,F,W,J)=>{let Y=m(T),{type:$,key:Z}=W;if($==="atom"||$==="mutable_atom")Y.selectorAtoms.set({selectorKey:F,atomKey:Z}),T.logger.info("\uD83D\uDD0D",_,F,`discovers root atom "${Z}"`);else{let G=z2(T,Z,J);T.logger.info("\uD83D\uDD0D",_,F,`discovers root atoms: [ ${G.map((X)=>`"${X}"`).join(", ")} ]`);for(let X of G)Y.selectorAtoms=Y.selectorAtoms.set({selectorKey:F,atomKey:X})}J.add(Z)};var w0=(T,_,F,W)=>({get:(...J)=>{let Y=m(T),$;if(J.length===2){let[O,M]=J;$=w_(T,O,M)}else[$]=J;let Z=$_(T,$),G=U0(T,Z),X=$.key;return T.logger.info("\uD83D\uDD0C",_,F,`registers dependency ( "${X}" =`,G,")"),Y.selectorGraph.set({upstreamSelectorKey:X,downstreamSelectorKey:F},{source:$.key}),X$(T,_,F,$,W),G},set:(...J)=>{let Y,$;if(J.length===2)Y=J[0],$=J[1];else{let X=J[0],O=J[1];$=J[2],Y=w_(T,X,O)}let Z=m(T),G=$_(Z,Y);W1(Z,G,$)},find:(...J)=>w_(T,...J),json:(J)=>$F(T,J)});var V2=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,{key:$,const:Z}=_,G="readonly_held_selector",{get:X,find:O,json:M}=w0(W,"readonly_held_selector",$,Y),K={..._,type:"readonly_held_selector",subject:J,install:(V)=>V2(V,_,F),get:()=>{return _.get({get:X,find:O,json:M},Z),sT(m(T),$,Z,J),Y.clear(),Z},...F&&{family:F}};W.readonlySelectors.set($,K),T.logger.info("\u2728","readonly_held_selector",$,"=",Z);let B={key:$,type:"readonly_held_selector"};if(F)B.family=F;return B};var K2=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,$=_.key,Z="readonly_pure_selector",{get:G,find:X,json:O}=w0(W,"readonly_pure_selector",$,Y),M=()=>{let V=_.get({get:G,find:X,json:O});return sT(m(T),$,V,J),Y.clear(),V},Q={..._,type:"readonly_pure_selector",subject:J,install:(V)=>K2(V,_,F),get:M,...F&&{family:F}};W.readonlySelectors.set($,Q);let K=M();T.logger.info("\u2728","readonly_pure_selector",$,"=",K);let B={key:$,type:"readonly_pure_selector"};if(F)B.family=F;return B};var L2=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,{key:$,const:Z}=_,G="writable_held_selector",X=w0(W,"writable_held_selector",$,Y),{find:O,get:M,json:Q}=X,K={find:O,get:M,json:Q},B=(y=_.get,u=m(T))=>{return y(K,Z),sT(u,$,Z,J),Y.clear(),Z},v={..._,type:"writable_held_selector",subject:J,install:(y)=>L2(y,_,F),get:B,set:(y)=>{let u=m(T),h=B(_.get,u),p=YF(y)(h);if(T.logger.info("\uD83D\uDCDD","writable_held_selector",$,"set (",h,"->",p,")"),sT(u,$,p,J),M0(u,$),O0(u))J.next({newValue:p,oldValue:h});_.set(X,p)},...F&&{family:F}};W.writableSelectors.set($,v);let q=B();T.logger.info("\u2728","writable_held_selector",$,"=",q);let j={key:$,type:"writable_held_selector"};if(F)j.family=F;return j};var aF=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,$=_.key,Z="writable_pure_selector",G=w0(W,"writable_pure_selector",$,Y),{find:X,get:O,json:M}=G,Q={find:X,get:O,json:M},K=(j=_.get,y=m(T))=>{let u=j(Q);return sT(y,$,u,J),Y.clear(),u},V={..._,type:"writable_pure_selector",subject:J,install:(j)=>aF(j,_,F),get:K,set:(j)=>{let y=m(T),u=K(_.get,y),h=YF(j)(u);if(T.logger.info("\uD83D\uDCDD","writable_pure_selector",$,"set (",u,"->",h,")"),sT(y,_.key,h,J),M0(y,_.key),O0(y))J.next({newValue:h,oldValue:u});_.set(G,h)},...F&&{family:F}};W.writableSelectors.set($,V);let v=K();T.logger.info("\u2728",V.type,V.key,"=",v);let q={key:$,type:"writable_pure_selector"};if(F)q.family=F;return q};function lY(T,_){let F="set"in _,W="const"in _;if(W&&F){let Y=L2(T,_,void 0);return T.on.selectorCreation.next(Y),Y}if(W){let Y=V2(T,_,void 0);return T.on.selectorCreation.next(Y),Y}if(F){let Y=aF(T,_,void 0);return T.on.selectorCreation.next(Y),Y}let J=K2(T,_,void 0);return T.on.selectorCreation.next(J),J}function M2(T,_,F){let W=_.key,J="writable_pure_selector_family",Y={key:W,type:"writable_pure_selector_family"},$=T.families.get(W);if($)T.logger.error("\u2757","writable_pure_selector_family",W,`Overwriting an existing ${F1($)} "${$.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let Z=new FT,X=Object.assign((O)=>{let M=rT(O),Q={key:W,subKey:M},K=`${W}(${M})`,B=m(T),V=aF(B,{key:K,get:_.get(O),set:_.set(O)},Q);return Z.next({type:"state_creation",token:V}),V},Y,{internalRoles:F,subject:Z,install:(O)=>M2(O,_),default:(O)=>{return _.get(O)({get:(...Q)=>eF(T,...Q),find:(...Q)=>w_(T,...Q),json:(Q)=>$F(T,Q)})}});return T.families.set(W,X),Y}function G$(T,_,F){let W=T.families.get(_.key);if(W===void 0)throw new rF(_,T);let J=W(F),Y=m(T);if(J.family){if(O0(Y))switch(J.type){case"atom":case"mutable_atom":T.on.atomCreation.next(J);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":T.on.selectorCreation.next(J);break}else if(M_(Y)&&Y.on.transactionApplying.state===null)Y.transactionMeta.update.updates.push({type:"state_creation",token:J})}return J}function A$(T,_,F){let W=rT(F),J=`${_.key}(${W})`,Y=m(T),$;switch(_.type){case"atom_family":case"mutable_atom_family":$=Y.atoms.get(J);break;case"writable_held_selector_family":case"writable_pure_selector_family":$=Y.writableSelectors.get(J);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":$=Y.readonlySelectors.get(J);break}if($)return nF($);return $}function w_(T,_,F){let W=A$(T,_,F);if(W)return W;let J=rT(F),Y=T.molecules.get(J);if(!Y&&T.config.lifespan==="immortal"){let $=iY(_,F);return T.logger.error("\u274C",$.type,$.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),$}if(W=G$(T,_,F),Y)m(T).moleculeData.set(J,_.key);return W}function H$(T,_){if(_.family){let F=T.families.get(_.family.key);if(F)return F}}function Q0(T,..._){let F,W,J,Y;if(_.length===2){if(F=_[0],Y=_[1],W=H$(T,F)??null,W)J=F.family?iF(F.family.subKey):null,F=w_(T,W,J)}else W=_[0],J=_[1],Y=_[2],F=w_(T,W,J);if("counterfeit"in F&&"family"in F){let G=F.family.subKey,X=T.disposalTraces.buffer.find((O)=>O?.key===G);T.logger.error("\u274C",F.type,F.key,`could not be set because it was not found in the store "${T.config.name}".`,X?`This state was previously disposed:
|
|
47
|
+
`)+"}");class oW{config;resolvedConfig;name;get[iT](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(T,_){if(this.config=fF(z.config,_),this.resolvedConfig=fF(z.resolvedConfig,_),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(c4).length}`,this.name in c4)E(`A Scope already named ${this.name} already exists`);c4[this.name]=this;let F=Object.entries(T).map((W)=>this.preparseOwnAliasEntry(...W));for(let[W,J]of F){let Y=W;if(W[0]==="#"){if(Y=W.slice(1),Y in this.aliases)E(R6(Y));this.aliases[Y]=J}else{if(Y in this.aliases)E(R6(W));this.aliases[Y]=J,this.exportedNames.push(Y)}if(!P(J,"module")&&!P(J,"generic")&&!J0(J)){let $=this.preparseOwnDefinitionFormat(J,{alias:Y});this.resolutions[Y]=P($,"root")?this.bindReference($):this.createParseContext($).id}}E6??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[E6.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=z.intrinsic?c(z.intrinsic,(W,J)=>W.startsWith("json")?[]:[W,this.bindReference(J)]):{}}cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(T){return T}generic=(...T)=>{let _=this;return(F,W)=>new G0(T,W?new yW(F):F,_,_,W??null)};units=(T,_)=>{let F=[];for(let J of T)if(!F.includes(J))F.push(J);let W=F.map((J)=>this.node("unit",{unit:J},_));return this.node("union",W,{..._,prereduced:!0})};lazyResolutions=[];lazilyResolve(T,_){let F=this.node("alias",{reference:_??"synthetic",resolve:T},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(F);return F}schema=(T,_)=>this.finalize(this.parseSchema(T,_));parseSchema=(T,_)=>this.node(yF(T),T,_);preparseNode(T,_,F){let W=typeof T==="string"?T:yF(_,T);if(OT(_)&&_.kind===W)return _;if(W==="alias"&&!F?.prereduced){let{reference:$}=gF.implementation.normalize(_,this);if($.startsWith("$")){let Z=this.resolveRoot($.slice(1));_=Z,W=Z.kind}}else if(W==="union"&&T_(_,"object")){let $=sH(_);if($?.length===1)_=$[0],W=yF(_)}if(OT(_)&&_.kind===W)return _;let Y=r0[W].normalize?.(_,this)??_;if(OT(Y))return Y.kind===W?Y:aH(W,Y.kind);return{...F,$:this,kind:W,def:Y,prefix:F.alias??W}}bindReference(T){let _;if(OT(T))_=T.$===this?T:new T.constructor(T.attachments,this);else _=T.$===this?T:new G0(T.params,T.bodyDef,T.$,this,T.hkt);if(!this.resolved)Object.assign(this.referencesById,_.referencesById);return _}resolveRoot(T){return this.maybeResolveRoot(T)??E(t4(T))}maybeResolveRoot(T){let _=this.maybeResolve(T);if(P(_,"generic"))return;return _}maybeResolveSubalias(T){return d4(this.aliases,T)??d4(this.ambient,T)}get ambient(){return z.ambient}maybeResolve(T){let _=this.resolutions[T];if(_){if(typeof _!=="string")return this.bindReference(_);let W=nT[_];if(P(W,"root"))return this.resolutions[T]=W;if(P(W,"context")){if(W.phase==="resolving")return this.node("alias",{reference:`$${T}`},{prereduced:!0});if(W.phase==="resolved")return e(`Unexpected resolved context for was uncached by its scope: ${d(W)}`);W.phase="resolving";let J=this.bindReference(this.parseOwnDefinitionFormat(W.def,W));return W.phase="resolved",nT[J.id]=J,nT[W.id]=J,this.resolutions[T]=J}return e(`Unexpected nodesById entry for ${_}: ${d(W)}`)}let F=this.aliases[T]??this.ambient?.[T];if(!F)return this.maybeResolveSubalias(T);if(F=this.normalizeRootScopeValue(F),P(F,"generic"))return this.resolutions[T]=this.bindReference(F);if(P(F,"module")){if(!F.root)E(I6(T));return this.resolutions[T]=this.bindReference(F.root)}return this.resolutions[T]=this.parse(F,{alias:T})}createParseContext(T){let _=T.id??C4(T.prefix);return nT[_]=Object.assign(T,{[iT]:"context",$:this,id:_,phase:"unresolved"})}traversal(T){return new f_(T,this.resolvedConfig)}import(...T){return new e0(c(this.export(...T),(_,F)=>[`#${_}`,F]))}precompilation;_exportedResolutions;_exports;export(...T){if(!this._exports){this._exports={};for(let F of this.exportedNames){let W=this.aliases[F];this._exports[F]=P(W,"module")?u4(W,this):z6(this.maybeResolve(F))}for(let F of this.lazyResolutions)F.resolution;if(this._exportedResolutions=S6(this,this._exports),this._json=D6(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let F=L6(this.references);this.precompilation=F.write(K6,4),V6(this.references,F)}this.resolved=!0}let _=T.length?T:this.exportedNames;return new e0(c(_,(F,W)=>[W,this._exports[W]]))}resolve(T){return this.export()[T]}node=(T,_,F={})=>{let W=this.preparseNode(T,_,F);if(OT(W))return this.bindReference(W);let J=this.createParseContext(W),Y=B4(J),$=this.bindReference(Y);return nT[J.id]=$};parse=(T,_={})=>this.finalize(this.parseDefinition(T,_));parseDefinition(T,_={}){if(P(T,"root"))return this.bindReference(T);let F=this.preparseOwnDefinitionFormat(T,_);if(P(F,"root"))return this.bindReference(F);let W=this.createParseContext(F);nT[W.id]=W;let J=this.bindReference(this.parseOwnDefinitionFormat(T,W));if(J.isCyclic)J=dJ(J,W.id);return nT[W.id]=J,J}finalize(T){if(z6(T),!T.precompilation&&!this.resolvedConfig.jitless)eH(T.references);return T}}class l4 extends oW{parseOwnDefinitionFormat(T,_){return B4(_)}preparseOwnDefinitionFormat(T,_){return this.preparseNode(yF(T),T,_)}preparseOwnAliasEntry(T,_){return[T,_]}normalizeRootScopeValue(T){return T}}var z6=(T)=>{let _=T.references.filter((F)=>F.hasKind("alias"));for(let F of _){Object.assign(F.referencesById,F.resolution.referencesById);for(let W of T.references)if(F.id in W.referencesById)Object.assign(W.referencesById,F.referencesById)}return T},D6=(T)=>c(T,(_,F)=>[_,P(F,"root")||P(F,"generic")?F.json:P(F,"module")?D6(F):e(`Unexpected resolution ${d(F)}`)]),d4=(T,_)=>{let F=_.indexOf(".");if(F===-1)return;let W=_.slice(0,F),J=T[W];if(J===void 0)return;if(!P(J,"module"))return E(T9(W));let Y=_.slice(F+1),$=J[Y];if($===void 0)return d4(J,Y);if(P($,"root")||P($,"generic"))return $;if(P($,"module"))return $.root??E(I6(_));e(`Unexpected resolution for alias '${_}': ${d($)}`)},uW=(T,_)=>new l4(T,_),uF=new l4({});var S6=(T,_)=>{let F={};for(let W in _){let J=_[W];if(P(J,"module")){let Y=S6(T,J),$=c(Y,(Z,G)=>[`${W}.${Z}`,G]);Object.assign(F,$)}else if(P(J,"root")||P(J,"generic"))F[W]=J;else e(`Unexpected scope resolution ${d(J)}`)}return F},t4=(T)=>`'${T}' is unresolvable`,T9=(T)=>`'${T}' must reference a module to be accessed using dot syntax`,I6=(T)=>`Reference to submodule '${T}' must specify an alias`;uF.export();var{schema:WT,node:TF,defineSchema:Zz,generic:V_}=uF;var i4="^(?:0|[1-9]\\d*)$",_9=new RegExp(i4),Az=VT(_9);var N6=uW({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();z.intrinsic={...N6};var C6=uW({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:i4}},{prereducedAliases:!0}).export();Object.assign(z.intrinsic,C6);var F9=uW({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),x={...N6,...C6,...F9,emptyStructure:TF("structure",{},{prereduced:!0})};z.intrinsic={...x};var k6=(T)=>typeof T==="string"&&T[0]==="d"&&(T[1]==="'"||T[1]==='"')&&T.at(-1)===T[1],B6=(T)=>T.toString()!=="Invalid Date",f6=(T)=>T.slice(2,-1),n4=(T)=>`'${T}' could not be parsed by the Date constructor`,P6=(T,_)=>W9(T,_),W9=(T,_)=>{let F=new Date(T);if(B6(F))return F;let W=GJ(T);if(W!==void 0){let J=new Date(W);if(B6(J))return J}return _?E(_===!0?n4(T):_):void 0};var r4=(T,_)=>{let F=T.scanner.shiftUntil(J9[j6[_]]);if(T.scanner.lookahead==="")return T.error($9(F,_));if(T.scanner.shift(),_==="/"){try{new RegExp(F)}catch(W){E(String(W))}T.root=T.ctx.$.node("intersection",{domain:"string",pattern:F},{prereduced:!0})}else if(qT(_,s4))T.root=T.ctx.$.node("unit",{unit:F});else{let W=P6(F,n4(F));T.root=T.ctx.$.node("unit",{meta:F,unit:W})}},s4={"'":1,'"':1},q6={"/":1,"'":1,'"':1},j6={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},J9={"'":(T)=>T.lookahead==="'",'"':(T)=>T.lookahead==='"',"/":(T)=>T.lookahead==="/"},Y9={'"':"double-quote","'":"single-quote","/":"forward slash"},$9=(T,_)=>`${_}${T} requires a closing ${Y9[j6[_]]}`;var y6=(T)=>`Private type references should not include '#'. Use '${T}' instead.`,cW="Optional definitions like 'string?' are only valid as properties in an object or tuple",dW="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var v6={">":!0,">=":!0},x6={"<":!0,"<=":!0};var _F={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},b6=(T)=>`Unmatched )${T===""?"":` before ${T}`}`,lW=(T)=>`Missing ${T}`,h6=(T,_)=>`Left bounds are only valid when paired with right bounds (try ...${_}${T})`,tW=(T)=>`Left-bounded expressions must specify their limits using < or <= (was ${T})`,p6=(T,_,F,W)=>`An expression may have at most one left bound (parsed ${T}${_F[_]}, ${F}${_F[W]})`;var g6=(T,_,F)=>m6(T,_,F,[]),m6=(T,_,F,W)=>{let J=F.parseUntilFinalizer();if(W.push(J.root),J.finalizer===">"){if(W.length!==_.params.length)return F.error(a4(T,_.names,W.map((Y)=>Y.expression)));return W}if(J.finalizer===",")return m6(T,_,F,W);return J.error(lW(">"))},a4=(T,_,F)=>`${T}<${_.join(", ")}> requires exactly ${_.length} args (got ${F.length}${F.length===0?"":`: ${F.join(", ")}`})`;var e4=(T)=>{let _=T.scanner.shiftUntilNextTerminator();if(_==="keyof")T.addPrefix("keyof");else T.root=X9(T,_)},Z9=(T,_,F)=>{if(F.scanner.shiftUntilNonWhitespace(),F.scanner.shift()!=="<")return F.error(a4(T,_.names,[]));let J=g6(T,_,F);return _(...J)},X9=(T,_)=>G9(T,_)??A9(T,_)??T.error(_===""?T.scanner.lookahead==="#"?y6(T.shiftedByOne().scanner.shiftUntilNextTerminator()):T2(T):t4(_)),G9=(T,_)=>{if(T.ctx.args?.[_]){let W=T.ctx.args[_];if(typeof W!=="string")return W;return T.ctx.$.node("alias",{reference:W},{prereduced:!0})}let F=T.ctx.$.maybeResolve(_);if(P(F,"root"))return F;if(F===void 0)return;if(P(F,"generic"))return Z9(_,F,T);return E(`Unexpected resolution ${d(F)}`)},A9=(T,_)=>{let F=AJ(_);if(F!==void 0)return T.ctx.$.node("unit",{unit:F});let W=OJ(_);if(W!==void 0)return T.ctx.$.node("unit",{unit:W})},T2=(T)=>{let _=T.previousOperator();return _?_2(_,T.scanner.unscanned):H9(T.scanner.unscanned)},_2=(T,_="")=>`Token '${T}' requires a right operand${_?` before '${_}'`:""}`,H9=(T)=>`Expected an expression${T?` before '${T}'`:""}`;var F2=(T)=>T.scanner.lookahead===""?T.error(T2(T)):T.scanner.lookahead==="("?T.shiftedByOne().reduceGroupOpen():T.scanner.lookaheadIsIn(q6)?r4(T,T.scanner.shift()):T.scanner.lookaheadIsIn(Y0)?F2(T.shiftedByOne()):T.scanner.lookahead==="d"?T.scanner.nextLookahead in s4?r4(T,`${T.scanner.shift()}${T.scanner.shift()}`):e4(T):e4(T);class r_ extends Z4{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in r_.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...Y0};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(T,_)=>T===">"?_[0]==="="?_[1]==="=":_.trimStart()===""||qT(_.trimStart()[0],r_.terminatingChars):T==="="?_[0]!=="=":T===","||T==="?"}var u6=(T,_)=>{let F=O9(T,_);if(T.root.hasKind("unit")){if(typeof T.root.unit==="number"){T.reduceLeftBound(T.root.unit,F),T.unsetRoot();return}if(T.root.unit instanceof Date){let W=`d'${T.root.description??T.root.unit.toISOString()}'`;T.unsetRoot(),T.reduceLeftBound(W,F);return}}return M9(T,F)},c6={"<":1,">":1,"=":1},O9=(T,_)=>T.scanner.lookaheadIs("=")?`${_}${T.scanner.shift()}`:_;var o6=(T,_,F,W)=>{if(F.extends(z.intrinsic.number)){if(typeof _!=="number")return E(W2(T,_,W));return T==="=="?["min","max"]:T[0]===">"?["min"]:["max"]}if(F.extends(z.intrinsic.lengthBoundable)){if(typeof _!=="number")return E(W2(T,_,W));return T==="=="?["exactLength"]:T[0]===">"?["minLength"]:["maxLength"]}if(F.extends(z.intrinsic.Date))return T==="=="?["after","before"]:T[0]===">"?["after"]:["before"];return E(qJ(F.expression))},U9=(T)=>({rule:k6(T.limit)?f6(T.limit):T.limit,exclusive:T.comparator.length===1}),M9=(T,_)=>{let F=T.unsetRoot(),W=T.scanner.location;T.parseOperand();let J=T.unsetRoot(),Y=T.scanner.sliceChars(W,T.scanner.location);if(T.root=F,!J.hasKind("unit")||typeof J.unit!=="number"&&!(J.unit instanceof Date))return T.error(W2(_,Y,"right"));let $=J.unit,Z=_.length===1,G=o6(_,typeof $==="number"?$:Y,F,"right");for(let O of G)T.constrainRoot(O,_==="=="?{rule:$}:{rule:$,exclusive:Z});if(!T.branches.leftBound)return;if(!qT(_,x6))return T.error(tW(_));let X=o6(T.branches.leftBound.comparator,T.branches.leftBound.limit,F,"left");T.constrainRoot(X[0],U9(T.branches.leftBound)),T.branches.leftBound=null},W2=(T,_,F)=>`Comparator ${F==="left"?_F[T]:T} must be ${F==="left"?"preceded":"followed"} by a corresponding literal (was ${_})`;var d6=(T)=>{T.scanner.shiftUntilNonWhitespace();let _=T.scanner.shiftUntilNextTerminator();T.root=T.root.brand(_)};var t6=(T)=>{let _=T.scanner.shiftUntilNextTerminator(),F=HJ(_,{errorOnFail:l6(_)});if(F===0)T.error(l6(0));T.root=T.root.constrain("divisor",F)},l6=(T)=>`% operator must be followed by a non-zero integer literal (was ${T})`;var J2=(T)=>{let _=T.scanner.shift();return _===""?T.finalize(""):_==="["?T.scanner.shift()==="]"?T.setRoot(T.root.array()):T.error(w9):_==="|"?T.scanner.lookahead===">"?T.shiftedByOne().pushRootToBranch("|>"):T.pushRootToBranch(_):_==="&"?T.pushRootToBranch(_):_===")"?T.finalizeGroup():r_.lookaheadIsFinalizing(_,T.scanner.unscanned)?T.finalize(_):qT(_,c6)?u6(T,_):_==="%"?t6(T):_==="#"?d6(T):(_ in Y0)?J2(T):T.error(iW(_))},iW=(T,_="")=>`'${T}' is not allowed here${_&&` (should be ${_})`}`,w9="Missing expected ']'";var i6=(T)=>{let _=T.unsetRoot();T.parseOperand();let F=T.unsetRoot();if(!F.hasKind("unit"))return T.error(Q9(F.expression));let W=F.unit instanceof Date?()=>new Date(F.unit):F.unit;return[_,"=",W]},Q9=(T)=>`Default value '${T}' must a literal value`;var Y2=(T,_)=>{let F=_.$.maybeResolveRoot(T);if(F)return F;if(T.endsWith("[]")){let Y=_.$.maybeResolveRoot(T.slice(0,-2));if(Y)return Y.array()}let W=new FF(new r_(T),_),J=R9(W);if(W.finalizer===">")E(iW(">"));return J},R9=(T)=>{T.parseOperand();let _=cF(T).root;if(!_)return e(`Root was unexpectedly unset after parsing string '${T.scanner.scanned}'`);if(T.finalizer==="=")_=i6(T);else if(T.finalizer==="?")_=[_,"?"];if(T.scanner.shiftUntilNonWhitespace(),T.scanner.lookahead)E(iW(T.scanner.lookahead));return _},cF=(T)=>{while(T.finalizer===void 0)E9(T);return T},E9=(T)=>T.hasRoot()?T.parseOperator():T.parseOperand();class FF{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(T,_){this.scanner=T,this.ctx=_}error(T){return E(T)}hasRoot(){return this.root!==void 0}setRoot(T){this.root=T}unsetRoot(){let T=this.root;return this.root=void 0,T}constrainRoot(...T){this.root=this.root.constrain(T[0],T[1])}finalize(T){if(this.groups.length)return this.error(lW(")"));this.finalizeBranches(),this.finalizer=T}reduceLeftBound(T,_){let F=_F[_];if(!qT(F,v6))return this.error(tW(_));if(this.branches.leftBound)return this.error(p6(this.branches.leftBound.limit,this.branches.leftBound.comparator,T,F));this.branches.leftBound={comparator:F,limit:T}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let T=this.groups.pop();if(!T)return this.error(b6(this.scanner.unscanned));this.branches=T}addPrefix(T){this.branches.prefixes.push(T)}applyPrefixes(){while(this.branches.prefixes.length){let T=this.branches.prefixes.pop();this.root=T==="keyof"?this.root.keyof():e(`Unexpected prefix '${T}'`)}}pushRootToBranch(T){this.assertRangeUnset(),this.applyPrefixes();let _=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(_)??_,T==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,T==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return cF(new FF(this.scanner,this.ctx))}parseOperator(){return J2(this)}parseOperand(){return F2(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(h6(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var z9="An empty string is not a valid generic parameter name",nW=(T,_,F)=>{T.shiftUntilNonWhitespace();let W=T.shiftUntilNextTerminator();if(W===""){if(T.lookahead===""&&_.length)return _;return E(z9)}return T.shiftUntilNonWhitespace(),K9(T,W,_,F)},n6="extends ",K9=(T,_,F,W)=>{if(T.shiftUntilNonWhitespace(),T.unscanned.startsWith(n6))T.jumpForward(n6.length);else{if(T.lookahead===",")T.shift();return F.push(_),nW(T,F,W)}let J=cF(new FF(T,W));return F.push([_,J.root]),nW(T,F,W)};class $2 extends k_{$;constructor(T){super((..._)=>new dF(T)(..._),{bind:T});this.$=T}in(T){return new dF(this.$,T===void 0?void 0:this.$.parse(T))}at(T,_){return new dF(this.$).at(T,_)}case(T,_){return new dF(this.$).case(T,_)}}class dF extends k_{$;in;key;branches=[];constructor(T,_){super((F)=>this.caseEntries(Object.entries(F).map(([W,J])=>W==="default"?[W,J]:[this.$.parse(W),J])));this.$=T,this.in=_}at(T,_){if(this.key)E(L9);if(this.branches.length)E(V9);return this.key=T,_?this.match(_):this}case(T,_){return this.caseEntry(this.$.parse(T),_)}caseEntry(T,_){let W=(this.key?this.$.parse({[this.key]:T}):T).pipe(_);return this.branches.push(W),this}match(T){return this(T)}strings(T){return this.caseEntries(Object.entries(T).map(([_,F])=>_==="default"?[_,F]:[this.$.node("unit",{unit:_}),F]))}caseEntries(T){for(let _=0;_<T.length;_++){let[F,W]=T[_];if(F==="default"){if(_!==T.length-1)E("default may only be specified as the last key of a switch definition");return this.default(W)}if(typeof W!=="function")return E(`Value for case "${F}" must be a function (was ${PT(W)})`);this.caseEntry(F,W)}return this}default(T){if(typeof T==="function")this.case(x.unknown,T);let _={branches:this.branches,ordered:!0};if(T==="never"||T==="assert")_.meta={onFail:r6};let F=this.$.node("union",_);if(!this.in)return this.$.finalize(F);let W=this.in.pipe(F);if(T==="never"||T==="assert")W=W.configureReferences({onFail:r6},"self");return this.$.finalize(W)}}var r6=(T)=>T.throw(),V9="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",L9="At most one key matcher may be specified per expression";var rW=(T,_)=>{if(XT(T)){if(T[1]==="=")return[_.$.parseOwnDefinitionFormat(T[0],_),"=",T[2]];if(T[1]==="?")return[_.$.parseOwnDefinitionFormat(T[0],_),"?"]}return sW(T,_)},s6="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",a6="Only required keys may specify default values, e.g. { value: 'number = 0' }";var e6=(T,_)=>{let F,W={},J=S0(T);for(let[$,Z]of J){let G=I9($);if(G.kind==="spread"){if(!h_(W))return E(S9);let V=_.$.parseOwnDefinitionFormat(Z,_);if(V.equals(x.object))continue;if(!V.hasKind("intersection")||!V.basis?.equals(x.object))return E(N9(V.expression));F=V.structure;continue}if(G.kind==="undeclared"){if(Z!=="reject"&&Z!=="delete"&&Z!=="ignore")E(D9(Z));W.undeclared=Z;continue}let X=rW(Z,_),O=G;if(G.kind==="required"){if(!XT(X))Z2(W,"required",{key:G.normalized,value:X},_);else Z2(W,"optional",X[1]==="="?{key:G.normalized,value:X[0],default:X[2]}:{key:G.normalized,value:X[0]},_);continue}if(XT(X)){if(X[1]==="?")E(s6);if(X[1]==="=")E(a6)}if(G.kind==="optional"){Z2(W,"optional",{key:G.normalized,value:X},_);continue}let M=_.$.parseOwnDefinitionFormat(O.normalized,_),Q=mW(M,X,_.$);if(Q.index)W.index=s(W.index,Q.index);if(Q.required)W.required=s(W.required,Q.required)}let Y=_.$.node("structure",W);return _.$.parseSchema({domain:"object",structure:F?.merge(Y)??Y})},Z2=(T,_,F,W)=>{T[_]=s(T[_],W.$.node(_,F))},D9=(T)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${d(T)})`,S9="Spread operator may only be used as the first key in an object",I9=(T)=>typeof T==="symbol"?{kind:"required",normalized:T}:T.at(-1)==="?"?T.at(-2)===DF?{kind:"required",normalized:`${T.slice(0,-2)}?`}:{kind:"optional",normalized:T.slice(0,-1)}:T[0]==="["&&T.at(-1)==="]"?{kind:"index",normalized:T.slice(1,-1)}:T[0]===DF&&T[1]==="["&&T.at(-1)==="]"?{kind:"required",normalized:T.slice(1)}:T==="..."?{kind:"spread"}:T==="+"?{kind:"undeclared"}:{kind:"required",normalized:T==="\\..."?"...":T==="\\+"?"+":T},N9=(T)=>`Spread operand must resolve to an object literal type (was ${T})`;var _Y=(T,_)=>x9(T)?YY[T[0]](T,_):y9(T)?JY[T[1]](T,_):null,C9=(T,_)=>_.$.parseOwnDefinitionFormat(T[1],_).keyof(),X2=(T,_)=>{if(T[2]===void 0)return E(_2(T[1],""));let F=_.$.parseOwnDefinitionFormat(T[0],_),W=_.$.parseOwnDefinitionFormat(T[2],_);if(T[1]==="|")return _.$.node("union",{branches:[F,W]});let J=T[1]==="&"?J_(F,W,_.$):jF(F,W,_.$);if(J instanceof N)return J.throw();return J},B9=(T,_)=>_.$.parseOwnDefinitionFormat(T[0],_).array(),k9=(T,_)=>{if(typeof T[2]!=="function")return E(FY("=>",T[2]));return _.$.parseOwnDefinitionFormat(T[0],_).pipe(T[2])},FY=(T,_)=>`${T===":"?"Narrow":"Morph"} expression requires a function following '${T}' (was ${typeof _})`,f9=(T,_)=>{if(typeof T[2]!=="function")return E(FY(":",T[2]));return _.$.parseOwnDefinitionFormat(T[0],_).constrain("predicate",T[2])},P9=(T,_)=>_.$.parseOwnDefinitionFormat(T[0],_).configureReferences(T[2],"shallow"),WY=(T)=>T,q9=WY({"[]":B9,"?":()=>E(cW)}),j9=WY({"|":X2,"&":X2,":":f9,"=>":k9,"|>":X2,"@":P9,"=":()=>E(dW)}),JY={...q9,...j9},y9=(T)=>JY[T[1]]!==void 0,v9=(T)=>T,YY=v9({keyof:C9,instanceof:(T,_)=>{if(typeof T[1]!=="function")return E(TY(VF(T[1])));let F=T.slice(1).map((W)=>typeof W==="function"?_.$.node("proto",{proto:W}):E(TY(VF(W))));return F.length===1?F[0]:_.$.node("union",{branches:F})},"===":(T,_)=>_.$.units(T.slice(1))}),x9=(T)=>YY[T[0]]!==void 0,TY=(T)=>`Expected a constructor following 'instanceof' operator (was ${T})`;var XY=(T,_)=>{let F=[{}],W=0;while(W<T.length){let J=!1;if(T[W]==="..."&&W<T.length-1)J=!0,W++;let Y=rW(T[W],_),[$,Z,G]=!XT(Y)?[Y]:Y;if(W++,J){if(!$.extends(z.intrinsic.Array))return E(p9($.expression));F=F.flatMap((X)=>$.distribute((O)=>h9(fW(X),O)))}else F=F.map((X)=>{if(Z==="?")return GY(X,$);if(Z==="=")return b9(X,$,G);return G2(X,$)})}return _.$.parseSchema(F.map((J)=>h_(J)?{proto:Array,exactLength:0}:{proto:Array,sequence:J}))},G2=(T,_)=>{if(T.defaultables||T.optionals)return E(T.variadic?g4:g9);if(T.variadic)T.postfix=s(T.postfix,_);else T.prefix=s(T.prefix,_);return T},GY=(T,_)=>{if(T.variadic)return E(AY);return T.optionals=s(T.optionals,_),T},b9=(T,_,F)=>{if(T.variadic)return E(AY);if(T.optionals)return E(m9);return T.defaultables=s(T.defaultables,[[_,F]]),T},$Y=(T,_)=>{if(T.postfix)E(ZY);if(T.variadic){if(!T.variadic.equals(_))E(ZY)}else T.variadic=_.internal;return T},h9=(T,_)=>{let F=_.select({method:"find",kind:"sequence"});if(!F)return $Y(T,z.intrinsic.unknown);if(F.prefix)for(let W of F.prefix)G2(T,W);if(F.optionals)for(let W of F.optionals)GY(T,W);if(F.variadic)$Y(T,F.variadic);if(F.postfix)for(let W of F.postfix)G2(T,W);return T},p9=(T)=>`Spread element must be an array (was ${T})`,ZY="A tuple may have at most one variadic element",g9="A required element may not follow an optional element",AY="An optional element may not follow a variadic element";var m9="A defaultable element may not follow an optional element without a default";var o9={},sW=(T,_)=>{if(typeof T==="string"){if(_.args&&Object.keys(_.args).some((W)=>T.includes(W)))return Y2(T,_);let F=o9[_.$.name]??={};return F[T]??=Y2(T,_)}return T_(T,"object")?u9(T,_):E(A2(PT(T)))},u9=(T,_)=>{let F=KF(T);switch(F){case void 0:if(P(T,"root"))return T;return e6(T,_);case"Array":return c9(T,_);case"RegExp":return _.$.node("intersection",{domain:"string",pattern:T},{prereduced:!0});case"Function":{let W=J0(T)?T():T;if(P(W,"root"))return W;return E(A2("Function"))}default:return E(A2(F??d(T)))}},c9=(T,_)=>_Y(T,_)??XY(T,_),A2=(T)=>`Type definitions must be strings or objects (was ${T})`;class H2 extends k_{constructor(T){let _=Object.assign({errors:F_,hkt:uT,$:T,raw:T.parse,module:T.constructor.module,scope:T.constructor.scope,define:T.define,match:T.match,generic:T.generic,schema:T.schema,keywords:T.ambient,unit:T.unit,enumerated:T.enumerated,instanceOf:T.instanceOf,valueOf:T.valueOf,or:T.or,and:T.and,merge:T.merge,pipe:T.pipe},T.ambientAttachments);super((...F)=>{if(F.length===1)return T.parse(F[0]);if(F.length===2&&typeof F[0]==="string"&&F[0][0]==="<"&&F[0].at(-1)===">"){let W=F[0].slice(1,-1),J=T.parseGenericParams(W,{});return new G0(J,F[1],T,T,null)}return T.parse(F)},{bind:T,attach:_})}}var WF=z;class aW extends oW{get ambientAttachments(){if(!WF.typeAttachments)return;return this.cacheGetter("ambientAttachments",c(WF.typeAttachments,(T,_)=>[T,this.bindReference(_)]))}preparseOwnAliasEntry(T,_){let F=T.indexOf("<");if(F===-1){if(P(_,"module")||P(_,"generic"))return[T,_];let Y=this.name==="ark"?T:T==="root"?this.name:`${this.name}.${T}`,$=this.resolvedConfig.keywords?.[Y];if($)_=[_,"@",$];return[T,_]}if(T.at(-1)!==">")E("'>' must be the last character of a generic declaration in a scope");let W=T.slice(0,F),J=T.slice(F+1,-1);return[W,()=>{let Y=this.parseGenericParams(J,{alias:W});return kJ(Y,_,this)}]}parseGenericParams(T,_){return nW(new r_(T),[],this.createParseContext({..._,def:T,prefix:"generic"}))}normalizeRootScopeValue(T){if(J0(T)&&!P(T,"generic"))return T();return T}preparseOwnDefinitionFormat(T,_){return{..._,def:T,prefix:_.alias??"type"}}parseOwnDefinitionFormat(T,_){if(!(_.alias&&(_.alias in this.aliases))&&!_.args)_.args={this:_.id};let W=sW(T,_);if(XT(W)){if(W[1]==="=")return E(dW);if(W[1]==="?")return E(cW)}return W}unit=(T)=>this.units([T]);valueOf=(T)=>this.units(n8(T));enumerated=(...T)=>this.units(T);instanceOf=(T)=>this.node("proto",{proto:T},{prereduced:!0});or=(...T)=>this.schema(T.map((_)=>this.parse(_)));and=(...T)=>T.reduce((_,F)=>_.and(this.parse(F)),this.intrinsic.unknown);merge=(...T)=>T.reduce((_,F)=>_.merge(this.parse(F)),this.intrinsic.object);pipe=(...T)=>this.intrinsic.unknown.pipe(...T);match=new $2(this);declare=()=>({type:this.type});define(T){return T}type=new H2(this);static scope=(T,_={})=>new aW(T,_);static module=(T,_={})=>this.scope(T,_).export()}var O2=Object.assign(aW.scope,{define:(T)=>T}),r=aW;class HY extends uT{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var d9=V_(["base",x.object],["props",x.object])((T)=>T.base.merge(T.props),HY),OY=r.module({Key:x.key,Merge:d9});class UY extends uT{}var l9=V_("element")((T)=>{let _=T.element.exclude(x.Array),F=_.array();return _.rawOr(F).pipe(W0).distribute((W)=>W.assertHasKind("morph").declareOut(F),WT)},UY),MY=r.module({root:x.Array,readonly:"root",index:x.nonNegativeIntegerString,liftFrom:l9},{name:"Array"});var U2=WT(["string",N0.FileConstructor]),t9=U2.rawOr(U2.array()),wY=WT({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:t9}}),QY=r.module({root:["instanceof",FormData],value:U2,parsed:wY,parse:WT({in:FormData,morphs:(T)=>{let _={};for(let[F,W]of T)if(F in _){let J=_[F];if(typeof J==="string"||J instanceof N0.FileConstructor)_[F]=[J,W];else J.push(W)}else _[F]=W;return _},declaredOut:wY})},{name:"FormData"});var RY=r.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var i9={Boolean:1,Number:1,String:1},EY=r.module({...c({...e1,..._4},(T,_)=>(T in i9)?[]:[T,["instanceof",_]]),Array:MY,TypedArray:RY,FormData:QY});var n9=WT({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),r9=WT({domain:"number",divisor:1}),eW=r.module({root:x.number,integer:r9,epoch:n9,safe:WT({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var ET=(T,_,F)=>{let W={domain:"string",pattern:{rule:T.source,flags:T.flags,meta:_}};if(F)W.meta={format:F};return TF("intersection",W)},zY=ET(SF,"a well-formed integer string"),PY=r.module({root:zY,parse:WT({in:zY,morphs:(T,_)=>{let F=Number.parseInt(T);return Number.isSafeInteger(F)?F:_.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:x.integer})},{name:"string.integer"}),s9=ET(/^[\dA-Fa-f]+$/,"hex characters only"),a9=r.module({root:ET(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:ET(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),KY=ET(/^[A-Z].*$/,"capitalized"),e9=r.module({root:WT({in:"string",morphs:(T)=>T.charAt(0).toUpperCase()+T.slice(1),declaredOut:KY}),preformatted:KY},{name:"string.capitalize"}),T7=(T)=>{let _=T.replaceAll(/[ -]+/g,""),F=0,W,J,Y=!1;for(let $=_.length-1;$>=0;$--){if(W=_.substring($,$+1),J=Number.parseInt(W,10),Y)J*=2,F+=J>=10?J%10+1:J;else F+=J;Y=!Y}return!!(F%10===0?_:!1)},_7=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,F7=WT({domain:"string",pattern:{meta:"a credit card number",rule:_7.source},predicate:{meta:"a credit card number",predicate:T7}});var W7=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var J7=(T)=>!Number.isNaN(new Date(T).valueOf()),VY=WT({domain:"string",predicate:{meta:"a parsable date",predicate:J7}}).assertHasKind("intersection"),LY=PY.root.internal.narrow((T,_)=>{let F=Number.parseInt(T),W=eW.epoch(F);if(W instanceof F_)return _.errors.merge(W),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),Y7=r.module({root:LY,parse:WT({in:LY,morphs:(T)=>new Date(T),declaredOut:x.Date})},{name:"string.date.epoch"}),DY=ET(W7,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),$7=r.module({root:DY,parse:WT({in:DY,morphs:(T)=>new Date(T),declaredOut:x.Date})},{name:"string.date.iso"}),Z7=r.module({root:VY,parse:WT({declaredIn:VY,in:"string",morphs:(T,_)=>{let F=new Date(T);if(Number.isNaN(F.valueOf()))return _.error("a parsable date");return F},declaredOut:x.Date}),iso:$7,epoch:Y7},{name:"string.date"}),X7=ET(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),SY="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A0=`(${SY}[.]){3}${SY}`,G7=new RegExp(`^${A0}$`),CT="(?:[0-9a-fA-F]{1,4})",A7=new RegExp(`^((?:${CT}:){7}(?:${CT}|:)|(?:${CT}:){6}(?:${A0}|:${CT}|:)|(?:${CT}:){5}(?::${A0}|(:${CT}){1,2}|:)|(?:${CT}:){4}(?:(:${CT}){0,1}:${A0}|(:${CT}){1,3}|:)|(?:${CT}:){3}(?:(:${CT}){0,2}:${A0}|(:${CT}){1,4}|:)|(?:${CT}:){2}(?:(:${CT}){0,3}:${A0}|(:${CT}){1,5}|:)|(?:${CT}:){1}(?:(:${CT}){0,4}:${A0}|(:${CT}){1,6}|:)|(?::((?::${CT}){0,5}:${A0}|(?::${CT}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),H7=r.module({root:["v4 | v6","@","an IP address"],v4:ET(G7,"an IPv4 address","ipv4"),v6:ET(A7,"an IPv6 address","ipv6")},{name:"string.ip"}),JF="a JSON string",qY=(T)=>{if(!(T instanceof SyntaxError))throw T;return`must be ${JF} (${T})`},O7=WT({meta:JF,domain:"string",predicate:{meta:JF,predicate:(T,_)=>{try{return JSON.parse(T),!0}catch(F){return _.reject({code:"predicate",expected:JF,problem:qY(F)})}}}}),U7=(T,_)=>{if(T.length===0)return _.error({code:"predicate",expected:JF,actual:"empty"});try{return JSON.parse(T)}catch(F){return _.error({code:"predicate",expected:JF,problem:qY(F)})}},M7=r.module({root:O7,parse:WT({meta:"safe JSON string parser",in:"string",morphs:U7,declaredOut:x.jsonObject})},{name:"string.json"}),IY=ET(/^[a-z]*$/,"only lowercase letters"),w7=r.module({root:WT({in:"string",morphs:(T)=>T.toLowerCase(),declaredOut:IY}),preformatted:IY},{name:"string.lower"}),jY=["NFC","NFD","NFKC","NFKD"],lF=c(jY,(T,_)=>[_,WT({domain:"string",predicate:(F)=>F.normalize(_)===F,meta:`${_}-normalized unicode`})]),T1=c(jY,(T,_)=>[_,WT({in:"string",morphs:(F)=>F.normalize(_),declaredOut:lF[_]})]),Q7=r.module({root:T1.NFC,preformatted:lF.NFC},{name:"string.normalize.NFC"}),R7=r.module({root:T1.NFD,preformatted:lF.NFD},{name:"string.normalize.NFD"}),E7=r.module({root:T1.NFKC,preformatted:lF.NFKC},{name:"string.normalize.NFKC"}),z7=r.module({root:T1.NFKD,preformatted:lF.NFKD},{name:"string.normalize.NFKD"}),K7=r.module({root:"NFC",NFC:Q7,NFD:R7,NFKC:E7,NFKD:z7},{name:"string.normalize"}),NY=ET(CW,"a well-formed numeric string"),V7=r.module({root:NY,parse:WT({in:NY,morphs:(T)=>Number.parseFloat(T),declaredOut:x.number})},{name:"string.numeric"}),CY="a regex pattern",L7=WT({domain:"string",predicate:{meta:CY,predicate:(T,_)=>{try{return new RegExp(T),!0}catch(F){return _.reject({code:"predicate",expected:CY,problem:String(F)})}}},meta:{format:"regex"}}),D7=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,S7=ET(D7,"a semantic version (see https://semver.org/)"),BY=ET(/^\S.*\S$|^\S?$/,"trimmed"),I7=r.module({root:WT({in:"string",morphs:(T)=>T.trim(),declaredOut:BY}),preformatted:BY},{name:"string.trim"}),kY=ET(/^[A-Z]*$/,"only uppercase letters"),N7=r.module({root:WT({in:"string",morphs:(T)=>T.toUpperCase(),declaredOut:kY}),preformatted:kY},{name:"string.upper"}),C7=(T)=>{if(URL.canParse)return URL.canParse(T);try{return new URL(T),!0}catch{return!1}},fY=WT({domain:"string",predicate:{meta:"a URL string",predicate:C7},meta:{format:"uri"}}),B7=r.module({root:fY,parse:WT({declaredIn:fY,in:"string",morphs:(T,_)=>{try{return new URL(T)}catch{return _.error("a URL string")}},declaredOut:WT(URL)})},{name:"string.url"}),k7=r.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:ET(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:ET(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:ET(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:ET(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:ET(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:ET(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:ET(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:ET(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),yY=r.module({root:x.string,alpha:ET(/^[A-Za-z]*$/,"only letters"),alphanumeric:ET(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:s9,base64:a9,capitalize:e9,creditCard:F7,date:Z7,digits:ET(/^\d*$/,"only digits 0-9"),email:X7,integer:PY,ip:H7,json:M7,lower:w7,normalize:K7,numeric:V7,regex:L7,semver:S7,trim:I7,upper:N7,url:B7,uuid:k7},{name:"string"});var vY=r.module({bigint:x.bigint,boolean:x.boolean,false:x.false,never:x.never,null:x.null,number:x.number,object:x.object,string:x.string,symbol:x.symbol,true:x.true,unknown:x.unknown,undefined:x.undefined}),xY=r.module({root:x.unknown,any:x.unknown},{name:"unknown"}),f7=r.module({root:x.jsonObject,stringify:TF("morph",{in:x.jsonObject,morphs:(T)=>JSON.stringify(T),declaredOut:x.string})},{name:"object.json"}),bY=r.module({root:x.object,json:f7},{name:"object"});class hY extends uT{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var P7=V_(["K",x.key],"V")((T)=>({domain:"object",index:{signature:T.K,value:T.V}}),hY);class pY extends uT{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var q7=V_(["T",x.object],["K",x.key])((T)=>T.T.pick(T.K),pY);class gY extends uT{description='omit a set of properties from an object like `Omit(User, "age")`'}var j7=V_(["T",x.object],["K",x.key])((T)=>T.T.omit(T.K),gY);class mY extends uT{description="make all named properties of an object optional like `Partial(User)`"}var y7=V_(["T",x.object])((T)=>T.T.partial(),mY);class oY extends uT{description="make all named properties of an object required like `Required(User)`"}var v7=V_(["T",x.object])((T)=>T.T.required(),oY);class uY extends uT{description='exclude branches of a union like `Exclude("boolean", "true")`'}var x7=V_("T","U")((T)=>T.T.exclude(T.U),uY);class cY extends uT{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var b7=V_("T","U")((T)=>T.T.extract(T.U),cY),dY=r.module({Exclude:x7,Extract:b7,Omit:j7,Partial:y7,Pick:q7,Record:P7,Required:v7});var H0=O2({...vY,...dY,...EY,...OY,string:yY,number:eW,object:bY,unknown:xY},{prereducedAliases:!0,name:"ark"}),jT=H0.export();Object.assign(WF.ambient,jT);WF.typeAttachments={string:jT.string.root,number:jT.number.root,bigint:jT.bigint,boolean:jT.boolean,symbol:jT.symbol,undefined:jT.undefined,null:jT.null,object:jT.object.root,unknown:jT.unknown.root,false:jT.false,true:jT.true,never:jT.never,arrayIndex:jT.Array.index,Key:jT.Key,Record:jT.Record,Array:jT.Array.root,Date:jT.Date};var Y_=Object.assign(H0.type,WF.typeAttachments),h7=H0.match,p7=H0.generic,qL=H0.schema,g7=H0.define,m7=H0.declare;class tF extends Promise{fate;resolve;reject;done=!1;constructor(T){let _,F;super((W,J)=>{_=W,F=J});this.resolve=_,this.reject=F,this.use(T instanceof Promise?T:new Promise(T))}pass(T,_){if(T===this.fate)this.resolve(_),this.done=!0}fail(T,_){if(T===this.fate)this.reject(_),this.done=!0}use(T){if(T instanceof Promise){let _=T;this.fate=_,_.then((F)=>{this.pass(_,F)},(F)=>{this.fail(_,F)})}else this.resolve(T),this.fate=void 0}}var rL=(T,_,F=tY.STORE)=>{return lY(F,{key:`${T.key}:JSON`,get:({get:W})=>_.toJson(W(T)),set:({set:W},J)=>{W(T,_.fromJson(J))}})};function eL(T,_,F){return M2(T,{key:`${_.key}:JSON`,get:(J)=>({get:Y})=>{let $=Y(_,J);return F.toJson($)},set:(J)=>({set:Y},$)=>{Y(_,J,F.fromJson($))}},["mutable","json"])}var iF=(T)=>JSON.parse(T),rT=(T)=>JSON.stringify(T),_D=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function m(T){while(T.child!==null)T=T.child;return T}class _1{_buffer;_index=0;constructor(T){let _;if(typeof T==="number")_=T;else _=T.length;this._buffer=Array.from({length:_})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new _1([...this._buffer]);return T._index=this._index,T}}var o7={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"};function iY(T,_){let F=rT(_),W=`${T.key}(${F})`,J=o7[T.type],Y={key:W,type:J};return Object.assign(Y,{family:{key:T.key,subKey:F}}),Object.assign(Y,{counterfeit:!0}),Y}function nF(T){let _={key:T.key,type:T.type};if("family"in T)_.family=T.family;return _}var w2=(T)=>(_,F,W,J,...Y)=>{console[T](`${_} ${F} "${W}" ${J}`,...Y)},u7={error:w2("error"),info:w2("info"),warn:w2("warn")};class Q2{logLevel;filter;logger;constructor(T,_,F=u7){this.logLevel=T,this.filter=_,this.logger=F}error=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel!==null){if(_===!0)this.logger.error(...T);else if(_!==!1)this.logger.error(..._)}};info=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel==="info"){if(_===!0)this.logger.info(...T);else if(_!==!1)this.logger.info(..._)}};warn=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel!=="error"&&this.logLevel!==null){if(_===!0)this.logger.warn(...T);else if(_!==!1)this.logger.warn(..._)}}}class g_{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,_)=>`${T}:${_}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,_){let F=this.relations.get(T),W=this.relations.get(_);if(F)F.add(_);else F=new Set([_]),this.relations.set(T,F);if(W)W.add(T);else W=new Set([T]),this.relations.set(_,W)}deleteRelation(T,_){let F=this.relations.get(T);if(F){if(F.delete(_),F.size===0)this.relations.delete(T);let W=this.relations.get(_);if(W){if(W.delete(T),W.size===0)this.relations.delete(_)}}}replaceRelationsUnsafely(T,_){this.relations.set(T,new Set(_));for(let F of _){let W=new Set().add(T);this.relations.set(F,W)}}replaceRelationsSafely(T,_){let F=this.relations.get(T),W=this.isAType?.(T)?T:void 0,J=W===void 0?T:void 0;if(F)for(let Y of F){W??=Y,J??=Y;let $=this.relations.get(Y);if($){if($.size===1)this.relations.delete(Y);else $.delete(T);this.contents.delete(this.makeContentKey(W,J))}}this.relations.set(T,new Set(_));for(let Y of _){let $=this.relations.get(Y);if($)$.add(T);else $=new Set().add(T),this.relations.set(Y,$)}}getContentInternal(T){return this.contents.get(T)}setContent(T,_){this.contents.set(T,_)}deleteContent(T){this.contents.delete(T)}constructor(T,_){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!_?.externalStore)this.relations=new Map(T.relations?.map(([F,W])=>[F,new Set(W)])),this.contents=new Map(T.contents);if(this.isAType=_?.isAType??null,this.isBType=_?.isBType??null,this.isContent=_?.isContent??null,_?.makeContentKey)this.makeContentKey=_.makeContentKey;if(_?.externalStore){let F=_.externalStore;if(this.has=(W,J)=>F.has(W,J),this.addRelation=(W,J)=>{F.addRelation(W,J)},this.deleteRelation=(W,J)=>{F.deleteRelation(W,J)},this.replaceRelationsSafely=(W,J)=>{F.replaceRelationsSafely(W,J)},this.replaceRelationsUnsafely=(W,J)=>{F.replaceRelationsUnsafely(W,J)},this.getRelatedKeys=(W)=>F.getRelatedKeys(W),F.getContent)this.getContentInternal=(W)=>{return F.getContent(W)},this.setContent=(W,J)=>{F.setContent(W,J)},this.deleteContent=(W)=>{F.deleteContent(W)};for(let[W,J]of T.relations??[]){let Y=this.isAType?.(W)?W:void 0,$=Y===void 0?W:void 0;for(let Z of J)Y??=Z,$??=Z,this.addRelation(Y,$)}for(let[W,J]of T.contents??[])this.setContent(W,J)}if(_?.warn)this.warn=_.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,_])=>[T,[..._]]),contents:[...this.contents.entries()]}}set(...T){let _,F,W;switch(T.length){case 1:{let J=T[0];_=J[this.a],F=J[this.b],W=void 0;break}case 2:{let J=T[0];if(typeof J==="string")[_,F]=T;else _=J[this.a],F=J[this.b],W=T[1];break}default:{_=T[0],F=T[1],W=T[2];break}}switch(this.cardinality){case"1:1":{let J=this.getRelatedKey(_);if(J&&J!==F)this.delete(_,J)}case"1:n":{let J=this.getRelatedKey(F);if(J&&J!==_)this.delete(J,F)}break;case"n:n":}if(W){let J=this.makeContentKey(_,F);this.setContent(J,W)}return this.addRelation(_,F),this}delete(T,_){_=typeof _==="string"?_:T[this.b];let F=typeof T==="string"?T:T[this.a];if(F===void 0&&typeof _==="string"){let W=this.getRelatedKeys(_);if(W)for(let J of W)this.delete(J,_)}if(typeof F==="string"&&_===void 0){let W=this.getRelatedKeys(F);if(W)for(let J of W)this.delete(F,J)}if(typeof F==="string"&&typeof _==="string"){this.deleteRelation(F,_);let W=this.makeContentKey(F,_);this.deleteContent(W)}return this}getRelatedKey(T){let _=this.getRelatedKeys(T);if(_){if(_.size>1)this.warn?.(`${_.size} related keys were found for key "${T}": (${[..._].map((W)=>`"${W}"`).join(", ")}). Only one related key was expected.`);let F;for(let W of _){F=W;break}return F}}replaceRelations(T,_,F){let W=!Array.isArray(_),J=W?Object.keys(_):_;if(F?.reckless)this.replaceRelationsUnsafely(T,J);else this.replaceRelationsSafely(T,J);if(W)for(let Y of J){let $=this.makeContentKey(T,Y),Z=_[Y];this.setContent($,Z)}return this}getContent(T,_){let F=this.makeContentKey(T,_);return this.getContentInternal(F)}getRelationEntries(T){let _=T[this.a],F=T[this.b];if(_!==void 0&&F===void 0){let W=this.getRelatedKeys(_);if(W)return[...W].map((J)=>{return[J,this.getContent(_,J)]})}if(_===void 0&&F!==void 0){let W=this.getRelatedKeys(F);if(W)return[...W].map((J)=>{return[J,this.getContent(J,F)]})}return[]}has(T,_){if(_)return this.getRelatedKeys(T)?.has(_)??!1;return this.relations.has(T)}}class FT{Subscriber;subscribers=new Map;subscribe(T,_){return this.subscribers.set(T,_),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let _=this.subscribers.values();for(let F of _)F(T)}}class R2 extends FT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function O0(T){return"epoch"in T.transactionMeta}function M_(T){return"phase"in T.transactionMeta}function nY(T){return T[0].toUpperCase()+T.slice(1)}function F1(T){return T.type.split("_").map(nY).join(" ")}class rF extends Error{constructor(T,_){super(`${F1(T)} ${rT(T.key)} not found in store "${_.config.name}".`)}}var YF=(T)=>(_)=>T instanceof Function?T(_):T;var U0=(T,_)=>{if(T.valueMap.has(_.key))return T.logger.info("\uD83D\uDCD6",_.type,_.key,"reading cached value"),rY(_,T);switch(_.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return T.logger.info("\uD83E\uDDEE",_.type,_.key,"computing value"),_.get();case"atom":case"mutable_atom":{let F=_.default,W;if(F instanceof Function)W=F();else W=F;return T.logger.info("\uD83D\uDC81","atom",_.key,"could not find cached value; using default",W),W}}};var sY=(T,_)=>{if(T.operation.open){let F=performance.now();return T.logger.info("\u2757",_.type,_.key,`deferring setState at T-${F} until setState for "${T.operation.token.key}" is done`),F}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:_},T.logger.info("\u2B55",_.type,_.key,`operation start in store "${T.config.name}"${!M_(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},aY=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},eY=(T,_)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",_,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(_)},M0=(T,_)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",_,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(_)};var T$=(T,_,F)=>{switch(_.type){case"mutable_atom":T.logger.info("\uD83D\uDCE2",_.type,_.key,"is now (",F.newValue,") subscribers:",_.subject.subscribers);break;case"atom":case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":T.logger.info("\uD83D\uDCE2",_.type,_.key,"went (",F.oldValue,"->",F.newValue,") subscribers:",_.subject.subscribers)}_.subject.next(F)};var E2=(T,_)=>{let F=m(T),W=F.selectorAtoms.getRelatedKeys(_.key);if(F.logger.info("\uD83E\uDDF9",_.type,_.key,W?`evicting ${W.size} states downstream:`:"no downstream states",W??"to evict"),W){if(F.operation.open)F.logger.info("\uD83E\uDDF9",_.type,_.key,`[ ${[...F.operation.done].join(", ")} ] already done`);for(let J of W){if(eY(F,J))continue;_$(J,F),M0(F,J)}}};var F$=(T,_,F)=>{let W=U0(T,_),J=W;if(_.type==="mutable_atom"&&M_(T)){let{parent:$}=T;J=sF(T,_,$)}if(J=YF(F)(J),T.logger.info("\uD83D\uDCDD","atom",_.key,"set to",J),J=sT(T,_.key,J,_.subject),J$(T,_.key))Y$(T,_.key);M0(T,_.key),E2(T,_);let Y={oldValue:W,newValue:J};if(!M_(T)){T$(T,_,Y);return}if(T.on.transactionApplying.state===null){let{key:$}=_;if(W$(Y.newValue))return;let Z={type:"atom_update",key:$,...Y};if(_.family)Z.family=_.family;T.transactionMeta.update.updates.push(Z),T.logger.info("\uD83D\uDCC1","atom",$,"stowed (",Y.oldValue,"->",Y.newValue,")")}else if(_.key.startsWith("*")){let $=_.key.slice(1),Z=T.atoms.get($),G=T.valueMap.get($);if(Z.type==="mutable_atom"&&M_(T)){let{parent:O}=T;G=sF(T,Z,O)}if(G.do(Y.newValue)===null)E2(T,Z)}};var W1=(T,_,F)=>{switch(_.type){case"atom":case"mutable_atom":F$(T,_,F);break;case"writable_pure_selector":case"writable_held_selector":_.set(F);break}};var J1=(T,_)=>m(T).atoms.has(_),c7=(T,_)=>m(T).writableSelectors.has(_),d7=(T,_)=>m(T).readonlySelectors.has(_),$$=(T,_)=>J1(T,_)||c7(T,_)||d7(T,_);var Y1=(T,_)=>{return m(T).selectorGraph.getRelationEntries({downstreamSelectorKey:_}).filter(([W,{source:J}])=>J!==_).map(([W,{source:J}])=>J).filter((W)=>$$(T,W))};var z2=(T,_,F)=>{let W=[],J=Y1(T,_);while(J.length>0){let Y=J.shift();if(F.has(Y))continue;if(F.add(Y),!J1(T,Y))J.push(...Y1(T,Y));else if(!W.includes(Y))W.push(Y)}return W},Z$=(T,_)=>{let F=T.key,W=Y1(_,F),J=new Set;return W.flatMap((Y)=>J1(_,Y)?Y:z2(_,Y,J))};var X$=(T,_,F,W,J)=>{let Y=m(T),{type:$,key:Z}=W;if($==="atom"||$==="mutable_atom")Y.selectorAtoms.set({selectorKey:F,atomKey:Z}),T.logger.info("\uD83D\uDD0D",_,F,`discovers root atom "${Z}"`);else{let G=z2(T,Z,J);T.logger.info("\uD83D\uDD0D",_,F,`discovers root atoms: [ ${G.map((X)=>`"${X}"`).join(", ")} ]`);for(let X of G)Y.selectorAtoms=Y.selectorAtoms.set({selectorKey:F,atomKey:X})}J.add(Z)};var w0=(T,_,F,W)=>({get:(...J)=>{let Y=m(T),$;if(J.length===2){let[O,M]=J;$=w_(T,O,M)}else[$]=J;let Z=$_(T,$),G=U0(T,Z),X=$.key;return T.logger.info("\uD83D\uDD0C",_,F,`registers dependency ( "${X}" =`,G,")"),Y.selectorGraph.set({upstreamSelectorKey:X,downstreamSelectorKey:F},{source:$.key}),X$(T,_,F,$,W),G},set:(...J)=>{let Y,$;if(J.length===2)Y=J[0],$=J[1];else{let X=J[0],O=J[1];$=J[2],Y=w_(T,X,O)}let Z=m(T),G=$_(Z,Y);W1(Z,G,$)},find:(...J)=>w_(T,...J),json:(J)=>$F(T,J)});var K2=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,{key:$,const:Z}=_,G="readonly_held_selector",{get:X,find:O,json:M}=w0(W,"readonly_held_selector",$,Y),V={..._,type:"readonly_held_selector",subject:J,install:(K)=>K2(K,_,F),get:()=>{return _.get({get:X,find:O,json:M},Z),sT(m(T),$,Z,J),Y.clear(),Z},...F&&{family:F}};W.readonlySelectors.set($,V),T.logger.info("\u2728","readonly_held_selector",$,"=",Z);let B={key:$,type:"readonly_held_selector"};if(F)B.family=F;return B};var V2=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,$=_.key,Z="readonly_pure_selector",{get:G,find:X,json:O}=w0(W,"readonly_pure_selector",$,Y),M=()=>{let K=_.get({get:G,find:X,json:O});return sT(m(T),$,K,J),Y.clear(),K},Q={..._,type:"readonly_pure_selector",subject:J,install:(K)=>V2(K,_,F),get:M,...F&&{family:F}};W.readonlySelectors.set($,Q);let V=M();T.logger.info("\u2728","readonly_pure_selector",$,"=",V);let B={key:$,type:"readonly_pure_selector"};if(F)B.family=F;return B};var L2=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,{key:$,const:Z}=_,G="writable_held_selector",X=w0(W,"writable_held_selector",$,Y),{find:O,get:M,json:Q}=X,V={find:O,get:M,json:Q},B=(y=_.get,u=m(T))=>{return y(V,Z),sT(u,$,Z,J),Y.clear(),Z},v={..._,type:"writable_held_selector",subject:J,install:(y)=>L2(y,_,F),get:B,set:(y)=>{let u=m(T),h=B(_.get,u),p=YF(y)(h);if(T.logger.info("\uD83D\uDCDD","writable_held_selector",$,"set (",h,"->",p,")"),sT(u,$,p,J),M0(u,$),O0(u))J.next({newValue:p,oldValue:h});_.set(X,p)},...F&&{family:F}};W.writableSelectors.set($,v);let q=B();T.logger.info("\u2728","writable_held_selector",$,"=",q);let j={key:$,type:"writable_held_selector"};if(F)j.family=F;return j};var aF=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,$=_.key,Z="writable_pure_selector",G=w0(W,"writable_pure_selector",$,Y),{find:X,get:O,json:M}=G,Q={find:X,get:O,json:M},V=(j=_.get,y=m(T))=>{let u=j(Q);return sT(y,$,u,J),Y.clear(),u},K={..._,type:"writable_pure_selector",subject:J,install:(j)=>aF(j,_,F),get:V,set:(j)=>{let y=m(T),u=V(_.get,y),h=YF(j)(u);if(T.logger.info("\uD83D\uDCDD","writable_pure_selector",$,"set (",u,"->",h,")"),sT(y,_.key,h,J),M0(y,_.key),O0(y))J.next({newValue:h,oldValue:u});_.set(G,h)},...F&&{family:F}};W.writableSelectors.set($,K);let v=V();T.logger.info("\u2728",K.type,K.key,"=",v);let q={key:$,type:"writable_pure_selector"};if(F)q.family=F;return q};function lY(T,_){let F="set"in _,W="const"in _;if(W&&F){let Y=L2(T,_,void 0);return T.on.selectorCreation.next(Y),Y}if(W){let Y=K2(T,_,void 0);return T.on.selectorCreation.next(Y),Y}if(F){let Y=aF(T,_,void 0);return T.on.selectorCreation.next(Y),Y}let J=V2(T,_,void 0);return T.on.selectorCreation.next(J),J}function M2(T,_,F){let W=_.key,J="writable_pure_selector_family",Y={key:W,type:"writable_pure_selector_family"},$=T.families.get(W);if($)T.logger.error("\u2757","writable_pure_selector_family",W,`Overwriting an existing ${F1($)} "${$.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let Z=new FT,X=Object.assign((O)=>{let M=rT(O),Q={key:W,subKey:M},V=`${W}(${M})`,B=m(T),K=aF(B,{key:V,get:_.get(O),set:_.set(O)},Q);return Z.next({type:"state_creation",token:K}),K},Y,{internalRoles:F,subject:Z,install:(O)=>M2(O,_),default:(O)=>{return _.get(O)({get:(...Q)=>eF(T,...Q),find:(...Q)=>w_(T,...Q),json:(Q)=>$F(T,Q)})}});return T.families.set(W,X),Y}function G$(T,_,F){let W=T.families.get(_.key);if(W===void 0)throw new rF(_,T);let J=W(F),Y=m(T);if(J.family){if(O0(Y))switch(J.type){case"atom":case"mutable_atom":T.on.atomCreation.next(J);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":T.on.selectorCreation.next(J);break}else if(M_(Y)&&Y.on.transactionApplying.state===null)Y.transactionMeta.update.updates.push({type:"state_creation",token:J})}return J}function A$(T,_,F){let W=rT(F),J=`${_.key}(${W})`,Y=m(T),$;switch(_.type){case"atom_family":case"mutable_atom_family":$=Y.atoms.get(J);break;case"writable_held_selector_family":case"writable_pure_selector_family":$=Y.writableSelectors.get(J);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":$=Y.readonlySelectors.get(J);break}if($)return nF($);return $}function w_(T,_,F){let W=A$(T,_,F);if(W)return W;let J=rT(F),Y=T.molecules.get(J);if(!Y&&T.config.lifespan==="immortal"){let $=iY(_,F);return T.logger.error("\u274C",$.type,$.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),$}if(W=G$(T,_,F),Y)m(T).moleculeData.set(J,_.key);return W}function H$(T,_){if(_.family){let F=T.families.get(_.family.key);if(F)return F}}function Q0(T,..._){let F,W,J,Y;if(_.length===2){if(F=_[0],Y=_[1],W=H$(T,F)??null,W)J=F.family?iF(F.family.subKey):null,F=w_(T,W,J)}else W=_[0],J=_[1],Y=_[2],F=w_(T,W,J);if("counterfeit"in F&&"family"in F){let G=F.family.subKey,X=T.disposalTraces.buffer.find((O)=>O?.key===G);T.logger.error("\u274C",F.type,F.key,`could not be set because it was not found in the store "${T.config.name}".`,X?`This state was previously disposed:
|
|
48
48
|
${X.trace}`:"No previous disposal trace was found.");return}let $=sY(T,F);if($){let G=T.on.operationClose.subscribe(`waiting to set "${F.key}" at T-${$}`,()=>{G(),T.logger.info("\uD83D\uDFE2",F.type,F.key,`resuming deferred setState from T-${$}`),Q0(T,F,Y)});return}let Z=$_(T,F);W1(T,Z,Y),aY(T)}function eF(T,..._){let F,W,J;if(_.length===1)F=_[0];else W=_[0],J=_[1],F=w_(T,W,J);if("counterfeit"in F&&"family"in F){W=T.families.get(F.family.key);let Y=F.family.subKey,$=T.disposalTraces.buffer.find((Z)=>Z?.key===Y);switch(T.logger.error("\u274C",F.type,F.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,$?`This state was previously disposed:
|
|
49
|
-
${$.trace}`:"No previous disposal trace was found."),W.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(W.key);case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(T.defaults.has(W.key))return T.defaults.get(F.family.key);let Z=$_(T,W).default(Y);return T.defaults.set(W.key,Z),Z}}}return U0(T,$_(T,F))}class O${parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new g_({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new g_({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new g_({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new g_({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new _1(100);molecules=new Map;moleculeJoins=new g_({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new g_({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new g_({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new FT,atomDisposal:new FT,selectorCreation:new FT,selectorDisposal:new FT,timelineCreation:new FT,transactionCreation:new FT,transactionApplying:new R2(null),operationClose:new FT,moleculeCreation:new FT,moleculeDisposal:new FT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Q2("warn",(T,_,F)=>!M$(F))];logger={error:(...T)=>{for(let _ of this.loggers)_.error(...T)},info:(...T)=>{for(let _ of this.loggers)_.info(...T)},warn:(...T)=>{for(let _ of this.loggers)_.warn(...T)}};constructor(T,_=null){if(this.config={..._?.config,...T},_!==null){if(this.valueMap=new Map(_?.valueMap),this.operation={..._?.operation},O0(_))this.transactionMeta={epoch:new Map(_?.transactionMeta.epoch),actionContinuities:new g_(_?.transactionMeta.actionContinuities.toJSON())};for(let[,W]of _.families){if(W.internalRoles?.includes("mutable")||W.internalRoles?.includes("join"))continue;W.install(this)}let F=new Set;for(let[,W]of _.atoms){if(F.has(W.key))continue;if(W.install(this),W.type==="mutable_atom"){let J=$F(_,W),Y=U$(W);F.add(J.key),F.add(Y.key)}}for(let[,W]of _.readonlySelectors)W.install(this);for(let[,W]of _.writableSelectors){if(F.has(W.key))continue;W.install(this)}for(let[,W]of _.transactions)W.install(this);for(let[,W]of _.timelines)W.install(this)}}}var tY={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new O$({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function $_(T,_){let F,W=T;while(W!==null){switch(_.type){case"atom":case"mutable_atom":F=W.atoms.get(_.key);break;case"writable_pure_selector":case"writable_held_selector":F=W.writableSelectors.get(_.key);break;case"readonly_pure_selector":case"readonly_held_selector":F=W.readonlySelectors.get(_.key);break;case"atom_family":case"mutable_atom_family":case"writable_pure_selector_family":case"readonly_pure_selector_family":case"writable_held_selector_family":case"readonly_held_selector_family":F=W.families.get(_.key);break;case"timeline":F=W.timelines.get(_.key);break;case"transaction":F=W.transactions.get(_.key);break}if(F)return F;W=W.child}throw new rF(_,T)}var w$=(T,_)=>{let F=m(T);if(F.operation.open)return F.operation.prev.get(_.key);return F.valueMap.get(_.key)};var D2=(T,_)=>{let F=m(T);return Z$(_,T).map((J)=>{let Y=F.atoms.get(J);if(Y===void 0)throw new Error(`Atom "${J}", a dependency of selector "${_.key}", not found in store "${T.config.name}".`);return Y.subject.subscribe(`${_.type}:${_.key}`,($)=>{T.logger.info("\uD83D\uDCE2",_.type,_.key,"root",J,"went",$.oldValue,"->",$.newValue);let Z=w$(F,_),G=U0(F,_);T.logger.info("\u2728",_.type,_.key,"went",Z,"->",G),_.subject.next({newValue:G,oldValue:Z})})})};function TW(T,_,F,W){function J(M){if(T.operation.open){let Q=T.on.operationClose.subscribe(`state subscription ${F}`,()=>{Q(),W(M)})}else W(M)}let Y=$_(T,_);T.logger.info("\uD83D\uDC40",Y.type,Y.key,`Adding subscription "${F}"`);let $=Y.type==="writable_pure_selector"||Y.type==="readonly_pure_selector",Z=null,G=J;if($)Z=D2(T,Y),G=(M)=>{if(Z)Z.length=0,Z.push(...D2(T,Y));J(M)};let X=Y.subject.subscribe(F,G);return()=>{if(T.logger.info("\uD83D\uDE48",Y.type,Y.key,`Removing subscription "${F}"`),X(),Z)for(let M of Z)M()}}var Q$=(T,_,F,W)=>{let J=$_(T,_);T.logger.info("\uD83D\uDC40","timeline",_.key,`Adding subscription "${F}"`);let Y=J.subject.subscribe(F,W);return()=>{T.logger.info("\uD83D\uDE48","timeline",_.key,`Removing subscription "${F}" from timeline`),Y()}};class S2{initializeState(T,_){let F=`*${T.key}`;_.atoms.delete(F),_.valueMap.delete(F);let W=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,J=I2(_,{key:F,default:null},W);if(_.parent?.valueMap.has(F)){let Y=_.parent.valueMap.get(F);_.valueMap.set(F,Y)}return J}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,_,F){let W=`tracker:${F.config.name}:${M_(F)?F.transactionMeta.update.key:"main"}:${T.key}`,J=eF(F,T);this.unsubscribeFromInnerValue=J.subscribe(W,(Y)=>{Q0(F,_,Y)}),this.unsubscribeFromState=TW(F,T,W,(Y)=>{if(Y.newValue!==Y.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=Y.newValue.subscribe(W,($)=>{Q0(F,_,$)})})}updateCore(T,_,F){let W=`tracker:${F.config.name}:${M_(F)?F.transactionMeta.update.key:"main"}:${T.key}`;TW(F,_,W,({newValue:J,oldValue:Y})=>{let $=F.timelineTopics.getRelatedKey(_.key);if($){if(F.timelines.get($)?.timeTraveling){let X=Q$(F,{key:$,type:"timeline"},W,(O)=>{X(),Q0(F,T,(M)=>{if(O==="redo"&&J)M.do(J);else if(O==="undo"&&Y)M.undo(Y);return M})});return}}let Z=F.on.operationClose.subscribe(W,()=>{Z();let G=eF(F,T),X=J===null?-1:G.getUpdateNumber(J),O=X-G.cacheUpdateNumber;if(J&&O===1)Q0(F,T,(M)=>(M.do(J),M));else F.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${G.cacheUpdateNumber+1}, but got ${X}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(T,_){this.mutableState=T;let F=m(_);this.latestUpdateState=this.initializeState(T,F),this.observeCore(T,this.latestUpdateState,F),this.updateCore(T,this.latestUpdateState,F),F.trackers.set(T.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),F.trackers.delete(T.key)}}}var $F=(T,_)=>{if(_.family){let W=m(T),Y={key:`${_.family.key}:JSON`,type:"writable_pure_selector_family"},$=$_(W,Y),Z=JSON.parse(_.family.subKey);return w_(T,$,Z)}return{type:"writable_pure_selector",key:`${_.key}:JSON`}};var U$=(T)=>{let F={type:"atom",key:`*${T.key}`};if(T.family)F.family={key:`*${T.family.key}`,subKey:T.family.subKey};return F};function W$(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function sF(T,_,F){let W=F.valueMap.get(_.key),J=T.valueMap.get(_.key);if(W!==J)return J;if(W===void 0)return _.default();F.logger.info("\uD83D\uDCC3","atom",_.key,"copying");let Y=_.toJson(W),$=_.fromJson(Y);return T.valueMap.set(_.key,$),new S2(_,F),$}function sT(T,_,F,W){let J=T.valueMap.get(_);if(J instanceof tF)J.use(F);if(F instanceof Promise){let Y=new tF(F);return T.valueMap.set(_,Y),Y.then(($)=>{sT(T,_,$,W),W.next({newValue:$,oldValue:Y})}).catch(($)=>{T.logger.error("\uD83D\uDCA5","state",_,"rejected:",$)}),Y}return T.valueMap.set(_,F),F}var rY=(T,_)=>{let F=_.valueMap.get(T.key);if(T.type==="mutable_atom"&&M_(_)){let{parent:W}=_;F=sF(_,T,W)}return F},_$=(T,_)=>{let F=_.valueMap.get(T);if(F instanceof tF){let W=F,J=_.writableSelectors.get(T)??_.readonlySelectors.get(T);if(J)W.use(J.get());return}if(_.operation.open)_.operation.prev.set(T,F);_.valueMap.delete(T),_.logger.info("\uD83D\uDDD1","state",T,"evicted")};var J$=(T,_)=>{return m(T).atomsThatAreDefault.has(_)},R$=(T,_)=>{let F=m(T);F.atomsThatAreDefault=new Set(F.atomsThatAreDefault).add(_)},Y$=(T,_)=>{let F=m(T);F.atomsThatAreDefault=new Set(m(T).atomsThatAreDefault),F.atomsThatAreDefault.delete(_)};function I2(T,_,F){let{key:J,default:Y}=_;T.logger.info("\uD83D\uDD28","atom",J,`creating in store "${T.config.name}"`);let $=m(T),Z=$.atoms.get(J);if(Z&&Z.type==="atom")return T.logger.error("\u274C","atom",J,"Tried to create atom, but it already exists in the store."),nF(Z);let G=new FT,X={..._,type:"atom",install:(Q)=>{return Q.logger.info("\uD83D\uDEE0\uFE0F","atom",J,`installing in store "${Q.config.name}"`),I2(Q,_,F)},subject:G};if(F)X.family=F;let O=Y;if(Y instanceof Function)O=Y();$.atoms.set(J,X),R$(T,J),sT($,J,O,G);let M=nF(X);if(_.effects){let Q=0,K=[];for(let B of _.effects){let V=B({setSelf:(v)=>{Q0(T,M,v)},onSet:(v)=>TW(T,M,`effect[${Q}]`,v)});if(V)K.push(V);++Q}X.cleanup=()=>{for(let B of K)B()}}return M}class ZF extends Set{mode="record";subject=new FT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,_=0){super(T);if(T instanceof ZF)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(_)this.cacheLimit=_,this.cache=new Array(_),this.subscribe("auto cache",(F)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=F})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let _=new ZF(T.members,T.cacheLimit);return _.cache=T.cache,_.cacheIdx=T.cacheIdx,_.cacheUpdateNumber=T.cacheUpdateNumber,_}add(T){let _=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${rT(T)}`);return _}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let _=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${rT(T)}`);return _}parent=null;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new ZF(this);let _=this.child._subscribe("transaction",(F)=>{this.transactionUpdates?.push(F)});try{if(T(this.child)){for(let W of this.transactionUpdates)this.doStep(W);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(F){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",F),F}finally{_(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,_){return this.subject.subscribe(T,_)}subscribe(T,_){return this.subject.subscribe(T,(F)=>{_(`${this.cacheUpdateNumber}=${F}`)})}emit(T){this.subject.next(T)}doStep(T){let _=T.indexOf(":"),F=T.substring(0,_),W=T.substring(_+1);switch(F){case"add":this.add(JSON.parse(W));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(W));break;case"tx":for(let J of W.split(";"))this.doStep(J)}}getUpdateNumber(T){let _=T.indexOf("=");return Number(T.substring(0,_))}do(T){let _=T.indexOf("="),F=Number(T.substring(0,_)),W=F-this.cacheUpdateNumber;if(W>0){if(W===1){this.mode="playback";let Y=T.substring(_+1);return this.doStep(Y),this.mode="record",this.cacheUpdateNumber=F,null}return this.cacheUpdateNumber+1}if(Math.abs(W)<this.cacheLimit){let Y=this.cacheIdx+W;if(this.cache[Y]===T)return null;this.mode="playback";let Z=!1;while(!Z){this.cacheIdx%=this.cacheLimit;let X=this.cache[this.cacheIdx];if(this.cacheIdx--,!X)return"OUT_OF_RANGE";this.undo(X),Z=this.cacheIdx===Y-1}let G=T.substring(_+1);return this.doStep(G),this.mode="record",this.cacheUpdateNumber=F,null}return"OUT_OF_RANGE"}undoStep(T){let _=T.indexOf(":"),F=T.substring(0,_),W=T.substring(_+1);switch(F){case"add":this.delete(JSON.parse(W));break;case"del":this.add(JSON.parse(W));break;case"clear":{let J=JSON.parse(W);for(let Y of J)this.add(Y);break}case"tx":{let J=W.split(";");for(let Y=J.length-1;Y>=0;Y--)this.undoStep(J[Y])}}}undo(T){let _=T.indexOf("=");if(Number(T.substring(0,_))===this.cacheUpdateNumber){this.mode="playback";let W=T.substring(_+1);return this.undoStep(W),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function M$(T){return T.startsWith("\uD83D\uDD0D ")}class $1{supported;constructor(T){this.supported=T}refine(T){for(let[_,F]of Object.entries(this.supported))try{if(F(T)===!0&&F!==Boolean)return{type:_,data:T}}catch(W){try{if(T instanceof F)return{type:_,data:T}}catch(J){}}return null}}var l7=new $1({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function t7(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var i7=new $1({object:t7,array:(T)=>Array.isArray(T)}),n7=new $1({...l7.supported,...i7.supported}),E$=(T)=>{if(T===void 0)return"undefined";let _=n7.refine(T);if(_)return _.type;return Object.getPrototypeOf(T).constructor.name};class Z1{listeners;globalListeners;handleEvent(T,..._){for(let W of this.globalListeners)W(T,..._);let F=this.listeners.get(T);if(F)for(let W of F)W(..._)}id="no_id_retrieved";emit;constructor(T){this.emit=T,this.listeners=new Map,this.globalListeners=new Set}on(T,_){let F=this.listeners.get(T);if(F)F.add(_);else this.listeners.set(T,new Set([_]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,_){let F=this.listeners.get(T);if(F)if(_)F.delete(_);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class z$ extends Z1{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((..._)=>{return this.out.next(_),this});this.id=T,this.in=new FT,this.out=new FT,this.in.subscribe("socket",(_)=>{this.handleEvent(..._)})}dispose(){for(let T of this.disposalFunctions)T()}}class N2 extends Z1{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(rT(T.map((_)=>_ instanceof ZF?`{ ${_.toJSON().members.join(" | ")} }`:_))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,..._)=>{let F=JSON.stringify([T,..._]);return this.process.stdout.write(F+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let _=T.toString();this.unprocessedEvents.push(..._.split("\x03"));let F=this.unprocessedEvents.shift();this.incompleteData+=F??"";try{let W=iF(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",W),this.handleEvent(...W);while(this.unprocessedEvents.length>0){let J=this.unprocessedEvents.shift();if(J){if(this.unprocessedEvents.length===0)this.incompleteData=J;let Y=iF(J);this.handleEvent(...Y)}}this.incompleteData=""}catch(W){if(W instanceof Error)this.logger.error("\u2757",W.message,W.cause,W.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let _=new z$(`user:${T}`);this.relays.set(T,_),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let F of this.relayServices){let W=F(_);if(W)_.disposalFunctions.push(W)}this.on(`user:${T}`,(...F)=>{_.in.next(F)}),_.out.subscribe("socket",(F)=>{this.emit(...F)})}),this.on("user-leaves",(T)=>{let _=this.relays.get(T);if(this.off(`relay:${T}`),_)_.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var{file:s5,serve:HO}=globalThis.Bun;import{readFileSync as L$}from"fs";import{createServer as e7}from"http";import{createServer as T3}from"https";import{resolve as B2}from"path";function V$(T,_){if(T instanceof Promise)throw new Error(_)}function r7(T,_){let F={},W=[];for(let J in T){let Y=T[J]["~standard"].validate(_[J]);if(V$(Y,`Validation must be synchronous, but ${J} returned a Promise.`),Y.issues){W.push(...Y.issues.map(($)=>({...$,message:$.message,path:[J,...$.path??[]]})));continue}F[J]=Y.value}if(W.length)return{issues:W};return{value:F}}function C2(T){let _=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[j,y]of Object.entries(_))if(y==="")delete _[j]}if(!!T.skipValidation)return _;let J=typeof T.client==="object"?T.client:{},Y=typeof T.server==="object"?T.server:{},$=typeof T.shared==="object"?T.shared:{},Z=T.isServer??(typeof window==="undefined"||("Deno"in window)),G=Z?{...Y,...$,...J}:{...J,...$},X=T.createFinalSchema?.(G,Z)["~standard"].validate(_)??r7(G,_);V$(X,"Validation must be synchronous");let O=T.onValidationError??((j)=>{throw console.error("\u274C Invalid environment variables:",j),new Error("Invalid environment variables")}),M=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(X.issues)return O(X.issues);let Q=(j)=>{if(!T.clientPrefix)return!0;return!j.startsWith(T.clientPrefix)&&!(j in $)},K=(j)=>{return Z||!Q(j)},B=(j)=>{return j==="__esModule"||j==="$$typeof"},V=(T.extends??[]).reduce((j,y)=>{return Object.assign(j,y)},{}),v=Object.assign(V,X.value);return new Proxy(v,{get(j,y){if(typeof y!=="string")return;if(B(y))return;if(!K(y))return M(y);return Reflect.get(j,y)}})}var s7="__vite_start_time"in globalThis,a7=typeof window!=="undefined",fN="vitest"in globalThis,s_=Y_("string"),K$=Y_('"true" | "false" | undefined'),q_=C2({isServer:!s7&&!a7,server:{CI:Y_("string | undefined").pipe(Boolean),POSTGRES_USER:s_,POSTGRES_PASSWORD:s_,POSTGRES_DATABASE:s_,POSTGRES_HOST:s_,POSTGRES_PORT:s_.pipe((T)=>Number.parseInt(T,10)),BACKEND_PORT:s_.pipe((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:K$.pipe((T)=>T==="true"),FRONTEND_PORT:s_.pipe((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:s_.pipe.try((T)=>JSON.parse(T),Y_("string[]")),API_KEY_OPENAI:Y_("string | undefined"),API_KEY_RESEND:Y_("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:s_,VITE_DEV_FRONTEND_HOST:Y_("string | undefined"),VITE_DEV_HTTPS:K$.pipe((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var D$=B2(import.meta.dirname,"../dev"),X1=q_.VITE_DEV_HTTPS?{cert:L$(B2(D$,"./cert.pem"),"utf-8"),key:L$(B2(D$,"./key.pem"),"utf-8")}:void 0;function bN(T){if(X1)return T3(X1,T);return e7({},T)}import JO from"path";var H=Symbol.for("drizzle:entityKind"),pN=Symbol.for("drizzle:hasOwnEntityKind");function R(T,_){if(!T||typeof T!=="object")return!1;if(T instanceof _)return!0;if(!Object.prototype.hasOwnProperty.call(_,H))throw new Error(`Class "${_.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let F=Object.getPrototypeOf(T).constructor;if(F)while(F){if(H in F&&F[H]===_[H])return!0;F=Object.getPrototypeOf(F)}return!1}class GT{constructor(T,_){this.table=T,this.config=_,this.name=_.name,this.keyAsName=_.keyAsName,this.notNull=_.notNull,this.default=_.default,this.defaultFn=_.defaultFn,this.onUpdateFn=_.onUpdateFn,this.hasDefault=_.hasDefault,this.primary=_.primaryKey,this.isUnique=_.isUnique,this.uniqueName=_.uniqueName,this.uniqueType=_.uniqueType,this.dataType=_.dataType,this.columnType=_.columnType,this.generated=_.generated,this.generatedIdentity=_.generatedIdentity}static[H]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class k2{static[H]="ColumnBuilder";config;constructor(T,_,F){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:_,columnType:F,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var j_=Symbol.for("drizzle:Name");class f2{static[H]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,_){if(this.reference=()=>{let{name:F,columns:W,foreignColumns:J}=T();return{name:F,columns:W,foreignTable:J[0].table,foreignColumns:J}},_)this._onUpdate=_.onUpdate,this._onDelete=_.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new S$(T,this)}}class S${constructor(T,_){this.table=T,this.reference=_.reference,this.onUpdate=_._onUpdate,this.onDelete=_._onDelete}static[H]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:_,foreignColumns:F}=this.reference(),W=_.map(($)=>$.name),J=F.map(($)=>$.name),Y=[this.table[j_],...W,F[0].table[j_],...J];return T??`${Y.join("_")}_fk`}}function G1(T,..._){return T(..._)}function I$(T,_){return`${T[j_]}_${_.join("_")}_unique`}function N$(T,_,F){for(let W=_;W<T.length;W++){let J=T[W];if(J==="\\"){W++;continue}if(J==='"')return[T.slice(_,W).replace(/\\/g,""),W+1];if(F)continue;if(J===","||J==="}")return[T.slice(_,W).replace(/\\/g,""),W]}return[T.slice(_).replace(/\\/g,""),T.length]}function C$(T,_=0){let F=[],W=_,J=!1;while(W<T.length){let Y=T[W];if(Y===","){if(J||W===_)F.push("");J=!0,W++;continue}if(J=!1,Y==="\\"){W+=2;continue}if(Y==='"'){let[G,X]=N$(T,W+1,!0);F.push(G),W=X;continue}if(Y==="}")return[F,W+1];if(Y==="{"){let[G,X]=C$(T,W+1);F.push(G),W=X;continue}let[$,Z]=N$(T,W,!1);F.push($),W=Z}return[F,W]}function B$(T){let[_]=C$(T,1);return _}function P2(T){return`{${T.map((_)=>{if(Array.isArray(_))return P2(_);if(typeof _==="string")return`"${_.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${_}`}).join(",")}}`}class f extends k2{foreignKeyConfigs=[];static[H]="PgColumnBuilder";array(T){return new f$(this.config.name,this,T)}references(T,_={}){return this.foreignKeyConfigs.push({ref:T,actions:_}),this}unique(T,_){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=_?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,_){return this.foreignKeyConfigs.map(({ref:F,actions:W})=>{return G1((J,Y)=>{let $=new f2(()=>{let Z=J();return{columns:[T],foreignColumns:[Z]}});if(Y.onUpdate)$.onUpdate(Y.onUpdate);if(Y.onDelete)$.onDelete(Y.onDelete);return $.build(_)},F,W)})}buildExtraConfigColumn(T){return new k$(T,this.config)}}class S extends GT{constructor(T,_){if(!_.uniqueName)_.uniqueName=I$(T,[_.name]);super(T,_);this.table=T}static[H]="PgColumn"}class k$ extends S{static[H]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(T){return this.indexConfig.opClass=T,this}}class _W{static[H]="IndexedColumn";constructor(T,_,F,W){this.name=T,this.keyAsName=_,this.type=F,this.indexConfig=W}name;keyAsName;type;indexConfig}class f$ extends f{static[H]="PgArrayBuilder";constructor(T,_,F){super(T,"array","PgArray");this.config.baseBuilder=_,this.config.size=F}build(T){let _=this.config.baseBuilder.build(T);return new q2(T,this.config,_)}}class q2 extends S{constructor(T,_,F,W){super(T,_);this.baseColumn=F,this.range=W,this.size=_.size}size;static[H]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=B$(T);return T.map((_)=>this.baseColumn.mapFromDriverValue(_))}mapToDriverValue(T,_=!1){let F=T.map((W)=>W===null?null:R(this.baseColumn,q2)?this.baseColumn.mapToDriverValue(W,!0):this.baseColumn.mapToDriverValue(W));if(_)return F;return P2(F)}}class P$ extends f{static[H]="PgEnumObjectColumnBuilder";constructor(T,_){super(T,"string","PgEnumObjectColumn");this.config.enum=_}build(T){return new q$(T,this.config)}}class q$ extends S{static[H]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(T,_){super(T,_);this.enum=_.enum}getSQLType(){return this.enum.enumName}}var A1=Symbol.for("drizzle:isPgEnum");function j$(T){return!!T&&typeof T==="function"&&A1 in T&&T[A1]===!0}class y$ extends f{static[H]="PgEnumColumnBuilder";constructor(T,_){super(T,"string","PgEnumColumn");this.config.enum=_}build(T){return new v$(T,this.config)}}class v$ extends S{static[H]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,_){super(T,_);this.enum=_.enum}getSQLType(){return this.enum.enumName}}function FW(T,_){return Array.isArray(_)?_3(T,[..._],void 0):F3(T,_,void 0)}function _3(T,_,F){let W=Object.assign((J)=>new y$(J??"",W),{enumName:T,enumValues:_,schema:F,[A1]:!0});return W}function F3(T,_,F){let W=Object.assign((J)=>new P$(J??"",W),{enumName:T,enumValues:Object.values(_),schema:F,[A1]:!0});return W}class IT{static[H]="Subquery";constructor(T,_,F,W=!1,J=[]){this._={brand:"Subquery",sql:T,selectedFields:_,alias:F,isWith:W,usedTables:J}}}class WW extends IT{static[H]="WithSubquery"}var x$="0.44.0";var j2,y2,AT={startActiveSpan(T,_){if(!j2)return _();if(!y2)y2=j2.trace.getTracer("drizzle-orm",x$);return G1((F,W)=>W.startActiveSpan(T,(J)=>{try{return _(J)}catch(Y){throw J.setStatus({code:F.SpanStatusCode.ERROR,message:Y instanceof Error?Y.message:"Unknown error"}),Y}finally{J.end()}}),j2,y2)}};var MT=Symbol.for("drizzle:ViewBaseConfig");var k0=Symbol.for("drizzle:Schema"),H1=Symbol.for("drizzle:Columns"),b$=Symbol.for("drizzle:ExtraConfigColumns"),v2=Symbol.for("drizzle:OriginalName"),x2=Symbol.for("drizzle:BaseName"),JW=Symbol.for("drizzle:IsAlias"),h$=Symbol.for("drizzle:ExtraConfigBuilder"),W3=Symbol.for("drizzle:IsDrizzleTable");class I{static[H]="Table";static Symbol={Name:j_,Schema:k0,OriginalName:v2,Columns:H1,ExtraConfigColumns:b$,BaseName:x2,IsAlias:JW,ExtraConfigBuilder:h$};[j_];[v2];[k0];[H1];[b$];[x2];[JW]=!1;[W3]=!0;[h$]=void 0;constructor(T,_,F){this[j_]=this[v2]=T,this[k0]=_,this[x2]=F}}function xT(T){return T[j_]}function f0(T){return`${T[k0]??"public"}.${T[j_]}`}function b2(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function J3(T){let _={sql:"",params:[]};for(let F of T)if(_.sql+=F.sql,_.params.push(...F.params),F.typings?.length){if(!_.typings)_.typings=[];_.typings.push(...F.typings)}return _}class yT{static[H]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new k([this])}}class k{constructor(T){this.queryChunks=T;for(let _ of T)if(R(_,I)){let F=_[I.Symbol.Schema];this.usedTables.push(F===void 0?_[I.Symbol.Name]:F+"."+_[I.Symbol.Name])}}static[H]="SQL";decoder=g$;shouldInlineParams=!1;usedTables=[];append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return AT.startActiveSpan("drizzle.buildSQL",(_)=>{let F=this.buildQueryFromSourceParams(this.queryChunks,T);return _?.setAttributes({"drizzle.query.text":F.sql,"drizzle.query.params":JSON.stringify(F.params)}),F})}buildQueryFromSourceParams(T,_){let F=Object.assign({},_,{inlineParams:_.inlineParams||this.shouldInlineParams,paramStartIndex:_.paramStartIndex||{value:0}}),{casing:W,escapeName:J,escapeParam:Y,prepareTyping:$,inlineParams:Z,paramStartIndex:G}=F;return J3(T.map((X)=>{if(R(X,yT))return{sql:X.value.join(""),params:[]};if(R(X,O1))return{sql:J(X.value),params:[]};if(X===void 0)return{sql:"",params:[]};if(Array.isArray(X)){let O=[new yT("(")];for(let[M,Q]of X.entries())if(O.push(Q),M<X.length-1)O.push(new yT(", "));return O.push(new yT(")")),this.buildQueryFromSourceParams(O,F)}if(R(X,k))return this.buildQueryFromSourceParams(X.queryChunks,{...F,inlineParams:Z||X.shouldInlineParams});if(R(X,I)){let O=X[I.Symbol.Schema],M=X[I.Symbol.Name];return{sql:O===void 0||X[JW]?J(M):J(O)+"."+J(M),params:[]}}if(R(X,GT)){let O=W.getColumnCasing(X);if(_.invokeSource==="indexes")return{sql:J(O),params:[]};let M=X.table[I.Symbol.Schema];return{sql:X.table[JW]||M===void 0?J(X.table[I.Symbol.Name])+"."+J(O):J(M)+"."+J(X.table[I.Symbol.Name])+"."+J(O),params:[]}}if(R(X,Z_)){let O=X[MT].schema,M=X[MT].name;return{sql:O===void 0||X[MT].isAlias?J(M):J(O)+"."+J(M),params:[]}}if(R(X,Q_)){if(R(X.value,R0))return{sql:Y(G.value++,X),params:[X],typings:["none"]};let O=X.value===null?null:X.encoder.mapToDriverValue(X.value);if(R(O,k))return this.buildQueryFromSourceParams([O],F);if(Z)return{sql:this.mapInlineParam(O,F),params:[]};let M=["none"];if($)M=[$(X.encoder)];return{sql:Y(G.value++,O),params:[O],typings:M}}if(R(X,R0))return{sql:Y(G.value++,X),params:[X],typings:["none"]};if(R(X,k.Aliased)&&X.fieldAlias!==void 0)return{sql:J(X.fieldAlias),params:[]};if(R(X,IT)){if(X._.isWith)return{sql:J(X._.alias),params:[]};return this.buildQueryFromSourceParams([new yT("("),X._.sql,new yT(") "),new O1(X._.alias)],F)}if(j$(X)){if(X.schema)return{sql:J(X.schema)+"."+J(X.enumName),params:[]};return{sql:J(X.enumName),params:[]}}if(b2(X)){if(X.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([X.getSQL()],F);return this.buildQueryFromSourceParams([new yT("("),X.getSQL(),new yT(")")],F)}if(Z)return{sql:this.mapInlineParam(X,F),params:[]};return{sql:Y(G.value++,X),params:[X],typings:["none"]}}))}mapInlineParam(T,{escapeString:_}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return _(T);if(typeof T==="object"){let F=T.toString();if(F==="[object Object]")return _(JSON.stringify(T));return _(F)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new k.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class O1{constructor(T){this.value=T}static[H]="Name";brand;getSQL(){return new k([this])}}function p$(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var g$={mapFromDriverValue:(T)=>T},m$={mapToDriverValue:(T)=>T},CC={...g$,...m$};class Q_{constructor(T,_=m$){this.value=T,this.encoder=_}static[H]="Param";brand;getSQL(){return new k([this])}}function U(T,..._){let F=[];if(_.length>0||T.length>0&&T[0]!=="")F.push(new yT(T[0]));for(let[W,J]of _.entries())F.push(J,new yT(T[W+1]));return new k(F)}((T)=>{function _(){return new k([])}T.empty=_;function F(G){return new k(G)}T.fromList=F;function W(G){return new k([new yT(G)])}T.raw=W;function J(G,X){let O=[];for(let[M,Q]of G.entries()){if(M>0&&X!==void 0)O.push(X);O.push(Q)}return new k(O)}T.join=J;function Y(G){return new O1(G)}T.identifier=Y;function $(G){return new R0(G)}T.placeholder=$;function Z(G,X){return new Q_(G,X)}T.param=Z})(U||(U={}));((T)=>{class _{constructor(F,W){this.sql=F,this.fieldAlias=W}static[H]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new _(this.sql,this.fieldAlias)}}T.Aliased=_})(k||(k={}));class R0{constructor(T){this.name=T}static[H]="Placeholder";getSQL(){return new k([this])}}function h2(T,_){return T.map((F)=>{if(R(F,R0)){if(!(F.name in _))throw new Error(`No value for placeholder "${F.name}" was provided`);return _[F.name]}if(R(F,Q_)&&R(F.value,R0)){if(!(F.value.name in _))throw new Error(`No value for placeholder "${F.value.name}" was provided`);return F.encoder.mapToDriverValue(_[F.value.name])}return F})}var Y3=Symbol.for("drizzle:IsDrizzleView");class Z_{static[H]="View";[MT];[Y3]=!0;constructor({name:T,schema:_,selectedFields:F,query:W}){this[MT]={name:T,originalName:T,schema:_,selectedFields:F,query:W,isExisting:!W,isAlias:!1}}getSQL(){return new k([this])}}GT.prototype.getSQL=function(){return new k([this])};I.prototype.getSQL=function(){return new k([this])};IT.prototype.getSQL=function(){return new k([this])};class XF{constructor(T){this.table=T}static[H]="ColumnAliasProxyHandler";get(T,_){if(_==="table")return this.table;return T[_]}}class YW{constructor(T,_){this.alias=T,this.replaceOriginalName=_}static[H]="TableAliasProxyHandler";get(T,_){if(_===I.Symbol.IsAlias)return!0;if(_===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&_===I.Symbol.OriginalName)return this.alias;if(_===MT)return{...T[MT],name:this.alias,isAlias:!0};if(_===I.Symbol.Columns){let W=T[I.Symbol.Columns];if(!W)return W;let J={};return Object.keys(W).map((Y)=>{J[Y]=new Proxy(W[Y],new XF(new Proxy(T,this)))}),J}let F=T[_];if(R(F,GT))return new Proxy(F,new XF(new Proxy(T,this)));return F}}function U1(T,_){return new Proxy(T,new YW(_,!1))}function m_(T,_){return new Proxy(T,new XF(new Proxy(T.table,new YW(_,!1))))}function p2(T,_){return new k.Aliased($W(T.sql,_),T.fieldAlias)}function $W(T,_){return U.join(T.queryChunks.map((F)=>{if(R(F,GT))return m_(F,_);if(R(F,k))return $W(F,_);if(R(F,k.Aliased))return p2(F,_);return F}))}class M1 extends Error{static[H]="DrizzleError";constructor({message:T,cause:_}){super(T);this.name="DrizzleError",this.cause=_}}class g2 extends M1{static[H]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class o${static[H]="ConsoleLogWriter";write(T){console.log(T)}}class m2{static[H]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new o$}logQuery(T,_){let F=_.map((J)=>{try{return JSON.stringify(J)}catch{return String(J)}}),W=F.length?` -- params: [${F.join(", ")}]`:"";this.writer.write(`Query: ${T}${W}`)}}class o2{static[H]="NoopLogger";logQuery(){}}class aT{static[H]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((_)=>{return T?.(),_},(_)=>{throw T?.(),_})}then(T,_){return this.execute().then(T,_)}}function u$(T,_,F){let W={},J=T.reduce((Y,{path:$,field:Z},G)=>{let X;if(R(Z,GT))X=Z;else if(R(Z,k))X=Z.decoder;else X=Z.sql.decoder;let O=Y;for(let[M,Q]of $.entries())if(M<$.length-1){if(!(Q in O))O[Q]={};O=O[Q]}else{let K=_[G],B=O[Q]=K===null?null:X.mapFromDriverValue(K);if(F&&R(Z,GT)&&$.length===2){let V=$[0];if(!(V in W))W[V]=B===null?xT(Z.table):!1;else if(typeof W[V]==="string"&&W[V]!==xT(Z.table))W[V]=!1}}return Y},{});if(F&&Object.keys(W).length>0){for(let[Y,$]of Object.entries(W))if(typeof $==="string"&&!F[$])J[Y]=null}return J}function L_(T,_){return Object.entries(T).reduce((F,[W,J])=>{if(typeof W!=="string")return F;let Y=_?[..._,W]:[W];if(R(J,GT)||R(J,k)||R(J,k.Aliased))F.push({path:Y,field:J});else if(R(J,I))F.push(...L_(J[I.Symbol.Columns],Y));else F.push(...L_(J,Y));return F},[])}function ZW(T,_){let F=Object.keys(T),W=Object.keys(_);if(F.length!==W.length)return!1;for(let[J,Y]of F.entries())if(Y!==W[J])return!1;return!0}function w1(T,_){let F=Object.entries(_).filter(([,W])=>W!==void 0).map(([W,J])=>{if(R(J,k)||R(J,GT))return[W,J];else return[W,new Q_(J,T[I.Symbol.Columns][W])]});if(F.length===0)throw new Error("No values to set");return Object.fromEntries(F)}function c$(T,_){for(let F of _)for(let W of Object.getOwnPropertyNames(F.prototype)){if(W==="constructor")continue;Object.defineProperty(T.prototype,W,Object.getOwnPropertyDescriptor(F.prototype,W)||Object.create(null))}}function d$(T){return T[I.Symbol.Columns]}function a_(T){return R(T,IT)?T._.alias:R(T,Z_)?T[MT].name:R(T,k)?void 0:T[I.Symbol.IsAlias]?T[I.Symbol.Name]:T[I.Symbol.BaseName]}function a(T,_){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:_}}function l$(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let _=typeof T.logger;if(_!=="boolean"&&(_!=="object"||typeof T.logger.logQuery!=="function")&&_!=="undefined")return!1;return!0}if("schema"in T){let _=typeof T.schema;if(_!=="object"&&_!=="undefined")return!1;return!0}if("casing"in T){let _=typeof T.casing;if(_!=="string"&&_!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let _=typeof T.connection;if(_!=="string"&&_!=="object"&&_!=="undefined")return!1;return!0}if("client"in T){let _=typeof T.client;if(_!=="object"&&_!=="function"&&_!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class E0 extends f{static[H]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:_,...F}=T;this.config.generatedIdentity={type:"always",sequenceName:_,sequenceOptions:F}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:_,...F}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:_,sequenceOptions:F}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class t$ extends E0{static[H]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new i$(T,this.config)}}class i$ extends S{static[H]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class n$ extends E0{static[H]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new r$(T,this.config)}}class r$ extends S{static[H]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function s$(T,_){let{name:F,config:W}=a(T,_);if(W.mode==="number")return new t$(F);return new n$(F)}class a$ extends f{static[H]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new e$(T,this.config)}}class e$ extends S{static[H]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class TZ extends f{static[H]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new _Z(T,this.config)}}class _Z extends S{static[H]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function FZ(T,_){let{name:F,config:W}=a(T,_);if(W.mode==="number")return new a$(F);return new TZ(F)}class WZ extends f{static[H]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new JZ(T,this.config)}}class JZ extends S{static[H]="PgBoolean";getSQLType(){return"boolean"}}function XW(T){return new WZ(T??"")}class YZ extends f{static[H]="PgCharBuilder";constructor(T,_){super(T,"string","PgChar");this.config.length=_.length,this.config.enumValues=_.enum}build(T){return new $Z(T,this.config)}}class $Z extends S{static[H]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function ZZ(T,_={}){let{name:F,config:W}=a(T,_);return new YZ(F,W)}class XZ extends f{static[H]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new GZ(T,this.config)}}class GZ extends S{static[H]="PgCidr";getSQLType(){return"cidr"}}function AZ(T){return new XZ(T??"")}class HZ extends f{static[H]="PgCustomColumnBuilder";constructor(T,_,F){super(T,"custom","PgCustomColumn");this.config.fieldConfig=_,this.config.customTypeParams=F}build(T){return new OZ(T,this.config)}}class OZ extends S{static[H]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,_){super(T,_);this.sqlName=_.customTypeParams.dataType(_.fieldConfig),this.mapTo=_.customTypeParams.toDriver,this.mapFrom=_.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function UZ(T){return(_,F)=>{let{name:W,config:J}=a(_,F);return new HZ(W,J,T)}}class e_ extends f{static[H]="PgDateColumnBaseBuilder";defaultNow(){return this.default(U`now()`)}}class MZ extends e_{static[H]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new Q1(T,this.config)}}class Q1 extends S{static[H]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class wZ extends e_{static[H]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new R1(T,this.config)}}class R1 extends S{static[H]="PgDateString";getSQLType(){return"date"}}function QZ(T,_){let{name:F,config:W}=a(T,_);if(W?.mode==="date")return new MZ(F);return new wZ(F)}class RZ extends f{static[H]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new EZ(T,this.config)}}class EZ extends S{static[H]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function zZ(T){return new RZ(T??"")}class VZ extends f{static[H]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new KZ(T,this.config)}}class KZ extends S{static[H]="PgInet";getSQLType(){return"inet"}}function LZ(T){return new VZ(T??"")}class DZ extends E0{static[H]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new SZ(T,this.config)}}class SZ extends S{static[H]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function GW(T){return new DZ(T??"")}class IZ extends f{static[H]="PgIntervalBuilder";constructor(T,_){super(T,"string","PgInterval");this.config.intervalConfig=_}build(T){return new NZ(T,this.config)}}class NZ extends S{static[H]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",_=this.precision?`(${this.precision})`:"";return`interval${T}${_}`}}function CZ(T,_={}){let{name:F,config:W}=a(T,_);return new IZ(F,W)}class BZ extends f{static[H]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new E1(T,this.config)}}class E1 extends S{static[H]="PgJson";constructor(T,_){super(T,_)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function kZ(T){return new BZ(T??"")}class fZ extends f{static[H]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new z1(T,this.config)}}class z1 extends S{static[H]="PgJsonb";constructor(T,_){super(T,_)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function PZ(T){return new fZ(T??"")}class qZ extends f{static[H]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new jZ(T,this.config)}}class jZ extends S{static[H]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[_,F,W]=T.slice(1,-1).split(",");return[Number.parseFloat(_),Number.parseFloat(F),Number.parseFloat(W)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class yZ extends f{static[H]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new vZ(T,this.config)}}class vZ extends S{static[H]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[_,F,W]=T.slice(1,-1).split(",");return{a:Number.parseFloat(_),b:Number.parseFloat(F),c:Number.parseFloat(W)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function xZ(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new qZ(F);return new yZ(F)}class bZ extends f{static[H]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new hZ(T,this.config)}}class hZ extends S{static[H]="PgMacaddr";getSQLType(){return"macaddr"}}function pZ(T){return new bZ(T??"")}class gZ extends f{static[H]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new mZ(T,this.config)}}class mZ extends S{static[H]="PgMacaddr8";getSQLType(){return"macaddr8"}}function oZ(T){return new gZ(T??"")}class uZ extends f{static[H]="PgNumericBuilder";constructor(T,_,F){super(T,"string","PgNumeric");this.config.precision=_,this.config.scale=F}build(T){return new V1(T,this.config)}}class V1 extends S{static[H]="PgNumeric";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue(T){if(typeof T==="string")return T;return String(T)}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class cZ extends f{static[H]="PgNumericNumberBuilder";constructor(T,_,F){super(T,"number","PgNumericNumber");this.config.precision=_,this.config.scale=F}build(T){return new dZ(T,this.config)}}class dZ extends S{static[H]="PgNumericNumber";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class lZ extends f{static[H]="PgNumericBigIntBuilder";constructor(T,_,F){super(T,"bigint","PgNumericBigInt");this.config.precision=_,this.config.scale=F}build(T){return new tZ(T,this.config)}}class tZ extends S{static[H]="PgNumericBigInt";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function iZ(T,_){let{name:F,config:W}=a(T,_),J=W?.mode;return J==="number"?new cZ(F,W?.precision,W?.scale):J==="bigint"?new lZ(F,W?.precision,W?.scale):new uZ(F,W?.precision,W?.scale)}class nZ extends f{static[H]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new rZ(T,this.config)}}class rZ extends S{static[H]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[_,F]=T.slice(1,-1).split(",");return[Number.parseFloat(_),Number.parseFloat(F)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class sZ extends f{static[H]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new aZ(T,this.config)}}class aZ extends S{static[H]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[_,F]=T.slice(1,-1).split(",");return{x:Number.parseFloat(_),y:Number.parseFloat(F)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function eZ(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new nZ(F);return new sZ(F)}function $3(T){let _=[];for(let F=0;F<T.length;F+=2)_.push(Number.parseInt(T.slice(F,F+2),16));return new Uint8Array(_)}function TX(T,_){let F=new ArrayBuffer(8),W=new DataView(F);for(let J=0;J<8;J++)W.setUint8(J,T[_+J]);return W.getFloat64(0,!0)}function u2(T){let _=$3(T),F=0,W=_[F];F+=1;let J=new DataView(_.buffer),Y=J.getUint32(F,W===1);F+=4;let $;if(Y&536870912)$=J.getUint32(F,W===1),F+=4;if((Y&65535)===1){let Z=TX(_,F);F+=8;let G=TX(_,F);return F+=8,[Z,G]}throw new Error("Unsupported geometry type")}class _X extends f{static[H]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new FX(T,this.config)}}class FX extends S{static[H]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return u2(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class WX extends f{static[H]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new JX(T,this.config)}}class JX extends S{static[H]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let _=u2(T);return{x:_[0],y:_[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function YX(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new _X(F);return new WX(F)}class $X extends f{static[H]="PgRealBuilder";constructor(T,_){super(T,"number","PgReal");this.config.length=_}build(T){return new ZX(T,this.config)}}class ZX extends S{static[H]="PgReal";constructor(T,_){super(T,_)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function XX(T){return new $X(T??"")}class GX extends f{static[H]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new AX(T,this.config)}}class AX extends S{static[H]="PgSerial";getSQLType(){return"serial"}}function HX(T){return new GX(T??"")}class OX extends E0{static[H]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new UX(T,this.config)}}class UX extends S{static[H]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function MX(T){return new OX(T??"")}class wX extends f{static[H]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new QX(T,this.config)}}class QX extends S{static[H]="PgSmallSerial";getSQLType(){return"smallserial"}}function RX(T){return new wX(T??"")}class EX extends f{static[H]="PgTextBuilder";constructor(T,_){super(T,"string","PgText");this.config.enumValues=_.enum}build(T){return new zX(T,this.config)}}class zX extends S{static[H]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function VX(T,_={}){let{name:F,config:W}=a(T,_);return new EX(F,W)}class KX extends e_{constructor(T,_,F){super(T,"string","PgTime");this.withTimezone=_,this.precision=F,this.config.withTimezone=_,this.config.precision=F}static[H]="PgTimeBuilder";build(T){return new K1(T,this.config)}}class K1 extends S{static[H]="PgTime";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function LX(T,_={}){let{name:F,config:W}=a(T,_);return new KX(F,W.withTimezone??!1,W.precision)}class DX extends e_{static[H]="PgTimestampBuilder";constructor(T,_,F){super(T,"date","PgTimestamp");this.config.withTimezone=_,this.config.precision=F}build(T){return new L1(T,this.config)}}class L1 extends S{static[H]="PgTimestamp";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class SX extends e_{static[H]="PgTimestampStringBuilder";constructor(T,_,F){super(T,"string","PgTimestampString");this.config.withTimezone=_,this.config.precision=F}build(T){return new D1(T,this.config)}}class D1 extends S{static[H]="PgTimestampString";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function IX(T,_={}){let{name:F,config:W}=a(T,_);if(W?.mode==="string")return new SX(F,W.withTimezone??!1,W.precision);return new DX(F,W?.withTimezone??!1,W?.precision)}class NX extends f{static[H]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(U`gen_random_uuid()`)}build(T){return new S1(T,this.config)}}class S1 extends S{static[H]="PgUUID";getSQLType(){return"uuid"}}function D_(T){return new NX(T??"")}class CX extends f{static[H]="PgVarcharBuilder";constructor(T,_){super(T,"string","PgVarchar");this.config.length=_.length,this.config.enumValues=_.enum}build(T){return new BX(T,this.config)}}class BX extends S{static[H]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function dT(T,_={}){let{name:F,config:W}=a(T,_);return new CX(F,W)}class kX extends f{static[H]="PgBinaryVectorBuilder";constructor(T,_){super(T,"string","PgBinaryVector");this.config.dimensions=_.dimensions}build(T){return new fX(T,this.config)}}class fX extends S{static[H]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function PX(T,_){let{name:F,config:W}=a(T,_);return new kX(F,W)}class qX extends f{static[H]="PgHalfVectorBuilder";constructor(T,_){super(T,"array","PgHalfVector");this.config.dimensions=_.dimensions}build(T){return new jX(T,this.config)}}class jX extends S{static[H]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((_)=>Number.parseFloat(_))}}function yX(T,_){let{name:F,config:W}=a(T,_);return new qX(F,W)}class vX extends f{static[H]="PgSparseVectorBuilder";constructor(T,_){super(T,"string","PgSparseVector");this.config.dimensions=_.dimensions}build(T){return new xX(T,this.config)}}class xX extends S{static[H]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function bX(T,_){let{name:F,config:W}=a(T,_);return new vX(F,W)}class hX extends f{static[H]="PgVectorBuilder";constructor(T,_){super(T,"array","PgVector");this.config.dimensions=_.dimensions}build(T){return new pX(T,this.config)}}class pX extends S{static[H]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((_)=>Number.parseFloat(_))}}function gX(T,_){let{name:F,config:W}=a(T,_);return new hX(F,W)}function mX(){return{bigint:s$,bigserial:FZ,boolean:XW,char:ZZ,cidr:AZ,customType:UZ,date:QZ,doublePrecision:zZ,inet:LZ,integer:GW,interval:CZ,json:kZ,jsonb:PZ,line:xZ,macaddr:pZ,macaddr8:oZ,numeric:iZ,point:eZ,geometry:YX,real:XX,serial:HX,smallint:MX,smallserial:RX,text:VX,time:LX,timestamp:IX,uuid:D_,varchar:dT,bit:PX,halfvec:yX,sparsevec:bX,vector:gX}}var c2=Symbol.for("drizzle:PgInlineForeignKeys"),oX=Symbol.for("drizzle:EnableRLS");class vT extends I{static[H]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:c2,EnableRLS:oX});[c2]=[];[oX]=!1;[I.Symbol.ExtraConfigBuilder]=void 0;[I.Symbol.ExtraConfigColumns]={}}function Z3(T,_,F,W,J=T){let Y=new vT(T,W,J),$=typeof _==="function"?_(mX()):_,Z=Object.fromEntries(Object.entries($).map(([O,M])=>{let Q=M;Q.setName(O);let K=Q.build(Y);return Y[c2].push(...Q.buildForeignKeys(K,Y)),[O,K]})),G=Object.fromEntries(Object.entries($).map(([O,M])=>{let Q=M;Q.setName(O);let K=Q.buildExtraConfigColumn(Y);return[O,K]})),X=Object.assign(Y,Z);if(X[I.Symbol.Columns]=Z,X[I.Symbol.ExtraConfigColumns]=G,F)X[vT.Symbol.ExtraConfigBuilder]=F;return Object.assign(X,{enableRLS:()=>{return X[vT.Symbol.EnableRLS]=!0,X}})}var z0=(T,_,F)=>{return Z3(T,_,F,void 0)};function uX(...T){if(T[0].columns)return new AW(T[0].columns,T[0].name);return new AW(T)}class AW{static[H]="PgPrimaryKeyBuilder";columns;name;constructor(T,_){this.columns=T,this.name=_}build(T){return new cX(T,this.columns,this.name)}}class cX{constructor(T,_,F){this.table=T,this.columns=_,this.name=F}static[H]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[vT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}function X_(T,_){if(p$(_)&&!b2(T)&&!R(T,Q_)&&!R(T,R0)&&!R(T,GT)&&!R(T,I)&&!R(T,Z_))return new Q_(T,_);return T}var I1=(T,_)=>{return U`${T} = ${X_(_,T)}`},dX=(T,_)=>{return U`${T} <> ${X_(_,T)}`};function HW(...T){let _=T.filter((F)=>F!==void 0);if(_.length===0)return;if(_.length===1)return new k(_);return new k([new yT("("),U.join(_,new yT(" and ")),new yT(")")])}function lX(...T){let _=T.filter((F)=>F!==void 0);if(_.length===0)return;if(_.length===1)return new k(_);return new k([new yT("("),U.join(_,new yT(" or ")),new yT(")")])}function tX(T){return U`not ${T}`}var iX=(T,_)=>{return U`${T} > ${X_(_,T)}`},nX=(T,_)=>{return U`${T} >= ${X_(_,T)}`},rX=(T,_)=>{return U`${T} < ${X_(_,T)}`},sX=(T,_)=>{return U`${T} <= ${X_(_,T)}`};function aX(T,_){if(Array.isArray(_)){if(_.length===0)return U`false`;return U`${T} in ${_.map((F)=>X_(F,T))}`}return U`${T} in ${X_(_,T)}`}function eX(T,_){if(Array.isArray(_)){if(_.length===0)return U`true`;return U`${T} not in ${_.map((F)=>X_(F,T))}`}return U`${T} not in ${X_(_,T)}`}function T5(T){return U`${T} is null`}function _5(T){return U`${T} is not null`}function F5(T){return U`exists ${T}`}function W5(T){return U`not exists ${T}`}function J5(T,_,F){return U`${T} between ${X_(_,T)} and ${X_(F,T)}`}function Y5(T,_,F){return U`${T} not between ${X_(_,T)} and ${X_(F,T)}`}function $5(T,_){return U`${T} like ${_}`}function Z5(T,_){return U`${T} not like ${_}`}function X5(T,_){return U`${T} ilike ${_}`}function G5(T,_){return U`${T} not ilike ${_}`}function A5(T){return U`${T} asc`}function H5(T){return U`${T} desc`}class d2{constructor(T,_,F){this.sourceTable=T,this.referencedTable=_,this.relationName=F,this.referencedTableName=_[I.Symbol.Name]}static[H]="Relation";referencedTableName;fieldName}class O5{constructor(T,_){this.table=T,this.config=_}static[H]="Relations"}class V0 extends d2{constructor(T,_,F,W){super(T,_,F?.relationName);this.config=F,this.isNullable=W}static[H]="One";withFieldName(T){let _=new V0(this.sourceTable,this.referencedTable,this.config,this.isNullable);return _.fieldName=T,_}}class OW extends d2{constructor(T,_,F){super(T,_,F?.relationName);this.config=F}static[H]="Many";withFieldName(T){let _=new OW(this.sourceTable,this.referencedTable,this.config);return _.fieldName=T,_}}function U5(){return{and:HW,between:J5,eq:I1,exists:F5,gt:iX,gte:nX,ilike:X5,inArray:aX,isNull:T5,isNotNull:_5,like:$5,lt:rX,lte:sX,ne:dX,not:tX,notBetween:Y5,notExists:W5,notLike:Z5,notIlike:G5,notInArray:eX,or:lX,sql:U}}function M5(){return{sql:U,asc:A5,desc:H5}}function w5(T,_){if(Object.keys(T).length===1&&"default"in T&&!R(T.default,I))T=T.default;let F={},W={},J={};for(let[Y,$]of Object.entries(T))if(R($,I)){let Z=f0($),G=W[Z];F[Z]=Y,J[Y]={tsName:Y,dbName:$[I.Symbol.Name],schema:$[I.Symbol.Schema],columns:$[I.Symbol.Columns],relations:G?.relations??{},primaryKey:G?.primaryKey??[]};for(let O of Object.values($[I.Symbol.Columns]))if(O.primary)J[Y].primaryKey.push(O);let X=$[I.Symbol.ExtraConfigBuilder]?.($[I.Symbol.ExtraConfigColumns]);if(X){for(let O of Object.values(X))if(R(O,AW))J[Y].primaryKey.push(...O.columns)}}else if(R($,O5)){let Z=f0($.table),G=F[Z],X=$.config(_($.table)),O;for(let[M,Q]of Object.entries(X))if(G){let K=J[G];if(K.relations[M]=Q,O)K.primaryKey.push(...O)}else{if(!(Z in W))W[Z]={relations:{},primaryKey:O};W[Z].relations[M]=Q}}return{tables:J,tableNamesMap:F}}function X3(T){return function _(F,W){return new V0(T,F,W,W?.fields.reduce((J,Y)=>J&&Y.notNull,!0)??!1)}}function G3(T){return function _(F,W){return new OW(T,F,W)}}function Q5(T,_,F){if(R(F,V0)&&F.config)return{fields:F.config.fields,references:F.config.references};let W=_[f0(F.referencedTable)];if(!W)throw new Error(`Table "${F.referencedTable[I.Symbol.Name]}" not found in schema`);let J=T[W];if(!J)throw new Error(`Table "${W}" not found in schema`);let Y=F.sourceTable,$=_[f0(Y)];if(!$)throw new Error(`Table "${Y[I.Symbol.Name]}" not found in schema`);let Z=[];for(let G of Object.values(J.relations))if(F.relationName&&F!==G&&G.relationName===F.relationName||!F.relationName&&G.referencedTable===F.sourceTable)Z.push(G);if(Z.length>1)throw F.relationName?new Error(`There are multiple relations with name "${F.relationName}" in table "${W}"`):new Error(`There are multiple relations between "${W}" and "${F.sourceTable[I.Symbol.Name]}". Please specify relation name`);if(Z[0]&&R(Z[0],V0)&&Z[0].config)return{fields:Z[0].config.references,references:Z[0].config.fields};throw new Error(`There is not enough information to infer relation "${$}.${F.fieldName}"`)}function R5(T){return{one:X3(T),many:G3(T)}}function N1(T,_,F,W,J=(Y)=>Y){let Y={};for(let[$,Z]of W.entries())if(Z.isJson){let G=_.relations[Z.tsKey],X=F[$],O=typeof X==="string"?JSON.parse(X):X;Y[Z.tsKey]=R(G,V0)?O&&N1(T,T[Z.relationTableTsKey],O,Z.selection,J):O.map((M)=>N1(T,T[Z.relationTableTsKey],M,Z.selection,J))}else{let G=J(F[$]),X=Z.field,O;if(R(X,GT))O=X;else if(R(X,k))O=X.decoder;else O=X.sql.decoder;Y[Z.tsKey]=G===null?null:O.mapFromDriverValue(G)}return Y}import j3 from"os";import y3 from"fs";var C1=new Map,l2=new Map,t2=Symbol("OriginError"),GF={};class S_ extends Promise{constructor(T,_,F,W,J={}){let Y,$;super((Z,G)=>{Y=Z,$=G});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=_,this.handler=F,this.canceller=W,this.options=J,this.state=null,this.statement=null,this.resolve=(Z)=>(this.active=!1,Y(Z)),this.reject=(Z)=>(this.active=!1,$(Z)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[t2]=this.handler.debug?new Error:this.tagged&&A3(this.strings)}get origin(){return(this.handler.debug?this[t2].stack:this.tagged&&l2.has(this.strings)?l2.get(this.strings):l2.set(this.strings,this[t2].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,_){if(this.options.simple=!1,typeof T==="function")_=T,T=1;if(this.cursorRows=T,typeof _==="function")return this.cursorFn=_,this;let F;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};F&&F();let W=new Promise((J,Y)=>{this.cursorFn=($)=>{return J({value:$,done:!1}),new Promise((Z)=>F=Z)},this.resolve=()=>(this.active=!1,J({done:!0})),this.reject=($)=>(this.active=!1,Y($))});return this.execute(),W},return(){return F&&F(GF),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function A3(T){if(C1.has(T))return C1.get(T);let _=Error.stackTraceLimit;return Error.stackTraceLimit=4,C1.set(T,new Error),Error.stackTraceLimit=_,C1.get(T)}class AF extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var BT={connection:E5,postgres:z5,generic:V5,notSupported:K5};function E5(T,_,F){let{host:W,port:J}=F||_,Y=Object.assign(new Error("write "+T+" "+(_.path||W+":"+J)),{code:T,errno:T,address:_.path||W},_.path?{}:{port:J});return Error.captureStackTrace(Y,E5),Y}function z5(T){let _=new AF(T);return Error.captureStackTrace(_,z5),_}function V5(T,_){let F=Object.assign(new Error(T+": "+_),{code:T});return Error.captureStackTrace(F,V5),F}function K5(T){let _=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(_,K5),_}var H3={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class f1{then(){i2()}catch(){i2()}finally(){i2()}}class QW extends f1{constructor(T){super();this.value=j1(T)}}class o_ extends f1{constructor(T,_,F){super();this.value=T,this.type=_,this.array=F}}class P1 extends f1{constructor(T,_){super();this.first=T,this.rest=_}build(T,_,F,W){let J=O3.map(([Y,$])=>({fn:$,i:T.search(Y)})).sort((Y,$)=>Y.i-$.i).pop();return J.i===-1?e2(this.first,W):J.fn(this.first,this.rest,_,F,W)}}function q1(T,_,F,W){let J=T instanceof o_?T.value:T;if(J===void 0){if(T instanceof o_?T.value=W.transform.undefined:J=T=W.transform.undefined,J===void 0)throw BT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+F.push(T instanceof o_?(_.push(T.value),T.array?T.array[T.type||k1(T.value)]||T.type||I5(T.value):T.type):(_.push(T),k1(T)))}var D5=C5(H3);function s2(T,_,F,W,J,Y){for(let $=1;$<T.strings.length;$++)_+=a2(_,F,W,J,Y)+T.strings[$],F=T.args[$];return _}function a2(T,_,F,W,J){return _ instanceof P1?_.build(T,F,W,J):_ instanceof S_?r2(_,F,W,J):_ instanceof QW?_.value:_&&_[0]instanceof S_?_.reduce((Y,$)=>Y+" "+r2($,F,W,J),""):q1(_,F,W,J)}function r2(T,_,F,W){return T.fragment=!0,s2(T,T.strings[0],T.args[0],_,F,W)}function S5(T,_,F,W,J){return T.map((Y)=>"("+W.map(($)=>a2("values",Y[$],_,F,J)).join(",")+")").join(",")}function L5(T,_,F,W,J){let Y=Array.isArray(T[0]),$=_.length?_.flat():Object.keys(Y?T[0]:T);return S5(Y?T:[T],F,W,$,J)}function B1(T,_,F,W,J){if(typeof T==="string"&&(T=[T].concat(_)),Array.isArray(T))return e2(T,J);let Y;return(_.length?_.flat():Object.keys(T)).map((Z)=>{return Y=T[Z],(Y instanceof S_?r2(Y,F,W,J):Y instanceof QW?Y.value:q1(Y,F,W,J))+" as "+j1(J.transform.column.to?J.transform.column.to(Z):Z)}).join(",")}var O3=Object.entries({values:L5,in:(...T)=>{let _=L5(...T);return _==="()"?"(null)":_},select:B1,as:B1,returning:B1,"\\(":B1,update(T,_,F,W,J){return(_.length?_.flat():Object.keys(T)).map((Y)=>j1(J.transform.column.to?J.transform.column.to(Y):Y)+"="+a2("values",T[Y],F,W,J))},insert(T,_,F,W,J){let Y=_.length?_.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+e2(Y,J)+")values"+S5(Array.isArray(T)?T:[T],F,W,Y,J)}}).map(([T,_])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),_]);function i2(){throw BT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:U3,parsers:M3}=D5;function I5(T){if(Array.isArray(T))return I5(T[0]);return typeof T==="string"?1009:0}var N5=function(T){let _=C5(T||{});return{serializers:Object.assign({},U3,_.serializers),parsers:Object.assign({},M3,_.parsers)}};function C5(T){return Object.keys(T).reduce((_,F)=>{if(T[F].from&&[].concat(T[F].from).forEach((W)=>_.parsers[W]=T[F].parse),T[F].serialize)_.serializers[T[F].to]=T[F].serialize,T[F].from&&[].concat(T[F].from).forEach((W)=>_.serializers[W]=T[F].serialize);return _},{parsers:{},serializers:{}})}function e2(T,{transform:{column:_}}){return T.map((F)=>j1(_.to?_.to(F):F)).join(",")}var j1=function T(_){return'"'+_.replace(/"/g,'""').replace(/\./g,'"."')+'"'},k1=function T(_){return _ instanceof o_?_.type:_ instanceof Date?1184:_ instanceof Uint8Array?17:_===!0||_===!1?16:typeof _==="bigint"?20:Array.isArray(_)?T(_[0]):0},w3=/\\/g,Q3=/"/g;function R3(T){return T.replace(w3,"\\\\").replace(Q3,"\\\"")}var B5=function T(_,F,W,J){if(Array.isArray(_)===!1)return _;if(!_.length)return"{}";let Y=_[0],$=J===1020?";":",";if(Array.isArray(Y)&&!Y.type)return"{"+_.map((Z)=>T(Z,F,W,J)).join($)+"}";return"{"+_.map((Z)=>{if(Z===void 0){if(Z=W.transform.undefined,Z===void 0)throw BT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return Z===null?"null":'"'+R3(F?F(Z.type?Z.value:Z):""+Z)+'"'}).join($)+"}"},n2={i:0,char:null,str:"",quoted:!1,last:0},k5=function T(_,F,W){return n2.i=n2.last=0,f5(n2,_,F,W)};function f5(T,_,F,W){let J=[],Y=W===1020?";":",";for(;T.i<_.length;T.i++){if(T.char=_[T.i],T.quoted)if(T.char==="\\")T.str+=_[++T.i];else if(T.char==='"')J.push(F?F(T.str):T.str),T.str="",T.quoted=_[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,J.push(f5(T,_,F,W));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&J.push(F?F(_.slice(T.last,T.i)):_.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===Y&&T.p!=="}"&&T.p!=='"')J.push(F?F(_.slice(T.last,T.i)):_.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&J.push(F?F(_.slice(T.last,T.i+1)):_.slice(T.last,T.i+1)),J}var P0=(T)=>{let _=T[0];for(let F=1;F<T.length;F++)_+=T[F]==="_"?T[++F].toUpperCase():T[F];return _},q0=(T)=>{let _=T[0].toUpperCase();for(let F=1;F<T.length;F++)_+=T[F]==="_"?T[++F].toUpperCase():T[F];return _},j0=(T)=>T.replace(/_/g,"-"),UW=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),MW=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),wW=(T)=>T.replace(/-/g,"_");function T8(T){return function _(F,W){return typeof F==="object"&&F!==null&&(W.type===114||W.type===3802)?Array.isArray(F)?F.map((J)=>_(J,W)):Object.entries(F).reduce((J,[Y,$])=>Object.assign(J,{[T(Y)]:_($,W)}),{}):F}}P0.column={from:P0};P0.value={from:T8(P0)};UW.column={to:UW};var _8={...P0};_8.column.to=UW;q0.column={from:q0};q0.value={from:T8(q0)};MW.column={to:MW};var F8={...q0};F8.column.to=MW;j0.column={from:j0};j0.value={from:T8(j0)};wW.column={to:wW};var W8={...j0};W8.column.to=wW;import P5 from"net";import K3 from"tls";import RW from"crypto";import J8 from"stream";import{performance as q5}from"perf_hooks";class y0 extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var R_=E3;function E3(T=[]){let _=T.slice(),F=0;return{get length(){return _.length-F},remove:(W)=>{let J=_.indexOf(W);return J===-1?null:(_.splice(J,1),W)},push:(W)=>(_.push(W),W),shift:()=>{let W=_[F++];if(F===_.length)F=0,_=[];else _[F-1]=void 0;return W}}}var lT=Buffer.allocUnsafe(256),z3="BCcDdEFfHPpQSX".split("").reduce((T,_)=>{let F=_.charCodeAt(0);return T[_]=()=>{return lT[0]=F,$T.i=5,$T},T},{}),$T=Object.assign(V3,z3,{N:String.fromCharCode(0),i:0,inc(T){return $T.i+=T,$T},str(T){let _=Buffer.byteLength(T);return y1(_),$T.i+=lT.write(T,$T.i,_,"utf8"),$T},i16(T){return y1(2),lT.writeUInt16BE(T,$T.i),$T.i+=2,$T},i32(T,_){if(_||_===0)return lT.writeUInt32BE(T,_),$T;return y1(4),lT.writeUInt32BE(T,$T.i),$T.i+=4,$T},z(T){return y1(T),lT.fill(0,$T.i,$T.i+T),$T.i+=T,$T},raw(T){return lT=Buffer.concat([lT.subarray(0,$T.i),T]),$T.i=lT.length,$T},end(T=1){lT.writeUInt32BE($T.i-T,T);let _=lT.subarray(0,$T.i);return $T.i=0,lT=Buffer.allocUnsafe(256),_}}),b=$T;function y1(T){if(lT.length-$T.i<T){let _=lT,F=_.length;lT=Buffer.allocUnsafe(F+(F>>1)+T),_.copy(lT)}}function V3(){return $T.i=0,$T}var Z8=v5,L3=1,K0=b().S().end(),j5=b().H().end(),D3=b().i32(8).i32(80877103).end(8),S3=Buffer.concat([b().E().str(b.N).i32(0).end(),K0]),I3=b().D().str("S").str(b.N).end(),HF=()=>{},N3=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),C3={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function v5(T,_={},{onopen:F=HF,onend:W=HF,onclose:J=HF}={}){let{ssl:Y,max:$,user:Z,host:G,port:X,database:O,parsers:M,transform:Q,onnotice:K,onnotify:B,onparameter:V,max_pipeline:v,keep_alive:q,backoff:j,target_session_attrs:y}=T,u=R_(),h=L3++,p={pid:null,secret:null},t=$8(i1,T.idle_timeout),ST=$8(i1,T.max_lifetime),A_=$8(JG,T.connect_timeout),D=null,ZT,i=new y0,TT=Buffer.alloc(0),bT=T.fetch_types,H_={},I_={},b0=Math.random().toString(36).slice(2),L=1,o=0,JT=0,zT=0,kT=0,n=0,YT=0,NT=0,VT=null,wT=null,gT=!1,HT=null,N_=null,hT=null,_0=null,fT=null,QT=null,C_=null,v_=null,C=null,wF=null,mT={queue:_.closed,idleTimer:t,connect(A){hT=A,y8()},terminate:RF,execute:QF,cancel:TG,end:i1,count:0,id:h};return _.closed&&_.closed.push(mT),mT;async function e5(){let A;try{A=T.socket?await Promise.resolve(T.socket(T)):new P5.Socket}catch(w){p0(w);return}return A.on("error",p0),A.on("close",v8),A.on("drain",q8),A}async function TG({pid:A,secret:w},g,_T){try{ZT=b().i32(16).i32(80877102).i32(A).i32(w).end(16),await j8(),D.once("error",_T),D.once("close",g)}catch(LT){_T(LT)}}function QF(A){if(gT)return IW(A,BT.connection("CONNECTION_DESTROYED",T));if(A.cancelled)return;try{return A.state=p,C?u.push(A):(C=A,C.active=!0),WG(A),pT(_G(A))&&!A.describeFirst&&!A.cursorFn&&u.length<v&&(!A.options.onexecute||A.options.onexecute(mT))}catch(w){return u.length===0&&pT(K0),x_(w),!0}}function _G(A){if(A.parameters.length>=65534)throw BT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return A.options.simple?b().Q().str(A.statement.string+b.N).end():A.describeFirst?Buffer.concat([k8(A),j5]):A.prepare?A.prepared?SW(A):Buffer.concat([k8(A),SW(A)]):FG(A)}function k8(A){return Buffer.concat([b8(A.statement.string,A.parameters,A.statement.types,A.statement.name),oG("S",A.statement.name)])}function SW(A){return Buffer.concat([mG(A.parameters,A.statement.types,A.statement.name,A.cursorName),A.cursorFn?h8("",A.cursorRows):S3])}function FG(A){return Buffer.concat([b8(A.statement.string,A.parameters,A.statement.types),I3,SW(A)])}function WG(A){let w=[],g=[],_T=s2(A,A.strings[0],A.args[0],w,g,T);!A.tagged&&A.args.forEach((LT)=>q1(LT,w,g,T)),A.prepare=T.prepare&&("prepare"in A.options?A.options.prepare:!0),A.string=_T,A.signature=A.prepare&&g+_T,A.onlyDescribe&&delete I_[A.signature],A.parameters=A.parameters||w,A.prepared=A.prepare&&A.signature in I_,A.describeFirst=A.onlyDescribe||w.length&&!A.prepared,A.statement=A.prepared?I_[A.signature]:{string:_T,types:g,name:A.prepare?b0+L++:""},typeof T.debug==="function"&&T.debug(h,_T,w,g)}function pT(A,w){if(QT=QT?Buffer.concat([QT,A]):Buffer.from(A),w||QT.length>=1024)return f8(w);return wT===null&&(wT=setImmediate(f8)),!0}function f8(A){let w=D.write(QT,A);return wT!==null&&clearImmediate(wT),QT=wT=null,w}function JG(){x_(BT.connection("CONNECT_TIMEOUT",T,D)),D.destroy()}async function P8(){if(pT(D3),!await new Promise((w)=>D.once("data",(g)=>w(g[0]===83)))&&Y==="prefer")return h0();D.removeAllListeners(),D=K3.connect({socket:D,servername:P5.isIP(D.host)?void 0:D.host,...Y==="require"||Y==="allow"||Y==="prefer"?{rejectUnauthorized:!1}:Y==="verify-full"?{}:typeof Y==="object"?Y:{}}),D.on("secureConnect",h0),D.on("error",p0),D.on("close",v8),D.on("drain",q8)}function q8(){!C&&F(mT)}function t1(A){if(HT){if(HT.push(A),JT-=A.length,JT>0)return}TT=HT?Buffer.concat(HT,n-JT):TT.length===0?A:Buffer.concat([TT,A],TT.length+A.length);while(TT.length>4){if(n=TT.readUInt32BE(1),n>=TT.length){JT=n-TT.length,HT=[TT];break}try{YG(TT.subarray(0,n+1))}catch(w){C&&(C.cursorFn||C.describeFirst)&&pT(K0),x_(w)}TT=TT.subarray(n+1),JT=0,HT=null}}async function j8(){if(gT=!1,H_={},D||(D=await e5()),!D)return;if(A_.start(),T.socket)return Y?P8():h0();if(D.on("connect",Y?P8:h0),T.path)return D.connect(T.path);D.ssl=Y,D.connect(X[zT],G[zT]),D.host=G[zT],D.port=X[zT],zT=(zT+1)%X.length}function y8(){setTimeout(j8,o?o+YT-q5.now():0)}function h0(){try{I_={},bT=T.fetch_types,b0=Math.random().toString(36).slice(2),L=1,ST.start(),D.on("data",t1),q&&D.setKeepAlive&&D.setKeepAlive(!0,1000*q);let A=cG();pT(A)}catch(A){p0(A)}}function p0(A){if(mT.queue===_.connecting&&T.host[kT+1])return;x_(A);while(u.length)IW(u.shift(),A)}function x_(A){fT&&(fT.destroy(A),fT=null),C&&IW(C,A),hT&&(IW(hT,A),hT=null)}function IW(A,w){if(A.reserve)return A.reject(w);if(!w||typeof w!=="object")w=new Error(w);"query"in w||"parameters"in w||Object.defineProperties(w,{stack:{value:w.stack+A.origin.replace(/.*\n/,`
|
|
50
|
-
`),enumerable:T.debug},query:{value:A.string,enumerable:T.debug},parameters:{value:A.parameters,enumerable:T.debug},args:{value:A.args,enumerable:T.debug},types:{value:A.statement&&A.statement.types,enumerable:T.debug}}),A.reject(w)}function i1(){return _0||(!mT.reserved&&W(mT),!mT.reserved&&!hT&&!C&&u.length===0?(RF(),new Promise((A)=>D&&D.readyState!=="closed"?D.once("close",A):A())):_0=new Promise((A)=>C_=A))}function RF(){if(gT=!0,fT||C||hT||u.length)p0(BT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(wT),D)D.removeListener("data",t1),D.removeListener("connect",h0),D.readyState==="open"&&D.end(b().X().end());C_&&(C_(),_0=C_=null)}async function v8(A){if(TT=Buffer.alloc(0),JT=0,HT=null,clearImmediate(wT),D.removeListener("data",t1),D.removeListener("connect",h0),t.cancel(),ST.cancel(),A_.cancel(),D.removeAllListeners(),D=null,hT)return y8();!A&&(C||u.length)&&p0(BT.connection("CONNECTION_CLOSED",T,D)),o=q5.now(),A&&T.shared.retries++,YT=(typeof j==="function"?j(T.shared.retries):j)*1000,J(mT,BT.connection("CONNECTION_CLOSED",T,D))}function YG(A,w=A[0]){(w===68?$G:w===100?jG:w===65?CG:w===83?ZG:w===90?XG:w===67?GG:w===50?x8:w===49?AG:w===116?HG:w===84?OG:w===82?UG:w===110?zG:w===75?
|
|
49
|
+
${$.trace}`:"No previous disposal trace was found."),W.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(W.key);case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(T.defaults.has(W.key))return T.defaults.get(F.family.key);let Z=$_(T,W).default(Y);return T.defaults.set(W.key,Z),Z}}}return U0(T,$_(T,F))}class O${parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new g_({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new g_({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new g_({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new g_({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new _1(100);molecules=new Map;moleculeJoins=new g_({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new g_({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new g_({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new FT,atomDisposal:new FT,selectorCreation:new FT,selectorDisposal:new FT,timelineCreation:new FT,transactionCreation:new FT,transactionApplying:new R2(null),operationClose:new FT,moleculeCreation:new FT,moleculeDisposal:new FT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Q2("warn",(T,_,F)=>!M$(F))];logger={error:(...T)=>{for(let _ of this.loggers)_.error(...T)},info:(...T)=>{for(let _ of this.loggers)_.info(...T)},warn:(...T)=>{for(let _ of this.loggers)_.warn(...T)}};constructor(T,_=null){if(this.config={..._?.config,...T},_!==null){if(this.valueMap=new Map(_?.valueMap),this.operation={..._?.operation},O0(_))this.transactionMeta={epoch:new Map(_?.transactionMeta.epoch),actionContinuities:new g_(_?.transactionMeta.actionContinuities.toJSON())};for(let[,W]of _.families){if(W.internalRoles?.includes("mutable")||W.internalRoles?.includes("join"))continue;W.install(this)}let F=new Set;for(let[,W]of _.atoms){if(F.has(W.key))continue;if(W.install(this),W.type==="mutable_atom"){let J=$F(_,W),Y=U$(W);F.add(J.key),F.add(Y.key)}}for(let[,W]of _.readonlySelectors)W.install(this);for(let[,W]of _.writableSelectors){if(F.has(W.key))continue;W.install(this)}for(let[,W]of _.transactions)W.install(this);for(let[,W]of _.timelines)W.install(this)}}}var tY={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new O$({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function $_(T,_){let F,W=T;while(W!==null){switch(_.type){case"atom":case"mutable_atom":F=W.atoms.get(_.key);break;case"writable_pure_selector":case"writable_held_selector":F=W.writableSelectors.get(_.key);break;case"readonly_pure_selector":case"readonly_held_selector":F=W.readonlySelectors.get(_.key);break;case"atom_family":case"mutable_atom_family":case"writable_pure_selector_family":case"readonly_pure_selector_family":case"writable_held_selector_family":case"readonly_held_selector_family":F=W.families.get(_.key);break;case"timeline":F=W.timelines.get(_.key);break;case"transaction":F=W.transactions.get(_.key);break}if(F)return F;W=W.child}throw new rF(_,T)}var w$=(T,_)=>{let F=m(T);if(F.operation.open)return F.operation.prev.get(_.key);return F.valueMap.get(_.key)};var D2=(T,_)=>{let F=m(T);return Z$(_,T).map((J)=>{let Y=F.atoms.get(J);if(Y===void 0)throw new Error(`Atom "${J}", a dependency of selector "${_.key}", not found in store "${T.config.name}".`);return Y.subject.subscribe(`${_.type}:${_.key}`,($)=>{T.logger.info("\uD83D\uDCE2",_.type,_.key,"root",J,"went",$.oldValue,"->",$.newValue);let Z=w$(F,_),G=U0(F,_);T.logger.info("\u2728",_.type,_.key,"went",Z,"->",G),_.subject.next({newValue:G,oldValue:Z})})})};function TW(T,_,F,W){function J(M){if(T.operation.open){let Q=T.on.operationClose.subscribe(`state subscription ${F}`,()=>{Q(),W(M)})}else W(M)}let Y=$_(T,_);T.logger.info("\uD83D\uDC40",Y.type,Y.key,`Adding subscription "${F}"`);let $=Y.type==="writable_pure_selector"||Y.type==="readonly_pure_selector",Z=null,G=J;if($)Z=D2(T,Y),G=(M)=>{if(Z)Z.length=0,Z.push(...D2(T,Y));J(M)};let X=Y.subject.subscribe(F,G);return()=>{if(T.logger.info("\uD83D\uDE48",Y.type,Y.key,`Removing subscription "${F}"`),X(),Z)for(let M of Z)M()}}var Q$=(T,_,F,W)=>{let J=$_(T,_);T.logger.info("\uD83D\uDC40","timeline",_.key,`Adding subscription "${F}"`);let Y=J.subject.subscribe(F,W);return()=>{T.logger.info("\uD83D\uDE48","timeline",_.key,`Removing subscription "${F}" from timeline`),Y()}};class S2{initializeState(T,_){let F=`*${T.key}`;_.atoms.delete(F),_.valueMap.delete(F);let W=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,J=I2(_,{key:F,default:null},W);if(_.parent?.valueMap.has(F)){let Y=_.parent.valueMap.get(F);_.valueMap.set(F,Y)}return J}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,_,F){let W=`tracker:${F.config.name}:${M_(F)?F.transactionMeta.update.key:"main"}:${T.key}`,J=eF(F,T);this.unsubscribeFromInnerValue=J.subscribe(W,(Y)=>{Q0(F,_,Y)}),this.unsubscribeFromState=TW(F,T,W,(Y)=>{if(Y.newValue!==Y.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=Y.newValue.subscribe(W,($)=>{Q0(F,_,$)})})}updateCore(T,_,F){let W=`tracker:${F.config.name}:${M_(F)?F.transactionMeta.update.key:"main"}:${T.key}`;TW(F,_,W,({newValue:J,oldValue:Y})=>{let $=F.timelineTopics.getRelatedKey(_.key);if($){if(F.timelines.get($)?.timeTraveling){let X=Q$(F,{key:$,type:"timeline"},W,(O)=>{X(),Q0(F,T,(M)=>{if(O==="redo"&&J)M.do(J);else if(O==="undo"&&Y)M.undo(Y);return M})});return}}let Z=F.on.operationClose.subscribe(W,()=>{Z();let G=eF(F,T),X=J===null?-1:G.getUpdateNumber(J),O=X-G.cacheUpdateNumber;if(J&&O===1)Q0(F,T,(M)=>(M.do(J),M));else F.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${G.cacheUpdateNumber+1}, but got ${X}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(T,_){this.mutableState=T;let F=m(_);this.latestUpdateState=this.initializeState(T,F),this.observeCore(T,this.latestUpdateState,F),this.updateCore(T,this.latestUpdateState,F),F.trackers.set(T.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),F.trackers.delete(T.key)}}}var $F=(T,_)=>{if(_.family){let W=m(T),Y={key:`${_.family.key}:JSON`,type:"writable_pure_selector_family"},$=$_(W,Y),Z=JSON.parse(_.family.subKey);return w_(T,$,Z)}return{type:"writable_pure_selector",key:`${_.key}:JSON`}};var U$=(T)=>{let F={type:"atom",key:`*${T.key}`};if(T.family)F.family={key:`*${T.family.key}`,subKey:T.family.subKey};return F};function W$(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function sF(T,_,F){let W=F.valueMap.get(_.key),J=T.valueMap.get(_.key);if(W!==J)return J;if(W===void 0)return _.default();F.logger.info("\uD83D\uDCC3","atom",_.key,"copying");let Y=_.toJson(W),$=_.fromJson(Y);return T.valueMap.set(_.key,$),new S2(_,F),$}function sT(T,_,F,W){let J=T.valueMap.get(_);if(J instanceof tF)J.use(F);if(F instanceof Promise){let Y=new tF(F);return T.valueMap.set(_,Y),Y.then(($)=>{sT(T,_,$,W),W.next({newValue:$,oldValue:Y})}).catch(($)=>{T.logger.error("\uD83D\uDCA5","state",_,"rejected:",$)}),Y}return T.valueMap.set(_,F),F}var rY=(T,_)=>{let F=_.valueMap.get(T.key);if(T.type==="mutable_atom"&&M_(_)){let{parent:W}=_;F=sF(_,T,W)}return F},_$=(T,_)=>{let F=_.valueMap.get(T);if(F instanceof tF){let W=F,J=_.writableSelectors.get(T)??_.readonlySelectors.get(T);if(J)W.use(J.get());return}if(_.operation.open)_.operation.prev.set(T,F);_.valueMap.delete(T),_.logger.info("\uD83D\uDDD1","state",T,"evicted")};var J$=(T,_)=>{return m(T).atomsThatAreDefault.has(_)},R$=(T,_)=>{let F=m(T);F.atomsThatAreDefault=new Set(F.atomsThatAreDefault).add(_)},Y$=(T,_)=>{let F=m(T);F.atomsThatAreDefault=new Set(m(T).atomsThatAreDefault),F.atomsThatAreDefault.delete(_)};function I2(T,_,F){let{key:J,default:Y}=_;T.logger.info("\uD83D\uDD28","atom",J,`creating in store "${T.config.name}"`);let $=m(T),Z=$.atoms.get(J);if(Z&&Z.type==="atom")return T.logger.error("\u274C","atom",J,"Tried to create atom, but it already exists in the store."),nF(Z);let G=new FT,X={..._,type:"atom",install:(Q)=>{return Q.logger.info("\uD83D\uDEE0\uFE0F","atom",J,`installing in store "${Q.config.name}"`),I2(Q,_,F)},subject:G};if(F)X.family=F;let O=Y;if(Y instanceof Function)O=Y();$.atoms.set(J,X),R$(T,J),sT($,J,O,G);let M=nF(X);if(_.effects){let Q=0,V=[];for(let B of _.effects){let K=B({setSelf:(v)=>{Q0(T,M,v)},onSet:(v)=>TW(T,M,`effect[${Q}]`,v)});if(K)V.push(K);++Q}X.cleanup=()=>{for(let B of V)B()}}return M}class ZF extends Set{mode="record";subject=new FT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,_=0){super(T);if(T instanceof ZF)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(_)this.cacheLimit=_,this.cache=new Array(_),this.subscribe("auto cache",(F)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=F})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let _=new ZF(T.members,T.cacheLimit);return _.cache=T.cache,_.cacheIdx=T.cacheIdx,_.cacheUpdateNumber=T.cacheUpdateNumber,_}add(T){let _=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${rT(T)}`);return _}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let _=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${rT(T)}`);return _}parent=null;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new ZF(this);let _=this.child._subscribe("transaction",(F)=>{this.transactionUpdates?.push(F)});try{if(T(this.child)){for(let W of this.transactionUpdates)this.doStep(W);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(F){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",F),F}finally{_(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,_){return this.subject.subscribe(T,_)}subscribe(T,_){return this.subject.subscribe(T,(F)=>{_(`${this.cacheUpdateNumber}=${F}`)})}emit(T){this.subject.next(T)}doStep(T){let _=T.indexOf(":"),F=T.substring(0,_),W=T.substring(_+1);switch(F){case"add":this.add(JSON.parse(W));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(W));break;case"tx":for(let J of W.split(";"))this.doStep(J)}}getUpdateNumber(T){let _=T.indexOf("=");return Number(T.substring(0,_))}do(T){let _=T.indexOf("="),F=Number(T.substring(0,_)),W=F-this.cacheUpdateNumber;if(W>0){if(W===1){this.mode="playback";let Y=T.substring(_+1);return this.doStep(Y),this.mode="record",this.cacheUpdateNumber=F,null}return this.cacheUpdateNumber+1}if(Math.abs(W)<this.cacheLimit){let Y=this.cacheIdx+W;if(this.cache[Y]===T)return null;this.mode="playback";let Z=!1;while(!Z){this.cacheIdx%=this.cacheLimit;let X=this.cache[this.cacheIdx];if(this.cacheIdx--,!X)return"OUT_OF_RANGE";this.undo(X),Z=this.cacheIdx===Y-1}let G=T.substring(_+1);return this.doStep(G),this.mode="record",this.cacheUpdateNumber=F,null}return"OUT_OF_RANGE"}undoStep(T){let _=T.indexOf(":"),F=T.substring(0,_),W=T.substring(_+1);switch(F){case"add":this.delete(JSON.parse(W));break;case"del":this.add(JSON.parse(W));break;case"clear":{let J=JSON.parse(W);for(let Y of J)this.add(Y);break}case"tx":{let J=W.split(";");for(let Y=J.length-1;Y>=0;Y--)this.undoStep(J[Y])}}}undo(T){let _=T.indexOf("=");if(Number(T.substring(0,_))===this.cacheUpdateNumber){this.mode="playback";let W=T.substring(_+1);return this.undoStep(W),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function M$(T){return T.startsWith("\uD83D\uDD0D ")}class $1{supported;constructor(T){this.supported=T}refine(T){for(let[_,F]of Object.entries(this.supported))try{if(F(T)===!0&&F!==Boolean)return{type:_,data:T}}catch(W){try{if(T instanceof F)return{type:_,data:T}}catch(J){}}return null}}var l7=new $1({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function t7(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var i7=new $1({object:t7,array:(T)=>Array.isArray(T)}),n7=new $1({...l7.supported,...i7.supported}),E$=(T)=>{if(T===void 0)return"undefined";let _=n7.refine(T);if(_)return _.type;return Object.getPrototypeOf(T).constructor.name};class Z1{listeners;globalListeners;handleEvent(T,..._){for(let W of this.globalListeners)W(T,..._);let F=this.listeners.get(T);if(F)for(let W of F)W(..._)}id="no_id_retrieved";emit;constructor(T){this.emit=T,this.listeners=new Map,this.globalListeners=new Set}on(T,_){let F=this.listeners.get(T);if(F)F.add(_);else this.listeners.set(T,new Set([_]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,_){let F=this.listeners.get(T);if(F)if(_)F.delete(_);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class z$ extends Z1{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((..._)=>{return this.out.next(_),this});this.id=T,this.in=new FT,this.out=new FT,this.in.subscribe("socket",(_)=>{this.handleEvent(..._)})}dispose(){for(let T of this.disposalFunctions)T()}}class N2 extends Z1{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(rT(T.map((_)=>_ instanceof ZF?`{ ${_.toJSON().members.join(" | ")} }`:_))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,..._)=>{let F=JSON.stringify([T,..._]);return this.process.stdout.write(F+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let _=T.toString();this.unprocessedEvents.push(..._.split("\x03"));let F=this.unprocessedEvents.shift();this.incompleteData+=F??"";try{let W=iF(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",W),this.handleEvent(...W);while(this.unprocessedEvents.length>0){let J=this.unprocessedEvents.shift();if(J){if(this.unprocessedEvents.length===0)this.incompleteData=J;let Y=iF(J);this.handleEvent(...Y)}}this.incompleteData=""}catch(W){if(W instanceof Error)this.logger.error("\u2757",W.message,W.cause,W.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let _=new z$(`user:${T}`);this.relays.set(T,_),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let F of this.relayServices){let W=F(_);if(W)_.disposalFunctions.push(W)}this.on(`user:${T}`,(...F)=>{_.in.next(F)}),_.out.subscribe("socket",(F)=>{this.emit(...F)})}),this.on("user-leaves",(T)=>{let _=this.relays.get(T);if(this.off(`relay:${T}`),_)_.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var{file:s5,serve:HO}=globalThis.Bun;import{readFileSync as L$}from"fs";import{createServer as e7}from"http";import{createServer as T3}from"https";import{resolve as B2}from"path";function K$(T,_){if(T instanceof Promise)throw new Error(_)}function r7(T,_){let F={},W=[];for(let J in T){let Y=T[J]["~standard"].validate(_[J]);if(K$(Y,`Validation must be synchronous, but ${J} returned a Promise.`),Y.issues){W.push(...Y.issues.map(($)=>({...$,message:$.message,path:[J,...$.path??[]]})));continue}F[J]=Y.value}if(W.length)return{issues:W};return{value:F}}function C2(T){let _=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[j,y]of Object.entries(_))if(y==="")delete _[j]}if(!!T.skipValidation)return _;let J=typeof T.client==="object"?T.client:{},Y=typeof T.server==="object"?T.server:{},$=typeof T.shared==="object"?T.shared:{},Z=T.isServer??(typeof window==="undefined"||("Deno"in window)),G=Z?{...Y,...$,...J}:{...J,...$},X=T.createFinalSchema?.(G,Z)["~standard"].validate(_)??r7(G,_);K$(X,"Validation must be synchronous");let O=T.onValidationError??((j)=>{throw console.error("\u274C Invalid environment variables:",j),new Error("Invalid environment variables")}),M=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(X.issues)return O(X.issues);let Q=(j)=>{if(!T.clientPrefix)return!0;return!j.startsWith(T.clientPrefix)&&!(j in $)},V=(j)=>{return Z||!Q(j)},B=(j)=>{return j==="__esModule"||j==="$$typeof"},K=(T.extends??[]).reduce((j,y)=>{return Object.assign(j,y)},{}),v=Object.assign(K,X.value);return new Proxy(v,{get(j,y){if(typeof y!=="string")return;if(B(y))return;if(!V(y))return M(y);return Reflect.get(j,y)}})}var s7="__vite_start_time"in globalThis,a7=typeof window!=="undefined",fN="vitest"in globalThis,s_=Y_("string"),V$=Y_('"true" | "false" | undefined'),q_=C2({isServer:!s7&&!a7,server:{CI:Y_("string | undefined").pipe(Boolean),POSTGRES_USER:s_,POSTGRES_PASSWORD:s_,POSTGRES_DATABASE:s_,POSTGRES_HOST:s_,POSTGRES_PORT:s_.pipe((T)=>Number.parseInt(T,10)),BACKEND_PORT:s_.pipe((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:V$.pipe((T)=>T==="true"),FRONTEND_PORT:s_.pipe((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:s_.pipe.try((T)=>JSON.parse(T),Y_("string[]")),API_KEY_OPENAI:Y_("string | undefined"),API_KEY_RESEND:Y_("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:s_,VITE_DEV_FRONTEND_HOST:Y_("string | undefined"),VITE_DEV_HTTPS:V$.pipe((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var D$=B2(import.meta.dirname,"../dev"),X1=q_.VITE_DEV_HTTPS?{cert:L$(B2(D$,"./cert.pem"),"utf-8"),key:L$(B2(D$,"./key.pem"),"utf-8")}:void 0;function bN(T){if(X1)return T3(X1,T);return e7({},T)}import JO from"path";var H=Symbol.for("drizzle:entityKind"),pN=Symbol.for("drizzle:hasOwnEntityKind");function R(T,_){if(!T||typeof T!=="object")return!1;if(T instanceof _)return!0;if(!Object.prototype.hasOwnProperty.call(_,H))throw new Error(`Class "${_.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let F=Object.getPrototypeOf(T).constructor;if(F)while(F){if(H in F&&F[H]===_[H])return!0;F=Object.getPrototypeOf(F)}return!1}class GT{constructor(T,_){this.table=T,this.config=_,this.name=_.name,this.keyAsName=_.keyAsName,this.notNull=_.notNull,this.default=_.default,this.defaultFn=_.defaultFn,this.onUpdateFn=_.onUpdateFn,this.hasDefault=_.hasDefault,this.primary=_.primaryKey,this.isUnique=_.isUnique,this.uniqueName=_.uniqueName,this.uniqueType=_.uniqueType,this.dataType=_.dataType,this.columnType=_.columnType,this.generated=_.generated,this.generatedIdentity=_.generatedIdentity}static[H]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class k2{static[H]="ColumnBuilder";config;constructor(T,_,F){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:_,columnType:F,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var j_=Symbol.for("drizzle:Name");class f2{static[H]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,_){if(this.reference=()=>{let{name:F,columns:W,foreignColumns:J}=T();return{name:F,columns:W,foreignTable:J[0].table,foreignColumns:J}},_)this._onUpdate=_.onUpdate,this._onDelete=_.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new S$(T,this)}}class S${constructor(T,_){this.table=T,this.reference=_.reference,this.onUpdate=_._onUpdate,this.onDelete=_._onDelete}static[H]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:_,foreignColumns:F}=this.reference(),W=_.map(($)=>$.name),J=F.map(($)=>$.name),Y=[this.table[j_],...W,F[0].table[j_],...J];return T??`${Y.join("_")}_fk`}}function G1(T,..._){return T(..._)}function I$(T,_){return`${T[j_]}_${_.join("_")}_unique`}function N$(T,_,F){for(let W=_;W<T.length;W++){let J=T[W];if(J==="\\"){W++;continue}if(J==='"')return[T.slice(_,W).replace(/\\/g,""),W+1];if(F)continue;if(J===","||J==="}")return[T.slice(_,W).replace(/\\/g,""),W]}return[T.slice(_).replace(/\\/g,""),T.length]}function C$(T,_=0){let F=[],W=_,J=!1;while(W<T.length){let Y=T[W];if(Y===","){if(J||W===_)F.push("");J=!0,W++;continue}if(J=!1,Y==="\\"){W+=2;continue}if(Y==='"'){let[G,X]=N$(T,W+1,!0);F.push(G),W=X;continue}if(Y==="}")return[F,W+1];if(Y==="{"){let[G,X]=C$(T,W+1);F.push(G),W=X;continue}let[$,Z]=N$(T,W,!1);F.push($),W=Z}return[F,W]}function B$(T){let[_]=C$(T,1);return _}function P2(T){return`{${T.map((_)=>{if(Array.isArray(_))return P2(_);if(typeof _==="string")return`"${_.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${_}`}).join(",")}}`}class f extends k2{foreignKeyConfigs=[];static[H]="PgColumnBuilder";array(T){return new f$(this.config.name,this,T)}references(T,_={}){return this.foreignKeyConfigs.push({ref:T,actions:_}),this}unique(T,_){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=_?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,_){return this.foreignKeyConfigs.map(({ref:F,actions:W})=>{return G1((J,Y)=>{let $=new f2(()=>{let Z=J();return{columns:[T],foreignColumns:[Z]}});if(Y.onUpdate)$.onUpdate(Y.onUpdate);if(Y.onDelete)$.onDelete(Y.onDelete);return $.build(_)},F,W)})}buildExtraConfigColumn(T){return new k$(T,this.config)}}class S extends GT{constructor(T,_){if(!_.uniqueName)_.uniqueName=I$(T,[_.name]);super(T,_);this.table=T}static[H]="PgColumn"}class k$ extends S{static[H]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(T){return this.indexConfig.opClass=T,this}}class _W{static[H]="IndexedColumn";constructor(T,_,F,W){this.name=T,this.keyAsName=_,this.type=F,this.indexConfig=W}name;keyAsName;type;indexConfig}class f$ extends f{static[H]="PgArrayBuilder";constructor(T,_,F){super(T,"array","PgArray");this.config.baseBuilder=_,this.config.size=F}build(T){let _=this.config.baseBuilder.build(T);return new q2(T,this.config,_)}}class q2 extends S{constructor(T,_,F,W){super(T,_);this.baseColumn=F,this.range=W,this.size=_.size}size;static[H]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=B$(T);return T.map((_)=>this.baseColumn.mapFromDriverValue(_))}mapToDriverValue(T,_=!1){let F=T.map((W)=>W===null?null:R(this.baseColumn,q2)?this.baseColumn.mapToDriverValue(W,!0):this.baseColumn.mapToDriverValue(W));if(_)return F;return P2(F)}}class P$ extends f{static[H]="PgEnumObjectColumnBuilder";constructor(T,_){super(T,"string","PgEnumObjectColumn");this.config.enum=_}build(T){return new q$(T,this.config)}}class q$ extends S{static[H]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(T,_){super(T,_);this.enum=_.enum}getSQLType(){return this.enum.enumName}}var A1=Symbol.for("drizzle:isPgEnum");function j$(T){return!!T&&typeof T==="function"&&A1 in T&&T[A1]===!0}class y$ extends f{static[H]="PgEnumColumnBuilder";constructor(T,_){super(T,"string","PgEnumColumn");this.config.enum=_}build(T){return new v$(T,this.config)}}class v$ extends S{static[H]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,_){super(T,_);this.enum=_.enum}getSQLType(){return this.enum.enumName}}function FW(T,_){return Array.isArray(_)?_3(T,[..._],void 0):F3(T,_,void 0)}function _3(T,_,F){let W=Object.assign((J)=>new y$(J??"",W),{enumName:T,enumValues:_,schema:F,[A1]:!0});return W}function F3(T,_,F){let W=Object.assign((J)=>new P$(J??"",W),{enumName:T,enumValues:Object.values(_),schema:F,[A1]:!0});return W}class IT{static[H]="Subquery";constructor(T,_,F,W=!1,J=[]){this._={brand:"Subquery",sql:T,selectedFields:_,alias:F,isWith:W,usedTables:J}}}class WW extends IT{static[H]="WithSubquery"}var x$="0.44.2";var j2,y2,AT={startActiveSpan(T,_){if(!j2)return _();if(!y2)y2=j2.trace.getTracer("drizzle-orm",x$);return G1((F,W)=>W.startActiveSpan(T,(J)=>{try{return _(J)}catch(Y){throw J.setStatus({code:F.SpanStatusCode.ERROR,message:Y instanceof Error?Y.message:"Unknown error"}),Y}finally{J.end()}}),j2,y2)}};var MT=Symbol.for("drizzle:ViewBaseConfig");var k0=Symbol.for("drizzle:Schema"),H1=Symbol.for("drizzle:Columns"),b$=Symbol.for("drizzle:ExtraConfigColumns"),v2=Symbol.for("drizzle:OriginalName"),x2=Symbol.for("drizzle:BaseName"),JW=Symbol.for("drizzle:IsAlias"),h$=Symbol.for("drizzle:ExtraConfigBuilder"),W3=Symbol.for("drizzle:IsDrizzleTable");class I{static[H]="Table";static Symbol={Name:j_,Schema:k0,OriginalName:v2,Columns:H1,ExtraConfigColumns:b$,BaseName:x2,IsAlias:JW,ExtraConfigBuilder:h$};[j_];[v2];[k0];[H1];[b$];[x2];[JW]=!1;[W3]=!0;[h$]=void 0;constructor(T,_,F){this[j_]=this[v2]=T,this[k0]=_,this[x2]=F}}function xT(T){return T[j_]}function f0(T){return`${T[k0]??"public"}.${T[j_]}`}function b2(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function J3(T){let _={sql:"",params:[]};for(let F of T)if(_.sql+=F.sql,_.params.push(...F.params),F.typings?.length){if(!_.typings)_.typings=[];_.typings.push(...F.typings)}return _}class yT{static[H]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new k([this])}}class k{constructor(T){this.queryChunks=T;for(let _ of T)if(R(_,I)){let F=_[I.Symbol.Schema];this.usedTables.push(F===void 0?_[I.Symbol.Name]:F+"."+_[I.Symbol.Name])}}static[H]="SQL";decoder=g$;shouldInlineParams=!1;usedTables=[];append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return AT.startActiveSpan("drizzle.buildSQL",(_)=>{let F=this.buildQueryFromSourceParams(this.queryChunks,T);return _?.setAttributes({"drizzle.query.text":F.sql,"drizzle.query.params":JSON.stringify(F.params)}),F})}buildQueryFromSourceParams(T,_){let F=Object.assign({},_,{inlineParams:_.inlineParams||this.shouldInlineParams,paramStartIndex:_.paramStartIndex||{value:0}}),{casing:W,escapeName:J,escapeParam:Y,prepareTyping:$,inlineParams:Z,paramStartIndex:G}=F;return J3(T.map((X)=>{if(R(X,yT))return{sql:X.value.join(""),params:[]};if(R(X,O1))return{sql:J(X.value),params:[]};if(X===void 0)return{sql:"",params:[]};if(Array.isArray(X)){let O=[new yT("(")];for(let[M,Q]of X.entries())if(O.push(Q),M<X.length-1)O.push(new yT(", "));return O.push(new yT(")")),this.buildQueryFromSourceParams(O,F)}if(R(X,k))return this.buildQueryFromSourceParams(X.queryChunks,{...F,inlineParams:Z||X.shouldInlineParams});if(R(X,I)){let O=X[I.Symbol.Schema],M=X[I.Symbol.Name];return{sql:O===void 0||X[JW]?J(M):J(O)+"."+J(M),params:[]}}if(R(X,GT)){let O=W.getColumnCasing(X);if(_.invokeSource==="indexes")return{sql:J(O),params:[]};let M=X.table[I.Symbol.Schema];return{sql:X.table[JW]||M===void 0?J(X.table[I.Symbol.Name])+"."+J(O):J(M)+"."+J(X.table[I.Symbol.Name])+"."+J(O),params:[]}}if(R(X,Z_)){let O=X[MT].schema,M=X[MT].name;return{sql:O===void 0||X[MT].isAlias?J(M):J(O)+"."+J(M),params:[]}}if(R(X,Q_)){if(R(X.value,R0))return{sql:Y(G.value++,X),params:[X],typings:["none"]};let O=X.value===null?null:X.encoder.mapToDriverValue(X.value);if(R(O,k))return this.buildQueryFromSourceParams([O],F);if(Z)return{sql:this.mapInlineParam(O,F),params:[]};let M=["none"];if($)M=[$(X.encoder)];return{sql:Y(G.value++,O),params:[O],typings:M}}if(R(X,R0))return{sql:Y(G.value++,X),params:[X],typings:["none"]};if(R(X,k.Aliased)&&X.fieldAlias!==void 0)return{sql:J(X.fieldAlias),params:[]};if(R(X,IT)){if(X._.isWith)return{sql:J(X._.alias),params:[]};return this.buildQueryFromSourceParams([new yT("("),X._.sql,new yT(") "),new O1(X._.alias)],F)}if(j$(X)){if(X.schema)return{sql:J(X.schema)+"."+J(X.enumName),params:[]};return{sql:J(X.enumName),params:[]}}if(b2(X)){if(X.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([X.getSQL()],F);return this.buildQueryFromSourceParams([new yT("("),X.getSQL(),new yT(")")],F)}if(Z)return{sql:this.mapInlineParam(X,F),params:[]};return{sql:Y(G.value++,X),params:[X],typings:["none"]}}))}mapInlineParam(T,{escapeString:_}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return _(T);if(typeof T==="object"){let F=T.toString();if(F==="[object Object]")return _(JSON.stringify(T));return _(F)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new k.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class O1{constructor(T){this.value=T}static[H]="Name";brand;getSQL(){return new k([this])}}function p$(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var g$={mapFromDriverValue:(T)=>T},m$={mapToDriverValue:(T)=>T},CC={...g$,...m$};class Q_{constructor(T,_=m$){this.value=T,this.encoder=_}static[H]="Param";brand;getSQL(){return new k([this])}}function U(T,..._){let F=[];if(_.length>0||T.length>0&&T[0]!=="")F.push(new yT(T[0]));for(let[W,J]of _.entries())F.push(J,new yT(T[W+1]));return new k(F)}((T)=>{function _(){return new k([])}T.empty=_;function F(G){return new k(G)}T.fromList=F;function W(G){return new k([new yT(G)])}T.raw=W;function J(G,X){let O=[];for(let[M,Q]of G.entries()){if(M>0&&X!==void 0)O.push(X);O.push(Q)}return new k(O)}T.join=J;function Y(G){return new O1(G)}T.identifier=Y;function $(G){return new R0(G)}T.placeholder=$;function Z(G,X){return new Q_(G,X)}T.param=Z})(U||(U={}));((T)=>{class _{constructor(F,W){this.sql=F,this.fieldAlias=W}static[H]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new _(this.sql,this.fieldAlias)}}T.Aliased=_})(k||(k={}));class R0{constructor(T){this.name=T}static[H]="Placeholder";getSQL(){return new k([this])}}function h2(T,_){return T.map((F)=>{if(R(F,R0)){if(!(F.name in _))throw new Error(`No value for placeholder "${F.name}" was provided`);return _[F.name]}if(R(F,Q_)&&R(F.value,R0)){if(!(F.value.name in _))throw new Error(`No value for placeholder "${F.value.name}" was provided`);return F.encoder.mapToDriverValue(_[F.value.name])}return F})}var Y3=Symbol.for("drizzle:IsDrizzleView");class Z_{static[H]="View";[MT];[Y3]=!0;constructor({name:T,schema:_,selectedFields:F,query:W}){this[MT]={name:T,originalName:T,schema:_,selectedFields:F,query:W,isExisting:!W,isAlias:!1}}getSQL(){return new k([this])}}GT.prototype.getSQL=function(){return new k([this])};I.prototype.getSQL=function(){return new k([this])};IT.prototype.getSQL=function(){return new k([this])};class XF{constructor(T){this.table=T}static[H]="ColumnAliasProxyHandler";get(T,_){if(_==="table")return this.table;return T[_]}}class YW{constructor(T,_){this.alias=T,this.replaceOriginalName=_}static[H]="TableAliasProxyHandler";get(T,_){if(_===I.Symbol.IsAlias)return!0;if(_===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&_===I.Symbol.OriginalName)return this.alias;if(_===MT)return{...T[MT],name:this.alias,isAlias:!0};if(_===I.Symbol.Columns){let W=T[I.Symbol.Columns];if(!W)return W;let J={};return Object.keys(W).map((Y)=>{J[Y]=new Proxy(W[Y],new XF(new Proxy(T,this)))}),J}let F=T[_];if(R(F,GT))return new Proxy(F,new XF(new Proxy(T,this)));return F}}function U1(T,_){return new Proxy(T,new YW(_,!1))}function m_(T,_){return new Proxy(T,new XF(new Proxy(T.table,new YW(_,!1))))}function p2(T,_){return new k.Aliased($W(T.sql,_),T.fieldAlias)}function $W(T,_){return U.join(T.queryChunks.map((F)=>{if(R(F,GT))return m_(F,_);if(R(F,k))return $W(F,_);if(R(F,k.Aliased))return p2(F,_);return F}))}class M1 extends Error{static[H]="DrizzleError";constructor({message:T,cause:_}){super(T);this.name="DrizzleError",this.cause=_}}class g2 extends M1{static[H]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class o${static[H]="ConsoleLogWriter";write(T){console.log(T)}}class m2{static[H]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new o$}logQuery(T,_){let F=_.map((J)=>{try{return JSON.stringify(J)}catch{return String(J)}}),W=F.length?` -- params: [${F.join(", ")}]`:"";this.writer.write(`Query: ${T}${W}`)}}class o2{static[H]="NoopLogger";logQuery(){}}class aT{static[H]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((_)=>{return T?.(),_},(_)=>{throw T?.(),_})}then(T,_){return this.execute().then(T,_)}}function u$(T,_,F){let W={},J=T.reduce((Y,{path:$,field:Z},G)=>{let X;if(R(Z,GT))X=Z;else if(R(Z,k))X=Z.decoder;else X=Z.sql.decoder;let O=Y;for(let[M,Q]of $.entries())if(M<$.length-1){if(!(Q in O))O[Q]={};O=O[Q]}else{let V=_[G],B=O[Q]=V===null?null:X.mapFromDriverValue(V);if(F&&R(Z,GT)&&$.length===2){let K=$[0];if(!(K in W))W[K]=B===null?xT(Z.table):!1;else if(typeof W[K]==="string"&&W[K]!==xT(Z.table))W[K]=!1}}return Y},{});if(F&&Object.keys(W).length>0){for(let[Y,$]of Object.entries(W))if(typeof $==="string"&&!F[$])J[Y]=null}return J}function L_(T,_){return Object.entries(T).reduce((F,[W,J])=>{if(typeof W!=="string")return F;let Y=_?[..._,W]:[W];if(R(J,GT)||R(J,k)||R(J,k.Aliased))F.push({path:Y,field:J});else if(R(J,I))F.push(...L_(J[I.Symbol.Columns],Y));else F.push(...L_(J,Y));return F},[])}function ZW(T,_){let F=Object.keys(T),W=Object.keys(_);if(F.length!==W.length)return!1;for(let[J,Y]of F.entries())if(Y!==W[J])return!1;return!0}function w1(T,_){let F=Object.entries(_).filter(([,W])=>W!==void 0).map(([W,J])=>{if(R(J,k)||R(J,GT))return[W,J];else return[W,new Q_(J,T[I.Symbol.Columns][W])]});if(F.length===0)throw new Error("No values to set");return Object.fromEntries(F)}function c$(T,_){for(let F of _)for(let W of Object.getOwnPropertyNames(F.prototype)){if(W==="constructor")continue;Object.defineProperty(T.prototype,W,Object.getOwnPropertyDescriptor(F.prototype,W)||Object.create(null))}}function d$(T){return T[I.Symbol.Columns]}function a_(T){return R(T,IT)?T._.alias:R(T,Z_)?T[MT].name:R(T,k)?void 0:T[I.Symbol.IsAlias]?T[I.Symbol.Name]:T[I.Symbol.BaseName]}function a(T,_){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:_}}function l$(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let _=typeof T.logger;if(_!=="boolean"&&(_!=="object"||typeof T.logger.logQuery!=="function")&&_!=="undefined")return!1;return!0}if("schema"in T){let _=typeof T.schema;if(_!=="object"&&_!=="undefined")return!1;return!0}if("casing"in T){let _=typeof T.casing;if(_!=="string"&&_!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let _=typeof T.connection;if(_!=="string"&&_!=="object"&&_!=="undefined")return!1;return!0}if("client"in T){let _=typeof T.client;if(_!=="object"&&_!=="function"&&_!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class E0 extends f{static[H]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:_,...F}=T;this.config.generatedIdentity={type:"always",sequenceName:_,sequenceOptions:F}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:_,...F}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:_,sequenceOptions:F}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class t$ extends E0{static[H]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new i$(T,this.config)}}class i$ extends S{static[H]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class n$ extends E0{static[H]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new r$(T,this.config)}}class r$ extends S{static[H]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function s$(T,_){let{name:F,config:W}=a(T,_);if(W.mode==="number")return new t$(F);return new n$(F)}class a$ extends f{static[H]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new e$(T,this.config)}}class e$ extends S{static[H]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class TZ extends f{static[H]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new _Z(T,this.config)}}class _Z extends S{static[H]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function FZ(T,_){let{name:F,config:W}=a(T,_);if(W.mode==="number")return new a$(F);return new TZ(F)}class WZ extends f{static[H]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new JZ(T,this.config)}}class JZ extends S{static[H]="PgBoolean";getSQLType(){return"boolean"}}function XW(T){return new WZ(T??"")}class YZ extends f{static[H]="PgCharBuilder";constructor(T,_){super(T,"string","PgChar");this.config.length=_.length,this.config.enumValues=_.enum}build(T){return new $Z(T,this.config)}}class $Z extends S{static[H]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function ZZ(T,_={}){let{name:F,config:W}=a(T,_);return new YZ(F,W)}class XZ extends f{static[H]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new GZ(T,this.config)}}class GZ extends S{static[H]="PgCidr";getSQLType(){return"cidr"}}function AZ(T){return new XZ(T??"")}class HZ extends f{static[H]="PgCustomColumnBuilder";constructor(T,_,F){super(T,"custom","PgCustomColumn");this.config.fieldConfig=_,this.config.customTypeParams=F}build(T){return new OZ(T,this.config)}}class OZ extends S{static[H]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,_){super(T,_);this.sqlName=_.customTypeParams.dataType(_.fieldConfig),this.mapTo=_.customTypeParams.toDriver,this.mapFrom=_.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function UZ(T){return(_,F)=>{let{name:W,config:J}=a(_,F);return new HZ(W,J,T)}}class e_ extends f{static[H]="PgDateColumnBaseBuilder";defaultNow(){return this.default(U`now()`)}}class MZ extends e_{static[H]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new Q1(T,this.config)}}class Q1 extends S{static[H]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class wZ extends e_{static[H]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new R1(T,this.config)}}class R1 extends S{static[H]="PgDateString";getSQLType(){return"date"}}function QZ(T,_){let{name:F,config:W}=a(T,_);if(W?.mode==="date")return new MZ(F);return new wZ(F)}class RZ extends f{static[H]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new EZ(T,this.config)}}class EZ extends S{static[H]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function zZ(T){return new RZ(T??"")}class KZ extends f{static[H]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new VZ(T,this.config)}}class VZ extends S{static[H]="PgInet";getSQLType(){return"inet"}}function LZ(T){return new KZ(T??"")}class DZ extends E0{static[H]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new SZ(T,this.config)}}class SZ extends S{static[H]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function GW(T){return new DZ(T??"")}class IZ extends f{static[H]="PgIntervalBuilder";constructor(T,_){super(T,"string","PgInterval");this.config.intervalConfig=_}build(T){return new NZ(T,this.config)}}class NZ extends S{static[H]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",_=this.precision?`(${this.precision})`:"";return`interval${T}${_}`}}function CZ(T,_={}){let{name:F,config:W}=a(T,_);return new IZ(F,W)}class BZ extends f{static[H]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new E1(T,this.config)}}class E1 extends S{static[H]="PgJson";constructor(T,_){super(T,_)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function kZ(T){return new BZ(T??"")}class fZ extends f{static[H]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new z1(T,this.config)}}class z1 extends S{static[H]="PgJsonb";constructor(T,_){super(T,_)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function PZ(T){return new fZ(T??"")}class qZ extends f{static[H]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new jZ(T,this.config)}}class jZ extends S{static[H]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[_,F,W]=T.slice(1,-1).split(",");return[Number.parseFloat(_),Number.parseFloat(F),Number.parseFloat(W)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class yZ extends f{static[H]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new vZ(T,this.config)}}class vZ extends S{static[H]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[_,F,W]=T.slice(1,-1).split(",");return{a:Number.parseFloat(_),b:Number.parseFloat(F),c:Number.parseFloat(W)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function xZ(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new qZ(F);return new yZ(F)}class bZ extends f{static[H]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new hZ(T,this.config)}}class hZ extends S{static[H]="PgMacaddr";getSQLType(){return"macaddr"}}function pZ(T){return new bZ(T??"")}class gZ extends f{static[H]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new mZ(T,this.config)}}class mZ extends S{static[H]="PgMacaddr8";getSQLType(){return"macaddr8"}}function oZ(T){return new gZ(T??"")}class uZ extends f{static[H]="PgNumericBuilder";constructor(T,_,F){super(T,"string","PgNumeric");this.config.precision=_,this.config.scale=F}build(T){return new K1(T,this.config)}}class K1 extends S{static[H]="PgNumeric";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue(T){if(typeof T==="string")return T;return String(T)}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class cZ extends f{static[H]="PgNumericNumberBuilder";constructor(T,_,F){super(T,"number","PgNumericNumber");this.config.precision=_,this.config.scale=F}build(T){return new dZ(T,this.config)}}class dZ extends S{static[H]="PgNumericNumber";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class lZ extends f{static[H]="PgNumericBigIntBuilder";constructor(T,_,F){super(T,"bigint","PgNumericBigInt");this.config.precision=_,this.config.scale=F}build(T){return new tZ(T,this.config)}}class tZ extends S{static[H]="PgNumericBigInt";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function iZ(T,_){let{name:F,config:W}=a(T,_),J=W?.mode;return J==="number"?new cZ(F,W?.precision,W?.scale):J==="bigint"?new lZ(F,W?.precision,W?.scale):new uZ(F,W?.precision,W?.scale)}class nZ extends f{static[H]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new rZ(T,this.config)}}class rZ extends S{static[H]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[_,F]=T.slice(1,-1).split(",");return[Number.parseFloat(_),Number.parseFloat(F)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class sZ extends f{static[H]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new aZ(T,this.config)}}class aZ extends S{static[H]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[_,F]=T.slice(1,-1).split(",");return{x:Number.parseFloat(_),y:Number.parseFloat(F)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function eZ(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new nZ(F);return new sZ(F)}function $3(T){let _=[];for(let F=0;F<T.length;F+=2)_.push(Number.parseInt(T.slice(F,F+2),16));return new Uint8Array(_)}function TX(T,_){let F=new ArrayBuffer(8),W=new DataView(F);for(let J=0;J<8;J++)W.setUint8(J,T[_+J]);return W.getFloat64(0,!0)}function u2(T){let _=$3(T),F=0,W=_[F];F+=1;let J=new DataView(_.buffer),Y=J.getUint32(F,W===1);F+=4;let $;if(Y&536870912)$=J.getUint32(F,W===1),F+=4;if((Y&65535)===1){let Z=TX(_,F);F+=8;let G=TX(_,F);return F+=8,[Z,G]}throw new Error("Unsupported geometry type")}class _X extends f{static[H]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new FX(T,this.config)}}class FX extends S{static[H]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return u2(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class WX extends f{static[H]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new JX(T,this.config)}}class JX extends S{static[H]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let _=u2(T);return{x:_[0],y:_[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function YX(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new _X(F);return new WX(F)}class $X extends f{static[H]="PgRealBuilder";constructor(T,_){super(T,"number","PgReal");this.config.length=_}build(T){return new ZX(T,this.config)}}class ZX extends S{static[H]="PgReal";constructor(T,_){super(T,_)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function XX(T){return new $X(T??"")}class GX extends f{static[H]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new AX(T,this.config)}}class AX extends S{static[H]="PgSerial";getSQLType(){return"serial"}}function HX(T){return new GX(T??"")}class OX extends E0{static[H]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new UX(T,this.config)}}class UX extends S{static[H]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function MX(T){return new OX(T??"")}class wX extends f{static[H]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new QX(T,this.config)}}class QX extends S{static[H]="PgSmallSerial";getSQLType(){return"smallserial"}}function RX(T){return new wX(T??"")}class EX extends f{static[H]="PgTextBuilder";constructor(T,_){super(T,"string","PgText");this.config.enumValues=_.enum}build(T){return new zX(T,this.config)}}class zX extends S{static[H]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function KX(T,_={}){let{name:F,config:W}=a(T,_);return new EX(F,W)}class VX extends e_{constructor(T,_,F){super(T,"string","PgTime");this.withTimezone=_,this.precision=F,this.config.withTimezone=_,this.config.precision=F}static[H]="PgTimeBuilder";build(T){return new V1(T,this.config)}}class V1 extends S{static[H]="PgTime";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function LX(T,_={}){let{name:F,config:W}=a(T,_);return new VX(F,W.withTimezone??!1,W.precision)}class DX extends e_{static[H]="PgTimestampBuilder";constructor(T,_,F){super(T,"date","PgTimestamp");this.config.withTimezone=_,this.config.precision=F}build(T){return new L1(T,this.config)}}class L1 extends S{static[H]="PgTimestamp";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class SX extends e_{static[H]="PgTimestampStringBuilder";constructor(T,_,F){super(T,"string","PgTimestampString");this.config.withTimezone=_,this.config.precision=F}build(T){return new D1(T,this.config)}}class D1 extends S{static[H]="PgTimestampString";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function IX(T,_={}){let{name:F,config:W}=a(T,_);if(W?.mode==="string")return new SX(F,W.withTimezone??!1,W.precision);return new DX(F,W?.withTimezone??!1,W?.precision)}class NX extends f{static[H]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(U`gen_random_uuid()`)}build(T){return new S1(T,this.config)}}class S1 extends S{static[H]="PgUUID";getSQLType(){return"uuid"}}function D_(T){return new NX(T??"")}class CX extends f{static[H]="PgVarcharBuilder";constructor(T,_){super(T,"string","PgVarchar");this.config.length=_.length,this.config.enumValues=_.enum}build(T){return new BX(T,this.config)}}class BX extends S{static[H]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function dT(T,_={}){let{name:F,config:W}=a(T,_);return new CX(F,W)}class kX extends f{static[H]="PgBinaryVectorBuilder";constructor(T,_){super(T,"string","PgBinaryVector");this.config.dimensions=_.dimensions}build(T){return new fX(T,this.config)}}class fX extends S{static[H]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function PX(T,_){let{name:F,config:W}=a(T,_);return new kX(F,W)}class qX extends f{static[H]="PgHalfVectorBuilder";constructor(T,_){super(T,"array","PgHalfVector");this.config.dimensions=_.dimensions}build(T){return new jX(T,this.config)}}class jX extends S{static[H]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((_)=>Number.parseFloat(_))}}function yX(T,_){let{name:F,config:W}=a(T,_);return new qX(F,W)}class vX extends f{static[H]="PgSparseVectorBuilder";constructor(T,_){super(T,"string","PgSparseVector");this.config.dimensions=_.dimensions}build(T){return new xX(T,this.config)}}class xX extends S{static[H]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function bX(T,_){let{name:F,config:W}=a(T,_);return new vX(F,W)}class hX extends f{static[H]="PgVectorBuilder";constructor(T,_){super(T,"array","PgVector");this.config.dimensions=_.dimensions}build(T){return new pX(T,this.config)}}class pX extends S{static[H]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((_)=>Number.parseFloat(_))}}function gX(T,_){let{name:F,config:W}=a(T,_);return new hX(F,W)}function mX(){return{bigint:s$,bigserial:FZ,boolean:XW,char:ZZ,cidr:AZ,customType:UZ,date:QZ,doublePrecision:zZ,inet:LZ,integer:GW,interval:CZ,json:kZ,jsonb:PZ,line:xZ,macaddr:pZ,macaddr8:oZ,numeric:iZ,point:eZ,geometry:YX,real:XX,serial:HX,smallint:MX,smallserial:RX,text:KX,time:LX,timestamp:IX,uuid:D_,varchar:dT,bit:PX,halfvec:yX,sparsevec:bX,vector:gX}}var c2=Symbol.for("drizzle:PgInlineForeignKeys"),oX=Symbol.for("drizzle:EnableRLS");class vT extends I{static[H]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:c2,EnableRLS:oX});[c2]=[];[oX]=!1;[I.Symbol.ExtraConfigBuilder]=void 0;[I.Symbol.ExtraConfigColumns]={}}function Z3(T,_,F,W,J=T){let Y=new vT(T,W,J),$=typeof _==="function"?_(mX()):_,Z=Object.fromEntries(Object.entries($).map(([O,M])=>{let Q=M;Q.setName(O);let V=Q.build(Y);return Y[c2].push(...Q.buildForeignKeys(V,Y)),[O,V]})),G=Object.fromEntries(Object.entries($).map(([O,M])=>{let Q=M;Q.setName(O);let V=Q.buildExtraConfigColumn(Y);return[O,V]})),X=Object.assign(Y,Z);if(X[I.Symbol.Columns]=Z,X[I.Symbol.ExtraConfigColumns]=G,F)X[vT.Symbol.ExtraConfigBuilder]=F;return Object.assign(X,{enableRLS:()=>{return X[vT.Symbol.EnableRLS]=!0,X}})}var z0=(T,_,F)=>{return Z3(T,_,F,void 0)};function uX(...T){if(T[0].columns)return new AW(T[0].columns,T[0].name);return new AW(T)}class AW{static[H]="PgPrimaryKeyBuilder";columns;name;constructor(T,_){this.columns=T,this.name=_}build(T){return new cX(T,this.columns,this.name)}}class cX{constructor(T,_,F){this.table=T,this.columns=_,this.name=F}static[H]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[vT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}function X_(T,_){if(p$(_)&&!b2(T)&&!R(T,Q_)&&!R(T,R0)&&!R(T,GT)&&!R(T,I)&&!R(T,Z_))return new Q_(T,_);return T}var I1=(T,_)=>{return U`${T} = ${X_(_,T)}`},dX=(T,_)=>{return U`${T} <> ${X_(_,T)}`};function HW(...T){let _=T.filter((F)=>F!==void 0);if(_.length===0)return;if(_.length===1)return new k(_);return new k([new yT("("),U.join(_,new yT(" and ")),new yT(")")])}function lX(...T){let _=T.filter((F)=>F!==void 0);if(_.length===0)return;if(_.length===1)return new k(_);return new k([new yT("("),U.join(_,new yT(" or ")),new yT(")")])}function tX(T){return U`not ${T}`}var iX=(T,_)=>{return U`${T} > ${X_(_,T)}`},nX=(T,_)=>{return U`${T} >= ${X_(_,T)}`},rX=(T,_)=>{return U`${T} < ${X_(_,T)}`},sX=(T,_)=>{return U`${T} <= ${X_(_,T)}`};function aX(T,_){if(Array.isArray(_)){if(_.length===0)return U`false`;return U`${T} in ${_.map((F)=>X_(F,T))}`}return U`${T} in ${X_(_,T)}`}function eX(T,_){if(Array.isArray(_)){if(_.length===0)return U`true`;return U`${T} not in ${_.map((F)=>X_(F,T))}`}return U`${T} not in ${X_(_,T)}`}function T5(T){return U`${T} is null`}function _5(T){return U`${T} is not null`}function F5(T){return U`exists ${T}`}function W5(T){return U`not exists ${T}`}function J5(T,_,F){return U`${T} between ${X_(_,T)} and ${X_(F,T)}`}function Y5(T,_,F){return U`${T} not between ${X_(_,T)} and ${X_(F,T)}`}function $5(T,_){return U`${T} like ${_}`}function Z5(T,_){return U`${T} not like ${_}`}function X5(T,_){return U`${T} ilike ${_}`}function G5(T,_){return U`${T} not ilike ${_}`}function A5(T){return U`${T} asc`}function H5(T){return U`${T} desc`}class d2{constructor(T,_,F){this.sourceTable=T,this.referencedTable=_,this.relationName=F,this.referencedTableName=_[I.Symbol.Name]}static[H]="Relation";referencedTableName;fieldName}class O5{constructor(T,_){this.table=T,this.config=_}static[H]="Relations"}class K0 extends d2{constructor(T,_,F,W){super(T,_,F?.relationName);this.config=F,this.isNullable=W}static[H]="One";withFieldName(T){let _=new K0(this.sourceTable,this.referencedTable,this.config,this.isNullable);return _.fieldName=T,_}}class OW extends d2{constructor(T,_,F){super(T,_,F?.relationName);this.config=F}static[H]="Many";withFieldName(T){let _=new OW(this.sourceTable,this.referencedTable,this.config);return _.fieldName=T,_}}function U5(){return{and:HW,between:J5,eq:I1,exists:F5,gt:iX,gte:nX,ilike:X5,inArray:aX,isNull:T5,isNotNull:_5,like:$5,lt:rX,lte:sX,ne:dX,not:tX,notBetween:Y5,notExists:W5,notLike:Z5,notIlike:G5,notInArray:eX,or:lX,sql:U}}function M5(){return{sql:U,asc:A5,desc:H5}}function w5(T,_){if(Object.keys(T).length===1&&"default"in T&&!R(T.default,I))T=T.default;let F={},W={},J={};for(let[Y,$]of Object.entries(T))if(R($,I)){let Z=f0($),G=W[Z];F[Z]=Y,J[Y]={tsName:Y,dbName:$[I.Symbol.Name],schema:$[I.Symbol.Schema],columns:$[I.Symbol.Columns],relations:G?.relations??{},primaryKey:G?.primaryKey??[]};for(let O of Object.values($[I.Symbol.Columns]))if(O.primary)J[Y].primaryKey.push(O);let X=$[I.Symbol.ExtraConfigBuilder]?.($[I.Symbol.ExtraConfigColumns]);if(X){for(let O of Object.values(X))if(R(O,AW))J[Y].primaryKey.push(...O.columns)}}else if(R($,O5)){let Z=f0($.table),G=F[Z],X=$.config(_($.table)),O;for(let[M,Q]of Object.entries(X))if(G){let V=J[G];if(V.relations[M]=Q,O)V.primaryKey.push(...O)}else{if(!(Z in W))W[Z]={relations:{},primaryKey:O};W[Z].relations[M]=Q}}return{tables:J,tableNamesMap:F}}function X3(T){return function _(F,W){return new K0(T,F,W,W?.fields.reduce((J,Y)=>J&&Y.notNull,!0)??!1)}}function G3(T){return function _(F,W){return new OW(T,F,W)}}function Q5(T,_,F){if(R(F,K0)&&F.config)return{fields:F.config.fields,references:F.config.references};let W=_[f0(F.referencedTable)];if(!W)throw new Error(`Table "${F.referencedTable[I.Symbol.Name]}" not found in schema`);let J=T[W];if(!J)throw new Error(`Table "${W}" not found in schema`);let Y=F.sourceTable,$=_[f0(Y)];if(!$)throw new Error(`Table "${Y[I.Symbol.Name]}" not found in schema`);let Z=[];for(let G of Object.values(J.relations))if(F.relationName&&F!==G&&G.relationName===F.relationName||!F.relationName&&G.referencedTable===F.sourceTable)Z.push(G);if(Z.length>1)throw F.relationName?new Error(`There are multiple relations with name "${F.relationName}" in table "${W}"`):new Error(`There are multiple relations between "${W}" and "${F.sourceTable[I.Symbol.Name]}". Please specify relation name`);if(Z[0]&&R(Z[0],K0)&&Z[0].config)return{fields:Z[0].config.references,references:Z[0].config.fields};throw new Error(`There is not enough information to infer relation "${$}.${F.fieldName}"`)}function R5(T){return{one:X3(T),many:G3(T)}}function N1(T,_,F,W,J=(Y)=>Y){let Y={};for(let[$,Z]of W.entries())if(Z.isJson){let G=_.relations[Z.tsKey],X=F[$],O=typeof X==="string"?JSON.parse(X):X;Y[Z.tsKey]=R(G,K0)?O&&N1(T,T[Z.relationTableTsKey],O,Z.selection,J):O.map((M)=>N1(T,T[Z.relationTableTsKey],M,Z.selection,J))}else{let G=J(F[$]),X=Z.field,O;if(R(X,GT))O=X;else if(R(X,k))O=X.decoder;else O=X.sql.decoder;Y[Z.tsKey]=G===null?null:O.mapFromDriverValue(G)}return Y}import j3 from"os";import y3 from"fs";var C1=new Map,l2=new Map,t2=Symbol("OriginError"),GF={};class S_ extends Promise{constructor(T,_,F,W,J={}){let Y,$;super((Z,G)=>{Y=Z,$=G});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=_,this.handler=F,this.canceller=W,this.options=J,this.state=null,this.statement=null,this.resolve=(Z)=>(this.active=!1,Y(Z)),this.reject=(Z)=>(this.active=!1,$(Z)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[t2]=this.handler.debug?new Error:this.tagged&&A3(this.strings)}get origin(){return(this.handler.debug?this[t2].stack:this.tagged&&l2.has(this.strings)?l2.get(this.strings):l2.set(this.strings,this[t2].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,_){if(this.options.simple=!1,typeof T==="function")_=T,T=1;if(this.cursorRows=T,typeof _==="function")return this.cursorFn=_,this;let F;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};F&&F();let W=new Promise((J,Y)=>{this.cursorFn=($)=>{return J({value:$,done:!1}),new Promise((Z)=>F=Z)},this.resolve=()=>(this.active=!1,J({done:!0})),this.reject=($)=>(this.active=!1,Y($))});return this.execute(),W},return(){return F&&F(GF),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function A3(T){if(C1.has(T))return C1.get(T);let _=Error.stackTraceLimit;return Error.stackTraceLimit=4,C1.set(T,new Error),Error.stackTraceLimit=_,C1.get(T)}class AF extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var BT={connection:E5,postgres:z5,generic:K5,notSupported:V5};function E5(T,_,F){let{host:W,port:J}=F||_,Y=Object.assign(new Error("write "+T+" "+(_.path||W+":"+J)),{code:T,errno:T,address:_.path||W},_.path?{}:{port:J});return Error.captureStackTrace(Y,E5),Y}function z5(T){let _=new AF(T);return Error.captureStackTrace(_,z5),_}function K5(T,_){let F=Object.assign(new Error(T+": "+_),{code:T});return Error.captureStackTrace(F,K5),F}function V5(T){let _=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(_,V5),_}var H3={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class f1{then(){i2()}catch(){i2()}finally(){i2()}}class QW extends f1{constructor(T){super();this.value=j1(T)}}class o_ extends f1{constructor(T,_,F){super();this.value=T,this.type=_,this.array=F}}class P1 extends f1{constructor(T,_){super();this.first=T,this.rest=_}build(T,_,F,W){let J=O3.map(([Y,$])=>({fn:$,i:T.search(Y)})).sort((Y,$)=>Y.i-$.i).pop();return J.i===-1?e2(this.first,W):J.fn(this.first,this.rest,_,F,W)}}function q1(T,_,F,W){let J=T instanceof o_?T.value:T;if(J===void 0){if(T instanceof o_?T.value=W.transform.undefined:J=T=W.transform.undefined,J===void 0)throw BT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+F.push(T instanceof o_?(_.push(T.value),T.array?T.array[T.type||k1(T.value)]||T.type||I5(T.value):T.type):(_.push(T),k1(T)))}var D5=C5(H3);function s2(T,_,F,W,J,Y){for(let $=1;$<T.strings.length;$++)_+=a2(_,F,W,J,Y)+T.strings[$],F=T.args[$];return _}function a2(T,_,F,W,J){return _ instanceof P1?_.build(T,F,W,J):_ instanceof S_?r2(_,F,W,J):_ instanceof QW?_.value:_&&_[0]instanceof S_?_.reduce((Y,$)=>Y+" "+r2($,F,W,J),""):q1(_,F,W,J)}function r2(T,_,F,W){return T.fragment=!0,s2(T,T.strings[0],T.args[0],_,F,W)}function S5(T,_,F,W,J){return T.map((Y)=>"("+W.map(($)=>a2("values",Y[$],_,F,J)).join(",")+")").join(",")}function L5(T,_,F,W,J){let Y=Array.isArray(T[0]),$=_.length?_.flat():Object.keys(Y?T[0]:T);return S5(Y?T:[T],F,W,$,J)}function B1(T,_,F,W,J){if(typeof T==="string"&&(T=[T].concat(_)),Array.isArray(T))return e2(T,J);let Y;return(_.length?_.flat():Object.keys(T)).map((Z)=>{return Y=T[Z],(Y instanceof S_?r2(Y,F,W,J):Y instanceof QW?Y.value:q1(Y,F,W,J))+" as "+j1(J.transform.column.to?J.transform.column.to(Z):Z)}).join(",")}var O3=Object.entries({values:L5,in:(...T)=>{let _=L5(...T);return _==="()"?"(null)":_},select:B1,as:B1,returning:B1,"\\(":B1,update(T,_,F,W,J){return(_.length?_.flat():Object.keys(T)).map((Y)=>j1(J.transform.column.to?J.transform.column.to(Y):Y)+"="+a2("values",T[Y],F,W,J))},insert(T,_,F,W,J){let Y=_.length?_.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+e2(Y,J)+")values"+S5(Array.isArray(T)?T:[T],F,W,Y,J)}}).map(([T,_])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),_]);function i2(){throw BT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:U3,parsers:M3}=D5;function I5(T){if(Array.isArray(T))return I5(T[0]);return typeof T==="string"?1009:0}var N5=function(T){let _=C5(T||{});return{serializers:Object.assign({},U3,_.serializers),parsers:Object.assign({},M3,_.parsers)}};function C5(T){return Object.keys(T).reduce((_,F)=>{if(T[F].from&&[].concat(T[F].from).forEach((W)=>_.parsers[W]=T[F].parse),T[F].serialize)_.serializers[T[F].to]=T[F].serialize,T[F].from&&[].concat(T[F].from).forEach((W)=>_.serializers[W]=T[F].serialize);return _},{parsers:{},serializers:{}})}function e2(T,{transform:{column:_}}){return T.map((F)=>j1(_.to?_.to(F):F)).join(",")}var j1=function T(_){return'"'+_.replace(/"/g,'""').replace(/\./g,'"."')+'"'},k1=function T(_){return _ instanceof o_?_.type:_ instanceof Date?1184:_ instanceof Uint8Array?17:_===!0||_===!1?16:typeof _==="bigint"?20:Array.isArray(_)?T(_[0]):0},w3=/\\/g,Q3=/"/g;function R3(T){return T.replace(w3,"\\\\").replace(Q3,"\\\"")}var B5=function T(_,F,W,J){if(Array.isArray(_)===!1)return _;if(!_.length)return"{}";let Y=_[0],$=J===1020?";":",";if(Array.isArray(Y)&&!Y.type)return"{"+_.map((Z)=>T(Z,F,W,J)).join($)+"}";return"{"+_.map((Z)=>{if(Z===void 0){if(Z=W.transform.undefined,Z===void 0)throw BT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return Z===null?"null":'"'+R3(F?F(Z.type?Z.value:Z):""+Z)+'"'}).join($)+"}"},n2={i:0,char:null,str:"",quoted:!1,last:0},k5=function T(_,F,W){return n2.i=n2.last=0,f5(n2,_,F,W)};function f5(T,_,F,W){let J=[],Y=W===1020?";":",";for(;T.i<_.length;T.i++){if(T.char=_[T.i],T.quoted)if(T.char==="\\")T.str+=_[++T.i];else if(T.char==='"')J.push(F?F(T.str):T.str),T.str="",T.quoted=_[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,J.push(f5(T,_,F,W));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&J.push(F?F(_.slice(T.last,T.i)):_.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===Y&&T.p!=="}"&&T.p!=='"')J.push(F?F(_.slice(T.last,T.i)):_.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&J.push(F?F(_.slice(T.last,T.i+1)):_.slice(T.last,T.i+1)),J}var P0=(T)=>{let _=T[0];for(let F=1;F<T.length;F++)_+=T[F]==="_"?T[++F].toUpperCase():T[F];return _},q0=(T)=>{let _=T[0].toUpperCase();for(let F=1;F<T.length;F++)_+=T[F]==="_"?T[++F].toUpperCase():T[F];return _},j0=(T)=>T.replace(/_/g,"-"),UW=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),MW=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),wW=(T)=>T.replace(/-/g,"_");function T8(T){return function _(F,W){return typeof F==="object"&&F!==null&&(W.type===114||W.type===3802)?Array.isArray(F)?F.map((J)=>_(J,W)):Object.entries(F).reduce((J,[Y,$])=>Object.assign(J,{[T(Y)]:_($,W)}),{}):F}}P0.column={from:P0};P0.value={from:T8(P0)};UW.column={to:UW};var _8={...P0};_8.column.to=UW;q0.column={from:q0};q0.value={from:T8(q0)};MW.column={to:MW};var F8={...q0};F8.column.to=MW;j0.column={from:j0};j0.value={from:T8(j0)};wW.column={to:wW};var W8={...j0};W8.column.to=wW;import P5 from"net";import V3 from"tls";import RW from"crypto";import J8 from"stream";import{performance as q5}from"perf_hooks";class y0 extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var R_=E3;function E3(T=[]){let _=T.slice(),F=0;return{get length(){return _.length-F},remove:(W)=>{let J=_.indexOf(W);return J===-1?null:(_.splice(J,1),W)},push:(W)=>(_.push(W),W),shift:()=>{let W=_[F++];if(F===_.length)F=0,_=[];else _[F-1]=void 0;return W}}}var lT=Buffer.allocUnsafe(256),z3="BCcDdEFfHPpQSX".split("").reduce((T,_)=>{let F=_.charCodeAt(0);return T[_]=()=>{return lT[0]=F,$T.i=5,$T},T},{}),$T=Object.assign(K3,z3,{N:String.fromCharCode(0),i:0,inc(T){return $T.i+=T,$T},str(T){let _=Buffer.byteLength(T);return y1(_),$T.i+=lT.write(T,$T.i,_,"utf8"),$T},i16(T){return y1(2),lT.writeUInt16BE(T,$T.i),$T.i+=2,$T},i32(T,_){if(_||_===0)return lT.writeUInt32BE(T,_),$T;return y1(4),lT.writeUInt32BE(T,$T.i),$T.i+=4,$T},z(T){return y1(T),lT.fill(0,$T.i,$T.i+T),$T.i+=T,$T},raw(T){return lT=Buffer.concat([lT.subarray(0,$T.i),T]),$T.i=lT.length,$T},end(T=1){lT.writeUInt32BE($T.i-T,T);let _=lT.subarray(0,$T.i);return $T.i=0,lT=Buffer.allocUnsafe(256),_}}),b=$T;function y1(T){if(lT.length-$T.i<T){let _=lT,F=_.length;lT=Buffer.allocUnsafe(F+(F>>1)+T),_.copy(lT)}}function K3(){return $T.i=0,$T}var Z8=v5,L3=1,V0=b().S().end(),j5=b().H().end(),D3=b().i32(8).i32(80877103).end(8),S3=Buffer.concat([b().E().str(b.N).i32(0).end(),V0]),I3=b().D().str("S").str(b.N).end(),HF=()=>{},N3=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),C3={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function v5(T,_={},{onopen:F=HF,onend:W=HF,onclose:J=HF}={}){let{ssl:Y,max:$,user:Z,host:G,port:X,database:O,parsers:M,transform:Q,onnotice:V,onnotify:B,onparameter:K,max_pipeline:v,keep_alive:q,backoff:j,target_session_attrs:y}=T,u=R_(),h=L3++,p={pid:null,secret:null},t=$8(i1,T.idle_timeout),ST=$8(i1,T.max_lifetime),A_=$8(JG,T.connect_timeout),D=null,ZT,i=new y0,TT=Buffer.alloc(0),bT=T.fetch_types,H_={},I_={},b0=Math.random().toString(36).slice(2),L=1,o=0,JT=0,zT=0,kT=0,n=0,YT=0,NT=0,KT=null,wT=null,gT=!1,HT=null,N_=null,hT=null,_0=null,fT=null,QT=null,C_=null,v_=null,C=null,wF=null,mT={queue:_.closed,idleTimer:t,connect(A){hT=A,y8()},terminate:RF,execute:QF,cancel:TG,end:i1,count:0,id:h};return _.closed&&_.closed.push(mT),mT;async function e5(){let A;try{A=T.socket?await Promise.resolve(T.socket(T)):new P5.Socket}catch(w){p0(w);return}return A.on("error",p0),A.on("close",v8),A.on("drain",q8),A}async function TG({pid:A,secret:w},g,_T){try{ZT=b().i32(16).i32(80877102).i32(A).i32(w).end(16),await j8(),D.once("error",_T),D.once("close",g)}catch(LT){_T(LT)}}function QF(A){if(gT)return IW(A,BT.connection("CONNECTION_DESTROYED",T));if(A.cancelled)return;try{return A.state=p,C?u.push(A):(C=A,C.active=!0),WG(A),pT(_G(A))&&!A.describeFirst&&!A.cursorFn&&u.length<v&&(!A.options.onexecute||A.options.onexecute(mT))}catch(w){return u.length===0&&pT(V0),x_(w),!0}}function _G(A){if(A.parameters.length>=65534)throw BT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return A.options.simple?b().Q().str(A.statement.string+b.N).end():A.describeFirst?Buffer.concat([k8(A),j5]):A.prepare?A.prepared?SW(A):Buffer.concat([k8(A),SW(A)]):FG(A)}function k8(A){return Buffer.concat([b8(A.statement.string,A.parameters,A.statement.types,A.statement.name),oG("S",A.statement.name)])}function SW(A){return Buffer.concat([mG(A.parameters,A.statement.types,A.statement.name,A.cursorName),A.cursorFn?h8("",A.cursorRows):S3])}function FG(A){return Buffer.concat([b8(A.statement.string,A.parameters,A.statement.types),I3,SW(A)])}function WG(A){let w=[],g=[],_T=s2(A,A.strings[0],A.args[0],w,g,T);!A.tagged&&A.args.forEach((LT)=>q1(LT,w,g,T)),A.prepare=T.prepare&&("prepare"in A.options?A.options.prepare:!0),A.string=_T,A.signature=A.prepare&&g+_T,A.onlyDescribe&&delete I_[A.signature],A.parameters=A.parameters||w,A.prepared=A.prepare&&A.signature in I_,A.describeFirst=A.onlyDescribe||w.length&&!A.prepared,A.statement=A.prepared?I_[A.signature]:{string:_T,types:g,name:A.prepare?b0+L++:""},typeof T.debug==="function"&&T.debug(h,_T,w,g)}function pT(A,w){if(QT=QT?Buffer.concat([QT,A]):Buffer.from(A),w||QT.length>=1024)return f8(w);return wT===null&&(wT=setImmediate(f8)),!0}function f8(A){let w=D.write(QT,A);return wT!==null&&clearImmediate(wT),QT=wT=null,w}function JG(){x_(BT.connection("CONNECT_TIMEOUT",T,D)),D.destroy()}async function P8(){if(pT(D3),!await new Promise((w)=>D.once("data",(g)=>w(g[0]===83)))&&Y==="prefer")return h0();D.removeAllListeners(),D=V3.connect({socket:D,servername:P5.isIP(D.host)?void 0:D.host,...Y==="require"||Y==="allow"||Y==="prefer"?{rejectUnauthorized:!1}:Y==="verify-full"?{}:typeof Y==="object"?Y:{}}),D.on("secureConnect",h0),D.on("error",p0),D.on("close",v8),D.on("drain",q8)}function q8(){!C&&F(mT)}function t1(A){if(HT){if(HT.push(A),JT-=A.length,JT>0)return}TT=HT?Buffer.concat(HT,n-JT):TT.length===0?A:Buffer.concat([TT,A],TT.length+A.length);while(TT.length>4){if(n=TT.readUInt32BE(1),n>=TT.length){JT=n-TT.length,HT=[TT];break}try{YG(TT.subarray(0,n+1))}catch(w){C&&(C.cursorFn||C.describeFirst)&&pT(V0),x_(w)}TT=TT.subarray(n+1),JT=0,HT=null}}async function j8(){if(gT=!1,H_={},D||(D=await e5()),!D)return;if(A_.start(),T.socket)return Y?P8():h0();if(D.on("connect",Y?P8:h0),T.path)return D.connect(T.path);D.ssl=Y,D.connect(X[zT],G[zT]),D.host=G[zT],D.port=X[zT],zT=(zT+1)%X.length}function y8(){setTimeout(j8,o?o+YT-q5.now():0)}function h0(){try{I_={},bT=T.fetch_types,b0=Math.random().toString(36).slice(2),L=1,ST.start(),D.on("data",t1),q&&D.setKeepAlive&&D.setKeepAlive(!0,1000*q);let A=cG();pT(A)}catch(A){p0(A)}}function p0(A){if(mT.queue===_.connecting&&T.host[kT+1])return;x_(A);while(u.length)IW(u.shift(),A)}function x_(A){fT&&(fT.destroy(A),fT=null),C&&IW(C,A),hT&&(IW(hT,A),hT=null)}function IW(A,w){if(A.reserve)return A.reject(w);if(!w||typeof w!=="object")w=new Error(w);"query"in w||"parameters"in w||Object.defineProperties(w,{stack:{value:w.stack+A.origin.replace(/.*\n/,`
|
|
50
|
+
`),enumerable:T.debug},query:{value:A.string,enumerable:T.debug},parameters:{value:A.parameters,enumerable:T.debug},args:{value:A.args,enumerable:T.debug},types:{value:A.statement&&A.statement.types,enumerable:T.debug}}),A.reject(w)}function i1(){return _0||(!mT.reserved&&W(mT),!mT.reserved&&!hT&&!C&&u.length===0?(RF(),new Promise((A)=>D&&D.readyState!=="closed"?D.once("close",A):A())):_0=new Promise((A)=>C_=A))}function RF(){if(gT=!0,fT||C||hT||u.length)p0(BT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(wT),D)D.removeListener("data",t1),D.removeListener("connect",h0),D.readyState==="open"&&D.end(b().X().end());C_&&(C_(),_0=C_=null)}async function v8(A){if(TT=Buffer.alloc(0),JT=0,HT=null,clearImmediate(wT),D.removeListener("data",t1),D.removeListener("connect",h0),t.cancel(),ST.cancel(),A_.cancel(),D.removeAllListeners(),D=null,hT)return y8();!A&&(C||u.length)&&p0(BT.connection("CONNECTION_CLOSED",T,D)),o=q5.now(),A&&T.shared.retries++,YT=(typeof j==="function"?j(T.shared.retries):j)*1000,J(mT,BT.connection("CONNECTION_CLOSED",T,D))}function YG(A,w=A[0]){(w===68?$G:w===100?jG:w===65?CG:w===83?ZG:w===90?XG:w===67?GG:w===50?x8:w===49?AG:w===116?HG:w===84?OG:w===82?UG:w===110?zG:w===75?KG:w===69?IG:w===115?BG:w===51?kG:w===71?fG:w===78?vG:w===72?PG:w===99?yG:w===73?xG:w===86?bG:w===118?hG:w===87?qG:pG)(A)}function $G(A){let w=7,g,_T,LT,oT=C.isRaw?new Array(C.statement.columns.length):{};for(let tT=0;tT<C.statement.columns.length;tT++)_T=C.statement.columns[tT],g=A.readInt32BE(w),w+=4,LT=g===-1?null:C.isRaw===!0?A.subarray(w,w+=g):_T.parser===void 0?A.toString("utf8",w,w+=g):_T.parser.array===!0?_T.parser(A.toString("utf8",w+1,w+=g)):_T.parser(A.toString("utf8",w,w+=g)),C.isRaw?oT[tT]=C.isRaw===!0?LT:Q.value.from?Q.value.from(LT,_T):LT:oT[_T.name]=Q.value.from?Q.value.from(LT,_T):LT;C.forEachFn?C.forEachFn(Q.row.from?Q.row.from(oT):oT,i):i[NT++]=Q.row.from?Q.row.from(oT):oT}function ZG(A){let[w,g]=A.toString("utf8",5,A.length-1).split(b.N);if(H_[w]=g,T.parameters[w]!==g)T.parameters[w]=g,K&&K(w,g)}function XG(A){if(C&&C.options.simple&&C.resolve(N_||i),C=N_=null,i=new y0,A_.cancel(),hT){if(y){if(!H_.in_hot_standby||!H_.default_transaction_read_only)return SG();else if(DG(y,H_))return RF()}if(bT)return hT.reserve&&(hT=null),VG();hT&&!hT.reserve&&QF(hT),T.shared.retries=kT=0,hT=null;return}while(u.length&&(C=u.shift())&&(C.active=!0,C.cancelled))v5(T).cancel(C.state,C.cancelled.resolve,C.cancelled.reject);if(C)return;mT.reserved?!mT.reserved.release&&A[5]===73?_0?RF():(mT.reserved=null,F(mT)):mT.reserved():_0?RF():F(mT)}function GG(A){NT=0;for(let w=A.length-1;w>0;w--){if(A[w]===32&&A[w+1]<58&&i.count===null)i.count=+A.toString("utf8",w+1,A.length-1);if(A[w-1]>=65){i.command=A.toString("utf8",5,w),i.state=p;break}}if(wF&&(wF(),wF=null),i.command==="BEGIN"&&$!==1&&!mT.reserved)return x_(BT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(C.options.simple)return x8();if(C.cursorFn)i.count&&C.cursorFn(i),pT(V0);C.resolve(i)}function AG(){C.parsing=!1}function x8(){!i.statement&&(i.statement=C.statement),i.columns=C.statement.columns}function HG(A){let w=A.readUInt16BE(5);for(let g=0;g<w;++g)!C.statement.types[g]&&(C.statement.types[g]=A.readUInt32BE(7+g*4));C.prepare&&(I_[C.signature]=C.statement),C.describeFirst&&!C.onlyDescribe&&(pT(SW(C)),C.describeFirst=!1)}function OG(A){if(i.command)N_=N_||[i],N_.push(i=new y0),i.count=null,C.statement.columns=null;let w=A.readUInt16BE(5),g=7,_T;C.statement.columns=Array(w);for(let LT=0;LT<w;++LT){_T=g;while(A[g++]!==0);let oT=A.readUInt32BE(g),tT=A.readUInt16BE(g+4),F0=A.readUInt32BE(g+6);C.statement.columns[LT]={name:Q.column.from?Q.column.from(A.toString("utf8",_T,g-1)):A.toString("utf8",_T,g-1),parser:M[F0],table:oT,number:tT,type:F0},g+=18}if(i.statement=C.statement,C.onlyDescribe)return C.resolve(C.statement),pT(V0)}async function UG(A,w=A.readUInt32BE(5)){(w===3?MG:w===5?wG:w===10?QG:w===11?RG:w===12?EG:w!==0?gG:HF)(A,w)}async function MG(){let A=await n1();pT(b().p().str(A).z(1).end())}async function wG(A){let w="md5"+await y5(Buffer.concat([Buffer.from(await y5(await n1()+Z)),A.subarray(9)]));pT(b().p().str(w).z(1).end())}async function QG(){v_=(await RW.randomBytes(18)).toString("base64"),b().p().str("SCRAM-SHA-256"+b.N);let A=b.i;pT(b.inc(4).str("n,,n=*,r="+v_).i32(b.i-A-4,A).end())}async function RG(A){let w=A.toString("utf8",9).split(",").reduce((tT,F0)=>(tT[F0[0]]=F0.slice(2),tT),{}),g=await RW.pbkdf2Sync(await n1(),Buffer.from(w.s,"base64"),parseInt(w.i),32,"sha256"),_T=await v1(g,"Client Key"),LT="n=*,r="+v_+",r="+w.r+",s="+w.s+",i="+w.i+",c=biws,r="+w.r;KT=(await v1(await v1(g,"Server Key"),LT)).toString("base64");let oT="c=biws,r="+w.r+",p="+k3(_T,Buffer.from(await v1(await B3(_T),LT))).toString("base64");pT(b().p().str(oT).end())}function EG(A){if(A.toString("utf8",9).split(b.N,1)[0].slice(2)===KT)return;x_(BT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),D.destroy()}function n1(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function zG(){if(i.statement=C.statement,i.statement.columns=[],C.onlyDescribe)return C.resolve(C.statement),pT(V0)}function KG(A){p.pid=A.readUInt32BE(5),p.secret=A.readUInt32BE(9)}async function VG(){bT=!1,(await new S_([`
|
|
51
51
|
select b.oid, b.typarray
|
|
52
52
|
from pg_catalog.pg_type a
|
|
53
53
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
@@ -57,7 +57,7 @@ ${$.trace}`:"No previous disposal trace was found."),W.type){case"atom_family":c
|
|
|
57
57
|
`],[],QF)).forEach(({oid:w,typarray:g})=>LG(w,g))}function LG(A,w){if(!!T.parsers[w]&&!!T.serializers[w])return;let g=T.parsers[A];T.shared.typeArrayMap[A]=w,T.parsers[w]=(_T)=>k5(_T,g,w),T.parsers[w].array=!0,T.serializers[w]=(_T)=>B5(_T,T.serializers[A],T,w)}function DG(A,w){return A==="read-write"&&w.default_transaction_read_only==="on"||A==="read-only"&&w.default_transaction_read_only==="off"||A==="primary"&&w.in_hot_standby==="on"||A==="standby"&&w.in_hot_standby==="off"||A==="prefer-standby"&&w.in_hot_standby==="off"&&T.host[kT]}function SG(){let A=new S_([`
|
|
58
58
|
show transaction_read_only;
|
|
59
59
|
select pg_catalog.pg_is_in_recovery()
|
|
60
|
-
`],[],QF,null,{simple:!0});A.resolve=([[w],[g]])=>{H_.default_transaction_read_only=w.transaction_read_only,H_.in_hot_standby=g.pg_is_in_recovery?"on":"off"},A.execute()}function IG(A){C&&(C.cursorFn||C.describeFirst)&&pT(
|
|
60
|
+
`],[],QF,null,{simple:!0});A.resolve=([[w],[g]])=>{H_.default_transaction_read_only=w.transaction_read_only,H_.in_hot_standby=g.pg_is_in_recovery?"on":"off"},A.execute()}function IG(A){C&&(C.cursorFn||C.describeFirst)&&pT(V0);let w=BT.postgres(Y8(A));C&&C.retried?x_(C.retried):C&&C.prepared&&N3.has(w.routine)?NG(C,w):x_(w)}function NG(A,w){delete I_[A.signature],A.retried=w,QF(A)}function CG(A){if(!B)return;let w=9;while(A[w++]!==0);B(A.toString("utf8",9,w-1),A.toString("utf8",w,A.length-1))}async function BG(){try{let A=await Promise.resolve(C.cursorFn(i));NT=0,A===GF?pT(uG(C.portal)):(i=new y0,pT(h8("",C.cursorRows)))}catch(A){pT(V0),C.reject(A)}}function kG(){i.count&&C.cursorFn(i),C.resolve(i)}function fG(){fT=new J8.Writable({autoDestroy:!0,write(A,w,g){D.write(b().d().raw(A).end(),g)},destroy(A,w){w(A),D.write(b().f().str(A+b.N).end()),fT=null},final(A){D.write(b().c().end()),wF=A}}),C.resolve(fT)}function PG(){fT=new J8.Readable({read(){D.resume()}}),C.resolve(fT)}function qG(){fT=new J8.Duplex({autoDestroy:!0,read(){D.resume()},write(A,w,g){D.write(b().d().raw(A).end(),g)},destroy(A,w){w(A),D.write(b().f().str(A+b.N).end()),fT=null},final(A){D.write(b().c().end()),wF=A}}),C.resolve(fT)}function jG(A){fT&&(fT.push(A.subarray(5))||D.pause())}function yG(){fT&&fT.push(null),fT=null}function vG(A){V?V(Y8(A)):console.log(Y8(A))}function xG(){}function bG(){x_(BT.notSupported("FunctionCallResponse"))}function hG(){x_(BT.notSupported("NegotiateProtocolVersion"))}function pG(A){console.error("Postgres.js : Unknown Message:",A[0])}function gG(A,w){console.error("Postgres.js : Unknown Auth:",w)}function mG(A,w,g="",_T=""){let LT,oT;return b().B().str(_T+b.N).str(g+b.N).i16(0).i16(A.length),A.forEach((tT,F0)=>{if(tT===null)return b.i32(4294967295);oT=w[F0],A[F0]=tT=oT in T.serializers?T.serializers[oT](tT):""+tT,LT=b.i,b.inc(4).str(tT).i32(b.i-LT-4,LT)}),b.i16(0),b.end()}function b8(A,w,g,_T=""){return b().P().str(_T+b.N).str(A+b.N).i16(w.length),w.forEach((LT,oT)=>b.i32(g[oT]||0)),b.end()}function oG(A,w=""){return b().D().str(A).str(w+b.N).end()}function h8(A="",w=0){return Buffer.concat([b().E().str(A+b.N).i32(w).end(),j5])}function uG(A=""){return Buffer.concat([b().C().str("P").str(A+b.N).end(),b().S().end()])}function cG(){return ZT||b().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:Z,database:O,client_encoding:"UTF8"},T.connection)).filter(([,A])=>A).map(([A,w])=>A+b.N+w).join(b.N)).z(2).end(0)}}function Y8(T){let _={},F=5;for(let W=5;W<T.length-1;W++)if(T[W]===0)_[C3[T[F]]]=T.toString("utf8",F+1,W),F=W+1;return _}function y5(T){return RW.createHash("md5").update(T).digest("hex")}function v1(T,_){return RW.createHmac("sha256",T).update(_).digest()}function B3(T){return RW.createHash("sha256").update(T).digest()}function k3(T,_){let F=Math.max(T.length,_.length),W=Buffer.allocUnsafe(F);for(let J=0;J<F;J++)W[J]=T[J]^_[J];return W}function $8(T,_){if(_=typeof _==="function"?_():_,!_)return{cancel:HF,start:HF};let F;return{cancel(){F&&(clearTimeout(F),F=null)},start(){F&&clearTimeout(F),F=setTimeout(W,_*1000,arguments)}};function W(J){T.apply(null,J),F=null}}var x5=()=>{};function X8(T,_){let F=new Map,W="postgresjs_"+Math.random().toString(36).slice(2),J={},Y,$,Z=!1,G=M.sql=T({..._,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{..._.connection,replication:"database"},onclose:async function(){if(Z)return;$=null,J.pid=J.secret=void 0,Q(await V(G,W,_.publications)),F.forEach((K)=>K.forEach(({onsubscribe:v})=>v()))},no_subscribe:!0}),X=G.end,O=G.close;return G.end=async()=>{return Z=!0,$&&await new Promise((K)=>($.once("close",K),$.end())),X()},G.close=async()=>{return $&&await new Promise((K)=>($.once("close",K),$.end())),O()},M;async function M(K,v,q=x5,j=x5){if(K=q3(K),!Y)Y=V(G,W,_.publications);let y={fn:v,onsubscribe:q},u=F.has(K)?F.get(K).add(y):F.set(K,new Set([y])).get(K),h=()=>{u.delete(y),u.size===0&&F.delete(K)};return Y.then((p)=>{return Q(p),q(),$&&$.on("error",j),{unsubscribe:h,state:J,sql:G}})}function Q(K){$=K.stream,J.pid=K.state.pid,J.secret=K.state.secret}async function V(K,v,q){if(!q)throw new Error("Missing publication names");let j=await K.unsafe(`CREATE_REPLICATION_SLOT ${v} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[y]=j,u=await K.unsafe(`START_REPLICATION SLOT ${v} LOGICAL ${y.consistent_point} (proto_version '1', publication_names '${q}')`).writable(),h={lsn:Buffer.concat(y.consistent_point.split("/").map((D)=>Buffer.from(("00000000"+D).slice(-8),"hex")))};return u.on("data",t),u.on("error",p),u.on("close",K.close),{stream:u,state:j.state};function p(D){console.error("Unexpected error during logical streaming - reconnecting",D)}function t(D){if(D[0]===119)P3(D.subarray(25),h,K.options.parsers,ST,_.transform);else if(D[0]===107&&D[17])h.lsn=D.subarray(1,9),A_()}function ST(D,ZT){let i=ZT.relation.schema+"."+ZT.relation.table;B("*",D,ZT),B("*:"+i,D,ZT),ZT.relation.keys.length&&B("*:"+i+"="+ZT.relation.keys.map((TT)=>D[TT.name]),D,ZT),B(ZT.command,D,ZT),B(ZT.command+":"+i,D,ZT),ZT.relation.keys.length&&B(ZT.command+":"+i+"="+ZT.relation.keys.map((TT)=>D[TT.name]),D,ZT)}function A_(){let D=Buffer.alloc(34);D[0]=114,D.fill(h.lsn,1),D.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),u.write(D)}}function B(K,v,q){F.has(K)&&F.get(K).forEach(({fn:j})=>j(v,q,K))}}function f3(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function P3(T,_,F,W,J){let Y=($,[Z,G])=>($[Z.charCodeAt(0)]=G,$);Object.entries({R:($)=>{let Z=1,G=_[$.readUInt32BE(Z)]={schema:$.toString("utf8",Z+=4,Z=$.indexOf(0,Z))||"pg_catalog",table:$.toString("utf8",Z+1,Z=$.indexOf(0,Z+1)),columns:Array($.readUInt16BE(Z+=2)),keys:[]};Z+=2;let X=0,O;while(Z<$.length)O=G.columns[X++]={key:$[Z++],name:J.column.from?J.column.from($.toString("utf8",Z,Z=$.indexOf(0,Z))):$.toString("utf8",Z,Z=$.indexOf(0,Z)),type:$.readUInt32BE(Z+=1),parser:F[$.readUInt32BE(Z)],atttypmod:$.readUInt32BE(Z+=4)},O.key&&G.keys.push(O),Z+=4},Y:()=>{},O:()=>{},B:($)=>{_.date=f3($.readBigInt64BE(9)),_.lsn=$.subarray(1,9)},I:($)=>{let Z=1,G=_[$.readUInt32BE(Z)],{row:X}=x1($,G.columns,Z+=7,J);W(X,{command:"insert",relation:G})},D:($)=>{let Z=1,G=_[$.readUInt32BE(Z)];Z+=4;let X=$[Z]===75;W(X||$[Z]===79?x1($,G.columns,Z+=3,J).row:null,{command:"delete",relation:G,key:X})},U:($)=>{let Z=1,G=_[$.readUInt32BE(Z)];Z+=4;let X=$[Z]===75,O=X||$[Z]===79?x1($,G.columns,Z+=3,J):null;O&&(Z=O.i);let{row:M}=x1($,G.columns,Z+3,J);W(M,{command:"update",relation:G,key:X,old:O&&O.row})},T:()=>{},C:()=>{}}).reduce(Y,{})[T[0]](T)}function x1(T,_,F,W){let J,Y,$,Z=W.raw?new Array(_.length):{};for(let G=0;G<_.length;G++)J=T[F++],Y=_[G],$=J===110?null:J===117?void 0:Y.parser===void 0?T.toString("utf8",F+4,F+=4+T.readUInt32BE(F)):Y.parser.array===!0?Y.parser(T.toString("utf8",F+5,F+=4+T.readUInt32BE(F))):Y.parser(T.toString("utf8",F+4,F+=4+T.readUInt32BE(F))),W.raw?Z[G]=W.raw===!0?$:W.value.from?W.value.from($,Y):$:Z[Y.name]=W.value.from?W.value.from($,Y):$;return{i:F,row:W.row.from?W.row.from(Z):Z}}function q3(T){let _=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!_)throw new Error("Malformed subscribe pattern: "+T);let[,F,W,J]=_;return(F||"*")+(W?":"+(W.indexOf(".")===-1?"public."+W:W):"")+(J?"="+J:"")}import b5 from"stream";function G8(T,_,F=393216){return new Promise(async(W,J)=>{await T.begin(async(Y)=>{let $;!_&&([{oid:_}]=await Y`select lo_creat(-1) as oid`);let[{fd:Z}]=await Y`select lo_open(${_}, ${F}) as fd`,G={writable:O,readable:X,close:()=>Y`select lo_close(${Z})`.then($),tell:()=>Y`select lo_tell64(${Z})`,read:(M)=>Y`select loread(${Z}, ${M}) as data`,write:(M)=>Y`select lowrite(${Z}, ${M})`,truncate:(M)=>Y`select lo_truncate64(${Z}, ${M})`,seek:(M,Q=0)=>Y`select lo_lseek64(${Z}, ${M}, ${Q})`,size:()=>Y`
|
|
61
61
|
select
|
|
62
62
|
lo_lseek64(${Z}, location, 0) as position,
|
|
63
63
|
seek.size
|
|
@@ -67,11 +67,11 @@ ${$.trace}`:"No previous disposal trace was found."),W.type){case"atom_family":c
|
|
|
67
67
|
tell.location
|
|
68
68
|
from (select lo_tell64($1) as location) tell
|
|
69
69
|
) seek
|
|
70
|
-
`};return W(G),new Promise(async(M)=>$=M);async function X({highWaterMark:M=16384,start:Q=0,end:K=1/0}={}){let B=K-Q;return Q&&await G.seek(Q),new b5.Readable({highWaterMark:M,async read(V){let v=V>B?V-B:V;B-=V;let[{data:q}]=await G.read(v);if(this.push(q),q.length<V)this.push(null)}})}async function O({highWaterMark:M=16384,start:Q=0}={}){return Q&&await G.seek(Q),new b5.Writable({highWaterMark:M,write(K,B,V){G.write(K).then(()=>V(),V)}})}}).catch(J)})}Object.assign(b1,{PostgresError:AF,toPascal:q0,pascal:F8,toCamel:P0,camel:_8,toKebab:j0,kebab:W8,fromPascal:MW,fromCamel:UW,fromKebab:wW,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var OF=b1;function b1(T,_){let F=v3(T,_),W=F.no_subscribe||X8(b1,{...F}),J=!1,Y=R_(),$=R_(),Z=R_(),G=R_(),X=R_(),O=R_(),M=R_(),Q=R_(),K={connecting:$,reserved:Z,closed:G,ended:X,open:O,busy:M,full:Q},B=[...Array(F.max)].map(()=>Z8(F,K,{onopen:I_,onend:H_,onclose:b0})),V=v(ST);return Object.assign(V,{get parameters(){return F.parameters},largeObject:G8.bind(null,V),subscribe:W,CLOSE:GF,END:GF,PostgresError:AF,options:F,reserve:y,listen:q,begin:u,close:i,end:ZT}),V;function v(L){return L.debug=F.debug,Object.entries(F.types).reduce((n,[YT,NT])=>{return n[YT]=(VT)=>new o_(VT,NT.to),n},o),Object.assign(JT,{types:o,typed:o,unsafe:zT,notify:j,array:t,json:p,file:kT}),JT;function o(n,YT){return new o_(n,YT)}function JT(n,...YT){return n&&Array.isArray(n.raw)?new S_(n,YT,L,D):typeof n==="string"&&!YT.length?new QW(F.transform.column.to?F.transform.column.to(n):n):new P1(n,YT)}function zT(n,YT=[],NT={}){return arguments.length===2&&!Array.isArray(YT)&&(NT=YT,YT=[]),new S_([n],YT,L,D,{prepare:!1,...NT,simple:"simple"in NT?NT.simple:YT.length===0})}function kT(n,YT=[],NT={}){return arguments.length===2&&!Array.isArray(YT)&&(NT=YT,YT=[]),new S_([],YT,(wT)=>{y3.readFile(n,"utf8",(gT,HT)=>{if(gT)return wT.reject(gT);wT.strings=[HT],L(wT)})},D,{...NT,simple:"simple"in NT?NT.simple:YT.length===0})}}async function q(L,o,JT){let zT={fn:o,onlisten:JT},kT=q.sql||(q.sql=b1({...F,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(q.channels).forEach(([wT,{listeners:gT}])=>{delete q.channels[wT],Promise.all(gT.map((HT)=>q(wT,HT.fn,HT.onlisten).catch(()=>{})))})},onnotify(wT,gT){wT in q.channels&&q.channels[wT].listeners.forEach((HT)=>HT.fn(gT))}})),n=q.channels||(q.channels={});if(L in n){n[L].listeners.push(zT);let wT=await n[L].result;return zT.onlisten&&zT.onlisten(),{state:wT.state,unlisten:VT}}n[L]={result:kT`listen ${kT.unsafe('"'+L.replace(/"/g,'""')+'"')}`,listeners:[zT]};let NT=await n[L].result;return zT.onlisten&&zT.onlisten(),{state:NT.state,unlisten:VT};async function VT(){if(L in n===!1)return;if(n[L].listeners=n[L].listeners.filter((wT)=>wT!==zT),n[L].listeners.length)return;return delete n[L],kT`unlisten ${kT.unsafe('"'+L.replace(/"/g,'""')+'"')}`}}async function j(L,o){return await V`select pg_notify(${L}, ${""+o})`}async function y(){let L=R_(),o=O.length?O.shift():await new Promise((kT,n)=>{let YT={reserve:kT,reject:n};Y.push(YT),G.length&&bT(G.shift(),YT)});h(o,Z),o.reserved=()=>L.length?o.execute(L.shift()):h(o,Z),o.reserved.release=!0;let JT=v(zT);return JT.release=()=>{o.reserved=null,I_(o)},JT;function zT(kT){o.queue===Q?L.push(kT):o.execute(kT)||h(o,Q)}}async function u(L,o){!o&&(o=L,L="");let JT=R_(),zT=0,kT,n=null;try{return await V.unsafe("begin "+L.replace(/[^a-z ]/ig,""),[],{onexecute:NT}).execute(),await Promise.race([YT(kT,o),new Promise((VT,wT)=>kT.onclose=wT)])}catch(VT){throw VT}async function YT(VT,wT,gT){let HT=v(fT);HT.savepoint=_0,HT.prepare=(QT)=>n=QT.replace(/[^a-z0-9$-_. ]/gi);let N_,hT;gT&&await HT`savepoint ${HT(gT)}`;try{if(hT=await new Promise((QT,C_)=>{let v_=wT(HT);Promise.resolve(Array.isArray(v_)?Promise.all(v_):v_).then(QT,C_)}),N_)throw N_}catch(QT){throw await(gT?HT`rollback to ${HT(gT)}`:HT`rollback`),QT instanceof AF&&QT.code==="25P02"&&N_||QT}if(!gT)n?await HT`prepare transaction '${HT.unsafe(n)}'`:await HT`commit`;return hT;function _0(QT,C_){if(QT&&Array.isArray(QT.raw))return _0((v_)=>v_.apply(v_,arguments));return arguments.length===1&&(C_=QT,QT=null),YT(VT,C_,"s"+zT+++(QT?"_"+QT:""))}function fT(QT){QT.catch((C_)=>N_||(N_=C_)),VT.queue===Q?JT.push(QT):VT.execute(QT)||h(VT,Q)}}function NT(VT){kT=VT,h(VT,Z),VT.reserved=()=>JT.length?VT.execute(JT.shift()):h(VT,Z)}}function h(L,o){return L.queue.remove(L),o.push(L),L.queue=o,o===O?L.idleTimer.start():L.idleTimer.cancel(),L}function p(L){return new o_(L,3802)}function t(L,o){if(!Array.isArray(L))return t(Array.from(arguments));return new o_(L,o||(L.length?k1(L)||25:0),F.shared.typeArrayMap)}function ST(L){if(J)return L.reject(BT.connection("CONNECTION_ENDED",F,F));if(O.length)return A_(O.shift(),L);if(G.length)return bT(G.shift(),L);M.length?A_(M.shift(),L):Y.push(L)}function A_(L,o){return L.execute(o)?h(L,M):h(L,Q)}function D(L){return new Promise((o,JT)=>{L.state?L.active?Z8(F).cancel(L.state,o,JT):L.cancelled={resolve:o,reject:JT}:(Y.remove(L),L.cancelled=!0,L.reject(BT.generic("57014","canceling statement due to user request")),o())})}async function ZT({timeout:L=null}={}){if(J)return J;await 1;let o;return J=Promise.race([new Promise((JT)=>L!==null&&(o=setTimeout(TT,L*1000,JT))),Promise.all(B.map((JT)=>JT.end()).concat(q.sql?q.sql.end({timeout:0}):[],W.sql?W.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(o))}async function i(){await Promise.all(B.map((L)=>L.end()))}async function TT(L){await Promise.all(B.map((o)=>o.terminate()));while(Y.length)Y.shift().reject(BT.connection("CONNECTION_DESTROYED",F));L()}function bT(L,o){return h(L,$),L.connect(o),L}function H_(L){h(L,X)}function I_(L){if(Y.length===0)return h(L,O);let o=Math.ceil(Y.length/($.length+1)),JT=!0;while(JT&&Y.length&&o-- >0){let zT=Y.shift();if(zT.reserve)return zT.reserve(L);JT=L.execute(zT)}JT?h(L,M):h(L,Q)}function b0(L,o){h(L,G),L.reserved=null,L.onclose&&(L.onclose(o),L.onclose=null),F.onclose&&F.onclose(L.id),Y.length&&bT(L,Y.shift())}}function v3(T,_){if(T&&T.shared)return T;let F=process.env,W=(!T||typeof T==="string"?_:T)||{},{url:J,multihost:Y}=g3(T),$=[...J.searchParams].reduce((Q,[K,B])=>(Q[K]=B,Q),{}),Z=W.hostname||W.host||Y||J.hostname||F.PGHOST||"localhost",G=W.port||J.port||F.PGPORT||5432,X=W.user||W.username||J.username||F.PGUSERNAME||F.PGUSER||m3();W.no_prepare&&(W.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in W&&(console.log("The timeout option is deprecated, use idle_timeout instead"),W.idle_timeout=W.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let O=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],M={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:h3,max_pipeline:100,backoff:b3,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(Z)?Z:Z.split(",").map((Q)=>Q.split(":")[0]),port:Array.isArray(G)?G:Z.split(",").map((Q)=>parseInt(Q.split(":")[1]||G)),path:W.path||Z.indexOf("/")>-1&&Z+"/.s.PGSQL."+G,database:W.database||W.db||(J.pathname||"").slice(1)||F.PGDATABASE||X,user:X,pass:W.pass||W.password||J.password||F.PGPASSWORD||"",...Object.entries(M).reduce((Q,[K,B])=>{let V=K in W?W[K]:(K in $)?$[K]==="disable"||$[K]==="false"?!1:$[K]:F["PG"+K.toUpperCase()]||B;return Q[K]=typeof V==="string"&&O.includes(K)?+V:V,Q},{}),connection:{application_name:F.PGAPPNAME||"postgres.js",...W.connection,...Object.entries($).reduce((Q,[K,B])=>((K in M)||(Q[K]=B),Q),{})},types:W.types||{},target_session_attrs:x3(W,J,F),onnotice:W.onnotice,onnotify:W.onnotify,onclose:W.onclose,onparameter:W.onparameter,socket:W.socket,transform:p3(W.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...N5(W.types)}}function x3(T,_,F){let W=T.target_session_attrs||_.searchParams.get("target_session_attrs")||F.PGTARGETSESSIONATTRS;if(!W||["read-write","read-only","primary","standby","prefer-standby"].includes(W))return W;throw new Error("target_session_attrs "+W+" is not supported")}function b3(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function h3(){return 60*(30+Math.random()*30)}function p3(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function g3(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let _=T;_=_.slice(_.indexOf("://")+3).split(/[?/]/)[0],_=decodeURIComponent(_.slice(_.indexOf("@")+1));let F=new URL(T.replace(_,_.split(",")[0]));return{url:{username:decodeURIComponent(F.username),password:decodeURIComponent(F.password),host:F.host,hostname:F.hostname,port:F.port,pathname:F.pathname,searchParams:F.searchParams},multihost:_.indexOf(",")>-1&&_}}function m3(){try{return j3.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class DT{static[H]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,_){if(_==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(_===MT)return{...T[MT],selectedFields:new Proxy(T[MT].selectedFields,this)};if(typeof _==="symbol")return T[_];let W=(R(T,IT)?T._.selectedFields:R(T,Z_)?T[MT].selectedFields:T)[_];if(R(W,k.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!W.isSelectionField)return W.sql;let J=W.clone();return J.isSelectionField=!0,J}if(R(W,k)){if(this.config.sqlBehavior==="sql")return W;throw new Error(`You tried to reference "${_}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(R(W,GT)){if(this.config.alias)return new Proxy(W,new XF(new Proxy(W.table,new YW(this.config.alias,this.config.replaceOriginalName??!1))));return W}if(typeof W!=="object"||W===null)return W;return new Proxy(W,new DT(this.config))}}class h5{constructor(T,_){this.unique=T,this.name=_}static[H]="PgIndexBuilderOn";on(...T){return new h1(T.map((_)=>{if(R(_,k))return _;_=_;let F=new _W(_.name,!!_.keyAsName,_.columnType,_.indexConfig);return _.indexConfig=JSON.parse(JSON.stringify(_.defaultConfig)),F}),this.unique,!1,this.name)}onOnly(...T){return new h1(T.map((_)=>{if(R(_,k))return _;_=_;let F=new _W(_.name,!!_.keyAsName,_.columnType,_.indexConfig);return _.indexConfig=_.defaultConfig,F}),this.unique,!0,this.name)}using(T,..._){return new h1(_.map((F)=>{if(R(F,k))return F;F=F;let W=new _W(F.name,!!F.keyAsName,F.columnType,F.indexConfig);return F.indexConfig=JSON.parse(JSON.stringify(F.defaultConfig)),W}),this.unique,!0,this.name,T)}}class h1{static[H]="PgIndexBuilder";config;constructor(T,_,F,W,J="btree"){this.config={name:W,columns:T,unique:_,only:F,method:J}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new p5(this.config,T)}}class p5{static[H]="PgIndex";config;constructor(T,_){this.config={...T,table:_}}}function A8(T){return new h5(!0,T)}function o3(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((F)=>F.toLowerCase()).join("_")}function u3(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((F,W,J)=>{let Y=J===0?W.toLowerCase():`${W[0].toUpperCase()}${W.slice(1)}`;return F+Y},"")}function c3(T){return T}class H8{static[H]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?o3:T==="camelCase"?u3:c3}getColumnCasing(T){if(!T.keyAsName)return T.name;let _=T.table[I.Symbol.Schema]??"public",F=T.table[I.Symbol.OriginalName],W=`${_}.${F}.${T.name}`;if(!this.cache[W])this.cacheTable(T.table);return this.cache[W]}cacheTable(T){let _=T[I.Symbol.Schema]??"public",F=T[I.Symbol.OriginalName],W=`${_}.${F}`;if(!this.cachedTables[W]){for(let J of Object.values(T[I.Symbol.Columns])){let Y=`${W}.${J.name}`;this.cache[Y]=this.convert(J.name)}this.cachedTables[W]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class EW extends Z_{static[H]="PgViewBase"}class v0{static[H]="PgDialect";casing;constructor(T){this.casing=new H8(T?.casing)}async migrate(T,_,F){let W=typeof F==="string"?"__drizzle_migrations":F.migrationsTable??"__drizzle_migrations",J=typeof F==="string"?"drizzle":F.migrationsSchema??"drizzle",Y=U`
|
|
70
|
+
`};return W(G),new Promise(async(M)=>$=M);async function X({highWaterMark:M=16384,start:Q=0,end:V=1/0}={}){let B=V-Q;return Q&&await G.seek(Q),new b5.Readable({highWaterMark:M,async read(K){let v=K>B?K-B:K;B-=K;let[{data:q}]=await G.read(v);if(this.push(q),q.length<K)this.push(null)}})}async function O({highWaterMark:M=16384,start:Q=0}={}){return Q&&await G.seek(Q),new b5.Writable({highWaterMark:M,write(V,B,K){G.write(V).then(()=>K(),K)}})}}).catch(J)})}Object.assign(b1,{PostgresError:AF,toPascal:q0,pascal:F8,toCamel:P0,camel:_8,toKebab:j0,kebab:W8,fromPascal:MW,fromCamel:UW,fromKebab:wW,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var OF=b1;function b1(T,_){let F=v3(T,_),W=F.no_subscribe||X8(b1,{...F}),J=!1,Y=R_(),$=R_(),Z=R_(),G=R_(),X=R_(),O=R_(),M=R_(),Q=R_(),V={connecting:$,reserved:Z,closed:G,ended:X,open:O,busy:M,full:Q},B=[...Array(F.max)].map(()=>Z8(F,V,{onopen:I_,onend:H_,onclose:b0})),K=v(ST);return Object.assign(K,{get parameters(){return F.parameters},largeObject:G8.bind(null,K),subscribe:W,CLOSE:GF,END:GF,PostgresError:AF,options:F,reserve:y,listen:q,begin:u,close:i,end:ZT}),K;function v(L){return L.debug=F.debug,Object.entries(F.types).reduce((n,[YT,NT])=>{return n[YT]=(KT)=>new o_(KT,NT.to),n},o),Object.assign(JT,{types:o,typed:o,unsafe:zT,notify:j,array:t,json:p,file:kT}),JT;function o(n,YT){return new o_(n,YT)}function JT(n,...YT){return n&&Array.isArray(n.raw)?new S_(n,YT,L,D):typeof n==="string"&&!YT.length?new QW(F.transform.column.to?F.transform.column.to(n):n):new P1(n,YT)}function zT(n,YT=[],NT={}){return arguments.length===2&&!Array.isArray(YT)&&(NT=YT,YT=[]),new S_([n],YT,L,D,{prepare:!1,...NT,simple:"simple"in NT?NT.simple:YT.length===0})}function kT(n,YT=[],NT={}){return arguments.length===2&&!Array.isArray(YT)&&(NT=YT,YT=[]),new S_([],YT,(wT)=>{y3.readFile(n,"utf8",(gT,HT)=>{if(gT)return wT.reject(gT);wT.strings=[HT],L(wT)})},D,{...NT,simple:"simple"in NT?NT.simple:YT.length===0})}}async function q(L,o,JT){let zT={fn:o,onlisten:JT},kT=q.sql||(q.sql=b1({...F,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(q.channels).forEach(([wT,{listeners:gT}])=>{delete q.channels[wT],Promise.all(gT.map((HT)=>q(wT,HT.fn,HT.onlisten).catch(()=>{})))})},onnotify(wT,gT){wT in q.channels&&q.channels[wT].listeners.forEach((HT)=>HT.fn(gT))}})),n=q.channels||(q.channels={});if(L in n){n[L].listeners.push(zT);let wT=await n[L].result;return zT.onlisten&&zT.onlisten(),{state:wT.state,unlisten:KT}}n[L]={result:kT`listen ${kT.unsafe('"'+L.replace(/"/g,'""')+'"')}`,listeners:[zT]};let NT=await n[L].result;return zT.onlisten&&zT.onlisten(),{state:NT.state,unlisten:KT};async function KT(){if(L in n===!1)return;if(n[L].listeners=n[L].listeners.filter((wT)=>wT!==zT),n[L].listeners.length)return;return delete n[L],kT`unlisten ${kT.unsafe('"'+L.replace(/"/g,'""')+'"')}`}}async function j(L,o){return await K`select pg_notify(${L}, ${""+o})`}async function y(){let L=R_(),o=O.length?O.shift():await new Promise((kT,n)=>{let YT={reserve:kT,reject:n};Y.push(YT),G.length&&bT(G.shift(),YT)});h(o,Z),o.reserved=()=>L.length?o.execute(L.shift()):h(o,Z),o.reserved.release=!0;let JT=v(zT);return JT.release=()=>{o.reserved=null,I_(o)},JT;function zT(kT){o.queue===Q?L.push(kT):o.execute(kT)||h(o,Q)}}async function u(L,o){!o&&(o=L,L="");let JT=R_(),zT=0,kT,n=null;try{return await K.unsafe("begin "+L.replace(/[^a-z ]/ig,""),[],{onexecute:NT}).execute(),await Promise.race([YT(kT,o),new Promise((KT,wT)=>kT.onclose=wT)])}catch(KT){throw KT}async function YT(KT,wT,gT){let HT=v(fT);HT.savepoint=_0,HT.prepare=(QT)=>n=QT.replace(/[^a-z0-9$-_. ]/gi);let N_,hT;gT&&await HT`savepoint ${HT(gT)}`;try{if(hT=await new Promise((QT,C_)=>{let v_=wT(HT);Promise.resolve(Array.isArray(v_)?Promise.all(v_):v_).then(QT,C_)}),N_)throw N_}catch(QT){throw await(gT?HT`rollback to ${HT(gT)}`:HT`rollback`),QT instanceof AF&&QT.code==="25P02"&&N_||QT}if(!gT)n?await HT`prepare transaction '${HT.unsafe(n)}'`:await HT`commit`;return hT;function _0(QT,C_){if(QT&&Array.isArray(QT.raw))return _0((v_)=>v_.apply(v_,arguments));return arguments.length===1&&(C_=QT,QT=null),YT(KT,C_,"s"+zT+++(QT?"_"+QT:""))}function fT(QT){QT.catch((C_)=>N_||(N_=C_)),KT.queue===Q?JT.push(QT):KT.execute(QT)||h(KT,Q)}}function NT(KT){kT=KT,h(KT,Z),KT.reserved=()=>JT.length?KT.execute(JT.shift()):h(KT,Z)}}function h(L,o){return L.queue.remove(L),o.push(L),L.queue=o,o===O?L.idleTimer.start():L.idleTimer.cancel(),L}function p(L){return new o_(L,3802)}function t(L,o){if(!Array.isArray(L))return t(Array.from(arguments));return new o_(L,o||(L.length?k1(L)||25:0),F.shared.typeArrayMap)}function ST(L){if(J)return L.reject(BT.connection("CONNECTION_ENDED",F,F));if(O.length)return A_(O.shift(),L);if(G.length)return bT(G.shift(),L);M.length?A_(M.shift(),L):Y.push(L)}function A_(L,o){return L.execute(o)?h(L,M):h(L,Q)}function D(L){return new Promise((o,JT)=>{L.state?L.active?Z8(F).cancel(L.state,o,JT):L.cancelled={resolve:o,reject:JT}:(Y.remove(L),L.cancelled=!0,L.reject(BT.generic("57014","canceling statement due to user request")),o())})}async function ZT({timeout:L=null}={}){if(J)return J;await 1;let o;return J=Promise.race([new Promise((JT)=>L!==null&&(o=setTimeout(TT,L*1000,JT))),Promise.all(B.map((JT)=>JT.end()).concat(q.sql?q.sql.end({timeout:0}):[],W.sql?W.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(o))}async function i(){await Promise.all(B.map((L)=>L.end()))}async function TT(L){await Promise.all(B.map((o)=>o.terminate()));while(Y.length)Y.shift().reject(BT.connection("CONNECTION_DESTROYED",F));L()}function bT(L,o){return h(L,$),L.connect(o),L}function H_(L){h(L,X)}function I_(L){if(Y.length===0)return h(L,O);let o=Math.ceil(Y.length/($.length+1)),JT=!0;while(JT&&Y.length&&o-- >0){let zT=Y.shift();if(zT.reserve)return zT.reserve(L);JT=L.execute(zT)}JT?h(L,M):h(L,Q)}function b0(L,o){h(L,G),L.reserved=null,L.onclose&&(L.onclose(o),L.onclose=null),F.onclose&&F.onclose(L.id),Y.length&&bT(L,Y.shift())}}function v3(T,_){if(T&&T.shared)return T;let F=process.env,W=(!T||typeof T==="string"?_:T)||{},{url:J,multihost:Y}=g3(T),$=[...J.searchParams].reduce((Q,[V,B])=>(Q[V]=B,Q),{}),Z=W.hostname||W.host||Y||J.hostname||F.PGHOST||"localhost",G=W.port||J.port||F.PGPORT||5432,X=W.user||W.username||J.username||F.PGUSERNAME||F.PGUSER||m3();W.no_prepare&&(W.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in W&&(console.log("The timeout option is deprecated, use idle_timeout instead"),W.idle_timeout=W.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let O=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],M={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:h3,max_pipeline:100,backoff:b3,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(Z)?Z:Z.split(",").map((Q)=>Q.split(":")[0]),port:Array.isArray(G)?G:Z.split(",").map((Q)=>parseInt(Q.split(":")[1]||G)),path:W.path||Z.indexOf("/")>-1&&Z+"/.s.PGSQL."+G,database:W.database||W.db||(J.pathname||"").slice(1)||F.PGDATABASE||X,user:X,pass:W.pass||W.password||J.password||F.PGPASSWORD||"",...Object.entries(M).reduce((Q,[V,B])=>{let K=V in W?W[V]:(V in $)?$[V]==="disable"||$[V]==="false"?!1:$[V]:F["PG"+V.toUpperCase()]||B;return Q[V]=typeof K==="string"&&O.includes(V)?+K:K,Q},{}),connection:{application_name:F.PGAPPNAME||"postgres.js",...W.connection,...Object.entries($).reduce((Q,[V,B])=>((V in M)||(Q[V]=B),Q),{})},types:W.types||{},target_session_attrs:x3(W,J,F),onnotice:W.onnotice,onnotify:W.onnotify,onclose:W.onclose,onparameter:W.onparameter,socket:W.socket,transform:p3(W.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...N5(W.types)}}function x3(T,_,F){let W=T.target_session_attrs||_.searchParams.get("target_session_attrs")||F.PGTARGETSESSIONATTRS;if(!W||["read-write","read-only","primary","standby","prefer-standby"].includes(W))return W;throw new Error("target_session_attrs "+W+" is not supported")}function b3(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function h3(){return 60*(30+Math.random()*30)}function p3(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function g3(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let _=T;_=_.slice(_.indexOf("://")+3).split(/[?/]/)[0],_=decodeURIComponent(_.slice(_.indexOf("@")+1));let F=new URL(T.replace(_,_.split(",")[0]));return{url:{username:decodeURIComponent(F.username),password:decodeURIComponent(F.password),host:F.host,hostname:F.hostname,port:F.port,pathname:F.pathname,searchParams:F.searchParams},multihost:_.indexOf(",")>-1&&_}}function m3(){try{return j3.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class DT{static[H]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,_){if(_==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(_===MT)return{...T[MT],selectedFields:new Proxy(T[MT].selectedFields,this)};if(typeof _==="symbol")return T[_];let W=(R(T,IT)?T._.selectedFields:R(T,Z_)?T[MT].selectedFields:T)[_];if(R(W,k.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!W.isSelectionField)return W.sql;let J=W.clone();return J.isSelectionField=!0,J}if(R(W,k)){if(this.config.sqlBehavior==="sql")return W;throw new Error(`You tried to reference "${_}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(R(W,GT)){if(this.config.alias)return new Proxy(W,new XF(new Proxy(W.table,new YW(this.config.alias,this.config.replaceOriginalName??!1))));return W}if(typeof W!=="object"||W===null)return W;return new Proxy(W,new DT(this.config))}}class h5{constructor(T,_){this.unique=T,this.name=_}static[H]="PgIndexBuilderOn";on(...T){return new h1(T.map((_)=>{if(R(_,k))return _;_=_;let F=new _W(_.name,!!_.keyAsName,_.columnType,_.indexConfig);return _.indexConfig=JSON.parse(JSON.stringify(_.defaultConfig)),F}),this.unique,!1,this.name)}onOnly(...T){return new h1(T.map((_)=>{if(R(_,k))return _;_=_;let F=new _W(_.name,!!_.keyAsName,_.columnType,_.indexConfig);return _.indexConfig=_.defaultConfig,F}),this.unique,!0,this.name)}using(T,..._){return new h1(_.map((F)=>{if(R(F,k))return F;F=F;let W=new _W(F.name,!!F.keyAsName,F.columnType,F.indexConfig);return F.indexConfig=JSON.parse(JSON.stringify(F.defaultConfig)),W}),this.unique,!0,this.name,T)}}class h1{static[H]="PgIndexBuilder";config;constructor(T,_,F,W,J="btree"){this.config={name:W,columns:T,unique:_,only:F,method:J}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new p5(this.config,T)}}class p5{static[H]="PgIndex";config;constructor(T,_){this.config={...T,table:_}}}function A8(T){return new h5(!0,T)}function o3(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((F)=>F.toLowerCase()).join("_")}function u3(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((F,W,J)=>{let Y=J===0?W.toLowerCase():`${W[0].toUpperCase()}${W.slice(1)}`;return F+Y},"")}function c3(T){return T}class H8{static[H]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?o3:T==="camelCase"?u3:c3}getColumnCasing(T){if(!T.keyAsName)return T.name;let _=T.table[I.Symbol.Schema]??"public",F=T.table[I.Symbol.OriginalName],W=`${_}.${F}.${T.name}`;if(!this.cache[W])this.cacheTable(T.table);return this.cache[W]}cacheTable(T){let _=T[I.Symbol.Schema]??"public",F=T[I.Symbol.OriginalName],W=`${_}.${F}`;if(!this.cachedTables[W]){for(let J of Object.values(T[I.Symbol.Columns])){let Y=`${W}.${J.name}`;this.cache[Y]=this.convert(J.name)}this.cachedTables[W]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class EW extends Z_{static[H]="PgViewBase"}class v0{static[H]="PgDialect";casing;constructor(T){this.casing=new H8(T?.casing)}async migrate(T,_,F){let W=typeof F==="string"?"__drizzle_migrations":F.migrationsTable??"__drizzle_migrations",J=typeof F==="string"?"drizzle":F.migrationsSchema??"drizzle",Y=U`
|
|
71
71
|
CREATE TABLE IF NOT EXISTS ${U.identifier(J)}.${U.identifier(W)} (
|
|
72
72
|
id SERIAL PRIMARY KEY,
|
|
73
73
|
hash text NOT NULL,
|
|
74
74
|
created_at bigint
|
|
75
75
|
)
|
|
76
|
-
`;await _.execute(U`CREATE SCHEMA IF NOT EXISTS ${U.identifier(J)}`),await _.execute(Y);let Z=(await _.all(U`select id, hash, created_at from ${U.identifier(J)}.${U.identifier(W)} order by created_at desc limit 1`))[0];await _.transaction(async(G)=>{for await(let X of T)if(!Z||Number(Z.created_at)<X.folderMillis){for(let O of X.sql)await G.execute(U.raw(O));await G.execute(U`insert into ${U.identifier(J)}.${U.identifier(W)} ("hash", "created_at") values(${X.hash}, ${X.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let _=[U`with `];for(let[F,W]of T.entries())if(_.push(U`${U.identifier(W._.alias)} as (${W._.sql})`),F<T.length-1)_.push(U`, `);return _.push(U` `),U.join(_)}buildDeleteQuery({table:T,where:_,returning:F,withList:W}){let J=this.buildWithCTE(W),Y=F?U` returning ${this.buildSelection(F,{isSingleTable:!0})}`:void 0,$=_?U` where ${_}`:void 0;return U`${J}delete from ${T}${$}${Y}`}buildUpdateSet(T,_){let F=T[I.Symbol.Columns],W=Object.keys(F).filter((Y)=>_[Y]!==void 0||F[Y]?.onUpdateFn!==void 0),J=W.length;return U.join(W.flatMap((Y,$)=>{let Z=F[Y],G=_[Y]??U.param(Z.onUpdateFn(),Z),X=U`${U.identifier(this.casing.getColumnCasing(Z))} = ${G}`;if($<J-1)return[X,U.raw(", ")];return[X]}))}buildUpdateQuery({table:T,set:_,where:F,returning:W,withList:J,from:Y,joins:$}){let Z=this.buildWithCTE(J),G=T[vT.Symbol.Name],X=T[vT.Symbol.Schema],O=T[vT.Symbol.OriginalName],M=G===O?void 0:G,Q=U`${X?U`${U.identifier(X)}.`:void 0}${U.identifier(O)}${M&&U` ${U.identifier(M)}`}`,K=this.buildUpdateSet(T,_),B=Y&&U.join([U.raw(" from "),this.buildFromTable(Y)]),V=this.buildJoins($),v=W?U` returning ${this.buildSelection(W,{isSingleTable:!Y})}`:void 0,q=F?U` where ${F}`:void 0;return U`${Z}update ${Q} set ${K}${B}${V}${q}${v}`}buildSelection(T,{isSingleTable:_=!1}={}){let F=T.length,W=T.flatMap(({field:J},Y)=>{let $=[];if(R(J,k.Aliased)&&J.isSelectionField)$.push(U.identifier(J.fieldAlias));else if(R(J,k.Aliased)||R(J,k)){let Z=R(J,k.Aliased)?J.sql:J;if(_)$.push(new k(Z.queryChunks.map((G)=>{if(R(G,S))return U.identifier(this.casing.getColumnCasing(G));return G})));else $.push(Z);if(R(J,k.Aliased))$.push(U` as ${U.identifier(J.fieldAlias)}`)}else if(R(J,GT))if(_)$.push(U.identifier(this.casing.getColumnCasing(J)));else $.push(J);if(Y<F-1)$.push(U`, `);return $});return U.join(W)}buildJoins(T){if(!T||T.length===0)return;let _=[];for(let[F,W]of T.entries()){if(F===0)_.push(U` `);let J=W.table,Y=W.lateral?U` lateral`:void 0,$=W.on?U` on ${W.on}`:void 0;if(R(J,vT)){let Z=J[vT.Symbol.Name],G=J[vT.Symbol.Schema],X=J[vT.Symbol.OriginalName],O=Z===X?void 0:W.alias;_.push(U`${U.raw(W.joinType)} join${Y} ${G?U`${U.identifier(G)}.`:void 0}${U.identifier(X)}${O&&U` ${U.identifier(O)}`}${$}`)}else if(R(J,Z_)){let Z=J[MT].name,G=J[MT].schema,X=J[MT].originalName,O=Z===X?void 0:W.alias;_.push(U`${U.raw(W.joinType)} join${Y} ${G?U`${U.identifier(G)}.`:void 0}${U.identifier(X)}${O&&U` ${U.identifier(O)}`}${$}`)}else _.push(U`${U.raw(W.joinType)} join${Y} ${J}${$}`);if(F<T.length-1)_.push(U` `)}return U.join(_)}buildFromTable(T){if(R(T,I)&&T[I.Symbol.IsAlias]){let _=U`${U.identifier(T[I.Symbol.OriginalName])}`;if(T[I.Symbol.Schema])_=U`${U.identifier(T[I.Symbol.Schema])}.${_}`;return U`${_} ${U.identifier(T[I.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:_,fieldsFlat:F,where:W,having:J,table:Y,joins:$,orderBy:Z,groupBy:G,limit:X,offset:O,lockingClause:M,distinct:Q,setOperators:K}){let B=F??L_(_);for(let TT of B)if(R(TT.field,GT)&&xT(TT.field.table)!==(R(Y,IT)?Y._.alias:R(Y,EW)?Y[MT].name:R(Y,k)?void 0:xT(Y))&&!((bT)=>$?.some(({alias:H_})=>H_===(bT[I.Symbol.IsAlias]?xT(bT):bT[I.Symbol.BaseName])))(TT.field.table)){let bT=xT(TT.field.table);throw new Error(`Your "${TT.path.join("->")}" field references a column "${bT}"."${TT.field.name}", but the table "${bT}" is not part of the query! Did you forget to join it?`)}let V=!$||$.length===0,v=this.buildWithCTE(T),q;if(Q)q=Q===!0?U` distinct`:U` distinct on (${U.join(Q.on,U`, `)})`;let j=this.buildSelection(B,{isSingleTable:V}),y=this.buildFromTable(Y),u=this.buildJoins($),h=W?U` where ${W}`:void 0,p=J?U` having ${J}`:void 0,t;if(Z&&Z.length>0)t=U` order by ${U.join(Z,U`, `)}`;let ST;if(G&&G.length>0)ST=U` group by ${U.join(G,U`, `)}`;let A_=typeof X==="object"||typeof X==="number"&&X>=0?U` limit ${X}`:void 0,D=O?U` offset ${O}`:void 0,ZT=U.empty();if(M){let TT=U` for ${U.raw(M.strength)}`;if(M.config.of)TT.append(U` of ${U.join(Array.isArray(M.config.of)?M.config.of:[M.config.of],U`, `)}`);if(M.config.noWait)TT.append(U` nowait`);else if(M.config.skipLocked)TT.append(U` skip locked`);ZT.append(TT)}let i=U`${v}select${q} ${j} from ${y}${u}${h}${ST}${p}${t}${A_}${D}${ZT}`;if(K.length>0)return this.buildSetOperations(i,K);return i}buildSetOperations(T,_){let[F,...W]=_;if(!F)throw new Error("Cannot pass undefined values to any set operator");if(W.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:F});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:F}),W)}buildSetOperationQuery({leftSelect:T,setOperator:{type:_,isAll:F,rightSelect:W,limit:J,orderBy:Y,offset:$}}){let Z=U`(${T.getSQL()}) `,G=U`(${W.getSQL()})`,X;if(Y&&Y.length>0){let K=[];for(let B of Y)if(R(B,S))K.push(U.identifier(B.name));else if(R(B,k)){for(let V=0;V<B.queryChunks.length;V++){let v=B.queryChunks[V];if(R(v,S))B.queryChunks[V]=U.identifier(v.name)}K.push(U`${B}`)}else K.push(U`${B}`);X=U` order by ${U.join(K,U`, `)} `}let O=typeof J==="object"||typeof J==="number"&&J>=0?U` limit ${J}`:void 0,M=U.raw(`${_} ${F?"all ":""}`),Q=$?U` offset ${$}`:void 0;return U`${Z}${M}${G}${X}${O}${Q}`}buildInsertQuery({table:T,values:_,onConflict:F,returning:W,withList:J,select:Y,overridingSystemValue_:$}){let Z=[],G=T[I.Symbol.Columns],X=Object.entries(G).filter(([v,q])=>!q.shouldDisableInsert()),O=X.map(([,v])=>U.identifier(this.casing.getColumnCasing(v)));if(Y){let v=_;if(R(v,k))Z.push(v);else Z.push(v.getSQL())}else{let v=_;Z.push(U.raw("values "));for(let[q,j]of v.entries()){let y=[];for(let[u,h]of X){let p=j[u];if(p===void 0||R(p,Q_)&&p.value===void 0)if(h.defaultFn!==void 0){let t=h.defaultFn(),ST=R(t,k)?t:U.param(t,h);y.push(ST)}else if(!h.default&&h.onUpdateFn!==void 0){let t=h.onUpdateFn(),ST=R(t,k)?t:U.param(t,h);y.push(ST)}else y.push(U`default`);else y.push(p)}if(Z.push(y),q<v.length-1)Z.push(U`, `)}}let M=this.buildWithCTE(J),Q=U.join(Z),K=W?U` returning ${this.buildSelection(W,{isSingleTable:!0})}`:void 0,B=F?U` on conflict ${F}`:void 0,V=$===!0?U`overriding system value `:void 0;return U`${M}insert into ${T} ${O} ${V}${Q}${B}${K}`}buildRefreshMaterializedViewQuery({view:T,concurrently:_,withNoData:F}){let W=_?U` concurrently`:void 0,J=F?U` with no data`:void 0;return U`refresh materialized view${W} ${T}${J}`}prepareTyping(T){if(R(T,z1)||R(T,E1))return"json";else if(R(T,V1))return"decimal";else if(R(T,K1))return"time";else if(R(T,L1)||R(T,D1))return"timestamp";else if(R(T,Q1)||R(T,R1))return"date";else if(R(T,S1))return"uuid";else return"none"}sqlToQuery(T,_){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:_})}buildRelationalQueryWithoutPK({fullSchema:T,schema:_,tableNamesMap:F,table:W,tableConfig:J,queryConfig:Y,tableAlias:$,nestedQueryRelation:Z,joinOn:G}){let X=[],O,M,Q=[],K,B=[];if(Y===!0)X=Object.entries(J.columns).map(([q,j])=>({dbKey:j.name,tsKey:q,field:m_(j,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let v=Object.fromEntries(Object.entries(J.columns).map(([p,t])=>[p,m_(t,$)]));if(Y.where){let p=typeof Y.where==="function"?Y.where(v,U5()):Y.where;K=p&&$W(p,$)}let q=[],j=[];if(Y.columns){let p=!1;for(let[t,ST]of Object.entries(Y.columns)){if(ST===void 0)continue;if(t in J.columns){if(!p&&ST===!0)p=!0;j.push(t)}}if(j.length>0)j=p?j.filter((t)=>Y.columns?.[t]===!0):Object.keys(J.columns).filter((t)=>!j.includes(t))}else j=Object.keys(J.columns);for(let p of j){let t=J.columns[p];q.push({tsKey:p,value:t})}let y=[];if(Y.with)y=Object.entries(Y.with).filter((p)=>!!p[1]).map(([p,t])=>({tsKey:p,queryConfig:t,relation:J.relations[p]}));let u;if(Y.extras){u=typeof Y.extras==="function"?Y.extras(v,{sql:U}):Y.extras;for(let[p,t]of Object.entries(u))q.push({tsKey:p,value:p2(t,$)})}for(let{tsKey:p,value:t}of q)X.push({dbKey:R(t,k.Aliased)?t.fieldAlias:J.columns[p].name,tsKey:p,field:R(t,GT)?m_(t,$):t,relationTableTsKey:void 0,isJson:!1,selection:[]});let h=typeof Y.orderBy==="function"?Y.orderBy(v,M5()):Y.orderBy??[];if(!Array.isArray(h))h=[h];Q=h.map((p)=>{if(R(p,GT))return m_(p,$);return $W(p,$)}),O=Y.limit,M=Y.offset;for(let{tsKey:p,queryConfig:t,relation:ST}of y){let A_=Q5(_,F,ST),D=f0(ST.referencedTable),ZT=F[D],i=`${$}_${p}`,TT=HW(...A_.fields.map((I_,b0)=>I1(m_(A_.references[b0],i),m_(I_,$)))),bT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:_,tableNamesMap:F,table:T[ZT],tableConfig:_[ZT],queryConfig:R(ST,V0)?t===!0?{limit:1}:{...t,limit:1}:t,tableAlias:i,joinOn:TT,nestedQueryRelation:ST}),H_=U`${U.identifier(i)}.${U.identifier("data")}`.as(p);B.push({on:U`true`,table:new IT(bT.sql,{},i),alias:i,joinType:"left",lateral:!0}),X.push({dbKey:p,tsKey:p,field:H_,relationTableTsKey:ZT,isJson:!0,selection:bT.selection})}}if(X.length===0)throw new M1({message:`No fields selected for table "${J.tsName}" ("${$}")`});let V;if(K=HW(G,K),Z){let v=U`json_build_array(${U.join(X.map(({field:y,tsKey:u,isJson:h})=>h?U`${U.identifier(`${$}_${u}`)}.${U.identifier("data")}`:R(y,k.Aliased)?y.sql:y),U`, `)})`;if(R(Z,OW))v=U`coalesce(json_agg(${v}${Q.length>0?U` order by ${U.join(Q,U`, `)}`:void 0}), '[]'::json)`;let q=[{dbKey:"data",tsKey:"data",field:v.as("data"),isJson:!0,relationTableTsKey:J.tsName,selection:X}];if(O!==void 0||M!==void 0||Q.length>0)V=this.buildSelectQuery({table:U1(W,$),fields:{},fieldsFlat:[{path:[],field:U.raw("*")}],where:K,limit:O,offset:M,orderBy:Q,setOperators:[]}),K=void 0,O=void 0,M=void 0,Q=[];else V=U1(W,$);V=this.buildSelectQuery({table:R(V,vT)?V:new IT(V,{},$),fields:{},fieldsFlat:q.map(({field:y})=>({path:[],field:R(y,GT)?m_(y,$):y})),joins:B,where:K,limit:O,offset:M,orderBy:Q,setOperators:[]})}else V=this.buildSelectQuery({table:U1(W,$),fields:{},fieldsFlat:X.map(({field:v})=>({path:[],field:R(v,GT)?m_(v,$):v})),joins:B,where:K,limit:O,offset:M,orderBy:Q,setOperators:[]});return{tableTsKey:J.tsName,sql:V,selection:X}}}class O8{static[H]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class eT{static[H]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let _=!!this.fields,F=T,W;if(this.fields)W=this.fields;else if(R(F,IT))W=Object.fromEntries(Object.keys(F._.selectedFields).map((J)=>[J,F[J]]));else if(R(F,EW))W=F[MT].selectedFields;else if(R(F,k))W={};else W=d$(F);return new U8({table:F,fields:W,isPartialSelect:_,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class g5 extends O8{static[H]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:T,fields:_,isPartialSelect:F,session:W,dialect:J,withList:Y,distinct:$}){super();this.config={withList:Y,table:T,fields:{..._},distinct:$,setOperators:[]},this.isPartialSelect=F,this.session=W,this.dialect=J,this._={selectedFields:_,config:this.config},this.tableName=a_(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let Z of y_(T))this.usedTables.add(Z)}getUsedTables(){return[...this.usedTables]}createJoin(T,_){return(F,W)=>{let J=this.tableName,Y=a_(F);for(let $ of y_(F))this.usedTables.add($);if(typeof Y==="string"&&this.config.joins?.some(($)=>$.alias===Y))throw new Error(`Alias "${Y}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof J==="string")this.config.fields={[J]:this.config.fields};if(typeof Y==="string"&&!R(F,k)){let $=R(F,IT)?F._.selectedFields:R(F,Z_)?F[MT].selectedFields:F[I.Symbol.Columns];this.config.fields[Y]=$}}if(typeof W==="function")W=W(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:W,table:F,joinType:T,alias:Y,lateral:_}),typeof Y==="string")switch(T){case"left":{this.joinsNotNullableMap[Y]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[Y]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[Y]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[Y]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(T,_){return(F)=>{let W=typeof F==="function"?F(d3()):F;if(!ZW(this.getSelectedFields(),W.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:_,rightSelect:W}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let _=T[0](new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(_)?_:[_]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let _=T[0](new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),F=Array.isArray(_)?_:[_];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=F;else this.config.orderBy=F}else{let _=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=_;else this.config.orderBy=_}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,_={}){return this.config.lockingClause={strength:T,config:_},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}as(T){let _=[];if(_.push(...y_(this.config.table)),this.config.joins)for(let F of this.config.joins)_.push(...y_(F.table));return new Proxy(new IT(this.getSQL(),this.config.fields,T,!1,[...new Set(_)]),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new DT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(T){return this.cacheConfig=T===void 0?{config:{},enable:!0,autoInvalidate:!0}:T===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...T},this}}class U8 extends g5{static[H]="PgSelect";_prepare(T){let{session:_,config:F,dialect:W,joinsNotNullableMap:J,authToken:Y,cacheConfig:$,usedTables:Z}=this;if(!_)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:G}=F;return AT.startActiveSpan("drizzle.prepareQuery",()=>{let X=L_(G),O=_.prepareQuery(W.sqlToQuery(this.getSQL()),X,T,!0,void 0,{type:"select",tables:[...Z]},$);return O.joinsNotNullableMap=J,O.setToken(Y)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}c$(U8,[aT]);function UF(T,_){return(F,W,...J)=>{let Y=[W,...J].map(($)=>({type:T,isAll:_,rightSelect:$}));for(let $ of Y)if(!ZW(F.getSelectedFields(),$.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return F.addSetOperators(Y)}}var d3=()=>({union:l3,unionAll:t3,intersect:i3,intersectAll:n3,except:r3,exceptAll:s3}),l3=UF("union",!1),t3=UF("union",!0),i3=UF("intersect",!1),n3=UF("intersect",!0),r3=UF("except",!1),s3=UF("except",!0);class zW{static[H]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=R(T,v0)?T:void 0,this.dialectConfig=R(T,v0)?void 0:T}$with=(T,_)=>{let F=this;return{as:(J)=>{if(typeof J==="function")J=J(F);return new Proxy(new WW(J.getSQL(),_??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let _=this;function F(Y){return new eT({fields:Y??void 0,session:void 0,dialect:_.getDialect(),withList:T})}function W(Y){return new eT({fields:Y??void 0,session:void 0,dialect:_.getDialect(),distinct:!0})}function J(Y,$){return new eT({fields:$??void 0,session:void 0,dialect:_.getDialect(),distinct:{on:Y}})}return{select:F,selectDistinct:W,selectDistinctOn:J}}select(T){return new eT({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new eT({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,_){return new eT({fields:_??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new v0(this.dialectConfig);return this.dialect}}function y_(T){if(R(T,vT))return[T[k0]?`${T[k0]}.${T[I.Symbol.BaseName]}`:T[I.Symbol.BaseName]];if(R(T,IT))return T._.usedTables??[];if(R(T,k))return T.usedTables??[];return[]}class p1 extends aT{constructor(T,_,F,W){super();this.session=_,this.dialect=F,this.config={table:T,withList:W}}static[H]="PgDelete";config;cacheConfig;where(T){return this.config.where=T,this}returning(T=this.config.table[I.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=L_(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"delete",tables:y_(this.config.table)},this.cacheConfig)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class g1{constructor(T,_,F,W,J){this.table=T,this.session=_,this.dialect=F,this.withList=W,this.overridingSystemValue_=J}static[H]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let _=T.map((F)=>{let W={},J=this.table[I.Symbol.Columns];for(let Y of Object.keys(F)){let $=F[Y];W[Y]=R($,k)?$:new Q_($,J[Y])}return W});return new M8(this.table,_,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let _=typeof T==="function"?T(new zW):T;if(!R(_,k)&&!ZW(this.table[H1],_._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new M8(this.table,_,this.session,this.dialect,this.withList,!0)}}class M8 extends aT{constructor(T,_,F,W,J,Y,$){super();this.session=F,this.dialect=W,this.config={table:T,values:_,withList:J,select:Y,overridingSystemValue_:$}}static[H]="PgInsert";config;cacheConfig;returning(T=this.config.table[I.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=L_(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=U`do nothing`;else{let _="";_=Array.isArray(T.target)?T.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let F=T.where?U` where ${T.where}`:void 0;this.config.onConflict=U`(${U.raw(_)})${F} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let _=T.where?U` where ${T.where}`:void 0,F=T.targetWhere?U` where ${T.targetWhere}`:void 0,W=T.setWhere?U` where ${T.setWhere}`:void 0,J=this.dialect.buildUpdateSet(this.config.table,w1(this.config.table,T.set)),Y="";return Y=Array.isArray(T.target)?T.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=U`(${U.raw(Y)})${F} do update set ${J}${_}${W}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"insert",tables:y_(this.config.table)},this.cacheConfig)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class w8 extends aT{constructor(T,_,F){super();this.session=_,this.dialect=F,this.config={view:T}}static[H]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class m1{constructor(T,_,F,W){this.table=T,this.session=_,this.dialect=F,this.withList=W}static[H]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new m5(this.table,w1(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class m5 extends aT{constructor(T,_,F,W,J){super();this.session=F,this.dialect=W,this.config={set:_,table:T,withList:J,joins:[]},this.tableName=a_(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[H]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(T){let _=T,F=a_(_);if(typeof F==="string")this.joinsNotNullableMap[F]=!0;return this.config.from=_,this}getTableLikeFields(T){if(R(T,vT))return T[I.Symbol.Columns];else if(R(T,IT))return T._.selectedFields;return T[MT].selectedFields}createJoin(T){return(_,F)=>{let W=a_(_);if(typeof W==="string"&&this.config.joins.some((J)=>J.alias===W))throw new Error(`Alias "${W}" is already used in this query`);if(typeof F==="function"){let J=this.config.from&&!R(this.config.from,k)?this.getTableLikeFields(this.config.from):void 0;F=F(new Proxy(this.config.table[I.Symbol.Columns],new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),J&&new Proxy(J,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:F,table:_,joinType:T,alias:W}),typeof W==="string")switch(T){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!0;break}case"inner":{this.joinsNotNullableMap[W]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[I.Symbol.Columns]),this.config.from){let _=a_(this.config.from);if(typeof _==="string"&&this.config.from&&!R(this.config.from,k)){let F=this.getTableLikeFields(this.config.from);T[_]=F}for(let F of this.config.joins){let W=a_(F.table);if(typeof W==="string"&&!R(F.table,k)){let J=this.getTableLikeFields(F.table);T[W]=J}}}}return this.config.returningFields=T,this.config.returning=L_(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){let _=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"insert",tables:y_(this.config.table)},this.cacheConfig);return _.joinsNotNullableMap=this.joinsNotNullableMap,_}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class VW extends k{constructor(T){super(VW.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=VW.buildCount(T.source,T.filters)}sql;token;static[H]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,_){return U`(select count(*) from ${T}${U.raw(" where ").if(_)}${_})`}static buildCount(T,_){return U`select count(*) as count from ${T}${U.raw(" where ").if(_)}${_};`}setToken(T){return this.token=T,this}then(T,_){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,_)}catch(T){return this.then(void 0,T)}finally(T){return this.then((_)=>{return T?.(),_},(_)=>{throw T?.(),_})}}class R8{constructor(T,_,F,W,J,Y,$){this.fullSchema=T,this.schema=_,this.tableNamesMap=F,this.table=W,this.tableConfig=J,this.dialect=Y,this.session=$}static[H]="PgRelationalQueryBuilder";findMany(T){return new Q8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new Q8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class Q8 extends aT{constructor(T,_,F,W,J,Y,$,Z,G){super();this.fullSchema=T,this.schema=_,this.tableNamesMap=F,this.table=W,this.tableConfig=J,this.dialect=Y,this.session=$,this.config=Z,this.mode=G}static[H]="PgRelationalQuery";_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:_,builtQuery:F}=this._toSQL();return this.session.prepareQuery(F,void 0,T,!0,(W,J)=>{let Y=W.map(($)=>N1(this.schema,this.tableConfig,$,_.selection,J));if(this.mode==="first")return Y[0];return Y})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),_=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:_}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class E8 extends aT{constructor(T,_,F,W){super();this.execute=T,this.sql=_,this.query=F,this.mapBatchResult=W}static[H]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,_){return _?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class KW{constructor(T,_,F){if(this.dialect=T,this.session=_,this._=F?{schema:F.schema,fullSchema:F.fullSchema,tableNamesMap:F.tableNamesMap,session:_}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:_},this.query={},this._.schema)for(let[W,J]of Object.entries(this._.schema))this.query[W]=new R8(F.fullSchema,this._.schema,this._.tableNamesMap,F.fullSchema[W],J,T,_);this.$cache={invalidate:async(W)=>{}}}static[H]="PgDatabase";query;$with=(T,_)=>{let F=this;return{as:(J)=>{if(typeof J==="function")J=J(new zW(F.dialect));return new Proxy(new WW(J.getSQL(),_??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,_){return new VW({source:T,filters:_,session:this.session})}$cache;with(...T){let _=this;function F(G){return new eT({fields:G??void 0,session:_.session,dialect:_.dialect,withList:T})}function W(G){return new eT({fields:G??void 0,session:_.session,dialect:_.dialect,withList:T,distinct:!0})}function J(G,X){return new eT({fields:X??void 0,session:_.session,dialect:_.dialect,withList:T,distinct:{on:G}})}function Y(G){return new m1(G,_.session,_.dialect,T)}function $(G){return new g1(G,_.session,_.dialect,T)}function Z(G){return new p1(G,_.session,_.dialect,T)}return{select:F,selectDistinct:W,selectDistinctOn:J,update:Y,insert:$,delete:Z}}select(T){return new eT({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new eT({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,_){return new eT({fields:_??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new m1(T,this.session,this.dialect)}insert(T){return new g1(T,this.session,this.dialect)}delete(T){return new p1(T,this.session,this.dialect)}refreshMaterializedView(T){return new w8(T,this.session,this.dialect)}authToken;execute(T){let _=typeof T==="string"?U.raw(T):T.getSQL(),F=this.dialect.sqlToQuery(_),W=this.session.prepareQuery(F,void 0,void 0,!1);return new E8(()=>W.execute(void 0,this.authToken),_,F,(J)=>W.mapResult(J,!0))}transaction(T,_){return this.session.transaction(T,_)}}class o5{static[H]="Cache"}class LW extends o5{strategy(){return"all"}static[H]="NoopCache";async get(T){return}async put(T,_,F,W){}async onMutate(T){}}async function z8(T,_){let F=`${T}-${JSON.stringify(_)}`,J=new TextEncoder().encode(F),Y=await crypto.subtle.digest("SHA-256",J);return[...new Uint8Array(Y)].map((G)=>G.toString(16).padStart(2,"0")).join("")}class T0 extends Error{constructor(T,_,F){super(`Failed query: ${T}
|
|
77
|
-
params: ${_}`);if(this.query=T,this.params=_,this.cause=F,Error.captureStackTrace(this,T0),F)this.cause=F}}class V8{constructor(T,_,F,W){if(this.query=T,this.cache=_,this.queryMetadata=F,this.cacheConfig=W,_&&_.strategy()==="all"&&W===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(T,_){return T}setToken(T){return this.authToken=T,this}static[H]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(T,_,F){if(this.cache===void 0||R(this.cache,LW)||this.queryMetadata===void 0)try{return await F()}catch(W){throw new T0(T,_,W)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await F()}catch(W){throw new T0(T,_,W)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[W]=await Promise.all([F(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return W}catch(W){throw new T0(T,_,W)}if(!this.cacheConfig)try{return await F()}catch(W){throw new T0(T,_,W)}if(this.queryMetadata.type==="select"){let W=await this.cache.get(this.cacheConfig.tag??await z8(T,_),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(W===void 0){let J;try{J=await F()}catch(Y){throw new T0(T,_,Y)}return await this.cache.put(this.cacheConfig.tag??await z8(T,_),J,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),J}return W}try{return await F()}catch(W){throw new T0(T,_,W)}}}class K8{constructor(T){this.dialect=T}static[H]="PgSession";execute(T,_){return AT.startActiveSpan("drizzle.operation",()=>{return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(_).execute(void 0,_)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,_){let F=await this.execute(T,_);return Number(F[0].count)}}class L8 extends KW{constructor(T,_,F,W=0){super(T,_,F);this.schema=F,this.nestedIndex=W}static[H]="PgTransaction";rollback(){throw new g2}getTransactionConfigSQL(T){let _=[];if(T.isolationLevel)_.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)_.push(T.accessMode);if(typeof T.deferrable==="boolean")_.push(T.deferrable?"deferrable":"not deferrable");return U.raw(_.join(" "))}setTransaction(T){return this.session.execute(U`set transaction ${this.getTransactionConfigSQL(T)}`)}}class u5 extends V8{constructor(T,_,F,W,J,Y,$,Z,G,X){super({sql:_,params:F},J,Y,$);this.client=T,this.queryString=_,this.params=F,this.logger=W,this.fields=Z,this._isResponseInArrayMode=G,this.customResultMapper=X}static[H]="PostgresJsPreparedQuery";async execute(T={}){return AT.startActiveSpan("drizzle.execute",async(_)=>{let F=h2(this.params,T);_?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F);let{fields:W,queryString:J,client:Y,joinsNotNullableMap:$,customResultMapper:Z}=this;if(!W&&!Z)return AT.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(J,F,async()=>{return await Y.unsafe(J,F)})});let G=await AT.startActiveSpan("drizzle.driver.execute",()=>{return _?.setAttributes({"drizzle.query.text":J,"drizzle.query.params":JSON.stringify(F)}),this.queryWithCache(J,F,async()=>{return await Y.unsafe(J,F).values()})});return AT.startActiveSpan("drizzle.mapResponse",()=>{return Z?Z(G):G.map((X)=>u$(W,X,$))})})}all(T={}){return AT.startActiveSpan("drizzle.execute",async(_)=>{let F=h2(this.params,T);return _?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F),AT.startActiveSpan("drizzle.driver.execute",()=>{return _?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.queryWithCache(this.queryString,F,async()=>{return this.client.unsafe(this.queryString,F)})})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class DW extends K8{constructor(T,_,F,W={}){super(_);this.client=T,this.schema=F,this.options=W,this.logger=W.logger??new o2,this.cache=W.cache??new LW}static[H]="PostgresJsSession";logger;cache;prepareQuery(T,_,F,W,J,Y,$){return new u5(this.client,T.sql,T.params,this.logger,this.cache,Y,$,_,W,J)}query(T,_){return this.logger.logQuery(T,_),this.client.unsafe(T,_).values()}queryObjects(T,_){return this.client.unsafe(T,_)}transaction(T,_){return this.client.begin(async(F)=>{let W=new DW(F,this.dialect,this.schema,this.options),J=new D8(this.dialect,W,this.schema);if(_)await J.setTransaction(_);return T(J)})}}class D8 extends L8{constructor(T,_,F,W=0){super(T,_,F,W);this.session=_}static[H]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((_)=>{let F=new DW(_,this.dialect,this.schema,this.session.options),W=new D8(this.dialect,F,this.schema);return T(W)})}}class c5 extends KW{static[H]="PostgresJsDatabase"}function MF(T,_={}){let F=(G)=>G;for(let G of["1184","1082","1083","1114","1182","1185","1115","1231"])T.options.parsers[G]=F,T.options.serializers[G]=F;T.options.serializers["114"]=F,T.options.serializers["3802"]=F;let W=new v0({casing:_.casing}),J;if(_.logger===!0)J=new m2;else if(_.logger!==!1)J=_.logger;let Y;if(_.schema){let G=w5(_.schema,R5);Y={fullSchema:_.schema,schema:G.tables,tableNamesMap:G.tableNamesMap}}let $=new DW(T,W,Y,{logger:J,cache:_.cache}),Z=new c5(W,$,Y);if(Z.$client=T,Z.$cache=_.cache,Z.$cache)Z.$cache.invalidate=_.cache?.onMutate;return Z}function o1(...T){if(typeof T[0]==="string"){let _=OF(T[0]);return MF(_,T[1])}if(l$(T[0])){let{connection:_,client:F,...W}=T[0];if(F)return MF(F,W);if(typeof _==="object"&&_.url!==void 0){let{url:Y,...$}=_,Z=OF(Y,$);return MF(Z,W)}let J=OF(_);return MF(J,W)}return MF(T[0],T[1])}((T)=>{function _(F){return MF({options:{parsers:{},serializers:{}}},F)}T.mock=_})(o1||(o1={}));var I8={};nG(I8,{users:()=>x0,untrackedUserColumnNames:()=>a3,twoFactorMethod:()=>n5,trackedUserColumnName:()=>e3,trackableUserColumnNames:()=>t5,signInHistory:()=>_O,role:()=>l5,players:()=>S8,passwordResetAttempts:()=>FO,games:()=>c1,banishedIps:()=>WO,accountActions:()=>TO,accountAction:()=>i5});function L0(){return dT({length:24}).$type()}function d5(T){return U`lower(${T})`}var u1=U`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,l5=FW("role",["admin","user"]),x0=z0("users",{id:D_().primaryKey().defaultRandom(),username:dT({length:16}).notNull(),emailOffered:dT({length:254}).notNull(),emailVerified:dT({length:254}),password:dT({length:254}),createdAtIso:L0().notNull().default(u1),createdIp:dT({length:45}).notNull(),isActive:XW().notNull().default(!1),verifiedAtIso:L0(),userRole:l5().default("user")},(T)=>[A8("usernameUniqueIndex").on(d5(T.username)),A8("emailVerifiedUniqueIndex").on(d5(T.emailVerified))]),a3=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],t5=["username","emailOffered","emailVerified","password","userRole"],e3=FW("trackedUserColumnName",t5),i5=FW("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),TO=z0("accountActions",{userId:D_().references(()=>x0.id).primaryKey(),action:i5().notNull(),code:dT({length:254}).notNull(),wrongCodeCount:GW().notNull().default(0),expiresAtIso:L0().notNull()}),c1=z0("games",{id:D_().primaryKey().defaultRandom()}),S8=z0("players",{userId:D_().notNull().references(()=>x0.id,{onDelete:"cascade"}),gameId:D_().notNull().references(()=>c1.id,{onDelete:"cascade"}),score:GW().notNull()},(T)=>[uX({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),_O=z0("signInHistory",{id:D_().primaryKey().defaultRandom(),userId:D_().references(()=>x0.id,{onDelete:"cascade"}),signInTimeIso:L0().notNull().default(u1),ipAddress:dT({length:45}).notNull(),userAgent:dT({length:1024}),successful:XW().notNull().default(!1)}),n5=FW("twoFactorMethod",["email","phone"]),FO=z0("passwordResetAttempts",{id:D_().primaryKey().defaultRandom(),userId:D_().notNull().references(()=>x0.id,{onDelete:"cascade"}),requestedIp:dT({length:45}).notNull(),requestedAtIso:L0().notNull().default(u1),succeededIp:dT({length:45}),succeededAtIso:L0(),verificationMethod:n5().notNull()}),WO=z0("banishedIps",{ip:dT({length:45}).primaryKey(),reason:dT({length:2048}).notNull(),banishedAtIso:L0().notNull().default(u1),banishedUntilIso:L0()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class N8{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(JO.resolve(__dirname,"notify_update.sql"));let T=[xT(x0),xT(c1),xT(S8)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(_)=>{let F=_.split(","),W=F[0],J=F[1],Y=`${W}("${J}")`;if(this.observers.has(Y))this.observers.get(Y).next(Y)})}constructor(T=!1,_={host:q_.POSTGRES_HOST,port:q_.POSTGRES_PORT,user:q_.POSTGRES_USER,password:q_.POSTGRES_PASSWORD,database:q_.POSTGRES_DATABASE}){this.options=_,this.sql=OF(_),this.drizzle=o1(this.sql,{schema:I8,logger:T})}observe(T,_){if(!this.observers.has(T))this.observers.set(T,new FT);this.observers.get(T).subscribe("SINGLETON",_)}}var d1={100:'"Continue"',101:'"Switching Protocols"',102:'"Processing"',103:'"Early Hints"',200:'"OK"',201:'"Created"',202:'"Accepted"',203:'"Non-Authoritative Information"',204:'"No Content"',205:'"Reset Content"',206:'"Partial Content"',207:'"Multi-Status"',208:'"Already Reported"',226:'"IM Used"',300:'"Multiple Choices"',301:'"Moved Permanently"',302:'"Found"',303:'"See Other"',304:'"Not Modified"',305:'"Use Proxy"',306:'"Switch Proxy"',307:'"Temporary Redirect"',308:'"Permanent Redirect"',400:'"Bad Request"',401:'"Unauthorized"',402:'"Payment Required"',403:'"Forbidden"',404:'"Not Found"',405:'"Method Not Allowed"',406:'"Not Acceptable"',407:'"Proxy Authentication Required"',408:'"Request Timeout"',409:'"Conflict"',410:'"Gone"',411:'"Length Required"',412:'"Precondition Failed"',413:'"Payload Too Large"',414:'"URI Too Long"',415:'"Unsupported Media Type"',416:'"Range Not Satisfiable"',417:'"Expectation Failed"',418:`"I'm a teapot"`,421:'"Misdirected Request"',422:'"Unprocessable Entity"',423:'"Locked"',424:'"Failed Dependency"',425:'"Too Early"',426:'"Upgrade Required"',428:'"Precondition Required"',429:'"Too Many Requests"',431:'"Request Header Fields Too Large"',451:'"Unavailable For Legal Reasons"',500:'"Internal Server Error"',501:'"Not Implemented"',502:'"Bad Gateway"',503:'"Service Unavailable"',504:'"Gateway Timeout"',505:'"HTTP Version Not Supported"',506:'"Variant Also Negotiates"',507:'"Insufficient Storage"',508:'"Loop Detected"',510:'"Not Extended"',511:'"Network Authentication Required"'};function YO(T){return Number.parseInt(T,10)}var $O=Y_(d1),ZO=$O.keyof().pipe((T)=>YO(T)),r5=Y_([ZO,"string"]);var B8=new N2,{logger:G_}=B8;Object.assign(console,G_,{log:G_.info});G_.info("ready");var C8=a5(import.meta.dir,"..","app"),ey=new N8({logQuery(T,_){G_.info("\uD83D\uDCDD query",T,_)}});HO({hostname:"0.0.0.0",port:q_.FRONTEND_PORT??3333,...X1??void 0,async fetch(T){try{let _=new Date,F=new URL(T.url);if(G_.info(T.method,F.pathname),F.pathname==="/")return new Response(Bun.file(a5(C8,"index.html")));if(F.pathname==="/index.html")return Response.redirect("/");let W=GO(C8,F.pathname),J=AO(W);if(!J.startsWith(C8))throw[403,"Access Denied"];if(!await s5(J).exists())return Response.redirect("/");return new Response(s5(J))}catch(_){let F=r5(_);if(F instanceof Y_.errors===!1){let[W,J]=F,$=`${d1[W]}. ${J}`;return G_.info(`\u274C ${W}: ${$}`),new Response($,{status:W})}if(_ instanceof Error)G_.error(_.message);else{let W=E$(_);G_.error("frontend server threw",W)}return new Response(d1[500],{status:500})}}});function l1(){G_.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{G_.info("\u2757 received SIGINT; exiting gracefully"),l1()});process.on("SIGTERM",()=>{G_.info("\u2757 received SIGTERM; exiting gracefully"),l1()});process.on("exit",()=>{G_.info("\u2757 received exit; exiting gracefully"),l1()});B8.on("timeToStop",()=>{G_.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),l1()});var{version:OO}=await Bun.file(XO.resolve(import.meta.dir,"../package.json")).json();G_.info(`\uD83D\uDEEB frontend v${OO} running at http://localhost:${q_.FRONTEND_PORT}/`);B8.emit("alive");
|
|
76
|
+
`;await _.execute(U`CREATE SCHEMA IF NOT EXISTS ${U.identifier(J)}`),await _.execute(Y);let Z=(await _.all(U`select id, hash, created_at from ${U.identifier(J)}.${U.identifier(W)} order by created_at desc limit 1`))[0];await _.transaction(async(G)=>{for await(let X of T)if(!Z||Number(Z.created_at)<X.folderMillis){for(let O of X.sql)await G.execute(U.raw(O));await G.execute(U`insert into ${U.identifier(J)}.${U.identifier(W)} ("hash", "created_at") values(${X.hash}, ${X.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let _=[U`with `];for(let[F,W]of T.entries())if(_.push(U`${U.identifier(W._.alias)} as (${W._.sql})`),F<T.length-1)_.push(U`, `);return _.push(U` `),U.join(_)}buildDeleteQuery({table:T,where:_,returning:F,withList:W}){let J=this.buildWithCTE(W),Y=F?U` returning ${this.buildSelection(F,{isSingleTable:!0})}`:void 0,$=_?U` where ${_}`:void 0;return U`${J}delete from ${T}${$}${Y}`}buildUpdateSet(T,_){let F=T[I.Symbol.Columns],W=Object.keys(F).filter((Y)=>_[Y]!==void 0||F[Y]?.onUpdateFn!==void 0),J=W.length;return U.join(W.flatMap((Y,$)=>{let Z=F[Y],G=_[Y]??U.param(Z.onUpdateFn(),Z),X=U`${U.identifier(this.casing.getColumnCasing(Z))} = ${G}`;if($<J-1)return[X,U.raw(", ")];return[X]}))}buildUpdateQuery({table:T,set:_,where:F,returning:W,withList:J,from:Y,joins:$}){let Z=this.buildWithCTE(J),G=T[vT.Symbol.Name],X=T[vT.Symbol.Schema],O=T[vT.Symbol.OriginalName],M=G===O?void 0:G,Q=U`${X?U`${U.identifier(X)}.`:void 0}${U.identifier(O)}${M&&U` ${U.identifier(M)}`}`,V=this.buildUpdateSet(T,_),B=Y&&U.join([U.raw(" from "),this.buildFromTable(Y)]),K=this.buildJoins($),v=W?U` returning ${this.buildSelection(W,{isSingleTable:!Y})}`:void 0,q=F?U` where ${F}`:void 0;return U`${Z}update ${Q} set ${V}${B}${K}${q}${v}`}buildSelection(T,{isSingleTable:_=!1}={}){let F=T.length,W=T.flatMap(({field:J},Y)=>{let $=[];if(R(J,k.Aliased)&&J.isSelectionField)$.push(U.identifier(J.fieldAlias));else if(R(J,k.Aliased)||R(J,k)){let Z=R(J,k.Aliased)?J.sql:J;if(_)$.push(new k(Z.queryChunks.map((G)=>{if(R(G,S))return U.identifier(this.casing.getColumnCasing(G));return G})));else $.push(Z);if(R(J,k.Aliased))$.push(U` as ${U.identifier(J.fieldAlias)}`)}else if(R(J,GT))if(_)$.push(U.identifier(this.casing.getColumnCasing(J)));else $.push(J);if(Y<F-1)$.push(U`, `);return $});return U.join(W)}buildJoins(T){if(!T||T.length===0)return;let _=[];for(let[F,W]of T.entries()){if(F===0)_.push(U` `);let J=W.table,Y=W.lateral?U` lateral`:void 0,$=W.on?U` on ${W.on}`:void 0;if(R(J,vT)){let Z=J[vT.Symbol.Name],G=J[vT.Symbol.Schema],X=J[vT.Symbol.OriginalName],O=Z===X?void 0:W.alias;_.push(U`${U.raw(W.joinType)} join${Y} ${G?U`${U.identifier(G)}.`:void 0}${U.identifier(X)}${O&&U` ${U.identifier(O)}`}${$}`)}else if(R(J,Z_)){let Z=J[MT].name,G=J[MT].schema,X=J[MT].originalName,O=Z===X?void 0:W.alias;_.push(U`${U.raw(W.joinType)} join${Y} ${G?U`${U.identifier(G)}.`:void 0}${U.identifier(X)}${O&&U` ${U.identifier(O)}`}${$}`)}else _.push(U`${U.raw(W.joinType)} join${Y} ${J}${$}`);if(F<T.length-1)_.push(U` `)}return U.join(_)}buildFromTable(T){if(R(T,I)&&T[I.Symbol.IsAlias]){let _=U`${U.identifier(T[I.Symbol.OriginalName])}`;if(T[I.Symbol.Schema])_=U`${U.identifier(T[I.Symbol.Schema])}.${_}`;return U`${_} ${U.identifier(T[I.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:_,fieldsFlat:F,where:W,having:J,table:Y,joins:$,orderBy:Z,groupBy:G,limit:X,offset:O,lockingClause:M,distinct:Q,setOperators:V}){let B=F??L_(_);for(let TT of B)if(R(TT.field,GT)&&xT(TT.field.table)!==(R(Y,IT)?Y._.alias:R(Y,EW)?Y[MT].name:R(Y,k)?void 0:xT(Y))&&!((bT)=>$?.some(({alias:H_})=>H_===(bT[I.Symbol.IsAlias]?xT(bT):bT[I.Symbol.BaseName])))(TT.field.table)){let bT=xT(TT.field.table);throw new Error(`Your "${TT.path.join("->")}" field references a column "${bT}"."${TT.field.name}", but the table "${bT}" is not part of the query! Did you forget to join it?`)}let K=!$||$.length===0,v=this.buildWithCTE(T),q;if(Q)q=Q===!0?U` distinct`:U` distinct on (${U.join(Q.on,U`, `)})`;let j=this.buildSelection(B,{isSingleTable:K}),y=this.buildFromTable(Y),u=this.buildJoins($),h=W?U` where ${W}`:void 0,p=J?U` having ${J}`:void 0,t;if(Z&&Z.length>0)t=U` order by ${U.join(Z,U`, `)}`;let ST;if(G&&G.length>0)ST=U` group by ${U.join(G,U`, `)}`;let A_=typeof X==="object"||typeof X==="number"&&X>=0?U` limit ${X}`:void 0,D=O?U` offset ${O}`:void 0,ZT=U.empty();if(M){let TT=U` for ${U.raw(M.strength)}`;if(M.config.of)TT.append(U` of ${U.join(Array.isArray(M.config.of)?M.config.of:[M.config.of],U`, `)}`);if(M.config.noWait)TT.append(U` nowait`);else if(M.config.skipLocked)TT.append(U` skip locked`);ZT.append(TT)}let i=U`${v}select${q} ${j} from ${y}${u}${h}${ST}${p}${t}${A_}${D}${ZT}`;if(V.length>0)return this.buildSetOperations(i,V);return i}buildSetOperations(T,_){let[F,...W]=_;if(!F)throw new Error("Cannot pass undefined values to any set operator");if(W.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:F});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:F}),W)}buildSetOperationQuery({leftSelect:T,setOperator:{type:_,isAll:F,rightSelect:W,limit:J,orderBy:Y,offset:$}}){let Z=U`(${T.getSQL()}) `,G=U`(${W.getSQL()})`,X;if(Y&&Y.length>0){let V=[];for(let B of Y)if(R(B,S))V.push(U.identifier(B.name));else if(R(B,k)){for(let K=0;K<B.queryChunks.length;K++){let v=B.queryChunks[K];if(R(v,S))B.queryChunks[K]=U.identifier(v.name)}V.push(U`${B}`)}else V.push(U`${B}`);X=U` order by ${U.join(V,U`, `)} `}let O=typeof J==="object"||typeof J==="number"&&J>=0?U` limit ${J}`:void 0,M=U.raw(`${_} ${F?"all ":""}`),Q=$?U` offset ${$}`:void 0;return U`${Z}${M}${G}${X}${O}${Q}`}buildInsertQuery({table:T,values:_,onConflict:F,returning:W,withList:J,select:Y,overridingSystemValue_:$}){let Z=[],G=T[I.Symbol.Columns],X=Object.entries(G).filter(([v,q])=>!q.shouldDisableInsert()),O=X.map(([,v])=>U.identifier(this.casing.getColumnCasing(v)));if(Y){let v=_;if(R(v,k))Z.push(v);else Z.push(v.getSQL())}else{let v=_;Z.push(U.raw("values "));for(let[q,j]of v.entries()){let y=[];for(let[u,h]of X){let p=j[u];if(p===void 0||R(p,Q_)&&p.value===void 0)if(h.defaultFn!==void 0){let t=h.defaultFn(),ST=R(t,k)?t:U.param(t,h);y.push(ST)}else if(!h.default&&h.onUpdateFn!==void 0){let t=h.onUpdateFn(),ST=R(t,k)?t:U.param(t,h);y.push(ST)}else y.push(U`default`);else y.push(p)}if(Z.push(y),q<v.length-1)Z.push(U`, `)}}let M=this.buildWithCTE(J),Q=U.join(Z),V=W?U` returning ${this.buildSelection(W,{isSingleTable:!0})}`:void 0,B=F?U` on conflict ${F}`:void 0,K=$===!0?U`overriding system value `:void 0;return U`${M}insert into ${T} ${O} ${K}${Q}${B}${V}`}buildRefreshMaterializedViewQuery({view:T,concurrently:_,withNoData:F}){let W=_?U` concurrently`:void 0,J=F?U` with no data`:void 0;return U`refresh materialized view${W} ${T}${J}`}prepareTyping(T){if(R(T,z1)||R(T,E1))return"json";else if(R(T,K1))return"decimal";else if(R(T,V1))return"time";else if(R(T,L1)||R(T,D1))return"timestamp";else if(R(T,Q1)||R(T,R1))return"date";else if(R(T,S1))return"uuid";else return"none"}sqlToQuery(T,_){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:_})}buildRelationalQueryWithoutPK({fullSchema:T,schema:_,tableNamesMap:F,table:W,tableConfig:J,queryConfig:Y,tableAlias:$,nestedQueryRelation:Z,joinOn:G}){let X=[],O,M,Q=[],V,B=[];if(Y===!0)X=Object.entries(J.columns).map(([q,j])=>({dbKey:j.name,tsKey:q,field:m_(j,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let v=Object.fromEntries(Object.entries(J.columns).map(([p,t])=>[p,m_(t,$)]));if(Y.where){let p=typeof Y.where==="function"?Y.where(v,U5()):Y.where;V=p&&$W(p,$)}let q=[],j=[];if(Y.columns){let p=!1;for(let[t,ST]of Object.entries(Y.columns)){if(ST===void 0)continue;if(t in J.columns){if(!p&&ST===!0)p=!0;j.push(t)}}if(j.length>0)j=p?j.filter((t)=>Y.columns?.[t]===!0):Object.keys(J.columns).filter((t)=>!j.includes(t))}else j=Object.keys(J.columns);for(let p of j){let t=J.columns[p];q.push({tsKey:p,value:t})}let y=[];if(Y.with)y=Object.entries(Y.with).filter((p)=>!!p[1]).map(([p,t])=>({tsKey:p,queryConfig:t,relation:J.relations[p]}));let u;if(Y.extras){u=typeof Y.extras==="function"?Y.extras(v,{sql:U}):Y.extras;for(let[p,t]of Object.entries(u))q.push({tsKey:p,value:p2(t,$)})}for(let{tsKey:p,value:t}of q)X.push({dbKey:R(t,k.Aliased)?t.fieldAlias:J.columns[p].name,tsKey:p,field:R(t,GT)?m_(t,$):t,relationTableTsKey:void 0,isJson:!1,selection:[]});let h=typeof Y.orderBy==="function"?Y.orderBy(v,M5()):Y.orderBy??[];if(!Array.isArray(h))h=[h];Q=h.map((p)=>{if(R(p,GT))return m_(p,$);return $W(p,$)}),O=Y.limit,M=Y.offset;for(let{tsKey:p,queryConfig:t,relation:ST}of y){let A_=Q5(_,F,ST),D=f0(ST.referencedTable),ZT=F[D],i=`${$}_${p}`,TT=HW(...A_.fields.map((I_,b0)=>I1(m_(A_.references[b0],i),m_(I_,$)))),bT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:_,tableNamesMap:F,table:T[ZT],tableConfig:_[ZT],queryConfig:R(ST,K0)?t===!0?{limit:1}:{...t,limit:1}:t,tableAlias:i,joinOn:TT,nestedQueryRelation:ST}),H_=U`${U.identifier(i)}.${U.identifier("data")}`.as(p);B.push({on:U`true`,table:new IT(bT.sql,{},i),alias:i,joinType:"left",lateral:!0}),X.push({dbKey:p,tsKey:p,field:H_,relationTableTsKey:ZT,isJson:!0,selection:bT.selection})}}if(X.length===0)throw new M1({message:`No fields selected for table "${J.tsName}" ("${$}")`});let K;if(V=HW(G,V),Z){let v=U`json_build_array(${U.join(X.map(({field:y,tsKey:u,isJson:h})=>h?U`${U.identifier(`${$}_${u}`)}.${U.identifier("data")}`:R(y,k.Aliased)?y.sql:y),U`, `)})`;if(R(Z,OW))v=U`coalesce(json_agg(${v}${Q.length>0?U` order by ${U.join(Q,U`, `)}`:void 0}), '[]'::json)`;let q=[{dbKey:"data",tsKey:"data",field:v.as("data"),isJson:!0,relationTableTsKey:J.tsName,selection:X}];if(O!==void 0||M!==void 0||Q.length>0)K=this.buildSelectQuery({table:U1(W,$),fields:{},fieldsFlat:[{path:[],field:U.raw("*")}],where:V,limit:O,offset:M,orderBy:Q,setOperators:[]}),V=void 0,O=void 0,M=void 0,Q=[];else K=U1(W,$);K=this.buildSelectQuery({table:R(K,vT)?K:new IT(K,{},$),fields:{},fieldsFlat:q.map(({field:y})=>({path:[],field:R(y,GT)?m_(y,$):y})),joins:B,where:V,limit:O,offset:M,orderBy:Q,setOperators:[]})}else K=this.buildSelectQuery({table:U1(W,$),fields:{},fieldsFlat:X.map(({field:v})=>({path:[],field:R(v,GT)?m_(v,$):v})),joins:B,where:V,limit:O,offset:M,orderBy:Q,setOperators:[]});return{tableTsKey:J.tsName,sql:K,selection:X}}}class O8{static[H]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class eT{static[H]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let _=!!this.fields,F=T,W;if(this.fields)W=this.fields;else if(R(F,IT))W=Object.fromEntries(Object.keys(F._.selectedFields).map((J)=>[J,F[J]]));else if(R(F,EW))W=F[MT].selectedFields;else if(R(F,k))W={};else W=d$(F);return new U8({table:F,fields:W,isPartialSelect:_,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class g5 extends O8{static[H]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:T,fields:_,isPartialSelect:F,session:W,dialect:J,withList:Y,distinct:$}){super();this.config={withList:Y,table:T,fields:{..._},distinct:$,setOperators:[]},this.isPartialSelect=F,this.session=W,this.dialect=J,this._={selectedFields:_,config:this.config},this.tableName=a_(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let Z of y_(T))this.usedTables.add(Z)}getUsedTables(){return[...this.usedTables]}createJoin(T,_){return(F,W)=>{let J=this.tableName,Y=a_(F);for(let $ of y_(F))this.usedTables.add($);if(typeof Y==="string"&&this.config.joins?.some(($)=>$.alias===Y))throw new Error(`Alias "${Y}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof J==="string")this.config.fields={[J]:this.config.fields};if(typeof Y==="string"&&!R(F,k)){let $=R(F,IT)?F._.selectedFields:R(F,Z_)?F[MT].selectedFields:F[I.Symbol.Columns];this.config.fields[Y]=$}}if(typeof W==="function")W=W(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:W,table:F,joinType:T,alias:Y,lateral:_}),typeof Y==="string")switch(T){case"left":{this.joinsNotNullableMap[Y]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[Y]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[Y]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[Y]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(T,_){return(F)=>{let W=typeof F==="function"?F(d3()):F;if(!ZW(this.getSelectedFields(),W.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:_,rightSelect:W}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let _=T[0](new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(_)?_:[_]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let _=T[0](new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),F=Array.isArray(_)?_:[_];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=F;else this.config.orderBy=F}else{let _=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=_;else this.config.orderBy=_}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,_={}){return this.config.lockingClause={strength:T,config:_},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}as(T){let _=[];if(_.push(...y_(this.config.table)),this.config.joins)for(let F of this.config.joins)_.push(...y_(F.table));return new Proxy(new IT(this.getSQL(),this.config.fields,T,!1,[...new Set(_)]),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new DT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(T){return this.cacheConfig=T===void 0?{config:{},enable:!0,autoInvalidate:!0}:T===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...T},this}}class U8 extends g5{static[H]="PgSelect";_prepare(T){let{session:_,config:F,dialect:W,joinsNotNullableMap:J,authToken:Y,cacheConfig:$,usedTables:Z}=this;if(!_)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:G}=F;return AT.startActiveSpan("drizzle.prepareQuery",()=>{let X=L_(G),O=_.prepareQuery(W.sqlToQuery(this.getSQL()),X,T,!0,void 0,{type:"select",tables:[...Z]},$);return O.joinsNotNullableMap=J,O.setToken(Y)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}c$(U8,[aT]);function UF(T,_){return(F,W,...J)=>{let Y=[W,...J].map(($)=>({type:T,isAll:_,rightSelect:$}));for(let $ of Y)if(!ZW(F.getSelectedFields(),$.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return F.addSetOperators(Y)}}var d3=()=>({union:l3,unionAll:t3,intersect:i3,intersectAll:n3,except:r3,exceptAll:s3}),l3=UF("union",!1),t3=UF("union",!0),i3=UF("intersect",!1),n3=UF("intersect",!0),r3=UF("except",!1),s3=UF("except",!0);class zW{static[H]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=R(T,v0)?T:void 0,this.dialectConfig=R(T,v0)?void 0:T}$with=(T,_)=>{let F=this;return{as:(J)=>{if(typeof J==="function")J=J(F);return new Proxy(new WW(J.getSQL(),_??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let _=this;function F(Y){return new eT({fields:Y??void 0,session:void 0,dialect:_.getDialect(),withList:T})}function W(Y){return new eT({fields:Y??void 0,session:void 0,dialect:_.getDialect(),distinct:!0})}function J(Y,$){return new eT({fields:$??void 0,session:void 0,dialect:_.getDialect(),distinct:{on:Y}})}return{select:F,selectDistinct:W,selectDistinctOn:J}}select(T){return new eT({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new eT({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,_){return new eT({fields:_??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new v0(this.dialectConfig);return this.dialect}}function y_(T){if(R(T,vT))return[T[k0]?`${T[k0]}.${T[I.Symbol.BaseName]}`:T[I.Symbol.BaseName]];if(R(T,IT))return T._.usedTables??[];if(R(T,k))return T.usedTables??[];return[]}class p1 extends aT{constructor(T,_,F,W){super();this.session=_,this.dialect=F,this.config={table:T,withList:W}}static[H]="PgDelete";config;cacheConfig;where(T){return this.config.where=T,this}returning(T=this.config.table[I.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=L_(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"delete",tables:y_(this.config.table)},this.cacheConfig)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class g1{constructor(T,_,F,W,J){this.table=T,this.session=_,this.dialect=F,this.withList=W,this.overridingSystemValue_=J}static[H]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let _=T.map((F)=>{let W={},J=this.table[I.Symbol.Columns];for(let Y of Object.keys(F)){let $=F[Y];W[Y]=R($,k)?$:new Q_($,J[Y])}return W});return new M8(this.table,_,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let _=typeof T==="function"?T(new zW):T;if(!R(_,k)&&!ZW(this.table[H1],_._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new M8(this.table,_,this.session,this.dialect,this.withList,!0)}}class M8 extends aT{constructor(T,_,F,W,J,Y,$){super();this.session=F,this.dialect=W,this.config={table:T,values:_,withList:J,select:Y,overridingSystemValue_:$}}static[H]="PgInsert";config;cacheConfig;returning(T=this.config.table[I.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=L_(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=U`do nothing`;else{let _="";_=Array.isArray(T.target)?T.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let F=T.where?U` where ${T.where}`:void 0;this.config.onConflict=U`(${U.raw(_)})${F} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let _=T.where?U` where ${T.where}`:void 0,F=T.targetWhere?U` where ${T.targetWhere}`:void 0,W=T.setWhere?U` where ${T.setWhere}`:void 0,J=this.dialect.buildUpdateSet(this.config.table,w1(this.config.table,T.set)),Y="";return Y=Array.isArray(T.target)?T.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=U`(${U.raw(Y)})${F} do update set ${J}${_}${W}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"insert",tables:y_(this.config.table)},this.cacheConfig)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class w8 extends aT{constructor(T,_,F){super();this.session=_,this.dialect=F,this.config={view:T}}static[H]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class m1{constructor(T,_,F,W){this.table=T,this.session=_,this.dialect=F,this.withList=W}static[H]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new m5(this.table,w1(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class m5 extends aT{constructor(T,_,F,W,J){super();this.session=F,this.dialect=W,this.config={set:_,table:T,withList:J,joins:[]},this.tableName=a_(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[H]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(T){let _=T,F=a_(_);if(typeof F==="string")this.joinsNotNullableMap[F]=!0;return this.config.from=_,this}getTableLikeFields(T){if(R(T,vT))return T[I.Symbol.Columns];else if(R(T,IT))return T._.selectedFields;return T[MT].selectedFields}createJoin(T){return(_,F)=>{let W=a_(_);if(typeof W==="string"&&this.config.joins.some((J)=>J.alias===W))throw new Error(`Alias "${W}" is already used in this query`);if(typeof F==="function"){let J=this.config.from&&!R(this.config.from,k)?this.getTableLikeFields(this.config.from):void 0;F=F(new Proxy(this.config.table[I.Symbol.Columns],new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),J&&new Proxy(J,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:F,table:_,joinType:T,alias:W}),typeof W==="string")switch(T){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!0;break}case"inner":{this.joinsNotNullableMap[W]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[I.Symbol.Columns]),this.config.from){let _=a_(this.config.from);if(typeof _==="string"&&this.config.from&&!R(this.config.from,k)){let F=this.getTableLikeFields(this.config.from);T[_]=F}for(let F of this.config.joins){let W=a_(F.table);if(typeof W==="string"&&!R(F.table,k)){let J=this.getTableLikeFields(F.table);T[W]=J}}}}return this.config.returningFields=T,this.config.returning=L_(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){let _=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"insert",tables:y_(this.config.table)},this.cacheConfig);return _.joinsNotNullableMap=this.joinsNotNullableMap,_}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class KW extends k{constructor(T){super(KW.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=KW.buildCount(T.source,T.filters)}sql;token;static[H]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,_){return U`(select count(*) from ${T}${U.raw(" where ").if(_)}${_})`}static buildCount(T,_){return U`select count(*) as count from ${T}${U.raw(" where ").if(_)}${_};`}setToken(T){return this.token=T,this}then(T,_){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,_)}catch(T){return this.then(void 0,T)}finally(T){return this.then((_)=>{return T?.(),_},(_)=>{throw T?.(),_})}}class R8{constructor(T,_,F,W,J,Y,$){this.fullSchema=T,this.schema=_,this.tableNamesMap=F,this.table=W,this.tableConfig=J,this.dialect=Y,this.session=$}static[H]="PgRelationalQueryBuilder";findMany(T){return new Q8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new Q8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class Q8 extends aT{constructor(T,_,F,W,J,Y,$,Z,G){super();this.fullSchema=T,this.schema=_,this.tableNamesMap=F,this.table=W,this.tableConfig=J,this.dialect=Y,this.session=$,this.config=Z,this.mode=G}static[H]="PgRelationalQuery";_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:_,builtQuery:F}=this._toSQL();return this.session.prepareQuery(F,void 0,T,!0,(W,J)=>{let Y=W.map(($)=>N1(this.schema,this.tableConfig,$,_.selection,J));if(this.mode==="first")return Y[0];return Y})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),_=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:_}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class E8 extends aT{constructor(T,_,F,W){super();this.execute=T,this.sql=_,this.query=F,this.mapBatchResult=W}static[H]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,_){return _?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class VW{constructor(T,_,F){if(this.dialect=T,this.session=_,this._=F?{schema:F.schema,fullSchema:F.fullSchema,tableNamesMap:F.tableNamesMap,session:_}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:_},this.query={},this._.schema)for(let[W,J]of Object.entries(this._.schema))this.query[W]=new R8(F.fullSchema,this._.schema,this._.tableNamesMap,F.fullSchema[W],J,T,_);this.$cache={invalidate:async(W)=>{}}}static[H]="PgDatabase";query;$with=(T,_)=>{let F=this;return{as:(J)=>{if(typeof J==="function")J=J(new zW(F.dialect));return new Proxy(new WW(J.getSQL(),_??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,_){return new KW({source:T,filters:_,session:this.session})}$cache;with(...T){let _=this;function F(G){return new eT({fields:G??void 0,session:_.session,dialect:_.dialect,withList:T})}function W(G){return new eT({fields:G??void 0,session:_.session,dialect:_.dialect,withList:T,distinct:!0})}function J(G,X){return new eT({fields:X??void 0,session:_.session,dialect:_.dialect,withList:T,distinct:{on:G}})}function Y(G){return new m1(G,_.session,_.dialect,T)}function $(G){return new g1(G,_.session,_.dialect,T)}function Z(G){return new p1(G,_.session,_.dialect,T)}return{select:F,selectDistinct:W,selectDistinctOn:J,update:Y,insert:$,delete:Z}}select(T){return new eT({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new eT({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,_){return new eT({fields:_??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new m1(T,this.session,this.dialect)}insert(T){return new g1(T,this.session,this.dialect)}delete(T){return new p1(T,this.session,this.dialect)}refreshMaterializedView(T){return new w8(T,this.session,this.dialect)}authToken;execute(T){let _=typeof T==="string"?U.raw(T):T.getSQL(),F=this.dialect.sqlToQuery(_),W=this.session.prepareQuery(F,void 0,void 0,!1);return new E8(()=>W.execute(void 0,this.authToken),_,F,(J)=>W.mapResult(J,!0))}transaction(T,_){return this.session.transaction(T,_)}}class o5{static[H]="Cache"}class LW extends o5{strategy(){return"all"}static[H]="NoopCache";async get(T){return}async put(T,_,F,W){}async onMutate(T){}}async function z8(T,_){let F=`${T}-${JSON.stringify(_)}`,J=new TextEncoder().encode(F),Y=await crypto.subtle.digest("SHA-256",J);return[...new Uint8Array(Y)].map((G)=>G.toString(16).padStart(2,"0")).join("")}class T0 extends Error{constructor(T,_,F){super(`Failed query: ${T}
|
|
77
|
+
params: ${_}`);if(this.query=T,this.params=_,this.cause=F,Error.captureStackTrace(this,T0),F)this.cause=F}}class K8{constructor(T,_,F,W){if(this.query=T,this.cache=_,this.queryMetadata=F,this.cacheConfig=W,_&&_.strategy()==="all"&&W===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(T,_){return T}setToken(T){return this.authToken=T,this}static[H]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(T,_,F){if(this.cache===void 0||R(this.cache,LW)||this.queryMetadata===void 0)try{return await F()}catch(W){throw new T0(T,_,W)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await F()}catch(W){throw new T0(T,_,W)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[W]=await Promise.all([F(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return W}catch(W){throw new T0(T,_,W)}if(!this.cacheConfig)try{return await F()}catch(W){throw new T0(T,_,W)}if(this.queryMetadata.type==="select"){let W=await this.cache.get(this.cacheConfig.tag??await z8(T,_),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(W===void 0){let J;try{J=await F()}catch(Y){throw new T0(T,_,Y)}return await this.cache.put(this.cacheConfig.tag??await z8(T,_),J,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),J}return W}try{return await F()}catch(W){throw new T0(T,_,W)}}}class V8{constructor(T){this.dialect=T}static[H]="PgSession";execute(T,_){return AT.startActiveSpan("drizzle.operation",()=>{return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(_).execute(void 0,_)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,_){let F=await this.execute(T,_);return Number(F[0].count)}}class L8 extends VW{constructor(T,_,F,W=0){super(T,_,F);this.schema=F,this.nestedIndex=W}static[H]="PgTransaction";rollback(){throw new g2}getTransactionConfigSQL(T){let _=[];if(T.isolationLevel)_.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)_.push(T.accessMode);if(typeof T.deferrable==="boolean")_.push(T.deferrable?"deferrable":"not deferrable");return U.raw(_.join(" "))}setTransaction(T){return this.session.execute(U`set transaction ${this.getTransactionConfigSQL(T)}`)}}class u5 extends K8{constructor(T,_,F,W,J,Y,$,Z,G,X){super({sql:_,params:F},J,Y,$);this.client=T,this.queryString=_,this.params=F,this.logger=W,this.fields=Z,this._isResponseInArrayMode=G,this.customResultMapper=X}static[H]="PostgresJsPreparedQuery";async execute(T={}){return AT.startActiveSpan("drizzle.execute",async(_)=>{let F=h2(this.params,T);_?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F);let{fields:W,queryString:J,client:Y,joinsNotNullableMap:$,customResultMapper:Z}=this;if(!W&&!Z)return AT.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(J,F,async()=>{return await Y.unsafe(J,F)})});let G=await AT.startActiveSpan("drizzle.driver.execute",()=>{return _?.setAttributes({"drizzle.query.text":J,"drizzle.query.params":JSON.stringify(F)}),this.queryWithCache(J,F,async()=>{return await Y.unsafe(J,F).values()})});return AT.startActiveSpan("drizzle.mapResponse",()=>{return Z?Z(G):G.map((X)=>u$(W,X,$))})})}all(T={}){return AT.startActiveSpan("drizzle.execute",async(_)=>{let F=h2(this.params,T);return _?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F),AT.startActiveSpan("drizzle.driver.execute",()=>{return _?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.queryWithCache(this.queryString,F,async()=>{return this.client.unsafe(this.queryString,F)})})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class DW extends V8{constructor(T,_,F,W={}){super(_);this.client=T,this.schema=F,this.options=W,this.logger=W.logger??new o2,this.cache=W.cache??new LW}static[H]="PostgresJsSession";logger;cache;prepareQuery(T,_,F,W,J,Y,$){return new u5(this.client,T.sql,T.params,this.logger,this.cache,Y,$,_,W,J)}query(T,_){return this.logger.logQuery(T,_),this.client.unsafe(T,_).values()}queryObjects(T,_){return this.client.unsafe(T,_)}transaction(T,_){return this.client.begin(async(F)=>{let W=new DW(F,this.dialect,this.schema,this.options),J=new D8(this.dialect,W,this.schema);if(_)await J.setTransaction(_);return T(J)})}}class D8 extends L8{constructor(T,_,F,W=0){super(T,_,F,W);this.session=_}static[H]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((_)=>{let F=new DW(_,this.dialect,this.schema,this.session.options),W=new D8(this.dialect,F,this.schema);return T(W)})}}class c5 extends VW{static[H]="PostgresJsDatabase"}function MF(T,_={}){let F=(G)=>G;for(let G of["1184","1082","1083","1114","1182","1185","1115","1231"])T.options.parsers[G]=F,T.options.serializers[G]=F;T.options.serializers["114"]=F,T.options.serializers["3802"]=F;let W=new v0({casing:_.casing}),J;if(_.logger===!0)J=new m2;else if(_.logger!==!1)J=_.logger;let Y;if(_.schema){let G=w5(_.schema,R5);Y={fullSchema:_.schema,schema:G.tables,tableNamesMap:G.tableNamesMap}}let $=new DW(T,W,Y,{logger:J,cache:_.cache}),Z=new c5(W,$,Y);if(Z.$client=T,Z.$cache=_.cache,Z.$cache)Z.$cache.invalidate=_.cache?.onMutate;return Z}function o1(...T){if(typeof T[0]==="string"){let _=OF(T[0]);return MF(_,T[1])}if(l$(T[0])){let{connection:_,client:F,...W}=T[0];if(F)return MF(F,W);if(typeof _==="object"&&_.url!==void 0){let{url:Y,...$}=_,Z=OF(Y,$);return MF(Z,W)}let J=OF(_);return MF(J,W)}return MF(T[0],T[1])}((T)=>{function _(F){return MF({options:{parsers:{},serializers:{}}},F)}T.mock=_})(o1||(o1={}));var I8={};nG(I8,{users:()=>x0,untrackedUserColumnNames:()=>a3,twoFactorMethod:()=>n5,trackedUserColumnName:()=>e3,trackableUserColumnNames:()=>t5,signInHistory:()=>_O,role:()=>l5,players:()=>S8,passwordResetAttempts:()=>FO,games:()=>c1,banishedIps:()=>WO,accountActions:()=>TO,accountAction:()=>i5});function L0(){return dT({length:24}).$type()}function d5(T){return U`lower(${T})`}var u1=U`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,l5=FW("role",["admin","user"]),x0=z0("users",{id:D_().primaryKey().defaultRandom(),username:dT({length:16}).notNull(),emailOffered:dT({length:254}).notNull(),emailVerified:dT({length:254}),password:dT({length:254}),createdAtIso:L0().notNull().default(u1),createdIp:dT({length:45}).notNull(),isActive:XW().notNull().default(!1),verifiedAtIso:L0(),userRole:l5().default("user")},(T)=>[A8("usernameUniqueIndex").on(d5(T.username)),A8("emailVerifiedUniqueIndex").on(d5(T.emailVerified))]),a3=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],t5=["username","emailOffered","emailVerified","password","userRole"],e3=FW("trackedUserColumnName",t5),i5=FW("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),TO=z0("accountActions",{userId:D_().references(()=>x0.id).primaryKey(),action:i5().notNull(),code:dT({length:254}).notNull(),wrongCodeCount:GW().notNull().default(0),expiresAtIso:L0().notNull()}),c1=z0("games",{id:D_().primaryKey().defaultRandom()}),S8=z0("players",{userId:D_().notNull().references(()=>x0.id,{onDelete:"cascade"}),gameId:D_().notNull().references(()=>c1.id,{onDelete:"cascade"}),score:GW().notNull()},(T)=>[uX({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),_O=z0("signInHistory",{id:D_().primaryKey().defaultRandom(),userId:D_().references(()=>x0.id,{onDelete:"cascade"}),signInTimeIso:L0().notNull().default(u1),ipAddress:dT({length:45}).notNull(),userAgent:dT({length:1024}),successful:XW().notNull().default(!1)}),n5=FW("twoFactorMethod",["email","phone"]),FO=z0("passwordResetAttempts",{id:D_().primaryKey().defaultRandom(),userId:D_().notNull().references(()=>x0.id,{onDelete:"cascade"}),requestedIp:dT({length:45}).notNull(),requestedAtIso:L0().notNull().default(u1),succeededIp:dT({length:45}),succeededAtIso:L0(),verificationMethod:n5().notNull()}),WO=z0("banishedIps",{ip:dT({length:45}).primaryKey(),reason:dT({length:2048}).notNull(),banishedAtIso:L0().notNull().default(u1),banishedUntilIso:L0()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class N8{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(JO.resolve(__dirname,"notify_update.sql"));let T=[xT(x0),xT(c1),xT(S8)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(_)=>{let F=_.split(","),W=F[0],J=F[1],Y=`${W}("${J}")`;if(this.observers.has(Y))this.observers.get(Y).next(Y)})}constructor(T=!1,_={host:q_.POSTGRES_HOST,port:q_.POSTGRES_PORT,user:q_.POSTGRES_USER,password:q_.POSTGRES_PASSWORD,database:q_.POSTGRES_DATABASE}){this.options=_,this.sql=OF(_),this.drizzle=o1(this.sql,{schema:I8,logger:T})}observe(T,_){if(!this.observers.has(T))this.observers.set(T,new FT);this.observers.get(T).subscribe("SINGLETON",_)}}var d1={100:'"Continue"',101:'"Switching Protocols"',102:'"Processing"',103:'"Early Hints"',200:'"OK"',201:'"Created"',202:'"Accepted"',203:'"Non-Authoritative Information"',204:'"No Content"',205:'"Reset Content"',206:'"Partial Content"',207:'"Multi-Status"',208:'"Already Reported"',226:'"IM Used"',300:'"Multiple Choices"',301:'"Moved Permanently"',302:'"Found"',303:'"See Other"',304:'"Not Modified"',305:'"Use Proxy"',306:'"Switch Proxy"',307:'"Temporary Redirect"',308:'"Permanent Redirect"',400:'"Bad Request"',401:'"Unauthorized"',402:'"Payment Required"',403:'"Forbidden"',404:'"Not Found"',405:'"Method Not Allowed"',406:'"Not Acceptable"',407:'"Proxy Authentication Required"',408:'"Request Timeout"',409:'"Conflict"',410:'"Gone"',411:'"Length Required"',412:'"Precondition Failed"',413:'"Payload Too Large"',414:'"URI Too Long"',415:'"Unsupported Media Type"',416:'"Range Not Satisfiable"',417:'"Expectation Failed"',418:`"I'm a teapot"`,421:'"Misdirected Request"',422:'"Unprocessable Entity"',423:'"Locked"',424:'"Failed Dependency"',425:'"Too Early"',426:'"Upgrade Required"',428:'"Precondition Required"',429:'"Too Many Requests"',431:'"Request Header Fields Too Large"',451:'"Unavailable For Legal Reasons"',500:'"Internal Server Error"',501:'"Not Implemented"',502:'"Bad Gateway"',503:'"Service Unavailable"',504:'"Gateway Timeout"',505:'"HTTP Version Not Supported"',506:'"Variant Also Negotiates"',507:'"Insufficient Storage"',508:'"Loop Detected"',510:'"Not Extended"',511:'"Network Authentication Required"'};function YO(T){return Number.parseInt(T,10)}var $O=Y_(d1),ZO=$O.keyof().pipe((T)=>YO(T)),r5=Y_([ZO,"string"]);var B8=new N2,{logger:G_}=B8;Object.assign(console,G_,{log:G_.info});G_.info("ready");var C8=a5(import.meta.dir,"..","app"),ey=new N8({logQuery(T,_){G_.info("\uD83D\uDCDD query",T,_)}});HO({hostname:"0.0.0.0",port:q_.FRONTEND_PORT??3333,...X1??void 0,async fetch(T){try{let _=new Date,F=new URL(T.url);if(G_.info(T.method,F.pathname),F.pathname==="/")return new Response(Bun.file(a5(C8,"index.html")));if(F.pathname==="/index.html")return Response.redirect("/");let W=GO(C8,F.pathname),J=AO(W);if(!J.startsWith(C8))throw[403,"Access Denied"];if(!await s5(J).exists())return Response.redirect("/");return new Response(s5(J))}catch(_){let F=r5(_);if(F instanceof Y_.errors===!1){let[W,J]=F,$=`${d1[W]}. ${J}`;return G_.info(`\u274C ${W}: ${$}`),new Response($,{status:W})}if(_ instanceof Error)G_.error(_.message);else{let W=E$(_);G_.error("frontend server threw",W)}return new Response(d1[500],{status:500})}}});function l1(){G_.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{G_.info("\u2757 received SIGINT; exiting gracefully"),l1()});process.on("SIGTERM",()=>{G_.info("\u2757 received SIGTERM; exiting gracefully"),l1()});process.on("exit",()=>{G_.info("\u2757 received exit; exiting gracefully"),l1()});B8.on("timeToStop",()=>{G_.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),l1()});var{version:OO}=await Bun.file(XO.resolve(import.meta.dir,"../package.json")).json();G_.info(`\uD83D\uDEEB frontend v${OO} running at http://localhost:${q_.FRONTEND_PORT}/`);B8.emit("alive");
|