drive-coding 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.he.md +98 -0
  3. package/README.md +97 -0
  4. package/dist/drive-coding.js +126981 -0
  5. package/frontend-dist/_app/env.js +1 -0
  6. package/frontend-dist/_app/immutable/assets/0.CU-P_407.css +1 -0
  7. package/frontend-dist/_app/immutable/assets/2.D9ALpOww.css +1 -0
  8. package/frontend-dist/_app/immutable/assets/3.E6ED7Syh.css +1 -0
  9. package/frontend-dist/_app/immutable/assets/5.YWA13FkN.css +1 -0
  10. package/frontend-dist/_app/immutable/assets/KaTeX_AMS-Regular.BQhdFMY1.woff2 +0 -0
  11. package/frontend-dist/_app/immutable/assets/KaTeX_AMS-Regular.DMm9YOAa.woff +0 -0
  12. package/frontend-dist/_app/immutable/assets/KaTeX_AMS-Regular.DRggAlZN.ttf +0 -0
  13. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Bold.ATXxdsX0.ttf +0 -0
  14. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Bold.BEiXGLvX.woff +0 -0
  15. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Bold.Dq_IR9rO.woff2 +0 -0
  16. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Regular.CTRA-rTL.woff +0 -0
  17. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Regular.Di6jR-x-.woff2 +0 -0
  18. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Regular.wX97UBjC.ttf +0 -0
  19. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Bold.BdnERNNW.ttf +0 -0
  20. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Bold.BsDP51OF.woff +0 -0
  21. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Bold.CL6g_b3V.woff2 +0 -0
  22. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Regular.CB_wures.ttf +0 -0
  23. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Regular.CTYiF6lA.woff2 +0 -0
  24. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Regular.Dxdc4cR9.woff +0 -0
  25. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Bold.Cx986IdX.woff2 +0 -0
  26. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Bold.Jm3AIy58.woff +0 -0
  27. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Bold.waoOVXN0.ttf +0 -0
  28. package/frontend-dist/_app/immutable/assets/KaTeX_Main-BoldItalic.DxDJ3AOS.woff2 +0 -0
  29. package/frontend-dist/_app/immutable/assets/KaTeX_Main-BoldItalic.DzxPMmG6.ttf +0 -0
  30. package/frontend-dist/_app/immutable/assets/KaTeX_Main-BoldItalic.SpSLRI95.woff +0 -0
  31. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Italic.3WenGoN9.ttf +0 -0
  32. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Italic.BMLOBm91.woff +0 -0
  33. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Italic.NWA7e6Wa.woff2 +0 -0
  34. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Regular.B22Nviop.woff2 +0 -0
  35. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Regular.Dr94JaBh.woff +0 -0
  36. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Regular.ypZvNtVU.ttf +0 -0
  37. package/frontend-dist/_app/immutable/assets/KaTeX_Math-BoldItalic.B3XSjfu4.ttf +0 -0
  38. package/frontend-dist/_app/immutable/assets/KaTeX_Math-BoldItalic.CZnvNsCZ.woff2 +0 -0
  39. package/frontend-dist/_app/immutable/assets/KaTeX_Math-BoldItalic.iY-2wyZ7.woff +0 -0
  40. package/frontend-dist/_app/immutable/assets/KaTeX_Math-Italic.DA0__PXp.woff +0 -0
  41. package/frontend-dist/_app/immutable/assets/KaTeX_Math-Italic.flOr_0UB.ttf +0 -0
  42. package/frontend-dist/_app/immutable/assets/KaTeX_Math-Italic.t53AETM-.woff2 +0 -0
  43. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Bold.CFMepnvq.ttf +0 -0
  44. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Bold.D1sUS0GD.woff2 +0 -0
  45. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Bold.DbIhKOiC.woff +0 -0
  46. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Italic.C3H0VqGB.woff2 +0 -0
  47. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Italic.DN2j7dab.woff +0 -0
  48. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Italic.YYjJ1zSn.ttf +0 -0
  49. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Regular.BNo7hRIc.ttf +0 -0
  50. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Regular.CS6fqUqJ.woff +0 -0
  51. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Regular.DDBCnlJ7.woff2 +0 -0
  52. package/frontend-dist/_app/immutable/assets/KaTeX_Script-Regular.C5JkGWo-.ttf +0 -0
  53. package/frontend-dist/_app/immutable/assets/KaTeX_Script-Regular.D3wIWfF6.woff2 +0 -0
  54. package/frontend-dist/_app/immutable/assets/KaTeX_Script-Regular.D5yQViql.woff +0 -0
  55. package/frontend-dist/_app/immutable/assets/KaTeX_Size1-Regular.C195tn64.woff +0 -0
  56. package/frontend-dist/_app/immutable/assets/KaTeX_Size1-Regular.Dbsnue_I.ttf +0 -0
  57. package/frontend-dist/_app/immutable/assets/KaTeX_Size1-Regular.mCD8mA8B.woff2 +0 -0
  58. package/frontend-dist/_app/immutable/assets/KaTeX_Size2-Regular.B7gKUWhC.ttf +0 -0
  59. package/frontend-dist/_app/immutable/assets/KaTeX_Size2-Regular.Dy4dx90m.woff2 +0 -0
  60. package/frontend-dist/_app/immutable/assets/KaTeX_Size2-Regular.oD1tc_U0.woff +0 -0
  61. package/frontend-dist/_app/immutable/assets/KaTeX_Size3-Regular.CTq5MqoE.woff +0 -0
  62. package/frontend-dist/_app/immutable/assets/KaTeX_Size3-Regular.DgpXs0kz.ttf +0 -0
  63. package/frontend-dist/_app/immutable/assets/KaTeX_Size4-Regular.BF-4gkZK.woff +0 -0
  64. package/frontend-dist/_app/immutable/assets/KaTeX_Size4-Regular.DWFBv043.ttf +0 -0
  65. package/frontend-dist/_app/immutable/assets/KaTeX_Size4-Regular.Dl5lxZxV.woff2 +0 -0
  66. package/frontend-dist/_app/immutable/assets/KaTeX_Typewriter-Regular.C0xS9mPB.woff +0 -0
  67. package/frontend-dist/_app/immutable/assets/KaTeX_Typewriter-Regular.CO6r4hn1.woff2 +0 -0
  68. package/frontend-dist/_app/immutable/assets/KaTeX_Typewriter-Regular.D3Ib7_Hf.ttf +0 -0
  69. package/frontend-dist/_app/immutable/assets/LoadingModal.DNP0Snt_.css +1 -0
  70. package/frontend-dist/_app/immutable/assets/ort-wasm-simd-threaded.jsep.CyqnNavA.wasm +0 -0
  71. package/frontend-dist/_app/immutable/chunks/6wE5kWJZ.js +1 -0
  72. package/frontend-dist/_app/immutable/chunks/BQWUQCb9.js +1 -0
  73. package/frontend-dist/_app/immutable/chunks/Ba9FG7d8.js +1 -0
  74. package/frontend-dist/_app/immutable/chunks/BeCtfktE.js +292 -0
  75. package/frontend-dist/_app/immutable/chunks/Bg0A44SF.js +1 -0
  76. package/frontend-dist/_app/immutable/chunks/CKhUHIER.js +1 -0
  77. package/frontend-dist/_app/immutable/chunks/CeZBaqrV.js +1 -0
  78. package/frontend-dist/_app/immutable/chunks/CisdKsFD.js +1 -0
  79. package/frontend-dist/_app/immutable/chunks/CqwDxRdj.js +1 -0
  80. package/frontend-dist/_app/immutable/chunks/CuPEg3Gz.js +2 -0
  81. package/frontend-dist/_app/immutable/chunks/CuT6ZSeQ.js +1 -0
  82. package/frontend-dist/_app/immutable/chunks/DgOhoED9.js +1 -0
  83. package/frontend-dist/_app/immutable/chunks/DvwKyUJ9.js +1 -0
  84. package/frontend-dist/_app/immutable/chunks/JqqgS7yq.js +1 -0
  85. package/frontend-dist/_app/immutable/chunks/LL0hSDod.js +1 -0
  86. package/frontend-dist/_app/immutable/chunks/LNR4j0nK.js +7 -0
  87. package/frontend-dist/_app/immutable/chunks/Oe6tjNLB.js +1 -0
  88. package/frontend-dist/_app/immutable/chunks/SrseV9LB.js +109 -0
  89. package/frontend-dist/_app/immutable/chunks/cseHWQnP.js +2 -0
  90. package/frontend-dist/_app/immutable/chunks/iM4ae5dg.js +1 -0
  91. package/frontend-dist/_app/immutable/entry/app.Dtr_WULu.js +2 -0
  92. package/frontend-dist/_app/immutable/entry/start.DNvi4k83.js +1 -0
  93. package/frontend-dist/_app/immutable/nodes/0.D_beALrd.js +423 -0
  94. package/frontend-dist/_app/immutable/nodes/1.BDPrJE0T.js +1 -0
  95. package/frontend-dist/_app/immutable/nodes/2.CFtWC6Ki.js +1 -0
  96. package/frontend-dist/_app/immutable/nodes/3.D_3DlZlE.js +9 -0
  97. package/frontend-dist/_app/immutable/nodes/4.xmsDSvqR.js +4 -0
  98. package/frontend-dist/_app/immutable/nodes/5.CihE_QrF.js +2881 -0
  99. package/frontend-dist/_app/version.json +1 -0
  100. package/frontend-dist/icons/apple-touch-icon.png +0 -0
  101. package/frontend-dist/icons/favicon-64.png +0 -0
  102. package/frontend-dist/icons/icon-180.png +0 -0
  103. package/frontend-dist/icons/icon-192.png +0 -0
  104. package/frontend-dist/icons/icon-512-maskable.png +0 -0
  105. package/frontend-dist/icons/icon-512.png +0 -0
  106. package/frontend-dist/index.html +67 -0
  107. package/frontend-dist/manifest.webmanifest +17 -0
  108. package/frontend-dist/wake-word/models/alexa_v0.1.onnx +0 -0
  109. package/frontend-dist/wake-word/models/embedding_model.onnx +0 -0
  110. package/frontend-dist/wake-word/models/hey_jarvis_v0.1.onnx +0 -0
  111. package/frontend-dist/wake-word/models/hey_mycroft_v0.1.onnx +0 -0
  112. package/frontend-dist/wake-word/models/hey_rhasspy_v0.1.onnx +0 -0
  113. package/frontend-dist/wake-word/models/melspectrogram.onnx +0 -0
  114. package/frontend-dist/wake-word/models/silero_vad.onnx +0 -0
  115. package/package.json +42 -0
  116. package/plugins/README.md +47 -0
  117. package/plugins/prompt-injector.ts +83 -0
@@ -0,0 +1,109 @@
1
+ var so=Object.defineProperty;var oo=(e,n,t)=>n in e?so(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var c=(e,n,t)=>oo(e,typeof n!="symbol"?n+"":n,t);const _e=e=>Array.isArray(e)?e:[e],ao=(e,n)=>{const t=[[],[]];for(const r of e)n(r)?t[0].push(r):t[1].push(r);return t},ni=Array,X=(e,n)=>e.includes(n),lo=(e,n=0)=>[...new Array(e)].map((t,r)=>r+n),N=(e,n,t)=>e===void 0?n===void 0?[]:Array.isArray(n)?n:[n]:(Array.isArray(n)?e.push(...n):e.push(n),e),fe=(e,n)=>n==null?e??[]:e==null?_e(n):e.concat(n),co=(...e)=>e.reduce(fe,[]),me=(e,n,t)=>{if(e===void 0)return Array.isArray(n)?n:[n];const r=(t==null?void 0:t.isEqual)??((i,s)=>i===s);for(const i of _e(n))e.some(s=>r(s,i))||e.push(i);return e},uo=(e,n)=>e.reduce((t,r)=>{const i=r[n];return t[i]=N(t[i],r),t},{}),Ie=(e,n,t)=>e.length===n.length&&e.every(t!=null&&t.isEqual?(r,i)=>t.isEqual(r,n[i]):(r,i)=>r===n[i]),ye=(e,n)=>G(e)===n,G=e=>{const n=typeof e;return n==="object"?e===null?"null":"object":n==="function"?"object":n},ee={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},ho={...ee,function:"a function"};class po extends Error{}const B=e=>Ne(e,po),Ne=(e,n=Error)=>{throw new n(e)};class fo extends Error{constructor(){super(...arguments);c(this,"name","ParseError")}}const f=e=>Ne(e,fo),ri=e=>` ${e}`,mo="​",R=(e,n)=>{const t={},r=Array.isArray(e);let i=!1;for(const[s,o]of Object.entries(e).entries()){const a=r?n(s,o[1]):n(...o,s);i||(i=typeof a[0]=="number");const l=Array.isArray(a[0])||a.length===0?a:[a];for(const[u,h]of l)typeof u=="object"?t[u.group]=N(t[u.group],h):t[u]=h}return i?Object.values(t):t},ii=Object.entries,W=(e,n)=>e in n,fn=(e,n)=>n in e;class go{constructor(n){Object.assign(this,n)}}const bo=class{};class si extends bo{}const yo=(e,n)=>{const t={},r={};let i;for(i in e)i in n?t[i]=e[i]:r[i]=e[i];return[t,r]},oi=(e,n)=>yo(e,n)[1],Ve=e=>Object.keys(e).length===0,ct=e=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map(n=>[n,e[n]])],ko=(e,n)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)),xo=e=>{const n=Object.keys(e).sort(),t={};for(let r=0;r<n.length;r++)t[n[r]]=e[n[r]];return t},Z=ri(`unset${mo}`),$o=e=>Object.values(e).filter(n=>typeof n=="number"?!0:typeof e[n]!="number"),ai={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},li=globalThis.File??Blob,ci={ArrayBuffer,Blob,File:li,FormData,Headers,Request,Response,URL},wo={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},Re={...ai,...ci,...wo,String,Number,Boolean},mn=e=>{var r;let n=Object.getPrototypeOf(e);for(;n!=null&&n.constructor&&(!W(n.constructor.name,Re)||!(e instanceof Re[n.constructor.name]));)n=Object.getPrototypeOf(n);const t=(r=n==null?void 0:n.constructor)==null?void 0:r.name;if(!(t===void 0||t==="Object"))return t},Vt=e=>typeof e=="object"&&e!==null?mn(e)??"object":G(e),L=Array.isArray,vo={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"},So={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"},Ao={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"},Io={...vo,...So,...Ao},gn=e=>{const n=Object(e).name??null;return n&&W(n,Re)&&Re[n]===e?n:null},jn=(e,n)=>{let t=e.prototype;for(;t!==null;){if(t===n.prototype)return!0;t=Object.getPrototypeOf(t)}return!1},No=e=>ui(e,new Map),ui=(e,n)=>{if(typeof e!="object"||e===null)return e;if(n!=null&&n.has(e))return n.get(e);const t=gn(e.constructor);if(t==="Date")return new Date(e.getTime());if(t&&t!=="Array")return e;const r=Array.isArray(e)?e.slice():Object.create(Object.getPrototypeOf(e)),i=Object.getOwnPropertyDescriptors(e);if(n){n.set(e,r);for(const s in i){const o=i[s];"get"in o||"set"in o||(o.value=ui(o.value,n))}}return Object.defineProperties(r,i),r},Ro=e=>{let n=Z;return()=>n===Z?n=e():n},wt=e=>typeof e=="function"&&e.length===0,Oo=class extends Function{constructor(...e){const n=e.slice(0,-1),t=e[e.length-1];try{super(...n,t)}catch(r){return B(`Encountered an unexpected error while compiling your definition:
2
+ Message: ${r}
3
+ Source: (${e.slice(0,-1)}) => {
4
+ ${e[e.length-1]}
5
+ }`)}}};class ue{constructor(n,...[t]){return Object.assign(Object.setPrototypeOf(n.bind((t==null?void 0:t.bind)??this),this.constructor.prototype),t==null?void 0:t.attach)}}const qo=Ro(()=>{try{return new Function("return false")()}catch{return!0}});class Q{constructor(){}}const Co=()=>{var e,n,t;try{return(((t=(((n=(e=new Error().stack)==null?void 0:e.split(`
6
+ `)[2])==null?void 0:n.trim())||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/))==null?void 0:t[1])||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}};var Ur;const Mo=((Ur=globalThis.process)==null?void 0:Ur.env)??{},Do={fileName:Co,env:Mo},Bo=e=>e[0].toUpperCase()+e.slice(1),Ko=e=>e[0].toLowerCase()+e.slice(1),hi=e=>new RegExp(zo(e),typeof e=="string"?"":e.flags),zo=e=>`^(?:${typeof e=="string"?e:e.source})$`,ae={negativeLookahead:e=>`(?!${e})`,nonCapturingGroup:e=>`(?:${e})`},je="\\",vt={" ":1,"\n":1," ":1},Eo=/^-0\.?0*$/.source,di=/[1-9]\d*/.source,Po=/\.\d+/.source,To=/\.\d*[1-9]/.source,pi=e=>hi(ae.negativeLookahead(Eo)+ae.nonCapturingGroup("-?"+ae.nonCapturingGroup(ae.nonCapturingGroup("0|"+di)+ae.nonCapturingGroup(e.decimalPattern)+"?")+(e.allowDecimalOnly?"|"+e.decimalPattern:"")+"?")),Fn=pi({decimalPattern:To,allowDecimalOnly:!1}),Lo=Fn.test.bind(Fn),Gt=pi({decimalPattern:Po,allowDecimalOnly:!0});Gt.test.bind(Gt);const jo=/^-?\d*\.?\d*$/,Fo=e=>e.length!==0&&jo.test(e),ut=hi(ae.negativeLookahead("^-0$")+"-?"+ae.nonCapturingGroup(ae.nonCapturingGroup("0|"+di))),Uo=ut.test.bind(ut),Ht=/^-?\d+$/,Jo=Ht.test.bind(Ht),fi={number:"a number",bigint:"a bigint",integer:"an integer"},mi=(e,n)=>`'${e}' was parsed as ${fi[n]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,_o=(e,n)=>n==="number"?Lo(e):Uo(e),Vo=(e,n)=>n==="number"?Number(e):Number.parseInt(e),Go=(e,n)=>n==="number"?Fo(e):Jo(e),Ho=(e,n)=>bn(e,"number",n),Zo=(e,n)=>bn(e,"number",{...n,strict:!0}),Wo=(e,n)=>bn(e,"integer",n),bn=(e,n,t)=>{const r=Vo(e,n);return!Number.isNaN(r)&&Go(e,n)?t!=null&&t.strict?_o(e,n)?r:f(mi(e,n)):r:t!=null&&t.errorOnFail?f((t==null?void 0:t.errorOnFail)===!0?`Failed to parse ${fi[n]} from '${e}'`:t==null?void 0:t.errorOnFail):void 0},Qo=e=>{if(e[e.length-1]!=="n")return;const n=e.slice(0,-1);let t;try{t=BigInt(n)}catch{return}if(ut.test(n))return t;if(Ht.test(n))return f(mi(e,"bigint"))},Yo="0.56.0",Xo={version:Yo,filename:Do.fileName(),FileConstructor:li},Ge=Xo,Un=new Map,Bt=Object.create(null),Zt=e=>{const n=Un.get(e);if(n)return n;let t=ea(e);return Bt[t]?t=`${t}${Bt[t]++}`:Bt[t]=1,Ge[t]=e,Un.set(e,t),t},Ue=e=>/^[$A-Z_a-z][\w$]*$/.test(e),ea=e=>{switch(typeof e){case"object":{if(e===null)break;const n=mn(e)??"object";return n[0].toLowerCase()+n.slice(1)}case"function":return Ue(e.name)?e.name:"fn";case"symbol":return e.description&&Ue(e.description)?e.description:"symbol"}return B(`Unexpected attempt to register serializable value of type ${G(e)}`)},yn=e=>typeof e=="string"?JSON.stringify(e):typeof e=="bigint"?`${e}n`:`${e}`,ta=(e,n={})=>Fe(e,{onUndefined:"$ark.undefined",onBigInt:t=>`$ark.bigint-${t}`,...n},[]),I=(e,n)=>{var t;switch(G(e)){case"object":const r=e,i=((t=r.constructor)==null?void 0:t.name)??"Object";return i==="Object"||i==="Array"?(n==null?void 0:n.quoteKeys)===!1?ht(r,(n==null?void 0:n.indent)??0,""):JSON.stringify(Fe(r,Oe,[]),null,n==null?void 0:n.indent):ht(r,(n==null?void 0:n.indent)??0,"");case"symbol":return Oe.onSymbol(e);default:return yn(e)}},ht=(e,n,t)=>{var s;if(typeof e=="function")return Oe.onFunction(e);if(typeof e!="object"||e===null)return yn(e);const r=t+" ".repeat(n);if(Array.isArray(e)){if(e.length===0)return"[]";const o=e.map(a=>ht(a,n,r)).join(`,
7
+ `+r);return n?`[
8
+ ${r}${o}
9
+ ${t}]`:`[${o}]`}const i=((s=e.constructor)==null?void 0:s.name)??"Object";if(i==="Object"){const o=ct(e).map(([a,l])=>{const u=typeof a=="symbol"?Oe.onSymbol(a):Ue(a)?a:JSON.stringify(a),h=ht(l,n,r);return`${r}${u}: ${h}`});return o.length===0?"{}":n?`{
10
+ ${o.join(`,
11
+ `)}
12
+ ${t}}`:`{${o.join(", ")}}`}return e instanceof Date?He(e):"expression"in e&&typeof e.expression=="string"?e.expression:i},Oe={onCycle:()=>"(cycle)",onSymbol:e=>`Symbol(${Zt(e)})`,onFunction:e=>`Function(${Zt(e)})`},Fe=(e,n,t)=>{var r,i;switch(G(e)){case"object":{const s=e;if("toJSON"in s&&typeof s.toJSON=="function")return s.toJSON();if(typeof s=="function")return Oe.onFunction(s);if(t.includes(s))return"(cycle)";const o=[...t,s];if(Array.isArray(s))return s.map(l=>Fe(l,n,o));if(s instanceof Date)return s.toDateString();const a={};for(const l in s)a[l]=Fe(s[l],n,o);for(const l of Object.getOwnPropertySymbols(s))a[((r=n.onSymbol)==null?void 0:r.call(n,l))??l.toString()]=Fe(s[l],n,o);return a}case"symbol":return Oe.onSymbol(e);case"bigint":return((i=n.onBigInt)==null?void 0:i.call(n,e))??`${e}n`;case"undefined":return n.onUndefined??"undefined";case"string":return e.replace(/\\/g,"\\\\");default:return e}},He=e=>{const n=e.getFullYear(),t=e.getMonth(),r=e.getDate(),i=e.getHours(),s=e.getMinutes(),o=e.getSeconds(),a=e.getMilliseconds();if(t===0&&r===1&&i===0&&s===0&&o===0&&a===0)return`${n}`;const l=`${na[t]} ${r}, ${n}`;if(i===0&&s===0&&o===0&&a===0)return l;let u=e.toLocaleTimeString();const h=u.endsWith(" AM")||u.endsWith(" PM")?u.slice(-3):"";return h&&(u=u.slice(0,-h.length)),a?u+=`.${ia(a,3)}`:ra.test(u)&&(u=u.slice(0,-3)),`${u+h}, ${l}`},na=["January","February","March","April","May","June","July","August","September","October","November","December"],ra=/:\d\d:00$/,ia=(e,n)=>String(e).padStart(n,"0"),gi=(e,n,...[t])=>{const r=(t==null?void 0:t.stringifySymbol)??I;let i=e;switch(typeof n){case"string":i=Ue(n)?e===""?n:`${e}.${n}`:`${e}[${JSON.stringify(n)}]`;break;case"number":i=`${e}[${n}]`;break;case"symbol":i=`${e}[${r(n)}]`;break;default:t!=null&&t.stringifyNonKey?i=`${e}[${t.stringifyNonKey(n)}]`:f(`${I(n)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return i},Ze=(e,...n)=>e.reduce((t,r)=>gi(t,r,...n),"");class bi extends ni{constructor(...t){super();c(this,"cache",{});this.push(...t)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let t=0;t<this.length;t++)this.cache.json.push(typeof this[t]=="symbol"?I(this[t]):this[t]);return this.cache.json}stringify(){return this.cache.stringify?this.cache.stringify:this.cache.stringify=Ze(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let t="";const r=[t];for(const i of this)t=gi(t,i),r.push(t);return this.cache.stringifyAncestors=r}}class yi{constructor(n){c(this,"chars");c(this,"i");c(this,"def");this.def=n,this.chars=[...n],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(n){let t="";for(;this.lookahead&&!n(this,t);)t+=this.shift();return t}shiftUntilEscapable(n){let t="";for(;this.lookahead;)if(this.lookahead===je)this.shift(),n(this,t)?t+=this.shift():this.lookahead===je?t+=this.shift():t+=`${je}${this.shift()}`;else{if(n(this,t))break;t+=this.shift()}return t}shiftUntilLookahead(n){return typeof n=="string"?this.shiftUntil(t=>t.lookahead===n):this.shiftUntil(t=>t.lookahead in n)}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in vt))}jumpToIndex(n){this.i=n<0?this.length+n:n}jumpForward(n){this.i+=n}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(n,t){return this.chars.slice(n,t).join("")}lookaheadIs(n){return this.lookahead===n}lookaheadIsIn(n){return this.lookahead in n}}const sa=(e,n)=>`Unmatched ${e}${n===""?"":` before ${n}`}`,ki=e=>`Missing ${e}`;let Wt="$ark",oa=2;for(;Wt in globalThis;)Wt=`$ark${oa++}`;const xi=Wt;globalThis[xi]=Ge;const g=Ge,aa=e=>`${xi}.${e}`,F=e=>aa(Zt(e));class $i extends si{constructor(...t){super();c(this,"argNames");c(this,"body","");c(this,"indentation",0);this.argNames=t;for(const r of t){if(r in this)throw new Error(`Arg name '${r}' would overwrite an existing property on FunctionBody`);this[r]=r}}indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(t,r=!1){return wi(t,r)}index(t,r=!1){return vi(`${t}`,r)}line(t){return this.body+=`${" ".repeat(this.indentation)}${t}
13
+ `,this}const(t,r){return this.line(`const ${t} = ${r}`),this}let(t,r){return this.line(`let ${t} = ${r}`)}set(t,r){return this.line(`${t} = ${r}`)}if(t,r){return this.block(`if (${t})`,r)}elseIf(t,r){return this.block(`else if (${t})`,r)}else(t){return this.block("else",t)}for(t,r,i=0){return this.block(`for (let i = ${i}; ${t}; i++)`,r)}forIn(t,r){return this.block(`for (const k in ${t})`,r)}block(t,r,i=""){return this.line(`${t} {`),this.indent(),r(this),this.dedent(),this.line(`}${i}`)}return(t=""){return this.line(`return ${t}`)}write(t="anonymous",r=0){return`${t}(${this.argNames.join(", ")}) { ${r?this.body.split(`
14
+ `).map(i=>" ".repeat(r)+`${i}`).join(`
15
+ `):this.body} }`}compile(){return new Oo(...this.argNames,this.body)}}const Ce=e=>ye(e,"object")||typeof e=="symbol"?F(e):yn(e),wi=(e,n=!1)=>typeof e=="string"&&Ue(e)?`${n?"?":""}.${e}`:vi(la(e),n),la=e=>typeof e=="symbol"?F(e):JSON.stringify(e),vi=(e,n=!1)=>`${n?"?.":""}[${e}]`;class Kt extends $i{constructor(t){super("data","ctx");c(this,"traversalKind");c(this,"optimistic");this.traversalKind=t.kind,this.optimistic=t.optimistic===!0}invoke(t,r){const i=(r==null?void 0:r.arg)??this.data,s=typeof t=="string"?!0:this.requiresContextFor(t),o=typeof t=="string"?t:t.id;return s?`${this.referenceToId(o,r)}(${i}, ${this.ctx})`:`${this.referenceToId(o,r)}(${i})`}referenceToId(t,r){const i=(r==null?void 0:r.kind)??this.traversalKind,s=`this.${t}${i}`;return r!=null&&r.bind?`${s}.bind(${r==null?void 0:r.bind})`:s}requiresContextFor(t){return this.traversalKind==="Apply"||t.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(t,r,i){const s=this.requiresContextFor(i);return s&&this.line(`${this.ctx}.path.push(${t})`),this.check(i,{arg:r}),s&&this.line(`${this.ctx}.path.pop()`),this}check(t,r){return this.traversalKind==="Allows"?this.if(`!${this.invoke(t,r)}`,()=>this.return(!1)):this.line(this.invoke(t,r))}}const Si=e=>R(e,(n,t)=>[n,L(t)?[...t]:t]),te=ri("arkKind"),k=(e,n)=>(e==null?void 0:e[te])===n,j=e=>k(e,"root")||k(e,"constraint"),ca=["unit","proto","domain"],St=["required","optional","index","sequence"],Ai=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],Ii=[...Ai,"structure","predicate"],kn=[...Ii,...St],At=["alias","union","morph","unit","intersection","proto","domain"],ua=[...At,...kn],Ni=R(kn,(e,n)=>[n,1]),ha=R([...St,"undeclared"],(e,n)=>[n,1]),Ri=R(ua,(e,n)=>[n,e]),at=e=>typeof e=="string"&&e in Ri,dt=e=>Ri[e],xn=e=>At.slice(dt(e)+1);[...xn("union")];[...xn("morph")];const ge=e=>typeof e=="string"||typeof e=="boolean"||e===null?e:typeof e=="number"?Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e:Ce(e),It=e=>{let n="{ ";for(const[t,r]of Object.entries(e))n+=`${t}: ${Ce(r)}, `;return n+" }"},M=e=>{var t,r,i,s;const n=e;return n.hasAssociatedError&&((t=n.defaults).expected??(t.expected=o=>"description"in o?o.description:n.defaults.description(o)),(r=n.defaults).actual??(r.actual=o=>I(o)),(i=n.defaults).problem??(i.problem=o=>`must be ${o.expected}${o.actual?` (was ${o.actual})`:""}`),(s=n.defaults).message??(s.message=o=>{if(o.path.length===0)return o.problem;const a=`${o.propString} ${o.problem}`;return a[0]==="["?`value at ${a}`:a})),n};class da extends Error{constructor(t,r){super(I(r,{quoteKeys:!1,indent:4}));c(this,"name","ToJsonSchemaError");c(this,"code");c(this,"context");this.code=t,this.context=r}hasCode(t){return this.code===t}}const pa={target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:e=>K.throw("arrayObject",e),arrayPostfix:e=>K.throw("arrayPostfix",e),defaultValue:e=>K.throw("defaultValue",e),domain:e=>K.throw("domain",e),morph:e=>K.throw("morph",e),patternIntersection:e=>K.throw("patternIntersection",e),predicate:e=>K.throw("predicate",e),proto:e=>K.throw("proto",e),symbolKey:e=>K.throw("symbolKey",e),unit:e=>K.throw("unit",e),date:e=>K.throw("date",e)}},K={Error:da,throw:(...e)=>{throw new K.Error(...e)},throwInternalOperandError:(e,n)=>B(`Unexpected JSON Schema input for ${e}: ${I(n)}`),defaultConfig:pa};g.config??(g.config={});const Qt=(e,n)=>{if(!n)return e;const t={...e};let r;for(r in n){const i={...e.keywords};if(r==="keywords"){for(const s in n[r]){const o=n.keywords[s];o!==void 0&&(i[s]=typeof o=="string"?{description:o}:o)}t.keywords=i}else r==="toJsonSchema"?t[r]=Oi(e.toJsonSchema,n.toJsonSchema):at(r)?t[r]={...e[r],...n[r]}:t[r]=n[r]}return t},fa={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"},Oi=((e,n)=>{if(!e)return Jn(n??{},void 0);if(!n)return e;const t={...e};let r;for(r in n)r==="fallback"?t.fallback=ma(e.fallback,n.fallback):t[r]=n[r];return Jn(t,n)}),Jn=(e,n)=>(n==null?void 0:n.dialect)!==void 0?e:(n==null?void 0:n.target)!==void 0?{...e,dialect:fa[n.target]}:e,ma=(e,n)=>{e=_n(e),n=_n(n);const t={};let r;for(r in K.defaultConfig.fallback)t[r]=n[r]??n.default??e[r]??e.default??K.defaultConfig.fallback[r];return t},_n=e=>typeof e=="function"?{default:e}:e??{};var Jr,_r;class qe extends(_r=si,Jr=te,_r){constructor({prefixPath:t,relativePath:r,...i},s){super();c(this,Jr,"error");c(this,"path");c(this,"data");c(this,"nodeConfig");c(this,"input");c(this,"ctx");this.input=i,this.ctx=s,ko(this,i);const o=s.data;i.code==="union"&&(i.errors=i.errors.flatMap(l=>{const u=l.hasCode("union")?l.errors:[l];return!t&&!r?u:u.map(h=>h.transform(d=>({...d,path:co(t,d.path,r)})))})),this.nodeConfig=s.config[this.code];const a=[...i.path??s.path];r&&a.push(...r),t&&a.unshift(...t),this.path=new bi(...a),this.data="data"in i?i.data:o}transform(t){return new qe(t({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(t){return this.code===t}get propString(){return Ze(this.path)}get expected(){var r;if(this.input.expected)return this.input.expected;const t=((r=this.meta)==null?void 0:r.expected)??this.nodeConfig.expected;return typeof t=="function"?t(this.input):t}get actual(){var r;if(this.input.actual)return this.input.actual;const t=((r=this.meta)==null?void 0:r.actual)??this.nodeConfig.actual;return typeof t=="function"?t(this.data):t}get problem(){var r;if(this.input.problem)return this.input.problem;const t=((r=this.meta)==null?void 0:r.problem)??this.nodeConfig.problem;return typeof t=="function"?t(this):t}get message(){var r;if(this.input.message)return this.input.message;const t=((r=this.meta)==null?void 0:r.message)??this.nodeConfig.message;return typeof t=="function"?t(this):t}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}var Vr,Gr;class ce extends(Gr=ni,Vr=te,Gr){constructor(t){super();c(this,Vr,"errors");c(this,"ctx");c(this,"byPath",Object.create(null));c(this,"byAncestorPath",Object.create(null));c(this,"count",0);c(this,"mutable",this);this.ctx=t}get flatByPath(){return R(this.byPath,(t,r)=>[t,r.flat])}get flatProblemsByPath(){return R(this.byPath,(t,r)=>[t,r.flat.map(i=>i.problem)])}throw(){throw this.toTraversalError()}toTraversalError(){return new ga(this)}add(t){const r=this.byPath[t.propString];if(r){if(t===r||r.hasCode("union")&&r.errors.length===0)return;const i=t.hasCode("union")&&t.errors.length===0?t:new qe({code:"intersection",errors:r.hasCode("intersection")?[...r.errors,t]:[r,t]},this.ctx),s=this.indexOf(r);this.mutable[s===-1?this.length:s]=i,this.byPath[t.propString]=i,this.addAncestorPaths(t)}else this.byPath[t.propString]=t,this.addAncestorPaths(t),this.mutable.push(t);this.count++}transform(t){const r=new ce(this.ctx);for(const i of this)r.add(t(i));return r}merge(t){for(const r of t)this.add(new qe({...r,path:[...this.ctx.path,...r.path]},this.ctx))}affectsPath(t){return this.length===0?!1:t.stringifyAncestors().some(r=>r in this.byPath)||t.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map(t=>t.toJSON())]}toString(){return this.join(`
16
+ `)}addAncestorPaths(t){for(const r of t.path.stringifyAncestors())this.byAncestorPath[r]=N(this.byAncestorPath[r],t)}}class ga extends Error{constructor(t){var n=(...Fd)=>(super(...Fd),c(this,"name","TraversalError"),this);t.length===1?n(t.summary):n(`
17
+ `+t.map(r=>` • ${ba(r)}`).join(`
18
+ `)),Object.defineProperty(this,"arkErrors",{value:t,enumerable:!1})}}const ba=e=>e.toString().split(`
19
+ `).join(`
20
+ `);class we{constructor(n,t){c(this,"path",[]);c(this,"errors",new ce(this));c(this,"root");c(this,"config");c(this,"queuedMorphs",[]);c(this,"branches",[]);c(this,"seen",{});this.root=n,this.config=t}get data(){let n=this.root;for(const t of this.path)n=n==null?void 0:n[t];return n}get propString(){return Ze(this.path)}reject(n){return this.error(n),!1}mustBe(n){return this.error(n),!1}error(n){const t=typeof n=="object"?n.code?n:{...n,code:"predicate"}:{code:"predicate",expected:n};return this.errorFromContext(t)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(n){const t={path:new bi(...this.path),morphs:n};this.currentBranch?this.currentBranch.queuedMorphs.push(t):this.queuedMorphs.push(t)}finalize(n){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()?n?n(this.errors):this.errors:this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(n){return this.errorFromContext(n)}errorFromContext(n){const t=new qe(n,this);return this.currentBranch?this.currentBranch.error=t:this.errors.add(t),t}applyQueuedMorphs(){for(;this.queuedMorphs.length;){const n=this.queuedMorphs;this.queuedMorphs=[];for(const{path:t,morphs:r}of n)this.errors.affectsPath(t)||this.applyMorphsAtPath(t,r)}}applyMorphsAtPath(n,t){const r=n[n.length-1];let i;if(r!==void 0){i=this.root;for(let s=0;s<n.length-1;s++)i=i[n[s]]}for(const s of t){this.path=[...n];const o=j(s),a=s(i===void 0?this.root:i[r],this);if(a instanceof qe){this.errors.includes(a)||this.errors.add(a);break}if(a instanceof ce){o||this.errors.merge(a),this.queuedMorphs=[];break}i===void 0?this.root=a:i[r]=a,this.applyQueuedMorphs()}}}const ne=(e,n,t)=>{if(!t)return n();t.path.push(e);const r=n();return t.path.pop(),r};class qi extends ue{constructor(t,r){var s;super((o,a,l=this.onFail)=>a?(this.traverseApply(o,a),a.hasError()?a.errors:a.data):this.rootApply(o,l),{attach:t});c(this,"attachments");c(this,"$");c(this,"onFail");c(this,"includesTransform");c(this,"includesContextualPredicate");c(this,"isCyclic");c(this,"allowsRequiresContext");c(this,"rootApplyStrategy");c(this,"contextFreeMorph");c(this,"rootApply");c(this,"referencesById");c(this,"shallowReferences");c(this,"flatRefs");c(this,"flatMorphs");c(this,"allows");c(this,"compiledMeta",xa(this.metaJson));c(this,"precedence",dt(this.kind));c(this,"precompilation");c(this,"assert",(t,r)=>this(t,r,i=>i.throw()));this.attachments=t,this.$=r,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((o,a)=>$a(o,a.shallowReferences),[this]);const i=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let o=0;o<this.children.length;o++){if(this.includesTransform||(this.includesTransform=this.children[o].includesTransform),this.includesContextualPredicate||(this.includesContextualPredicate=this.children[o].includesContextualPredicate),this.isCyclic||(this.isCyclic=this.children[o].isCyclic),!i){const a=this.children[o].flatRefs;for(let l=0;l<a.length;l++){const u=a[l];if(!this.flatRefs.some(h=>Ci(h,u))){this.flatRefs.push(u);for(const h of u.node.branches)(h.hasKind("morph")||h.hasKind("intersection")&&((s=h.structure)==null?void 0:s.structuralMorph)!==void 0)&&this.flatMorphs.push({path:u.path,propString:u.propString,node:h})}}}Object.assign(this.referencesById,this.children[o].referencesById)}this.flatRefs.sort((o,a)=>o.path.length>a.path.length?1:o.path.length<a.path.length?-1:o.propString>a.propString?1:o.propString<a.propString||o.node.expression<a.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(o=>o.length===1||o.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some(o=>o.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?o=>this.traverseAllows(o,new we(o,this.$.resolvedConfig)):o=>this.traverseAllows(o)}get shallowMorphs(){return[]}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(r,i)=>{if(this.allows(r))return r;const s=new we(r,this.$.resolvedConfig);return this.traverseApply(r,s),s.finalize(i)};case"contextual":return(r,i)=>{const s=new we(r,this.$.resolvedConfig);return this.traverseApply(r,s),s.finalize(i)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];const t=this.$.resolvedConfig.clone;return(r,i)=>{if(this.allows(r))return this.contextFreeMorph(t&&(typeof r=="object"&&r!==null||typeof r=="function")?t(r):r);const s=new we(r,this.$.resolvedConfig);return this.traverseApply(r,s),s.finalize(i)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,B(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}cacheGetter(t,r){return Object.defineProperty(this,t,{value:r}),r}get description(){var t;return this.cacheGetter("description",((t=this.meta)==null?void 0:t.description)??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}traverse(t,r){return this(t,r,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(t){if(!this.includesTransform)return this;const r={};for(const[i,s]of this.innerEntries){const o=this.impl.keys[i];if(o.reduceIo)o.reduceIo(t,r,s);else if(o.child){const a=s;r[i]=L(a)?a.map(l=>t==="in"?l.rawIn:l.rawOut):t==="in"?a.rawIn:a.rawOut}else r[i]=s}return this.$.node(this.kind,r)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(t){const r=j(t)?t:this.$.parseDefinition(t);return this.innerHash===r.innerHash}ifEquals(t){return this.equals(t)?this:void 0}hasKind(t){return this.kind===t}assertHasKind(t){return this.kind!==t&&Ne(`${this.kind} node was not of asserted kind ${t}`),this}hasKindIn(...t){return t.includes(this.kind)}assertHasKindIn(...t){return X(t,this.kind)||Ne(`${this.kind} node was not one of asserted kinds ${t}`),this}isBasis(){return X(ca,this.kind)}isConstraint(){return X(kn,this.kind)}isStructural(){return X(St,this.kind)}isRefinement(){return X(Ii,this.kind)}isRoot(){return X(At,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(t){return this.hasKind("unit")&&this.allows(t)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(t){const r=Pe.normalize(t);return this._select(r)}_select(t){let r=Pe.applyBoundary[t.boundary??"references"](this);return t.kind&&(r=r.filter(i=>i.kind===t.kind)),t.where&&(r=r.filter(t.where)),Pe.applyMethod[t.method??"filter"](r,this,t)}transform(t,r){return this._transform(t,this._createTransformContext(r))}_createTransformContext(t){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:(t==null?void 0:t.prereduced)??!1},undeclaredKeyHandling:void 0,...t}}_transform(t,r){var d;const i=r.bindScope??this.$;if(r.seen[this.id])return this.$.lazilyResolve(r.seen[this.id]);if(((d=r.shouldTransform)==null?void 0:d.call(r,this,r))===!1)return this;let s;r.seen[this.id]=()=>s,this.hasKind("structure")&&this.undeclared!==r.undeclaredKeyHandling&&(r={...r,undeclaredKeyHandling:this.undeclared});const o=R(this.inner,(m,b)=>{if(!this.impl.keys[m].child)return[m,b];const p=b;if(!L(p)){const $=p._transform(t,r);return $?[m,$]:[]}if(p.length===0)return[m,b];const S=p.flatMap($=>$._transform(t,r)??[]);return S.length?[m,S]:[]});delete r.seen[this.id];const a=Object.assign(o,{meta:this.meta}),l=r.selected&&!r.selected.includes(this)?a:t(this.kind,a,r);if(l===null)return null;if(j(l))return s=l;const u=Object.keys(l);return(u.length===0||u.length===1&&u[0]==="meta")&&!Ve(this.inner)?null:(this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in l)?r.undeclaredKeyHandling?{...l,value:g.intrinsic.unknown}:null:(this.kind==="morph"&&(l.in??(l.in=g.intrinsic.unknown)),s=i.node(this.kind,l,r.parseOptions))}configureReferences(t,r="references"){const i=Pe.normalize(r),s=typeof t=="string"?(u,h)=>({...h,meta:{...h.meta,description:t}}):typeof t=="function"?(u,h)=>({...h,meta:t(h.meta)}):(u,h)=>({...h,meta:{...h.meta,...t}});if(i.boundary==="self")return this.$.node(this.kind,s(this.kind,{...this.inner,meta:this.meta}));const o=this._select(i),a=o&&_e(o),l=i.boundary==="child"?(u,h)=>h.root.children.includes(u):i.boundary==="shallow"?u=>u.kind!=="structure":()=>!0;return this.$.finalize(this.transform(s,{shouldTransform:l,selected:a}))}}const Pe={applyBoundary:{self:e=>[e],child:e=>[...e.children],shallow:e=>[...e.shallowReferences],references:e=>[...e.references]},applyMethod:{filter:e=>e,assertFilter:(e,n,t)=>(e.length===0&&Ne(Vn(n,t)),e),find:e=>e[0],assertFind:(e,n,t)=>(e.length===0&&Ne(Vn(n,t)),e[0])},normalize:e=>typeof e=="function"?{boundary:"references",method:"filter",where:e}:typeof e=="string"?W(e,Pe.applyBoundary)?{method:"filter",boundary:e}:{boundary:"references",method:"filter",kind:e}:{boundary:"references",method:"filter",...e}},Vn=(e,n)=>`${e} had no references matching ${I(n)}.`,ya=e=>Ze(e,{stringifyNonKey:n=>n.expression}),ka=/"(\$ark\.[^"]+)"/g,xa=e=>JSON.stringify(e).replace(ka,"$1"),le=(e,n)=>({path:e,node:n,propString:ya(e)}),Ci=(e,n)=>e.propString===n.propString&&e.node.equals(n.node),Gn=(e,n)=>me(e,n,{isEqual:Ci}),$a=(e,n)=>me(e,n,{isEqual:(t,r)=>t.equals(r)});class y extends Array{static init(n,t,r,i){return new y({kind:n,l:t,r,path:(i==null?void 0:i.path)??[],optional:(i==null?void 0:i.optional)??!1})}add(n,t,r,i){return this.push({kind:n,l:t,r,path:(i==null?void 0:i.path)??[],optional:(i==null?void 0:i.optional)??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){const{path:n,l:t,r}=this[0],i=Ze(n);return Mi(`Intersection${i&&` at ${i}`} of ${Hn(t,r)}`)}return`The following intersections result in unsatisfiable types:
21
+ • ${this.map(({path:n,l:t,r})=>`${n}: ${Hn(t,r)}`).join(`
22
+ • `)}`}throw(){return f(this.describeReasons())}invert(){const n=this.map(t=>({...t,l:t.r,r:t.l}));return n instanceof y?n:new y(...n)}withPrefixKey(n,t){return this.map(r=>({...r,path:[n,...r.path],optional:r.optional||t==="optional"}))}toNeverIfDisjoint(){return g.intrinsic.never}}const Hn=(e,n)=>`${Yt(e)} and ${Yt(n)}`,Yt=e=>j(e)?e.expression:L(e)?e.map(Yt).join(" | ")||"never":String(e),Mi=e=>`${e} results in an unsatisfiable type`,xe={},re=(e,n,t)=>P(e,n,{$:t,invert:!1,pipe:!1}),Xt=(e,n,t)=>P(e,n,{$:t,invert:!1,pipe:!0}),P=((e,n,t)=>{const r=t.pipe?"|>":"&",i=`${e.hash}${r}${n.hash}`;if(xe[i]!==void 0)return xe[i];if(!t.pipe){const a=`${n.hash}${r}${e.hash}`;if(xe[a]!==void 0){const l=xe[a],u=l instanceof y?l.invert():l;return xe[i]=u,u}}const s=!t.pipe||!e.includesTransform&&!n.includesTransform;if(s&&e.equals(n))return e;let o=s?en(e,n,t):e.hasKindIn(...At)?wa(e,n,t):en(e,n,t);return j(o)&&(e.equals(o)?o=e:n.equals(o)&&(o=n)),xe[i]=o,o}),en=(e,n,t)=>{const r=e.precedence<n.precedence?e.kind:n.kind,i=e.impl.intersections[n.kind]??n.impl.intersections[e.kind];if(i===void 0)return null;if(r===e.kind)return i(e,n,t);{let s=i(n,e,{...t,invert:!t.invert});return s instanceof y&&(s=s.invert()),s}},wa=(e,n,t)=>e.includesTransform||n.includesTransform?t.invert?Zn(n,e,t):Zn(e,n,t):en(e,n,t),Zn=(e,n,t)=>e.distribute(r=>va(r,n,t),r=>{const i=r.filter(j);if(i.length===0)return y.init("union",e.branches,n.branches);if(i.length<e.branches.length||!e.branches.every((o,a)=>o.rawIn.equals(i[a].rawIn)))return t.$.parseSchema(i);if(i.length===1)return i[0];const s={branches:i};return t.$.parseSchema(s)}),va=(e,n,t)=>{if(e.hasKind("morph")){const i=[...e.morphs];if(e.lastMorphIfNode){const s=P(e.lastMorphIfNode,n,t);if(s instanceof y)return s;i[i.length-1]=s}else i.push(n);return t.$.node("morph",{morphs:i,in:e.inner.in})}if(n.hasKind("morph")){const i=P(e,n.rawIn,t);return i instanceof y?i:t.$.node("morph",{morphs:[n],in:i})}return t.$.node("morph",{morphs:[n],in:e})};class Me extends qi{constructor(t,r){super(t,r);c(this,"impliedSiblings");Object.defineProperty(this,te,{value:"constraint",enumerable:!1})}intersect(t){return re(this,t,this.$)}}class Nt extends Me{constructor(){super(...arguments);c(this,"traverseApply",(t,r)=>{this.traverseAllows(t,r)||r.errorFromNodeContext(this.errorContext)})}compile(t){t.traversalKind==="Allows"?t.return(this.compiledCondition):t.if(this.compiledNegation,()=>t.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return It(this.errorContext)}}const U=e=>(n,t)=>{if(L(n)){if(n.length===0)return;const i=n.map(s=>t.$.node(e,s));return e==="predicate"?i:i.sort((s,o)=>s.hash<o.hash?-1:1)}const r=t.$.node(e,n);return r.hasOpenIntersection()?[r]:r},pt=e=>{const n=e.r.shift();if(!n){let r=e.l.length===0&&e.kind==="structure"?g.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,Sa(e.l)),{prereduced:!0});for(const i of e.roots){if(r instanceof y)return r;r=P(i,r,e.ctx)}return r}let t=!1;for(let r=0;r<e.l.length;r++){const i=P(e.l[r],n,e.ctx);if(i!==null){if(i instanceof y)return i;if(i.isRoot())return e.roots.push(i),e.l.splice(r),pt(e);if(!t)e.l[r]=i,t=!0;else if(!e.l.includes(i))return B(`Unexpectedly encountered multiple distinct intersection results for refinement ${n}`)}}if(t||e.l.push(n),e.kind==="intersection"&&n.impliedSiblings)for(const r of n.impliedSiblings)me(e.r,r);return pt(e)},ft=e=>Object.entries(e).flatMap(([t,r])=>t in Ni?r:[]).sort((t,r)=>t.precedence<r.precedence?-1:t.precedence>r.precedence?1:t.kind==="predicate"&&r.kind==="predicate"?0:t.hash<r.hash?-1:1),Sa=e=>{const n={};for(const t of e)if(t.hasOpenIntersection())n[t.kind]=N(n[t.kind],t);else{if(n[t.kind])return B(`Unexpected intersection of closed refinements of kind ${t.kind}`);n[t.kind]=t}return n},Aa=(...e)=>f(Ia(...e)),Ia=(e,n,t)=>{const r=t.hasKind("morph")?"a morph":t.isUnknown()?"unknown":t.exclude(n).defaultShortDescription;return`${Bo(e)} operand must be ${n.description} (was ${r})`},Na=(e,n,t)=>new mt(e,n,t,t,null);class Di extends ue{}var Hr,Zr;class mt extends(Zr=ue,Hr=te,Zr){constructor(t,r,i,s,o){super((...a)=>{const l=R(this.names,(u,h)=>{const d=this.arg$.parse(a[u]);return d.extends(this.constraints[u])||f(Ra(h,this.constraints[u].expression,d.expression)),[h,d]});if(this.defIsLazy()){const u=this.bodyDef(l);return this.$.parse(u)}return this.$.parse(r,{args:l})});c(this,Hr,"generic");c(this,"paramDefs");c(this,"bodyDef");c(this,"$");c(this,"arg$");c(this,"baseInstantiation");c(this,"hkt");c(this,"description");this.paramDefs=t,this.bodyDef=r,this.$=i,this.arg$=s,this.hkt=o,this.description=o?new o().description??`a generic type for ${o.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof Di}cacheGetter(t,r){return Object.defineProperty(this,t,{value:r}),r}get json(){return this.cacheGetter("json",{params:this.params.map(t=>t[1].isUnknown()?t[0]:[t[0],t[1].json]),body:ta(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map(t=>typeof t=="string"?[t,g.intrinsic.unknown]:[t[0],this.$.parse(t[1])]))}get names(){return this.cacheGetter("names",this.params.map(t=>t[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map(t=>t[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}const Ra=(e,n,t)=>`${e} must be assignable to ${n} (was ${t})`,Oa=M({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:e=>typeof e=="function"?{predicate:e}:e,defaults:{description:e=>`valid according to ${e.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class qa extends Me{constructor(){super(...arguments);c(this,"serializedPredicate",F(this.predicate));c(this,"compiledCondition",`${this.serializedPredicate}(data, ctx)`);c(this,"compiledNegation",`!${this.compiledCondition}`);c(this,"impliedBasis",null);c(this,"expression",this.serializedPredicate);c(this,"traverseAllows",this.predicate);c(this,"errorContext",{code:"predicate",description:this.description,meta:this.meta});c(this,"compiledErrorContext",It(this.errorContext));c(this,"traverseApply",(t,r)=>{const i=r.currentErrorCount;!this.predicate(t,r.external)&&r.currentErrorCount===i&&r.errorFromNodeContext(this.errorContext)})}compile(t){if(t.traversalKind==="Allows"){t.return(this.compiledCondition);return}t.initializeErrorCount(),t.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>t.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(t,r){return r.fallback.predicate({code:"predicate",base:t,predicate:this.predicate})}}const Bi={implementation:Oa,Node:qa},Ca=M({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:e=>Number.isInteger(e)?e:f(Da(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,n,t)=>t.$.node("divisor",{rule:Math.abs(e.rule*n.rule/Ba(e.rule,n.rule))})},obviatesBasisDescription:!0});class Ma extends Nt{constructor(){super(...arguments);c(this,"traverseAllows",t=>t%this.rule===0);c(this,"compiledCondition",`data % ${this.rule} === 0`);c(this,"compiledNegation",`data % ${this.rule} !== 0`);c(this,"impliedBasis",g.intrinsic.number.internal);c(this,"expression",`% ${this.rule}`)}reduceJsonSchema(t){return t.type="integer",this.rule===1||(t.multipleOf=this.rule),t}}const Ki={implementation:Ca,Node:Ma},Da=e=>`divisor must be an integer (was ${e})`,Ba=(e,n)=>{let t,r=e,i=n;for(;i!==0;)t=i,i=r%i,r=t;return r};class De extends Nt{constructor(){super(...arguments);c(this,"boundOperandKind",Pa[this.kind]);c(this,"compiledActual",this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()");c(this,"comparator",Ta(this.kind,this.exclusive));c(this,"numericLimit",this.rule.valueOf());c(this,"expression",`${this.comparator} ${this.rule}`);c(this,"compiledCondition",`${this.compiledActual} ${this.comparator} ${this.numericLimit}`);c(this,"compiledNegation",`${this.compiledActual} ${Ka[this.comparator]} ${this.numericLimit}`);c(this,"stringLimit",this.boundOperandKind==="date"?La(this.numericLimit):`${this.numericLimit}`);c(this,"limitKind",this.comparator[0]==="<"?"upper":"lower")}isStricterThan(t){return(this.limitKind==="upper"?this.numericLimit<t.numericLimit:this.numericLimit>t.numericLimit)||this.numericLimit===t.numericLimit&&this.exclusive===!0&&!t.exclusive}overlapsRange(t){return!(this.isStricterThan(t)||this.numericLimit===t.numericLimit&&(this.exclusive||t.exclusive))}overlapIsUnit(t){return this.numericLimit===t.numericLimit&&!this.exclusive&&!t.exclusive}}const Ka={"<":">=","<=":">",">":"<=",">=":"<"},za={min:"max",minLength:"maxLength",after:"before"},zi={parse:e=>e||void 0},Ei=e=>n=>{if(typeof n=="number")return{rule:n};const{exclusive:t,...r}=n;return t?{...r,rule:e==="minLength"?r.rule+1:r.rule-1}:r},Pi=e=>n=>{if(typeof n=="number"||typeof n=="string"||n instanceof Date)return{rule:n};const{exclusive:t,...r}=n;if(!t)return r;const i=typeof r.rule=="number"?r.rule:typeof r.rule=="string"?new Date(r.rule).valueOf():r.rule.valueOf();return t?{...r,rule:e==="after"?i+1:i-1}:r},Ti=e=>typeof e=="string"||typeof e=="number"?new Date(e):e,Ea=(e,n)=>`${e} bound must be a positive integer (was ${n})`,$n=e=>n=>((!Number.isInteger(n)||n<0)&&f(Ea(e,n)),n),Pa={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},Ta=(e,n)=>`${W(e,za)?">":"<"}${n?"":"="}`,La=e=>typeof e=="string"?e:new Date(e).toLocaleString(),ja=e=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`,Fa=M({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Ti,serialize:e=>e.toISOString()}},normalize:Pi("after"),defaults:{description:e=>`${e.collapsibleLimitString} or later`,actual:He},intersections:{after:(e,n)=>e.isStricterThan(n)?e:n}});class Ua extends De{constructor(){super(...arguments);c(this,"impliedBasis",g.intrinsic.Date.internal);c(this,"collapsibleLimitString",He(this.rule));c(this,"traverseAllows",t=>t>=this.rule)}reduceJsonSchema(t,r){return r.fallback.date({code:"date",base:t,after:this.rule})}}const Li={implementation:Fa,Node:Ua},Ja=M({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Ti,serialize:e=>e.toISOString()}},normalize:Pi("before"),defaults:{description:e=>`${e.collapsibleLimitString} or earlier`,actual:He},intersections:{before:(e,n)=>e.isStricterThan(n)?e:n,after:(e,n,t)=>e.overlapsRange(n)?e.overlapIsUnit(n)?t.$.node("unit",{unit:e.rule}):null:y.init("range",e,n)}});class _a extends De{constructor(){super(...arguments);c(this,"collapsibleLimitString",He(this.rule));c(this,"traverseAllows",t=>t<=this.rule);c(this,"impliedBasis",g.intrinsic.Date.internal)}reduceJsonSchema(t,r){return r.fallback.date({code:"date",base:t,before:this.rule})}}const ji={implementation:Ja,Node:_a},Va=M({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:$n("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,n,t)=>y.init("unit",t.$.node("unit",{unit:e.rule}),t.$.node("unit",{unit:n.rule}),{path:["length"]}),minLength:(e,n)=>e.rule>=n.rule?e:y.init("range",e,n),maxLength:(e,n)=>e.rule<=n.rule?e:y.init("range",e,n)}});class Ga extends Nt{constructor(){super(...arguments);c(this,"traverseAllows",t=>t.length===this.rule);c(this,"compiledCondition",`data.length === ${this.rule}`);c(this,"compiledNegation",`data.length !== ${this.rule}`);c(this,"impliedBasis",g.intrinsic.lengthBoundable.internal);c(this,"expression",`== ${this.rule}`)}reduceJsonSchema(t){switch(t.type){case"string":return t.minLength=this.rule,t.maxLength=this.rule,t;case"array":return t.minItems=this.rule,t.maxItems=this.rule,t;default:return K.throwInternalOperandError("exactLength",t)}}}const Fi={implementation:Va,Node:Ga},Ha=M({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:zi},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,n)=>e.isStricterThan(n)?e:n,min:(e,n,t)=>e.overlapsRange(n)?e.overlapIsUnit(n)?t.$.node("unit",{unit:e.rule}):null:y.init("range",e,n)},obviatesBasisDescription:!0});class Za extends De{constructor(){super(...arguments);c(this,"impliedBasis",g.intrinsic.number.internal);c(this,"traverseAllows",this.exclusive?t=>t<this.rule:t=>t<=this.rule)}reduceJsonSchema(t){return this.exclusive?t.exclusiveMaximum=this.rule:t.maximum=this.rule,t}}const Ui={implementation:Ha,Node:Za},Wa=M({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:$n("maxLength")}},reduce:(e,n)=>e.rule===0?n.node("exactLength",e):void 0,normalize:Ei("maxLength"),defaults:{description:e=>`at most length ${e.rule}`,actual:e=>`${e.length}`},intersections:{maxLength:(e,n)=>e.isStricterThan(n)?e:n,minLength:(e,n,t)=>e.overlapsRange(n)?e.overlapIsUnit(n)?t.$.node("exactLength",{rule:e.rule}):null:y.init("range",e,n)}});class Qa extends De{constructor(){super(...arguments);c(this,"impliedBasis",g.intrinsic.lengthBoundable.internal);c(this,"traverseAllows",t=>t.length<=this.rule)}reduceJsonSchema(t){switch(t.type){case"string":return t.maxLength=this.rule,t;case"array":return t.maxItems=this.rule,t;default:return K.throwInternalOperandError("maxLength",t)}}}const Ji={implementation:Wa,Node:Qa},Ya=M({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:zi},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,n)=>e.isStricterThan(n)?e:n},obviatesBasisDescription:!0});class Xa extends De{constructor(){super(...arguments);c(this,"impliedBasis",g.intrinsic.number.internal);c(this,"traverseAllows",this.exclusive?t=>t>this.rule:t=>t>=this.rule)}reduceJsonSchema(t){return this.exclusive?t.exclusiveMinimum=this.rule:t.minimum=this.rule,t}}const _i={implementation:Ya,Node:Xa},el=M({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:$n("minLength")}},reduce:e=>e.rule===0?g.intrinsic.unknown:void 0,normalize:Ei("minLength"),defaults:{description:e=>e.rule===1?"non-empty":`at least length ${e.rule}`,actual:e=>e.length===0?"":`${e.length}`},intersections:{minLength:(e,n)=>e.isStricterThan(n)?e:n}});class tl extends De{constructor(){super(...arguments);c(this,"impliedBasis",g.intrinsic.lengthBoundable.internal);c(this,"traverseAllows",t=>t.length>=this.rule)}reduceJsonSchema(t){switch(t.type){case"string":return t.minLength=this.rule,t;case"array":return t.minItems=this.rule,t;default:return K.throwInternalOperandError("minLength",t)}}}const Vi={implementation:el,Node:tl},nl={min:_i.implementation,max:Ui.implementation,minLength:Vi.implementation,maxLength:Ji.implementation,exactLength:Fi.implementation,after:Li.implementation,before:ji.implementation},rl={min:_i.Node,max:Ui.Node,minLength:Vi.Node,maxLength:Ji.Node,exactLength:Fi.Node,after:Li.Node,before:ji.Node},il=M({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}});class sl extends Nt{constructor(){super(...arguments);c(this,"instance",new RegExp(this.rule,this.flags));c(this,"expression",`${this.instance}`);c(this,"traverseAllows",this.instance.test.bind(this.instance));c(this,"compiledCondition",`${this.expression}.test(data)`);c(this,"compiledNegation",`!${this.compiledCondition}`);c(this,"impliedBasis",g.intrinsic.string.internal)}reduceJsonSchema(t,r){return t.pattern?r.fallback.patternIntersection({code:"patternIntersection",base:t,pattern:this.rule}):(t.pattern=this.rule,t)}}const Gi={implementation:il,Node:sl},lt=(e,n)=>{const t=ol(e);return n&&!n.includes(t)?f(`Root of kind ${t} should be one of ${n}`):t},ol=e=>{if(k(e,"root"))return e.kind;if(typeof e=="string")return e[0]==="$"?"alias":e in ee?"domain":"proto";if(typeof e=="function")return"proto";if(typeof e!="object"||e===null)return f(Wn(e));if("morphs"in e)return"morph";if("branches"in e||L(e))return"union";if("unit"in e)return"unit";if("reference"in e)return"alias";const n=Object.keys(e);return n.length===0||n.some(t=>t in Ni)?"intersection":"proto"in e?"proto":"domain"in e?"domain":f(Wn(e))},Wn=e=>`${I(e)} is not a valid type schema`,tt={},al=e=>L(e)?e.map(n=>n.collapsibleJson):e.collapsibleJson,J={};g.nodesByRegisteredId=J;const Hi=e=>(tt[e]??(tt[e]=0),`${e}${++tt[e]}`),Zi=e=>{var u;const n=Rt[e.kind],t=((u=n.applyConfig)==null?void 0:u.call(n,e.def,e.$.resolvedConfig))??e.def,r={},{meta:i,...s}=t,o=i===void 0?{}:typeof i=="string"?{description:i}:i,a=ii(s).sort(([h],[d])=>at(h)?at(d)?dt(h)-dt(d):1:at(d)||h<d?-1:1).filter(([h,d])=>{if(h.startsWith("meta.")){const m=h.slice(5);return o[m]=d,!1}return!0});for(const h of a){const d=h[0],m=n.keys[d];if(!m)return f(`Key ${d} is not valid on ${e.kind} schema`);const b=m.parse?m.parse(h[1],e):h[1];b!==Z&&(b!==void 0||m.preserveUndefined)&&(r[d]=b)}if(n.reduce&&!e.prereduced){const h=n.reduce(r,e.$);if(h)return h instanceof y?h.throw():cl(h,o)}return wn({id:e.id,kind:e.kind,inner:r,meta:o,$:e.$})},wn=({id:e,kind:n,inner:t,meta:r,$:i,ignoreCache:s})=>{const o=Rt[n],a=ii(t),l=[];let u={};for(const[C,z]of a){const Y=o.keys[C],Dt=Y.serialize??(Y.child?al:ge);if(u[C]=Dt(z),Y.child===!0){const de=z;L(de)?l.push(...de):l.push(de)}else typeof Y.child=="function"&&l.push(...Y.child(z))}o.finalizeInnerJson&&(u=o.finalizeInnerJson(u));let h={...u},d={};Ve(r)||(d=R(r,(C,z)=>[C,C==="examples"?z:ge(z)]),h.meta=nt(d,"description",!0)),u=nt(u,o.collapsibleKey,!1);const m=JSON.stringify({kind:n,...u});h=nt(h,o.collapsibleKey,!1);const b=nt(h,o.collapsibleKey,!0),p=JSON.stringify({kind:n,...h});if(i.nodesByHash[p]&&!s)return i.nodesByHash[p];const S={id:e,kind:n,impl:o,inner:t,innerEntries:a,innerJson:u,innerHash:m,meta:r,metaJson:d,json:h,hash:p,collapsibleJson:b,children:l};if(n!=="intersection")for(const C in t)C!=="in"&&C!=="out"&&(S[C]=t[C]);const $=new fc[n](S,i);return i.nodesByHash[p]=$},ll=(e,n)=>e.id===n?e:(j(J[n])&&B(`Unexpected attempt to overwrite node id ${n}`),wn({id:n,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})),cl=(e,n,t)=>wn({id:Hi(n.alias??e.kind),kind:e.kind,inner:e.inner,meta:n,$:e.$}),nt=(e,n,t)=>{const r=Object.keys(e);if(r.length===1&&r[0]===n){const i=e[n];if(t||ye(i,"object")&&(Object.keys(i).length===1||Array.isArray(i)))return i}return e},tn=(e,n,t)=>{if(e.key!==n.key)return null;const r=e.key;let i=P(e.value,n.value,t);const s=e.required||n.required?"required":"optional";if(i instanceof y)if(s==="optional")i=g.intrinsic.never.internal;else return i.withPrefixKey(e.key,e.required&&n.required?"required":"optional");if(s==="required")return t.$.node("required",{key:r,value:i});const o=e.hasDefault()?n.hasDefault()?e.default===n.default?e.default:f(Qi(e.default,n.default)):e.default:n.hasDefault()?n.default:Z;return t.$.node("optional",{key:r,value:i,default:o})};class Wi extends Me{constructor(){super(...arguments);c(this,"required",this.kind==="required");c(this,"optional",this.kind==="optional");c(this,"impliedBasis",g.intrinsic.object.internal);c(this,"serializedKey",Ce(this.key));c(this,"compiledKey",typeof this.key=="string"?this.key:this.serializedKey);c(this,"flatRefs",N(this.value.flatRefs.map(t=>le([this.key,...t.path],t.node)),le([this.key],this.value)));c(this,"traverseAllows",(t,r)=>this.key in t?ne(this.key,()=>this.value.traverseAllows(t[this.key],r),r):this.optional);c(this,"traverseApply",(t,r)=>{this.key in t?ne(this.key,()=>this.value.traverseApply(t[this.key],r),r):this.hasKind("required")&&r.errorFromNodeContext(this.errorContext)})}_transform(t,r){r.path.push(this.key);const i=super._transform(t,r);return r.path.pop(),i}hasDefault(){return"default"in this.inner}compile(t){t.if(`${this.serializedKey} in data`,()=>t.traverseKey(this.serializedKey,`data${t.prop(this.key)}`,this.value)),this.hasKind("required")&&t.else(()=>t.traversalKind==="Apply"?t.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):t.return(!1)),t.traversalKind==="Allows"&&t.return(!0)}}const Qi=(e,n)=>`Invalid intersection of default values ${I(e)} & ${I(n)}`,ul=M({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,n)=>n.$.parseSchema(e)},default:{preserveUndefined:!0}},normalize:e=>e,reduce:(e,n)=>{if(n.resolvedConfig.exactOptionalPropertyTypes===!1&&!e.value.allows(void 0))return n.node("optional",{...e,value:e.value.or(x.undefined)},{prereduced:!0})},defaults:{description:e=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:tn}});class hl extends Wi{constructor(...t){super(...t);c(this,"expression",this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${I(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`);c(this,"defaultValueMorph",dl(this));c(this,"defaultValueMorphRef",this.defaultValueMorph&&F(this.defaultValueMorph));"default"in this.inner&&Sn(this.value,this.inner.default,this.key)}get rawIn(){const t=super.rawIn;return this.hasDefault()?this.$.node("optional",oi(t.inner,{default:!0}),{prereduced:!0}):t}get outProp(){if(!this.hasDefault())return this;const{default:t,...r}=this.inner;return this.cacheGetter("outProp",this.$.node("required",r,{prereduced:!0}))}}const vn={implementation:ul,Node:hl},zt={},dl=e=>{if(!e.hasDefault())return;const n=`{${e.compiledKey}: ${e.value.id} = ${ge(e.default)}}`;return zt[n]??(zt[n]=Yi(e.key,e.value,e.default))},Yi=(e,n,t)=>{if(typeof t=="function")return n.includesTransform?(i,s)=>(ne(e,()=>n(i[e]=t(),s),s),i):i=>(i[e]=t(),i);const r=n.includesTransform?n.assert(t):t;return ye(r,"object")?(i,s)=>(ne(e,()=>n(i[e]=t,s),s),i):i=>(i[e]=r,i)},Sn=(e,n,t)=>{const r=wt(n);ye(n,"object")&&!r&&f(pl(t));const i=e.in(r?n():n);if(i instanceof ce){t===null&&f(`Default ${i.summary}`);const s=i.transform(o=>o.transform(a=>({...a,prefixPath:[t]})));f(`Default for ${s.summary}`)}return n},pl=e=>`Non-primitive default ${e===null?"":typeof e=="number"?`for value at [${e}] `:`for ${Ce(e)} `}must be specified as a function like () => ({my: 'object'})`;class We extends qi{constructor(t,r){super(t,r);c(this,"branches",this.hasKind("union")?this.inner.branches:[this]);c(this,"_keyof");c(this,"pipe",Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)}));Object.defineProperty(this,te,{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:t=>{const r=this(t);return r instanceof ce?r:{value:r}},jsonSchema:{input:t=>this.rawIn.toJsonSchema({target:Qn(t.target),...t.libraryOptions}),output:t=>this.rawOut.toJsonSchema({target:Qn(t.target),...t.libraryOptions})}}}as(){return this}brand(t){return t===""?f(fl):this}readonly(){return this}distribute(t,r){const i=this.branches.map(t);return(r==null?void 0:r(i))??i}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(t={}){const r=Oi(this.$.resolvedConfig.toJsonSchema,t);r.useRefs||(r.useRefs=this.isCyclic);const i=typeof r.dialect=="string"?{$schema:r.dialect}:{};if(Object.assign(i,this.toJsonSchemaRecurse(r)),r.useRefs){const s=R(this.references,(o,a)=>a.isRoot()&&!a.alwaysExpandJsonSchema?[a.id,a.toResolvedJsonSchema(r)]:[]);r.target==="draft-07"?Object.assign(i,{definitions:s}):i.$defs=s}return i}toJsonSchemaRecurse(t){return t.useRefs&&!this.alwaysExpandJsonSchema?{$ref:`#/${t.target==="draft-07"?"definitions":"$defs"}/${this.id}`}:this.toResolvedJsonSchema(t)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(t){const r=this.innerToJsonSchema(t);return Object.assign(r,this.metaJson)}intersect(t){const r=this.$.parseDefinition(t),i=this.rawIntersect(r);return i instanceof y?i:this.$.finalize(i)}rawIntersect(t){return re(this,t,this.$)}toNeverIfDisjoint(){return this}and(t){const r=this.intersect(t);return r instanceof y?r.throw():r}rawAnd(t){const r=this.rawIntersect(t);return r instanceof y?r.throw():r}or(t){const r=this.$.parseDefinition(t);return this.$.finalize(this.rawOr(r))}rawOr(t){const r=[...this.branches,...t.branches];return this.$.node("union",r)}map(t){return this.$.schema(this.applyStructuralOperation("map",[t]))}pick(...t){return this.$.schema(this.applyStructuralOperation("pick",t))}omit(...t){return this.$.schema(this.applyStructuralOperation("omit",t))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}keyof(){if(this._keyof)return this._keyof;const t=this.applyStructuralOperation("keyof",[]).reduce((r,i)=>r.intersect(i).toNeverIfDisjoint(),g.intrinsic.unknown.internal);return t.branches.length===0&&f(Mi(`keyof ${this.expression}`)),this._keyof=this.$.finalize(t)}get props(){return this.branches.length!==1?f(gl(this.expression)):[...this.applyStructuralOperation("props",[])[0]]}merge(t){const r=this.$.parseDefinition(t);return this.$.schema(r.distribute(i=>this.applyStructuralOperation("merge",[Yn(i)??f(Xn("merge",i.expression))])))}applyStructuralOperation(t,r){return this.distribute(i=>{if(i.equals(g.intrinsic.object)&&t!=="merge")return i;const s=Yn(i);if(s||f(Xn(t,i.expression)),t==="keyof")return s.keyof();if(t==="get")return s.get(...r);if(t==="props")return s.props;const o=t==="required"?"require":t==="partial"?"optionalize":t;return this.$.node("intersection",{domain:"object",structure:s[o](...r)})})}get(...t){return t[0]===void 0?this:this.$.schema(this.applyStructuralOperation("get",t))}extract(t){const r=this.$.parseDefinition(t);return this.$.schema(this.branches.filter(i=>i.extends(r)))}exclude(t){const r=this.$.parseDefinition(t);return this.$.schema(this.branches.filter(i=>!i.extends(r)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(t){return!(this.intersect(t)instanceof y)}extends(t){if(this.isNever())return!0;const r=this.intersect(t);return!(r instanceof y)&&this.equals(r)}ifExtends(t){return this.extends(t)?this:void 0}subsumes(t){return this.$.parseDefinition(t).extends(this)}configure(t,r="shallow"){return this.configureReferences(t,r)}describe(t,r="shallow"){return this.configure({description:t},r)}optional(){return[this,"?"]}default(t){return Sn(this,t,null),[this,"=",t]}from(t){return this.assert(t)}_pipe(...t){const r=t.reduce((i,s)=>i.rawPipeOnce(s),this);return this.$.finalize(r)}tryPipe(...t){const r=t.reduce((i,s)=>i.rawPipeOnce(k(s,"root")?s:((o,a)=>{try{return s(o,a)}catch(l){return a.error({code:"predicate",predicate:s,actual:`aborted due to error:
23
+ ${l}
24
+ `})}})),this);return this.$.finalize(r)}to(t){return this.$.finalize(this.toNode(this.$.parseDefinition(t)))}toNode(t){const r=Xt(this,t,this.$);return r instanceof y?r.throw():r}rawPipeOnce(t){return k(t,"root")?this.toNode(t):this.distribute(r=>r.hasKind("morph")?this.$.node("morph",{in:r.inner.in,morphs:[...r.morphs,t]}):this.$.node("morph",{in:r,morphs:[t]}),this.$.parseSchema)}narrow(t){return this.constrainOut("predicate",t)}constrain(t,r){return this._constrain("root",t,r)}constrainIn(t,r){return this._constrain("in",t,r)}constrainOut(t,r){return this._constrain("out",t,r)}_constrain(t,r,i){const s=this.$.node(r,i);if(s.isRoot())return s.isUnknown()?this:B(`Unexpected constraint node ${s}`);const o=t==="root"?this:t==="in"?this.rawIn:this.rawOut;if(o.hasKind("morph")||s.impliedBasis&&!o.extends(s.impliedBasis))return Aa(r,s.impliedBasis,this);const a=this.$.node("intersection",{[s.kind]:s}),l=t==="out"?Xt(this,a,this.$):re(this,a,this.$);return l instanceof y&&l.throw(),this.$.finalize(l)}onUndeclaredKey(t){const r=typeof t=="string"?t:t.rule,i=typeof t=="string"?!1:t.deep;return this.$.finalize(this.transform((s,o)=>s==="structure"?r==="ignore"?oi(o,{undeclared:1}):{...o,undeclared:r}:o,i?void 0:{shouldTransform:s=>!X(St,s.kind)}))}hasEqualMorphs(t){return!this.includesTransform&&!t.includesTransform?!0:!(!Ie(this.shallowMorphs,t.shallowMorphs)||!Ie(this.flatMorphs,t.flatMorphs,{isEqual:(r,i)=>{var s,o;return r.propString===i.propString&&(r.node.hasKind("morph")&&i.node.hasKind("morph")?r.node.hasEqualMorphs(i.node):r.node.hasKind("intersection")&&i.node.hasKind("intersection")?((s=r.node.structure)==null?void 0:s.structuralMorphRef)===((o=i.node.structure)==null?void 0:o.structuralMorphRef):!1)}}))}onDeepUndeclaredKey(t){return this.onUndeclaredKey({rule:t,deep:!0})}filter(t){return this.constrainIn("predicate",t)}divisibleBy(t){return this.constrain("divisor",t)}matching(t){return this.constrain("pattern",t)}atLeast(t){return this.constrain("min",t)}atMost(t){return this.constrain("max",t)}moreThan(t){return this.constrain("min",$e(t))}lessThan(t){return this.constrain("max",$e(t))}atLeastLength(t){return this.constrain("minLength",t)}atMostLength(t){return this.constrain("maxLength",t)}moreThanLength(t){return this.constrain("minLength",$e(t))}lessThanLength(t){return this.constrain("maxLength",$e(t))}exactlyLength(t){return this.constrain("exactLength",t)}atOrAfter(t){return this.constrain("after",t)}atOrBefore(t){return this.constrain("before",t)}laterThan(t){return this.constrain("after",$e(t))}earlierThan(t){return this.constrain("before",$e(t))}}const fl="Expected a non-empty brand name after #",Xi=["draft-2020-12","draft-07"],ml=e=>`JSONSchema target '${e}' is not supported (must be ${Xi.map(n=>`"${n}"`).join(" or ")})`,Qn=e=>(X(Xi,e)||f(ml(e)),e),$e=e=>typeof e=="object"&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},rt=(e,n)=>k(n,"root")?k(e,"root")?e.extends(n):n.allows(e):k(e,"root")?e.hasUnit(n):n===e,Yn=e=>{var n;return e.hasKind("morph")?null:e.hasKind("intersection")?e.inner.structure??(((n=e.basis)==null?void 0:n.domain)==="object"?e.$.bindReference(g.intrinsic.emptyStructure):null):e.isBasis()&&e.domain==="object"?e.$.bindReference(g.intrinsic.emptyStructure):null},gl=e=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
25
+ ${e}`,Xn=(e,n)=>`${e} operand must be an object (was ${n})`,Qe=(e,n)=>R(xn(e),(t,r)=>[r,n]),bl=e=>typeof e=="string"?{reference:e}:e,er=e=>e instanceof y?g.intrinsic.never.internal:e,yl=M({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:e=>e.startsWith("$")?e:`$ark.${e}`},resolve:{}},normalize:bl,defaults:{description:e=>e.reference},intersections:{alias:(e,n,t)=>t.$.lazilyResolve(()=>er(P(e.resolution,n.resolution,t)),`${e.reference}${t.pipe?"=>":"&"}${n.reference}`),...Qe("alias",(e,n,t)=>n.isUnknown()?e:n.isNever()?n:n.isBasis()&&!n.overlaps(g.intrinsic.object)?y.init("assignability",g.intrinsic.object,n):t.$.lazilyResolve(()=>er(P(e.resolution,n,t)),`${e.reference}${t.pipe?"=>":"&"}${n.id}`))}});class kl extends We{constructor(){super(...arguments);c(this,"expression",this.reference);c(this,"structure");c(this,"traverseAllows",(t,r)=>{const i=r.seen[this.reference];return i!=null&&i.includes(t)?!0:(r.seen[this.reference]=N(i,t),this.resolution.traverseAllows(t,r))});c(this,"traverseApply",(t,r)=>{const i=r.seen[this.reference];i!=null&&i.includes(t)||(r.seen[this.reference]=N(i,t),this.resolution.traverseApply(t,r))})}get resolution(){const t=this._resolve();return J[this.id]=t}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));const t=this.reference;let r=J[t];const i=[];for(;k(r,"context");){if(i.includes(r.id))return f(xl(r.id,i));i.push(r.id),r=J[r.id]}return k(r,"root")?r:B(`Unexpected resolution for reference ${this.reference}
26
+ Seen: [${i.join("->")}]
27
+ Resolution: ${I(r)}`)}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;const t=this.reference.slice(1),r=this.$.resolutions[t];return typeof r=="string"?r:k(r,"root")?r.id:B(`Unexpected resolution for reference ${this.reference}: ${I(r)}`)}get defaultShortDescription(){return ee.object}innerToJsonSchema(t){return this.resolution.toJsonSchemaRecurse(t)}compile(t){const r=this.resolutionId;t.if(`ctx.seen.${r} && ctx.seen.${r}.includes(data)`,()=>t.return(!0)),t.if(`!ctx.seen.${r}`,()=>t.line(`ctx.seen.${r} = []`)),t.line(`ctx.seen.${r}.push(data)`),t.return(t.invoke(r))}}const xl=(e,n)=>`Alias '${e}' has a shallow resolution cycle: ${[...n,e].join("->")}`,An={implementation:yl,Node:kl};class In extends We{constructor(){super(...arguments);c(this,"traverseApply",(t,r)=>{this.traverseAllows(t,r)||r.errorFromNodeContext(this.errorContext)})}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return It(this.errorContext)}compile(t){t.traversalKind==="Allows"?t.return(this.compiledCondition):t.if(this.compiledNegation,()=>t.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}const $l=M({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:e=>typeof e=="string"?{domain:e}:fn(e,"numberAllowsNaN")&&e.domain!=="number"?f(Nn.writeBadAllowNanMessage(e.domain)):e,applyConfig:(e,n)=>e.numberAllowsNaN===void 0&&e.domain==="number"&&n.numberAllowsNaN?{...e,numberAllowsNaN:!0}:e,defaults:{description:e=>ee[e.domain],actual:e=>Number.isNaN(e)?"NaN":ee[G(e)]},intersections:{domain:(e,n)=>e.domain==="number"&&n.domain==="number"?e.numberAllowsNaN?n:e:y.init("domain",e,n)}});class wl extends In{constructor(){super(...arguments);c(this,"requiresNaNCheck",this.domain==="number"&&!this.numberAllowsNaN);c(this,"traverseAllows",this.requiresNaNCheck?t=>typeof t=="number"&&!Number.isNaN(t):t=>G(t)===this.domain);c(this,"compiledCondition",this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`);c(this,"compiledNegation",this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`);c(this,"expression",this.numberAllowsNaN?"number | NaN":this.domain)}get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return ee[this.domain]}innerToJsonSchema(t){return this.domain==="bigint"||this.domain==="symbol"?t.fallback.domain({code:"domain",base:{},domain:this.domain}):{type:this.domain}}}const Nn={implementation:$l,Node:wl,writeBadAllowNanMessage:e=>`numberAllowsNaN may only be specified with domain "number" (was ${e})`},vl=M({kind:"intersection",hasAssociatedError:!0,normalize:e=>{if(j(e))return e;const{structure:n,...t}=e,r=!!n,i=n??{},s=R(t,(o,a)=>W(o,ha)?(r&&f(`Flattened structure key ${o} cannot be specified alongside a root 'structure' key.`),i[o]=a,[]):[o,a]);return(k(i,"constraint")||!Ve(i))&&(s.structure=i),s},finalizeInnerJson:({structure:e,...n})=>ye(e,"object")?{...e,...n}:n,keys:{domain:{child:!0,parse:(e,n)=>n.$.node("domain",e)},proto:{child:!0,parse:(e,n)=>n.$.node("proto",e)},structure:{child:!0,parse:(e,n)=>n.$.node("structure",e),serialize:e=>{var o;if(!((o=e.sequence)!=null&&o.minLength))return e.collapsibleJson;const{sequence:n,...t}=e.collapsibleJson,{minVariadicLength:r,...i}=n,s=i.variadic&&Object.keys(i).length===1?i.variadic:i;return{...t,sequence:s}}},divisor:{child:!0,parse:U("divisor")},max:{child:!0,parse:U("max")},min:{child:!0,parse:U("min")},maxLength:{child:!0,parse:U("maxLength")},minLength:{child:!0,parse:U("minLength")},exactLength:{child:!0,parse:U("exactLength")},before:{child:!0,parse:U("before")},after:{child:!0,parse:U("after")},pattern:{child:!0,parse:U("pattern")},predicate:{child:!0,parse:U("predicate")}},reduce:(e,n)=>tr({},e,{$:n,invert:!1,pipe:!1}),defaults:{description:e=>{if(e.children.length===0)return"unknown";if(e.structure)return e.structure.description;const n=[];if(e.basis&&!e.prestructurals.some(t=>t.impl.obviatesBasisDescription)&&n.push(e.basis.description),e.prestructurals.length){const t=e.prestructurals.slice().sort((r,i)=>r.kind==="min"&&i.kind==="max"?-1:0).map(r=>r.description);n.push(...t)}return e.inner.predicate&&n.push(...e.inner.predicate.map(t=>t.description)),n.join(" and ")},expected:e=>` ◦ ${e.errors.map(n=>n.expected).join(`
28
+ ◦ `)}`,problem:e=>`(${e.actual}) must be...
29
+ ${e.expected}`},intersections:{intersection:(e,n,t)=>tr(e.inner,n.inner,t),...Qe("intersection",(e,n,t)=>{var l;if(e.children.length===0)return n;const{domain:r,proto:i,...s}=e.inner,o=i??r,a=o?P(o,n,t):n;return a instanceof y?a:(l=e==null?void 0:e.basis)!=null&&l.equals(a)?e:e.$.node("intersection",{...s,[a.kind]:a},{prereduced:!0})})}});class Sl extends We{constructor(){super(...arguments);c(this,"basis",this.inner.domain??this.inner.proto??null);c(this,"prestructurals",[]);c(this,"refinements",this.children.filter(t=>t.isRefinement()?(X(Ai,t.kind)&&this.prestructurals.push(t),!0):!1));c(this,"structure",this.inner.structure);c(this,"expression",Al(this));c(this,"traverseAllows",(t,r)=>this.children.every(i=>i.traverseAllows(t,r)));c(this,"traverseApply",(t,r)=>{const i=r.currentErrorCount;if(!(this.basis&&(this.basis.traverseApply(t,r),r.currentErrorCount>i))){if(this.prestructurals.length){for(let s=0;s<this.prestructurals.length-1;s++)if(this.prestructurals[s].traverseApply(t,r),r.failFast&&r.currentErrorCount>i)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(t,r),r.currentErrorCount>i)return}if(!(this.structure&&(this.structure.traverseApply(t,r),r.currentErrorCount>i))&&this.inner.predicate){for(let s=0;s<this.inner.predicate.length-1;s++)if(this.inner.predicate[s].traverseApply(t,r),r.failFast&&r.currentErrorCount>i)return;this.inner.predicate[this.inner.predicate.length-1].traverseApply(t,r)}}})}get shallowMorphs(){var t;return(t=this.inner.structure)!=null&&t.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){var t;return((t=this.basis)==null?void 0:t.defaultShortDescription)??"present"}innerToJsonSchema(t){return this.children.reduce((r,i)=>i.isBasis()?i.toJsonSchemaRecurse(t):i.reduceJsonSchema(r,t),{})}compile(t){if(t.traversalKind==="Allows"){for(const r of this.children)t.check(r);t.return(!0);return}if(t.initializeErrorCount(),this.basis&&(t.check(this.basis),this.children.length>1&&t.returnIfFail()),this.prestructurals.length){for(let r=0;r<this.prestructurals.length-1;r++)t.check(this.prestructurals[r]),t.returnIfFailFast();t.check(this.prestructurals[this.prestructurals.length-1]),(this.structure||this.inner.predicate)&&t.returnIfFail()}if(this.structure&&(t.check(this.structure),this.inner.predicate&&t.returnIfFail()),this.inner.predicate){for(let r=0;r<this.inner.predicate.length-1;r++)t.check(this.inner.predicate[r]),t.returnIfFail();t.check(this.inner.predicate[this.inner.predicate.length-1])}}}const es={implementation:vl,Node:Sl},Al=e=>{var i;if((i=e.structure)!=null&&i.expression)return e.structure.expression;const n=e.basis&&!e.prestructurals.some(s=>s.impl.obviatesBasisExpression)?e.basis.nestableExpression:"",t=e.prestructurals.map(s=>s.expression).join(" & "),r=`${n}${n?" ":""}${t}`;return r==="Array == 0"?"[]":r||"unknown"},tr=(e,n,t)=>{const r={},i=e.proto??e.domain,s=n.proto??n.domain,o=i?s?P(i,s,t):i:s;return o instanceof y?o:(o&&(r[o.kind]=o),pt({kind:"intersection",baseInner:r,l:ft(e),r:ft(n),roots:[],ctx:t}))},Il=M({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,n)=>n.$.parseSchema(e)},morphs:{parse:_e,serialize:e=>e.map(n=>k(n,"root")?n.json:F(n))},declaredIn:{child:!1,serialize:e=>e.json},declaredOut:{child:!1,serialize:e=>e.json}},normalize:e=>e,defaults:{description:e=>{var n;return`a morph from ${e.rawIn.description} to ${((n=e.rawOut)==null?void 0:n.description)??"unknown"}`}},intersections:{morph:(e,n,t)=>{if(!e.hasEqualMorphs(n))return f(Rl(e.expression,n.expression));const r=P(e.rawIn,n.rawIn,t);if(r instanceof y)return r;const i={morphs:e.morphs};if(e.declaredIn||n.declaredIn){const s=P(e.rawIn,n.rawIn,t);if(s instanceof y)return s.throw();i.declaredIn=s}if(e.declaredOut||n.declaredOut){const s=P(e.rawOut,n.rawOut,t);if(s instanceof y)return s.throw();i.declaredOut=s}return r.distribute(s=>t.$.node("morph",{...i,in:s}),t.$.parseSchema)},...Qe("morph",(e,n,t)=>{const r=e.inner.in?P(e.inner.in,n,t):n;return r instanceof y?r:r.equals(e.inner.in)?e:t.$.node("morph",{...e.inner,in:r})})}});class Nl extends We{constructor(){super(...arguments);c(this,"serializedMorphs",this.morphs.map(F));c(this,"compiledMorphs",`[${this.serializedMorphs}]`);c(this,"lastMorph",this.inner.morphs[this.inner.morphs.length-1]);c(this,"lastMorphIfNode",k(this.lastMorph,"root")?this.lastMorph:void 0);c(this,"introspectableIn",this.inner.in);c(this,"introspectableOut",this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.rawOut:void 0);c(this,"expression",`(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.rawOut.expression}>`);c(this,"traverseAllows",(t,r)=>!this.introspectableIn||this.introspectableIn.traverseAllows(t,r));c(this,"traverseApply",(t,r)=>{this.introspectableIn&&this.introspectableIn.traverseApply(t,r),r.queueMorphs(this.morphs)})}get shallowMorphs(){var t;return Array.isArray((t=this.inner.in)==null?void 0:t.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get rawIn(){var t;return this.declaredIn??((t=this.inner.in)==null?void 0:t.rawIn)??g.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??g.intrinsic.unknown.internal}declareIn(t){return this.$.node("morph",{...this.inner,declaredIn:t})}declareOut(t){return this.$.node("morph",{...this.inner,declaredOut:t})}get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(t){var r;return t.fallback.morph({code:"morph",base:this.rawIn.toJsonSchemaRecurse(t),out:((r=this.introspectableOut)==null?void 0:r.toJsonSchemaRecurse(t))??null})}compile(t){if(t.traversalKind==="Allows"){if(!this.introspectableIn)return;t.return(t.invoke(this.introspectableIn));return}this.introspectableIn&&t.line(t.invoke(this.introspectableIn)),t.line(`ctx.queueMorphs(${this.compiledMorphs})`)}hasEqualMorphs(t){return Ie(this.morphs,t.morphs,{isEqual:(r,i)=>r===i||k(r,"root")&&k(i,"root")&&r.equals(i)})}}const ts={implementation:Il,Node:Nl},Rl=(e,n)=>`The intersection of distinct morphs at a single path is indeterminate:
30
+ Left: ${e}
31
+ Right: ${n}`,Ol=M({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:e=>gn(e)??ge(e)},dateAllowsInvalid:{}},normalize:e=>{const n=typeof e=="string"?{proto:Re[e]}:typeof e=="function"?j(e)?e:{proto:e}:typeof e.proto=="string"?{...e,proto:Re[e.proto]}:e;return typeof n.proto!="function"&&f(gt.writeInvalidSchemaMessage(n.proto)),fn(n,"dateAllowsInvalid")&&n.proto!==Date&&f(gt.writeBadInvalidDateMessage(n.proto)),n},applyConfig:(e,n)=>e.dateAllowsInvalid===void 0&&e.proto===Date&&n.dateAllowsInvalid?{...e,dateAllowsInvalid:!0}:e,defaults:{description:e=>e.builtinName?Io[e.builtinName]:`an instance of ${e.proto.name}`,actual:e=>e instanceof Date&&e.toString()==="Invalid Date"?"an invalid Date":Vt(e)},intersections:{proto:(e,n)=>e.proto===Date&&n.proto===Date?e.dateAllowsInvalid?n:e:jn(e.proto,n.proto)?e:jn(n.proto,e.proto)?n:y.init("proto",e,n),domain:(e,n)=>n.domain==="object"?e:y.init("domain",g.intrinsic.object.internal,n)}});class ql extends In{constructor(){super(...arguments);c(this,"builtinName",gn(this.proto));c(this,"serializedConstructor",this.json.proto);c(this,"requiresInvalidDateCheck",this.proto===Date&&!this.dateAllowsInvalid);c(this,"traverseAllows",this.requiresInvalidDateCheck?t=>t instanceof Date&&t.toString()!=="Invalid Date":t=>t instanceof this.proto);c(this,"compiledCondition",`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`);c(this,"compiledNegation",`!(${this.compiledCondition})`);c(this,"expression",this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name);c(this,"domain","object")}innerToJsonSchema(t){var r,i;switch(this.builtinName){case"Array":return{type:"array"};case"Date":return((i=(r=t.fallback).date)==null?void 0:i.call(r,{code:"date",base:{}}))??t.fallback.proto({code:"proto",base:{},proto:this.proto});default:return t.fallback.proto({code:"proto",base:{},proto:this.proto})}}get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}get defaultShortDescription(){return this.description}}const gt={implementation:Ol,Node:ql,writeBadInvalidDateMessage:e=>`dateAllowsInvalid may only be specified with constructor Date (was ${e.name})`,writeInvalidSchemaMessage:e=>`instanceOf operand must be a function (was ${G(e)})`},Cl=M({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(e,n)=>{const t=[];for(const r of e){const i=k(r,"root")?r.branches:n.$.parseSchema(r).branches;for(const s of i)if(s.hasKind("morph")){const o=t.findIndex(a=>a.hasKind("morph")&&a.hasEqualMorphs(s));if(o===-1)t.push(s);else{const a=t[o];t[o]=n.$.node("morph",{...a.inner,in:a.rawIn.rawOr(s.rawIn)})}}else t.push(s)}return n.def.ordered||t.sort((r,i)=>r.hash<i.hash?-1:1),t}}},normalize:e=>L(e)?{branches:e}:e,reduce:(e,n)=>{const t=Fl(e);if(t.length===1)return t[0];if(t.length!==e.branches.length)return n.node("union",{...e,branches:t},{prereduced:!0})},defaults:{description:e=>e.distribute(n=>n.description,Se),expected:e=>{const n=uo(e.errors,"propString"),t=Object.entries(n).map(([r,i])=>{const s=[];for(const l of i)me(s,l.expected);const o=Se(s),a=i.every(l=>l.actual===i[0].actual)?i[0].actual:I(i[0].data);return`${r&&`${r} `}must be ${o}${a&&` (was ${a})`}`});return Se(t)},problem:e=>e.expected,message:e=>e.problem[0]==="["?`value at ${e.problem}`:e.problem},intersections:{union:(e,n,t)=>{if(e.isNever!==n.isNever)return y.init("presence",e,n);let r;return e.ordered?(n.ordered&&f(Jl(e.expression,n.expression)),r=Et(n.branches,e.branches,t),r instanceof y&&r.invert()):r=Et(e.branches,n.branches,t),r instanceof y?r:t.$.parseSchema(e.ordered||n.ordered?{branches:r,ordered:!0}:{branches:r})},...Qe("union",(e,n,t)=>{const r=Et(e.branches,[n],t);return r instanceof y?r:r.length===1?r[0]:t.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}});class Ml extends We{constructor(){super(...arguments);c(this,"isBoolean",this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0));c(this,"unitBranches",this.branches.filter(t=>t.rawIn.hasKind("unit")));c(this,"discriminant",this.discriminate());c(this,"discriminantJson",this.discriminant?Tl(this.discriminant):null);c(this,"expression",this.distribute(t=>t.nestableExpression,jl));c(this,"traverseAllows",(t,r)=>this.branches.some(i=>i.traverseAllows(t,r)));c(this,"traverseApply",(t,r)=>{const i=[];for(let s=0;s<this.branches.length;s++){if(r.pushBranch(),this.branches[s].traverseApply(t,r),!r.hasError())return this.branches[s].includesTransform?r.queuedMorphs.push(...r.popBranch().queuedMorphs):r.popBranch();i.push(r.popBranch().error)}r.errorFromNodeContext({code:"union",errors:i,meta:this.meta})});c(this,"traverseOptimistic",t=>{for(let r=0;r<this.branches.length;r++){const i=this.branches[r];if(i.traverseAllows(t))return i.contextFreeMorph?i.contextFreeMorph(t):t}return Z})}get branchGroups(){const t=[];let r=-1;for(const i of this.branches){if(i.hasKind("unit")&&i.domain==="boolean"){r===-1?(r=t.length,t.push(i)):t[r]=g.intrinsic.boolean;continue}t.push(i)}return t}createBranchedOptimisticRootApply(){return(t,r)=>{const i=this.traverseOptimistic(t);if(i!==Z)return i;const s=new we(t,this.$.resolvedConfig);return this.traverseApply(t,s),s.finalize(r)}}get shallowMorphs(){return this.branches.reduce((t,r)=>me(t,r.shallowMorphs),[])}get defaultShortDescription(){return this.distribute(t=>t.defaultShortDescription,Se)}innerToJsonSchema(t){if(this.branchGroups.length===1&&this.branchGroups[0].equals(g.intrinsic.boolean))return{type:"boolean"};const r=this.branchGroups.map(i=>i.toJsonSchemaRecurse(t));return r.every(i=>Object.keys(i).length===1&&fn(i,"const"))?{enum:r.map(i=>i.const)}:{anyOf:r}}compile(t){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(t);let r=this.discriminant.optionallyChainedPropString;this.discriminant.kind==="domain"&&(r=`typeof ${r} === "object" ? ${r} === null ? "null" : "object" : typeof ${r} === "function" ? "object" : typeof ${r}`);const i=this.discriminant.cases,s=Object.keys(i),{optimistic:o}=t;if(t.optimistic=!1,t.block(`switch(${r})`,()=>{for(const d in i){const m=i[d],b=d==="default"?d:`case ${d}`;let p;m===!0?p=o?"data":"true":o?m.rootApplyStrategy==="branchedOptimistic"?p=t.invoke(m,{kind:"Optimistic"}):m.contextFreeMorph?p=`${t.invoke(m)} ? ${F(m.contextFreeMorph)}(data) : "${Z}"`:p=`${t.invoke(m)} ? data : "${Z}"`:p=t.invoke(m),t.line(`${b}: return ${p}`)}return t}),t.traversalKind==="Allows"){t.return(o?`"${Z}"`:!1);return}const a=Se(this.discriminant.kind==="domain"?s.map(d=>{const m=d.slice(1,-1);return m==="function"?ee.object:ee[m]}):s),l=this.discriminant.path.map(d=>typeof d=="symbol"?F(d):JSON.stringify(d)),u=JSON.stringify(a),h=this.discriminant.kind==="domain"?`${El}[${r}]`:`${Pl}(${r})`;t.line(`ctx.errorFromNodeContext({
32
+ code: "predicate",
33
+ expected: ${u},
34
+ actual: ${h},
35
+ relativePath: [${l}],
36
+ meta: ${this.compiledMeta}
37
+ })`)}compileIndiscriminable(t){if(t.traversalKind==="Apply"){t.const("errors","[]");for(const r of this.branches)t.line("ctx.pushBranch()").line(t.invoke(r)).if("!ctx.hasError()",()=>t.return(r.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");t.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{const{optimistic:r}=t;t.optimistic=!1;for(const i of this.branches)t.if(`${t.invoke(i)}`,()=>t.return(r?i.contextFreeMorph?`${F(i.contextFreeMorph)}(data)`:"data":!0));t.return(r?`"${Z}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){var o,a;if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){const l=R(this.unitBranches,(u,h)=>[`${h.rawIn.serializedValue}`,h.hasKind("morph")?h:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:l}}const t=[];for(let l=0;l<this.branches.length-1;l++){const u=this.branches[l];for(let h=l+1;h<this.branches.length;h++){const d=this.branches[h],m=re(u.rawIn,d.rawIn,u.$);if(m instanceof y)for(const b of m){if(!b.kind||b.optional)continue;let p,S;if(b.kind==="domain"){const C=b.l,z=b.r;p=`"${typeof C=="string"?C:C.domain}"`,S=`"${typeof z=="string"?z:z.domain}"`}else if(b.kind==="unit")p=b.l.serializedValue,S=b.r.serializedValue;else continue;const $=t.find(C=>Ie(C.path,b.path)&&C.kind===b.kind);$?($.cases[p]?$.cases[p].branchIndices=me($.cases[p].branchIndices,l):(o=$.cases)[p]??(o[p]={branchIndices:[l],condition:b.l}),$.cases[S]?$.cases[S].branchIndices=me($.cases[S].branchIndices,h):(a=$.cases)[S]??(a[S]={branchIndices:[h],condition:b.r})):t.push({kind:b.kind,cases:{[p]:{branchIndices:[l],condition:b.l},[S]:{branchIndices:[h],condition:b.r}},path:b.path})}}}const r=this.ordered?Kl(t,this.branches):t;if(!r.length)return null;const i=Dl(r,this),s={};for(const l in i.best.cases){const u=Bl(i,l);if(u===null){s[l]=!0;continue}if(u.length===this.branches.length)return null;this.ordered&&u.sort((m,b)=>m.originalIndex-b.originalIndex);const h=u.map(m=>m.branch),d=h.length===1?h[0]:this.$.node("union",this.ordered?{branches:h,ordered:!0}:h);Object.assign(this.referencesById,d.referencesById),s[l]=d}if(i.defaultEntries.length){const l=i.defaultEntries.map(u=>u.branch);s.default=this.$.node("union",this.ordered?{branches:l,ordered:!0}:l,{prereduced:!0}),Object.assign(this.referencesById,s.default.referencesById)}return Object.assign(i.location,{cases:s})}}const Dl=(e,n)=>{const r=e.sort((o,a)=>o.path.length===a.path.length?Object.keys(a.cases).length-Object.keys(o.cases).length:o.path.length-a.path.length)[0],i={kind:r.kind,path:r.path,optionallyChainedPropString:ns(r.path)},s=n.branches.map((o,a)=>({originalIndex:a,branch:o}));return{best:r,location:i,defaultEntries:s,node:n}},Bl=(e,n)=>{const t=e.best.cases[n],r=zl(t.condition,e.location.path,e.node.$);let i=[];const s=[];for(let o=0;o<e.defaultEntries.length;o++){const a=e.defaultEntries[o];if(t.branchIndices.includes(a.originalIndex)){const l=nr(e.node.branches[a.originalIndex],e.location);l===null?i=null:i==null||i.push({originalIndex:a.originalIndex,branch:l})}else if(a.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")i==null||i.push(a);else{if(a.branch.rawIn.overlaps(r)){const l=nr(a.branch,e.location);i==null||i.push({originalIndex:a.originalIndex,branch:l})}s.push(a)}}return e.defaultEntries=s,i},Kl=(e,n)=>e.filter(r=>{const i=Object.values(r.cases).map(s=>s.branchIndices);for(let s=0;s<i.length-1;s++){const o=i[s];for(let a=s+1;a<i.length;a++){const l=i[a];for(const u of o)for(const h of l)if(u>h&&n[u].overlaps(n[h]))return!1}}return!0}),zl=(e,n,t)=>{let r=e==="undefined"?t.node("unit",{unit:void 0}):e==="null"?t.node("unit",{unit:null}):e==="boolean"?t.units([!0,!1]):e;for(let i=n.length-1;i>=0;i--){const s=n[i];r=t.node("intersection",typeof s=="number"?{proto:"Array",sequence:[...lo(s).map(o=>({})),r]}:{domain:"object",required:[{key:s,value:r}]})}return r},ns=e=>e.reduce((n,t)=>n+wi(t,!0),"data"),El=F(ho),Pl=F(I),rs={implementation:Cl,Node:Ml},Tl=e=>({kind:e.kind,path:e.path.map(n=>typeof n=="string"?n:Ce(n)),cases:R(e.cases,(n,t)=>[n,t===!0?t:t.hasKind("union")&&t.discriminantJson?t.discriminantJson:t.json])}),Ll={delimiter:" | ",finalDelimiter:" | "},jl=e=>Se(e,Ll),Se=(e,n)=>{const t=(n==null?void 0:n.delimiter)??", ",r=(n==null?void 0:n.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";const i={},s=e.filter(a=>i[a]?!1:i[a]=!0),o=s.pop();return`${s.join(t)}${s.length?r:""}${o}`},Et=(e,n,t)=>{const r=n.map(()=>[]);for(let s=0;s<e.length;s++){let o={};for(let a=0;a<n.length;a++){if(r[a]===null)continue;if(e[s].equals(n[a])){r[a]=null,o={};break}const l=P(e[s],n[a],t);if(!(l instanceof y)){if(l.equals(e[s])){r[a].push(e[s]),o={};break}l.equals(n[a])?r[a]=null:o[a]=l}}for(const a in o)r[a][s]=o[a]}const i=r.flatMap((s,o)=>(s==null?void 0:s.flatMap(a=>a.branches))??n[o]);return i.length===0?y.init("union",e,n):i},Fl=({branches:e,ordered:n})=>{if(e.length<2)return e;const t=e.map(()=>!0);for(let r=0;r<e.length;r++)for(let i=r+1;i<e.length&&t[r]&&t[i];i++){if(e[r].equals(e[i])){t[i]=!1;continue}const s=re(e[r].rawIn,e[i].rawIn,e[0].$);s instanceof y||(n||Ul(e[r],e[i]),s.equals(e[r].rawIn)?t[r]=!!n:s.equals(e[i].rawIn)&&(t[i]=!1))}return e.filter((r,i)=>t[i])},Ul=(e,n)=>{!e.includesTransform&&!n.includesTransform||(Ie(e.shallowMorphs,n.shallowMorphs)||f(rr(e.expression,n.expression)),Ie(e.flatMorphs,n.flatMorphs,{isEqual:(t,r)=>{var i,s;return t.propString===r.propString&&(t.node.hasKind("morph")&&r.node.hasKind("morph")?t.node.hasEqualMorphs(r.node):t.node.hasKind("intersection")&&r.node.hasKind("intersection")?((i=t.node.structure)==null?void 0:i.structuralMorphRef)===((s=r.node.structure)==null?void 0:s.structuralMorphRef):!1)}})||f(rr(e.expression,n.expression)))},nr=(e,n)=>e.transform((t,r)=>t==="domain"||t==="unit"?null:r,{shouldTransform:(t,r)=>{const i=ns(r.path);return n.optionallyChainedPropString.startsWith(i)?t.hasKind("domain")&&t.domain==="object"||(t.hasKind("domain")||n.kind==="unit")&&i===n.optionallyChainedPropString?!0:t.children.length!==0&&t.kind!=="index":!1}}),rr=(e,n)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
38
+ Left: ${e}
39
+ Right: ${n}`,Jl=(e,n)=>`The intersection of two ordered unions is indeterminate:
40
+ Left: ${e}
41
+ Right: ${n}`,_l=M({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:e=>e instanceof Date?e.toISOString():ge(e)}},normalize:e=>e,defaults:{description:e=>I(e.unit),problem:({expected:e,actual:n})=>`${e===n?`must be reference equal to ${e} (serialized to the same value)`:`must be ${e} (was ${n})`}`},intersections:{unit:(e,n)=>y.init("unit",e,n),...Qe("unit",(e,n)=>{if(n.allows(e.unit))return e;const t=n.hasKind("intersection")?n.basis:n;if(t){const r=t.hasKind("domain")?t:g.intrinsic.object;if(e.domain!==r.domain){const i=e.domain==="undefined"||e.domain==="null"||e.domain==="boolean"?e.domain:g.intrinsic[e.domain];return y.init("domain",i,r)}}return y.init("assignability",e,n.hasKind("intersection")?n.children.find(r=>!r.allows(e.unit)):n)})}});class Vl extends In{constructor(){super(...arguments);c(this,"compiledValue",this.json.unit);c(this,"serializedValue",typeof this.unit=="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`);c(this,"compiledCondition",ir(this.unit,this.serializedValue));c(this,"compiledNegation",ir(this.unit,this.serializedValue,"negated"));c(this,"expression",I(this.unit));c(this,"domain",G(this.unit));c(this,"traverseAllows",this.unit instanceof Date?t=>t instanceof Date&&t.toISOString()===this.compiledValue:Number.isNaN(this.unit)?t=>Number.isNaN(t):t=>t===this.unit)}get defaultShortDescription(){return this.domain==="object"?ee.object:this.description}innerToJsonSchema(t){return this.unit===null?{type:"null"}:g.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:t.fallback.unit({code:"unit",base:{},unit:this.unit})}}const is={implementation:_l,Node:Vl},ir=(e,n,t)=>{if(e instanceof Date){const r=`data instanceof Date && data.toISOString() === ${n}`;return t?`!(${r})`:r}return Number.isNaN(e)?`${t?"!":""}Number.isNaN(data)`:`data ${t?"!":"="}== ${n}`},Gl=M({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,n)=>{const t=n.$.parseSchema(e);if(!t.extends(g.intrinsic.key))return f(Wl(t.expression));const r=t.branches.filter(i=>i.hasKind("unit"));return r.length?f(Zl(r.map(i=>I(i.unit)))):t}},value:{child:!0,parse:(e,n)=>n.$.parseSchema(e)}},normalize:e=>e,defaults:{description:e=>`[${e.signature.expression}]: ${e.value.description}`},intersections:{index:(e,n,t)=>{if(e.signature.equals(n.signature)){const r=P(e.value,n.value,t),i=r instanceof y?g.intrinsic.never.internal:r;return t.$.node("index",{signature:e.signature,value:i})}return e.signature.extends(n.signature)&&e.value.subsumes(n.value)?n:n.signature.extends(e.signature)&&n.value.subsumes(e.value)?e:null}}});class Hl extends Me{constructor(){super(...arguments);c(this,"impliedBasis",g.intrinsic.object.internal);c(this,"expression",`[${this.signature.expression}]: ${this.value.expression}`);c(this,"flatRefs",N(this.value.flatRefs.map(t=>le([this.signature,...t.path],t.node)),le([this.signature],this.value)));c(this,"traverseAllows",(t,r)=>ct(t).every(i=>this.signature.traverseAllows(i[0],r)?ne(i[0],()=>this.value.traverseAllows(i[1],r),r):!0));c(this,"traverseApply",(t,r)=>{for(const i of ct(t))this.signature.traverseAllows(i[0],r)&&ne(i[0],()=>this.value.traverseApply(i[1],r),r)})}_transform(t,r){r.path.push(this.signature);const i=super._transform(t,r);return r.path.pop(),i}compile(){}}const ss={implementation:Gl,Node:Hl},Zl=e=>`Index keys ${e.join(", ")} should be specified as named props.`,Wl=e=>`Indexed key definition '${e}' must be a string or symbol`,Ql=M({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,n)=>n.$.parseSchema(e)}},normalize:e=>e,defaults:{description:e=>`${e.compiledKey}: ${e.value.description}`,expected:e=>e.missingValueDescription,actual:()=>"missing"},intersections:{required:tn,optional:tn}});class Yl extends Wi{constructor(){super(...arguments);c(this,"expression",`${this.compiledKey}: ${this.value.expression}`);c(this,"errorContext",Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta}));c(this,"compiledErrorContext",It(this.errorContext))}}const os={implementation:Ql,Node:Yl},Xl=M({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(e,n)=>{if(e.length!==0)return e.map(t=>n.$.parseSchema(t))}},optionals:{child:!0,parse:(e,n)=>{if(e.length!==0)return e.map(t=>n.$.parseSchema(t))}},defaultables:{child:e=>e.map(n=>n[0]),parse:(e,n)=>{if(e.length!==0)return e.map(t=>{const r=n.$.parseSchema(t[0]);return Sn(r,t[1],null),[r,t[1]]})},serialize:e=>e.map(n=>[n[0].collapsibleJson,ge(n[1])]),reduceIo:(e,n,t)=>{if(e==="in"){n.optionals=t.map(r=>r[0].rawIn);return}n.prefix=t.map(r=>r[0].rawOut)}},variadic:{child:!0,parse:(e,n)=>n.$.parseSchema(e,n)},minVariadicLength:{parse:e=>e===0?void 0:e},postfix:{child:!0,parse:(e,n)=>{if(e.length!==0)return e.map(t=>n.$.parseSchema(t))}}},normalize:e=>{var n,t,r;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((n=e.postfix)!=null&&n.length){if(!e.variadic)return f(rc);if((t=e.optionals)!=null&&t.length||(r=e.defaultables)!=null&&r.length)return f(ls)}return e.minVariadicLength&&!e.variadic?f("minVariadicLength may not be specified without a variadic element"):e}return{variadic:e}},reduce:(e,n)=>{var a,l,u,h,d,m,b;let t=e.minVariadicLength??0;const r=((a=e.prefix)==null?void 0:a.slice())??[],i=((l=e.defaultables)==null?void 0:l.slice())??[],s=((u=e.optionals)==null?void 0:u.slice())??[],o=((h=e.postfix)==null?void 0:h.slice())??[];if(e.variadic){for(;(d=s[s.length-1])!=null&&d.equals(e.variadic);)s.pop();if(s.length===0&&i.length===0)for(;(m=r[r.length-1])!=null&&m.equals(e.variadic);)r.pop(),t++;for(;(b=o[0])!=null&&b.equals(e.variadic);)o.shift(),t++}else s.length===0&&i.length===0&&r.push(...o.splice(0));if(t!==e.minVariadicLength||e.prefix&&e.prefix.length!==r.length)return n.node("sequence",{...e,prefix:r,defaultables:i,optionals:s,postfix:o,minVariadicLength:t},{prereduced:!0})},defaults:{description:e=>e.isVariadicOnly?`${e.variadic.nestableExpression}[]`:`[${e.tuple.map(t=>t.kind==="defaultables"?`${t.node.nestableExpression} = ${I(t.default)}`:t.kind==="optionals"?`${t.node.nestableExpression}?`:t.kind==="variadic"?`...${t.node.nestableExpression}[]`:t.node.expression).join(", ")}]`},intersections:{sequence:(e,n,t)=>{const r=Te({l:e.tuple,r:n.tuple,disjoint:new y,result:[],fixedVariants:[],ctx:t}),i=r.disjoint.length===0?[r,...r.fixedVariants]:r.fixedVariants;return i.length===0?r.disjoint:i.length===1?t.$.node("sequence",sr(i[0].result)):t.$.node("union",i.map(s=>({proto:Array,sequence:sr(s.result)})))}}});var Wr,Qr,Yr,Xr;class ec extends Me{constructor(){super(...arguments);c(this,"impliedBasis",g.intrinsic.Array.internal);c(this,"tuple",nc(this.inner));c(this,"prefixLength",((Wr=this.prefix)==null?void 0:Wr.length)??0);c(this,"defaultablesLength",((Qr=this.defaultables)==null?void 0:Qr.length)??0);c(this,"optionalsLength",((Yr=this.optionals)==null?void 0:Yr.length)??0);c(this,"postfixLength",((Xr=this.postfix)==null?void 0:Xr.length)??0);c(this,"defaultablesAndOptionals",[]);c(this,"prevariadic",this.tuple.filter(t=>t.kind==="defaultables"||t.kind==="optionals"?(this.defaultablesAndOptionals.push(t.node),!0):t.kind==="prefix"));c(this,"variadicOrPostfix",fe(this.variadic&&[this.variadic],this.postfix));c(this,"flatRefs",this.addFlatRefs());c(this,"isVariadicOnly",this.prevariadic.length+this.postfixLength===0);c(this,"minVariadicLength",this.inner.minVariadicLength??0);c(this,"minLength",this.prefixLength+this.minVariadicLength+this.postfixLength);c(this,"minLengthNode",this.minLength===0?null:this.$.node("minLength",this.minLength));c(this,"maxLength",this.variadic?null:this.tuple.length);c(this,"maxLengthNode",this.maxLength===null?null:this.$.node("maxLength",this.maxLength));c(this,"impliedSiblings",this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[]);c(this,"defaultValueMorphs",tc(this));c(this,"defaultValueMorphsReference",this.defaultValueMorphs.length?F(this.defaultValueMorphs):void 0);c(this,"traverseAllows",(t,r)=>{for(let i=0;i<t.length;i++)if(!this.elementAtIndex(t,i).node.traverseAllows(t[i],r))return!1;return!0});c(this,"traverseApply",(t,r)=>{let i=0;for(;i<t.length;i++)ne(i,()=>this.elementAtIndex(t,i).node.traverseApply(t[i],r),r)});c(this,"expression",this.description)}addFlatRefs(){return Gn(this.flatRefs,this.prevariadic.flatMap((t,r)=>N(t.node.flatRefs.map(i=>le([`${r}`,...i.path],i.node)),le([`${r}`],t.node)))),Gn(this.flatRefs,this.variadicOrPostfix.flatMap(t=>N(t.flatRefs.map(r=>le([g.intrinsic.nonNegativeIntegerString.internal,...r.path],r.node)),le([g.intrinsic.nonNegativeIntegerString.internal],t)))),this.flatRefs}elementAtIndex(t,r){if(r<this.prevariadic.length)return this.tuple[r];const i=t.length-this.postfixLength;return r>=i?{kind:"postfix",node:this.postfix[r-i]}:{kind:"variadic",node:this.variadic??B(`Unexpected attempt to access index ${r} on ${this}`)}}get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(t){if(this.prefix)for(const[r,i]of this.prefix.entries())t.traverseKey(`${r}`,`data[${r}]`,i);for(const[r,i]of this.defaultablesAndOptionals.entries()){const s=`${r+this.prefixLength}`;t.if(`${s} >= data.length`,()=>t.traversalKind==="Allows"?t.return(!0):t.return()),t.traverseKey(s,`data[${s}]`,i)}if(this.variadic&&(this.postfix&&t.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`),t.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>t.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix))for(const[r,i]of this.postfix.entries()){const s=`firstPostfixIndex + ${r}`;t.traverseKey(s,`data[${s}]`,i)}t.traversalKind==="Allows"&&t.return(!0)}_transform(t,r){r.path.push(g.intrinsic.nonNegativeIntegerString.internal);const i=super._transform(t,r);return r.path.pop(),i}reduceJsonSchema(t,r){const i=r.target==="draft-07";if(this.prevariadic.length){const s=this.prevariadic.map(o=>{const a=o.node.toJsonSchemaRecurse(r);if(o.kind==="defaultables"){const l=typeof o.default=="function"?o.default():o.default;a.default=g.intrinsic.jsonData.allows(l)?l:r.fallback.defaultValue({code:"defaultValue",base:a,value:l})}return a});i?t.items=s:t.prefixItems=s}if(this.minLength&&(t.minItems=this.minLength),this.variadic){const s=this.variadic.toJsonSchemaRecurse(r);if(i&&this.prevariadic.length?t.additionalItems=s:t.items=s,this.maxLength&&(t.maxItems=this.maxLength),this.postfix){const o=this.postfix.map(a=>a.toJsonSchemaRecurse(r));t=r.fallback.arrayPostfix({code:"arrayPostfix",base:t,elements:o})}}else i?t.additionalItems=!1:t.items=!1,delete t.maxItems;return t}}const Pt={},tc=e=>{if(!e.defaultables)return[];const n=[];let t="[";const r=e.prefixLength+e.defaultablesLength-1;for(let i=e.prefixLength;i<=r;i++){const[s,o]=e.defaultables[i-e.prefixLength];n.push(Yi(i,s,o)),t+=`${i}: ${s.id} = ${ge(o)}, `}return t+="]",Pt[t]??(Pt[t]=n)},as={implementation:Xl,Node:ec},nc=e=>{const n=[];if(e.prefix)for(const t of e.prefix)n.push({kind:"prefix",node:t});if(e.defaultables)for(const[t,r]of e.defaultables)n.push({kind:"defaultables",node:t,default:r});if(e.optionals)for(const t of e.optionals)n.push({kind:"optionals",node:t});if(e.variadic&&n.push({kind:"variadic",node:e.variadic}),e.postfix)for(const t of e.postfix)n.push({kind:"postfix",node:t});return n},sr=e=>e.reduce((n,t)=>(t.kind==="variadic"?n.variadic=t.node:t.kind==="defaultables"?n.defaultables=N(n.defaultables,[[t.node,t.default]]):n[t.kind]=N(n[t.kind],t.node),n),{}),ls="A postfix required element cannot follow an optional or defaultable element",rc="A postfix element requires a variadic element",Te=e=>{var d,m;const[n,...t]=e.l,[r,...i]=e.r;if(!n||!r)return e;const s=((d=t[t.length-1])==null?void 0:d.kind)==="postfix",o=((m=i[i.length-1])==null?void 0:m.kind)==="postfix",a=n.kind==="prefix"||r.kind==="prefix"?"prefix":n.kind==="postfix"||r.kind==="postfix"?"postfix":n.kind==="variadic"&&r.kind==="variadic"?"variadic":s||o?"prefix":n.kind==="defaultables"||r.kind==="defaultables"?"defaultables":"optionals";if(n.kind==="prefix"&&r.kind==="variadic"&&o){const b=Te({...e,fixedVariants:[],r:i.map(p=>({...p,kind:"prefix"}))});b.disjoint.length===0&&e.fixedVariants.push(b)}else if(r.kind==="prefix"&&n.kind==="variadic"&&s){const b=Te({...e,fixedVariants:[],l:t.map(p=>({...p,kind:"prefix"}))});b.disjoint.length===0&&e.fixedVariants.push(b)}const l=P(n.node,r.node,e.ctx);if(l instanceof y)if(a==="prefix"||a==="postfix")e.disjoint.push(...l.withPrefixKey(a==="prefix"?e.result.length:`-${t.length+1}`,or(n)&&or(r)?"required":"optional")),e.result=[...e.result,{kind:a,node:g.intrinsic.never.internal}];else return a==="optionals"||a==="defaultables"?e:Te({...e,fixedVariants:[],l:t.map(b=>({...b,kind:"prefix"})),r:t.map(b=>({...b,kind:"prefix"}))});else a==="defaultables"?(n.kind==="defaultables"&&r.kind==="defaultables"&&n.default!==r.default&&f(Qi(n.default,r.default)),e.result=[...e.result,{kind:a,node:l,default:n.kind==="defaultables"?n.default:r.kind==="defaultables"?r.default:B(`Unexpected defaultable intersection from ${n.kind} and ${r.kind} elements.`)}]):e.result=[...e.result,{kind:a,node:l}];const u=e.l.length,h=e.r.length;return(n.kind!=="variadic"||u>=h&&(r.kind==="variadic"||h===1))&&(e.l=t),(r.kind!=="variadic"||h>=u&&(n.kind==="variadic"||u===1))&&(e.r=i),Te(e)},or=e=>e.kind==="prefix"||e.kind==="postfix",cs=e=>n=>{var t,r;if(n.props.length||n.index){const i=((t=n.index)==null?void 0:t.map(o=>o[e]))??[];for(const o of n.props)i.push(o[e]);n.undeclared&&i.push(`+ (undeclared): ${n.undeclared}`);const s=`{ ${i.join(", ")} }`;return n.sequence?`${s} & ${n.sequence.description}`:s}return((r=n.sequence)==null?void 0:r.description)??"{}"},ic=cs("description"),sc=cs("expression"),ar=(e,n,t)=>{const r=e.required?"required":"optional";if(!n.signature.allows(e.key))return null;const i=re(e.value,n.value,t);return i instanceof y?r==="optional"?t.node("optional",{key:e.key,value:g.intrinsic.never.internal}):i.withPrefixKey(e.key,e.kind):null},oc=M({kind:"structure",hasAssociatedError:!1,normalize:e=>e,applyConfig:(e,n)=>!e.undeclared&&n.onUndeclaredKey!=="ignore"?{...e,undeclared:n.onUndeclaredKey}:e,keys:{required:{child:!0,parse:U("required"),reduceIo:(e,n,t)=>{n.required=N(n.required,t.map(r=>e==="in"?r.rawIn:r.rawOut))}},optional:{child:!0,parse:U("optional"),reduceIo:(e,n,t)=>{if(e==="in"){n.optional=t.map(r=>r.rawIn);return}for(const r of t)n[r.outProp.kind]=N(n[r.outProp.kind],r.outProp.rawOut)}},index:{child:!0,parse:U("index")},sequence:{child:!0,parse:U("sequence")},undeclared:{parse:e=>e==="ignore"?void 0:e,reduceIo:(e,n,t)=>{if(t==="reject"){n.undeclared="reject";return}e==="in"?delete n.undeclared:n.undeclared="reject"}}},defaults:{description:ic},intersections:{structure:(e,n,t)=>{const r={...e.inner},i={...n.inner},s=new y;if(e.undeclared){const l=e.keyof();for(const u of n.requiredKeys)l.allows(u)||s.add("presence",g.intrinsic.never.internal,n.propsByKey[u].value,{path:[u]});i.optional&&(i.optional=i.optional.filter(u=>l.allows(u.key))),i.index&&(i.index=i.index.flatMap(u=>{if(u.signature.extends(l))return u;const h=re(l,u.signature,t.$);if(h instanceof y)return[];const d=nn(h,u.value,t.$);return d.required&&(i.required=fe(i.required,d.required)),d.optional&&(i.optional=fe(i.optional,d.optional)),d.index??[]}))}if(n.undeclared){const l=n.keyof();for(const u of e.requiredKeys)l.allows(u)||s.add("presence",e.propsByKey[u].value,g.intrinsic.never.internal,{path:[u]});r.optional&&(r.optional=r.optional.filter(u=>l.allows(u.key))),r.index&&(r.index=r.index.flatMap(u=>{if(u.signature.extends(l))return u;const h=re(l,u.signature,t.$);if(h instanceof y)return[];const d=nn(h,u.value,t.$);return d.required&&(r.required=fe(r.required,d.required)),d.optional&&(r.optional=fe(r.optional,d.optional)),d.index??[]}))}const o={};(e.undeclared||n.undeclared)&&(o.undeclared=e.undeclared==="reject"||n.undeclared==="reject"?"reject":"delete");const a=pt({kind:"structure",baseInner:o,l:ft(r),r:ft(i),roots:[],ctx:t});return a instanceof y&&s.push(...a),s.length?s:a}},reduce:(e,n)=>{if(!e.required&&!e.optional)return;const t={};let r=!1;const i=e.optional?[...e.optional]:[];if(e.required)for(let s=0;s<e.required.length;s++){const o=e.required[s];if(o.key in t&&f(cr(o.key)),t[o.key]=!0,e.index)for(const a of e.index){const l=ar(o,a,n);if(l instanceof y)return l}}if(e.optional)for(let s=0;s<e.optional.length;s++){const o=e.optional[s];if(o.key in t&&f(cr(o.key)),t[o.key]=!0,e.index)for(const a of e.index){const l=ar(o,a,n);if(l instanceof y)return l;l!==null&&(i[s]=l,r=!0)}}if(r)return n.node("structure",{...e,optional:i},{prereduced:!0})}});var ei,ti;class ac extends Me{constructor(){super(...arguments);c(this,"impliedBasis",g.intrinsic.object.internal);c(this,"impliedSiblings",this.children.flatMap(t=>t.impliedSiblings??[]));c(this,"props",fe(this.required,this.optional));c(this,"propsByKey",R(this.props,(t,r)=>[r.key,r]));c(this,"propsByKeyReference",F(this.propsByKey));c(this,"expression",sc(this));c(this,"requiredKeys",((ei=this.required)==null?void 0:ei.map(t=>t.key))??[]);c(this,"optionalKeys",((ti=this.optional)==null?void 0:ti.map(t=>t.key))??[]);c(this,"literalKeys",[...this.requiredKeys,...this.optionalKeys]);c(this,"_keyof");c(this,"traverseAllows",(t,r)=>this._traverse("Allows",t,r));c(this,"traverseApply",(t,r)=>this._traverse("Apply",t,r));c(this,"_traverse",(t,r,i)=>{const s=(i==null?void 0:i.currentErrorCount)??0;for(let o=0;o<this.props.length;o++)if(t==="Allows"){if(!this.props[o].traverseAllows(r,i))return!1}else if(this.props[o].traverseApply(r,i),i.failFast&&i.currentErrorCount>s)return!1;if(this.sequence){if(t==="Allows"){if(!this.sequence.traverseAllows(r,i))return!1}else if(this.sequence.traverseApply(r,i),i.failFast&&i.currentErrorCount>s)return!1}if(this.index||this.undeclared==="reject"){const o=Object.keys(r);o.push(...Object.getOwnPropertySymbols(r));for(let a=0;a<o.length;a++){const l=o[a];if(this.index){for(const u of this.index)if(u.signature.traverseAllows(l,i)){if(t==="Allows"){if(!ne(l,()=>u.value.traverseAllows(r[l],i),i))return!1}else if(ne(l,()=>u.value.traverseApply(r[l],i),i),i.failFast&&i.currentErrorCount>s)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(l)&&(t==="Allows"||(i.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[l],meta:this.meta}),i.failFast)))return!1}}return this.structuralMorph&&i&&!i.hasError()&&i.queueMorphs([this.structuralMorph]),!0});c(this,"declaresKey",t=>{var r;return t in this.propsByKey||((r=this.index)==null?void 0:r.some(i=>i.signature.allows(t)))||this.sequence!==void 0&&g.intrinsic.nonNegativeIntegerString.allows(t)});c(this,"structuralMorphRef",this.structuralMorph&&F(this.structuralMorph))}keyof(){if(this._keyof)return this._keyof;let t=this.$.units(this.literalKeys).branches;if(this.index)for(const{signature:r}of this.index)t=t.concat(r.branches);return this._keyof=this.$.node("union",t)}map(t){return this.$.node("structure",this.props.flatMap(t).reduce((r,i)=>{const s=this.propsByKey[i.key];if(j(i))return i.kind!=="required"&&i.kind!=="optional"?f(`Map result must have kind "required" or "optional" (was ${i.kind})`):(r[i.kind]=N(r[i.kind],i),r);const o=i.kind??(s==null?void 0:s.kind)??"required",a=R(i,(l,u)=>l in vn.implementation.keys?[l,u]:[]);return r[o]=N(r[o],this.$.node(o,a)),r},{}))}assertHasKeys(t){const r=t.filter(i=>!rt(i,this.keyof()));if(r.length)return f(lr(this.expression,r))}get(t,...r){var l;let i,s=!1;const o=hc(t);if((typeof o=="string"||typeof o=="symbol")&&this.propsByKey[o]&&(i=this.propsByKey[o].value,s=this.propsByKey[o].required),this.index)for(const u of this.index)rt(o,u.signature)&&(i=(i==null?void 0:i.and(u.value))??u.value);if(this.sequence&&rt(o,g.intrinsic.nonNegativeIntegerString))if(k(o,"root"))this.sequence.variadic&&(i=(i==null?void 0:i.and(this.sequence.element))??this.sequence.element);else{const u=Number.parseInt(o);if(u<this.sequence.prevariadic.length){const h=this.sequence.prevariadic[u].node;i=(i==null?void 0:i.and(h))??h,s||(s=u<this.sequence.prefixLength)}else if(this.sequence.variadic){const h=this.$.node("union",this.sequence.variadicOrPostfix);i=(i==null?void 0:i.and(h))??h}}if(!i)return(l=this.sequence)!=null&&l.variadic&&k(o,"root")&&o.extends(g.intrinsic.number)?f(dc(o.expression,this.sequence.expression)):f(lr(this.expression,[o]));const a=i.get(...r);return s?a:a.or(g.intrinsic.undefined)}pick(...t){return this.assertHasKeys(t),this.$.node("structure",this.filterKeys("pick",t))}omit(...t){return this.assertHasKeys(t),this.$.node("structure",this.filterKeys("omit",t))}optionalize(){const{required:t,...r}=this.inner;return this.$.node("structure",{...r,optional:this.props.map(i=>i.hasKind("required")?this.$.node("optional",i.inner):i)})}require(){const{optional:t,...r}=this.inner;return this.$.node("structure",{...r,required:this.props.map(i=>i.hasKind("optional")?{key:i.key,value:i.value}:i)})}merge(t){const r=this.filterKeys("omit",[t.keyof()]);return t.required&&(r.required=N(r.required,t.required)),t.optional&&(r.optional=N(r.optional,t.optional)),t.index&&(r.index=N(r.index,t.index)),t.sequence&&(r.sequence=t.sequence),t.undeclared?r.undeclared=t.undeclared:delete r.undeclared,this.$.node("structure",r)}filterKeys(t,r){const i=Si(this.inner),s=o=>{const a=r.some(l=>rt(o,l));return t==="pick"?a:!a};return i.required&&(i.required=i.required.filter(o=>s(o.key))),i.optional&&(i.optional=i.optional.filter(o=>s(o.key))),i.index&&(i.index=i.index.filter(o=>s(o.signature))),i}get defaultable(){var t;return this.cacheGetter("defaultable",((t=this.optional)==null?void 0:t.filter(r=>r.hasDefault()))??[])}_compileDeclaresKey(t){const r=[];if(this.props.length&&r.push(`k in ${this.propsByKeyReference}`),this.index)for(const i of this.index)r.push(t.invoke(i.signature,{kind:"Allows",arg:"k"}));return this.sequence&&r.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)"),r.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",cc(this))}compile(t){t.traversalKind==="Apply"&&t.initializeErrorCount();for(const r of this.props)t.check(r),t.traversalKind==="Apply"&&t.returnIfFailFast();if(this.sequence&&(t.check(this.sequence),t.traversalKind==="Apply"&&t.returnIfFailFast()),(this.index||this.undeclared==="reject")&&(t.const("keys","Object.keys(data)"),t.line("keys.push(...Object.getOwnPropertySymbols(data))"),t.for("i < keys.length",()=>this.compileExhaustiveEntry(t))),t.traversalKind==="Allows")return t.return(!0);this.structuralMorphRef&&t.if("ctx && !ctx.hasError()",()=>(t.line("ctx.queueMorphs(["),uc(t,this),t.line("])")))}compileExhaustiveEntry(t){if(t.const("k","keys[i]"),this.index)for(const r of this.index)t.if(`${t.invoke(r.signature,{arg:"k",kind:"Allows"})}`,()=>t.traverseKey("k","data[k]",r.value));return this.undeclared==="reject"&&t.if(`!(${this._compileDeclaresKey(t)})`,()=>t.traversalKind==="Allows"?t.return(!1):t.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>t.return())),t}reduceJsonSchema(t,r){var i;switch(t.type){case"object":return this.reduceObjectJsonSchema(t,r);case"array":const s=((i=this.sequence)==null?void 0:i.reduceJsonSchema(t,r))??t;return this.props.length||this.index?r.fallback.arrayObject({code:"arrayObject",base:s,object:this.reduceObjectJsonSchema({type:"object"},r)}):s;default:return K.throwInternalOperandError("structure",t)}}reduceObjectJsonSchema(t,r){if(this.props.length){t.properties={};for(const i of this.props){const s=i.value.toJsonSchemaRecurse(r);if(typeof i.key=="symbol"){r.fallback.symbolKey({code:"symbolKey",base:t,key:i.key,value:s,optional:i.optional});continue}if(i.hasDefault()){const o=typeof i.default=="function"?i.default():i.default;s.default=g.intrinsic.jsonData.allows(o)?o:r.fallback.defaultValue({code:"defaultValue",base:s,value:o})}t.properties[i.key]=s}this.requiredKeys.length&&t.properties&&(t.required=this.requiredKeys.filter(i=>typeof i=="string"&&i in t.properties))}if(this.index)for(const i of this.index){const s=i.value.toJsonSchemaRecurse(r);if(i.signature.equals(g.intrinsic.string)){t.additionalProperties=s;continue}for(const o of i.signature.branches){if(!o.extends(g.intrinsic.string)){t=r.fallback.symbolKey({code:"symbolKey",base:t,key:null,value:s,optional:!1});continue}let a={type:"string"};if(o.hasKind("morph")&&(a=r.fallback.morph({code:"morph",base:o.rawIn.toJsonSchemaRecurse(r),out:o.rawOut.toJsonSchemaRecurse(r)})),!o.hasKind("intersection"))return B(`Unexpected index branch kind ${o.kind}.`);const{pattern:l}=o.inner;if(l){const u=Object.assign(a,{pattern:l[0].rule});for(let h=1;h<l.length;h++)a=r.fallback.patternIntersection({code:"patternIntersection",base:u,pattern:l[h].rule});t.patternProperties??(t.patternProperties={}),t.patternProperties[u.pattern]=s}}}return this.undeclared&&!t.additionalProperties&&(t.additionalProperties=!1),t}}const Tt={},lc=e=>{var t,r;let n="";for(let i=0;i<e.defaultable.length;i++)n+=e.defaultable[i].defaultValueMorphRef;if((t=e.sequence)!=null&&t.defaultValueMorphsReference&&(n+=(r=e.sequence)==null?void 0:r.defaultValueMorphsReference),e.undeclared==="delete"){if(n+="delete !(",e.required)for(const i of e.required)n+=i.compiledKey+" | ";if(e.optional)for(const i of e.optional)n+=i.compiledKey+" | ";if(e.index)for(const i of e.index)n+=i.signature.id+" | ";if(e.sequence)if(e.sequence.maxLength===null)n+=x.nonNegativeIntegerString.id;else for(let i=0;i<e.sequence.tuple.length;i++)n+=i+" | ";n+=")"}return n},cc=e=>{const n=lc(e);if(!n)return;if(Tt[n])return Tt[n];const t=(r,i)=>{var s;for(let o=0;o<e.defaultable.length;o++)e.defaultable[o].key in r||e.defaultable[o].defaultValueMorph(r,i);if((s=e.sequence)!=null&&s.defaultables)for(let o=r.length-e.sequence.prefixLength;o<e.sequence.defaultables.length;o++)e.sequence.defaultValueMorphs[o](r,i);if(e.undeclared==="delete")for(const o in r)e.declaresKey(o)||delete r[o];return r};return Tt[n]=t},uc=(e,n)=>{var i;const r=`(data${n.defaultable.some(s=>s.defaultValueMorph.length===2)||((i=n.sequence)==null?void 0:i.defaultValueMorphs.some(s=>s.length===2))?", ctx":""})`;return e.block(`${r} => `,s=>{var o;for(let a=0;a<n.defaultable.length;a++){const{serializedKey:l,defaultValueMorphRef:u}=n.defaultable[a];s.if(`!(${l} in data)`,h=>h.line(`${u}${r}`))}return(o=n.sequence)!=null&&o.defaultables&&s.for(`i < ${n.sequence.defaultables.length}`,a=>a.set("data[i]",5),`data.length - ${n.sequence.prefixLength}`),n.undeclared==="delete"&&s.forIn("data",a=>a.if(`!(${n._compileDeclaresKey(a)})`,l=>l.line("delete data[k]"))),s.return("data")})},us={implementation:oc,Node:ac},hc=e=>(k(e,"root")&&e.hasKind("unit")&&(e=e.unit),typeof e=="number"&&(e=`${e}`),e),dc=(e,n)=>`${e} is not allowed as an array index on ${n}. Use the 'nonNegativeIntegerString' keyword instead.`,nn=(e,n,t)=>{const[r,i]=ao(e.branches,o=>o.hasKind("unit"));if(!r.length)return{index:t.node("index",{signature:e,value:n})};const s={};for(const o of r){const a=t.node("required",{key:o.unit,value:n});s[a.kind]=N(s[a.kind],a)}return i.length&&(s.index=t.node("index",{signature:i,value:n})),s},pc=e=>k(e,"root")?e.expression:I(e),lr=(e,n)=>`Key${n.length===1?"":"s"} ${n.map(pc).join(", ")} ${n.length===1?"does":"do"} not exist on ${e}`,cr=e=>`Duplicate key ${Ce(e)}`,Rt={...nl,alias:An.implementation,domain:Nn.implementation,unit:is.implementation,proto:gt.implementation,union:rs.implementation,morph:ts.implementation,intersection:es.implementation,divisor:Ki.implementation,pattern:Gi.implementation,predicate:Bi.implementation,required:os.implementation,optional:vn.implementation,index:ss.implementation,sequence:as.implementation,structure:us.implementation};g.defaultConfig=xo(Object.assign(R(Rt,(e,n)=>[e,n.defaults]),{jitless:qo(),clone:No,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:K.defaultConfig}));g.resolvedConfig=Qt(g.defaultConfig,g.config);const fc={...rl,alias:An.Node,domain:Nn.Node,unit:is.Node,proto:gt.Node,union:rs.Node,morph:ts.Node,intersection:es.Node,divisor:Ki.Node,pattern:Gi.Node,predicate:Bi.Node,required:os.Node,optional:vn.Node,index:ss.Node,sequence:as.Node,structure:us.Node};class rn extends go{get[te](){return"module"}}const hs=(e,n)=>new rn(R(e,(t,r)=>[t,k(r,"module")?hs(r,n):n.bindReference(r)])),mc=e=>L(e)?e:"branches"in e&&L(e.branches)?e.branches:void 0,gc=(e,n)=>f(`Node of kind ${n} is not valid as a ${e} definition`),ur=e=>`#${e} duplicates public alias ${e}`,Lt={};g.ambient??(g.ambient={});let hr;const ds="function $",bc=e=>ps(e,fs(e)),ps=(e,n)=>{const t=n.write(ds,4),r=n.compile()();for(const i of e)i.precompilation||(i.traverseAllows=r[`${i.id}Allows`].bind(r),i.isRoot()&&!i.allowsRequiresContext&&(i.allows=i.traverseAllows),i.traverseApply=r[`${i.id}Apply`].bind(r),r[`${i.id}Optimistic`]&&(i.traverseOptimistic=r[`${i.id}Optimistic`].bind(r)),i.precompilation=t)},fs=e=>new $i().return(e.reduce((n,t)=>{const r=new Kt({kind:"Allows"}).indent();t.compile(r);const i=r.write(`${t.id}Allows`),s=new Kt({kind:"Apply"}).indent();t.compile(s);const o=s.write(`${t.id}Apply`),a=`${n}${i},
42
+ ${o},
43
+ `;if(!t.hasKind("union"))return a;const l=new Kt({kind:"Allows",optimistic:!0}).indent();t.compile(l);const u=l.write(`${t.id}Optimistic`);return`${a}${u},
44
+ `},`{
45
+ `)+"}");class ms{constructor(n,t){c(this,"config");c(this,"resolvedConfig");c(this,"name");c(this,"referencesById",{});c(this,"references",[]);c(this,"resolutions",{});c(this,"exportedNames",[]);c(this,"aliases",{});c(this,"resolved",!1);c(this,"nodesByHash",{});c(this,"intrinsic");c(this,"_json");c(this,"generic",(...n)=>{const t=this;return(r,i)=>new mt(n,i?new Di(r):r,t,t,i??null)});c(this,"units",(n,t)=>{const r=[];for(const s of n)r.includes(s)||r.push(s);const i=r.map(s=>this.node("unit",{unit:s},t));return this.node("union",i,{...t,prereduced:!0})});c(this,"lazyResolutions",[]);c(this,"schema",(n,t)=>this.finalize(this.parseSchema(n,t)));c(this,"parseSchema",(n,t)=>this.node(lt(n),n,t));c(this,"precompilation");c(this,"_exportedResolutions");c(this,"_exports");c(this,"node",(n,t,r={})=>{const i=this.preparseNode(n,t,r);if(j(i))return this.bindReference(i);const s=this.createParseContext(i),o=Zi(s),a=this.bindReference(o);return J[s.id]=a});c(this,"parse",(n,t={})=>this.finalize(this.parseDefinition(n,t)));this.config=Qt(g.config,t),this.resolvedConfig=Qt(g.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Lt).length}`,this.name in Lt&&f(`A Scope already named ${this.name} already exists`),Lt[this.name]=this;const r=Object.entries(n).map(i=>this.preparseOwnAliasEntry(...i));for(const[i,s]of r){let o=i;if(i[0]==="#"?(o=i.slice(1),o in this.aliases&&f(ur(o)),this.aliases[o]=s):(o in this.aliases&&f(ur(i)),this.aliases[o]=s,this.exportedNames.push(o)),!k(s,"module")&&!k(s,"generic")&&!wt(s)){const a=this.preparseOwnDefinitionFormat(s,{alias:o});this.resolutions[o]=k(a,"root")?this.bindReference(a):this.createParseContext(a).id}}hr??(hr=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0})),this.nodesByHash[hr.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=g.intrinsic?R(g.intrinsic,(i,s)=>i.startsWith("json")?[]:[i,this.bindReference(s)]):{}}get[te](){return"scope"}cacheGetter(n,t){return Object.defineProperty(this,n,{value:t}),t}get internal(){return this}get json(){return this._json||this.export(),this._json}defineSchema(n){return n}lazilyResolve(n,t){const r=this.node("alias",{reference:t??"synthetic",resolve:n},{prereduced:!0});return this.resolved||this.lazyResolutions.push(r),r}preparseNode(n,t,r){var a;let i=typeof n=="string"?n:lt(t,n);if(j(t)&&t.kind===i)return t;if(i==="alias"&&!(r!=null&&r.prereduced)){const{reference:l}=An.implementation.normalize(t,this);if(l.startsWith("$")){const u=this.resolveRoot(l.slice(1));t=u,i=u.kind}}else if(i==="union"&&ye(t,"object")){const l=mc(t);(l==null?void 0:l.length)===1&&(t=l[0],i=lt(t))}if(j(t)&&t.kind===i)return t;const s=Rt[i],o=((a=s.normalize)==null?void 0:a.call(s,t,this))??t;return j(o)?o.kind===i?o:gc(i,o.kind):{...r,$:this,kind:i,def:o,prefix:r.alias??i}}bindReference(n){let t;return j(n)?t=n.$===this?n:new n.constructor(n.attachments,this):t=n.$===this?n:new mt(n.params,n.bodyDef,n.$,this,n.hkt),this.resolved||Object.assign(this.referencesById,t.referencesById),t}resolveRoot(n){return this.maybeResolveRoot(n)??f(ks(n))}maybeResolveRoot(n){const t=this.maybeResolve(n);if(!k(t,"generic"))return t}maybeResolveSubalias(n){return sn(this.aliases,n)??sn(this.ambient,n)}get ambient(){return g.ambient}maybeResolve(n){var i;const t=this.resolutions[n];if(t){if(typeof t!="string")return this.bindReference(t);const s=J[t];if(k(s,"root"))return this.resolutions[n]=s;if(k(s,"context")){if(s.phase==="resolving")return this.node("alias",{reference:`$${n}`},{prereduced:!0});if(s.phase==="resolved")return B(`Unexpected resolved context for was uncached by its scope: ${I(s)}`);s.phase="resolving";const o=this.bindReference(this.parseOwnDefinitionFormat(s.def,s));return s.phase="resolved",J[o.id]=o,J[s.id]=o,this.resolutions[n]=o}return B(`Unexpected nodesById entry for ${t}: ${I(s)}`)}let r=this.aliases[n]??((i=this.ambient)==null?void 0:i[n]);return r?(r=this.normalizeRootScopeValue(r),k(r,"generic")?this.resolutions[n]=this.bindReference(r):k(r,"module")?(r.root||f(xs(n)),this.resolutions[n]=this.bindReference(r.root)):this.resolutions[n]=this.parse(r,{alias:n})):this.maybeResolveSubalias(n)}createParseContext(n){const t=n.id??Hi(n.prefix);return J[t]=Object.assign(n,{[te]:"context",$:this,id:t,phase:"unresolved"})}traversal(n){return new we(n,this.resolvedConfig)}import(...n){return new rn(R(this.export(...n),(t,r)=>[`#${t}`,r]))}export(...n){if(!this._exports){this._exports={};for(const r of this.exportedNames){const i=this.aliases[r];this._exports[r]=k(i,"module")?hs(i,this):dr(this.maybeResolve(r))}for(const r of this.lazyResolutions)r.resolution;if(this._exportedResolutions=ys(this,this._exports),this._json=bs(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){const r=fs(this.references);this.precompilation=r.write(ds,4),ps(this.references,r)}this.resolved=!0}const t=n.length?n:this.exportedNames;return new rn(R(t,(r,i)=>[i,this._exports[i]]))}resolve(n){return this.export()[n]}parseDefinition(n,t={}){if(k(n,"root"))return this.bindReference(n);const r=this.preparseOwnDefinitionFormat(n,t);if(k(r,"root"))return this.bindReference(r);const i=this.createParseContext(r);J[i.id]=i;let s=this.bindReference(this.parseOwnDefinitionFormat(n,i));return s.isCyclic&&(s=ll(s,i.id)),J[i.id]=s,s}finalize(n){return dr(n),!n.precompilation&&!this.resolvedConfig.jitless&&bc(n.references),n}}class gs extends ms{parseOwnDefinitionFormat(n,t){return Zi(t)}preparseOwnDefinitionFormat(n,t){return this.preparseNode(lt(n),n,t)}preparseOwnAliasEntry(n,t){return[n,t]}normalizeRootScopeValue(n){return n}}const dr=e=>{const n=e.references.filter(t=>t.hasKind("alias"));for(const t of n){Object.assign(t.referencesById,t.resolution.referencesById);for(const r of e.references)t.id in r.referencesById&&Object.assign(r.referencesById,t.referencesById)}return e},bs=e=>R(e,(n,t)=>[n,k(t,"root")||k(t,"generic")?t.json:k(t,"module")?bs(t):B(`Unexpected resolution ${I(t)}`)]),sn=(e,n)=>{const t=n.indexOf(".");if(t===-1)return;const r=n.slice(0,t),i=e[r];if(i===void 0)return;if(!k(i,"module"))return f(yc(r));const s=n.slice(t+1),o=i[s];if(o===void 0)return sn(i,s);if(k(o,"root")||k(o,"generic"))return o;if(k(o,"module"))return o.root??f(xs(n));B(`Unexpected resolution for alias '${n}': ${I(o)}`)},Rn=(e,n)=>new gs(e,n),Ye=new gs({}),ys=(e,n)=>{const t={};for(const r in n){const i=n[r];if(k(i,"module")){const s=ys(e,i),o=R(s,(a,l)=>[`${r}.${a}`,l]);Object.assign(t,o)}else k(i,"root")||k(i,"generic")?t[r]=i:B(`Unexpected scope resolution ${I(i)}`)}return t},ks=e=>`'${e}' is unresolvable`,yc=e=>`'${e}' must reference a module to be accessed using dot syntax`,xs=e=>`Reference to submodule '${e}' must specify an alias`;Ye.export();const O=Ye.schema,On=Ye.node;Ye.defineSchema;const ie=Ye.generic,$s="^(?:0|[1-9]\\d*)$",kc=new RegExp($s);F(kc);const ws=Rn({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();g.intrinsic={...ws};const vs=Rn({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:$s}},{prereducedAliases:!0}).export();Object.assign(g.intrinsic,vs);const xc=Rn({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),x={...ws,...vs,...xc,emptyStructure:On("structure",{},{prereduced:!0})};g.intrinsic={...x};const pr=((e,n)=>new RegExp(e,n));Object.assign(pr,{as:pr});const $c=e=>typeof e=="string"&&e[0]==="d"&&(e[1]==="'"||e[1]==='"')&&e[e.length-1]===e[1],fr=e=>e.toString()!=="Invalid Date",wc=e=>e.slice(2,-1),Ss=e=>`'${e}' could not be parsed by the Date constructor`,vc=(e,n)=>Sc(e,n),Sc=(e,n)=>{const t=new Date(e);if(fr(t))return t;const r=Ho(e);if(r!==void 0){const i=new Date(r);if(fr(i))return i}return n?f(n===!0?Ss(e):n):void 0},Ac=O({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),jt=(e,n)=>{const t=e.scanner.shiftUntilEscapable(Rc[Ns[n]]);if(e.scanner.lookahead==="")return e.error(qc(t,n));if(e.scanner.shift(),n in Is){let r;try{r=new RegExp(t)}catch(i){f(String(i))}e.root=e.ctx.$.node("intersection",{domain:"string",pattern:t},{prereduced:!0}),n==="x/"&&(e.root=e.ctx.$.node("morph",{in:e.root,morphs:i=>r.exec(i),declaredOut:Ac}))}else if(W(n,As))e.root=e.ctx.$.node("unit",{unit:t});else{const r=vc(t,Ss(t));e.root=e.ctx.$.node("unit",{meta:t,unit:r})}},As={"'":1,'"':1},Ic={"/":1,"'":1,'"':1},Nc={"d'":"'",'d"':'"',"'":"'",'"':'"'},Is={"/":"/","x/":"/"},Ns={...Nc,...Is},Rc={"'":e=>e.lookahead==="'",'"':e=>e.lookahead==='"',"/":e=>e.lookahead==="/"},Oc={'"':"double-quote","'":"single-quote","/":"forward slash"},qc=(e,n)=>`${n}${e} requires a closing ${Oc[Ns[n]]}`,Cc=e=>`Private type references should not include '#'. Use '${e}' instead.`,Rs="Optional definitions like 'string?' are only valid as properties in an object or tuple",Os="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple",Be={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...vt},Mc=(e,n)=>e===">"?n[0]==="="?n[1]==="=":n.trimStart()===""||W(n.trimStart()[0],Be):e==="="?n[0]!=="=":e===","||e==="?",Dc=(e,n,t)=>qs(e,n,t,[]),qs=(e,n,t,r)=>{const i=t.parseUntilFinalizer();return r.push(i.root),i.finalizer===">"?r.length!==n.params.length?t.error(Cs(e,n.names,r.map(s=>s.expression))):r:i.finalizer===","?qs(e,n,t,r):i.error(ki(">"))},Cs=(e,n,t)=>`${e}<${n.join(", ")}> requires exactly ${n.length} args (got ${t.length}${t.length===0?"":`: ${t.join(", ")}`})`,Ft=e=>{const n=e.scanner.shiftUntilLookahead(Be);n==="keyof"?e.addPrefix("keyof"):e.root=Kc(e,n)},Bc=(e,n,t)=>{if(t.scanner.shiftUntilNonWhitespace(),t.scanner.shift()!=="<")return t.error(Cs(e,n.names,[]));const i=Dc(e,n,t);return n(...i)},Kc=(e,n)=>zc(e,n)??Ec(e,n)??e.error(n===""?e.scanner.lookahead==="#"?Cc(e.shiftedBy(1).scanner.shiftUntilLookahead(Be)):Ms(e):ks(n)),zc=(e,n)=>{var r;if((r=e.ctx.args)!=null&&r[n]){const i=e.ctx.args[n];return typeof i!="string"?i:e.ctx.$.node("alias",{reference:i},{prereduced:!0})}const t=e.ctx.$.maybeResolve(n);if(k(t,"root"))return t;if(t!==void 0)return k(t,"generic")?Bc(n,t,e):f(`Unexpected resolution ${I(t)}`)},Ec=(e,n)=>{const t=Zo(n);if(t!==void 0)return e.ctx.$.node("unit",{unit:t});const r=Qo(n);if(r!==void 0)return e.ctx.$.node("unit",{unit:r})},Ms=e=>{const n=e.previousOperator();return n?Ds(n,e.scanner.unscanned):Pc(e.scanner.unscanned)},Ds=(e,n="")=>`Token '${e}' requires a right operand${n?` before '${n}'`:""}`,Pc=e=>`Expected an expression${e?` before '${e}'`:""}`,Bs=e=>e.scanner.lookahead===""?e.error(Ms(e)):e.scanner.lookahead==="("?e.shiftedBy(1).reduceGroupOpen():e.scanner.lookaheadIsIn(Ic)?jt(e,e.scanner.shift()):e.scanner.lookaheadIsIn(vt)?Bs(e.shiftedBy(1)):e.scanner.lookahead==="d"?e.scanner.nextLookahead in As?jt(e,`${e.scanner.shift()}${e.scanner.shift()}`):Ft(e):e.scanner.lookahead==="x"&&e.scanner.nextLookahead==="/"?e.shiftedBy(2)&&jt(e,"x/"):Ft(e),Tc={">":!0,">=":!0},Lc={"<":!0,"<=":!0},bt={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},jc=(e,n)=>`Left bounds are only valid when paired with right bounds (try ...${n}${e})`,Ks=e=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,Fc=(e,n,t,r)=>`An expression may have at most one left bound (parsed ${e}${bt[n]}, ${t}${bt[r]})`,Uc=(e,n)=>{const t=_c(e,n);if(e.root.hasKind("unit")){if(typeof e.root.unit=="number"){e.reduceLeftBound(e.root.unit,t),e.unsetRoot();return}if(e.root.unit instanceof Date){const r=`d'${e.root.description??e.root.unit.toISOString()}'`;e.unsetRoot(),e.reduceLeftBound(r,t);return}}return Gc(e,t)},Jc={"<":1,">":1,"=":1},_c=(e,n)=>e.scanner.lookaheadIs("=")?`${n}${e.scanner.shift()}`:n,mr=(e,n,t,r)=>t.extends(g.intrinsic.number)?typeof n!="number"?f(on(e,n,r)):e==="=="?["min","max"]:e[0]===">"?["min"]:["max"]:t.extends(g.intrinsic.lengthBoundable)?typeof n!="number"?f(on(e,n,r)):e==="=="?["exactLength"]:e[0]===">"?["minLength"]:["maxLength"]:t.extends(g.intrinsic.Date)?e==="=="?["after","before"]:e[0]===">"?["after"]:["before"]:f(ja(t.expression)),Vc=e=>({rule:$c(e.limit)?wc(e.limit):e.limit,exclusive:e.comparator.length===1}),Gc=(e,n)=>{const t=e.unsetRoot(),r=e.scanner.location;e.parseOperand();const i=e.unsetRoot(),s=e.scanner.sliceChars(r,e.scanner.location);if(e.root=t,!i.hasKind("unit")||typeof i.unit!="number"&&!(i.unit instanceof Date))return e.error(on(n,s,"right"));const o=i.unit,a=n.length===1,l=mr(n,typeof o=="number"?o:s,t,"right");for(const h of l)e.constrainRoot(h,n==="=="?{rule:o}:{rule:o,exclusive:a});if(!e.branches.leftBound)return;if(!W(n,Lc))return e.error(Ks(n));const u=mr(e.branches.leftBound.comparator,e.branches.leftBound.limit,t,"left");e.constrainRoot(u[0],Vc(e.branches.leftBound)),e.branches.leftBound=null},on=(e,n,t)=>`Comparator ${t==="left"?bt[e]:e} must be ${t==="left"?"preceded":"followed"} by a corresponding literal (was ${n})`,Hc=e=>{e.scanner.shiftUntilNonWhitespace();const n=e.scanner.shiftUntilLookahead(Be);e.root=e.root.brand(n)},Zc=e=>{e.scanner.shiftUntilNonWhitespace();const n=e.scanner.shiftUntilLookahead(Be),t=Wo(n,{errorOnFail:gr(n)});t===0&&e.error(gr(0)),e.root=e.root.constrain("divisor",t)},gr=e=>`% operator must be followed by a non-zero integer literal (was ${e})`,zs=e=>{const n=e.scanner.shift();return n===""?e.finalize(""):n==="["?e.scanner.shift()==="]"?e.setRoot(e.root.array()):e.error(Wc):n==="|"?e.scanner.lookahead===">"?e.shiftedBy(1).pushRootToBranch("|>"):e.pushRootToBranch(n):n==="&"?e.pushRootToBranch(n):n===")"?e.finalizeGroup():Mc(n,e.scanner.unscanned)?e.finalize(n):W(n,Jc)?Uc(e,n):n==="%"?Zc(e):n==="#"?Hc(e):n in vt?zs(e):e.error(qn(n))},qn=(e,n="")=>`'${e}' is not allowed here${n&&` (should be ${n})`}`,Wc="Missing expected ']'",Qc=e=>{const n=e.unsetRoot();e.parseOperand();const t=e.unsetRoot();if(!t.hasKind("unit"))return e.error(Yc(t.expression));const r=t.unit instanceof Date?()=>new Date(t.unit):t.unit;return[n,"=",r]},Yc=e=>`Default value '${e}' must be a literal value`,br=(e,n)=>{const t=n.$.maybeResolveRoot(e);if(t)return t;if(e.endsWith("[]")){const s=n.$.maybeResolveRoot(e.slice(0,-2));if(s)return s.array()}const r=new Ot(new yi(e),n),i=Xc(r);return r.finalizer===">"&&f(qn(">")),i},Xc=e=>{e.parseOperand();let n=Cn(e).root;return n?(e.finalizer==="="?n=Qc(e):e.finalizer==="?"&&(n=[n,"?"]),e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead&&f(qn(e.scanner.lookahead)),n):B(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`)},Cn=e=>{for(;e.finalizer===void 0;)eu(e);return e},eu=e=>e.hasRoot()?e.parseOperator():e.parseOperand();class Ot{constructor(n,t){c(this,"root");c(this,"branches",{prefixes:[],leftBound:null,intersection:null,union:null,pipe:null});c(this,"finalizer");c(this,"groups",[]);c(this,"scanner");c(this,"ctx");this.scanner=n,this.ctx=t}error(n){return f(n)}hasRoot(){return this.root!==void 0}setRoot(n){this.root=n}unsetRoot(){const n=this.root;return this.root=void 0,n}constrainRoot(...n){this.root=this.root.constrain(n[0],n[1])}finalize(n){if(this.groups.length)return this.error(ki(")"));this.finalizeBranches(),this.finalizer=n}reduceLeftBound(n,t){const r=bt[t];if(!W(r,Tc))return this.error(Ks(t));if(this.branches.leftBound)return this.error(Fc(this.branches.leftBound.limit,this.branches.leftBound.comparator,n,r));this.branches.leftBound={comparator:r,limit:n}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();const n=this.groups.pop();if(!n)return this.error(sa(")",this.scanner.unscanned));this.branches=n}addPrefix(n){this.branches.prefixes.push(n)}applyPrefixes(){for(;this.branches.prefixes.length;){const n=this.branches.prefixes.pop();this.root=n==="keyof"?this.root.keyof():B(`Unexpected prefix '${n}'`)}}pushRootToBranch(n){var r,i,s;this.assertRangeUnset(),this.applyPrefixes();const t=this.root;this.root=void 0,this.branches.intersection=((r=this.branches.intersection)==null?void 0:r.rawAnd(t))??t,n!=="&"&&(this.branches.union=((i=this.branches.union)==null?void 0:i.rawOr(this.branches.intersection))??this.branches.intersection,this.branches.intersection=null,n!=="|"&&(this.branches.pipe=((s=this.branches.pipe)==null?void 0:s.rawPipeOnce(this.branches.union))??this.branches.union,this.branches.union=null))}parseUntilFinalizer(){return Cn(new Ot(this.scanner,this.ctx))}parseOperator(){return zs(this)}parseOperand(){return Bs(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(jc(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(){var n;return((n=this.branches.leftBound)==null?void 0:n.comparator)??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedBy(n){return this.scanner.jumpForward(n),this}}const tu="An empty string is not a valid generic parameter name",an=(e,n,t)=>{e.shiftUntilNonWhitespace();const r=e.shiftUntilLookahead(Be);return r===""?e.lookahead===""&&n.length?n:f(tu):(e.shiftUntilNonWhitespace(),nu(e,r,n,t))},yr="extends ",nu=(e,n,t,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(yr))e.jumpForward(yr.length);else return e.lookahead===","&&e.shift(),t.push(n),an(e,t,r);const i=Cn(new Ot(e,r));return t.push([n,i.root]),an(e,t,r)};class ru extends ue{constructor(n){const t={$:n,raw:n.fn};super((...r)=>{const i=r.indexOf(":"),s=i===-1?r.length-1:i-1,o=r.slice(0,s+1),a=n.parse(o).assertHasKind("intersection");let l=n.intrinsic.unknown;if(i!==-1){if(i!==r.length-2)return f(su);l=n.parse(r[i+1])}return u=>new iu(u,a,l)},{attach:t})}}class iu extends ue{constructor(t,r,i){const s=`typed ${t.name}`,o={[s]:(...l)=>{const u=r.assert(l),h=t(...u);return i.assert(h)}}[s];super(o);c(this,"raw");c(this,"params");c(this,"returns");c(this,"expression");this.raw=t,this.params=r,this.returns=i;let a=r.expression;a[0]==="["&&a[a.length-1]==="]"?a=a.slice(1,-1):a.endsWith("[]")&&(a=`...${a}`),this.expression=`(${a}) => ${(i==null?void 0:i.expression)??"unknown"}`}}const su=`":" must be followed by exactly one return type e.g:
46
+ fn("string", ":", "number")(s => s.length)`;class ou extends ue{constructor(t){super((...r)=>new it(t)(...r),{bind:t});c(this,"$");this.$=t}in(t){return new it(this.$,t===void 0?void 0:this.$.parse(t))}at(t,r){return new it(this.$).at(t,r)}case(t,r){return new it(this.$).case(t,r)}}class it extends ue{constructor(t,r){super(i=>this.caseEntries(Object.entries(i).map(([s,o])=>s==="default"?[s,o]:[this.$.parse(s),o])));c(this,"$");c(this,"in");c(this,"key");c(this,"branches",[]);this.$=t,this.in=r}at(t,r){return this.key&&f(lu),this.branches.length&&f(au),this.key=t,r?this.match(r):this}case(t,r){return this.caseEntry(this.$.parse(t),r)}caseEntry(t,r){const s=(this.key?this.$.parse({[this.key]:t}):t).pipe(r);return this.branches.push(s),this}match(t){return this(t)}strings(t){return this.caseEntries(Object.entries(t).map(([r,i])=>r==="default"?[r,i]:[this.$.node("unit",{unit:r}),i]))}caseEntries(t){for(let r=0;r<t.length;r++){const[i,s]=t[r];if(i==="default")return r!==t.length-1&&f("default may only be specified as the last key of a switch definition"),this.default(s);if(typeof s!="function")return f(`Value for case "${i}" must be a function (was ${G(s)})`);this.caseEntry(i,s)}return this}default(t){typeof t=="function"&&this.case(x.unknown,t);const r={branches:this.branches,ordered:!0};(t==="never"||t==="assert")&&(r.meta={onFail:kr});const i=this.$.node("union",r);if(!this.in)return this.$.finalize(i);let s=this.in.pipe(i);return(t==="never"||t==="assert")&&(s=s.configureReferences({onFail:kr},"self")),this.$.finalize(s)}}const kr=e=>e.throw(),au="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",lu="At most one key matcher may be specified per expression",Es=(e,n)=>{if(L(e)){if(e[1]==="=")return[n.$.parseOwnDefinitionFormat(e[0],n),"=",e[2]];if(e[1]==="?")return[n.$.parseOwnDefinitionFormat(e[0],n),"?"]}return Js(e,n)},cu="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",uu="Only required keys may specify default values, e.g. { value: 'number = 0' }",hu=(e,n)=>{var o;let t;const r={},i=ct(e);for(const[a,l]of i){const u=fu(a);if(u.kind==="spread"){if(!Ve(r))return f(pu);const p=n.$.parseOwnDefinitionFormat(l,n);if(p.equals(x.object))continue;if(!p.hasKind("intersection")||!((o=p.basis)!=null&&o.equals(x.object)))return f(mu(p.expression));t=p.structure;continue}if(u.kind==="undeclared"){l!=="reject"&&l!=="delete"&&l!=="ignore"&&f(du(l)),r.undeclared=l;continue}const h=Es(l,n),d=u;if(u.kind==="required"){L(h)?Ut(r,"optional",h[1]==="="?{key:u.normalized,value:h[0],default:h[2]}:{key:u.normalized,value:h[0]},n):Ut(r,"required",{key:u.normalized,value:h},n);continue}if(L(h)&&(h[1]==="?"&&f(cu),h[1]==="="&&f(uu)),u.kind==="optional"){Ut(r,"optional",{key:u.normalized,value:h},n);continue}const m=n.$.parseOwnDefinitionFormat(d.normalized,n),b=nn(m,h,n.$);b.index&&(r.index=N(r.index,b.index)),b.required&&(r.required=N(r.required,b.required))}const s=n.$.node("structure",r);return n.$.parseSchema({domain:"object",structure:(t==null?void 0:t.merge(s))??s})},Ut=(e,n,t,r)=>{e[n]=N(e[n],r.$.node(n,t))},du=e=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${I(e)})`,pu="Spread operator may only be used as the first key in an object",fu=e=>typeof e=="symbol"?{kind:"required",normalized:e}:e[e.length-1]==="?"?e[e.length-2]===je?{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]===je&&e[1]==="["&&e[e.length-1]==="]"?{kind:"required",normalized:e.slice(1)}:e==="..."?{kind:"spread"}:e==="+"?{kind:"undeclared"}:{kind:"required",normalized:e==="\\..."?"...":e==="\\+"?"+":e},mu=e=>`Spread operand must resolve to an object literal type (was ${e})`,gu=(e,n)=>Iu(e)?js[e[0]](e,n):Su(e)?Ls[e[1]](e,n):null,bu=(e,n)=>n.$.parseOwnDefinitionFormat(e[1],n).keyof(),Jt=(e,n)=>{if(e[2]===void 0)return f(Ds(e[1],""));const t=n.$.parseOwnDefinitionFormat(e[0],n),r=n.$.parseOwnDefinitionFormat(e[2],n);if(e[1]==="|")return n.$.node("union",{branches:[t,r]});const i=e[1]==="&"?re(t,r,n.$):Xt(t,r,n.$);return i instanceof y?i.throw():i},yu=(e,n)=>n.$.parseOwnDefinitionFormat(e[0],n).array(),ku=(e,n)=>typeof e[2]!="function"?f(Ps("=>",e[2])):n.$.parseOwnDefinitionFormat(e[0],n).pipe(e[2]),Ps=(e,n)=>`${e===":"?"Narrow":"Morph"} expression requires a function following '${e}' (was ${typeof n})`,xu=(e,n)=>typeof e[2]!="function"?f(Ps(":",e[2])):n.$.parseOwnDefinitionFormat(e[0],n).constrain("predicate",e[2]),$u=(e,n)=>n.$.parseOwnDefinitionFormat(e[0],n).configure(e[2],e[3]),Ts=e=>e,wu=Ts({"[]":yu,"?":()=>f(Rs)}),vu=Ts({"|":Jt,"&":Jt,":":xu,"=>":ku,"|>":Jt,"@":$u,"=":()=>f(Os)}),Ls={...wu,...vu},Su=e=>Ls[e[1]]!==void 0,Au=e=>e,js=Au({keyof:bu,instanceof:(e,n)=>{if(typeof e[1]!="function")return f(xr(Vt(e[1])));const t=e.slice(1).map(r=>typeof r=="function"?n.$.node("proto",{proto:r}):f(xr(Vt(r))));return t.length===1?t[0]:n.$.node("union",{branches:t})},"===":(e,n)=>n.$.units(e.slice(1))}),Iu=e=>js[e[0]]!==void 0,xr=e=>`Expected a constructor following 'instanceof' operator (was ${e})`,Nu=(e,n)=>{let t=[{}],r=0;for(;r<e.length;){let i=!1;e[r]==="..."&&r<e.length-1&&(i=!0,r++);const s=Es(e[r],n),[o,a,l]=L(s)?s:[s];if(r++,i){if(!o.extends(g.intrinsic.Array))return f(qu(o.expression));t=t.flatMap(u=>o.distribute(h=>Ou(Si(u),h)))}else t=t.map(u=>a==="?"?Fs(u,o):a==="="?Ru(u,o,l):ln(u,o))}return n.$.parseSchema(t.map(i=>Ve(i)?{proto:Array,exactLength:0}:{proto:Array,sequence:i}))},ln=(e,n)=>e.defaultables||e.optionals?f(e.variadic?ls:Cu):(e.variadic?e.postfix=N(e.postfix,n):e.prefix=N(e.prefix,n),e),Fs=(e,n)=>e.variadic?f(Us):(e.optionals=N(e.optionals,n),e),Ru=(e,n,t)=>e.variadic?f(Us):e.optionals?f(Mu):(e.defaultables=N(e.defaultables,[[n,t]]),e),$r=(e,n)=>(e.postfix&&f(wr),e.variadic?e.variadic.equals(n)||f(wr):e.variadic=n.internal,e),Ou=(e,n)=>{const t=n.select({method:"find",kind:"sequence"});if(!t)return $r(e,g.intrinsic.unknown);if(t.prefix)for(const r of t.prefix)ln(e,r);if(t.optionals)for(const r of t.optionals)Fs(e,r);if(t.variadic&&$r(e,t.variadic),t.postfix)for(const r of t.postfix)ln(e,r);return e},qu=e=>`Spread element must be an array (was ${e})`,wr="A tuple may have at most one variadic element",Cu="A required element may not follow an optional element",Us="An optional element may not follow a variadic element",Mu="A defaultable element may not follow an optional element without a default",_t={},Js=(e,n)=>{var t;if(typeof e=="string"){if(n.args&&Object.keys(n.args).some(i=>e.includes(i)))return br(e,n);const r=_t[t=n.$.name]??(_t[t]={});return r[e]??(r[e]=br(e,n))}return ye(e,"object")?Du(e,n):f(cn(G(e)))},Du=(e,n)=>{const t=mn(e);switch(t){case void 0:return k(e,"root")?e:"~standard"in e?Bu(e,n):hu(e,n);case"Array":return Ku(e,n);case"RegExp":return n.$.node("intersection",{domain:"string",pattern:e},{prereduced:!0});case"Function":{const r=wt(e)?e():e;return k(r,"root")?r:f(cn("Function"))}default:return f(cn(t??I(e)))}},Bu=(e,n)=>n.$.intrinsic.unknown.pipe((t,r)=>{const i=e["~standard"].validate(t);if(!i.issues)return i.value;for(const{message:s,path:o}of i.issues)o?o.length?r.error({problem:Ko(s),relativePath:o.map(a=>typeof a=="object"?a.key:a)}):r.error({message:s}):r.error({message:s})}),Ku=(e,n)=>gu(e,n)??Nu(e,n),cn=e=>`Type definitions must be strings or objects (was ${e})`;class zu extends ue{constructor(n){const t=Object.assign({errors:ce,hkt:Q,$:n,raw:n.parse,module:n.constructor.module,scope:n.constructor.scope,declare:n.declare,define:n.define,match:n.match,generic:n.generic,schema:n.schema,keywords:n.ambient,unit:n.unit,enumerated:n.enumerated,instanceOf:n.instanceOf,valueOf:n.valueOf,or:n.or,and:n.and,merge:n.merge,pipe:n.pipe,fn:n.fn},n.ambientAttachments);super((...r)=>{if(r.length===1)return n.parse(r[0]);if(r.length===2&&typeof r[0]=="string"&&r[0][0]==="<"&&r[0][r[0].length-1]===">"){const i=r[0].slice(1,-1),s=n.parseGenericParams(i,{});return new mt(s,r[1],n,n,null)}return n.parse(r)},{attach:t})}}const Je=g,ve=class ve extends ms{constructor(){super(...arguments);c(this,"unit",t=>this.units([t]));c(this,"valueOf",t=>this.units($o(t)));c(this,"enumerated",(...t)=>this.units(t));c(this,"instanceOf",t=>this.node("proto",{proto:t},{prereduced:!0}));c(this,"or",(...t)=>this.schema(t.map(r=>this.parse(r))));c(this,"and",(...t)=>t.reduce((r,i)=>r.and(this.parse(i)),this.intrinsic.unknown));c(this,"merge",(...t)=>t.reduce((r,i)=>r.merge(this.parse(i)),this.intrinsic.object));c(this,"pipe",(...t)=>this.intrinsic.unknown.pipe(...t));c(this,"fn",new ru(this));c(this,"match",new ou(this));c(this,"declare",()=>({type:this.type}));c(this,"type",new zu(this))}get ambientAttachments(){if(Je.typeAttachments)return this.cacheGetter("ambientAttachments",R(Je.typeAttachments,(t,r)=>[t,this.bindReference(r)]))}preparseOwnAliasEntry(t,r){var a;const i=t.indexOf("<");if(i===-1){if(k(r,"module")||k(r,"generic"))return[t,r];const l=this.name==="ark"?t:t==="root"?this.name:`${this.name}.${t}`,u=(a=this.resolvedConfig.keywords)==null?void 0:a[l];return u&&(r=[r,"@",u]),[t,r]}t[t.length-1]!==">"&&f("'>' must be the last character of a generic declaration in a scope");const s=t.slice(0,i),o=t.slice(i+1,-1);return[s,()=>{const l=this.parseGenericParams(o,{alias:s});return Na(l,r,this)}]}parseGenericParams(t,r){return an(new yi(t),[],this.createParseContext({...r,def:t,prefix:"generic"}))}normalizeRootScopeValue(t){return wt(t)&&!k(t,"generic")?t():t}preparseOwnDefinitionFormat(t,r){return{...r,def:t,prefix:r.alias??"type"}}parseOwnDefinitionFormat(t,r){!(r.alias&&r.alias in this.aliases)&&!r.args&&(r.args={this:r.id});const s=Js(t,r);if(L(s)){if(s[1]==="=")return f(Os);if(s[1]==="?")return f(Rs)}return s}define(t){return t}};c(ve,"scope",((t,r={})=>new ve(t,r))),c(ve,"module",((t,r={})=>ve.scope(t,r).export()));let yt=ve;const Eu=Object.assign(yt.scope,{define:e=>e}),v=yt;class Pu extends Q{constructor(){super(...arguments);c(this,"description",'merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`')}}const Tu=ie(["base",x.object],["props",x.object])(e=>e.base.merge(e.props),Pu),Lu=v.module({Key:x.key,Merge:Tu});class ju extends Q{}const Fu=ie("element")(e=>{const n=e.element.exclude(x.Array),t=n.array();return n.rawOr(t).pipe(_e).distribute(r=>r.assertHasKind("morph").declareOut(t),O)},ju),Uu=v.module({root:x.Array,readonly:"root",index:x.nonNegativeIntegerString,liftFrom:Fu},{name:"Array"}),un=O(["string",Ge.FileConstructor]),Ju=un.rawOr(un.array()),vr=O({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:Ju}}),_u=v.module({root:["instanceof",FormData],value:un,parsed:vr,parse:O({in:FormData,morphs:e=>{const n={};for(const[t,r]of e)if(t in n){const i=n[t];typeof i=="string"||i instanceof Ge.FileConstructor?n[t]=[i,r]:i.push(r)}else n[t]=r;return n},declaredOut:vr})},{name:"FormData"}),Vu=v.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"}),Gu={Boolean:1,Number:1,String:1},Hu=v.module({...R({...ai,...ci},(e,n)=>e in Gu?[]:[e,["instanceof",n]]),Array:Uu,TypedArray:Vu,FormData:_u}),Zu=O({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"}),Wu=O({domain:"number",divisor:1}),_s=v.module({root:x.number,integer:Wu,epoch:Zu,safe:O({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"}),q=(e,n,t)=>{const r={domain:"string",pattern:{rule:e.source,flags:e.flags,meta:n}};return t&&(r.meta={format:t}),On("intersection",r)},Sr=q(ut,"a well-formed integer string"),Vs=v.module({root:Sr,parse:O({in:Sr,morphs:(e,n)=>{const t=Number.parseInt(e);return Number.isSafeInteger(t)?t:n.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:x.integer})},{name:"string.integer"}),Qu=q(/^[\dA-Fa-f]+$/,"hex characters only"),Yu=v.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"}),Ar=q(/^[A-Z].*$/,"capitalized"),Xu=v.module({root:O({in:"string",morphs:e=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:Ar}),preformatted:Ar},{name:"string.capitalize"}),eh=e=>{const n=e.replace(/[ -]+/g,"");let t=0,r,i,s=!1;for(let o=n.length-1;o>=0;o--)r=n.substring(o,o+1),i=Number.parseInt(r,10),s?(i*=2,t+=i>=10?i%10+1:i):t+=i,s=!s;return!!(t%10===0&&n)},th=/^(?: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}))$/,nh=O({domain:"string",pattern:{meta:"a credit card number",rule:th.source},predicate:{meta:"a credit card number",predicate:eh}}),rh=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,ih=e=>!Number.isNaN(new Date(e).valueOf()),Ir=O({domain:"string",predicate:{meta:"a parsable date",predicate:ih}}).assertHasKind("intersection"),Nr=Vs.root.internal.narrow((e,n)=>{const t=Number.parseInt(e),r=_s.epoch(t);return r instanceof ce?(n.errors.merge(r),!1):!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),sh=v.module({root:Nr,parse:O({in:Nr,morphs:e=>new Date(e),declaredOut:x.Date})},{name:"string.date.epoch"}),Rr=q(rh,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),oh=v.module({root:Rr,parse:O({in:Rr,morphs:e=>new Date(e),declaredOut:x.Date})},{name:"string.date.iso"}),ah=v.module({root:Ir,parse:O({declaredIn:Ir,in:"string",morphs:(e,n)=>{const t=new Date(e);return Number.isNaN(t.valueOf())?n.error("a parsable date"):t},declaredOut:x.Date}),iso:oh,epoch:sh},{name:"string.date"}),lh=q(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),Or="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",oe=`(${Or}[.]){3}${Or}`,ch=new RegExp(`^${oe}$`),D="(?:[0-9a-fA-F]{1,4})",uh=new RegExp(`^((?:${D}:){7}(?:${D}|:)|(?:${D}:){6}(?:${oe}|:${D}|:)|(?:${D}:){5}(?::${oe}|(:${D}){1,2}|:)|(?:${D}:){4}(?:(:${D}){0,1}:${oe}|(:${D}){1,3}|:)|(?:${D}:){3}(?:(:${D}){0,2}:${oe}|(:${D}){1,4}|:)|(?:${D}:){2}(?:(:${D}){0,3}:${oe}|(:${D}){1,5}|:)|(?:${D}:){1}(?:(:${D}){0,4}:${oe}|(:${D}){1,6}|:)|(?::((?::${D}){0,5}:${oe}|(?::${D}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),hh=v.module({root:["v4 | v6","@","an IP address"],v4:q(ch,"an IPv4 address","ipv4"),v6:q(uh,"an IPv6 address","ipv6")},{name:"string.ip"}),Ae="a JSON string",Gs=e=>{if(!(e instanceof SyntaxError))throw e;return`must be ${Ae} (${e})`},dh=O({meta:Ae,domain:"string",predicate:{meta:Ae,predicate:(e,n)=>{try{return JSON.parse(e),!0}catch(t){return n.reject({code:"predicate",expected:Ae,problem:Gs(t)})}}}}),ph=(e,n)=>{if(e.length===0)return n.error({code:"predicate",expected:Ae,actual:"empty"});try{return JSON.parse(e)}catch(t){return n.error({code:"predicate",expected:Ae,problem:Gs(t)})}},fh=v.module({root:dh,parse:O({meta:"safe JSON string parser",in:"string",morphs:ph,declaredOut:x.jsonObject})},{name:"string.json"}),qr=q(/^[a-z]*$/,"only lowercase letters"),mh=v.module({root:O({in:"string",morphs:e=>e.toLowerCase(),declaredOut:qr}),preformatted:qr},{name:"string.lower"}),Hs=["NFC","NFD","NFKC","NFKD"],Xe=R(Hs,(e,n)=>[n,O({domain:"string",predicate:t=>t.normalize(n)===t,meta:`${n}-normalized unicode`})]),qt=R(Hs,(e,n)=>[n,O({in:"string",morphs:t=>t.normalize(n),declaredOut:Xe[n]})]),gh=v.module({root:qt.NFC,preformatted:Xe.NFC},{name:"string.normalize.NFC"}),bh=v.module({root:qt.NFD,preformatted:Xe.NFD},{name:"string.normalize.NFD"}),yh=v.module({root:qt.NFKC,preformatted:Xe.NFKC},{name:"string.normalize.NFKC"}),kh=v.module({root:qt.NFKD,preformatted:Xe.NFKD},{name:"string.normalize.NFKD"}),xh=v.module({root:"NFC",NFC:gh,NFD:bh,NFKC:yh,NFKD:kh},{name:"string.normalize"}),Cr=q(Gt,"a well-formed numeric string"),$h=v.module({root:Cr,parse:O({in:Cr,morphs:e=>Number.parseFloat(e),declaredOut:x.number})},{name:"string.numeric"}),Mr="a regex pattern",wh=O({domain:"string",predicate:{meta:Mr,predicate:(e,n)=>{try{return new RegExp(e),!0}catch(t){return n.reject({code:"predicate",expected:Mr,problem:String(t)})}}},meta:{format:"regex"}}),vh=/^(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-]+)*))?$/,Sh=q(vh,"a semantic version (see https://semver.org/)"),Dr=q(/^\S.*\S$|^\S?$/,"trimmed"),Ah=v.module({root:O({in:"string",morphs:e=>e.trim(),declaredOut:Dr}),preformatted:Dr},{name:"string.trim"}),Br=q(/^[A-Z]*$/,"only uppercase letters"),Ih=v.module({root:O({in:"string",morphs:e=>e.toUpperCase(),declaredOut:Br}),preformatted:Br},{name:"string.upper"}),Nh=e=>URL.canParse(e),Kr=O({domain:"string",predicate:{meta:"a URL string",predicate:Nh},meta:{format:"uri"}}),Rh=v.module({root:Kr,parse:O({declaredIn:Kr,in:"string",morphs:(e,n)=>{try{return new URL(e)}catch{return n.error("a URL string")}},declaredOut:O(URL)})},{name:"string.url"}),Oh=v.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"}),qh=v.module({root:x.string,alpha:q(/^[A-Za-z]*$/,"only letters"),alphanumeric:q(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:Qu,base64:Yu,capitalize:Xu,creditCard:nh,date:ah,digits:q(/^\d*$/,"only digits 0-9"),email:lh,integer:Vs,ip:hh,json:fh,lower:mh,normalize:xh,numeric:$h,regex:wh,semver:Sh,trim:Ah,upper:Ih,url:Rh,uuid:Oh},{name:"string"}),Ch=v.module({bigint:x.bigint,boolean:x.boolean,false:x.false,never:x.never,null:x.null,number:x.number,object:x.object,string:x.string,symbol:x.symbol,true:x.true,unknown:x.unknown,undefined:x.undefined}),Mh=v.module({root:x.unknown,any:x.unknown},{name:"unknown"}),Dh=v.module({root:x.jsonObject,stringify:On("morph",{in:x.jsonObject,morphs:e=>JSON.stringify(e),declaredOut:x.string})},{name:"object.json"}),Bh=v.module({root:x.object,json:Dh},{name:"object"});class Kh extends Q{constructor(){super(...arguments);c(this,"description",'instantiate an object from an index signature and corresponding value type like `Record("string", "number")`')}}const zh=ie(["K",x.key],"V")(e=>({domain:"object",index:{signature:e.K,value:e.V}}),Kh);class Eh extends Q{constructor(){super(...arguments);c(this,"description",'pick a set of properties from an object like `Pick(User, "name | age")`')}}const Ph=ie(["T",x.object],["K",x.key])(e=>e.T.pick(e.K),Eh);class Th extends Q{constructor(){super(...arguments);c(this,"description",'omit a set of properties from an object like `Omit(User, "age")`')}}const Lh=ie(["T",x.object],["K",x.key])(e=>e.T.omit(e.K),Th);class jh extends Q{constructor(){super(...arguments);c(this,"description","make all named properties of an object optional like `Partial(User)`")}}const Fh=ie(["T",x.object])(e=>e.T.partial(),jh);class Uh extends Q{constructor(){super(...arguments);c(this,"description","make all named properties of an object required like `Required(User)`")}}const Jh=ie(["T",x.object])(e=>e.T.required(),Uh);class _h extends Q{constructor(){super(...arguments);c(this,"description",'exclude branches of a union like `Exclude("boolean", "true")`')}}const Vh=ie("T","U")(e=>e.T.exclude(e.U),_h);class Gh extends Q{constructor(){super(...arguments);c(this,"description",'extract branches of a union like `Extract("0 | false | 1", "number")`')}}const Hh=ie("T","U")(e=>e.T.extract(e.U),Gh),Zh=v.module({Exclude:Vh,Extract:Hh,Omit:Lh,Partial:Fh,Pick:Ph,Record:zh,Required:Jh}),he=Eu({...Ch,...Zh,...Hu,...Lu,string:qh,number:_s,object:Bh,unknown:Mh},{prereducedAliases:!0,name:"ark"}),E=he.export();Object.assign(Je.ambient,E);Je.typeAttachments={string:E.string.root,number:E.number.root,bigint:E.bigint,boolean:E.boolean,symbol:E.symbol,undefined:E.undefined,null:E.null,object:E.object.root,unknown:E.unknown.root,false:E.false,true:E.true,never:E.never,arrayIndex:E.Array.index,Key:E.Key,Record:E.Record,Array:E.Array.root,Date:E.Date};const Pd=Object.assign(he.type,Je.typeAttachments);he.match;he.fn;he.generic;he.schema;he.define;he.declare;function Mn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ke=Mn();function Zs(e){ke=e}var pe={exec:()=>null};function w(e,n=""){let t=typeof e=="string"?e:e.source,r={replace:(i,s)=>{let o=typeof s=="string"?s:s.source;return o=o.replace(T.caret,"$1"),t=t.replace(i,o),r},getRegex:()=>new RegExp(t,n)};return r}var Wh=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),T={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},Qh=/^(?:[ \t]*(?:\n|$))+/,Yh=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Xh=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,et=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ed=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Dn=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ws=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Qs=w(Ws).replace(/bull/g,Dn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),td=w(Ws).replace(/bull/g,Dn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Bn=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,nd=/^[^\n]+/,Kn=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,rd=w(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Kn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),id=w(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Dn).getRegex(),Ct="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",zn=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,sd=w("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",zn).replace("tag",Ct).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ys=w(Bn).replace("hr",et).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ct).getRegex(),od=w(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ys).getRegex(),En={blockquote:od,code:Yh,def:rd,fences:Xh,heading:ed,hr:et,html:sd,lheading:Qs,list:id,newline:Qh,paragraph:Ys,table:pe,text:nd},zr=w("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",et).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ct).getRegex(),ad={...En,lheading:td,table:zr,paragraph:w(Bn).replace("hr",et).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",zr).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ct).getRegex()},ld={...En,html:w(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",zn).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:pe,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:w(Bn).replace("hr",et).replace("heading",` *#{1,6} *[^
47
+ ]`).replace("lheading",Qs).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},cd=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ud=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Xs=/^( {2,}|\\)\n(?!\s*$)/,hd=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ke=/[\p{P}\p{S}]/u,Mt=/[\s\p{P}\p{S}]/u,Pn=/[^\s\p{P}\p{S}]/u,dd=w(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Mt).getRegex(),eo=/(?!~)[\p{P}\p{S}]/u,pd=/(?!~)[\s\p{P}\p{S}]/u,fd=/(?:[^\s\p{P}\p{S}]|~)/u,md=w(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Wh?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),to=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,gd=w(to,"u").replace(/punct/g,Ke).getRegex(),bd=w(to,"u").replace(/punct/g,eo).getRegex(),no="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",yd=w(no,"gu").replace(/notPunctSpace/g,Pn).replace(/punctSpace/g,Mt).replace(/punct/g,Ke).getRegex(),kd=w(no,"gu").replace(/notPunctSpace/g,fd).replace(/punctSpace/g,pd).replace(/punct/g,eo).getRegex(),xd=w("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Pn).replace(/punctSpace/g,Mt).replace(/punct/g,Ke).getRegex(),$d=w(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ke).getRegex(),wd="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",vd=w(wd,"gu").replace(/notPunctSpace/g,Pn).replace(/punctSpace/g,Mt).replace(/punct/g,Ke).getRegex(),Sd=w(/\\(punct)/,"gu").replace(/punct/g,Ke).getRegex(),Ad=w(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Id=w(zn).replace("(?:-->|$)","-->").getRegex(),Nd=w("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Id).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),kt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Rd=w(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",kt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ro=w(/^!?\[(label)\]\[(ref)\]/).replace("label",kt).replace("ref",Kn).getRegex(),io=w(/^!?\[(ref)\](?:\[\])?/).replace("ref",Kn).getRegex(),Od=w("reflink|nolink(?!\\()","g").replace("reflink",ro).replace("nolink",io).getRegex(),Er=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Tn={_backpedal:pe,anyPunctuation:Sd,autolink:Ad,blockSkip:md,br:Xs,code:ud,del:pe,delLDelim:pe,delRDelim:pe,emStrongLDelim:gd,emStrongRDelimAst:yd,emStrongRDelimUnd:xd,escape:cd,link:Rd,nolink:io,punctuation:dd,reflink:ro,reflinkSearch:Od,tag:Nd,text:hd,url:pe},qd={...Tn,link:w(/^!?\[(label)\]\((.*?)\)/).replace("label",kt).getRegex(),reflink:w(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",kt).getRegex()},hn={...Tn,emStrongRDelimAst:kd,emStrongLDelim:bd,delLDelim:$d,delRDelim:vd,url:w(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Er).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:w(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Er).getRegex()},Cd={...hn,br:w(Xs).replace("{2,}","*").getRegex(),text:w(hn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},st={normal:En,gfm:ad,pedantic:ld},Ee={normal:Tn,gfm:hn,breaks:Cd,pedantic:qd},Md={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Pr=e=>Md[e];function H(e,n){if(n){if(T.escapeTest.test(e))return e.replace(T.escapeReplace,Pr)}else if(T.escapeTestNoEncode.test(e))return e.replace(T.escapeReplaceNoEncode,Pr);return e}function Tr(e){try{e=encodeURI(e).replace(T.percentDecode,"%")}catch{return null}return e}function Lr(e,n){var s;let t=e.replace(T.findPipe,(o,a,l)=>{let u=!1,h=a;for(;--h>=0&&l[h]==="\\";)u=!u;return u?"|":" |"}),r=t.split(T.splitPipe),i=0;if(r[0].trim()||r.shift(),r.length>0&&!((s=r.at(-1))!=null&&s.trim())&&r.pop(),n)if(r.length>n)r.splice(n);else for(;r.length<n;)r.push("");for(;i<r.length;i++)r[i]=r[i].trim().replace(T.slashPipe,"|");return r}function se(e,n,t){let r=e.length;if(r===0)return"";let i=0;for(;i<r&&e.charAt(r-i-1)===n;)i++;return e.slice(0,r-i)}function jr(e){let n=e.split(`
48
+ `),t=n.length-1;for(;t>=0&&T.blankLine.test(n[t]);)t--;return n.length-t<=2?e:n.slice(0,t+1).join(`
49
+ `)}function Dd(e,n){if(e.indexOf(n[1])===-1)return-1;let t=0;for(let r=0;r<e.length;r++)if(e[r]==="\\")r++;else if(e[r]===n[0])t++;else if(e[r]===n[1]&&(t--,t<0))return r;return t>0?-2:-1}function Bd(e,n=0){let t=n,r="";for(let i of e)if(i===" "){let s=4-t%4;r+=" ".repeat(s),t+=s}else r+=i,t++;return r}function Fr(e,n,t,r,i){let s=n.href,o=n.title||null,a=e[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;let l={type:e[0].charAt(0)==="!"?"image":"link",raw:t,href:s,title:o,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,l}function Kd(e,n,t){let r=e.match(t.other.indentCodeCompensation);if(r===null)return n;let i=r[1];return n.split(`
50
+ `).map(s=>{let o=s.match(t.other.beginningSpace);if(o===null)return s;let[a]=o;return a.length>=i.length?s.slice(i.length):s}).join(`
51
+ `)}var xt=class{constructor(e){c(this,"options");c(this,"rules");c(this,"lexer");this.options=e||ke}space(e){let n=this.rules.block.newline.exec(e);if(n&&n[0].length>0)return{type:"space",raw:n[0]}}code(e){let n=this.rules.block.code.exec(e);if(n){let t=this.options.pedantic?n[0]:jr(n[0]),r=t.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t,codeBlockStyle:"indented",text:r}}}fences(e){let n=this.rules.block.fences.exec(e);if(n){let t=n[0],r=Kd(t,n[3]||"",this.rules);return{type:"code",raw:t,lang:n[2]?n[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):n[2],text:r}}}heading(e){let n=this.rules.block.heading.exec(e);if(n){let t=n[2].trim();if(this.rules.other.endingHash.test(t)){let r=se(t,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(t=r.trim())}return{type:"heading",raw:se(n[0],`
52
+ `),depth:n[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(e){let n=this.rules.block.hr.exec(e);if(n)return{type:"hr",raw:se(n[0],`
53
+ `)}}blockquote(e){let n=this.rules.block.blockquote.exec(e);if(n){let t=se(n[0],`
54
+ `).split(`
55
+ `),r="",i="",s=[];for(;t.length>0;){let o=!1,a=[],l;for(l=0;l<t.length;l++)if(this.rules.other.blockquoteStart.test(t[l]))a.push(t[l]),o=!0;else if(!o)a.push(t[l]);else break;t=t.slice(l);let u=a.join(`
56
+ `),h=u.replace(this.rules.other.blockquoteSetextReplace,`
57
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
58
+ ${u}`:u,i=i?`${i}
59
+ ${h}`:h;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(h,s,!0),this.lexer.state.top=d,t.length===0)break;let m=s.at(-1);if((m==null?void 0:m.type)==="code")break;if((m==null?void 0:m.type)==="blockquote"){let b=m,p=b.raw+`
60
+ `+t.join(`
61
+ `),S=this.blockquote(p);s[s.length-1]=S,r=r.substring(0,r.length-b.raw.length)+S.raw,i=i.substring(0,i.length-b.text.length)+S.text;break}else if((m==null?void 0:m.type)==="list"){let b=m,p=b.raw+`
62
+ `+t.join(`
63
+ `),S=this.list(p);s[s.length-1]=S,r=r.substring(0,r.length-m.raw.length)+S.raw,i=i.substring(0,i.length-b.raw.length)+S.raw,t=p.substring(s.at(-1).raw.length).split(`
64
+ `);continue}}return{type:"blockquote",raw:r,tokens:s,text:i}}}list(e){let n=this.rules.block.list.exec(e);if(n){let t=n[1].trim(),r=t.length>1,i={type:"list",raw:"",ordered:r,start:r?+t.slice(0,-1):"",loose:!1,items:[]};t=r?`\\d{1,9}\\${t.slice(-1)}`:`\\${t}`,this.options.pedantic&&(t=r?t:"[*+-]");let s=this.rules.other.listItemRegex(t),o=!1;for(;e;){let l=!1,u="",h="";if(!(n=s.exec(e))||this.rules.block.hr.test(e))break;u=n[0],e=e.substring(u.length);let d=Bd(n[2].split(`
65
+ `,1)[0],n[1].length),m=e.split(`
66
+ `,1)[0],b=!d.trim(),p=0;if(this.options.pedantic?(p=2,h=d.trimStart()):b?p=n[1].length+1:(p=d.search(this.rules.other.nonSpaceChar),p=p>4?1:p,h=d.slice(p),p+=n[1].length),b&&this.rules.other.blankLine.test(m)&&(u+=m+`
67
+ `,e=e.substring(m.length+1),l=!0),!l){let S=this.rules.other.nextBulletRegex(p),$=this.rules.other.hrRegex(p),C=this.rules.other.fencesBeginRegex(p),z=this.rules.other.headingBeginRegex(p),Y=this.rules.other.htmlBeginRegex(p),Dt=this.rules.other.blockquoteBeginRegex(p);for(;e;){let de=e.split(`
68
+ `,1)[0],ze;if(m=de,this.options.pedantic?(m=m.replace(this.rules.other.listReplaceNesting," "),ze=m):ze=m.replace(this.rules.other.tabCharGlobal," "),C.test(m)||z.test(m)||Y.test(m)||Dt.test(m)||S.test(m)||$.test(m))break;if(ze.search(this.rules.other.nonSpaceChar)>=p||!m.trim())h+=`
69
+ `+ze.slice(p);else{if(b||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||C.test(d)||z.test(d)||$.test(d))break;h+=`
70
+ `+m}b=!m.trim(),u+=de+`
71
+ `,e=e.substring(de.length+1),d=ze.slice(p)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(o=!0)),i.items.push({type:"list_item",raw:u,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]}),i.raw+=u}let a=i.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let u=l.tokens[0];if(l.task&&((u==null?void 0:u.type)==="text"||(u==null?void 0:u.type)==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),u.raw=u.raw.replace(this.rules.other.listReplaceTask,""),u.text=u.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let h=this.rules.other.listTaskCheckbox.exec(l.raw);if(h){let d={type:"checkbox",raw:h[0]+" ",checked:h[0]!=="[ ]"};l.checked=d.checked,i.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=d.raw+l.tokens[0].raw,l.tokens[0].text=d.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(d)):l.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):l.tokens.unshift(d)}}else l.task&&(l.task=!1);if(!i.loose){let h=l.tokens.filter(m=>m.type==="space"),d=h.length>0&&h.some(m=>this.rules.other.anyLine.test(m.raw));i.loose=d}}if(i.loose)for(let l of i.items){l.loose=!0;for(let u of l.tokens)u.type==="text"&&(u.type="paragraph")}return i}}html(e){let n=this.rules.block.html.exec(e);if(n){let t=jr(n[0]);return{type:"html",block:!0,raw:t,pre:n[1]==="pre"||n[1]==="script"||n[1]==="style",text:t}}}def(e){let n=this.rules.block.def.exec(e);if(n){let t=n[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=n[2]?n[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=n[3]?n[3].substring(1,n[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):n[3];return{type:"def",tag:t,raw:se(n[0],`
72
+ `),href:r,title:i}}}table(e){var o;let n=this.rules.block.table.exec(e);if(!n||!this.rules.other.tableDelimiter.test(n[2]))return;let t=Lr(n[1]),r=n[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=(o=n[3])!=null&&o.trim()?n[3].replace(this.rules.other.tableRowBlankLine,"").split(`
73
+ `):[],s={type:"table",raw:se(n[0],`
74
+ `),header:[],align:[],rows:[]};if(t.length===r.length){for(let a of r)this.rules.other.tableAlignRight.test(a)?s.align.push("right"):this.rules.other.tableAlignCenter.test(a)?s.align.push("center"):this.rules.other.tableAlignLeft.test(a)?s.align.push("left"):s.align.push(null);for(let a=0;a<t.length;a++)s.header.push({text:t[a],tokens:this.lexer.inline(t[a]),header:!0,align:s.align[a]});for(let a of i)s.rows.push(Lr(a,s.header.length).map((l,u)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:s.align[u]})));return s}}lheading(e){let n=this.rules.block.lheading.exec(e);if(n){let t=n[1].trim();return{type:"heading",raw:se(n[0],`
75
+ `),depth:n[2].charAt(0)==="="?1:2,text:t,tokens:this.lexer.inline(t)}}}paragraph(e){let n=this.rules.block.paragraph.exec(e);if(n){let t=n[1].charAt(n[1].length-1)===`
76
+ `?n[1].slice(0,-1):n[1];return{type:"paragraph",raw:n[0],text:t,tokens:this.lexer.inline(t)}}}text(e){let n=this.rules.block.text.exec(e);if(n)return{type:"text",raw:n[0],text:n[0],tokens:this.lexer.inline(n[0])}}escape(e){let n=this.rules.inline.escape.exec(e);if(n)return{type:"escape",raw:n[0],text:n[1]}}tag(e){let n=this.rules.inline.tag.exec(e);if(n)return!this.lexer.state.inLink&&this.rules.other.startATag.test(n[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(n[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(n[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(n[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:n[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:n[0]}}link(e){let n=this.rules.inline.link.exec(e);if(n){let t=n[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let s=se(t.slice(0,-1),"\\");if((t.length-s.length)%2===0)return}else{let s=Dd(n[2],"()");if(s===-2)return;if(s>-1){let o=(n[0].indexOf("!")===0?5:4)+n[1].length+s;n[2]=n[2].substring(0,s),n[0]=n[0].substring(0,o).trim(),n[3]=""}}let r=n[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],i=s[3])}else i=n[3]?n[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?r=r.slice(1):r=r.slice(1,-1)),Fr(n,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},n[0],this.lexer,this.rules)}}reflink(e,n){let t;if((t=this.rules.inline.reflink.exec(e))||(t=this.rules.inline.nolink.exec(e))){let r=(t[2]||t[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=n[r.toLowerCase()];if(!i){let s=t[0].charAt(0);return{type:"text",raw:s,text:s}}return Fr(t,i,t[0],this.lexer,this.rules)}}emStrong(e,n,t=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&t.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!t||this.rules.inline.punctuation.exec(t))){let i=[...r[0]].length-1,s,o,a=i,l=0,u=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,n=n.slice(-1*e.length+i);(r=u.exec(n))!==null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s)continue;if(o=[...s].length,r[3]||r[4]){a+=o;continue}else if((r[5]||r[6])&&i%3&&!((i+o)%3)){l+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a+l);let h=[...r[0]][0].length,d=e.slice(0,i+r.index+h+o);if(Math.min(i,o)%2){let b=d.slice(1,-1);return{type:"em",raw:d,text:b,tokens:this.lexer.inlineTokens(b)}}let m=d.slice(2,-2);return{type:"strong",raw:d,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let n=this.rules.inline.code.exec(e);if(n){let t=n[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(t),i=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return r&&i&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:n[0],text:t}}}br(e){let n=this.rules.inline.br.exec(e);if(n)return{type:"br",raw:n[0]}}del(e,n,t=""){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!t||this.rules.inline.punctuation.exec(t))){let i=[...r[0]].length-1,s,o,a=i,l=this.rules.inline.delRDelim;for(l.lastIndex=0,n=n.slice(-1*e.length+i);(r=l.exec(n))!==null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s||(o=[...s].length,o!==i))continue;if(r[3]||r[4]){a+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a);let u=[...r[0]][0].length,h=e.slice(0,i+r.index+u+o),d=h.slice(i,-i);return{type:"del",raw:h,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let n=this.rules.inline.autolink.exec(e);if(n){let t,r;return n[2]==="@"?(t=n[1],r="mailto:"+t):(t=n[1],r=t),{type:"link",raw:n[0],text:t,href:r,tokens:[{type:"text",raw:t,text:t}]}}}url(e){var t;let n;if(n=this.rules.inline.url.exec(e)){let r,i;if(n[2]==="@")r=n[0],i="mailto:"+r;else{let s;do s=n[0],n[0]=((t=this.rules.inline._backpedal.exec(n[0]))==null?void 0:t[0])??"";while(s!==n[0]);r=n[0],n[1]==="www."?i="http://"+n[0]:i=n[0]}return{type:"link",raw:n[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let n=this.rules.inline.text.exec(e);if(n){let t=this.lexer.state.inRawBlock;return{type:"text",raw:n[0],text:n[0],escaped:t}}}},_=class dn{constructor(n){c(this,"tokens");c(this,"options");c(this,"state");c(this,"inlineQueue");c(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=n||ke,this.options.tokenizer=this.options.tokenizer||new xt,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:T,block:st.normal,inline:Ee.normal};this.options.pedantic?(t.block=st.pedantic,t.inline=Ee.pedantic):this.options.gfm&&(t.block=st.gfm,this.options.breaks?t.inline=Ee.breaks:t.inline=Ee.gfm),this.tokenizer.rules=t}static get rules(){return{block:st,inline:Ee}}static lex(n,t){return new dn(t).lex(n)}static lexInline(n,t){return new dn(t).inlineTokens(n)}lex(n){n=n.replace(T.carriageReturn,`
77
+ `),this.blockTokens(n,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let r=this.inlineQueue[t];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(n,t=[],r=!1){var s,o,a;this.tokenizer.lexer=this,this.options.pedantic&&(n=n.replace(T.tabCharGlobal," ").replace(T.spaceLine,""));let i=1/0;for(;n;){if(n.length<i)i=n.length;else{this.infiniteLoopError(n.charCodeAt(0));break}let l;if((o=(s=this.options.extensions)==null?void 0:s.block)!=null&&o.some(h=>(l=h.call({lexer:this},n,t))?(n=n.substring(l.raw.length),t.push(l),!0):!1))continue;if(l=this.tokenizer.space(n)){n=n.substring(l.raw.length);let h=t.at(-1);l.raw.length===1&&h!==void 0?h.raw+=`
78
+ `:t.push(l);continue}if(l=this.tokenizer.code(n)){n=n.substring(l.raw.length);let h=t.at(-1);(h==null?void 0:h.type)==="paragraph"||(h==null?void 0:h.type)==="text"?(h.raw+=(h.raw.endsWith(`
79
+ `)?"":`
80
+ `)+l.raw,h.text+=`
81
+ `+l.text,this.inlineQueue.at(-1).src=h.text):t.push(l);continue}if(l=this.tokenizer.fences(n)){n=n.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.heading(n)){n=n.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.hr(n)){n=n.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.blockquote(n)){n=n.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.list(n)){n=n.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.html(n)){n=n.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.def(n)){n=n.substring(l.raw.length);let h=t.at(-1);(h==null?void 0:h.type)==="paragraph"||(h==null?void 0:h.type)==="text"?(h.raw+=(h.raw.endsWith(`
82
+ `)?"":`
83
+ `)+l.raw,h.text+=`
84
+ `+l.raw,this.inlineQueue.at(-1).src=h.text):this.tokens.links[l.tag]||(this.tokens.links[l.tag]={href:l.href,title:l.title},t.push(l));continue}if(l=this.tokenizer.table(n)){n=n.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.lheading(n)){n=n.substring(l.raw.length),t.push(l);continue}let u=n;if((a=this.options.extensions)!=null&&a.startBlock){let h=1/0,d=n.slice(1),m;this.options.extensions.startBlock.forEach(b=>{m=b.call({lexer:this},d),typeof m=="number"&&m>=0&&(h=Math.min(h,m))}),h<1/0&&h>=0&&(u=n.substring(0,h+1))}if(this.state.top&&(l=this.tokenizer.paragraph(u))){let h=t.at(-1);r&&(h==null?void 0:h.type)==="paragraph"?(h.raw+=(h.raw.endsWith(`
85
+ `)?"":`
86
+ `)+l.raw,h.text+=`
87
+ `+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=h.text):t.push(l),r=u.length!==n.length,n=n.substring(l.raw.length);continue}if(l=this.tokenizer.text(n)){n=n.substring(l.raw.length);let h=t.at(-1);(h==null?void 0:h.type)==="text"?(h.raw+=(h.raw.endsWith(`
88
+ `)?"":`
89
+ `)+l.raw,h.text+=`
90
+ `+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=h.text):t.push(l);continue}if(n){this.infiniteLoopError(n.charCodeAt(0));break}}return this.state.top=!0,t}inline(n,t=[]){return this.inlineQueue.push({src:n,tokens:t}),t}inlineTokens(n,t=[]){var u,h,d,m,b;this.tokenizer.lexer=this;let r=n,i=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)p.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let s;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)s=i[2]?i[2].length:0,r=r.slice(0,i.index+s)+"["+"a".repeat(i[0].length-s-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=((h=(u=this.options.hooks)==null?void 0:u.emStrongMask)==null?void 0:h.call({lexer:this},r))??r;let o=!1,a="",l=1/0;for(;n;){if(n.length<l)l=n.length;else{this.infiniteLoopError(n.charCodeAt(0));break}o||(a=""),o=!1;let p;if((m=(d=this.options.extensions)==null?void 0:d.inline)!=null&&m.some($=>(p=$.call({lexer:this},n,t))?(n=n.substring(p.raw.length),t.push(p),!0):!1))continue;if(p=this.tokenizer.escape(n)){n=n.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.tag(n)){n=n.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.link(n)){n=n.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.reflink(n,this.tokens.links)){n=n.substring(p.raw.length);let $=t.at(-1);p.type==="text"&&($==null?void 0:$.type)==="text"?($.raw+=p.raw,$.text+=p.text):t.push(p);continue}if(p=this.tokenizer.emStrong(n,r,a)){n=n.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.codespan(n)){n=n.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.br(n)){n=n.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.del(n,r,a)){n=n.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.autolink(n)){n=n.substring(p.raw.length),t.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(n))){n=n.substring(p.raw.length),t.push(p);continue}let S=n;if((b=this.options.extensions)!=null&&b.startInline){let $=1/0,C=n.slice(1),z;this.options.extensions.startInline.forEach(Y=>{z=Y.call({lexer:this},C),typeof z=="number"&&z>=0&&($=Math.min($,z))}),$<1/0&&$>=0&&(S=n.substring(0,$+1))}if(p=this.tokenizer.inlineText(S)){n=n.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),o=!0;let $=t.at(-1);($==null?void 0:$.type)==="text"?($.raw+=p.raw,$.text+=p.text):t.push(p);continue}if(n){this.infiniteLoopError(n.charCodeAt(0));break}}return t}infiniteLoopError(n){let t="Infinite loop on byte: "+n;if(this.options.silent)console.error(t);else throw new Error(t)}},$t=class{constructor(e){c(this,"options");c(this,"parser");this.options=e||ke}space(e){return""}code({text:e,lang:n,escaped:t}){var s;let r=(s=(n||"").match(T.notSpaceStart))==null?void 0:s[0],i=e.replace(T.endingNewline,"")+`
91
+ `;return r?'<pre><code class="language-'+H(r)+'">'+(t?i:H(i,!0))+`</code></pre>
92
+ `:"<pre><code>"+(t?i:H(i,!0))+`</code></pre>
93
+ `}blockquote({tokens:e}){return`<blockquote>
94
+ ${this.parser.parse(e)}</blockquote>
95
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:n}){return`<h${n}>${this.parser.parseInline(e)}</h${n}>
96
+ `}hr(e){return`<hr>
97
+ `}list(e){let n=e.ordered,t=e.start,r="";for(let o=0;o<e.items.length;o++){let a=e.items[o];r+=this.listitem(a)}let i=n?"ol":"ul",s=n&&t!==1?' start="'+t+'"':"";return"<"+i+s+`>
98
+ `+r+"</"+i+`>
99
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
100
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
101
+ `}table(e){let n="",t="";for(let i=0;i<e.header.length;i++)t+=this.tablecell(e.header[i]);n+=this.tablerow({text:t});let r="";for(let i=0;i<e.rows.length;i++){let s=e.rows[i];t="";for(let o=0;o<s.length;o++)t+=this.tablecell(s[o]);r+=this.tablerow({text:t})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
102
+ <thead>
103
+ `+n+`</thead>
104
+ `+r+`</table>
105
+ `}tablerow({text:e}){return`<tr>
106
+ ${e}</tr>
107
+ `}tablecell(e){let n=this.parser.parseInline(e.tokens),t=e.header?"th":"td";return(e.align?`<${t} align="${e.align}">`:`<${t}>`)+n+`</${t}>
108
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${H(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:n,tokens:t}){let r=this.parser.parseInline(t),i=Tr(e);if(i===null)return r;e=i;let s='<a href="'+e+'"';return n&&(s+=' title="'+H(n)+'"'),s+=">"+r+"</a>",s}image({href:e,title:n,text:t,tokens:r}){r&&(t=this.parser.parseInline(r,this.parser.textRenderer));let i=Tr(e);if(i===null)return H(t);e=i;let s=`<img src="${e}" alt="${H(t)}"`;return n&&(s+=` title="${H(n)}"`),s+=">",s}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:H(e.text)}},Ln=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},V=class pn{constructor(n){c(this,"options");c(this,"renderer");c(this,"textRenderer");this.options=n||ke,this.options.renderer=this.options.renderer||new $t,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ln}static parse(n,t){return new pn(t).parse(n)}static parseInline(n,t){return new pn(t).parseInline(n)}parse(n){var r,i;this.renderer.parser=this;let t="";for(let s=0;s<n.length;s++){let o=n[s];if((i=(r=this.options.extensions)==null?void 0:r.renderers)!=null&&i[o.type]){let l=o,u=this.options.extensions.renderers[l.type].call({parser:this},l);if(u!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(l.type)){t+=u||"";continue}}let a=o;switch(a.type){case"space":{t+=this.renderer.space(a);break}case"hr":{t+=this.renderer.hr(a);break}case"heading":{t+=this.renderer.heading(a);break}case"code":{t+=this.renderer.code(a);break}case"table":{t+=this.renderer.table(a);break}case"blockquote":{t+=this.renderer.blockquote(a);break}case"list":{t+=this.renderer.list(a);break}case"checkbox":{t+=this.renderer.checkbox(a);break}case"html":{t+=this.renderer.html(a);break}case"def":{t+=this.renderer.def(a);break}case"paragraph":{t+=this.renderer.paragraph(a);break}case"text":{t+=this.renderer.text(a);break}default:{let l='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return t}parseInline(n,t=this.renderer){var i,s;this.renderer.parser=this;let r="";for(let o=0;o<n.length;o++){let a=n[o];if((s=(i=this.options.extensions)==null?void 0:i.renderers)!=null&&s[a.type]){let u=this.options.extensions.renderers[a.type].call({parser:this},a);if(u!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){r+=u||"";continue}}let l=a;switch(l.type){case"escape":{r+=t.text(l);break}case"html":{r+=t.html(l);break}case"link":{r+=t.link(l);break}case"image":{r+=t.image(l);break}case"checkbox":{r+=t.checkbox(l);break}case"strong":{r+=t.strong(l);break}case"em":{r+=t.em(l);break}case"codespan":{r+=t.codespan(l);break}case"br":{r+=t.br(l);break}case"del":{r+=t.del(l);break}case"text":{r+=t.text(l);break}default:{let u='Token with "'+l.type+'" type was not found.';if(this.options.silent)return console.error(u),"";throw new Error(u)}}}return r}},ot,Le=(ot=class{constructor(e){c(this,"options");c(this,"block");this.options=e||ke}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?_.lex:_.lexInline}provideParser(e=this.block){return e?V.parse:V.parseInline}},c(ot,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),c(ot,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),ot),zd=class{constructor(...e){c(this,"defaults",Mn());c(this,"options",this.setOptions);c(this,"parse",this.parseMarkdown(!0));c(this,"parseInline",this.parseMarkdown(!1));c(this,"Parser",V);c(this,"Renderer",$t);c(this,"TextRenderer",Ln);c(this,"Lexer",_);c(this,"Tokenizer",xt);c(this,"Hooks",Le);this.use(...e)}walkTokens(e,n){var r,i;let t=[];for(let s of e)switch(t=t.concat(n.call(this,s)),s.type){case"table":{let o=s;for(let a of o.header)t=t.concat(this.walkTokens(a.tokens,n));for(let a of o.rows)for(let l of a)t=t.concat(this.walkTokens(l.tokens,n));break}case"list":{let o=s;t=t.concat(this.walkTokens(o.items,n));break}default:{let o=s;(i=(r=this.defaults.extensions)==null?void 0:r.childTokens)!=null&&i[o.type]?this.defaults.extensions.childTokens[o.type].forEach(a=>{let l=o[a].flat(1/0);t=t.concat(this.walkTokens(l,n))}):o.tokens&&(t=t.concat(this.walkTokens(o.tokens,n)))}}return t}use(...e){let n=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(t=>{let r={...t};if(r.async=this.defaults.async||r.async||!1,t.extensions&&(t.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let s=n.renderers[i.name];s?n.renderers[i.name]=function(...o){let a=i.renderer.apply(this,o);return a===!1&&(a=s.apply(this,o)),a}:n.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=n[i.level];s?s.unshift(i.tokenizer):n[i.level]=[i.tokenizer],i.start&&(i.level==="block"?n.startBlock?n.startBlock.push(i.start):n.startBlock=[i.start]:i.level==="inline"&&(n.startInline?n.startInline.push(i.start):n.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(n.childTokens[i.name]=i.childTokens)}),r.extensions=n),t.renderer){let i=this.defaults.renderer||new $t(this.defaults);for(let s in t.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let o=s,a=t.renderer[o],l=i[o];i[o]=(...u)=>{let h=a.apply(i,u);return h===!1&&(h=l.apply(i,u)),h||""}}r.renderer=i}if(t.tokenizer){let i=this.defaults.tokenizer||new xt(this.defaults);for(let s in t.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let o=s,a=t.tokenizer[o],l=i[o];i[o]=(...u)=>{let h=a.apply(i,u);return h===!1&&(h=l.apply(i,u)),h}}r.tokenizer=i}if(t.hooks){let i=this.defaults.hooks||new Le;for(let s in t.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let o=s,a=t.hooks[o],l=i[o];Le.passThroughHooks.has(s)?i[o]=u=>{if(this.defaults.async&&Le.passThroughHooksRespectAsync.has(s))return(async()=>{let d=await a.call(i,u);return l.call(i,d)})();let h=a.call(i,u);return l.call(i,h)}:i[o]=(...u)=>{if(this.defaults.async)return(async()=>{let d=await a.apply(i,u);return d===!1&&(d=await l.apply(i,u)),d})();let h=a.apply(i,u);return h===!1&&(h=l.apply(i,u)),h}}r.hooks=i}if(t.walkTokens){let i=this.defaults.walkTokens,s=t.walkTokens;r.walkTokens=function(o){let a=[];return a.push(s.call(this,o)),i&&(a=a.concat(i.call(this,o))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,n){return _.lex(e,n??this.defaults)}parser(e,n){return V.parse(e,n??this.defaults)}parseMarkdown(e){return(n,t)=>{let r={...t},i={...this.defaults,...r},s=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let o=i.hooks?await i.hooks.preprocess(n):n,a=await(i.hooks?await i.hooks.provideLexer(e):e?_.lex:_.lexInline)(o,i),l=i.hooks?await i.hooks.processAllTokens(a):a;i.walkTokens&&await Promise.all(this.walkTokens(l,i.walkTokens));let u=await(i.hooks?await i.hooks.provideParser(e):e?V.parse:V.parseInline)(l,i);return i.hooks?await i.hooks.postprocess(u):u})().catch(s);try{i.hooks&&(n=i.hooks.preprocess(n));let o=(i.hooks?i.hooks.provideLexer(e):e?_.lex:_.lexInline)(n,i);i.hooks&&(o=i.hooks.processAllTokens(o)),i.walkTokens&&this.walkTokens(o,i.walkTokens);let a=(i.hooks?i.hooks.provideParser(e):e?V.parse:V.parseInline)(o,i);return i.hooks&&(a=i.hooks.postprocess(a)),a}catch(o){return s(o)}}}onError(e,n){return t=>{if(t.message+=`
109
+ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+H(t.message+"",!0)+"</pre>";return n?Promise.resolve(r):r}if(n)return Promise.reject(t);throw t}}},be=new zd;function A(e,n){return be.parse(e,n)}A.options=A.setOptions=function(e){return be.setOptions(e),A.defaults=be.defaults,Zs(A.defaults),A};A.getDefaults=Mn;A.defaults=ke;A.use=function(...e){return be.use(...e),A.defaults=be.defaults,Zs(A.defaults),A};A.walkTokens=function(e,n){return be.walkTokens(e,n)};A.parseInline=be.parseInline;A.Parser=V;A.parser=V.parse;A.Renderer=$t;A.TextRenderer=Ln;A.Lexer=_;A.lexer=_.lex;A.Tokenizer=xt;A.Hooks=Le;A.parse=A;A.options;A.setOptions;A.use;A.walkTokens;A.parseInline;V.parse;_.lex;export{A as g,Pd as t};