1import{g as e,gn as t}from"./CoKk4mC0.js";import{t as n}from"./C6cmUah7.js";var r=e=>Array.isArray(e)?e:[e],i=(e,t)=>{let n=[[],[]];for(let r of e)t(r)?n[0].push(r):n[1].push(r);return n},a=Array,o=(e,t)=>e.includes(t),s=(e,t=0)=>[...Array(e)].map((e,n)=>n+t),c=(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),l=(e,t)=>t==null?e??[]:e==null?r(t):e.concat(t),u=(...e)=>e.reduce(l,[]),d=(e,t,n)=>{if(e===void 0)return Array.isArray(t)?t:[t];let i=n?.isEqual??((e,t)=>e===t);for(let n of r(t))e.some(e=>i(e,n))||e.push(n);return e},ee=(e,t)=>e.reduce((e,n)=>{let r=n[t];return e[r]=c(e[r],n),e},{}),f=(e,t,n)=>e.length===t.length&&e.every(n?.isEqual?(e,r)=>n.isEqual(e,t[r]):(e,n)=>e===t[n]),p=(e,t)=>m(e)===t,m=e=>{let t=typeof e;return t===`object`?e===null?`null`:`object`:t===`function`?`object`:t},h={boolean:`boolean`,null:`null`,undefined:`undefined`,bigint:`a bigint`,number:`a number`,object:`an object`,string:`a string`,symbol:`a symbol`},te={...h,function:`a function`},ne=class extends Error{},g=e=>re(e,ne),re=(e,t=Error)=>{throw new t(e)},ie=class extends Error{name=`ParseError`},_=e=>re(e,ie),ae=e=>` ${e}`,v=(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]=c(n[e.group],t):n[e]=t}return i?Object.values(n):n},oe=Object.entries,y=(e,t)=>e in t,se=(e,t)=>t in e,ce=class{constructor(e){Object.assign(this,e)}},le=class{},ue=class extends le{},de=(e,t)=>{let n={},r={},i;for(i in e)i in t?n[i]=e[i]:r[i]=e[i];return[n,r]},fe=(e,t)=>de(e,t)[1],pe=e=>Object.keys(e).length===0,me=e=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map(t=>[t,e[t]])],he=(e,t)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)),ge=e=>{let t=Object.keys(e).sort(),n={};for(let r=0;r<t.length;r++)n[t[r]]=e[t[r]];return n},b=ae(`unsetâ`),_e=e=>Object.values(e).filter(t=>typeof t==`number`||typeof e[t]!=`number`),ve={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},ye=globalThis.File??Blob,be={ArrayBuffer,Blob,File:ye,FormData,Headers,Request,Response,URL},xe={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},Se={...ve,...be,...xe,String,Number,Boolean},Ce=e=>{let t=Object.getPrototypeOf(e);for(;t?.constructor&&(!y(t.constructor.name,Se)||!(e instanceof Se[t.constructor.name]));)t=Object.getPrototypeOf(t);let n=t?.constructor?.name;if(!(n===void 0||n===`Object`))return n},we=e=>typeof e==`object`&&e?Ce(e)??`object`:m(e),x=Array.isArray,Te={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`},Ee={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`},De={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`},Oe={...Te,...Ee,...De},ke=e=>{let t=Object(e).name??null;return t&&y(t,Se)&&Se[t]===e?t:null},Ae=(e,t)=>{let n=e.prototype;for(;n!==null;){if(n===t.prototype)return!0;n=Object.getPrototypeOf(n)}return!1},je=e=>Me(e,new Map),Me=(e,t)=>{if(typeof e!=`object`||!e)return e;if(t?.has(e))return t.get(e);let n=ke(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=Me(n.value,t))}}return Object.defineProperties(r,i),r},Ne=e=>{let t=b;return()=>t===b?t=e():t},Pe=e=>typeof e==`function`&&e.length===0,Fe=class extends Function{constructor(...e){let t=e.slice(0,-1),n=e[e.length-1];try{super(...t,n)}catch(t){return g(`Encountered an unexpected error while compiling your definition: 2 Message: ${t} 3 Source: (${e.slice(0,-1)}) => { 4 ${e[e.length-1]} 5 }`)}}}
5,S=class{constructor(e,...[t]){return Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}},Ie=Ne(()=>{try{return Function(`return false`)()}catch{return!0}});ae(`brand`),ae(`arkInferred`),ae(`args`);var C=class{constructor(){}},Le={fileName:()=>{try{return((Error().stack?.split(` 6`)[2]?.trim()||``).match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||`unknown`).replace(/^file:\/\//,``)}catch{return`unknown`}},env:{}},Re=e=>e[0].toUpperCase()+e.slice(1),ze=e=>e[0].toLowerCase()+e.slice(1),Be=e=>new RegExp(Ve(e),typeof e==`string`?``:e.flags),Ve=e=>`^(?:${typeof e==`string`?e:e.source})$`,w={negativeLookahead:e=>`(?!${e})`,nonCapturingGroup:e=>`(?:${e})`},He={" ":1,"\n":1," ":1},Ue=`^-0\\.?0*$`,We=`[1-9]\\d*`,Ge=`\\.\\d+`,Ke=`\\.\\d*[1-9]`,qe=e=>Be(w.negativeLookahead(Ue)+w.nonCapturingGroup(`-?`+w.nonCapturingGroup(w.nonCapturingGroup(`0|`+We)+w.nonCapturingGroup(e.decimalPattern)+`?`)+(e.allowDecimalOnly?`|`+e.decimalPattern:``)+`?`)),Je=qe({decimalPattern:Ke,allowDecimalOnly:!1}),Ye=Je.test.bind(Je),Xe=qe({decimalPattern:Ge,allowDecimalOnly:!0});Xe.test.bind(Xe);var Ze=/^-?\d*\.?\d*$/,Qe=e=>e.length!==0&&Ze.test(e),$e=Be(w.negativeLookahead(`^-0$`)+`-?`+w.nonCapturingGroup(w.nonCapturingGroup(`0|`+We))),et=$e.test.bind($e),tt=/^-?\d+$/,nt=tt.test.bind(tt),rt={number:`a number`,bigint:`a bigint`,integer:`an integer`},it=(e,t)=>`'${e}' was parsed as ${rt[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,at=(e,t)=>t===`number`?Ye(e):et(e),ot=(e,t)=>t===`number`?Number(e):Number.parseInt(e),st=(e,t)=>t===`number`?Qe(e):nt(e),ct=(e,t)=>dt(e,`number`,t),lt=(e,t)=>dt(e,`number`,{...t,strict:!0}),ut=(e,t)=>dt(e,`integer`,t),dt=(e,t,n)=>{let r=ot(e,t);return!Number.isNaN(r)&&st(e,t)?n?.strict?at(e,t)?r:_(it(e,t)):r:n?.errorOnFail?_(n?.errorOnFail===!0?`Failed to parse ${rt[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($e.test(t))return n;if(tt.test(t))return _(it(e,`bigint`))},pt={version:`0.56.2`,filename:Le.fileName(),FileConstructor:ye},mt=new Map,ht=Object.create(null),gt=e=>{let t=mt.get(e);if(t)return t;let n=vt(e);return ht[n]?n=`${n}${ht[n]++}`:ht[n]=1,pt[n]=e,mt.set(e,n),n},_t=e=>/^[$A-Z_a-z][\w$]*$/.test(e),vt=e=>{switch(typeof e){case`object`:{if(e===null)break;let t=Ce(e)??`object`;return t[0].toLowerCase()+t.slice(1)}case`function`:return _t(e.name)?e.name:`fn`;case`symbol`:return e.description&&_t(e.description)?e.description:`symbol`}return g(`Unexpected attempt to register serializable value of type ${m(e)}`)},yt=e=>typeof e==`string`?JSON.stringify(e):typeof e==`bigint`?`${e}n`:`${e}`,bt=(e,t={})=>St(e,{onUndefined:`$ark.undefined`,onBigInt:e=>`$ark.bigint-${e}`,...t},[]),T=(e,t)=>{switch(m(e)){case`object`:let n=e,r=n.constructor?.name??`Object`;return r===`Object`||r===`Array`?t?.quoteKeys===!1?xt(n,t?.indent??0,``):JSON.stringify(St(n,E,[]),null,t?.indent):xt(n,t?.indent??0,``);case`symbol`:return E.onSymbol(e);default:return yt(e)}},xt=(e,t,n)=>{if(typeof e==`function`)return E.onFunction(e);if(typeof e!=`object`||!e)return yt(e);let r=n+` `.repeat(t);if(Array.isArray(e)){if(e.length===0)return`[]`;let i=e.map(e=>xt(e,t,r)).join(`, 7`+r);return t?`[\n${r}${i}\n${n}]`:`[${i}]`}let i=e.constructor?.name??`Object`;if(i===`Object`){let i=me(e).map(([e,n])=>{let i=typeof e==`symbol`?E.onSymbol(e):_t(e)?e:JSON.stringify(e),a=xt(n,t,r);return`${r}${i}: ${a}`});return i.length===0?`{}`:t?`{\n${i.join(`, 8`)}\n${n}}`:`{${i.join(`, `)}}`}return e instanceof Date?Ct(e):`expression`in e&&typeof e.expression==`string`?e.expression:i},E={onCycle:()=>`(cycle)`,onSymbol:e=>`Symbol(${gt(e)})`,onFunction:e=>`Function(${gt(e)})`},St=(e,t,n)=>{switch(m(e)){case`object`:{let r=e;if(`toJSON`in r&&typeof r.toJSON==`function`)return r.toJSON();if(typeof r==`function`)return E.onFunction(r);if(n.includes(r))return`(cycle)`;let i=[...n,r];if(Array.isArray(r))return r.map(e=>St(e,t,i));if(r instanceof Date)return r.toDateString();let a={};for(let e in r)a[e]=St(r[e],t,i);for(let e of Object.getOwnPropertySymbols(r))a[t.onSymbol?.(e)??e.toString()]=St(r[e],t,i);return a}case`symbol`:return E.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}},Ct=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=`${wt[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+=`.${Et(s,3)}`:Tt.test(l)&&(l=l.slice(0,-3)),`${l+u}, ${c}`},wt=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Tt=/:\d\d:00$/,Et=(e,t)=>
8String(e).padStart(t,`0`),Dt=(e,t,...[n])=>{let r=n?.stringifySymbol??T,i=e;switch(typeof t){case`string`:i=_t(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)}]`:_(`${T(t)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return i},Ot=(e,...t)=>e.reduce((e,n)=>Dt(e,n,...t),``),kt=class extends a{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`?T(this[e]):this[e]);return this.cache.json}stringify(){return this.cache.stringify?this.cache.stringify:this.cache.stringify=Ot(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e=``,t=[e];for(let n of this)e=Dt(e,n),t.push(e);return this.cache.stringifyAncestors=t}},At=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 He))}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}},jt=(e,t)=>`Unmatched ${e}${t===``?``:` before ${t}`}`,Mt=e=>`Missing ${e}`;ae(`implementedTraits`);for(var Nt=`$ark`,Pt=2;Nt in globalThis;)Nt=`$ark${Pt++}`;var Ft=Nt;globalThis[Ft]=pt;var D=pt,It=e=>`${Ft}.${e}`,O=e=>It(gt(e)),Lt=class extends ue{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 Rt(e,t)}index(e,t=!1){return Bt(`${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(` 9`).map(e=>` `.repeat(t)+`${e}`).join(` 10`):this.body} }`}compile(){return new Fe(...this.argNames,this.body)}},k=e=>p(e,`object`)||typeof e==`symbol`?O(e):yt(e),Rt=(e,t=!1)=>typeof e==`string`&&_t(e)?`${t?`?`:``}.${e}`:Bt(zt(e),t),zt=e=>typeof e==`symbol`?O(e):JSON.stringify(e),Bt=(e,t=!1)=>`${t?`?.`:``}[${e}]`,Vt=class extends Lt{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`||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))}},Ht=e=>v(e,(e,t)=>[e,x(t)?[...t]:t]),A=ae(`arkKind`),j=(e,t)=>e?.[A]===t,M=e=>j(e,`root`)||j(e,`constraint`),Ut=[`unit`,`proto`,`domain`],Wt=[`required`,`optional`,`index`,`sequence`],Gt=[`pattern`,`divisor`,`exactLength`,`max`,`min`,`maxLength`,`minLength`,`before`,`after`],Kt=[...Gt,`structure`,`predicate`],qt=[...Kt,...Wt],Jt=[`alias`,`union`,`morph`,`unit`,`intersection`,`proto`,`domain`],Yt=[...Jt,...qt],Xt=v(qt,(e,t)=>[t,1]),Zt=v([...Wt,`undeclared`],(e,t)=>[t,1]),Qt=v(Yt,(e,t)=>[t,e]),$t=e=>typeof e==`string`&&e in Qt,en=e=>Qt[e],tn=e=>Jt.slice(en(e)+1);[...tn(`union`)],[...tn(`morph`)];var N=e=>typeof e==`string`||typeof e==`boolean`||e===null?e:typeof e==`number`?Number.isNaN(e)?`NaN`:e===1/0?`Infinity`:e===-1/0?`-Infinity`:e:k(e),nn=e=>{let t=`{ `;
10for(let[n,r]of Object.entries(e))t+=`${n}: ${k(r)}, `;return t+` }`},P=e=>{let t=e;return t.hasAssociatedError&&(t.defaults.expected??=e=>`description`in e?e.description:t.defaults.description(e),t.defaults.actual??=e=>T(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},F={Error:class extends Error{name=`ToJsonSchemaError`;code;context;constructor(e,t){super(T(t,{quoteKeys:!1,indent:4})),this.code=e,this.context=t}hasCode(e){return this.code===e}},throw:(...e)=>{throw new F.Error(...e)},throwInternalOperandError:(e,t)=>g(`Unexpected JSON Schema input for ${e}: ${T(t)}`),defaultConfig:{target:`draft-2020-12`,dialect:`https://json-schema.org/draft/2020-12/schema`,useRefs:!1,fallback:{arrayObject:e=>F.throw(`arrayObject`,e),arrayPostfix:e=>F.throw(`arrayPostfix`,e),defaultValue:e=>F.throw(`defaultValue`,e),domain:e=>F.throw(`domain`,e),morph:e=>F.throw(`morph`,e),patternIntersection:e=>F.throw(`patternIntersection`,e),predicate:e=>F.throw(`predicate`,e),proto:e=>F.throw(`proto`,e),symbolKey:e=>F.throw(`symbolKey`,e),unit:e=>F.throw(`unit`,e),date:e=>F.throw(`date`,e)}}};D.config??={};var rn=(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]=on(e.toJsonSchema,t.toJsonSchema):$t(r)?n[r]={...e[r],...t[r]}:n[r]=t[r]}return n},an={"draft-2020-12":`https://json-schema.org/draft/2020-12/schema`,"draft-07":`http://json-schema.org/draft-07/schema#`},on=((e,t)=>{if(!e)return sn(t??{},void 0);if(!t)return e;let n={...e},r;for(r in t)r===`fallback`?n.fallback=cn(e.fallback,t.fallback):n[r]=t[r];return sn(n,t)}),sn=(e,t)=>t?.dialect===void 0?t?.target===void 0?e:{...e,dialect:an[t.target]}:e,cn=(e,t)=>{e=ln(e),t=ln(t);let n={},r;for(r in F.defaultConfig.fallback)n[r]=t[r]??t.default??e[r]??e.default??F.defaultConfig.fallback[r];return n},ln=e=>typeof e==`function`?{default:e}:e??{},un=class e extends ue{[A]=`error`;path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:t,...n},r){super(),this.input=n,this.ctx=r,he(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:u(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 kt(...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 Ot(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}},dn=class e extends a{[A]=`errors`;static get[Symbol.species](){return Array}ctx;constructor(e){super(),this.ctx=e}byPath=Object.create(null);get flatByPath(){return v(this.byPath,(e,t)=>[e,t.flat])}get flatProblemsByPath(){return v(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 fn(this)}add(e){let t=this.byPath[e.propString];if(t){if(e===t||t.hasCode(`union`)&&t.errors.length===0)return;
10let n=e.hasCode(`union`)&&e.errors.length===0?e:new un({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 un({...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(` 11`)}addAncestorPaths(e){for(let t of e.path.stringifyAncestors())this.byAncestorPath[t]=c(this.byAncestorPath[t],e)}},fn=class extends Error{name=`TraversalError`;constructor(e){e.length===1?super(e.summary):super(` 12`+e.map(e=>` ⢠${pn(e)}`).join(` 13`)),Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}},pn=e=>e.toString().split(` 14`).join(` 15 `),mn=class{path=[];errors=new dn(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 Ot(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 kt(...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: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 un(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=M(i),a=i(r===void 0?this.root:r[n],this);if(a instanceof un){this.errors.add(a);break}if(a instanceof dn){t||this.errors.merge(a),this.queuedMorphs=[];break}r===void 0?this.root=a:r[n]=a,this.applyQueuedMorphs()}}},I=(e,t,n)=>{if(!n)return t();n.path.push(e);let r=t();return n.path.pop(),r},hn=class extends S{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)=>Cn(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=>xn(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)=>
15e.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 mn(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 mn(e,this.$.resolvedConfig);return this.traverseApply(e,n),n.finalize(t)};case`contextual`:return(e,t)=>{let n=new mn(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 mn(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case`branchedOptimistic`:return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,g(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=bn(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]=x(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=M(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&&re(`${this.kind} node was not of asserted kind ${e}`),this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){return o(e,this.kind)||re(`${this.kind} node was not one of asserted kinds ${e}`),this}isBasis(){return o(Ut,this.kind)}isConstraint(){return o(qt,this.kind)}isStructural(){return o(Wt,this.kind)}isRefinement(){return o(Kt,this.kind)}isRoot(){return o(Jt,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=gn.normalize(e);return this._select(t)}_select(e){let t=gn.applyBoundary[e.boundary??`references`](this);return e.kind&&(t=t.filter(t=>t.kind===e.kind)),e.where&&(t=t.filter(e.where)),gn.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=v(this.inner,(n,r)=>{if(!this.impl.keys[n].child)return[n,r];let i=r;if(!x(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(M(o))return r=o;let s=Object.keys(o);return(s.length===0||s.length===1&&s[0]===`meta`)&&!pe(this.inner)?null:(this.kind===`required`||this.kind===`optional`||this.kind===`index`)&&!(`value`in o)?t.undeclaredKeyHandling?{...o,value:D.intrinsic.unknown}:null:(this.kind===`morph`&&(o.in??=D.intrinsic.unknown),r=n.node(this.kind,o,t.parseOptions))}configureReferences(e,t=`references`){let n=gn.normalize(t),i=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,i(this.kind,{...this.inner,meta:this.meta}));let a=this._select(n),o=a&&r(a),s=n.boundary===`child`?(e,t)=>t.root.children.includes(e):n.boundary===`shallow`?e=>e.kind!==`structure`:()=>!0;return this.$.finalize(this.transform(i,{shouldTransform:s,selected:o}))}},gn={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&&re(_n(t,n)),e),find:e=>e[0],assertFind:(e,t,n)=>(e.length===0&&re(_n(t,n)),e[0])},normalize:e=>typeof e==`function`?{boundary:`references`,method:`filter`,where:e}:typeof e==`string`?y(e,gn.applyBoundary)?{method:`filter`,boundary:e}:{boundary:`references`,method:`filter`,kind:e}:{boundary:`references`,method:`filter`,...e}},_n=(e,t)=>`${e} had no references matching ${T(t)}.`,vn=e=>Ot(e,{stringifyNonKey:e=>e.expression}),yn=/"(\$ark\.[^"]+)"/g,bn=e=>JSON.stringify(e).replace(yn,`$1`),L=(e,t)=>({path:e,node:t,propString:vn(e)}),xn=(e,t)=>e.propString===t.propString&&e.node.equals(t.node),Sn=(e,t)=>d(e,t,{isEqual:xn}),Cn=(e,t)=>d(e,t,{isEqual:(e,t)=>e.equals(t)}),R=class e extends Array{static init(t,n,r,i){return new e({kind:t,l:n,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=Ot(e);return En(`Intersection${r&&` at ${r}`} of ${wn(t,n)}`)}return`The following intersections result in unsatisfiable types:\n⢠${this.map(({path:e,l:t,r:n})=>`${e}: ${wn(t,n)}`).join(` 16⢠`)}`}throw(){return _(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`}))}
16toNeverIfDisjoint(){return D.intrinsic.never}},wn=(e,t)=>`${Tn(e)} and ${Tn(t)}`,Tn=e=>M(e)?e.expression:x(e)?e.map(Tn).join(` | `)||`never`:String(e),En=e=>`${e} results in an unsatisfiable type`,Dn={},z=(e,t,n)=>B(e,t,{$:n,invert:!1,pipe:!1}),On=(e,t,n)=>B(e,t,{$:n,invert:!1,pipe:!0}),B=((e,t,n)=>{let r=n.pipe?`|>`:`&`,i=`${e.hash}${r}${t.hash}`;if(Dn[i]!==void 0)return Dn[i];if(!n.pipe){let n=`${t.hash}${r}${e.hash}`;if(Dn[n]!==void 0){let e=Dn[n],t=e instanceof R?e.invert():e;return Dn[i]=t,t}}let a=!n.pipe||!e.includesTransform&&!t.includesTransform;if(a&&e.equals(t))return e;let o=a?kn(e,t,n):e.hasKindIn(...Jt)?An(e,t,n):kn(e,t,n);return M(o)&&(e.equals(o)?o=e:t.equals(o)&&(o=t)),Dn[i]=o,o}),kn=(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 R&&(r=r.invert()),r}},An=(e,t,n)=>e.includesTransform||t.includesTransform?n.invert?jn(t,e,n):jn(e,t,n):kn(e,t,n),jn=(e,t,n)=>e.distribute(e=>Mn(e,t,n),r=>{let i=r.filter(M);if(i.length===0)return R.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)}),Mn=(e,t,n)=>{if(e.hasKind(`morph`)){let r=[...e.morphs];if(e.lastMorphIfNode){let i=B(e.lastMorphIfNode,t,n);if(i instanceof R)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=B(e,t.rawIn,n);return r instanceof R?r:n.$.node(`morph`,{morphs:[t],in:r})}return n.$.node(`morph`,{morphs:[t],in:e})},Nn=class extends hn{constructor(e,t){super(e,t),Object.defineProperty(this,A,{value:`constraint`,enumerable:!1})}impliedSiblings;intersect(e){return z(this,e,this.$)}},Pn=class extends Nn{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 nn(this.errorContext)}},V=e=>(t,n)=>{if(x(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);if(!r.isRoot())return r.hasOpenIntersection()?[r]:r},Fn=e=>{let t=e.r.shift();if(!t){let t=e.l.length===0&&e.kind===`structure`?D.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,Ln(e.l)),{prereduced:!0});for(let n of e.roots){if(t instanceof R)return t;t=B(n,t,e.ctx)}return t}let n=!1;for(let r=0;r<e.l.length;r++){let i=B(e.l[r],t,e.ctx);if(i!==null){if(i instanceof R)return i;if(i.isRoot())return e.roots.push(i),e.l.splice(r),Fn(e);if(!n)e.l[r]=i,n=!0;else if(!e.l.includes(i))return g(`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)d(e.r,n);return Fn(e)},In=e=>Object.entries(e).flatMap(([e,t])=>e in Xt?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),Ln=e=>{let t={};for(let n of e)if(n.hasOpenIntersection())t[n.kind]=c(t[n.kind],n);else{if(t[n.kind])return g(`Unexpected intersection of closed refinements of kind ${n.kind}`);t[n.kind]=n}return t},Rn=(...e)=>_(zn(...e)),zn=(e,t,n)=>{let r=n.hasKind(`morph`)?`a morph`:n.isUnknown()?`unknown`:n.exclude(t).defaultShortDescription;return`${Re(e)} operand must be ${t.description} (was ${r})`},Bn=(e,t,n)=>new Hn(e,t,n,n,null),Vn=class extends S{},Hn=class extends S{[A]=`generic`;paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,t,n,r,i){super((...e)=>{let n=v(this.names,(t,n)=>{let r=this.arg$.parse(e[t]);return r.extends(this.constraints[t])||_(Un(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 Vn}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:bt(this.bodyDef)})}get params(){return this.cacheGetter(`params`,this.paramDefs.map(e=>typeof e==`string`?[e,D.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}},Un=(e,t,n)=>`${e} must be assignable to ${t} (was ${n})`,Wn={implementation:P({kind:`predicate`,hasAssociatedError:!0,
16collapsibleKey:`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 Nn{serializedPredicate=O(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=nn(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})}}},Gn={implementation:P({kind:`divisor`,collapsibleKey:`rule`,keys:{rule:{parse:e=>Number.isInteger(e)?e:_(Kn(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/qn(e.rule,t.rule))})},obviatesBasisDescription:!0}),Node:class extends Pn{traverseAllows=e=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=D.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){return e.type=`integer`,this.rule===1||(e.multipleOf=this.rule),e}}},Kn=e=>`divisor must be an integer (was ${e})`,qn=(e,t)=>{let n,r=e,i=t;for(;i!==0;)n=i,i=r%i,r=n;return r},Jn=class extends Pn{boundOperandKind=rr[this.kind];compiledActual=this.boundOperandKind===`value`?`data`:this.boundOperandKind===`length`?`data.length`:`data.valueOf()`;comparator=ir(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${Yn[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind===`date`?ar(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}},Yn={"<":`>=`,"<=":`>`,">":`<=`,">=":`<`},Xn={min:`max`,minLength:`maxLength`,after:`before`},Zn={parse:e=>e||void 0},Qn=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},$n=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},er=e=>typeof e==`string`||typeof e==`number`?new Date(e):e,tr=(e,t)=>`${e} bound must be a positive integer (was ${t})`,nr=e=>t=>((!Number.isInteger(t)||t<0)&&_(tr(e,t)),t),rr={min:`value`,max:`value`,minLength:`length`,maxLength:`length`,after:`date`,before:`date`},ir=(e,t)=>`${y(e,Xn)?`>`:`<`}${t?``:`=`}`,ar=e=>typeof e==`string`?e:new Date(e).toLocaleString(),or=e=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`,sr={implementation:P({kind:`after`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:er,serialize:e=>e.toISOString()}},normalize:$n(`after`),defaults:{description:e=>`${e.collapsibleLimitString} or later`,actual:Ct},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}}),Node:class extends Jn{impliedBasis=D.intrinsic.Date.internal;collapsibleLimitString=Ct(this.rule);traverseAllows=e=>e>=this.rule;reduceJsonSchema(e,t){return t.fallback.date({code:`date`,base:e,after:this.rule})}}},cr={implementation:P({kind:`before`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:er,serialize:e=>e.toISOString()}},normalize:$n(`before`),defaults:{description:e=>`${e.collapsibleLimitString} or earlier`,actual:Ct},intersections:{before:(e,t)=>
16e.isStricterThan(t)?e:t,after:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node(`unit`,{unit:e.rule}):null:R.init(`range`,e,t)}}),Node:class extends Jn{collapsibleLimitString=Ct(this.rule);traverseAllows=e=>e<=this.rule;impliedBasis=D.intrinsic.Date.internal;reduceJsonSchema(e,t){return t.fallback.date({code:`date`,base:e,before:this.rule})}}},lr={implementation:P({kind:`exactLength`,collapsibleKey:`rule`,keys:{rule:{parse:nr(`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)=>R.init(`unit`,n.$.node(`unit`,{unit:e.rule}),n.$.node(`unit`,{unit:t.rule}),{path:[`length`]}),minLength:(e,t)=>e.rule>=t.rule?e:R.init(`range`,e,t),maxLength:(e,t)=>e.rule<=t.rule?e:R.init(`range`,e,t)}}),Node:class extends Pn{traverseAllows=e=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=D.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 F.throwInternalOperandError(`exactLength`,e)}}}},ur={implementation:P({kind:`max`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{},exclusive:Zn},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:R.init(`range`,e,t)}
16,obviatesBasisDescription:!0}),Node:class extends Jn{impliedBasis=D.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}}},dr={implementation:P({kind:`maxLength`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:nr(`maxLength`)}},reduce:(e,t)=>e.rule===0?t.node(`exactLength`,e):void 0,normalize:Qn(`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:R.init(`range`,e,t)}}),Node:class extends Jn{impliedBasis=D.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 F.throwInternalOperandError(`maxLength`,e)}}}},fr={implementation:P({kind:`min`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{},exclusive:Zn},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 Jn{impliedBasis=D.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}}},pr={implementation:P({kind:`minLength`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:nr(`minLength`)}},reduce:e=>e.rule===0?D.intrinsic.unknown:void 0,normalize:Qn(`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 Jn{impliedBasis=D.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 F.throwInternalOperandError(`minLength`,e)}}}},mr={min:fr.implementation,max:ur.implementation,minLength:pr.implementation,maxLength:dr.implementation,exactLength:lr.implementation,after:sr.implementation,before:cr.implementation},hr={min:fr.Node,max:ur.Node,minLength:pr.Node,maxLength:dr.Node,exactLength:lr.Node,after:sr.Node,before:cr.Node},gr={implementation:P({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 Pn{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=D.intrinsic.string.internal;reduceJsonSchema(e,t){return e.pattern?t.fallback.patternIntersection({code:`patternIntersection`,base:e,pattern:this.rule}):(e.pattern=this.rule,e)}}},_r=(e,t)=>{let n=vr(e);return t&&!t.includes(n)?_(`Root of kind ${n} should be one of ${t}`):n},vr=e=>{if(j(e,`root`))return e.kind;if(typeof e==`string`)return e[0]===`$`?`alias`:e in h?`domain`:`proto`;if(typeof e==`function`)return`proto`;if(typeof e!=`object`||!e)return _(yr(e));if(`morphs`in e)return`morph`;if(`branches`in e||x(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 Xt)?`intersection`:`proto`in e?`proto`:`domain`in e?`domain`:_(yr(e))},yr=e=>`${T(e)} is not a valid type schema`,br={},xr=e=>x(e)?e.map(e=>e.collapsibleJson):e.collapsibleJson,H={};D.nodesByRegisteredId=H;var Sr=e=>(br[e]??=0,`${e}${++br[e]}`),Cr=e=>{let t=ca[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])=>$t(e)?$t(t)?en(e)-en(t):1:$t(t)||e<t?-1:1).filter(([e,t])=>
16{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 _(`Key ${i} is not valid on ${e.kind} schema`);let o=a.parse?a.parse(n[1],e):n[1];o!==b&&(o!==void 0||a.preserveUndefined)&&(r[i]=o)}if(t.reduce&&!e.prereduced){let n=t.reduce(r,e.$);if(n)return n instanceof R?n.throw():Er(n,o)}return wr({id:e.id,kind:e.kind,inner:r,meta:o,$:e.$})},wr=({id:e,kind:t,inner:n,meta:r,$:i,ignoreCache:a})=>{let o=ca[t],s=oe(n),c=[],l={};for(let[e,t]of s){let n=o.keys[e],r=n.serialize??(n.child?xr:N);if(l[e]=r(t),n.child===!0){let e=t;x(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={};pe(r)||(d=v(r,(e,t)=>[e,e===`examples`?t:N(t)]),u.meta=Dr(d,`description`,!0)),l=Dr(l,o.collapsibleKey,!1);let ee=JSON.stringify({kind:t,...l});u=Dr(u,o.collapsibleKey,!1);let f=Dr(u,o.collapsibleKey,!0),p=JSON.stringify({kind:t,...u});if(i.nodesByHash[p]&&!a)return i.nodesByHash[p];let m={id:e,kind:t,impl:o,inner:n,innerEntries:s,innerJson:l,innerHash:ee,meta:r,metaJson:d,json:u,hash:p,c
16ollapsibleJson:f,children:c};if(t!==`intersection`)for(let e in n)e!==`in`&&e!==`out`&&(m[e]=n[e]);let h=new la[t](m,i);return i.nodesByHash[p]=h},Tr=(e,t)=>e.id===t?e:(M(H[t])&&g(`Unexpected attempt to overwrite node id ${t}`),wr({id:t,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})),Er=(e,t,n)=>(n&&M(H[n])&&g(`Unexpected attempt to overwrite node id ${n}`),wr({id:n??Sr(t.alias??e.kind),kind:e.kind,inner:e.inner,meta:t,$:e.$})),Dr=(e,t,n)=>{let r=Object.keys(e);if(r.length===1&&r[0]===t){let r=e[t];if(n||p(r,`object`)&&(Object.keys(r).length===1||Array.isArray(r)))return r}return e},Or=(e,t,n)=>{if(e.key!==t.key)return null;let r=e.key,i=B(e.value,t.value,n),a=e.required||t.required?`required`:`optional`;if(i instanceof R)if(a===`optional`)i=D.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:_(Ar(e.default,t.default)):e.default:t.hasDefault()?t.default:b;return n.$.node(`optional`,{key:r,value:i,default:o})},kr=class extends Nn{required=this.kind===`required`;optional=this.kind===`optional`;impliedBasis=D.intrinsic.object.internal;serializedKey=k(this.key);compiledKey=typeof this.key==`string`?this.key:this.serializedKey;flatRefs=c(this.value.flatRefs.map(e=>L([this.key,...e.path],e.node)),L([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?I(this.key,()=>this.value.traverseAllows(e[this.key],t),t):this.optional;traverseApply=(e,t)=>{this.key in e?I(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)}},Ar=(e,t)=>`Invalid intersection of default values ${T(e)} & ${T(t)}`,jr={implementation:P({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(G.undefined)},{prereduced:!0})},defaults:{description:e=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:Or}}),Node:class extends kr{constructor(...e){super(...e),`default`in this.inner&&Fr(this.value,this.inner.default,this.key)}get rawIn(){let e=super.rawIn;return this.hasDefault()?this.$.node(`optional`,fe(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} = ${T(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=Nr(this);defaultValueMorphRef=this.defaultValueMorph&&O(this.defaultValueMorph)}},Mr={},Nr=e=>{if(!e.hasDefault())return;let t=`{${e.compiledKey}: ${e.value.id} = ${N(e.default)}}`;return Mr[t]??=Pr(e.key,e.value,e.default)},Pr=(e,t,n)=>{if(typeof n==`function`)return t.includesTransform?(r,i)=>(I(e,()=>t(r[e]=n(),i),i),r):t=>(t[e]=n(),t);let r=t.includesTransform?t.assert(n):n;return p(r,`object`)?(r,i)=>(I(e,()=>t(r[e]=n,i),i),r):t=>(t[e]=r,t)},Fr=(e,t,n)=>{let r=Pe(t);p(t,`object`)&&!r&&_(Ir(n));let i=e.in(r?t():t);return i instanceof dn&&(n===null&&_(`Default ${i.summary}`),_(`Default for ${i.transform(e=>e.transform(e=>({...e,prefixPath:[n]}))).summary}`)),t},Ir=e=>`Non-primitive default ${e===null?``:typeof e==`number`?`for value at [${e}] `:`for ${k(e)} `}must be specified as a function like () => ({my: 'object'})`,Lr=class extends hn{constructor(e,t){super(e,t),Object.defineProperty(this,A,{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 dn?t:{value:t}},jsonSchema:{input:e=>this.rawIn.toJsonSchema({target:Vr(e.target),...e.libraryOptions}),output:e=>this.rawOut.toJsonSchema({target:Vr(e.target),...e.libraryOptions})}}}as(){return this}brand(e){return e===``?_(Rr):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.defaultShortDe
16scription}toJsonSchema(e={}){let t=on(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=v(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 R?n:this.$.finalize(n)}rawIntersect(e){return z(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){let t=this.intersect(e);return t instanceof R?t.throw():t}rawAnd(e){let t=this.rawIntersect(e);return t instanceof R?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(),D.intrinsic.unknown.internal);return e.branches.length===0&&_(En(`keyof ${this.expression}`)),this._keyof=this.$.finalize(e)}get props(){return this.branches.length===1?[...this.applyStructuralOperation(`props`,[])[0]]:_(Gr(this.expression))}merge(e){let t=this.$.parseDefinition(e);return this.$.schema(t.distribute(e=>this.applyStructuralOperation(`merge`,[Wr(e)??_(Kr(`merge`,e.expression))])))}applyStructuralOperation(e,t){return this.distribute(n=>{if(n.equals(D.intrinsic.object)&&e!==`merge`)return n;let r=Wr(n);if(r||_(Kr(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 R)}extends(e){if(this.isNever())return!0;let t=this.intersect(e);return!(t instanceof R)&&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 Fr(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(j(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=On(this,e,this.$);return t instanceof R?t.throw():t}rawPipeOnce(e){return j(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:g(`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 Rn(t,r.impliedBasis,this);let a=this.$.node(`intersection`,{[r.kind]:r}),o=e===`out`?On(this,a,this.$):z(this,a,this.$);return o instanceof R&&o.throw(),this.$.finalize(o)}onUndeclaredKey(e){let t=typeof e==`string`?e:e.rule,n=typeof e!=`string`&&e.deep;return this.$.finalize(this.transform((e,n)=>e===`structure`?t===`ignore`?fe(n,{undeclared:1}):{...n,undeclared:t}:n,n?void 0:{shouldTransform:e=>!o(Wt,e.kind)}))}
16hasEqualMorphs(e){return!this.includesTransform&&!e.includesTransform||!(!f(this.shallowMorphs,e.shallowMorphs)||!f(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`,Hr(e))}lessThan(e){return this.constrain(`max`,Hr(e))}atLeastLength(e){return this.constrain(`minLength`,e)}atMostLength(e){return this.constrain(`maxLength`,e)}moreThanLength(e){return this.constrain(`minLength`,Hr(e))}lessThanLength(e){return this.constrain(`maxLength`,Hr(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`,Hr(e))}earlierThan(e){return this.constrain(`before`,Hr(e))}},Rr=`Expected a non-empty brand name after #`,zr=[`draft-2020-12`,`draft-07`],Br=e=>`JSONSchema target '${e}' is not supported (must be ${zr.map(e=>`"${e}"`).join(` or `)})`,Vr=e=>(o(zr,e)||_(Br(e)),e),Hr=e=>typeof e==`object`&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},Ur=(e,t)=>j(t,`root`)?j(e,`root`)?e.extends(t):t.allows(e):j(e,`root`)?e.hasUnit(t):t===e,Wr=e=>e.hasKind(`morph`)?null:e.hasKind(`intersection`)?e.inner.structure??(e.basis?.domain===`object`?e.$.bindReference(D.intrinsic.emptyStructure):null):e.isBasis()&&e.domain===`object`?e.$.bindReference(D.intrinsic.emptyStructure):null,Gr=e=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received: 17${e}`,Kr=(e,t)=>`${e} operand must be an object (was ${t})`,qr=(e,t)=>v(tn(e),(e,n)=>[n,t]),Jr=e=>typeof e==`string`?{reference:e}:e,Yr=e=>e instanceof R?D.intrinsic.never.internal:e,Xr=P({kind:`alias`,hasAssociatedError:!1,collapsibleKey:`reference`,keys:{reference:{serialize:e=>e.startsWith(`$`)?e:`$ark.${e}`},resolve:{}},normalize:Jr,defaults:{description:e=>e.reference},intersections:{alias:(e,t,n)=>n.$.lazilyResolve(()=>Yr(B(e.resolution,t.resolution,n)),`${e.reference}${n.pipe?`=>`:`&`}${t.reference}`),...qr(`alias`,(e,t,n)=>t.isUnknown()?e:t.isNever()?t:t.isBasis()&&!t.overlaps(D.intrinsic.object)?R.init(`assignability`,D.intrinsic.object,t):n.$.lazilyResolve(()=>Yr(B(e.resolution,t,n)),`${e.reference}${n.pipe?`=>`:`&`}${t.id}`))}}),Zr=class extends Lr{expression=this.reference;structure=void 0;get resolution(){let e=this._resolve();return H[this.id]=e}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]===`$`)return this.$.resolveRoot(this.reference.slice(1));let e=H[this.reference],t=[];for(;j(e,`context`);){if(t.includes(e.id))return _(Qr(e.id,t));t.push(e.id),e=H[e.id]}return j(e,`root`)?e:g(`Unexpected resolution for reference ${this.reference} 18Seen: [${t.join(`->`)}] 19Resolution: ${T(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:j(t,`root`)?t.id:g(`Unexpected resolution for reference ${this.reference}: ${T(t)}`)}get defaultShortDescription(){return h.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]=c(n,e),this.resolution.traverseAllows(e,t))};traverseApply=(e,t)=>{let n=t.seen[this.reference];n?.includes(e)||(t.seen[this.reference]=c(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))}},Qr=(e,t)=>
19`Alias '${e}' has a shallow resolution cycle: ${[...t,e].join(`->`)}`,$r={implementation:Xr,Node:Zr},ei=class extends Lr{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 nn(this.errorContext)}compile(e){e.traversalKind===`Allows`?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}},ti={implementation:P({kind:`domain`,hasAssociatedError:!0,collapsibleKey:`domain`,keys:{domain:{},numberAllowsNaN:{}},normalize:e=>typeof e==`string`?{domain:e}:se(e,`numberAllowsNaN`)&&e.domain!==`number`?_(ti.writeBadAllowNanMessage(e.domain)):e,applyConfig:(e,t)=>e.numberAllowsNaN===void 0&&e.domain===`number`&&t.numberAllowsNaN?{...e,numberAllowsNaN:!0}:e,defaults:{description:e=>h[e.domain],actual:e=>Number.isNaN(e)?`NaN`:h[m(e)]},intersections:{domain:(e,t)=>e.domain===`number`&&t.domain===`number`?e.numberAllowsNaN?t:e:R.init(`domain`,e,t)}}),Node:class extends ei{requiresNaNCheck=this.domain===`number`&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?e=>typeof e==`number`&&!Number.isNaN(e):e=>m(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 h[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})`},ni={implementation:P({kind:`intersection`,hasAssociatedError:!0,normalize:e=>{if(M(e))return e;let{structure:t,...n}=e,r=!!t,i=t??{},a=v(n,(e,t)=>y(e,Zt)?(r&&_(`Flattened structure key ${e} cannot be specified alongside a root 'structure' key.`),i[e]=t,[]):[e,t]);return(j(i,`constraint`)||!pe(i))&&(a.structure=i),a},finalizeInnerJson:({structure:e,...t})=>p(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:V(`divisor`)},max:{child:!0,parse:V(`max`)},min:{child:!0,parse:V(`min`)},maxLength:{child:!0,parse:V(`maxLength`)},minLength:{child:!0,parse:V(`minLength`)},exactLength:{child:!0,parse:V(`exactLength`)},before:{child:!0,parse:V(`before`)},after:{child:!0,parse:V(`after`)},pattern:{child:!0,parse:V(`pattern`)},predicate:{child:!0,parse:V(`predicate`)}},reduce:(e,t)=>ii({},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(` 20 ⦠`)}`,problem:e=>`(${e.actual}) must be...\n${e.expected}`},intersections:{intersection:(e,t,n)=>ii(e.inner,t.inner,n),...qr(`intersection`,(e,t,n)=>{if(e.children.length===0)return t;let{domain:r,proto:i,...a}=e.inner,o=i??r,s=o?B(o,t,n):t;
20return s instanceof R?s:e?.basis?.equals(s)?e:e.$.node(`intersection`,{...a,[s.kind]:s},{prereduced:!0})})}}),Node:class extends Lr{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter(e=>e.isRefinement()?(o(Gt,e.kind)&&this.prestructurals.push(e),!0):!1);structure=this.inner.structure;expression=ri(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])}}}},ri=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?` `:``}${n}`;return r===`Array == 0`?`[]`:r||`unknown`},ii=(e,t,n)=>{let r={},i=e.proto??e.domain,a=t.proto??t.domain,o=i?a?B(i,a,n):i:a;return o instanceof R?o:(o&&(r[o.kind]=o),Fn({kind:`intersection`,baseInner:r,l:In(e),r:In(t),roots:[],ctx:n}))},ai={implementation:P({kind:`morph`,hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},morphs:{parse:r,serialize:e=>e.map(e=>j(e,`root`)?e.json:O(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)=>
20{if(!e.hasEqualMorphs(t))return _(oi(e.expression,t.expression));let r=B(e.rawIn,t.rawIn,n);if(r instanceof R)return r;let i={morphs:e.morphs};if(e.declaredIn||t.declaredIn){let r=B(e.rawIn,t.rawIn,n);if(r instanceof R)return r.throw();i.declaredIn=r}if(e.declaredOut||t.declaredOut){let r=B(e.rawOut,t.rawOut,n);if(r instanceof R)return r.throw();i.declaredOut=r}return r.distribute(e=>n.$.node(`morph`,{...i,in:e}),n.$.parseSchema)},...qr(`morph`,(e,t,n)=>{let r=e.inner.in?B(e.inner.in,t,n):t;return r instanceof R?r:r.equals(e.inner.in)?e:n.$.node(`morph`,{...e.inner,in:r})})}}),Node:class extends Lr{serializedMorphs=this.morphs.map(O);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=j(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??D.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??D.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)};
20hasEqualMorphs(e){return f(this.morphs,e.morphs,{isEqual:(e,t)=>e===t||j(e,`root`)&&j(t,`root`)&&e.equals(t)})}}},oi=(e,t)=>`The intersection of distinct morphs at a single path is indeterminate: 21Left: ${e} 22Right: ${t}`,si={implementation:P({kind:`proto`,hasAssociatedError:!0,collapsibleKey:`proto`,keys:{proto:{serialize:e=>ke(e)??N(e)},dateAllowsInvalid:{}},normalize:e=>{let t=typeof e==`string`?{proto:Se[e]}:typeof e==`function`?M(e)?e:{proto:e}:typeof e.proto==`string`?{...e,proto:Se[e.proto]}:e;return typeof t.proto!=`function`&&_(si.writeInvalidSchemaMessage(t.proto)),se(t,`dateAllowsInvalid`)&&t.proto!==Date&&_(si.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?Oe[e.builtinName]:`an instance of ${e.proto.name}`,actual:e=>e instanceof Date&&e.toString()===`Invalid Date`?`an invalid Date`:we(e)},intersections:{proto:(e,t)=>e.proto===Date&&t.proto===Date?e.dateAllowsInvalid?t:e:Ae(e.proto,t.proto)?e:Ae(t.proto,e.proto)?t:R.init(`proto`,e,t),domain:(e,t)=>t.domain===`object`?e:R.init(`domain`,D.intrinsic.object.internal,t)}}),Node:class extends ei{builtinName=ke(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 ${m(e)})`}
22,ci=P({kind:`union`,hasAssociatedError:!0,collapsibleKey:`branches`,keys:{ordered:{},branches:{child:!0,parse:(e,t)=>{let n=[];for(let r of e){let e=j(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=>x(e)?{branches:e}:e,reduce:(e,t)=>{let n=Ci(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,xi),expected:e=>{let t=ee(e.errors,`propString`);return xi(Object.entries(t).map(([e,t])=>{let n=[];for(let e of t)d(n,e.expected);let r=xi(n),i=t.every(e=>e.actual===t[0].actual)?t[0].actual:T(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 R.init(`presence`,e,t);let r;return e.ordered?(t.ordered&&_(Di(e.expression,t.expression)),r=Si(t.branches,e.branches,n),r instanceof R&&r.invert()):r=Si(e.branches,t.branches,n),r instanceof R?r:n.$.parseSchema(e.ordered||t.ordered?{branches:r,ordered:!0}
22:{branches:r})},...qr(`union`,(e,t,n)=>{let r=Si(e.branches,[t],n);return r instanceof R?r:r.length===1?r[0]:n.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}}),li=class extends Lr{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]=D.intrinsic.boolean;continue}e.push(n)}return e}unitBranches=this.branches.filter(e=>e.rawIn.hasKind(`unit`));discriminant=this.discriminate();discriminantJson=this.discriminant?vi(this.discriminant):null;expression=this.distribute(e=>e.nestableExpression,bi);createBranchedOptimisticRootApply(){return(e,t)=>{let n=this.traverseOptimistic(e);if(n!==b)return n;let r=new mn(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize(t)}}get shallowMorphs(){return this.branches.reduce((e,t)=>d(e,t.shallowMorphs),[])}get defaultShortDescription(){return this.distribute(e=>e.defaultShortDescription,xi)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(D.intrinsic.boolean))return{type:`boolean`};let t=this.branchGroups.map(t=>t.toJsonSchemaRecurse(e));return t.every(e=>Object.keys(e).length===1&&se(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 b};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)} ? ${O(r.contextFreeMorph)}(data) : "${b}"`:`${e.invoke(r)} ? data : "${b}"`:e.invoke(r),e.line(`${a}: return ${o}`)}return e}),e.traversalKind===`Allows`){e.return(i?`"${b}"`:!1);return}let a=xi(this.discriminant.kind===`domain`?r.map(e=>{let t=e.slice(1,-1);return t===`function`?h.object:h[t]}):r),o=this.discriminant.path.map(e=>typeof e==`symbol`?O(e):JSON.stringify(e)),s=JSON.stringify(a),c=this.discriminant.kind===`domain`?`${hi}[${t}]`:`${gi}(${t})`;e.line(`ctx.errorFromNodeContext({ 23 code: "predicate", 24 expected: ${s}, 25 actual: ${c}, 26 relativePath: [${o}], 27 meta: ${this.compiledMeta} 28})`)}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?`${O(n.contextFreeMorph)}(data)`:`data`:!0));e.return(t?`"${b}"`:!1)}}get nestableExpression(){return this.isBoolean?`boolean`:`(${this.expression})`}discriminate(){if(this.branches.length<2)return null;if(this.unitBranches.length===this.branches.length)return{kind:`unit`,path:[],optionallyChainedPropString:`data`,cases:v(this.unitBranches,(e,t)=>[`${t.rawIn.serializedValue}`,!t.hasKind(`morph`)||t])};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=z(n.rawIn,i.rawIn,n.$);if(a instanceof R)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=>f(e.path,n.path)&&e.kind===n.kind);o?(o.cases[i]?o.cases[i].branchIndices=d(o.cases[i].branchIndices,t):o.cases[i]??={branchIndices:[t],
28condition:n.l},o.cases[a]?o.cases[a].branchIndices=d(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?fi(e,this.branches):e;if(!t.length)return null;let n=ui(t,this),r={};for(let e in n.best.cases){let t=di(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})}},ui=(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:mi(n.path)},defaultEntries:t.branches.map((e,t)=>({originalIndex:t,branch:e})),node:t}},di=(e,t)=>{let n=e.best.cases[t],r=pi(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=Ti(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=Ti(o.branch,e.location);i?.push({originalIndex:o.originalIndex,branch:t})}a.push(o)}}return e.defaultEntries=a,i},fi=(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}),pi=(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:[...s(i).map(e=>({})),r]}:{domain:`object`,required:[{key:i,value:r}]})}return r},mi=e=>e.reduce((e,t)=>e+Rt(t,!0),`data`),hi=O(te),gi=O(T),_i={implementation:ci,Node:li},vi=e=>({kind:e.kind,path:e.path.map(e=>typeof e==`string`?e:k(e)),cases:v(e.cases,(e,t)=>[e,t===!0?t:t.hasKind(`union`)&&t.discriminantJson?t.discriminantJson:t.json])}),yi={delimiter:` | `,finalDelimiter:` | `},bi=e=>xi(e,yi),xi=(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}`},Si=(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=B(e[i],t[o],n);if(!(s instanceof R)){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?R.init(`union`,e,t):i},Ci=({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=z(e[r].rawIn,e[i].rawIn,e[0].$);a instanceof R||(t||wi(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])},wi=(e,t)=>{!e.includesTransform&&!t.includesTransform||(f(e.shallowMorphs,t.shallowMorphs)||_(Ei(e.expression,t.expression)),f(e.flatMorphs,t.flatMorphs,{isEqual:(e,t)=>e.propString===t.propString&&(e.node.hasKind(`morph`)&&t.node.hasKind(`morph`)?e.node.hasEqualMorp
28hs(t.node):e.node.hasKind(`intersection`)&&t.node.hasKind(`intersection`)?e.node.structure?.structuralMorphRef===t.node.structure?.structuralMorphRef:!1)})||_(Ei(e.expression,t.expression)))},Ti=(e,t)=>e.transform((e,t)=>e===`domain`||e===`unit`?null:t,{shouldTransform:(e,n)=>{let r=mi(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}}),Ei=(e,t)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate: 29Left: ${e} 30Right: ${t}`,Di=(e,t)=>`The intersection of two ordered unions is indeterminate: 31Left: ${e} 32Right: ${t}`,Oi={implementation:P({kind:`unit`,hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:e=>e instanceof Date?e.toISOString():N(e)}},normalize:e=>e,defaults:{description:e=>T(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)=>R.init(`unit`,e,t),...qr(`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:D.intrinsic.object;if(e.domain!==t.domain){let n=e.domain===`undefined`||e.domain===`null`||e.domain===`boolean`?e.domain:D.intrinsic[e.domain];return R.init(`domain`,n,t)}}return R.init(`assignability`,e,t.hasKind(`intersection`)?t.children.find(t=>!t.allows(e.unit)):t)})}}),Node:class extends ei{compiledValue=this.json.unit;serializedValue=typeof this.unit==`string`||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=ki(this.unit,this.serializedValue);compiledNegation=ki(this.unit,this.serializedValue,`negated`);expression=T(this.unit);domain=m(this.unit);get defaultShortDescription(){return this.domain===`object`?h.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:`null`}:D.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}},ki=(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}`},Ai={implementation:P({kind:`index`,hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{let n=t.$.parseSchema(e);if(!n.extends(D.intrinsic.key))return _(Mi(n.expression));let r=n.branches.filter(e=>e.hasKind(`unit`));return r.length?_(ji(r.map(e=>T(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=B(e.value,t.value,n),i=r instanceof R?D.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 Nn{impliedBasis=D.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=c(this.value.flatRefs.map(e=>L([this.signature,...e.path],e.node)),L([this.signature],this.value));traverseAllows=(e,t)=>me(e).every(e=>!this.signature.traverseAllows(e[0],t)||I(e[0],()=>this.value.traverseAllows(e[1],t),t));traverseApply=(e,t)=>{for(let n of me(e))this.signature.traverseAllows(n[0],t)&&I(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(){}}},ji=e=>`Index keys ${e.join(`, `)} should be specified as named props.`,Mi=e=>`Indexed key definition '${e}' must be a string or symbol`,Ni={implementation:P({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:Or,optional:Or}}),Node:class extends kr{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:`required`,missingValueDescription:this.value.defaultShortDe
32scription,relativePath:[this.key],meta:this.meta});compiledErrorContext=nn(this.errorContext)}},Pi=P({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 Fr(n,e[1],null),[n,e[1]]})},serialize:e=>e.map(e=>[e[0].collapsibleJson,N(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 _(Hi);if(e.optionals?.length||e.defaultables?.length)return _(Vi)}return e.minVariadicLength&&!e.variadic?_(`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} = ${T(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=Ui({l:e.tuple,r:t.tuple,disjoint:new R,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`,Bi(i[0].result)):n.$.node(`union`,i.map(e=>({proto:Array,sequence:Bi(e.result)})))}}}),Fi=class extends Nn{impliedBasis=D.intrinsic.Array.internal;tuple=zi(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=l(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return Sn(this.flatRefs,this.prevariadic.flatMap((e,t)=>c(e.node.flatRefs.map(e=>L([`${t}`,...e.path],e.node)),L([`${t}`],e.node)))),Sn(this.flatRefs,this.variadicOrPostfix.flatMap(e=>c(e.flatRefs.map(e=>L([D.intrinsic.nonNegativeIntegerString.internal,...e.path],e.node)),L([D.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=Li(this);defaultValueMorphsReference=this.defaultValueMorphs.length?O(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??g(`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++)I(n,()=>this.elementAtIndex(e,n).node.traverseApply(e[n],t),t)};
32get 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(D.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=D.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}},Ii={},Li=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(Pr(i,r,a)),n+=`${i}: ${r.id} = ${N(a)}, `}return n+=`]`,Ii[n]??=t},Ri={implementation:Pi,Node:Fi},zi=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},Bi=e=>e.reduce((e,t)=>(t.kind===`variadic`?e.variadic=t.node:t.kind===`defaultables`?e.defaultables=c(e.defaultables,[[t.node,t.default]]):e[t.kind]=c(e[t.kind],t.node),e),{}),Vi=`A postfix required element cannot follow an optional or defaultable element`,Hi=`A postfix element requires a variadic element`,Ui=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=Ui({...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=Ui({...e,fixedVariants:[],l:n.map(e=>({...e,kind:`prefix`}))});t.disjoint.length===0&&e.fixedVariants.push(t)}let c=B(t.node,r.node,e.ctx);if(c instanceof R)if(s===`prefix`||s===`postfix`)e.disjoint.push(...c.withPrefixKey(s===`prefix`?e.result.length:`-${n.length+1}`,Wi(t)&&Wi(r)?`required`:`optional`)),e.result=[...e.result,{kind:s,node:D.intrinsic.never.internal}];else if(s===`optionals`||s===`defaultables`)return e;else return Ui({...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&&_(Ar(t.default,r.default)),e.result=[...e.result,{kind:s,node:c,default:t.kind===`defaultables`?t.default:r.kind===`defaultables`?r.default:g(`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),Ui(e)},Wi=e=>e.kind===`prefix`||e.kind===`postfix`,Gi=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??`{}`},Ki=Gi(`description`),qi=Gi(`expression`),Ji=(e,t,n)=>{let r=e.required?`required`:`optional`;if(!t.signature.allows(e.key))return null;let i=z(e.value,t.value,n);return i instanceof R?r===`optional`?n.node(`optional`,{key:e.key,value:D.intrinsic.never.internal}):i.withPrefixKey(e.key,e.kind):null},Yi=P({kind:`structure`,hasAssociatedError:!1,normalize:e=>e,applyConfig:(e,t)=>
32!e.undeclared&&t.onUndeclaredKey!==`ignore`?{...e,undeclared:t.onUndeclaredKey}:e,keys:{required:{child:!0,parse:V(`required`),reduceIo:(e,t,n)=>{t.required=c(t.required,n.map(t=>e===`in`?t.rawIn:t.rawOut))}},optional:{child:!0,parse:V(`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]=c(t[e.outProp.kind],e.outProp.rawOut)}},index:{child:!0,parse:V(`index`)},sequence:{child:!0,parse:V(`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:Ki},intersections:{structure:(e,t,n)=>{let r={...e.inner},i={...t.inner},a=new R;if(e.undeclared){let r=e.keyof();for(let e of t.requiredKeys)r.allows(e)||a.add(`presence`,D.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=z(r,e.signature,n.$);if(t instanceof R)return[];let a=ia(t,e.value,n.$);return a.required&&(i.required=l(i.required,a.required)),a.optional&&(i.optional=l(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,D.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=z(i,e.signature,n.$);if(t instanceof R)return[];let a=ia(t,e.value,n.$);return a.required&&(r.required=l(r.required,a.required)),a.optional&&(r.optional=l(r.optional,a.optional)),a.index??[]})}let o={};(e.undeclared||t.undeclared)&&(o.undeclared=e.undeclared===`reject`||t.undeclared===`reject`?`reject`:`delete`);let s=Fn({kind:`structure`,baseInner:o,l:In(r),r:In(i),roots:[],ctx:n});return s instanceof R&&a.push(...s),a.length?a:s}},reduce:(e,t)=>{if(!e.required&&!e.optional)return;let n=Object.create(null),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&&_(sa(i.key)),n[i.key]=!0,e.index)for(let n of e.index){let e=Ji(i,n,t);if(e instanceof R)return e}}if(e.optional)for(let a=0;a<e.optional.length;a++){let o=e.optional[a];if(o.key in n&&_(sa(o.key)),n[o.key]=!0,e.index)for(let n of e.index){let e=Ji(o,n,t);if(e instanceof R)return e;e!==null&&(i[a]=e,r=!0)}}if(r)return t.node(`structure`,{...e,optional:i},{prereduced:!0})}}),Xi=class extends Nn{impliedBasis=D.intrinsic.object.internal;impliedSiblings=this.children.flatMap(e=>e.impliedSiblings??[]);props=l(this.required,this.optional);propsByKey=v(this.props,(e,t)=>[t.key,t]);propsByKeyReference=O(this.propsByKey);expression=qi(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(M(t))return t.kind!==`required`&&t.kind!==`optional`?_(`Map result must have kind "required" or "optional" (was ${t.kind})`):(e[t.kind]=c(e[t.kind],t),e);let r=t.kind??n?.kind??`required`,i=v(t,(e,t)=>e in jr.implementation.keys?[e,t]:[]);return e[r]=c(e[r],this.$.node(r,i)),e},{}))}assertHasKeys(e){let t=e.filter(e=>!Ur(e,this.keyof()));if(t.length)return _(oa(this.expression,t))}get(e,...t){let n,r=!1,i=na(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)Ur(i,e.signature)&&(n=n?.and(e.value)??e.value);if(this.sequence&&Ur(i,D.intrinsic.nonNegativeIntegerString))if(j(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&&j(i,`root`)&&i.extends(D.intrinsic.number)?_(ra(i.expression,this.sequence.expression)):_(oa(this.expression,[i]));let a=n.get(...t);return r?a:a.or(D.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=c(t.required,e.required)),e.optional&&(t.optional=c(t.o
32ptional,e.optional)),e.index&&(t.index=c(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=Ht(this.inner),r=n=>{let r=t.some(e=>Ur(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(!I(o,()=>i.value.traverseAllows(t[o],n),n))return!1}else if(I(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&&D.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`,$i(this))}structuralMorphRef=this.structuralMorph&&O(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([`),ea(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 F.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=D.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(D.intrinsic.string)){e.additionalProperties=r;continue}for(let i of n.signature.branches){if(!i.extends(D.intrinsic.string)){e=t.fallback.symbolKey({code:`symbolKey`,base:e,key:null,value:r,optional:!1});continue}let n={type:`string`};
32if(i.hasKind(`morph`)&&(n=t.fallback.morph({code:`morph`,base:i.rawIn.toJsonSchemaRecurse(t),out:i.rawOut.toJsonSchemaRecurse(t)})),!i.hasKind(`intersection`))return g(`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}},Zi={},Qi=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+=G.nonNegativeIntegerString.id;else for(let n=0;n<e.sequence.tuple.length;n++)t+=n+` | `;t+=`)`}return t},$i=e=>{let t=Qi(e);return t?Zi[t]?Zi[t]:Zi[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},ea=(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.line(`${t.sequence.defaultValueMorphsReference}[i]${n}`),`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`)})},ta={implementation:Yi,Node:Xi},na=e=>(j(e,`root`)&&e.hasKind(`unit`)&&(e=e.unit),typeof e==`number`&&(e=`${e}`),e),ra=(e,t)=>`${e} is not allowed as an array index on ${t}. Use the 'nonNegativeIntegerString' keyword instead.`,ia=(e,t,n)=>{let[r,a]=i(e.branches,e=>e.hasKind(`unit`));if(!r.length)return{index:n.node(`index`,{signature:e,value:t})};let o={};for(let e of r){let r=n.node(`required`,{key:e.unit,value:t});o[r.kind]=c(o[r.kind],r)}return a.length&&(o.index=n.node(`index`,{signature:a,value:t})),o},aa=e=>j(e,`root`)?e.expression:T(e),oa=(e,t)=>`Key${t.length===1?``:`s`} ${t.map(aa).join(`, `)} ${t.length===1?`does`:`do`} not exist on ${e}`,sa=e=>`Duplicate key ${k(e)}`,ca={...mr,alias:$r.implementation,domain:ti.implementation,unit:Oi.implementation,proto:si.implementation,union:_i.implementation,morph:ai.implementation,intersection:ni.implementation,divisor:Gn.implementation,pattern:gr.implementation,predicate:Wn.implementation,required:Ni.implementation,optional:jr.implementation,index:Ai.implementation,sequence:Ri.implementation,structure:ta.implementation};D.defaultConfig=ge(Object.assign(v(ca,(e,t)=>[e,t.defaults]),{jitless:Ie(),clone:je,onUndeclaredKey:`ignore`,exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:F.defaultConfig})),D.resolvedConfig=rn(D.defaultConfig,D.config);var la={...hr,alias:$r.Node,domain:ti.Node,unit:Oi.Node,proto:si.Node,union:_i.Node,morph:ai.Node,intersection:ni.Node,divisor:Gn.Node,pattern:gr.Node,predicate:Wn.Node,required:Ni.Node,optional:jr.Node,index:Ai.Node,sequence:Ri.Node,structure:ta.Node},ua=class extends ce{get[A](){return`module`}},da=(e,t)=>new ua(v(e,(e,n)=>[e,j(n,`module`)?da(n,t):t.bindReference(n)])),fa=e=>x(e)?e:`branches`in e&&x(e.branches)?e.branches:void 0,pa=(e,t)=>_(`Node of kind ${t} is not valid as a ${e} definition`),ma=e=>`#${e} duplicates public alias ${e}`,ha={};D.ambient??={};var ga,_a=`function $`,va=e=>ya(e,ba(e)),ya=(e,t,n)=>{let r=t.write(_a,4),i=t.compile()();for(let t of e)t.precompilation&&(!n||t.$!==n)||(t.traverseAllows=i[`${t.id}Allows`].bind(i),t.isRoot()&&!t.allowsRequiresContext&&(t.allows=t.traverseAllows),t.traverseApply=i[`${t.id}Apply`].bind(i),i[`${t.id}Optimistic`]&&(t.traverseOptimistic=i[`${t.id}Optimistic`].bind(i)),t.precompilation=r)},ba=e=>new Lt().return(e.reduce((e,t)=>
32{let n=new Vt({kind:`Allows`}).indent();t.compile(n);let r=n.write(`${t.id}Allows`),i=new Vt({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 Vt({kind:`Allows`,optimistic:!0}).indent();return t.compile(o),`${a}${o.write(`${t.id}Optimistic`)},\n`},`{ 33`)+`}`),xa=class{config;resolvedConfig;name;get[A](){return`scope`}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,t){this.config=rn(D.config,t),this.resolvedConfig=rn(D.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(ha).length}`,this.name in ha&&_(`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&&_(ma(n)),this.aliases[n]=t):(n in this.aliases&&_(ma(e)),this.aliases[n]=t,this.exportedNames.push(n)),!j(t,`module`)&&!j(t,`generic`)&&!Pe(t)){let e=this.preparseOwnDefinitionFormat(t,{alias:n});this.resolutions[n]=j(e,`root`)?this.bindReference(e):this.createParseContext(e).id}}ga??=this.node(`union`,{branches:[`string`,`number`,`object`,`bigint`,`symbol`,{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[ga.hash]=this.node(`intersection`,{},{prereduced:!0}),this.intrinsic=D.intrinsic?v(D.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 Hn(e,r?new Vn(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(_r(e),e,t);preparseNode(e,t,n){let r=typeof e==`string`?e:_r(t,e);if(M(t)&&t.kind===r)return t;if(r===`alias`&&!n?.prereduced){let{reference:e}=$r.implementation.normalize(t,this);if(e.startsWith(`$`)){let n=this.resolveRoot(e.slice(1));t=n,r=n.kind}}else if(r===`union`&&p(t,`object`)){let e=fa(t);e?.length===1&&(t=e[0],r=_r(t))}if(M(t)&&t.kind===r)return t;let i=ca[r].normalize?.(t,this)??t;return M(i)?i.kind===r?i:pa(r,i.kind):{...n,$:this,kind:r,def:i,prefix:n.alias??r}}bindReference(e){let t;return t=M(e)?e.$===this?e:new e.constructor(e.attachments,this):e.$===this?e:new Hn(e.params,e.bodyDef,e.$,this,e.hkt),this.resolved||Object.assign(this.referencesById,t.referencesById),t}resolveRoot(e){return this.maybeResolveRoot(e)??_(ka(e))}maybeResolveRoot(e){let t=this.maybeResolve(e);if(!j(t,`generic`))return t}maybeResolveSubalias(e){return Ta(this.aliases,e)??Ta(this.ambient,e)}get ambient(){return D.ambient}maybeResolve(e){let t=this.resolutions[e];if(t){if(typeof t!=`string`)return this.bindReference(t);let n=H[t];if(j(n,`root`))return this.resolutions[e]=n;if(j(n,`context`)){if(n.phase===`resolving`)return this.node(`alias`,{reference:`$${e}`},{prereduced:!0});if(n.phase===`resolved`)return g(`Unexpected resolved context for was uncached by its scope: ${T(n)}`);n.phase=`resolving`;let t=this.bindReference(this.parseOwnDefinitionFormat(n.def,n));return n.phase=`resolved`,H[t.id]=t,H[n.id]=t,this.resolutions[e]=t}return g(`Unexpected nodesById entry for ${t}: ${T(n)}`)}let n=this.aliases[e]??this.ambient?.[e];return n?(n=this.normalizeRootScopeValue(n),j(n,`generic`)?this.resolutions[e]=this.bindReference(n):j(n,`module`)?(n.root||_(ja(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??Sr(e.prefix);return H[t]=Object.assign(e,{[A]:`context`,$:this,id:t,phase:`unresolved`})}traversal(e){return new mn(e,this.resolvedConfig)}import(...e){return new ua(v(this.export(...e),(e,t)=>[`#${e}`,t]))}precompilation;_exportedResolutions;_exports;
33export(...e){if(!this._exports){this._exports={};for(let e of this.exportedNames){let t=this.aliases[e];this._exports[e]=j(t,`module`)?da(t,this):Ca(this.maybeResolve(e))}for(let e of this.lazyResolutions)e.resolution;if(this._exportedResolutions=Oa(this,this._exports),this._json=wa(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let e=ba(this.references);this.precompilation=e.write(_a,4),ya(this.references,e,this)}this.resolved=!0}return new ua(v(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(M(r))return this.bindReference(r);let i=this.createParseContext(r),a=Cr(i),o=this.bindReference(a);return H[i.id]=o};parse=(e,t={})=>this.finalize(this.parseDefinition(e,t));parseDefinition(e,t={}){if(j(e,`root`))return this.bindReference(e);let n=this.preparseOwnDefinitionFormat(e,t);if(j(n,`root`))return this.bindReference(n);let r=this.createParseContext(n);H[r.id]=r;let i=this.bindReference(this.parseOwnDefinitionFormat(e,r));return i.isCyclic&&(i=Tr(i,r.id)),H[r.id]=i,i}finalize(e){return Ca(e),!e.precompilation&&!this.resolvedConfig.jitless&&va(e.references),e}},Sa=class extends xa{parseOwnDefinitionFormat(e,t){return Cr(t)}preparseOwnDefinitionFormat(e,t){return this.preparseNode(_r(e),e,t)}preparseOwnAliasEntry(e,t){return[e,t]}normalizeRootScopeValue(e){return e}},Ca=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},wa=e=>v(e,(e,t)=>[e,j(t,`root`)||j(t,`generic`)?t.json:j(t,`module`)?wa(t):g(`Unexpected resolution ${T(t)}`)]),Ta=(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(!j(i,`module`))return _(Aa(r));let a=t.slice(n+1),o=i[a];if(o===void 0)return Ta(i,a);if(j(o,`root`)||j(o,`generic`))return o;if(j(o,`module`))return o.root??_(ja(t));g(`Unexpected resolution for alias '${t}': ${T(o)}`)},Ea=(e,t)=>new Sa(e,t),Da=new Sa({}),Oa=(e,t)=>{let n={};for(let r in t){let i=t[r];if(j(i,`module`)){let t=v(Oa(e,i),(e,t)=>[`${r}.${e}`,t]);Object.assign(n,t)}else j(i,`root`)||j(i,`generic`)?n[r]=i:g(`Unexpected scope resolution ${T(i)}`)}return n},ka=e=>`'${e}' is unresolvable`,Aa=e=>`'${e}' must reference a module to be accessed using dot syntax`,ja=e=>`Reference to submodule '${e}' must specify an alias`;Da.export();var U=Da.schema,Ma=Da.node;Da.defineSchema;var W=Da.generic,Na=`^(?:0|[1-9]\\d*)$`;O(new RegExp(Na));var Pa=Ea({bigint:`bigint`,boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:`number`,object:`object`,string:`string`,symbol:`symbol`,true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();D.intrinsic={...Pa};var Fa=Ea({integer:{domain:`number`,divisor:1},lengthBoundable:[`string`,Array],key:[`string`,`symbol`],nonNegativeIntegerString:{domain:`string`,pattern:Na}},{prereducedAliases:!0}).export();Object.assign(D.intrinsic,Fa);var Ia=Ea({jsonPrimitive:[`string`,`number`,{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:`object`,index:{signature:`string`,value:`$jsonData`}},jsonData:[`$jsonPrimitive`,`$jsonObject`]},{prereducedAliases:!0}).export(),G={...Pa,...Fa,...Ia,emptyStructure:Ma(`structure`,{},{prereduced:!0})};D.intrinsic={...G};var La=((e,t)=>new RegExp(e,t));Object.assign(La,{as:La});var Ra=e=>typeof e==`string`&&e[0]===`d`&&(e[1]===`'`||e[1]===`"`)&&e[e.length-1]===e[1],za=e=>e.toString()!==`Invalid Date`,Ba=e=>e.slice(2,-1),Va=e=>`'${e}' could not be parsed by the Date constructor`,Ha=(e,t)=>Ua(e,t),Ua=(e,t)=>{let n=new Date(e);if(za(n))return n;let r=ct(e);if(r!==void 0){let e=new Date(r);if(za(e))return e}return t?_(t===!0?Va(e):t):void 0},Wa=U({proto:`Array`,sequence:`string`,required:{key:`groups`,value:[`object`,{unit:void 0}]}}),Ga=(e,t)=>{let n=e.scanner.shiftUntilEscapable(Za[Xa[t]]);if(e.scanner.lookahead===``)return e.error($a(n,t));if(e.scanner.shift(),t in Ya){let r;try{r=new RegExp(n)}catch(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:Wa}))}else if(y(t,Ka))e.root=e.ctx.$.node(`unit`,{unit:n});else{let t=Ha(n,Va(n));e.root=e.ctx.$.node(`unit`,{meta:n,unit:t})}},Ka={"'":1,'"':1},qa={"/":1,"'":1,'"':1},Ja={"d'":`'`,'d"':`"`,"'":`'`,'"':`"`},Ya={"/":`/`,"x/":`/`},Xa={...Ja,...Ya},Za={"'":e=>e.lookahead===`'`,'"':e=>e.lookahead===`"`,"/":e=>e.lookahead===`/`},Qa={'"':`double-quote`,"'":`single-quote`,"/":`forward slash`},$a=(e,t)=>`${t}${e} requires a closing ${Qa[Xa[t]]}`,eo=e=>`Private type references should not include '#'. Use '${e}' instead.`,to=`Optional definitions like 'string?' are only valid as properties in an object or tuple`,
33no=`Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple`,ro={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...He},io=(e,t)=>e===`>`?t[0]===`=`?t[1]===`=`:t.trimStart()===``||y(t.trimStart()[0],ro):e===`=`?t[0]!==`=`:e===`,`||e===`?`,ao=(e,t,n)=>oo(e,t,n,[]),oo=(e,t,n,r)=>{let i=n.parseUntilFinalizer();return r.push(i.root),i.finalizer===`>`?r.length===t.params.length?r:n.error(so(e,t.names,r.map(e=>e.expression))):i.finalizer===`,`?oo(e,t,n,r):i.error(Mt(`>`))},so=(e,t,n)=>`${e}<${t.join(`, `)}> requires exactly ${t.length} args (got ${n.length}${n.length===0?``:`: ${n.join(`, `)}`})`,co=e=>{let t=e.scanner.shiftUntilLookahead(ro);t===`keyof`?e.addPrefix(`keyof`):e.root=uo(e,t)},lo=(e,t,n)=>(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()===`<`?t(...ao(e,t,n)):n.error(so(e,t.names,[]))),uo=(e,t)=>fo(e,t)??po(e,t)??e.error(t===``?e.scanner.lookahead===`#`?eo(e.shiftedBy(1).scanner.shiftUntilLookahead(ro)):mo(e):ka(t)),fo=(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(j(n,`root`))return n;if(n!==void 0)return j(n,`generic`)?lo(t,n,e):_(`Unexpected resolution ${T(n)}`)},po=(e,t)=>{let n=lt(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})},mo=e=>{let t=e.previousOperator();return t?ho(t,e.scanner.unscanned):go(e.scanner.unscanned)},ho=(e,t=``)=>`Token '${e}' requires a right operand${t?` before '${t}'`:``}`,go=e=>`Expected an expression${e?` before '${e}'`:``}`,_o=e=>e.scanner.lookahead===``?e.error(mo(e)):e.scanner.lookahead===`(`?e.shiftedBy(1).reduceGroupOpen():e.scanner.lookaheadIsIn(qa)?Ga(e,e.scanner.shift()):e.scanner.lookaheadIsIn(He)?_o(e.shiftedBy(1)):e.scanner.lookahead===`d`?e.scanner.nextLookahead in Ka?Ga(e,`${e.scanner.shift()}${e.scanner.shift()}`):co(e):e.scanner.lookahead===`x`&&e.scanner.nextLookahead===`/`?e.shiftedBy(2)&&Ga(e,`x/`):co(e),vo={">":!0,">=":!0},yo={"<":!0,"<=":!0},bo={"<":`>`,">":`<`,"<=":`>=`,">=":`<=`,"==":`==`},xo=(e,t)=>`Left bounds are only valid when paired with right bounds (try ...${t}${e})`,So=e=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,Co=(e,t,n,r)=>`An expression may have at most one left bound (parsed ${e}${bo[t]}, ${n}${bo[r]})`,wo=(e,t)=>{let n=Eo(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 ko(e,n)},To={"<":1,">":1,"=":1},Eo=(e,t)=>e.scanner.lookaheadIs(`=`)?`${t}${e.scanner.shift()}`:t,Do=(e,t,n,r)=>n.extends(D.intrinsic.number)?typeof t==`number`?e===`==`?[`min`,`max`]:e[0]===`>`?[`min`]:[`max`]:_(Ao(e,t,r)):n.extends(D.intrinsic.lengthBoundable)?typeof t==`number`?e===`==`?[`exactLength`]:e[0]===`>`?[`minLength`]:[`maxLength`]:_(Ao(e,t,r)):n.extends(D.intrinsic.Date)?e===`==`?[`after`,`before`]:e[0]===`>`?[`after`]:[`before`]:_(or(n.expression)),Oo=e=>({rule:Ra(e.limit)?Ba(e.limit):e.limit,exclusive:e.comparator.length===1}),ko=(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(Ao(t,a,`right`));let o=i.unit,s=t.length===1,c=Do(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(!y(t,yo))return e.error(So(t));let l=Do(e.branches.leftBound.comparator,e.branches.leftBound.limit,n,`left`);e.constrainRoot(l[0],Oo(e.branches.leftBound)),e.branches.leftBound=null},Ao=(e,t,n)=>`Comparator ${n===`left`?bo[e]:e} must be ${n===`left`?`preceded`:`followed`} by a corresponding literal (was ${t})`,jo=e=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(ro);e.root=e.root.brand(t)},Mo=e=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(ro),n=ut(t,{errorOnFail:No(t)});n===0&&e.error(No(0)),e.root=e.root.constrain(`divisor`,n)},No=e=>`% operator must be followed by a non-zero integer literal (was ${e})`,Po=e=>{let t=e.scanner.shift();return t===``?e.finalize(``):t===`[`?e.scanner.shift()===`]`?e.setRoot(e.root.array()):e.error(Io):t===`|`?e.scanner.lookahead===`>`?e.shiftedBy(1).pushRootToBranch(`|>`):e.pushRootToBranch(t):t===`&`?e.pushRootToBranch(t):t===`)`?e.finalizeGroup():io(t,e.scanner.unscanned)?e.finalize(t):y(t,To)?wo(e,t):t===`%`?Mo(e):t===`#`?jo(e):t in He?Po(e):e.error(Fo(t))},Fo=(e,t=``)=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,Io=`Missing expected ']'`,Lo=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(Ro(n.expression))},Ro=e=>`Default value '${e}' must be a literal value`,zo=(e,t)=>{let n=t.$.maybeResolveRoot(e);
33if(n)return n;if(e.endsWith(`[]`)){let n=t.$.maybeResolveRoot(e.slice(0,-2));if(n)return n.array()}let r=new Uo(new At(e),t),i=Bo(r);return r.finalizer===`>`&&_(Fo(`>`)),i},Bo=e=>{e.parseOperand();let t=Vo(e).root;return t?(e.finalizer===`=`?t=Lo(e):e.finalizer===`?`&&(t=[t,`?`]),e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead&&_(Fo(e.scanner.lookahead)),t):g(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`)},Vo=e=>{for(;e.finalizer===void 0;)Ho(e);return e},Ho=e=>e.hasRoot()?e.parseOperator():e.parseOperand(),Uo=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)}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(Mt(`)`));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){let n=bo[t];if(!y(n,vo))return this.error(So(t));if(this.branches.leftBound)return this.error(Co(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(jt(`)`,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():g(`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 Vo(new e(this.scanner,this.ctx))}parseOperator(){return Po(this)}parseOperand(){return _o(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(xo(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}},Wo=`An empty string is not a valid generic parameter name`,Go=(e,t,n)=>{e.shiftUntilNonWhitespace();let r=e.shiftUntilLookahead(ro);return r===``?e.lookahead===``&&t.length?t:_(Wo):(e.shiftUntilNonWhitespace(),qo(e,r,t,n))},Ko=`extends `,qo=(e,t,n,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(Ko))e.jumpForward(8);else return e.lookahead===`,`&&e.shift(),n.push(t),Go(e,n,r);let i=Vo(new Uo(e,r));return n.push([t,i.root]),Go(e,n,r)},Jo=class extends S{constructor(e){let t=(...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 _(Xo);o=e.parse(t[n+1])}return e=>new Yo(e,a,o)};super(t,{attach:{$:e,raw:t}})}},Yo=class extends S{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`}`}},Xo=`":" must be followed by exactly one return type e.g: 34fn("string", ":", "number")(s => s.length)`,Zo=class extends S{$;constructor(e){super((...t)=>new Qo(e)(...t),{bind:e}),this.$=e}in(e){return new Qo(this.$,e===void 0?void 0:this.$.parse(e))}at(e,t){return new Qo(this.$).at(e,t)}case(e,t){return new Qo(this.$).case(e,t)}},Qo=class extends S{$;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&&_(ts),this.branches.length&&_(es),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&&_(`default may only be specified as the last key of a switch definition`),this.default(r);if(typeof r!=`function`)return _(`Value for case "${n}" must be a function (was ${m(r)})`);this.caseEntry(n,r)}return this}default(e){typeof e==`function`&&this.case(G.unknown,e);let t={branches:this.branches,ordered:!0}
34;(e===`never`||e===`assert`)&&(t.meta={onFail:$o});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:$o},`self`)),this.$.finalize(r)}},$o=e=>e.throw(),es=`A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`,ts=`At most one key matcher may be specified per expression`,ns=(e,t)=>{if(x(e)){if(e[1]===`=`)return[t.$.parseOwnDefinitionFormat(e[0],t),`=`,e[2]];if(e[1]===`?`)return[t.$.parseOwnDefinitionFormat(e[0],t),`?`]}return zs(e,t)},rs=`Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`,is=`Only required keys may specify default values, e.g. { value: 'number = 0' }`,as=(e,t)=>{let n,r={},i=me(e);for(let[e,a]of i){let i=ls(e);if(i.kind===`spread`){if(!pe(r))return _(cs);let e=t.$.parseOwnDefinitionFormat(a,t);if(e.equals(G.object))continue;if(!e.hasKind(`intersection`)||!e.basis?.equals(G.object))return _(us(e.expression));n=e.structure;continue}if(i.kind===`undeclared`){a!==`reject`&&a!==`delete`&&a!==`ignore`&&_(ss(a)),r.undeclared=a;continue}let o=ns(a,t),s=i;if(i.kind===`required`){x(o)?os(r,`optional`,o[1]===`=`?{key:i.normalized,value:o[0],default:o[2]}:{key:i.normalized,value:o[0]},t):os(r,`required`,{key:i.normalized,value:o},t);continue}if(x(o)&&(o[1]===`?`&&_(rs),o[1]===`=`&&_(is)),i.kind===`optional`){os(r,`optional`,{key:i.normalized,value:o},t);continue}let l=ia(t.$.parseOwnDefinitionFormat(s.normalized,t),o,t.$);l.index&&(r.index=c(r.index,l.index)),l.required&&(r.required=c(r.required,l.required))}let a=t.$.node(`structure`,r);return t.$.parseSchema({domain:`object`,structure:n?.merge(a)??a})},os=(e,t,n,r)=>{e[t]=c(e[t],r.$.node(t,n))},ss=e=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${T(e)})`,cs=`Spread operator may only be used as the first key in an object`,ls=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},us=e=>`Spread operand must resolve to an object literal type (was ${e})`,ds=(e,t)=>Ts(e)?ws[e[0]](e,t):Cs(e)?Ss[e[1]](e,t):null,fs=(e,t)=>t.$.parseOwnDefinitionFormat(e[1],t).keyof(),ps=(e,t)=>{if(e[2]===void 0)return _(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]===`&`?z(n,r,t.$):On(n,r,t.$);return i instanceof R?i.throw():i},ms=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).array(),hs=(e,t)=>typeof e[2]==`function`?t.$.parseOwnDefinitionFormat(e[0],t).pipe(e[2]):_(gs(`=>`,e[2])),gs=(e,t)=>`${e===`:`?`Narrow`:`Morph`} expression requires a function following '${e}' (was ${typeof t})`,_s=(e,t)=>typeof e[2]==`function`?t.$.parseOwnDefinitionFormat(e[0],t).constrain(`predicate`,e[2]):_(gs(`:`,e[2])),vs=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).configure(e[2],e[3]),ys=e=>e,bs=ys({"[]":ms,"?":()=>_(to)}),xs=ys({"|":ps,"&":ps,":":_s,"=>":hs,"|>":ps,"@":vs,"=":()=>_(no)}),Ss={...bs,...xs},Cs=e=>Ss[e[1]]!==void 0,ws=(e=>e)({keyof:fs,instanceof:(e,t)=>{if(typeof e[1]!=`function`)return _(Es(we(e[1])));let n=e.slice(1).map(e=>typeof e==`function`?t.$.node(`proto`,{proto:e}):_(Es(we(e))));return n.length===1?n[0]:t.$.node(`union`,{branches:n})},"===":(e,t)=>
34t.$.units(e.slice(1))}),Ts=e=>ws[e[0]]!==void 0,Es=e=>`Expected a constructor following 'instanceof' operator (was ${e})`,Ds=(e,t)=>{let n=[{}],r=0;for(;r<e.length;){let i=!1;e[r]===`...`&&r<e.length-1&&(i=!0,r++);let a=ns(e[r],t),[o,s,c]=x(a)?a:[a];if(r++,i){if(!o.extends(D.intrinsic.Array))return _(Ns(o.expression));n=n.flatMap(e=>o.distribute(t=>Ms(Ht(e),t)))}else n=n.map(e=>s===`?`?ks(e,o):s===`=`?As(e,o,c):Os(e,o))}return t.$.parseSchema(n.map(e=>pe(e)?{proto:Array,exactLength:0}:{proto:Array,sequence:e}))},Os=(e,t)=>e.defaultables||e.optionals?_(e.variadic?Vi:Fs):(e.variadic?e.postfix=c(e.postfix,t):e.prefix=c(e.prefix,t),e),ks=(e,t)=>e.variadic?_(Is):(e.optionals=c(e.optionals,t),e),As=(e,t,n)=>e.variadic?_(Is):e.optionals?_(Ls):(e.defaultables=c(e.defaultables,[[t,n]]),e),js=(e,t)=>(e.postfix&&_(Ps),e.variadic?e.variadic.equals(t)||_(Ps):e.variadic=t.internal,e),Ms=(e,t)=>{let n=t.select({method:`find`,kind:`sequence`});if(!n)return js(e,D.intrinsic.unknown);if(n.prefix)for(let t of n.prefix)Os(e,t);if(n.optionals)for(let t of n.optionals)ks(e,t);if(n.variadic&&js(e,n.variadic),n.postfix)for(let t of n.postfix)Os(e,t);return e},Ns=e=>`Spread element must be an array (was ${e})`,Ps=`A tuple may have at most one variadic element`,Fs=`A required element may not follow an optional element`,Is=`An optional element may not follow a variadic element`,Ls=`A defaultable element may not follow an optional element without a default`,Rs={},zs=(e,t)=>{if(typeof e==`string`){if(t.args&&Object.keys(t.args).some(t=>e.includes(t)))return zo(e,t);let n=Rs[t.$.name]??={};return n[e]??=zo(e,t)}return p(e,`object`)?Bs(e,t):_(Us(m(e)))},Bs=(e,t)=>{let n=Ce(e);switch(n){case void 0:return j(e,`root`)?e:`~standard`in e?Vs(e,t):as(e,t);case`Array`:return Hs(e,t);case`RegExp`:return t.$.node(`intersection`,{domain:`string`,pattern:e},{prereduced:!0});case`Function`:{let t=Pe(e)?e():e;return j(t,`root`)?t:_(Us(`Function`))}default:return _(Us(n??T(e)))}},Vs=(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:ze(e),relativePath:t.map(e=>typeof e==`object`?e.key:e)}):n.error({message:e})}),Hs=(e,t)=>ds(e,t)??Ds(e,t),Us=e=>`Type definitions must be strings or objects (was ${e})`,Ws=class extends S{constructor(e){let t=Object.assign({errors:dn,hkt:C,$: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 Hn(e.parseGenericParams(n,{}),t[1],e,e,null)}return e.parse(t)},{attach:t})}},Gs=D,Ks=class e extends xa{get ambientAttachments(){if(Gs.typeAttachments)return this.cacheGetter(`ambientAttachments`,v(Gs.typeAttachments,(e,t)=>[e,this.bindReference(t)]))}preparseOwnAliasEntry(e,t){let n=e.indexOf(`<`);if(n===-1){if(j(t,`module`)||j(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]!==`>`&&_(`'>' 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,()=>Bn(this.parseGenericParams(i,{alias:r}),t,this)]}parseGenericParams(e,t){return Go(new At(e),[],this.createParseContext({...t,def:e,prefix:`generic`}))}normalizeRootScopeValue(e){return Pe(e)&&!j(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=zs(e,t);if(x(n)){if(n[1]===`=`)return _(no);if(n[1]===`?`)return _(to)}return n}unit=e=>this.units([e]);valueOf=e=>this.units(_e(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)=>
34e.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 Jo(this);match=new Zo(this);declare=()=>({type:this.type});define(e){return e}type=new Ws(this);static scope=((t,n={})=>new e(t,n));static module=((e,t={})=>this.scope(e,t).export())},qs=Object.assign(Ks.scope,{define:e=>e}),K=Ks,Js=class extends C{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'},Ys=W([`base`,G.object],[`props`,G.object])(e=>e.base.merge(e.props),Js),Xs=K.module({Key:G.key,Merge:Ys}),Zs=class extends C{},Qs=W(`element`)(e=>{let t=e.element.exclude(G.Array),n=t.array();return t.rawOr(n).pipe(r).distribute(e=>e.assertHasKind(`morph`).declareOut(n),U)},Zs),$s=K.module({root:G.Array,readonly:`root`,index:G.nonNegativeIntegerString,liftFrom:Qs},{name:`Array`}),ec=U([`string`,pt.FileConstructor]),tc=U({meta:`an object representing parsed form data`,domain:`object`,index:{signature:`string`,value:ec.rawOr(ec.array())}}),nc=K.module({root:[`instanceof`,FormData],value:ec,parsed:tc,parse:U({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 pt.FileConstructor?t[n]=[e,r]:e.push(r)}else t[n]=r;return t},declaredOut:tc})},{name:`FormData`}),rc=K.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`}),ic={Boolean:1,Number:1,String:1},ac=K.module({...v({...ve,...be},(e,t)=>e in ic?[]:[e,[`instanceof`,t]]),Array:$s,TypedArray:rc,FormData:nc}),oc=U({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`}),sc=U({domain:`number`,divisor:1}),cc=K.module({root:G.number,integer:sc,epoch:oc,safe:U({domain:{domain:`number`,numberAllowsNaN:!1},min:-(2**53-1),max:2**53-1}),NaN:[`===`,NaN],Infinity:[`===`,1/0],NegativeInfinity:[`===`,-1/0]},{name:`number`}),q=(e,t,n)=>{let r={domain:`string`,pattern:{rule:e.source,flags:e.flags,meta:t}};return n&&(r.meta={format:n}),Ma(`intersection`,r)},lc=q($e,`a well-formed integer string`),uc=K.module({root:lc,parse:U({in:lc,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:G.integer})},{name:`string.integer`}),dc=q(/^[\dA-Fa-f]+$/,`hex characters only`),fc=K.module({root:q(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,`base64-encoded`),url:q(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,`base64url-encoded`)},{name:`string.base64`}),pc=q(/^[A-Z].*$/,`capitalized`),mc=K.module({root:U({in:`string`,morphs:e=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:pc}),preformatted:pc},{name:`string.capitalize`}),hc=U({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)}}}),gc=/^([+-]?\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]|([+-]
34)([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,_c=U({domain:`string`,predicate:{meta:`a parsable date`,predicate:e=>!Number.isNaN(new Date(e).valueOf())}}).assertHasKind(`intersection`),vc=uc.root.internal.narrow((e,t)=>{let n=Number.parseInt(e),r=cc.epoch(n);return r instanceof dn?(t.errors.merge(r),!1):!0}).configure({description:`an integer string representing a safe Unix timestamp`},`self`).assertHasKind(`intersection`),yc=K.module({root:vc,parse:U({in:vc,morphs:e=>new Date(e),declaredOut:G.Date})},{name:`string.date.epoch`}),bc=q(gc,`an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date`).internal.assertHasKind(`intersection`),xc=K.module({root:bc,parse:U({in:bc,morphs:e=>new Date(e),declaredOut:G.Date})},{name:`string.date.iso`}),Sc=K.module({root:_c,parse:U({declaredIn:_c,in:`string`,morphs:(e,t)=>{let n=new Date(e);return Number.isNaN(n.valueOf())?t.error(`a parsable date`):n},declaredOut:G.Date}),iso:xc,epoch:yc},{name:`string.date`}),Cc=q(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,`an email address`,`email`),wc=`(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])`,J=`(${wc}[.]){3}${wc}`,Tc=RegExp(`^${J}$`),Y=`(?:[0-9a-fA-F]{1,4})`,Ec=RegExp(`^((?:${Y}:){7}(?:${Y}|:)|(?:${Y}:){6}(?:${J}|:${Y}|:)|(?:${Y}:){5}(?::${J}|(:${Y}){1,2}|:)|(?:${Y}:){4}(?:(:${Y}){0,1}:${J}|(:${Y}){1,3}|:)|(?:${Y}:){3}(?:(:${Y}){0,2}:${J}|(:${Y}){1,4}|:)|(?:${Y}:){2}(?:(:${Y}){0,3}:${J}|(:${Y}){1,5}|:)|(?:${Y}:){1}(?:(:${Y}){0,4}:${J}|(:${Y}){1,6}|:)|(?::((?::${Y}){0,5}:${J}|(?::${Y}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?\$`),Dc=K.module({root:[`v4 | v6`,`@`,`an IP address`],v4:q(Tc,`an IPv4 address`,`ipv4`),v6:q(Ec,`an IPv6 address`,`ipv6`)},{name:`string.ip`}),Oc=`a JSON string`,kc=e=>{if(!(e instanceof SyntaxError))throw e;return`must be ${Oc} (${e})`},Ac=U({meta:Oc,domain:`string`,predicate:{meta:Oc,predicate:(e,t)=>{try{return JSON.parse(e),!0}catch(e){return t.reject({code:`predicate`,expected:Oc,problem:kc(e)})}}}}),jc=K.module({root:Ac,parse:U({meta:`safe JSON string parser`,in:`string`,morphs:(e,t)=>{if(e.length===0)return t.error({code:`predicate`,expected:Oc,actual:`empty`});try{return JSON.parse(e)}catch(e){return t.error({code:`predicate`,expected:Oc,problem:kc(e)})}},declaredOut:G.jsonObject})},{name:`string.json`}),Mc=q(/^[a-z]*$/,`only lowercase letters`),Nc=K.module({root:U({in:`string`,morphs:e=>e.toLowerCase(),declaredOut:Mc}),preformatted:Mc},{name:`string.lower`}),Pc=[`NFC`,`NFD`,`NFKC`,`NFKD`],Fc=v(Pc,(e,t)=>[t,U({domain:`string`,predicate:e=>e.normalize(t)===e,meta:`${t}-normalized unicode`})]),Ic=v(Pc,(e,t)=>[t,U({in:`string`,morphs:e=>e.normalize(t),declaredOut:Fc[t]})]),Lc=K.module({root:Ic.NFC,preformatted:Fc.NFC},{name:`string.normalize.NFC`}),Rc=K.module({root:Ic.NFD,preformatted:Fc.NFD},{name:`string.normalize.NFD`}),zc=K.module({root:Ic.NFKC,preformatted:Fc.NFKC},{name:`string.normalize.NFKC`}),Bc=K.module({root:Ic.NFKD,preformatted:Fc.NFKD},{name:`string.normalize.NFKD`}),Vc=K.module({root:`NFC`,NFC:Lc,NFD:Rc,NFKC:zc,NFKD:Bc},{name:`string.normalize`}),Hc=q(Xe,`a well-formed numeric string`),Uc=K.module({root:Hc,parse:U({in:Hc,morphs:e=>Number.parseFloat(e),declaredOut:G.number})},{name:`string.numeric`}),Wc=`a regex pattern`,Gc=U({domain:`string`,predicate:{meta:Wc,predicate:(e,t)=>{try{return new RegExp(e),!0}catch(e){return t.reject({code:`predicate`,expected:Wc,problem:String(e)})}}},meta:{format:`regex`}}),Kc=q(/^(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/)`),qc=q(/^\S.*\S$|^\S?$/,`trimmed`),Jc=K.module({root:U({in:`string`,morphs:e=>e.trim(),declaredOut:qc}),preformatted:qc},{name:`string.trim`}),Yc=q(/^[A-Z]*$/,`only uppercase letters`),Xc=K.module({root:U({in:`string`,morphs:e=>e.toUpperCase(),declaredOut:Yc}),preformatted:Yc},{name:`string.upper`}),Zc=U({domain:`string`,predicate:{meta:`a URL string`,predicate:e=>URL.canParse(e)},meta:{format:`uri`}}),Qc=K.module({root:Zc,parse:U({declaredIn:Zc,in:`string`,morphs:(e,t)=>{try{return new URL(e)}catch{return t.error(`a URL string`)}},declaredOut:U(URL)})},{name:`string.url`}),$c=K.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:q(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv1`),v2:q(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv2`),v3:q(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv3`),v4:q(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv4`),v5:q(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv5`),v6:q(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv6`),v7:q(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv7`),v8:q(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv8`)},{name:`string.uuid`}),el=K.module({root:G.string,alpha:q(/^[A-Za-z]*$/,`only letters`),alphanumeric:q(/^[\dA-Za-z]*$/,`only letters and digits 0-9`),hex:dc,base64:fc,capitalize:mc,creditCard:hc,date:Sc,digits:q(/^\d*$/,`only digits 0-9`),email:Cc,integer:uc,ip:Dc,json:jc,lower:Nc,normalize:Vc,numeric:Uc,regex:Gc,semver:Kc,trim:Jc,upper:Xc,url:Qc,uuid:$c},{name:`string`}),tl=K.module({bigint:G.bigint,boolean:G.boolean,false:G.false,never:G.never,null:G.null,number:G.number,object:G.object,string:G.string,symbol:G.symbol,true:G.true,unknown:G.unknown,undefined:G.undefined}),nl=K.module({root:G.unknown,any:G.unknown},{name:`unknown`}),rl=K.module({root:G.jsonObject,stringify:Ma(`morph`,{in:G.jsonObject,morphs:e=>JSON.stringify(e),declaredOut:G.string})},{name:`object.json`}),il=K.module({root:G.object,json:rl},{name:`object`}),al=class extends C{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'},ol=W([`K`,G.key],`V`)(e=>({domain:`object`,index:{signature:e.K,value:e.V}}),al),sl=class extends C{description='pick a set of properties from an object like `Pick(User, "name | age")`'},cl=W([`T`,G.object],[`K`,G.key])(e=>e.T.pick(e.K),sl),ll=class extends C{description='omit a set of properties from an object like `Omit(User, "age")`'},ul=W([`T`,G.object],[`K`,G.key])(e=>e.T.omit(e.K),ll),dl=class extends C{description="make all named properties of an object optional like `Partial(User)`"},fl=W([`T`,G.object])(e=>e.T.partial(),dl),pl=class extends C{description="make all named properties of an object required like `Required(User)`"},ml=W([`T`,G.object])(e=>e.T.required(),pl),hl=class extends C{description='exclude branches of a union like `Exclude("boolean", "true")`'},gl=W(`T`,`U`)(e=>e.T.exclude(e.U),hl),_l=class extends C{description='extract branches of a union like `Extract("0 | false | 1", "number")`'},vl=W(`T`,`U`)(e=>e.T.extract(e.U),_l),yl=K.module({Exclude:gl,Extract:vl,Omit:ul,Partial:fl,Pick:cl,Record:ol,Required:ml}),X=qs({...tl,...yl,...ac,...Xs,string:el,number:cc,object:il,unknown:nl},{prereducedAliases:!0,name:`ark`}),Z=X.export();Object.assign(Gs.ambient,Z),Gs.typeAttachments={string:Z.string.root,number:Z.number.root,bigint:Z.bigint,boolean:Z.boolean,symbol:Z.symbol,undefined:
34Z.undefined,null:Z.null,object:Z.object.root,unknown:Z.unknown.root,false:Z.false,true:Z.true,never:Z.never,arrayIndex:Z.Array.index,Key:Z.Key,Record:Z.Record,Array:Z.Array.root,Date:Z.Date};var Q=Object.assign(X.type,Gs.typeAttachments);X.match,X.fn,X.generic,X.schema,X.define,X.declare;var $={REQUIRED:`ÐÑо поле обÑзаÑелÑное Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ`,PASSWORD_CONFIRM:`ÐведеннÑе паÑоли не ÑовпадаÑÑ`,LENGTH_LESS:`ÐолиÑеÑÑво Ñимволов не должно бÑÑÑ Ð¼ÐµÐ½ÑÑе`,LENGTH_LONG:`ÐолиÑеÑÑво Ñимволов не должно пÑевÑÑаÑÑ`},bl=/^[\s\S]{8,32}$/,xl=Q({firstName:Q(`string`).narrow((e,t)=>e.length>0&&e.length<=32?!0:e.length===0?t.reject({message:$.REQUIRED,actual:``}):t.reject({message:`${$.LENGTH_LONG} 32 Ñимвола`,actual:``})),lastName:Q(`string`).narrow((e,t)=>e.length>0&&e.length<=32?!0:e.length===0?t.reject({message:$.REQUIRED,actual:``}):t.reject({message:`${$.LENGTH_LONG} 32 Ñимвола`,actual:``}))}),Sl=()=>{let r=t({firstName:``,lastName:``,email:``,password:``,confirmPassword:``,agreedWithPlatformTerms:void 0});return{signUpSchema:e(()=>Q({agreedWithPlatformTerms:Q(`unknown`).narrow((e,t)=>e===!0||t.reject({message:$.REQUIRED,actual:``})),firstName:Q(`string`).narrow((e,t)=>e.length>0&&e.length<=32?!0:e.length===0?t.reject({message:$.REQUIRED,actual:``}):t.reject({message:`${$.LENGTH_LONG} 32 Ñимвола`,actual:``})),lastName:Q(`string`).narrow((e,t)=>e.length>0&&e.length<=32?!0:e.length===0?t.reject({message:$.REQUIRED,actual:``}):t.reject({message:`${$.LENGTH_LONG} 32 Ñимвола`,actual:``})),email:Q(`string.email`).configure({message:`ÐевалиднÑй адÑÐµÑ Ð¿Ð¾ÑÑÑ`}),password:Q(`string`).narrow((e,t)=>bl.test(e)?!0:t.reject({message:`ÐинимÑм 8 Ñимволов`,actual:``})),confirmPassword:Q(`string`).narrow((e,t)=>e===t.root.password||t.reject({message:`ÐаÑоли не ÑовпадаÑÑ`,actual:``}))})),signUpState:r,submitForm:async e=>{await n(`/api/v1/auth/sign-up`,{body:e,method:`POST`})}}};export{Q as i,bl as n,Sl as r,xl as t}; 35//# sourceMappingURL=CY-xNfA82.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.