@paroicms/content-loading-plugin 0.27.23 → 0.27.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1,2 @@
|
|
|
1
|
-
.PaSearchApp-form{
|
|
1
|
+
.PaSearchApp-form{justify-content:center;margin-bottom:20px;display:flex}.PaSearchOpenerButton{cursor:pointer;display:flex}.PaSearchOpenerButton-svg{fill:currentColor}.PaSearchOpener{box-sizing:border-box;flex-direction:column;justify-content:center;align-items:center;gap:20px;width:100%;max-width:500px;padding:30px 0;display:flex}.PaSearchOpener-input{width:100%;padding:10px;font-size:1.2rem}.PaSearchOpener-button{cursor:pointer;padding:20px 25px}
|
|
2
|
+
/*$vite$:1*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{delegateEvents as gn,insert as _,setAttribute as At,template as V,isServer as Ue,getRequestEvent as Gt,createComponent as E,memo as Wt,effect as ft,render as Ur,setStyleProperty as ho}from"https://cdn.jsdelivr.net/npm/solid-js@1.9.11/web/+esm";import{createMemo as Z,getOwner as Tr,runWithOwner as _r,useContext as Jr,createContext as Vr,createSignal as Y,createRenderEffect as po,on as He,startTransition as fo,resetErrorBoundaries as mo,batch as go,untrack as Gr,createComponent as yo,children as Wr,mergeProps as bo,Show as Se,createRoot as $o,onCleanup as Hr,sharedConfig as Dt,createEffect as Zr}from"https://cdn.jsdelivr.net/npm/solid-js@1.9.11/+esm";import wo from"https://cdn.jsdelivr.net/npm/@paroicms/tiny-modal@0.8.3/+esm";function vo(t){let e=t;const n=e.indexOf("?");n!==-1&&(e=e.substring(0,n));const r=e.indexOf("#");r!==-1&&(e=e.substring(0,r));const i=e.lastIndexOf("/");return i===-1?void 0:e.slice(0,i)}function X(t){return t!=null&&t!==""}const Ze=t=>Array.isArray(t)?t:[t],xo=(t,e)=>{const n=[[],[]];for(const r of t)e(r)?n[0].push(r):n[1].push(r);return n},Yr=Array,re=(t,e)=>t.includes(e),ko=(t,e=0)=>[...new Array(t)].map((n,r)=>r+e),N=(t,e,n)=>t===void 0?e===void 0?[]:Array.isArray(e)?e:[e]:(Array.isArray(e)?t.push(...e):t.push(e),t),ge=(t,e)=>e==null?t??[]:t==null?Ze(e):t.concat(e),Ao=(...t)=>t.reduce(ge,[]),ye=(t,e,n)=>{if(t===void 0)return Array.isArray(e)?e:[e];const r=n?.isEqual??((i,s)=>i===s);for(const i of Ze(e))t.some(s=>r(s,i))||t.push(i);return t},Io=(t,e)=>t.reduce((n,r)=>{const i=r[e];return n[i]=N(n[i],r),n},{}),Ce=(t,e,n)=>t.length===e.length&&t.every(n?.isEqual?(r,i)=>n.isEqual(r,e[i]):(r,i)=>r===e[i]),$e=(t,e)=>Q(t)===e,Q=t=>{const e=typeof t;return e==="object"?t===null?"null":"object":e==="function"?"object":e},ie={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},So={...ie,function:"a function"};class No extends Error{}const K=t=>Me(t,No),Me=(t,e=Error)=>{throw new e(t)};class Oo extends Error{name="ParseError"}const d=t=>Me(t,Oo),Qr=t=>` ${t}`,Ro="",O=(t,e)=>{const n={},r=Array.isArray(t);let i=!1;for(const[s,o]of Object.entries(t).entries()){const a=r?e(s,o[1]):e(...o,s);i||=typeof a[0]=="number";const c=Array.isArray(a[0])||a.length===0?a:[a];for(const[l,u]of c)typeof l=="object"?n[l.group]=N(n[l.group],u):n[l]=u}return i?Object.values(n):n},Xr=Object.entries,te=(t,e)=>t in e,yn=(t,e)=>e in t;class Co{constructor(e){Object.assign(this,e)}}const Mo=class{};class ei extends Mo{}const Po=(t,e)=>{const n={},r={};let i;for(i in t)i in e?n[i]=t[i]:r[i]=t[i];return[n,r]},ti=(t,e)=>Po(t,e)[1],Ye=t=>Object.keys(t).length===0,mt=t=>[...Object.entries(t),...Object.getOwnPropertySymbols(t).map(e=>[e,t[e]])],qo=(t,e)=>Object.defineProperties(t,Object.getOwnPropertyDescriptors(e)),Eo=t=>{const e=Object.keys(t).sort(),n={};for(let r=0;r<e.length;r++)n[e[r]]=t[e[r]];return n},ee=Qr(`unset${Ro}`),Do=t=>Object.values(t).filter(e=>typeof e=="number"?!0:typeof t[e]!="number"),ni={Array:Array,Boolean:Boolean,Date:Date,Error:Error,Function:Function,Map:Map,Number:Number,Promise:Promise,RegExp:RegExp,Set:Set,String:String,WeakMap:WeakMap,WeakSet:WeakSet},ri=globalThis.File??Blob,ii={ArrayBuffer:ArrayBuffer,Blob:Blob,File:ri,FormData:FormData,Headers:Headers,Request:Request,Response:Response,URL:URL},Ko={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array,BigInt64Array:BigInt64Array,BigUint64Array:BigUint64Array},Pe={...ni,...ii,...Ko,String:String,Number:Number,Boolean:Boolean},bn=t=>{let e=Object.getPrototypeOf(t);for(;e?.constructor&&(!te(e.constructor.name,Pe)||!(t instanceof Pe[e.constructor.name]));)e=Object.getPrototypeOf(e);const n=e?.constructor?.name;if(!(n===void 0||n==="Object"))return n},Ht=t=>typeof t=="object"&&t!==null?bn(t)??"object":Q(t),F=Array.isArray,Lo={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"},Bo={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"},jo={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"},Fo={...Lo,...Bo,...jo},$n=t=>{const e=Object(t).name??null;return e&&te(e,Pe)&&Pe[e]===t?e:null},zn=(t,e)=>{let n=t.prototype;for(;n!==null;){if(n===e.prototype)return!0;n=Object.getPrototypeOf(n)}return!1},zo=t=>si(t,new Map),si=(t,e)=>{if(typeof t!="object"||t===null)return t;if(e?.has(t))return e.get(t);const n=$n(t.constructor);if(n==="Date")return new Date(t.getTime());if(n&&n!=="Array")return t;const r=Array.isArray(t)?t.slice():Object.create(Object.getPrototypeOf(t)),i=Object.getOwnPropertyDescriptors(t);if(e){e.set(t,r);for(const s in i){const o=i[s];"get"in o||"set"in o||(o.value=si(o.value,e))}}return Object.defineProperties(r,i),r},Uo=t=>{let e=ee;return()=>e===ee?e=t():e},It=t=>typeof t=="function"&&t.length===0,To=class extends Function{constructor(...t){const e=t.slice(0,-1),n=t[t.length-1];try{super(...e,n)}catch(r){return K(`Encountered an unexpected error while compiling your definition:\n Message: ${r} \n Source: (${t.slice(0,-1)}) => {\n ${t[t.length-1]}\n }`)}}};class pe{constructor(e,...[n]){return Object.assign(Object.setPrototypeOf(e.bind(n?.bind??this),this.constructor.prototype),n?.attach)}}const _o=Uo(()=>{try{return new Function("return false")()}catch{return!0}});class ne{constructor(){}}const Jo=()=>{try{return(((new Error).stack?.split(`\n`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},Vo=globalThis.process?.env??{},Go={fileName:Jo,env:Vo},Wo=t=>t[0].toUpperCase()+t.slice(1),Ho=t=>t[0].toLowerCase()+t.slice(1),oi=t=>new RegExp(Zo(t),typeof t=="string"?"":t.flags),Zo=t=>`^(?:${typeof t=="string"?t:t.source})$`,ue={negativeLookahead:t=>`(?!${t})`,nonCapturingGroup:t=>`(?:${t})`},Te="\\",St={" ":1,"\n":1,"\t":1},Yo=/^-0\.?0*$/.source,ai=/[1-9]\d*/.source,Qo=/\.\d+/.source,Xo=/\.\d*[1-9]/.source,ci=t=>oi(ue.negativeLookahead(Yo)+ue.nonCapturingGroup("-?"+ue.nonCapturingGroup(ue.nonCapturingGroup("0|"+ai)+ue.nonCapturingGroup(t.decimalPattern)+"?")+(t.allowDecimalOnly?"|"+t.decimalPattern:"")+"?")),Un=ci({decimalPattern:Xo,allowDecimalOnly:!1}),ea=Un.test.bind(Un),Zt=ci({decimalPattern:Qo,allowDecimalOnly:!0});Zt.test.bind(Zt);const ta=/^-?\d*\.?\d*$/,na=t=>t.length!==0&&ta.test(t),gt=oi(ue.negativeLookahead("^-0$")+"-?"+ue.nonCapturingGroup(ue.nonCapturingGroup("0|"+ai))),ra=gt.test.bind(gt),Yt=/^-?\d+$/,ia=Yt.test.bind(Yt),li={number:"a number",bigint:"a bigint",integer:"an integer"},ui=(t,e)=>`'${t}' was parsed as ${li[e]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,sa=(t,e)=>e==="number"?ea(t):ra(t),oa=(t,e)=>e==="number"?Number(t):Number.parseInt(t),aa=(t,e)=>e==="number"?na(t):ia(t),ca=(t,e)=>wn(t,"number",e),la=(t,e)=>wn(t,"number",{...e,strict:!0}),ua=(t,e)=>wn(t,"integer",e),wn=(t,e,n)=>{const r=oa(t,e);return!Number.isNaN(r)&&aa(t,e)?n?.strict?sa(t,e)?r:d(ui(t,e)):r:n?.errorOnFail?d(n?.errorOnFail===!0?`Failed to parse ${li[e]} from '${t}'`:n?.errorOnFail):void 0},da=t=>{if(t[t.length-1]!=="n")return;const e=t.slice(0,-1);let n;try{n=BigInt(e)}catch{return}if(gt.test(e))return n;if(Yt.test(e))return d(ui(t,"bigint"))},ha="0.56.0",pa={version:ha,filename:Go.fileName(),FileConstructor:ri},Qe=pa,Tn=new Map,Kt=Object.create(null),Qt=t=>{const e=Tn.get(t);if(e)return e;let n=fa(t);return Kt[n]?n=`${n}${Kt[n]++}`:Kt[n]=1,Qe[n]=t,Tn.set(t,n),n},Ge=t=>/^[$A-Z_a-z][\w$]*$/.test(t),fa=t=>{switch(typeof t){case"object":{if(t===null)break;const e=bn(t)??"object";return e[0].toLowerCase()+e.slice(1)}case"function":return Ge(t.name)?t.name:"fn";case"symbol":return t.description&&Ge(t.description)?t.description:"symbol"}return K(`Unexpected attempt to register serializable value of type ${Q(t)}`)},vn=t=>typeof t=="string"?JSON.stringify(t):typeof t=="bigint"?`${t}n`:`${t}`,ma=(t,e={})=>_e(t,{onUndefined:"$ark.undefined",onBigInt:n=>`$ark.bigint-${n}`,...e},[]),S=(t,e)=>{switch(Q(t)){case"object":const n=t,r=n.constructor?.name??"Object";return r==="Object"||r==="Array"?e?.quoteKeys===!1?yt(n,e?.indent??0,""):JSON.stringify(_e(n,qe,[]),null,e?.indent):yt(n,e?.indent??0,"");case"symbol":return qe.onSymbol(t);default:return vn(t)}},yt=(t,e,n)=>{if(typeof t=="function")return qe.onFunction(t);if(typeof t!="object"||t===null)return vn(t);const r=n+" ".repeat(e);if(Array.isArray(t)){if(t.length===0)return"[]";const s=t.map(o=>yt(o,e,r)).join(`,\n`+r);return e?`[\n${r}${s}\n${n}]`:`[${s}]`}const i=t.constructor?.name??"Object";if(i==="Object"){const s=mt(t).map(([o,a])=>{const c=typeof o=="symbol"?qe.onSymbol(o):Ge(o)?o:JSON.stringify(o),l=yt(a,e,r);return`${r}${c}: ${l}`});return s.length===0?"{}":e?`{\n${s.join(`,\n`)}\n${n}}`:`{${s.join(", ")}}`}return t instanceof Date?Xe(t):"expression"in t&&typeof t.expression=="string"?t.expression:i},qe={onCycle:()=>"(cycle)",onSymbol:t=>`Symbol(${Qt(t)})`,onFunction:t=>`Function(${Qt(t)})`},_e=(t,e,n)=>{switch(Q(t)){case"object":{const r=t;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();if(typeof r=="function")return qe.onFunction(r);if(n.includes(r))return"(cycle)";const i=[...n,r];if(Array.isArray(r))return r.map(o=>_e(o,e,i));if(r instanceof Date)return r.toDateString();const s={};for(const o in r)s[o]=_e(r[o],e,i);for(const o of Object.getOwnPropertySymbols(r))s[e.onSymbol?.(o)??o.toString()]=_e(r[o],e,i);return s}case"symbol":return qe.onSymbol(t);case"bigint":return e.onBigInt?.(t)??`${t}n`;case"undefined":return e.onUndefined??"undefined";case"string":return t.replace(/\\/g,"\\\\");default:return t}},Xe=t=>{const e=t.getFullYear(),n=t.getMonth(),r=t.getDate(),i=t.getHours(),s=t.getMinutes(),o=t.getSeconds(),a=t.getMilliseconds();if(n===0&&r===1&&i===0&&s===0&&o===0&&a===0)return`${e}`;const c=`${ga[n]} ${r}, ${e}`;if(i===0&&s===0&&o===0&&a===0)return c;let l=t.toLocaleTimeString();const u=l.endsWith(" AM")||l.endsWith(" PM")?l.slice(-3):"";return u&&(l=l.slice(0,-u.length)),a?l+=`.${ba(a,3)}`:ya.test(l)&&(l=l.slice(0,-3)),`${l+u}, ${c}`},ga=["January","February","March","April","May","June","July","August","September","October","November","December"],ya=/:\d\d:00$/,ba=(t,e)=>String(t).padStart(e,"0"),di=(t,e,...[n])=>{const r=n?.stringifySymbol??S;let i=t;switch(typeof e){case"string":i=Ge(e)?t===""?e:`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;break;case"number":i=`${t}[${e}]`;break;case"symbol":i=`${t}[${r(e)}]`;break;default:n?.stringifyNonKey?i=`${t}[${n.stringifyNonKey(e)}]`:d(`${S(e)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return i},et=(t,...e)=>t.reduce((n,r)=>di(n,r,...e),"");class hi extends Yr{cache={};constructor(...e){super(),this.push(...e)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let e=0;e<this.length;e++)this.cache.json.push(typeof this[e]=="symbol"?S(this[e]):this[e]);return this.cache.json}stringify(){return this.cache.stringify?this.cache.stringify:this.cache.stringify=et(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e="";const n=[e];for(const r of this)e=di(e,r),n.push(e);return this.cache.stringifyAncestors=n}}class pi{chars;i;def;constructor(e){this.def=e,this.chars=[...e],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(e){let n="";for(;this.lookahead&&!e(this,n);)n+=this.shift();return n}shiftUntilEscapable(e){let n="";for(;this.lookahead;)if(this.lookahead===Te)this.shift(),e(this,n)?n+=this.shift():this.lookahead===Te?n+=this.shift():n+=`${Te}${this.shift()}`;else{if(e(this,n))break;n+=this.shift()}return n}shiftUntilLookahead(e){return typeof e=="string"?this.shiftUntil(n=>n.lookahead===e):this.shiftUntil(n=>n.lookahead in e)}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in St))}jumpToIndex(e){this.i=e<0?this.length+e:e}jumpForward(e){this.i+=e}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(e,n){return this.chars.slice(e,n).join("")}lookaheadIs(e){return this.lookahead===e}lookaheadIsIn(e){return this.lookahead in e}}const $a=(t,e)=>`Unmatched ${t}${e===""?"":` before ${e}`}`,fi=t=>`Missing ${t}`;let Xt="$ark",wa=2;for(;Xt in globalThis;)Xt=`$ark${wa++}`;const mi=Xt;globalThis[mi]=Qe;const p=Qe,va=t=>`${mi}.${t}`,U=t=>va(Qt(t));class gi extends ei{argNames;body="";constructor(...e){super(),this.argNames=e;for(const n of e){if(n in this)throw new Error(`Arg name '${n}' would overwrite an existing property on FunctionBody`);this[n]=n}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(e,n=!1){return yi(e,n)}index(e,n=!1){return bi(`${e}`,n)}line(e){return this.body+=`${" ".repeat(this.indentation)}${e}\n`,this}const(e,n){return this.line(`const ${e} = ${n}`),this}let(e,n){return this.line(`let ${e} = ${n}`)}set(e,n){return this.line(`${e} = ${n}`)}if(e,n){return this.block(`if (${e})`,n)}elseIf(e,n){return this.block(`else if (${e})`,n)}else(e){return this.block("else",e)}for(e,n,r=0){return this.block(`for (let i = ${r}; ${e}; i++)`,n)}forIn(e,n){return this.block(`for (const k in ${e})`,n)}block(e,n,r=""){return this.line(`${e} {`),this.indent(),n(this),this.dedent(),this.line(`}${r}`)}return(e=""){return this.line(`return ${e}`)}write(e="anonymous",n=0){return`${e}(${this.argNames.join(", ")}) { ${n?this.body.split(`\n`).map(r=>" ".repeat(n)+`${r}`).join(`\n`):this.body} }`}compile(){return new To(...this.argNames,this.body)}}const De=t=>$e(t,"object")||typeof t=="symbol"?U(t):vn(t),yi=(t,e=!1)=>typeof t=="string"&&Ge(t)?`${e?"?":""}.${t}`:bi(xa(t),e),xa=t=>typeof t=="symbol"?U(t):JSON.stringify(t),bi=(t,e=!1)=>`${e?"?.":""}[${t}]`;class Lt extends gi{traversalKind;optimistic;constructor(e){super("data","ctx"),this.traversalKind=e.kind,this.optimistic=e.optimistic===!0}invoke(e,n){const r=n?.arg??this.data,i=typeof e=="string"?!0:this.requiresContextFor(e),s=typeof e=="string"?e:e.id;return i?`${this.referenceToId(s,n)}(${r}, ${this.ctx})`:`${this.referenceToId(s,n)}(${r})`}referenceToId(e,n){const r=n?.kind??this.traversalKind,i=`this.${e}${r}`;return n?.bind?`${i}.bind(${n?.bind})`:i}requiresContextFor(e){return this.traversalKind==="Apply"||e.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(e,n,r){const i=this.requiresContextFor(r);return i&&this.line(`${this.ctx}.path.push(${e})`),this.check(r,{arg:n}),i&&this.line(`${this.ctx}.path.pop()`),this}check(e,n){return this.traversalKind==="Allows"?this.if(`!${this.invoke(e,n)}`,()=>this.return(!1)):this.line(this.invoke(e,n))}}const $i=t=>O(t,(e,n)=>[e,F(n)?[...n]:n]),se=Qr("arkKind"),b=(t,e)=>t?.[se]===e,z=t=>b(t,"root")||b(t,"constraint"),ka=["unit","proto","domain"],Nt=["required","optional","index","sequence"],wi=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],vi=[...wi,"structure","predicate"],xn=[...vi,...Nt],Ot=["alias","union","morph","unit","intersection","proto","domain"],Aa=[...Ot,...xn],xi=O(xn,(t,e)=>[e,1]),Ia=O([...Nt,"undeclared"],(t,e)=>[e,1]),ki=O(Aa,(t,e)=>[e,t]),dt=t=>typeof t=="string"&&t in ki,bt=t=>ki[t],kn=t=>Ot.slice(bt(t)+1);[...kn("union")];[...kn("morph")];const be=t=>typeof t=="string"||typeof t=="boolean"||t===null?t:typeof t=="number"?Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t:De(t),Rt=t=>{let e="{ ";for(const[n,r]of Object.entries(t))e+=`${n}: ${De(r)}, `;return e+" }"},q=t=>{const e=t;return e.hasAssociatedError&&(e.defaults.expected??=n=>"description"in n?n.description:e.defaults.description(n),e.defaults.actual??=n=>S(n),e.defaults.problem??=n=>`must be ${n.expected}${n.actual?` (was ${n.actual})`:""}`,e.defaults.message??=n=>{if(n.path.length===0)return n.problem;const r=`${n.propString} ${n.problem}`;return r[0]==="["?`value at ${r}`:r}),e};class Sa extends Error{name="ToJsonSchemaError";code;context;constructor(e,n){super(S(n,{quoteKeys:!1,indent:4})),this.code=e,this.context=n}hasCode(e){return this.code===e}}const Na={target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:t=>L.throw("arrayObject",t),arrayPostfix:t=>L.throw("arrayPostfix",t),defaultValue:t=>L.throw("defaultValue",t),domain:t=>L.throw("domain",t),morph:t=>L.throw("morph",t),patternIntersection:t=>L.throw("patternIntersection",t),predicate:t=>L.throw("predicate",t),proto:t=>L.throw("proto",t),symbolKey:t=>L.throw("symbolKey",t),unit:t=>L.throw("unit",t),date:t=>L.throw("date",t)}},L={Error:Sa,throw:(...t)=>{throw new L.Error(...t)},throwInternalOperandError:(t,e)=>K(`Unexpected JSON Schema input for ${t}: ${S(e)}`),defaultConfig:Na};p.config??={};const en=(t,e)=>{if(!e)return t;const n={...t};let r;for(r in e){const i={...t.keywords};if(r==="keywords"){for(const s in e[r]){const o=e.keywords[s];o!==void 0&&(i[s]=typeof o=="string"?{description:o}:o)}n.keywords=i}else r==="toJsonSchema"?n[r]=Ai(t.toJsonSchema,e.toJsonSchema):dt(r)?n[r]={...t[r],...e[r]}:n[r]=e[r]}return n},Oa={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"},Ai=(t,e)=>{if(!t)return _n(e??{},void 0);if(!e)return t;const n={...t};let r;for(r in e)r==="fallback"?n.fallback=Ra(t.fallback,e.fallback):n[r]=e[r];return _n(n,e)},_n=(t,e)=>e?.dialect!==void 0?t:e?.target!==void 0?{...t,dialect:Oa[e.target]}:t,Ra=(t,e)=>{t=Jn(t),e=Jn(e);const n={};let r;for(r in L.defaultConfig.fallback)n[r]=e[r]??e.default??t[r]??t.default??L.defaultConfig.fallback[r];return n},Jn=t=>typeof t=="function"?{default:t}:t??{};class Ee extends ei{[se]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:n,...r},i){super(),this.input=r,this.ctx=i,qo(this,r);const s=i.data;r.code==="union"&&(r.errors=r.errors.flatMap(a=>{const c=a.hasCode("union")?a.errors:[a];return!e&&!n?c:c.map(l=>l.transform(u=>({...u,path:Ao(e,u.path,n)})))})),this.nodeConfig=i.config[this.code];const o=[...r.path??i.path];n&&o.push(...n),e&&o.unshift(...e),this.path=new hi(...o),this.data="data"in r?r.data:s}transform(e){return new Ee(e({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return et(this.path)}get expected(){if(this.input.expected)return this.input.expected;const e=this.meta?.expected??this.nodeConfig.expected;return typeof e=="function"?e(this.input):e}get actual(){if(this.input.actual)return this.input.actual;const e=this.meta?.actual??this.nodeConfig.actual;return typeof e=="function"?e(this.data):e}get problem(){if(this.input.problem)return this.input.problem;const e=this.meta?.problem??this.nodeConfig.problem;return typeof e=="function"?e(this):e}get message(){if(this.input.message)return this.input.message;const e=this.meta?.message??this.nodeConfig.message;return typeof e=="function"?e(this):e}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 he extends Yr{[se]="errors";ctx;constructor(e){super(),this.ctx=e}byPath=Object.create(null);get flatByPath(){return O(this.byPath,(e,n)=>[e,n.flat])}get flatProblemsByPath(){return O(this.byPath,(e,n)=>[e,n.flat.map(r=>r.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new Ca(this)}add(e){const n=this.byPath[e.propString];if(n){if(e===n||n.hasCode("union")&&n.errors.length===0)return;const r=e.hasCode("union")&&e.errors.length===0?e:new Ee({code:"intersection",errors:n.hasCode("intersection")?[...n.errors,e]:[n,e]},this.ctx),i=this.indexOf(n);this.mutable[i===-1?this.length:i]=r,this.byPath[e.propString]=r,this.addAncestorPaths(e)}else this.byPath[e.propString]=e,this.addAncestorPaths(e),this.mutable.push(e);this.count++}transform(e){const n=new he(this.ctx);for(const r of this)n.add(e(r));return n}merge(e){for(const n of e)this.add(new Ee({...n,path:[...this.ctx.path,...n.path]},this.ctx))}affectsPath(e){return this.length===0?!1:e.stringifyAncestors().some(n=>n in this.byPath)||e.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map(e=>e.toJSON())]}toString(){return this.join(`\n`)}addAncestorPaths(e){for(const n of e.path.stringifyAncestors())this.byAncestorPath[n]=N(this.byAncestorPath[n],e)}}class Ca extends Error{name="TraversalError";constructor(e){e.length===1?super(e.summary):super(`\n`+e.map(n=>` • ${Ma(n)}`).join(`\n`)),Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}}const Ma=t=>t.toString().split(`\n`).join(`\n `);class Ne{path=[];errors=new he(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(e,n){this.root=e,this.config=n}get data(){let e=this.root;for(const n of this.path)e=e?.[n];return e}get propString(){return et(this.path)}reject(e){return this.error(e),!1}mustBe(e){return this.error(e),!1}error(e){const n=typeof e=="object"?e.code?e:{...e,code:"predicate"}:{code:"predicate",expected:e};return this.errorFromContext(n)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(e){const n={path:new hi(...this.path),morphs:e};this.currentBranch?this.currentBranch.queuedMorphs.push(n):this.queuedMorphs.push(n)}finalize(e){return this.queuedMorphs.length&&(typeof this.root=="object"&&this.root!==null&&this.config.clone&&(this.root=this.config.clone(this.root)),this.applyQueuedMorphs()),this.hasError()?e?e(this.errors):this.errors: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(e){return this.errorFromContext(e)}errorFromContext(e){const n=new Ee(e,this);return this.currentBranch?this.currentBranch.error=n:this.errors.add(n),n}applyQueuedMorphs(){for(;this.queuedMorphs.length;){const e=this.queuedMorphs;this.queuedMorphs=[];for(const{path:n,morphs:r}of e)this.errors.affectsPath(n)||this.applyMorphsAtPath(n,r)}}applyMorphsAtPath(e,n){const r=e[e.length-1];let i;if(r!==void 0){i=this.root;for(let s=0;s<e.length-1;s++)i=i[e[s]]}for(const s of n){this.path=[...e];const o=z(s),a=s(i===void 0?this.root:i[r],this);if(a instanceof Ee){this.errors.includes(a)||this.errors.add(a);break}if(a instanceof he){o||this.errors.merge(a),this.queuedMorphs=[];break}i===void 0?this.root=a:i[r]=a,this.applyQueuedMorphs()}}}const oe=(t,e,n)=>{if(!n)return e();n.path.push(t);const r=e();return n.path.pop(),r};class Ii extends pe{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(e,n){super((i,s,o=this.onFail)=>s?(this.traverseApply(i,s),s.hasError()?s.errors:s.data):this.rootApply(i,o),{attach:e}),this.attachments=e,this.$=n,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0||this.hasKind("sequence")&&this.inner.defaultables!==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((i,s)=>Da(i,s.shallowReferences),[this]);const r=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let i=0;i<this.children.length;i++){if(this.includesTransform||=this.children[i].includesTransform,this.includesContextualPredicate||=this.children[i].includesContextualPredicate,this.isCyclic||=this.children[i].isCyclic,!r){const s=this.children[i].flatRefs;for(let o=0;o<s.length;o++){const a=s[o];if(!this.flatRefs.some(c=>Si(c,a))){this.flatRefs.push(a);for(const c of a.node.branches)(c.hasKind("morph")||c.hasKind("intersection")&&c.structure?.structuralMorph!==void 0)&&this.flatMorphs.push({path:a.path,propString:a.propString,node:c})}}}Object.assign(this.referencesById,this.children[i].referencesById)}this.flatRefs.sort((i,s)=>i.path.length>s.path.length?1:i.path.length<s.path.length?-1:i.propString>s.propString?1:i.propString<s.propString||i.node.expression<s.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(i=>i.length===1||i.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some(i=>i.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?i=>this.traverseAllows(i,new Ne(i,this.$.resolvedConfig)):i=>this.traverseAllows(i)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(n,r)=>{if(this.allows(n))return n;const i=new Ne(n,this.$.resolvedConfig);return this.traverseApply(n,i),i.finalize(r)};case"contextual":return(n,r)=>{const i=new Ne(n,this.$.resolvedConfig);return this.traverseApply(n,i),i.finalize(r)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];const e=this.$.resolvedConfig.clone;return(n,r)=>{if(this.allows(n))return this.contextFreeMorph(e&&(typeof n=="object"&&n!==null||typeof n=="function")?e(n):n);const i=new Ne(n,this.$.resolvedConfig);return this.traverseApply(n,i),i.finalize(r)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,K(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=Ea(this.metaJson);cacheGetter(e,n){return Object.defineProperty(this,e,{value:n}),n}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=bt(this.kind);precompilation;assert=(e,n)=>this(e,n,r=>r.throw());traverse(e,n){return this(e,n,null)}get in(){return this.cacheGetter("in",this.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter("rawIn",this.getIo("in"))}get out(){return this.cacheGetter("out",this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter("rawOut",this.getIo("out"))}getIo(e){if(!this.includesTransform)return this;const n={};for(const[r,i]of this.innerEntries){const s=this.impl.keys[r];if(s.reduceIo)s.reduceIo(e,n,i);else if(s.child){const o=i;n[r]=F(o)?o.map(a=>e==="in"?a.rawIn:a.rawOut):e==="in"?o.rawIn:o.rawOut}else n[r]=i}return this.$.node(this.kind,n)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(e){const n=z(e)?e:this.$.parseDefinition(e);return this.innerHash===n.innerHash}ifEquals(e){return this.equals(e)?this:void 0}hasKind(e){return this.kind===e}assertHasKind(e){return this.kind!==e&&Me(`${this.kind} node was not of asserted kind ${e}`),this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){return re(e,this.kind)||Me(`${this.kind} node was not one of asserted kinds ${e}`),this}isBasis(){return re(ka,this.kind)}isConstraint(){return re(xn,this.kind)}isStructural(){return re(Nt,this.kind)}isRefinement(){return re(vi,this.kind)}isRoot(){return re(Ot,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(e){return this.hasKind("unit")&&this.allows(e)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(e){const n=Fe.normalize(e);return this._select(n)}_select(e){let n=Fe.applyBoundary[e.boundary??"references"](this);return e.kind&&(n=n.filter(r=>r.kind===e.kind)),e.where&&(n=n.filter(e.where)),Fe.applyMethod[e.method??"filter"](n,this,e)}transform(e,n){return this._transform(e,this._createTransformContext(n))}_createTransformContext(e){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:e?.prereduced??!1},undeclaredKeyHandling:void 0,...e}}_transform(e,n){const r=n.bindScope??this.$;if(n.seen[this.id])return this.$.lazilyResolve(n.seen[this.id]);if(n.shouldTransform?.(this,n)===!1)return this;let i;n.seen[this.id]=()=>i,this.hasKind("structure")&&this.undeclared!==n.undeclaredKeyHandling&&(n={...n,undeclaredKeyHandling:this.undeclared});const s=O(this.inner,(u,h)=>{if(!this.impl.keys[u].child)return[u,h];const m=h;if(!F(m)){const v=m._transform(e,n);return v?[u,v]:[]}if(m.length===0)return[u,h];const y=m.flatMap(v=>v._transform(e,n)??[]);return y.length?[u,y]:[]});delete n.seen[this.id];const o=Object.assign(s,{meta:this.meta}),a=n.selected&&!n.selected.includes(this)?o:e(this.kind,o,n);if(a===null)return null;if(z(a))return i=a;const c=Object.keys(a);return(c.length===0||c.length===1&&c[0]==="meta")&&!Ye(this.inner)?null:(this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in a)?n.undeclaredKeyHandling?{...a,value:p.intrinsic.unknown}:null:(this.kind==="morph"&&(a.in??=p.intrinsic.unknown),i=r.node(this.kind,a,n.parseOptions))}configureReferences(e,n="references"){const r=Fe.normalize(n),i=typeof e=="string"?(c,l)=>({...l,meta:{...l.meta,description:e}}):typeof e=="function"?(c,l)=>({...l,meta:e(l.meta)}):(c,l)=>({...l,meta:{...l.meta,...e}});if(r.boundary==="self")return this.$.node(this.kind,i(this.kind,{...this.inner,meta:this.meta}));const s=this._select(r),o=s&&Ze(s),a=r.boundary==="child"?(c,l)=>l.root.children.includes(c):r.boundary==="shallow"?c=>c.kind!=="structure":()=>!0;return this.$.finalize(this.transform(i,{shouldTransform:a,selected:o}))}}const Fe={applyBoundary:{self:t=>[t],child:t=>[...t.children],shallow:t=>[...t.shallowReferences],references:t=>[...t.references]},applyMethod:{filter:t=>t,assertFilter:(t,e,n)=>(t.length===0&&Me(Vn(e,n)),t),find:t=>t[0],assertFind:(t,e,n)=>(t.length===0&&Me(Vn(e,n)),t[0])},normalize:t=>typeof t=="function"?{boundary:"references",method:"filter",where:t}:typeof t=="string"?te(t,Fe.applyBoundary)?{method:"filter",boundary:t}:{boundary:"references",method:"filter",kind:t}:{boundary:"references",method:"filter",...t}},Vn=(t,e)=>`${t} had no references matching ${S(e)}.`,Pa=t=>et(t,{stringifyNonKey:e=>e.expression}),qa=/"(\$ark\.[^"]+)"/g,Ea=t=>JSON.stringify(t).replace(qa,"$1"),de=(t,e)=>({path:t,node:e,propString:Pa(t)}),Si=(t,e)=>t.propString===e.propString&&t.node.equals(e.node),Gn=(t,e)=>ye(t,e,{isEqual:Si}),Da=(t,e)=>ye(t,e,{isEqual:(n,r)=>n.equals(r)});class g extends Array{static init(e,n,r,i){return new g({kind:e,l:n,r:r,path:i?.path??[],optional:i?.optional??!1})}add(e,n,r,i){return this.push({kind:e,l:n,r:r,path:i?.path??[],optional:i?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){const{path:e,l:n,r:r}=this[0],i=et(e);return Ni(`Intersection${i&&` at ${i}`} of ${Wn(n,r)}`)}return`The following intersections result in unsatisfiable types:\n• ${this.map(({path:e,l:n,r:r})=>`${e}: ${Wn(n,r)}`).join(`\n• `)}`}throw(){return d(this.describeReasons())}invert(){const e=this.map(n=>({...n,l:n.r,r:n.l}));return e instanceof g?e:new g(...e)}withPrefixKey(e,n){return this.map(r=>({...r,path:[e,...r.path],optional:r.optional||n==="optional"}))}toNeverIfDisjoint(){return p.intrinsic.never}}const Wn=(t,e)=>`${tn(t)} and ${tn(e)}`,tn=t=>z(t)?t.expression:F(t)?t.map(tn).join(" | ")||"never":String(t),Ni=t=>`${t} results in an unsatisfiable type`,Ae={},ae=(t,e,n)=>j(t,e,{$:n,invert:!1,pipe:!1}),nn=(t,e,n)=>j(t,e,{$:n,invert:!1,pipe:!0}),j=(t,e,n)=>{const r=n.pipe?"|>":"&",i=`${t.hash}${r}${e.hash}`;if(Ae[i]!==void 0)return Ae[i];if(!n.pipe){const a=`${e.hash}${r}${t.hash}`;if(Ae[a]!==void 0){const c=Ae[a],l=c instanceof g?c.invert():c;return Ae[i]=l,l}}const s=!n.pipe||!t.includesTransform&&!e.includesTransform;if(s&&t.equals(e))return t;let o=s?rn(t,e,n):t.hasKindIn(...Ot)?Ka(t,e,n):rn(t,e,n);return z(o)&&(t.equals(o)?o=t:e.equals(o)&&(o=e)),Ae[i]=o,o},rn=(t,e,n)=>{const r=t.precedence<e.precedence?t.kind:e.kind,i=t.impl.intersections[e.kind]??e.impl.intersections[t.kind];if(i===void 0)return null;if(r===t.kind)return i(t,e,n);{let s=i(e,t,{...n,invert:!n.invert});return s instanceof g&&(s=s.invert()),s}},Ka=(t,e,n)=>t.includesTransform||e.includesTransform?n.invert?Hn(e,t,n):Hn(t,e,n):rn(t,e,n),Hn=(t,e,n)=>t.distribute(r=>La(r,e,n),r=>{const i=r.filter(z);if(i.length===0)return g.init("union",t.branches,e.branches);if(i.length<t.branches.length||!t.branches.every((o,a)=>o.rawIn.equals(i[a].rawIn)))return n.$.parseSchema(i);if(i.length===1)return i[0];const s={branches:i};return n.$.parseSchema(s)}),La=(t,e,n)=>{if(t.hasKind("morph")){const i=[...t.morphs];if(t.lastMorphIfNode){const s=j(t.lastMorphIfNode,e,n);if(s instanceof g)return s;i[i.length-1]=s}else i.push(e);return n.$.node("morph",{morphs:i,in:t.inner.in})}if(e.hasKind("morph")){const i=j(t,e.rawIn,n);return i instanceof g?i:n.$.node("morph",{morphs:[e],in:i})}return n.$.node("morph",{morphs:[e],in:t})};class Ke extends Ii{constructor(e,n){super(e,n),Object.defineProperty(this,se,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(e){return ae(this,e,this.$)}}class Ct extends Ke{traverseApply=(e,n)=>{this.traverseAllows(e,n)||n.errorFromNodeContext(this.errorContext)};compile(e){e.traversalKind==="Allows"?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Rt(this.errorContext)}}const T=t=>(e,n)=>{if(F(e)){if(e.length===0)return;const i=e.map(s=>n.$.node(t,s));return t==="predicate"?i:i.sort((s,o)=>s.hash<o.hash?-1:1)}const r=n.$.node(t,e);return r.hasOpenIntersection()?[r]:r},$t=t=>{const e=t.r.shift();if(!e){let r=t.l.length===0&&t.kind==="structure"?p.intrinsic.unknown.internal:t.ctx.$.node(t.kind,Object.assign(t.baseInner,Ba(t.l)),{prereduced:!0});for(const i of t.roots){if(r instanceof g)return r;r=j(i,r,t.ctx)}return r}let n=!1;for(let r=0;r<t.l.length;r++){const i=j(t.l[r],e,t.ctx);if(i!==null){if(i instanceof g)return i;if(i.isRoot())return t.roots.push(i),t.l.splice(r),$t(t);if(!n)t.l[r]=i,n=!0;else if(!t.l.includes(i))return K(`Unexpectedly encountered multiple distinct intersection results for refinement ${e}`)}}if(n||t.l.push(e),t.kind==="intersection"&&e.impliedSiblings)for(const r of e.impliedSiblings)ye(t.r,r);return $t(t)},wt=t=>Object.entries(t).flatMap(([n,r])=>n in xi?r:[]).sort((n,r)=>n.precedence<r.precedence?-1:n.precedence>r.precedence?1:n.kind==="predicate"&&r.kind==="predicate"?0:n.hash<r.hash?-1:1),Ba=t=>{const e={};for(const n of t)if(n.hasOpenIntersection())e[n.kind]=N(e[n.kind],n);else{if(e[n.kind])return K(`Unexpected intersection of closed refinements of kind ${n.kind}`);e[n.kind]=n}return e},ja=(...t)=>d(Fa(...t)),Fa=(t,e,n)=>{const r=n.hasKind("morph")?"a morph":n.isUnknown()?"unknown":n.exclude(e).defaultShortDescription;return`${Wo(t)} operand must be ${e.description} (was ${r})`},za=(t,e,n)=>new vt(t,e,n,n,null);class Oi extends pe{}class vt extends pe{[se]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,n,r,i,s){super((...o)=>{const a=O(this.names,(c,l)=>{const u=this.arg$.parse(o[c]);return u.extends(this.constraints[c])||d(Ua(l,this.constraints[c].expression,u.expression)),[l,u]});if(this.defIsLazy()){const c=this.bodyDef(a);return this.$.parse(c)}return this.$.parse(n,{args:a})}),this.paramDefs=e,this.bodyDef=n,this.$=r,this.arg$=i,this.hkt=s,this.description=s?(new s).description??`a generic type for ${s.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof Oi}cacheGetter(e,n){return Object.defineProperty(this,e,{value:n}),n}get json(){return this.cacheGetter("json",{params:this.params.map(e=>e[1].isUnknown()?e[0]:[e[0],e[1].json]),body:ma(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map(e=>typeof e=="string"?[e,p.intrinsic.unknown]:[e[0],this.$.parse(e[1])]))}get names(){return this.cacheGetter("names",this.params.map(e=>e[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map(e=>e[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}const Ua=(t,e,n)=>`${t} must be assignable to ${e} (was ${n})`,Ta=q({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 _a extends Ke{serializedPredicate=U(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=Rt(this.errorContext);traverseApply=(e,n)=>{const r=n.currentErrorCount;!this.predicate(e,n.external)&&n.currentErrorCount===r&&n.errorFromNodeContext(this.errorContext)};compile(e){if(e.traversalKind==="Allows"){e.return(this.compiledCondition);return}e.initializeErrorCount(),e.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(e,n){return n.fallback.predicate({code:"predicate",base:e,predicate:this.predicate})}}const Ri={implementation:Ta,Node:_a},Ja=q({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:t=>Number.isInteger(t)?t:d(Ga(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,e,n)=>n.$.node("divisor",{rule:Math.abs(t.rule*e.rule/Wa(t.rule,e.rule))})},obviatesBasisDescription:!0});class Va extends Ct{traverseAllows=e=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=p.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){return e.type="integer",this.rule===1||(e.multipleOf=this.rule),e}}const Ci={implementation:Ja,Node:Va},Ga=t=>`divisor must be an integer (was ${t})`,Wa=(t,e)=>{let n,r=t,i=e;for(;i!==0;)n=i,i=r%i,r=n;return r};class Le extends Ct{boundOperandKind=Qa[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=Xa(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${Ha[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?ec(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator[0]==="<"?"upper":"lower";isStricterThan(e){return(this.limitKind==="upper"?this.numericLimit<e.numericLimit:this.numericLimit>e.numericLimit)||this.numericLimit===e.numericLimit&&this.exclusive===!0&&!e.exclusive}overlapsRange(e){return!(this.isStricterThan(e)||this.numericLimit===e.numericLimit&&(this.exclusive||e.exclusive))}overlapIsUnit(e){return this.numericLimit===e.numericLimit&&!this.exclusive&&!e.exclusive}}const Ha={"<":">=","<=":">",">":"<=",">=":"<"},Za={min:"max",minLength:"maxLength",after:"before"},Mi={parse:t=>t||void 0},Pi=t=>e=>{if(typeof e=="number")return{rule:e};const{exclusive:n,...r}=e;return n?{...r,rule:t==="minLength"?r.rule+1:r.rule-1}:r},qi=t=>e=>{if(typeof e=="number"||typeof e=="string"||e instanceof Date)return{rule:e};const{exclusive:n,...r}=e;if(!n)return r;const i=typeof r.rule=="number"?r.rule:typeof r.rule=="string"?new Date(r.rule).valueOf():r.rule.valueOf();return n?{...r,rule:t==="after"?i+1:i-1}:r},Ei=t=>typeof t=="string"||typeof t=="number"?new Date(t):t,Ya=(t,e)=>`${t} bound must be a positive integer (was ${e})`,An=t=>e=>((!Number.isInteger(e)||e<0)&&d(Ya(t,e)),e),Qa={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},Xa=(t,e)=>`${te(t,Za)?">":"<"}${e?"":"="}`,ec=t=>typeof t=="string"?t:new Date(t).toLocaleString(),tc=t=>`Bounded expression ${t} must be exactly one of number, string, Array, or Date`,nc=q({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Ei,serialize:t=>t.toISOString()}},normalize:qi("after"),defaults:{description:t=>`${t.collapsibleLimitString} or later`,actual:Xe},intersections:{after:(t,e)=>t.isStricterThan(e)?t:e}});class rc extends Le{impliedBasis=p.intrinsic.Date.internal;collapsibleLimitString=Xe(this.rule);traverseAllows=e=>e>=this.rule;reduceJsonSchema(e,n){return n.fallback.date({code:"date",base:e,after:this.rule})}}const Di={implementation:nc,Node:rc},ic=q({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Ei,serialize:t=>t.toISOString()}},normalize:qi("before"),defaults:{description:t=>`${t.collapsibleLimitString} or earlier`,actual:Xe},intersections:{before:(t,e)=>t.isStricterThan(e)?t:e,after:(t,e,n)=>t.overlapsRange(e)?t.overlapIsUnit(e)?n.$.node("unit",{unit:t.rule}):null:g.init("range",t,e)}});class sc extends Le{collapsibleLimitString=Xe(this.rule);traverseAllows=e=>e<=this.rule;impliedBasis=p.intrinsic.Date.internal;reduceJsonSchema(e,n){return n.fallback.date({code:"date",base:e,before:this.rule})}}const Ki={implementation:ic,Node:sc},oc=q({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:An("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,e,n)=>g.init("unit",n.$.node("unit",{unit:t.rule}),n.$.node("unit",{unit:e.rule}),{path:["length"]}),minLength:(t,e)=>t.rule>=e.rule?t:g.init("range",t,e),maxLength:(t,e)=>t.rule<=e.rule?t:g.init("range",t,e)}});class ac extends Ct{traverseAllows=e=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=p.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(e){switch(e.type){case"string":return e.minLength=this.rule,e.maxLength=this.rule,e;case"array":return e.minItems=this.rule,e.maxItems=this.rule,e;default:return L.throwInternalOperandError("exactLength",e)}}}const Li={implementation:oc,Node:ac},cc=q({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Mi},normalize:t=>typeof t=="number"?{rule:t}:t,defaults:{description:t=>t.rule===0?t.exclusive?"negative":"non-positive":`${t.exclusive?"less than":"at most"} ${t.rule}`},intersections:{max:(t,e)=>t.isStricterThan(e)?t:e,min:(t,e,n)=>t.overlapsRange(e)?t.overlapIsUnit(e)?n.$.node("unit",{unit:t.rule}):null:g.init("range",t,e)},obviatesBasisDescription:!0});class lc extends Le{impliedBasis=p.intrinsic.number.internal;traverseAllows=this.exclusive?e=>e<this.rule:e=>e<=this.rule;reduceJsonSchema(e){return this.exclusive?e.exclusiveMaximum=this.rule:e.maximum=this.rule,e}}const Bi={implementation:cc,Node:lc},uc=q({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:An("maxLength")}},reduce:(t,e)=>t.rule===0?e.node("exactLength",t):void 0,normalize:Pi("maxLength"),defaults:{description:t=>`at most length ${t.rule}`,actual:t=>`${t.length}`},intersections:{maxLength:(t,e)=>t.isStricterThan(e)?t:e,minLength:(t,e,n)=>t.overlapsRange(e)?t.overlapIsUnit(e)?n.$.node("exactLength",{rule:t.rule}):null:g.init("range",t,e)}});class dc extends Le{impliedBasis=p.intrinsic.lengthBoundable.internal;traverseAllows=e=>e.length<=this.rule;reduceJsonSchema(e){switch(e.type){case"string":return e.maxLength=this.rule,e;case"array":return e.maxItems=this.rule,e;default:return L.throwInternalOperandError("maxLength",e)}}}const ji={implementation:uc,Node:dc},hc=q({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Mi},normalize:t=>typeof t=="number"?{rule:t}:t,defaults:{description:t=>t.rule===0?t.exclusive?"positive":"non-negative":`${t.exclusive?"more than":"at least"} ${t.rule}`},intersections:{min:(t,e)=>t.isStricterThan(e)?t:e},obviatesBasisDescription:!0});class pc extends Le{impliedBasis=p.intrinsic.number.internal;traverseAllows=this.exclusive?e=>e>this.rule:e=>e>=this.rule;reduceJsonSchema(e){return this.exclusive?e.exclusiveMinimum=this.rule:e.minimum=this.rule,e}}const Fi={implementation:hc,Node:pc},fc=q({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:An("minLength")}},reduce:t=>t.rule===0?p.intrinsic.unknown:void 0,normalize:Pi("minLength"),defaults:{description:t=>t.rule===1?"non-empty":`at least length ${t.rule}`,actual:t=>t.length===0?"":`${t.length}`},intersections:{minLength:(t,e)=>t.isStricterThan(e)?t:e}});class mc extends Le{impliedBasis=p.intrinsic.lengthBoundable.internal;traverseAllows=e=>e.length>=this.rule;reduceJsonSchema(e){switch(e.type){case"string":return e.minLength=this.rule,e;case"array":return e.minItems=this.rule,e;default:return L.throwInternalOperandError("minLength",e)}}}const zi={implementation:fc,Node:mc},gc={min:Fi.implementation,max:Bi.implementation,minLength:zi.implementation,maxLength:ji.implementation,exactLength:Li.implementation,after:Di.implementation,before:Ki.implementation},yc={min:Fi.Node,max:Bi.Node,minLength:zi.Node,maxLength:ji.Node,exactLength:Li.Node,after:Di.Node,before:Ki.Node},bc=q({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 $c extends Ct{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=p.intrinsic.string.internal;reduceJsonSchema(e,n){return e.pattern?n.fallback.patternIntersection({code:"patternIntersection",base:e,pattern:this.rule}):(e.pattern=this.rule,e)}}const Ui={implementation:bc,Node:$c},ht=(t,e)=>{const n=wc(t);return e&&!e.includes(n)?d(`Root of kind ${n} should be one of ${e}`):n},wc=t=>{if(b(t,"root"))return t.kind;if(typeof t=="string")return t[0]==="$"?"alias":t in ie?"domain":"proto";if(typeof t=="function")return"proto";if(typeof t!="object"||t===null)return d(Zn(t));if("morphs"in t)return"morph";if("branches"in t||F(t))return"union";if("unit"in t)return"unit";if("reference"in t)return"alias";const e=Object.keys(t);return e.length===0||e.some(n=>n in xi)?"intersection":"proto"in t?"proto":"domain"in t?"domain":d(Zn(t))},Zn=t=>`${S(t)} is not a valid type schema`,Yn={},vc=t=>F(t)?t.map(e=>e.collapsibleJson):t.collapsibleJson,W={};p.nodesByRegisteredId=W;const Ti=t=>(Yn[t]??=0,`${t}${++Yn[t]}`),_i=t=>{const e=Mt[t.kind],n=e.applyConfig?.(t.def,t.$.resolvedConfig)??t.def,r={},{meta:i,...s}=n,o=i===void 0?{}:typeof i=="string"?{description:i}:i,a=Xr(s).sort(([l],[u])=>dt(l)?dt(u)?bt(l)-bt(u):1:dt(u)||l<u?-1:1).filter(([l,u])=>{if(l.startsWith("meta.")){const h=l.slice(5);return o[h]=u,!1}return!0});for(const l of a){const u=l[0],h=e.keys[u];if(!h)return d(`Key ${u} is not valid on ${t.kind} schema`);const m=h.parse?h.parse(l[1],t):l[1];m!==ee&&(m!==void 0||h.preserveUndefined)&&(r[u]=m)}if(e.reduce&&!t.prereduced){const l=e.reduce(r,t.$);if(l)return l instanceof g?l.throw():kc(l,o)}return In({id:t.id,kind:t.kind,inner:r,meta:o,$:t.$})},In=({id:t,kind:e,inner:n,meta:r,$:i,ignoreCache:s})=>{const o=Mt[e],a=Xr(n),c=[];let l={};for(const[x,A]of a){const P=o.keys[x],G=P.serialize??(P.child?vc:be);if(l[x]=G(A),P.child===!0){const H=A;F(H)?c.push(...H):c.push(H)}else typeof P.child=="function"&&c.push(...P.child(A))}o.finalizeInnerJson&&(l=o.finalizeInnerJson(l));let u={...l},h={};Ye(r)||(h=O(r,(x,A)=>[x,x==="examples"?A:be(A)]),u.meta=ct(h,"description",!0)),l=ct(l,o.collapsibleKey,!1);const m=JSON.stringify({kind:e,...l});u=ct(u,o.collapsibleKey,!1);const y=ct(u,o.collapsibleKey,!0),v=JSON.stringify({kind:e,...u});if(i.nodesByHash[v]&&!s)return i.nodesByHash[v];const f={id:t,kind:e,impl:o,inner:n,innerEntries:a,innerJson:l,innerHash:m,meta:r,metaJson:h,json:u,hash:v,collapsibleJson:y,children:c};if(e!=="intersection")for(const x in n)x!=="in"&&x!=="out"&&(f[x]=n[x]);const w=new Cl[e](f,i);return i.nodesByHash[v]=w},xc=(t,e)=>t.id===e?t:(z(W[e])&&K(`Unexpected attempt to overwrite node id ${e}`),In({id:e,kind:t.kind,inner:t.inner,meta:t.meta,$:t.$,ignoreCache:!0})),kc=(t,e,n)=>In({id:Ti(e.alias??t.kind),kind:t.kind,inner:t.inner,meta:e,$:t.$}),ct=(t,e,n)=>{const r=Object.keys(t);if(r.length===1&&r[0]===e){const i=t[e];if(n||$e(i,"object")&&(Object.keys(i).length===1||Array.isArray(i)))return i}return t},sn=(t,e,n)=>{if(t.key!==e.key)return null;const r=t.key;let i=j(t.value,e.value,n);const s=t.required||e.required?"required":"optional";if(i instanceof g)if(s==="optional")i=p.intrinsic.never.internal;else return i.withPrefixKey(t.key,t.required&&e.required?"required":"optional");if(s==="required")return n.$.node("required",{key:r,value:i});const o=t.hasDefault()?e.hasDefault()?t.default===e.default?t.default:d(Vi(t.default,e.default)):t.default:e.hasDefault()?e.default:ee;return n.$.node("optional",{key:r,value:i,default:o})};class Ji extends Ke{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=p.intrinsic.object.internal;serializedKey=De(this.key);compiledKey=typeof this.key=="string"?this.key:this.serializedKey;flatRefs=N(this.value.flatRefs.map(e=>de([this.key,...e.path],e.node)),de([this.key],this.value));_transform(e,n){n.path.push(this.key);const r=super._transform(e,n);return n.path.pop(),r}hasDefault(){return"default"in this.inner}traverseAllows=(e,n)=>this.key in e?oe(this.key,()=>this.value.traverseAllows(e[this.key],n),n):this.optional;traverseApply=(e,n)=>{this.key in e?oe(this.key,()=>this.value.traverseApply(e[this.key],n),n):this.hasKind("required")&&n.errorFromNodeContext(this.errorContext)};compile(e){e.if(`${this.serializedKey} in data`,()=>e.traverseKey(this.serializedKey,`data${e.prop(this.key)}`,this.value)),this.hasKind("required")&&e.else(()=>e.traversalKind==="Apply"?e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):e.return(!1)),e.traversalKind==="Allows"&&e.return(!0)}}const Vi=(t,e)=>`Invalid intersection of default values ${S(t)} & ${S(e)}`,Ac=q({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(t,e)=>e.$.parseSchema(t)},default:{preserveUndefined:!0}},normalize:t=>t,reduce:(t,e)=>{if(e.resolvedConfig.exactOptionalPropertyTypes===!1&&!t.value.allows(void 0))return e.node("optional",{...t,value:t.value.or($.undefined)},{prereduced:!0})},defaults:{description:t=>`${t.compiledKey}?: ${t.value.description}`},intersections:{optional:sn}});class Ic extends Ji{constructor(...e){super(...e),"default"in this.inner&&Nn(this.value,this.inner.default,this.key)}get rawIn(){const e=super.rawIn;return this.hasDefault()?this.$.node("optional",ti(e.inner,{default:!0}),{prereduced:!0}):e}get outProp(){if(!this.hasDefault())return this;const{default:e,...n}=this.inner;return this.cacheGetter("outProp",this.$.node("required",n,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${S(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=Nc(this);defaultValueMorphRef=this.defaultValueMorph&&U(this.defaultValueMorph)}const Sn={implementation:Ac,Node:Ic},Sc={},Nc=t=>{if(!t.hasDefault())return;const e=`{${t.compiledKey}: ${t.value.id} = ${be(t.default)}}`;return Sc[e]??=Gi(t.key,t.value,t.default)},Gi=(t,e,n)=>{if(typeof n=="function")return e.includesTransform?(i,s)=>(oe(t,()=>e(i[t]=n(),s),s),i):i=>(i[t]=n(),i);const r=e.includesTransform?e.assert(n):n;return $e(r,"object")?(i,s)=>(oe(t,()=>e(i[t]=n,s),s),i):i=>(i[t]=r,i)},Nn=(t,e,n)=>{const r=It(e);$e(e,"object")&&!r&&d(Oc(n));const i=t.in(r?e():e);if(i instanceof he){n===null&&d(`Default ${i.summary}`);const s=i.transform(o=>o.transform(a=>({...a,prefixPath:[n]})));d(`Default for ${s.summary}`)}return e},Oc=t=>`Non-primitive default ${t===null?"":typeof t=="number"?`for value at [${t}] `:`for ${De(t)} `}must be specified as a function like () => ({my: 'object'})`;class tt extends Ii{constructor(e,n){super(e,n),Object.defineProperty(this,se,{value:"root",enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get"~standard"(){return{vendor:"arktype",version:1,validate:e=>{const n=this(e);return n instanceof he?n:{value:n}},jsonSchema:{input:e=>this.rawIn.toJsonSchema({target:Qn(e.target),...e.libraryOptions}),output:e=>this.rawOut.toJsonSchema({target:Qn(e.target),...e.libraryOptions})}}}as(){return this}brand(e){return e===""?d(Rc):this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(e,n){const r=this.branches.map(e);return n?.(r)??r}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(e={}){const n=Ai(this.$.resolvedConfig.toJsonSchema,e);n.useRefs||=this.isCyclic;const r=typeof n.dialect=="string"?{$schema:n.dialect}:{};if(Object.assign(r,this.toJsonSchemaRecurse(n)),n.useRefs){const i=O(this.references,(s,o)=>o.isRoot()&&!o.alwaysExpandJsonSchema?[o.id,o.toResolvedJsonSchema(n)]:[]);n.target==="draft-07"?Object.assign(r,{definitions:i}):r.$defs=i}return r}toJsonSchemaRecurse(e){return e.useRefs&&!this.alwaysExpandJsonSchema?{$ref:`#/${e.target==="draft-07"?"definitions":"$defs"}/${this.id}`}:this.toResolvedJsonSchema(e)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(e){const n=this.innerToJsonSchema(e);return Object.assign(n,this.metaJson)}intersect(e){const n=this.$.parseDefinition(e),r=this.rawIntersect(n);return r instanceof g?r:this.$.finalize(r)}rawIntersect(e){return ae(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){const n=this.intersect(e);return n instanceof g?n.throw():n}rawAnd(e){const n=this.rawIntersect(e);return n instanceof g?n.throw():n}or(e){const n=this.$.parseDefinition(e);return this.$.finalize(this.rawOr(n))}rawOr(e){const n=[...this.branches,...e.branches];return this.$.node("union",n)}map(e){return this.$.schema(this.applyStructuralOperation("map",[e]))}pick(...e){return this.$.schema(this.applyStructuralOperation("pick",e))}omit(...e){return this.$.schema(this.applyStructuralOperation("omit",e))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;const e=this.applyStructuralOperation("keyof",[]).reduce((n,r)=>n.intersect(r).toNeverIfDisjoint(),p.intrinsic.unknown.internal);return e.branches.length===0&&d(Ni(`keyof ${this.expression}`)),this._keyof=this.$.finalize(e)}get props(){return this.branches.length!==1?d(Mc(this.expression)):[...this.applyStructuralOperation("props",[])[0]]}merge(e){const n=this.$.parseDefinition(e);return this.$.schema(n.distribute(r=>this.applyStructuralOperation("merge",[Xn(r)??d(er("merge",r.expression))])))}applyStructuralOperation(e,n){return this.distribute(r=>{if(r.equals(p.intrinsic.object)&&e!=="merge")return r;const i=Xn(r);if(i||d(er(e,r.expression)),e==="keyof")return i.keyof();if(e==="get")return i.get(...n);if(e==="props")return i.props;const s=e==="required"?"require":e==="partial"?"optionalize":e;return this.$.node("intersection",{domain:"object",structure:i[s](...n)})})}get(...e){return e[0]===void 0?this:this.$.schema(this.applyStructuralOperation("get",e))}extract(e){const n=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(r=>r.extends(n)))}exclude(e){const n=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(r=>!r.extends(n)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(e){return!(this.intersect(e)instanceof g)}extends(e){if(this.isNever())return!0;const n=this.intersect(e);return!(n instanceof g)&&this.equals(n)}ifExtends(e){return this.extends(e)?this:void 0}subsumes(e){return this.$.parseDefinition(e).extends(this)}configure(e,n="shallow"){return this.configureReferences(e,n)}describe(e,n="shallow"){return this.configure({description:e},n)}optional(){return[this,"?"]}default(e){return Nn(this,e,null),[this,"=",e]}from(e){return this.assert(e)}_pipe(...e){const n=e.reduce((r,i)=>r.rawPipeOnce(i),this);return this.$.finalize(n)}tryPipe(...e){const n=e.reduce((r,i)=>r.rawPipeOnce(b(i,"root")?i:(s,o)=>{try{return i(s,o)}catch(a){return o.error({code:"predicate",predicate:i,actual:`aborted due to error:\n ${a}\n`})}}),this);return this.$.finalize(n)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(e){return this.$.finalize(this.toNode(this.$.parseDefinition(e)))}toNode(e){const n=nn(this,e,this.$);return n instanceof g?n.throw():n}rawPipeOnce(e){return b(e,"root")?this.toNode(e):this.distribute(n=>n.hasKind("morph")?this.$.node("morph",{in:n.inner.in,morphs:[...n.morphs,e]}):this.$.node("morph",{in:n,morphs:[e]}),this.$.parseSchema)}narrow(e){return this.constrainOut("predicate",e)}constrain(e,n){return this._constrain("root",e,n)}constrainIn(e,n){return this._constrain("in",e,n)}constrainOut(e,n){return this._constrain("out",e,n)}_constrain(e,n,r){const i=this.$.node(n,r);if(i.isRoot())return i.isUnknown()?this:K(`Unexpected constraint node ${i}`);const s=e==="root"?this:e==="in"?this.rawIn:this.rawOut;if(s.hasKind("morph")||i.impliedBasis&&!s.extends(i.impliedBasis))return ja(n,i.impliedBasis,this);const o=this.$.node("intersection",{[i.kind]:i}),a=e==="out"?nn(this,o,this.$):ae(this,o,this.$);return a instanceof g&&a.throw(),this.$.finalize(a)}onUndeclaredKey(e){const n=typeof e=="string"?e:e.rule,r=typeof e=="string"?!1:e.deep;return this.$.finalize(this.transform((i,s)=>i==="structure"?n==="ignore"?ti(s,{undeclared:1}):{...s,undeclared:n}:s,r?void 0:{shouldTransform:i=>!re(Nt,i.kind)}))}hasEqualMorphs(e){return!this.includesTransform&&!e.includesTransform?!0:!(!Ce(this.shallowMorphs,e.shallowMorphs)||!Ce(this.flatMorphs,e.flatMorphs,{isEqual:(n,r)=>n.propString===r.propString&&(n.node.hasKind("morph")&&r.node.hasKind("morph")?n.node.hasEqualMorphs(r.node):n.node.hasKind("intersection")&&r.node.hasKind("intersection")?n.node.structure?.structuralMorphRef===r.node.structure?.structuralMorphRef:!1)}))}onDeepUndeclaredKey(e){return this.onUndeclaredKey({rule:e,deep:!0})}filter(e){return this.constrainIn("predicate",e)}divisibleBy(e){return this.constrain("divisor",e)}matching(e){return this.constrain("pattern",e)}atLeast(e){return this.constrain("min",e)}atMost(e){return this.constrain("max",e)}moreThan(e){return this.constrain("min",Ie(e))}lessThan(e){return this.constrain("max",Ie(e))}atLeastLength(e){return this.constrain("minLength",e)}atMostLength(e){return this.constrain("maxLength",e)}moreThanLength(e){return this.constrain("minLength",Ie(e))}lessThanLength(e){return this.constrain("maxLength",Ie(e))}exactlyLength(e){return this.constrain("exactLength",e)}atOrAfter(e){return this.constrain("after",e)}atOrBefore(e){return this.constrain("before",e)}laterThan(e){return this.constrain("after",Ie(e))}earlierThan(e){return this.constrain("before",Ie(e))}}const Rc="Expected a non-empty brand name after #",Wi=["draft-2020-12","draft-07"],Cc=t=>`JSONSchema target '${t}' is not supported (must be ${Wi.map(e=>`"${e}"`).join(" or ")})`,Qn=t=>(re(Wi,t)||d(Cc(t)),t),Ie=t=>typeof t=="object"&&!(t instanceof Date)?{...t,exclusive:!0}:{rule:t,exclusive:!0},lt=(t,e)=>b(e,"root")?b(t,"root")?t.extends(e):e.allows(t):b(t,"root")?t.hasUnit(e):e===t,Xn=t=>t.hasKind("morph")?null:t.hasKind("intersection")?t.inner.structure??(t.basis?.domain==="object"?t.$.bindReference(p.intrinsic.emptyStructure):null):t.isBasis()&&t.domain==="object"?t.$.bindReference(p.intrinsic.emptyStructure):null,Mc=t=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:\n${t}`,er=(t,e)=>`${t} operand must be an object (was ${e})`,nt=(t,e)=>O(kn(t),(n,r)=>[r,e]),Pc=t=>typeof t=="string"?{reference:t}:t,tr=t=>t instanceof g?p.intrinsic.never.internal:t,qc=q({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:t=>t.startsWith("$")?t:`$ark.${t}`},resolve:{}},normalize:Pc,defaults:{description:t=>t.reference},intersections:{alias:(t,e,n)=>n.$.lazilyResolve(()=>tr(j(t.resolution,e.resolution,n)),`${t.reference}${n.pipe?"=>":"&"}${e.reference}`),...nt("alias",(t,e,n)=>e.isUnknown()?t:e.isNever()?e:e.isBasis()&&!e.overlaps(p.intrinsic.object)?g.init("assignability",p.intrinsic.object,e):n.$.lazilyResolve(()=>tr(j(t.resolution,e,n)),`${t.reference}${n.pipe?"=>":"&"}${e.id}`))}});class Ec extends tt{expression=this.reference;structure=void 0;get resolution(){const e=this._resolve();return W[this.id]=e}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));const e=this.reference;let n=W[e];const r=[];for(;b(n,"context");){if(r.includes(n.id))return d(Dc(n.id,r));r.push(n.id),n=W[n.id]}return b(n,"root")?n:K(`Unexpected resolution for reference ${this.reference}\nSeen: [${r.join("->")}] \nResolution: ${S(n)}`)}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;const e=this.reference.slice(1),n=this.$.resolutions[e];return typeof n=="string"?n:b(n,"root")?n.id:K(`Unexpected resolution for reference ${this.reference}: ${S(n)}`)}get defaultShortDescription(){return ie.object}innerToJsonSchema(e){return this.resolution.toJsonSchemaRecurse(e)}traverseAllows=(e,n)=>{const r=n.seen[this.reference];return r?.includes(e)?!0:(n.seen[this.reference]=N(r,e),this.resolution.traverseAllows(e,n))};traverseApply=(e,n)=>{const r=n.seen[this.reference];r?.includes(e)||(n.seen[this.reference]=N(r,e),this.resolution.traverseApply(e,n))};compile(e){const n=this.resolutionId;e.if(`ctx.seen.${n} && ctx.seen.${n}.includes(data)`,()=>e.return(!0)),e.if(`!ctx.seen.${n}`,()=>e.line(`ctx.seen.${n} = []`)),e.line(`ctx.seen.${n}.push(data)`),e.return(e.invoke(n))}}const Dc=(t,e)=>`Alias '${t}' has a shallow resolution cycle: ${[...e,t].join("->")}`,On={implementation:qc,Node:Ec};class Rn extends tt{traverseApply=(e,n)=>{this.traverseAllows(e,n)||n.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Rt(this.errorContext)}compile(e){e.traversalKind==="Allows"?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}const Kc=q({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:t=>typeof t=="string"?{domain:t}:yn(t,"numberAllowsNaN")&&t.domain!=="number"?d(Cn.writeBadAllowNanMessage(t.domain)):t,applyConfig:(t,e)=>t.numberAllowsNaN===void 0&&t.domain==="number"&&e.numberAllowsNaN?{...t,numberAllowsNaN:!0}:t,defaults:{description:t=>ie[t.domain],actual:t=>Number.isNaN(t)?"NaN":ie[Q(t)]},intersections:{domain:(t,e)=>t.domain==="number"&&e.domain==="number"?t.numberAllowsNaN?e:t:g.init("domain",t,e)}});class Lc extends Rn{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?e=>typeof e=="number"&&!Number.isNaN(e):e=>Q(e)===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 ie[this.domain]}innerToJsonSchema(e){return this.domain==="bigint"||this.domain==="symbol"?e.fallback.domain({code:"domain",base:{},domain:this.domain}):{type:this.domain}}}const Cn={implementation:Kc,Node:Lc,writeBadAllowNanMessage:t=>`numberAllowsNaN may only be specified with domain "number" (was ${t})`},Bc=q({kind:"intersection",hasAssociatedError:!0,normalize:t=>{if(z(t))return t;const{structure:e,...n}=t,r=!!e,i=e??{},s=O(n,(o,a)=>te(o,Ia)?(r&&d(`Flattened structure key ${o} cannot be specified alongside a root 'structure' key.`),i[o]=a,[]):[o,a]);return(b(i,"constraint")||!Ye(i))&&(s.structure=i),s},finalizeInnerJson:({structure:t,...e})=>$e(t,"object")?{...t,...e}:e,keys:{domain:{child:!0,parse:(t,e)=>e.$.node("domain",t)},proto:{child:!0,parse:(t,e)=>e.$.node("proto",t)},structure:{child:!0,parse:(t,e)=>e.$.node("structure",t),serialize:t=>{if(!t.sequence?.minLength)return t.collapsibleJson;const{sequence:e,...n}=t.collapsibleJson,{minVariadicLength:r,...i}=e,s=i.variadic&&Object.keys(i).length===1?i.variadic:i;return{...n,sequence:s}}},divisor:{child:!0,parse:T("divisor")},max:{child:!0,parse:T("max")},min:{child:!0,parse:T("min")},maxLength:{child:!0,parse:T("maxLength")},minLength:{child:!0,parse:T("minLength")},exactLength:{child:!0,parse:T("exactLength")},before:{child:!0,parse:T("before")},after:{child:!0,parse:T("after")},pattern:{child:!0,parse:T("pattern")},predicate:{child:!0,parse:T("predicate")}},reduce:(t,e)=>nr({},t,{$:e,invert:!1,pipe:!1}),defaults:{description:t=>{if(t.children.length===0)return"unknown";if(t.structure)return t.structure.description;const e=[];if(t.basis&&!t.prestructurals.some(n=>n.impl.obviatesBasisDescription)&&e.push(t.basis.description),t.prestructurals.length){const n=t.prestructurals.slice().sort((r,i)=>r.kind==="min"&&i.kind==="max"?-1:0).map(r=>r.description);e.push(...n)}return t.inner.predicate&&e.push(...t.inner.predicate.map(n=>n.description)),e.join(" and ")},expected:t=>` ◦ ${t.errors.map(e=>e.expected).join(`\n ◦ `)}`,problem:t=>`(${t.actual}) must be...\n${t.expected}`},intersections:{intersection:(t,e,n)=>nr(t.inner,e.inner,n),...nt("intersection",(t,e,n)=>{if(t.children.length===0)return e;const{domain:r,proto:i,...s}=t.inner,o=i??r,a=o?j(o,e,n):e;return a instanceof g?a:t?.basis?.equals(a)?t:t.$.node("intersection",{...s,[a.kind]:a},{prereduced:!0})})}});class jc extends tt{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter(e=>e.isRefinement()?(re(wi,e.kind)&&this.prestructurals.push(e),!0):!1);structure=this.inner.structure;expression=Fc(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(e){return this.children.reduce((n,r)=>r.isBasis()?r.toJsonSchemaRecurse(e):r.reduceJsonSchema(n,e),{})}traverseAllows=(e,n)=>this.children.every(r=>r.traverseAllows(e,n));traverseApply=(e,n)=>{const r=n.currentErrorCount;if(!(this.basis&&(this.basis.traverseApply(e,n),n.currentErrorCount>r))){if(this.prestructurals.length){for(let i=0;i<this.prestructurals.length-1;i++)if(this.prestructurals[i].traverseApply(e,n),n.failFast&&n.currentErrorCount>r)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(e,n),n.currentErrorCount>r)return}if(!(this.structure&&(this.structure.traverseApply(e,n),n.currentErrorCount>r))&&this.inner.predicate){for(let i=0;i<this.inner.predicate.length-1;i++)if(this.inner.predicate[i].traverseApply(e,n),n.failFast&&n.currentErrorCount>r)return;this.inner.predicate[this.inner.predicate.length-1].traverseApply(e,n)}}};compile(e){if(e.traversalKind==="Allows"){for(const n of this.children)e.check(n);e.return(!0);return}if(e.initializeErrorCount(),this.basis&&(e.check(this.basis),this.children.length>1&&e.returnIfFail()),this.prestructurals.length){for(let n=0;n<this.prestructurals.length-1;n++)e.check(this.prestructurals[n]),e.returnIfFailFast();e.check(this.prestructurals[this.prestructurals.length-1]),(this.structure||this.inner.predicate)&&e.returnIfFail()}if(this.structure&&(e.check(this.structure),this.inner.predicate&&e.returnIfFail()),this.inner.predicate){for(let n=0;n<this.inner.predicate.length-1;n++)e.check(this.inner.predicate[n]),e.returnIfFail();e.check(this.inner.predicate[this.inner.predicate.length-1])}}}const Hi={implementation:Bc,Node:jc},Fc=t=>{if(t.structure?.expression)return t.structure.expression;const e=t.basis&&!t.prestructurals.some(i=>i.impl.obviatesBasisExpression)?t.basis.nestableExpression:"",n=t.prestructurals.map(i=>i.expression).join(" & "),r=`${e}${e?" ":""}${n}`;return r==="Array == 0"?"[]":r||"unknown"},nr=(t,e,n)=>{const r={},i=t.proto??t.domain,s=e.proto??e.domain,o=i?s?j(i,s,n):i:s;return o instanceof g?o:(o&&(r[o.kind]=o),$t({kind:"intersection",baseInner:r,l:wt(t),r:wt(e),roots:[],ctx:n}))},zc=q({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(t,e)=>e.$.parseSchema(t)},morphs:{parse:Ze,serialize:t=>t.map(e=>b(e,"root")?e.json:U(e))},declaredIn:{child:!1,serialize:t=>t.json},declaredOut:{child:!1,serialize:t=>t.json}},normalize:t=>t,defaults:{description:t=>`a morph from ${t.rawIn.description} to ${t.rawOut?.description??"unknown"}`},intersections:{morph:(t,e,n)=>{if(!t.hasEqualMorphs(e))return d(Tc(t.expression,e.expression));const r=j(t.rawIn,e.rawIn,n);if(r instanceof g)return r;const i={morphs:t.morphs};if(t.declaredIn||e.declaredIn){const s=j(t.rawIn,e.rawIn,n);if(s instanceof g)return s.throw();i.declaredIn=s}if(t.declaredOut||e.declaredOut){const s=j(t.rawOut,e.rawOut,n);if(s instanceof g)return s.throw();i.declaredOut=s}return r.distribute(s=>n.$.node("morph",{...i,in:s}),n.$.parseSchema)},...nt("morph",(t,e,n)=>{const r=t.inner.in?j(t.inner.in,e,n):e;return r instanceof g?r:r.equals(t.inner.in)?t:n.$.node("morph",{...t.inner,in:r})})}});class Uc extends tt{serializedMorphs=this.morphs.map(U);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=b(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.rawOut:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get rawIn(){return this.declaredIn??this.inner.in?.rawIn??p.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??p.intrinsic.unknown.internal}declareIn(e){return this.$.node("morph",{...this.inner,declaredIn:e})}declareOut(e){return this.$.node("morph",{...this.inner,declaredOut:e})}expression=`(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.rawOut.expression}>`;get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(e){return e.fallback.morph({code:"morph",base:this.rawIn.toJsonSchemaRecurse(e),out:this.introspectableOut?.toJsonSchemaRecurse(e)??null})}compile(e){if(e.traversalKind==="Allows"){if(!this.introspectableIn)return;e.return(e.invoke(this.introspectableIn));return}this.introspectableIn&&e.line(e.invoke(this.introspectableIn)),e.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(e,n)=>!this.introspectableIn||this.introspectableIn.traverseAllows(e,n);traverseApply=(e,n)=>{this.introspectableIn&&this.introspectableIn.traverseApply(e,n),n.queueMorphs(this.morphs)};hasEqualMorphs(e){return Ce(this.morphs,e.morphs,{isEqual:(n,r)=>n===r||b(n,"root")&&b(r,"root")&&n.equals(r)})}}const Zi={implementation:zc,Node:Uc},Tc=(t,e)=>`The intersection of distinct morphs at a single path is indeterminate:\nLeft: ${t}\nRight: ${e}`,_c=q({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:t=>$n(t)??be(t)},dateAllowsInvalid:{}},normalize:t=>{const e=typeof t=="string"?{proto:Pe[t]}:typeof t=="function"?z(t)?t:{proto:t}:typeof t.proto=="string"?{...t,proto:Pe[t.proto]}:t;return typeof e.proto!="function"&&d(xt.writeInvalidSchemaMessage(e.proto)),yn(e,"dateAllowsInvalid")&&e.proto!==Date&&d(xt.writeBadInvalidDateMessage(e.proto)),e},applyConfig:(t,e)=>t.dateAllowsInvalid===void 0&&t.proto===Date&&e.dateAllowsInvalid?{...t,dateAllowsInvalid:!0}:t,defaults:{description:t=>t.builtinName?Fo[t.builtinName]:`an instance of ${t.proto.name}`,actual:t=>t instanceof Date&&t.toString()==="Invalid Date"?"an invalid Date":Ht(t)},intersections:{proto:(t,e)=>t.proto===Date&&e.proto===Date?t.dateAllowsInvalid?e:t:zn(t.proto,e.proto)?t:zn(e.proto,t.proto)?e:g.init("proto",t,e),domain:(t,e)=>e.domain==="object"?t:g.init("domain",p.intrinsic.object.internal,e)}});class Jc extends Rn{builtinName=$n(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?e=>e instanceof Date&&e.toString()!=="Invalid Date":e=>e instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(e){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return e.fallback.date?.({code:"date",base:{}})??e.fallback.proto({code:"proto",base:{},proto:this.proto});default:return e.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}}const xt={implementation:_c,Node:Jc,writeBadInvalidDateMessage:t=>`dateAllowsInvalid may only be specified with constructor Date (was ${t.name})`,writeInvalidSchemaMessage:t=>`instanceOf operand must be a function (was ${Q(t)})`},Vc=q({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(t,e)=>{const n=[];for(const r of t){const i=b(r,"root")?r.branches:e.$.parseSchema(r).branches;for(const s of i)if(s.hasKind("morph")){const o=n.findIndex(a=>a.hasKind("morph")&&a.hasEqualMorphs(s));if(o===-1)n.push(s);else{const a=n[o];n[o]=e.$.node("morph",{...a.inner,in:a.rawIn.rawOr(s.rawIn)})}}else n.push(s)}return e.def.ordered||n.sort((r,i)=>r.hash<i.hash?-1:1),n}}},normalize:t=>F(t)?{branches:t}:t,reduce:(t,e)=>{const n=rl(t);if(n.length===1)return n[0];if(n.length!==t.branches.length)return e.node("union",{...t,branches:n},{prereduced:!0})},defaults:{description:t=>t.distribute(e=>e.description,Oe),expected:t=>{const e=Io(t.errors,"propString"),n=Object.entries(e).map(([r,i])=>{const s=[];for(const c of i)ye(s,c.expected);const o=Oe(s),a=i.every(c=>c.actual===i[0].actual)?i[0].actual:S(i[0].data);return`${r&&`${r} `}must be ${o}${a&&` (was ${a})`}`});return Oe(n)},problem:t=>t.expected,message:t=>t.problem[0]==="["?`value at ${t.problem}`:t.problem},intersections:{union:(t,e,n)=>{if(t.isNever!==e.isNever)return g.init("presence",t,e);let r;return t.ordered?(e.ordered&&d(sl(t.expression,e.expression)),r=Bt(e.branches,t.branches,n),r instanceof g&&r.invert()):r=Bt(t.branches,e.branches,n),r instanceof g?r:n.$.parseSchema(t.ordered||e.ordered?{branches:r,ordered:!0}:{branches:r})},...nt("union",(t,e,n)=>{const r=Bt(t.branches,[e],n);return r instanceof g?r:r.length===1?r[0]:n.$.parseSchema(t.ordered?{branches:r,ordered:!0}:{branches:r})})}});class Gc extends tt{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){const e=[];let n=-1;for(const r of this.branches){if(r.hasKind("unit")&&r.domain==="boolean"){n===-1?(n=e.length,e.push(r)):e[n]=p.intrinsic.boolean;continue}e.push(r)}return e}unitBranches=this.branches.filter(e=>e.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?el(this.discriminant):null;expression=this.distribute(e=>e.nestableExpression,nl);createBranchedOptimisticRootApply(){return(e,n)=>{const r=this.traverseOptimistic(e);if(r!==ee)return r;const i=new Ne(e,this.$.resolvedConfig);return this.traverseApply(e,i),i.finalize(n)}}get shallowMorphs(){return this.branches.reduce((e,n)=>ye(e,n.shallowMorphs),[])}get defaultShortDescription(){return this.distribute(e=>e.defaultShortDescription,Oe)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(p.intrinsic.boolean))return{type:"boolean"};const n=this.branchGroups.map(r=>r.toJsonSchemaRecurse(e));return n.every(r=>Object.keys(r).length===1&&yn(r,"const"))?{enum:n.map(r=>r.const)}:{anyOf:n}}traverseAllows=(e,n)=>this.branches.some(r=>r.traverseAllows(e,n));traverseApply=(e,n)=>{const r=[];for(let i=0;i<this.branches.length;i++){if(n.pushBranch(),this.branches[i].traverseApply(e,n),!n.hasError())return this.branches[i].includesTransform?n.queuedMorphs.push(...n.popBranch().queuedMorphs):n.popBranch();r.push(n.popBranch().error)}n.errorFromNodeContext({code:"union",errors:r,meta:this.meta})};traverseOptimistic=e=>{for(let n=0;n<this.branches.length;n++){const r=this.branches[n];if(r.traverseAllows(e))return r.contextFreeMorph?r.contextFreeMorph(e):e}return ee};compile(e){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(e);let n=this.discriminant.optionallyChainedPropString;this.discriminant.kind==="domain"&&(n=`typeof ${n} === "object" ? ${n} === null ? "null" : "object" : typeof ${n} === "function" ? "object" : typeof ${n}`);const r=this.discriminant.cases,i=Object.keys(r),{optimistic:s}=e;if(e.optimistic=!1,e.block(`switch(${n})`,()=>{for(const u in r){const h=r[u],m=u==="default"?u:`case ${u}`;let y;h===!0?y=s?"data":"true":s?h.rootApplyStrategy==="branchedOptimistic"?y=e.invoke(h,{kind:"Optimistic"}):h.contextFreeMorph?y=`${e.invoke(h)} ? ${U(h.contextFreeMorph)}(data) : "${ee}"`:y=`${e.invoke(h)} ? data : "${ee}"`:y=e.invoke(h),e.line(`${m}: return ${y}`)}return e}),e.traversalKind==="Allows"){e.return(s?`"${ee}"`:!1);return}const o=Oe(this.discriminant.kind==="domain"?i.map(u=>{const h=u.slice(1,-1);return h==="function"?ie.object:ie[h]}):i),a=this.discriminant.path.map(u=>typeof u=="symbol"?U(u):JSON.stringify(u)),c=JSON.stringify(o),l=this.discriminant.kind==="domain"?`${Qc}[${n}]`:`${Xc}(${n})`;e.line(`ctx.errorFromNodeContext({\n\tcode: "predicate",\n\texpected: ${c},\n\tactual: ${l},\n\trelativePath: [${a}],\n\tmeta: ${this.compiledMeta}\n})`)}compileIndiscriminable(e){if(e.traversalKind==="Apply"){e.const("errors","[]");for(const n of this.branches)e.line("ctx.pushBranch()").line(e.invoke(n)).if("!ctx.hasError()",()=>e.return(n.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");e.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{const{optimistic:n}=e;e.optimistic=!1;for(const r of this.branches)e.if(`${e.invoke(r)}`,()=>e.return(n?r.contextFreeMorph?`${U(r.contextFreeMorph)}(data)`:"data":!0));e.return(n?`"${ee}"`:!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){const s=O(this.unitBranches,(o,a)=>[`${a.rawIn.serializedValue}`,a.hasKind("morph")?a:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:s}}const e=[];for(let s=0;s<this.branches.length-1;s++){const o=this.branches[s];for(let a=s+1;a<this.branches.length;a++){const c=this.branches[a],l=ae(o.rawIn,c.rawIn,o.$);if(l instanceof g)for(const u of l){if(!u.kind||u.optional)continue;let h,m;if(u.kind==="domain"){const v=u.l,f=u.r;h=`"${typeof v=="string"?v:v.domain}"`,m=`"${typeof f=="string"?f:f.domain}"`}else if(u.kind==="unit")h=u.l.serializedValue,m=u.r.serializedValue;else continue;const y=e.find(v=>Ce(v.path,u.path)&&v.kind===u.kind);y?(y.cases[h]?y.cases[h].branchIndices=ye(y.cases[h].branchIndices,s):y.cases[h]??={branchIndices:[s],condition:u.l},y.cases[m]?y.cases[m].branchIndices=ye(y.cases[m].branchIndices,a):y.cases[m]??={branchIndices:[a],condition:u.r}):e.push({kind:u.kind,cases:{[h]:{branchIndices:[s],condition:u.l},[m]:{branchIndices:[a],condition:u.r}},path:u.path})}}}const n=this.ordered?Zc(e,this.branches):e;if(!n.length)return null;const r=Wc(n,this),i={};for(const s in r.best.cases){const o=Hc(r,s);if(o===null){i[s]=!0;continue}if(o.length===this.branches.length)return null;this.ordered&&o.sort((l,u)=>l.originalIndex-u.originalIndex);const a=o.map(l=>l.branch),c=a.length===1?a[0]:this.$.node("union",this.ordered?{branches:a,ordered:!0}:a);Object.assign(this.referencesById,c.referencesById),i[s]=c}if(r.defaultEntries.length){const s=r.defaultEntries.map(o=>o.branch);i.default=this.$.node("union",this.ordered?{branches:s,ordered:!0}:s,{prereduced:!0}),Object.assign(this.referencesById,i.default.referencesById)}return Object.assign(r.location,{cases:i})}}const Wc=(t,e)=>{const r=t.sort((o,a)=>o.path.length===a.path.length?Object.keys(a.cases).length-Object.keys(o.cases).length:o.path.length-a.path.length)[0],i={kind:r.kind,path:r.path,optionallyChainedPropString:Yi(r.path)},s=e.branches.map((o,a)=>({originalIndex:a,branch:o}));return{best:r,location:i,defaultEntries:s,node:e}},Hc=(t,e)=>{const n=t.best.cases[e],r=Yc(n.condition,t.location.path,t.node.$);let i=[];const s=[];for(let o=0;o<t.defaultEntries.length;o++){const a=t.defaultEntries[o];if(n.branchIndices.includes(a.originalIndex)){const c=rr(t.node.branches[a.originalIndex],t.location);c===null?i=null:i?.push({originalIndex:a.originalIndex,branch:c})}else if(a.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")i?.push(a);else{if(a.branch.rawIn.overlaps(r)){const c=rr(a.branch,t.location);i?.push({originalIndex:a.originalIndex,branch:c})}s.push(a)}}return t.defaultEntries=s,i},Zc=(t,e)=>t.filter(r=>{const i=Object.values(r.cases).map(s=>s.branchIndices);for(let s=0;s<i.length-1;s++){const o=i[s];for(let a=s+1;a<i.length;a++){const c=i[a];for(const l of o)for(const u of c)if(l>u&&e[l].overlaps(e[u]))return!1}}return!0}),Yc=(t,e,n)=>{let r=t==="undefined"?n.node("unit",{unit:void 0}):t==="null"?n.node("unit",{unit:null}):t==="boolean"?n.units([!0,!1]):t;for(let i=e.length-1;i>=0;i--){const s=e[i];r=n.node("intersection",typeof s=="number"?{proto:"Array",sequence:[...ko(s).map(o=>({})),r]}:{domain:"object",required:[{key:s,value:r}]})}return r},Yi=t=>t.reduce((e,n)=>e+yi(n,!0),"data"),Qc=U(So),Xc=U(S),Qi={implementation:Vc,Node:Gc},el=t=>({kind:t.kind,path:t.path.map(e=>typeof e=="string"?e:De(e)),cases:O(t.cases,(e,n)=>[e,n===!0?n:n.hasKind("union")&&n.discriminantJson?n.discriminantJson:n.json])}),tl={delimiter:" | ",finalDelimiter:" | "},nl=t=>Oe(t,tl),Oe=(t,e)=>{const n=e?.delimiter??", ",r=e?.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";const i={},s=t.filter(a=>i[a]?!1:i[a]=!0),o=s.pop();return`${s.join(n)}${s.length?r:""}${o}`},Bt=(t,e,n)=>{const r=e.map(()=>[]);for(let s=0;s<t.length;s++){let o={};for(let a=0;a<e.length;a++){if(r[a]===null)continue;if(t[s].equals(e[a])){r[a]=null,o={};break}const c=j(t[s],e[a],n);if(!(c instanceof g)){if(c.equals(t[s])){r[a].push(t[s]),o={};break}c.equals(e[a])?r[a]=null:o[a]=c}}for(const a in o)r[a][s]=o[a]}const i=r.flatMap((s,o)=>s?.flatMap(a=>a.branches)??e[o]);return i.length===0?g.init("union",t,e):i},rl=({branches:t,ordered:e})=>{if(t.length<2)return t;const n=t.map(()=>!0);for(let r=0;r<t.length;r++)for(let i=r+1;i<t.length&&n[r]&&n[i];i++){if(t[r].equals(t[i])){n[i]=!1;continue}const s=ae(t[r].rawIn,t[i].rawIn,t[0].$);s instanceof g||(e||il(t[r],t[i]),s.equals(t[r].rawIn)?n[r]=!!e:s.equals(t[i].rawIn)&&(n[i]=!1))}return t.filter((r,i)=>n[i])},il=(t,e)=>{!t.includesTransform&&!e.includesTransform||(Ce(t.shallowMorphs,e.shallowMorphs)||d(ir(t.expression,e.expression)),Ce(t.flatMorphs,e.flatMorphs,{isEqual:(n,r)=>n.propString===r.propString&&(n.node.hasKind("morph")&&r.node.hasKind("morph")?n.node.hasEqualMorphs(r.node):n.node.hasKind("intersection")&&r.node.hasKind("intersection")?n.node.structure?.structuralMorphRef===r.node.structure?.structuralMorphRef:!1)})||d(ir(t.expression,e.expression)))},rr=(t,e)=>t.transform((n,r)=>n==="domain"||n==="unit"?null:r,{shouldTransform:(n,r)=>{const i=Yi(r.path);return e.optionallyChainedPropString.startsWith(i)?n.hasKind("domain")&&n.domain==="object"||(n.hasKind("domain")||e.kind==="unit")&&i===e.optionallyChainedPropString?!0:n.children.length!==0&&n.kind!=="index":!1}}),ir=(t,e)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:\nLeft: ${t}\nRight: ${e}`,sl=(t,e)=>`The intersection of two ordered unions is indeterminate:\nLeft: ${t}\nRight: ${e}`,ol=q({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:t=>t instanceof Date?t.toISOString():be(t)}},normalize:t=>t,defaults:{description:t=>S(t.unit),problem:({expected:t,actual:e})=>`${t===e?`must be reference equal to ${t} (serialized to the same value)`:`must be ${t} (was ${e})`}`},intersections:{unit:(t,e)=>g.init("unit",t,e),...nt("unit",(t,e)=>{if(e.allows(t.unit))return t;const n=e.hasKind("intersection")?e.basis:e;if(n){const r=n.hasKind("domain")?n:p.intrinsic.object;if(t.domain!==r.domain){const i=t.domain==="undefined"||t.domain==="null"||t.domain==="boolean"?t.domain:p.intrinsic[t.domain];return g.init("domain",i,r)}}return g.init("assignability",t,e.hasKind("intersection")?e.children.find(r=>!r.allows(t.unit)):e)})}});class al extends Rn{compiledValue=this.json.unit;serializedValue=typeof this.unit=="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=sr(this.unit,this.serializedValue);compiledNegation=sr(this.unit,this.serializedValue,"negated");expression=S(this.unit);domain=Q(this.unit);get defaultShortDescription(){return this.domain==="object"?ie.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:"null"}:p.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:e.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?e=>e instanceof Date&&e.toISOString()===this.compiledValue:Number.isNaN(this.unit)?e=>Number.isNaN(e):e=>e===this.unit}const Xi={implementation:ol,Node:al},sr=(t,e,n)=>{if(t instanceof Date){const r=`data instanceof Date && data.toISOString() === ${e}`;return n?`!(${r})`:r}return Number.isNaN(t)?`${n?"!":""}Number.isNaN(data)`:`data ${n?"!":"="}== ${e}`},cl=q({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(t,e)=>{const n=e.$.parseSchema(t);if(!n.extends(p.intrinsic.key))return d(dl(n.expression));const r=n.branches.filter(i=>i.hasKind("unit"));return r.length?d(ul(r.map(i=>S(i.unit)))):n}},value:{child:!0,parse:(t,e)=>e.$.parseSchema(t)}},normalize:t=>t,defaults:{description:t=>`[${t.signature.expression}]: ${t.value.description}`},intersections:{index:(t,e,n)=>{if(t.signature.equals(e.signature)){const r=j(t.value,e.value,n),i=r instanceof g?p.intrinsic.never.internal:r;return n.$.node("index",{signature:t.signature,value:i})}return t.signature.extends(e.signature)&&t.value.subsumes(e.value)?e:e.signature.extends(t.signature)&&e.value.subsumes(t.value)?t:null}}});class ll extends Ke{impliedBasis=p.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=N(this.value.flatRefs.map(e=>de([this.signature,...e.path],e.node)),de([this.signature],this.value));traverseAllows=(e,n)=>mt(e).every(r=>this.signature.traverseAllows(r[0],n)?oe(r[0],()=>this.value.traverseAllows(r[1],n),n):!0);traverseApply=(e,n)=>{for(const r of mt(e))this.signature.traverseAllows(r[0],n)&&oe(r[0],()=>this.value.traverseApply(r[1],n),n)};_transform(e,n){n.path.push(this.signature);const r=super._transform(e,n);return n.path.pop(),r}compile(){}}const es={implementation:cl,Node:ll},ul=t=>`Index keys ${t.join(", ")} should be specified as named props.`,dl=t=>`Indexed key definition '${t}' must be a string or symbol`,hl=q({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(t,e)=>e.$.parseSchema(t)}},normalize:t=>t,defaults:{description:t=>`${t.compiledKey}: ${t.value.description}`,expected:t=>t.missingValueDescription,actual:()=>"missing"},intersections:{required:sn,optional:sn}});class pl extends Ji{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=Rt(this.errorContext)}const ts={implementation:hl,Node:pl},fl=q({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(t,e)=>{if(t.length!==0)return t.map(n=>e.$.parseSchema(n))}},optionals:{child:!0,parse:(t,e)=>{if(t.length!==0)return t.map(n=>e.$.parseSchema(n))}},defaultables:{child:t=>t.map(e=>e[0]),parse:(t,e)=>{if(t.length!==0)return t.map(n=>{const r=e.$.parseSchema(n[0]);return Nn(r,n[1],null),[r,n[1]]})},serialize:t=>t.map(e=>[e[0].collapsibleJson,be(e[1])]),reduceIo:(t,e,n)=>{if(t==="in"){e.optionals=n.map(r=>r[0].rawIn);return}e.prefix=n.map(r=>r[0].rawOut)}},variadic:{child:!0,parse:(t,e)=>e.$.parseSchema(t,e)},minVariadicLength:{parse:t=>t===0?void 0:t},postfix:{child:!0,parse:(t,e)=>{if(t.length!==0)return t.map(n=>e.$.parseSchema(n))}}},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 d($l);if(t.optionals?.length||t.defaultables?.length)return d(rs)}return t.minVariadicLength&&!t.variadic?d("minVariadicLength may not be specified without a variadic element"):t}return{variadic:t}},reduce:(t,e)=>{let n=t.minVariadicLength??0;const r=t.prefix?.slice()??[],i=t.defaultables?.slice()??[],s=t.optionals?.slice()??[],o=t.postfix?.slice()??[];if(t.variadic){for(;s[s.length-1]?.equals(t.variadic);)s.pop();if(s.length===0&&i.length===0)for(;r[r.length-1]?.equals(t.variadic);)r.pop(),n++;for(;o[0]?.equals(t.variadic);)o.shift(),n++}else s.length===0&&i.length===0&&r.push(...o.splice(0));if(n!==t.minVariadicLength||t.prefix&&t.prefix.length!==r.length)return e.node("sequence",{...t,prefix:r,defaultables:i,optionals:s,postfix:o,minVariadicLength:n},{prereduced:!0})},defaults:{description:t=>t.isVariadicOnly?`${t.variadic.nestableExpression}[]`:`[${t.tuple.map(n=>n.kind==="defaultables"?`${n.node.nestableExpression} = ${S(n.default)}`:n.kind==="optionals"?`${n.node.nestableExpression}?`:n.kind==="variadic"?`...${n.node.nestableExpression}[]`:n.node.expression).join(", ")}]`},intersections:{sequence:(t,e,n)=>{const r=ze({l:t.tuple,r:e.tuple,disjoint:new g,result:[],fixedVariants:[],ctx:n}),i=r.disjoint.length===0?[r,...r.fixedVariants]:r.fixedVariants;return i.length===0?r.disjoint:i.length===1?n.$.node("sequence",or(i[0].result)):n.$.node("union",i.map(s=>({proto:Array,sequence:or(s.result)})))}}});class ml extends Ke{impliedBasis=p.intrinsic.Array.internal;tuple=bl(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(e=>e.kind==="defaultables"||e.kind==="optionals"?(this.defaultablesAndOptionals.push(e.node),!0):e.kind==="prefix");variadicOrPostfix=ge(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return Gn(this.flatRefs,this.prevariadic.flatMap((e,n)=>N(e.node.flatRefs.map(r=>de([`${n}`,...r.path],r.node)),de([`${n}`],e.node)))),Gn(this.flatRefs,this.variadicOrPostfix.flatMap(e=>N(e.flatRefs.map(n=>de([p.intrinsic.nonNegativeIntegerString.internal,...n.path],n.node)),de([p.intrinsic.nonNegativeIntegerString.internal],e)))),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=yl(this);defaultValueMorphsReference=this.defaultValueMorphs.length?U(this.defaultValueMorphs):void 0;elementAtIndex(e,n){if(n<this.prevariadic.length)return this.tuple[n];const r=e.length-this.postfixLength;return n>=r?{kind:"postfix",node:this.postfix[n-r]}:{kind:"variadic",node:this.variadic??K(`Unexpected attempt to access index ${n} on ${this}`)}}traverseAllows=(e,n)=>{for(let r=0;r<e.length;r++)if(!this.elementAtIndex(e,r).node.traverseAllows(e[r],n))return!1;return!0};traverseApply=(e,n)=>{let r=0;for(;r<e.length;r++)oe(r,()=>this.elementAtIndex(e,r).node.traverseApply(e[r],n),n)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(e){if(this.prefix)for(const[n,r]of this.prefix.entries())e.traverseKey(`${n}`,`data[${n}]`,r);for(const[n,r]of this.defaultablesAndOptionals.entries()){const i=`${n+this.prefixLength}`;e.if(`${i} >= data.length`,()=>e.traversalKind==="Allows"?e.return(!0):e.return()),e.traverseKey(i,`data[${i}]`,r)}if(this.variadic&&(this.postfix&&e.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`),e.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>e.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix))for(const[n,r]of this.postfix.entries()){const i=`firstPostfixIndex + ${n}`;e.traverseKey(i,`data[${i}]`,r)}e.traversalKind==="Allows"&&e.return(!0)}_transform(e,n){n.path.push(p.intrinsic.nonNegativeIntegerString.internal);const r=super._transform(e,n);return n.path.pop(),r}expression=this.description;reduceJsonSchema(e,n){const r=n.target==="draft-07";if(this.prevariadic.length){const i=this.prevariadic.map(s=>{const o=s.node.toJsonSchemaRecurse(n);if(s.kind==="defaultables"){const a=typeof s.default=="function"?s.default():s.default;o.default=p.intrinsic.jsonData.allows(a)?a:n.fallback.defaultValue({code:"defaultValue",base:o,value:a})}return o});r?e.items=i:e.prefixItems=i}if(this.minLength&&(e.minItems=this.minLength),this.variadic){const i=this.variadic.toJsonSchemaRecurse(n);if(r&&this.prevariadic.length?e.additionalItems=i:e.items=i,this.maxLength&&(e.maxItems=this.maxLength),this.postfix){const s=this.postfix.map(o=>o.toJsonSchemaRecurse(n));e=n.fallback.arrayPostfix({code:"arrayPostfix",base:e,elements:s})}}else r?e.additionalItems=!1:e.items=!1,delete e.maxItems;return e}}const gl={},yl=t=>{if(!t.defaultables)return[];const e=[];let n="[";const r=t.prefixLength+t.defaultablesLength-1;for(let i=t.prefixLength;i<=r;i++){const[s,o]=t.defaultables[i-t.prefixLength];e.push(Gi(i,s,o)),n+=`${i}: ${s.id} = ${be(o)}, `}return n+="]",gl[n]??=e},ns={implementation:fl,Node:ml},bl=t=>{const e=[];if(t.prefix)for(const n of t.prefix)e.push({kind:"prefix",node:n});if(t.defaultables)for(const[n,r]of t.defaultables)e.push({kind:"defaultables",node:n,default:r});if(t.optionals)for(const n of t.optionals)e.push({kind:"optionals",node:n});if(t.variadic&&e.push({kind:"variadic",node:t.variadic}),t.postfix)for(const n of t.postfix)e.push({kind:"postfix",node:n});return e},or=t=>t.reduce((e,n)=>(n.kind==="variadic"?e.variadic=n.node:n.kind==="defaultables"?e.defaultables=N(e.defaultables,[[n.node,n.default]]):e[n.kind]=N(e[n.kind],n.node),e),{}),rs="A postfix required element cannot follow an optional or defaultable element",$l="A postfix element requires a variadic element",ze=t=>{const[e,...n]=t.l,[r,...i]=t.r;if(!e||!r)return t;const s=n[n.length-1]?.kind==="postfix",o=i[i.length-1]?.kind==="postfix",a=e.kind==="prefix"||r.kind==="prefix"?"prefix":e.kind==="postfix"||r.kind==="postfix"?"postfix":e.kind==="variadic"&&r.kind==="variadic"?"variadic":s||o?"prefix":e.kind==="defaultables"||r.kind==="defaultables"?"defaultables":"optionals";if(e.kind==="prefix"&&r.kind==="variadic"&&o){const h=ze({...t,fixedVariants:[],r:i.map(m=>({...m,kind:"prefix"}))});h.disjoint.length===0&&t.fixedVariants.push(h)}else if(r.kind==="prefix"&&e.kind==="variadic"&&s){const h=ze({...t,fixedVariants:[],l:n.map(m=>({...m,kind:"prefix"}))});h.disjoint.length===0&&t.fixedVariants.push(h)}const c=j(e.node,r.node,t.ctx);if(c instanceof g)if(a==="prefix"||a==="postfix")t.disjoint.push(...c.withPrefixKey(a==="prefix"?t.result.length:`-${n.length+1}`,ar(e)&&ar(r)?"required":"optional")),t.result=[...t.result,{kind:a,node:p.intrinsic.never.internal}];else return a==="optionals"||a==="defaultables"?t:ze({...t,fixedVariants:[],l:n.map(h=>({...h,kind:"prefix"})),r:n.map(h=>({...h,kind:"prefix"}))});else a==="defaultables"?(e.kind==="defaultables"&&r.kind==="defaultables"&&e.default!==r.default&&d(Vi(e.default,r.default)),t.result=[...t.result,{kind:a,node:c,default:e.kind==="defaultables"?e.default:r.kind==="defaultables"?r.default:K(`Unexpected defaultable intersection from ${e.kind} and ${r.kind} elements.`)}]):t.result=[...t.result,{kind:a,node:c}];const l=t.l.length,u=t.r.length;return(e.kind!=="variadic"||l>=u&&(r.kind==="variadic"||u===1))&&(t.l=n),(r.kind!=="variadic"||u>=l&&(e.kind==="variadic"||l===1))&&(t.r=i),ze(t)},ar=t=>t.kind==="prefix"||t.kind==="postfix",is=t=>e=>{if(e.props.length||e.index){const n=e.index?.map(i=>i[t])??[];for(const i of e.props)n.push(i[t]);e.undeclared&&n.push(`+ (undeclared): ${e.undeclared}`);const r=`{ ${n.join(", ")} }`;return e.sequence?`${r} & ${e.sequence.description}`:r}return e.sequence?.description??"{}"},wl=is("description"),vl=is("expression"),cr=(t,e,n)=>{const r=t.required?"required":"optional";if(!e.signature.allows(t.key))return null;const i=ae(t.value,e.value,n);return i instanceof g?r==="optional"?n.node("optional",{key:t.key,value:p.intrinsic.never.internal}):i.withPrefixKey(t.key,t.kind):null},xl=q({kind:"structure",hasAssociatedError:!1,normalize:t=>t,applyConfig:(t,e)=>!t.undeclared&&e.onUndeclaredKey!=="ignore"?{...t,undeclared:e.onUndeclaredKey}:t,keys:{required:{child:!0,parse:T("required"),reduceIo:(t,e,n)=>{e.required=N(e.required,n.map(r=>t==="in"?r.rawIn:r.rawOut))}},optional:{child:!0,parse:T("optional"),reduceIo:(t,e,n)=>{if(t==="in"){e.optional=n.map(r=>r.rawIn);return}for(const r of n)e[r.outProp.kind]=N(e[r.outProp.kind],r.outProp.rawOut)}},index:{child:!0,parse:T("index")},sequence:{child:!0,parse:T("sequence")},undeclared:{parse:t=>t==="ignore"?void 0:t,reduceIo:(t,e,n)=>{if(n==="reject"){e.undeclared="reject";return}t==="in"?delete e.undeclared:e.undeclared="reject"}}},defaults:{description:wl},intersections:{structure:(t,e,n)=>{const r={...t.inner},i={...e.inner},s=new g;if(t.undeclared){const c=t.keyof();for(const l of e.requiredKeys)c.allows(l)||s.add("presence",p.intrinsic.never.internal,e.propsByKey[l].value,{path:[l]});i.optional&&(i.optional=i.optional.filter(l=>c.allows(l.key))),i.index&&(i.index=i.index.flatMap(l=>{if(l.signature.extends(c))return l;const u=ae(c,l.signature,n.$);if(u instanceof g)return[];const h=on(u,l.value,n.$);return h.required&&(i.required=ge(i.required,h.required)),h.optional&&(i.optional=ge(i.optional,h.optional)),h.index??[]}))}if(e.undeclared){const c=e.keyof();for(const l of t.requiredKeys)c.allows(l)||s.add("presence",t.propsByKey[l].value,p.intrinsic.never.internal,{path:[l]});r.optional&&(r.optional=r.optional.filter(l=>c.allows(l.key))),r.index&&(r.index=r.index.flatMap(l=>{if(l.signature.extends(c))return l;const u=ae(c,l.signature,n.$);if(u instanceof g)return[];const h=on(u,l.value,n.$);return h.required&&(r.required=ge(r.required,h.required)),h.optional&&(r.optional=ge(r.optional,h.optional)),h.index??[]}))}const o={};(t.undeclared||e.undeclared)&&(o.undeclared=t.undeclared==="reject"||e.undeclared==="reject"?"reject":"delete");const a=$t({kind:"structure",baseInner:o,l:wt(r),r:wt(i),roots:[],ctx:n});return a instanceof g&&s.push(...a),s.length?s:a}},reduce:(t,e)=>{if(!t.required&&!t.optional)return;const n={};let r=!1;const i=t.optional?[...t.optional]:[];if(t.required)for(let s=0;s<t.required.length;s++){const o=t.required[s];if(o.key in n&&d(ur(o.key)),n[o.key]=!0,t.index)for(const a of t.index){const c=cr(o,a,e);if(c instanceof g)return c}}if(t.optional)for(let s=0;s<t.optional.length;s++){const o=t.optional[s];if(o.key in n&&d(ur(o.key)),n[o.key]=!0,t.index)for(const a of t.index){const c=cr(o,a,e);if(c instanceof g)return c;c!==null&&(i[s]=c,r=!0)}}if(r)return e.node("structure",{...t,optional:i},{prereduced:!0})}});class kl extends Ke{impliedBasis=p.intrinsic.object.internal;impliedSiblings=this.children.flatMap(e=>e.impliedSiblings??[]);props=ge(this.required,this.optional);propsByKey=O(this.props,(e,n)=>[n.key,n]);propsByKeyReference=U(this.propsByKey);expression=vl(this);requiredKeys=this.required?.map(e=>e.key)??[];optionalKeys=this.optional?.map(e=>e.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.$.units(this.literalKeys).branches;if(this.index)for(const{signature:n}of this.index)e=e.concat(n.branches);return this._keyof=this.$.node("union",e)}map(e){return this.$.node("structure",this.props.flatMap(e).reduce((n,r)=>{const i=this.propsByKey[r.key];if(z(r))return r.kind!=="required"&&r.kind!=="optional"?d(`Map result must have kind "required" or "optional" (was ${r.kind})`):(n[r.kind]=N(n[r.kind],r),n);const s=r.kind??i?.kind??"required",o=O(r,(a,c)=>a in Sn.implementation.keys?[a,c]:[]);return n[s]=N(n[s],this.$.node(s,o)),n},{}))}assertHasKeys(e){const n=e.filter(r=>!lt(r,this.keyof()));if(n.length)return d(lr(this.expression,n))}get(e,...n){let r,i=!1;const s=Nl(e);if((typeof s=="string"||typeof s=="symbol")&&this.propsByKey[s]&&(r=this.propsByKey[s].value,i=this.propsByKey[s].required),this.index)for(const a of this.index)lt(s,a.signature)&&(r=r?.and(a.value)??a.value);if(this.sequence&<(s,p.intrinsic.nonNegativeIntegerString))if(b(s,"root"))this.sequence.variadic&&(r=r?.and(this.sequence.element)??this.sequence.element);else{const a=Number.parseInt(s);if(a<this.sequence.prevariadic.length){const c=this.sequence.prevariadic[a].node;r=r?.and(c)??c,i||=a<this.sequence.prefixLength}else if(this.sequence.variadic){const c=this.$.node("union",this.sequence.variadicOrPostfix);r=r?.and(c)??c}}if(!r)return this.sequence?.variadic&&b(s,"root")&&s.extends(p.intrinsic.number)?d(Ol(s.expression,this.sequence.expression)):d(lr(this.expression,[s]));const o=r.get(...n);return i?o:o.or(p.intrinsic.undefined)}pick(...e){return this.assertHasKeys(e),this.$.node("structure",this.filterKeys("pick",e))}omit(...e){return this.assertHasKeys(e),this.$.node("structure",this.filterKeys("omit",e))}optionalize(){const{required:e,...n}=this.inner;return this.$.node("structure",{...n,optional:this.props.map(r=>r.hasKind("required")?this.$.node("optional",r.inner):r)})}require(){const{optional:e,...n}=this.inner;return this.$.node("structure",{...n,required:this.props.map(r=>r.hasKind("optional")?{key:r.key,value:r.value}:r)})}merge(e){const n=this.filterKeys("omit",[e.keyof()]);return e.required&&(n.required=N(n.required,e.required)),e.optional&&(n.optional=N(n.optional,e.optional)),e.index&&(n.index=N(n.index,e.index)),e.sequence&&(n.sequence=e.sequence),e.undeclared?n.undeclared=e.undeclared:delete n.undeclared,this.$.node("structure",n)}filterKeys(e,n){const r=$i(this.inner),i=s=>{const o=n.some(a=>lt(s,a));return e==="pick"?o:!o};return r.required&&(r.required=r.required.filter(s=>i(s.key))),r.optional&&(r.optional=r.optional.filter(s=>i(s.key))),r.index&&(r.index=r.index.filter(s=>i(s.signature))),r}traverseAllows=(e,n)=>this._traverse("Allows",e,n);traverseApply=(e,n)=>this._traverse("Apply",e,n);_traverse=(e,n,r)=>{const i=r?.currentErrorCount??0;for(let s=0;s<this.props.length;s++)if(e==="Allows"){if(!this.props[s].traverseAllows(n,r))return!1}else if(this.props[s].traverseApply(n,r),r.failFast&&r.currentErrorCount>i)return!1;if(this.sequence){if(e==="Allows"){if(!this.sequence.traverseAllows(n,r))return!1}else if(this.sequence.traverseApply(n,r),r.failFast&&r.currentErrorCount>i)return!1}if(this.index||this.undeclared==="reject"){const s=Object.keys(n);s.push(...Object.getOwnPropertySymbols(n));for(let o=0;o<s.length;o++){const a=s[o];if(this.index){for(const c of this.index)if(c.signature.traverseAllows(a,r)){if(e==="Allows"){if(!oe(a,()=>c.value.traverseAllows(n[a],r),r))return!1}else if(oe(a,()=>c.value.traverseApply(n[a],r),r),r.failFast&&r.currentErrorCount>i)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(a)&&(e==="Allows"||(r.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[a],meta:this.meta}),r.failFast)))return!1}}return this.structuralMorph&&r&&!r.hasError()&&r.queueMorphs([this.structuralMorph]),!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter(e=>e.hasDefault())??[])}declaresKey=e=>e in this.propsByKey||this.index?.some(n=>n.signature.allows(e))||this.sequence!==void 0&&p.intrinsic.nonNegativeIntegerString.allows(e);_compileDeclaresKey(e){const n=[];if(this.props.length&&n.push(`k in ${this.propsByKeyReference}`),this.index)for(const r of this.index)n.push(e.invoke(r.signature,{kind:"Allows",arg:"k"}));return this.sequence&&n.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)"),n.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",Il(this))}structuralMorphRef=this.structuralMorph&&U(this.structuralMorph);compile(e){e.traversalKind==="Apply"&&e.initializeErrorCount();for(const n of this.props)e.check(n),e.traversalKind==="Apply"&&e.returnIfFailFast();if(this.sequence&&(e.check(this.sequence),e.traversalKind==="Apply"&&e.returnIfFailFast()),(this.index||this.undeclared==="reject")&&(e.const("keys","Object.keys(data)"),e.line("keys.push(...Object.getOwnPropertySymbols(data))"),e.for("i < keys.length",()=>this.compileExhaustiveEntry(e))),e.traversalKind==="Allows")return e.return(!0);this.structuralMorphRef&&e.if("ctx && !ctx.hasError()",()=>(e.line("ctx.queueMorphs(["),Sl(e,this),e.line("])")))}compileExhaustiveEntry(e){if(e.const("k","keys[i]"),this.index)for(const n of this.index)e.if(`${e.invoke(n.signature,{arg:"k",kind:"Allows"})}`,()=>e.traverseKey("k","data[k]",n.value));return this.undeclared==="reject"&&e.if(`!(${this._compileDeclaresKey(e)})`,()=>e.traversalKind==="Allows"?e.return(!1):e.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>e.return())),e}reduceJsonSchema(e,n){switch(e.type){case"object":return this.reduceObjectJsonSchema(e,n);case"array":const r=this.sequence?.reduceJsonSchema(e,n)??e;return this.props.length||this.index?n.fallback.arrayObject({code:"arrayObject",base:r,object:this.reduceObjectJsonSchema({type:"object"},n)}):r;default:return L.throwInternalOperandError("structure",e)}}reduceObjectJsonSchema(e,n){if(this.props.length){e.properties={};for(const r of this.props){const i=r.value.toJsonSchemaRecurse(n);if(typeof r.key=="symbol"){n.fallback.symbolKey({code:"symbolKey",base:e,key:r.key,value:i,optional:r.optional});continue}if(r.hasDefault()){const s=typeof r.default=="function"?r.default():r.default;i.default=p.intrinsic.jsonData.allows(s)?s:n.fallback.defaultValue({code:"defaultValue",base:i,value:s})}e.properties[r.key]=i}this.requiredKeys.length&&e.properties&&(e.required=this.requiredKeys.filter(r=>typeof r=="string"&&r in e.properties))}if(this.index)for(const r of this.index){const i=r.value.toJsonSchemaRecurse(n);if(r.signature.equals(p.intrinsic.string)){e.additionalProperties=i;continue}for(const s of r.signature.branches){if(!s.extends(p.intrinsic.string)){e=n.fallback.symbolKey({code:"symbolKey",base:e,key:null,value:i,optional:!1});continue}let o={type:"string"};if(s.hasKind("morph")&&(o=n.fallback.morph({code:"morph",base:s.rawIn.toJsonSchemaRecurse(n),out:s.rawOut.toJsonSchemaRecurse(n)})),!s.hasKind("intersection"))return K(`Unexpected index branch kind ${s.kind}.`);const{pattern:a}=s.inner;if(a){const c=Object.assign(o,{pattern:a[0].rule});for(let l=1;l<a.length;l++)o=n.fallback.patternIntersection({code:"patternIntersection",base:c,pattern:a[l].rule});e.patternProperties??={},e.patternProperties[c.pattern]=i}}}return this.undeclared&&!e.additionalProperties&&(e.additionalProperties=!1),e}}const jt={},Al=t=>{let e="";for(let n=0;n<t.defaultable.length;n++)e+=t.defaultable[n].defaultValueMorphRef;if(t.sequence?.defaultValueMorphsReference&&(e+=t.sequence?.defaultValueMorphsReference),t.undeclared==="delete"){if(e+="delete !(",t.required)for(const n of t.required)e+=n.compiledKey+" | ";if(t.optional)for(const n of t.optional)e+=n.compiledKey+" | ";if(t.index)for(const n of t.index)e+=n.signature.id+" | ";if(t.sequence)if(t.sequence.maxLength===null)e+=$.nonNegativeIntegerString.id;else for(let n=0;n<t.sequence.tuple.length;n++)e+=n+" | ";e+=")"}return e},Il=t=>{const e=Al(t);if(!e)return;if(jt[e])return jt[e];const n=(r,i)=>{for(let s=0;s<t.defaultable.length;s++)t.defaultable[s].key in r||t.defaultable[s].defaultValueMorph(r,i);if(t.sequence?.defaultables)for(let s=r.length-t.sequence.prefixLength;s<t.sequence.defaultables.length;s++)t.sequence.defaultValueMorphs[s](r,i);if(t.undeclared==="delete")for(const s in r)t.declaresKey(s)||delete r[s];return r};return jt[e]=n},Sl=(t,e)=>{const r=`(data${e.defaultable.some(i=>i.defaultValueMorph.length===2)||e.sequence?.defaultValueMorphs.some(i=>i.length===2)?", ctx":""})`;return t.block(`${r} => `,i=>{for(let s=0;s<e.defaultable.length;s++){const{serializedKey:o,defaultValueMorphRef:a}=e.defaultable[s];i.if(`!(${o} in data)`,c=>c.line(`${a}${r}`))}return e.sequence?.defaultables&&i.for(`i < ${e.sequence.defaultables.length}`,s=>s.set("data[i]",5),`data.length - ${e.sequence.prefixLength}`),e.undeclared==="delete"&&i.forIn("data",s=>s.if(`!(${e._compileDeclaresKey(s)})`,o=>o.line("delete data[k]"))),i.return("data")})},ss={implementation:xl,Node:kl},Nl=t=>(b(t,"root")&&t.hasKind("unit")&&(t=t.unit),typeof t=="number"&&(t=`${t}`),t),Ol=(t,e)=>`${t} is not allowed as an array index on ${e}. Use the 'nonNegativeIntegerString' keyword instead.`,on=(t,e,n)=>{const[r,i]=xo(t.branches,o=>o.hasKind("unit"));if(!r.length)return{index:n.node("index",{signature:t,value:e})};const s={};for(const o of r){const a=n.node("required",{key:o.unit,value:e});s[a.kind]=N(s[a.kind],a)}return i.length&&(s.index=n.node("index",{signature:i,value:e})),s},Rl=t=>b(t,"root")?t.expression:S(t),lr=(t,e)=>`Key${e.length===1?"":"s"} ${e.map(Rl).join(", ")} ${e.length===1?"does":"do"} not exist on ${t}`,ur=t=>`Duplicate key ${De(t)}`,Mt={...gc,alias:On.implementation,domain:Cn.implementation,unit:Xi.implementation,proto:xt.implementation,union:Qi.implementation,morph:Zi.implementation,intersection:Hi.implementation,divisor:Ci.implementation,pattern:Ui.implementation,predicate:Ri.implementation,required:ts.implementation,optional:Sn.implementation,index:es.implementation,sequence:ns.implementation,structure:ss.implementation};p.defaultConfig=Eo(Object.assign(O(Mt,(t,e)=>[t,e.defaults]),{jitless:_o(),clone:zo,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:L.defaultConfig}));p.resolvedConfig=en(p.defaultConfig,p.config);const Cl={...yc,alias:On.Node,domain:Cn.Node,unit:Xi.Node,proto:xt.Node,union:Qi.Node,morph:Zi.Node,intersection:Hi.Node,divisor:Ci.Node,pattern:Ui.Node,predicate:Ri.Node,required:ts.Node,optional:Sn.Node,index:es.Node,sequence:ns.Node,structure:ss.Node};class an extends Co{get[se](){return"module"}}const os=(t,e)=>new an(O(t,(n,r)=>[n,b(r,"module")?os(r,e):e.bindReference(r)])),Ml=t=>F(t)?t:"branches"in t&&F(t.branches)?t.branches:void 0,Pl=(t,e)=>d(`Node of kind ${e} is not valid as a ${t} definition`),dr=t=>`#${t} duplicates public alias ${t}`,Ft={};p.ambient??={};let hr;const as="function $",ql=t=>cs(t,ls(t)),cs=(t,e)=>{const n=e.write(as,4),r=e.compile()();for(const i of t)i.precompilation||(i.traverseAllows=r[`${i.id}Allows`].bind(r),i.isRoot()&&!i.allowsRequiresContext&&(i.allows=i.traverseAllows),i.traverseApply=r[`${i.id}Apply`].bind(r),r[`${i.id}Optimistic`]&&(i.traverseOptimistic=r[`${i.id}Optimistic`].bind(r)),i.precompilation=n)},ls=t=>(new gi).return(t.reduce((e,n)=>{const r=new Lt({kind:"Allows"}).indent();n.compile(r);const i=r.write(`${n.id}Allows`),s=new Lt({kind:"Apply"}).indent();n.compile(s);const o=s.write(`${n.id}Apply`),a=`${e}${i},\n${o},\n`;if(!n.hasKind("union"))return a;const c=new Lt({kind:"Allows",optimistic:!0}).indent();n.compile(c);const l=c.write(`${n.id}Optimistic`);return`${a}${l},\n`},`{\n`)+"}");class us{config;resolvedConfig;name;get[se](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,n){this.config=en(p.config,n),this.resolvedConfig=en(p.resolvedConfig,n),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Ft).length}`,this.name in Ft&&d(`A Scope already named ${this.name} already exists`),Ft[this.name]=this;const r=Object.entries(e).map(i=>this.preparseOwnAliasEntry(...i));for(const[i,s]of r){let o=i;if(i[0]==="#"?(o=i.slice(1),o in this.aliases&&d(dr(o)),this.aliases[o]=s):(o in this.aliases&&d(dr(i)),this.aliases[o]=s,this.exportedNames.push(o)),!b(s,"module")&&!b(s,"generic")&&!It(s)){const a=this.preparseOwnDefinitionFormat(s,{alias:o});this.resolutions[o]=b(a,"root")?this.bindReference(a):this.createParseContext(a).id}}hr??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[hr.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=p.intrinsic?O(p.intrinsic,(i,s)=>i.startsWith("json")?[]:[i,this.bindReference(s)]):{}}cacheGetter(e,n){return Object.defineProperty(this,e,{value:n}),n}get internal(){return this}_json;get json(){return this._json||this.export(),this._json}defineSchema(e){return e}generic=(...e)=>{const n=this;return(r,i)=>new vt(e,i?new Oi(r):r,n,n,i??null)};units=(e,n)=>{const r=[];for(const s of e)r.includes(s)||r.push(s);const i=r.map(s=>this.node("unit",{unit:s},n));return this.node("union",i,{...n,prereduced:!0})};lazyResolutions=[];lazilyResolve(e,n){const r=this.node("alias",{reference:n??"synthetic",resolve:e},{prereduced:!0});return this.resolved||this.lazyResolutions.push(r),r}schema=(e,n)=>this.finalize(this.parseSchema(e,n));parseSchema=(e,n)=>this.node(ht(e),e,n);preparseNode(e,n,r){let i=typeof e=="string"?e:ht(n,e);if(z(n)&&n.kind===i)return n;if(i==="alias"&&!r?.prereduced){const{reference:a}=On.implementation.normalize(n,this);if(a.startsWith("$")){const c=this.resolveRoot(a.slice(1));n=c,i=c.kind}}else if(i==="union"&&$e(n,"object")){const a=Ml(n);a?.length===1&&(n=a[0],i=ht(n))}if(z(n)&&n.kind===i)return n;const o=Mt[i].normalize?.(n,this)??n;return z(o)?o.kind===i?o:Pl(i,o.kind):{...r,$:this,kind:i,def:o,prefix:r.alias??i}}bindReference(e){let n;return z(e)?n=e.$===this?e:new e.constructor(e.attachments,this):n=e.$===this?e:new vt(e.params,e.bodyDef,e.$,this,e.hkt),this.resolved||Object.assign(this.referencesById,n.referencesById),n}resolveRoot(e){return this.maybeResolveRoot(e)??d(fs(e))}maybeResolveRoot(e){const n=this.maybeResolve(e);if(!b(n,"generic"))return n}maybeResolveSubalias(e){return cn(this.aliases,e)??cn(this.ambient,e)}get ambient(){return p.ambient}maybeResolve(e){const n=this.resolutions[e];if(n){if(typeof n!="string")return this.bindReference(n);const i=W[n];if(b(i,"root"))return this.resolutions[e]=i;if(b(i,"context")){if(i.phase==="resolving")return this.node("alias",{reference:`$${e}`},{prereduced:!0});if(i.phase==="resolved")return K(`Unexpected resolved context for was uncached by its scope: ${S(i)}`);i.phase="resolving";const s=this.bindReference(this.parseOwnDefinitionFormat(i.def,i));return i.phase="resolved",W[s.id]=s,W[i.id]=s,this.resolutions[e]=s}return K(`Unexpected nodesById entry for ${n}: ${S(i)}`)}let r=this.aliases[e]??this.ambient?.[e];return r?(r=this.normalizeRootScopeValue(r),b(r,"generic")?this.resolutions[e]=this.bindReference(r):b(r,"module")?(r.root||d(ms(e)),this.resolutions[e]=this.bindReference(r.root)):this.resolutions[e]=this.parse(r,{alias:e})):this.maybeResolveSubalias(e)}createParseContext(e){const n=e.id??Ti(e.prefix);return W[n]=Object.assign(e,{[se]:"context",$:this,id:n,phase:"unresolved"})}traversal(e){return new Ne(e,this.resolvedConfig)}import(...e){return new an(O(this.export(...e),(n,r)=>[`#${n}`,r]))}precompilation;_exportedResolutions;_exports;export(...e){if(!this._exports){this._exports={};for(const r of this.exportedNames){const i=this.aliases[r];this._exports[r]=b(i,"module")?os(i,this):pr(this.maybeResolve(r))}for(const r of this.lazyResolutions)r.resolution;if(this._exportedResolutions=ps(this,this._exports),this._json=hs(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){const r=ls(this.references);this.precompilation=r.write(as,4),cs(this.references,r)}this.resolved=!0}const n=e.length?e:this.exportedNames;return new an(O(n,(r,i)=>[i,this._exports[i]]))}resolve(e){return this.export()[e]}node=(e,n,r={})=>{const i=this.preparseNode(e,n,r);if(z(i))return this.bindReference(i);const s=this.createParseContext(i),o=_i(s),a=this.bindReference(o);return W[s.id]=a};parse=(e,n={})=>this.finalize(this.parseDefinition(e,n));parseDefinition(e,n={}){if(b(e,"root"))return this.bindReference(e);const r=this.preparseOwnDefinitionFormat(e,n);if(b(r,"root"))return this.bindReference(r);const i=this.createParseContext(r);W[i.id]=i;let s=this.bindReference(this.parseOwnDefinitionFormat(e,i));return s.isCyclic&&(s=xc(s,i.id)),W[i.id]=s,s}finalize(e){return pr(e),!e.precompilation&&!this.resolvedConfig.jitless&&ql(e.references),e}}class ds extends us{parseOwnDefinitionFormat(e,n){return _i(n)}preparseOwnDefinitionFormat(e,n){return this.preparseNode(ht(e),e,n)}preparseOwnAliasEntry(e,n){return[e,n]}normalizeRootScopeValue(e){return e}}const pr=t=>{const e=t.references.filter(n=>n.hasKind("alias"));for(const n of e){Object.assign(n.referencesById,n.resolution.referencesById);for(const r of t.references)n.id in r.referencesById&&Object.assign(r.referencesById,n.referencesById)}return t},hs=t=>O(t,(e,n)=>[e,b(n,"root")||b(n,"generic")?n.json:b(n,"module")?hs(n):K(`Unexpected resolution ${S(n)}`)]),cn=(t,e)=>{const n=e.indexOf(".");if(n===-1)return;const r=e.slice(0,n),i=t[r];if(i===void 0)return;if(!b(i,"module"))return d(El(r));const s=e.slice(n+1),o=i[s];if(o===void 0)return cn(i,s);if(b(o,"root")||b(o,"generic"))return o;if(b(o,"module"))return o.root??d(ms(e));K(`Unexpected resolution for alias '${e}': ${S(o)}`)},Mn=(t,e)=>new ds(t,e),rt=new ds({}),ps=(t,e)=>{const n={};for(const r in e){const i=e[r];if(b(i,"module")){const s=ps(t,i),o=O(s,(a,c)=>[`${r}.${a}`,c]);Object.assign(n,o)}else b(i,"root")||b(i,"generic")?n[r]=i:K(`Unexpected scope resolution ${S(i)}`)}return n},fs=t=>`'${t}' is unresolvable`,El=t=>`'${t}' must reference a module to be accessed using dot syntax`,ms=t=>`Reference to submodule '${t}' must specify an alias`;rt.export();const R=rt.schema,Pn=rt.node;rt.defineSchema;const ce=rt.generic,gs="^(?:0|[1-9]\\d*)$",Dl=new RegExp(gs);U(Dl);const ys=Mn({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:Array,Date:Date},{prereducedAliases:!0}).export();p.intrinsic={...ys};const bs=Mn({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:gs}},{prereducedAliases:!0}).export();Object.assign(p.intrinsic,bs);const Kl=Mn({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),$={...ys,...bs,...Kl,emptyStructure:Pn("structure",{},{prereduced:!0})};p.intrinsic={...$};const fr=(t,e)=>new RegExp(t,e);Object.assign(fr,{as:fr});const Ll=t=>typeof t=="string"&&t[0]==="d"&&(t[1]==="'"||t[1]==='"')&&t[t.length-1]===t[1],mr=t=>t.toString()!=="Invalid Date",Bl=t=>t.slice(2,-1),$s=t=>`'${t}' could not be parsed by the Date constructor`,jl=(t,e)=>Fl(t,e),Fl=(t,e)=>{const n=new Date(t);if(mr(n))return n;const r=ca(t);if(r!==void 0){const i=new Date(r);if(mr(i))return i}return e?d(e===!0?$s(t):e):void 0},zl=R({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),zt=(t,e)=>{const n=t.scanner.shiftUntilEscapable(_l[xs[e]]);if(t.scanner.lookahead==="")return t.error(Vl(n,e));if(t.scanner.shift(),e in vs){let r;try{r=new RegExp(n)}catch(i){d(String(i))}t.root=t.ctx.$.node("intersection",{domain:"string",pattern:n},{prereduced:!0}),e==="x/"&&(t.root=t.ctx.$.node("morph",{in:t.root,morphs:i=>r.exec(i),declaredOut:zl}))}else if(te(e,ws))t.root=t.ctx.$.node("unit",{unit:n});else{const r=jl(n,$s(n));t.root=t.ctx.$.node("unit",{meta:n,unit:r})}},ws={"'":1,'"':1},Ul={"/":1,"'":1,'"':1},Tl={"d'":"'",'d"':'"',"'":"'",'"':'"'},vs={"/":"/","x/":"/"},xs={...Tl,...vs},_l={"'":t=>t.lookahead==="'",'"':t=>t.lookahead==='"',"/":t=>t.lookahead==="/"},Jl={'"':"double-quote","'":"single-quote","/":"forward slash"},Vl=(t,e)=>`${e}${t} requires a closing ${Jl[xs[e]]}`,Gl=t=>`Private type references should not include '#'. Use '${t}' instead.`,ks="Optional definitions like 'string?' are only valid as properties in an object or tuple",As="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple",Be={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...St},Wl=(t,e)=>t===">"?e[0]==="="?e[1]==="=":e.trimStart()===""||te(e.trimStart()[0],Be):t==="="?e[0]!=="=":t===","||t==="?",Hl=(t,e,n)=>Is(t,e,n,[]),Is=(t,e,n,r)=>{const i=n.parseUntilFinalizer();return r.push(i.root),i.finalizer===">"?r.length!==e.params.length?n.error(Ss(t,e.names,r.map(s=>s.expression))):r:i.finalizer===","?Is(t,e,n,r):i.error(fi(">"))},Ss=(t,e,n)=>`${t}<${e.join(", ")}> requires exactly ${e.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`,Ut=t=>{const e=t.scanner.shiftUntilLookahead(Be);e==="keyof"?t.addPrefix("keyof"):t.root=Yl(t,e)},Zl=(t,e,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(Ss(t,e.names,[]));const i=Hl(t,e,n);return e(...i)},Yl=(t,e)=>Ql(t,e)??Xl(t,e)??t.error(e===""?t.scanner.lookahead==="#"?Gl(t.shiftedBy(1).scanner.shiftUntilLookahead(Be)):Ns(t):fs(e)),Ql=(t,e)=>{if(t.ctx.args?.[e]){const r=t.ctx.args[e];return typeof r!="string"?r:t.ctx.$.node("alias",{reference:r},{prereduced:!0})}const n=t.ctx.$.maybeResolve(e);if(b(n,"root"))return n;if(n!==void 0)return b(n,"generic")?Zl(e,n,t):d(`Unexpected resolution ${S(n)}`)},Xl=(t,e)=>{const n=la(e);if(n!==void 0)return t.ctx.$.node("unit",{unit:n});const r=da(e);if(r!==void 0)return t.ctx.$.node("unit",{unit:r})},Ns=t=>{const e=t.previousOperator();return e?Os(e,t.scanner.unscanned):eu(t.scanner.unscanned)},Os=(t,e="")=>`Token '${t}' requires a right operand${e?` before '${e}'`:""}`,eu=t=>`Expected an expression${t?` before '${t}'`:""}`,Rs=t=>t.scanner.lookahead===""?t.error(Ns(t)):t.scanner.lookahead==="("?t.shiftedBy(1).reduceGroupOpen():t.scanner.lookaheadIsIn(Ul)?zt(t,t.scanner.shift()):t.scanner.lookaheadIsIn(St)?Rs(t.shiftedBy(1)):t.scanner.lookahead==="d"?t.scanner.nextLookahead in ws?zt(t,`${t.scanner.shift()}${t.scanner.shift()}`):Ut(t):t.scanner.lookahead==="x"&&t.scanner.nextLookahead==="/"?t.shiftedBy(2)&&zt(t,"x/"):Ut(t),tu={">":!0,">=":!0},nu={"<":!0,"<=":!0},kt={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},ru=(t,e)=>`Left bounds are only valid when paired with right bounds (try ...${e}${t})`,Cs=t=>`Left-bounded expressions must specify their limits using < or <= (was ${t})`,iu=(t,e,n,r)=>`An expression may have at most one left bound (parsed ${t}${kt[e]}, ${n}${kt[r]})`,su=(t,e)=>{const n=au(t,e);if(t.root.hasKind("unit")){if(typeof t.root.unit=="number"){t.reduceLeftBound(t.root.unit,n),t.unsetRoot();return}if(t.root.unit instanceof Date){const r=`d'${t.root.description??t.root.unit.toISOString()}'`;t.unsetRoot(),t.reduceLeftBound(r,n);return}}return lu(t,n)},ou={"<":1,">":1,"=":1},au=(t,e)=>t.scanner.lookaheadIs("=")?`${e}${t.scanner.shift()}`:e,gr=(t,e,n,r)=>n.extends(p.intrinsic.number)?typeof e!="number"?d(ln(t,e,r)):t==="=="?["min","max"]:t[0]===">"?["min"]:["max"]:n.extends(p.intrinsic.lengthBoundable)?typeof e!="number"?d(ln(t,e,r)):t==="=="?["exactLength"]:t[0]===">"?["minLength"]:["maxLength"]:n.extends(p.intrinsic.Date)?t==="=="?["after","before"]:t[0]===">"?["after"]:["before"]:d(tc(n.expression)),cu=t=>({rule:Ll(t.limit)?Bl(t.limit):t.limit,exclusive:t.comparator.length===1}),lu=(t,e)=>{const n=t.unsetRoot(),r=t.scanner.location;t.parseOperand();const i=t.unsetRoot(),s=t.scanner.sliceChars(r,t.scanner.location);if(t.root=n,!i.hasKind("unit")||typeof i.unit!="number"&&!(i.unit instanceof Date))return t.error(ln(e,s,"right"));const o=i.unit,a=e.length===1,c=gr(e,typeof o=="number"?o:s,n,"right");for(const u of c)t.constrainRoot(u,e==="=="?{rule:o}:{rule:o,exclusive:a});if(!t.branches.leftBound)return;if(!te(e,nu))return t.error(Cs(e));const l=gr(t.branches.leftBound.comparator,t.branches.leftBound.limit,n,"left");t.constrainRoot(l[0],cu(t.branches.leftBound)),t.branches.leftBound=null},ln=(t,e,n)=>`Comparator ${n==="left"?kt[t]:t} must be ${n==="left"?"preceded":"followed"} by a corresponding literal (was ${e})`,uu=t=>{t.scanner.shiftUntilNonWhitespace();const e=t.scanner.shiftUntilLookahead(Be);t.root=t.root.brand(e)},du=t=>{t.scanner.shiftUntilNonWhitespace();const e=t.scanner.shiftUntilLookahead(Be),n=ua(e,{errorOnFail:yr(e)});n===0&&t.error(yr(0)),t.root=t.root.constrain("divisor",n)},yr=t=>`% operator must be followed by a non-zero integer literal (was ${t})`,Ms=t=>{const e=t.scanner.shift();return e===""?t.finalize(""):e==="["?t.scanner.shift()==="]"?t.setRoot(t.root.array()):t.error(hu):e==="|"?t.scanner.lookahead===">"?t.shiftedBy(1).pushRootToBranch("|>"):t.pushRootToBranch(e):e==="&"?t.pushRootToBranch(e):e===")"?t.finalizeGroup():Wl(e,t.scanner.unscanned)?t.finalize(e):te(e,ou)?su(t,e):e==="%"?du(t):e==="#"?uu(t):e in St?Ms(t):t.error(qn(e))},qn=(t,e="")=>`'${t}' is not allowed here${e&&` (should be ${e})`}`,hu="Missing expected ']'",pu=t=>{const e=t.unsetRoot();t.parseOperand();const n=t.unsetRoot();if(!n.hasKind("unit"))return t.error(fu(n.expression));const r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[e,"=",r]},fu=t=>`Default value '${t}' must be a literal value`,br=(t,e)=>{const n=e.$.maybeResolveRoot(t);if(n)return n;if(t.endsWith("[]")){const s=e.$.maybeResolveRoot(t.slice(0,-2));if(s)return s.array()}const r=new Pt(new pi(t),e),i=mu(r);return r.finalizer===">"&&d(qn(">")),i},mu=t=>{t.parseOperand();let e=En(t).root;return e?(t.finalizer==="="?e=pu(t):t.finalizer==="?"&&(e=[e,"?"]),t.scanner.shiftUntilNonWhitespace(),t.scanner.lookahead&&d(qn(t.scanner.lookahead)),e):K(`Root was unexpectedly unset after parsing string '${t.scanner.scanned}'`)},En=t=>{for(;t.finalizer===void 0;)gu(t);return t},gu=t=>t.hasRoot()?t.parseOperator():t.parseOperand();class Pt{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(e,n){this.scanner=e,this.ctx=n}error(e){return d(e)}hasRoot(){return this.root!==void 0}setRoot(e){this.root=e}unsetRoot(){const e=this.root;return this.root=void 0,e}constrainRoot(...e){this.root=this.root.constrain(e[0],e[1])}finalize(e){if(this.groups.length)return this.error(fi(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,n){const r=kt[n];if(!te(r,tu))return this.error(Cs(n));if(this.branches.leftBound)return this.error(iu(this.branches.leftBound.limit,this.branches.leftBound.comparator,e,r));this.branches.leftBound={comparator:r,limit:e}}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();const e=this.groups.pop();if(!e)return this.error($a(")",this.scanner.unscanned));this.branches=e}addPrefix(e){this.branches.prefixes.push(e)}applyPrefixes(){for(;this.branches.prefixes.length;){const e=this.branches.prefixes.pop();this.root=e==="keyof"?this.root.keyof():K(`Unexpected prefix '${e}'`)}}pushRootToBranch(e){this.assertRangeUnset(),this.applyPrefixes();const n=this.root;this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(n)??n,e!=="&"&&(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,e!=="|"&&(this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null))}parseUntilFinalizer(){return En(new Pt(this.scanner,this.ctx))}parseOperator(){return Ms(this)}parseOperand(){return Rs(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(ru(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[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedBy(e){return this.scanner.jumpForward(e),this}}const yu="An empty string is not a valid generic parameter name",un=(t,e,n)=>{t.shiftUntilNonWhitespace();const r=t.shiftUntilLookahead(Be);return r===""?t.lookahead===""&&e.length?e:d(yu):(t.shiftUntilNonWhitespace(),bu(t,r,e,n))},$r="extends ",bu=(t,e,n,r)=>{if(t.shiftUntilNonWhitespace(),t.unscanned.startsWith($r))t.jumpForward($r.length);else return t.lookahead===","&&t.shift(),n.push(e),un(t,n,r);const i=En(new Pt(t,r));return n.push([e,i.root]),un(t,n,r)};class $u extends pe{constructor(e){const n={$:e,raw:e.fn};super((...r)=>{const i=r.indexOf(":"),s=i===-1?r.length-1:i-1,o=r.slice(0,s+1),a=e.parse(o).assertHasKind("intersection");let c=e.intrinsic.unknown;if(i!==-1){if(i!==r.length-2)return d(vu);c=e.parse(r[i+1])}return l=>new wu(l,a,c)},{attach:n})}}class wu extends pe{raw;params;returns;expression;constructor(e,n,r){const i=`typed ${e.name}`,s={[i]:(...a)=>{const c=n.assert(a),l=e(...c);return r.assert(l)}}[i];super(s),this.raw=e,this.params=n,this.returns=r;let o=n.expression;o[0]==="["&&o[o.length-1]==="]"?o=o.slice(1,-1):o.endsWith("[]")&&(o=`...${o}`),this.expression=`(${o}) => ${r?.expression??"unknown"}`}}const vu=`":" must be followed by exactly one return type e.g:\nfn("string", ":", "number")(s => s.length)`;class xu extends pe{$;constructor(e){super((...n)=>new ut(e)(...n),{bind:e}),this.$=e}in(e){return new ut(this.$,e===void 0?void 0:this.$.parse(e))}at(e,n){return new ut(this.$).at(e,n)}case(e,n){return new ut(this.$).case(e,n)}}class ut extends pe{$;in;key;branches=[];constructor(e,n){super(r=>this.caseEntries(Object.entries(r).map(([i,s])=>i==="default"?[i,s]:[this.$.parse(i),s]))),this.$=e,this.in=n}at(e,n){return this.key&&d(Au),this.branches.length&&d(ku),this.key=e,n?this.match(n):this}case(e,n){return this.caseEntry(this.$.parse(e),n)}caseEntry(e,n){const i=(this.key?this.$.parse({[this.key]:e}):e).pipe(n);return this.branches.push(i),this}match(e){return this(e)}strings(e){return this.caseEntries(Object.entries(e).map(([n,r])=>n==="default"?[n,r]:[this.$.node("unit",{unit:n}),r]))}caseEntries(e){for(let n=0;n<e.length;n++){const[r,i]=e[n];if(r==="default")return n!==e.length-1&&d("default may only be specified as the last key of a switch definition"),this.default(i);if(typeof i!="function")return d(`Value for case "${r}" must be a function (was ${Q(i)})`);this.caseEntry(r,i)}return this}default(e){typeof e=="function"&&this.case($.unknown,e);const n={branches:this.branches,ordered:!0};(e==="never"||e==="assert")&&(n.meta={onFail:wr});const r=this.$.node("union",n);if(!this.in)return this.$.finalize(r);let i=this.in.pipe(r);return(e==="never"||e==="assert")&&(i=i.configureReferences({onFail:wr},"self")),this.$.finalize(i)}}const wr=t=>t.throw(),ku="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",Au="At most one key matcher may be specified per expression",Ps=(t,e)=>{if(F(t)){if(t[1]==="=")return[e.$.parseOwnDefinitionFormat(t[0],e),"=",t[2]];if(t[1]==="?")return[e.$.parseOwnDefinitionFormat(t[0],e),"?"]}return js(t,e)},Iu="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",Su="Only required keys may specify default values, e.g. { value: 'number = 0' }",Nu=(t,e)=>{let n;const r={},i=mt(t);for(const[o,a]of i){const c=Cu(o);if(c.kind==="spread"){if(!Ye(r))return d(Ru);const y=e.$.parseOwnDefinitionFormat(a,e);if(y.equals($.object))continue;if(!y.hasKind("intersection")||!y.basis?.equals($.object))return d(Mu(y.expression));n=y.structure;continue}if(c.kind==="undeclared"){a!=="reject"&&a!=="delete"&&a!=="ignore"&&d(Ou(a)),r.undeclared=a;continue}const l=Ps(a,e),u=c;if(c.kind==="required"){F(l)?Tt(r,"optional",l[1]==="="?{key:c.normalized,value:l[0],default:l[2]}:{key:c.normalized,value:l[0]},e):Tt(r,"required",{key:c.normalized,value:l},e);continue}if(F(l)&&(l[1]==="?"&&d(Iu),l[1]==="="&&d(Su)),c.kind==="optional"){Tt(r,"optional",{key:c.normalized,value:l},e);continue}const h=e.$.parseOwnDefinitionFormat(u.normalized,e),m=on(h,l,e.$);m.index&&(r.index=N(r.index,m.index)),m.required&&(r.required=N(r.required,m.required))}const s=e.$.node("structure",r);return e.$.parseSchema({domain:"object",structure:n?.merge(s)??s})},Tt=(t,e,n,r)=>{t[e]=N(t[e],r.$.node(e,n))},Ou=t=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${S(t)})`,Ru="Spread operator may only be used as the first key in an object",Cu=t=>typeof t=="symbol"?{kind:"required",normalized:t}:t[t.length-1]==="?"?t[t.length-2]===Te?{kind:"required",normalized:`${t.slice(0,-2)}?`}:{kind:"optional",normalized:t.slice(0,-1)}:t[0]==="["&&t[t.length-1]==="]"?{kind:"index",normalized:t.slice(1,-1)}:t[0]===Te&&t[1]==="["&&t[t.length-1]==="]"?{kind:"required",normalized:t.slice(1)}:t==="..."?{kind:"spread"}:t==="+"?{kind:"undeclared"}:{kind:"required",normalized:t==="\\..."?"...":t==="\\+"?"+":t},Mu=t=>`Spread operand must resolve to an object literal type (was ${t})`,Pu=(t,e)=>Uu(t)?Ks[t[0]](t,e):Fu(t)?Ds[t[1]](t,e):null,qu=(t,e)=>e.$.parseOwnDefinitionFormat(t[1],e).keyof(),_t=(t,e)=>{if(t[2]===void 0)return d(Os(t[1],""));const n=e.$.parseOwnDefinitionFormat(t[0],e),r=e.$.parseOwnDefinitionFormat(t[2],e);if(t[1]==="|")return e.$.node("union",{branches:[n,r]});const i=t[1]==="&"?ae(n,r,e.$):nn(n,r,e.$);return i instanceof g?i.throw():i},Eu=(t,e)=>e.$.parseOwnDefinitionFormat(t[0],e).array(),Du=(t,e)=>typeof t[2]!="function"?d(qs("=>",t[2])):e.$.parseOwnDefinitionFormat(t[0],e).pipe(t[2]),qs=(t,e)=>`${t===":"?"Narrow":"Morph"} expression requires a function following '${t}' (was ${typeof e})`,Ku=(t,e)=>typeof t[2]!="function"?d(qs(":",t[2])):e.$.parseOwnDefinitionFormat(t[0],e).constrain("predicate",t[2]),Lu=(t,e)=>e.$.parseOwnDefinitionFormat(t[0],e).configure(t[2],t[3]),Es=t=>t,Bu=Es({"[]":Eu,"?":()=>d(ks)}),ju=Es({"|":_t,"&":_t,":":Ku,"=>":Du,"|>":_t,"@":Lu,"=":()=>d(As)}),Ds={...Bu,...ju},Fu=t=>Ds[t[1]]!==void 0,zu=t=>t,Ks=zu({keyof:qu,instanceof:(t,e)=>{if(typeof t[1]!="function")return d(vr(Ht(t[1])));const n=t.slice(1).map(r=>typeof r=="function"?e.$.node("proto",{proto:r}):d(vr(Ht(r))));return n.length===1?n[0]:e.$.node("union",{branches:n})},"===":(t,e)=>e.$.units(t.slice(1))}),Uu=t=>Ks[t[0]]!==void 0,vr=t=>`Expected a constructor following 'instanceof' operator (was ${t})`,Tu=(t,e)=>{let n=[{}],r=0;for(;r<t.length;){let i=!1;t[r]==="..."&&r<t.length-1&&(i=!0,r++);const s=Ps(t[r],e),[o,a,c]=F(s)?s:[s];if(r++,i){if(!o.extends(p.intrinsic.Array))return d(Vu(o.expression));n=n.flatMap(l=>o.distribute(u=>Ju($i(l),u)))}else n=n.map(l=>a==="?"?Ls(l,o):a==="="?_u(l,o,c):dn(l,o))}return e.$.parseSchema(n.map(i=>Ye(i)?{proto:Array,exactLength:0}:{proto:Array,sequence:i}))},dn=(t,e)=>t.defaultables||t.optionals?d(t.variadic?rs:Gu):(t.variadic?t.postfix=N(t.postfix,e):t.prefix=N(t.prefix,e),t),Ls=(t,e)=>t.variadic?d(Bs):(t.optionals=N(t.optionals,e),t),_u=(t,e,n)=>t.variadic?d(Bs):t.optionals?d(Wu):(t.defaultables=N(t.defaultables,[[e,n]]),t),xr=(t,e)=>(t.postfix&&d(kr),t.variadic?t.variadic.equals(e)||d(kr):t.variadic=e.internal,t),Ju=(t,e)=>{const n=e.select({method:"find",kind:"sequence"});if(!n)return xr(t,p.intrinsic.unknown);if(n.prefix)for(const r of n.prefix)dn(t,r);if(n.optionals)for(const r of n.optionals)Ls(t,r);if(n.variadic&&xr(t,n.variadic),n.postfix)for(const r of n.postfix)dn(t,r);return t},Vu=t=>`Spread element must be an array (was ${t})`,kr="A tuple may have at most one variadic element",Gu="A required element may not follow an optional element",Bs="An optional element may not follow a variadic element",Wu="A defaultable element may not follow an optional element without a default",Hu={},js=(t,e)=>{if(typeof t=="string"){if(e.args&&Object.keys(e.args).some(r=>t.includes(r)))return br(t,e);const n=Hu[e.$.name]??={};return n[t]??=br(t,e)}return $e(t,"object")?Zu(t,e):d(hn(Q(t)))},Zu=(t,e)=>{const n=bn(t);switch(n){case void 0:return b(t,"root")?t:"~standard"in t?Yu(t,e):Nu(t,e);case"Array":return Qu(t,e);case"RegExp":return e.$.node("intersection",{domain:"string",pattern:t},{prereduced:!0});case"Function":{const r=It(t)?t():t;return b(r,"root")?r:d(hn("Function"))}default:return d(hn(n??S(t)))}},Yu=(t,e)=>e.$.intrinsic.unknown.pipe((n,r)=>{const i=t["~standard"].validate(n);if(!i.issues)return i.value;for(const{message:s,path:o}of i.issues)o?o.length?r.error({problem:Ho(s),relativePath:o.map(a=>typeof a=="object"?a.key:a)}):r.error({message:s}):r.error({message:s})}),Qu=(t,e)=>Pu(t,e)??Tu(t,e),hn=t=>`Type definitions must be strings or objects (was ${t})`;class Xu extends pe{constructor(e){const n=Object.assign({errors:he,hkt:ne,$:e,raw:e.parse,module:e.constructor.module,scope:e.constructor.scope,declare:e.declare,define:e.define,match:e.match,generic:e.generic,schema:e.schema,keywords:e.ambient,unit:e.unit,enumerated:e.enumerated,instanceOf:e.instanceOf,valueOf:e.valueOf,or:e.or,and:e.and,merge:e.merge,pipe:e.pipe,fn:e.fn},e.ambientAttachments);super((...r)=>{if(r.length===1)return e.parse(r[0]);if(r.length===2&&typeof r[0]=="string"&&r[0][0]==="<"&&r[0][r[0].length-1]===">"){const i=r[0].slice(1,-1),s=e.parseGenericParams(i,{});return new vt(s,r[1],e,e,null)}return e.parse(r)},{attach:n})}}const We=p;class qt extends us{get ambientAttachments(){if(We.typeAttachments)return this.cacheGetter("ambientAttachments",O(We.typeAttachments,(e,n)=>[e,this.bindReference(n)]))}preparseOwnAliasEntry(e,n){const r=e.indexOf("<");if(r===-1){if(b(n,"module")||b(n,"generic"))return[e,n];const o=this.name==="ark"?e:e==="root"?this.name:`${this.name}.${e}`,a=this.resolvedConfig.keywords?.[o];return a&&(n=[n,"@",a]),[e,n]}e[e.length-1]!==">"&&d("'>' must be the last character of a generic declaration in a scope");const i=e.slice(0,r),s=e.slice(r+1,-1);return[i,()=>{const o=this.parseGenericParams(s,{alias:i});return za(o,n,this)}]}parseGenericParams(e,n){return un(new pi(e),[],this.createParseContext({...n,def:e,prefix:"generic"}))}normalizeRootScopeValue(e){return It(e)&&!b(e,"generic")?e():e}preparseOwnDefinitionFormat(e,n){return{...n,def:e,prefix:n.alias??"type"}}parseOwnDefinitionFormat(e,n){!(n.alias&&n.alias in this.aliases)&&!n.args&&(n.args={this:n.id});const i=js(e,n);if(F(i)){if(i[1]==="=")return d(As);if(i[1]==="?")return d(ks)}return i}unit=e=>this.units([e]);valueOf=e=>this.units(Do(e));enumerated=(...e)=>this.units(e);instanceOf=e=>this.node("proto",{proto:e},{prereduced:!0});or=(...e)=>this.schema(e.map(n=>this.parse(n)));and=(...e)=>e.reduce((n,r)=>n.and(this.parse(r)),this.intrinsic.unknown);merge=(...e)=>e.reduce((n,r)=>n.merge(this.parse(r)),this.intrinsic.object);pipe=(...e)=>this.intrinsic.unknown.pipe(...e);fn=new $u(this);match=new xu(this);declare=()=>({type:this.type});define(e){return e}type=new Xu(this);static scope=(e,n={})=>new qt(e,n);static module=(e,n={})=>this.scope(e,n).export()}const ed=Object.assign(qt.scope,{define:t=>t}),I=qt;class td extends ne{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}const nd=ce(["base",$.object],["props",$.object])(t=>t.base.merge(t.props),td),rd=I.module({Key:$.key,Merge:nd});class id extends ne{}const sd=ce("element")(t=>{const e=t.element.exclude($.Array),n=e.array();return e.rawOr(n).pipe(Ze).distribute(r=>r.assertHasKind("morph").declareOut(n),R)},id),od=I.module({root:$.Array,readonly:"root",index:$.nonNegativeIntegerString,liftFrom:sd},{name:"Array"}),pn=R(["string",Qe.FileConstructor]),ad=pn.rawOr(pn.array()),Ar=R({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:ad}}),cd=I.module({root:["instanceof",FormData],value:pn,parsed:Ar,parse:R({in:FormData,morphs:t=>{const e={};for(const[n,r]of t)if(n in e){const i=e[n];typeof i=="string"||i instanceof Qe.FileConstructor?e[n]=[i,r]:i.push(r)}else e[n]=r;return e},declaredOut:Ar})},{name:"FormData"}),ld=I.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"}),ud={Boolean:1,Number:1,String:1},dd=I.module({...O({...ni,...ii},(t,e)=>t in ud?[]:[t,["instanceof",e]]),Array:od,TypedArray:ld,FormData:cd}),hd=R({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-864e13,meta:"a Unix timestamp after -8640000000000000"},max:{rule:864e13,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),pd=R({domain:"number",divisor:1}),Fs=I.module({root:$.number,integer:pd,epoch:hd,safe:R({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"}),M=(t,e,n)=>{const r={domain:"string",pattern:{rule:t.source,flags:t.flags,meta:e}};return n&&(r.meta={format:n}),Pn("intersection",r)},Ir=M(gt,"a well-formed integer string"),zs=I.module({root:Ir,parse:R({in:Ir,morphs:(t,e)=>{const n=Number.parseInt(t);return Number.isSafeInteger(n)?n:e.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:$.integer})},{name:"string.integer"}),fd=M(/^[\dA-Fa-f]+$/,"hex characters only"),md=I.module({root:M(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:M(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),Sr=M(/^[A-Z].*$/,"capitalized"),gd=I.module({root:R({in:"string",morphs:t=>t.charAt(0).toUpperCase()+t.slice(1),declaredOut:Sr}),preformatted:Sr},{name:"string.capitalize"}),yd=t=>{const e=t.replace(/[ -]+/g,"");let n=0,r,i,s=!1;for(let o=e.length-1;o>=0;o--)r=e.substring(o,o+1),i=Number.parseInt(r,10),s?(i*=2,n+=i>=10?i%10+1:i):n+=i,s=!s;return!!(n%10===0&&e)},bd=/^(?: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}))$/,$d=R({domain:"string",pattern:{meta:"a credit card number",rule:bd.source},predicate:{meta:"a credit card number",predicate:yd}}),wd=/^([+-]?\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)?)?)?)?$/,vd=t=>!Number.isNaN(new Date(t).valueOf()),Nr=R({domain:"string",predicate:{meta:"a parsable date",predicate:vd}}).assertHasKind("intersection"),Or=zs.root.internal.narrow((t,e)=>{const n=Number.parseInt(t),r=Fs.epoch(n);return r instanceof he?(e.errors.merge(r),!1):!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),xd=I.module({root:Or,parse:R({in:Or,morphs:t=>new Date(t),declaredOut:$.Date})},{name:"string.date.epoch"}),Rr=M(wd,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),kd=I.module({root:Rr,parse:R({in:Rr,morphs:t=>new Date(t),declaredOut:$.Date})},{name:"string.date.iso"}),Ad=I.module({root:Nr,parse:R({declaredIn:Nr,in:"string",morphs:(t,e)=>{const n=new Date(t);return Number.isNaN(n.valueOf())?e.error("a parsable date"):n},declaredOut:$.Date}),iso:kd,epoch:xd},{name:"string.date"}),Id=M(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),Cr="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",le=`(${Cr}[.]){3}${Cr}`,Sd=new RegExp(`^${le}$`),D="(?:[0-9a-fA-F]{1,4})",Nd=new RegExp(`^((?:${D}:){7}(?:${D}|:)|(?:${D}:){6}(?:${le}|:${D}|:)|(?:${D}:){5}(?::${le}|(:${D}){1,2}|:)|(?:${D}:){4}(?:(:${D}){0,1}:${le}|(:${D}){1,3}|:)|(?:${D}:){3}(?:(:${D}){0,2}:${le}|(:${D}){1,4}|:)|(?:${D}:){2}(?:(:${D}){0,3}:${le}|(:${D}){1,5}|:)|(?:${D}:){1}(?:(:${D}){0,4}:${le}|(:${D}){1,6}|:)|(?::((?::${D}){0,5}:${le}|(?::${D}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),Od=I.module({root:["v4 | v6","@","an IP address"],v4:M(Sd,"an IPv4 address","ipv4"),v6:M(Nd,"an IPv6 address","ipv6")},{name:"string.ip"}),Re="a JSON string",Us=t=>{if(!(t instanceof SyntaxError))throw t;return`must be ${Re} (${t})`},Rd=R({meta:Re,domain:"string",predicate:{meta:Re,predicate:(t,e)=>{try{return JSON.parse(t),!0}catch(n){return e.reject({code:"predicate",expected:Re,problem:Us(n)})}}}}),Cd=(t,e)=>{if(t.length===0)return e.error({code:"predicate",expected:Re,actual:"empty"});try{return JSON.parse(t)}catch(n){return e.error({code:"predicate",expected:Re,problem:Us(n)})}},Md=I.module({root:Rd,parse:R({meta:"safe JSON string parser",in:"string",morphs:Cd,declaredOut:$.jsonObject})},{name:"string.json"}),Mr=M(/^[a-z]*$/,"only lowercase letters"),Pd=I.module({root:R({in:"string",morphs:t=>t.toLowerCase(),declaredOut:Mr}),preformatted:Mr},{name:"string.lower"}),Ts=["NFC","NFD","NFKC","NFKD"],it=O(Ts,(t,e)=>[e,R({domain:"string",predicate:n=>n.normalize(e)===n,meta:`${e}-normalized unicode`})]),Et=O(Ts,(t,e)=>[e,R({in:"string",morphs:n=>n.normalize(e),declaredOut:it[e]})]),qd=I.module({root:Et.NFC,preformatted:it.NFC},{name:"string.normalize.NFC"}),Ed=I.module({root:Et.NFD,preformatted:it.NFD},{name:"string.normalize.NFD"}),Dd=I.module({root:Et.NFKC,preformatted:it.NFKC},{name:"string.normalize.NFKC"}),Kd=I.module({root:Et.NFKD,preformatted:it.NFKD},{name:"string.normalize.NFKD"}),Ld=I.module({root:"NFC",NFC:qd,NFD:Ed,NFKC:Dd,NFKD:Kd},{name:"string.normalize"}),Pr=M(Zt,"a well-formed numeric string"),Bd=I.module({root:Pr,parse:R({in:Pr,morphs:t=>Number.parseFloat(t),declaredOut:$.number})},{name:"string.numeric"}),qr="a regex pattern",jd=R({domain:"string",predicate:{meta:qr,predicate:(t,e)=>{try{return new RegExp(t),!0}catch(n){return e.reject({code:"predicate",expected:qr,problem:String(n)})}}},meta:{format:"regex"}}),Fd=/^(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-]+)*))?$/,zd=M(Fd,"a semantic version (see https://semver.org/)"),Er=M(/^\S.*\S$|^\S?$/,"trimmed"),Ud=I.module({root:R({in:"string",morphs:t=>t.trim(),declaredOut:Er}),preformatted:Er},{name:"string.trim"}),Dr=M(/^[A-Z]*$/,"only uppercase letters"),Td=I.module({root:R({in:"string",morphs:t=>t.toUpperCase(),declaredOut:Dr}),preformatted:Dr},{name:"string.upper"}),_d=t=>URL.canParse(t),Kr=R({domain:"string",predicate:{meta:"a URL string",predicate:_d},meta:{format:"uri"}}),Jd=I.module({root:Kr,parse:R({declaredIn:Kr,in:"string",morphs:(t,e)=>{try{return new URL(t)}catch{return e.error("a URL string")}},declaredOut:R(URL)})},{name:"string.url"}),Vd=I.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:M(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:M(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:M(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:M(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:M(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:M(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:M(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:M(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),Gd=I.module({root:$.string,alpha:M(/^[A-Za-z]*$/,"only letters"),alphanumeric:M(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:fd,base64:md,capitalize:gd,creditCard:$d,date:Ad,digits:M(/^\d*$/,"only digits 0-9"),email:Id,integer:zs,ip:Od,json:Md,lower:Pd,normalize:Ld,numeric:Bd,regex:jd,semver:zd,trim:Ud,upper:Td,url:Jd,uuid:Vd},{name:"string"}),Wd=I.module({bigint:$.bigint,boolean:$.boolean,false:$.false,never:$.never,null:$.null,number:$.number,object:$.object,string:$.string,symbol:$.symbol,true:$.true,unknown:$.unknown,undefined:$.undefined}),Hd=I.module({root:$.unknown,any:$.unknown},{name:"unknown"}),Zd=I.module({root:$.jsonObject,stringify:Pn("morph",{in:$.jsonObject,morphs:t=>JSON.stringify(t),declaredOut:$.string})},{name:"object.json"}),Yd=I.module({root:$.object,json:Zd},{name:"object"});class Qd extends ne{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}const Xd=ce(["K",$.key],"V")(t=>({domain:"object",index:{signature:t.K,value:t.V}}),Qd);class eh extends ne{description='pick a set of properties from an object like `Pick(User, "name | age")`'}const th=ce(["T",$.object],["K",$.key])(t=>t.T.pick(t.K),eh);class nh extends ne{description='omit a set of properties from an object like `Omit(User, "age")`'}const rh=ce(["T",$.object],["K",$.key])(t=>t.T.omit(t.K),nh);class ih extends ne{description="make all named properties of an object optional like `Partial(User)`"}const sh=ce(["T",$.object])(t=>t.T.partial(),ih);class oh extends ne{description="make all named properties of an object required like `Required(User)`"}const ah=ce(["T",$.object])(t=>t.T.required(),oh);class ch extends ne{description='exclude branches of a union like `Exclude("boolean", "true")`'}const lh=ce("T","U")(t=>t.T.exclude(t.U),ch);class uh extends ne{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}const dh=ce("T","U")(t=>t.T.extract(t.U),uh),hh=I.module({Exclude:lh,Extract:dh,Omit:rh,Partial:sh,Pick:th,Record:Xd,Required:ah}),fe=ed({...Wd,...hh,...dd,...rd,string:Gd,number:Fs,object:Yd,unknown:Hd},{prereducedAliases:!0,name:"ark"}),B=fe.export();Object.assign(We.ambient,B);We.typeAttachments={string:B.string.root,number:B.number.root,bigint:B.bigint,boolean:B.boolean,symbol:B.symbol,undefined:B.undefined,null:B.null,object:B.object.root,unknown:B.unknown.root,false:B.false,true:B.true,never:B.never,arrayIndex:B.Array.index,Key:B.Key,Record:B.Record,Array:B.Array.root,Date:B.Date};const _s=Object.assign(fe.type,We.typeAttachments);fe.match;fe.fn;fe.generic;fe.schema;fe.define;fe.declare;const ph="/api/plugin/content-loading-plugin",Js=ph,Vs=vo(import.meta.url);async function fh(t){const e=`${Js}${t}`,n=await fetch(e);if(n.status!==200)throw new Error(`api error ${n.status}`);return await n.text()}function fn(t){const e=document.createElement("div");return e.innerHTML=t,[...e.children]}const Gs=t=>t!=null&&(t=Object.getPrototypeOf(t),t===Array.prototype||t===Object.prototype);function Ws(t,e,n){for(const[r,i]of Object.entries(e)){const s=`${n}.${r}`;t[s]=i,Gs(i)&&Ws(t,i,s)}}function mh(t){const e={...t};for(const[n,r]of Object.entries(t))Gs(r)&&Ws(e,r,n);return e}const gh=(t,e)=>{if(e)for(const[n,r]of Object.entries(e))t=t.replace(new RegExp(`{{\\s*${n}\\s*}}`,"g"),r);return t},yh=t=>t;function bh(t,e=yh){return(n,...r)=>{n[0]==="."&&(n=n.slice(1));const i=t()?.[n];switch(typeof i){case"function":return i(...r);case"string":return e(i,r[0]);default:return i}}}const $h={magnifierTitle:"Auf der Website suchen…",nothingMessage:"Keine Ergebnisse gefunden für",search:"Suchen"},wh={loadMore:"Mehr laden"},vh={searchApp:$h,infiniteLoading:wh},xh={magnifierTitle:"Search in the site…",nothingMessage:"No results found for",search:"Search"},kh={loadMore:"Load more"},Ah={searchApp:xh,infiniteLoading:kh},Ih={magnifierTitle:"Buscar en el sitio…",nothingMessage:"No se encontraron resultados para",search:"Buscar"},Sh={loadMore:"Cargar más"},Nh={searchApp:Ih,infiniteLoading:Sh},Oh={magnifierTitle:"Rechercher dans le site…",nothingMessage:"Aucun résultat trouvé pour",search:"Rechercher"},Rh={loadMore:"Charger la suite"},Ch={searchApp:Oh,infiniteLoading:Rh},Mh={magnifierTitle:"Cerca nel sito…",nothingMessage:"Nessun risultato trovato per",search:"Cerca"},Ph={loadMore:"Carica altro"},qh={searchApp:Mh,infiniteLoading:Ph},Eh={magnifierTitle:"Pesquisar no site…",nothingMessage:"Nenhum resultado encontrado para",search:"Pesquisar"},Dh={loadMore:"Carregar mais"},Kh={searchApp:Eh,infiniteLoading:Dh},Lr={en:Ah,fr:Ch,es:Nh,de:vh,it:qh,pt:Kh};function st(t){const e=Z(()=>{const r=t in Lr?t:"en";return mh(Lr[r])});return{t:bh(e,gh)}}var Lh=V('<button class="PaInfiniteLoading-loadButton PaButton"type=button>'),Bh=V("<div class=PaInfiniteLoading-loadMore>"),jh=V('<img class="PaInfiniteLoading-loading PaLoading"width=50 height=50 alt=…>');const Fh=_s({"offset?":"string|undefined","total?":"string|undefined","limit?":"string|undefined","parentDocumentId?":"string|undefined","template?":"string|undefined","labeledWith?":"string|undefined","termNodeId?":"string|undefined","sorting?":"string|undefined","+":"ignore"}).pipe(t=>({offset:X(t.offset)?Number(t.offset):void 0,total:X(t.total)?Number(t.total):void 0,limit:X(t.limit)?Number(t.limit):void 0,parentDocumentId:X(t.parentDocumentId)?t.parentDocumentId:void 0,templateName:X(t.template)?t.template:void 0,termNodeId:X(t.termNodeId)?t.termNodeId:void 0,labeledWith:X(t.labeledWith)?t.labeledWith:void 0,sorting:X(t.sorting)?t.sorting:void 0}));function zh(t,{language:e}){const{templateName:n,offset:r,total:i,limit:s,parentDocumentId:o,sorting:a,termNodeId:c,labeledWith:l}=Fh.assert(t.dataset);if(!(r===void 0||i===void 0||o===void 0||s===void 0||n===void 0)){if(!e)throw new Error("Missing language");Uh({language:e,limit:s,parentDocumentId:o,root:t,offset:r,total:i,sorting:a,labeledWith:c!==void 0&&l?{termNodeId:c,fieldName:l}:void 0,templateName:n})}}function Uh({language:t,limit:e,root:n,offset:r,total:i,parentDocumentId:s,sorting:o,templateName:a,labeledWith:c}){const{t:l}=st(t);let u=r;if(u>=i)return;const h=(()=>{var f=Lh();return f.$$click=v,_(f,()=>l("infiniteLoading.loadMore")),f})(),m=(()=>{var f=Bh();return _(f,h),f})(),y=(()=>{var f=jh();return At(f,"src",`${Vs}/spinner.svg`),f})();n.appendChild(m);async function v(){n.appendChild(y);const f=await Th({limit:e,newOffset:u,parentDocumentId:s,sorting:o,labeledWith:c,templateName:a});for(const w of f)n.insertBefore(w,m);u+=e,u>=i&&m.remove(),y.remove()}}async function Th({limit:t,newOffset:e,parentDocumentId:n,labeledWith:r,sorting:i,templateName:s}){const o=[["template",s],["children-of",n],["offset",e],["limit",t]];i&&o.push(["sorting",i]),r&&(o.push(["labeled-t",r.termNodeId]),o.push(["labeled-f",r.fieldName]));const a=`/partials?${o.map(([l,u])=>`${l}=${encodeURIComponent(u)}`).join("&")}`,c=await fh(a);return fn(c)}gn(["click"]);function Hs(){let t=new Set;function e(i){return t.add(i),()=>t.delete(i)}let n=!1;function r(i,s){if(n)return!(n=!1);const o={to:i,options:s,defaultPrevented:!1,preventDefault:()=>o.defaultPrevented=!0};for(const a of t)a.listener({...o,from:a.location,retry:c=>{c&&(n=!0),a.navigate(i,{...s,resolve:!1})}});return!o.defaultPrevented}return{subscribe:e,confirm:r}}let mn;function Dn(){(!window.history.state||window.history.state._depth==null)&&window.history.replaceState({...window.history.state,_depth:window.history.length-1},""),mn=window.history.state._depth}Ue||Dn();function _h(t){return{...t,_depth:window.history.state&&window.history.state._depth}}function Jh(t,e){let n=!1;return()=>{const r=mn;Dn();const i=r==null?null:mn-r;if(n){n=!1;return}i&&e(i)?(n=!0,window.history.go(-i)):t()}}const Vh=/^(?:[a-z0-9]+:)?\/\//i,Gh=/^\/+|(\/)\/+$/g,Zs="http://sr";function Je(t,e=!1){const n=t.replace(Gh,"$1");return n?e||/^[?#]/.test(n)?n:"/"+n:""}function pt(t,e,n){if(Vh.test(e))return;const r=Je(t),i=n&&Je(n);let s="";return!i||e.startsWith("/")?s=r:i.toLowerCase().indexOf(r.toLowerCase())!==0?s=r+i:s=i,(s||"/")+Je(e,!s)}function Wh(t,e){if(t==null)throw new Error(e);return t}function Hh(t,e){return Je(t).replace(/\/*(\*.*)?$/g,"")+Je(e)}function Ys(t){const e={};return t.searchParams.forEach((n,r)=>{r in e?Array.isArray(e[r])?e[r].push(n):e[r]=[e[r],n]:e[r]=n}),e}function Zh(t,e,n){const[r,i]=t.split("/*",2),s=r.split("/").filter(Boolean),o=s.length;return a=>{const c=a.split("/").filter(Boolean),l=c.length-o;if(l<0||l>0&&i===void 0&&!e)return null;const u={path:o?"":"/",params:{}},h=m=>n===void 0?void 0:n[m];for(let m=0;m<o;m++){const y=s[m],v=y[0]===":",f=v?c[m]:c[m].toLowerCase(),w=v?y.slice(1):y.toLowerCase();if(v&&Jt(f,h(w)))u.params[w]=f;else if(v||!Jt(f,w))return null;u.path+=`/${f}`}if(i){const m=l?c.slice(-l).join("/"):"";if(Jt(m,h(i)))u.params[i]=m;else return null}return u}}function Jt(t,e){const n=r=>r===t;return e===void 0?!0:typeof e=="string"?n(e):typeof e=="function"?e(t):Array.isArray(e)?e.some(n):e instanceof RegExp?e.test(t):!1}function Yh(t){const[e,n]=t.pattern.split("/*",2),r=e.split("/").filter(Boolean);return r.reduce((i,s)=>i+(s.startsWith(":")?2:3),r.length-(n===void 0?0:1))}function Qs(t){const e=new Map,n=Tr();return new Proxy({},{get(r,i){return e.has(i)||_r(n,()=>e.set(i,Z(()=>t()[i]))),e.get(i)()},getOwnPropertyDescriptor(){return{enumerable:!0,configurable:!0}},ownKeys(){return Reflect.ownKeys(t())},has(r,i){return i in t()}})}function Xs(t){let e=/(\/?\:[^\/]+)\?/.exec(t);if(!e)return[t];let n=t.slice(0,e.index),r=t.slice(e.index+e[0].length);const i=[n,n+=e[1]];for(;e=/^(\/\:[^\/]+)\?/.exec(r);)i.push(n+=e[1]),r=r.slice(e[0].length);return Xs(r).reduce((s,o)=>[...s,...i.map(a=>a+o)],[])}const Qh=100,eo=Vr(),to=Vr(),Kn=()=>Wh(Jr(eo),"<A> and 'use' router primitives can be only used inside a Route."),no=()=>Kn().navigatorFactory(),Xh=()=>Kn().location,ep=()=>Kn().params;function tp(t,e=""){const{component:n,preload:r,load:i,children:s,info:o}=t,a=!s||Array.isArray(s)&&!s.length,c={key:t,component:n,preload:r||i,info:o};return ro(t.path).reduce((l,u)=>{for(const h of Xs(u)){const m=Hh(e,h);let y=a?m:m.split("/*",1)[0];y=y.split("/").map(v=>v.startsWith(":")||v.startsWith("*")?v:encodeURIComponent(v)).join("/"),l.push({...c,originalPath:u,pattern:y,matcher:Zh(y,!a,t.matchFilters)})}return l},[])}function np(t,e=0){return{routes:t,score:Yh(t[t.length-1])*1e4-e,matcher(n){const r=[];for(let i=t.length-1;i>=0;i--){const s=t[i],o=s.matcher(n);if(!o)return null;r.unshift({...o,route:s})}return r}}}function ro(t){return Array.isArray(t)?t:[t]}function io(t,e="",n=[],r=[]){const i=ro(t);for(let s=0,o=i.length;s<o;s++){const a=i[s];if(a&&typeof a=="object"){a.hasOwnProperty("path")||(a.path="");const c=tp(a,e);for(const l of c){n.push(l);const u=Array.isArray(a.children)&&a.children.length===0;if(a.children&&!u)io(a.children,l.pattern,n,r);else{const h=np([...n],r.length);r.push(h)}n.pop()}}}return n.length?r:r.sort((s,o)=>o.score-s.score)}function Ve(t,e){for(let n=0,r=t.length;n<r;n++){const i=t[n].matcher(e);if(i)return i}return[]}function rp(t,e,n){const r=new URL(Zs),i=Z(u=>{const h=t();try{return new URL(h,r)}catch{return console.error(`Invalid path ${h}`),u}},r,{equals:(u,h)=>u.href===h.href}),s=Z(()=>i().pathname),o=Z(()=>i().search,!0),a=Z(()=>i().hash),c=()=>"",l=He(o,()=>Ys(i()));return{get pathname(){return s()},get search(){return o()},get hash(){return a()},get state(){return e()},get key(){return c()},query:n?n(l):Qs(l)}}let me;function ip(){return me}function sp(t,e,n,r={}){const{signal:[i,s],utils:o={}}=t,a=o.parsePath||(k=>k),c=o.renderPath||(k=>k),l=o.beforeLeave||Hs(),u=pt("",r.base||"");if(u===void 0)throw new Error(`${u} is not a valid base path`);u&&!i().value&&s({value:u,replace:!0,scroll:!1});const[h,m]=Y(!1);let y;const v=(k,C)=>{C.value===f()&&C.state===x()||(y===void 0&&m(!0),me=k,y=C,fo(()=>{y===C&&(w(y.value),A(y.state),mo(),Ue||H[1](J=>J.filter(we=>we.pending)))}).finally(()=>{y===C&&go(()=>{me=void 0,k==="navigate"&&co(y),m(!1),y=void 0})}))},[f,w]=Y(i().value),[x,A]=Y(i().state),P=rp(f,x,o.queryWrapper),G=[],H=Y(Ue?uo():[]),je=Z(()=>typeof r.transformUrl=="function"?Ve(e(),r.transformUrl(P.pathname)):Ve(e(),P.pathname)),Ln=()=>{const k=je(),C={};for(let J=0;J<k.length;J++)Object.assign(C,k[J].params);return C},so=o.paramsWrapper?o.paramsWrapper(Ln,e):Qs(Ln),Bn={pattern:u,path:()=>u,outlet:()=>null,resolvePath(k){return pt(u,k)}};return po(He(i,k=>v("native",k),{defer:!0})),{base:Bn,location:P,params:so,isRouting:h,renderPath:c,parsePath:a,navigatorFactory:ao,matches:je,beforeLeave:l,preloadRoute:lo,singleFlight:r.singleFlight===void 0?!0:r.singleFlight,submissions:H};function oo(k,C,J){Gr(()=>{if(typeof C=="number"){C&&(o.go?o.go(C):console.warn("Router integration does not support relative routing"));return}const we=!C||C[0]==="?",{replace:ot,resolve:ve,scroll:at,state:xe}={replace:!1,resolve:!we,scroll:!0,...J},ke=ve?k.resolvePath(C):pt(we&&P.pathname||"",C);if(ke===void 0)throw new Error(`Path '${C}' is not a routable path`);if(G.length>=Qh)throw new Error("Too many redirects");const jn=f();if(ke!==jn||xe!==x())if(Ue){const Fn=Gt();Fn&&(Fn.response={status:302,headers:new Headers({Location:ke})}),s({value:ke,replace:ot,scroll:at,state:xe})}else l.confirm(ke,J)&&(G.push({value:jn,replace:ot,scroll:at,state:x()}),v("navigate",{value:ke,state:xe}))})}function ao(k){return k=k||Jr(to)||Bn,(C,J)=>oo(k,C,J)}function co(k){const C=G[0];C&&(s({...k,replace:C.replace,scroll:C.scroll}),G.length=0)}function lo(k,C){const J=Ve(e(),k.pathname),we=me;me="preload";for(let ot in J){const{route:ve,params:at}=J[ot];ve.component&&ve.component.preload&&ve.component.preload();const{preload:xe}=ve;C&&xe&&_r(n(),()=>xe({params:at,location:{pathname:k.pathname,search:k.search,hash:k.hash,query:Ys(k),state:null,key:""},intent:"preload"}))}me=we}function uo(){const k=Gt();return k&&k.router&&k.router.submission?[k.router.submission]:[]}}function op(t,e,n,r){const{base:i,location:s,params:o}=t,{pattern:a,component:c,preload:l}=r().route,u=Z(()=>r().path);c&&c.preload&&c.preload();const h=l?l({params:o,location:s,intent:me||"initial"}):void 0;return{parent:e,pattern:a,path:u,outlet:()=>c?yo(c,{params:o,location:s,data:h,get children(){return n()}}):n(),resolvePath(y){return pt(i.path(),y,u())}}}const ap=t=>e=>{const{base:n}=e,r=Wr(()=>e.children),i=Z(()=>io(r(),e.base||""));let s;const o=sp(t,i,()=>s,{base:n,singleFlight:e.singleFlight,transformUrl:e.transformUrl});return t.create&&t.create(o),E(eo.Provider,{value:o,get children(){return E(cp,{routerState:o,get root(){return e.root},get preload(){return e.rootPreload||e.rootLoad},get children(){return[Wt(()=>(s=Tr())&&null),E(lp,{routerState:o,get branches(){return i()}})]}})}})};function cp(t){const e=t.routerState.location,n=t.routerState.params,r=Z(()=>t.preload&&Gr(()=>{t.preload({params:n,location:e,intent:ip()||"initial"})}));return E(Se,{get when(){return t.root},keyed:!0,get fallback(){return t.children},children:i=>E(i,{params:n,location:e,get data(){return r()},get children(){return t.children}})})}function lp(t){if(Ue){const i=Gt();if(i&&i.router&&i.router.dataOnly){up(i,t.routerState,t.branches);return}i&&((i.router||(i.router={})).matches||(i.router.matches=t.routerState.matches().map(({route:s,path:o,params:a})=>({path:s.originalPath,pattern:s.pattern,match:o,params:a,info:s.info}))))}const e=[];let n;const r=Z(He(t.routerState.matches,(i,s,o)=>{let a=s&&i.length===s.length;const c=[];for(let l=0,u=i.length;l<u;l++){const h=s&&s[l],m=i[l];o&&h&&m.route.key===h.route.key?c[l]=o[l]:(a=!1,e[l]&&e[l](),$o(y=>{e[l]=y,c[l]=op(t.routerState,c[l-1]||t.routerState.base,Br(()=>r()[l+1]),()=>{const v=t.routerState.matches();return v[l]??v[0]})}))}return e.splice(i.length).forEach(l=>l()),o&&a?o:(n=c[0],c)}));return Br(()=>r()&&n)()}const Br=t=>()=>E(Se,{get when(){return t()},keyed:!0,children:e=>E(to.Provider,{value:e,get children(){return e.outlet()}})}),Vt=t=>{const e=Wr(()=>t.children);return bo(t,{get children(){return e()}})};function up(t,e,n){const r=new URL(t.request.url),i=Ve(n,new URL(t.router.previousUrl||t.request.url).pathname),s=Ve(n,r.pathname);for(let o=0;o<s.length;o++){(!i[o]||s[o].route!==i[o].route)&&(t.router.dataOnly=!0);const{route:a,params:c}=s[o];a.preload&&a.preload({params:c,location:e.location,intent:"preload"})}}function dp([t,e],n,r){return[t,r?i=>e(r(i)):e]}function hp(t){let e=!1;const n=i=>typeof i=="string"?{value:i}:i,r=dp(Y(n(t.get()),{equals:(i,s)=>i.value===s.value&&i.state===s.state}),void 0,i=>(!e&&t.set(i),Dt.registry&&!Dt.done&&(Dt.done=!0),i));return t.init&&Hr(t.init((i=t.get())=>{e=!0,r[1](n(i)),e=!1})),ap({signal:r,create:t.create,utils:t.utils})}function pp(t,e,n){return t.addEventListener(e,n),()=>t.removeEventListener(e,n)}function fp(t,e){const n=t&&document.getElementById(t);n?n.scrollIntoView():e&&window.scrollTo(0,0)}const mp=new Map;function gp(t=!0,e=!1,n="/_server",r){return i=>{const s=i.base.path(),o=i.navigatorFactory(i.base);let a,c;function l(f){return f.namespaceURI==="http://www.w3.org/2000/svg"}function u(f){if(f.defaultPrevented||f.button!==0||f.metaKey||f.altKey||f.ctrlKey||f.shiftKey)return;const w=f.composedPath().find(je=>je instanceof Node&&je.nodeName.toUpperCase()==="A");if(!w||e&&!w.hasAttribute("link"))return;const x=l(w),A=x?w.href.baseVal:w.href;if((x?w.target.baseVal:w.target)||!A&&!w.hasAttribute("state"))return;const G=(w.getAttribute("rel")||"").split(/\s+/);if(w.hasAttribute("download")||G&&G.includes("external"))return;const H=x?new URL(A,document.baseURI):new URL(A);if(!(H.origin!==window.location.origin||s&&H.pathname&&!H.pathname.toLowerCase().startsWith(s.toLowerCase())))return[w,H]}function h(f){const w=u(f);if(!w)return;const[x,A]=w,P=i.parsePath(A.pathname+A.search+A.hash),G=x.getAttribute("state");f.preventDefault(),o(P,{resolve:!1,replace:x.hasAttribute("replace"),scroll:!x.hasAttribute("noscroll"),state:G?JSON.parse(G):void 0})}function m(f){const w=u(f);if(!w)return;const[x,A]=w;i.preloadRoute(A,x.getAttribute("preload")!=="false")}function y(f){clearTimeout(a);const w=u(f);if(!w)return c=null;const[x,A]=w;c!==x&&(a=setTimeout(()=>{i.preloadRoute(A,x.getAttribute("preload")!=="false"),c=x},20))}function v(f){if(f.defaultPrevented)return;let w=f.submitter&&f.submitter.hasAttribute("formaction")?f.submitter.getAttribute("formaction"):f.target.getAttribute("action");if(!w)return;if(!w.startsWith("https://action/")){const A=new URL(w,Zs);if(w=i.parsePath(A.pathname+A.search),!w.startsWith(n))return}if(f.target.method.toUpperCase()!=="POST")throw new Error("Only POST forms are supported for Actions");const x=mp.get(w);if(x){f.preventDefault();const A=new FormData(f.target,f.submitter);x.call({r:i,f:f.target},f.target.enctype==="multipart/form-data"?A:new URLSearchParams(A))}}gn(["click","submit"]),document.addEventListener("click",h),t&&(document.addEventListener("mousemove",y,{passive:!0}),document.addEventListener("focusin",m,{passive:!0}),document.addEventListener("touchstart",m,{passive:!0})),document.addEventListener("submit",v),Hr(()=>{document.removeEventListener("click",h),t&&(document.removeEventListener("mousemove",y),document.removeEventListener("focusin",m),document.removeEventListener("touchstart",m)),document.removeEventListener("submit",v)})}}function yp(t){const e=t.replace(/^.*?#/,"");if(!e.startsWith("/")){const[,n="/"]=window.location.hash.split("#",2);return`${n}#${e}`}return e}function bp(t){const e=()=>window.location.hash.slice(1),n=Hs();return hp({get:e,set({value:r,replace:i,scroll:s,state:o}){i?window.history.replaceState(_h(o),"","#"+r):window.history.pushState(o,"","#"+r);const a=r.indexOf("#"),c=a>=0?r.slice(a+1):"";fp(c,s),Dn()},init:r=>pp(window,"hashchange",Jh(r,i=>!n.confirm(i&&i<0?i:e()))),create:gp(t.preload,t.explicitLinks,t.actionBase),utils:{go:r=>window.history.go(r),renderPath:r=>`#${r}`,parsePath:yp,beforeLeave:n}})(t)}function $p(t){const e=no(),n=Xh(),{href:r,state:i}=t,s=typeof r=="function"?r({navigate:e,location:n}):r;return e(s,{replace:!0,state:i}),null}async function jr({language:t,text:e,limit:n,offset:r,templateName:i}){const s=`${Js}/search?language=${encodeURIComponent(t)}&q=${encodeURIComponent(e)}&limit=${encodeURIComponent(n)}&offset=${encodeURIComponent(r)}&tpl=${encodeURIComponent(i)}`,o=await fetch(s,{method:"GET"});if(o.status!==200){const c=await o.text();throw new Error(`API error (${o.status}): ${c}`)}return await o.json()}var wp=V('<form class=PaSearchApp-form><input class="PaSearchApp-input PaInput"type=search><button class="PaSearchApp-searchButton PaButton"type=submit>');function vp(t){const e=no(),[n,r]=Y(t.value??""),{t:i}=st(t.language);Zr(He(()=>t.value,()=>r(t.value??"")));const s=async o=>{o.preventDefault(),e(`/q/${encodeURIComponent(n())}`)};return(()=>{var o=wp(),a=o.firstChild,c=a.nextSibling;return o.addEventListener("submit",s),a.addEventListener("change",l=>r(l.currentTarget.value)),_(c,()=>i("searchApp.search")),ft(()=>At(a,"placeholder",i("searchApp.search"))),ft(()=>a.value=n()),o})()}var xp=V("<div class=PaSearchApp-loadMore>"),kp=V("<div class=PaSearchApp-results>"),Ap=V("<div class=PaSearchApp>"),Ip=V("<div class=PaSearchApp-nothing> <span class=PaSearchApp-quote>"),Sp=V('<img class="PaSearchApp-loading PaLoading"width=80 height=80 alt=…>'),Np=V('<button class="PaSearchApp-loadButton PaButton"type=button>');function Fr({language:t,limit:e,templateName:n}){const{t:r}=st(t),i=ep(),[s,o]=Y([]),[a,c]=Y(-1),[l,u]=Y(0),[h,m]=Y(!1);Zr(He(()=>i.searchString,y));async function y(){if(i.searchString){m(!0);try{o([]),u(0),c(-1);const f=await jr({language:t,text:decodeURIComponent(i.searchString),limit:e,offset:l(),templateName:n});if(c(f.total),u(l()+e),!f.html)return;o(fn(f.html))}finally{m(!1)}}}async function v(){if(!i.searchString)return;const f=a();if(!(f===-1||l()>=f)){m(!0);try{const w=await jr({language:t,text:decodeURIComponent(i.searchString),limit:e,offset:l(),templateName:n});if(!w.html)return;o([...s(),...fn(w.html)]),u(l()+e)}finally{m(!1)}}}return(()=>{var f=Ap();return _(f,E(vp,{language:t,get value(){return Wt(()=>!!i.searchString)()?decodeURIComponent(i.searchString):void 0}}),null),_(f,E(Se,{get when(){return i.searchString},get children(){var w=kp();return _(w,E(Se,{get when(){return a()!==-1},get children(){return E(Se,{get when(){return s().length>0},get fallback(){return(()=>{var x=Ip(),A=x.firstChild,P=A.nextSibling;return _(x,()=>r("searchApp.nothingMessage"),A),_(P,()=>i.searchString),x})()},get children(){return s()}})}}),null),_(w,E(Se,{get when(){return a()===-1||h()||l()<a()},get children(){var x=xp();return _(x,(()=>{var A=Wt(()=>!!h());return()=>A()?(()=>{var P=Sp();return At(P,"src",`${Vs}/spinner.svg`),P})():(()=>{var P=Np();return P.$$click=v,_(P,()=>r("infiniteLoading.loadMore")),P})()})()),x}}),null),w}}),null),f})()}gn(["click"]);const Op=_s({"limit?":"string|undefined","template?":"string|undefined","+":"ignore"}).pipe(t=>({limit:X(t.limit)?Number(t.limit):void 0,templateName:X(t.template)?t.template:void 0}));function Rp(t,{language:e}){if(!e)throw new Error("Missing language");const{limit:n,templateName:r}=Op.assert(t.dataset);n===void 0||r===void 0||Ur(()=>E(bp,{explicitLinks:!0,get children(){return[E(Vt,{path:"/",component:()=>E($p,{href:"/q"})}),E(Vt,{path:"/q",component:()=>E(Fr,{language:e,templateName:r,limit:n})}),E(Vt,{path:"/q/:searchString",component:()=>E(Fr,{language:e,templateName:r,limit:n})})]}}),t)}var Cp=V('<input class="PaSearchOpener-input PaInput"type=search required>'),Mp=V('<form class=PaSearchOpener><button class="PaSearchOpener-button PaButton"type=submit>');function Pp({searchURL:t,language:e}){const[n,r]=Y(""),{t:i}=st(e),s=(()=>{var a=Cp();return a.addEventListener("change",c=>r(c.currentTarget.value)),ft(()=>At(a,"placeholder",i("searchApp.search"))),ft(()=>a.value=n()),a})(),o=a=>{a.preventDefault(),window.location.href=`${t}#/q/${encodeURIComponent(n())}`};return(()=>{var a=Mp(),c=a.firstChild;return a.addEventListener("submit",o),_(a,s,c),_(c,()=>i("searchApp.search")),a})()}var qp=V('<button class=PaSearchOpenerButton type=button><svg class=PaSearchOpenerButton-svg width=20 height=20 xmlns=http://www.w3.org/2000/svg viewBox="0 0 490.4 490.4"><title></title><g id=SVGRepo_bgCarrier stroke-width=0></g><g id=SVGRepo_tracerCarrier stroke-linecap=round stroke-linejoin=round></g><g id=SVGRepo_iconCarrier><g><path d="M484.1,454.796l-110.5-110.6c29.8-36.3,47.6-82.8,47.6-133.4c0-116.3-94.3-210.6-210.6-210.6S0,94.496,0,210.796 s94.3,210.6,210.6,210.6c50.8,0,97.4-18,133.8-48l110.5,110.5c12.9,11.8,25,4.2,29.2,0C492.5,475.596,492.5,463.096,484.1,454.796z M41.1,210.796c0-93.6,75.9-169.5,169.5-169.5s169.6,75.9,169.6,169.5s-75.9,169.5-169.5,169.5S41.1,304.396,41.1,210.796z"></path> ');function Ep({searchIconColor:t,language:e,searchURL:n}){const{t:r}=st(e),i=(()=>{var a=qp(),c=a.firstChild,l=c.firstChild;return ho(c,"fill",t),_(l,()=>r("searchApp.magnifierTitle")),a})(),s=E(Pp,{searchURL:n,language:e});return wo({openButton:i,dialogContent:s,modalClass:"_paSearchOpener",loadCss:!0}).on("open",()=>{s.querySelector("input")?.focus()}),i}function Dp(t,{language:e}){const n=t.dataset.searchUrl,r=t.dataset.iconColor;if(!e)throw new Error("Missing language");if(!n)throw new Error("Missing search url");Ur(()=>E(Ep,{language:e,searchURL:n,searchIconColor:r}),t)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",zr):zr();function zr(){const t=document.documentElement.lang,e={paSearchOpener:Dp,paSearchApp:Rp,paInfiniteLoading:zh},n=document.querySelectorAll("[data-effect]");for(const r of n){const i=r.dataset.effect;if(!i)continue;const s=e[i];s&&s(r,{language:t})}}
|
|
1
|
+
import{createComponent as e,delegateEvents as t,effect as n,getRequestEvent as r,insert as i,isServer as a,memo as o,render as s,setAttribute as c,setStyleProperty as l,template as u}from"https://cdn.jsdelivr.net/npm/solid-js@1.9.12/web/+esm";import{Show as d,batch as f,children as p,createComponent as m,createContext as h,createEffect as g,createMemo as _,createRenderEffect as ee,createRoot as te,createSignal as v,getOwner as ne,mergeProps as re,on as ie,onCleanup as ae,resetErrorBoundaries as oe,runWithOwner as se,sharedConfig as ce,startTransition as le,untrack as ue,useContext as de}from"https://cdn.jsdelivr.net/npm/solid-js@1.9.12/+esm";import fe from"https://cdn.jsdelivr.net/npm/@paroicms/tiny-modal@0.8.4/+esm";function pe(e){let t=e,n=t.indexOf("?");n!==-1&&(t=t.substring(0,n));let r=t.indexOf("#");r!==-1&&(t=t.substring(0,r));let i=t.lastIndexOf("/");return i===-1?void 0:t.slice(0,i)}function y(e){return e!=null&&e!==""}var me=e=>Array.isArray(e)?e:[e],he=(e,t)=>{let n=[[],[]];for(let r of e)t(r)?n[0].push(r):n[1].push(r);return n},ge=Array,b=(e,t)=>e.includes(t),_e=(e,t=0)=>[...Array(e)].map((e,n)=>n+t),x=(e,t,n)=>e===void 0?t===void 0?[]:Array.isArray(t)?t:[t]:(n?.prepend?Array.isArray(t)?e.unshift(...t):e.unshift(t):Array.isArray(t)?e.push(...t):e.push(t),e),ve=(e,t)=>t==null?e??[]:e==null?me(t):e.concat(t),ye=(...e)=>e.reduce(ve,[]),S=(e,t,n)=>{if(e===void 0)return Array.isArray(t)?t:[t];let r=n?.isEqual??((e,t)=>e===t);for(let n of me(t))e.some(e=>r(e,n))||e.push(n);return e},be=(e,t)=>e.reduce((e,n)=>{let r=n[t];return e[r]=x(e[r],n),e},{}),xe=(e,t,n)=>e.length===t.length&&e.every(n?.isEqual?(e,r)=>n.isEqual(e,t[r]):(e,n)=>e===t[n]),Se=(e,t)=>C(e)===t,C=e=>{let t=typeof e;return t==="object"?e===null?"null":"object":t==="function"?"object":t},w={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},Ce={...w,function:"a function"},we=class extends Error{},T=e=>Te(e,we),Te=(e,t=Error)=>{throw new t(e)},Ee=class extends Error{name="ParseError"},E=e=>Te(e,Ee),De=e=>` ${e}`,D=(e,t)=>{let n={},r=Array.isArray(e),i=!1;for(let[a,o]of Object.entries(e).entries()){let e=r?t(a,o[1]):t(...o,a);i||=typeof e[0]=="number";let s=Array.isArray(e[0])||e.length===0?e:[e];for(let[e,t]of s)typeof e=="object"?n[e.group]=x(n[e.group],t):n[e]=t}return i?Object.values(n):n},Oe=Object.entries,O=(e,t)=>e in t,ke=(e,t)=>t in e,Ae=class{constructor(e){Object.assign(this,e)}},je=class{},Me=class extends je{},Ne=(e,t)=>{let n={},r={},i;for(i in e)i in t?n[i]=e[i]:r[i]=e[i];return[n,r]},Pe=(e,t)=>Ne(e,t)[1],Fe=e=>Object.keys(e).length===0,Ie=e=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map(t=>[t,e[t]])],Le=(e,t)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)),Re=e=>{let t=Object.keys(e).sort(),n={};for(let r=0;r<t.length;r++)n[t[r]]=e[t[r]];return n},k=De("unset"),ze=e=>Object.values(e).filter(t=>typeof t=="number"?!0:typeof e[t]!="number"),Be={Array:Array,Boolean:Boolean,Date:Date,Error:Error,Function:Function,Map:Map,Number:Number,Promise:Promise,RegExp:RegExp,Set:Set,String:String,WeakMap:WeakMap,WeakSet:WeakSet},Ve=globalThis.File??Blob,He={ArrayBuffer:ArrayBuffer,Blob:Blob,File:Ve,FormData:FormData,Headers:Headers,Request:Request,Response:Response,URL:URL},Ue={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array,BigInt64Array:BigInt64Array,BigUint64Array:BigUint64Array},We={...Be,...He,...Ue,String:String,Number:Number,Boolean:Boolean},Ge=e=>{let t=Object.getPrototypeOf(e);for(;t?.constructor&&(!O(t.constructor.name,We)||!(e instanceof We[t.constructor.name]));)t=Object.getPrototypeOf(t);let n=t?.constructor?.name;if(!(n===void 0||n==="Object"))return n},Ke=e=>typeof e=="object"&&e?Ge(e)??"object":C(e),A=Array.isArray,qe={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"},Je={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"},Ye={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"},Xe={...qe,...Je,...Ye},Ze=e=>{let t=Object(e).name??null;return t&&O(t,We)&&We[t]===e?t:null},Qe=(e,t)=>{let n=e.prototype;for(;n!==null;){if(n===t.prototype)return!0;n=Object.getPrototypeOf(n)}return!1},$e=e=>et(e,new Map),et=(e,t)=>{if(typeof e!="object"||!e)return e;if(t?.has(e))return t.get(e);let n=Ze(e.constructor);if(n==="Date")return new Date(e.getTime());if(n&&n!=="Array")return e;let r=Array.isArray(e)?e.slice():Object.create(Object.getPrototypeOf(e)),i=Object.getOwnPropertyDescriptors(e);if(t){t.set(e,r);for(let e in i){let n=i[e];"get"in n||"set"in n||(n.value=et(n.value,t))}}return Object.defineProperties(r,i),r},tt=e=>{let t=k;return()=>t===k?t=e():t},nt=e=>typeof e=="function"&&e.length===0,rt=class extends Function{constructor(...e){let t=e.slice(0,-1),n=e[e.length-1];try{super(...t,n)}catch(t){return T(`Encountered an unexpected error while compiling your definition:\n Message: ${t} \n Source: (${e.slice(0,-1)}) => {\n ${e[e.length-1]}\n }`)}}},j=class{constructor(e,...[t]){return Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}},it=tt(()=>{try{return Function("return false")()}catch{return!0}});De("brand"),De("arkInferred"),De("args");var M=class{constructor(){}},at={fileName:()=>{try{return((Error().stack?.split("\n")[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},env:globalThis.process?.env??{}},ot=e=>e[0].toUpperCase()+e.slice(1),st=e=>e[0].toLowerCase()+e.slice(1),ct=e=>new RegExp(lt(e),typeof e=="string"?"":e.flags),lt=e=>`^(?:${typeof e=="string"?e:e.source})$`,ut={negativeLookahead:e=>`(?!${e})`,nonCapturingGroup:e=>`(?:${e})`},dt={" ":1,"\n":1,"\t":1},ft="^-0\\.?0*$",pt="[1-9]\\d*",mt="\\.\\d+",ht="\\.\\d*[1-9]",gt=e=>ct(ut.negativeLookahead(ft)+ut.nonCapturingGroup("-?"+ut.nonCapturingGroup(ut.nonCapturingGroup("0|"+pt)+ut.nonCapturingGroup(e.decimalPattern)+"?")+(e.allowDecimalOnly?"|"+e.decimalPattern:"")+"?")),_t=gt({decimalPattern:ht,allowDecimalOnly:!1}),vt=_t.test.bind(_t),yt=gt({decimalPattern:mt,allowDecimalOnly:!0});yt.test.bind(yt);var bt=/^-?\d*\.?\d*$/,xt=e=>e.length!==0&&bt.test(e),St=ct(ut.negativeLookahead("^-0$")+"-?"+ut.nonCapturingGroup(ut.nonCapturingGroup("0|"+pt))),Ct=St.test.bind(St),wt=/^-?\d+$/,Tt=wt.test.bind(wt),Et={number:"a number",bigint:"a bigint",integer:"an integer"},Dt=(e,t)=>`'${e}' was parsed as ${Et[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,Ot=(e,t)=>t==="number"?vt(e):Ct(e),kt=(e,t)=>t==="number"?Number(e):Number.parseInt(e),At=(e,t)=>t==="number"?xt(e):Tt(e),jt=(e,t)=>Pt(e,"number",t),Mt=(e,t)=>Pt(e,"number",{...t,strict:!0}),Nt=(e,t)=>Pt(e,"integer",t),Pt=(e,t,n)=>{let r=kt(e,t);return!Number.isNaN(r)&&At(e,t)?n?.strict?Ot(e,t)?r:E(Dt(e,t)):r:n?.errorOnFail?E(n?.errorOnFail===!0?`Failed to parse ${Et[t]} from '${e}'`:n?.errorOnFail):void 0},Ft=e=>{if(e[e.length-1]!=="n")return;let t=e.slice(0,-1),n;try{n=BigInt(t)}catch{return}if(St.test(t))return n;if(wt.test(t))return E(Dt(e,"bigint"))},It={version:"0.56.0",filename:at.fileName(),FileConstructor:Ve},Lt=new Map,Rt=Object.create(null),zt=e=>{let t=Lt.get(e);if(t)return t;let n=Vt(e);return Rt[n]?n=`${n}${Rt[n]++}`:Rt[n]=1,It[n]=e,Lt.set(e,n),n},Bt=e=>/^[$A-Z_a-z][\w$]*$/.test(e),Vt=e=>{switch(typeof e){case"object":{if(e===null)break;let t=Ge(e)??"object";return t[0].toLowerCase()+t.slice(1)}case"function":return Bt(e.name)?e.name:"fn";case"symbol":return e.description&&Bt(e.description)?e.description:"symbol"}return T(`Unexpected attempt to register serializable value of type ${C(e)}`)},Ht=e=>typeof e=="string"?JSON.stringify(e):typeof e=="bigint"?`${e}n`:`${e}`,Ut=(e,t={})=>Kt(e,{onUndefined:"$ark.undefined",onBigInt:e=>`$ark.bigint-${e}`,...t},[]),N=(e,t)=>{switch(C(e)){case"object":let n=e,r=n.constructor?.name??"Object";return r==="Object"||r==="Array"?t?.quoteKeys===!1?Wt(n,t?.indent??0,""):JSON.stringify(Kt(n,Gt,[]),null,t?.indent):Wt(n,t?.indent??0,"");case"symbol":return Gt.onSymbol(e);default:return Ht(e)}},Wt=(e,t,n)=>{if(typeof e=="function")return Gt.onFunction(e);if(typeof e!="object"||!e)return Ht(e);let r=n+" ".repeat(t);if(Array.isArray(e)){if(e.length===0)return"[]";let i=e.map(e=>Wt(e,t,r)).join(",\n"+r);return t?`[\n${r}${i}\n${n}]`:`[${i}]`}let i=e.constructor?.name??"Object";if(i==="Object"){let i=Ie(e).map(([e,n])=>`${r}${typeof e=="symbol"?Gt.onSymbol(e):Bt(e)?e:JSON.stringify(e)}: ${Wt(n,t,r)}`);return i.length===0?"{}":t?`{\n${i.join(",\n")}\n${n}}`:`{${i.join(", ")}}`}return e instanceof Date?qt(e):"expression"in e&&typeof e.expression=="string"?e.expression:i},Gt={onCycle:()=>"(cycle)",onSymbol:e=>`Symbol(${zt(e)})`,onFunction:e=>`Function(${zt(e)})`},Kt=(e,t,n)=>{switch(C(e)){case"object":{let r=e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();if(typeof r=="function")return Gt.onFunction(r);if(n.includes(r))return"(cycle)";let i=[...n,r];if(Array.isArray(r))return r.map(e=>Kt(e,t,i));if(r instanceof Date)return r.toDateString();let a={};for(let e in r)a[e]=Kt(r[e],t,i);for(let e of Object.getOwnPropertySymbols(r))a[t.onSymbol?.(e)??e.toString()]=Kt(r[e],t,i);return a}case"symbol":return Gt.onSymbol(e);case"bigint":return t.onBigInt?.(e)??`${e}n`;case"undefined":return t.onUndefined??"undefined";case"string":return e.replace(/\\/g,"\\\\");default:return e}},qt=e=>{let t=e.getFullYear(),n=e.getMonth(),r=e.getDate(),i=e.getHours(),a=e.getMinutes(),o=e.getSeconds(),s=e.getMilliseconds();if(n===0&&r===1&&i===0&&a===0&&o===0&&s===0)return`${t}`;let c=`${Jt[n]} ${r}, ${t}`;if(i===0&&a===0&&o===0&&s===0)return c;let l=e.toLocaleTimeString(),u=l.endsWith(" AM")||l.endsWith(" PM")?l.slice(-3):"";return u&&(l=l.slice(0,-u.length)),s?l+=`.${Xt(s,3)}`:Yt.test(l)&&(l=l.slice(0,-3)),`${l+u}, ${c}`},Jt=["January","February","March","April","May","June","July","August","September","October","November","December"],Yt=/:\d\d:00$/,Xt=(e,t)=>String(e).padStart(t,"0"),Zt=(e,t,...[n])=>{let r=n?.stringifySymbol??N,i=e;switch(typeof t){case"string":i=Bt(t)?e===""?t:`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;break;case"number":i=`${e}[${t}]`;break;case"symbol":i=`${e}[${r(t)}]`;break;default:n?.stringifyNonKey?i=`${e}[${n.stringifyNonKey(t)}]`:E(`${N(t)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return i},Qt=(e,...t)=>e.reduce((e,n)=>Zt(e,n,...t),""),$t=class extends ge{cache={};constructor(...e){super(),this.push(...e)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let e=0;e<this.length;e++)this.cache.json.push(typeof this[e]=="symbol"?N(this[e]):this[e]);return this.cache.json}stringify(){return this.cache.stringify?this.cache.stringify:this.cache.stringify=Qt(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e="",t=[e];for(let n of this)e=Zt(e,n),t.push(e);return this.cache.stringifyAncestors=t}},en=class{chars;i;def;constructor(e){this.def=e,this.chars=[...e],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(e){let t="";for(;this.lookahead&&!e(this,t);)t+=this.shift();return t}shiftUntilEscapable(e){let t="";for(;this.lookahead;)if(this.lookahead==="\\")this.shift(),e(this,t)||this.lookahead==="\\"?t+=this.shift():t+=`\\${this.shift()}`;else if(e(this,t))break;else t+=this.shift();return t}shiftUntilLookahead(e){return typeof e=="string"?this.shiftUntil(t=>t.lookahead===e):this.shiftUntil(t=>t.lookahead in e)}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in dt))}jumpToIndex(e){this.i=e<0?this.length+e:e}jumpForward(e){this.i+=e}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(e,t){return this.chars.slice(e,t).join("")}lookaheadIs(e){return this.lookahead===e}lookaheadIsIn(e){return this.lookahead in e}},tn=(e,t)=>`Unmatched ${e}${t===""?"":` before ${t}`}`,nn=e=>`Missing ${e}`;De("implementedTraits");for(var rn="$ark",an=2;rn in globalThis;)rn=`$ark${an++}`;var on=rn;globalThis[on]=It;var P=It,sn=e=>`${on}.${e}`,F=e=>sn(zt(e)),cn=class extends Me{argNames;body="";constructor(...e){super(),this.argNames=e;for(let t of e){if(t in this)throw Error(`Arg name '${t}' would overwrite an existing property on FunctionBody`);this[t]=t}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(e,t=!1){return un(e,t)}index(e,t=!1){return fn(`${e}`,t)}line(e){return this.body+=`${" ".repeat(this.indentation)}${e}\n`,this}const(e,t){return this.line(`const ${e} = ${t}`),this}let(e,t){return this.line(`let ${e} = ${t}`)}set(e,t){return this.line(`${e} = ${t}`)}if(e,t){return this.block(`if (${e})`,t)}elseIf(e,t){return this.block(`else if (${e})`,t)}else(e){return this.block("else",e)}for(e,t,n=0){return this.block(`for (let i = ${n}; ${e}; i++)`,t)}forIn(e,t){return this.block(`for (const k in ${e})`,t)}block(e,t,n=""){return this.line(`${e} {`),this.indent(),t(this),this.dedent(),this.line(`}${n}`)}return(e=""){return this.line(`return ${e}`)}write(e="anonymous",t=0){return`${e}(${this.argNames.join(", ")}) { ${t?this.body.split("\n").map(e=>" ".repeat(t)+`${e}`).join("\n"):this.body} }`}compile(){return new rt(...this.argNames,this.body)}},ln=e=>Se(e,"object")||typeof e=="symbol"?F(e):Ht(e),un=(e,t=!1)=>typeof e=="string"&&Bt(e)?`${t?"?":""}.${e}`:fn(dn(e),t),dn=e=>typeof e=="symbol"?F(e):JSON.stringify(e),fn=(e,t=!1)=>`${t?"?.":""}[${e}]`,pn=class extends cn{traversalKind;optimistic;constructor(e){super("data","ctx"),this.traversalKind=e.kind,this.optimistic=e.optimistic===!0}invoke(e,t){let n=t?.arg??this.data,r=typeof e=="string"?!0:this.requiresContextFor(e),i=typeof e=="string"?e:e.id;return r?`${this.referenceToId(i,t)}(${n}, ${this.ctx})`:`${this.referenceToId(i,t)}(${n})`}referenceToId(e,t){let n=`this.${e}${t?.kind??this.traversalKind}`;return t?.bind?`${n}.bind(${t?.bind})`:n}requiresContextFor(e){return this.traversalKind==="Apply"||e.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(e,t,n){let r=this.requiresContextFor(n);return r&&this.line(`${this.ctx}.path.push(${e})`),this.check(n,{arg:t}),r&&this.line(`${this.ctx}.path.pop()`),this}check(e,t){return this.traversalKind==="Allows"?this.if(`!${this.invoke(e,t)}`,()=>this.return(!1)):this.line(this.invoke(e,t))}},mn=e=>D(e,(e,t)=>[e,A(t)?[...t]:t]),I=De("arkKind"),L=(e,t)=>e?.[I]===t,R=e=>L(e,"root")||L(e,"constraint"),hn=["unit","proto","domain"],gn=["required","optional","index","sequence"],_n=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],vn=[..._n,"structure","predicate"],yn=[...vn,...gn],bn=["alias","union","morph","unit","intersection","proto","domain"],xn=[...bn,...yn],Sn=D(yn,(e,t)=>[t,1]),Cn=D([...gn,"undeclared"],(e,t)=>[t,1]),wn=D(xn,(e,t)=>[t,e]),Tn=e=>typeof e=="string"&&e in wn,En=e=>wn[e],Dn=e=>bn.slice(En(e)+1);[...Dn("union")],[...Dn("morph")];var On=e=>typeof e=="string"||typeof e=="boolean"||e===null?e:typeof e=="number"?Number.isNaN(e)?"NaN":e===Infinity?"Infinity":e===-Infinity?"-Infinity":e:ln(e),kn=e=>{let t="{ ";for(let[n,r]of Object.entries(e))t+=`${n}: ${ln(r)}, `;return t+" }"},z=e=>{let t=e;return t.hasAssociatedError&&(t.defaults.expected??=e=>"description"in e?e.description:t.defaults.description(e),t.defaults.actual??=e=>N(e),t.defaults.problem??=e=>`must be ${e.expected}${e.actual?` (was ${e.actual})`:""}`,t.defaults.message??=e=>{if(e.path.length===0)return e.problem;let t=`${e.propString} ${e.problem}`;return t[0]==="["?`value at ${t}`:t}),t},B={Error:class extends Error{name="ToJsonSchemaError";code;context;constructor(e,t){super(N(t,{quoteKeys:!1,indent:4})),this.code=e,this.context=t}hasCode(e){return this.code===e}},throw:(...e)=>{throw new B.Error(...e)},throwInternalOperandError:(e,t)=>T(`Unexpected JSON Schema input for ${e}: ${N(t)}`),defaultConfig:{target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:e=>B.throw("arrayObject",e),arrayPostfix:e=>B.throw("arrayPostfix",e),defaultValue:e=>B.throw("defaultValue",e),domain:e=>B.throw("domain",e),morph:e=>B.throw("morph",e),patternIntersection:e=>B.throw("patternIntersection",e),predicate:e=>B.throw("predicate",e),proto:e=>B.throw("proto",e),symbolKey:e=>B.throw("symbolKey",e),unit:e=>B.throw("unit",e),date:e=>B.throw("date",e)}}};P.config??={};var An=(e,t)=>{if(!t)return e;let n={...e},r;for(r in t){let i={...e.keywords};if(r==="keywords"){for(let e in t[r]){let n=t.keywords[e];n!==void 0&&(i[e]=typeof n=="string"?{description:n}:n)}n.keywords=i}else r==="toJsonSchema"?n[r]=Mn(e.toJsonSchema,t.toJsonSchema):Tn(r)?n[r]={...e[r],...t[r]}:n[r]=t[r]}return n},jn={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"},Mn=(e,t)=>{if(!e)return Nn(t??{},void 0);if(!t)return e;let n={...e},r;for(r in t)r==="fallback"?n.fallback=Pn(e.fallback,t.fallback):n[r]=t[r];return Nn(n,t)},Nn=(e,t)=>t?.dialect===void 0?t?.target===void 0?e:{...e,dialect:jn[t.target]}:e,Pn=(e,t)=>{e=Fn(e),t=Fn(t);let n={},r;for(r in B.defaultConfig.fallback)n[r]=t[r]??t.default??e[r]??e.default??B.defaultConfig.fallback[r];return n},Fn=e=>typeof e=="function"?{default:e}:e??{},In=class e extends Me{[I]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:t,...n},r){super(),this.input=n,this.ctx=r,Le(this,n);let i=r.data;n.code==="union"&&(n.errors=n.errors.flatMap(n=>{let r=n.hasCode("union")?n.errors:[n];return!e&&!t?r:r.map(n=>n.transform(n=>({...n,path:ye(e,n.path,t)})))})),this.nodeConfig=r.config[this.code];let a=[...n.path??r.path];t&&a.push(...t),e&&a.unshift(...e),this.path=new $t(...a),this.data="data"in n?n.data:i}transform(t){return new e(t({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return Qt(this.path)}get expected(){if(this.input.expected)return this.input.expected;let e=this.meta?.expected??this.nodeConfig.expected;return typeof e=="function"?e(this.input):e}get actual(){if(this.input.actual)return this.input.actual;let e=this.meta?.actual??this.nodeConfig.actual;return typeof e=="function"?e(this.data):e}get problem(){if(this.input.problem)return this.input.problem;let e=this.meta?.problem??this.nodeConfig.problem;return typeof e=="function"?e(this):e}get message(){if(this.input.message)return this.input.message;let e=this.meta?.message??this.nodeConfig.message;return typeof e=="function"?e(this):e}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}},Ln=class e extends ge{[I]="errors";ctx;constructor(e){super(),this.ctx=e}byPath=Object.create(null);get flatByPath(){return D(this.byPath,(e,t)=>[e,t.flat])}get flatProblemsByPath(){return D(this.byPath,(e,t)=>[e,t.flat.map(e=>e.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new Rn(this)}add(e){let t=this.byPath[e.propString];if(t){if(e===t||t.hasCode("union")&&t.errors.length===0)return;let n=e.hasCode("union")&&e.errors.length===0?e:new In({code:"intersection",errors:t.hasCode("intersection")?[...t.errors,e]:[t,e]},this.ctx),r=this.indexOf(t);this.mutable[r===-1?this.length:r]=n,this.byPath[e.propString]=n,this.addAncestorPaths(e)}else this.byPath[e.propString]=e,this.addAncestorPaths(e),this.mutable.push(e);this.count++}transform(t){let n=new e(this.ctx);for(let e of this)n.add(t(e));return n}merge(e){for(let t of e)this.add(new In({...t,path:[...this.ctx.path,...t.path]},this.ctx))}affectsPath(e){return this.length===0?!1:e.stringifyAncestors().some(e=>e in this.byPath)||e.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map(e=>e.toJSON())]}toString(){return this.join("\n")}addAncestorPaths(e){for(let t of e.path.stringifyAncestors())this.byAncestorPath[t]=x(this.byAncestorPath[t],e)}},Rn=class extends Error{name="TraversalError";constructor(e){e.length===1?super(e.summary):super("\n"+e.map(e=>` • ${zn(e)}`).join("\n")),Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}},zn=e=>e.toString().split("\n").join("\n "),Bn=class{path=[];errors=new Ln(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(e,t){this.root=e,this.config=t}get data(){let e=this.root;for(let t of this.path)e=e?.[t];return e}get propString(){return Qt(this.path)}reject(e){return this.error(e),!1}mustBe(e){return this.error(e),!1}error(e){let t=typeof e=="object"?e.code?e:{...e,code:"predicate"}:{code:"predicate",expected:e};return this.errorFromContext(t)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(e){let t={path:new $t(...this.path),morphs:e};this.currentBranch?this.currentBranch.queuedMorphs.push(t):this.queuedMorphs.push(t)}finalize(e){return this.queuedMorphs.length&&(typeof this.root=="object"&&this.root!==null&&this.config.clone&&(this.root=this.config.clone(this.root)),this.applyQueuedMorphs()),this.hasError()?e?e(this.errors):this.errors: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(e){return this.errorFromContext(e)}errorFromContext(e){let t=new In(e,this);return this.currentBranch?this.currentBranch.error=t:this.errors.add(t),t}applyQueuedMorphs(){for(;this.queuedMorphs.length;){let e=this.queuedMorphs;this.queuedMorphs=[];for(let{path:t,morphs:n}of e)this.errors.affectsPath(t)||this.applyMorphsAtPath(t,n)}}applyMorphsAtPath(e,t){let n=e[e.length-1],r;if(n!==void 0){r=this.root;for(let t=0;t<e.length-1;t++)r=r[e[t]]}for(let i of t){this.path=[...e];let t=R(i),a=i(r===void 0?this.root:r[n],this);if(a instanceof In){this.errors.includes(a)||this.errors.add(a);break}if(a instanceof Ln){t||this.errors.merge(a),this.queuedMorphs=[];break}r===void 0?this.root=a:r[n]=a,this.applyQueuedMorphs()}}},V=(e,t,n)=>{if(!n)return t();n.path.push(e);let r=t();return n.path.pop(),r},Vn=class extends j{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(e,t){super((e,t,n=this.onFail)=>t?(this.traverseApply(e,t),t.hasError()?t.errors:t.data):this.rootApply(e,n),{attach:e}),this.attachments=e,this.$=t,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0||this.hasKind("sequence")&&this.inner.defaultables!==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((e,t)=>Xn(e,t.shallowReferences),[this]);let n=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let e=0;e<this.children.length;e++){if(this.includesTransform||=this.children[e].includesTransform,this.includesContextualPredicate||=this.children[e].includesContextualPredicate,this.isCyclic||=this.children[e].isCyclic,!n){let t=this.children[e].flatRefs;for(let e=0;e<t.length;e++){let n=t[e];if(!this.flatRefs.some(e=>Jn(e,n))){this.flatRefs.push(n);for(let e of n.node.branches)(e.hasKind("morph")||e.hasKind("intersection")&&e.structure?.structuralMorph!==void 0)&&this.flatMorphs.push({path:n.path,propString:n.propString,node:e})}}}Object.assign(this.referencesById,this.children[e].referencesById)}this.flatRefs.sort((e,t)=>e.path.length>t.path.length?1:e.path.length<t.path.length?-1:e.propString>t.propString?1:e.propString<t.propString||e.node.expression<t.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(e=>e.length===1||e.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some(e=>e.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?e=>this.traverseAllows(e,new Bn(e,this.$.resolvedConfig)):e=>this.traverseAllows(e)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(e,t)=>{if(this.allows(e))return e;let n=new Bn(e,this.$.resolvedConfig);return this.traverseApply(e,n),n.finalize(t)};case"contextual":return(e,t)=>{let n=new Bn(e,this.$.resolvedConfig);return this.traverseApply(e,n),n.finalize(t)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let e=this.$.resolvedConfig.clone;return(t,n)=>{if(this.allows(t))return this.contextFreeMorph(e&&(typeof t=="object"&&t||typeof t=="function")?e(t):t);let r=new Bn(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,T(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=Kn(this.metaJson);cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=En(this.kind);precompilation;assert=(e,t)=>this(e,t,e=>e.throw());traverse(e,t){return this(e,t,null)}get in(){return this.cacheGetter("in",this.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter("rawIn",this.getIo("in"))}get out(){return this.cacheGetter("out",this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter("rawOut",this.getIo("out"))}getIo(e){if(!this.includesTransform)return this;let t={};for(let[n,r]of this.innerEntries){let i=this.impl.keys[n];if(i.reduceIo)i.reduceIo(e,t,r);else if(i.child){let i=r;t[n]=A(i)?i.map(t=>e==="in"?t.rawIn:t.rawOut):e==="in"?i.rawIn:i.rawOut}else t[n]=r}return this.$.node(this.kind,t)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(e){let t=R(e)?e:this.$.parseDefinition(e);return this.innerHash===t.innerHash}ifEquals(e){return this.equals(e)?this:void 0}hasKind(e){return this.kind===e}assertHasKind(e){return this.kind!==e&&Te(`${this.kind} node was not of asserted kind ${e}`),this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){return b(e,this.kind)||Te(`${this.kind} node was not one of asserted kinds ${e}`),this}isBasis(){return b(hn,this.kind)}isConstraint(){return b(yn,this.kind)}isStructural(){return b(gn,this.kind)}isRefinement(){return b(vn,this.kind)}isRoot(){return b(bn,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(e){return this.hasKind("unit")&&this.allows(e)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(e){let t=Hn.normalize(e);return this._select(t)}_select(e){let t=Hn.applyBoundary[e.boundary??"references"](this);return e.kind&&(t=t.filter(t=>t.kind===e.kind)),e.where&&(t=t.filter(e.where)),Hn.applyMethod[e.method??"filter"](t,this,e)}transform(e,t){return this._transform(e,this._createTransformContext(t))}_createTransformContext(e){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:e?.prereduced??!1},undeclaredKeyHandling:void 0,...e}}_transform(e,t){let n=t.bindScope??this.$;if(t.seen[this.id])return this.$.lazilyResolve(t.seen[this.id]);if(t.shouldTransform?.(this,t)===!1)return this;let r;t.seen[this.id]=()=>r,this.hasKind("structure")&&this.undeclared!==t.undeclaredKeyHandling&&(t={...t,undeclaredKeyHandling:this.undeclared});let i=D(this.inner,(n,r)=>{if(!this.impl.keys[n].child)return[n,r];let i=r;if(!A(i)){let r=i._transform(e,t);return r?[n,r]:[]}if(i.length===0)return[n,r];let a=i.flatMap(n=>n._transform(e,t)??[]);return a.length?[n,a]:[]});delete t.seen[this.id];let a=Object.assign(i,{meta:this.meta}),o=t.selected&&!t.selected.includes(this)?a:e(this.kind,a,t);if(o===null)return null;if(R(o))return r=o;let s=Object.keys(o);return(s.length===0||s.length===1&&s[0]==="meta")&&!Fe(this.inner)?null:(this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in o)?t.undeclaredKeyHandling?{...o,value:P.intrinsic.unknown}:null:(this.kind==="morph"&&(o.in??=P.intrinsic.unknown),r=n.node(this.kind,o,t.parseOptions))}configureReferences(e,t="references"){let n=Hn.normalize(t),r=typeof e=="string"?(t,n)=>({...n,meta:{...n.meta,description:e}}):typeof e=="function"?(t,n)=>({...n,meta:e(n.meta)}):(t,n)=>({...n,meta:{...n.meta,...e}});if(n.boundary==="self")return this.$.node(this.kind,r(this.kind,{...this.inner,meta:this.meta}));let i=this._select(n),a=i&&me(i),o=n.boundary==="child"?(e,t)=>t.root.children.includes(e):n.boundary==="shallow"?e=>e.kind!=="structure":()=>!0;return this.$.finalize(this.transform(r,{shouldTransform:o,selected:a}))}},Hn={applyBoundary:{self:e=>[e],child:e=>[...e.children],shallow:e=>[...e.shallowReferences],references:e=>[...e.references]},applyMethod:{filter:e=>e,assertFilter:(e,t,n)=>(e.length===0&&Te(Un(t,n)),e),find:e=>e[0],assertFind:(e,t,n)=>(e.length===0&&Te(Un(t,n)),e[0])},normalize:e=>typeof e=="function"?{boundary:"references",method:"filter",where:e}:typeof e=="string"?O(e,Hn.applyBoundary)?{method:"filter",boundary:e}:{boundary:"references",method:"filter",kind:e}:{boundary:"references",method:"filter",...e}},Un=(e,t)=>`${e} had no references matching ${N(t)}.`,Wn=e=>Qt(e,{stringifyNonKey:e=>e.expression}),Gn=/"(\$ark\.[^"]+)"/g,Kn=e=>JSON.stringify(e).replace(Gn,"$1"),qn=(e,t)=>({path:e,node:t,propString:Wn(e)}),Jn=(e,t)=>e.propString===t.propString&&e.node.equals(t.node),Yn=(e,t)=>S(e,t,{isEqual:Jn}),Xn=(e,t)=>S(e,t,{isEqual:(e,t)=>e.equals(t)}),H=class e extends Array{static init(t,n,r,i){return new e({kind:t,l:n,r:r,path:i?.path??[],optional:i?.optional??!1})}add(e,t,n,r){return this.push({kind:e,l:t,r:n,path:r?.path??[],optional:r?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:e,l:t,r:n}=this[0],r=Qt(e);return $n(`Intersection${r&&` at ${r}`} of ${Zn(t,n)}`)}return`The following intersections result in unsatisfiable types:\n• ${this.map(({path:e,l:t,r:n})=>`${e}: ${Zn(t,n)}`).join("\n• ")}`}throw(){return E(this.describeReasons())}invert(){let t=this.map(e=>({...e,l:e.r,r:e.l}));return t instanceof e?t:new e(...t)}withPrefixKey(e,t){return this.map(n=>({...n,path:[e,...n.path],optional:n.optional||t==="optional"}))}toNeverIfDisjoint(){return P.intrinsic.never}},Zn=(e,t)=>`${Qn(e)} and ${Qn(t)}`,Qn=e=>R(e)?e.expression:A(e)?e.map(Qn).join(" | ")||"never":String(e),$n=e=>`${e} results in an unsatisfiable type`,er={},U=(e,t,n)=>W(e,t,{$:n,invert:!1,pipe:!1}),tr=(e,t,n)=>W(e,t,{$:n,invert:!1,pipe:!0}),W=(e,t,n)=>{let r=n.pipe?"|>":"&",i=`${e.hash}${r}${t.hash}`;if(er[i]!==void 0)return er[i];if(!n.pipe){let n=`${t.hash}${r}${e.hash}`;if(er[n]!==void 0){let e=er[n],t=e instanceof H?e.invert():e;return er[i]=t,t}}let a=!n.pipe||!e.includesTransform&&!t.includesTransform;if(a&&e.equals(t))return e;let o=a?nr(e,t,n):e.hasKindIn(...bn)?rr(e,t,n):nr(e,t,n);return R(o)&&(e.equals(o)?o=e:t.equals(o)&&(o=t)),er[i]=o,o},nr=(e,t,n)=>{let r=e.precedence<t.precedence?e.kind:t.kind,i=e.impl.intersections[t.kind]??t.impl.intersections[e.kind];if(i===void 0)return null;if(r===e.kind)return i(e,t,n);{let r=i(t,e,{...n,invert:!n.invert});return r instanceof H&&(r=r.invert()),r}},rr=(e,t,n)=>e.includesTransform||t.includesTransform?n.invert?ir(t,e,n):ir(e,t,n):nr(e,t,n),ir=(e,t,n)=>e.distribute(e=>ar(e,t,n),r=>{let i=r.filter(R);if(i.length===0)return H.init("union",e.branches,t.branches);if(i.length<e.branches.length||!e.branches.every((e,t)=>e.rawIn.equals(i[t].rawIn)))return n.$.parseSchema(i);if(i.length===1)return i[0];let a={branches:i};return n.$.parseSchema(a)}),ar=(e,t,n)=>{if(e.hasKind("morph")){let r=[...e.morphs];if(e.lastMorphIfNode){let i=W(e.lastMorphIfNode,t,n);if(i instanceof H)return i;r[r.length-1]=i}else r.push(t);return n.$.node("morph",{morphs:r,in:e.inner.in})}if(t.hasKind("morph")){let r=W(e,t.rawIn,n);return r instanceof H?r:n.$.node("morph",{morphs:[t],in:r})}return n.$.node("morph",{morphs:[t],in:e})},or=class extends Vn{constructor(e,t){super(e,t),Object.defineProperty(this,I,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(e){return U(this,e,this.$)}},sr=class extends or{traverseApply=(e,t)=>{this.traverseAllows(e,t)||t.errorFromNodeContext(this.errorContext)};compile(e){e.traversalKind==="Allows"?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return kn(this.errorContext)}},G=e=>(t,n)=>{if(A(t)){if(t.length===0)return;let r=t.map(t=>n.$.node(e,t));return e==="predicate"?r:r.sort((e,t)=>e.hash<t.hash?-1:1)}let r=n.$.node(e,t);return r.hasOpenIntersection()?[r]:r},cr=e=>{let t=e.r.shift();if(!t){let t=e.l.length===0&&e.kind==="structure"?P.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,ur(e.l)),{prereduced:!0});for(let n of e.roots){if(t instanceof H)return t;t=W(n,t,e.ctx)}return t}let n=!1;for(let r=0;r<e.l.length;r++){let i=W(e.l[r],t,e.ctx);if(i!==null){if(i instanceof H)return i;if(i.isRoot())return e.roots.push(i),e.l.splice(r),cr(e);if(!n)e.l[r]=i,n=!0;else if(!e.l.includes(i))return T(`Unexpectedly encountered multiple distinct intersection results for refinement ${t}`)}}if(n||e.l.push(t),e.kind==="intersection"&&t.impliedSiblings)for(let n of t.impliedSiblings)S(e.r,n);return cr(e)},lr=e=>Object.entries(e).flatMap(([e,t])=>e in Sn?t:[]).sort((e,t)=>e.precedence<t.precedence?-1:e.precedence>t.precedence?1:e.kind==="predicate"&&t.kind==="predicate"?0:e.hash<t.hash?-1:1),ur=e=>{let t={};for(let n of e)if(n.hasOpenIntersection())t[n.kind]=x(t[n.kind],n);else{if(t[n.kind])return T(`Unexpected intersection of closed refinements of kind ${n.kind}`);t[n.kind]=n}return t},dr=(...e)=>E(fr(...e)),fr=(e,t,n)=>{let r=n.hasKind("morph")?"a morph":n.isUnknown()?"unknown":n.exclude(t).defaultShortDescription;return`${ot(e)} operand must be ${t.description} (was ${r})`},pr=(e,t,n)=>new hr(e,t,n,n,null),mr=class extends j{},hr=class extends j{[I]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,t,n,r,i){super((...e)=>{let n=D(this.names,(t,n)=>{let r=this.arg$.parse(e[t]);return r.extends(this.constraints[t])||E(gr(n,this.constraints[t].expression,r.expression)),[n,r]});if(this.defIsLazy()){let e=this.bodyDef(n);return this.$.parse(e)}return this.$.parse(t,{args:n})}),this.paramDefs=e,this.bodyDef=t,this.$=n,this.arg$=r,this.hkt=i,this.description=i?(new i).description??`a generic type for ${i.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof mr}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get json(){return this.cacheGetter("json",{params:this.params.map(e=>e[1].isUnknown()?e[0]:[e[0],e[1].json]),body:Ut(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map(e=>typeof e=="string"?[e,P.intrinsic.unknown]:[e[0],this.$.parse(e[1])]))}get names(){return this.cacheGetter("names",this.params.map(e=>e[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map(e=>e[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}},gr=(e,t,n)=>`${e} must be assignable to ${t} (was ${n})`,_r={implementation:z({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:e=>typeof e=="function"?{predicate:e}:e,defaults:{description:e=>`valid according to ${e.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}}),Node:class extends or{serializedPredicate=F(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=kn(this.errorContext);traverseApply=(e,t)=>{let n=t.currentErrorCount;!this.predicate(e,t.external)&&t.currentErrorCount===n&&t.errorFromNodeContext(this.errorContext)};compile(e){if(e.traversalKind==="Allows"){e.return(this.compiledCondition);return}e.initializeErrorCount(),e.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(e,t){return t.fallback.predicate({code:"predicate",base:e,predicate:this.predicate})}}},vr={implementation:z({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:e=>Number.isInteger(e)?e:E(yr(e))}},normalize:e=>typeof e=="number"?{rule:e}:e,hasAssociatedError:!0,defaults:{description:e=>e.rule===1?"an integer":e.rule===2?"even":`a multiple of ${e.rule}`},intersections:{divisor:(e,t,n)=>n.$.node("divisor",{rule:Math.abs(e.rule*t.rule/br(e.rule,t.rule))})},obviatesBasisDescription:!0}),Node:class extends sr{traverseAllows=e=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=P.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){return e.type="integer",this.rule===1||(e.multipleOf=this.rule),e}}},yr=e=>`divisor must be an integer (was ${e})`,br=(e,t)=>{let n,r=e,i=t;for(;i!==0;)n=i,i=r%i,r=n;return r},xr=class extends sr{boundOperandKind=Ar[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=jr(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${Sr[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?Mr(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator[0]==="<"?"upper":"lower";isStricterThan(e){return(this.limitKind==="upper"?this.numericLimit<e.numericLimit:this.numericLimit>e.numericLimit)||this.numericLimit===e.numericLimit&&this.exclusive===!0&&!e.exclusive}overlapsRange(e){return!(this.isStricterThan(e)||this.numericLimit===e.numericLimit&&(this.exclusive||e.exclusive))}overlapIsUnit(e){return this.numericLimit===e.numericLimit&&!this.exclusive&&!e.exclusive}},Sr={"<":">=","<=":">",">":"<=",">=":"<"},Cr={min:"max",minLength:"maxLength",after:"before"},wr={parse:e=>e||void 0},Tr=e=>t=>{if(typeof t=="number")return{rule:t};let{exclusive:n,...r}=t;return n?{...r,rule:e==="minLength"?r.rule+1:r.rule-1}:r},Er=e=>t=>{if(typeof t=="number"||typeof t=="string"||t instanceof Date)return{rule:t};let{exclusive:n,...r}=t;if(!n)return r;let i=typeof r.rule=="number"?r.rule:typeof r.rule=="string"?new Date(r.rule).valueOf():r.rule.valueOf();return n?{...r,rule:e==="after"?i+1:i-1}:r},Dr=e=>typeof e=="string"||typeof e=="number"?new Date(e):e,Or=(e,t)=>`${e} bound must be a positive integer (was ${t})`,kr=e=>t=>((!Number.isInteger(t)||t<0)&&E(Or(e,t)),t),Ar={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},jr=(e,t)=>`${O(e,Cr)?">":"<"}${t?"":"="}`,Mr=e=>typeof e=="string"?e:new Date(e).toLocaleString(),Nr=e=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`,Pr={implementation:z({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Dr,serialize:e=>e.toISOString()}},normalize:Er("after"),defaults:{description:e=>`${e.collapsibleLimitString} or later`,actual:qt},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}}),Node:class extends xr{impliedBasis=P.intrinsic.Date.internal;collapsibleLimitString=qt(this.rule);traverseAllows=e=>e>=this.rule;reduceJsonSchema(e,t){return t.fallback.date({code:"date",base:e,after:this.rule})}}},Fr={implementation:z({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Dr,serialize:e=>e.toISOString()}},normalize:Er("before"),defaults:{description:e=>`${e.collapsibleLimitString} or earlier`,actual:qt},intersections:{before:(e,t)=>e.isStricterThan(t)?e:t,after:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node("unit",{unit:e.rule}):null:H.init("range",e,t)}}),Node:class extends xr{collapsibleLimitString=qt(this.rule);traverseAllows=e=>e<=this.rule;impliedBasis=P.intrinsic.Date.internal;reduceJsonSchema(e,t){return t.fallback.date({code:"date",base:e,before:this.rule})}}},Ir={implementation:z({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:kr("exactLength")}},normalize:e=>typeof e=="number"?{rule:e}:e,hasAssociatedError:!0,defaults:{description:e=>`exactly length ${e.rule}`,actual:e=>`${e.length}`},intersections:{exactLength:(e,t,n)=>H.init("unit",n.$.node("unit",{unit:e.rule}),n.$.node("unit",{unit:t.rule}),{path:["length"]}),minLength:(e,t)=>e.rule>=t.rule?e:H.init("range",e,t),maxLength:(e,t)=>e.rule<=t.rule?e:H.init("range",e,t)}}),Node:class extends sr{traverseAllows=e=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=P.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(e){switch(e.type){case"string":return e.minLength=this.rule,e.maxLength=this.rule,e;case"array":return e.minItems=this.rule,e.maxItems=this.rule,e;default:return B.throwInternalOperandError("exactLength",e)}}}},Lr={implementation:z({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:wr},normalize:e=>typeof e=="number"?{rule:e}:e,defaults:{description:e=>e.rule===0?e.exclusive?"negative":"non-positive":`${e.exclusive?"less than":"at most"} ${e.rule}`},intersections:{max:(e,t)=>e.isStricterThan(t)?e:t,min:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node("unit",{unit:e.rule}):null:H.init("range",e,t)},obviatesBasisDescription:!0}),Node:class extends xr{impliedBasis=P.intrinsic.number.internal;traverseAllows=this.exclusive?e=>e<this.rule:e=>e<=this.rule;reduceJsonSchema(e){return this.exclusive?e.exclusiveMaximum=this.rule:e.maximum=this.rule,e}}},Rr={implementation:z({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:kr("maxLength")}},reduce:(e,t)=>e.rule===0?t.node("exactLength",e):void 0,normalize:Tr("maxLength"),defaults:{description:e=>`at most length ${e.rule}`,actual:e=>`${e.length}`},intersections:{maxLength:(e,t)=>e.isStricterThan(t)?e:t,minLength:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node("exactLength",{rule:e.rule}):null:H.init("range",e,t)}}),Node:class extends xr{impliedBasis=P.intrinsic.lengthBoundable.internal;traverseAllows=e=>e.length<=this.rule;reduceJsonSchema(e){switch(e.type){case"string":return e.maxLength=this.rule,e;case"array":return e.maxItems=this.rule,e;default:return B.throwInternalOperandError("maxLength",e)}}}},zr={implementation:z({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:wr},normalize:e=>typeof e=="number"?{rule:e}:e,defaults:{description:e=>e.rule===0?e.exclusive?"positive":"non-negative":`${e.exclusive?"more than":"at least"} ${e.rule}`},intersections:{min:(e,t)=>e.isStricterThan(t)?e:t},obviatesBasisDescription:!0}),Node:class extends xr{impliedBasis=P.intrinsic.number.internal;traverseAllows=this.exclusive?e=>e>this.rule:e=>e>=this.rule;reduceJsonSchema(e){return this.exclusive?e.exclusiveMinimum=this.rule:e.minimum=this.rule,e}}},Br={implementation:z({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:kr("minLength")}},reduce:e=>e.rule===0?P.intrinsic.unknown:void 0,normalize:Tr("minLength"),defaults:{description:e=>e.rule===1?"non-empty":`at least length ${e.rule}`,actual:e=>e.length===0?"":`${e.length}`},intersections:{minLength:(e,t)=>e.isStricterThan(t)?e:t}}),Node:class extends xr{impliedBasis=P.intrinsic.lengthBoundable.internal;traverseAllows=e=>e.length>=this.rule;reduceJsonSchema(e){switch(e.type){case"string":return e.minLength=this.rule,e;case"array":return e.minItems=this.rule,e;default:return B.throwInternalOperandError("minLength",e)}}}},Vr={min:zr.implementation,max:Lr.implementation,minLength:Br.implementation,maxLength:Rr.implementation,exactLength:Ir.implementation,after:Pr.implementation,before:Fr.implementation},Hr={min:zr.Node,max:Lr.Node,minLength:Br.Node,maxLength:Rr.Node,exactLength:Ir.Node,after:Pr.Node,before:Fr.Node},Ur={implementation:z({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:e=>typeof e=="string"?{rule:e}:e instanceof RegExp?e.flags?{rule:e.source,flags:e.flags}:{rule:e.source}:e,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:e=>`matched by ${e.rule}`},intersections:{pattern:()=>null}}),Node:class extends sr{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=P.intrinsic.string.internal;reduceJsonSchema(e,t){return e.pattern?t.fallback.patternIntersection({code:"patternIntersection",base:e,pattern:this.rule}):(e.pattern=this.rule,e)}}},Wr=(e,t)=>{let n=Gr(e);return t&&!t.includes(n)?E(`Root of kind ${n} should be one of ${t}`):n},Gr=e=>{if(L(e,"root"))return e.kind;if(typeof e=="string")return e[0]==="$"?"alias":e in w?"domain":"proto";if(typeof e=="function")return"proto";if(typeof e!="object"||!e)return E(Kr(e));if("morphs"in e)return"morph";if("branches"in e||A(e))return"union";if("unit"in e)return"unit";if("reference"in e)return"alias";let t=Object.keys(e);return t.length===0||t.some(e=>e in Sn)?"intersection":"proto"in e?"proto":"domain"in e?"domain":E(Kr(e))},Kr=e=>`${N(e)} is not a valid type schema`,qr={},Jr=e=>A(e)?e.map(e=>e.collapsibleJson):e.collapsibleJson,K={};P.nodesByRegisteredId=K;var Yr=e=>(qr[e]??=0,`${e}${++qr[e]}`),Xr=e=>{let t=Fa[e.kind],n=t.applyConfig?.(e.def,e.$.resolvedConfig)??e.def,r={},{meta:i,...a}=n,o=i===void 0?{}:typeof i=="string"?{description:i}:i,s=Oe(a).sort(([e],[t])=>Tn(e)?Tn(t)?En(e)-En(t):1:Tn(t)||e<t?-1:1).filter(([e,t])=>{if(e.startsWith("meta.")){let n=e.slice(5);return o[n]=t,!1}return!0});for(let n of s){let i=n[0],a=t.keys[i];if(!a)return E(`Key ${i} is not valid on ${e.kind} schema`);let o=a.parse?a.parse(n[1],e):n[1];o!==k&&(o!==void 0||a.preserveUndefined)&&(r[i]=o)}if(t.reduce&&!e.prereduced){let n=t.reduce(r,e.$);if(n)return n instanceof H?n.throw():$r(n,o)}return Zr({id:e.id,kind:e.kind,inner:r,meta:o,$:e.$})},Zr=({id:e,kind:t,inner:n,meta:r,$:i,ignoreCache:a})=>{let o=Fa[t],s=Oe(n),c=[],l={};for(let[e,t]of s){let n=o.keys[e],r=n.serialize??(n.child?Jr:On);if(l[e]=r(t),n.child===!0){let e=t;A(e)?c.push(...e):c.push(e)}else typeof n.child=="function"&&c.push(...n.child(t))}o.finalizeInnerJson&&(l=o.finalizeInnerJson(l));let u={...l},d={};Fe(r)||(d=D(r,(e,t)=>[e,e==="examples"?t:On(t)]),u.meta=ei(d,"description",!0)),l=ei(l,o.collapsibleKey,!1);let f=JSON.stringify({kind:t,...l});u=ei(u,o.collapsibleKey,!1);let p=ei(u,o.collapsibleKey,!0),m=JSON.stringify({kind:t,...u});if(i.nodesByHash[m]&&!a)return i.nodesByHash[m];let h={id:e,kind:t,impl:o,inner:n,innerEntries:s,innerJson:l,innerHash:f,meta:r,metaJson:d,json:u,hash:m,collapsibleJson:p,children:c};if(t!=="intersection")for(let e in n)e!=="in"&&e!=="out"&&(h[e]=n[e]);let g=new Ia[t](h,i);return i.nodesByHash[m]=g},Qr=(e,t)=>e.id===t?e:(R(K[t])&&T(`Unexpected attempt to overwrite node id ${t}`),Zr({id:t,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})),$r=(e,t,n)=>(n&&R(K[n])&&T(`Unexpected attempt to overwrite node id ${n}`),Zr({id:n??Yr(t.alias??e.kind),kind:e.kind,inner:e.inner,meta:t,$:e.$})),ei=(e,t,n)=>{let r=Object.keys(e);if(r.length===1&&r[0]===t){let r=e[t];if(n||Se(r,"object")&&(Object.keys(r).length===1||Array.isArray(r)))return r}return e},ti=(e,t,n)=>{if(e.key!==t.key)return null;let r=e.key,i=W(e.value,t.value,n),a=e.required||t.required?"required":"optional";if(i instanceof H)if(a==="optional")i=P.intrinsic.never.internal;else return i.withPrefixKey(e.key,e.required&&t.required?"required":"optional");if(a==="required")return n.$.node("required",{key:r,value:i});let o=e.hasDefault()?t.hasDefault()?e.default===t.default?e.default:E(ri(e.default,t.default)):e.default:t.hasDefault()?t.default:k;return n.$.node("optional",{key:r,value:i,default:o})},ni=class extends or{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=P.intrinsic.object.internal;serializedKey=ln(this.key);compiledKey=typeof this.key=="string"?this.key:this.serializedKey;flatRefs=x(this.value.flatRefs.map(e=>qn([this.key,...e.path],e.node)),qn([this.key],this.value));_transform(e,t){t.path.push(this.key);let n=super._transform(e,t);return t.path.pop(),n}hasDefault(){return"default"in this.inner}traverseAllows=(e,t)=>this.key in e?V(this.key,()=>this.value.traverseAllows(e[this.key],t),t):this.optional;traverseApply=(e,t)=>{this.key in e?V(this.key,()=>this.value.traverseApply(e[this.key],t),t):this.hasKind("required")&&t.errorFromNodeContext(this.errorContext)};compile(e){e.if(`${this.serializedKey} in data`,()=>e.traverseKey(this.serializedKey,`data${e.prop(this.key)}`,this.value)),this.hasKind("required")&&e.else(()=>e.traversalKind==="Apply"?e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):e.return(!1)),e.traversalKind==="Allows"&&e.return(!0)}},ri=(e,t)=>`Invalid intersection of default values ${N(e)} & ${N(t)}`,ii={implementation:z({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},default:{preserveUndefined:!0}},normalize:e=>e,reduce:(e,t)=>{if(t.resolvedConfig.exactOptionalPropertyTypes===!1&&!e.value.allows(void 0))return t.node("optional",{...e,value:e.value.or(Y.undefined)},{prereduced:!0})},defaults:{description:e=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:ti}}),Node:class extends ni{constructor(...e){super(...e),"default"in this.inner&&ci(this.value,this.inner.default,this.key)}get rawIn(){let e=super.rawIn;return this.hasDefault()?this.$.node("optional",Pe(e.inner,{default:!0}),{prereduced:!0}):e}get outProp(){if(!this.hasDefault())return this;let{default:e,...t}=this.inner;return this.cacheGetter("outProp",this.$.node("required",t,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${N(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=oi(this);defaultValueMorphRef=this.defaultValueMorph&&F(this.defaultValueMorph)}},ai={},oi=e=>{if(!e.hasDefault())return;let t=`{${e.compiledKey}: ${e.value.id} = ${On(e.default)}}`;return ai[t]??=si(e.key,e.value,e.default)},si=(e,t,n)=>{if(typeof n=="function")return t.includesTransform?(r,i)=>(V(e,()=>t(r[e]=n(),i),i),r):t=>(t[e]=n(),t);let r=t.includesTransform?t.assert(n):n;return Se(r,"object")?(r,i)=>(V(e,()=>t(r[e]=n,i),i),r):t=>(t[e]=r,t)},ci=(e,t,n)=>{let r=nt(t);Se(t,"object")&&!r&&E(li(n));let i=e.in(r?t():t);return i instanceof Ln&&(n===null&&E(`Default ${i.summary}`),E(`Default for ${i.transform(e=>e.transform(e=>({...e,prefixPath:[n]}))).summary}`)),t},li=e=>`Non-primitive default ${e===null?"":typeof e=="number"?`for value at [${e}] `:`for ${ln(e)} `}must be specified as a function like () => ({my: 'object'})`,ui=class extends Vn{constructor(e,t){super(e,t),Object.defineProperty(this,I,{value:"root",enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get"~standard"(){return{vendor:"arktype",version:1,validate:e=>{let t=this(e);return t instanceof Ln?t:{value:t}},jsonSchema:{input:e=>this.rawIn.toJsonSchema({target:mi(e.target),...e.libraryOptions}),output:e=>this.rawOut.toJsonSchema({target:mi(e.target),...e.libraryOptions})}}}as(){return this}brand(e){return e===""?E(di):this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(e,t){let n=this.branches.map(e);return t?.(n)??n}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(e={}){let t=Mn(this.$.resolvedConfig.toJsonSchema,e);t.useRefs||=this.isCyclic;let n=typeof t.dialect=="string"?{$schema:t.dialect}:{};if(Object.assign(n,this.toJsonSchemaRecurse(t)),t.useRefs){let e=D(this.references,(e,n)=>n.isRoot()&&!n.alwaysExpandJsonSchema?[n.id,n.toResolvedJsonSchema(t)]:[]);t.target==="draft-07"?Object.assign(n,{definitions:e}):n.$defs=e}return n}toJsonSchemaRecurse(e){return e.useRefs&&!this.alwaysExpandJsonSchema?{$ref:`#/${e.target==="draft-07"?"definitions":"$defs"}/${this.id}`}:this.toResolvedJsonSchema(e)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(e){let t=this.innerToJsonSchema(e);return Object.assign(t,this.metaJson)}intersect(e){let t=this.$.parseDefinition(e),n=this.rawIntersect(t);return n instanceof H?n:this.$.finalize(n)}rawIntersect(e){return U(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){let t=this.intersect(e);return t instanceof H?t.throw():t}rawAnd(e){let t=this.rawIntersect(e);return t instanceof H?t.throw():t}or(e){let t=this.$.parseDefinition(e);return this.$.finalize(this.rawOr(t))}rawOr(e){let t=[...this.branches,...e.branches];return this.$.node("union",t)}map(e){return this.$.schema(this.applyStructuralOperation("map",[e]))}pick(...e){return this.$.schema(this.applyStructuralOperation("pick",e))}omit(...e){return this.$.schema(this.applyStructuralOperation("omit",e))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.applyStructuralOperation("keyof",[]).reduce((e,t)=>e.intersect(t).toNeverIfDisjoint(),P.intrinsic.unknown.internal);return e.branches.length===0&&E($n(`keyof ${this.expression}`)),this._keyof=this.$.finalize(e)}get props(){return this.branches.length===1?[...this.applyStructuralOperation("props",[])[0]]:E(vi(this.expression))}merge(e){let t=this.$.parseDefinition(e);return this.$.schema(t.distribute(e=>this.applyStructuralOperation("merge",[_i(e)??E(yi("merge",e.expression))])))}applyStructuralOperation(e,t){return this.distribute(n=>{if(n.equals(P.intrinsic.object)&&e!=="merge")return n;let r=_i(n);if(r||E(yi(e,n.expression)),e==="keyof")return r.keyof();if(e==="get")return r.get(...t);if(e==="props")return r.props;let i=e==="required"?"require":e==="partial"?"optionalize":e;return this.$.node("intersection",{domain:"object",structure:r[i](...t)})})}get(...e){return e[0]===void 0?this:this.$.schema(this.applyStructuralOperation("get",e))}extract(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(e=>e.extends(t)))}exclude(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(e=>!e.extends(t)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(e){return!(this.intersect(e)instanceof H)}extends(e){if(this.isNever())return!0;let t=this.intersect(e);return!(t instanceof H)&&this.equals(t)}ifExtends(e){return this.extends(e)?this:void 0}subsumes(e){return this.$.parseDefinition(e).extends(this)}configure(e,t="shallow"){return this.configureReferences(e,t)}describe(e,t="shallow"){return this.configure({description:e},t)}optional(){return[this,"?"]}default(e){return ci(this,e,null),[this,"=",e]}from(e){return this.assert(e)}_pipe(...e){let t=e.reduce((e,t)=>e.rawPipeOnce(t),this);return this.$.finalize(t)}tryPipe(...e){let t=e.reduce((e,t)=>e.rawPipeOnce(L(t,"root")?t:(e,n)=>{try{return t(e,n)}catch(e){return n.error({code:"predicate",predicate:t,actual:`aborted due to error:\n ${e}\n`})}}),this);return this.$.finalize(t)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(e){return this.$.finalize(this.toNode(this.$.parseDefinition(e)))}toNode(e){let t=tr(this,e,this.$);return t instanceof H?t.throw():t}rawPipeOnce(e){return L(e,"root")?this.toNode(e):this.distribute(t=>t.hasKind("morph")?this.$.node("morph",{in:t.inner.in,morphs:[...t.morphs,e]}):this.$.node("morph",{in:t,morphs:[e]}),this.$.parseSchema)}narrow(e){return this.constrainOut("predicate",e)}constrain(e,t){return this._constrain("root",e,t)}constrainIn(e,t){return this._constrain("in",e,t)}constrainOut(e,t){return this._constrain("out",e,t)}_constrain(e,t,n){let r=this.$.node(t,n);if(r.isRoot())return r.isUnknown()?this:T(`Unexpected constraint node ${r}`);let i=e==="root"?this:e==="in"?this.rawIn:this.rawOut;if(i.hasKind("morph")||r.impliedBasis&&!i.extends(r.impliedBasis))return dr(t,r.impliedBasis,this);let a=this.$.node("intersection",{[r.kind]:r}),o=e==="out"?tr(this,a,this.$):U(this,a,this.$);return o instanceof H&&o.throw(),this.$.finalize(o)}onUndeclaredKey(e){let t=typeof e=="string"?e:e.rule,n=typeof e=="string"?!1:e.deep;return this.$.finalize(this.transform((e,n)=>e==="structure"?t==="ignore"?Pe(n,{undeclared:1}):{...n,undeclared:t}:n,n?void 0:{shouldTransform:e=>!b(gn,e.kind)}))}hasEqualMorphs(e){return!this.includesTransform&&!e.includesTransform?!0:!(!xe(this.shallowMorphs,e.shallowMorphs)||!xe(this.flatMorphs,e.flatMorphs,{isEqual:(e,t)=>e.propString===t.propString&&(e.node.hasKind("morph")&&t.node.hasKind("morph")?e.node.hasEqualMorphs(t.node):e.node.hasKind("intersection")&&t.node.hasKind("intersection")?e.node.structure?.structuralMorphRef===t.node.structure?.structuralMorphRef:!1)}))}onDeepUndeclaredKey(e){return this.onUndeclaredKey({rule:e,deep:!0})}filter(e){return this.constrainIn("predicate",e)}divisibleBy(e){return this.constrain("divisor",e)}matching(e){return this.constrain("pattern",e)}atLeast(e){return this.constrain("min",e)}atMost(e){return this.constrain("max",e)}moreThan(e){return this.constrain("min",hi(e))}lessThan(e){return this.constrain("max",hi(e))}atLeastLength(e){return this.constrain("minLength",e)}atMostLength(e){return this.constrain("maxLength",e)}moreThanLength(e){return this.constrain("minLength",hi(e))}lessThanLength(e){return this.constrain("maxLength",hi(e))}exactlyLength(e){return this.constrain("exactLength",e)}atOrAfter(e){return this.constrain("after",e)}atOrBefore(e){return this.constrain("before",e)}laterThan(e){return this.constrain("after",hi(e))}earlierThan(e){return this.constrain("before",hi(e))}},di="Expected a non-empty brand name after #",fi=["draft-2020-12","draft-07"],pi=e=>`JSONSchema target '${e}' is not supported (must be ${fi.map(e=>`"${e}"`).join(" or ")})`,mi=e=>(b(fi,e)||E(pi(e)),e),hi=e=>typeof e=="object"&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},gi=(e,t)=>L(t,"root")?L(e,"root")?e.extends(t):t.allows(e):L(e,"root")?e.hasUnit(t):t===e,_i=e=>e.hasKind("morph")?null:e.hasKind("intersection")?e.inner.structure??(e.basis?.domain==="object"?e.$.bindReference(P.intrinsic.emptyStructure):null):e.isBasis()&&e.domain==="object"?e.$.bindReference(P.intrinsic.emptyStructure):null,vi=e=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:\n${e}`,yi=(e,t)=>`${e} operand must be an object (was ${t})`,bi=(e,t)=>D(Dn(e),(e,n)=>[n,t]),xi=e=>typeof e=="string"?{reference:e}:e,Si=e=>e instanceof H?P.intrinsic.never.internal:e,Ci=z({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:e=>e.startsWith("$")?e:`$ark.${e}`},resolve:{}},normalize:xi,defaults:{description:e=>e.reference},intersections:{alias:(e,t,n)=>n.$.lazilyResolve(()=>Si(W(e.resolution,t.resolution,n)),`${e.reference}${n.pipe?"=>":"&"}${t.reference}`),...bi("alias",(e,t,n)=>t.isUnknown()?e:t.isNever()?t:t.isBasis()&&!t.overlaps(P.intrinsic.object)?H.init("assignability",P.intrinsic.object,t):n.$.lazilyResolve(()=>Si(W(e.resolution,t,n)),`${e.reference}${n.pipe?"=>":"&"}${t.id}`))}}),wi=class extends ui{expression=this.reference;structure=void 0;get resolution(){let e=this._resolve();return K[this.id]=e}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let e=K[this.reference],t=[];for(;L(e,"context");){if(t.includes(e.id))return E(Ti(e.id,t));t.push(e.id),e=K[e.id]}return L(e,"root")?e:T(`Unexpected resolution for reference ${this.reference}\nSeen: [${t.join("->")}] \nResolution: ${N(e)}`)}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let e=this.reference.slice(1),t=this.$.resolutions[e];return typeof t=="string"?t:L(t,"root")?t.id:T(`Unexpected resolution for reference ${this.reference}: ${N(t)}`)}get defaultShortDescription(){return w.object}innerToJsonSchema(e){return this.resolution.toJsonSchemaRecurse(e)}traverseAllows=(e,t)=>{let n=t.seen[this.reference];return n?.includes(e)?!0:(t.seen[this.reference]=x(n,e),this.resolution.traverseAllows(e,t))};traverseApply=(e,t)=>{let n=t.seen[this.reference];n?.includes(e)||(t.seen[this.reference]=x(n,e),this.resolution.traverseApply(e,t))};compile(e){let t=this.resolutionId;e.if(`ctx.seen.${t} && ctx.seen.${t}.includes(data)`,()=>e.return(!0)),e.if(`!ctx.seen.${t}`,()=>e.line(`ctx.seen.${t} = []`)),e.line(`ctx.seen.${t}.push(data)`),e.return(e.invoke(t))}},Ti=(e,t)=>`Alias '${e}' has a shallow resolution cycle: ${[...t,e].join("->")}`,Ei={implementation:Ci,Node:wi},Di=class extends ui{traverseApply=(e,t)=>{this.traverseAllows(e,t)||t.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return kn(this.errorContext)}compile(e){e.traversalKind==="Allows"?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}},Oi={implementation:z({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:e=>typeof e=="string"?{domain:e}:ke(e,"numberAllowsNaN")&&e.domain!=="number"?E(Oi.writeBadAllowNanMessage(e.domain)):e,applyConfig:(e,t)=>e.numberAllowsNaN===void 0&&e.domain==="number"&&t.numberAllowsNaN?{...e,numberAllowsNaN:!0}:e,defaults:{description:e=>w[e.domain],actual:e=>Number.isNaN(e)?"NaN":w[C(e)]},intersections:{domain:(e,t)=>e.domain==="number"&&t.domain==="number"?e.numberAllowsNaN?t:e:H.init("domain",e,t)}}),Node:class extends Di{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?e=>typeof e=="number"&&!Number.isNaN(e):e=>C(e)===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 w[this.domain]}innerToJsonSchema(e){return this.domain==="bigint"||this.domain==="symbol"?e.fallback.domain({code:"domain",base:{},domain:this.domain}):{type:this.domain}}},writeBadAllowNanMessage:e=>`numberAllowsNaN may only be specified with domain "number" (was ${e})`},ki={implementation:z({kind:"intersection",hasAssociatedError:!0,normalize:e=>{if(R(e))return e;let{structure:t,...n}=e,r=!!t,i=t??{},a=D(n,(e,t)=>O(e,Cn)?(r&&E(`Flattened structure key ${e} cannot be specified alongside a root 'structure' key.`),i[e]=t,[]):[e,t]);return(L(i,"constraint")||!Fe(i))&&(a.structure=i),a},finalizeInnerJson:({structure:e,...t})=>Se(e,"object")?{...e,...t}:t,keys:{domain:{child:!0,parse:(e,t)=>t.$.node("domain",e)},proto:{child:!0,parse:(e,t)=>t.$.node("proto",e)},structure:{child:!0,parse:(e,t)=>t.$.node("structure",e),serialize:e=>{if(!e.sequence?.minLength)return e.collapsibleJson;let{sequence:t,...n}=e.collapsibleJson,{minVariadicLength:r,...i}=t,a=i.variadic&&Object.keys(i).length===1?i.variadic:i;return{...n,sequence:a}}},divisor:{child:!0,parse:G("divisor")},max:{child:!0,parse:G("max")},min:{child:!0,parse:G("min")},maxLength:{child:!0,parse:G("maxLength")},minLength:{child:!0,parse:G("minLength")},exactLength:{child:!0,parse:G("exactLength")},before:{child:!0,parse:G("before")},after:{child:!0,parse:G("after")},pattern:{child:!0,parse:G("pattern")},predicate:{child:!0,parse:G("predicate")}},reduce:(e,t)=>ji({},e,{$:t,invert:!1,pipe:!1}),defaults:{description:e=>{if(e.children.length===0)return"unknown";if(e.structure)return e.structure.description;let t=[];if(e.basis&&!e.prestructurals.some(e=>e.impl.obviatesBasisDescription)&&t.push(e.basis.description),e.prestructurals.length){let n=e.prestructurals.slice().sort((e,t)=>e.kind==="min"&&t.kind==="max"?-1:0).map(e=>e.description);t.push(...n)}return e.inner.predicate&&t.push(...e.inner.predicate.map(e=>e.description)),t.join(" and ")},expected:e=>` ◦ ${e.errors.map(e=>e.expected).join("\n ◦ ")}`,problem:e=>`(${e.actual}) must be...\n${e.expected}`},intersections:{intersection:(e,t,n)=>ji(e.inner,t.inner,n),...bi("intersection",(e,t,n)=>{if(e.children.length===0)return t;let{domain:r,proto:i,...a}=e.inner,o=i??r,s=o?W(o,t,n):t;return s instanceof H?s:e?.basis?.equals(s)?e:e.$.node("intersection",{...a,[s.kind]:s},{prereduced:!0})})}}),Node:class extends ui{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter(e=>e.isRefinement()?(b(_n,e.kind)&&this.prestructurals.push(e),!0):!1);structure=this.inner.structure;expression=Ai(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(e){return this.children.reduce((t,n)=>n.isBasis()?n.toJsonSchemaRecurse(e):n.reduceJsonSchema(t,e),{})}traverseAllows=(e,t)=>this.children.every(n=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=t.currentErrorCount;if(!(this.basis&&(this.basis.traverseApply(e,t),t.currentErrorCount>n))){if(this.prestructurals.length){for(let r=0;r<this.prestructurals.length-1;r++)if(this.prestructurals[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(e,t),t.currentErrorCount>n)return}if(!(this.structure&&(this.structure.traverseApply(e,t),t.currentErrorCount>n))&&this.inner.predicate){for(let r=0;r<this.inner.predicate.length-1;r++)if(this.inner.predicate[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;this.inner.predicate[this.inner.predicate.length-1].traverseApply(e,t)}}};compile(e){if(e.traversalKind==="Allows"){for(let t of this.children)e.check(t);e.return(!0);return}if(e.initializeErrorCount(),this.basis&&(e.check(this.basis),this.children.length>1&&e.returnIfFail()),this.prestructurals.length){for(let t=0;t<this.prestructurals.length-1;t++)e.check(this.prestructurals[t]),e.returnIfFailFast();e.check(this.prestructurals[this.prestructurals.length-1]),(this.structure||this.inner.predicate)&&e.returnIfFail()}if(this.structure&&(e.check(this.structure),this.inner.predicate&&e.returnIfFail()),this.inner.predicate){for(let t=0;t<this.inner.predicate.length-1;t++)e.check(this.inner.predicate[t]),e.returnIfFail();e.check(this.inner.predicate[this.inner.predicate.length-1])}}}},Ai=e=>{if(e.structure?.expression)return e.structure.expression;let t=e.basis&&!e.prestructurals.some(e=>e.impl.obviatesBasisExpression)?e.basis.nestableExpression:"",n=e.prestructurals.map(e=>e.expression).join(" & "),r=`${t}${t?" ":""}${n}`;return r==="Array == 0"?"[]":r||"unknown"},ji=(e,t,n)=>{let r={},i=e.proto??e.domain,a=t.proto??t.domain,o=i?a?W(i,a,n):i:a;return o instanceof H?o:(o&&(r[o.kind]=o),cr({kind:"intersection",baseInner:r,l:lr(e),r:lr(t),roots:[],ctx:n}))},Mi={implementation:z({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},morphs:{parse:me,serialize:e=>e.map(e=>L(e,"root")?e.json:F(e))},declaredIn:{child:!1,serialize:e=>e.json},declaredOut:{child:!1,serialize:e=>e.json}},normalize:e=>e,defaults:{description:e=>`a morph from ${e.rawIn.description} to ${e.rawOut?.description??"unknown"}`},intersections:{morph:(e,t,n)=>{if(!e.hasEqualMorphs(t))return E(Ni(e.expression,t.expression));let r=W(e.rawIn,t.rawIn,n);if(r instanceof H)return r;let i={morphs:e.morphs};if(e.declaredIn||t.declaredIn){let r=W(e.rawIn,t.rawIn,n);if(r instanceof H)return r.throw();i.declaredIn=r}if(e.declaredOut||t.declaredOut){let r=W(e.rawOut,t.rawOut,n);if(r instanceof H)return r.throw();i.declaredOut=r}return r.distribute(e=>n.$.node("morph",{...i,in:e}),n.$.parseSchema)},...bi("morph",(e,t,n)=>{let r=e.inner.in?W(e.inner.in,t,n):t;return r instanceof H?r:r.equals(e.inner.in)?e:n.$.node("morph",{...e.inner,in:r})})}}),Node:class extends ui{serializedMorphs=this.morphs.map(F);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=L(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.rawOut:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get rawIn(){return this.declaredIn??this.inner.in?.rawIn??P.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??P.intrinsic.unknown.internal}declareIn(e){return this.$.node("morph",{...this.inner,declaredIn:e})}declareOut(e){return this.$.node("morph",{...this.inner,declaredOut:e})}expression=`(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.rawOut.expression}>`;get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(e){return e.fallback.morph({code:"morph",base:this.rawIn.toJsonSchemaRecurse(e),out:this.introspectableOut?.toJsonSchemaRecurse(e)??null})}compile(e){if(e.traversalKind==="Allows"){if(!this.introspectableIn)return;e.return(e.invoke(this.introspectableIn));return}this.introspectableIn&&e.line(e.invoke(this.introspectableIn)),e.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(e,t)=>!this.introspectableIn||this.introspectableIn.traverseAllows(e,t);traverseApply=(e,t)=>{this.introspectableIn&&this.introspectableIn.traverseApply(e,t),t.queueMorphs(this.morphs)};hasEqualMorphs(e){return xe(this.morphs,e.morphs,{isEqual:(e,t)=>e===t||L(e,"root")&&L(t,"root")&&e.equals(t)})}}},Ni=(e,t)=>`The intersection of distinct morphs at a single path is indeterminate:\nLeft: ${e}\nRight: ${t}`,Pi={implementation:z({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:e=>Ze(e)??On(e)},dateAllowsInvalid:{}},normalize:e=>{let t=typeof e=="string"?{proto:We[e]}:typeof e=="function"?R(e)?e:{proto:e}:typeof e.proto=="string"?{...e,proto:We[e.proto]}:e;return typeof t.proto!="function"&&E(Pi.writeInvalidSchemaMessage(t.proto)),ke(t,"dateAllowsInvalid")&&t.proto!==Date&&E(Pi.writeBadInvalidDateMessage(t.proto)),t},applyConfig:(e,t)=>e.dateAllowsInvalid===void 0&&e.proto===Date&&t.dateAllowsInvalid?{...e,dateAllowsInvalid:!0}:e,defaults:{description:e=>e.builtinName?Xe[e.builtinName]:`an instance of ${e.proto.name}`,actual:e=>e instanceof Date&&e.toString()==="Invalid Date"?"an invalid Date":Ke(e)},intersections:{proto:(e,t)=>e.proto===Date&&t.proto===Date?e.dateAllowsInvalid?t:e:Qe(e.proto,t.proto)?e:Qe(t.proto,e.proto)?t:H.init("proto",e,t),domain:(e,t)=>t.domain==="object"?e:H.init("domain",P.intrinsic.object.internal,t)}}),Node:class extends Di{builtinName=Ze(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?e=>e instanceof Date&&e.toString()!=="Invalid Date":e=>e instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(e){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return e.fallback.date?.({code:"date",base:{}})??e.fallback.proto({code:"proto",base:{},proto:this.proto});default:return e.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}},writeBadInvalidDateMessage:e=>`dateAllowsInvalid may only be specified with constructor Date (was ${e.name})`,writeInvalidSchemaMessage:e=>`instanceOf operand must be a function (was ${C(e)})`},Fi=z({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(e,t)=>{let n=[];for(let r of e){let e=L(r,"root")?r.branches:t.$.parseSchema(r).branches;for(let r of e)if(r.hasKind("morph")){let e=n.findIndex(e=>e.hasKind("morph")&&e.hasEqualMorphs(r));if(e===-1)n.push(r);else{let i=n[e];n[e]=t.$.node("morph",{...i.inner,in:i.rawIn.rawOr(r.rawIn)})}}else n.push(r)}return t.def.ordered||n.sort((e,t)=>e.hash<t.hash?-1:1),n}}},normalize:e=>A(e)?{branches:e}:e,reduce:(e,t)=>{let n=Xi(e);if(n.length===1)return n[0];if(n.length!==e.branches.length)return t.node("union",{...e,branches:n},{prereduced:!0})},defaults:{description:e=>e.distribute(e=>e.description,Ji),expected:e=>{let t=be(e.errors,"propString");return Ji(Object.entries(t).map(([e,t])=>{let n=[];for(let e of t)S(n,e.expected);let r=Ji(n),i=t.every(e=>e.actual===t[0].actual)?t[0].actual:N(t[0].data);return`${e&&`${e} `}must be ${r}${i&&` (was ${i})`}`}))},problem:e=>e.expected,message:e=>e.problem[0]==="["?`value at ${e.problem}`:e.problem},intersections:{union:(e,t,n)=>{if(e.isNever!==t.isNever)return H.init("presence",e,t);let r;return e.ordered?(t.ordered&&E(ea(e.expression,t.expression)),r=Yi(t.branches,e.branches,n),r instanceof H&&r.invert()):r=Yi(e.branches,t.branches,n),r instanceof H?r:n.$.parseSchema(e.ordered||t.ordered?{branches:r,ordered:!0}:{branches:r})},...bi("union",(e,t,n)=>{let r=Yi(e.branches,[t],n);return r instanceof H?r:r.length===1?r[0]:n.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}}),Ii=class extends ui{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let e=[],t=-1;for(let n of this.branches){if(n.hasKind("unit")&&n.domain==="boolean"){t===-1?(t=e.length,e.push(n)):e[t]=P.intrinsic.boolean;continue}e.push(n)}return e}unitBranches=this.branches.filter(e=>e.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?Gi(this.discriminant):null;expression=this.distribute(e=>e.nestableExpression,qi);createBranchedOptimisticRootApply(){return(e,t)=>{let n=this.traverseOptimistic(e);if(n!==k)return n;let r=new Bn(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize(t)}}get shallowMorphs(){return this.branches.reduce((e,t)=>S(e,t.shallowMorphs),[])}get defaultShortDescription(){return this.distribute(e=>e.defaultShortDescription,Ji)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(P.intrinsic.boolean))return{type:"boolean"};let t=this.branchGroups.map(t=>t.toJsonSchemaRecurse(e));return t.every(e=>Object.keys(e).length===1&&ke(e,"const"))?{enum:t.map(e=>e.const)}:{anyOf:t}}traverseAllows=(e,t)=>this.branches.some(n=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=[];for(let r=0;r<this.branches.length;r++){if(t.pushBranch(),this.branches[r].traverseApply(e,t),!t.hasError())return this.branches[r].includesTransform?t.queuedMorphs.push(...t.popBranch().queuedMorphs):t.popBranch();n.push(t.popBranch().error)}t.errorFromNodeContext({code:"union",errors:n,meta:this.meta})};traverseOptimistic=e=>{for(let t=0;t<this.branches.length;t++){let n=this.branches[t];if(n.traverseAllows(e))return n.contextFreeMorph?n.contextFreeMorph(e):e}return k};compile(e){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(e);let t=this.discriminant.optionallyChainedPropString;this.discriminant.kind==="domain"&&(t=`typeof ${t} === "object" ? ${t} === null ? "null" : "object" : typeof ${t} === "function" ? "object" : typeof ${t}`);let n=this.discriminant.cases,r=Object.keys(n),{optimistic:i}=e;if(e.optimistic=!1,e.block(`switch(${t})`,()=>{for(let t in n){let r=n[t],a=t==="default"?t:`case ${t}`,o;o=r===!0?i?"data":"true":i?r.rootApplyStrategy==="branchedOptimistic"?e.invoke(r,{kind:"Optimistic"}):r.contextFreeMorph?`${e.invoke(r)} ? ${F(r.contextFreeMorph)}(data) : "${k}"`:`${e.invoke(r)} ? data : "${k}"`:e.invoke(r),e.line(`${a}: return ${o}`)}return e}),e.traversalKind==="Allows"){e.return(i?`"${k}"`:!1);return}let a=Ji(this.discriminant.kind==="domain"?r.map(e=>{let t=e.slice(1,-1);return t==="function"?w.object:w[t]}):r),o=this.discriminant.path.map(e=>typeof e=="symbol"?F(e):JSON.stringify(e)),s=JSON.stringify(a),c=this.discriminant.kind==="domain"?`${Hi}[${t}]`:`${Ui}(${t})`;e.line(`ctx.errorFromNodeContext({\n\tcode: "predicate",\n\texpected: ${s},\n\tactual: ${c},\n\trelativePath: [${o}],\n\tmeta: ${this.compiledMeta}\n})`)}compileIndiscriminable(e){if(e.traversalKind==="Apply"){e.const("errors","[]");for(let t of this.branches)e.line("ctx.pushBranch()").line(e.invoke(t)).if("!ctx.hasError()",()=>e.return(t.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");e.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:t}=e;e.optimistic=!1;for(let n of this.branches)e.if(`${e.invoke(n)}`,()=>e.return(t?n.contextFreeMorph?`${F(n.contextFreeMorph)}(data)`:"data":!0));e.return(t?`"${k}"`:!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)return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:D(this.unitBranches,(e,t)=>[`${t.rawIn.serializedValue}`,t.hasKind("morph")?t:!0])};let e=[];for(let t=0;t<this.branches.length-1;t++){let n=this.branches[t];for(let r=t+1;r<this.branches.length;r++){let i=this.branches[r],a=U(n.rawIn,i.rawIn,n.$);if(a instanceof H)for(let n of a){if(!n.kind||n.optional)continue;let i,a;if(n.kind==="domain"){let e=n.l,t=n.r;i=`"${typeof e=="string"?e:e.domain}"`,a=`"${typeof t=="string"?t:t.domain}"`}else if(n.kind==="unit")i=n.l.serializedValue,a=n.r.serializedValue;else continue;let o=e.find(e=>xe(e.path,n.path)&&e.kind===n.kind);o?(o.cases[i]?o.cases[i].branchIndices=S(o.cases[i].branchIndices,t):o.cases[i]??={branchIndices:[t],condition:n.l},o.cases[a]?o.cases[a].branchIndices=S(o.cases[a].branchIndices,r):o.cases[a]??={branchIndices:[r],condition:n.r}):e.push({kind:n.kind,cases:{[i]:{branchIndices:[t],condition:n.l},[a]:{branchIndices:[r],condition:n.r}},path:n.path})}}}let t=this.ordered?zi(e,this.branches):e;if(!t.length)return null;let n=Li(t,this),r={};for(let e in n.best.cases){let t=Ri(n,e);if(t===null){r[e]=!0;continue}if(t.length===this.branches.length)return null;this.ordered&&t.sort((e,t)=>e.originalIndex-t.originalIndex);let i=t.map(e=>e.branch),a=i.length===1?i[0]:this.$.node("union",this.ordered?{branches:i,ordered:!0}:i);Object.assign(this.referencesById,a.referencesById),r[e]=a}if(n.defaultEntries.length){let e=n.defaultEntries.map(e=>e.branch);r.default=this.$.node("union",this.ordered?{branches:e,ordered:!0}:e,{prereduced:!0}),Object.assign(this.referencesById,r.default.referencesById)}return Object.assign(n.location,{cases:r})}},Li=(e,t)=>{let n=e.sort((e,t)=>e.path.length===t.path.length?Object.keys(t.cases).length-Object.keys(e.cases).length:e.path.length-t.path.length)[0];return{best:n,location:{kind:n.kind,path:n.path,optionallyChainedPropString:Vi(n.path)},defaultEntries:t.branches.map((e,t)=>({originalIndex:t,branch:e})),node:t}},Ri=(e,t)=>{let n=e.best.cases[t],r=Bi(n.condition,e.location.path,e.node.$),i=[],a=[];for(let t=0;t<e.defaultEntries.length;t++){let o=e.defaultEntries[t];if(n.branchIndices.includes(o.originalIndex)){let t=Qi(e.node.branches[o.originalIndex],e.location);t===null?i=null:i?.push({originalIndex:o.originalIndex,branch:t})}else if(o.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")i?.push(o);else{if(o.branch.rawIn.overlaps(r)){let t=Qi(o.branch,e.location);i?.push({originalIndex:o.originalIndex,branch:t})}a.push(o)}}return e.defaultEntries=a,i},zi=(e,t)=>e.filter(e=>{let n=Object.values(e.cases).map(e=>e.branchIndices);for(let e=0;e<n.length-1;e++){let r=n[e];for(let i=e+1;i<n.length;i++){let e=n[i];for(let n of r)for(let r of e)if(n>r&&t[n].overlaps(t[r]))return!1}}return!0}),Bi=(e,t,n)=>{let r=e==="undefined"?n.node("unit",{unit:void 0}):e==="null"?n.node("unit",{unit:null}):e==="boolean"?n.units([!0,!1]):e;for(let e=t.length-1;e>=0;e--){let i=t[e];r=n.node("intersection",typeof i=="number"?{proto:"Array",sequence:[..._e(i).map(e=>({})),r]}:{domain:"object",required:[{key:i,value:r}]})}return r},Vi=e=>e.reduce((e,t)=>e+un(t,!0),"data"),Hi=F(Ce),Ui=F(N),Wi={implementation:Fi,Node:Ii},Gi=e=>({kind:e.kind,path:e.path.map(e=>typeof e=="string"?e:ln(e)),cases:D(e.cases,(e,t)=>[e,t===!0?t:t.hasKind("union")&&t.discriminantJson?t.discriminantJson:t.json])}),Ki={delimiter:" | ",finalDelimiter:" | "},qi=e=>Ji(e,Ki),Ji=(e,t)=>{let n=t?.delimiter??", ",r=t?.finalDelimiter??" or ";if(e.length===0)return"never";if(e.length===1)return e[0];if(e.length===2&&e[0]==="false"&&e[1]==="true"||e[0]==="true"&&e[1]==="false")return"boolean";let i={},a=e.filter(e=>i[e]?!1:i[e]=!0),o=a.pop();return`${a.join(n)}${a.length?r:""}${o}`},Yi=(e,t,n)=>{let r=t.map(()=>[]);for(let i=0;i<e.length;i++){let a={};for(let o=0;o<t.length;o++){if(r[o]===null)continue;if(e[i].equals(t[o])){r[o]=null,a={};break}let s=W(e[i],t[o],n);if(!(s instanceof H)){if(s.equals(e[i])){r[o].push(e[i]),a={};break}s.equals(t[o])?r[o]=null:a[o]=s}}for(let e in a)r[e][i]=a[e]}let i=r.flatMap((e,n)=>e?.flatMap(e=>e.branches)??t[n]);return i.length===0?H.init("union",e,t):i},Xi=({branches:e,ordered:t})=>{if(e.length<2)return e;let n=e.map(()=>!0);for(let r=0;r<e.length;r++)for(let i=r+1;i<e.length&&n[r]&&n[i];i++){if(e[r].equals(e[i])){n[i]=!1;continue}let a=U(e[r].rawIn,e[i].rawIn,e[0].$);a instanceof H||(t||Zi(e[r],e[i]),a.equals(e[r].rawIn)?n[r]=!!t:a.equals(e[i].rawIn)&&(n[i]=!1))}return e.filter((e,t)=>n[t])},Zi=(e,t)=>{!e.includesTransform&&!t.includesTransform||(xe(e.shallowMorphs,t.shallowMorphs)||E($i(e.expression,t.expression)),xe(e.flatMorphs,t.flatMorphs,{isEqual:(e,t)=>e.propString===t.propString&&(e.node.hasKind("morph")&&t.node.hasKind("morph")?e.node.hasEqualMorphs(t.node):e.node.hasKind("intersection")&&t.node.hasKind("intersection")?e.node.structure?.structuralMorphRef===t.node.structure?.structuralMorphRef:!1)})||E($i(e.expression,t.expression)))},Qi=(e,t)=>e.transform((e,t)=>e==="domain"||e==="unit"?null:t,{shouldTransform:(e,n)=>{let r=Vi(n.path);return t.optionallyChainedPropString.startsWith(r)?e.hasKind("domain")&&e.domain==="object"||(e.hasKind("domain")||t.kind==="unit")&&r===t.optionallyChainedPropString?!0:e.children.length!==0&&e.kind!=="index":!1}}),$i=(e,t)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:\nLeft: ${e}\nRight: ${t}`,ea=(e,t)=>`The intersection of two ordered unions is indeterminate:\nLeft: ${e}\nRight: ${t}`,ta={implementation:z({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:e=>e instanceof Date?e.toISOString():On(e)}},normalize:e=>e,defaults:{description:e=>N(e.unit),problem:({expected:e,actual:t})=>`${e===t?`must be reference equal to ${e} (serialized to the same value)`:`must be ${e} (was ${t})`}`},intersections:{unit:(e,t)=>H.init("unit",e,t),...bi("unit",(e,t)=>{if(t.allows(e.unit))return e;let n=t.hasKind("intersection")?t.basis:t;if(n){let t=n.hasKind("domain")?n:P.intrinsic.object;if(e.domain!==t.domain){let n=e.domain==="undefined"||e.domain==="null"||e.domain==="boolean"?e.domain:P.intrinsic[e.domain];return H.init("domain",n,t)}}return H.init("assignability",e,t.hasKind("intersection")?t.children.find(t=>!t.allows(e.unit)):t)})}}),Node:class extends Di{compiledValue=this.json.unit;serializedValue=typeof this.unit=="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=na(this.unit,this.serializedValue);compiledNegation=na(this.unit,this.serializedValue,"negated");expression=N(this.unit);domain=C(this.unit);get defaultShortDescription(){return this.domain==="object"?w.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:"null"}:P.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:e.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?e=>e instanceof Date&&e.toISOString()===this.compiledValue:Number.isNaN(this.unit)?e=>Number.isNaN(e):e=>e===this.unit}},na=(e,t,n)=>{if(e instanceof Date){let e=`data instanceof Date && data.toISOString() === ${t}`;return n?`!(${e})`:e}return Number.isNaN(e)?`${n?"!":""}Number.isNaN(data)`:`data ${n?"!":"="}== ${t}`},ra={implementation:z({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{let n=t.$.parseSchema(e);if(!n.extends(P.intrinsic.key))return E(aa(n.expression));let r=n.branches.filter(e=>e.hasKind("unit"));return r.length?E(ia(r.map(e=>N(e.unit)))):n}},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:e=>e,defaults:{description:e=>`[${e.signature.expression}]: ${e.value.description}`},intersections:{index:(e,t,n)=>{if(e.signature.equals(t.signature)){let r=W(e.value,t.value,n),i=r instanceof H?P.intrinsic.never.internal:r;return n.$.node("index",{signature:e.signature,value:i})}return e.signature.extends(t.signature)&&e.value.subsumes(t.value)?t:t.signature.extends(e.signature)&&t.value.subsumes(e.value)?e:null}}}),Node:class extends or{impliedBasis=P.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=x(this.value.flatRefs.map(e=>qn([this.signature,...e.path],e.node)),qn([this.signature],this.value));traverseAllows=(e,t)=>Ie(e).every(e=>this.signature.traverseAllows(e[0],t)?V(e[0],()=>this.value.traverseAllows(e[1],t),t):!0);traverseApply=(e,t)=>{for(let n of Ie(e))this.signature.traverseAllows(n[0],t)&&V(n[0],()=>this.value.traverseApply(n[1],t),t)};_transform(e,t){t.path.push(this.signature);let n=super._transform(e,t);return t.path.pop(),n}compile(){}}},ia=e=>`Index keys ${e.join(", ")} should be specified as named props.`,aa=e=>`Indexed key definition '${e}' must be a string or symbol`,oa={implementation:z({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:e=>e,defaults:{description:e=>`${e.compiledKey}: ${e.value.description}`,expected:e=>e.missingValueDescription,actual:()=>"missing"},intersections:{required:ti,optional:ti}}),Node:class extends ni{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=kn(this.errorContext)}},sa=z({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}},optionals:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}},defaultables:{child:e=>e.map(e=>e[0]),parse:(e,t)=>{if(e.length!==0)return e.map(e=>{let n=t.$.parseSchema(e[0]);return ci(n,e[1],null),[n,e[1]]})},serialize:e=>e.map(e=>[e[0].collapsibleJson,On(e[1])]),reduceIo:(e,t,n)=>{if(e==="in"){t.optionals=n.map(e=>e[0].rawIn);return}t.prefix=n.map(e=>e[0].rawOut)}},variadic:{child:!0,parse:(e,t)=>t.$.parseSchema(e,t)},minVariadicLength:{parse:e=>e===0?void 0:e},postfix:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}}},normalize:e=>{if(typeof e=="string")return{variadic:e};if("variadic"in e||"prefix"in e||"defaultables"in e||"optionals"in e||"postfix"in e||"minVariadicLength"in e){if(e.postfix?.length){if(!e.variadic)return E(ha);if(e.optionals?.length||e.defaultables?.length)return E(ma)}return e.minVariadicLength&&!e.variadic?E("minVariadicLength may not be specified without a variadic element"):e}return{variadic:e}},reduce:(e,t)=>{let n=e.minVariadicLength??0,r=e.prefix?.slice()??[],i=e.defaultables?.slice()??[],a=e.optionals?.slice()??[],o=e.postfix?.slice()??[];if(e.variadic){for(;a[a.length-1]?.equals(e.variadic);)a.pop();if(a.length===0&&i.length===0)for(;r[r.length-1]?.equals(e.variadic);)r.pop(),n++;for(;o[0]?.equals(e.variadic);)o.shift(),n++}else a.length===0&&i.length===0&&r.push(...o.splice(0));if(n!==e.minVariadicLength||e.prefix&&e.prefix.length!==r.length)return t.node("sequence",{...e,prefix:r,defaultables:i,optionals:a,postfix:o,minVariadicLength:n},{prereduced:!0})},defaults:{description:e=>e.isVariadicOnly?`${e.variadic.nestableExpression}[]`:`[${e.tuple.map(e=>e.kind==="defaultables"?`${e.node.nestableExpression} = ${N(e.default)}`:e.kind==="optionals"?`${e.node.nestableExpression}?`:e.kind==="variadic"?`...${e.node.nestableExpression}[]`:e.node.expression).join(", ")}]`},intersections:{sequence:(e,t,n)=>{let r=ga({l:e.tuple,r:t.tuple,disjoint:new H,result:[],fixedVariants:[],ctx:n}),i=r.disjoint.length===0?[r,...r.fixedVariants]:r.fixedVariants;return i.length===0?r.disjoint:i.length===1?n.$.node("sequence",pa(i[0].result)):n.$.node("union",i.map(e=>({proto:Array,sequence:pa(e.result)})))}}}),ca=class extends or{impliedBasis=P.intrinsic.Array.internal;tuple=fa(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(e=>e.kind==="defaultables"||e.kind==="optionals"?(this.defaultablesAndOptionals.push(e.node),!0):e.kind==="prefix");variadicOrPostfix=ve(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return Yn(this.flatRefs,this.prevariadic.flatMap((e,t)=>x(e.node.flatRefs.map(e=>qn([`${t}`,...e.path],e.node)),qn([`${t}`],e.node)))),Yn(this.flatRefs,this.variadicOrPostfix.flatMap(e=>x(e.flatRefs.map(e=>qn([P.intrinsic.nonNegativeIntegerString.internal,...e.path],e.node)),qn([P.intrinsic.nonNegativeIntegerString.internal],e)))),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=ua(this);defaultValueMorphsReference=this.defaultValueMorphs.length?F(this.defaultValueMorphs):void 0;elementAtIndex(e,t){if(t<this.prevariadic.length)return this.tuple[t];let n=e.length-this.postfixLength;return t>=n?{kind:"postfix",node:this.postfix[t-n]}:{kind:"variadic",node:this.variadic??T(`Unexpected attempt to access index ${t} on ${this}`)}}traverseAllows=(e,t)=>{for(let n=0;n<e.length;n++)if(!this.elementAtIndex(e,n).node.traverseAllows(e[n],t))return!1;return!0};traverseApply=(e,t)=>{let n=0;for(;n<e.length;n++)V(n,()=>this.elementAtIndex(e,n).node.traverseApply(e[n],t),t)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(e){if(this.prefix)for(let[t,n]of this.prefix.entries())e.traverseKey(`${t}`,`data[${t}]`,n);for(let[t,n]of this.defaultablesAndOptionals.entries()){let r=`${t+this.prefixLength}`;e.if(`${r} >= data.length`,()=>e.traversalKind==="Allows"?e.return(!0):e.return()),e.traverseKey(r,`data[${r}]`,n)}if(this.variadic&&(this.postfix&&e.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`),e.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>e.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix))for(let[t,n]of this.postfix.entries()){let r=`firstPostfixIndex + ${t}`;e.traverseKey(r,`data[${r}]`,n)}e.traversalKind==="Allows"&&e.return(!0)}_transform(e,t){t.path.push(P.intrinsic.nonNegativeIntegerString.internal);let n=super._transform(e,t);return t.path.pop(),n}expression=this.description;reduceJsonSchema(e,t){let n=t.target==="draft-07";if(this.prevariadic.length){let r=this.prevariadic.map(e=>{let n=e.node.toJsonSchemaRecurse(t);if(e.kind==="defaultables"){let r=typeof e.default=="function"?e.default():e.default;n.default=P.intrinsic.jsonData.allows(r)?r:t.fallback.defaultValue({code:"defaultValue",base:n,value:r})}return n});n?e.items=r:e.prefixItems=r}if(this.minLength&&(e.minItems=this.minLength),this.variadic){let r=this.variadic.toJsonSchemaRecurse(t);if(n&&this.prevariadic.length?e.additionalItems=r:e.items=r,this.maxLength&&(e.maxItems=this.maxLength),this.postfix){let n=this.postfix.map(e=>e.toJsonSchemaRecurse(t));e=t.fallback.arrayPostfix({code:"arrayPostfix",base:e,elements:n})}}else n?e.additionalItems=!1:e.items=!1,delete e.maxItems;return e}},la={},ua=e=>{if(!e.defaultables)return[];let t=[],n="[",r=e.prefixLength+e.defaultablesLength-1;for(let i=e.prefixLength;i<=r;i++){let[r,a]=e.defaultables[i-e.prefixLength];t.push(si(i,r,a)),n+=`${i}: ${r.id} = ${On(a)}, `}return n+="]",la[n]??=t},da={implementation:sa,Node:ca},fa=e=>{let t=[];if(e.prefix)for(let n of e.prefix)t.push({kind:"prefix",node:n});if(e.defaultables)for(let[n,r]of e.defaultables)t.push({kind:"defaultables",node:n,default:r});if(e.optionals)for(let n of e.optionals)t.push({kind:"optionals",node:n});if(e.variadic&&t.push({kind:"variadic",node:e.variadic}),e.postfix)for(let n of e.postfix)t.push({kind:"postfix",node:n});return t},pa=e=>e.reduce((e,t)=>(t.kind==="variadic"?e.variadic=t.node:t.kind==="defaultables"?e.defaultables=x(e.defaultables,[[t.node,t.default]]):e[t.kind]=x(e[t.kind],t.node),e),{}),ma="A postfix required element cannot follow an optional or defaultable element",ha="A postfix element requires a variadic element",ga=e=>{let[t,...n]=e.l,[r,...i]=e.r;if(!t||!r)return e;let a=n[n.length-1]?.kind==="postfix",o=i[i.length-1]?.kind==="postfix",s=t.kind==="prefix"||r.kind==="prefix"?"prefix":t.kind==="postfix"||r.kind==="postfix"?"postfix":t.kind==="variadic"&&r.kind==="variadic"?"variadic":a||o?"prefix":t.kind==="defaultables"||r.kind==="defaultables"?"defaultables":"optionals";if(t.kind==="prefix"&&r.kind==="variadic"&&o){let t=ga({...e,fixedVariants:[],r:i.map(e=>({...e,kind:"prefix"}))});t.disjoint.length===0&&e.fixedVariants.push(t)}else if(r.kind==="prefix"&&t.kind==="variadic"&&a){let t=ga({...e,fixedVariants:[],l:n.map(e=>({...e,kind:"prefix"}))});t.disjoint.length===0&&e.fixedVariants.push(t)}let c=W(t.node,r.node,e.ctx);if(c instanceof H)if(s==="prefix"||s==="postfix")e.disjoint.push(...c.withPrefixKey(s==="prefix"?e.result.length:`-${n.length+1}`,_a(t)&&_a(r)?"required":"optional")),e.result=[...e.result,{kind:s,node:P.intrinsic.never.internal}];else if(s==="optionals"||s==="defaultables")return e;else return ga({...e,fixedVariants:[],l:n.map(e=>({...e,kind:"prefix"})),r:n.map(e=>({...e,kind:"prefix"}))});else s==="defaultables"?(t.kind==="defaultables"&&r.kind==="defaultables"&&t.default!==r.default&&E(ri(t.default,r.default)),e.result=[...e.result,{kind:s,node:c,default:t.kind==="defaultables"?t.default:r.kind==="defaultables"?r.default:T(`Unexpected defaultable intersection from ${t.kind} and ${r.kind} elements.`)}]):e.result=[...e.result,{kind:s,node:c}];let l=e.l.length,u=e.r.length;return(t.kind!=="variadic"||l>=u&&(r.kind==="variadic"||u===1))&&(e.l=n),(r.kind!=="variadic"||u>=l&&(t.kind==="variadic"||l===1))&&(e.r=i),ga(e)},_a=e=>e.kind==="prefix"||e.kind==="postfix",va=e=>t=>{if(t.props.length||t.index){let n=t.index?.map(t=>t[e])??[];for(let r of t.props)n.push(r[e]);t.undeclared&&n.push(`+ (undeclared): ${t.undeclared}`);let r=`{ ${n.join(", ")} }`;return t.sequence?`${r} & ${t.sequence.description}`:r}return t.sequence?.description??"{}"},ya=va("description"),ba=va("expression"),xa=(e,t,n)=>{let r=e.required?"required":"optional";if(!t.signature.allows(e.key))return null;let i=U(e.value,t.value,n);return i instanceof H?r==="optional"?n.node("optional",{key:e.key,value:P.intrinsic.never.internal}):i.withPrefixKey(e.key,e.kind):null},Sa=z({kind:"structure",hasAssociatedError:!1,normalize:e=>e,applyConfig:(e,t)=>!e.undeclared&&t.onUndeclaredKey!=="ignore"?{...e,undeclared:t.onUndeclaredKey}:e,keys:{required:{child:!0,parse:G("required"),reduceIo:(e,t,n)=>{t.required=x(t.required,n.map(t=>e==="in"?t.rawIn:t.rawOut))}},optional:{child:!0,parse:G("optional"),reduceIo:(e,t,n)=>{if(e==="in"){t.optional=n.map(e=>e.rawIn);return}for(let e of n)t[e.outProp.kind]=x(t[e.outProp.kind],e.outProp.rawOut)}},index:{child:!0,parse:G("index")},sequence:{child:!0,parse:G("sequence")},undeclared:{parse:e=>e==="ignore"?void 0:e,reduceIo:(e,t,n)=>{if(n==="reject"){t.undeclared="reject";return}e==="in"?delete t.undeclared:t.undeclared="reject"}}},defaults:{description:ya},intersections:{structure:(e,t,n)=>{let r={...e.inner},i={...t.inner},a=new H;if(e.undeclared){let r=e.keyof();for(let e of t.requiredKeys)r.allows(e)||a.add("presence",P.intrinsic.never.internal,t.propsByKey[e].value,{path:[e]});i.optional&&=i.optional.filter(e=>r.allows(e.key)),i.index&&=i.index.flatMap(e=>{if(e.signature.extends(r))return e;let t=U(r,e.signature,n.$);if(t instanceof H)return[];let a=ja(t,e.value,n.$);return a.required&&(i.required=ve(i.required,a.required)),a.optional&&(i.optional=ve(i.optional,a.optional)),a.index??[]})}if(t.undeclared){let i=t.keyof();for(let t of e.requiredKeys)i.allows(t)||a.add("presence",e.propsByKey[t].value,P.intrinsic.never.internal,{path:[t]});r.optional&&=r.optional.filter(e=>i.allows(e.key)),r.index&&=r.index.flatMap(e=>{if(e.signature.extends(i))return e;let t=U(i,e.signature,n.$);if(t instanceof H)return[];let a=ja(t,e.value,n.$);return a.required&&(r.required=ve(r.required,a.required)),a.optional&&(r.optional=ve(r.optional,a.optional)),a.index??[]})}let o={};(e.undeclared||t.undeclared)&&(o.undeclared=e.undeclared==="reject"||t.undeclared==="reject"?"reject":"delete");let s=cr({kind:"structure",baseInner:o,l:lr(r),r:lr(i),roots:[],ctx:n});return s instanceof H&&a.push(...s),a.length?a:s}},reduce:(e,t)=>{if(!e.required&&!e.optional)return;let n={},r=!1,i=e.optional?[...e.optional]:[];if(e.required)for(let r=0;r<e.required.length;r++){let i=e.required[r];if(i.key in n&&E(Pa(i.key)),n[i.key]=!0,e.index)for(let n of e.index){let e=xa(i,n,t);if(e instanceof H)return e}}if(e.optional)for(let a=0;a<e.optional.length;a++){let o=e.optional[a];if(o.key in n&&E(Pa(o.key)),n[o.key]=!0,e.index)for(let n of e.index){let e=xa(o,n,t);if(e instanceof H)return e;e!==null&&(i[a]=e,r=!0)}}if(r)return t.node("structure",{...e,optional:i},{prereduced:!0})}}),Ca=class extends or{impliedBasis=P.intrinsic.object.internal;impliedSiblings=this.children.flatMap(e=>e.impliedSiblings??[]);props=ve(this.required,this.optional);propsByKey=D(this.props,(e,t)=>[t.key,t]);propsByKeyReference=F(this.propsByKey);expression=ba(this);requiredKeys=this.required?.map(e=>e.key)??[];optionalKeys=this.optional?.map(e=>e.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:t}of this.index)e=e.concat(t.branches);return this._keyof=this.$.node("union",e)}map(e){return this.$.node("structure",this.props.flatMap(e).reduce((e,t)=>{let n=this.propsByKey[t.key];if(R(t))return t.kind!=="required"&&t.kind!=="optional"?E(`Map result must have kind "required" or "optional" (was ${t.kind})`):(e[t.kind]=x(e[t.kind],t),e);let r=t.kind??n?.kind??"required",i=D(t,(e,t)=>e in ii.implementation.keys?[e,t]:[]);return e[r]=x(e[r],this.$.node(r,i)),e},{}))}assertHasKeys(e){let t=e.filter(e=>!gi(e,this.keyof()));if(t.length)return E(Na(this.expression,t))}get(e,...t){let n,r=!1,i=ka(e);if((typeof i=="string"||typeof i=="symbol")&&this.propsByKey[i]&&(n=this.propsByKey[i].value,r=this.propsByKey[i].required),this.index)for(let e of this.index)gi(i,e.signature)&&(n=n?.and(e.value)??e.value);if(this.sequence&&gi(i,P.intrinsic.nonNegativeIntegerString))if(L(i,"root"))this.sequence.variadic&&(n=n?.and(this.sequence.element)??this.sequence.element);else{let e=Number.parseInt(i);if(e<this.sequence.prevariadic.length){let t=this.sequence.prevariadic[e].node;n=n?.and(t)??t,r||=e<this.sequence.prefixLength}else if(this.sequence.variadic){let e=this.$.node("union",this.sequence.variadicOrPostfix);n=n?.and(e)??e}}if(!n)return this.sequence?.variadic&&L(i,"root")&&i.extends(P.intrinsic.number)?E(Aa(i.expression,this.sequence.expression)):E(Na(this.expression,[i]));let a=n.get(...t);return r?a:a.or(P.intrinsic.undefined)}pick(...e){return this.assertHasKeys(e),this.$.node("structure",this.filterKeys("pick",e))}omit(...e){return this.assertHasKeys(e),this.$.node("structure",this.filterKeys("omit",e))}optionalize(){let{required:e,...t}=this.inner;return this.$.node("structure",{...t,optional:this.props.map(e=>e.hasKind("required")?this.$.node("optional",e.inner):e)})}require(){let{optional:e,...t}=this.inner;return this.$.node("structure",{...t,required:this.props.map(e=>e.hasKind("optional")?{key:e.key,value:e.value}:e)})}merge(e){let t=this.filterKeys("omit",[e.keyof()]);return e.required&&(t.required=x(t.required,e.required)),e.optional&&(t.optional=x(t.optional,e.optional)),e.index&&(t.index=x(t.index,e.index)),e.sequence&&(t.sequence=e.sequence),e.undeclared?t.undeclared=e.undeclared:delete t.undeclared,this.$.node("structure",t)}filterKeys(e,t){let n=mn(this.inner),r=n=>{let r=t.some(e=>gi(n,e));return e==="pick"?r:!r};return n.required&&=n.required.filter(e=>r(e.key)),n.optional&&=n.optional.filter(e=>r(e.key)),n.index&&=n.index.filter(e=>r(e.signature)),n}traverseAllows=(e,t)=>this._traverse("Allows",e,t);traverseApply=(e,t)=>this._traverse("Apply",e,t);_traverse=(e,t,n)=>{let r=n?.currentErrorCount??0;for(let i=0;i<this.props.length;i++)if(e==="Allows"){if(!this.props[i].traverseAllows(t,n))return!1}else if(this.props[i].traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1;if(this.sequence){if(e==="Allows"){if(!this.sequence.traverseAllows(t,n))return!1}else if(this.sequence.traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1}if(this.index||this.undeclared==="reject"){let i=Object.keys(t);i.push(...Object.getOwnPropertySymbols(t));for(let a=0;a<i.length;a++){let o=i[a];if(this.index){for(let i of this.index)if(i.signature.traverseAllows(o,n)){if(e==="Allows"){if(!V(o,()=>i.value.traverseAllows(t[o],n),n))return!1}else if(V(o,()=>i.value.traverseApply(t[o],n),n),n.failFast&&n.currentErrorCount>r)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(o)&&(e==="Allows"||(n.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[o],meta:this.meta}),n.failFast)))return!1}}return this.structuralMorph&&n&&!n.hasError()&&n.queueMorphs([this.structuralMorph]),!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter(e=>e.hasDefault())??[])}declaresKey=e=>e in this.propsByKey||this.index?.some(t=>t.signature.allows(e))||this.sequence!==void 0&&P.intrinsic.nonNegativeIntegerString.allows(e);_compileDeclaresKey(e){let t=[];if(this.props.length&&t.push(`k in ${this.propsByKeyReference}`),this.index)for(let n of this.index)t.push(e.invoke(n.signature,{kind:"Allows",arg:"k"}));return this.sequence&&t.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)"),t.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",Ea(this))}structuralMorphRef=this.structuralMorph&&F(this.structuralMorph);compile(e){e.traversalKind==="Apply"&&e.initializeErrorCount();for(let t of this.props)e.check(t),e.traversalKind==="Apply"&&e.returnIfFailFast();if(this.sequence&&(e.check(this.sequence),e.traversalKind==="Apply"&&e.returnIfFailFast()),(this.index||this.undeclared==="reject")&&(e.const("keys","Object.keys(data)"),e.line("keys.push(...Object.getOwnPropertySymbols(data))"),e.for("i < keys.length",()=>this.compileExhaustiveEntry(e))),e.traversalKind==="Allows")return e.return(!0);this.structuralMorphRef&&e.if("ctx && !ctx.hasError()",()=>(e.line("ctx.queueMorphs(["),Da(e,this),e.line("])")))}compileExhaustiveEntry(e){if(e.const("k","keys[i]"),this.index)for(let t of this.index)e.if(`${e.invoke(t.signature,{arg:"k",kind:"Allows"})}`,()=>e.traverseKey("k","data[k]",t.value));return this.undeclared==="reject"&&e.if(`!(${this._compileDeclaresKey(e)})`,()=>e.traversalKind==="Allows"?e.return(!1):e.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>e.return())),e}reduceJsonSchema(e,t){switch(e.type){case"object":return this.reduceObjectJsonSchema(e,t);case"array":let n=this.sequence?.reduceJsonSchema(e,t)??e;return this.props.length||this.index?t.fallback.arrayObject({code:"arrayObject",base:n,object:this.reduceObjectJsonSchema({type:"object"},t)}):n;default:return B.throwInternalOperandError("structure",e)}}reduceObjectJsonSchema(e,t){if(this.props.length){e.properties={};for(let n of this.props){let r=n.value.toJsonSchemaRecurse(t);if(typeof n.key=="symbol"){t.fallback.symbolKey({code:"symbolKey",base:e,key:n.key,value:r,optional:n.optional});continue}if(n.hasDefault()){let e=typeof n.default=="function"?n.default():n.default;r.default=P.intrinsic.jsonData.allows(e)?e:t.fallback.defaultValue({code:"defaultValue",base:r,value:e})}e.properties[n.key]=r}this.requiredKeys.length&&e.properties&&(e.required=this.requiredKeys.filter(t=>typeof t=="string"&&t in e.properties))}if(this.index)for(let n of this.index){let r=n.value.toJsonSchemaRecurse(t);if(n.signature.equals(P.intrinsic.string)){e.additionalProperties=r;continue}for(let i of n.signature.branches){if(!i.extends(P.intrinsic.string)){e=t.fallback.symbolKey({code:"symbolKey",base:e,key:null,value:r,optional:!1});continue}let n={type:"string"};if(i.hasKind("morph")&&(n=t.fallback.morph({code:"morph",base:i.rawIn.toJsonSchemaRecurse(t),out:i.rawOut.toJsonSchemaRecurse(t)})),!i.hasKind("intersection"))return T(`Unexpected index branch kind ${i.kind}.`);let{pattern:a}=i.inner;if(a){let i=Object.assign(n,{pattern:a[0].rule});for(let e=1;e<a.length;e++)n=t.fallback.patternIntersection({code:"patternIntersection",base:i,pattern:a[e].rule});e.patternProperties??={},e.patternProperties[i.pattern]=r}}}return this.undeclared&&!e.additionalProperties&&(e.additionalProperties=!1),e}},wa={},Ta=e=>{let t="";for(let n=0;n<e.defaultable.length;n++)t+=e.defaultable[n].defaultValueMorphRef;if(e.sequence?.defaultValueMorphsReference&&(t+=e.sequence?.defaultValueMorphsReference),e.undeclared==="delete"){if(t+="delete !(",e.required)for(let n of e.required)t+=n.compiledKey+" | ";if(e.optional)for(let n of e.optional)t+=n.compiledKey+" | ";if(e.index)for(let n of e.index)t+=n.signature.id+" | ";if(e.sequence)if(e.sequence.maxLength===null)t+=Y.nonNegativeIntegerString.id;else for(let n=0;n<e.sequence.tuple.length;n++)t+=n+" | ";t+=")"}return t},Ea=e=>{let t=Ta(e);return t?wa[t]?wa[t]:wa[t]=(t,n)=>{for(let r=0;r<e.defaultable.length;r++)e.defaultable[r].key in t||e.defaultable[r].defaultValueMorph(t,n);if(e.sequence?.defaultables)for(let r=t.length-e.sequence.prefixLength;r<e.sequence.defaultables.length;r++)e.sequence.defaultValueMorphs[r](t,n);if(e.undeclared==="delete")for(let n in t)e.declaresKey(n)||delete t[n];return t}:void 0},Da=(e,t)=>{let n=`(data${t.defaultable.some(e=>e.defaultValueMorph.length===2)||t.sequence?.defaultValueMorphs.some(e=>e.length===2)?", ctx":""})`;return e.block(`${n} => `,e=>{for(let r=0;r<t.defaultable.length;r++){let{serializedKey:i,defaultValueMorphRef:a}=t.defaultable[r];e.if(`!(${i} in data)`,e=>e.line(`${a}${n}`))}return t.sequence?.defaultables&&e.for(`i < ${t.sequence.defaultables.length}`,e=>e.set("data[i]",5),`data.length - ${t.sequence.prefixLength}`),t.undeclared==="delete"&&e.forIn("data",e=>e.if(`!(${t._compileDeclaresKey(e)})`,e=>e.line("delete data[k]"))),e.return("data")})},Oa={implementation:Sa,Node:Ca},ka=e=>(L(e,"root")&&e.hasKind("unit")&&(e=e.unit),typeof e=="number"&&(e=`${e}`),e),Aa=(e,t)=>`${e} is not allowed as an array index on ${t}. Use the 'nonNegativeIntegerString' keyword instead.`,ja=(e,t,n)=>{let[r,i]=he(e.branches,e=>e.hasKind("unit"));if(!r.length)return{index:n.node("index",{signature:e,value:t})};let a={};for(let e of r){let r=n.node("required",{key:e.unit,value:t});a[r.kind]=x(a[r.kind],r)}return i.length&&(a.index=n.node("index",{signature:i,value:t})),a},Ma=e=>L(e,"root")?e.expression:N(e),Na=(e,t)=>`Key${t.length===1?"":"s"} ${t.map(Ma).join(", ")} ${t.length===1?"does":"do"} not exist on ${e}`,Pa=e=>`Duplicate key ${ln(e)}`,Fa={...Vr,alias:Ei.implementation,domain:Oi.implementation,unit:ta.implementation,proto:Pi.implementation,union:Wi.implementation,morph:Mi.implementation,intersection:ki.implementation,divisor:vr.implementation,pattern:Ur.implementation,predicate:_r.implementation,required:oa.implementation,optional:ii.implementation,index:ra.implementation,sequence:da.implementation,structure:Oa.implementation};P.defaultConfig=Re(Object.assign(D(Fa,(e,t)=>[e,t.defaults]),{jitless:it(),clone:$e,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:B.defaultConfig})),P.resolvedConfig=An(P.defaultConfig,P.config);var Ia={...Hr,alias:Ei.Node,domain:Oi.Node,unit:ta.Node,proto:Pi.Node,union:Wi.Node,morph:Mi.Node,intersection:ki.Node,divisor:vr.Node,pattern:Ur.Node,predicate:_r.Node,required:oa.Node,optional:ii.Node,index:ra.Node,sequence:da.Node,structure:Oa.Node},La=class extends Ae{get[I](){return"module"}},Ra=(e,t)=>new La(D(e,(e,n)=>[e,L(n,"module")?Ra(n,t):t.bindReference(n)])),za=e=>A(e)?e:"branches"in e&&A(e.branches)?e.branches:void 0,Ba=(e,t)=>E(`Node of kind ${t} is not valid as a ${e} definition`),Va=e=>`#${e} duplicates public alias ${e}`,Ha={};P.ambient??={};var Ua,Wa="function $",Ga=e=>Ka(e,qa(e)),Ka=(e,t)=>{let n=t.write(Wa,4),r=t.compile()();for(let t of e)t.precompilation||=(t.traverseAllows=r[`${t.id}Allows`].bind(r),t.isRoot()&&!t.allowsRequiresContext&&(t.allows=t.traverseAllows),t.traverseApply=r[`${t.id}Apply`].bind(r),r[`${t.id}Optimistic`]&&(t.traverseOptimistic=r[`${t.id}Optimistic`].bind(r)),n)},qa=e=>(new cn).return(e.reduce((e,t)=>{let n=new pn({kind:"Allows"}).indent();t.compile(n);let r=n.write(`${t.id}Allows`),i=new pn({kind:"Apply"}).indent();t.compile(i);let a=`${e}${r},\n${i.write(`${t.id}Apply`)},\n`;if(!t.hasKind("union"))return a;let o=new pn({kind:"Allows",optimistic:!0}).indent();return t.compile(o),`${a}${o.write(`${t.id}Optimistic`)},\n`},"{\n")+"}"),Ja=class{config;resolvedConfig;name;get[I](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,t){this.config=An(P.config,t),this.resolvedConfig=An(P.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Ha).length}`,this.name in Ha&&E(`A Scope already named ${this.name} already exists`),Ha[this.name]=this;let n=Object.entries(e).map(e=>this.preparseOwnAliasEntry(...e));for(let[e,t]of n){let n=e;if(e[0]==="#"?(n=e.slice(1),n in this.aliases&&E(Va(n)),this.aliases[n]=t):(n in this.aliases&&E(Va(e)),this.aliases[n]=t,this.exportedNames.push(n)),!L(t,"module")&&!L(t,"generic")&&!nt(t)){let e=this.preparseOwnDefinitionFormat(t,{alias:n});this.resolutions[n]=L(e,"root")?this.bindReference(e):this.createParseContext(e).id}}Ua??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[Ua.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=P.intrinsic?D(P.intrinsic,(e,t)=>e.startsWith("json")?[]:[e,this.bindReference(t)]):{}}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get internal(){return this}_json;get json(){return this._json||this.export(),this._json}defineSchema(e){return e}generic=(...e)=>{let t=this;return(n,r)=>new hr(e,r?new mr(n):n,t,t,r??null)};units=(e,t)=>{let n=[];for(let t of e)n.includes(t)||n.push(t);let r=n.map(e=>this.node("unit",{unit:e},t));return this.node("union",r,{...t,prereduced:!0})};lazyResolutions=[];lazilyResolve(e,t){let n=this.node("alias",{reference:t??"synthetic",resolve:e},{prereduced:!0});return this.resolved||this.lazyResolutions.push(n),n}schema=(e,t)=>this.finalize(this.parseSchema(e,t));parseSchema=(e,t)=>this.node(Wr(e),e,t);preparseNode(e,t,n){let r=typeof e=="string"?e:Wr(t,e);if(R(t)&&t.kind===r)return t;if(r==="alias"&&!n?.prereduced){let{reference:e}=Ei.implementation.normalize(t,this);if(e.startsWith("$")){let n=this.resolveRoot(e.slice(1));t=n,r=n.kind}}else if(r==="union"&&Se(t,"object")){let e=za(t);e?.length===1&&(t=e[0],r=Wr(t))}if(R(t)&&t.kind===r)return t;let i=Fa[r].normalize?.(t,this)??t;return R(i)?i.kind===r?i:Ba(r,i.kind):{...n,$:this,kind:r,def:i,prefix:n.alias??r}}bindReference(e){let t;return t=R(e)?e.$===this?e:new e.constructor(e.attachments,this):e.$===this?e:new hr(e.params,e.bodyDef,e.$,this,e.hkt),this.resolved||Object.assign(this.referencesById,t.referencesById),t}resolveRoot(e){return this.maybeResolveRoot(e)??E(no(e))}maybeResolveRoot(e){let t=this.maybeResolve(e);if(!L(t,"generic"))return t}maybeResolveSubalias(e){return Qa(this.aliases,e)??Qa(this.ambient,e)}get ambient(){return P.ambient}maybeResolve(e){let t=this.resolutions[e];if(t){if(typeof t!="string")return this.bindReference(t);let n=K[t];if(L(n,"root"))return this.resolutions[e]=n;if(L(n,"context")){if(n.phase==="resolving")return this.node("alias",{reference:`$${e}`},{prereduced:!0});if(n.phase==="resolved")return T(`Unexpected resolved context for was uncached by its scope: ${N(n)}`);n.phase="resolving";let t=this.bindReference(this.parseOwnDefinitionFormat(n.def,n));return n.phase="resolved",K[t.id]=t,K[n.id]=t,this.resolutions[e]=t}return T(`Unexpected nodesById entry for ${t}: ${N(n)}`)}let n=this.aliases[e]??this.ambient?.[e];return n?(n=this.normalizeRootScopeValue(n),L(n,"generic")?this.resolutions[e]=this.bindReference(n):L(n,"module")?(n.root||E(io(e)),this.resolutions[e]=this.bindReference(n.root)):this.resolutions[e]=this.parse(n,{alias:e})):this.maybeResolveSubalias(e)}createParseContext(e){let t=e.id??Yr(e.prefix);return K[t]=Object.assign(e,{[I]:"context",$:this,id:t,phase:"unresolved"})}traversal(e){return new Bn(e,this.resolvedConfig)}import(...e){return new La(D(this.export(...e),(e,t)=>[`#${e}`,t]))}precompilation;_exportedResolutions;_exports;export(...e){if(!this._exports){this._exports={};for(let e of this.exportedNames){let t=this.aliases[e];this._exports[e]=L(t,"module")?Ra(t,this):Xa(this.maybeResolve(e))}for(let e of this.lazyResolutions)e.resolution;if(this._exportedResolutions=to(this,this._exports),this._json=Za(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let e=qa(this.references);this.precompilation=e.write(Wa,4),Ka(this.references,e)}this.resolved=!0}return new La(D(e.length?e:this.exportedNames,(e,t)=>[t,this._exports[t]]))}resolve(e){return this.export()[e]}node=(e,t,n={})=>{let r=this.preparseNode(e,t,n);if(R(r))return this.bindReference(r);let i=this.createParseContext(r),a=Xr(i),o=this.bindReference(a);return K[i.id]=o};parse=(e,t={})=>this.finalize(this.parseDefinition(e,t));parseDefinition(e,t={}){if(L(e,"root"))return this.bindReference(e);let n=this.preparseOwnDefinitionFormat(e,t);if(L(n,"root"))return this.bindReference(n);let r=this.createParseContext(n);K[r.id]=r;let i=this.bindReference(this.parseOwnDefinitionFormat(e,r));return i.isCyclic&&(i=Qr(i,r.id)),K[r.id]=i,i}finalize(e){return Xa(e),!e.precompilation&&!this.resolvedConfig.jitless&&Ga(e.references),e}},Ya=class extends Ja{parseOwnDefinitionFormat(e,t){return Xr(t)}preparseOwnDefinitionFormat(e,t){return this.preparseNode(Wr(e),e,t)}preparseOwnAliasEntry(e,t){return[e,t]}normalizeRootScopeValue(e){return e}},Xa=e=>{let t=e.references.filter(e=>e.hasKind("alias"));for(let n of t){Object.assign(n.referencesById,n.resolution.referencesById);for(let t of e.references)n.id in t.referencesById&&Object.assign(t.referencesById,n.referencesById)}return e},Za=e=>D(e,(e,t)=>[e,L(t,"root")||L(t,"generic")?t.json:L(t,"module")?Za(t):T(`Unexpected resolution ${N(t)}`)]),Qa=(e,t)=>{let n=t.indexOf(".");if(n===-1)return;let r=t.slice(0,n),i=e[r];if(i===void 0)return;if(!L(i,"module"))return E(ro(r));let a=t.slice(n+1),o=i[a];if(o===void 0)return Qa(i,a);if(L(o,"root")||L(o,"generic"))return o;if(L(o,"module"))return o.root??E(io(t));T(`Unexpected resolution for alias '${t}': ${N(o)}`)},$a=(e,t)=>new Ya(e,t),eo=new Ya({}),to=(e,t)=>{let n={};for(let r in t){let i=t[r];if(L(i,"module")){let t=D(to(e,i),(e,t)=>[`${r}.${e}`,t]);Object.assign(n,t)}else L(i,"root")||L(i,"generic")?n[r]=i:T(`Unexpected scope resolution ${N(i)}`)}return n},no=e=>`'${e}' is unresolvable`,ro=e=>`'${e}' must reference a module to be accessed using dot syntax`,io=e=>`Reference to submodule '${e}' must specify an alias`;eo.export();var q=eo.schema,ao=eo.node;eo.defineSchema;var J=eo.generic,oo="^(?:0|[1-9]\\d*)$";F(new RegExp(oo));var so=$a({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:Array,Date:Date},{prereducedAliases:!0}).export();P.intrinsic={...so};var co=$a({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:oo}},{prereducedAliases:!0}).export();Object.assign(P.intrinsic,co);var lo=$a({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),Y={...so,...co,...lo,emptyStructure:ao("structure",{},{prereduced:!0})};P.intrinsic={...Y};var uo=(e,t)=>new RegExp(e,t);Object.assign(uo,{as:uo});var fo=e=>typeof e=="string"&&e[0]==="d"&&(e[1]==="'"||e[1]==='"')&&e[e.length-1]===e[1],po=e=>e.toString()!=="Invalid Date",mo=e=>e.slice(2,-1),ho=e=>`'${e}' could not be parsed by the Date constructor`,go=(e,t)=>_o(e,t),_o=(e,t)=>{let n=new Date(e);if(po(n))return n;let r=jt(e);if(r!==void 0){let e=new Date(r);if(po(e))return e}return t?E(t===!0?ho(e):t):void 0},vo=q({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),yo=(e,t)=>{let n=e.scanner.shiftUntilEscapable(To[wo[t]]);if(e.scanner.lookahead==="")return e.error(Do(n,t));if(e.scanner.shift(),t in Co){let r;try{r=new RegExp(n)}catch(e){E(String(e))}e.root=e.ctx.$.node("intersection",{domain:"string",pattern:n},{prereduced:!0}),t==="x/"&&(e.root=e.ctx.$.node("morph",{in:e.root,morphs:e=>r.exec(e),declaredOut:vo}))}else if(O(t,bo))e.root=e.ctx.$.node("unit",{unit:n});else{let t=go(n,ho(n));e.root=e.ctx.$.node("unit",{meta:n,unit:t})}},bo={"'":1,'"':1},xo={"/":1,"'":1,'"':1},So={"d'":"'",'d"':'"',"'":"'",'"':'"'},Co={"/":"/","x/":"/"},wo={...So,...Co},To={"'":e=>e.lookahead==="'",'"':e=>e.lookahead==='"',"/":e=>e.lookahead==="/"},Eo={'"':"double-quote","'":"single-quote","/":"forward slash"},Do=(e,t)=>`${t}${e} requires a closing ${Eo[wo[t]]}`,Oo=e=>`Private type references should not include '#'. Use '${e}' instead.`,ko="Optional definitions like 'string?' are only valid as properties in an object or tuple",Ao="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple",jo={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...dt},Mo=(e,t)=>e===">"?t[0]==="="?t[1]==="=":t.trimStart()===""||O(t.trimStart()[0],jo):e==="="?t[0]!=="=":e===","||e==="?",No=(e,t,n)=>Po(e,t,n,[]),Po=(e,t,n,r)=>{let i=n.parseUntilFinalizer();return r.push(i.root),i.finalizer===">"?r.length===t.params.length?r:n.error(Fo(e,t.names,r.map(e=>e.expression))):i.finalizer===","?Po(e,t,n,r):i.error(nn(">"))},Fo=(e,t,n)=>`${e}<${t.join(", ")}> requires exactly ${t.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`,Io=e=>{let t=e.scanner.shiftUntilLookahead(jo);t==="keyof"?e.addPrefix("keyof"):e.root=Ro(e,t)},Lo=(e,t,n)=>(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()==="<"?t(...No(e,t,n)):n.error(Fo(e,t.names,[]))),Ro=(e,t)=>zo(e,t)??Bo(e,t)??e.error(t===""?e.scanner.lookahead==="#"?Oo(e.shiftedBy(1).scanner.shiftUntilLookahead(jo)):Vo(e):no(t)),zo=(e,t)=>{if(e.ctx.args?.[t]){let n=e.ctx.args[t];return typeof n=="string"?e.ctx.$.node("alias",{reference:n},{prereduced:!0}):n}let n=e.ctx.$.maybeResolve(t);if(L(n,"root"))return n;if(n!==void 0)return L(n,"generic")?Lo(t,n,e):E(`Unexpected resolution ${N(n)}`)},Bo=(e,t)=>{let n=Mt(t);if(n!==void 0)return e.ctx.$.node("unit",{unit:n});let r=Ft(t);if(r!==void 0)return e.ctx.$.node("unit",{unit:r})},Vo=e=>{let t=e.previousOperator();return t?Ho(t,e.scanner.unscanned):Uo(e.scanner.unscanned)},Ho=(e,t="")=>`Token '${e}' requires a right operand${t?` before '${t}'`:""}`,Uo=e=>`Expected an expression${e?` before '${e}'`:""}`,Wo=e=>e.scanner.lookahead===""?e.error(Vo(e)):e.scanner.lookahead==="("?e.shiftedBy(1).reduceGroupOpen():e.scanner.lookaheadIsIn(xo)?yo(e,e.scanner.shift()):e.scanner.lookaheadIsIn(dt)?Wo(e.shiftedBy(1)):e.scanner.lookahead==="d"?e.scanner.nextLookahead in bo?yo(e,`${e.scanner.shift()}${e.scanner.shift()}`):Io(e):e.scanner.lookahead==="x"&&e.scanner.nextLookahead==="/"?e.shiftedBy(2)&&yo(e,"x/"):Io(e),Go={">":!0,">=":!0},Ko={"<":!0,"<=":!0},qo={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Jo=(e,t)=>`Left bounds are only valid when paired with right bounds (try ...${t}${e})`,Yo=e=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,Xo=(e,t,n,r)=>`An expression may have at most one left bound (parsed ${e}${qo[t]}, ${n}${qo[r]})`,Zo=(e,t)=>{let n=$o(e,t);if(e.root.hasKind("unit")){if(typeof e.root.unit=="number"){e.reduceLeftBound(e.root.unit,n),e.unsetRoot();return}if(e.root.unit instanceof Date){let t=`d'${e.root.description??e.root.unit.toISOString()}'`;e.unsetRoot(),e.reduceLeftBound(t,n);return}}return ns(e,n)},Qo={"<":1,">":1,"=":1},$o=(e,t)=>e.scanner.lookaheadIs("=")?`${t}${e.scanner.shift()}`:t,es=(e,t,n,r)=>n.extends(P.intrinsic.number)?typeof t=="number"?e==="=="?["min","max"]:e[0]===">"?["min"]:["max"]:E(rs(e,t,r)):n.extends(P.intrinsic.lengthBoundable)?typeof t=="number"?e==="=="?["exactLength"]:e[0]===">"?["minLength"]:["maxLength"]:E(rs(e,t,r)):n.extends(P.intrinsic.Date)?e==="=="?["after","before"]:e[0]===">"?["after"]:["before"]:E(Nr(n.expression)),ts=e=>({rule:fo(e.limit)?mo(e.limit):e.limit,exclusive:e.comparator.length===1}),ns=(e,t)=>{let n=e.unsetRoot(),r=e.scanner.location;e.parseOperand();let i=e.unsetRoot(),a=e.scanner.sliceChars(r,e.scanner.location);if(e.root=n,!i.hasKind("unit")||typeof i.unit!="number"&&!(i.unit instanceof Date))return e.error(rs(t,a,"right"));let o=i.unit,s=t.length===1,c=es(t,typeof o=="number"?o:a,n,"right");for(let n of c)e.constrainRoot(n,t==="=="?{rule:o}:{rule:o,exclusive:s});if(!e.branches.leftBound)return;if(!O(t,Ko))return e.error(Yo(t));let l=es(e.branches.leftBound.comparator,e.branches.leftBound.limit,n,"left");e.constrainRoot(l[0],ts(e.branches.leftBound)),e.branches.leftBound=null},rs=(e,t,n)=>`Comparator ${n==="left"?qo[e]:e} must be ${n==="left"?"preceded":"followed"} by a corresponding literal (was ${t})`,is=e=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(jo);e.root=e.root.brand(t)},as=e=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(jo),n=Nt(t,{errorOnFail:os(t)});n===0&&e.error(os(0)),e.root=e.root.constrain("divisor",n)},os=e=>`% operator must be followed by a non-zero integer literal (was ${e})`,ss=e=>{let t=e.scanner.shift();return t===""?e.finalize(""):t==="["?e.scanner.shift()==="]"?e.setRoot(e.root.array()):e.error(ls):t==="|"?e.scanner.lookahead===">"?e.shiftedBy(1).pushRootToBranch("|>"):e.pushRootToBranch(t):t==="&"?e.pushRootToBranch(t):t===")"?e.finalizeGroup():Mo(t,e.scanner.unscanned)?e.finalize(t):O(t,Qo)?Zo(e,t):t==="%"?as(e):t==="#"?is(e):t in dt?ss(e):e.error(cs(t))},cs=(e,t="")=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,ls="Missing expected ']'",us=e=>{let t=e.unsetRoot();e.parseOperand();let n=e.unsetRoot();return n.hasKind("unit")?[t,"=",n.unit instanceof Date?()=>new Date(n.unit):n.unit]:e.error(ds(n.expression))},ds=e=>`Default value '${e}' must be a literal value`,fs=(e,t)=>{let n=t.$.maybeResolveRoot(e);if(n)return n;if(e.endsWith("[]")){let n=t.$.maybeResolveRoot(e.slice(0,-2));if(n)return n.array()}let r=new gs(new en(e),t),i=ps(r);return r.finalizer===">"&&E(cs(">")),i},ps=e=>{e.parseOperand();let t=ms(e).root;return t?(e.finalizer==="="?t=us(e):e.finalizer==="?"&&(t=[t,"?"]),e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead&&E(cs(e.scanner.lookahead)),t):T(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`)},ms=e=>{for(;e.finalizer===void 0;)hs(e);return e},hs=e=>e.hasRoot()?e.parseOperator():e.parseOperand(),gs=class e{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(e,t){this.scanner=e,this.ctx=t}error(e){return E(e)}hasRoot(){return this.root!==void 0}setRoot(e){this.root=e}unsetRoot(){let e=this.root;return this.root=void 0,e}constrainRoot(...e){this.root=this.root.constrain(e[0],e[1])}finalize(e){if(this.groups.length)return this.error(nn(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){let n=qo[t];if(!O(n,Go))return this.error(Yo(t));if(this.branches.leftBound)return this.error(Xo(this.branches.leftBound.limit,this.branches.leftBound.comparator,e,n));this.branches.leftBound={comparator:n,limit:e}}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 e=this.groups.pop();if(!e)return this.error(tn(")",this.scanner.unscanned));this.branches=e}addPrefix(e){this.branches.prefixes.push(e)}applyPrefixes(){for(;this.branches.prefixes.length;){let e=this.branches.prefixes.pop();this.root=e==="keyof"?this.root.keyof():T(`Unexpected prefix '${e}'`)}}pushRootToBranch(e){this.assertRangeUnset(),this.applyPrefixes();let t=this.root;this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(t)??t,e!=="&"&&(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,e!=="|"&&(this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null))}parseUntilFinalizer(){return ms(new e(this.scanner,this.ctx))}parseOperator(){return ss(this)}parseOperand(){return Wo(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Jo(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[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedBy(e){return this.scanner.jumpForward(e),this}},_s="An empty string is not a valid generic parameter name",vs=(e,t,n)=>{e.shiftUntilNonWhitespace();let r=e.shiftUntilLookahead(jo);return r===""?e.lookahead===""&&t.length?t:E(_s):(e.shiftUntilNonWhitespace(),bs(e,r,t,n))},ys="extends ",bs=(e,t,n,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(ys))e.jumpForward(8);else return e.lookahead===","&&e.shift(),n.push(t),vs(e,n,r);let i=ms(new gs(e,r));return n.push([t,i.root]),vs(e,n,r)},xs=class extends j{constructor(e){let t={$:e,raw:e.fn};super((...t)=>{let n=t.indexOf(":"),r=n===-1?t.length-1:n-1,i=t.slice(0,r+1),a=e.parse(i).assertHasKind("intersection"),o=e.intrinsic.unknown;if(n!==-1){if(n!==t.length-2)return E(Cs);o=e.parse(t[n+1])}return e=>new Ss(e,a,o)},{attach:t})}},Ss=class extends j{raw;params;returns;expression;constructor(e,t,n){let r=`typed ${e.name}`,i={[r]:(...r)=>{let i=e(...t.assert(r));return n.assert(i)}}[r];super(i),this.raw=e,this.params=t,this.returns=n;let a=t.expression;a[0]==="["&&a[a.length-1]==="]"?a=a.slice(1,-1):a.endsWith("[]")&&(a=`...${a}`),this.expression=`(${a}) => ${n?.expression??"unknown"}`}},Cs='":" must be followed by exactly one return type e.g:\nfn("string", ":", "number")(s => s.length)',ws=class extends j{$;constructor(e){super((...t)=>new Ts(e)(...t),{bind:e}),this.$=e}in(e){return new Ts(this.$,e===void 0?void 0:this.$.parse(e))}at(e,t){return new Ts(this.$).at(e,t)}case(e,t){return new Ts(this.$).case(e,t)}},Ts=class extends j{$;in;key;branches=[];constructor(e,t){super(e=>this.caseEntries(Object.entries(e).map(([e,t])=>e==="default"?[e,t]:[this.$.parse(e),t]))),this.$=e,this.in=t}at(e,t){return this.key&&E(Os),this.branches.length&&E(Ds),this.key=e,t?this.match(t):this}case(e,t){return this.caseEntry(this.$.parse(e),t)}caseEntry(e,t){let n=(this.key?this.$.parse({[this.key]:e}):e).pipe(t);return this.branches.push(n),this}match(e){return this(e)}strings(e){return this.caseEntries(Object.entries(e).map(([e,t])=>e==="default"?[e,t]:[this.$.node("unit",{unit:e}),t]))}caseEntries(e){for(let t=0;t<e.length;t++){let[n,r]=e[t];if(n==="default")return t!==e.length-1&&E("default may only be specified as the last key of a switch definition"),this.default(r);if(typeof r!="function")return E(`Value for case "${n}" must be a function (was ${C(r)})`);this.caseEntry(n,r)}return this}default(e){typeof e=="function"&&this.case(Y.unknown,e);let t={branches:this.branches,ordered:!0};(e==="never"||e==="assert")&&(t.meta={onFail:Es});let n=this.$.node("union",t);if(!this.in)return this.$.finalize(n);let r=this.in.pipe(n);return(e==="never"||e==="assert")&&(r=r.configureReferences({onFail:Es},"self")),this.$.finalize(r)}},Es=e=>e.throw(),Ds="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",Os="At most one key matcher may be specified per expression",ks=(e,t)=>{if(A(e)){if(e[1]==="=")return[t.$.parseOwnDefinitionFormat(e[0],t),"=",e[2]];if(e[1]==="?")return[t.$.parseOwnDefinitionFormat(e[0],t),"?"]}return fc(e,t)},As="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",js="Only required keys may specify default values, e.g. { value: 'number = 0' }",Ms=(e,t)=>{let n,r={},i=Ie(e);for(let[e,a]of i){let i=Is(e);if(i.kind==="spread"){if(!Fe(r))return E(Fs);let e=t.$.parseOwnDefinitionFormat(a,t);if(e.equals(Y.object))continue;if(!e.hasKind("intersection")||!e.basis?.equals(Y.object))return E(Ls(e.expression));n=e.structure;continue}if(i.kind==="undeclared"){a!=="reject"&&a!=="delete"&&a!=="ignore"&&E(Ps(a)),r.undeclared=a;continue}let o=ks(a,t),s=i;if(i.kind==="required"){A(o)?Ns(r,"optional",o[1]==="="?{key:i.normalized,value:o[0],default:o[2]}:{key:i.normalized,value:o[0]},t):Ns(r,"required",{key:i.normalized,value:o},t);continue}if(A(o)&&(o[1]==="?"&&E(As),o[1]==="="&&E(js)),i.kind==="optional"){Ns(r,"optional",{key:i.normalized,value:o},t);continue}let c=ja(t.$.parseOwnDefinitionFormat(s.normalized,t),o,t.$);c.index&&(r.index=x(r.index,c.index)),c.required&&(r.required=x(r.required,c.required))}let a=t.$.node("structure",r);return t.$.parseSchema({domain:"object",structure:n?.merge(a)??a})},Ns=(e,t,n,r)=>{e[t]=x(e[t],r.$.node(t,n))},Ps=e=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${N(e)})`,Fs="Spread operator may only be used as the first key in an object",Is=e=>typeof e=="symbol"?{kind:"required",normalized:e}:e[e.length-1]==="?"?e[e.length-2]==="\\"?{kind:"required",normalized:`${e.slice(0,-2)}?`}:{kind:"optional",normalized:e.slice(0,-1)}:e[0]==="["&&e[e.length-1]==="]"?{kind:"index",normalized:e.slice(1,-1)}:e[0]==="\\"&&e[1]==="["&&e[e.length-1]==="]"?{kind:"required",normalized:e.slice(1)}:e==="..."?{kind:"spread"}:e==="+"?{kind:"undeclared"}:{kind:"required",normalized:e==="\\..."?"...":e==="\\+"?"+":e},Ls=e=>`Spread operand must resolve to an object literal type (was ${e})`,Rs=(e,t)=>Qs(e)?Zs[e[0]](e,t):Xs(e)?Ys[e[1]](e,t):null,zs=(e,t)=>t.$.parseOwnDefinitionFormat(e[1],t).keyof(),Bs=(e,t)=>{if(e[2]===void 0)return E(Ho(e[1],""));let n=t.$.parseOwnDefinitionFormat(e[0],t),r=t.$.parseOwnDefinitionFormat(e[2],t);if(e[1]==="|")return t.$.node("union",{branches:[n,r]});let i=e[1]==="&"?U(n,r,t.$):tr(n,r,t.$);return i instanceof H?i.throw():i},Vs=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).array(),Hs=(e,t)=>typeof e[2]=="function"?t.$.parseOwnDefinitionFormat(e[0],t).pipe(e[2]):E(Us("=>",e[2])),Us=(e,t)=>`${e===":"?"Narrow":"Morph"} expression requires a function following '${e}' (was ${typeof t})`,Ws=(e,t)=>typeof e[2]=="function"?t.$.parseOwnDefinitionFormat(e[0],t).constrain("predicate",e[2]):E(Us(":",e[2])),Gs=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).configure(e[2],e[3]),Ks=e=>e,qs=Ks({"[]":Vs,"?":()=>E(ko)}),Js=Ks({"|":Bs,"&":Bs,":":Ws,"=>":Hs,"|>":Bs,"@":Gs,"=":()=>E(Ao)}),Ys={...qs,...Js},Xs=e=>Ys[e[1]]!==void 0,Zs=(e=>e)({keyof:zs,instanceof:(e,t)=>{if(typeof e[1]!="function")return E($s(Ke(e[1])));let n=e.slice(1).map(e=>typeof e=="function"?t.$.node("proto",{proto:e}):E($s(Ke(e))));return n.length===1?n[0]:t.$.node("union",{branches:n})},"===":(e,t)=>t.$.units(e.slice(1))}),Qs=e=>Zs[e[0]]!==void 0,$s=e=>`Expected a constructor following 'instanceof' operator (was ${e})`,ec=(e,t)=>{let n=[{}],r=0;for(;r<e.length;){let i=!1;e[r]==="..."&&r<e.length-1&&(i=!0,r++);let a=ks(e[r],t),[o,s,c]=A(a)?a:[a];if(r++,i){if(!o.extends(P.intrinsic.Array))return E(oc(o.expression));n=n.flatMap(e=>o.distribute(t=>ac(mn(e),t)))}else n=n.map(e=>s==="?"?nc(e,o):s==="="?rc(e,o,c):tc(e,o))}return t.$.parseSchema(n.map(e=>Fe(e)?{proto:Array,exactLength:0}:{proto:Array,sequence:e}))},tc=(e,t)=>e.defaultables||e.optionals?E(e.variadic?ma:cc):(e.variadic?e.postfix=x(e.postfix,t):e.prefix=x(e.prefix,t),e),nc=(e,t)=>e.variadic?E(lc):(e.optionals=x(e.optionals,t),e),rc=(e,t,n)=>e.variadic?E(lc):e.optionals?E(uc):(e.defaultables=x(e.defaultables,[[t,n]]),e),ic=(e,t)=>(e.postfix&&E(sc),e.variadic?e.variadic.equals(t)||E(sc):e.variadic=t.internal,e),ac=(e,t)=>{let n=t.select({method:"find",kind:"sequence"});if(!n)return ic(e,P.intrinsic.unknown);if(n.prefix)for(let t of n.prefix)tc(e,t);if(n.optionals)for(let t of n.optionals)nc(e,t);if(n.variadic&&ic(e,n.variadic),n.postfix)for(let t of n.postfix)tc(e,t);return e},oc=e=>`Spread element must be an array (was ${e})`,sc="A tuple may have at most one variadic element",cc="A required element may not follow an optional element",lc="An optional element may not follow a variadic element",uc="A defaultable element may not follow an optional element without a default",dc={},fc=(e,t)=>{if(typeof e=="string"){if(t.args&&Object.keys(t.args).some(t=>e.includes(t)))return fs(e,t);let n=dc[t.$.name]??={};return n[e]??=fs(e,t)}return Se(e,"object")?pc(e,t):E(gc(C(e)))},pc=(e,t)=>{let n=Ge(e);switch(n){case void 0:return L(e,"root")?e:"~standard"in e?mc(e,t):Ms(e,t);case"Array":return hc(e,t);case"RegExp":return t.$.node("intersection",{domain:"string",pattern:e},{prereduced:!0});case"Function":{let t=nt(e)?e():e;return L(t,"root")?t:E(gc("Function"))}default:return E(gc(n??N(e)))}},mc=(e,t)=>t.$.intrinsic.unknown.pipe((t,n)=>{let r=e["~standard"].validate(t);if(!r.issues)return r.value;for(let{message:e,path:t}of r.issues)t&&t.length?n.error({problem:st(e),relativePath:t.map(e=>typeof e=="object"?e.key:e)}):n.error({message:e})}),hc=(e,t)=>Rs(e,t)??ec(e,t),gc=e=>`Type definitions must be strings or objects (was ${e})`,_c=class extends j{constructor(e){let t=Object.assign({errors:Ln,hkt:M,$:e,raw:e.parse,module:e.constructor.module,scope:e.constructor.scope,declare:e.declare,define:e.define,match:e.match,generic:e.generic,schema:e.schema,keywords:e.ambient,unit:e.unit,enumerated:e.enumerated,instanceOf:e.instanceOf,valueOf:e.valueOf,or:e.or,and:e.and,merge:e.merge,pipe:e.pipe,fn:e.fn},e.ambientAttachments);super((...t)=>{if(t.length===1)return e.parse(t[0]);if(t.length===2&&typeof t[0]=="string"&&t[0][0]==="<"&&t[0][t[0].length-1]===">"){let n=t[0].slice(1,-1);return new hr(e.parseGenericParams(n,{}),t[1],e,e,null)}return e.parse(t)},{attach:t})}},vc=P,yc=class e extends Ja{get ambientAttachments(){if(vc.typeAttachments)return this.cacheGetter("ambientAttachments",D(vc.typeAttachments,(e,t)=>[e,this.bindReference(t)]))}preparseOwnAliasEntry(e,t){let n=e.indexOf("<");if(n===-1){if(L(t,"module")||L(t,"generic"))return[e,t];let n=this.name==="ark"?e:e==="root"?this.name:`${this.name}.${e}`,r=this.resolvedConfig.keywords?.[n];return r&&(t=[t,"@",r]),[e,t]}e[e.length-1]!==">"&&E("'>' must be the last character of a generic declaration in a scope");let r=e.slice(0,n),i=e.slice(n+1,-1);return[r,()=>pr(this.parseGenericParams(i,{alias:r}),t,this)]}parseGenericParams(e,t){return vs(new en(e),[],this.createParseContext({...t,def:e,prefix:"generic"}))}normalizeRootScopeValue(e){return nt(e)&&!L(e,"generic")?e():e}preparseOwnDefinitionFormat(e,t){return{...t,def:e,prefix:t.alias??"type"}}parseOwnDefinitionFormat(e,t){!(t.alias&&t.alias in this.aliases)&&!t.args&&(t.args={this:t.id});let n=fc(e,t);if(A(n)){if(n[1]==="=")return E(Ao);if(n[1]==="?")return E(ko)}return n}unit=e=>this.units([e]);valueOf=e=>this.units(ze(e));enumerated=(...e)=>this.units(e);instanceOf=e=>this.node("proto",{proto:e},{prereduced:!0});or=(...e)=>this.schema(e.map(e=>this.parse(e)));and=(...e)=>e.reduce((e,t)=>e.and(this.parse(t)),this.intrinsic.unknown);merge=(...e)=>e.reduce((e,t)=>e.merge(this.parse(t)),this.intrinsic.object);pipe=(...e)=>this.intrinsic.unknown.pipe(...e);fn=new xs(this);match=new ws(this);declare=()=>({type:this.type});define(e){return e}type=new _c(this);static scope=(t,n={})=>new e(t,n);static module=(e,t={})=>this.scope(e,t).export()},bc=Object.assign(yc.scope,{define:e=>e}),X=yc,xc=class extends M{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'},Sc=J(["base",Y.object],["props",Y.object])(e=>e.base.merge(e.props),xc),Cc=X.module({Key:Y.key,Merge:Sc}),wc=class extends M{},Tc=J("element")(e=>{let t=e.element.exclude(Y.Array),n=t.array();return t.rawOr(n).pipe(me).distribute(e=>e.assertHasKind("morph").declareOut(n),q)},wc),Ec=X.module({root:Y.Array,readonly:"root",index:Y.nonNegativeIntegerString,liftFrom:Tc},{name:"Array"}),Dc=q(["string",It.FileConstructor]),Oc=q({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:Dc.rawOr(Dc.array())}}),kc=X.module({root:["instanceof",FormData],value:Dc,parsed:Oc,parse:q({in:FormData,morphs:e=>{let t={};for(let[n,r]of e)if(n in t){let e=t[n];typeof e=="string"||e instanceof It.FileConstructor?t[n]=[e,r]:e.push(r)}else t[n]=r;return t},declaredOut:Oc})},{name:"FormData"}),Ac=X.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"}),jc={Boolean:1,Number:1,String:1},Mc=X.module({...D({...Be,...He},(e,t)=>e in jc?[]:[e,["instanceof",t]]),Array:Ec,TypedArray:Ac,FormData:kc}),Nc=q({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-864e13,meta:"a Unix timestamp after -8640000000000000"},max:{rule:864e13,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),Pc=q({domain:"number",divisor:1}),Fc=X.module({root:Y.number,integer:Pc,epoch:Nc,safe:q({domain:{domain:"number",numberAllowsNaN:!1},min:-(2**53-1),max:2**53-1}),NaN:["===",NaN],Infinity:["===",Infinity],NegativeInfinity:["===",-Infinity]},{name:"number"}),Z=(e,t,n)=>{let r={domain:"string",pattern:{rule:e.source,flags:e.flags,meta:t}};return n&&(r.meta={format:n}),ao("intersection",r)},Ic=Z(St,"a well-formed integer string"),Lc=X.module({root:Ic,parse:q({in:Ic,morphs:(e,t)=>{let n=Number.parseInt(e);return Number.isSafeInteger(n)?n:t.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:Y.integer})},{name:"string.integer"}),Rc=Z(/^[\dA-Fa-f]+$/,"hex characters only"),zc=X.module({root:Z(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:Z(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),Bc=Z(/^[A-Z].*$/,"capitalized"),Vc=X.module({root:q({in:"string",morphs:e=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:Bc}),preformatted:Bc},{name:"string.capitalize"}),Hc=q({domain:"string",pattern:{meta:"a credit card number",rule:"^(?: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}))$"},predicate:{meta:"a credit card number",predicate:e=>{let t=e.replace(/[ -]+/g,""),n=0,r,i,a=!1;for(let e=t.length-1;e>=0;e--)r=t.substring(e,e+1),i=Number.parseInt(r,10),a?(i*=2,n+=i>=10?i%10+1:i):n+=i,a=!a;return!!(n%10==0&&t)}}}),Uc=/^([+-]?\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)?)?)?)?$/,Wc=q({domain:"string",predicate:{meta:"a parsable date",predicate:e=>!Number.isNaN(new Date(e).valueOf())}}).assertHasKind("intersection"),Gc=Lc.root.internal.narrow((e,t)=>{let n=Number.parseInt(e),r=Fc.epoch(n);return r instanceof Ln?(t.errors.merge(r),!1):!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),Kc=X.module({root:Gc,parse:q({in:Gc,morphs:e=>new Date(e),declaredOut:Y.Date})},{name:"string.date.epoch"}),qc=Z(Uc,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),Jc=X.module({root:qc,parse:q({in:qc,morphs:e=>new Date(e),declaredOut:Y.Date})},{name:"string.date.iso"}),Yc=X.module({root:Wc,parse:q({declaredIn:Wc,in:"string",morphs:(e,t)=>{let n=new Date(e);return Number.isNaN(n.valueOf())?t.error("a parsable date"):n},declaredOut:Y.Date}),iso:Jc,epoch:Kc},{name:"string.date"}),Xc=Z(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),Zc="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",Qc=`(${Zc}[.]){3}${Zc}`,$c=RegExp(`^${Qc}$`),Q="(?:[0-9a-fA-F]{1,4})",el=RegExp(`^((?:${Q}:){7}(?:${Q}|:)|(?:${Q}:){6}(?:${Qc}|:${Q}|:)|(?:${Q}:){5}(?::${Qc}|(:${Q}){1,2}|:)|(?:${Q}:){4}(?:(:${Q}){0,1}:${Qc}|(:${Q}){1,3}|:)|(?:${Q}:){3}(?:(:${Q}){0,2}:${Qc}|(:${Q}){1,4}|:)|(?:${Q}:){2}(?:(:${Q}){0,3}:${Qc}|(:${Q}){1,5}|:)|(?:${Q}:){1}(?:(:${Q}){0,4}:${Qc}|(:${Q}){1,6}|:)|(?::((?::${Q}){0,5}:${Qc}|(?::${Q}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),tl=X.module({root:["v4 | v6","@","an IP address"],v4:Z($c,"an IPv4 address","ipv4"),v6:Z(el,"an IPv6 address","ipv6")},{name:"string.ip"}),nl="a JSON string",rl=e=>{if(!(e instanceof SyntaxError))throw e;return`must be ${nl} (${e})`},il=q({meta:nl,domain:"string",predicate:{meta:nl,predicate:(e,t)=>{try{return JSON.parse(e),!0}catch(e){return t.reject({code:"predicate",expected:nl,problem:rl(e)})}}}}),al=X.module({root:il,parse:q({meta:"safe JSON string parser",in:"string",morphs:(e,t)=>{if(e.length===0)return t.error({code:"predicate",expected:nl,actual:"empty"});try{return JSON.parse(e)}catch(e){return t.error({code:"predicate",expected:nl,problem:rl(e)})}},declaredOut:Y.jsonObject})},{name:"string.json"}),ol=Z(/^[a-z]*$/,"only lowercase letters"),sl=X.module({root:q({in:"string",morphs:e=>e.toLowerCase(),declaredOut:ol}),preformatted:ol},{name:"string.lower"}),cl=["NFC","NFD","NFKC","NFKD"],ll=D(cl,(e,t)=>[t,q({domain:"string",predicate:e=>e.normalize(t)===e,meta:`${t}-normalized unicode`})]),ul=D(cl,(e,t)=>[t,q({in:"string",morphs:e=>e.normalize(t),declaredOut:ll[t]})]),dl=X.module({root:ul.NFC,preformatted:ll.NFC},{name:"string.normalize.NFC"}),fl=X.module({root:ul.NFD,preformatted:ll.NFD},{name:"string.normalize.NFD"}),pl=X.module({root:ul.NFKC,preformatted:ll.NFKC},{name:"string.normalize.NFKC"}),ml=X.module({root:ul.NFKD,preformatted:ll.NFKD},{name:"string.normalize.NFKD"}),hl=X.module({root:"NFC",NFC:dl,NFD:fl,NFKC:pl,NFKD:ml},{name:"string.normalize"}),gl=Z(yt,"a well-formed numeric string"),_l=X.module({root:gl,parse:q({in:gl,morphs:e=>Number.parseFloat(e),declaredOut:Y.number})},{name:"string.numeric"}),vl="a regex pattern",yl=q({domain:"string",predicate:{meta:vl,predicate:(e,t)=>{try{return new RegExp(e),!0}catch(e){return t.reject({code:"predicate",expected:vl,problem:String(e)})}}},meta:{format:"regex"}}),bl=Z(/^(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-]+)*))?$/,"a semantic version (see https://semver.org/)"),xl=Z(/^\S.*\S$|^\S?$/,"trimmed"),Sl=X.module({root:q({in:"string",morphs:e=>e.trim(),declaredOut:xl}),preformatted:xl},{name:"string.trim"}),Cl=Z(/^[A-Z]*$/,"only uppercase letters"),wl=X.module({root:q({in:"string",morphs:e=>e.toUpperCase(),declaredOut:Cl}),preformatted:Cl},{name:"string.upper"}),Tl=q({domain:"string",predicate:{meta:"a URL string",predicate:e=>URL.canParse(e)},meta:{format:"uri"}}),El=X.module({root:Tl,parse:q({declaredIn:Tl,in:"string",morphs:(e,t)=>{try{return new URL(e)}catch{return t.error("a URL string")}},declaredOut:q(URL)})},{name:"string.url"}),Dl=X.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:Z(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:Z(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:Z(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:Z(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:Z(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:Z(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:Z(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:Z(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),Ol=X.module({root:Y.string,alpha:Z(/^[A-Za-z]*$/,"only letters"),alphanumeric:Z(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:Rc,base64:zc,capitalize:Vc,creditCard:Hc,date:Yc,digits:Z(/^\d*$/,"only digits 0-9"),email:Xc,integer:Lc,ip:tl,json:al,lower:sl,normalize:hl,numeric:_l,regex:yl,semver:bl,trim:Sl,upper:wl,url:El,uuid:Dl},{name:"string"}),kl=X.module({bigint:Y.bigint,boolean:Y.boolean,false:Y.false,never:Y.never,null:Y.null,number:Y.number,object:Y.object,string:Y.string,symbol:Y.symbol,true:Y.true,unknown:Y.unknown,undefined:Y.undefined}),Al=X.module({root:Y.unknown,any:Y.unknown},{name:"unknown"}),jl=X.module({root:Y.jsonObject,stringify:ao("morph",{in:Y.jsonObject,morphs:e=>JSON.stringify(e),declaredOut:Y.string})},{name:"object.json"}),Ml=X.module({root:Y.object,json:jl},{name:"object"}),Nl=class extends M{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'},Pl=J(["K",Y.key],"V")(e=>({domain:"object",index:{signature:e.K,value:e.V}}),Nl),Fl=class extends M{description='pick a set of properties from an object like `Pick(User, "name | age")`'},Il=J(["T",Y.object],["K",Y.key])(e=>e.T.pick(e.K),Fl),Ll=class extends M{description='omit a set of properties from an object like `Omit(User, "age")`'},Rl=J(["T",Y.object],["K",Y.key])(e=>e.T.omit(e.K),Ll),zl=class extends M{description="make all named properties of an object optional like `Partial(User)`"},Bl=J(["T",Y.object])(e=>e.T.partial(),zl),Vl=class extends M{description="make all named properties of an object required like `Required(User)`"},Hl=J(["T",Y.object])(e=>e.T.required(),Vl),Ul=class extends M{description='exclude branches of a union like `Exclude("boolean", "true")`'},Wl=J("T","U")(e=>e.T.exclude(e.U),Ul),Gl=class extends M{description='extract branches of a union like `Extract("0 | false | 1", "number")`'},Kl=J("T","U")(e=>e.T.extract(e.U),Gl),ql=X.module({Exclude:Wl,Extract:Kl,Omit:Rl,Partial:Bl,Pick:Il,Record:Pl,Required:Hl}),Jl=bc({...kl,...ql,...Mc,...Cc,string:Ol,number:Fc,object:Ml,unknown:Al},{prereducedAliases:!0,name:"ark"}),$=Jl.export();Object.assign(vc.ambient,$),vc.typeAttachments={string:$.string.root,number:$.number.root,bigint:$.bigint,boolean:$.boolean,symbol:$.symbol,undefined:$.undefined,null:$.null,object:$.object.root,unknown:$.unknown.root,false:$.false,true:$.true,never:$.never,arrayIndex:$.Array.index,Key:$.Key,Record:$.Record,Array:$.Array.root,Date:$.Date};var Yl=Object.assign(Jl.type,vc.typeAttachments);Jl.match,Jl.fn,Jl.generic,Jl.schema,Jl.define,Jl.declare;var Xl="/api/plugin/content-loading-plugin",Zl=pe(import.meta.url);async function Ql(e){let t=`${Xl}${e}`,n=await fetch(t);if(n.status!==200)throw Error(`api error ${n.status}`);return await n.text()}function $l(e){let t=document.createElement("div");return t.innerHTML=e,[...t.children]}var eu=e=>e!=null&&(e=Object.getPrototypeOf(e),e===Array.prototype||e===Object.prototype);function tu(e,t,n){for(let[r,i]of Object.entries(t)){let t=`${n}.${r}`;e[t]=i,eu(i)&&tu(e,i,t)}}function nu(e){let t={...e};for(let[n,r]of Object.entries(e))eu(r)&&tu(t,r,n);return t}var ru=(e,t)=>{if(t)for(let[n,r]of Object.entries(t))e=e.replace(RegExp(`{{\\s*${n}\\s*}}`,"g"),r);return e},iu=e=>e;function au(e,t=iu){return(n,...r)=>{n[0]==="."&&(n=n.slice(1));let i=e()?.[n];switch(typeof i){case"function":return i(...r);case"string":return t(i,r[0]);default:return i}}}var ou={en:{searchApp:{magnifierTitle:"Search in the site…",nothingMessage:"No results found for",search:"Search"},infiniteLoading:{loadMore:"Load more"}},fr:{searchApp:{magnifierTitle:"Rechercher dans le site…",nothingMessage:"Aucun résultat trouvé pour",search:"Rechercher"},infiniteLoading:{loadMore:"Charger la suite"}},es:{searchApp:{magnifierTitle:"Buscar en el sitio…",nothingMessage:"No se encontraron resultados para",search:"Buscar"},infiniteLoading:{loadMore:"Cargar más"}},de:{searchApp:{magnifierTitle:"Auf der Website suchen…",nothingMessage:"Keine Ergebnisse gefunden für",search:"Suchen"},infiniteLoading:{loadMore:"Mehr laden"}},it:{searchApp:{magnifierTitle:"Cerca nel sito…",nothingMessage:"Nessun risultato trovato per",search:"Cerca"},infiniteLoading:{loadMore:"Carica altro"}},pt:{searchApp:{magnifierTitle:"Pesquisar no site…",nothingMessage:"Nenhum resultado encontrado para",search:"Pesquisar"},infiniteLoading:{loadMore:"Carregar mais"}}};function su(e){return{t:au(_(()=>nu(ou[e in ou?e:"en"])),ru)}}var cu=u('<button class="PaInfiniteLoading-loadButton PaButton"type=button>'),lu=u("<div class=PaInfiniteLoading-loadMore>"),uu=u('<img class="PaInfiniteLoading-loading PaLoading"width=50 height=50 alt=…>'),du=Yl({"offset?":"string|undefined","total?":"string|undefined","limit?":"string|undefined","parentDocumentId?":"string|undefined","template?":"string|undefined","labeledWith?":"string|undefined","termNodeId?":"string|undefined","sorting?":"string|undefined","+":"ignore"}).pipe(e=>({offset:y(e.offset)?Number(e.offset):void 0,total:y(e.total)?Number(e.total):void 0,limit:y(e.limit)?Number(e.limit):void 0,parentDocumentId:y(e.parentDocumentId)?e.parentDocumentId:void 0,templateName:y(e.template)?e.template:void 0,termNodeId:y(e.termNodeId)?e.termNodeId:void 0,labeledWith:y(e.labeledWith)?e.labeledWith:void 0,sorting:y(e.sorting)?e.sorting:void 0}));function fu(e,{language:t}){let{templateName:n,offset:r,total:i,limit:a,parentDocumentId:o,sorting:s,termNodeId:c,labeledWith:l}=du.assert(e.dataset);if(!(r===void 0||i===void 0||o===void 0||a===void 0||n===void 0)){if(!t)throw Error("Missing language");pu({language:t,limit:a,parentDocumentId:o,root:e,offset:r,total:i,sorting:s,labeledWith:c!==void 0&&l?{termNodeId:c,fieldName:l}:void 0,templateName:n})}}function pu({language:e,limit:t,root:n,offset:r,total:a,parentDocumentId:o,sorting:s,templateName:l,labeledWith:u}){let{t:d}=su(e),f=r;if(f>=a)return;let p=(()=>{var e=cu();return e.$$click=g,i(e,()=>d("infiniteLoading.loadMore")),e})(),m=(()=>{var e=lu();return i(e,p),e})(),h=(()=>{var e=uu();return c(e,"src",`${Zl}/spinner.svg`),e})();n.appendChild(m);async function g(){n.appendChild(h);let e=await mu({limit:t,newOffset:f,parentDocumentId:o,sorting:s,labeledWith:u,templateName:l});for(let t of e)n.insertBefore(t,m);f+=t,f>=a&&m.remove(),h.remove()}}async function mu({limit:e,newOffset:t,parentDocumentId:n,labeledWith:r,sorting:i,templateName:a}){let o=[["template",a],["children-of",n],["offset",t],["limit",e]];return i&&o.push(["sorting",i]),r&&(o.push(["labeled-t",r.termNodeId]),o.push(["labeled-f",r.fieldName])),$l(await Ql(`/partials?${o.map(([e,t])=>`${e}=${encodeURIComponent(t)}`).join("&")}`))}t(["click"]);function hu(){let e=new Set;function t(t){return e.add(t),()=>e.delete(t)}let n=!1;function r(t,r){if(n)return!(n=!1);let i={to:t,options:r,defaultPrevented:!1,preventDefault:()=>i.defaultPrevented=!0};for(let a of e)a.listener({...i,from:a.location,retry:e=>{e&&(n=!0),a.navigate(t,{...r,resolve:!1})}});return!i.defaultPrevented}return{subscribe:t,confirm:r}}var gu;function _u(){(!window.history.state||window.history.state._depth==null)&&window.history.replaceState({...window.history.state,_depth:window.history.length-1},""),gu=window.history.state._depth}a||_u();function vu(e){return{...e,_depth:window.history.state&&window.history.state._depth}}function yu(e,t){let n=!1;return()=>{let r=gu;_u();let i=r==null?null:gu-r;if(n){n=!1;return}i&&t(i)?(n=!0,window.history.go(-i)):e()}}var bu=/^(?:[a-z0-9]+:)?\/\//i,xu=/^\/+|(\/)\/+$/g,Su="http://sr";function Cu(e,t=!1){let n=e.replace(xu,"$1");return n?t||/^[?#]/.test(n)?n:"/"+n:""}function wu(e,t,n){if(bu.test(t))return;let r=Cu(e),i=n&&Cu(n),a="";return a=!i||t.startsWith("/")?r:i.toLowerCase().indexOf(r.toLowerCase())===0?i:r+i,(a||"/")+Cu(t,!a)}function Tu(e,t){if(e==null)throw Error(t);return e}function Eu(e,t){return Cu(e).replace(/\/*(\*.*)?$/g,"")+Cu(t)}function Du(e){let t={};return e.searchParams.forEach((e,n)=>{n in t?Array.isArray(t[n])?t[n].push(e):t[n]=[t[n],e]:t[n]=e}),t}function Ou(e,t,n){let[r,i]=e.split("/*",2),a=r.split("/").filter(Boolean),o=a.length;return e=>{let r=e.split("/").filter(Boolean),s=r.length-o;if(s<0||s>0&&i===void 0&&!t)return null;let c={path:o?"":"/",params:{}},l=e=>n===void 0?void 0:n[e];for(let e=0;e<o;e++){let t=a[e],n=t[0]===":",i=n?r[e]:r[e].toLowerCase(),o=n?t.slice(1):t.toLowerCase();if(n&&ku(i,l(o)))c.params[o]=i;else if(n||!ku(i,o))return null;c.path+=`/${i}`}if(i){let e=s?r.slice(-s).join("/"):"";if(ku(e,l(i)))c.params[i]=e;else return null}return c}}function ku(e,t){let n=t=>t===e;return t===void 0?!0:typeof t=="string"?n(t):typeof t=="function"?t(e):Array.isArray(t)?t.some(n):t instanceof RegExp?t.test(e):!1}function Au(e){let[t,n]=e.pattern.split("/*",2),r=t.split("/").filter(Boolean);return r.reduce((e,t)=>e+(t.startsWith(":")?2:3),r.length-(n===void 0?0:1))}function ju(e){let t=new Map,n=ne();return new Proxy({},{get(r,i){return t.has(i)||se(n,()=>t.set(i,_(()=>e()[i]))),t.get(i)()},getOwnPropertyDescriptor(){return{enumerable:!0,configurable:!0}},ownKeys(){return Reflect.ownKeys(e())},has(t,n){return n in e()}})}function Mu(e){let t=/(\/?\:[^\/]+)\?/.exec(e);if(!t)return[e];let n=e.slice(0,t.index),r=e.slice(t.index+t[0].length),i=[n,n+=t[1]];for(;t=/^(\/\:[^\/]+)\?/.exec(r);)i.push(n+=t[1]),r=r.slice(t[0].length);return Mu(r).reduce((e,t)=>[...e,...i.map(e=>e+t)],[])}var Nu=100,Pu=h(),Fu=h(),Iu=()=>Tu(de(Pu),"<A> and 'use' router primitives can be only used inside a Route."),Lu=()=>Iu().navigatorFactory(),Ru=()=>Iu().location,zu=()=>Iu().params;function Bu(e,t=""){let{component:n,preload:r,load:i,children:a,info:o}=e,s=!a||Array.isArray(a)&&!a.length,c={key:e,component:n,preload:r||i,info:o};return Hu(e.path).reduce((n,r)=>{for(let i of Mu(r)){let a=Eu(t,i),o=s?a:a.split("/*",1)[0];o=o.split("/").map(e=>e.startsWith(":")||e.startsWith("*")?e:encodeURIComponent(e)).join("/"),n.push({...c,originalPath:r,pattern:o,matcher:Ou(o,!s,e.matchFilters)})}return n},[])}function Vu(e,t=0){return{routes:e,score:Au(e[e.length-1])*1e4-t,matcher(t){let n=[];for(let r=e.length-1;r>=0;r--){let i=e[r],a=i.matcher(t);if(!a)return null;n.unshift({...a,route:i})}return n}}}function Hu(e){return Array.isArray(e)?e:[e]}function Uu(e,t="",n=[],r=[]){let i=Hu(e);for(let e=0,a=i.length;e<a;e++){let a=i[e];if(a&&typeof a=="object"){a.hasOwnProperty("path")||(a.path="");let e=Bu(a,t);for(let t of e){n.push(t);let e=Array.isArray(a.children)&&a.children.length===0;if(a.children&&!e)Uu(a.children,t.pattern,n,r);else{let e=Vu([...n],r.length);r.push(e)}n.pop()}}}return n.length?r:r.sort((e,t)=>t.score-e.score)}function Wu(e,t){for(let n=0,r=e.length;n<r;n++){let r=e[n].matcher(t);if(r)return r}return[]}function Gu(e,t,n){let r=new URL(Su),i=_(t=>{let n=e();try{return new URL(n,r)}catch{return console.error(`Invalid path ${n}`),t}},r,{equals:(e,t)=>e.href===t.href}),a=_(()=>i().pathname),o=_(()=>i().search,!0),s=_(()=>i().hash),c=()=>"",l=ie(o,()=>Du(i()));return{get pathname(){return a()},get search(){return o()},get hash(){return s()},get state(){return t()},get key(){return c()},query:n?n(l):ju(l)}}var Ku;function qu(){return Ku}function Ju(e,t,n,i={}){let{signal:[o,s],utils:c={}}=e,l=c.parsePath||(e=>e),u=c.renderPath||(e=>e),d=c.beforeLeave||hu(),p=wu("",i.base||"");if(p===void 0)throw Error(`${p} is not a valid base path`);p&&!o().value&&s({value:p,replace:!0,scroll:!1});let[m,h]=v(!1),g,te=(e,t)=>{t.value===ne()&&t.state===ae()||(g===void 0&&h(!0),Ku=e,g=t,le(()=>{g===t&&(re(g.value),ce(g.state),oe(),a||y[1](e=>e.filter(e=>e.pending)))}).finally(()=>{g===t&&f(()=>{Ku=void 0,e==="navigate"&&ve(g),h(!1),g=void 0})}))},[ne,re]=v(o().value),[ae,ce]=v(o().state),fe=Gu(ne,ae,c.queryWrapper),pe=[],y=v(a?S():[]),me=_(()=>typeof i.transformUrl=="function"?Wu(t(),i.transformUrl(fe.pathname)):Wu(t(),fe.pathname)),he=()=>{let e=me(),t={};for(let n=0;n<e.length;n++)Object.assign(t,e[n].params);return t},ge=c.paramsWrapper?c.paramsWrapper(he,t):ju(he),b={pattern:p,path:()=>p,outlet:()=>null,resolvePath(e){return wu(p,e)}};return ee(ie(o,e=>te("native",e),{defer:!0})),{base:b,location:fe,params:ge,isRouting:m,renderPath:u,parsePath:l,navigatorFactory:x,matches:me,beforeLeave:d,preloadRoute:ye,singleFlight:i.singleFlight===void 0?!0:i.singleFlight,submissions:y};function _e(e,t,n){ue(()=>{if(typeof t=="number"){t&&(c.go?c.go(t):console.warn("Router integration does not support relative routing"));return}let i=!t||t[0]==="?",{replace:o,resolve:l,scroll:u,state:f}={replace:!1,resolve:!i,scroll:!0,...n},p=l?e.resolvePath(t):wu(i&&fe.pathname||"",t);if(p===void 0)throw Error(`Path '${t}' is not a routable path`);if(pe.length>=Nu)throw Error("Too many redirects");let m=ne();if(p!==m||f!==ae())if(a){let e=r();e&&(e.response={status:302,headers:new Headers({Location:p})}),s({value:p,replace:o,scroll:u,state:f})}else d.confirm(p,n)&&(pe.push({value:m,replace:o,scroll:u,state:ae()}),te("navigate",{value:p,state:f}))})}function x(e){return e=e||de(Fu)||b,(t,n)=>_e(e,t,n)}function ve(e){let t=pe[0];t&&(s({...e,replace:t.replace,scroll:t.scroll}),pe.length=0)}function ye(e,r){let i=Wu(t(),e.pathname),a=Ku;Ku="preload";for(let t in i){let{route:a,params:o}=i[t];a.component&&a.component.preload&&a.component.preload();let{preload:s}=a;r&&s&&se(n(),()=>s({params:o,location:{pathname:e.pathname,search:e.search,hash:e.hash,query:Du(e),state:null,key:""},intent:"preload"}))}Ku=a}function S(){let e=r();return e&&e.router&&e.router.submission?[e.router.submission]:[]}}function Yu(e,t,n,r){let{base:i,location:a,params:o}=e,{pattern:s,component:c,preload:l}=r().route,u=_(()=>r().path);c&&c.preload&&c.preload();let d=l?l({params:o,location:a,intent:Ku||"initial"}):void 0;return{parent:t,pattern:s,path:u,outlet:()=>c?m(c,{params:o,location:a,data:d,get children(){return n()}}):n(),resolvePath(e){return wu(i.path(),e,u())}}}var Xu=t=>n=>{let{base:r}=n,i=p(()=>n.children),a=_(()=>Uu(i(),n.base||"")),s,c=Ju(t,a,()=>s,{base:r,singleFlight:n.singleFlight,transformUrl:n.transformUrl});return t.create&&t.create(c),e(Pu.Provider,{value:c,get children(){return e(Zu,{routerState:c,get root(){return n.root},get preload(){return n.rootPreload||n.rootLoad},get children(){return[o(()=>(s=ne())&&null),e(Qu,{routerState:c,get branches(){return a()}})]}})}})};function Zu(t){let n=t.routerState.location,r=t.routerState.params,i=_(()=>t.preload&&ue(()=>{t.preload({params:r,location:n,intent:qu()||"initial"})}));return e(d,{get when(){return t.root},keyed:!0,get fallback(){return t.children},children:a=>e(a,{params:r,location:n,get data(){return i()},get children(){return t.children}})})}function Qu(e){if(a){let t=r();if(t&&t.router&&t.router.dataOnly){td(t,e.routerState,e.branches);return}t&&((t.router||={}).matches||(t.router.matches=e.routerState.matches().map(({route:e,path:t,params:n})=>({path:e.originalPath,pattern:e.pattern,match:t,params:n,info:e.info}))))}let t=[],n,i=_(ie(e.routerState.matches,(r,a,o)=>{let s=a&&r.length===a.length,c=[];for(let n=0,l=r.length;n<l;n++){let l=a&&a[n],u=r[n];o&&l&&u.route.key===l.route.key?c[n]=o[n]:(s=!1,t[n]&&t[n](),te(r=>{t[n]=r,c[n]=Yu(e.routerState,c[n-1]||e.routerState.base,$u(()=>i()[n+1]),()=>{let t=e.routerState.matches();return t[n]??t[0]})}))}return t.splice(r.length).forEach(e=>e()),o&&s?o:(n=c[0],c)}));return $u(()=>i()&&n)()}var $u=t=>()=>e(d,{get when(){return t()},keyed:!0,children:t=>e(Fu.Provider,{value:t,get children(){return t.outlet()}})}),ed=e=>{let t=p(()=>e.children);return re(e,{get children(){return t()}})};function td(e,t,n){let r=new URL(e.request.url),i=Wu(n,new URL(e.router.previousUrl||e.request.url).pathname),a=Wu(n,r.pathname);for(let n=0;n<a.length;n++){(!i[n]||a[n].route!==i[n].route)&&(e.router.dataOnly=!0);let{route:r,params:o}=a[n];r.preload&&r.preload({params:o,location:t.location,intent:"preload"})}}function nd([e,t],n,r){return[n?()=>n(e()):e,r?e=>t(r(e)):t]}function rd(e){let t=!1,n=e=>typeof e=="string"?{value:e}:e,r=nd(v(n(e.get()),{equals:(e,t)=>e.value===t.value&&e.state===t.state}),void 0,n=>(!t&&e.set(n),ce.registry&&!ce.done&&(ce.done=!0),n));return e.init&&ae(e.init((i=e.get())=>{t=!0,r[1](n(i)),t=!1})),Xu({signal:r,create:e.create,utils:e.utils})}function id(e,t,n){return e.addEventListener(t,n),()=>e.removeEventListener(t,n)}function ad(e,t){let n=e&&document.getElementById(e);n?n.scrollIntoView():t&&window.scrollTo(0,0)}var od=new Map;function sd({preload:e=!0,explicitLinks:n=!1,actionBase:r="/_server",transformUrl:i}={}){return a=>{let o=a.base.path(),s=a.navigatorFactory(a.base),c,l;function u(e){return e.namespaceURI==="http://www.w3.org/2000/svg"}function d(e){if(e.defaultPrevented||e.button!==0||e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return;let t=e.composedPath().find(e=>e instanceof Node&&e.nodeName.toUpperCase()==="A");if(!t||n&&!t.hasAttribute("link"))return;let r=u(t),i=r?t.href.baseVal:t.href;if((r?t.target.baseVal:t.target)||!i&&!t.hasAttribute("state"))return;let a=(t.getAttribute("rel")||"").split(/\s+/);if(t.hasAttribute("download")||a&&a.includes("external"))return;let s=r?new URL(i,document.baseURI):new URL(i);if(!(s.origin!==window.location.origin||o&&s.pathname&&!s.pathname.toLowerCase().startsWith(o.toLowerCase())))return[t,s]}function f(e){let t=d(e);if(!t)return;let[n,r]=t,i=a.parsePath(r.pathname+r.search+r.hash),o=n.getAttribute("state");e.preventDefault(),s(i,{resolve:!1,replace:n.hasAttribute("replace"),scroll:!n.hasAttribute("noscroll"),state:o?JSON.parse(o):void 0})}function p(e){let t=d(e);if(!t)return;let[n,r]=t;i&&(r.pathname=i(r.pathname)),a.preloadRoute(r,n.getAttribute("preload")!=="false")}function m(e){clearTimeout(c);let t=d(e);if(!t)return l=null;let[n,r]=t;l!==n&&(i&&(r.pathname=i(r.pathname)),c=setTimeout(()=>{a.preloadRoute(r,n.getAttribute("preload")!=="false"),l=n},20))}function h(e){if(e.defaultPrevented)return;let t=e.submitter&&e.submitter.hasAttribute("formaction")?e.submitter.getAttribute("formaction"):e.target.getAttribute("action");if(!t)return;if(!t.startsWith("https://action/")){let e=new URL(t,Su);if(t=a.parsePath(e.pathname+e.search),!t.startsWith(r))return}if(e.target.method.toUpperCase()!=="POST")throw Error("Only POST forms are supported for Actions");let n=od.get(t);if(n){e.preventDefault();let t=new FormData(e.target,e.submitter);n.call({r:a,f:e.target},e.target.enctype==="multipart/form-data"?t:new URLSearchParams(t))}}t(["click","submit"]),document.addEventListener("click",f),e&&(document.addEventListener("mousemove",m,{passive:!0}),document.addEventListener("focusin",p,{passive:!0}),document.addEventListener("touchstart",p,{passive:!0})),document.addEventListener("submit",h),ae(()=>{document.removeEventListener("click",f),e&&(document.removeEventListener("mousemove",m),document.removeEventListener("focusin",p),document.removeEventListener("touchstart",p)),document.removeEventListener("submit",h)})}}function cd(e){let t=e.replace(/^.*?#/,"");if(!t.startsWith("/")){let[,e="/"]=window.location.hash.split("#",2);return`${e}#${t}`}return t}function ld(e){let t=()=>window.location.hash.slice(1),n=hu();return rd({get:t,set({value:e,replace:t,scroll:n,state:r}){t?window.history.replaceState(vu(r),"","#"+e):window.history.pushState(r,"","#"+e);let i=e.indexOf("#");ad(i>=0?e.slice(i+1):"",n),_u()},init:e=>id(window,"hashchange",yu(e,e=>!n.confirm(e&&e<0?e:t()))),create:sd({preload:e.preload,explicitLinks:e.explicitLinks,actionBase:e.actionBase}),utils:{go:e=>window.history.go(e),renderPath:e=>`#${e}`,parsePath:cd,beforeLeave:n}})(e)}function ud(e){let t=Lu(),n=Ru(),{href:r,state:i}=e;return t(typeof r=="function"?r({navigate:t,location:n}):r,{replace:!0,state:i}),null}async function dd({language:e,text:t,limit:n,offset:r,templateName:i}){let a=`${Xl}/search?language=${encodeURIComponent(e)}&q=${encodeURIComponent(t)}&limit=${encodeURIComponent(n)}&offset=${encodeURIComponent(r)}&tpl=${encodeURIComponent(i)}`,o=await fetch(a,{method:"GET"});if(o.status!==200){let e=await o.text();throw Error(`API error (${o.status}): ${e}`)}return await o.json()}var fd=u('<form class=PaSearchApp-form><input class="PaSearchApp-input PaInput"type=search><button class="PaSearchApp-searchButton PaButton"type=submit>');function pd(e){let t=Lu(),[r,a]=v(e.value??""),{t:o}=su(e.language);g(ie(()=>e.value,()=>a(e.value??"")));let s=async e=>{e.preventDefault(),t(`/q/${encodeURIComponent(r())}`)};return(()=>{var e=fd(),t=e.firstChild,l=t.nextSibling;return e.addEventListener("submit",s),t.addEventListener("change",e=>a(e.currentTarget.value)),i(l,()=>o("searchApp.search")),n(()=>c(t,"placeholder",o("searchApp.search"))),n(()=>t.value=r()),e})()}var md=u("<div class=PaSearchApp-loadMore>"),hd=u("<div class=PaSearchApp-results>"),gd=u("<div class=PaSearchApp>"),_d=u("<div class=PaSearchApp-nothing> <span class=PaSearchApp-quote>"),vd=u('<img class="PaSearchApp-loading PaLoading"width=80 height=80 alt=…>'),yd=u('<button class="PaSearchApp-loadButton PaButton"type=button>');function bd({language:t,limit:n,templateName:r}){let{t:a}=su(t),s=zu(),[l,u]=v([]),[f,p]=v(-1),[m,h]=v(0),[_,ee]=v(!1);g(ie(()=>s.searchString,te));async function te(){if(s.searchString){ee(!0);try{u([]),h(0),p(-1);let e=await dd({language:t,text:decodeURIComponent(s.searchString),limit:n,offset:m(),templateName:r});if(p(e.total),h(m()+n),!e.html)return;u($l(e.html))}finally{ee(!1)}}}async function ne(){if(!s.searchString)return;let e=f();if(!(e===-1||m()>=e)){ee(!0);try{let e=await dd({language:t,text:decodeURIComponent(s.searchString),limit:n,offset:m(),templateName:r});if(!e.html)return;u([...l(),...$l(e.html)]),h(m()+n)}finally{ee(!1)}}}return(()=>{var n=gd();return i(n,e(pd,{language:t,get value(){return o(()=>!!s.searchString)()?decodeURIComponent(s.searchString):void 0}}),null),i(n,e(d,{get when(){return s.searchString},get children(){var t=hd();return i(t,e(d,{get when(){return f()!==-1},get children(){return e(d,{get when(){return l().length>0},get fallback(){return(()=>{var e=_d(),t=e.firstChild,n=t.nextSibling;return i(e,()=>a("searchApp.nothingMessage"),t),i(n,()=>s.searchString),e})()},get children(){return l()}})}}),null),i(t,e(d,{get when(){return f()===-1||_()||m()<f()},get children(){var e=md();return i(e,(()=>{var e=o(()=>!!_());return()=>e()?(()=>{var e=vd();return c(e,"src",`${Zl}/spinner.svg`),e})():(()=>{var e=yd();return e.$$click=ne,i(e,()=>a("infiniteLoading.loadMore")),e})()})()),e}}),null),t}}),null),n})()}t(["click"]);var xd=Yl({"limit?":"string|undefined","template?":"string|undefined","+":"ignore"}).pipe(e=>({limit:y(e.limit)?Number(e.limit):void 0,templateName:y(e.template)?e.template:void 0}));function Sd(t,{language:n}){if(!n)throw Error("Missing language");let{limit:r,templateName:i}=xd.assert(t.dataset);r===void 0||i===void 0||s(()=>e(ld,{explicitLinks:!0,get children(){return[e(ed,{path:"/",component:()=>e(ud,{href:"/q"})}),e(ed,{path:"/q",component:()=>e(bd,{language:n,templateName:i,limit:r})}),e(ed,{path:"/q/:searchString",component:()=>e(bd,{language:n,templateName:i,limit:r})})]}}),t)}var Cd=u('<input class="PaSearchOpener-input PaInput"type=search required>'),wd=u('<form class=PaSearchOpener><button class="PaSearchOpener-button PaButton"type=submit>');function Td({searchURL:e,language:t}){let[r,a]=v(""),{t:o}=su(t),s=(()=>{var e=Cd();return e.addEventListener("change",e=>a(e.currentTarget.value)),n(()=>c(e,"placeholder",o("searchApp.search"))),n(()=>e.value=r()),e})(),l=t=>{t.preventDefault(),window.location.href=`${e}#/q/${encodeURIComponent(r())}`};return(()=>{var e=wd(),t=e.firstChild;return e.addEventListener("submit",l),i(e,s,t),i(t,()=>o("searchApp.search")),e})()}var Ed=u('<button class=PaSearchOpenerButton type=button><svg class=PaSearchOpenerButton-svg width=20 height=20 xmlns=http://www.w3.org/2000/svg viewBox="0 0 490.4 490.4"><title></title><g id=SVGRepo_bgCarrier stroke-width=0></g><g id=SVGRepo_tracerCarrier stroke-linecap=round stroke-linejoin=round></g><g id=SVGRepo_iconCarrier><g><path d="M484.1,454.796l-110.5-110.6c29.8-36.3,47.6-82.8,47.6-133.4c0-116.3-94.3-210.6-210.6-210.6S0,94.496,0,210.796 s94.3,210.6,210.6,210.6c50.8,0,97.4-18,133.8-48l110.5,110.5c12.9,11.8,25,4.2,29.2,0C492.5,475.596,492.5,463.096,484.1,454.796z M41.1,210.796c0-93.6,75.9-169.5,169.5-169.5s169.6,75.9,169.6,169.5s-75.9,169.5-169.5,169.5S41.1,304.396,41.1,210.796z"></path> ');function Dd({searchIconColor:t,language:n,searchURL:r}){let{t:a}=su(n),o=(()=>{var e=Ed(),n=e.firstChild,r=n.firstChild;return l(n,"fill",t),i(r,()=>a("searchApp.magnifierTitle")),e})(),s=e(Td,{searchURL:r,language:n});return fe({openButton:o,dialogContent:s,modalClass:"_paSearchOpener",loadCss:!0}).on("open",()=>{s.querySelector("input")?.focus()}),o}function Od(t,{language:n}){let r=t.dataset.searchUrl,i=t.dataset.iconColor;if(!n)throw Error("Missing language");if(!r)throw Error("Missing search url");s(()=>e(Dd,{language:n,searchURL:r,searchIconColor:i}),t)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",kd):kd();function kd(){let e=document.documentElement.lang,t={paSearchOpener:Od,paSearchApp:Sd,paInfiniteLoading:fu},n=document.querySelectorAll("[data-effect]");for(let r of n){let n=r.dataset.effect;if(!n)continue;let i=t[n];i&&i(r,{language:e})}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@paroicms/content-loading-plugin",
|
|
3
|
-
"version": "0.27.
|
|
3
|
+
"version": "0.27.25",
|
|
4
4
|
"description": "Content loading plugin for ParoiCMS",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"paroicms",
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
"license": "MIT",
|
|
18
18
|
"scripts": {
|
|
19
19
|
"build": "npm run build:backend && npm run build:frontend",
|
|
20
|
+
"build:ci": "npm run build",
|
|
20
21
|
"build:backend": "(cd backend && tsc)",
|
|
21
22
|
"build:backend:watch": "(cd backend && tsc --watch --preserveWatchOutput)",
|
|
22
23
|
"build:frontend": "(cd frontend && npm run build)",
|
|
@@ -24,7 +25,7 @@
|
|
|
24
25
|
"clear": "rimraf backend/dist/* frontend/dist/*"
|
|
25
26
|
},
|
|
26
27
|
"dependencies": {
|
|
27
|
-
"@paroicms/script-lib": "0.3.
|
|
28
|
+
"@paroicms/script-lib": "0.3.22",
|
|
28
29
|
"arktype": "~2.2.0"
|
|
29
30
|
},
|
|
30
31
|
"peerDependencies": {
|
|
@@ -32,12 +33,12 @@
|
|
|
32
33
|
"@paroicms/public-server-lib": "0"
|
|
33
34
|
},
|
|
34
35
|
"devDependencies": {
|
|
35
|
-
"@paroicms/public-anywhere-lib": "0.43.
|
|
36
|
-
"@paroicms/public-server-lib": "0.56.
|
|
37
|
-
"@paroicms/tiny-modal": "0.8.
|
|
38
|
-
"@types/node": "~24.
|
|
36
|
+
"@paroicms/public-anywhere-lib": "0.43.1",
|
|
37
|
+
"@paroicms/public-server-lib": "0.56.2",
|
|
38
|
+
"@paroicms/tiny-modal": "0.8.4",
|
|
39
|
+
"@types/node": "~24.12.2",
|
|
39
40
|
"rimraf": "~6.1.3",
|
|
40
|
-
"typescript": "~
|
|
41
|
+
"typescript": "~6.0.2"
|
|
41
42
|
},
|
|
42
43
|
"type": "module",
|
|
43
44
|
"main": "backend/dist/index.js",
|