@paroicms/content-loading-plugin 0.27.25 → 0.27.26

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 @@
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})}}
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.5/+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.25",
3
+ "version": "0.27.26",
4
4
  "description": "Content loading plugin for ParoiCMS",
5
5
  "keywords": [
6
6
  "paroicms",
@@ -25,7 +25,7 @@
25
25
  "clear": "rimraf backend/dist/* frontend/dist/*"
26
26
  },
27
27
  "dependencies": {
28
- "@paroicms/script-lib": "0.3.22",
28
+ "@paroicms/script-lib": "0.3.23",
29
29
  "arktype": "~2.2.0"
30
30
  },
31
31
  "peerDependencies": {
@@ -33,9 +33,9 @@
33
33
  "@paroicms/public-server-lib": "0"
34
34
  },
35
35
  "devDependencies": {
36
- "@paroicms/public-anywhere-lib": "0.43.1",
37
- "@paroicms/public-server-lib": "0.56.2",
38
- "@paroicms/tiny-modal": "0.8.4",
36
+ "@paroicms/public-anywhere-lib": "0.43.2",
37
+ "@paroicms/public-server-lib": "0.56.3",
38
+ "@paroicms/tiny-modal": "0.8.5",
39
39
  "@types/node": "~24.12.2",
40
40
  "rimraf": "~6.1.3",
41
41
  "typescript": "~6.0.2"