diff --git "a/assets/ArtifactWorkspace-V584eUXP.js" "b/assets/ArtifactWorkspace-V584eUXP.js" new file mode 100644--- /dev/null +++ "b/assets/ArtifactWorkspace-V584eUXP.js" @@ -0,0 +1,152 @@ +var p$=Object.defineProperty;var m$=(t,e,r)=>e in t?p$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var pe=(t,e,r)=>m$(t,typeof e!="symbol"?e+"":e,r);import{d as on,r as Pr,j as b,z as U,N as uy,E as st,g as g$,X as hy,C as y$}from"./index-BZSSY1sh.js";import{u as dy,P as fy,b as py,M as v$,R as w$,W as _$,d as wh,A as b$,n as $$,L as S$,N as my,O as k$}from"./chatLaunch-CKlwqu5t.js";import"./katex.min-BSBacQyE.js";import{H as _l,a as bl,b as $l}from"./hover-card-D76WQ2tT.js";import{u as vn}from"./useQuery-ChQJ5JTK.js";import{f as x$,p as E$,T as C$}from"./github-BtOxXy1c.js";import{G as _h}from"./github-Ciw4HHJ-.js";import{r as P$,a as T$,P as gy}from"./PaperPreviewLink-Gx1cMS9v.js";import{M as R$,r as A$,d as M$}from"./index-D18Nk99v.js";import{c as vp}from"./chat-D1LnB_ZX.js";import{F as I$}from"./file-text-1mzaYcQV.js";import{u as Io}from"./useMutation-D9jgIdpk.js";import{E as O$}from"./external-link-okvHh2tI.js";/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const N$=on("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Hc=on("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const bh=on("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const j$=on("FilePlus2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}],["path",{d:"M6 12v6",key:"1u72j0"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const D$=on("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yy=on("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const L$=on("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const z$=on("ThumbsDown",[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const F$=on("ThumbsUp",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);function Sl({selection:t,editable:e=!1,onRemove:r}){const n=Pr.useId(),s=Pr.useRef(null),[i,o]=Pr.useState(!1),[a,l]=Pr.useState(!1),c=`Selection · Page ${t.page}`;return Pr.useEffect(()=>{const u=s.current;!u||i||l(u.scrollHeight>u.clientHeight+1)},[i,t.text]),b.jsxs("div",{className:`chat-paper-selection${e?" is-editable":""}`,children:[b.jsxs("div",{className:"chat-paper-selection-header",children:[b.jsx("span",{className:"chat-paper-selection-label",children:c}),b.jsxs("div",{className:"chat-paper-selection-actions",children:[(a||i)&&b.jsx("button",{type:"button",className:"chat-paper-selection-toggle","aria-expanded":i,"aria-controls":n,onClick:()=>o(u=>!u),children:i?"Collapse":"Expand"}),e&&r&&b.jsx("button",{type:"button",className:"chat-paper-selection-remove","aria-label":"Remove selected paper passage",onClick:r,children:"Remove"})]})]}),b.jsx("blockquote",{id:n,ref:s,className:`chat-paper-selection-quote${i?" is-expanded":""}`,children:t.text})]})}const q$=$$(),aH=({onSend:t,busy:e,placeholder:r,autoFocus:n,draft:s,onDraftChange:i,onStop:o,models:a=[],selectedModel:l,onModelChange:c,disabled:u=!1,describedBy:h,paperMentionsEnabled:d=!1,paperSelectionEnabled:f=!0,webSearchAvailable:p=!1,webSearchEnabled:y=!1,onWebSearchChange:v,reasoningEffort:m="low",onReasoningEffortChange:_,paperArtifactsEnabled:$=!1})=>{const[E,x]=Pr.useState(q$),P=s??E,R=Pr.useRef(null),[z,L]=Pr.useState(0),H=G=>{s||x(G),i==null||i(G)},O=dy({draft:P,onChange:H,enabled:d,textareaRef:R});Pr.useEffect(()=>{const G=R.current;G&&(G.style.height="auto",G.style.height=`${Math.min(G.scrollHeight,200)}px`)},[P.text]),Pr.useEffect(()=>{var G;n&&((G=R.current)==null||G.focus())},[n]);const B=()=>{const G=P.text.length-P.text.trimStart().length,re=P.text.trim(),Oe=!!P.paperSelection&&!f;if(!re||e||u||Oe)return;const Ee=G+re.length,M={text:re,paperMentions:P.paperMentions.filter(S=>S.start>=G&&S.end<=Ee).map(S=>({...S,start:S.start-G,end:S.end-G})),...P.paperSelection?{paperSelection:P.paperSelection}:{}};t(M)},Z=!!P.paperSelection&&!f,I=!!P.text.trim()&&!Z,Q=$&&P.text==="/";return b.jsxs("div",{className:"chat-composer",children:[P.paperSelection&&b.jsx(Sl,{selection:P.paperSelection,editable:!0,onRemove:()=>{var G;H({text:P.text,paperMentions:P.paperMentions}),(G=R.current)==null||G.focus()}}),Z&&b.jsx("div",{className:"chat-paper-selection-disabled",role:"status",children:"Paper selection is currently disabled. Remove the selected passage or wait for the feature to recover."}),b.jsxs("div",{className:"chat-composer-textarea-wrap",children:[b.jsx(fy,{text:P.text,mentions:P.paperMentions,scrollTop:z}),b.jsx("textarea",{ref:R,rows:1,value:P.text,placeholder:r||(P.paperSelection?"Ask about this selection…":"Ask anything about research…"),onChange:G=>O.updateText(G.target.value,G.target.selectionStart),onSelect:G=>O.refresh(G.currentTarget.selectionStart),onClick:G=>O.refresh(G.currentTarget.selectionStart),onScroll:G=>L(G.currentTarget.scrollTop),onBlur:G=>{var re,Oe;(Oe=(re=G.relatedTarget)==null?void 0:re.closest)!=null&&Oe.call(re,".chat-paper-picker, .chat-slash-command")||window.setTimeout(O.close,0)},onKeyDown:G=>{O.keyDown(G)||G.key==="Enter"&&!G.shiftKey&&!G.nativeEvent.isComposing&&(G.preventDefault(),B())},role:"combobox","aria-expanded":O.open||Q,"aria-controls":O.open?O.pickerId:Q?"chat-write-paper-command":void 0,"aria-activedescendant":O.open&&O.results.length?`${O.optionIdPrefix}-${O.activeIndex}`:Q?"chat-write-paper-command":void 0,"aria-autocomplete":"list","aria-describedby":[h,O.message?"chat-paper-mention-message":null].filter(Boolean).join(" ")||void 0}),b.jsx(py,{open:O.open,query:O.query,results:O.results,activeIndex:O.activeIndex,loading:O.loading,error:O.error,onSelect:O.select,id:O.pickerId,optionIdPrefix:O.optionIdPrefix}),Q&&b.jsxs("button",{type:"button",id:"chat-write-paper-command",className:"chat-slash-command",role:"option",onMouseDown:G=>{var re;G.preventDefault(),H({...P,text:"/write-paper "}),(re=R.current)==null||re.focus()},children:[b.jsx("code",{children:"/write-paper"}),b.jsx("span",{children:"Draft a paper from this research chat"})]})]}),O.message&&b.jsx("div",{id:"chat-paper-mention-message",className:"chat-paper-mention-message",role:"alert",children:O.message}),b.jsxs("div",{className:"chat-composer-row",children:[b.jsxs("div",{className:"chat-composer-tools",children:[a.length>0&&l&&c&&b.jsx(v$,{models:a,selectedModel:l,onModelChange:c,disabled:e}),_&&b.jsx(w$,{value:m,onChange:_,disabled:e}),p&&v&&b.jsx(_$,{enabled:y,onChange:v,disabled:e}),b.jsx("span",{className:"chat-composer-hint",children:"Enter to send · Shift+Enter for newline"})]}),b.jsx("button",{type:"button",className:`chat-send${e||I?" chat-send-on":""}`,onClick:e?o:B,disabled:u||(e?!o:!I),"aria-label":e?"Stop generating":"Send message",children:e?o?b.jsx("span",{"aria-hidden":"true",children:"■"}):b.jsx(wh,{light:!0}):b.jsx(b$,{})})]})]})},rc=new Map,vy=t=>{if(!t)return Promise.resolve();const e=rc.get(t);if(e)return e;const r=new Promise(n=>{const s=new Image;s.onload=()=>{n()},s.onerror=()=>{rc.delete(t),n()},s.src=t});return rc.set(t,r),r},B$=new Set(["huggingface.co","www.huggingface.co"]),V$=new Set(["api","blog","chat","collections","docs","enterprise","join","login","models","new","organizations","papers","posts","pricing","search","settings","spaces","tasks"]);function H$(t){let e;try{e=new URL(t)}catch{return null}if(e.protocol!=="https:"||!B$.has(e.hostname))return null;const r=e.pathname.split("/").filter(Boolean),n=r[0]==="datasets"?"dataset":"model",s=n==="dataset"?r.slice(1):r;if(s.length!==2||n==="model"&&V$.has(s[0])||s.some(c=>!c||c==="."||c===".."))return null;const i=s.join("/"),o=s.map(encodeURIComponent).join("/"),a=n==="dataset"?`datasets/${o}`:o,l=n==="dataset"?"datasets":"models";return{type:n,repoId:i,url:`https://huggingface.co/${a}`,thumbnailUrl:`https://cdn-thumbnails.huggingface.co/social-thumbnails/${l}/${o}.png`}}const U$=()=>typeof window.matchMedia=="function"&&window.matchMedia("(hover: none), (pointer: coarse)").matches,W$=({repo:t})=>{const[e,r]=U.useState(!1);return b.jsxs("div",{className:"hf-preview-card",children:[e?b.jsx("div",{className:"hf-preview-fallback","aria-hidden":"true",children:"🤗"}):b.jsx("img",{className:"hf-preview-image","data-testid":"hf-preview-image",src:t.thumbnailUrl,alt:"",loading:"eager",decoding:"async",onError:()=>r(!0)}),b.jsxs("div",{className:"hf-preview-meta",children:[b.jsxs("span",{className:"hf-preview-kind",children:["Hugging Face ",t.type]}),b.jsx("strong",{children:t.repoId}),b.jsx("span",{children:"huggingface.co"})]})]})},K$=({repo:t,children:e})=>{const[r,n]=U.useState(!1),s=U.useRef(null),i=U.useCallback(()=>{vy(t.thumbnailUrl)},[t.thumbnailUrl]);return U.useEffect(()=>{const o=s.current;if(!o||typeof IntersectionObserver>"u")return;const a=new IntersectionObserver(([l])=>{l.isIntersecting&&(i(),a.disconnect())},{rootMargin:"200px"});return a.observe(o),()=>a.disconnect()},[i]),b.jsxs(_l,{open:r,onOpenChange:o=>{(!o||!U$())&&n(o)},openDelay:150,closeDelay:100,children:[b.jsx(bl,{asChild:!0,children:b.jsx("a",{ref:s,className:"chat-paper-link chat-hf-link",href:t.url,target:"_blank",rel:"noopener noreferrer",onPointerEnter:i,onFocus:i,children:e})}),b.jsx($l,{className:"hf-preview-pop",side:"bottom",align:"start",collisionPadding:12,children:b.jsx(W$,{repo:t})})]})},Z$=()=>typeof window.matchMedia=="function"&&window.matchMedia("(hover: none), (pointer: coarse)").matches,G$=({repo:t,preview:e,unavailable:r})=>{const[n,s]=U.useState(!1),i=!!(e!=null&&e.avatarUrl)&&!n;return b.jsxs("div",{className:"github-preview-card",children:[i?b.jsx("img",{className:"github-preview-image","data-testid":"github-preview-image",src:e==null?void 0:e.avatarUrl,alt:"",loading:"eager",decoding:"async",onError:()=>s(!0)}):b.jsx("div",{className:"github-preview-fallback","aria-hidden":"true",children:b.jsx(_h,{})}),b.jsxs("div",{className:"github-preview-meta",children:[b.jsx("span",{className:"github-preview-kind",children:"GitHub repository"}),b.jsx("strong",{children:t.repoId}),(e==null?void 0:e.description)&&b.jsx("span",{className:"github-preview-description",children:e.description}),e?b.jsxs("span",{className:"github-preview-stats",children:[e.language&&b.jsxs(b.Fragment,{children:[e.language," · "]}),"★ ",e.stars.toLocaleString()," · ⑂ ",e.forks.toLocaleString(),e.archived&&b.jsx(b.Fragment,{children:" · Archived"})]}):b.jsx("span",{children:r?"Preview unavailable":"Loading preview…"})]})]})},J$=({repo:t,children:e})=>{var c;const[r,n]=U.useState(!1),[s,i]=U.useState(!1),o=U.useRef(null),a=U.useCallback(()=>i(!0),[]),l=vn({queryKey:["github-repository-preview",t.repoId.toLowerCase()],queryFn:({signal:u})=>x$(t,u),enabled:r||s,staleTime:30*60*1e3,gcTime:60*60*1e3,retry:!1});return U.useEffect(()=>{const u=o.current;if(!u||typeof IntersectionObserver>"u")return;const h=new IntersectionObserver(([d])=>{d.isIntersecting&&(a(),h.disconnect())},{rootMargin:"200px"});return h.observe(u),()=>h.disconnect()},[a]),U.useEffect(()=>{var u;(u=l.data)!=null&&u.avatarUrl&&vy(l.data.avatarUrl)},[(c=l.data)==null?void 0:c.avatarUrl]),b.jsxs(_l,{open:r,onOpenChange:u=>{(!u||!Z$())&&n(u)},openDelay:150,closeDelay:100,children:[b.jsx(bl,{asChild:!0,children:b.jsxs("a",{ref:o,className:"chat-github-link",href:t.url,target:"_blank",rel:"noopener noreferrer",onPointerEnter:a,onFocus:a,children:[b.jsx(_h,{"aria-hidden":"true"}),e]})}),b.jsx($l,{className:"github-preview-pop",side:"bottom",align:"start",collisionPadding:12,children:b.jsx(G$,{repo:t,preview:l.data,unavailable:l.isError})})]})},Y$=()=>typeof window.matchMedia=="function"&&window.matchMedia("(hover: none), (pointer: coarse)").matches;function Q$(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return"Web source"}}const X$=({citation:t})=>{const[e,r]=U.useState(!1),[n,s]=U.useState(!1),i=t.thumbnail_url,o=t.favicon_url;return b.jsxs("div",{className:"web-preview-card",children:[i&&!e&&b.jsx("img",{className:"web-preview-image","data-testid":"web-preview-image",src:i,alt:"",loading:"eager",decoding:"async",referrerPolicy:"no-referrer",onError:()=>r(!0)}),b.jsxs("div",{className:"web-preview-meta",children:[b.jsxs("div",{className:"web-preview-source",children:[o&&!n&&b.jsx("img",{src:o,alt:"",loading:"eager",decoding:"async",referrerPolicy:"no-referrer",onError:()=>s(!0)}),b.jsx("span",{children:Q$(t.url??"")}),t.published&&b.jsxs(b.Fragment,{children:[b.jsx("span",{"aria-hidden":"true",children:"·"}),b.jsx("time",{children:t.published.slice(0,10)})]})]}),b.jsx("strong",{children:t.title}),t.excerpt&&b.jsx("p",{children:t.excerpt.replace(/\s+/g," ").trim()})]})]})},e1=({citation:t,children:e})=>{const[r,n]=U.useState(!1),s=t.url??"";return b.jsxs(_l,{open:r,onOpenChange:i=>{(!i||!Y$())&&n(i)},openDelay:150,closeDelay:100,children:[b.jsx(bl,{asChild:!0,children:b.jsx("a",{href:s,className:"chat-web-citation",target:"_blank",rel:"noopener noreferrer",children:e})}),b.jsx($l,{className:"web-preview-pop",side:"bottom",align:"start",collisionPadding:12,children:b.jsx(X$,{citation:t})})]})},t1=()=>typeof window.matchMedia=="function"&&window.matchMedia("(hover: none), (pointer: coarse)").matches,r1=t=>t==="semantic_scholar"?"Semantic Scholar":"External paper",n1=({citation:t})=>{var e,r;return b.jsxs("div",{className:"external-paper-preview-card",children:[b.jsxs("div",{className:"external-paper-preview-source",children:[b.jsx("span",{children:r1(t.provider)}),t.published&&b.jsxs(b.Fragment,{children:[b.jsx("span",{"aria-hidden":"true",children:"·"}),b.jsx("time",{children:t.published.slice(0,10)})]})]}),b.jsx("strong",{children:t.title}),(((e=t.authors)==null?void 0:e.length)??0)>0&&b.jsx("p",{className:"external-paper-preview-authors",children:(r=t.authors)==null?void 0:r.join(", ")}),t.excerpt&&b.jsx("p",{children:t.excerpt.replace(/\s+/g," ").trim()}),t.citation_count!==null&&t.citation_count!==void 0&&b.jsxs("span",{className:"external-paper-preview-citations",children:[t.citation_count.toLocaleString()," citations"]})]})},s1=({citation:t,children:e})=>{const[r,n]=U.useState(!1);return b.jsxs(_l,{open:r,onOpenChange:s=>{(!s||!t1())&&n(s)},openDelay:150,closeDelay:100,children:[b.jsx(bl,{asChild:!0,children:b.jsx("a",{href:t.url??"",className:"chat-external-paper-citation",target:"_blank",rel:"noopener noreferrer",children:e})}),b.jsx($l,{className:"external-paper-preview-pop",side:"bottom",align:"start",collisionPadding:12,children:b.jsx(n1,{citation:t})})]})};function i1(t){const e=[];let r=0,n=null;for(const s of t.match(/.*(?:\n|$)/g)??[]){if(!s)continue;const i=s.endsWith(` +`)?s.slice(0,-1):s;if(n){const l=i.match(/^ {0,3}(`+|~+)[ \t]*$/);l&&l[1][0]===n.marker&&l[1].length>=n.length&&(e.push({start:n.start,end:r+s.length}),n=null),r+=s.length;continue}const o=i.match(/^ {0,3}(`{3,}|~{3,})/);if(o){n={marker:o[1][0],length:o[1].length,start:r},r+=s.length;continue}let a=0;for(;ae>=r.start&&e=0&&t[n]==="\\";n-=1)r+=1;return r%2===0}function bp(t,e,r,n){const s=[];let i=0;for(;in.name),published:e.metadata.published,conference:e.metadata.conference,citationCount:e.metadata.citation_count,tasks:e.metadata.tasks};if(r)return{routeId:t,title:r.title,arxivId:r.arxiv_id??null,source:r.arxiv_id?"arxiv":"external",sourceUrl:r.source_url,thumbnailUrl:r.thumbnail_url??null,authors:r.authors??[],published:r.published??null,conference:r.conference??null,citationCount:r.citation_count??null,tasks:[]}}const wy=({routeId:t,paper:e,citation:r,className:n="chat-paper-link",children:s})=>b.jsx(gy,{routeId:t,initialData:a1(t,e,r),className:n,target:"_blank",children:s});function l1(t){const e=t.lastIndexOf("[");if(e===-1)return t;const r=t.slice(e);return/^\[[^\]]*(\]\(?[^)\s]*)?$/.test(r)?t.slice(0,e):t}const c1=t=>t.startsWith("paper:")?t:M$(t);function u1(t){try{const e=new URL(t);return e.protocol==="https:"&&(e.hostname==="github.com"||e.hostname==="www.github.com")}catch{return!1}}const Uc=({text:t,streaming:e,papers:r,citations:n,webCitations:s})=>{const i=o1(e?l1(t):t);return b.jsx(R$,{remarkPlugins:[A$,T$],rehypePlugins:[P$],urlTransform:c1,components:{a:({href:o,children:a})=>{if(o!=null&&o.startsWith("paper:")){const u=o.slice(6);return!r[u]&&!(n!=null&&n[u])?b.jsx("span",{className:"chat-invalid-citation",children:a}):b.jsx(wy,{routeId:u,paper:r[u],citation:n==null?void 0:n[u],children:a})}const l=o?H$(o):null;if(l)return b.jsx(K$,{repo:l,children:a});const c=o?E$(o):null;return c?b.jsx(J$,{repo:c,children:a}):o&&u1(o)?b.jsxs("a",{href:o,className:"chat-github-link",target:"_blank",rel:"noopener noreferrer",children:[b.jsx(_h,{"aria-hidden":"true"}),a]}):o!=null&&o.startsWith("https://")&&(s!=null&&s[o])?s[o].source_type==="paper"?b.jsx(s1,{citation:s[o],children:a}):b.jsx(e1,{citation:s[o],children:a}):o!=null&&o.startsWith("https://")?b.jsx("a",{href:o,className:"chat-external-link",target:"_blank",rel:"noopener noreferrer",children:a}):b.jsx("span",{children:a})}},children:i})},h1=Object.freeze({status:"aborted"});function q(t,e,r){function n(a,l){var c;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(c=a._zod).traits??(c.traits=new Set),a._zod.traits.add(t),e(a,l);for(const u in o.prototype)u in a||Object.defineProperty(a,u,{value:o.prototype[u].bind(a)});a._zod.constr=o,a._zod.def=l}const s=(r==null?void 0:r.Parent)??Object;class i extends s{}Object.defineProperty(i,"name",{value:t});function o(a){var l;const c=r!=null&&r.Parent?new i:this;n(c,a),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>{var l,c;return r!=null&&r.Parent&&a instanceof r.Parent?!0:(c=(l=a==null?void 0:a._zod)==null?void 0:l.traits)==null?void 0:c.has(t)}}),Object.defineProperty(o,"name",{value:t}),o}class Ki extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const _y={};function Pn(t){return _y}function d1(t){const e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function f1(t,e){return typeof e=="bigint"?e.toString():e}function $h(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Sh(t){return t==null}function kh(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function p1(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}function He(t,e,r){Object.defineProperty(t,e,{get(){{const n=r();return t[e]=n,n}},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function kl(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function fi(t){return JSON.stringify(t)}const by=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ia(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const m1=$h(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Oa(t){if(Ia(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(Ia(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const g1=new Set(["string","number","symbol"]);function co(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ps(t,e,r){const n=new t._zod.constr(e??t._zod.def);return(!e||r!=null&&r.parent)&&(n._zod.parent=t),n}function se(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function y1(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const v1={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function w1(t,e){const r={},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return ps(t,{...t._zod.def,shape:r,checks:[]})}function _1(t,e){const r={...t._zod.def.shape},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return ps(t,{...t._zod.def,shape:r,checks:[]})}function b1(t,e){if(!Oa(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const n={...t._zod.def.shape,...e};return kl(this,"shape",n),n},checks:[]};return ps(t,r)}function $1(t,e){return ps(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return kl(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function S1(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=t?new t({type:"optional",innerType:n[i]}):n[i])}else for(const i in n)s[i]=t?new t({type:"optional",innerType:n[i]}):n[i];return ps(e,{...e._zod.def,shape:s,checks:[]})}function k1(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new t({type:"nonoptional",innerType:n[i]}))}else for(const i in n)s[i]=new t({type:"nonoptional",innerType:n[i]});return ps(e,{...e._zod.def,shape:s,checks:[]})}function Ri(t,e=0){var r;for(let n=e;n{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Oo(t){return typeof t=="string"?t:t==null?void 0:t.message}function Tn(t,e,r){var s,i,o,a,l,c;const n={...t,path:t.path??[]};if(!t.message){const u=Oo((o=(i=(s=t.inst)==null?void 0:s._zod.def)==null?void 0:i.error)==null?void 0:o.call(i,t))??Oo((a=e==null?void 0:e.error)==null?void 0:a.call(e,t))??Oo((l=r.customError)==null?void 0:l.call(r,t))??Oo((c=r.localeError)==null?void 0:c.call(r,t))??"Invalid input";n.message=u}return delete n.inst,delete n.continue,e!=null&&e.reportInput||delete n.input,n}function xh(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Zi(...t){const[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}const $y=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,f1,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Sy=q("$ZodError",$y),ky=q("$ZodError",$y,{Parent:Error});function x1(t,e=r=>r.message){const r={},n=[];for(const s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function E1(t,e){const r=e||function(i){return i.message},n={_errors:[]},s=i=>{for(const o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>s({issues:a}));else if(o.code==="invalid_key")s({issues:o.issues});else if(o.code==="invalid_element")s({issues:o.issues});else if(o.path.length===0)n._errors.push(r(o));else{let a=n,l=0;for(;l(e,r,n,s)=>{const i=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new Ki;if(o.issues.length){const a=new((s==null?void 0:s.Err)??t)(o.issues.map(l=>Tn(l,i,Pn())));throw by(a,s==null?void 0:s.callee),a}return o.value},P1=t=>async(e,r,n,s)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){const a=new((s==null?void 0:s.Err)??t)(o.issues.map(l=>Tn(l,i,Pn())));throw by(a,s==null?void 0:s.callee),a}return o.value},xy=t=>(e,r,n)=>{const s=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ki;return i.issues.length?{success:!1,error:new(t??Sy)(i.issues.map(o=>Tn(o,s,Pn())))}:{success:!0,data:i.value}},Ey=xy(ky),Cy=t=>async(e,r,n)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let i=e._zod.run({value:r,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(o=>Tn(o,s,Pn())))}:{success:!0,data:i.value}},T1=Cy(ky),R1=/^[cC][^\s-]{8,}$/,A1=/^[0-9a-z]+$/,M1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,I1=/^[0-9a-vA-V]{20}$/,O1=/^[A-Za-z0-9]{27}$/,N1=/^[a-zA-Z0-9_-]{21}$/,j1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,D1=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,$p=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,L1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,z1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function F1(){return new RegExp(z1,"u")}const q1=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,B1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,V1=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,H1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,U1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Py=/^[A-Za-z0-9_-]*$/,W1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,K1=/^\+(?:[0-9]){6,14}[0-9]$/,Ty="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Z1=new RegExp(`^${Ty}$`);function Ry(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function G1(t){return new RegExp(`^${Ry(t)}$`)}function J1(t){const e=Ry({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Ty}T(?:${n})$`)}const Y1=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Q1=/^\d+$/,X1=/^-?\d+(?:\.\d+)?/i,eS=/true|false/i,tS=/null/i,rS=/undefined/i,nS=/^[^A-Z]*$/,sS=/^[^a-z]*$/,Vt=q("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Ay={number:"number",bigint:"bigint",object:"date"},My=q("$ZodCheckLessThan",(t,e)=>{Vt.init(t,e);const r=Ay[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,i=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{Vt.init(t,e);const r=Ay[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,i=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),iS=q("$ZodCheckMultipleOf",(t,e)=>{Vt.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):p1(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),oS=q("$ZodCheckNumberFormat",(t,e)=>{var o;Vt.init(t,e),e.format=e.format||"float64";const r=(o=e.format)==null?void 0:o.includes("int"),n=r?"int":"number",[s,i]=v1[e.format];t._zod.onattach.push(a=>{const l=a._zod.bag;l.format=e.format,l.minimum=s,l.maximum=i,r&&(l.pattern=Q1)}),t._zod.check=a=>{const l=a.value;if(r){if(!Number.isInteger(l)){a.issues.push({expected:n,format:e.format,code:"invalid_type",input:l,inst:t});return}if(!Number.isSafeInteger(l)){l>0?a.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):a.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}li&&a.issues.push({origin:"number",input:l,code:"too_big",maximum:i,inst:t})}}),aS=q("$ZodCheckMaxLength",(t,e)=>{var r;Vt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!Sh(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{const s=n.value;if(s.length<=e.maximum)return;const o=xh(s);n.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),lS=q("$ZodCheckMinLength",(t,e)=>{var r;Vt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!Sh(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{const s=n.value;if(s.length>=e.minimum)return;const o=xh(s);n.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),cS=q("$ZodCheckLengthEquals",(t,e)=>{var r;Vt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!Sh(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{const s=n.value,i=s.length;if(i===e.length)return;const o=xh(s),a=i>e.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),xl=q("$ZodCheckStringFormat",(t,e)=>{var r,n;Vt.init(t,e),t._zod.onattach.push(s=>{const i=s._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),uS=q("$ZodCheckRegex",(t,e)=>{xl.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),hS=q("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=nS),xl.init(t,e)}),dS=q("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=sS),xl.init(t,e)}),fS=q("$ZodCheckIncludes",(t,e)=>{Vt.init(t,e);const r=co(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{const i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),pS=q("$ZodCheckStartsWith",(t,e)=>{Vt.init(t,e);const r=new RegExp(`^${co(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),mS=q("$ZodCheckEndsWith",(t,e)=>{Vt.init(t,e);const r=new RegExp(`.*${co(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),gS=q("$ZodCheckOverwrite",(t,e)=>{Vt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class yS{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const n=e.split(` +`).filter(o=>o),s=Math.min(...n.map(o=>o.length-o.trimStart().length)),i=n.map(o=>o.slice(s)).map(o=>" ".repeat(this.indent*2)+o);for(const o of i)this.content.push(o)}compile(){const e=Function,r=this==null?void 0:this.args,s=[...((this==null?void 0:this.content)??[""]).map(i=>` ${i}`)];return new e(...r,s.join(` +`))}}const vS={major:4,minor:0,patch:0},Fe=q("$ZodType",(t,e)=>{var s;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=vS;const n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(const i of n)for(const o of i._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),(s=t._zod.deferred)==null||s.push(()=>{t._zod.run=t._zod.parse});else{const i=(o,a,l)=>{let c=Ri(o),u;for(const h of a){if(h._zod.def.when){if(!h._zod.def.when(o))continue}else if(c)continue;const d=o.issues.length,f=h._zod.check(o);if(f instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Ki;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,o.issues.length!==d&&(c||(c=Ri(o,d)))});else{if(o.issues.length===d)continue;c||(c=Ri(o,d))}}return u?u.then(()=>o):o};t._zod.run=(o,a)=>{const l=t._zod.parse(o,a);if(l instanceof Promise){if(a.async===!1)throw new Ki;return l.then(c=>i(c,n,a))}return i(l,n,a)}}t["~standard"]={validate:i=>{var o;try{const a=Ey(t,i);return a.success?{value:a.data}:{issues:(o=a.error)==null?void 0:o.issues}}catch{return T1(t,i).then(l=>{var c;return l.success?{value:l.data}:{issues:(c=l.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),Eh=q("$ZodString",(t,e)=>{var r;Fe.init(t,e),t._zod.pattern=[...((r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)??[]].pop()??Y1(t._zod.bag),t._zod.parse=(n,s)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),Ze=q("$ZodStringFormat",(t,e)=>{xl.init(t,e),Eh.init(t,e)}),wS=q("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=D1),Ze.init(t,e)}),_S=q("$ZodUUID",(t,e)=>{if(e.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=$p(n))}else e.pattern??(e.pattern=$p());Ze.init(t,e)}),bS=q("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=L1),Ze.init(t,e)}),$S=q("$ZodURL",(t,e)=>{Ze.init(t,e),t._zod.check=r=>{try{const n=r.value,s=new URL(n),i=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:W1.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),SS=q("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=F1()),Ze.init(t,e)}),kS=q("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=N1),Ze.init(t,e)}),xS=q("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=R1),Ze.init(t,e)}),ES=q("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=A1),Ze.init(t,e)}),CS=q("$ZodULID",(t,e)=>{e.pattern??(e.pattern=M1),Ze.init(t,e)}),PS=q("$ZodXID",(t,e)=>{e.pattern??(e.pattern=I1),Ze.init(t,e)}),TS=q("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=O1),Ze.init(t,e)}),RS=q("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=J1(e)),Ze.init(t,e)}),AS=q("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Z1),Ze.init(t,e)}),MS=q("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=G1(e)),Ze.init(t,e)}),IS=q("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=j1),Ze.init(t,e)}),OS=q("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=q1),Ze.init(t,e),t._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),NS=q("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=B1),Ze.init(t,e),t._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),jS=q("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=V1),Ze.init(t,e)}),DS=q("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=H1),Ze.init(t,e),t._zod.check=r=>{const[n,s]=r.value.split("/");try{if(!s)throw new Error;const i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Oy(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const LS=q("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=U1),Ze.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Oy(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function zS(t){if(!Py.test(t))return!1;const e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Oy(r)}const FS=q("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Py),Ze.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{zS(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),qS=q("$ZodE164",(t,e)=>{e.pattern??(e.pattern=K1),Ze.init(t,e)});function BS(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const s=JSON.parse(atob(n));return!("typ"in s&&(s==null?void 0:s.typ)!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const VS=q("$ZodJWT",(t,e)=>{Ze.init(t,e),t._zod.check=r=>{BS(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ny=q("$ZodNumber",(t,e)=>{Fe.init(t,e),t._zod.pattern=t._zod.bag.pattern??X1,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const s=r.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;const i=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...i?{received:i}:{}}),r}}),HS=q("$ZodNumber",(t,e)=>{oS.init(t,e),Ny.init(t,e)}),US=q("$ZodBoolean",(t,e)=>{Fe.init(t,e),t._zod.pattern=eS,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}const s=r.value;return typeof s=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),r}}),WS=q("$ZodUndefined",(t,e)=>{Fe.init(t,e),t._zod.pattern=rS,t._zod.values=new Set([void 0]),t._zod.optin="optional",t._zod.optout="optional",t._zod.parse=(r,n)=>{const s=r.value;return typeof s>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:s,inst:t}),r}}),KS=q("$ZodNull",(t,e)=>{Fe.init(t,e),t._zod.pattern=tS,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{const s=r.value;return s===null||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}}),ZS=q("$ZodAny",(t,e)=>{Fe.init(t,e),t._zod.parse=r=>r}),GS=q("$ZodUnknown",(t,e)=>{Fe.init(t,e),t._zod.parse=r=>r}),JS=q("$ZodNever",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Sp(t,e,r){t.issues.length&&e.issues.push(...Qn(r,t.issues)),e.value[r]=t.value}const YS=q("$ZodArray",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),r;r.value=Array(s.length);const i=[];for(let o=0;oSp(c,r,o))):Sp(l,r,o)}return i.length?Promise.all(i).then(()=>r):r}});function No(t,e,r){t.issues.length&&e.issues.push(...Qn(r,t.issues)),e.value[r]=t.value}function kp(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Qn(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}const QS=q("$ZodObject",(t,e)=>{Fe.init(t,e);const r=$h(()=>{const h=Object.keys(e.shape);for(const f of h)if(!(e.shape[f]instanceof Fe))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);const d=y1(e.shape);return{shape:e.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(d)}});He(t._zod,"propValues",()=>{const h=e.shape,d={};for(const f in h){const p=h[f]._zod;if(p.values){d[f]??(d[f]=new Set);for(const y of p.values)d[f].add(y)}}return d});const n=h=>{const d=new yS(["shape","payload","ctx"]),f=r.value,p=_=>{const $=fi(_);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};d.write("const input = payload.value;");const y=Object.create(null);let v=0;for(const _ of f.keys)y[_]=`key_${v++}`;d.write("const newResult = {}");for(const _ of f.keys)if(f.optionalKeys.has(_)){const $=y[_];d.write(`const ${$} = ${p(_)};`);const E=fi(_);d.write(` + if (${$}.issues.length) { + if (input[${E}] === undefined) { + if (${E} in input) { + newResult[${E}] = undefined; + } + } else { + payload.issues = payload.issues.concat( + ${$}.issues.map((iss) => ({ + ...iss, + path: iss.path ? [${E}, ...iss.path] : [${E}], + })) + ); + } + } else if (${$}.value === undefined) { + if (${E} in input) newResult[${E}] = undefined; + } else { + newResult[${E}] = ${$}.value; + } + `)}else{const $=y[_];d.write(`const ${$} = ${p(_)};`),d.write(` + if (${$}.issues.length) payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${fi(_)}, ...iss.path] : [${fi(_)}] + })));`),d.write(`newResult[${fi(_)}] = ${$}.value`)}d.write("payload.value = newResult;"),d.write("return payload;");const m=d.compile();return(_,$)=>m(h,_,$)};let s;const i=Ia,o=!_y.jitless,l=o&&m1.value,c=e.catchall;let u;t._zod.parse=(h,d)=>{u??(u=r.value);const f=h.value;if(!i(f))return h.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),h;const p=[];if(o&&l&&(d==null?void 0:d.async)===!1&&d.jitless!==!0)s||(s=n(e.shape)),h=s(h,d);else{h.value={};const $=u.shape;for(const E of u.keys){const x=$[E],P=x._zod.run({value:f[E],issues:[]},d),R=x._zod.optin==="optional"&&x._zod.optout==="optional";P instanceof Promise?p.push(P.then(z=>R?kp(z,h,E,f):No(z,h,E))):R?kp(P,h,E,f):No(P,h,E)}}if(!c)return p.length?Promise.all(p).then(()=>h):h;const y=[],v=u.keySet,m=c._zod,_=m.def.type;for(const $ of Object.keys(f)){if(v.has($))continue;if(_==="never"){y.push($);continue}const E=m.run({value:f[$],issues:[]},d);E instanceof Promise?p.push(E.then(x=>No(x,h,$))):No(E,h,$)}return y.length&&h.issues.push({code:"unrecognized_keys",keys:y,input:f,inst:t}),p.length?Promise.all(p).then(()=>h):h}});function xp(t,e,r,n){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>Tn(i,n,Pn())))}),e}const jy=q("$ZodUnion",(t,e)=>{Fe.init(t,e),He(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),He(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),He(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),He(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>kh(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1;const i=[];for(const o of e.options){const a=o._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)i.push(a),s=!0;else{if(a.issues.length===0)return a;i.push(a)}}return s?Promise.all(i).then(o=>xp(o,r,t,n)):xp(i,r,t,n)}}),XS=q("$ZodDiscriminatedUnion",(t,e)=>{jy.init(t,e);const r=t._zod.parse;He(t._zod,"propValues",()=>{const s={};for(const i of e.options){const o=i._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(const[a,l]of Object.entries(o)){s[a]||(s[a]=new Set);for(const c of l)s[a].add(c)}}return s});const n=$h(()=>{const s=e.options,i=new Map;for(const o of s){const a=o._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const l of a){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,o)}}return i});t._zod.parse=(s,i)=>{const o=s.value;if(!Ia(o))return s.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),s;const a=n.value.get(o==null?void 0:o[e.discriminator]);return a?a._zod.run(s,i):e.unionFallback?r(s,i):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),s)}}),ek=q("$ZodIntersection",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,n)=>{const s=r.value,i=e.left._zod.run({value:s,issues:[]},n),o=e.right._zod.run({value:s,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([l,c])=>Ep(r,l,c)):Ep(r,i,o)}});function Wc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Oa(t)&&Oa(e)){const r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),s={...t,...e};for(const i of n){const o=Wc(t[i],e[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};s[i]=o.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n{Fe.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!Oa(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;const i=[];if(e.keyType._zod.values){const o=e.keyType._zod.values;r.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=e.valueType._zod.run({value:s[l],issues:[]},n);c instanceof Promise?i.push(c.then(u=>{u.issues.length&&r.issues.push(...Qn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...Qn(l,c.issues)),r.value[l]=c.value)}let a;for(const l in s)o.has(l)||(a=a??[],a.push(l));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{r.value={};for(const o of Reflect.ownKeys(s)){if(o==="__proto__")continue;const a=e.keyType._zod.run({value:o,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(c=>Tn(c,n,Pn())),input:o,path:[o],inst:t}),r.value[a.value]=a.value;continue}const l=e.valueType._zod.run({value:s[o],issues:[]},n);l instanceof Promise?i.push(l.then(c=>{c.issues.length&&r.issues.push(...Qn(o,c.issues)),r.value[a.value]=c.value})):(l.issues.length&&r.issues.push(...Qn(o,l.issues)),r.value[a.value]=l.value)}}return i.length?Promise.all(i).then(()=>r):r}}),rk=q("$ZodEnum",(t,e)=>{Fe.init(t,e);const r=d1(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>g1.has(typeof n)).map(n=>typeof n=="string"?co(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{const i=n.value;return t._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:t}),n}}),nk=q("$ZodLiteral",(t,e)=>{Fe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?co(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{const s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),sk=q("$ZodTransform",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,n)=>{const s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(o=>(r.value=o,r));if(s instanceof Promise)throw new Ki;return r.value=s,r}}),ik=q("$ZodOptional",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",He(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),He(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${kh(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),ok=q("$ZodNullable",(t,e)=>{Fe.init(t,e),He(t._zod,"optin",()=>e.innerType._zod.optin),He(t._zod,"optout",()=>e.innerType._zod.optout),He(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${kh(r.source)}|null)$`):void 0}),He(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),ak=q("$ZodDefault",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",He(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>Cp(i,e)):Cp(s,e)}});function Cp(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const lk=q("$ZodPrefault",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",He(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),ck=q("$ZodNonOptional",(t,e)=>{Fe.init(t,e),He(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>Pp(i,t)):Pp(s,t)}});function Pp(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const uk=q("$ZodCatch",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",He(t._zod,"optout",()=>e.innerType._zod.optout),He(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(o=>Tn(o,n,Pn()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Tn(i,n,Pn()))},input:r.value}),r.issues=[]),r)}}),hk=q("$ZodPipe",(t,e)=>{Fe.init(t,e),He(t._zod,"values",()=>e.in._zod.values),He(t._zod,"optin",()=>e.in._zod.optin),He(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{const s=e.in._zod.run(r,n);return s instanceof Promise?s.then(i=>Tp(i,e,n)):Tp(s,e,n)}});function Tp(t,e,r){return Ri(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const dk=q("$ZodReadonly",(t,e)=>{Fe.init(t,e),He(t._zod,"propValues",()=>e.innerType._zod.propValues),He(t._zod,"values",()=>e.innerType._zod.values),He(t._zod,"optin",()=>e.innerType._zod.optin),He(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(Rp):Rp(s)}});function Rp(t){return t.value=Object.freeze(t.value),t}const fk=q("$ZodCustom",(t,e)=>{Vt.init(t,e),Fe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{const n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(i=>Ap(i,r,n,t));Ap(s,r,n,t)}});function Ap(t,e,r,n){if(!t){const s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(Zi(s))}}class pk{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function mk(){return new pk}const jo=mk();function gk(t,e){return new t({type:"string",...se(e)})}function yk(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...se(e)})}function Mp(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...se(e)})}function vk(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...se(e)})}function wk(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...se(e)})}function _k(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...se(e)})}function bk(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...se(e)})}function Dy(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...se(e)})}function $k(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...se(e)})}function Sk(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...se(e)})}function kk(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...se(e)})}function xk(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...se(e)})}function Ek(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...se(e)})}function Ck(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...se(e)})}function Pk(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...se(e)})}function Tk(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...se(e)})}function Rk(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...se(e)})}function Ak(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...se(e)})}function Mk(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...se(e)})}function Ik(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...se(e)})}function Ok(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...se(e)})}function Nk(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...se(e)})}function jk(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...se(e)})}function Dk(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...se(e)})}function Lk(t,e){return new t({type:"string",format:"date",check:"string_format",...se(e)})}function zk(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...se(e)})}function Fk(t,e){return new t({type:"string",format:"duration",check:"string_format",...se(e)})}function qk(t,e){return new t({type:"number",checks:[],...se(e)})}function Bk(t,e){return new t({type:"number",coerce:!0,checks:[],...se(e)})}function Vk(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...se(e)})}function Hk(t,e){return new t({type:"boolean",...se(e)})}function Uk(t,e){return new t({type:"undefined",...se(e)})}function Wk(t,e){return new t({type:"null",...se(e)})}function Kk(t){return new t({type:"any"})}function Zk(t){return new t({type:"unknown"})}function Gk(t,e){return new t({type:"never",...se(e)})}function Ip(t,e){return new My({check:"less_than",...se(e),value:t,inclusive:!1})}function nc(t,e){return new My({check:"less_than",...se(e),value:t,inclusive:!0})}function Op(t,e){return new Iy({check:"greater_than",...se(e),value:t,inclusive:!1})}function sc(t,e){return new Iy({check:"greater_than",...se(e),value:t,inclusive:!0})}function Np(t,e){return new iS({check:"multiple_of",...se(e),value:t})}function Ly(t,e){return new aS({check:"max_length",...se(e),maximum:t})}function Na(t,e){return new lS({check:"min_length",...se(e),minimum:t})}function zy(t,e){return new cS({check:"length_equals",...se(e),length:t})}function Jk(t,e){return new uS({check:"string_format",format:"regex",...se(e),pattern:t})}function Yk(t){return new hS({check:"string_format",format:"lowercase",...se(t)})}function Qk(t){return new dS({check:"string_format",format:"uppercase",...se(t)})}function Xk(t,e){return new fS({check:"string_format",format:"includes",...se(e),includes:t})}function ex(t,e){return new pS({check:"string_format",format:"starts_with",...se(e),prefix:t})}function tx(t,e){return new mS({check:"string_format",format:"ends_with",...se(e),suffix:t})}function uo(t){return new gS({check:"overwrite",tx:t})}function rx(t){return uo(e=>e.normalize(t))}function nx(){return uo(t=>t.trim())}function sx(){return uo(t=>t.toLowerCase())}function ix(){return uo(t=>t.toUpperCase())}function ox(t,e,r){return new t({type:"array",element:e,...se(r)})}function ax(t,e,r){const n=se(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function lx(t,e,r){return new t({type:"custom",check:"custom",fn:e,...se(r)})}const cx=q("ZodISODateTime",(t,e)=>{RS.init(t,e),Je.init(t,e)});function Fy(t){return Dk(cx,t)}const ux=q("ZodISODate",(t,e)=>{AS.init(t,e),Je.init(t,e)});function hx(t){return Lk(ux,t)}const dx=q("ZodISOTime",(t,e)=>{MS.init(t,e),Je.init(t,e)});function fx(t){return zk(dx,t)}const px=q("ZodISODuration",(t,e)=>{IS.init(t,e),Je.init(t,e)});function mx(t){return Fk(px,t)}const gx=(t,e)=>{Sy.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>E1(t,r)},flatten:{value:r=>x1(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},El=q("ZodError",gx,{Parent:Error}),yx=C1(El),vx=P1(El),wx=xy(El),_x=Cy(El),Ue=q("ZodType",(t,e)=>(Fe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>ps(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>yx(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>wx(t,r,n),t.parseAsync=async(r,n)=>vx(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>_x(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(dE(r,n)),t.superRefine=r=>t.check(fE(r)),t.overwrite=r=>t.check(uo(r)),t.optional=()=>Ge(t),t.nullable=()=>Lp(t),t.nullish=()=>Ge(Lp(t)),t.nonoptional=r=>sE(t,r),t.array=()=>K(t),t.or=r=>xe([t,r]),t.and=r=>Th(t,r),t.transform=r=>Jc(t,Wy(r)),t.default=r=>tE(t,r),t.prefault=r=>nE(t,r),t.catch=r=>oE(t,r),t.pipe=r=>Jc(t,r),t.readonly=()=>cE(t),t.describe=r=>{const n=t.clone();return jo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){var r;return(r=jo.get(t))==null?void 0:r.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return jo.get(t);const n=t.clone();return jo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),qy=q("_ZodString",(t,e)=>{Eh.init(t,e),Ue.init(t,e);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Jk(...n)),t.includes=(...n)=>t.check(Xk(...n)),t.startsWith=(...n)=>t.check(ex(...n)),t.endsWith=(...n)=>t.check(tx(...n)),t.min=(...n)=>t.check(Na(...n)),t.max=(...n)=>t.check(Ly(...n)),t.length=(...n)=>t.check(zy(...n)),t.nonempty=(...n)=>t.check(Na(1,...n)),t.lowercase=n=>t.check(Yk(n)),t.uppercase=n=>t.check(Qk(n)),t.trim=()=>t.check(nx()),t.normalize=(...n)=>t.check(rx(...n)),t.toLowerCase=()=>t.check(sx()),t.toUpperCase=()=>t.check(ix())}),bx=q("ZodString",(t,e)=>{Eh.init(t,e),qy.init(t,e),t.email=r=>t.check(yk($x,r)),t.url=r=>t.check(Dy(By,r)),t.jwt=r=>t.check(jk(Lx,r)),t.emoji=r=>t.check($k(kx,r)),t.guid=r=>t.check(Mp(jp,r)),t.uuid=r=>t.check(vk(Do,r)),t.uuidv4=r=>t.check(wk(Do,r)),t.uuidv6=r=>t.check(_k(Do,r)),t.uuidv7=r=>t.check(bk(Do,r)),t.nanoid=r=>t.check(Sk(xx,r)),t.guid=r=>t.check(Mp(jp,r)),t.cuid=r=>t.check(kk(Ex,r)),t.cuid2=r=>t.check(xk(Cx,r)),t.ulid=r=>t.check(Ek(Px,r)),t.base64=r=>t.check(Ik(Nx,r)),t.base64url=r=>t.check(Ok(jx,r)),t.xid=r=>t.check(Ck(Tx,r)),t.ksuid=r=>t.check(Pk(Rx,r)),t.ipv4=r=>t.check(Tk(Ax,r)),t.ipv6=r=>t.check(Rk(Mx,r)),t.cidrv4=r=>t.check(Ak(Ix,r)),t.cidrv6=r=>t.check(Mk(Ox,r)),t.e164=r=>t.check(Nk(Dx,r)),t.datetime=r=>t.check(Fy(r)),t.date=r=>t.check(hx(r)),t.time=r=>t.check(fx(r)),t.duration=r=>t.check(mx(r))});function T(t){return gk(bx,t)}const Je=q("ZodStringFormat",(t,e)=>{Ze.init(t,e),qy.init(t,e)}),$x=q("ZodEmail",(t,e)=>{bS.init(t,e),Je.init(t,e)}),jp=q("ZodGUID",(t,e)=>{wS.init(t,e),Je.init(t,e)}),Do=q("ZodUUID",(t,e)=>{_S.init(t,e),Je.init(t,e)}),By=q("ZodURL",(t,e)=>{$S.init(t,e),Je.init(t,e)});function Sx(t){return Dy(By,t)}const kx=q("ZodEmoji",(t,e)=>{SS.init(t,e),Je.init(t,e)}),xx=q("ZodNanoID",(t,e)=>{kS.init(t,e),Je.init(t,e)}),Ex=q("ZodCUID",(t,e)=>{xS.init(t,e),Je.init(t,e)}),Cx=q("ZodCUID2",(t,e)=>{ES.init(t,e),Je.init(t,e)}),Px=q("ZodULID",(t,e)=>{CS.init(t,e),Je.init(t,e)}),Tx=q("ZodXID",(t,e)=>{PS.init(t,e),Je.init(t,e)}),Rx=q("ZodKSUID",(t,e)=>{TS.init(t,e),Je.init(t,e)}),Ax=q("ZodIPv4",(t,e)=>{OS.init(t,e),Je.init(t,e)}),Mx=q("ZodIPv6",(t,e)=>{NS.init(t,e),Je.init(t,e)}),Ix=q("ZodCIDRv4",(t,e)=>{jS.init(t,e),Je.init(t,e)}),Ox=q("ZodCIDRv6",(t,e)=>{DS.init(t,e),Je.init(t,e)}),Nx=q("ZodBase64",(t,e)=>{LS.init(t,e),Je.init(t,e)}),jx=q("ZodBase64URL",(t,e)=>{FS.init(t,e),Je.init(t,e)}),Dx=q("ZodE164",(t,e)=>{qS.init(t,e),Je.init(t,e)}),Lx=q("ZodJWT",(t,e)=>{VS.init(t,e),Je.init(t,e)}),Ch=q("ZodNumber",(t,e)=>{Ny.init(t,e),Ue.init(t,e),t.gt=(n,s)=>t.check(Op(n,s)),t.gte=(n,s)=>t.check(sc(n,s)),t.min=(n,s)=>t.check(sc(n,s)),t.lt=(n,s)=>t.check(Ip(n,s)),t.lte=(n,s)=>t.check(nc(n,s)),t.max=(n,s)=>t.check(nc(n,s)),t.int=n=>t.check(Dp(n)),t.safe=n=>t.check(Dp(n)),t.positive=n=>t.check(Op(0,n)),t.nonnegative=n=>t.check(sc(0,n)),t.negative=n=>t.check(Ip(0,n)),t.nonpositive=n=>t.check(nc(0,n)),t.multipleOf=(n,s)=>t.check(Np(n,s)),t.step=(n,s)=>t.check(Np(n,s)),t.finite=()=>t;const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ye(t){return qk(Ch,t)}const zx=q("ZodNumberFormat",(t,e)=>{HS.init(t,e),Ch.init(t,e)});function Dp(t){return Vk(zx,t)}const Fx=q("ZodBoolean",(t,e)=>{US.init(t,e),Ue.init(t,e)});function Pe(t){return Hk(Fx,t)}const qx=q("ZodUndefined",(t,e)=>{WS.init(t,e),Ue.init(t,e)});function Kc(t){return Uk(qx,t)}const Bx=q("ZodNull",(t,e)=>{KS.init(t,e),Ue.init(t,e)});function Vx(t){return Wk(Bx,t)}const Hx=q("ZodAny",(t,e)=>{ZS.init(t,e),Ue.init(t,e)});function Ph(){return Kk(Hx)}const Ux=q("ZodUnknown",(t,e)=>{GS.init(t,e),Ue.init(t,e)});function ze(){return Zk(Ux)}const Wx=q("ZodNever",(t,e)=>{JS.init(t,e),Ue.init(t,e)});function Zc(t){return Gk(Wx,t)}const Kx=q("ZodArray",(t,e)=>{YS.init(t,e),Ue.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Na(r,n)),t.nonempty=r=>t.check(Na(1,r)),t.max=(r,n)=>t.check(Ly(r,n)),t.length=(r,n)=>t.check(zy(r,n)),t.unwrap=()=>t.element});function K(t,e){return ox(Kx,t,e)}const Vy=q("ZodObject",(t,e)=>{QS.init(t,e),Ue.init(t,e),He(t,"shape",()=>e.shape),t.keyof=()=>Zt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ze()}),t.loose=()=>t.clone({...t._zod.def,catchall:ze()}),t.strict=()=>t.clone({...t._zod.def,catchall:Zc()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>b1(t,r),t.merge=r=>$1(t,r),t.pick=r=>w1(t,r),t.omit=r=>_1(t,r),t.partial=(...r)=>S1(Ky,t,r[0]),t.required=(...r)=>k1(Zy,t,r[0])});function D(t,e){const r={type:"object",get shape(){return kl(this,"shape",{...t}),this.shape},...se(e)};return new Vy(r)}function _t(t,e){return new Vy({type:"object",get shape(){return kl(this,"shape",{...t}),this.shape},catchall:ze(),...se(e)})}const Hy=q("ZodUnion",(t,e)=>{jy.init(t,e),Ue.init(t,e),t.options=e.options});function xe(t,e){return new Hy({type:"union",options:t,...se(e)})}const Zx=q("ZodDiscriminatedUnion",(t,e)=>{Hy.init(t,e),XS.init(t,e)});function Uy(t,e,r){return new Zx({type:"union",options:e,discriminator:t,...se(r)})}const Gx=q("ZodIntersection",(t,e)=>{ek.init(t,e),Ue.init(t,e)});function Th(t,e){return new Gx({type:"intersection",left:t,right:e})}const Jx=q("ZodRecord",(t,e)=>{tk.init(t,e),Ue.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Te(t,e,r){return new Jx({type:"record",keyType:t,valueType:e,...se(r)})}const Gc=q("ZodEnum",(t,e)=>{rk.init(t,e),Ue.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{const i={};for(const o of n)if(r.has(o))i[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Gc({...e,checks:[],...se(s),entries:i})},t.exclude=(n,s)=>{const i={...e.entries};for(const o of n)if(r.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new Gc({...e,checks:[],...se(s),entries:i})}});function Zt(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Gc({type:"enum",entries:r,...se(e)})}const Yx=q("ZodLiteral",(t,e)=>{nk.init(t,e),Ue.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function N(t,e){return new Yx({type:"literal",values:Array.isArray(t)?t:[t],...se(e)})}const Qx=q("ZodTransform",(t,e)=>{sk.init(t,e),Ue.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(Zi(i,r.value,e));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!0),r.issues.push(Zi(o))}};const s=e.transform(r.value,r);return s instanceof Promise?s.then(i=>(r.value=i,r)):(r.value=s,r)}});function Wy(t){return new Qx({type:"transform",transform:t})}const Ky=q("ZodOptional",(t,e)=>{ik.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ge(t){return new Ky({type:"optional",innerType:t})}const Xx=q("ZodNullable",(t,e)=>{ok.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Lp(t){return new Xx({type:"nullable",innerType:t})}const eE=q("ZodDefault",(t,e)=>{ak.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function tE(t,e){return new eE({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const rE=q("ZodPrefault",(t,e)=>{lk.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});function nE(t,e){return new rE({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const Zy=q("ZodNonOptional",(t,e)=>{ck.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});function sE(t,e){return new Zy({type:"nonoptional",innerType:t,...se(e)})}const iE=q("ZodCatch",(t,e)=>{uk.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function oE(t,e){return new iE({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const aE=q("ZodPipe",(t,e)=>{hk.init(t,e),Ue.init(t,e),t.in=e.in,t.out=e.out});function Jc(t,e){return new aE({type:"pipe",in:t,out:e})}const lE=q("ZodReadonly",(t,e)=>{dk.init(t,e),Ue.init(t,e)});function cE(t){return new lE({type:"readonly",innerType:t})}const Gy=q("ZodCustom",(t,e)=>{fk.init(t,e),Ue.init(t,e)});function uE(t){const e=new Vt({check:"custom"});return e._zod.check=t,e}function hE(t,e){return ax(Gy,t??(()=>!0),e)}function dE(t,e={}){return lx(Gy,t,e)}function fE(t){const e=uE(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Zi(n,r.value,e._zod.def));else{const s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(Zi(s))}},t(r.value,r)));return e}function Jy(t,e){return Jc(Wy(t),e)}const pE={custom:"custom"};function mE(t){return Bk(Ch,t)}const Cl="2025-11-25",gE=[Cl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Vn="io.modelcontextprotocol/related-task",Pl="2.0",lt=hE(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Yy=xe([T(),ye().int()]),Qy=T();_t({ttl:ye().optional(),pollInterval:ye().optional()});const yE=D({ttl:ye().optional()}),vE=D({taskId:T()}),Rh=_t({progressToken:Yy.optional(),[Vn]:vE.optional()}),Gt=D({_meta:Rh.optional()}),ho=Gt.extend({task:yE.optional()}),wE=t=>ho.safeParse(t).success,$t=D({method:T(),params:Gt.loose().optional()}),rr=D({_meta:Rh.optional()}),nr=D({method:T(),params:rr.loose().optional()}),St=_t({_meta:Rh.optional()}),fo=xe([T(),ye().int()]),Xy=D({jsonrpc:N(Pl),id:fo,...$t.shape}).strict(),Yc=t=>Xy.safeParse(t).success,e0=D({jsonrpc:N(Pl),...nr.shape}).strict(),_E=t=>e0.safeParse(t).success,Ah=D({jsonrpc:N(Pl),id:fo,result:St}).strict(),Si=t=>Ah.safeParse(t).success;var fe;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(fe||(fe={}));const Mh=D({jsonrpc:N(Pl),id:fo.optional(),error:D({code:ye().int(),message:T(),data:ze().optional()})}).strict(),bE=t=>Mh.safeParse(t).success,ma=xe([Xy,e0,Ah,Mh]);xe([Ah,Mh]);const Es=St.strict(),$E=rr.extend({requestId:fo.optional(),reason:T().optional()}),Ih=nr.extend({method:N("notifications/cancelled"),params:$E}),SE=D({src:T(),mimeType:T().optional(),sizes:K(T()).optional(),theme:Zt(["light","dark"]).optional()}),po=D({icons:K(SE).optional()}),Fs=D({name:T(),title:T().optional()}),Tl=Fs.extend({...Fs.shape,...po.shape,version:T(),websiteUrl:T().optional(),description:T().optional()}),kE=Th(D({applyDefaults:Pe().optional()}),Te(T(),ze())),xE=Jy(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Th(D({form:kE.optional(),url:lt.optional()}),Te(T(),ze()).optional())),EE=_t({list:lt.optional(),cancel:lt.optional(),requests:_t({sampling:_t({createMessage:lt.optional()}).optional(),elicitation:_t({create:lt.optional()}).optional()}).optional()}),CE=_t({list:lt.optional(),cancel:lt.optional(),requests:_t({tools:_t({call:lt.optional()}).optional()}).optional()}),PE=D({experimental:Te(T(),lt).optional(),sampling:D({context:lt.optional(),tools:lt.optional()}).optional(),elicitation:xE.optional(),roots:D({listChanged:Pe().optional()}).optional(),tasks:EE.optional(),extensions:Te(T(),lt).optional()}),TE=Gt.extend({protocolVersion:T(),capabilities:PE,clientInfo:Tl}),RE=$t.extend({method:N("initialize"),params:TE}),AE=D({experimental:Te(T(),lt).optional(),logging:lt.optional(),completions:lt.optional(),prompts:D({listChanged:Pe().optional()}).optional(),resources:D({subscribe:Pe().optional(),listChanged:Pe().optional()}).optional(),tools:D({listChanged:Pe().optional()}).optional(),tasks:CE.optional(),extensions:Te(T(),lt).optional()}),t0=St.extend({protocolVersion:T(),capabilities:AE,serverInfo:Tl,instructions:T().optional()}),r0=nr.extend({method:N("notifications/initialized"),params:rr.optional()}),ME=t=>r0.safeParse(t).success,Rl=$t.extend({method:N("ping"),params:Gt.optional()}),IE=D({progress:ye(),total:Ge(ye()),message:Ge(T())}),OE=D({...rr.shape,...IE.shape,progressToken:Yy}),Oh=nr.extend({method:N("notifications/progress"),params:OE}),NE=Gt.extend({cursor:Qy.optional()}),mo=$t.extend({params:NE.optional()}),go=St.extend({nextCursor:Qy.optional()}),jE=Zt(["working","input_required","completed","failed","cancelled"]),yo=D({taskId:T(),status:jE,ttl:xe([ye(),Vx()]),createdAt:T(),lastUpdatedAt:T(),pollInterval:Ge(ye()),statusMessage:Ge(T())}),Gi=St.extend({task:yo}),DE=rr.merge(yo),ja=nr.extend({method:N("notifications/tasks/status"),params:DE}),Nh=$t.extend({method:N("tasks/get"),params:Gt.extend({taskId:T()})}),jh=St.merge(yo),Dh=$t.extend({method:N("tasks/result"),params:Gt.extend({taskId:T()})});St.loose();const Lh=mo.extend({method:N("tasks/list")}),zh=go.extend({tasks:K(yo)}),Fh=$t.extend({method:N("tasks/cancel"),params:Gt.extend({taskId:T()})}),LE=St.merge(yo),n0=D({uri:T(),mimeType:Ge(T()),_meta:Te(T(),ze()).optional()}),s0=n0.extend({text:T()}),qh=T().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),i0=n0.extend({blob:qh}),vo=Zt(["user","assistant"]),ri=D({audience:K(vo).optional(),priority:ye().min(0).max(1).optional(),lastModified:Fy({offset:!0}).optional()}),o0=D({...Fs.shape,...po.shape,uri:T(),description:Ge(T()),mimeType:Ge(T()),size:Ge(ye()),annotations:ri.optional(),_meta:Ge(_t({}))}),zE=D({...Fs.shape,...po.shape,uriTemplate:T(),description:Ge(T()),mimeType:Ge(T()),annotations:ri.optional(),_meta:Ge(_t({}))}),a0=mo.extend({method:N("resources/list")}),Bh=go.extend({resources:K(o0)}),l0=mo.extend({method:N("resources/templates/list")}),Vh=go.extend({resourceTemplates:K(zE)}),Hh=Gt.extend({uri:T()}),FE=Hh,c0=$t.extend({method:N("resources/read"),params:FE}),Uh=St.extend({contents:K(xe([s0,i0]))}),Wh=nr.extend({method:N("notifications/resources/list_changed"),params:rr.optional()}),qE=Hh,BE=$t.extend({method:N("resources/subscribe"),params:qE}),VE=Hh,HE=$t.extend({method:N("resources/unsubscribe"),params:VE}),UE=rr.extend({uri:T()}),WE=nr.extend({method:N("notifications/resources/updated"),params:UE}),KE=D({name:T(),description:Ge(T()),required:Ge(Pe())}),ZE=D({...Fs.shape,...po.shape,description:Ge(T()),arguments:Ge(K(KE)),_meta:Ge(_t({}))}),u0=mo.extend({method:N("prompts/list")}),Kh=go.extend({prompts:K(ZE)}),GE=Gt.extend({name:T(),arguments:Te(T(),T()).optional()}),JE=$t.extend({method:N("prompts/get"),params:GE}),Zh=D({type:N("text"),text:T(),annotations:ri.optional(),_meta:Te(T(),ze()).optional()}),Gh=D({type:N("image"),data:qh,mimeType:T(),annotations:ri.optional(),_meta:Te(T(),ze()).optional()}),Jh=D({type:N("audio"),data:qh,mimeType:T(),annotations:ri.optional(),_meta:Te(T(),ze()).optional()}),YE=D({type:N("tool_use"),name:T(),id:T(),input:Te(T(),ze()),_meta:Te(T(),ze()).optional()}),h0=D({type:N("resource"),resource:xe([s0,i0]),annotations:ri.optional(),_meta:Te(T(),ze()).optional()}),d0=o0.extend({type:N("resource_link")}),wo=xe([Zh,Gh,Jh,d0,h0]),QE=D({role:vo,content:wo}),f0=St.extend({description:T().optional(),messages:K(QE)}),Yh=nr.extend({method:N("notifications/prompts/list_changed"),params:rr.optional()}),XE=D({title:T().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),eC=D({taskSupport:Zt(["required","optional","forbidden"]).optional()}),Qh=D({...Fs.shape,...po.shape,description:T().optional(),inputSchema:D({type:N("object"),properties:Te(T(),lt).optional(),required:K(T()).optional()}).catchall(ze()),outputSchema:D({type:N("object"),properties:Te(T(),lt).optional(),required:K(T()).optional()}).catchall(ze()).optional(),annotations:XE.optional(),execution:eC.optional(),_meta:Te(T(),ze()).optional()}),tC=mo.extend({method:N("tools/list")}),Xh=go.extend({tools:K(Qh)}),rs=St.extend({content:K(wo).default([]),structuredContent:Te(T(),ze()).optional(),isError:Pe().optional()});rs.or(St.extend({toolResult:ze()}));const rC=ho.extend({name:T(),arguments:Te(T(),ze()).optional()}),p0=$t.extend({method:N("tools/call"),params:rC}),ed=nr.extend({method:N("notifications/tools/list_changed"),params:rr.optional()}),nC=D({autoRefresh:Pe().default(!0),debounceMs:ye().int().nonnegative().default(300)}),m0=Zt(["debug","info","notice","warning","error","critical","alert","emergency"]),sC=Gt.extend({level:m0}),iC=$t.extend({method:N("logging/setLevel"),params:sC}),oC=rr.extend({level:m0,logger:T().optional(),data:ze()}),g0=nr.extend({method:N("notifications/message"),params:oC}),aC=D({name:T().optional()}),lC=D({hints:K(aC).optional(),costPriority:ye().min(0).max(1).optional(),speedPriority:ye().min(0).max(1).optional(),intelligencePriority:ye().min(0).max(1).optional()}),cC=D({mode:Zt(["auto","required","none"]).optional()}),uC=D({type:N("tool_result"),toolUseId:T().describe("The unique identifier for the corresponding tool call."),content:K(wo).default([]),structuredContent:D({}).loose().optional(),isError:Pe().optional(),_meta:Te(T(),ze()).optional()}),hC=Uy("type",[Zh,Gh,Jh]),Da=Uy("type",[Zh,Gh,Jh,YE,uC]),dC=D({role:vo,content:xe([Da,K(Da)]),_meta:Te(T(),ze()).optional()}),fC=ho.extend({messages:K(dC),modelPreferences:lC.optional(),systemPrompt:T().optional(),includeContext:Zt(["none","thisServer","allServers"]).optional(),temperature:ye().optional(),maxTokens:ye().int(),stopSequences:K(T()).optional(),metadata:lt.optional(),tools:K(Qh).optional(),toolChoice:cC.optional()}),td=$t.extend({method:N("sampling/createMessage"),params:fC}),y0=St.extend({model:T(),stopReason:Ge(Zt(["endTurn","stopSequence","maxTokens"]).or(T())),role:vo,content:hC}),v0=St.extend({model:T(),stopReason:Ge(Zt(["endTurn","stopSequence","maxTokens","toolUse"]).or(T())),role:vo,content:xe([Da,K(Da)])}),pC=D({type:N("boolean"),title:T().optional(),description:T().optional(),default:Pe().optional()}),mC=D({type:N("string"),title:T().optional(),description:T().optional(),minLength:ye().optional(),maxLength:ye().optional(),format:Zt(["email","uri","date","date-time"]).optional(),default:T().optional()}),gC=D({type:Zt(["number","integer"]),title:T().optional(),description:T().optional(),minimum:ye().optional(),maximum:ye().optional(),default:ye().optional()}),yC=D({type:N("string"),title:T().optional(),description:T().optional(),enum:K(T()),default:T().optional()}),vC=D({type:N("string"),title:T().optional(),description:T().optional(),oneOf:K(D({const:T(),title:T()})),default:T().optional()}),wC=D({type:N("string"),title:T().optional(),description:T().optional(),enum:K(T()),enumNames:K(T()).optional(),default:T().optional()}),_C=xe([yC,vC]),bC=D({type:N("array"),title:T().optional(),description:T().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:D({type:N("string"),enum:K(T())}),default:K(T()).optional()}),$C=D({type:N("array"),title:T().optional(),description:T().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:D({anyOf:K(D({const:T(),title:T()}))}),default:K(T()).optional()}),SC=xe([bC,$C]),kC=xe([wC,_C,SC]),xC=xe([kC,pC,mC,gC]),EC=ho.extend({mode:N("form").optional(),message:T(),requestedSchema:D({type:N("object"),properties:Te(T(),xC),required:K(T()).optional()})}),CC=ho.extend({mode:N("url"),message:T(),elicitationId:T(),url:T().url()}),PC=xe([EC,CC]),w0=$t.extend({method:N("elicitation/create"),params:PC}),TC=rr.extend({elicitationId:T()}),RC=nr.extend({method:N("notifications/elicitation/complete"),params:TC}),_0=St.extend({action:Zt(["accept","decline","cancel"]),content:Jy(t=>t===null?void 0:t,Te(T(),xe([T(),ye(),Pe(),K(T())])).optional())}),AC=D({type:N("ref/resource"),uri:T()}),MC=D({type:N("ref/prompt"),name:T()}),IC=Gt.extend({ref:xe([MC,AC]),argument:D({name:T(),value:T()}),context:D({arguments:Te(T(),T()).optional()}).optional()}),OC=$t.extend({method:N("completion/complete"),params:IC}),b0=St.extend({completion:_t({values:K(T()).max(100),total:Ge(ye().int()),hasMore:Ge(Pe())})}),NC=D({uri:T().startsWith("file://"),name:T().optional(),_meta:Te(T(),ze()).optional()}),jC=$t.extend({method:N("roots/list"),params:Gt.optional()}),DC=St.extend({roots:K(NC)}),LC=nr.extend({method:N("notifications/roots/list_changed"),params:rr.optional()});xe([Rl,RE,OC,iC,JE,u0,a0,l0,c0,BE,HE,p0,tC,Nh,Dh,Lh,Fh]);xe([Ih,Oh,r0,LC,ja]);xe([Es,y0,v0,_0,DC,jh,zh,Gi]);xe([Rl,td,w0,jC,Nh,Dh,Lh,Fh]);xe([Ih,Oh,g0,WE,Wh,ed,Yh,ja,RC]);xe([Es,t0,b0,f0,Kh,Bh,Vh,Uh,rs,Xh,jh,zh,Gi]);class ue extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===fe.UrlElicitationRequired&&n){const s=n;if(s.elicitations)return new zC(s.elicitations,r)}return new ue(e,r,n)}}class zC extends ue{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(fe.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){var e;return((e=this.data)==null?void 0:e.elicitations)??[]}}function rd(t){return!!t._zod}function fn(t,e){return rd(t)?Ey(t,e):t.safeParse(e)}function $0(t){var r,n;if(!t)return;let e;if(rd(t)?e=(n=(r=t._zod)==null?void 0:r.def)==null?void 0:n.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function S0(t){var s;if(rd(t)){const o=(s=t._zod)==null?void 0:s.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}const r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=t.value;if(n!==void 0)return n}function Dn(t){return t==="completed"||t==="failed"||t==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function zp(t){const e=$0(t),r=e==null?void 0:e.method;if(!r)throw new Error("Schema is missing a method literal");const n=S0(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Fp(t,e){const r=fn(t,e);if(!r.success)throw r.error;return r.data}const FC=6e4;class k0{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ih,r=>{this._oncancel(r)}),this.setNotificationHandler(Oh,r=>{this._onprogress(r)}),this.setRequestHandler(Rl,r=>({})),this._taskStore=e==null?void 0:e.taskStore,this._taskMessageQueue=e==null?void 0:e.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Nh,async(r,n)=>{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ue(fe.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Dh,async(r,n)=>{const s=async()=>{var a;const i=r.params.taskId;if(this._taskMessageQueue){let l;for(;l=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(l.type==="response"||l.type==="error"){const c=l.message,u=c.id,h=this._requestResolvers.get(u);if(h)if(this._requestResolvers.delete(u),l.type==="response")h(c);else{const d=c,f=new ue(d.error.code,d.error.message,d.error.data);h(f)}else{const d=l.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await((a=this._transport)==null?void 0:a.send(l.message,{relatedRequestId:n.requestId}))}}const o=await this._taskStore.getTask(i,n.sessionId);if(!o)throw new ue(fe.InvalidParams,`Task not found: ${i}`);if(!Dn(o.status))return await this._waitForTaskUpdate(i,n.signal),await s();if(Dn(o.status)){const l=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...l,_meta:{...l._meta,[Vn]:{taskId:i}}}}return await s()};return await s()}),this.setRequestHandler(Lh,async(r,n)=>{var s;try{const{tasks:i,nextCursor:o}=await this._taskStore.listTasks((s=r.params)==null?void 0:s.cursor,n.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new ue(fe.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(Fh,async(r,n)=>{try{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ue(fe.InvalidParams,`Task not found: ${r.params.taskId}`);if(Dn(s.status))throw new ue(fe.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new ue(fe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(s){throw s instanceof ue?s:new ue(fe.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const r=this._requestHandlerAbortControllers.get(e.params.requestId);r==null||r.abort(e.params.reason)}_setupTimeout(e,r,n,s,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:s})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),ue.fromError(fe.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var i,o,a;if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const r=(i=this.transport)==null?void 0:i.onclose;this._transport.onclose=()=>{r==null||r(),this._onclose()};const n=(o=this.transport)==null?void 0:o.onerror;this._transport.onerror=l=>{n==null||n(l),this._onerror(l)};const s=(a=this._transport)==null?void 0:a.onmessage;this._transport.onmessage=(l,c)=>{s==null||s(l,c),Si(l)||bE(l)?this._onresponse(l):Yc(l)?this._onrequest(l,c):_E(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var n;const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const s of this._timeoutInfo.values())clearTimeout(s.timeoutId);this._timeoutInfo.clear();for(const s of this._requestHandlerAbortControllers.values())s.abort();this._requestHandlerAbortControllers.clear();const r=ue.fromError(fe.ConnectionClosed,"Connection closed");this._transport=void 0,(n=this.onclose)==null||n.call(this);for(const s of e.values())s(r)}_onerror(e){var r;(r=this.onerror)==null||r.call(this,e)}_onnotification(e){const r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){var u,h,d,f;const n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,i=(d=(h=(u=e.params)==null?void 0:u._meta)==null?void 0:h[Vn])==null?void 0:d.taskId;if(n===void 0){const p={jsonrpc:"2.0",id:e.id,error:{code:fe.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:p,timestamp:Date.now()},s==null?void 0:s.sessionId).catch(y=>this._onerror(new Error(`Failed to enqueue error response: ${y}`))):s==null||s.send(p).catch(y=>this._onerror(new Error(`Failed to send an error response: ${y}`)));return}const o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);const a=wE(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s==null?void 0:s.sessionId):void 0,c={signal:o.signal,sessionId:s==null?void 0:s.sessionId,_meta:(f=e.params)==null?void 0:f._meta,sendNotification:async p=>{if(o.signal.aborted)return;const y={relatedRequestId:e.id};i&&(y.relatedTask={taskId:i}),await this.notification(p,y)},sendRequest:async(p,y,v)=>{var $;if(o.signal.aborted)throw new ue(fe.ConnectionClosed,"Request was cancelled");const m={...v,relatedRequestId:e.id};i&&!m.relatedTask&&(m.relatedTask={taskId:i});const _=(($=m.relatedTask)==null?void 0:$.taskId)??i;return _&&l&&await l.updateTaskStatus(_,"input_required"),await this.request(p,y,m)},authInfo:r==null?void 0:r.authInfo,requestId:e.id,requestInfo:r==null?void 0:r.requestInfo,taskId:i,taskStore:l,taskRequestedTtl:a==null?void 0:a.ttl,closeSSEStream:r==null?void 0:r.closeSSEStream,closeStandaloneSSEStream:r==null?void 0:r.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async p=>{if(o.signal.aborted)return;const y={result:p,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:y,timestamp:Date.now()},s==null?void 0:s.sessionId):await(s==null?void 0:s.send(y))},async p=>{if(o.signal.aborted)return;const y={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:fe.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:y,timestamp:Date.now()},s==null?void 0:s.sessionId):await(s==null?void 0:s.send(y))}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===o&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...n}=e.params,s=Number(r),i=this._progressHandlers.get(s);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),o(l);return}i(n)}_onresponse(e){const r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Si(e))n(e);else{const o=new ue(e.error.code,e.error.message,e.error.data);n(o)}return}const s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Si(e)&&e.result&&typeof e.result=="object"){const o=e.result;if(o.task&&typeof o.task=="object"){const a=o.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Si(e))s(e);else{const o=ue.fromError(e.error.code,e.error.message,e.error.data);s(o)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)==null?void 0:e.close())}async*requestStream(e,r,n){var o,a;const{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(l){yield{type:"error",error:l instanceof ue?l:new ue(fe.InternalError,String(l))}}return}let i;try{const l=await this.request(e,Gi,n);if(l.task)i=l.task.taskId,yield{type:"taskCreated",task:l.task};else throw new ue(fe.InternalError,"Task creation did not return a task");for(;;){const c=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:c},Dn(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:c.status==="failed"?yield{type:"error",error:new ue(fe.InternalError,`Task ${i} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new ue(fe.InternalError,`Task ${i} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}const u=c.pollInterval??((o=this._options)==null?void 0:o.defaultTaskPollInterval)??1e3;await new Promise(h=>setTimeout(h,u)),(a=n==null?void 0:n.signal)==null||a.throwIfAborted()}}catch(l){yield{type:"error",error:l instanceof ue?l:new ue(fe.InternalError,String(l))}}}request(e,r,n){const{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{var _,$,E,x,P;const h=R=>{u(R)};if(!this._transport){h(new Error("Not connected"));return}if(((_=this._options)==null?void 0:_.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(R){h(R);return}($=n==null?void 0:n.signal)==null||$.throwIfAborted();const d=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:d};n!=null&&n.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...((E=e.params)==null?void 0:E._meta)||{},progressToken:d}}),a&&(f.params={...f.params,task:a}),l&&(f.params={...f.params,_meta:{...((x=f.params)==null?void 0:x._meta)||{},[Vn]:l}});const p=R=>{var L;this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),(L=this._transport)==null||L.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(R)}},{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o}).catch(H=>this._onerror(new Error(`Failed to send cancellation: ${H}`)));const z=R instanceof ue?R:new ue(fe.RequestTimeout,String(R));u(z)};this._responseHandlers.set(d,R=>{var z;if(!((z=n==null?void 0:n.signal)!=null&&z.aborted)){if(R instanceof Error)return u(R);try{const L=fn(r,R.result);L.success?c(L.data):u(L.error)}catch(L){u(L)}}}),(P=n==null?void 0:n.signal)==null||P.addEventListener("abort",()=>{var R;p((R=n==null?void 0:n.signal)==null?void 0:R.reason)});const y=(n==null?void 0:n.timeout)??FC,v=()=>p(ue.fromError(fe.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(d,y,n==null?void 0:n.maxTotalTimeout,v,(n==null?void 0:n.resetTimeoutOnProgress)??!1);const m=l==null?void 0:l.taskId;if(m){const R=z=>{const L=this._responseHandlers.get(d);L?L(z):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,R),this._enqueueTaskMessage(m,{type:"request",message:f,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(d),u(z)})}else this._transport.send(f,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o}).catch(R=>{this._cleanupTimeout(d),u(R)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},jh,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},zh,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},LE,r)}async notification(e,r){var a,l,c,u;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const n=(a=r==null?void 0:r.relatedTask)==null?void 0:a.taskId;if(n){const h={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...((l=e.params)==null?void 0:l._meta)||{},[Vn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:h,timestamp:Date.now()});return}if((((c=this._options)==null?void 0:c.debouncedNotificationMethods)??[]).includes(e.method)&&!e.params&&!(r!=null&&r.relatedRequestId)&&!(r!=null&&r.relatedTask)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var d,f;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let h={...e,jsonrpc:"2.0"};r!=null&&r.relatedTask&&(h={...h,params:{...h.params,_meta:{...((d=h.params)==null?void 0:d._meta)||{},[Vn]:r.relatedTask}}}),(f=this._transport)==null||f.send(h,r).catch(p=>this._onerror(p))});return}let o={...e,jsonrpc:"2.0"};r!=null&&r.relatedTask&&(o={...o,params:{...o.params,_meta:{...((u=o.params)==null?void 0:u._meta)||{},[Vn]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){const n=zp(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,i)=>{const o=Fp(e,s);return Promise.resolve(r(o,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){const n=zp(e);this._notificationHandlers.set(n,s=>{const i=Fp(e,s);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){var i;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=(i=this._options)==null?void 0:i.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,r);for(const s of n)if(s.type==="request"&&Yc(s.message)){const i=s.message.id,o=this._requestResolvers.get(i);o?(o(new ue(fe.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){var s,i;let n=((s=this._options)==null?void 0:s.defaultTaskPollInterval)??1e3;try{const o=await((i=this._taskStore)==null?void 0:i.getTask(e));o!=null&&o.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,a)=>{if(r.aborted){a(new ue(fe.InvalidRequest,"Request cancelled"));return}const l=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(l),a(new ue(fe.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{const i=await n.getTask(s,r);if(!i)throw new ue(fe.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(s,i,o)=>{await n.storeTaskResult(s,i,o,r);const a=await n.getTask(s,r);if(a){const l=ja.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Dn(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,i,o)=>{const a=await n.getTask(s,r);if(!a)throw new ue(fe.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Dn(a.status))throw new ue(fe.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,i,o,r);const l=await n.getTask(s,r);if(l){const c=ja.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Dn(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}function qp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function qC(t,e){const r={...t};for(const n in e){const s=n,i=e[s];if(i===void 0)continue;const o=r[s];qp(o)&&qp(i)?r[s]={...o,...i}:r[s]=i}return r}(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});class BC extends k0{constructor(){super(...arguments);pe(this,"_registeredMethods",new Set);pe(this,"_eventSlots",new Map);pe(this,"setRequestHandler",(r,n)=>{this._assertMethodNotRegistered(r,"setRequestHandler"),super.setRequestHandler(r,n)});pe(this,"setNotificationHandler",(r,n)=>{this._assertMethodNotRegistered(r,"setNotificationHandler"),super.setNotificationHandler(r,n)});pe(this,"replaceRequestHandler",(r,n)=>{let s=r.shape.method.value;this._registeredMethods.add(s),super.setRequestHandler(r,n)})}onEventDispatch(r,n){}_ensureEventSlot(r){let n=this._eventSlots.get(r);if(!n){let s=this.eventSchemas[r];if(!s)throw Error(`Unknown event: ${String(r)}`);n={listeners:[]},this._eventSlots.set(r,n);let i=s.shape.method.value;this._registeredMethods.add(i);let o=n;super.setNotificationHandler(s,a=>{var c;let l=a.params;this.onEventDispatch(r,l),(c=o.onHandler)==null||c.call(o,l);for(let u of[...o.listeners])u(l)})}return n}setEventHandler(r,n){let s=this._ensureEventSlot(r);s.onHandler&&n&&console.warn(`[MCP Apps] on${String(r)} handler replaced. Use addEventListener("${String(r)}", …) to add multiple listeners without replacing.`),s.onHandler=n}getEventHandler(r){var n;return(n=this._eventSlots.get(r))==null?void 0:n.onHandler}addEventListener(r,n){this._ensureEventSlot(r).listeners.push(n)}removeEventListener(r,n){let s=this._eventSlots.get(r);if(!s)return;let i=s.listeners.indexOf(n);i!==-1&&s.listeners.splice(i,1)}warnIfRequestHandlerReplaced(r,n,s){n&&s&&console.warn(`[MCP Apps] ${r} handler replaced. Previous handler will no longer be called.`)}_assertMethodNotRegistered(r,n){let s=r.shape.method.value;if(this._registeredMethods.has(s))throw Error(`Handler for "${s}" already registered (via ${n}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(s)}}var x0="2026-01-26",VC="ui/notifications/tool-input-partial",HC=xe([N("light"),N("dark")]).describe("Color theme preference for the host environment."),Ji=xe([N("inline"),N("fullscreen"),N("pip")]).describe("Display mode for UI presentation."),UC=xe([N("--color-background-primary"),N("--color-background-secondary"),N("--color-background-tertiary"),N("--color-background-inverse"),N("--color-background-ghost"),N("--color-background-info"),N("--color-background-danger"),N("--color-background-success"),N("--color-background-warning"),N("--color-background-disabled"),N("--color-text-primary"),N("--color-text-secondary"),N("--color-text-tertiary"),N("--color-text-inverse"),N("--color-text-ghost"),N("--color-text-info"),N("--color-text-danger"),N("--color-text-success"),N("--color-text-warning"),N("--color-text-disabled"),N("--color-border-primary"),N("--color-border-secondary"),N("--color-border-tertiary"),N("--color-border-inverse"),N("--color-border-ghost"),N("--color-border-info"),N("--color-border-danger"),N("--color-border-success"),N("--color-border-warning"),N("--color-border-disabled"),N("--color-ring-primary"),N("--color-ring-secondary"),N("--color-ring-inverse"),N("--color-ring-info"),N("--color-ring-danger"),N("--color-ring-success"),N("--color-ring-warning"),N("--font-sans"),N("--font-mono"),N("--font-weight-normal"),N("--font-weight-medium"),N("--font-weight-semibold"),N("--font-weight-bold"),N("--font-text-xs-size"),N("--font-text-sm-size"),N("--font-text-md-size"),N("--font-text-lg-size"),N("--font-heading-xs-size"),N("--font-heading-sm-size"),N("--font-heading-md-size"),N("--font-heading-lg-size"),N("--font-heading-xl-size"),N("--font-heading-2xl-size"),N("--font-heading-3xl-size"),N("--font-text-xs-line-height"),N("--font-text-sm-line-height"),N("--font-text-md-line-height"),N("--font-text-lg-line-height"),N("--font-heading-xs-line-height"),N("--font-heading-sm-line-height"),N("--font-heading-md-line-height"),N("--font-heading-lg-line-height"),N("--font-heading-xl-line-height"),N("--font-heading-2xl-line-height"),N("--font-heading-3xl-line-height"),N("--border-radius-xs"),N("--border-radius-sm"),N("--border-radius-md"),N("--border-radius-lg"),N("--border-radius-xl"),N("--border-radius-full"),N("--border-width-regular"),N("--shadow-hairline"),N("--shadow-sm"),N("--shadow-md"),N("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),WC=Te(UC.describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),xe([T(),Kc()]).describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),KC=D({method:N("ui/open-link"),params:D({url:T().describe("URL to open in the host's browser")})});D({isError:Pe().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough();D({isError:Pe().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough();D({isError:Pe().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough();var ZC=D({method:N("ui/notifications/sandbox-proxy-ready"),params:D({})}),nd=D({connectDomains:K(T()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket). + +- Maps to CSP \`connect-src\` directive +- Empty or omitted → no network connections (secure default)`),resourceDomains:K(T()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:K(T()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:K(T()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),sd=D({camera:D({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:D({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:D({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:D({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),GC=D({method:N("ui/notifications/size-changed"),params:D({width:ye().optional().describe("New width in pixels."),height:ye().optional().describe("New height in pixels.")})});D({method:N("ui/notifications/tool-input"),params:D({arguments:Te(T(),ze().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})});D({method:N("ui/notifications/tool-input-partial"),params:D({arguments:Te(T(),ze().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})});D({method:N("ui/notifications/tool-cancelled"),params:D({reason:T().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})});var JC=D({fonts:T().optional()}),YC=D({variables:WC.optional().describe("CSS variables for theming the app."),css:JC.optional().describe("CSS blocks that apps can inject.")});D({method:N("ui/resource-teardown"),params:D({})});var QC=Te(T(),ze()),Bp=D({text:D({}).optional().describe("Host supports text content blocks."),image:D({}).optional().describe("Host supports image content blocks."),audio:D({}).optional().describe("Host supports audio content blocks."),resource:D({}).optional().describe("Host supports resource content blocks."),resourceLink:D({}).optional().describe("Host supports resource link content blocks."),structuredContent:D({}).optional().describe("Host supports structured content.")}),XC=D({method:N("ui/notifications/request-teardown"),params:D({}).optional()}),eP=D({experimental:Te(T(),Te(T(),Ph()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:D({}).optional().describe("Host supports opening external URLs."),downloadFile:D({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:D({listChanged:Pe().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:D({listChanged:Pe().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:D({}).optional().describe("Host accepts log messages."),sandbox:D({permissions:sd.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:nd.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:Bp.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:Bp.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:D({tools:D({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),tP=D({experimental:Te(T(),Te(T(),Ph()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:D({listChanged:Pe().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:K(Ji).optional().describe("Display modes the app supports.")}),rP=D({method:N("ui/notifications/initialized"),params:D({}).optional()});D({csp:nd.optional().describe("Content Security Policy configuration for UI resources."),permissions:sd.optional().describe("Sandbox permissions requested by the UI resource."),domain:T().optional().describe(`Dedicated origin for view sandbox. + +Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists. + +**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include: +- Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`) +- URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`) + +If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:Pe().optional().describe(`Visual boundary preference - true if view prefers a visible border. + +Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary. + +- \`true\`: request visible border + background +- \`false\`: request no visible border + background +- omitted: host decides border`)});var Vp=D({method:N("ui/request-display-mode"),params:D({mode:Ji.describe("The display mode being requested.")})});D({mode:Ji.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough();var nP=xe([N("model"),N("app")]).describe("Tool visibility scope - who can access the tool.");D({resourceUri:T().optional(),visibility:K(nP).optional().describe(`Who can access this tool. Default: ["model", "app"] +- "model": Tool visible to and callable by the agent +- "app": Tool callable by the app from this server only`),csp:Zc().optional(),permissions:Zc().optional()});D({mimeTypes:K(T()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});var sP=D({method:N("ui/download-file"),params:D({contents:K(xe([h0,d0])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),iP=D({method:N("ui/message"),params:D({role:N("user").describe('Message role, currently only "user" is supported.'),content:K(wo).describe("Message content blocks (text, image, etc.).")})});D({method:N("ui/notifications/sandbox-resource-ready"),params:D({html:T().describe("HTML content to load into the inner iframe."),sandbox:T().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:nd.optional().describe("CSP configuration from resource metadata."),permissions:sd.optional().describe("Sandbox permissions from resource metadata.")})});D({method:N("ui/notifications/tool-result"),params:rs.describe("Standard MCP tool execution result.")});var E0=D({toolInfo:D({id:fo.optional().describe("JSON-RPC id of the tools/call request."),tool:Qh.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:HC.optional().describe("Current color theme preference."),styles:YC.optional().describe("Style configuration for theming the app."),displayMode:Ji.optional().describe("How the UI is currently displayed."),availableDisplayModes:K(Ji).optional().describe("Display modes the host supports."),containerDimensions:xe([D({height:ye().describe("Fixed container height in pixels.")}),D({maxHeight:xe([ye(),Kc()]).optional().describe("Maximum container height in pixels.")})]).and(xe([D({width:ye().describe("Fixed container width in pixels.")}),D({maxWidth:xe([ye(),Kc()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other +container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:T().optional().describe("User's language and region preference in BCP 47 format."),timeZone:T().optional().describe("User's timezone in IANA format."),userAgent:T().optional().describe("Host application identifier."),platform:xe([N("web"),N("desktop"),N("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:D({touch:Pe().optional().describe("Whether the device supports touch input."),hover:Pe().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:D({top:ye().describe("Top safe area inset in pixels."),right:ye().describe("Right safe area inset in pixels."),bottom:ye().describe("Bottom safe area inset in pixels."),left:ye().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough();D({method:N("ui/notifications/host-context-changed"),params:E0.describe("Partial context update containing only changed fields.")});var oP=D({method:N("ui/update-model-context"),params:D({content:K(wo).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:Te(T(),ze().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),aP=D({method:N("ui/initialize"),params:D({appInfo:Tl.describe("App identification (name and version)."),appCapabilities:tP.describe("Features and capabilities this app provides."),protocolVersion:T().describe("Protocol version this app supports.")})});D({protocolVersion:T().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Tl.describe("Host application identification and version."),hostCapabilities:eP.describe("Features and capabilities provided by the host."),hostContext:E0.describe("Rich context about the host environment.")}).passthrough();class lP{constructor(e=window.parent,r){pe(this,"eventTarget");pe(this,"eventSource");pe(this,"messageListener");pe(this,"onclose");pe(this,"onerror");pe(this,"onmessage");pe(this,"sessionId");pe(this,"setProtocolVersion");this.eventTarget=e,this.eventSource=r,this.messageListener=n=>{var i,o,a;if(r&&n.source!==this.eventSource){console.debug("Ignoring message from unknown source",n);return}let s=ma.safeParse(n.data);s.success?(console.debug("Parsed message",s.data),(i=this.onmessage)==null||i.call(this,s.data)):((o=n.data)==null?void 0:o.jsonrpc)!=="2.0"?console.debug("Ignoring non-JSON-RPC message",s.error.message,n):(console.error("Failed to parse message",s.error.message,n),(a=this.onerror)==null||a.call(this,Error("Invalid JSON-RPC message received: "+s.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,r){e.method!==VC&&console.debug("Sending message",e),this.eventTarget.postMessage(e,"*")}async close(){var e;window.removeEventListener("message",this.messageListener),(e=this.onclose)==null||e.call(this)}}var cP=[x0];class uP extends BC{constructor(r,n,s,i){super(i);pe(this,"_client");pe(this,"_hostInfo");pe(this,"_capabilities");pe(this,"_appCapabilities");pe(this,"_hostContext",{});pe(this,"_appInfo");pe(this,"_initializedReceived",!1);pe(this,"_baseReplaceRequestHandler",this.replaceRequestHandler);pe(this,"replaceRequestHandler",(r,n)=>{this._baseReplaceRequestHandler(r,(s,i)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${s.method}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),n(s,i)))});pe(this,"eventSchemas",{sizechange:GC,sandboxready:ZC,initialized:rP,requestteardown:XC,loggingmessage:g0});pe(this,"onping");pe(this,"_onmessage");pe(this,"_onopenlink");pe(this,"_ondownloadfile");pe(this,"_onrequestdisplaymode");pe(this,"_onupdatemodelcontext");pe(this,"_oncalltool");pe(this,"_onlistresources");pe(this,"_onlistresourcetemplates");pe(this,"_onreadresource");pe(this,"_onlistprompts");pe(this,"sendResourceTeardown",this.teardownResource);this._client=r,this._hostInfo=n,this._capabilities=s,this.addEventListener("initialized",()=>{this._initializedReceived=!0}),this._hostContext=(i==null?void 0:i.hostContext)||{},this.setRequestHandler(aP,o=>this._oninitialize(o)),this.setRequestHandler(Rl,(o,a)=>{var l;return(l=this.onping)==null||l.call(this,o.params,a),{}}),this.replaceRequestHandler(Vp,o=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(r){this.setEventHandler("sizechange",r)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(r){this.setEventHandler("sandboxready",r)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(r){this.setEventHandler("initialized",r)}get onmessage(){return this._onmessage}set onmessage(r){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,r),this._onmessage=r,this.replaceRequestHandler(iP,async(n,s)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(n.params,s)})}get onopenlink(){return this._onopenlink}set onopenlink(r){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,r),this._onopenlink=r,this.replaceRequestHandler(KC,async(n,s)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(n.params,s)})}get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(r){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,r),this._ondownloadfile=r,this.replaceRequestHandler(sP,async(n,s)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(n.params,s)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(r){this.setEventHandler("requestteardown",r)}get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(r){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,r),this._onrequestdisplaymode=r,this.replaceRequestHandler(Vp,async(n,s)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(n.params,s)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(r){this.setEventHandler("loggingmessage",r)}get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(r){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,r),this._onupdatemodelcontext=r,this.replaceRequestHandler(oP,async(n,s)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(n.params,s)})}get oncalltool(){return this._oncalltool}set oncalltool(r){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,r),this._oncalltool=r,this.replaceRequestHandler(p0,async(n,s)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(n.params,s)})}set oncreatesamplingmessage(r){this.setRequestHandler(td,async(n,s)=>r(n.params,s))}sendToolListChanged(r={}){return this.notification({method:"notifications/tools/list_changed",params:r})}get onlistresources(){return this._onlistresources}set onlistresources(r){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,r),this._onlistresources=r,this.replaceRequestHandler(a0,async(n,s)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(n.params,s)})}get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(r){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,r),this._onlistresourcetemplates=r,this.replaceRequestHandler(l0,async(n,s)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(n.params,s)})}get onreadresource(){return this._onreadresource}set onreadresource(r){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,r),this._onreadresource=r,this.replaceRequestHandler(c0,async(n,s)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(n.params,s)})}sendResourceListChanged(r={}){return this.notification({method:"notifications/resources/list_changed",params:r})}get onlistprompts(){return this._onlistprompts}set onlistprompts(r){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,r),this._onlistprompts=r,this.replaceRequestHandler(u0,async(n,s)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(n.params,s)})}sendPromptListChanged(r={}){return this.notification({method:"notifications/prompts/list_changed",params:r})}assertCapabilityForMethod(r){}assertRequestHandlerCapability(r){}assertNotificationCapability(r){}assertTaskCapability(r){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(r){throw Error("Task handlers are not supported in MCP Apps")}getCapabilities(){return this._capabilities}async _oninitialize(r){let n=r.params.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=r.params.appCapabilities,this._appInfo=r.params.appInfo,{protocolVersion:cP.includes(n)?n:x0,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(r){let n={},s=!1;for(let i of Object.keys(r)){let o=this._hostContext[i],a=r[i];hP(o,a)||(n[i]=a,s=!0)}s&&(this._hostContext=r,this.sendHostContextChange(n))}sendHostContextChange(r){return this.notification({method:"ui/notifications/host-context-changed",params:r})}sendToolInput(r){return this.notification({method:"ui/notifications/tool-input",params:r})}sendToolInputPartial(r){return this.notification({method:"ui/notifications/tool-input-partial",params:r})}sendToolResult(r){return this.notification({method:"ui/notifications/tool-result",params:r})}sendToolCancelled(r){return this.notification({method:"ui/notifications/tool-cancelled",params:r})}sendSandboxResourceReady(r){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:r})}teardownResource(r,n){return this.request({method:"ui/resource-teardown",params:r},QC,n)}callTool(r,n){return this.request({method:"tools/call",params:r},rs,n)}listTools(r,n){return this.request({method:"tools/list",params:r},Xh,n)}async connect(r){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let n=this._client.getServerCapabilities();if(!n)throw Error("Client server capabilities not available");n.tools&&(this.oncalltool=async(s,i)=>this._client.request({method:"tools/call",params:s},rs,{signal:i.signal}),n.tools.listChanged&&this._client.setNotificationHandler(ed,s=>this.sendToolListChanged(s.params))),n.resources&&(this.onlistresources=async(s,i)=>this._client.request({method:"resources/list",params:s},Bh,{signal:i.signal}),this.onlistresourcetemplates=async(s,i)=>this._client.request({method:"resources/templates/list",params:s},Vh,{signal:i.signal}),this.onreadresource=async(s,i)=>this._client.request({method:"resources/read",params:s},Uh,{signal:i.signal}),n.resources.listChanged&&this._client.setNotificationHandler(Wh,s=>this.sendResourceListChanged(s.params))),n.prompts&&(this.onlistprompts=async(s,i)=>this._client.request({method:"prompts/list",params:s},Kh,{signal:i.signal}),n.prompts.listChanged&&this._client.setNotificationHandler(Yh,s=>this.sendPromptListChanged(s.params)))}return super.connect(r)}}function hP(t,e){return JSON.stringify(t)===JSON.stringify(e)}const dP={x:0,y:0,width:1024,height:768},Qc=28,fP=12,pP=.9;function wn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function C0(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Xc(t){if(Array.isArray(t))return t.map(Xc);const e=C0(t);return e?Object.fromEntries(Object.entries(e).map(([r,n])=>[r,(r==="text"||r==="originalText")&&typeof n=="string"?n.replace(/\\r\\n|\\n|\\r/gu,` +`):Xc(n)])):t}function mP(t){return t.type==="text"&&typeof(t.text??t.originalText)=="string"}function P0(t){const e=String(t.text??t.originalText??""),r=wn(t.fontSize)??20,n=e.length*r*pP,s=wn(t.width);return Math.max(s&&s>0?s:0,n)}function gP(t){for(const e of t){if(e.type!=="cameraUpdate")continue;const r=wn(e.width),n=wn(e.height);if(!(!r||r<=0||!n||n<=0))return{x:wn(e.x)??0,y:wn(e.y)??0,width:r,height:n}}return dP}function yP(t,e){const r=wn(t.x);if(r===void 0)return!1;const n=P0(t),s=e.x+Qc,i=e.x+e.width-Qc;return ri+1}function vP(t,e){const r={...t},n=wn(r.fontSize)??20;let s=P0(r);const i=Math.max(1,e.width-Qc*2);if(s>i){const o=i/s;r.fontSize=Math.max(fP,n*o),typeof r.height=="number"&&(r.height*=Number(r.fontSize)/n),s=Math.min(i,s*(Number(r.fontSize)/n))}return r.width=s,r.autoResize=!1,r.textAlign="left",r.x=e.x+(e.width-s)/2,r}function wP(t){const r=Xc(t).map(C0);if(r.some(i=>i===void 0))return t;const n=r,s=gP(n);return n.map(i=>!mP(i)||!yP(i,s)?i:vP(i,s))}var eu={exports:{}},T0={},fr={},qs={},_o={},Se={},Yi={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(_){if(super(),!t.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce(($,E)=>`${$}${E}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce(($,E)=>(E instanceof r&&($[E.str]=($[E.str]||0)+1),$),{})}}t._Code=n,t.nil=new n("");function s(m,..._){const $=[m[0]];let E=0;for(;E<_.length;)a($,_[E]),$.push(m[++E]);return new n($)}t._=s;const i=new n("+");function o(m,..._){const $=[f(m[0])];let E=0;for(;E<_.length;)$.push(i),a($,_[E]),$.push(i,f(m[++E]));return l($),new n($)}t.str=o;function a(m,_){_ instanceof n?m.push(..._._items):_ instanceof r?m.push(_):m.push(h(_))}t.addCodeArg=a;function l(m){let _=1;for(;_{if(h.scopePath===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return(0,e._)`${c}${h.scopePath}`})}scopeCode(c=this._values,u,h){return this._reduceValues(c,d=>{if(d.value===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return d.value.code},u,h)}_reduceValues(c,u,h={},d){let f=e.nil;for(const p in c){const y=c[p];if(!y)continue;const v=h[p]=h[p]||new Map;y.forEach(m=>{if(v.has(m))return;v.set(m,n.Started);let _=u(m);if(_){const $=this.opts.es5?t.varKinds.var:t.varKinds.const;f=(0,e._)`${f}${$} ${m} = ${_};${this.opts._n}`}else if(_=d==null?void 0:d(m))f=(0,e._)`${f}${_}${this.opts._n}`;else throw new r(m);v.set(m,n.Completed)})}return f}}t.ValueScope=a})(tu);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=Yi,r=tu;var n=Yi;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var s=tu;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class i{optimizeNodes(){return this}optimizeNames(g,w){return this}}class o extends i{constructor(g,w,C){super(),this.varKind=g,this.name=w,this.rhs=C}render({es5:g,_n:w}){const C=g?r.varKinds.var:this.varKind,V=this.rhs===void 0?"":` = ${this.rhs}`;return`${C} ${this.name}${V};`+w}optimizeNames(g,w){if(g[this.name.str])return this.rhs&&(this.rhs=I(this.rhs,g,w)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends i{constructor(g,w,C){super(),this.lhs=g,this.rhs=w,this.sideEffects=C}render({_n:g}){return`${this.lhs} = ${this.rhs};`+g}optimizeNames(g,w){if(!(this.lhs instanceof e.Name&&!g[this.lhs.str]&&!this.sideEffects))return this.rhs=I(this.rhs,g,w),this}get names(){const g=this.lhs instanceof e.Name?{}:{...this.lhs.names};return Z(g,this.rhs)}}class l extends a{constructor(g,w,C,V){super(g,C,V),this.op=w}render({_n:g}){return`${this.lhs} ${this.op}= ${this.rhs};`+g}}class c extends i{constructor(g){super(),this.label=g,this.names={}}render({_n:g}){return`${this.label}:`+g}}class u extends i{constructor(g){super(),this.label=g,this.names={}}render({_n:g}){return`break${this.label?` ${this.label}`:""};`+g}}class h extends i{constructor(g){super(),this.error=g}render({_n:g}){return`throw ${this.error};`+g}get names(){return this.error.names}}class d extends i{constructor(g){super(),this.code=g}render({_n:g}){return`${this.code};`+g}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(g,w){return this.code=I(this.code,g,w),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class f extends i{constructor(g=[]){super(),this.nodes=g}render(g){return this.nodes.reduce((w,C)=>w+C.render(g),"")}optimizeNodes(){const{nodes:g}=this;let w=g.length;for(;w--;){const C=g[w].optimizeNodes();Array.isArray(C)?g.splice(w,1,...C):C?g[w]=C:g.splice(w,1)}return g.length>0?this:void 0}optimizeNames(g,w){const{nodes:C}=this;let V=C.length;for(;V--;){const F=C[V];F.optimizeNames(g,w)||(Q(g,F.names),C.splice(V,1))}return C.length>0?this:void 0}get names(){return this.nodes.reduce((g,w)=>B(g,w.names),{})}}class p extends f{render(g){return"{"+g._n+super.render(g)+"}"+g._n}}class y extends f{}class v extends p{}v.kind="else";class m extends p{constructor(g,w){super(w),this.condition=g}render(g){let w=`if(${this.condition})`+super.render(g);return this.else&&(w+="else "+this.else.render(g)),w}optimizeNodes(){super.optimizeNodes();const g=this.condition;if(g===!0)return this.nodes;let w=this.else;if(w){const C=w.optimizeNodes();w=this.else=Array.isArray(C)?new v(C):C}if(w)return g===!1?w instanceof m?w:w.nodes:this.nodes.length?this:new m(G(g),w instanceof m?[w]:w.nodes);if(!(g===!1||!this.nodes.length))return this}optimizeNames(g,w){var C;if(this.else=(C=this.else)===null||C===void 0?void 0:C.optimizeNames(g,w),!!(super.optimizeNames(g,w)||this.else))return this.condition=I(this.condition,g,w),this}get names(){const g=super.names;return Z(g,this.condition),this.else&&B(g,this.else.names),g}}m.kind="if";class _ extends p{}_.kind="for";class $ extends _{constructor(g){super(),this.iteration=g}render(g){return`for(${this.iteration})`+super.render(g)}optimizeNames(g,w){if(super.optimizeNames(g,w))return this.iteration=I(this.iteration,g,w),this}get names(){return B(super.names,this.iteration.names)}}class E extends _{constructor(g,w,C,V){super(),this.varKind=g,this.name=w,this.from=C,this.to=V}render(g){const w=g.es5?r.varKinds.var:this.varKind,{name:C,from:V,to:F}=this;return`for(${w} ${C}=${V}; ${C}<${F}; ${C}++)`+super.render(g)}get names(){const g=Z(super.names,this.from);return Z(g,this.to)}}class x extends _{constructor(g,w,C,V){super(),this.loop=g,this.varKind=w,this.name=C,this.iterable=V}render(g){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(g)}optimizeNames(g,w){if(super.optimizeNames(g,w))return this.iterable=I(this.iterable,g,w),this}get names(){return B(super.names,this.iterable.names)}}class P extends p{constructor(g,w,C){super(),this.name=g,this.args=w,this.async=C}render(g){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(g)}}P.kind="func";class R extends f{render(g){return"return "+super.render(g)}}R.kind="return";class z extends p{render(g){let w="try"+super.render(g);return this.catch&&(w+=this.catch.render(g)),this.finally&&(w+=this.finally.render(g)),w}optimizeNodes(){var g,w;return super.optimizeNodes(),(g=this.catch)===null||g===void 0||g.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(g,w){var C,V;return super.optimizeNames(g,w),(C=this.catch)===null||C===void 0||C.optimizeNames(g,w),(V=this.finally)===null||V===void 0||V.optimizeNames(g,w),this}get names(){const g=super.names;return this.catch&&B(g,this.catch.names),this.finally&&B(g,this.finally.names),g}}class L extends p{constructor(g){super(),this.error=g}render(g){return`catch(${this.error})`+super.render(g)}}L.kind="catch";class H extends p{render(g){return"finally"+super.render(g)}}H.kind="finally";class O{constructor(g,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?` +`:""},this._extScope=g,this._scope=new r.Scope({parent:g}),this._nodes=[new y]}toString(){return this._root.render(this.opts)}name(g){return this._scope.name(g)}scopeName(g){return this._extScope.name(g)}scopeValue(g,w){const C=this._extScope.value(g,w);return(this._values[C.prefix]||(this._values[C.prefix]=new Set)).add(C),C}getScopeValue(g,w){return this._extScope.getValue(g,w)}scopeRefs(g){return this._extScope.scopeRefs(g,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(g,w,C,V){const F=this._scope.toName(w);return C!==void 0&&V&&(this._constants[F.str]=C),this._leafNode(new o(g,F,C)),F}const(g,w,C){return this._def(r.varKinds.const,g,w,C)}let(g,w,C){return this._def(r.varKinds.let,g,w,C)}var(g,w,C){return this._def(r.varKinds.var,g,w,C)}assign(g,w,C){return this._leafNode(new a(g,w,C))}add(g,w){return this._leafNode(new l(g,t.operators.ADD,w))}code(g){return typeof g=="function"?g():g!==e.nil&&this._leafNode(new d(g)),this}object(...g){const w=["{"];for(const[C,V]of g)w.length>1&&w.push(","),w.push(C),(C!==V||this.opts.es5)&&(w.push(":"),(0,e.addCodeArg)(w,V));return w.push("}"),new e._Code(w)}if(g,w,C){if(this._blockNode(new m(g)),w&&C)this.code(w).else().code(C).endIf();else if(w)this.code(w).endIf();else if(C)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(g){return this._elseNode(new m(g))}else(){return this._elseNode(new v)}endIf(){return this._endBlockNode(m,v)}_for(g,w){return this._blockNode(g),w&&this.code(w).endFor(),this}for(g,w){return this._for(new $(g),w)}forRange(g,w,C,V,F=this.opts.es5?r.varKinds.var:r.varKinds.let){const ne=this._scope.toName(g);return this._for(new E(F,ne,w,C),()=>V(ne))}forOf(g,w,C,V=r.varKinds.const){const F=this._scope.toName(g);if(this.opts.es5){const ne=w instanceof e.Name?w:this.var("_arr",w);return this.forRange("_i",0,(0,e._)`${ne}.length`,te=>{this.var(F,(0,e._)`${ne}[${te}]`),C(F)})}return this._for(new x("of",V,F,w),()=>C(F))}forIn(g,w,C,V=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(g,(0,e._)`Object.keys(${w})`,C);const F=this._scope.toName(g);return this._for(new x("in",V,F,w),()=>C(F))}endFor(){return this._endBlockNode(_)}label(g){return this._leafNode(new c(g))}break(g){return this._leafNode(new u(g))}return(g){const w=new R;if(this._blockNode(w),this.code(g),w.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(R)}try(g,w,C){if(!w&&!C)throw new Error('CodeGen: "try" without "catch" and "finally"');const V=new z;if(this._blockNode(V),this.code(g),w){const F=this.name("e");this._currNode=V.catch=new L(F),w(F)}return C&&(this._currNode=V.finally=new H,this.code(C)),this._endBlockNode(L,H)}throw(g){return this._leafNode(new h(g))}block(g,w){return this._blockStarts.push(this._nodes.length),g&&this.code(g).endBlock(w),this}endBlock(g){const w=this._blockStarts.pop();if(w===void 0)throw new Error("CodeGen: not in self-balancing block");const C=this._nodes.length-w;if(C<0||g!==void 0&&C!==g)throw new Error(`CodeGen: wrong number of nodes: ${C} vs ${g} expected`);return this._nodes.length=w,this}func(g,w=e.nil,C,V){return this._blockNode(new P(g,w,C)),V&&this.code(V).endFunc(),this}endFunc(){return this._endBlockNode(P)}optimize(g=1){for(;g-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(g){return this._currNode.nodes.push(g),this}_blockNode(g){this._currNode.nodes.push(g),this._nodes.push(g)}_endBlockNode(g,w){const C=this._currNode;if(C instanceof g||w&&C instanceof w)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${w?`${g.kind}/${w.kind}`:g.kind}"`)}_elseNode(g){const w=this._currNode;if(!(w instanceof m))throw new Error('CodeGen: "else" without "if"');return this._currNode=w.else=g,this}get _root(){return this._nodes[0]}get _currNode(){const g=this._nodes;return g[g.length-1]}set _currNode(g){const w=this._nodes;w[w.length-1]=g}}t.CodeGen=O;function B(k,g){for(const w in g)k[w]=(k[w]||0)+(g[w]||0);return k}function Z(k,g){return g instanceof e._CodeOrName?B(k,g.names):k}function I(k,g,w){if(k instanceof e.Name)return C(k);if(!V(k))return k;return new e._Code(k._items.reduce((F,ne)=>(ne instanceof e.Name&&(ne=C(ne)),ne instanceof e._Code?F.push(...ne._items):F.push(ne),F),[]));function C(F){const ne=w[F.str];return ne===void 0||g[F.str]!==1?F:(delete g[F.str],ne)}function V(F){return F instanceof e._Code&&F._items.some(ne=>ne instanceof e.Name&&g[ne.str]===1&&w[ne.str]!==void 0)}}function Q(k,g){for(const w in g)k[w]=(k[w]||0)-(g[w]||0)}function G(k){return typeof k=="boolean"||typeof k=="number"||k===null?!k:(0,e._)`!${A(k)}`}t.not=G;const re=S(t.operators.AND);function Oe(...k){return k.reduce(re)}t.and=Oe;const Ee=S(t.operators.OR);function M(...k){return k.reduce(Ee)}t.or=M;function S(k){return(g,w)=>g===e.nil?w:w===e.nil?g:(0,e._)`${A(g)} ${k} ${A(w)}`}function A(k){return k instanceof e.Name?k:(0,e._)`(${k})`}})(Se);var X={};Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;const Ne=Se,_P=Yi;function bP(t){const e={};for(const r of t)e[r]=!0;return e}X.toHash=bP;function $P(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(R0(t,e),!A0(e,t.self.RULES.all))}X.alwaysValidSchema=$P;function R0(t,e=t.schema){const{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;const s=n.RULES.keywords;for(const i in e)s[i]||O0(t,`unknown keyword: "${i}"`)}X.checkUnknownRules=R0;function A0(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(e[r])return!0;return!1}X.schemaHasRules=A0;function SP(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}X.schemaHasRulesButRef=SP;function kP({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ne._)`${r}`}return(0,Ne._)`${t}${e}${(0,Ne.getProperty)(n)}`}X.schemaRefOrVal=kP;function xP(t){return M0(decodeURIComponent(t))}X.unescapeFragment=xP;function EP(t){return encodeURIComponent(id(t))}X.escapeFragment=EP;function id(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=id;function M0(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=M0;function CP(t,e){if(Array.isArray(t))for(const r of t)e(r);else e(t)}X.eachItem=CP;function Hp({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,i,o,a)=>{const l=o===void 0?i:o instanceof Ne.Name?(i instanceof Ne.Name?t(s,i,o):e(s,i,o),o):i instanceof Ne.Name?(e(s,o,i),i):r(i,o);return a===Ne.Name&&!(l instanceof Ne.Name)?n(s,l):l}}X.mergeEvaluated={props:Hp({mergeNames:(t,e,r)=>t.if((0,Ne._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ne._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ne._)`${r} || {}`).code((0,Ne._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ne._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ne._)`${r} || {}`),od(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:I0}),items:Hp({mergeNames:(t,e,r)=>t.if((0,Ne._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ne._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ne._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ne._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function I0(t,e){if(e===!0)return t.var("props",!0);const r=t.var("props",(0,Ne._)`{}`);return e!==void 0&&od(t,r,e),r}X.evaluatedPropsToName=I0;function od(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ne._)`${e}${(0,Ne.getProperty)(n)}`,!0))}X.setEvaluated=od;const Up={};function PP(t,e){return t.scopeValue("func",{ref:e,code:Up[e.code]||(Up[e.code]=new _P._Code(e.code))})}X.useFunc=PP;var ru;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ru||(X.Type=ru={}));function TP(t,e,r){if(t instanceof Ne.Name){const n=e===ru.Num;return r?n?(0,Ne._)`"[" + ${t} + "]"`:(0,Ne._)`"['" + ${t} + "']"`:n?(0,Ne._)`"/" + ${t}`:(0,Ne._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ne.getProperty)(t).toString():"/"+id(t)}X.getErrorPath=TP;function O0(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}X.checkStrictMode=O0;var qr={};Object.defineProperty(qr,"__esModule",{value:!0});const xt=Se,RP={data:new xt.Name("data"),valCxt:new xt.Name("valCxt"),instancePath:new xt.Name("instancePath"),parentData:new xt.Name("parentData"),parentDataProperty:new xt.Name("parentDataProperty"),rootData:new xt.Name("rootData"),dynamicAnchors:new xt.Name("dynamicAnchors"),vErrors:new xt.Name("vErrors"),errors:new xt.Name("errors"),this:new xt.Name("this"),self:new xt.Name("self"),scope:new xt.Name("scope"),json:new xt.Name("json"),jsonPos:new xt.Name("jsonPos"),jsonLen:new xt.Name("jsonLen"),jsonPart:new xt.Name("jsonPart")};qr.default=RP;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=Se,r=X,n=qr;t.keywordError={message:({keyword:v})=>(0,e.str)`must pass "${v}" keyword validation`},t.keyword$DataError={message:({keyword:v,schemaType:m})=>m?(0,e.str)`"${v}" keyword must be ${m} ($data)`:(0,e.str)`"${v}" keyword is invalid ($data)`};function s(v,m=t.keywordError,_,$){const{it:E}=v,{gen:x,compositeRule:P,allErrors:R}=E,z=h(v,m,_);$??(P||R)?l(x,z):c(E,(0,e._)`[${z}]`)}t.reportError=s;function i(v,m=t.keywordError,_){const{it:$}=v,{gen:E,compositeRule:x,allErrors:P}=$,R=h(v,m,_);l(E,R),x||P||c($,n.default.vErrors)}t.reportExtraError=i;function o(v,m){v.assign(n.default.errors,m),v.if((0,e._)`${n.default.vErrors} !== null`,()=>v.if(m,()=>v.assign((0,e._)`${n.default.vErrors}.length`,m),()=>v.assign(n.default.vErrors,null)))}t.resetErrorsCount=o;function a({gen:v,keyword:m,schemaValue:_,data:$,errsCount:E,it:x}){if(E===void 0)throw new Error("ajv implementation error");const P=v.name("err");v.forRange("i",E,n.default.errors,R=>{v.const(P,(0,e._)`${n.default.vErrors}[${R}]`),v.if((0,e._)`${P}.instancePath === undefined`,()=>v.assign((0,e._)`${P}.instancePath`,(0,e.strConcat)(n.default.instancePath,x.errorPath))),v.assign((0,e._)`${P}.schemaPath`,(0,e.str)`${x.errSchemaPath}/${m}`),x.opts.verbose&&(v.assign((0,e._)`${P}.schema`,_),v.assign((0,e._)`${P}.data`,$))})}t.extendErrors=a;function l(v,m){const _=v.const("err",m);v.if((0,e._)`${n.default.vErrors} === null`,()=>v.assign(n.default.vErrors,(0,e._)`[${_}]`),(0,e._)`${n.default.vErrors}.push(${_})`),v.code((0,e._)`${n.default.errors}++`)}function c(v,m){const{gen:_,validateName:$,schemaEnv:E}=v;E.$async?_.throw((0,e._)`new ${v.ValidationError}(${m})`):(_.assign((0,e._)`${$}.errors`,m),_.return(!1))}const u={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function h(v,m,_){const{createErrors:$}=v.it;return $===!1?(0,e._)`{}`:d(v,m,_)}function d(v,m,_={}){const{gen:$,it:E}=v,x=[f(E,_),p(v,_)];return y(v,m,x),$.object(...x)}function f({errorPath:v},{instancePath:m}){const _=m?(0,e.str)`${v}${(0,r.getErrorPath)(m,r.Type.Str)}`:v;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,_)]}function p({keyword:v,it:{errSchemaPath:m}},{schemaPath:_,parentSchema:$}){let E=$?m:(0,e.str)`${m}/${v}`;return _&&(E=(0,e.str)`${E}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,E]}function y(v,{params:m,message:_},$){const{keyword:E,data:x,schemaValue:P,it:R}=v,{opts:z,propertyName:L,topSchemaRef:H,schemaPath:O}=R;$.push([u.keyword,E],[u.params,typeof m=="function"?m(v):m||(0,e._)`{}`]),z.messages&&$.push([u.message,typeof _=="function"?_(v):_]),z.verbose&&$.push([u.schema,P],[u.parentSchema,(0,e._)`${H}${O}`],[n.default.data,x]),L&&$.push([u.propertyName,L])}})(_o);Object.defineProperty(qs,"__esModule",{value:!0});qs.boolOrEmptySchema=qs.topBoolOrEmptySchema=void 0;const AP=_o,MP=Se,IP=qr,OP={message:"boolean schema is false"};function NP(t){const{gen:e,schema:r,validateName:n}=t;r===!1?N0(t,!1):typeof r=="object"&&r.$async===!0?e.return(IP.default.data):(e.assign((0,MP._)`${n}.errors`,null),e.return(!0))}qs.topBoolOrEmptySchema=NP;function jP(t,e){const{gen:r,schema:n}=t;n===!1?(r.var(e,!1),N0(t)):r.var(e,!0)}qs.boolOrEmptySchema=jP;function N0(t,e){const{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,AP.reportError)(s,OP,void 0,e)}var it={},ns={};Object.defineProperty(ns,"__esModule",{value:!0});ns.getRules=ns.isJSONType=void 0;const DP=["string","number","integer","boolean","null","object","array"],LP=new Set(DP);function zP(t){return typeof t=="string"&&LP.has(t)}ns.isJSONType=zP;function FP(){const t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}ns.getRules=FP;var Xr={};Object.defineProperty(Xr,"__esModule",{value:!0});Xr.shouldUseRule=Xr.shouldUseGroup=Xr.schemaHasRulesForType=void 0;function qP({schema:t,self:e},r){const n=e.RULES.types[r];return n&&n!==!0&&j0(t,n)}Xr.schemaHasRulesForType=qP;function j0(t,e){return e.rules.some(r=>D0(t,r))}Xr.shouldUseGroup=j0;function D0(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Xr.shouldUseRule=D0;Object.defineProperty(it,"__esModule",{value:!0});it.reportTypeError=it.checkDataTypes=it.checkDataType=it.coerceAndCheckDataType=it.getJSONTypes=it.getSchemaTypes=it.DataType=void 0;const BP=ns,VP=Xr,HP=_o,me=Se,L0=X;var As;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(As||(it.DataType=As={}));function UP(t){const e=z0(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}it.getSchemaTypes=UP;function z0(t){const e=Array.isArray(t)?t:t?[t]:[];if(e.every(BP.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}it.getJSONTypes=z0;function WP(t,e){const{gen:r,data:n,opts:s}=t,i=KP(e,s.coerceTypes),o=e.length>0&&!(i.length===0&&e.length===1&&(0,VP.schemaHasRulesForType)(t,e[0]));if(o){const a=ad(e,n,s.strictNumbers,As.Wrong);r.if(a,()=>{i.length?ZP(t,e,i):ld(t)})}return o}it.coerceAndCheckDataType=WP;const F0=new Set(["string","number","integer","boolean","null"]);function KP(t,e){return e?t.filter(r=>F0.has(r)||e==="array"&&r==="array"):[]}function ZP(t,e,r){const{gen:n,data:s,opts:i}=t,o=n.let("dataType",(0,me._)`typeof ${s}`),a=n.let("coerced",(0,me._)`undefined`);i.coerceTypes==="array"&&n.if((0,me._)`${o} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,me._)`${s}[0]`).assign(o,(0,me._)`typeof ${s}`).if(ad(e,s,i.strictNumbers),()=>n.assign(a,s))),n.if((0,me._)`${a} !== undefined`);for(const c of r)(F0.has(c)||c==="array"&&i.coerceTypes==="array")&&l(c);n.else(),ld(t),n.endIf(),n.if((0,me._)`${a} !== undefined`,()=>{n.assign(s,a),GP(t,a)});function l(c){switch(c){case"string":n.elseIf((0,me._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,me._)`"" + ${s}`).elseIf((0,me._)`${s} === null`).assign(a,(0,me._)`""`);return;case"number":n.elseIf((0,me._)`${o} == "boolean" || ${s} === null + || (${o} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,me._)`+${s}`);return;case"integer":n.elseIf((0,me._)`${o} === "boolean" || ${s} === null + || (${o} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,me._)`+${s}`);return;case"boolean":n.elseIf((0,me._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,me._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,me._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,me._)`${o} === "string" || ${o} === "number" + || ${o} === "boolean" || ${s} === null`).assign(a,(0,me._)`[${s}]`)}}}function GP({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,me._)`${e} !== undefined`,()=>t.assign((0,me._)`${e}[${r}]`,n))}function nu(t,e,r,n=As.Correct){const s=n===As.Correct?me.operators.EQ:me.operators.NEQ;let i;switch(t){case"null":return(0,me._)`${e} ${s} null`;case"array":i=(0,me._)`Array.isArray(${e})`;break;case"object":i=(0,me._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=o((0,me._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=o();break;default:return(0,me._)`typeof ${e} ${s} ${t}`}return n===As.Correct?i:(0,me.not)(i);function o(a=me.nil){return(0,me.and)((0,me._)`typeof ${e} == "number"`,a,r?(0,me._)`isFinite(${e})`:me.nil)}}it.checkDataType=nu;function ad(t,e,r,n){if(t.length===1)return nu(t[0],e,r,n);let s;const i=(0,L0.toHash)(t);if(i.array&&i.object){const o=(0,me._)`typeof ${e} != "object"`;s=i.null?o:(0,me._)`!${e} || ${o}`,delete i.null,delete i.array,delete i.object}else s=me.nil;i.number&&delete i.integer;for(const o in i)s=(0,me.and)(s,nu(o,e,r,n));return s}it.checkDataTypes=ad;const JP={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,me._)`{type: ${t}}`:(0,me._)`{type: ${e}}`};function ld(t){const e=YP(t);(0,HP.reportError)(e,JP)}it.reportTypeError=ld;function YP(t){const{gen:e,data:r,schema:n}=t,s=(0,L0.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}var Al={};Object.defineProperty(Al,"__esModule",{value:!0});Al.assignDefaults=void 0;const ms=Se,QP=X;function XP(t,e){const{properties:r,items:n}=t.schema;if(e==="object"&&r)for(const s in r)Wp(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,i)=>Wp(t,i,s.default))}Al.assignDefaults=XP;function Wp(t,e,r){const{gen:n,compositeRule:s,data:i,opts:o}=t;if(r===void 0)return;const a=(0,ms._)`${i}${(0,ms.getProperty)(e)}`;if(s){(0,QP.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,ms._)`${a} === undefined`;o.useDefaults==="empty"&&(l=(0,ms._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,ms._)`${a} = ${(0,ms.stringify)(r)}`)}var Ir={},be={};Object.defineProperty(be,"__esModule",{value:!0});be.validateUnion=be.validateArray=be.usePattern=be.callValidateCode=be.schemaProperties=be.allSchemaProperties=be.noPropertyInData=be.propertyInData=be.isOwnProperty=be.hasPropFunc=be.reportMissingProp=be.checkMissingProp=be.checkReportMissingProp=void 0;const Be=Se,cd=X,cn=qr,eT=X;function tT(t,e){const{gen:r,data:n,it:s}=t;r.if(hd(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Be._)`${e}`},!0),t.error()})}be.checkReportMissingProp=tT;function rT({gen:t,data:e,it:{opts:r}},n,s){return(0,Be.or)(...n.map(i=>(0,Be.and)(hd(t,e,i,r.ownProperties),(0,Be._)`${s} = ${i}`)))}be.checkMissingProp=rT;function nT(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=nT;function q0(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Be._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=q0;function ud(t,e,r){return(0,Be._)`${q0(t)}.call(${e}, ${r})`}be.isOwnProperty=ud;function sT(t,e,r,n){const s=(0,Be._)`${e}${(0,Be.getProperty)(r)} !== undefined`;return n?(0,Be._)`${s} && ${ud(t,e,r)}`:s}be.propertyInData=sT;function hd(t,e,r,n){const s=(0,Be._)`${e}${(0,Be.getProperty)(r)} === undefined`;return n?(0,Be.or)(s,(0,Be.not)(ud(t,e,r))):s}be.noPropertyInData=hd;function B0(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=B0;function iT(t,e){return B0(e).filter(r=>!(0,cd.alwaysValidSchema)(t,e[r]))}be.schemaProperties=iT;function oT({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:i},it:o},a,l,c){const u=c?(0,Be._)`${t}, ${e}, ${n}${s}`:e,h=[[cn.default.instancePath,(0,Be.strConcat)(cn.default.instancePath,i)],[cn.default.parentData,o.parentData],[cn.default.parentDataProperty,o.parentDataProperty],[cn.default.rootData,cn.default.rootData]];o.opts.dynamicRef&&h.push([cn.default.dynamicAnchors,cn.default.dynamicAnchors]);const d=(0,Be._)`${u}, ${r.object(...h)}`;return l!==Be.nil?(0,Be._)`${a}.call(${l}, ${d})`:(0,Be._)`${a}(${d})`}be.callValidateCode=oT;const aT=(0,Be._)`new RegExp`;function lT({gen:t,it:{opts:e}},r){const n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,i=s(r,n);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,Be._)`${s.code==="new RegExp"?aT:(0,eT.useFunc)(t,s)}(${r}, ${n})`})}be.usePattern=lT;function cT(t){const{gen:e,data:r,keyword:n,it:s}=t,i=e.name("valid");if(s.allErrors){const a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(i,!0),o(()=>e.break()),i;function o(a){const l=e.const("len",(0,Be._)`${r}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:n,dataProp:c,dataPropType:cd.Type.Num},i),e.if((0,Be.not)(i),a)})}}be.validateArray=cT;function uT(t){const{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,cd.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;const o=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,c)=>{const u=t.subschema({keyword:n,schemaProp:c,compositeRule:!0},a);e.assign(o,(0,Be._)`${o} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Be.not)(o))})),t.result(o,()=>t.reset(),()=>t.error(!0))}be.validateUnion=uT;Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateKeywordUsage=Ir.validSchemaType=Ir.funcKeywordCode=Ir.macroKeywordCode=void 0;const Rt=Se,Un=qr,hT=be,dT=_o;function fT(t,e){const{gen:r,keyword:n,schema:s,parentSchema:i,it:o}=t,a=e.macro.call(o.self,s,i,o),l=V0(r,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);const c=r.name("valid");t.subschema({schema:a,schemaPath:Rt.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}Ir.macroKeywordCode=fT;function pT(t,e){var r;const{gen:n,keyword:s,schema:i,parentSchema:o,$data:a,it:l}=t;gT(l,e);const c=!a&&e.compile?e.compile.call(l.self,i,o,l):e.validate,u=V0(n,s,c),h=n.let("valid");t.block$data(h,d),t.ok((r=e.valid)!==null&&r!==void 0?r:h);function d(){if(e.errors===!1)y(),e.modifying&&Kp(t),v(()=>t.error());else{const m=e.async?f():p();e.modifying&&Kp(t),v(()=>mT(t,m))}}function f(){const m=n.let("ruleErrs",null);return n.try(()=>y((0,Rt._)`await `),_=>n.assign(h,!1).if((0,Rt._)`${_} instanceof ${l.ValidationError}`,()=>n.assign(m,(0,Rt._)`${_}.errors`),()=>n.throw(_))),m}function p(){const m=(0,Rt._)`${u}.errors`;return n.assign(m,null),y(Rt.nil),m}function y(m=e.async?(0,Rt._)`await `:Rt.nil){const _=l.opts.passContext?Un.default.this:Un.default.self,$=!("compile"in e&&!a||e.schema===!1);n.assign(h,(0,Rt._)`${m}${(0,hT.callValidateCode)(t,u,_,$)}`,e.modifying)}function v(m){var _;n.if((0,Rt.not)((_=e.valid)!==null&&_!==void 0?_:h),m)}}Ir.funcKeywordCode=pT;function Kp(t){const{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Rt._)`${n.parentData}[${n.parentDataProperty}]`))}function mT(t,e){const{gen:r}=t;r.if((0,Rt._)`Array.isArray(${e})`,()=>{r.assign(Un.default.vErrors,(0,Rt._)`${Un.default.vErrors} === null ? ${e} : ${Un.default.vErrors}.concat(${e})`).assign(Un.default.errors,(0,Rt._)`${Un.default.vErrors}.length`),(0,dT.extendErrors)(t)},()=>t.error())}function gT({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function V0(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Rt.stringify)(r)})}function yT(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ir.validSchemaType=yT;function vT({schema:t,opts:e,self:r,errSchemaPath:n},s,i){if(Array.isArray(s.keyword)?!s.keyword.includes(i):s.keyword!==i)throw new Error("ajv implementation error");const o=s.dependencies;if(o!=null&&o.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${o.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[i])){const l=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Ir.validateKeywordUsage=vT;var xn={};Object.defineProperty(xn,"__esModule",{value:!0});xn.extendSubschemaMode=xn.extendSubschemaData=xn.getSubschema=void 0;const Tr=Se,H0=X;function wT(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:i,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){const a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Tr._)`${t.schemaPath}${(0,Tr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Tr._)`${t.schemaPath}${(0,Tr.getProperty)(e)}${(0,Tr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,H0.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||i===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:o,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}xn.getSubschema=wT;function _T(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:i,propertyName:o}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=e;if(r!==void 0){const{errorPath:c,dataPathArr:u,opts:h}=e,d=a.let("data",(0,Tr._)`${e.data}${(0,Tr.getProperty)(r)}`,!0);l(d),t.errorPath=(0,Tr.str)`${c}${(0,H0.getErrorPath)(r,n,h.jsPropertySyntax)}`,t.parentDataProperty=(0,Tr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(s!==void 0){const c=s instanceof Tr.Name?s:a.let("data",s,!0);l(c),o!==void 0&&(t.propertyName=o)}i&&(t.dataTypes=i);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}xn.extendSubschemaData=_T;function bT(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:i}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=r}xn.extendSubschemaMode=bT;var yt={},Ml=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,i;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[s]))return!1;for(s=n;s--!==0;){var o=i[s];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r},U0={exports:{}},_n=U0.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};ga(e,n,s,t,"",t)};_n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};_n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};_n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};_n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function ga(t,e,r,n,s,i,o,a,l,c){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,i,o,a,l,c);for(var u in n){var h=n[u];if(Array.isArray(h)){if(u in _n.arrayKeywords)for(var d=0;de+=W0(n)),e===1/0))return 1/0}return e}function K0(t,e="",r){r!==!1&&(e=Ms(e));const n=t.parse(e);return Z0(t,n)}yt.getFullPath=K0;function Z0(t,e){return t.serialize(e).split("#")[0]+"#"}yt._getFullPath=Z0;const RT=/#\/?$/;function Ms(t){return t?t.replace(RT,""):""}yt.normalizeId=Ms;function AT(t,e,r){return r=Ms(r),t.resolve(e,r)}yt.resolveUrl=AT;const MT=/^[a-z_][-a-z0-9._]*$/i;function IT(t,e){if(typeof t=="boolean")return{};const{schemaId:r,uriResolver:n}=this.opts,s=Ms(t[r]||e),i={"":s},o=K0(n,s,!1),a={},l=new Set;return ET(t,{allKeys:!0},(h,d,f,p)=>{if(p===void 0)return;const y=o+d;let v=i[p];typeof h[r]=="string"&&(v=m.call(this,h[r])),_.call(this,h.$anchor),_.call(this,h.$dynamicAnchor),i[d]=v;function m($){const E=this.opts.uriResolver.resolve;if($=Ms(v?E(v,$):$),l.has($))throw u($);l.add($);let x=this.refs[$];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?c(h,x.schema,$):$!==Ms(y)&&($[0]==="#"?(c(h,a[$],$),a[$]=h):this.refs[$]=y),$}function _($){if(typeof $=="string"){if(!MT.test($))throw new Error(`invalid anchor "${$}"`);m.call(this,`#${$}`)}}}),a;function c(h,d,f){if(d!==void 0&&!xT(h,d))throw u(f)}function u(h){return new Error(`reference "${h}" resolves to more than one schema`)}}yt.getSchemaRefs=IT;Object.defineProperty(fr,"__esModule",{value:!0});fr.getData=fr.KeywordCxt=fr.validateFunctionCode=void 0;const G0=qs,Zp=it,dd=Xr,La=it,OT=Al,Ai=Ir,ic=xn,oe=Se,he=qr,NT=yt,en=X,pi=_o;function jT(t){if(Q0(t)&&(X0(t),Y0(t))){zT(t);return}J0(t,()=>(0,G0.topBoolOrEmptySchema)(t))}fr.validateFunctionCode=jT;function J0({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},i){s.code.es5?t.func(e,(0,oe._)`${he.default.data}, ${he.default.valCxt}`,n.$async,()=>{t.code((0,oe._)`"use strict"; ${Gp(r,s)}`),LT(t,s),t.code(i)}):t.func(e,(0,oe._)`${he.default.data}, ${DT(s)}`,n.$async,()=>t.code(Gp(r,s)).code(i))}function DT(t){return(0,oe._)`{${he.default.instancePath}="", ${he.default.parentData}, ${he.default.parentDataProperty}, ${he.default.rootData}=${he.default.data}${t.dynamicRef?(0,oe._)`, ${he.default.dynamicAnchors}={}`:oe.nil}}={}`}function LT(t,e){t.if(he.default.valCxt,()=>{t.var(he.default.instancePath,(0,oe._)`${he.default.valCxt}.${he.default.instancePath}`),t.var(he.default.parentData,(0,oe._)`${he.default.valCxt}.${he.default.parentData}`),t.var(he.default.parentDataProperty,(0,oe._)`${he.default.valCxt}.${he.default.parentDataProperty}`),t.var(he.default.rootData,(0,oe._)`${he.default.valCxt}.${he.default.rootData}`),e.dynamicRef&&t.var(he.default.dynamicAnchors,(0,oe._)`${he.default.valCxt}.${he.default.dynamicAnchors}`)},()=>{t.var(he.default.instancePath,(0,oe._)`""`),t.var(he.default.parentData,(0,oe._)`undefined`),t.var(he.default.parentDataProperty,(0,oe._)`undefined`),t.var(he.default.rootData,he.default.data),e.dynamicRef&&t.var(he.default.dynamicAnchors,(0,oe._)`{}`)})}function zT(t){const{schema:e,opts:r,gen:n}=t;J0(t,()=>{r.$comment&&e.$comment&&tv(t),HT(t),n.let(he.default.vErrors,null),n.let(he.default.errors,0),r.unevaluated&&FT(t),ev(t),KT(t)})}function FT(t){const{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,oe._)`${r}.evaluated`),e.if((0,oe._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,oe._)`${t.evaluated}.props`,(0,oe._)`undefined`)),e.if((0,oe._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,oe._)`${t.evaluated}.items`,(0,oe._)`undefined`))}function Gp(t,e){const r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,oe._)`/*# sourceURL=${r} */`:oe.nil}function qT(t,e){if(Q0(t)&&(X0(t),Y0(t))){BT(t,e);return}(0,G0.boolOrEmptySchema)(t,e)}function Y0({schema:t,self:e}){if(typeof t=="boolean")return!t;for(const r in t)if(e.RULES.all[r])return!0;return!1}function Q0(t){return typeof t.schema!="boolean"}function BT(t,e){const{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&tv(t),UT(t),WT(t);const i=n.const("_errs",he.default.errors);ev(t,i),n.var(e,(0,oe._)`${i} === ${he.default.errors}`)}function X0(t){(0,en.checkUnknownRules)(t),VT(t)}function ev(t,e){if(t.opts.jtd)return Jp(t,[],!1,e);const r=(0,Zp.getSchemaTypes)(t.schema),n=(0,Zp.coerceAndCheckDataType)(t,r);Jp(t,r,!n,e)}function VT(t){const{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,en.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function HT(t){const{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,en.checkStrictMode)(t,"default is ignored in the schema root")}function UT(t){const e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,NT.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function WT(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function tv({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){const i=r.$comment;if(s.$comment===!0)t.code((0,oe._)`${he.default.self}.logger.log(${i})`);else if(typeof s.$comment=="function"){const o=(0,oe.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,oe._)`${he.default.self}.opts.$comment(${i}, ${o}, ${a}.schema)`)}}function KT(t){const{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:i}=t;r.$async?e.if((0,oe._)`${he.default.errors} === 0`,()=>e.return(he.default.data),()=>e.throw((0,oe._)`new ${s}(${he.default.vErrors})`)):(e.assign((0,oe._)`${n}.errors`,he.default.vErrors),i.unevaluated&&ZT(t),e.return((0,oe._)`${he.default.errors} === 0`))}function ZT({gen:t,evaluated:e,props:r,items:n}){r instanceof oe.Name&&t.assign((0,oe._)`${e}.props`,r),n instanceof oe.Name&&t.assign((0,oe._)`${e}.items`,n)}function Jp(t,e,r,n){const{gen:s,schema:i,data:o,allErrors:a,opts:l,self:c}=t,{RULES:u}=c;if(i.$ref&&(l.ignoreKeywordsWithRef||!(0,en.schemaHasRulesButRef)(i,u))){s.block(()=>sv(t,"$ref",u.all.$ref.definition));return}l.jtd||GT(t,e),s.block(()=>{for(const d of u.rules)h(d);h(u.post)});function h(d){(0,dd.shouldUseGroup)(i,d)&&(d.type?(s.if((0,La.checkDataType)(d.type,o,l.strictNumbers)),Yp(t,d),e.length===1&&e[0]===d.type&&r&&(s.else(),(0,La.reportTypeError)(t)),s.endIf()):Yp(t,d),a||s.if((0,oe._)`${he.default.errors} === ${n||0}`))}}function Yp(t,e){const{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,OT.assignDefaults)(t,e.type),r.block(()=>{for(const i of e.rules)(0,dd.shouldUseRule)(n,i)&&sv(t,i.keyword,i.definition,e.type)})}function GT(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(JT(t,e),t.opts.allowUnionTypes||YT(t,e),QT(t,t.dataTypes))}function JT(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{rv(t.dataTypes,r)||fd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),eR(t,e)}}function YT(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&fd(t,"use allowUnionTypes to allow union type keyword")}function QT(t,e){const r=t.self.RULES.all;for(const n in r){const s=r[n];if(typeof s=="object"&&(0,dd.shouldUseRule)(t.schema,s)){const{type:i}=s.definition;i.length&&!i.some(o=>XT(e,o))&&fd(t,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function XT(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function rv(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function eR(t,e){const r=[];for(const n of t.dataTypes)rv(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function fd(t,e){const r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,en.checkStrictMode)(t,e,t.opts.strictTypes)}let nv=class{constructor(e,r,n){if((0,Ai.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,en.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",iv(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ai.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",he.default.errors))}result(e,r,n){this.failResult((0,oe.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,oe.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:r}=this;this.fail((0,oe._)`${r} !== undefined && (${(0,oe.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?pi.reportExtraError:pi.reportError)(this,this.def.error,r)}$dataError(){(0,pi.reportError)(this,this.def.$dataError||pi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,pi.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=oe.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=oe.nil,r=oe.nil){if(!this.$data)return;const{gen:n,schemaCode:s,schemaType:i,def:o}=this;n.if((0,oe.or)((0,oe._)`${s} === undefined`,r)),e!==oe.nil&&n.assign(e,!0),(i.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==oe.nil&&n.assign(e,!1)),n.else()}invalid$data(){const{gen:e,schemaCode:r,schemaType:n,def:s,it:i}=this;return(0,oe.or)(o(),a());function o(){if(n.length){if(!(r instanceof oe.Name))throw new Error("ajv implementation error");const l=Array.isArray(n)?n:[n];return(0,oe._)`${(0,La.checkDataTypes)(l,r,i.opts.strictNumbers,La.DataType.Wrong)}`}return oe.nil}function a(){if(s.validateSchema){const l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,oe._)`!${l}(${r})`}return oe.nil}}subschema(e,r){const n=(0,ic.getSubschema)(this.it,e);(0,ic.extendSubschemaData)(n,this.it,e),(0,ic.extendSubschemaMode)(n,e);const s={...this.it,...n,items:void 0,props:void 0};return qT(s,r),s}mergeEvaluated(e,r){const{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=en.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=en.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){const{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,oe.Name)),!0}};fr.KeywordCxt=nv;function sv(t,e,r,n){const s=new nv(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Ai.funcKeywordCode)(s,r):"macro"in r?(0,Ai.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Ai.funcKeywordCode)(s,r)}const tR=/^\/(?:[^~]|~0|~1)*$/,rR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function iv(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,i;if(t==="")return he.default.rootData;if(t[0]==="/"){if(!tR.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,i=he.default.rootData}else{const c=rR.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);const u=+c[1];if(s=c[2],s==="#"){if(u>=e)throw new Error(l("property/index",u));return n[e-u]}if(u>e)throw new Error(l("data",u));if(i=r[e-u],!s)return i}let o=i;const a=s.split("/");for(const c of a)c&&(i=(0,oe._)`${i}${(0,oe.getProperty)((0,en.unescapeJsonPointer)(c))}`,o=(0,oe._)`${o} && ${i}`);return o;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}fr.getData=iv;var bo={};Object.defineProperty(bo,"__esModule",{value:!0});let nR=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};bo.default=nR;var ni={};Object.defineProperty(ni,"__esModule",{value:!0});const oc=yt;let sR=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,oc.resolveUrl)(e,r,n),this.missingSchema=(0,oc.normalizeId)((0,oc.getFullPath)(e,this.missingRef))}};ni.default=sR;var Lt={};Object.defineProperty(Lt,"__esModule",{value:!0});Lt.resolveSchema=Lt.getCompilingSchema=Lt.resolveRef=Lt.compileSchema=Lt.SchemaEnv=void 0;const ir=Se,iR=bo,Ln=qr,cr=yt,Qp=X,oR=fr;let Il=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,cr.normalizeId)(n==null?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n==null?void 0:n.$async,this.refs={}}};Lt.SchemaEnv=Il;function pd(t){const e=ov.call(this,t);if(e)return e;const r=(0,cr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:i}=this.opts,o=new ir.CodeGen(this.scope,{es5:n,lines:s,ownProperties:i});let a;t.$async&&(a=o.scopeValue("Error",{ref:iR.default,code:(0,ir._)`require("ajv/dist/runtime/validation_error").default`}));const l=o.scopeName("validate");t.validateName=l;const c={gen:o,allErrors:this.opts.allErrors,data:Ln.default.data,parentData:Ln.default.parentData,parentDataProperty:Ln.default.parentDataProperty,dataNames:[Ln.default.data],dataPathArr:[ir.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ir.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ir.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ir._)`""`,opts:this.opts,self:this};let u;try{this._compilations.add(t),(0,oR.validateFunctionCode)(c),o.optimize(this.opts.code.optimize);const h=o.toString();u=`${o.scopeRefs(Ln.default.scope)}return ${h}`,this.opts.code.process&&(u=this.opts.code.process(u,t));const f=new Function(`${Ln.default.self}`,`${Ln.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:l,validateCode:h,scopeValues:o._values}),this.opts.unevaluated){const{props:p,items:y}=c;f.evaluated={props:p instanceof ir.Name?void 0:p,items:y instanceof ir.Name?void 0:y,dynamicProps:p instanceof ir.Name,dynamicItems:y instanceof ir.Name},f.source&&(f.source.evaluated=(0,ir.stringify)(f.evaluated))}return t.validate=f,t}catch(h){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),h}finally{this._compilations.delete(t)}}Lt.compileSchema=pd;function aR(t,e,r){var n;r=(0,cr.resolveUrl)(this.opts.uriResolver,e,r);const s=t.refs[r];if(s)return s;let i=uR.call(this,t,r);if(i===void 0){const o=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;o&&(i=new Il({schema:o,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[r]=lR.call(this,i)}Lt.resolveRef=aR;function lR(t){return(0,cr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:pd.call(this,t)}function ov(t){for(const e of this._compilations)if(cR(e,t))return e}Lt.getCompilingSchema=ov;function cR(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function uR(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ol.call(this,t,e)}function Ol(t,e){const r=this.opts.uriResolver.parse(e),n=(0,cr._getFullPath)(this.opts.uriResolver,r);let s=(0,cr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return ac.call(this,r,t);const i=(0,cr.normalizeId)(n),o=this.refs[i]||this.schemas[i];if(typeof o=="string"){const a=Ol.call(this,t,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:ac.call(this,r,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||pd.call(this,o),i===(0,cr.normalizeId)(e)){const{schema:a}=o,{schemaId:l}=this.opts,c=a[l];return c&&(s=(0,cr.resolveUrl)(this.opts.uriResolver,s,c)),new Il({schema:a,schemaId:l,root:t,baseId:s})}return ac.call(this,r,o)}}Lt.resolveSchema=Ol;const hR=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ac(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(const a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;const l=r[(0,Qp.unescapeFragment)(a)];if(l===void 0)return;r=l;const c=typeof r=="object"&&r[this.opts.schemaId];!hR.has(a)&&c&&(e=(0,cr.resolveUrl)(this.opts.uriResolver,e,c))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Qp.schemaHasRulesButRef)(r,this.RULES)){const a=(0,cr.resolveUrl)(this.opts.uriResolver,e,r.$ref);i=Ol.call(this,n,a)}const{schemaId:o}=this.opts;if(i=i||new Il({schema:r,schemaId:o,root:n,baseId:e}),i.schema!==i.root.schema)return i}const dR="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",fR="Meta-schema for $data reference (JSON AnySchema extension proposal)",pR="object",mR=["$data"],gR={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},yR=!1,vR={$id:dR,description:fR,type:pR,required:mR,properties:gR,additionalProperties:yR};var md={},Nl={exports:{}};const wR=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),av=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),gd=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),lv=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),_R=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function cv(t){let e="",r=0,n=0;for(n=0;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}const bR=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Xp(t){return t.length=0,!0}function $R(t,e,r){if(t.length){const n=cv(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function SR(t){let e=0;const r={error:!1,address:"",zone:""},n=[],s=[];let i=!1,o=!1,a=$R;for(let l=0;l7){r.error=!0;break}l>0&&t[l-1]===":"&&(i=!0),n.push(":");continue}else if(c==="%"){if(!a(s,n,r))break;a=Xp}else{s.push(c);continue}}return s.length&&(a===Xp?r.zone=s.join(""):o?n.push(s.join("")):n.push(cv(s))),r.address=n.join(""),r}function uv(t){if(kR(t,":")<2)return{host:t,isIPV6:!1};const e=SR(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function kR(t,e){let r=0;for(let n=0;nER[n])}function TR(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n65535))return"URI port is malformed."}function Fa(t,e){const r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let s=!1,i=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);const o=t.match(iA);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",s=!0);const a=t.match(oA);if(a!==null){const c=a[1],u=c.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",s=!0):c.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",s=!0))}const l=t.match(sA);if(l){n.scheme=l[1],n.userinfo=l[3],n.host=l[4],n.port=parseInt(l[5],10),n.path=l[6]||"",n.query=l[7],n.fragment=l[8],isNaN(n.port)&&(n.port=l[5]);const c=aA(n,l);if(c!==void 0&&(n.error=n.error||c,s=!0),n.host)if(QR(n.host)===!1){const d=WR(n.host);n.host=d.host.toLowerCase(),i=d.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");const u=yv(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&i===!1&&XR(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(h){n.error=n.error||"Host's domain name can not be converted to ASCII: "+h}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=YR(unescape(n.host),i))),n.path&&(n.path=GR(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:s}}function qa(t,e){return Fa(t,e).parsed}function lA(t,e){return wv(t,e).normalized}function wv(t,e){const{parsed:r,malformedAuthorityOrPort:n}=Fa(t,e);return{normalized:n?t:ss(r,e),malformedAuthorityOrPort:n}}function em(t,e){if(typeof t=="string"){const{normalized:r,malformedAuthorityOrPort:n}=wv(t,e);return n?void 0:r}if(typeof t=="object")return ss(t,e)}const vd={SCHEMES:eA,normalize:tA,resolve:rA,resolveComponent:vv,equal:nA,serialize:ss,parse:qa};Nl.exports=vd;Nl.exports.default=vd;Nl.exports.fastUri=vd;var _v=Nl.exports;Object.defineProperty(md,"__esModule",{value:!0});const bv=_v;bv.code='require("ajv/dist/runtime/uri").default';md.default=bv;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=fr;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Se;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=bo,s=ni,i=ns,o=Lt,a=Se,l=yt,c=it,u=X,h=vR,d=md,f=(M,S)=>new RegExp(M,S);f.code="new RegExp";const p=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),v={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},m={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function $(M){var S,A,k,g,w,C,V,F,ne,te,ve,Tt,Hr,Ur,Wr,Kr,Zr,Gr,Jr,Yr,vr,wr,_r,br,$r;const Nt=M.strict,Sr=(S=M.code)===null||S===void 0?void 0:S.optimize,an=Sr===!0||Sr===void 0?1:Sr||0,ln=(k=(A=M.code)===null||A===void 0?void 0:A.regExp)!==null&&k!==void 0?k:f,j=(g=M.uriResolver)!==null&&g!==void 0?g:d.default;return{strictSchema:(C=(w=M.strictSchema)!==null&&w!==void 0?w:Nt)!==null&&C!==void 0?C:!0,strictNumbers:(F=(V=M.strictNumbers)!==null&&V!==void 0?V:Nt)!==null&&F!==void 0?F:!0,strictTypes:(te=(ne=M.strictTypes)!==null&&ne!==void 0?ne:Nt)!==null&&te!==void 0?te:"log",strictTuples:(Tt=(ve=M.strictTuples)!==null&&ve!==void 0?ve:Nt)!==null&&Tt!==void 0?Tt:"log",strictRequired:(Ur=(Hr=M.strictRequired)!==null&&Hr!==void 0?Hr:Nt)!==null&&Ur!==void 0?Ur:!1,code:M.code?{...M.code,optimize:an,regExp:ln}:{optimize:an,regExp:ln},loopRequired:(Wr=M.loopRequired)!==null&&Wr!==void 0?Wr:_,loopEnum:(Kr=M.loopEnum)!==null&&Kr!==void 0?Kr:_,meta:(Zr=M.meta)!==null&&Zr!==void 0?Zr:!0,messages:(Gr=M.messages)!==null&&Gr!==void 0?Gr:!0,inlineRefs:(Jr=M.inlineRefs)!==null&&Jr!==void 0?Jr:!0,schemaId:(Yr=M.schemaId)!==null&&Yr!==void 0?Yr:"$id",addUsedSchema:(vr=M.addUsedSchema)!==null&&vr!==void 0?vr:!0,validateSchema:(wr=M.validateSchema)!==null&&wr!==void 0?wr:!0,validateFormats:(_r=M.validateFormats)!==null&&_r!==void 0?_r:!0,unicodeRegExp:(br=M.unicodeRegExp)!==null&&br!==void 0?br:!0,int32range:($r=M.int32range)!==null&&$r!==void 0?$r:!0,uriResolver:j}}class E{constructor(S={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,S=this.opts={...S,...$(S)};const{es5:A,lines:k}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:y,es5:A,lines:k}),this.logger=B(S.logger);const g=S.validateFormats;S.validateFormats=!1,this.RULES=(0,i.getRules)(),x.call(this,v,S,"NOT SUPPORTED"),x.call(this,m,S,"DEPRECATED","warn"),this._metaOpts=H.call(this),S.formats&&z.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),S.keywords&&L.call(this,S.keywords),typeof S.meta=="object"&&this.addMetaSchema(S.meta),R.call(this),S.validateFormats=g}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:S,meta:A,schemaId:k}=this.opts;let g=h;k==="id"&&(g={...h},g.id=g.$id,delete g.$id),A&&S&&this.addMetaSchema(g,g[k],!1)}defaultMeta(){const{meta:S,schemaId:A}=this.opts;return this.opts.defaultMeta=typeof S=="object"?S[A]||S:void 0}validate(S,A){let k;if(typeof S=="string"){if(k=this.getSchema(S),!k)throw new Error(`no schema with key or ref "${S}"`)}else k=this.compile(S);const g=k(A);return"$async"in k||(this.errors=k.errors),g}compile(S,A){const k=this._addSchema(S,A);return k.validate||this._compileSchemaEnv(k)}compileAsync(S,A){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:k}=this.opts;return g.call(this,S,A);async function g(te,ve){await w.call(this,te.$schema);const Tt=this._addSchema(te,ve);return Tt.validate||C.call(this,Tt)}async function w(te){te&&!this.getSchema(te)&&await g.call(this,{$ref:te},!0)}async function C(te){try{return this._compileSchemaEnv(te)}catch(ve){if(!(ve instanceof s.default))throw ve;return V.call(this,ve),await F.call(this,ve.missingSchema),C.call(this,te)}}function V({missingSchema:te,missingRef:ve}){if(this.refs[te])throw new Error(`AnySchema ${te} is loaded but ${ve} cannot be resolved`)}async function F(te){const ve=await ne.call(this,te);this.refs[te]||await w.call(this,ve.$schema),this.refs[te]||this.addSchema(ve,te,A)}async function ne(te){const ve=this._loading[te];if(ve)return ve;try{return await(this._loading[te]=k(te))}finally{delete this._loading[te]}}}addSchema(S,A,k,g=this.opts.validateSchema){if(Array.isArray(S)){for(const C of S)this.addSchema(C,void 0,k,g);return this}let w;if(typeof S=="object"){const{schemaId:C}=this.opts;if(w=S[C],w!==void 0&&typeof w!="string")throw new Error(`schema ${C} must be string`)}return A=(0,l.normalizeId)(A||w),this._checkUnique(A),this.schemas[A]=this._addSchema(S,k,A,g,!0),this}addMetaSchema(S,A,k=this.opts.validateSchema){return this.addSchema(S,A,!0,k),this}validateSchema(S,A){if(typeof S=="boolean")return!0;let k;if(k=S.$schema,k!==void 0&&typeof k!="string")throw new Error("$schema must be a string");if(k=k||this.opts.defaultMeta||this.defaultMeta(),!k)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const g=this.validate(k,S);if(!g&&A){const w="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(w);else throw new Error(w)}return g}getSchema(S){let A;for(;typeof(A=P.call(this,S))=="string";)S=A;if(A===void 0){const{schemaId:k}=this.opts,g=new o.SchemaEnv({schema:{},schemaId:k});if(A=o.resolveSchema.call(this,g,S),!A)return;this.refs[S]=A}return A.validate||this._compileSchemaEnv(A)}removeSchema(S){if(S instanceof RegExp)return this._removeAllSchemas(this.schemas,S),this._removeAllSchemas(this.refs,S),this;switch(typeof S){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const A=P.call(this,S);return typeof A=="object"&&this._cache.delete(A.schema),delete this.schemas[S],delete this.refs[S],this}case"object":{const A=S;this._cache.delete(A);let k=S[this.opts.schemaId];return k&&(k=(0,l.normalizeId)(k),delete this.schemas[k],delete this.refs[k]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(S){for(const A of S)this.addKeyword(A);return this}addKeyword(S,A){let k;if(typeof S=="string")k=S,typeof A=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),A.keyword=k);else if(typeof S=="object"&&A===void 0){if(A=S,k=A.keyword,Array.isArray(k)&&!k.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(I.call(this,k,A),!A)return(0,u.eachItem)(k,w=>Q.call(this,w)),this;re.call(this,A);const g={...A,type:(0,c.getJSONTypes)(A.type),schemaType:(0,c.getJSONTypes)(A.schemaType)};return(0,u.eachItem)(k,g.type.length===0?w=>Q.call(this,w,g):w=>g.type.forEach(C=>Q.call(this,w,g,C))),this}getKeyword(S){const A=this.RULES.all[S];return typeof A=="object"?A.definition:!!A}removeKeyword(S){const{RULES:A}=this;delete A.keywords[S],delete A.all[S];for(const k of A.rules){const g=k.rules.findIndex(w=>w.keyword===S);g>=0&&k.rules.splice(g,1)}return this}addFormat(S,A){return typeof A=="string"&&(A=new RegExp(A)),this.formats[S]=A,this}errorsText(S=this.errors,{separator:A=", ",dataVar:k="data"}={}){return!S||S.length===0?"No errors":S.map(g=>`${k}${g.instancePath} ${g.message}`).reduce((g,w)=>g+A+w)}$dataMetaSchema(S,A){const k=this.RULES.all;S=JSON.parse(JSON.stringify(S));for(const g of A){const w=g.split("/").slice(1);let C=S;for(const V of w)C=C[V];for(const V in k){const F=k[V];if(typeof F!="object")continue;const{$data:ne}=F.definition,te=C[V];ne&&te&&(C[V]=Ee(te))}}return S}_removeAllSchemas(S,A){for(const k in S){const g=S[k];(!A||A.test(k))&&(typeof g=="string"?delete S[k]:g&&!g.meta&&(this._cache.delete(g.schema),delete S[k]))}}_addSchema(S,A,k,g=this.opts.validateSchema,w=this.opts.addUsedSchema){let C;const{schemaId:V}=this.opts;if(typeof S=="object")C=S[V];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof S!="boolean")throw new Error("schema must be object or boolean")}let F=this._cache.get(S);if(F!==void 0)return F;k=(0,l.normalizeId)(C||k);const ne=l.getSchemaRefs.call(this,S,k);return F=new o.SchemaEnv({schema:S,schemaId:V,meta:A,baseId:k,localRefs:ne}),this._cache.set(F.schema,F),w&&!k.startsWith("#")&&(k&&this._checkUnique(k),this.refs[k]=F),g&&this.validateSchema(S,!0),F}_checkUnique(S){if(this.schemas[S]||this.refs[S])throw new Error(`schema with key or id "${S}" already exists`)}_compileSchemaEnv(S){if(S.meta?this._compileMetaSchema(S):o.compileSchema.call(this,S),!S.validate)throw new Error("ajv implementation error");return S.validate}_compileMetaSchema(S){const A=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,S)}finally{this.opts=A}}}E.ValidationError=n.default,E.MissingRefError=s.default,t.default=E;function x(M,S,A,k="error"){for(const g in M){const w=g;w in S&&this.logger[k](`${A}: option ${g}. ${M[w]}`)}}function P(M){return M=(0,l.normalizeId)(M),this.schemas[M]||this.refs[M]}function R(){const M=this.opts.schemas;if(M)if(Array.isArray(M))this.addSchema(M);else for(const S in M)this.addSchema(M[S],S)}function z(){for(const M in this.opts.formats){const S=this.opts.formats[M];S&&this.addFormat(M,S)}}function L(M){if(Array.isArray(M)){this.addVocabulary(M);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const S in M){const A=M[S];A.keyword||(A.keyword=S),this.addKeyword(A)}}function H(){const M={...this.opts};for(const S of p)delete M[S];return M}const O={log(){},warn(){},error(){}};function B(M){if(M===!1)return O;if(M===void 0)return console;if(M.log&&M.warn&&M.error)return M;throw new Error("logger must implement log, warn and error methods")}const Z=/^[a-z_$][a-z0-9_$:-]*$/i;function I(M,S){const{RULES:A}=this;if((0,u.eachItem)(M,k=>{if(A.keywords[k])throw new Error(`Keyword ${k} is already defined`);if(!Z.test(k))throw new Error(`Keyword ${k} has invalid name`)}),!!S&&S.$data&&!("code"in S||"validate"in S))throw new Error('$data keyword must have "code" or "validate" function')}function Q(M,S,A){var k;const g=S==null?void 0:S.post;if(A&&g)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:w}=this;let C=g?w.post:w.rules.find(({type:F})=>F===A);if(C||(C={type:A,rules:[]},w.rules.push(C)),w.keywords[M]=!0,!S)return;const V={keyword:M,definition:{...S,type:(0,c.getJSONTypes)(S.type),schemaType:(0,c.getJSONTypes)(S.schemaType)}};S.before?G.call(this,C,V,S.before):C.rules.push(V),w.all[M]=V,(k=S.implements)===null||k===void 0||k.forEach(F=>this.addKeyword(F))}function G(M,S,A){const k=M.rules.findIndex(g=>g.keyword===A);k>=0?M.rules.splice(k,0,S):(M.rules.push(S),this.logger.warn(`rule ${A} is not defined`))}function re(M){let{metaSchema:S}=M;S!==void 0&&(M.$data&&this.opts.$data&&(S=Ee(S)),M.validateSchema=this.compile(S,!0))}const Oe={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ee(M){return{anyOf:[M,Oe]}}})(T0);var wd={},_d={},bd={};Object.defineProperty(bd,"__esModule",{value:!0});const cA={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};bd.default=cA;var is={};Object.defineProperty(is,"__esModule",{value:!0});is.callRef=is.getValidate=void 0;const uA=ni,tm=be,jt=Se,gs=qr,rm=Lt,Lo=X,hA={keyword:"$ref",schemaType:"string",code(t){const{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:i,validateName:o,opts:a,self:l}=n,{root:c}=i;if((r==="#"||r==="#/")&&s===c.baseId)return h();const u=rm.resolveRef.call(l,c,s,r);if(u===void 0)throw new uA.default(n.opts.uriResolver,s,r);if(u instanceof rm.SchemaEnv)return d(u);return f(u);function h(){if(i===c)return va(t,o,i,i.$async);const p=e.scopeValue("root",{ref:c});return va(t,(0,jt._)`${p}.validate`,c,c.$async)}function d(p){const y=$v(t,p);va(t,y,p,p.$async)}function f(p){const y=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,jt.stringify)(p)}:{ref:p}),v=e.name("valid"),m=t.subschema({schema:p,dataTypes:[],schemaPath:jt.nil,topSchemaRef:y,errSchemaPath:r},v);t.mergeEvaluated(m),t.ok(v)}}};function $v(t,e){const{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,jt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}is.getValidate=$v;function va(t,e,r,n){const{gen:s,it:i}=t,{allErrors:o,schemaEnv:a,opts:l}=i,c=l.passContext?gs.default.this:jt.nil;n?u():h();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");const p=s.let("valid");s.try(()=>{s.code((0,jt._)`await ${(0,tm.callValidateCode)(t,e,c)}`),f(e),o||s.assign(p,!0)},y=>{s.if((0,jt._)`!(${y} instanceof ${i.ValidationError})`,()=>s.throw(y)),d(y),o||s.assign(p,!1)}),t.ok(p)}function h(){t.result((0,tm.callValidateCode)(t,e,c),()=>f(e),()=>d(e))}function d(p){const y=(0,jt._)`${p}.errors`;s.assign(gs.default.vErrors,(0,jt._)`${gs.default.vErrors} === null ? ${y} : ${gs.default.vErrors}.concat(${y})`),s.assign(gs.default.errors,(0,jt._)`${gs.default.vErrors}.length`)}function f(p){var y;if(!i.opts.unevaluated)return;const v=(y=r==null?void 0:r.validate)===null||y===void 0?void 0:y.evaluated;if(i.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(i.props=Lo.mergeEvaluated.props(s,v.props,i.props));else{const m=s.var("props",(0,jt._)`${p}.evaluated.props`);i.props=Lo.mergeEvaluated.props(s,m,i.props,jt.Name)}if(i.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(i.items=Lo.mergeEvaluated.items(s,v.items,i.items));else{const m=s.var("items",(0,jt._)`${p}.evaluated.items`);i.items=Lo.mergeEvaluated.items(s,m,i.items,jt.Name)}}}is.callRef=va;is.default=hA;Object.defineProperty(_d,"__esModule",{value:!0});const dA=bd,fA=is,pA=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",dA.default,fA.default];_d.default=pA;var $d={},Sd={};Object.defineProperty(Sd,"__esModule",{value:!0});const Ba=Se,un=Ba.operators,Va={maximum:{okStr:"<=",ok:un.LTE,fail:un.GT},minimum:{okStr:">=",ok:un.GTE,fail:un.LT},exclusiveMaximum:{okStr:"<",ok:un.LT,fail:un.GTE},exclusiveMinimum:{okStr:">",ok:un.GT,fail:un.LTE}},mA={message:({keyword:t,schemaCode:e})=>(0,Ba.str)`must be ${Va[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ba._)`{comparison: ${Va[t].okStr}, limit: ${e}}`},gA={keyword:Object.keys(Va),type:"number",schemaType:"number",$data:!0,error:mA,code(t){const{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Ba._)`${r} ${Va[e].fail} ${n} || isNaN(${r})`)}};Sd.default=gA;var kd={};Object.defineProperty(kd,"__esModule",{value:!0});const Mi=Se,yA={message:({schemaCode:t})=>(0,Mi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Mi._)`{multipleOf: ${t}}`},vA={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:yA,code(t){const{gen:e,data:r,schemaCode:n,it:s}=t,i=s.opts.multipleOfPrecision,o=e.let("res"),a=i?(0,Mi._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${i}`:(0,Mi._)`${o} !== parseInt(${o})`;t.fail$data((0,Mi._)`(${n} === 0 || (${o} = ${r}/${n}, ${a}))`)}};kd.default=vA;var xd={},Ed={};Object.defineProperty(Ed,"__esModule",{value:!0});function Sv(t){const e=t.length;let r=0,n=0,s;for(;n=55296&&s<=56319&&n(0,Wn._)`{limit: ${t}}`},$A={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:bA,code(t){const{keyword:e,data:r,schemaCode:n,it:s}=t,i=e==="maxLength"?Wn.operators.GT:Wn.operators.LT,o=s.opts.unicode===!1?(0,Wn._)`${r}.length`:(0,Wn._)`${(0,wA.useFunc)(t.gen,_A.default)}(${r})`;t.fail$data((0,Wn._)`${o} ${i} ${n}`)}};xd.default=$A;var Cd={};Object.defineProperty(Cd,"__esModule",{value:!0});const SA=be,kA=X,Cs=Se,xA={message:({schemaCode:t})=>(0,Cs.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Cs._)`{pattern: ${t}}`},EA={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:xA,code(t){const{gen:e,data:r,$data:n,schema:s,schemaCode:i,it:o}=t,a=o.opts.unicodeRegExp?"u":"";if(n){const{regExp:l}=o.opts.code,c=l.code==="new RegExp"?(0,Cs._)`new RegExp`:(0,kA.useFunc)(e,l),u=e.let("valid");e.try(()=>e.assign(u,(0,Cs._)`${c}(${i}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Cs._)`!${u}`)}else{const l=(0,SA.usePattern)(t,s);t.fail$data((0,Cs._)`!${l}.test(${r})`)}}};Cd.default=EA;var Pd={};Object.defineProperty(Pd,"__esModule",{value:!0});const Ii=Se,CA={message({keyword:t,schemaCode:e}){const r=t==="maxProperties"?"more":"fewer";return(0,Ii.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ii._)`{limit: ${t}}`},PA={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:CA,code(t){const{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Ii.operators.GT:Ii.operators.LT;t.fail$data((0,Ii._)`Object.keys(${r}).length ${s} ${n}`)}};Pd.default=PA;var Td={};Object.defineProperty(Td,"__esModule",{value:!0});const mi=be,Oi=Se,TA=X,RA={message:({params:{missingProperty:t}})=>(0,Oi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Oi._)`{missingProperty: ${t}}`},AA={keyword:"required",type:"object",schemaType:"array",$data:!0,error:RA,code(t){const{gen:e,schema:r,schemaCode:n,data:s,$data:i,it:o}=t,{opts:a}=o;if(!i&&r.length===0)return;const l=r.length>=a.loopRequired;if(o.allErrors?c():u(),a.strictRequired){const f=t.parentSchema.properties,{definedProperties:p}=t.it;for(const y of r)if((f==null?void 0:f[y])===void 0&&!p.has(y)){const v=o.schemaEnv.baseId+o.errSchemaPath,m=`required property "${y}" is not defined at "${v}" (strictRequired)`;(0,TA.checkStrictMode)(o,m,o.opts.strictRequired)}}function c(){if(l||i)t.block$data(Oi.nil,h);else for(const f of r)(0,mi.checkReportMissingProp)(t,f)}function u(){const f=e.let("missing");if(l||i){const p=e.let("valid",!0);t.block$data(p,()=>d(f,p)),t.ok(p)}else e.if((0,mi.checkMissingProp)(t,r,f)),(0,mi.reportMissingProp)(t,f),e.else()}function h(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,mi.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function d(f,p){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(p,(0,mi.propertyInData)(e,s,f,a.ownProperties)),e.if((0,Oi.not)(p),()=>{t.error(),e.break()})},Oi.nil)}}};Td.default=AA;var Rd={};Object.defineProperty(Rd,"__esModule",{value:!0});const Ni=Se,MA={message({keyword:t,schemaCode:e}){const r=t==="maxItems"?"more":"fewer";return(0,Ni.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ni._)`{limit: ${t}}`},IA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:MA,code(t){const{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Ni.operators.GT:Ni.operators.LT;t.fail$data((0,Ni._)`${r}.length ${s} ${n}`)}};Rd.default=IA;var Ad={},$o={};Object.defineProperty($o,"__esModule",{value:!0});const kv=Ml;kv.code='require("ajv/dist/runtime/equal").default';$o.default=kv;Object.defineProperty(Ad,"__esModule",{value:!0});const lc=it,ft=Se,OA=X,NA=$o,jA={message:({params:{i:t,j:e}})=>(0,ft.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ft._)`{i: ${t}, j: ${e}}`},DA={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:jA,code(t){const{gen:e,data:r,$data:n,schema:s,parentSchema:i,schemaCode:o,it:a}=t;if(!n&&!s)return;const l=e.let("valid"),c=i.items?(0,lc.getSchemaTypes)(i.items):[];t.block$data(l,u,(0,ft._)`${o} === false`),t.ok(l);function u(){const p=e.let("i",(0,ft._)`${r}.length`),y=e.let("j");t.setParams({i:p,j:y}),e.assign(l,!0),e.if((0,ft._)`${p} > 1`,()=>(h()?d:f)(p,y))}function h(){return c.length>0&&!c.some(p=>p==="object"||p==="array")}function d(p,y){const v=e.name("item"),m=(0,lc.checkDataTypes)(c,v,a.opts.strictNumbers,lc.DataType.Wrong),_=e.const("indices",(0,ft._)`{}`);e.for((0,ft._)`;${p}--;`,()=>{e.let(v,(0,ft._)`${r}[${p}]`),e.if(m,(0,ft._)`continue`),c.length>1&&e.if((0,ft._)`typeof ${v} == "string"`,(0,ft._)`${v} += "_"`),e.if((0,ft._)`typeof ${_}[${v}] == "number"`,()=>{e.assign(y,(0,ft._)`${_}[${v}]`),t.error(),e.assign(l,!1).break()}).code((0,ft._)`${_}[${v}] = ${p}`)})}function f(p,y){const v=(0,OA.useFunc)(e,NA.default),m=e.name("outer");e.label(m).for((0,ft._)`;${p}--;`,()=>e.for((0,ft._)`${y} = ${p}; ${y}--;`,()=>e.if((0,ft._)`${v}(${r}[${p}], ${r}[${y}])`,()=>{t.error(),e.assign(l,!1).break(m)})))}}};Ad.default=DA;var Md={};Object.defineProperty(Md,"__esModule",{value:!0});const iu=Se,LA=X,zA=$o,FA={message:"must be equal to constant",params:({schemaCode:t})=>(0,iu._)`{allowedValue: ${t}}`},qA={keyword:"const",$data:!0,error:FA,code(t){const{gen:e,data:r,$data:n,schemaCode:s,schema:i}=t;n||i&&typeof i=="object"?t.fail$data((0,iu._)`!${(0,LA.useFunc)(e,zA.default)}(${r}, ${s})`):t.fail((0,iu._)`${i} !== ${r}`)}};Md.default=qA;var Id={};Object.defineProperty(Id,"__esModule",{value:!0});const xi=Se,BA=X,VA=$o,HA={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,xi._)`{allowedValues: ${t}}`},UA={keyword:"enum",schemaType:"array",$data:!0,error:HA,code(t){const{gen:e,data:r,$data:n,schema:s,schemaCode:i,it:o}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");const a=s.length>=o.opts.loopEnum;let l;const c=()=>l??(l=(0,BA.useFunc)(e,VA.default));let u;if(a||n)u=e.let("valid"),t.block$data(u,h);else{if(!Array.isArray(s))throw new Error("ajv implementation error");const f=e.const("vSchema",i);u=(0,xi.or)(...s.map((p,y)=>d(f,y)))}t.pass(u);function h(){e.assign(u,!1),e.forOf("v",i,f=>e.if((0,xi._)`${c()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function d(f,p){const y=s[p];return typeof y=="object"&&y!==null?(0,xi._)`${c()}(${r}, ${f}[${p}])`:(0,xi._)`${r} === ${y}`}}};Id.default=UA;Object.defineProperty($d,"__esModule",{value:!0});const WA=Sd,KA=kd,ZA=xd,GA=Cd,JA=Pd,YA=Td,QA=Rd,XA=Ad,eM=Md,tM=Id,rM=[WA.default,KA.default,ZA.default,GA.default,JA.default,YA.default,QA.default,XA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},eM.default,tM.default];$d.default=rM;var Od={},si={};Object.defineProperty(si,"__esModule",{value:!0});si.validateAdditionalItems=void 0;const Kn=Se,ou=X,nM={message:({params:{len:t}})=>(0,Kn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Kn._)`{limit: ${t}}`},sM={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:nM,code(t){const{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,ou.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}xv(t,n)}};function xv(t,e){const{gen:r,schema:n,data:s,keyword:i,it:o}=t;o.items=!0;const a=r.const("len",(0,Kn._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Kn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ou.alwaysValidSchema)(o,n)){const c=r.var("valid",(0,Kn._)`${a} <= ${e.length}`);r.if((0,Kn.not)(c),()=>l(c)),t.ok(c)}function l(c){r.forRange("i",e.length,a,u=>{t.subschema({keyword:i,dataProp:u,dataPropType:ou.Type.Num},c),o.allErrors||r.if((0,Kn.not)(c),()=>r.break())})}}si.validateAdditionalItems=xv;si.default=sM;var Nd={},ii={};Object.defineProperty(ii,"__esModule",{value:!0});ii.validateTuple=void 0;const nm=Se,wa=X,iM=be,oM={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){const{schema:e,it:r}=t;if(Array.isArray(e))return Ev(t,"additionalItems",e);r.items=!0,!(0,wa.alwaysValidSchema)(r,e)&&t.ok((0,iM.validateArray)(t))}};function Ev(t,e,r=t.schema){const{gen:n,parentSchema:s,data:i,keyword:o,it:a}=t;u(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=wa.mergeEvaluated.items(n,r.length,a.items));const l=n.name("valid"),c=n.const("len",(0,nm._)`${i}.length`);r.forEach((h,d)=>{(0,wa.alwaysValidSchema)(a,h)||(n.if((0,nm._)`${c} > ${d}`,()=>t.subschema({keyword:o,schemaProp:d,dataProp:d},l)),t.ok(l))});function u(h){const{opts:d,errSchemaPath:f}=a,p=r.length,y=p===h.minItems&&(p===h.maxItems||h[e]===!1);if(d.strictTuples&&!y){const v=`"${o}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,wa.checkStrictMode)(a,v,d.strictTuples)}}}ii.validateTuple=Ev;ii.default=oM;Object.defineProperty(Nd,"__esModule",{value:!0});const aM=ii,lM={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,aM.validateTuple)(t,"items")};Nd.default=lM;var jd={};Object.defineProperty(jd,"__esModule",{value:!0});const sm=Se,cM=X,uM=be,hM=si,dM={message:({params:{len:t}})=>(0,sm.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,sm._)`{limit: ${t}}`},fM={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:dM,code(t){const{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,cM.alwaysValidSchema)(n,e)&&(s?(0,hM.validateAdditionalItems)(t,s):t.ok((0,uM.validateArray)(t)))}};jd.default=fM;var Dd={};Object.defineProperty(Dd,"__esModule",{value:!0});const Jt=Se,zo=X,pM={message:({params:{min:t,max:e}})=>e===void 0?(0,Jt.str)`must contain at least ${t} valid item(s)`:(0,Jt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Jt._)`{minContains: ${t}}`:(0,Jt._)`{minContains: ${t}, maxContains: ${e}}`},mM={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:pM,code(t){const{gen:e,schema:r,parentSchema:n,data:s,it:i}=t;let o,a;const{minContains:l,maxContains:c}=n;i.opts.next?(o=l===void 0?1:l,a=c):o=1;const u=e.const("len",(0,Jt._)`${s}.length`);if(t.setParams({min:o,max:a}),a===void 0&&o===0){(0,zo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,zo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,zo.alwaysValidSchema)(i,r)){let y=(0,Jt._)`${u} >= ${o}`;a!==void 0&&(y=(0,Jt._)`${y} && ${u} <= ${a}`),t.pass(y);return}i.items=!0;const h=e.name("valid");a===void 0&&o===1?f(h,()=>e.if(h,()=>e.break())):o===0?(e.let(h,!0),a!==void 0&&e.if((0,Jt._)`${s}.length > 0`,d)):(e.let(h,!1),d()),t.result(h,()=>t.reset());function d(){const y=e.name("_valid"),v=e.let("count",0);f(y,()=>e.if(y,()=>p(v)))}function f(y,v){e.forRange("i",0,u,m=>{t.subschema({keyword:"contains",dataProp:m,dataPropType:zo.Type.Num,compositeRule:!0},y),v()})}function p(y){e.code((0,Jt._)`${y}++`),a===void 0?e.if((0,Jt._)`${y} >= ${o}`,()=>e.assign(h,!0).break()):(e.if((0,Jt._)`${y} > ${a}`,()=>e.assign(h,!1).break()),o===1?e.assign(h,!0):e.if((0,Jt._)`${y} >= ${o}`,()=>e.assign(h,!0)))}}};Dd.default=mM;var Cv={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=Se,r=X,n=be;t.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const h=c===1?"property":"properties";return(0,e.str)`must have ${h} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:h}})=>(0,e._)`{property: ${l}, + missingProperty: ${h}, + depsCount: ${c}, + deps: ${u}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(l){const[c,u]=i(l);o(l,c),a(l,u)}};function i({schema:l}){const c={},u={};for(const h in l){if(h==="__proto__")continue;const d=Array.isArray(l[h])?c:u;d[h]=l[h]}return[c,u]}function o(l,c=l.schema){const{gen:u,data:h,it:d}=l;if(Object.keys(c).length===0)return;const f=u.let("missing");for(const p in c){const y=c[p];if(y.length===0)continue;const v=(0,n.propertyInData)(u,h,p,d.opts.ownProperties);l.setParams({property:p,depsCount:y.length,deps:y.join(", ")}),d.allErrors?u.if(v,()=>{for(const m of y)(0,n.checkReportMissingProp)(l,m)}):(u.if((0,e._)`${v} && (${(0,n.checkMissingProp)(l,y,f)})`),(0,n.reportMissingProp)(l,f),u.else())}}t.validatePropertyDeps=o;function a(l,c=l.schema){const{gen:u,data:h,keyword:d,it:f}=l,p=u.name("valid");for(const y in c)(0,r.alwaysValidSchema)(f,c[y])||(u.if((0,n.propertyInData)(u,h,y,f.opts.ownProperties),()=>{const v=l.subschema({keyword:d,schemaProp:y},p);l.mergeValidEvaluated(v,p)},()=>u.var(p,!0)),l.ok(p))}t.validateSchemaDeps=a,t.default=s})(Cv);var Ld={};Object.defineProperty(Ld,"__esModule",{value:!0});const Pv=Se,gM=X,yM={message:"property name must be valid",params:({params:t})=>(0,Pv._)`{propertyName: ${t.propertyName}}`},vM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:yM,code(t){const{gen:e,schema:r,data:n,it:s}=t;if((0,gM.alwaysValidSchema)(s,r))return;const i=e.name("valid");e.forIn("key",n,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},i),e.if((0,Pv.not)(i),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(i)}};Ld.default=vM;var jl={};Object.defineProperty(jl,"__esModule",{value:!0});const Fo=be,ar=Se,wM=qr,qo=X,_M={message:"must NOT have additional properties",params:({params:t})=>(0,ar._)`{additionalProperty: ${t.additionalProperty}}`},bM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:_M,code(t){const{gen:e,schema:r,parentSchema:n,data:s,errsCount:i,it:o}=t;if(!i)throw new Error("ajv implementation error");const{allErrors:a,opts:l}=o;if(o.props=!0,l.removeAdditional!=="all"&&(0,qo.alwaysValidSchema)(o,r))return;const c=(0,Fo.allSchemaProperties)(n.properties),u=(0,Fo.allSchemaProperties)(n.patternProperties);h(),t.ok((0,ar._)`${i} === ${wM.default.errors}`);function h(){e.forIn("key",s,v=>{!c.length&&!u.length?p(v):e.if(d(v),()=>p(v))})}function d(v){let m;if(c.length>8){const _=(0,qo.schemaRefOrVal)(o,n.properties,"properties");m=(0,Fo.isOwnProperty)(e,_,v)}else c.length?m=(0,ar.or)(...c.map(_=>(0,ar._)`${v} === ${_}`)):m=ar.nil;return u.length&&(m=(0,ar.or)(m,...u.map(_=>(0,ar._)`${(0,Fo.usePattern)(t,_)}.test(${v})`))),(0,ar.not)(m)}function f(v){e.code((0,ar._)`delete ${s}[${v}]`)}function p(v){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){f(v);return}if(r===!1){t.setParams({additionalProperty:v}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,qo.alwaysValidSchema)(o,r)){const m=e.name("valid");l.removeAdditional==="failing"?(y(v,m,!1),e.if((0,ar.not)(m),()=>{t.reset(),f(v)})):(y(v,m),a||e.if((0,ar.not)(m),()=>e.break()))}}function y(v,m,_){const $={keyword:"additionalProperties",dataProp:v,dataPropType:qo.Type.Str};_===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema($,m)}}};jl.default=bM;var zd={};Object.defineProperty(zd,"__esModule",{value:!0});const $M=fr,im=be,cc=X,om=jl,SM={keyword:"properties",type:"object",schemaType:"object",code(t){const{gen:e,schema:r,parentSchema:n,data:s,it:i}=t;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&om.default.code(new $M.KeywordCxt(i,om.default,"additionalProperties"));const o=(0,im.allSchemaProperties)(r);for(const h of o)i.definedProperties.add(h);i.opts.unevaluated&&o.length&&i.props!==!0&&(i.props=cc.mergeEvaluated.props(e,(0,cc.toHash)(o),i.props));const a=o.filter(h=>!(0,cc.alwaysValidSchema)(i,r[h]));if(a.length===0)return;const l=e.name("valid");for(const h of a)c(h)?u(h):(e.if((0,im.propertyInData)(e,s,h,i.opts.ownProperties)),u(h),i.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(h),t.ok(l);function c(h){return i.opts.useDefaults&&!i.compositeRule&&r[h].default!==void 0}function u(h){t.subschema({keyword:"properties",schemaProp:h,dataProp:h},l)}}};zd.default=SM;var Fd={};Object.defineProperty(Fd,"__esModule",{value:!0});const am=be,Bo=Se,lm=X,cm=X,kM={keyword:"patternProperties",type:"object",schemaType:"object",code(t){const{gen:e,schema:r,data:n,parentSchema:s,it:i}=t,{opts:o}=i,a=(0,am.allSchemaProperties)(r),l=a.filter(y=>(0,lm.alwaysValidSchema)(i,r[y]));if(a.length===0||l.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;const c=o.strictSchema&&!o.allowMatchingProperties&&s.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof Bo.Name)&&(i.props=(0,cm.evaluatedPropsToName)(e,i.props));const{props:h}=i;d();function d(){for(const y of a)c&&f(y),i.allErrors?p(y):(e.var(u,!0),p(y),e.if(u))}function f(y){for(const v in c)new RegExp(y).test(v)&&(0,lm.checkStrictMode)(i,`property ${v} matches pattern ${y} (use allowMatchingProperties)`)}function p(y){e.forIn("key",n,v=>{e.if((0,Bo._)`${(0,am.usePattern)(t,y)}.test(${v})`,()=>{const m=l.includes(y);m||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:v,dataPropType:cm.Type.Str},u),i.opts.unevaluated&&h!==!0?e.assign((0,Bo._)`${h}[${v}]`,!0):!m&&!i.allErrors&&e.if((0,Bo.not)(u),()=>e.break())})})}}};Fd.default=kM;var qd={};Object.defineProperty(qd,"__esModule",{value:!0});const xM=X,EM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:e,schema:r,it:n}=t;if((0,xM.alwaysValidSchema)(n,r)){t.fail();return}const s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};qd.default=EM;var Bd={};Object.defineProperty(Bd,"__esModule",{value:!0});const CM=be,PM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:CM.validateUnion,error:{message:"must match a schema in anyOf"}};Bd.default=PM;var Vd={};Object.defineProperty(Vd,"__esModule",{value:!0});const _a=Se,TM=X,RM={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,_a._)`{passingSchemas: ${t.passing}}`},AM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:RM,code(t){const{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;const i=r,o=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(c),t.result(o,()=>t.reset(),()=>t.error(!0));function c(){i.forEach((u,h)=>{let d;(0,TM.alwaysValidSchema)(s,u)?e.var(l,!0):d=t.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},l),h>0&&e.if((0,_a._)`${l} && ${o}`).assign(o,!1).assign(a,(0,_a._)`[${a}, ${h}]`).else(),e.if(l,()=>{e.assign(o,!0),e.assign(a,h),d&&t.mergeEvaluated(d,_a.Name)})})}}};Vd.default=AM;var Hd={};Object.defineProperty(Hd,"__esModule",{value:!0});const MM=X,IM={keyword:"allOf",schemaType:"array",code(t){const{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");const s=e.name("valid");r.forEach((i,o)=>{if((0,MM.alwaysValidSchema)(n,i))return;const a=t.subschema({keyword:"allOf",schemaProp:o},s);t.ok(s),t.mergeEvaluated(a)})}};Hd.default=IM;var Ud={};Object.defineProperty(Ud,"__esModule",{value:!0});const Ha=Se,Tv=X,OM={message:({params:t})=>(0,Ha.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ha._)`{failingKeyword: ${t.ifClause}}`},NM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:OM,code(t){const{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Tv.checkStrictMode)(n,'"if" without "then" and "else" is ignored');const s=um(n,"then"),i=um(n,"else");if(!s&&!i)return;const o=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),s&&i){const u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,c("then",u),c("else",u))}else s?e.if(a,c("then")):e.if((0,Ha.not)(a),c("else"));t.pass(o,()=>t.error(!0));function l(){const u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function c(u,h){return()=>{const d=t.subschema({keyword:u},a);e.assign(o,a),t.mergeValidEvaluated(d,o),h?e.assign(h,(0,Ha._)`${u}`):t.setParams({ifClause:u})}}}};function um(t,e){const r=t.schema[e];return r!==void 0&&!(0,Tv.alwaysValidSchema)(t,r)}Ud.default=NM;var Wd={};Object.defineProperty(Wd,"__esModule",{value:!0});const jM=X,DM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,jM.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Wd.default=DM;Object.defineProperty(Od,"__esModule",{value:!0});const LM=si,zM=Nd,FM=ii,qM=jd,BM=Dd,VM=Cv,HM=Ld,UM=jl,WM=zd,KM=Fd,ZM=qd,GM=Bd,JM=Vd,YM=Hd,QM=Ud,XM=Wd;function eI(t=!1){const e=[ZM.default,GM.default,JM.default,YM.default,QM.default,XM.default,HM.default,UM.default,VM.default,WM.default,KM.default];return t?e.push(zM.default,qM.default):e.push(LM.default,FM.default),e.push(BM.default),e}Od.default=eI;var Kd={},Zd={};Object.defineProperty(Zd,"__esModule",{value:!0});const Xe=Se,tI={message:({schemaCode:t})=>(0,Xe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Xe._)`{format: ${t}}`},rI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:tI,code(t,e){const{gen:r,data:n,$data:s,schema:i,schemaCode:o,it:a}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:h}=a;if(!l.validateFormats)return;s?d():f();function d(){const p=r.scopeValue("formats",{ref:h.formats,code:l.code.formats}),y=r.const("fDef",(0,Xe._)`${p}[${o}]`),v=r.let("fType"),m=r.let("format");r.if((0,Xe._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(v,(0,Xe._)`${y}.type || "string"`).assign(m,(0,Xe._)`${y}.validate`),()=>r.assign(v,(0,Xe._)`"string"`).assign(m,y)),t.fail$data((0,Xe.or)(_(),$()));function _(){return l.strictSchema===!1?Xe.nil:(0,Xe._)`${o} && !${m}`}function $(){const E=u.$async?(0,Xe._)`(${y}.async ? await ${m}(${n}) : ${m}(${n}))`:(0,Xe._)`${m}(${n})`,x=(0,Xe._)`(typeof ${m} == "function" ? ${E} : ${m}.test(${n}))`;return(0,Xe._)`${m} && ${m} !== true && ${v} === ${e} && !${x}`}}function f(){const p=h.formats[i];if(!p){_();return}if(p===!0)return;const[y,v,m]=$(p);y===e&&t.pass(E());function _(){if(l.strictSchema===!1){h.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${i}" ignored in schema at path "${c}"`}}function $(x){const P=x instanceof RegExp?(0,Xe.regexpCode)(x):l.code.formats?(0,Xe._)`${l.code.formats}${(0,Xe.getProperty)(i)}`:void 0,R=r.scopeValue("formats",{key:i,ref:x,code:P});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,Xe._)`${R}.validate`]:["string",x,R]}function E(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Xe._)`await ${m}(${n})`}return typeof v=="function"?(0,Xe._)`${m}(${n})`:(0,Xe._)`${m}.test(${n})`}}}};Zd.default=rI;Object.defineProperty(Kd,"__esModule",{value:!0});const nI=Zd,sI=[nI.default];Kd.default=sI;var Bs={};Object.defineProperty(Bs,"__esModule",{value:!0});Bs.contentVocabulary=Bs.metadataVocabulary=void 0;Bs.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Bs.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(wd,"__esModule",{value:!0});const iI=_d,oI=$d,aI=Od,lI=Kd,hm=Bs,cI=[iI.default,oI.default,(0,aI.default)(),lI.default,hm.metadataVocabulary,hm.contentVocabulary];wd.default=cI;var Gd={},Dl={};Object.defineProperty(Dl,"__esModule",{value:!0});Dl.DiscrError=void 0;var dm;(function(t){t.Tag="tag",t.Mapping="mapping"})(dm||(Dl.DiscrError=dm={}));Object.defineProperty(Gd,"__esModule",{value:!0});const bs=Se,au=Dl,fm=Lt,uI=ni,hI=X,dI={message:({params:{discrError:t,tagName:e}})=>t===au.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,bs._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},fI={keyword:"discriminator",type:"object",schemaType:"object",error:dI,code(t){const{gen:e,data:r,schema:n,parentSchema:s,it:i}=t,{oneOf:o}=s;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");const a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");const l=e.let("valid",!1),c=e.const("tag",(0,bs._)`${r}${(0,bs.getProperty)(a)}`);e.if((0,bs._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:au.DiscrError.Tag,tag:c,tagName:a})),t.ok(l);function u(){const f=d();e.if(!1);for(const p in f)e.elseIf((0,bs._)`${c} === ${p}`),e.assign(l,h(f[p]));e.else(),t.error(!1,{discrError:au.DiscrError.Mapping,tag:c,tagName:a}),e.endIf()}function h(f){const p=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:f},p);return t.mergeEvaluated(y,bs.Name),p}function d(){var f;const p={},y=m(s);let v=!0;for(let E=0;Ethis.addVocabulary(p)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const p=this.opts.$data?this.$dataMetaSchema(i,o):i;this.addMetaSchema(p,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}e.Ajv=l,t.exports=e=l,t.exports.Ajv=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=fr;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Se;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var h=bo;Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return h.default}});var d=ni;Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return d.default}})})(eu,eu.exports);var bI=eu.exports;const $I=uy(bI);var lu={exports:{}},Rv={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(O,B){return{validate:O,compare:B}}t.fullFormats={date:e(i,o),time:e(l(!0),c),"date-time":e(d(!0),f),"iso-time":e(l(),u),"iso-date-time":e(d(),p),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:m,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:H,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:$,int32:{type:"number",validate:P},int64:{type:"number",validate:R},float:{type:"number",validate:z},double:{type:"number",validate:z},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,f),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,p),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);function r(O){return O%4===0&&(O%100!==0||O%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i(O){const B=n.exec(O);if(!B)return!1;const Z=+B[1],I=+B[2],Q=+B[3];return I>=1&&I<=12&&Q>=1&&Q<=(I===2&&r(Z)?29:s[I])}function o(O,B){if(O&&B)return O>B?1:O23||S>59||O&&!Oe)return!1;if(Q<=23&&G<=59&&re<60)return!0;const A=G-S*Ee,k=Q-M*Ee-(A<0?1:0);return(k===23||k===-1)&&(A===59||A===-1)&&re<61}}function c(O,B){if(!(O&&B))return;const Z=new Date("2020-01-01T"+O).valueOf(),I=new Date("2020-01-01T"+B).valueOf();if(Z&&I)return Z-I}function u(O,B){if(!(O&&B))return;const Z=a.exec(O),I=a.exec(B);if(Z&&I)return O=Z[1]+Z[2]+Z[3],B=I[1]+I[2]+I[3],O>B?1:O=E}function R(O){return Number.isInteger(O)}function z(){return!0}const L=/[^\\]\\Z/;function H(O){if(L.test(O))return!1;try{return new RegExp(O),!0}catch{return!1}}})(Rv);var Av={},cu={exports:{}},Mv={},pr={},Vs={},So={},_e={},Qi={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(_){if(super(),!t.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce(($,E)=>`${$}${E}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce(($,E)=>(E instanceof r&&($[E.str]=($[E.str]||0)+1),$),{})}}t._Code=n,t.nil=new n("");function s(m,..._){const $=[m[0]];let E=0;for(;E<_.length;)a($,_[E]),$.push(m[++E]);return new n($)}t._=s;const i=new n("+");function o(m,..._){const $=[f(m[0])];let E=0;for(;E<_.length;)$.push(i),a($,_[E]),$.push(i,f(m[++E]));return l($),new n($)}t.str=o;function a(m,_){_ instanceof n?m.push(..._._items):_ instanceof r?m.push(_):m.push(h(_))}t.addCodeArg=a;function l(m){let _=1;for(;_{if(h.scopePath===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return(0,e._)`${c}${h.scopePath}`})}scopeCode(c=this._values,u,h){return this._reduceValues(c,d=>{if(d.value===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return d.value.code},u,h)}_reduceValues(c,u,h={},d){let f=e.nil;for(const p in c){const y=c[p];if(!y)continue;const v=h[p]=h[p]||new Map;y.forEach(m=>{if(v.has(m))return;v.set(m,n.Started);let _=u(m);if(_){const $=this.opts.es5?t.varKinds.var:t.varKinds.const;f=(0,e._)`${f}${$} ${m} = ${_};${this.opts._n}`}else if(_=d==null?void 0:d(m))f=(0,e._)`${f}${_}${this.opts._n}`;else throw new r(m);v.set(m,n.Completed)})}return f}}t.ValueScope=a})(uu);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=Qi,r=uu;var n=Qi;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var s=uu;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class i{optimizeNodes(){return this}optimizeNames(g,w){return this}}class o extends i{constructor(g,w,C){super(),this.varKind=g,this.name=w,this.rhs=C}render({es5:g,_n:w}){const C=g?r.varKinds.var:this.varKind,V=this.rhs===void 0?"":` = ${this.rhs}`;return`${C} ${this.name}${V};`+w}optimizeNames(g,w){if(g[this.name.str])return this.rhs&&(this.rhs=I(this.rhs,g,w)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends i{constructor(g,w,C){super(),this.lhs=g,this.rhs=w,this.sideEffects=C}render({_n:g}){return`${this.lhs} = ${this.rhs};`+g}optimizeNames(g,w){if(!(this.lhs instanceof e.Name&&!g[this.lhs.str]&&!this.sideEffects))return this.rhs=I(this.rhs,g,w),this}get names(){const g=this.lhs instanceof e.Name?{}:{...this.lhs.names};return Z(g,this.rhs)}}class l extends a{constructor(g,w,C,V){super(g,C,V),this.op=w}render({_n:g}){return`${this.lhs} ${this.op}= ${this.rhs};`+g}}class c extends i{constructor(g){super(),this.label=g,this.names={}}render({_n:g}){return`${this.label}:`+g}}class u extends i{constructor(g){super(),this.label=g,this.names={}}render({_n:g}){return`break${this.label?` ${this.label}`:""};`+g}}class h extends i{constructor(g){super(),this.error=g}render({_n:g}){return`throw ${this.error};`+g}get names(){return this.error.names}}class d extends i{constructor(g){super(),this.code=g}render({_n:g}){return`${this.code};`+g}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(g,w){return this.code=I(this.code,g,w),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class f extends i{constructor(g=[]){super(),this.nodes=g}render(g){return this.nodes.reduce((w,C)=>w+C.render(g),"")}optimizeNodes(){const{nodes:g}=this;let w=g.length;for(;w--;){const C=g[w].optimizeNodes();Array.isArray(C)?g.splice(w,1,...C):C?g[w]=C:g.splice(w,1)}return g.length>0?this:void 0}optimizeNames(g,w){const{nodes:C}=this;let V=C.length;for(;V--;){const F=C[V];F.optimizeNames(g,w)||(Q(g,F.names),C.splice(V,1))}return C.length>0?this:void 0}get names(){return this.nodes.reduce((g,w)=>B(g,w.names),{})}}class p extends f{render(g){return"{"+g._n+super.render(g)+"}"+g._n}}class y extends f{}class v extends p{}v.kind="else";class m extends p{constructor(g,w){super(w),this.condition=g}render(g){let w=`if(${this.condition})`+super.render(g);return this.else&&(w+="else "+this.else.render(g)),w}optimizeNodes(){super.optimizeNodes();const g=this.condition;if(g===!0)return this.nodes;let w=this.else;if(w){const C=w.optimizeNodes();w=this.else=Array.isArray(C)?new v(C):C}if(w)return g===!1?w instanceof m?w:w.nodes:this.nodes.length?this:new m(G(g),w instanceof m?[w]:w.nodes);if(!(g===!1||!this.nodes.length))return this}optimizeNames(g,w){var C;if(this.else=(C=this.else)===null||C===void 0?void 0:C.optimizeNames(g,w),!!(super.optimizeNames(g,w)||this.else))return this.condition=I(this.condition,g,w),this}get names(){const g=super.names;return Z(g,this.condition),this.else&&B(g,this.else.names),g}}m.kind="if";class _ extends p{}_.kind="for";class $ extends _{constructor(g){super(),this.iteration=g}render(g){return`for(${this.iteration})`+super.render(g)}optimizeNames(g,w){if(super.optimizeNames(g,w))return this.iteration=I(this.iteration,g,w),this}get names(){return B(super.names,this.iteration.names)}}class E extends _{constructor(g,w,C,V){super(),this.varKind=g,this.name=w,this.from=C,this.to=V}render(g){const w=g.es5?r.varKinds.var:this.varKind,{name:C,from:V,to:F}=this;return`for(${w} ${C}=${V}; ${C}<${F}; ${C}++)`+super.render(g)}get names(){const g=Z(super.names,this.from);return Z(g,this.to)}}class x extends _{constructor(g,w,C,V){super(),this.loop=g,this.varKind=w,this.name=C,this.iterable=V}render(g){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(g)}optimizeNames(g,w){if(super.optimizeNames(g,w))return this.iterable=I(this.iterable,g,w),this}get names(){return B(super.names,this.iterable.names)}}class P extends p{constructor(g,w,C){super(),this.name=g,this.args=w,this.async=C}render(g){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(g)}}P.kind="func";class R extends f{render(g){return"return "+super.render(g)}}R.kind="return";class z extends p{render(g){let w="try"+super.render(g);return this.catch&&(w+=this.catch.render(g)),this.finally&&(w+=this.finally.render(g)),w}optimizeNodes(){var g,w;return super.optimizeNodes(),(g=this.catch)===null||g===void 0||g.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(g,w){var C,V;return super.optimizeNames(g,w),(C=this.catch)===null||C===void 0||C.optimizeNames(g,w),(V=this.finally)===null||V===void 0||V.optimizeNames(g,w),this}get names(){const g=super.names;return this.catch&&B(g,this.catch.names),this.finally&&B(g,this.finally.names),g}}class L extends p{constructor(g){super(),this.error=g}render(g){return`catch(${this.error})`+super.render(g)}}L.kind="catch";class H extends p{render(g){return"finally"+super.render(g)}}H.kind="finally";class O{constructor(g,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?` +`:""},this._extScope=g,this._scope=new r.Scope({parent:g}),this._nodes=[new y]}toString(){return this._root.render(this.opts)}name(g){return this._scope.name(g)}scopeName(g){return this._extScope.name(g)}scopeValue(g,w){const C=this._extScope.value(g,w);return(this._values[C.prefix]||(this._values[C.prefix]=new Set)).add(C),C}getScopeValue(g,w){return this._extScope.getValue(g,w)}scopeRefs(g){return this._extScope.scopeRefs(g,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(g,w,C,V){const F=this._scope.toName(w);return C!==void 0&&V&&(this._constants[F.str]=C),this._leafNode(new o(g,F,C)),F}const(g,w,C){return this._def(r.varKinds.const,g,w,C)}let(g,w,C){return this._def(r.varKinds.let,g,w,C)}var(g,w,C){return this._def(r.varKinds.var,g,w,C)}assign(g,w,C){return this._leafNode(new a(g,w,C))}add(g,w){return this._leafNode(new l(g,t.operators.ADD,w))}code(g){return typeof g=="function"?g():g!==e.nil&&this._leafNode(new d(g)),this}object(...g){const w=["{"];for(const[C,V]of g)w.length>1&&w.push(","),w.push(C),(C!==V||this.opts.es5)&&(w.push(":"),(0,e.addCodeArg)(w,V));return w.push("}"),new e._Code(w)}if(g,w,C){if(this._blockNode(new m(g)),w&&C)this.code(w).else().code(C).endIf();else if(w)this.code(w).endIf();else if(C)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(g){return this._elseNode(new m(g))}else(){return this._elseNode(new v)}endIf(){return this._endBlockNode(m,v)}_for(g,w){return this._blockNode(g),w&&this.code(w).endFor(),this}for(g,w){return this._for(new $(g),w)}forRange(g,w,C,V,F=this.opts.es5?r.varKinds.var:r.varKinds.let){const ne=this._scope.toName(g);return this._for(new E(F,ne,w,C),()=>V(ne))}forOf(g,w,C,V=r.varKinds.const){const F=this._scope.toName(g);if(this.opts.es5){const ne=w instanceof e.Name?w:this.var("_arr",w);return this.forRange("_i",0,(0,e._)`${ne}.length`,te=>{this.var(F,(0,e._)`${ne}[${te}]`),C(F)})}return this._for(new x("of",V,F,w),()=>C(F))}forIn(g,w,C,V=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(g,(0,e._)`Object.keys(${w})`,C);const F=this._scope.toName(g);return this._for(new x("in",V,F,w),()=>C(F))}endFor(){return this._endBlockNode(_)}label(g){return this._leafNode(new c(g))}break(g){return this._leafNode(new u(g))}return(g){const w=new R;if(this._blockNode(w),this.code(g),w.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(R)}try(g,w,C){if(!w&&!C)throw new Error('CodeGen: "try" without "catch" and "finally"');const V=new z;if(this._blockNode(V),this.code(g),w){const F=this.name("e");this._currNode=V.catch=new L(F),w(F)}return C&&(this._currNode=V.finally=new H,this.code(C)),this._endBlockNode(L,H)}throw(g){return this._leafNode(new h(g))}block(g,w){return this._blockStarts.push(this._nodes.length),g&&this.code(g).endBlock(w),this}endBlock(g){const w=this._blockStarts.pop();if(w===void 0)throw new Error("CodeGen: not in self-balancing block");const C=this._nodes.length-w;if(C<0||g!==void 0&&C!==g)throw new Error(`CodeGen: wrong number of nodes: ${C} vs ${g} expected`);return this._nodes.length=w,this}func(g,w=e.nil,C,V){return this._blockNode(new P(g,w,C)),V&&this.code(V).endFunc(),this}endFunc(){return this._endBlockNode(P)}optimize(g=1){for(;g-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(g){return this._currNode.nodes.push(g),this}_blockNode(g){this._currNode.nodes.push(g),this._nodes.push(g)}_endBlockNode(g,w){const C=this._currNode;if(C instanceof g||w&&C instanceof w)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${w?`${g.kind}/${w.kind}`:g.kind}"`)}_elseNode(g){const w=this._currNode;if(!(w instanceof m))throw new Error('CodeGen: "else" without "if"');return this._currNode=w.else=g,this}get _root(){return this._nodes[0]}get _currNode(){const g=this._nodes;return g[g.length-1]}set _currNode(g){const w=this._nodes;w[w.length-1]=g}}t.CodeGen=O;function B(k,g){for(const w in g)k[w]=(k[w]||0)+(g[w]||0);return k}function Z(k,g){return g instanceof e._CodeOrName?B(k,g.names):k}function I(k,g,w){if(k instanceof e.Name)return C(k);if(!V(k))return k;return new e._Code(k._items.reduce((F,ne)=>(ne instanceof e.Name&&(ne=C(ne)),ne instanceof e._Code?F.push(...ne._items):F.push(ne),F),[]));function C(F){const ne=w[F.str];return ne===void 0||g[F.str]!==1?F:(delete g[F.str],ne)}function V(F){return F instanceof e._Code&&F._items.some(ne=>ne instanceof e.Name&&g[ne.str]===1&&w[ne.str]!==void 0)}}function Q(k,g){for(const w in g)k[w]=(k[w]||0)-(g[w]||0)}function G(k){return typeof k=="boolean"||typeof k=="number"||k===null?!k:(0,e._)`!${A(k)}`}t.not=G;const re=S(t.operators.AND);function Oe(...k){return k.reduce(re)}t.and=Oe;const Ee=S(t.operators.OR);function M(...k){return k.reduce(Ee)}t.or=M;function S(k){return(g,w)=>g===e.nil?w:w===e.nil?g:(0,e._)`${A(g)} ${k} ${A(w)}`}function A(k){return k instanceof e.Name?k:(0,e._)`(${k})`}})(_e);var ee={};Object.defineProperty(ee,"__esModule",{value:!0});ee.checkStrictMode=ee.getErrorPath=ee.Type=ee.useFunc=ee.setEvaluated=ee.evaluatedPropsToName=ee.mergeEvaluated=ee.eachItem=ee.unescapeJsonPointer=ee.escapeJsonPointer=ee.escapeFragment=ee.unescapeFragment=ee.schemaRefOrVal=ee.schemaHasRulesButRef=ee.schemaHasRules=ee.checkUnknownRules=ee.alwaysValidSchema=ee.toHash=void 0;const je=_e,SI=Qi;function kI(t){const e={};for(const r of t)e[r]=!0;return e}ee.toHash=kI;function xI(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Iv(t,e),!Ov(e,t.self.RULES.all))}ee.alwaysValidSchema=xI;function Iv(t,e=t.schema){const{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;const s=n.RULES.keywords;for(const i in e)s[i]||Dv(t,`unknown keyword: "${i}"`)}ee.checkUnknownRules=Iv;function Ov(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(e[r])return!0;return!1}ee.schemaHasRules=Ov;function EI(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ee.schemaHasRulesButRef=EI;function CI({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,je._)`${r}`}return(0,je._)`${t}${e}${(0,je.getProperty)(n)}`}ee.schemaRefOrVal=CI;function PI(t){return Nv(decodeURIComponent(t))}ee.unescapeFragment=PI;function TI(t){return encodeURIComponent(Jd(t))}ee.escapeFragment=TI;function Jd(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ee.escapeJsonPointer=Jd;function Nv(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ee.unescapeJsonPointer=Nv;function RI(t,e){if(Array.isArray(t))for(const r of t)e(r);else e(t)}ee.eachItem=RI;function pm({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,i,o,a)=>{const l=o===void 0?i:o instanceof je.Name?(i instanceof je.Name?t(s,i,o):e(s,i,o),o):i instanceof je.Name?(e(s,o,i),i):r(i,o);return a===je.Name&&!(l instanceof je.Name)?n(s,l):l}}ee.mergeEvaluated={props:pm({mergeNames:(t,e,r)=>t.if((0,je._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,je._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,je._)`${r} || {}`).code((0,je._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,je._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,je._)`${r} || {}`),Yd(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:jv}),items:pm({mergeNames:(t,e,r)=>t.if((0,je._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,je._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,je._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,je._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function jv(t,e){if(e===!0)return t.var("props",!0);const r=t.var("props",(0,je._)`{}`);return e!==void 0&&Yd(t,r,e),r}ee.evaluatedPropsToName=jv;function Yd(t,e,r){Object.keys(r).forEach(n=>t.assign((0,je._)`${e}${(0,je.getProperty)(n)}`,!0))}ee.setEvaluated=Yd;const mm={};function AI(t,e){return t.scopeValue("func",{ref:e,code:mm[e.code]||(mm[e.code]=new SI._Code(e.code))})}ee.useFunc=AI;var hu;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(hu||(ee.Type=hu={}));function MI(t,e,r){if(t instanceof je.Name){const n=e===hu.Num;return r?n?(0,je._)`"[" + ${t} + "]"`:(0,je._)`"['" + ${t} + "']"`:n?(0,je._)`"/" + ${t}`:(0,je._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,je.getProperty)(t).toString():"/"+Jd(t)}ee.getErrorPath=MI;function Dv(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ee.checkStrictMode=Dv;var Br={};Object.defineProperty(Br,"__esModule",{value:!0});const Et=_e,II={data:new Et.Name("data"),valCxt:new Et.Name("valCxt"),instancePath:new Et.Name("instancePath"),parentData:new Et.Name("parentData"),parentDataProperty:new Et.Name("parentDataProperty"),rootData:new Et.Name("rootData"),dynamicAnchors:new Et.Name("dynamicAnchors"),vErrors:new Et.Name("vErrors"),errors:new Et.Name("errors"),this:new Et.Name("this"),self:new Et.Name("self"),scope:new Et.Name("scope"),json:new Et.Name("json"),jsonPos:new Et.Name("jsonPos"),jsonLen:new Et.Name("jsonLen"),jsonPart:new Et.Name("jsonPart")};Br.default=II;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=_e,r=ee,n=Br;t.keywordError={message:({keyword:v})=>(0,e.str)`must pass "${v}" keyword validation`},t.keyword$DataError={message:({keyword:v,schemaType:m})=>m?(0,e.str)`"${v}" keyword must be ${m} ($data)`:(0,e.str)`"${v}" keyword is invalid ($data)`};function s(v,m=t.keywordError,_,$){const{it:E}=v,{gen:x,compositeRule:P,allErrors:R}=E,z=h(v,m,_);$??(P||R)?l(x,z):c(E,(0,e._)`[${z}]`)}t.reportError=s;function i(v,m=t.keywordError,_){const{it:$}=v,{gen:E,compositeRule:x,allErrors:P}=$,R=h(v,m,_);l(E,R),x||P||c($,n.default.vErrors)}t.reportExtraError=i;function o(v,m){v.assign(n.default.errors,m),v.if((0,e._)`${n.default.vErrors} !== null`,()=>v.if(m,()=>v.assign((0,e._)`${n.default.vErrors}.length`,m),()=>v.assign(n.default.vErrors,null)))}t.resetErrorsCount=o;function a({gen:v,keyword:m,schemaValue:_,data:$,errsCount:E,it:x}){if(E===void 0)throw new Error("ajv implementation error");const P=v.name("err");v.forRange("i",E,n.default.errors,R=>{v.const(P,(0,e._)`${n.default.vErrors}[${R}]`),v.if((0,e._)`${P}.instancePath === undefined`,()=>v.assign((0,e._)`${P}.instancePath`,(0,e.strConcat)(n.default.instancePath,x.errorPath))),v.assign((0,e._)`${P}.schemaPath`,(0,e.str)`${x.errSchemaPath}/${m}`),x.opts.verbose&&(v.assign((0,e._)`${P}.schema`,_),v.assign((0,e._)`${P}.data`,$))})}t.extendErrors=a;function l(v,m){const _=v.const("err",m);v.if((0,e._)`${n.default.vErrors} === null`,()=>v.assign(n.default.vErrors,(0,e._)`[${_}]`),(0,e._)`${n.default.vErrors}.push(${_})`),v.code((0,e._)`${n.default.errors}++`)}function c(v,m){const{gen:_,validateName:$,schemaEnv:E}=v;E.$async?_.throw((0,e._)`new ${v.ValidationError}(${m})`):(_.assign((0,e._)`${$}.errors`,m),_.return(!1))}const u={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function h(v,m,_){const{createErrors:$}=v.it;return $===!1?(0,e._)`{}`:d(v,m,_)}function d(v,m,_={}){const{gen:$,it:E}=v,x=[f(E,_),p(v,_)];return y(v,m,x),$.object(...x)}function f({errorPath:v},{instancePath:m}){const _=m?(0,e.str)`${v}${(0,r.getErrorPath)(m,r.Type.Str)}`:v;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,_)]}function p({keyword:v,it:{errSchemaPath:m}},{schemaPath:_,parentSchema:$}){let E=$?m:(0,e.str)`${m}/${v}`;return _&&(E=(0,e.str)`${E}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,E]}function y(v,{params:m,message:_},$){const{keyword:E,data:x,schemaValue:P,it:R}=v,{opts:z,propertyName:L,topSchemaRef:H,schemaPath:O}=R;$.push([u.keyword,E],[u.params,typeof m=="function"?m(v):m||(0,e._)`{}`]),z.messages&&$.push([u.message,typeof _=="function"?_(v):_]),z.verbose&&$.push([u.schema,P],[u.parentSchema,(0,e._)`${H}${O}`],[n.default.data,x]),L&&$.push([u.propertyName,L])}})(So);Object.defineProperty(Vs,"__esModule",{value:!0});Vs.boolOrEmptySchema=Vs.topBoolOrEmptySchema=void 0;const OI=So,NI=_e,jI=Br,DI={message:"boolean schema is false"};function LI(t){const{gen:e,schema:r,validateName:n}=t;r===!1?Lv(t,!1):typeof r=="object"&&r.$async===!0?e.return(jI.default.data):(e.assign((0,NI._)`${n}.errors`,null),e.return(!0))}Vs.topBoolOrEmptySchema=LI;function zI(t,e){const{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Lv(t)):r.var(e,!0)}Vs.boolOrEmptySchema=zI;function Lv(t,e){const{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,OI.reportError)(s,DI,void 0,e)}var ot={},os={};Object.defineProperty(os,"__esModule",{value:!0});os.getRules=os.isJSONType=void 0;const FI=["string","number","integer","boolean","null","object","array"],qI=new Set(FI);function BI(t){return typeof t=="string"&&qI.has(t)}os.isJSONType=BI;function VI(){const t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}os.getRules=VI;var tn={};Object.defineProperty(tn,"__esModule",{value:!0});tn.shouldUseRule=tn.shouldUseGroup=tn.schemaHasRulesForType=void 0;function HI({schema:t,self:e},r){const n=e.RULES.types[r];return n&&n!==!0&&zv(t,n)}tn.schemaHasRulesForType=HI;function zv(t,e){return e.rules.some(r=>Fv(t,r))}tn.shouldUseGroup=zv;function Fv(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}tn.shouldUseRule=Fv;Object.defineProperty(ot,"__esModule",{value:!0});ot.reportTypeError=ot.checkDataTypes=ot.checkDataType=ot.coerceAndCheckDataType=ot.getJSONTypes=ot.getSchemaTypes=ot.DataType=void 0;const UI=os,WI=tn,KI=So,ge=_e,qv=ee;var Is;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Is||(ot.DataType=Is={}));function ZI(t){const e=Bv(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ot.getSchemaTypes=ZI;function Bv(t){const e=Array.isArray(t)?t:t?[t]:[];if(e.every(UI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ot.getJSONTypes=Bv;function GI(t,e){const{gen:r,data:n,opts:s}=t,i=JI(e,s.coerceTypes),o=e.length>0&&!(i.length===0&&e.length===1&&(0,WI.schemaHasRulesForType)(t,e[0]));if(o){const a=Qd(e,n,s.strictNumbers,Is.Wrong);r.if(a,()=>{i.length?YI(t,e,i):Xd(t)})}return o}ot.coerceAndCheckDataType=GI;const Vv=new Set(["string","number","integer","boolean","null"]);function JI(t,e){return e?t.filter(r=>Vv.has(r)||e==="array"&&r==="array"):[]}function YI(t,e,r){const{gen:n,data:s,opts:i}=t,o=n.let("dataType",(0,ge._)`typeof ${s}`),a=n.let("coerced",(0,ge._)`undefined`);i.coerceTypes==="array"&&n.if((0,ge._)`${o} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,ge._)`${s}[0]`).assign(o,(0,ge._)`typeof ${s}`).if(Qd(e,s,i.strictNumbers),()=>n.assign(a,s))),n.if((0,ge._)`${a} !== undefined`);for(const c of r)(Vv.has(c)||c==="array"&&i.coerceTypes==="array")&&l(c);n.else(),Xd(t),n.endIf(),n.if((0,ge._)`${a} !== undefined`,()=>{n.assign(s,a),QI(t,a)});function l(c){switch(c){case"string":n.elseIf((0,ge._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,ge._)`"" + ${s}`).elseIf((0,ge._)`${s} === null`).assign(a,(0,ge._)`""`);return;case"number":n.elseIf((0,ge._)`${o} == "boolean" || ${s} === null + || (${o} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,ge._)`+${s}`);return;case"integer":n.elseIf((0,ge._)`${o} === "boolean" || ${s} === null + || (${o} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,ge._)`+${s}`);return;case"boolean":n.elseIf((0,ge._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,ge._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ge._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ge._)`${o} === "string" || ${o} === "number" + || ${o} === "boolean" || ${s} === null`).assign(a,(0,ge._)`[${s}]`)}}}function QI({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ge._)`${e} !== undefined`,()=>t.assign((0,ge._)`${e}[${r}]`,n))}function du(t,e,r,n=Is.Correct){const s=n===Is.Correct?ge.operators.EQ:ge.operators.NEQ;let i;switch(t){case"null":return(0,ge._)`${e} ${s} null`;case"array":i=(0,ge._)`Array.isArray(${e})`;break;case"object":i=(0,ge._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=o((0,ge._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=o();break;default:return(0,ge._)`typeof ${e} ${s} ${t}`}return n===Is.Correct?i:(0,ge.not)(i);function o(a=ge.nil){return(0,ge.and)((0,ge._)`typeof ${e} == "number"`,a,r?(0,ge._)`isFinite(${e})`:ge.nil)}}ot.checkDataType=du;function Qd(t,e,r,n){if(t.length===1)return du(t[0],e,r,n);let s;const i=(0,qv.toHash)(t);if(i.array&&i.object){const o=(0,ge._)`typeof ${e} != "object"`;s=i.null?o:(0,ge._)`!${e} || ${o}`,delete i.null,delete i.array,delete i.object}else s=ge.nil;i.number&&delete i.integer;for(const o in i)s=(0,ge.and)(s,du(o,e,r,n));return s}ot.checkDataTypes=Qd;const XI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ge._)`{type: ${t}}`:(0,ge._)`{type: ${e}}`};function Xd(t){const e=eO(t);(0,KI.reportError)(e,XI)}ot.reportTypeError=Xd;function eO(t){const{gen:e,data:r,schema:n}=t,s=(0,qv.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}var Ll={};Object.defineProperty(Ll,"__esModule",{value:!0});Ll.assignDefaults=void 0;const ys=_e,tO=ee;function rO(t,e){const{properties:r,items:n}=t.schema;if(e==="object"&&r)for(const s in r)gm(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,i)=>gm(t,i,s.default))}Ll.assignDefaults=rO;function gm(t,e,r){const{gen:n,compositeRule:s,data:i,opts:o}=t;if(r===void 0)return;const a=(0,ys._)`${i}${(0,ys.getProperty)(e)}`;if(s){(0,tO.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,ys._)`${a} === undefined`;o.useDefaults==="empty"&&(l=(0,ys._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,ys._)`${a} = ${(0,ys.stringify)(r)}`)}var Or={},$e={};Object.defineProperty($e,"__esModule",{value:!0});$e.validateUnion=$e.validateArray=$e.usePattern=$e.callValidateCode=$e.schemaProperties=$e.allSchemaProperties=$e.noPropertyInData=$e.propertyInData=$e.isOwnProperty=$e.hasPropFunc=$e.reportMissingProp=$e.checkMissingProp=$e.checkReportMissingProp=void 0;const Ve=_e,ef=ee,hn=Br,nO=ee;function sO(t,e){const{gen:r,data:n,it:s}=t;r.if(rf(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ve._)`${e}`},!0),t.error()})}$e.checkReportMissingProp=sO;function iO({gen:t,data:e,it:{opts:r}},n,s){return(0,Ve.or)(...n.map(i=>(0,Ve.and)(rf(t,e,i,r.ownProperties),(0,Ve._)`${s} = ${i}`)))}$e.checkMissingProp=iO;function oO(t,e){t.setParams({missingProperty:e},!0),t.error()}$e.reportMissingProp=oO;function Hv(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ve._)`Object.prototype.hasOwnProperty`})}$e.hasPropFunc=Hv;function tf(t,e,r){return(0,Ve._)`${Hv(t)}.call(${e}, ${r})`}$e.isOwnProperty=tf;function aO(t,e,r,n){const s=(0,Ve._)`${e}${(0,Ve.getProperty)(r)} !== undefined`;return n?(0,Ve._)`${s} && ${tf(t,e,r)}`:s}$e.propertyInData=aO;function rf(t,e,r,n){const s=(0,Ve._)`${e}${(0,Ve.getProperty)(r)} === undefined`;return n?(0,Ve.or)(s,(0,Ve.not)(tf(t,e,r))):s}$e.noPropertyInData=rf;function Uv(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}$e.allSchemaProperties=Uv;function lO(t,e){return Uv(e).filter(r=>!(0,ef.alwaysValidSchema)(t,e[r]))}$e.schemaProperties=lO;function cO({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:i},it:o},a,l,c){const u=c?(0,Ve._)`${t}, ${e}, ${n}${s}`:e,h=[[hn.default.instancePath,(0,Ve.strConcat)(hn.default.instancePath,i)],[hn.default.parentData,o.parentData],[hn.default.parentDataProperty,o.parentDataProperty],[hn.default.rootData,hn.default.rootData]];o.opts.dynamicRef&&h.push([hn.default.dynamicAnchors,hn.default.dynamicAnchors]);const d=(0,Ve._)`${u}, ${r.object(...h)}`;return l!==Ve.nil?(0,Ve._)`${a}.call(${l}, ${d})`:(0,Ve._)`${a}(${d})`}$e.callValidateCode=cO;const uO=(0,Ve._)`new RegExp`;function hO({gen:t,it:{opts:e}},r){const n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,i=s(r,n);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,Ve._)`${s.code==="new RegExp"?uO:(0,nO.useFunc)(t,s)}(${r}, ${n})`})}$e.usePattern=hO;function dO(t){const{gen:e,data:r,keyword:n,it:s}=t,i=e.name("valid");if(s.allErrors){const a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(i,!0),o(()=>e.break()),i;function o(a){const l=e.const("len",(0,Ve._)`${r}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:n,dataProp:c,dataPropType:ef.Type.Num},i),e.if((0,Ve.not)(i),a)})}}$e.validateArray=dO;function fO(t){const{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,ef.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;const o=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,c)=>{const u=t.subschema({keyword:n,schemaProp:c,compositeRule:!0},a);e.assign(o,(0,Ve._)`${o} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Ve.not)(o))})),t.result(o,()=>t.reset(),()=>t.error(!0))}$e.validateUnion=fO;Object.defineProperty(Or,"__esModule",{value:!0});Or.validateKeywordUsage=Or.validSchemaType=Or.funcKeywordCode=Or.macroKeywordCode=void 0;const At=_e,Zn=Br,pO=$e,mO=So;function gO(t,e){const{gen:r,keyword:n,schema:s,parentSchema:i,it:o}=t,a=e.macro.call(o.self,s,i,o),l=Wv(r,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);const c=r.name("valid");t.subschema({schema:a,schemaPath:At.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}Or.macroKeywordCode=gO;function yO(t,e){var r;const{gen:n,keyword:s,schema:i,parentSchema:o,$data:a,it:l}=t;wO(l,e);const c=!a&&e.compile?e.compile.call(l.self,i,o,l):e.validate,u=Wv(n,s,c),h=n.let("valid");t.block$data(h,d),t.ok((r=e.valid)!==null&&r!==void 0?r:h);function d(){if(e.errors===!1)y(),e.modifying&&ym(t),v(()=>t.error());else{const m=e.async?f():p();e.modifying&&ym(t),v(()=>vO(t,m))}}function f(){const m=n.let("ruleErrs",null);return n.try(()=>y((0,At._)`await `),_=>n.assign(h,!1).if((0,At._)`${_} instanceof ${l.ValidationError}`,()=>n.assign(m,(0,At._)`${_}.errors`),()=>n.throw(_))),m}function p(){const m=(0,At._)`${u}.errors`;return n.assign(m,null),y(At.nil),m}function y(m=e.async?(0,At._)`await `:At.nil){const _=l.opts.passContext?Zn.default.this:Zn.default.self,$=!("compile"in e&&!a||e.schema===!1);n.assign(h,(0,At._)`${m}${(0,pO.callValidateCode)(t,u,_,$)}`,e.modifying)}function v(m){var _;n.if((0,At.not)((_=e.valid)!==null&&_!==void 0?_:h),m)}}Or.funcKeywordCode=yO;function ym(t){const{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,At._)`${n.parentData}[${n.parentDataProperty}]`))}function vO(t,e){const{gen:r}=t;r.if((0,At._)`Array.isArray(${e})`,()=>{r.assign(Zn.default.vErrors,(0,At._)`${Zn.default.vErrors} === null ? ${e} : ${Zn.default.vErrors}.concat(${e})`).assign(Zn.default.errors,(0,At._)`${Zn.default.vErrors}.length`),(0,mO.extendErrors)(t)},()=>t.error())}function wO({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Wv(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,At.stringify)(r)})}function _O(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Or.validSchemaType=_O;function bO({schema:t,opts:e,self:r,errSchemaPath:n},s,i){if(Array.isArray(s.keyword)?!s.keyword.includes(i):s.keyword!==i)throw new Error("ajv implementation error");const o=s.dependencies;if(o!=null&&o.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${o.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[i])){const l=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Or.validateKeywordUsage=bO;var En={};Object.defineProperty(En,"__esModule",{value:!0});En.extendSubschemaMode=En.extendSubschemaData=En.getSubschema=void 0;const Rr=_e,Kv=ee;function $O(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:i,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){const a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Rr._)`${t.schemaPath}${(0,Rr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Rr._)`${t.schemaPath}${(0,Rr.getProperty)(e)}${(0,Rr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Kv.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||i===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:o,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}En.getSubschema=$O;function SO(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:i,propertyName:o}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=e;if(r!==void 0){const{errorPath:c,dataPathArr:u,opts:h}=e,d=a.let("data",(0,Rr._)`${e.data}${(0,Rr.getProperty)(r)}`,!0);l(d),t.errorPath=(0,Rr.str)`${c}${(0,Kv.getErrorPath)(r,n,h.jsPropertySyntax)}`,t.parentDataProperty=(0,Rr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(s!==void 0){const c=s instanceof Rr.Name?s:a.let("data",s,!0);l(c),o!==void 0&&(t.propertyName=o)}i&&(t.dataTypes=i);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}En.extendSubschemaData=SO;function kO(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:i}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=r}En.extendSubschemaMode=kO;var vt={},Zv={exports:{}},bn=Zv.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};ba(e,n,s,t,"",t)};bn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};bn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};bn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};bn.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function ba(t,e,r,n,s,i,o,a,l,c){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,i,o,a,l,c);for(var u in n){var h=n[u];if(Array.isArray(h)){if(u in bn.arrayKeywords)for(var d=0;de+=Gv(n)),e===1/0))return 1/0}return e}function Jv(t,e="",r){r!==!1&&(e=Os(e));const n=t.parse(e);return Yv(t,n)}vt.getFullPath=Jv;function Yv(t,e){return t.serialize(e).split("#")[0]+"#"}vt._getFullPath=Yv;const IO=/#\/?$/;function Os(t){return t?t.replace(IO,""):""}vt.normalizeId=Os;function OO(t,e,r){return r=Os(r),t.resolve(e,r)}vt.resolveUrl=OO;const NO=/^[a-z_][-a-z0-9._]*$/i;function jO(t,e){if(typeof t=="boolean")return{};const{schemaId:r,uriResolver:n}=this.opts,s=Os(t[r]||e),i={"":s},o=Jv(n,s,!1),a={},l=new Set;return TO(t,{allKeys:!0},(h,d,f,p)=>{if(p===void 0)return;const y=o+d;let v=i[p];typeof h[r]=="string"&&(v=m.call(this,h[r])),_.call(this,h.$anchor),_.call(this,h.$dynamicAnchor),i[d]=v;function m($){const E=this.opts.uriResolver.resolve;if($=Os(v?E(v,$):$),l.has($))throw u($);l.add($);let x=this.refs[$];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?c(h,x.schema,$):$!==Os(y)&&($[0]==="#"?(c(h,a[$],$),a[$]=h):this.refs[$]=y),$}function _($){if(typeof $=="string"){if(!NO.test($))throw new Error(`invalid anchor "${$}"`);m.call(this,`#${$}`)}}}),a;function c(h,d,f){if(d!==void 0&&!PO(h,d))throw u(f)}function u(h){return new Error(`reference "${h}" resolves to more than one schema`)}}vt.getSchemaRefs=jO;Object.defineProperty(pr,"__esModule",{value:!0});pr.getData=pr.KeywordCxt=pr.validateFunctionCode=void 0;const Qv=Vs,vm=ot,nf=tn,Ua=ot,DO=Ll,ji=Or,uc=En,ae=_e,de=Br,LO=vt,rn=ee,gi=So;function zO(t){if(tw(t)&&(rw(t),ew(t))){BO(t);return}Xv(t,()=>(0,Qv.topBoolOrEmptySchema)(t))}pr.validateFunctionCode=zO;function Xv({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},i){s.code.es5?t.func(e,(0,ae._)`${de.default.data}, ${de.default.valCxt}`,n.$async,()=>{t.code((0,ae._)`"use strict"; ${wm(r,s)}`),qO(t,s),t.code(i)}):t.func(e,(0,ae._)`${de.default.data}, ${FO(s)}`,n.$async,()=>t.code(wm(r,s)).code(i))}function FO(t){return(0,ae._)`{${de.default.instancePath}="", ${de.default.parentData}, ${de.default.parentDataProperty}, ${de.default.rootData}=${de.default.data}${t.dynamicRef?(0,ae._)`, ${de.default.dynamicAnchors}={}`:ae.nil}}={}`}function qO(t,e){t.if(de.default.valCxt,()=>{t.var(de.default.instancePath,(0,ae._)`${de.default.valCxt}.${de.default.instancePath}`),t.var(de.default.parentData,(0,ae._)`${de.default.valCxt}.${de.default.parentData}`),t.var(de.default.parentDataProperty,(0,ae._)`${de.default.valCxt}.${de.default.parentDataProperty}`),t.var(de.default.rootData,(0,ae._)`${de.default.valCxt}.${de.default.rootData}`),e.dynamicRef&&t.var(de.default.dynamicAnchors,(0,ae._)`${de.default.valCxt}.${de.default.dynamicAnchors}`)},()=>{t.var(de.default.instancePath,(0,ae._)`""`),t.var(de.default.parentData,(0,ae._)`undefined`),t.var(de.default.parentDataProperty,(0,ae._)`undefined`),t.var(de.default.rootData,de.default.data),e.dynamicRef&&t.var(de.default.dynamicAnchors,(0,ae._)`{}`)})}function BO(t){const{schema:e,opts:r,gen:n}=t;Xv(t,()=>{r.$comment&&e.$comment&&sw(t),KO(t),n.let(de.default.vErrors,null),n.let(de.default.errors,0),r.unevaluated&&VO(t),nw(t),JO(t)})}function VO(t){const{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,ae._)`${r}.evaluated`),e.if((0,ae._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,ae._)`${t.evaluated}.props`,(0,ae._)`undefined`)),e.if((0,ae._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,ae._)`${t.evaluated}.items`,(0,ae._)`undefined`))}function wm(t,e){const r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,ae._)`/*# sourceURL=${r} */`:ae.nil}function HO(t,e){if(tw(t)&&(rw(t),ew(t))){UO(t,e);return}(0,Qv.boolOrEmptySchema)(t,e)}function ew({schema:t,self:e}){if(typeof t=="boolean")return!t;for(const r in t)if(e.RULES.all[r])return!0;return!1}function tw(t){return typeof t.schema!="boolean"}function UO(t,e){const{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&sw(t),ZO(t),GO(t);const i=n.const("_errs",de.default.errors);nw(t,i),n.var(e,(0,ae._)`${i} === ${de.default.errors}`)}function rw(t){(0,rn.checkUnknownRules)(t),WO(t)}function nw(t,e){if(t.opts.jtd)return _m(t,[],!1,e);const r=(0,vm.getSchemaTypes)(t.schema),n=(0,vm.coerceAndCheckDataType)(t,r);_m(t,r,!n,e)}function WO(t){const{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,rn.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function KO(t){const{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,rn.checkStrictMode)(t,"default is ignored in the schema root")}function ZO(t){const e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,LO.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function GO(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function sw({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){const i=r.$comment;if(s.$comment===!0)t.code((0,ae._)`${de.default.self}.logger.log(${i})`);else if(typeof s.$comment=="function"){const o=(0,ae.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,ae._)`${de.default.self}.opts.$comment(${i}, ${o}, ${a}.schema)`)}}function JO(t){const{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:i}=t;r.$async?e.if((0,ae._)`${de.default.errors} === 0`,()=>e.return(de.default.data),()=>e.throw((0,ae._)`new ${s}(${de.default.vErrors})`)):(e.assign((0,ae._)`${n}.errors`,de.default.vErrors),i.unevaluated&&YO(t),e.return((0,ae._)`${de.default.errors} === 0`))}function YO({gen:t,evaluated:e,props:r,items:n}){r instanceof ae.Name&&t.assign((0,ae._)`${e}.props`,r),n instanceof ae.Name&&t.assign((0,ae._)`${e}.items`,n)}function _m(t,e,r,n){const{gen:s,schema:i,data:o,allErrors:a,opts:l,self:c}=t,{RULES:u}=c;if(i.$ref&&(l.ignoreKeywordsWithRef||!(0,rn.schemaHasRulesButRef)(i,u))){s.block(()=>aw(t,"$ref",u.all.$ref.definition));return}l.jtd||QO(t,e),s.block(()=>{for(const d of u.rules)h(d);h(u.post)});function h(d){(0,nf.shouldUseGroup)(i,d)&&(d.type?(s.if((0,Ua.checkDataType)(d.type,o,l.strictNumbers)),bm(t,d),e.length===1&&e[0]===d.type&&r&&(s.else(),(0,Ua.reportTypeError)(t)),s.endIf()):bm(t,d),a||s.if((0,ae._)`${de.default.errors} === ${n||0}`))}}function bm(t,e){const{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,DO.assignDefaults)(t,e.type),r.block(()=>{for(const i of e.rules)(0,nf.shouldUseRule)(n,i)&&aw(t,i.keyword,i.definition,e.type)})}function QO(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(XO(t,e),t.opts.allowUnionTypes||eN(t,e),tN(t,t.dataTypes))}function XO(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{iw(t.dataTypes,r)||sf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),nN(t,e)}}function eN(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&sf(t,"use allowUnionTypes to allow union type keyword")}function tN(t,e){const r=t.self.RULES.all;for(const n in r){const s=r[n];if(typeof s=="object"&&(0,nf.shouldUseRule)(t.schema,s)){const{type:i}=s.definition;i.length&&!i.some(o=>rN(e,o))&&sf(t,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function rN(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function iw(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function nN(t,e){const r=[];for(const n of t.dataTypes)iw(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function sf(t,e){const r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,rn.checkStrictMode)(t,e,t.opts.strictTypes)}class ow{constructor(e,r,n){if((0,ji.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,rn.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",lw(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ji.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",de.default.errors))}result(e,r,n){this.failResult((0,ae.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,ae.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:r}=this;this.fail((0,ae._)`${r} !== undefined && (${(0,ae.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?gi.reportExtraError:gi.reportError)(this,this.def.error,r)}$dataError(){(0,gi.reportError)(this,this.def.$dataError||gi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,gi.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=ae.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=ae.nil,r=ae.nil){if(!this.$data)return;const{gen:n,schemaCode:s,schemaType:i,def:o}=this;n.if((0,ae.or)((0,ae._)`${s} === undefined`,r)),e!==ae.nil&&n.assign(e,!0),(i.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==ae.nil&&n.assign(e,!1)),n.else()}invalid$data(){const{gen:e,schemaCode:r,schemaType:n,def:s,it:i}=this;return(0,ae.or)(o(),a());function o(){if(n.length){if(!(r instanceof ae.Name))throw new Error("ajv implementation error");const l=Array.isArray(n)?n:[n];return(0,ae._)`${(0,Ua.checkDataTypes)(l,r,i.opts.strictNumbers,Ua.DataType.Wrong)}`}return ae.nil}function a(){if(s.validateSchema){const l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,ae._)`!${l}(${r})`}return ae.nil}}subschema(e,r){const n=(0,uc.getSubschema)(this.it,e);(0,uc.extendSubschemaData)(n,this.it,e),(0,uc.extendSubschemaMode)(n,e);const s={...this.it,...n,items:void 0,props:void 0};return HO(s,r),s}mergeEvaluated(e,r){const{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=rn.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=rn.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){const{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,ae.Name)),!0}}pr.KeywordCxt=ow;function aw(t,e,r,n){const s=new ow(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,ji.funcKeywordCode)(s,r):"macro"in r?(0,ji.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,ji.funcKeywordCode)(s,r)}const sN=/^\/(?:[^~]|~0|~1)*$/,iN=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function lw(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,i;if(t==="")return de.default.rootData;if(t[0]==="/"){if(!sN.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,i=de.default.rootData}else{const c=iN.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);const u=+c[1];if(s=c[2],s==="#"){if(u>=e)throw new Error(l("property/index",u));return n[e-u]}if(u>e)throw new Error(l("data",u));if(i=r[e-u],!s)return i}let o=i;const a=s.split("/");for(const c of a)c&&(i=(0,ae._)`${i}${(0,ae.getProperty)((0,rn.unescapeJsonPointer)(c))}`,o=(0,ae._)`${o} && ${i}`);return o;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}pr.getData=lw;var ko={};Object.defineProperty(ko,"__esModule",{value:!0});class oN extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}ko.default=oN;var oi={};Object.defineProperty(oi,"__esModule",{value:!0});const hc=vt;class aN extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,hc.resolveUrl)(e,r,n),this.missingSchema=(0,hc.normalizeId)((0,hc.getFullPath)(e,this.missingRef))}}oi.default=aN;var zt={};Object.defineProperty(zt,"__esModule",{value:!0});zt.resolveSchema=zt.getCompilingSchema=zt.resolveRef=zt.compileSchema=zt.SchemaEnv=void 0;const or=_e,lN=ko,zn=Br,ur=vt,$m=ee,cN=pr;class zl{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,ur.normalizeId)(n==null?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n==null?void 0:n.$async,this.refs={}}}zt.SchemaEnv=zl;function of(t){const e=cw.call(this,t);if(e)return e;const r=(0,ur.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:i}=this.opts,o=new or.CodeGen(this.scope,{es5:n,lines:s,ownProperties:i});let a;t.$async&&(a=o.scopeValue("Error",{ref:lN.default,code:(0,or._)`require("ajv/dist/runtime/validation_error").default`}));const l=o.scopeName("validate");t.validateName=l;const c={gen:o,allErrors:this.opts.allErrors,data:zn.default.data,parentData:zn.default.parentData,parentDataProperty:zn.default.parentDataProperty,dataNames:[zn.default.data],dataPathArr:[or.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,or.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:or.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,or._)`""`,opts:this.opts,self:this};let u;try{this._compilations.add(t),(0,cN.validateFunctionCode)(c),o.optimize(this.opts.code.optimize);const h=o.toString();u=`${o.scopeRefs(zn.default.scope)}return ${h}`,this.opts.code.process&&(u=this.opts.code.process(u,t));const f=new Function(`${zn.default.self}`,`${zn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:l,validateCode:h,scopeValues:o._values}),this.opts.unevaluated){const{props:p,items:y}=c;f.evaluated={props:p instanceof or.Name?void 0:p,items:y instanceof or.Name?void 0:y,dynamicProps:p instanceof or.Name,dynamicItems:y instanceof or.Name},f.source&&(f.source.evaluated=(0,or.stringify)(f.evaluated))}return t.validate=f,t}catch(h){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),h}finally{this._compilations.delete(t)}}zt.compileSchema=of;function uN(t,e,r){var n;r=(0,ur.resolveUrl)(this.opts.uriResolver,e,r);const s=t.refs[r];if(s)return s;let i=fN.call(this,t,r);if(i===void 0){const o=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;o&&(i=new zl({schema:o,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[r]=hN.call(this,i)}zt.resolveRef=uN;function hN(t){return(0,ur.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:of.call(this,t)}function cw(t){for(const e of this._compilations)if(dN(e,t))return e}zt.getCompilingSchema=cw;function dN(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function fN(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Fl.call(this,t,e)}function Fl(t,e){const r=this.opts.uriResolver.parse(e),n=(0,ur._getFullPath)(this.opts.uriResolver,r);let s=(0,ur.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return dc.call(this,r,t);const i=(0,ur.normalizeId)(n),o=this.refs[i]||this.schemas[i];if(typeof o=="string"){const a=Fl.call(this,t,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:dc.call(this,r,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||of.call(this,o),i===(0,ur.normalizeId)(e)){const{schema:a}=o,{schemaId:l}=this.opts,c=a[l];return c&&(s=(0,ur.resolveUrl)(this.opts.uriResolver,s,c)),new zl({schema:a,schemaId:l,root:t,baseId:s})}return dc.call(this,r,o)}}zt.resolveSchema=Fl;const pN=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function dc(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(const a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;const l=r[(0,$m.unescapeFragment)(a)];if(l===void 0)return;r=l;const c=typeof r=="object"&&r[this.opts.schemaId];!pN.has(a)&&c&&(e=(0,ur.resolveUrl)(this.opts.uriResolver,e,c))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,$m.schemaHasRulesButRef)(r,this.RULES)){const a=(0,ur.resolveUrl)(this.opts.uriResolver,e,r.$ref);i=Fl.call(this,n,a)}const{schemaId:o}=this.opts;if(i=i||new zl({schema:r,schemaId:o,root:n,baseId:e}),i.schema!==i.root.schema)return i}const mN="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",gN="Meta-schema for $data reference (JSON AnySchema extension proposal)",yN="object",vN=["$data"],wN={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},_N=!1,bN={$id:mN,description:gN,type:yN,required:vN,properties:wN,additionalProperties:_N};var af={};Object.defineProperty(af,"__esModule",{value:!0});const uw=_v;uw.code='require("ajv/dist/runtime/uri").default';af.default=uw;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=pr;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=_e;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=ko,s=oi,i=os,o=zt,a=_e,l=vt,c=ot,u=ee,h=bN,d=af,f=(M,S)=>new RegExp(M,S);f.code="new RegExp";const p=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),v={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},m={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function $(M){var S,A,k,g,w,C,V,F,ne,te,ve,Tt,Hr,Ur,Wr,Kr,Zr,Gr,Jr,Yr,vr,wr,_r,br,$r;const Nt=M.strict,Sr=(S=M.code)===null||S===void 0?void 0:S.optimize,an=Sr===!0||Sr===void 0?1:Sr||0,ln=(k=(A=M.code)===null||A===void 0?void 0:A.regExp)!==null&&k!==void 0?k:f,j=(g=M.uriResolver)!==null&&g!==void 0?g:d.default;return{strictSchema:(C=(w=M.strictSchema)!==null&&w!==void 0?w:Nt)!==null&&C!==void 0?C:!0,strictNumbers:(F=(V=M.strictNumbers)!==null&&V!==void 0?V:Nt)!==null&&F!==void 0?F:!0,strictTypes:(te=(ne=M.strictTypes)!==null&&ne!==void 0?ne:Nt)!==null&&te!==void 0?te:"log",strictTuples:(Tt=(ve=M.strictTuples)!==null&&ve!==void 0?ve:Nt)!==null&&Tt!==void 0?Tt:"log",strictRequired:(Ur=(Hr=M.strictRequired)!==null&&Hr!==void 0?Hr:Nt)!==null&&Ur!==void 0?Ur:!1,code:M.code?{...M.code,optimize:an,regExp:ln}:{optimize:an,regExp:ln},loopRequired:(Wr=M.loopRequired)!==null&&Wr!==void 0?Wr:_,loopEnum:(Kr=M.loopEnum)!==null&&Kr!==void 0?Kr:_,meta:(Zr=M.meta)!==null&&Zr!==void 0?Zr:!0,messages:(Gr=M.messages)!==null&&Gr!==void 0?Gr:!0,inlineRefs:(Jr=M.inlineRefs)!==null&&Jr!==void 0?Jr:!0,schemaId:(Yr=M.schemaId)!==null&&Yr!==void 0?Yr:"$id",addUsedSchema:(vr=M.addUsedSchema)!==null&&vr!==void 0?vr:!0,validateSchema:(wr=M.validateSchema)!==null&&wr!==void 0?wr:!0,validateFormats:(_r=M.validateFormats)!==null&&_r!==void 0?_r:!0,unicodeRegExp:(br=M.unicodeRegExp)!==null&&br!==void 0?br:!0,int32range:($r=M.int32range)!==null&&$r!==void 0?$r:!0,uriResolver:j}}class E{constructor(S={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,S=this.opts={...S,...$(S)};const{es5:A,lines:k}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:y,es5:A,lines:k}),this.logger=B(S.logger);const g=S.validateFormats;S.validateFormats=!1,this.RULES=(0,i.getRules)(),x.call(this,v,S,"NOT SUPPORTED"),x.call(this,m,S,"DEPRECATED","warn"),this._metaOpts=H.call(this),S.formats&&z.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),S.keywords&&L.call(this,S.keywords),typeof S.meta=="object"&&this.addMetaSchema(S.meta),R.call(this),S.validateFormats=g}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:S,meta:A,schemaId:k}=this.opts;let g=h;k==="id"&&(g={...h},g.id=g.$id,delete g.$id),A&&S&&this.addMetaSchema(g,g[k],!1)}defaultMeta(){const{meta:S,schemaId:A}=this.opts;return this.opts.defaultMeta=typeof S=="object"?S[A]||S:void 0}validate(S,A){let k;if(typeof S=="string"){if(k=this.getSchema(S),!k)throw new Error(`no schema with key or ref "${S}"`)}else k=this.compile(S);const g=k(A);return"$async"in k||(this.errors=k.errors),g}compile(S,A){const k=this._addSchema(S,A);return k.validate||this._compileSchemaEnv(k)}compileAsync(S,A){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:k}=this.opts;return g.call(this,S,A);async function g(te,ve){await w.call(this,te.$schema);const Tt=this._addSchema(te,ve);return Tt.validate||C.call(this,Tt)}async function w(te){te&&!this.getSchema(te)&&await g.call(this,{$ref:te},!0)}async function C(te){try{return this._compileSchemaEnv(te)}catch(ve){if(!(ve instanceof s.default))throw ve;return V.call(this,ve),await F.call(this,ve.missingSchema),C.call(this,te)}}function V({missingSchema:te,missingRef:ve}){if(this.refs[te])throw new Error(`AnySchema ${te} is loaded but ${ve} cannot be resolved`)}async function F(te){const ve=await ne.call(this,te);this.refs[te]||await w.call(this,ve.$schema),this.refs[te]||this.addSchema(ve,te,A)}async function ne(te){const ve=this._loading[te];if(ve)return ve;try{return await(this._loading[te]=k(te))}finally{delete this._loading[te]}}}addSchema(S,A,k,g=this.opts.validateSchema){if(Array.isArray(S)){for(const C of S)this.addSchema(C,void 0,k,g);return this}let w;if(typeof S=="object"){const{schemaId:C}=this.opts;if(w=S[C],w!==void 0&&typeof w!="string")throw new Error(`schema ${C} must be string`)}return A=(0,l.normalizeId)(A||w),this._checkUnique(A),this.schemas[A]=this._addSchema(S,k,A,g,!0),this}addMetaSchema(S,A,k=this.opts.validateSchema){return this.addSchema(S,A,!0,k),this}validateSchema(S,A){if(typeof S=="boolean")return!0;let k;if(k=S.$schema,k!==void 0&&typeof k!="string")throw new Error("$schema must be a string");if(k=k||this.opts.defaultMeta||this.defaultMeta(),!k)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const g=this.validate(k,S);if(!g&&A){const w="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(w);else throw new Error(w)}return g}getSchema(S){let A;for(;typeof(A=P.call(this,S))=="string";)S=A;if(A===void 0){const{schemaId:k}=this.opts,g=new o.SchemaEnv({schema:{},schemaId:k});if(A=o.resolveSchema.call(this,g,S),!A)return;this.refs[S]=A}return A.validate||this._compileSchemaEnv(A)}removeSchema(S){if(S instanceof RegExp)return this._removeAllSchemas(this.schemas,S),this._removeAllSchemas(this.refs,S),this;switch(typeof S){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const A=P.call(this,S);return typeof A=="object"&&this._cache.delete(A.schema),delete this.schemas[S],delete this.refs[S],this}case"object":{const A=S;this._cache.delete(A);let k=S[this.opts.schemaId];return k&&(k=(0,l.normalizeId)(k),delete this.schemas[k],delete this.refs[k]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(S){for(const A of S)this.addKeyword(A);return this}addKeyword(S,A){let k;if(typeof S=="string")k=S,typeof A=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),A.keyword=k);else if(typeof S=="object"&&A===void 0){if(A=S,k=A.keyword,Array.isArray(k)&&!k.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(I.call(this,k,A),!A)return(0,u.eachItem)(k,w=>Q.call(this,w)),this;re.call(this,A);const g={...A,type:(0,c.getJSONTypes)(A.type),schemaType:(0,c.getJSONTypes)(A.schemaType)};return(0,u.eachItem)(k,g.type.length===0?w=>Q.call(this,w,g):w=>g.type.forEach(C=>Q.call(this,w,g,C))),this}getKeyword(S){const A=this.RULES.all[S];return typeof A=="object"?A.definition:!!A}removeKeyword(S){const{RULES:A}=this;delete A.keywords[S],delete A.all[S];for(const k of A.rules){const g=k.rules.findIndex(w=>w.keyword===S);g>=0&&k.rules.splice(g,1)}return this}addFormat(S,A){return typeof A=="string"&&(A=new RegExp(A)),this.formats[S]=A,this}errorsText(S=this.errors,{separator:A=", ",dataVar:k="data"}={}){return!S||S.length===0?"No errors":S.map(g=>`${k}${g.instancePath} ${g.message}`).reduce((g,w)=>g+A+w)}$dataMetaSchema(S,A){const k=this.RULES.all;S=JSON.parse(JSON.stringify(S));for(const g of A){const w=g.split("/").slice(1);let C=S;for(const V of w)C=C[V];for(const V in k){const F=k[V];if(typeof F!="object")continue;const{$data:ne}=F.definition,te=C[V];ne&&te&&(C[V]=Ee(te))}}return S}_removeAllSchemas(S,A){for(const k in S){const g=S[k];(!A||A.test(k))&&(typeof g=="string"?delete S[k]:g&&!g.meta&&(this._cache.delete(g.schema),delete S[k]))}}_addSchema(S,A,k,g=this.opts.validateSchema,w=this.opts.addUsedSchema){let C;const{schemaId:V}=this.opts;if(typeof S=="object")C=S[V];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof S!="boolean")throw new Error("schema must be object or boolean")}let F=this._cache.get(S);if(F!==void 0)return F;k=(0,l.normalizeId)(C||k);const ne=l.getSchemaRefs.call(this,S,k);return F=new o.SchemaEnv({schema:S,schemaId:V,meta:A,baseId:k,localRefs:ne}),this._cache.set(F.schema,F),w&&!k.startsWith("#")&&(k&&this._checkUnique(k),this.refs[k]=F),g&&this.validateSchema(S,!0),F}_checkUnique(S){if(this.schemas[S]||this.refs[S])throw new Error(`schema with key or id "${S}" already exists`)}_compileSchemaEnv(S){if(S.meta?this._compileMetaSchema(S):o.compileSchema.call(this,S),!S.validate)throw new Error("ajv implementation error");return S.validate}_compileMetaSchema(S){const A=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,S)}finally{this.opts=A}}}E.ValidationError=n.default,E.MissingRefError=s.default,t.default=E;function x(M,S,A,k="error"){for(const g in M){const w=g;w in S&&this.logger[k](`${A}: option ${g}. ${M[w]}`)}}function P(M){return M=(0,l.normalizeId)(M),this.schemas[M]||this.refs[M]}function R(){const M=this.opts.schemas;if(M)if(Array.isArray(M))this.addSchema(M);else for(const S in M)this.addSchema(M[S],S)}function z(){for(const M in this.opts.formats){const S=this.opts.formats[M];S&&this.addFormat(M,S)}}function L(M){if(Array.isArray(M)){this.addVocabulary(M);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const S in M){const A=M[S];A.keyword||(A.keyword=S),this.addKeyword(A)}}function H(){const M={...this.opts};for(const S of p)delete M[S];return M}const O={log(){},warn(){},error(){}};function B(M){if(M===!1)return O;if(M===void 0)return console;if(M.log&&M.warn&&M.error)return M;throw new Error("logger must implement log, warn and error methods")}const Z=/^[a-z_$][a-z0-9_$:-]*$/i;function I(M,S){const{RULES:A}=this;if((0,u.eachItem)(M,k=>{if(A.keywords[k])throw new Error(`Keyword ${k} is already defined`);if(!Z.test(k))throw new Error(`Keyword ${k} has invalid name`)}),!!S&&S.$data&&!("code"in S||"validate"in S))throw new Error('$data keyword must have "code" or "validate" function')}function Q(M,S,A){var k;const g=S==null?void 0:S.post;if(A&&g)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:w}=this;let C=g?w.post:w.rules.find(({type:F})=>F===A);if(C||(C={type:A,rules:[]},w.rules.push(C)),w.keywords[M]=!0,!S)return;const V={keyword:M,definition:{...S,type:(0,c.getJSONTypes)(S.type),schemaType:(0,c.getJSONTypes)(S.schemaType)}};S.before?G.call(this,C,V,S.before):C.rules.push(V),w.all[M]=V,(k=S.implements)===null||k===void 0||k.forEach(F=>this.addKeyword(F))}function G(M,S,A){const k=M.rules.findIndex(g=>g.keyword===A);k>=0?M.rules.splice(k,0,S):(M.rules.push(S),this.logger.warn(`rule ${A} is not defined`))}function re(M){let{metaSchema:S}=M;S!==void 0&&(M.$data&&this.opts.$data&&(S=Ee(S)),M.validateSchema=this.compile(S,!0))}const Oe={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ee(M){return{anyOf:[M,Oe]}}})(Mv);var lf={},cf={},uf={};Object.defineProperty(uf,"__esModule",{value:!0});const $N={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};uf.default=$N;var as={};Object.defineProperty(as,"__esModule",{value:!0});as.callRef=as.getValidate=void 0;const SN=oi,Sm=$e,Dt=_e,vs=Br,km=zt,Vo=ee,kN={keyword:"$ref",schemaType:"string",code(t){const{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:i,validateName:o,opts:a,self:l}=n,{root:c}=i;if((r==="#"||r==="#/")&&s===c.baseId)return h();const u=km.resolveRef.call(l,c,s,r);if(u===void 0)throw new SN.default(n.opts.uriResolver,s,r);if(u instanceof km.SchemaEnv)return d(u);return f(u);function h(){if(i===c)return $a(t,o,i,i.$async);const p=e.scopeValue("root",{ref:c});return $a(t,(0,Dt._)`${p}.validate`,c,c.$async)}function d(p){const y=hw(t,p);$a(t,y,p,p.$async)}function f(p){const y=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Dt.stringify)(p)}:{ref:p}),v=e.name("valid"),m=t.subschema({schema:p,dataTypes:[],schemaPath:Dt.nil,topSchemaRef:y,errSchemaPath:r},v);t.mergeEvaluated(m),t.ok(v)}}};function hw(t,e){const{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Dt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}as.getValidate=hw;function $a(t,e,r,n){const{gen:s,it:i}=t,{allErrors:o,schemaEnv:a,opts:l}=i,c=l.passContext?vs.default.this:Dt.nil;n?u():h();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");const p=s.let("valid");s.try(()=>{s.code((0,Dt._)`await ${(0,Sm.callValidateCode)(t,e,c)}`),f(e),o||s.assign(p,!0)},y=>{s.if((0,Dt._)`!(${y} instanceof ${i.ValidationError})`,()=>s.throw(y)),d(y),o||s.assign(p,!1)}),t.ok(p)}function h(){t.result((0,Sm.callValidateCode)(t,e,c),()=>f(e),()=>d(e))}function d(p){const y=(0,Dt._)`${p}.errors`;s.assign(vs.default.vErrors,(0,Dt._)`${vs.default.vErrors} === null ? ${y} : ${vs.default.vErrors}.concat(${y})`),s.assign(vs.default.errors,(0,Dt._)`${vs.default.vErrors}.length`)}function f(p){var y;if(!i.opts.unevaluated)return;const v=(y=r==null?void 0:r.validate)===null||y===void 0?void 0:y.evaluated;if(i.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(i.props=Vo.mergeEvaluated.props(s,v.props,i.props));else{const m=s.var("props",(0,Dt._)`${p}.evaluated.props`);i.props=Vo.mergeEvaluated.props(s,m,i.props,Dt.Name)}if(i.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(i.items=Vo.mergeEvaluated.items(s,v.items,i.items));else{const m=s.var("items",(0,Dt._)`${p}.evaluated.items`);i.items=Vo.mergeEvaluated.items(s,m,i.items,Dt.Name)}}}as.callRef=$a;as.default=kN;Object.defineProperty(cf,"__esModule",{value:!0});const xN=uf,EN=as,CN=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",xN.default,EN.default];cf.default=CN;var hf={},df={};Object.defineProperty(df,"__esModule",{value:!0});const Wa=_e,dn=Wa.operators,Ka={maximum:{okStr:"<=",ok:dn.LTE,fail:dn.GT},minimum:{okStr:">=",ok:dn.GTE,fail:dn.LT},exclusiveMaximum:{okStr:"<",ok:dn.LT,fail:dn.GTE},exclusiveMinimum:{okStr:">",ok:dn.GT,fail:dn.LTE}},PN={message:({keyword:t,schemaCode:e})=>(0,Wa.str)`must be ${Ka[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Wa._)`{comparison: ${Ka[t].okStr}, limit: ${e}}`},TN={keyword:Object.keys(Ka),type:"number",schemaType:"number",$data:!0,error:PN,code(t){const{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Wa._)`${r} ${Ka[e].fail} ${n} || isNaN(${r})`)}};df.default=TN;var ff={};Object.defineProperty(ff,"__esModule",{value:!0});const Di=_e,RN={message:({schemaCode:t})=>(0,Di.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Di._)`{multipleOf: ${t}}`},AN={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:RN,code(t){const{gen:e,data:r,schemaCode:n,it:s}=t,i=s.opts.multipleOfPrecision,o=e.let("res"),a=i?(0,Di._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${i}`:(0,Di._)`${o} !== parseInt(${o})`;t.fail$data((0,Di._)`(${n} === 0 || (${o} = ${r}/${n}, ${a}))`)}};ff.default=AN;var pf={},mf={};Object.defineProperty(mf,"__esModule",{value:!0});function dw(t){const e=t.length;let r=0,n=0,s;for(;n=55296&&s<=56319&&n(0,Gn._)`{limit: ${t}}`},NN={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ON,code(t){const{keyword:e,data:r,schemaCode:n,it:s}=t,i=e==="maxLength"?Gn.operators.GT:Gn.operators.LT,o=s.opts.unicode===!1?(0,Gn._)`${r}.length`:(0,Gn._)`${(0,MN.useFunc)(t.gen,IN.default)}(${r})`;t.fail$data((0,Gn._)`${o} ${i} ${n}`)}};pf.default=NN;var gf={};Object.defineProperty(gf,"__esModule",{value:!0});const jN=$e,DN=ee,Ps=_e,LN={message:({schemaCode:t})=>(0,Ps.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ps._)`{pattern: ${t}}`},zN={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:LN,code(t){const{gen:e,data:r,$data:n,schema:s,schemaCode:i,it:o}=t,a=o.opts.unicodeRegExp?"u":"";if(n){const{regExp:l}=o.opts.code,c=l.code==="new RegExp"?(0,Ps._)`new RegExp`:(0,DN.useFunc)(e,l),u=e.let("valid");e.try(()=>e.assign(u,(0,Ps._)`${c}(${i}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Ps._)`!${u}`)}else{const l=(0,jN.usePattern)(t,s);t.fail$data((0,Ps._)`!${l}.test(${r})`)}}};gf.default=zN;var yf={};Object.defineProperty(yf,"__esModule",{value:!0});const Li=_e,FN={message({keyword:t,schemaCode:e}){const r=t==="maxProperties"?"more":"fewer";return(0,Li.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Li._)`{limit: ${t}}`},qN={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:FN,code(t){const{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Li.operators.GT:Li.operators.LT;t.fail$data((0,Li._)`Object.keys(${r}).length ${s} ${n}`)}};yf.default=qN;var vf={};Object.defineProperty(vf,"__esModule",{value:!0});const yi=$e,zi=_e,BN=ee,VN={message:({params:{missingProperty:t}})=>(0,zi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,zi._)`{missingProperty: ${t}}`},HN={keyword:"required",type:"object",schemaType:"array",$data:!0,error:VN,code(t){const{gen:e,schema:r,schemaCode:n,data:s,$data:i,it:o}=t,{opts:a}=o;if(!i&&r.length===0)return;const l=r.length>=a.loopRequired;if(o.allErrors?c():u(),a.strictRequired){const f=t.parentSchema.properties,{definedProperties:p}=t.it;for(const y of r)if((f==null?void 0:f[y])===void 0&&!p.has(y)){const v=o.schemaEnv.baseId+o.errSchemaPath,m=`required property "${y}" is not defined at "${v}" (strictRequired)`;(0,BN.checkStrictMode)(o,m,o.opts.strictRequired)}}function c(){if(l||i)t.block$data(zi.nil,h);else for(const f of r)(0,yi.checkReportMissingProp)(t,f)}function u(){const f=e.let("missing");if(l||i){const p=e.let("valid",!0);t.block$data(p,()=>d(f,p)),t.ok(p)}else e.if((0,yi.checkMissingProp)(t,r,f)),(0,yi.reportMissingProp)(t,f),e.else()}function h(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,yi.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function d(f,p){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(p,(0,yi.propertyInData)(e,s,f,a.ownProperties)),e.if((0,zi.not)(p),()=>{t.error(),e.break()})},zi.nil)}}};vf.default=HN;var wf={};Object.defineProperty(wf,"__esModule",{value:!0});const Fi=_e,UN={message({keyword:t,schemaCode:e}){const r=t==="maxItems"?"more":"fewer";return(0,Fi.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Fi._)`{limit: ${t}}`},WN={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:UN,code(t){const{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Fi.operators.GT:Fi.operators.LT;t.fail$data((0,Fi._)`${r}.length ${s} ${n}`)}};wf.default=WN;var _f={},xo={};Object.defineProperty(xo,"__esModule",{value:!0});const fw=Ml;fw.code='require("ajv/dist/runtime/equal").default';xo.default=fw;Object.defineProperty(_f,"__esModule",{value:!0});const fc=ot,pt=_e,KN=ee,ZN=xo,GN={message:({params:{i:t,j:e}})=>(0,pt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,pt._)`{i: ${t}, j: ${e}}`},JN={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:GN,code(t){const{gen:e,data:r,$data:n,schema:s,parentSchema:i,schemaCode:o,it:a}=t;if(!n&&!s)return;const l=e.let("valid"),c=i.items?(0,fc.getSchemaTypes)(i.items):[];t.block$data(l,u,(0,pt._)`${o} === false`),t.ok(l);function u(){const p=e.let("i",(0,pt._)`${r}.length`),y=e.let("j");t.setParams({i:p,j:y}),e.assign(l,!0),e.if((0,pt._)`${p} > 1`,()=>(h()?d:f)(p,y))}function h(){return c.length>0&&!c.some(p=>p==="object"||p==="array")}function d(p,y){const v=e.name("item"),m=(0,fc.checkDataTypes)(c,v,a.opts.strictNumbers,fc.DataType.Wrong),_=e.const("indices",(0,pt._)`{}`);e.for((0,pt._)`;${p}--;`,()=>{e.let(v,(0,pt._)`${r}[${p}]`),e.if(m,(0,pt._)`continue`),c.length>1&&e.if((0,pt._)`typeof ${v} == "string"`,(0,pt._)`${v} += "_"`),e.if((0,pt._)`typeof ${_}[${v}] == "number"`,()=>{e.assign(y,(0,pt._)`${_}[${v}]`),t.error(),e.assign(l,!1).break()}).code((0,pt._)`${_}[${v}] = ${p}`)})}function f(p,y){const v=(0,KN.useFunc)(e,ZN.default),m=e.name("outer");e.label(m).for((0,pt._)`;${p}--;`,()=>e.for((0,pt._)`${y} = ${p}; ${y}--;`,()=>e.if((0,pt._)`${v}(${r}[${p}], ${r}[${y}])`,()=>{t.error(),e.assign(l,!1).break(m)})))}}};_f.default=JN;var bf={};Object.defineProperty(bf,"__esModule",{value:!0});const pu=_e,YN=ee,QN=xo,XN={message:"must be equal to constant",params:({schemaCode:t})=>(0,pu._)`{allowedValue: ${t}}`},e2={keyword:"const",$data:!0,error:XN,code(t){const{gen:e,data:r,$data:n,schemaCode:s,schema:i}=t;n||i&&typeof i=="object"?t.fail$data((0,pu._)`!${(0,YN.useFunc)(e,QN.default)}(${r}, ${s})`):t.fail((0,pu._)`${i} !== ${r}`)}};bf.default=e2;var $f={};Object.defineProperty($f,"__esModule",{value:!0});const Ei=_e,t2=ee,r2=xo,n2={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ei._)`{allowedValues: ${t}}`},s2={keyword:"enum",schemaType:"array",$data:!0,error:n2,code(t){const{gen:e,data:r,$data:n,schema:s,schemaCode:i,it:o}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");const a=s.length>=o.opts.loopEnum;let l;const c=()=>l??(l=(0,t2.useFunc)(e,r2.default));let u;if(a||n)u=e.let("valid"),t.block$data(u,h);else{if(!Array.isArray(s))throw new Error("ajv implementation error");const f=e.const("vSchema",i);u=(0,Ei.or)(...s.map((p,y)=>d(f,y)))}t.pass(u);function h(){e.assign(u,!1),e.forOf("v",i,f=>e.if((0,Ei._)`${c()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function d(f,p){const y=s[p];return typeof y=="object"&&y!==null?(0,Ei._)`${c()}(${r}, ${f}[${p}])`:(0,Ei._)`${r} === ${y}`}}};$f.default=s2;Object.defineProperty(hf,"__esModule",{value:!0});const i2=df,o2=ff,a2=pf,l2=gf,c2=yf,u2=vf,h2=wf,d2=_f,f2=bf,p2=$f,m2=[i2.default,o2.default,a2.default,l2.default,c2.default,u2.default,h2.default,d2.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},f2.default,p2.default];hf.default=m2;var Sf={},ai={};Object.defineProperty(ai,"__esModule",{value:!0});ai.validateAdditionalItems=void 0;const Jn=_e,mu=ee,g2={message:({params:{len:t}})=>(0,Jn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Jn._)`{limit: ${t}}`},y2={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:g2,code(t){const{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,mu.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}pw(t,n)}};function pw(t,e){const{gen:r,schema:n,data:s,keyword:i,it:o}=t;o.items=!0;const a=r.const("len",(0,Jn._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Jn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,mu.alwaysValidSchema)(o,n)){const c=r.var("valid",(0,Jn._)`${a} <= ${e.length}`);r.if((0,Jn.not)(c),()=>l(c)),t.ok(c)}function l(c){r.forRange("i",e.length,a,u=>{t.subschema({keyword:i,dataProp:u,dataPropType:mu.Type.Num},c),o.allErrors||r.if((0,Jn.not)(c),()=>r.break())})}}ai.validateAdditionalItems=pw;ai.default=y2;var kf={},li={};Object.defineProperty(li,"__esModule",{value:!0});li.validateTuple=void 0;const xm=_e,Sa=ee,v2=$e,w2={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){const{schema:e,it:r}=t;if(Array.isArray(e))return mw(t,"additionalItems",e);r.items=!0,!(0,Sa.alwaysValidSchema)(r,e)&&t.ok((0,v2.validateArray)(t))}};function mw(t,e,r=t.schema){const{gen:n,parentSchema:s,data:i,keyword:o,it:a}=t;u(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Sa.mergeEvaluated.items(n,r.length,a.items));const l=n.name("valid"),c=n.const("len",(0,xm._)`${i}.length`);r.forEach((h,d)=>{(0,Sa.alwaysValidSchema)(a,h)||(n.if((0,xm._)`${c} > ${d}`,()=>t.subschema({keyword:o,schemaProp:d,dataProp:d},l)),t.ok(l))});function u(h){const{opts:d,errSchemaPath:f}=a,p=r.length,y=p===h.minItems&&(p===h.maxItems||h[e]===!1);if(d.strictTuples&&!y){const v=`"${o}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Sa.checkStrictMode)(a,v,d.strictTuples)}}}li.validateTuple=mw;li.default=w2;Object.defineProperty(kf,"__esModule",{value:!0});const _2=li,b2={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,_2.validateTuple)(t,"items")};kf.default=b2;var xf={};Object.defineProperty(xf,"__esModule",{value:!0});const Em=_e,$2=ee,S2=$e,k2=ai,x2={message:({params:{len:t}})=>(0,Em.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Em._)`{limit: ${t}}`},E2={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:x2,code(t){const{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,$2.alwaysValidSchema)(n,e)&&(s?(0,k2.validateAdditionalItems)(t,s):t.ok((0,S2.validateArray)(t)))}};xf.default=E2;var Ef={};Object.defineProperty(Ef,"__esModule",{value:!0});const Yt=_e,Ho=ee,C2={message:({params:{min:t,max:e}})=>e===void 0?(0,Yt.str)`must contain at least ${t} valid item(s)`:(0,Yt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Yt._)`{minContains: ${t}}`:(0,Yt._)`{minContains: ${t}, maxContains: ${e}}`},P2={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:C2,code(t){const{gen:e,schema:r,parentSchema:n,data:s,it:i}=t;let o,a;const{minContains:l,maxContains:c}=n;i.opts.next?(o=l===void 0?1:l,a=c):o=1;const u=e.const("len",(0,Yt._)`${s}.length`);if(t.setParams({min:o,max:a}),a===void 0&&o===0){(0,Ho.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Ho.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ho.alwaysValidSchema)(i,r)){let y=(0,Yt._)`${u} >= ${o}`;a!==void 0&&(y=(0,Yt._)`${y} && ${u} <= ${a}`),t.pass(y);return}i.items=!0;const h=e.name("valid");a===void 0&&o===1?f(h,()=>e.if(h,()=>e.break())):o===0?(e.let(h,!0),a!==void 0&&e.if((0,Yt._)`${s}.length > 0`,d)):(e.let(h,!1),d()),t.result(h,()=>t.reset());function d(){const y=e.name("_valid"),v=e.let("count",0);f(y,()=>e.if(y,()=>p(v)))}function f(y,v){e.forRange("i",0,u,m=>{t.subschema({keyword:"contains",dataProp:m,dataPropType:Ho.Type.Num,compositeRule:!0},y),v()})}function p(y){e.code((0,Yt._)`${y}++`),a===void 0?e.if((0,Yt._)`${y} >= ${o}`,()=>e.assign(h,!0).break()):(e.if((0,Yt._)`${y} > ${a}`,()=>e.assign(h,!1).break()),o===1?e.assign(h,!0):e.if((0,Yt._)`${y} >= ${o}`,()=>e.assign(h,!0)))}}};Ef.default=P2;var gw={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=_e,r=ee,n=$e;t.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const h=c===1?"property":"properties";return(0,e.str)`must have ${h} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:h}})=>(0,e._)`{property: ${l}, + missingProperty: ${h}, + depsCount: ${c}, + deps: ${u}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(l){const[c,u]=i(l);o(l,c),a(l,u)}};function i({schema:l}){const c={},u={};for(const h in l){if(h==="__proto__")continue;const d=Array.isArray(l[h])?c:u;d[h]=l[h]}return[c,u]}function o(l,c=l.schema){const{gen:u,data:h,it:d}=l;if(Object.keys(c).length===0)return;const f=u.let("missing");for(const p in c){const y=c[p];if(y.length===0)continue;const v=(0,n.propertyInData)(u,h,p,d.opts.ownProperties);l.setParams({property:p,depsCount:y.length,deps:y.join(", ")}),d.allErrors?u.if(v,()=>{for(const m of y)(0,n.checkReportMissingProp)(l,m)}):(u.if((0,e._)`${v} && (${(0,n.checkMissingProp)(l,y,f)})`),(0,n.reportMissingProp)(l,f),u.else())}}t.validatePropertyDeps=o;function a(l,c=l.schema){const{gen:u,data:h,keyword:d,it:f}=l,p=u.name("valid");for(const y in c)(0,r.alwaysValidSchema)(f,c[y])||(u.if((0,n.propertyInData)(u,h,y,f.opts.ownProperties),()=>{const v=l.subschema({keyword:d,schemaProp:y},p);l.mergeValidEvaluated(v,p)},()=>u.var(p,!0)),l.ok(p))}t.validateSchemaDeps=a,t.default=s})(gw);var Cf={};Object.defineProperty(Cf,"__esModule",{value:!0});const yw=_e,T2=ee,R2={message:"property name must be valid",params:({params:t})=>(0,yw._)`{propertyName: ${t.propertyName}}`},A2={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:R2,code(t){const{gen:e,schema:r,data:n,it:s}=t;if((0,T2.alwaysValidSchema)(s,r))return;const i=e.name("valid");e.forIn("key",n,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},i),e.if((0,yw.not)(i),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(i)}};Cf.default=A2;var ql={};Object.defineProperty(ql,"__esModule",{value:!0});const Uo=$e,lr=_e,M2=Br,Wo=ee,I2={message:"must NOT have additional properties",params:({params:t})=>(0,lr._)`{additionalProperty: ${t.additionalProperty}}`},O2={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:I2,code(t){const{gen:e,schema:r,parentSchema:n,data:s,errsCount:i,it:o}=t;if(!i)throw new Error("ajv implementation error");const{allErrors:a,opts:l}=o;if(o.props=!0,l.removeAdditional!=="all"&&(0,Wo.alwaysValidSchema)(o,r))return;const c=(0,Uo.allSchemaProperties)(n.properties),u=(0,Uo.allSchemaProperties)(n.patternProperties);h(),t.ok((0,lr._)`${i} === ${M2.default.errors}`);function h(){e.forIn("key",s,v=>{!c.length&&!u.length?p(v):e.if(d(v),()=>p(v))})}function d(v){let m;if(c.length>8){const _=(0,Wo.schemaRefOrVal)(o,n.properties,"properties");m=(0,Uo.isOwnProperty)(e,_,v)}else c.length?m=(0,lr.or)(...c.map(_=>(0,lr._)`${v} === ${_}`)):m=lr.nil;return u.length&&(m=(0,lr.or)(m,...u.map(_=>(0,lr._)`${(0,Uo.usePattern)(t,_)}.test(${v})`))),(0,lr.not)(m)}function f(v){e.code((0,lr._)`delete ${s}[${v}]`)}function p(v){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){f(v);return}if(r===!1){t.setParams({additionalProperty:v}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Wo.alwaysValidSchema)(o,r)){const m=e.name("valid");l.removeAdditional==="failing"?(y(v,m,!1),e.if((0,lr.not)(m),()=>{t.reset(),f(v)})):(y(v,m),a||e.if((0,lr.not)(m),()=>e.break()))}}function y(v,m,_){const $={keyword:"additionalProperties",dataProp:v,dataPropType:Wo.Type.Str};_===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema($,m)}}};ql.default=O2;var Pf={};Object.defineProperty(Pf,"__esModule",{value:!0});const N2=pr,Cm=$e,pc=ee,Pm=ql,j2={keyword:"properties",type:"object",schemaType:"object",code(t){const{gen:e,schema:r,parentSchema:n,data:s,it:i}=t;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Pm.default.code(new N2.KeywordCxt(i,Pm.default,"additionalProperties"));const o=(0,Cm.allSchemaProperties)(r);for(const h of o)i.definedProperties.add(h);i.opts.unevaluated&&o.length&&i.props!==!0&&(i.props=pc.mergeEvaluated.props(e,(0,pc.toHash)(o),i.props));const a=o.filter(h=>!(0,pc.alwaysValidSchema)(i,r[h]));if(a.length===0)return;const l=e.name("valid");for(const h of a)c(h)?u(h):(e.if((0,Cm.propertyInData)(e,s,h,i.opts.ownProperties)),u(h),i.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(h),t.ok(l);function c(h){return i.opts.useDefaults&&!i.compositeRule&&r[h].default!==void 0}function u(h){t.subschema({keyword:"properties",schemaProp:h,dataProp:h},l)}}};Pf.default=j2;var Tf={};Object.defineProperty(Tf,"__esModule",{value:!0});const Tm=$e,Ko=_e,Rm=ee,Am=ee,D2={keyword:"patternProperties",type:"object",schemaType:"object",code(t){const{gen:e,schema:r,data:n,parentSchema:s,it:i}=t,{opts:o}=i,a=(0,Tm.allSchemaProperties)(r),l=a.filter(y=>(0,Rm.alwaysValidSchema)(i,r[y]));if(a.length===0||l.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;const c=o.strictSchema&&!o.allowMatchingProperties&&s.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof Ko.Name)&&(i.props=(0,Am.evaluatedPropsToName)(e,i.props));const{props:h}=i;d();function d(){for(const y of a)c&&f(y),i.allErrors?p(y):(e.var(u,!0),p(y),e.if(u))}function f(y){for(const v in c)new RegExp(y).test(v)&&(0,Rm.checkStrictMode)(i,`property ${v} matches pattern ${y} (use allowMatchingProperties)`)}function p(y){e.forIn("key",n,v=>{e.if((0,Ko._)`${(0,Tm.usePattern)(t,y)}.test(${v})`,()=>{const m=l.includes(y);m||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:v,dataPropType:Am.Type.Str},u),i.opts.unevaluated&&h!==!0?e.assign((0,Ko._)`${h}[${v}]`,!0):!m&&!i.allErrors&&e.if((0,Ko.not)(u),()=>e.break())})})}}};Tf.default=D2;var Rf={};Object.defineProperty(Rf,"__esModule",{value:!0});const L2=ee,z2={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:e,schema:r,it:n}=t;if((0,L2.alwaysValidSchema)(n,r)){t.fail();return}const s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Rf.default=z2;var Af={};Object.defineProperty(Af,"__esModule",{value:!0});const F2=$e,q2={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:F2.validateUnion,error:{message:"must match a schema in anyOf"}};Af.default=q2;var Mf={};Object.defineProperty(Mf,"__esModule",{value:!0});const ka=_e,B2=ee,V2={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ka._)`{passingSchemas: ${t.passing}}`},H2={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:V2,code(t){const{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;const i=r,o=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(c),t.result(o,()=>t.reset(),()=>t.error(!0));function c(){i.forEach((u,h)=>{let d;(0,B2.alwaysValidSchema)(s,u)?e.var(l,!0):d=t.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},l),h>0&&e.if((0,ka._)`${l} && ${o}`).assign(o,!1).assign(a,(0,ka._)`[${a}, ${h}]`).else(),e.if(l,()=>{e.assign(o,!0),e.assign(a,h),d&&t.mergeEvaluated(d,ka.Name)})})}}};Mf.default=H2;var If={};Object.defineProperty(If,"__esModule",{value:!0});const U2=ee,W2={keyword:"allOf",schemaType:"array",code(t){const{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");const s=e.name("valid");r.forEach((i,o)=>{if((0,U2.alwaysValidSchema)(n,i))return;const a=t.subschema({keyword:"allOf",schemaProp:o},s);t.ok(s),t.mergeEvaluated(a)})}};If.default=W2;var Of={};Object.defineProperty(Of,"__esModule",{value:!0});const Za=_e,vw=ee,K2={message:({params:t})=>(0,Za.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Za._)`{failingKeyword: ${t.ifClause}}`},Z2={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:K2,code(t){const{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,vw.checkStrictMode)(n,'"if" without "then" and "else" is ignored');const s=Mm(n,"then"),i=Mm(n,"else");if(!s&&!i)return;const o=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),s&&i){const u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,c("then",u),c("else",u))}else s?e.if(a,c("then")):e.if((0,Za.not)(a),c("else"));t.pass(o,()=>t.error(!0));function l(){const u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function c(u,h){return()=>{const d=t.subschema({keyword:u},a);e.assign(o,a),t.mergeValidEvaluated(d,o),h?e.assign(h,(0,Za._)`${u}`):t.setParams({ifClause:u})}}}};function Mm(t,e){const r=t.schema[e];return r!==void 0&&!(0,vw.alwaysValidSchema)(t,r)}Of.default=Z2;var Nf={};Object.defineProperty(Nf,"__esModule",{value:!0});const G2=ee,J2={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,G2.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Nf.default=J2;Object.defineProperty(Sf,"__esModule",{value:!0});const Y2=ai,Q2=kf,X2=li,ej=xf,tj=Ef,rj=gw,nj=Cf,sj=ql,ij=Pf,oj=Tf,aj=Rf,lj=Af,cj=Mf,uj=If,hj=Of,dj=Nf;function fj(t=!1){const e=[aj.default,lj.default,cj.default,uj.default,hj.default,dj.default,nj.default,sj.default,rj.default,ij.default,oj.default];return t?e.push(Q2.default,ej.default):e.push(Y2.default,X2.default),e.push(tj.default),e}Sf.default=fj;var jf={},Df={};Object.defineProperty(Df,"__esModule",{value:!0});const et=_e,pj={message:({schemaCode:t})=>(0,et.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,et._)`{format: ${t}}`},mj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:pj,code(t,e){const{gen:r,data:n,$data:s,schema:i,schemaCode:o,it:a}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:h}=a;if(!l.validateFormats)return;s?d():f();function d(){const p=r.scopeValue("formats",{ref:h.formats,code:l.code.formats}),y=r.const("fDef",(0,et._)`${p}[${o}]`),v=r.let("fType"),m=r.let("format");r.if((0,et._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(v,(0,et._)`${y}.type || "string"`).assign(m,(0,et._)`${y}.validate`),()=>r.assign(v,(0,et._)`"string"`).assign(m,y)),t.fail$data((0,et.or)(_(),$()));function _(){return l.strictSchema===!1?et.nil:(0,et._)`${o} && !${m}`}function $(){const E=u.$async?(0,et._)`(${y}.async ? await ${m}(${n}) : ${m}(${n}))`:(0,et._)`${m}(${n})`,x=(0,et._)`(typeof ${m} == "function" ? ${E} : ${m}.test(${n}))`;return(0,et._)`${m} && ${m} !== true && ${v} === ${e} && !${x}`}}function f(){const p=h.formats[i];if(!p){_();return}if(p===!0)return;const[y,v,m]=$(p);y===e&&t.pass(E());function _(){if(l.strictSchema===!1){h.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${i}" ignored in schema at path "${c}"`}}function $(x){const P=x instanceof RegExp?(0,et.regexpCode)(x):l.code.formats?(0,et._)`${l.code.formats}${(0,et.getProperty)(i)}`:void 0,R=r.scopeValue("formats",{key:i,ref:x,code:P});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,et._)`${R}.validate`]:["string",x,R]}function E(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!u.$async)throw new Error("async format in sync schema");return(0,et._)`await ${m}(${n})`}return typeof v=="function"?(0,et._)`${m}(${n})`:(0,et._)`${m}.test(${n})`}}}};Df.default=mj;Object.defineProperty(jf,"__esModule",{value:!0});const gj=Df,yj=[gj.default];jf.default=yj;var Hs={};Object.defineProperty(Hs,"__esModule",{value:!0});Hs.contentVocabulary=Hs.metadataVocabulary=void 0;Hs.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Hs.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(lf,"__esModule",{value:!0});const vj=cf,wj=hf,_j=Sf,bj=jf,Im=Hs,$j=[vj.default,wj.default,(0,_j.default)(),bj.default,Im.metadataVocabulary,Im.contentVocabulary];lf.default=$j;var Lf={},Bl={};Object.defineProperty(Bl,"__esModule",{value:!0});Bl.DiscrError=void 0;var Om;(function(t){t.Tag="tag",t.Mapping="mapping"})(Om||(Bl.DiscrError=Om={}));Object.defineProperty(Lf,"__esModule",{value:!0});const $s=_e,gu=Bl,Nm=zt,Sj=oi,kj=ee,xj={message:({params:{discrError:t,tagName:e}})=>t===gu.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,$s._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Ej={keyword:"discriminator",type:"object",schemaType:"object",error:xj,code(t){const{gen:e,data:r,schema:n,parentSchema:s,it:i}=t,{oneOf:o}=s;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");const a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");const l=e.let("valid",!1),c=e.const("tag",(0,$s._)`${r}${(0,$s.getProperty)(a)}`);e.if((0,$s._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:gu.DiscrError.Tag,tag:c,tagName:a})),t.ok(l);function u(){const f=d();e.if(!1);for(const p in f)e.elseIf((0,$s._)`${c} === ${p}`),e.assign(l,h(f[p]));e.else(),t.error(!1,{discrError:gu.DiscrError.Mapping,tag:c,tagName:a}),e.endIf()}function h(f){const p=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:f},p);return t.mergeEvaluated(y,$s.Name),p}function d(){var f;const p={},y=m(s);let v=!0;for(let E=0;Ethis.addVocabulary(p)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const p=this.opts.$data?this.$dataMetaSchema(i,o):i;this.addMetaSchema(p,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}e.Ajv=l,t.exports=e=l,t.exports.Ajv=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=pr;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=_e;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var h=ko;Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return h.default}});var d=oi;Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return d.default}})})(cu,cu.exports);var Oj=cu.exports;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const e=Oj,r=_e,n=r.operators,s={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},i={message:({keyword:a,schemaCode:l})=>(0,r.str)`should be ${s[a].okStr} ${l}`,params:({keyword:a,schemaCode:l})=>(0,r._)`{comparison: ${s[a].okStr}, limit: ${l}}`};t.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:i,code(a){const{gen:l,data:c,schemaCode:u,keyword:h,it:d}=a,{opts:f,self:p}=d;if(!f.validateFormats)return;const y=new e.KeywordCxt(d,p.RULES.all.format.definition,"format");y.$data?v():m();function v(){const $=l.scopeValue("formats",{ref:p.formats,code:f.code.formats}),E=l.const("fmt",(0,r._)`${$}[${y.schemaCode}]`);a.fail$data((0,r.or)((0,r._)`typeof ${E} != "object"`,(0,r._)`${E} instanceof RegExp`,(0,r._)`typeof ${E}.compare != "function"`,_(E)))}function m(){const $=y.schema,E=p.formats[$];if(!E||E===!0)return;if(typeof E!="object"||E instanceof RegExp||typeof E.compare!="function")throw new Error(`"${h}": format "${$}" does not define "compare" function`);const x=l.scopeValue("formats",{key:$,ref:E,code:f.code.formats?(0,r._)`${f.code.formats}${(0,r.getProperty)($)}`:void 0});a.fail$data(_(x))}function _($){return(0,r._)`${$}.compare(${c}, ${u}) ${s[h].fail} 0`}},dependencies:["format"]};const o=a=>(a.addKeyword(t.formatLimitDefinition),a);t.default=o})(Av);(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});const r=Rv,n=Av,s=_e,i=new s.Name("fullFormats"),o=new s.Name("fastFormats"),a=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,i),c;const[h,d]=u.mode==="fast"?[r.fastFormats,o]:[r.fullFormats,i],f=u.formats||r.formatNames;return l(c,f,h,d),u.keywords&&(0,n.default)(c),c};a.get=(c,u="full")=>{const d=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!d)throw new Error(`Unknown format "${c}"`);return d};function l(c,u,h,d){var f,p;(f=(p=c.opts.code).formats)!==null&&f!==void 0||(p.formats=(0,s._)`require("ajv-formats/dist/formats").${d}`);for(const y of u)c.addFormat(y,h[y])}t.exports=e=a,Object.defineProperty(e,"__esModule",{value:!0}),e.default=a})(lu,lu.exports);var Nj=lu.exports;const jj=uy(Nj);function Dj(){const t=new $I({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return jj(t),t}class Lj{constructor(e){this._ajv=e??Dj()}getValidator(e){const r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}class zj{constructor(e){this._client=e}async*callToolStream(e,r=rs,n){const s=this._client,i={...n,task:(n==null?void 0:n.task)??(s.isToolTask(e.name)?{}:void 0)},o=s.requestStream({method:"tools/call",params:e},r,i),a=s.getToolOutputValidator(e.name);for await(const l of o){if(l.type==="result"&&a){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new ue(fe.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=a(c.structuredContent);if(!u.valid){yield{type:"error",error:new ue(fe.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof ue){yield{type:"error",error:u};return}yield{type:"error",error:new ue(fe.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}}function Fj(t,e,r){var n;if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!((n=t.tools)!=null&&n.call))throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break}}function qj(t,e,r){var n,s;if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!((n=t.sampling)!=null&&n.createMessage))throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!((s=t.elicitation)!=null&&s.create))throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break}}function xa(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){const r=e,n=t.properties;for(const s of Object.keys(n)){const i=n[s];r[s]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[s]=i.default),r[s]!==void 0&&xa(i,r[s])}}if(Array.isArray(t.anyOf))for(const r of t.anyOf)typeof r!="boolean"&&xa(r,e);if(Array.isArray(t.oneOf))for(const r of t.oneOf)typeof r!="boolean"&&xa(r,e)}}function Bj(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};const e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}class Vj extends k0{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=(r==null?void 0:r.capabilities)??{},this._jsonSchemaValidator=(r==null?void 0:r.jsonSchemaValidator)??new Lj,r!=null&&r.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){var r,n,s,i,o,a;e.tools&&((n=(r=this._serverCapabilities)==null?void 0:r.tools)!=null&&n.listChanged)&&this._setupListChangedHandler("tools",ed,e.tools,async()=>(await this.listTools()).tools),e.prompts&&((i=(s=this._serverCapabilities)==null?void 0:s.prompts)!=null&&i.listChanged)&&this._setupListChangedHandler("prompts",Yh,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&((a=(o=this._serverCapabilities)==null?void 0:o.resources)!=null&&a.listChanged)&&this._setupListChangedHandler("resources",Wh,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new zj(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qC(this._capabilities,e)}setRequestHandler(e,r){const n=$0(e),s=n==null?void 0:n.method;if(!s)throw new Error("Schema is missing a method literal");const i=S0(s);if(typeof i!="string")throw new Error("Schema method literal must be a string");const o=i;if(o==="elicitation/create"){const a=async(l,c)=>{var _,$;const u=fn(w0,l);if(!u.success){const E=u.error instanceof Error?u.error.message:String(u.error);throw new ue(fe.InvalidParams,`Invalid elicitation request: ${E}`)}const{params:h}=u.data;h.mode=h.mode??"form";const{supportsFormMode:d,supportsUrlMode:f}=Bj(this._capabilities.elicitation);if(h.mode==="form"&&!d)throw new ue(fe.InvalidParams,"Client does not support form-mode elicitation requests");if(h.mode==="url"&&!f)throw new ue(fe.InvalidParams,"Client does not support URL-mode elicitation requests");const p=await Promise.resolve(r(l,c));if(h.task){const E=fn(Gi,p);if(!E.success){const x=E.error instanceof Error?E.error.message:String(E.error);throw new ue(fe.InvalidParams,`Invalid task creation result: ${x}`)}return E.data}const y=fn(_0,p);if(!y.success){const E=y.error instanceof Error?y.error.message:String(y.error);throw new ue(fe.InvalidParams,`Invalid elicitation result: ${E}`)}const v=y.data,m=h.mode==="form"?h.requestedSchema:void 0;if(h.mode==="form"&&v.action==="accept"&&v.content&&m&&($=(_=this._capabilities.elicitation)==null?void 0:_.form)!=null&&$.applyDefaults)try{xa(m,v.content)}catch{}return v};return super.setRequestHandler(e,a)}if(o==="sampling/createMessage"){const a=async(l,c)=>{const u=fn(td,l);if(!u.success){const v=u.error instanceof Error?u.error.message:String(u.error);throw new ue(fe.InvalidParams,`Invalid sampling request: ${v}`)}const{params:h}=u.data,d=await Promise.resolve(r(l,c));if(h.task){const v=fn(Gi,d);if(!v.success){const m=v.error instanceof Error?v.error.message:String(v.error);throw new ue(fe.InvalidParams,`Invalid task creation result: ${m}`)}return v.data}const p=h.tools||h.toolChoice?v0:y0,y=fn(p,d);if(!y.success){const v=y.error instanceof Error?y.error.message:String(y.error);throw new ue(fe.InvalidParams,`Invalid sampling result: ${v}`)}return y.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){var n;if(!((n=this._serverCapabilities)!=null&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:Cl,capabilities:this._capabilities,clientInfo:this._clientInfo}},t0,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!gE.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,s,i,o;switch(e){case"logging/setLevel":if(!((r=this._serverCapabilities)!=null&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!((n=this._serverCapabilities)!=null&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!((s=this._serverCapabilities)!=null&&s.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!((i=this._serverCapabilities)!=null&&i.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!((o=this._serverCapabilities)!=null&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!((r=this._capabilities.roots)!=null&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break}}assertTaskCapability(e){var r,n;Fj((n=(r=this._serverCapabilities)==null?void 0:r.tasks)==null?void 0:n.requests,e,"Server")}assertTaskHandlerCapability(e){var r;this._capabilities&&qj((r=this._capabilities.tasks)==null?void 0:r.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Es,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},b0,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Es,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},f0,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Kh,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Bh,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Vh,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Uh,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Es,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Es,r)}async callTool(e,r=rs,n){if(this.isToolTaskRequired(e.name))throw new ue(fe.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const s=await this.request({method:"tools/call",params:e},r,n),i=this.getToolOutputValidator(e.name);if(i){if(!s.structuredContent&&!s.isError)throw new ue(fe.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{const o=i(s.structuredContent);if(!o.valid)throw new ue(fe.InvalidParams,`Structured content does not match the tool's output schema: ${o.errorMessage}`)}catch(o){throw o instanceof ue?o:new ue(fe.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return s}isToolTask(e){var r,n,s,i;return(i=(s=(n=(r=this._serverCapabilities)==null?void 0:r.tasks)==null?void 0:n.requests)==null?void 0:s.tools)!=null&&i.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){var r;this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const n of e){if(n.outputSchema){const i=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,i)}const s=(r=n.execution)==null?void 0:r.taskSupport;(s==="required"||s==="optional")&&this._cachedKnownTaskTools.add(n.name),s==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const n=await this.request({method:"tools/list",params:e},Xh,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,s){const i=nC.safeParse(n);if(!i.success)throw new Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:o,debounceMs:a}=i.data,{onChanged:l}=n,c=async()=>{if(!o){l(null,null);return}try{const h=await s();l(null,h)}catch(h){const d=h instanceof Error?h:new Error(String(h));l(d,null)}},u=()=>{if(a){const h=this._listChangedDebounceTimers.get(e);h&&clearTimeout(h);const d=setTimeout(c,a);this._listChangedDebounceTimers.set(e,d)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}var zf={};/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */var jm=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,Hj=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,ww=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,Uj=/\\([\u000b\u0020-\u00ff])/g,Wj=/([\\"])/g,_w=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;zf.format=Kj;zf.parse=Zj;function Kj(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!_w.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var s,i=Object.keys(e).sort(),o=0;o0&&!Hj.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(Wj,"\\$1")+'"'}function Yj(t){this.parameters=Object.create(null),this.type=t}function Qj(t){if(t)try{return zf.parse(t).type}catch{const e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function yu(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Xj(t=fetch,e){return e?async(r,n)=>{const s={...e,...n,headers:n!=null&&n.headers?{...yu(e.headers),...yu(n.headers)}:e.headers};return t(r,s)}:t}let Ff;Ff=globalThis.crypto;async function eD(t){return(await Ff).getRandomValues(new Uint8Array(t))}async function tD(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length;let n="";for(;n.length128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await rD(t),r=await nD(e);return{code_verifier:e,code_challenge:r}}const gt=Sx().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:pE.custom,message:"URL must be parseable",fatal:!0}),h1}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),iD=_t({resource:T().url(),authorization_servers:K(gt).optional(),jwks_uri:T().url().optional(),scopes_supported:K(T()).optional(),bearer_methods_supported:K(T()).optional(),resource_signing_alg_values_supported:K(T()).optional(),resource_name:T().optional(),resource_documentation:T().optional(),resource_policy_uri:T().url().optional(),resource_tos_uri:T().url().optional(),tls_client_certificate_bound_access_tokens:Pe().optional(),authorization_details_types_supported:K(T()).optional(),dpop_signing_alg_values_supported:K(T()).optional(),dpop_bound_access_tokens_required:Pe().optional()}),bw=_t({issuer:T(),authorization_endpoint:gt,token_endpoint:gt,registration_endpoint:gt.optional(),scopes_supported:K(T()).optional(),response_types_supported:K(T()),response_modes_supported:K(T()).optional(),grant_types_supported:K(T()).optional(),token_endpoint_auth_methods_supported:K(T()).optional(),token_endpoint_auth_signing_alg_values_supported:K(T()).optional(),service_documentation:gt.optional(),revocation_endpoint:gt.optional(),revocation_endpoint_auth_methods_supported:K(T()).optional(),revocation_endpoint_auth_signing_alg_values_supported:K(T()).optional(),introspection_endpoint:T().optional(),introspection_endpoint_auth_methods_supported:K(T()).optional(),introspection_endpoint_auth_signing_alg_values_supported:K(T()).optional(),code_challenge_methods_supported:K(T()).optional(),client_id_metadata_document_supported:Pe().optional()}),oD=_t({issuer:T(),authorization_endpoint:gt,token_endpoint:gt,userinfo_endpoint:gt.optional(),jwks_uri:gt,registration_endpoint:gt.optional(),scopes_supported:K(T()).optional(),response_types_supported:K(T()),response_modes_supported:K(T()).optional(),grant_types_supported:K(T()).optional(),acr_values_supported:K(T()).optional(),subject_types_supported:K(T()),id_token_signing_alg_values_supported:K(T()),id_token_encryption_alg_values_supported:K(T()).optional(),id_token_encryption_enc_values_supported:K(T()).optional(),userinfo_signing_alg_values_supported:K(T()).optional(),userinfo_encryption_alg_values_supported:K(T()).optional(),userinfo_encryption_enc_values_supported:K(T()).optional(),request_object_signing_alg_values_supported:K(T()).optional(),request_object_encryption_alg_values_supported:K(T()).optional(),request_object_encryption_enc_values_supported:K(T()).optional(),token_endpoint_auth_methods_supported:K(T()).optional(),token_endpoint_auth_signing_alg_values_supported:K(T()).optional(),display_values_supported:K(T()).optional(),claim_types_supported:K(T()).optional(),claims_supported:K(T()).optional(),service_documentation:T().optional(),claims_locales_supported:K(T()).optional(),ui_locales_supported:K(T()).optional(),claims_parameter_supported:Pe().optional(),request_parameter_supported:Pe().optional(),request_uri_parameter_supported:Pe().optional(),require_request_uri_registration:Pe().optional(),op_policy_uri:gt.optional(),op_tos_uri:gt.optional(),client_id_metadata_document_supported:Pe().optional()}),aD=D({...oD.shape,...bw.pick({code_challenge_methods_supported:!0}).shape}),lD=D({access_token:T(),id_token:T().optional(),token_type:T(),expires_in:mE().optional(),scope:T().optional(),refresh_token:T().optional()}).strip(),cD=D({error:T(),error_description:T().optional(),error_uri:T().optional()}),Dm=gt.optional().or(N("").transform(()=>{})),uD=D({redirect_uris:K(gt),token_endpoint_auth_method:T().optional(),grant_types:K(T()).optional(),response_types:K(T()).optional(),client_name:T().optional(),client_uri:gt.optional(),logo_uri:Dm,scope:T().optional(),contacts:K(T()).optional(),tos_uri:Dm,policy_uri:T().optional(),jwks_uri:gt.optional(),jwks:Ph().optional(),software_id:T().optional(),software_version:T().optional(),software_statement:T().optional()}).strip(),hD=D({client_id:T(),client_secret:T().optional(),client_id_issued_at:ye().optional(),client_secret_expires_at:ye().optional()}).strip(),dD=uD.merge(hD);D({error:T(),error_description:T().optional()}).strip();D({token:T(),token_type_hint:T().optional()}).strip();function fD(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function pD({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length=400&&t.status<500&&e!=="/"}async function ED(t,e,r,n){const s=new URL(t),i=(n==null?void 0:n.protocolVersion)??Cl;let o;if(n!=null&&n.metadataUrl)o=new URL(n.metadataUrl);else{const l=kD(e,s.pathname);o=new URL(l,(n==null?void 0:n.metadataServerUrl)??s),o.search=s.search}let a=await zm(o,i,r);if(!(n!=null&&n.metadataUrl)&&xD(a,s.pathname)){const l=new URL(`/.well-known/${e}`,s);a=await zm(l,i,r)}return a}function CD(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function kw(t,{fetchFn:e=fetch,protocolVersion:r=Cl}={}){var i;const n={"MCP-Protocol-Version":r,Accept:"application/json"},s=CD(t);for(const{url:o,type:a}of s){const l=await qf(o,n,e);if(l){if(!l.ok){if(await((i=l.body)==null?void 0:i.cancel()),l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`)}return a==="oauth"?bw.parse(await l.json()):aD.parse(await l.json())}}}async function PD(t,e){let r,n;try{r=await Sw(t,{resourceMetadataUrl:e==null?void 0:e.resourceMetadataUrl},e==null?void 0:e.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",t)));const s=await kw(n,{fetchFn:e==null?void 0:e.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:s,resourceMetadata:r}}async function TD(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:i,resource:o}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(mc))throw new Error(`Incompatible auth server: does not support response type ${mc}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(gc))throw new Error(`Incompatible auth server: does not support code challenge method ${gc}`)}else a=new URL("/authorize",t);const l=await sD(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",mc),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",gc),a.searchParams.set("redirect_uri",String(n)),i&&a.searchParams.set("state",i),s&&a.searchParams.set("scope",s),s!=null&&s.includes("offline_access")&&a.searchParams.append("prompt","consent"),o&&a.searchParams.set("resource",o.href),{authorizationUrl:a,codeVerifier:c}}function RD(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function xw(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:i,fetchFn:o}){const a=e!=null&&e.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),s)await s(l,r,a,e);else if(n){const u=(e==null?void 0:e.token_endpoint_auth_methods_supported)??[],h=yD(n,u);vD(h,n,l,r)}const c=await(o??fetch)(a,{method:"POST",headers:l,body:r});if(!c.ok)throw await $w(c);return lD.parse(await c.json())}async function AD(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:i,fetchFn:o}){const a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await xw(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:i,resource:s,fetchFn:o});return{refresh_token:n,...l}}async function MD(t,e,{metadata:r,resource:n,authorizationCode:s,fetchFn:i}={}){const o=t.clientMetadata.scope;let a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(o)),!a){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await t.codeVerifier();a=RD(s,c,t.redirectUrl)}const l=await t.clientInformation();return xw(e,{metadata:r,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:i})}async function ID(t,{metadata:e,clientMetadata:r,scope:n,fetchFn:s}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);const o=await(s??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!o.ok)throw await $w(o);return dD.parse(await o.json())}class wc extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}const Fm=10,OD=13,Fn=32;function _c(t){}function ND(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:e=_c,onError:r=_c,onRetry:n=_c,onComment:s,maxBufferSize:i}=t,o=[];let a=0,l=!0,c,u="",h=0,d,f=!1;function p(x){if(f)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,x.charCodeAt(0)===239&&x.charCodeAt(1)===187&&x.charCodeAt(2)===191&&(x=x.slice(3))),o.length===0){const z=v(x);z!==""&&(o.push(z),a=z.length),y();return}if(x.indexOf(` +`)===-1&&x.indexOf("\r")===-1){o.push(x),a+=x.length,y();return}o.push(x);const P=o.join("");o.length=0,a=0;const R=v(P);R!==""&&(o.push(R),a=R.length),y()}function y(){i!==void 0&&(a+u.length<=i||(f=!0,o.length=0,a=0,c=void 0,u="",h=0,d=void 0,r(new wc(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function v(x){let P=0;if(x.indexOf("\r")===-1){let R=x.indexOf(` +`,P);for(;R!==-1;){if(P===R){h>0&&e({id:c,event:d,data:u}),c=void 0,u="",h=0,d=void 0,P=R+1,R=x.indexOf(` +`,P);continue}const z=x.charCodeAt(P);if(qm(x,P,z)){const L=x.charCodeAt(P+5)===Fn?P+6:P+5,H=x.slice(L,R);if(h===0&&x.charCodeAt(R+1)===Fm){e({id:c,event:d,data:H}),c=void 0,u="",d=void 0,P=R+2,R=x.indexOf(` +`,P);continue}u=h===0?H:`${u} +${H}`,h++}else Bm(x,P,z)?d=x.slice(x.charCodeAt(P+6)===Fn?P+7:P+6,R)||void 0:m(x,P,R);P=R+1,R=x.indexOf(` +`,P)}return x.slice(P)}for(;P20?`${x.slice(0,20)}…`:x}"`,{type:"unknown-field",field:x,value:P,line:R}));break}}function $(){h>0&&e({id:c,event:d,data:u}),c=void 0,u="",h=0,d=void 0}function E(x={}){if(x.consume&&o.length>0){const P=o.join("");m(P,0,P.length)}l=!0,c=void 0,u="",h=0,d=void 0,o.length=0,a=0,f=!1}return{feed:p,reset:E}}function qm(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function Bm(t,e,r){return r===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}class jD extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:s}={}){let i;super({start(o){i=ND({onEvent:a=>{o.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&o.error(a)},onRetry:r,onComment:n,maxBufferSize:s})},transform(o){i.feed(o)}})}}const DD={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class _s extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class LD{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch,this._fetchWithInit=Xj(r==null?void 0:r.fetch,r==null?void 0:r.requestInit),this._sessionId=r==null?void 0:r.sessionId,this._reconnectionOptions=(r==null?void 0:r.reconnectionOptions)??DD}async _authThenStart(){var r;if(!this._authProvider)throw new ws("No auth provider");let e;try{e=await Zo(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(r=this.onerror)==null||r.call(this,n),n}if(e!=="AUTHORIZED")throw new ws;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var n;const e={};if(this._authProvider){const s=await this._authProvider.tokens();s&&(e.Authorization=`Bearer ${s.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const r=yu((n=this._requestInit)==null?void 0:n.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){var n,s,i;const{resumptionToken:r}=e;try{const o=await this._commonHeaders();o.set("Accept","text/event-stream"),r&&o.set("last-event-id",r);const a=await(this._fetch??fetch)(this._url,{method:"GET",headers:o,signal:(n=this._abortController)==null?void 0:n.signal});if(!a.ok){if(await((s=a.body)==null?void 0:s.cancel()),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new _s(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(o){throw(i=this.onerror)==null||i.call(this,o),o}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,s=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),s)}_scheduleReconnection(e,r=0){var i;const n=this._reconnectionOptions.maxRetries;if(r>=n){(i=this.onerror)==null||i.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var a;(a=this.onerror)==null||a.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,n){if(!e)return;const{onresumptiontoken:s,replayMessageId:i}=r;let o,a=!1,l=!1;(async()=>{var u,h,d,f;try{const p=e.pipeThrough(new TextDecoderStream).pipeThrough(new jD({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){const{value:m,done:_}=await p.read();if(_)break;if(m.id&&(o=m.id,a=!0,s==null||s(m.id)),!!m.data&&(!m.event||m.event==="message"))try{const $=ma.parse(JSON.parse(m.data));Si($)&&(l=!0,i!==void 0&&($.id=i)),(u=this.onmessage)==null||u.call(this,$)}catch($){(h=this.onerror)==null||h.call(this,$)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:o,onresumptiontoken:s,replayMessageId:i},0)}catch(p){if((d=this.onerror)==null||d.call(this,new Error(`SSE stream disconnected: ${p}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:s,replayMessageId:i},0)}catch(m){(f=this.onerror)==null||f.call(this,new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new ws("No auth provider");if(await Zo(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ws("Failed to authorize")}async close(){var e,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(e,r){var n,s,i,o,a,l;try{const{resumptionToken:c,onresumptiontoken:u}=r||{};if(c){this._startOrAuthSse({resumptionToken:c,replayMessageId:Yc(e)?e.id:void 0}).catch($=>{var E;return(E=this.onerror)==null?void 0:E.call(this,$)});return}const h=await this._commonHeaders();h.set("content-type","application/json"),h.set("accept","application/json, text/event-stream");const d={...this._requestInit,method:"POST",headers:h,body:JSON.stringify(e),signal:(n=this._abortController)==null?void 0:n.signal},f=await(this._fetch??fetch)(this._url,d),p=f.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!f.ok){const $=await f.text().catch(()=>null);if(f.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new _s(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:E,scope:x}=Lm(f);if(this._resourceMetadataUrl=E,this._scope=x,await Zo(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ws;return this._hasCompletedAuthFlow=!0,this.send(e)}if(f.status===403&&this._authProvider){const{resourceMetadataUrl:E,scope:x,error:P}=Lm(f);if(P==="insufficient_scope"){const R=f.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===R)throw new _s(403,"Server returned 403 after trying upscoping");if(x&&(this._scope=x),E&&(this._resourceMetadataUrl=E),this._lastUpscopingHeader=R??void 0,await Zo(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new ws;return this.send(e)}}throw new _s(f.status,`Error POSTing to endpoint: ${$}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,f.status===202){await((s=f.body)==null?void 0:s.cancel()),ME(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch($=>{var E;return(E=this.onerror)==null?void 0:E.call(this,$)});return}const v=(Array.isArray(e)?e:[e]).filter($=>"method"in $&&"id"in $&&$.id!==void 0).length>0,m=f.headers.get("content-type"),_=Qj(m);if(v)if(_==="text/event-stream")this._handleSseStream(f.body,{onresumptiontoken:u},!1);else if(_==="application/json"){const $=await f.json(),E=Array.isArray($)?$.map(x=>ma.parse(x)):[ma.parse($)];for(const x of E)(i=this.onmessage)==null||i.call(this,x)}else throw await((o=f.body)==null?void 0:o.cancel()),new _s(-1,`Unexpected content type: ${m}`);else await((a=f.body)==null?void 0:a.cancel())}catch(c){throw(l=this.onerror)==null||l.call(this,c),c}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n;if(this._sessionId)try{const s=await this._commonHeaders(),i={...this._requestInit,method:"DELETE",headers:s,signal:(e=this._abortController)==null?void 0:e.signal},o=await(this._fetch??fetch)(this._url,i);if(await((r=o.body)==null?void 0:r.cancel()),!o.ok&&o.status!==405)throw new _s(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(s){throw(n=this.onerror)==null||n.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r==null?void 0:r.onresumptiontoken})}}const zD="https://mcp.excalidraw.com/mcp",FD="mcp.excalidraw.com",qD="/api/v1/chat/mcp-apps/excalidraw",Ew="ui://excalidraw/mcp-app.html",BD=["read_me","create_view"],Cw=new Set(["export_to_excalidraw","save_checkpoint","read_checkpoint"]),VD=256*1024,HD=1024*1024,UD=1024*1024,WD=240,KD=720,ZD=525;function GD(t){return!Number.isFinite(t)||t<=0?ZD:Math.max(WD,Math.min(KD,Math.round(t*3/4)))}const JD={excalidraw:{id:"excalidraw",endpoint:zD,hostname:FD,resourceUri:Ew,modelTools:BD,appTools:Cw}};function YD(t){return JD[t]}function QD(){return new URL(st(qD),window.location.origin)}class XD{constructor(){pe(this,"client",new Vj({name:"pwc-chat-mcp-app-host",version:"1"}));pe(this,"transport",new LD(QD(),{requestInit:{credentials:"include"}}));pe(this,"connected");pe(this,"bytes",0);pe(this,"closed",!1)}connect(){return this.closed?Promise.reject(new Error("App host client is closed")):(this.connected||(this.connected=this.client.connect(this.transport).then(()=>{},e=>{throw this.connected=void 0,this.retire(),e})),this.connected)}async readResource(e){if(e!==Ew)throw new Error("Unapproved App resource");await this.connect();const n=(await this.client.readResource({uri:e})).contents[0];if(!n||!("text"in n)||typeof n.text!="string"||n.mimeType!=="text/html;profile=mcp-app")throw new Error("Incompatible App resource");this.consume(n.text,UD);const s=await nL(n.text);return{text:n.text,digest:s}}async callTool(e,r){if(!Cw.has(e))throw new Error("Unapproved App tool");const n=JSON.stringify(r);this.consume(n);try{await this.connect();const s=await this.client.callTool({name:e,arguments:r});return this.consume(JSON.stringify(s)),s}catch(s){throw this.retire(),s}}close(){this.closed=!0,this.connected=void 0,this.transport.close()}retire(){this.close(),$n===this&&($n=void 0)}consume(e,r=VD){const n=new TextEncoder().encode(e).byteLength;if(n>r||this.bytes+n>HD)throw new Error("App request exceeds host limit");this.bytes+=n}}let $n;function eL(){return $n??($n=new XD),$n}function tL(){$n==null||$n.close(),$n=void 0}function rL(t){tL()}async function nL(t){const e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(r)].map(n=>n.toString(16).padStart(2,"0")).join("")}function sL(t,e){let r=!1,n=0;const s=()=>{r||!t.contentWindow||(r=!0,e())};t.addEventListener("load",s);const i=window.requestAnimationFrame(()=>{n=window.requestAnimationFrame(s)});return()=>{r=!0,t.removeEventListener("load",s),window.cancelAnimationFrame(i),window.cancelAnimationFrame(n)}}const iL=({block:t})=>{const e=U.useRef(null),r=U.useRef(null),n=U.useRef(!1),s=U.useRef(t),i=U.useRef(!1);s.current=t;const[o,a]=U.useState(),[l,c]=U.useState("loading"),[u,h]=U.useState(t.height),[d,f]=U.useState(!1),[p,y]=U.useState(0),v=U.useRef(null),m=t.input.elements,_=!!t.permissions.clipboardWrite;i.current=d;const $=U.useCallback(()=>{f(!1),document.fullscreenElement&&document.exitFullscreen()},[]),E=U.useCallback(()=>{var R,z;if(d){$();return}f(!0),(z=(R=v.current)==null?void 0:R.requestFullscreen)==null||z.call(R).catch(()=>{})},[$,d]),x=U.useCallback(()=>{rL(),a(void 0),c("loading"),y(R=>R+1)},[]);U.useEffect(()=>{const R=v.current;if(!R)return;const z=()=>{i.current||h(GD(R.clientWidth))};z();const L=new ResizeObserver(z);return L.observe(R),()=>L.disconnect()},[]),U.useEffect(()=>{if(!d)return;const R=v.current,z=H=>{H.key==="Escape"&&(document.fullscreenElement||$())},L=()=>{document.fullscreenElement||f(!1)};return window.addEventListener("keydown",z),document.addEventListener("fullscreenchange",L),()=>{window.removeEventListener("keydown",z),document.removeEventListener("fullscreenchange",L),document.fullscreenElement===R&&document.exitFullscreen()}},[$,d]),U.useEffect(()=>{YD(t.provider);{c("unavailable");return}},[p,t.provider,t.resource_uri]),U.useEffect(()=>{if(!o||l!=="ready")return;const R=e.current;if(!R)return;let z=null;const L=[],H=sL(R,()=>{R.contentWindow&&(z=new uP(null,{name:"Papers with Code",version:"1"},{serverTools:{},openLinks:{},logging:{},..._?{clipboard:{write:{}}}:{}},{hostContext:{theme:document.documentElement.dataset.theme==="dark"?"dark":"light",displayMode:d?"fullscreen":"inline"}}),z.oncalltool=async({name:O,arguments:B})=>{if(s.current.public_fork&&O!=="export_to_excalidraw")throw new Error("Shared diagrams cannot mutate owner state");return eL().callTool(O,B??{})},z.onopenlink=async({url:O})=>{const B=new URL(O);if(B.protocol!=="https:"||B.hostname!=="excalidraw.com")throw new Error("External navigation denied");if(!window.confirm("This export opens Excalidraw and uploads the diagram to its service. Continue?"))throw new Error("Export cancelled");return window.open(B.href,"_blank","noopener,noreferrer"),{}},z.onsizechange=()=>{},z.oninitialized=()=>{n.current=!0;try{const O=JSON.parse(m),B={arguments:{elements:Array.isArray(O)?wP(O):O}};for(const Z of[0,50,200,750])L.push(window.setTimeout(()=>{r.current===z&&z.sendToolInput(B)},Z));z.sendToolResult(s.current.result)}catch{c("error")}},r.current=z,z.connect(new lP(R.contentWindow??void 0,R.contentWindow)).catch(()=>c("error")))});return()=>{H(),L.forEach(O=>window.clearTimeout(O)),n.current=!1,z==null||z.teardownResource({}).catch(()=>{}),r.current===z&&(r.current=null)}},[o,l,d,m,_,p]),U.useEffect(()=>{var R;l!=="ready"||!n.current||(R=r.current)==null||R.sendToolResult(t.result).catch(()=>{})},[t.result,l]);const P=l==="unavailable"||l==="incompatible"||l==="error";return b.jsxs("section",{ref:v,className:`chat-mcp-app${d?" chat-mcp-app-fullscreen":""}`,"aria-label":"Interactive Excalidraw diagram",children:[b.jsx("header",{children:b.jsx("button",{type:"button",onClick:E,children:d?"Exit fullscreen":"Fullscreen"})}),l==="loading"&&b.jsx("div",{className:"chat-mcp-loading",role:"status",children:"Loading interactive diagram…"}),P&&b.jsxs("div",{className:"chat-mcp-error",children:["Interactive diagram unavailable. The cited text answer is still available.",b.jsx("button",{type:"button",onClick:x,children:"Retry diagram"})]}),o&&l==="ready"&&b.jsx("iframe",{ref:e,title:"Interactive Excalidraw diagram",sandbox:"allow-scripts",allow:_?"clipboard-write":void 0,srcDoc:o,style:{height:u}},p)]})};let Ru=[],Pw=[];(()=>{let t="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,r=0;e>1;if(t=Pw[n])e=n+1;else return!0;if(e==r)return!1}}function Vm(t){return t>=127462&&t<=127487}const Hm=8205;function aL(t,e,r=!0,n=!0){return(r?Tw:lL)(t,e,n)}function Tw(t,e,r){if(e==t.length)return e;e&&Rw(t.charCodeAt(e))&&Aw(t.charCodeAt(e-1))&&e--;let n=bc(t,e);for(e+=Um(n);e=0&&Vm(bc(t,o));)i++,o-=2;if(i%2==0)break;e+=2}else break}return e}function lL(t,e,r){for(;e>1;){let n=Tw(t,e-2,r);if(n=56320&&t<57344}function Aw(t){return t>=55296&&t<56320}function Um(t){return t<65536?1:2}let Ie=class Mw{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,r,n){[e,r]=Ws(this,e,r);let s=[];return this.decompose(0,e,s,2),n.length&&n.decompose(0,n.length,s,3),this.decompose(r,this.length,s,1),Ar.from(s,this.length-(r-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,r=this.length){[e,r]=Ws(this,e,r);let n=[];return this.decompose(e,r,n,0),Ar.from(n,r-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let r=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),s=new qi(this),i=new qi(e);for(let o=r,a=r;;){if(s.next(o),i.next(o),o=0,s.lineBreak!=i.lineBreak||s.done!=i.done||s.value!=i.value)return!1;if(a+=s.value.length,s.done||a>=n)return!0}}iter(e=1){return new qi(this,e)}iterRange(e,r=this.length){return new Iw(this,e,r)}iterLines(e,r){let n;if(e==null)n=this.iter();else{r==null&&(r=this.lines+1);let s=this.line(e).from;n=this.iterRange(s,Math.max(s,r==this.lines+1?this.length:r<=1?0:this.line(r-1).to))}return new Ow(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?Mw.empty:e.length<=32?new tt(e):Ar.from(tt.split(e,[]))}};class tt extends Ie{constructor(e,r=cL(e)){super(),this.text=e,this.length=r}get lines(){return this.text.length}get children(){return null}lineInner(e,r,n,s){for(let i=0;;i++){let o=this.text[i],a=s+o.length;if((r?n:a)>=e)return new uL(s,a,n,o);s=a+1,n++}}decompose(e,r,n,s){let i=e<=0&&r>=this.length?this:new tt(Wm(this.text,e,r),Math.min(r,this.length)-Math.max(0,e));if(s&1){let o=n.pop(),a=Ea(i.text,o.text.slice(),0,i.length);if(a.length<=32)n.push(new tt(a,o.length+i.length));else{let l=a.length>>1;n.push(new tt(a.slice(0,l)),new tt(a.slice(l)))}}else n.push(i)}replace(e,r,n){if(!(n instanceof tt))return super.replace(e,r,n);[e,r]=Ws(this,e,r);let s=Ea(this.text,Ea(n.text,Wm(this.text,0,e)),r),i=this.length+n.length-(r-e);return s.length<=32?new tt(s,i):Ar.from(tt.split(s,[]),i)}sliceString(e,r=this.length,n=` +`){[e,r]=Ws(this,e,r);let s="";for(let i=0,o=0;i<=r&&oe&&o&&(s+=n),ei&&(s+=a.slice(Math.max(0,e-i),r-i)),i=l+1}return s}flatten(e){for(let r of this.text)e.push(r)}scanIdentical(){return 0}static split(e,r){let n=[],s=-1;for(let i of e)n.push(i),s+=i.length+1,n.length==32&&(r.push(new tt(n,s)),n=[],s=-1);return s>-1&&r.push(new tt(n,s)),r}}class Ar extends Ie{constructor(e,r){super(),this.children=e,this.length=r,this.lines=0;for(let n of e)this.lines+=n.lines}lineInner(e,r,n,s){for(let i=0;;i++){let o=this.children[i],a=s+o.length,l=n+o.lines-1;if((r?l:a)>=e)return o.lineInner(e,r,n,s);s=a+1,n=l+1}}decompose(e,r,n,s){for(let i=0,o=0;o<=r&&i=o){let c=s&((o<=e?1:0)|(l>=r?2:0));o>=e&&l<=r&&!c?n.push(a):a.decompose(e-o,r-o,n,c)}o=l+1}}replace(e,r,n){if([e,r]=Ws(this,e,r),n.lines=i&&r<=a){let l=o.replace(e-i,r-i,n),c=this.lines-o.lines+l.lines;if(l.lines>4&&l.lines>c>>6){let u=this.children.slice();return u[s]=l,new Ar(u,this.length-(r-e)+n.length)}return super.replace(i,a,l)}i=a+1}return super.replace(e,r,n)}sliceString(e,r=this.length,n=` +`){[e,r]=Ws(this,e,r);let s="";for(let i=0,o=0;ie&&i&&(s+=n),eo&&(s+=a.sliceString(e-o,r-o,n)),o=l+1}return s}flatten(e){for(let r of this.children)r.flatten(e)}scanIdentical(e,r){if(!(e instanceof Ar))return 0;let n=0,[s,i,o,a]=r>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=r,i+=r){if(s==o||i==a)return n;let l=this.children[s],c=e.children[i];if(l!=c)return n+l.scanIdentical(c,r);n+=l.length+1}}static from(e,r=e.reduce((n,s)=>n+s.length+1,-1)){let n=0;for(let f of e)n+=f.lines;if(n<32){let f=[];for(let p of e)p.flatten(f);return new tt(f,r)}let s=Math.max(32,n>>5),i=s<<1,o=s>>1,a=[],l=0,c=-1,u=[];function h(f){let p;if(f.lines>i&&f instanceof Ar)for(let y of f.children)h(y);else f.lines>o&&(l>o||!l)?(d(),a.push(f)):f instanceof tt&&l&&(p=u[u.length-1])instanceof tt&&f.lines+p.lines<=32?(l+=f.lines,c+=f.length+1,u[u.length-1]=new tt(p.text.concat(f.text),p.length+1+f.length)):(l+f.lines>s&&d(),l+=f.lines,c+=f.length+1,u.push(f))}function d(){l!=0&&(a.push(u.length==1?u[0]:Ar.from(u,c)),c=-1,l=u.length=0)}for(let f of e)h(f);return d(),a.length==1?a[0]:new Ar(a,r)}}Ie.empty=new tt([""],0);function cL(t){let e=-1;for(let r of t)e+=r.length+1;return e}function Ea(t,e,r=0,n=1e9){for(let s=0,i=0,o=!0;i=r&&(l>n&&(a=a.slice(0,n-s)),s0?1:(e instanceof tt?e.text.length:e.children.length)<<1]}nextInner(e,r){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,s=this.nodes[n],i=this.offsets[n],o=i>>1,a=s instanceof tt?s.text.length:s.children.length;if(o==(r>0?a:0)){if(n==0)return this.done=!0,this.value="",this;r>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((i&1)==(r>0?0:1)){if(this.offsets[n]+=r,e==0)return this.lineBreak=!0,this.value=` +`,this;e--}else if(s instanceof tt){let l=s.text[o+(r<0?-1:0)];if(this.offsets[n]+=r,l.length>Math.max(0,e))return this.value=e==0?l:r>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=s.children[o+(r<0?-1:0)];e>l.length?(e-=l.length,this.offsets[n]+=r):(r<0&&this.offsets[n]--,this.nodes.push(l),this.offsets.push(r>0?1:(l instanceof tt?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Iw{constructor(e,r,n){this.value="",this.done=!1,this.cursor=new qi(e,r>n?-1:1),this.pos=r>n?e.length:0,this.from=Math.min(r,n),this.to=Math.max(r,n)}nextInner(e,r){if(r<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,r<0?this.pos-this.to:this.from-this.pos);let n=r<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*r,this.value=s.length<=n?s:r<0?s.slice(s.length-n):s.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Ow{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:r,lineBreak:n,value:s}=this.inner.next(e);return r&&this.afterBreak?(this.value="",this.afterBreak=!1):r?(this.done=!0,this.value=""):n?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(Ie.prototype[Symbol.iterator]=function(){return this.iter()},qi.prototype[Symbol.iterator]=Iw.prototype[Symbol.iterator]=Ow.prototype[Symbol.iterator]=function(){return this});class uL{constructor(e,r,n,s){this.from=e,this.to=r,this.number=n,this.text=s}get length(){return this.to-this.from}}function Ws(t,e,r){return e=Math.max(0,Math.min(t.length,e)),[e,Math.max(e,Math.min(t.length,r))]}function ht(t,e,r=!0,n=!0){return aL(t,e,r,n)}function hL(t){return t>=56320&&t<57344}function dL(t){return t>=55296&&t<56320}function Nw(t,e){let r=t.charCodeAt(e);if(!dL(r)||e+1==t.length)return r;let n=t.charCodeAt(e+1);return hL(n)?(r-55296<<10)+(n-56320)+65536:r}function fL(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode((t>>10)+55296,(t&1023)+56320))}function jw(t){return t<65536?1:2}const Au=/\r\n?|\n/;var Wt=function(t){return t[t.Simple=0]="Simple",t[t.TrackDel=1]="TrackDel",t[t.TrackBefore=2]="TrackBefore",t[t.TrackAfter=3]="TrackAfter",t}(Wt||(Wt={}));class Fr{constructor(e){this.sections=e}get length(){let e=0;for(let r=0;re)return i+(e-s);i+=a}else{if(n!=Wt.Simple&&c>=e&&(n==Wt.TrackDel&&se||n==Wt.TrackBefore&&se))return null;if(c>e||c==e&&r<0&&!a)return e==s||r<0?i:i+l;i+=l}s=c}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return i}touchesRange(e,r=e){for(let n=0,s=0;n=0&&s<=r&&a>=e)return sr?"cover":!0;s=a}return!1}toString(){let e="";for(let r=0;r=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(r=>typeof r!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Fr(e)}static create(e){return new Fr(e)}}class at extends Fr{constructor(e,r){super(e),this.inserted=r}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Mu(this,(r,n,s,i,o)=>e=e.replace(s,s+(n-r),o),!1),e}mapDesc(e,r=!1){return Iu(this,e,r,!0)}invert(e){let r=this.sections.slice(),n=[];for(let s=0,i=0;s=0){r[s]=a,r[s+1]=o;let l=s>>1;for(;n.length0&&Sn(n,r,i.text),i.forward(u),a+=u}let c=e[o++];for(;a>1].toJSON()))}return e}static of(e,r,n){let s=[],i=[],o=0,a=null;function l(u=!1){if(!u&&!s.length)return;od||h<0||d>r)throw new RangeError(`Invalid change range ${h} to ${d} (in doc of length ${r})`);let p=f?typeof f=="string"?Ie.of(f.split(n||Au)):f:Ie.empty,y=p.length;if(h==d&&y==0)return;ho&&Ct(s,h-o,-1),Ct(s,d-h,y),Sn(i,s,p),o=d}}return c(e),l(!a),a}static empty(e){return new at(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let r=[],n=[];for(let s=0;sa&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(i.length==1)r.push(i[0],0);else{for(;n.length=0&&r<=0&&r==t[s+1]?t[s]+=e:s>=0&&e==0&&t[s]==0?t[s+1]+=r:n?(t[s]+=e,t[s+1]+=r):t.push(e,r)}function Sn(t,e,r){if(r.length==0)return;let n=e.length-2>>1;if(n>1])),!(r||o==t.sections.length||t.sections[o+1]<0);)a=t.sections[o++],l=t.sections[o++];e(s,c,i,u,h),s=c,i=u}}}function Iu(t,e,r,n=!1){let s=[],i=n?[]:null,o=new Xi(t),a=new Xi(e);for(let l=-1;;){if(o.done&&a.len||a.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&a.ins==-1){let c=Math.min(o.len,a.len);Ct(s,c,-1),o.forward(c),a.forward(c)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len=0&&l=0){let c=0,u=o.len;for(;u;)if(a.ins==-1){let h=Math.min(u,a.len);c+=h,u-=h,a.forward(h)}else if(a.ins==0&&a.lenl||o.ins>=0&&o.len>l)&&(a||n.length>c),i.forward2(l),o.forward(l)}}}}class Xi{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return r>=e.length?Ie.empty:e[r]}textBit(e){let{inserted:r}=this.set,n=this.i-2>>1;return n>=r.length&&!e?Ie.empty:r[n].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class gn{constructor(e,r,n,s){this.from=e,this.to=r,this.flags=n,this.goalColumn=s}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,r=-1){let n,s;return this.empty?n=s=e.mapPos(this.from,r):(n=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),n==this.from&&s==this.to?this:new gn(n,s,this.flags,this.goalColumn)}extend(e,r=e,n=0){if(e<=this.anchor&&r>=this.anchor)return W.range(e,r,void 0,void 0,n);let s=Math.abs(e-this.anchor)>Math.abs(r-this.anchor)?e:r;return W.range(this.anchor,s,void 0,void 0,n)}eq(e,r=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!r||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return W.range(e.anchor,e.head)}static create(e,r,n,s){return new gn(e,r,n,s)}}class W{constructor(e,r){this.ranges=e,this.mainIndex=r}map(e,r=-1){return e.empty?this:W.create(this.ranges.map(n=>n.map(e,r)),this.mainIndex)}eq(e,r=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let n=0;ne.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new W(e.ranges.map(r=>gn.fromJSON(r)),e.main)}static single(e,r=e){return new W([W.range(e,r)],0)}static create(e,r=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let n=0,s=0;ss.from-i.from),r=e.indexOf(n);for(let s=1;si.head?W.range(l,a):W.range(a,l))}}return new W(e,r)}}function Lw(t,e){for(let r of t.ranges)if(r.to>e)throw new RangeError("Selection points outside of document")}let Bf=0;class ie{constructor(e,r,n,s,i){this.combine=e,this.compareInput=r,this.compare=n,this.isStatic=s,this.id=Bf++,this.default=e([]),this.extensions=typeof i=="function"?i(this):i}get reader(){return this}static define(e={}){return new ie(e.combine||(r=>r),e.compareInput||((r,n)=>r===n),e.compare||(e.combine?(r,n)=>r===n:Vf),!!e.static,e.enables)}of(e){return new Ca([],this,0,e)}compute(e,r){if(this.isStatic)throw new Error("Can't compute a static facet");return new Ca(e,this,1,r)}computeN(e,r){if(this.isStatic)throw new Error("Can't compute a static facet");return new Ca(e,this,2,r)}from(e,r){return r||(r=n=>n),this.compute([e],n=>r(n.field(e)))}}function Vf(t,e){return t==e||t.length==e.length&&t.every((r,n)=>r===e[n])}class Ca{constructor(e,r,n,s){this.dependencies=e,this.facet=r,this.type=n,this.value=s,this.id=Bf++}dynamicSlot(e){var r;let n=this.value,s=this.facet.compareInput,i=this.id,o=e[i]>>1,a=this.type==2,l=!1,c=!1,u=[];for(let h of this.dependencies)h=="doc"?l=!0:h=="selection"?c=!0:((r=e[h.id])!==null&&r!==void 0?r:1)&1||u.push(e[h.id]);return{create(h){return h.values[o]=n(h),1},update(h,d){if(l&&d.docChanged||c&&(d.docChanged||d.selection)||Ou(h,u)){let f=n(h);if(a?!Km(f,h.values[o],s):!s(f,h.values[o]))return h.values[o]=f,1}return 0},reconfigure:(h,d)=>{let f,p=d.config.address[i];if(p!=null){let y=el(d,p);if(this.dependencies.every(v=>v instanceof ie?d.facet(v)===h.facet(v):v instanceof Vr?d.field(v,!1)==h.field(v,!1):!0)||(a?Km(f=n(h),y,s):s(f=n(h),y)))return h.values[o]=y,0}else f=n(h);return h.values[o]=f,1}}}get extension(){return this}}function Km(t,e,r){if(t.length!=e.length)return!1;for(let n=0;nt[l.id]),s=r.map(l=>l.type),i=n.filter(l=>!(l&1)),o=t[e.id]>>1;function a(l){let c=[];for(let u=0;un===s),e);return e.provide&&(r.provides=e.provide(r)),r}create(e){let r=e.facet(Go).find(n=>n.field==this);return((r==null?void 0:r.create)||this.createF)(e)}slot(e){let r=e[this.id]>>1;return{create:n=>(n.values[r]=this.create(n),1),update:(n,s)=>{let i=n.values[r],o=this.updateF(i,s);return this.compareF(i,o)?0:(n.values[r]=o,1)},reconfigure:(n,s)=>{let i=n.facet(Go),o=s.facet(Go),a;return(a=i.find(l=>l.field==this))&&a!=o.find(l=>l.field==this)?(n.values[r]=a.create(n),1):s.config.address[this.id]!=null?(n.values[r]=s.field(this),0):(n.values[r]=this.create(n),1)}}}init(e){return[this,Go.of({field:this,create:e})]}get extension(){return this}}const Yn={lowest:4,low:3,default:2,high:1,highest:0};function vi(t){return e=>new zw(e,t)}const Vl={highest:vi(Yn.highest),high:vi(Yn.high),default:vi(Yn.default),low:vi(Yn.low),lowest:vi(Yn.lowest)};class zw{constructor(e,r){this.inner=e,this.prec=r}get extension(){return this}}class Eo{of(e){return new Nu(this,e)}reconfigure(e){return Eo.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Nu{constructor(e,r){this.compartment=e,this.inner=r}get extension(){return this}}class Xa{constructor(e,r,n,s,i,o){for(this.base=e,this.compartments=r,this.dynamicSlots=n,this.address=s,this.staticValues=i,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,r,n){let s=[],i=Object.create(null),o=new Map;for(let d of mL(e,r,o))d instanceof Vr?s.push(d):(i[d.facet.id]||(i[d.facet.id]=[])).push(d);let a=Object.create(null),l=[],c=[];for(let d of s)a[d.id]=c.length<<1,c.push(f=>d.slot(f));let u=n==null?void 0:n.config.facets;for(let d in i){let f=i[d],p=f[0].facet,y=u&&u[d]||[];if(f.every(v=>v.type==0))if(a[p.id]=l.length<<1|1,Vf(y,f))l.push(n.facet(p));else{let v=p.combine(f.map(m=>m.value));l.push(n&&p.compare(v,n.facet(p))?n.facet(p):v)}else{for(let v of f)v.type==0?(a[v.id]=l.length<<1|1,l.push(v.value)):(a[v.id]=c.length<<1,c.push(m=>v.dynamicSlot(m)));a[p.id]=c.length<<1,c.push(v=>pL(v,p,f))}}let h=c.map(d=>d(a));return new Xa(e,o,h,a,l,i)}}function mL(t,e,r){let n=[[],[],[],[],[]],s=new Map;function i(o,a){let l=s.get(o);if(l!=null){if(l<=a)return;let c=n[l].indexOf(o);c>-1&&n[l].splice(c,1),o instanceof Nu&&r.delete(o.compartment)}if(s.set(o,a),Array.isArray(o))for(let c of o)i(c,a);else if(o instanceof Nu){if(r.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let c=e.get(o.compartment)||o.inner;r.set(o.compartment,c),i(c,a)}else if(o instanceof zw)i(o.inner,o.prec);else if(o instanceof Vr)n[a].push(o),o.provides&&i(o.provides,a);else if(o instanceof Ca)n[a].push(o),o.facet.extensions&&i(o.facet.extensions,Yn.default);else{let c=o.extension;if(!c)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(c==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);i(c,a)}}return i(t,Yn.default),n.reduce((o,a)=>o.concat(a))}function Bi(t,e){if(e&1)return 2;let r=e>>1,n=t.status[r];if(n==4)throw new Error("Cyclic dependency between fields and/or facets");if(n&2)return n;t.status[r]=4;let s=t.computeSlot(t,t.config.dynamicSlots[r]);return t.status[r]=2|s}function el(t,e){return e&1?t.config.staticValues[e>>1]:t.values[e>>1]}const Fw=ie.define(),ju=ie.define({combine:t=>t.some(e=>e),static:!0}),qw=ie.define({combine:t=>t.length?t[0]:void 0,static:!0}),Bw=ie.define(),Vw=ie.define(),Hw=ie.define(),Uw=ie.define({combine:t=>t.length?t[0]:!1});class On{constructor(e,r){this.type=e,this.value=r}static define(){return new gL}}class gL{of(e){return new On(this,e)}}class yL{constructor(e){this.map=e}of(e){return new Le(this,e)}}class Le{constructor(e,r){this.type=e,this.value=r}map(e){let r=this.type.map(this.value,e);return r===void 0?void 0:r==this.value?this:new Le(this.type,r)}is(e){return this.type==e}static define(e={}){return new yL(e.map||(r=>r))}static mapEffects(e,r){if(!e.length)return e;let n=[];for(let s of e){let i=s.map(r);i&&n.push(i)}return n}}Le.reconfigure=Le.define();Le.appendConfig=Le.define();class ct{constructor(e,r,n,s,i,o){this.startState=e,this.changes=r,this.selection=n,this.effects=s,this.annotations=i,this.scrollIntoView=o,this._doc=null,this._state=null,n&&Lw(n,r.newLength),i.some(a=>a.type==ct.time)||(this.annotations=i.concat(ct.time.of(Date.now())))}static create(e,r,n,s,i,o){return new ct(e,r,n,s,i,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let r of this.annotations)if(r.type==e)return r.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let r=this.annotation(ct.userEvent);return!!(r&&(r==e||r.length>e.length&&r.slice(0,e.length)==e&&r[e.length]=="."))}}ct.time=On.define();ct.userEvent=On.define();ct.addToHistory=On.define();ct.remote=On.define();function vL(t,e){let r=[];for(let n=0,s=0;;){let i,o;if(n=t[n]))i=t[n++],o=t[n++];else if(s=0;s--){let i=n[s](t);i instanceof ct?t=i:Array.isArray(i)&&i.length==1&&i[0]instanceof ct?t=i[0]:t=Kw(e,Ns(i),!1)}return t}function _L(t){let e=t.startState,r=e.facet(Hw),n=t;for(let s=r.length-1;s>=0;s--){let i=r[s](t);i&&Object.keys(i).length&&(n=Ww(n,Du(e,i,t.changes.newLength),!0))}return n==t?t:ct.create(e,t.changes,t.selection,n.effects,n.annotations,n.scrollIntoView)}const bL=[];function Ns(t){return t==null?bL:Array.isArray(t)?t:[t]}var nt=function(t){return t[t.Word=0]="Word",t[t.Space=1]="Space",t[t.Other=2]="Other",t}(nt||(nt={}));const $L=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Lu;try{Lu=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function SL(t){if(Lu)return Lu.test(t);for(let e=0;e"€"&&(r.toUpperCase()!=r.toLowerCase()||$L.test(r)))return!0}return!1}function kL(t){return e=>{if(!/\S/.test(e))return nt.Space;if(SL(e))return nt.Word;for(let r=0;r-1)return nt.Word;return nt.Other}}class Me{constructor(e,r,n,s,i,o){this.config=e,this.doc=r,this.selection=n,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=i,o&&(o._state=this);for(let a=0;as.set(c,l)),r=null),s.set(a.value.compartment,a.value.extension)):a.is(Le.reconfigure)?(r=null,n=a.value):a.is(Le.appendConfig)&&(r=null,n=Ns(n).concat(a.value));let i;r?i=e.startState.values.slice():(r=Xa.resolve(n,s,this),i=new Me(r,this.doc,this.selection,r.dynamicSlots.map(()=>null),(l,c)=>c.reconfigure(l,this),null).values);let o=e.startState.facet(ju)?e.newSelection:e.newSelection.asSingle();new Me(r,e.newDoc,o,i,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:e},range:W.cursor(r.from+e.length)}))}changeByRange(e){let r=this.selection,n=e(r.ranges[0]),s=this.changes(n.changes),i=[n.range],o=Ns(n.effects);for(let a=1;ao.spec.fromJSON(a,l)))}}return Me.create({doc:e.doc,selection:W.fromJSON(e.selection),extensions:r.extensions?s.concat([r.extensions]):s})}static create(e={}){let r=Xa.resolve(e.extensions||[],new Map),n=e.doc instanceof Ie?e.doc:Ie.of((e.doc||"").split(r.staticFacet(Me.lineSeparator)||Au)),s=e.selection?e.selection instanceof W?e.selection:W.single(e.selection.anchor,e.selection.head):W.single(0);return Lw(s,n.length),r.staticFacet(ju)||(s=s.asSingle()),new Me(r,n,s,r.dynamicSlots.map(()=>null),(i,o)=>o.create(i),null)}get tabSize(){return this.facet(Me.tabSize)}get lineBreak(){return this.facet(Me.lineSeparator)||` +`}get readOnly(){return this.facet(Uw)}phrase(e,...r){for(let n of this.facet(Me.phrases))if(Object.prototype.hasOwnProperty.call(n,e)){e=n[e];break}return r.length&&(e=e.replace(/\$(\$|\d*)/g,(n,s)=>{if(s=="$")return"$";let i=+(s||1);return!i||i>r.length?n:r[i-1]})),e}languageDataAt(e,r,n=-1){let s=[];for(let i of this.facet(Fw))for(let o of i(this,r,n))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){let r=this.languageDataAt("wordChars",e);return kL(r.length?r[0]:"")}wordAt(e){let{text:r,from:n,length:s}=this.doc.lineAt(e),i=this.charCategorizer(e),o=e-n,a=e-n;for(;o>0;){let l=ht(r,o,!1);if(i(r.slice(l,o))!=nt.Word)break;o=l}for(;at.length?t[0]:4});Me.lineSeparator=qw;Me.readOnly=Uw;Me.phrases=ie.define({compare(t,e){let r=Object.keys(t),n=Object.keys(e);return r.length==n.length&&r.every(s=>t[s]==e[s])}});Me.languageData=Fw;Me.changeFilter=Bw;Me.transactionFilter=Vw;Me.transactionExtender=Hw;Eo.reconfigure=Le.define();function ci(t,e,r={}){let n={};for(let s of t)for(let i of Object.keys(s)){let o=s[i],a=n[i];if(a===void 0)n[i]=o;else if(!(a===o||o===void 0))if(Object.hasOwnProperty.call(r,i))n[i]=r[i](a,o);else throw new Error("Config merge conflict for field "+i)}for(let s in e)n[s]===void 0&&(n[s]=e[s]);return n}class ls{eq(e){return this==e}range(e,r=e){return zu.create(e,r,this)}}ls.prototype.startSide=ls.prototype.endSide=0;ls.prototype.point=!1;ls.prototype.mapMode=Wt.TrackDel;function Hf(t,e){return t==e||t.constructor==e.constructor&&t.eq(e)}let zu=class Zw{constructor(e,r,n){this.from=e,this.to=r,this.value=n}static create(e,r,n){return new Zw(e,r,n)}};function Fu(t,e){return t.from-e.from||t.value.startSide-e.value.startSide}class Uf{constructor(e,r,n,s){this.from=e,this.to=r,this.value=n,this.maxPoint=s}get length(){return this.to[this.to.length-1]}findIndex(e,r,n,s=0){let i=n?this.to:this.from;for(let o=s,a=i.length;;){if(o==a)return o;let l=o+a>>1,c=i[l]-e||(n?this.value[l].endSide:this.value[l].startSide)-r;if(l==o)return c>=0?o:a;c>=0?a=l:o=l+1}}between(e,r,n,s){for(let i=this.findIndex(r,-1e9,!0),o=this.findIndex(n,1e9,!1,i);if||d==f&&c.startSide>0&&c.endSide<=0)continue;(f-d||c.endSide-c.startSide)<0||(o<0&&(o=d),c.point&&(a=Math.max(a,f-d)),n.push(c),s.push(d-o),i.push(f-o))}return{mapped:n.length?new Uf(s,i,n,a):null,pos:o}}}class Ae{constructor(e,r,n,s){this.chunkPos=e,this.chunk=r,this.nextLayer=n,this.maxPoint=s}static create(e,r,n,s){return new Ae(e,r,n,s)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let r of this.chunk)e+=r.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:r=[],sort:n=!1,filterFrom:s=0,filterTo:i=this.length}=e,o=e.filter;if(r.length==0&&!o)return this;if(n&&(r=r.slice().sort(Fu)),this.isEmpty)return r.length?Ae.of(r):this;let a=new Gw(this,null,-1).goto(0),l=0,c=[],u=new eo;for(;a.value||l=0){let h=r[l++];u.addInner(h.from,h.to,h.value)||c.push(h)}else a.rangeIndex==1&&a.chunkIndexthis.chunkEnd(a.chunkIndex)||ia.to||i=i&&e<=i+o.length&&o.between(i,e-i,r-i,n)===!1)return}this.nextLayer.between(e,r,n)}}iter(e=0){return to.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,r=0){return to.from(e).goto(r)}static compare(e,r,n,s,i=-1){let o=e.filter(h=>h.maxPoint>0||!h.isEmpty&&h.maxPoint>=i),a=r.filter(h=>h.maxPoint>0||!h.isEmpty&&h.maxPoint>=i),l=Zm(o,a,n),c=new wi(o,l,i),u=new wi(a,l,i);n.iterGaps((h,d,f)=>Gm(c,h,u,d,f,s)),n.empty&&n.length==0&&Gm(c,0,u,0,0,s)}static eq(e,r,n=0,s){s==null&&(s=999999999);let i=e.filter(u=>!u.isEmpty&&r.indexOf(u)<0),o=r.filter(u=>!u.isEmpty&&e.indexOf(u)<0);if(i.length!=o.length)return!1;if(!i.length)return!0;let a=Zm(i,o),l=new wi(i,a,0).goto(n),c=new wi(o,a,0).goto(n);for(;;){if(l.to!=c.to||!qu(l.active,c.active)||l.point&&(!c.point||!Hf(l.point,c.point)))return!1;if(l.to>s)return!0;l.next(),c.next()}}static spans(e,r,n,s,i=-1){let o=new wi(e,null,i).goto(r),a=r,l=o.openStart;for(;;){let c=Math.min(o.to,n);if(o.point){let u=o.activeForPoint(o.to),h=o.pointFroma&&(s.span(a,c,o.active,l),l=o.openEnd(c));if(o.to>n)return l+(o.point&&o.to>n?1:0);a=o.to,o.next()}}static of(e,r=!1){let n=new eo;for(let s of e instanceof zu?[e]:r?xL(e):e)n.add(s.from,s.to,s.value);return n.finish()}static join(e){if(!e.length)return Ae.empty;let r=e[e.length-1];for(let n=e.length-2;n>=0;n--)for(let s=e[n];s!=Ae.empty;s=s.nextLayer)r=new Ae(s.chunkPos,s.chunk,r,Math.max(s.maxPoint,r.maxPoint));return r}}Ae.empty=new Ae([],[],null,-1);function xL(t){if(t.length>1)for(let e=t[0],r=1;r0)return t.slice().sort(Fu);e=n}return t}Ae.empty.nextLayer=Ae.empty;class eo{finishChunk(e){this.chunks.push(new Uf(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,r,n){this.addInner(e,r,n)||(this.nextLayer||(this.nextLayer=new eo)).add(e,r,n)}addInner(e,r,n){let s=e-this.lastTo||n.startSide-this.last.endSide;if(s<=0&&(e-this.lastFrom||n.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return s<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(r-this.chunkStart),this.last=n,this.lastFrom=e,this.lastTo=r,this.value.push(n),n.point&&(this.maxPoint=Math.max(this.maxPoint,r-e)),!0)}addChunk(e,r){if((e-this.lastTo||r.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,r.maxPoint),this.chunks.push(r),this.chunkPos.push(e);let n=r.value.length-1;return this.last=r.value[n],this.lastFrom=r.from[n]+e,this.lastTo=r.to[n]+e,!0}finish(){return this.finishInner(Ae.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let r=Ae.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,r}}function Zm(t,e,r){let n=new Map;for(let i of t)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=n&&s.push(new Gw(o,r,n,i));return s.length==1?s[0]:new to(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,r=-1e9){for(let n of this.heap)n.goto(e,r);for(let n=this.heap.length>>1;n>=0;n--)$c(this.heap,n);return this.next(),this}forward(e,r){for(let n of this.heap)n.forward(e,r);for(let n=this.heap.length>>1;n>=0;n--)$c(this.heap,n);(this.to-e||this.value.endSide-r)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),$c(this.heap,0)}}}function $c(t,e){for(let r=t[e];;){let n=(e<<1)+1;if(n>=t.length)break;let s=t[n];if(n+1=0&&(s=t[n+1],n++),r.compare(s)<0)break;t[n]=r,t[e]=s,e=n}}class wi{constructor(e,r,n){this.minPoint=n,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=to.from(e,r,n)}goto(e,r=-1e9){return this.cursor.goto(e,r),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=r,this.openStart=-1,this.next(),this}forward(e,r){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-r)<0;)this.removeActive(this.minActive);this.cursor.forward(e,r)}removeActive(e){Jo(this.active,e),Jo(this.activeTo,e),Jo(this.activeRank,e),this.minActive=Jm(this.active,this.activeTo)}addActive(e){let r=0,{value:n,to:s,rank:i}=this.cursor;for(;r0;)r++;Yo(this.active,r,n),Yo(this.activeTo,r,s),Yo(this.activeRank,r,i),e&&Yo(e,r,this.cursor.from),this.minActive=Jm(this.active,this.activeTo)}next(){let e=this.to,r=this.point;this.point=null;let n=this.openStart<0?[]:null;for(;;){let s=this.minActive;if(s>-1&&(this.activeTo[s]-this.cursor.from||this.active[s].endSide-this.cursor.startSide)<0){if(this.activeTo[s]>e){this.to=this.activeTo[s],this.endSide=this.active[s].endSide;break}this.removeActive(s),n&&Jo(n,s)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let i=this.cursor.value;if(!i.point)this.addActive(n),this.cursor.next();else if(r&&this.cursor.to==this.to&&this.cursor.from=0&&n[s]=0&&!(this.activeRank[n]e||this.activeTo[n]==e&&this.active[n].endSide>=this.point.endSide)&&r.push(this.active[n]);return r.reverse()}openEnd(e){let r=0;for(let n=this.activeTo.length-1;n>=0&&this.activeTo[n]>e;n--)r++;return r}}function Gm(t,e,r,n,s,i){t.goto(e),r.goto(n);let o=n+s,a=n,l=n-e,c=!!i.boundChange;for(let u=!1;;){let h=t.to+l-r.to,d=h||t.endSide-r.endSide,f=d<0?t.to+l:r.to,p=Math.min(f,o);if(t.point||r.point?(t.point&&r.point&&Hf(t.point,r.point)&&qu(t.activeForPoint(t.to),r.activeForPoint(r.to))||i.comparePoint(a,p,t.point,r.point),u=!1):(u&&i.boundChange(a),p>a&&!qu(t.active,r.active)&&i.compareRange(a,p,t.active,r.active),c&&po)break;a=f,d<=0&&t.next(),d>=0&&r.next()}}function qu(t,e){if(t.length!=e.length)return!1;for(let r=0;r=e;n--)t[n+1]=t[n];t[e]=r}function Jm(t,e){let r=-1,n=1e9;for(let s=0;s=e)return s;if(s==t.length)break;i+=t.charCodeAt(s)==9?r-i%r:1,s=ht(t,s)}return t.length}const Bu="ͼ",Ym=typeof Symbol>"u"?"__"+Bu:Symbol.for(Bu),Vu=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),Qm=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class Ks{constructor(e,r){this.rules=[];let{finish:n}=r||{};function s(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function i(o,a,l,c){let u=[],h=/^@(\w+)\b/.exec(o[0]),d=h&&h[1]=="keyframes";if(h&&a==null)return l.push(o[0]+";");for(let f in a){let p=a[f];if(/&/.test(f))i(f.split(/,\s*/).map(y=>o.map(v=>y.replace(/&/,v))).reduce((y,v)=>y.concat(v)),p,l);else if(p&&typeof p=="object"){if(!h)throw new RangeError("The value of a property ("+f+") should be a primitive value.");i(s(f),p,u,d)}else p!=null&&u.push(f.replace(/_.*/,"").replace(/[A-Z]/g,y=>"-"+y.toLowerCase())+": "+p+";")}(u.length||d)&&l.push((n&&!h&&!c?o.map(n):o).join(", ")+" {"+u.join(" ")+"}")}for(let o in e)i(s(o),e[o],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=Qm[Ym]||1;return Qm[Ym]=e+1,Bu+e.toString(36)}static mount(e,r,n){let s=e[Vu],i=n&&n.nonce;s?i&&s.setNonce(i):s=new CL(e,i),s.mount(Array.isArray(r)?r:[r],e)}}let Xm=new Map;class CL{constructor(e,r){let n=e.ownerDocument||e,s=n.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let i=Xm.get(n);if(i)return e[Vu]=i;this.sheet=new s.CSSStyleSheet,Xm.set(n,this)}else this.styleTag=n.createElement("style"),r&&this.styleTag.setAttribute("nonce",r);this.modules=[],e[Vu]=this}mount(e,r){let n=this.sheet,s=0,i=0;for(let o=0;o-1&&(this.modules.splice(l,1),i--,l=-1),l==-1){if(this.modules.splice(i++,0,a),n)for(let c=0;c",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},PL=typeof navigator<"u"&&/Mac/.test(navigator.platform),TL=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var wt=0;wt<10;wt++)Rn[48+wt]=Rn[96+wt]=String(wt);for(var wt=1;wt<=24;wt++)Rn[wt+111]="F"+wt;for(var wt=65;wt<=90;wt++)Rn[wt]=String.fromCharCode(wt+32),ro[wt]=String.fromCharCode(wt);for(var Sc in Rn)ro.hasOwnProperty(Sc)||(ro[Sc]=Rn[Sc]);function RL(t){var e=PL&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||TL&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",r=!e&&t.key||(t.shiftKey?ro:Rn)[t.keyCode]||t.key||"Unidentified";return r=="Esc"&&(r="Escape"),r=="Del"&&(r="Delete"),r=="Left"&&(r="ArrowLeft"),r=="Up"&&(r="ArrowUp"),r=="Right"&&(r="ArrowRight"),r=="Down"&&(r="ArrowDown"),r}function ut(){var t=arguments[0];typeof t=="string"&&(t=document.createElement(t));var e=1,r=arguments[1];if(r&&typeof r=="object"&&r.nodeType==null&&!Array.isArray(r)){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)){var s=r[n];typeof s=="string"?t.setAttribute(n,s):s!=null&&(t[n]=s)}e++}for(;e2);var Y={mac:rg||/Mac/.test(Mt.platform),windows:/Win/.test(Mt.platform),linux:/Linux|X11/.test(Mt.platform),ie:Ul,ie_version:Yw?Hu.documentMode||6:Wu?+Wu[1]:Uu?+Uu[1]:0,gecko:eg,gecko_version:eg?+(/Firefox\/(\d+)/.exec(Mt.userAgent)||[0,0])[1]:0,chrome:!!kc,chrome_version:kc?+kc[1]:0,ios:rg,android:/Android\b/.test(Mt.userAgent),webkit:tg,webkit_version:tg?+(/\bAppleWebKit\/(\d+)/.exec(Mt.userAgent)||[0,0])[1]:0,safari:Ku,safari_version:Ku?+(/\bVersion\/(\d+(\.\d+)?)/.exec(Mt.userAgent)||[0,0])[1]:0,tabSize:Hu.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Wf(t,e){for(let r in t)r=="class"&&e.class?e.class+=" "+t.class:r=="style"&&e.style?e.style+=";"+t.style:e[r]=t[r];return e}const tl=Object.create(null);function Kf(t,e,r){if(t==e)return!0;t||(t=tl),e||(e=tl);let n=Object.keys(t),s=Object.keys(e);if(n.length-0!=s.length-0)return!1;for(let i of n)if(i!=r&&(s.indexOf(i)==-1||t[i]!==e[i]))return!1;return!0}function AL(t,e){for(let r=t.attributes.length-1;r>=0;r--){let n=t.attributes[r].name;e[n]==null&&t.removeAttribute(n)}for(let r in e){let n=e[r];r=="style"?t.style.cssText=n:t.getAttribute(r)!=n&&t.setAttribute(r,n)}}function ng(t,e,r){let n=!1;if(e)for(let s in e)r&&s in r||(n=!0,s=="style"?t.style.cssText="":t.removeAttribute(s));if(r)for(let s in r)e&&e[s]==r[s]||(n=!0,s=="style"?t.style.cssText=r[s]:t.setAttribute(s,r[s]));return n}function ML(t){let e=Object.create(null);for(let r=0;r0?3e8:-4e8:r>0?1e8:-1e8,new cs(e,r,r,n,e.widget||null,!1)}static replace(e){let r=!!e.block,n,s;if(e.isBlockGap)n=-5e8,s=4e8;else{let{start:i,end:o}=Qw(e,r);n=(i?r?-3e8:-1:5e8)-1,s=(o?r?2e8:1:-6e8)+1}return new cs(e,n,s,r,e.widget||null,!0)}static line(e){return new Po(e)}static set(e,r=!1){return Ae.of(e,r)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}Ce.none=Ae.empty;class Co extends Ce{constructor(e){let{start:r,end:n}=Qw(e);super(r?-1:5e8,n?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?Wf(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||tl}eq(e){return this==e||e instanceof Co&&this.tagName==e.tagName&&Kf(this.attrs,e.attrs)}range(e,r=e){if(e>=r)throw new RangeError("Mark decorations may not be empty");return super.range(e,r)}}Co.prototype.point=!1;class Po extends Ce{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof Po&&this.spec.class==e.spec.class&&Kf(this.spec.attributes,e.spec.attributes)}range(e,r=e){if(r!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,r)}}Po.prototype.mapMode=Wt.TrackBefore;Po.prototype.point=!0;class cs extends Ce{constructor(e,r,n,s,i,o){super(r,n,i,e),this.block=s,this.isReplace=o,this.mapMode=s?r<=0?Wt.TrackBefore:Wt.TrackAfter:Wt.TrackDel}get type(){return this.startSide!=this.endSide?bt.WidgetRange:this.startSide<=0?bt.WidgetBefore:bt.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof cs&&IL(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,r=e){if(this.isReplace&&(e>r||e==r&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&r!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,r)}}cs.prototype.point=!0;function Qw(t,e=!1){let{inclusiveStart:r,inclusiveEnd:n}=t;return r==null&&(r=t.inclusive),n==null&&(n=t.inclusive),{start:r??e,end:n??e}}function IL(t,e){return t==e||!!(t&&e&&t.compare(e))}function js(t,e,r,n=0){let s=r.length-1;s>=0&&r[s]+n>=t?r[s]=Math.max(r[s],e):r.push(t,e)}class no extends ls{constructor(e,r,n){super(),this.tagName=e,this.attributes=r,this.rank=n}eq(e){return e==this||e instanceof no&&this.tagName==e.tagName&&Kf(this.attributes,e.attributes)}static create(e){return new no(e.tagName,e.attributes||tl,e.rank==null?50:Math.max(0,Math.min(e.rank,100)))}static set(e,r=!1){return Ae.of(e,r)}}no.prototype.startSide=no.prototype.endSide=-1;function so(t){let e;return t.nodeType==11?e=t.getSelection?t:t.ownerDocument:e=t,e.getSelection()}function Zu(t,e){return e?t==e||t.contains(e.nodeType!=1?e.parentNode:e):!1}function Vi(t,e){if(!e.anchorNode)return!1;try{return Zu(t,e.anchorNode)}catch{return!1}}function Pa(t){return t.nodeType==3?io(t,0,t.nodeValue.length).getClientRects():t.nodeType==1?t.getClientRects():[]}function Hi(t,e,r,n){return r?sg(t,e,r,n,-1)||sg(t,e,r,n,1):!1}function An(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e}function rl(t){return t.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(t.nodeName)}function sg(t,e,r,n,s){for(;;){if(t==r&&e==n)return!0;if(e==(s<0?0:sn(t))){if(t.nodeName=="DIV")return!1;let i=t.parentNode;if(!i||i.nodeType!=1)return!1;e=An(t)+(s<0?0:1),t=i}else if(t.nodeType==1){if(t=t.childNodes[e+(s<0?-1:0)],t.nodeType==1&&t.contentEditable=="false")return!1;e=s<0?sn(t):0}else return!1}}function sn(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function nl(t,e){let{left:r,right:n}=t;if(r==n)return t;let s=e?r:n;return{left:s,right:s,top:t.top,bottom:t.bottom}}function OL(t){let e=t.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.innerWidth,top:0,bottom:t.innerHeight}}function Xw(t,e){let r=e.width/t.offsetWidth,n=e.height/t.offsetHeight;return(r>.995&&r<1.005||!isFinite(r)||Math.abs(e.width-t.offsetWidth)<1)&&(r=1),(n>.995&&n<1.005||!isFinite(n)||Math.abs(e.height-t.offsetHeight)<1)&&(n=1),{scaleX:r,scaleY:n}}function NL(t,e,r,n,s,i,o,a){let l=t.ownerDocument,c=l.defaultView||window;for(let u=t,h=!1;u&&!h;)if(u.nodeType==1){let d,f=u==l.body,p=1,y=1;if(f)d=OL(c);else{if(/^(fixed|sticky)$/.test(getComputedStyle(u).position)&&(h=!0),u.scrollHeight<=u.clientHeight&&u.scrollWidth<=u.clientWidth){u=u.assignedSlot||u.parentNode;continue}let _=u.getBoundingClientRect();({scaleX:p,scaleY:y}=Xw(u,_)),d={left:_.left,right:_.left+u.clientWidth*p,top:_.top,bottom:_.top+u.clientHeight*y}}let v=0,m=0;if(s=="nearest")e.top0&&e.bottom>d.bottom+m&&(m=e.bottom-d.bottom+o)):e.bottom>d.bottom-o&&(m=e.bottom-d.bottom+o,r<0&&e.top-m0&&e.right>d.right+v&&(v=e.right-d.right+i)):e.right>d.right-i&&(v=e.right-d.right+i,r<0&&e.leftd.bottom||e.leftd.right)&&(e={left:Math.max(e.left,d.left),right:Math.min(e.right,d.right),top:Math.max(e.top,d.top),bottom:Math.min(e.bottom,d.bottom)}),u=u.assignedSlot||u.parentNode}else if(u.nodeType==11)u=u.host;else break}function e_(t,e=!0){let r=t.ownerDocument,n=null,s=null;for(let i=t.parentNode;i&&!(i==r.body||(!e||n)&&s);)if(i.nodeType==1)!s&&i.scrollHeight>i.clientHeight&&(s=i),e&&!n&&i.scrollWidth>i.clientWidth&&(n=i),i=i.assignedSlot||i.parentNode;else if(i.nodeType==11)i=i.host;else break;return{x:n,y:s}}class jL{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:r,focusNode:n}=e;this.set(r,Math.min(e.anchorOffset,r?sn(r):0),n,Math.min(e.focusOffset,n?sn(n):0))}set(e,r,n,s){this.anchorNode=e,this.anchorOffset=r,this.focusNode=n,this.focusOffset=s}}function t_(t){let e=[];for(let r=t;r;r=r.nodeType==11?r.host:r.parentNode)r.nodeType==1&&e.push({node:r,left:r.scrollLeft,top:r.scrollTop});return e}function r_(t,e=!0){for(let{node:r,left:n,top:s}of t)e&&r.scrollTop!=s&&(r.scrollTop=s),r.scrollLeft!=n&&(r.scrollLeft=n)}let Hn=null;Y.safari&&Y.safari_version>=26&&(Hn=!1);function n_(t){if(t.setActive)return t.setActive();if(Hn)return t.focus(Hn);let e=t_(t);t.focus(Hn==null?{get preventScroll(){return Hn={preventScroll:!0},!0}}:void 0),Hn||(Hn=!1,r_(e))}let ig;function io(t,e,r=e){let n=ig||(ig=document.createRange());return n.setEnd(t,r),n.setStart(t,e),n}function Ds(t,e,r,n){let s={key:e,code:e,keyCode:r,which:r,cancelable:!0};n&&({altKey:s.altKey,ctrlKey:s.ctrlKey,shiftKey:s.shiftKey,metaKey:s.metaKey}=n);let i=new KeyboardEvent("keydown",s);i.synthetic=!0,t.dispatchEvent(i);let o=new KeyboardEvent("keyup",s);return o.synthetic=!0,t.dispatchEvent(o),i.defaultPrevented||o.defaultPrevented}function DL(t){for(;t;){if(t&&(t.nodeType==9||t.nodeType==11&&t.host))return t;t=t.assignedSlot||t.parentNode}return null}function LL(t,e){let r=e.focusNode,n=e.focusOffset;if(!r||e.anchorNode!=r||e.anchorOffset!=n)return!1;for(n=Math.min(n,sn(r));;)if(n){if(r.nodeType!=1)return!1;let s=r.childNodes[n-1];s.contentEditable=="false"?n--:(r=s,n=sn(r))}else{if(r==t)return!0;n=An(r),r=r.parentNode}}function s_(t){return t instanceof Window?t.pageYOffset>Math.max(0,t.document.documentElement.scrollHeight-t.innerHeight-4):t.scrollTop>Math.max(1,t.scrollHeight-t.clientHeight-4)}function i_(t,e){for(let r=t,n=e;;){if(r.nodeType==3&&n>0)return{node:r,offset:n};if(r.nodeType==1&&n>0){if(r.contentEditable=="false")return null;r=r.childNodes[n-1],n=sn(r)}else if(r.parentNode&&!rl(r))n=An(r),r=r.parentNode;else return null}}function o_(t,e){for(let r=t,n=e;;){if(r.nodeType==3&&n=r){if(a.level==n)return o;(i<0||(s!=0?s<0?a.fromr:e[i].level>a.level))&&(i=o)}}if(i<0)throw new RangeError("Index out of range");return i}}function c_(t,e){if(t.length!=e.length)return!1;for(let r=0;r=0;y-=3)if(kr[y+1]==-f){let v=kr[y+2],m=v&2?s:v&4?v&1?i:s:0;m&&(De[h]=De[kr[y]]=m),a=y;break}}else{if(kr.length==189)break;kr[a++]=h,kr[a++]=d,kr[a++]=l}else if((p=De[h])==2||p==1){let y=p==s;l=y?0:1;for(let v=a-3;v>=0;v-=3){let m=kr[v+2];if(m&2)break;if(y)kr[v+2]|=2;else{if(m&4)break;kr[v+2]|=4}}}}}function HL(t,e,r,n){for(let s=0,i=n;s<=r.length;s++){let o=s?r[s-1].to:t,a=sl;)p==v&&(p=r[--y].from,v=y?r[y-1].to:t),De[--p]=f;l=u}else i=c,l++}}}function Ju(t,e,r,n,s,i,o){let a=n%2?2:1;if(n%2==s%2)for(let l=e,c=0;ll&&o.push(new Nr(l,y.from,f));let v=y.direction==us!=!(f%2);Yu(t,v?n+1:n,s,y.inner,y.from,y.to,o),l=y.to}p=y.to}else{if(p==r||(u?De[p]!=a:De[p]==a))break;p++}d?Ju(t,l,p,n+1,s,d,o):le;){let u=!0,h=!1;if(!c||l>i[c-1].to){let y=De[l-1];y!=a&&(u=!1,h=y==16)}let d=!u&&a==1?[]:null,f=u?n:n+1,p=l;e:for(;;)if(c&&p==i[c-1].to){if(h)break e;let y=i[--c];if(!u)for(let v=y.from,m=c;;){if(v==e)break e;if(m&&i[m-1].to==v)v=i[--m].from;else{if(De[v-1]==a)break e;break}}if(d)d.push(y);else{y.toDe.length;)De[De.length]=256;let n=[],s=e==us?0:1;return Yu(t,s,s,r,0,t.length,n),n}function u_(t){return[new Nr(0,t,0)]}let h_="";function WL(t,e,r,n,s){var i;let o=n.head-t.from,a=Nr.find(e,o,(i=n.bidiLevel)!==null&&i!==void 0?i:-1,n.assoc),l=e[a],c=l.side(s,r);if(o==c){let d=a+=s?1:-1;if(d<0||d>=e.length)return null;l=e[a=d],o=l.side(!s,r),c=l.side(s,r)}let u=ht(t.text,o,l.forward(s,r));(ul.to)&&(u=c),h_=t.text.slice(Math.min(o,u),Math.max(o,u));let h=a==(s?e.length-1:0)?null:e[a+(s?1:-1)];return h&&u==c&&h.level+(s?0:1)t.some(e=>e)}),w_=ie.define({combine:t=>t.some(e=>e)}),__=ie.define();class Ls{constructor(e,r,n,s,i,o=!1){this.range=e,this.y=r,this.x=n,this.yMargin=s,this.xMargin=i,this.isSnapshot=o}map(e){return e.empty?this:new Ls(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new Ls(W.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const Qo=Le.define({map:(t,e)=>t.map(e)}),b_=Le.define();function jr(t,e,r){let n=t.facet(m_);n.length?n[0](e):window.onerror&&window.onerror(String(e),r,void 0,void 0,e)||(r?console.error(r+":",e):console.error(e))}const Qr=ie.define({combine:t=>t.length?t[0]:!0});let ZL=0;const Ts=ie.define({combine(t){return t.filter((e,r)=>{for(let n=0;n{let l=[];return o&&l.push(Kl.of(c=>{let u=c.plugin(a);return u?o(u):Ce.none})),i&&l.push(i(a)),l})}static fromClass(e,r){return Kt.define((n,s)=>new e(n,s),r)}}class xc{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let r=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(r)}catch(n){if(jr(r.state,n,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(r){jr(e.state,r,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var r;if(!((r=this.value)===null||r===void 0)&&r.destroy)try{this.value.destroy()}catch(n){jr(e.state,n,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const $_=ie.define(),Yf=ie.define(),Kl=ie.define(),S_=ie.define(),Qf=ie.define(),To=ie.define(),k_=ie.define();function og(t,e){let r=t.state.facet(k_);if(!r.length)return r;let n=r.map(i=>i instanceof Function?i(t):i),s=[];return Ae.spans(n,e.from,e.to,{point(){},span(i,o,a,l){let c=i-e.from,u=o-e.from,h=s;for(let d=a.length-1;d>=0;d--,l--){let f=a[d].spec.bidiIsolate,p;if(f==null&&(f=KL(e.text,c,u)),l>0&&h.length&&(p=h[h.length-1]).to==c&&p.direction==f)p.to=u,h=p.inner;else{let y={from:c,to:u,direction:f,inner:[]};h.push(y),h=y.inner}}}}),s}const x_=ie.define();function E_(t){let e=0,r=0,n=0,s=0;for(let i of t.state.facet(x_)){let o=i(t);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(r=Math.max(r,o.right)),o.top!=null&&(n=Math.max(n,o.top)),o.bottom!=null&&(s=Math.max(s,o.bottom)))}return{left:e,right:r,top:n,bottom:s}}const Ci=ie.define();class Xt{constructor(e,r,n,s){this.fromA=e,this.toA=r,this.fromB=n,this.toB=s}join(e){return new Xt(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let r=e.length,n=this;for(;r>0;r--){let s=e[r-1];if(!(s.fromA>n.toA)){if(s.toAs.push(new Xt(i,o,a,l))),this.changedRanges=s}static create(e,r,n){return new sl(e,r,n)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}const GL=[];class Ye{constructor(e,r,n=0){this.dom=e,this.length=r,this.flags=n,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return GL}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let r=this.domAttrs;r&&AL(this.dom,r)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,r=this.posAtStart){let n=r;for(let s of this.children){if(s==e)return n;n+=s.length+s.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,r,n){return null}domPosFor(e,r){let n=An(this.dom),s=this.length?e>0:r>0;return new dr(this.parent.dom,n+(s?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof Gl)return e;return null}static get(e){return e.cmTile}}class Zl extends Ye{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let r=this.dom,n=null,s,i=(e==null?void 0:e.node)==r?e:null,o=0;for(let a of this.children){if(a.sync(e),o+=a.length+a.breakAfter,s=n?n.nextSibling:r.firstChild,i&&s!=a.dom&&(i.written=!0),a.dom.parentNode==r)for(;s&&s!=a.dom;)s=ag(s);else r.insertBefore(a.dom,s);n=a.dom}for(s=n?n.nextSibling:r.firstChild,i&&s&&(i.written=!0);s;)s=ag(s);this.length=o}}function ag(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class Gl extends Zl{constructor(e,r){super(r),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let r=Ye.get(e);if(r&&this.owns(r))return r;e=e.parentNode}}blockTiles(e){for(let r=[],n=this,s=0,i=0;;)if(s==n.children.length){if(!r.length)return;n=n.parent,n.breakAfter&&i++,s=r.pop()}else{let o=n.children[s++];if(o instanceof nn)r.push(s),n=o,s=0;else{let a=i+o.length,l=e(o,i);if(l!==void 0)return l;i=a+o.breakAfter}}}resolveBlock(e,r){let n,s=-1,i,o=-1;if(this.blockTiles((a,l)=>{let c=l+a.length;if(e>=l&&e<=c){if(a.isWidget()&&r>=-1&&r<=1){if(a.flags&32)return!0;a.flags&16&&(n=void 0)}(le||e==l&&(r>1?a.length:a.covers(-1)))&&(!i||!a.isWidget()&&i.isWidget())&&(i=a,o=e-l)}}),!n&&!i)throw new Error("No tile at position "+e);return n&&r<0||!i?{tile:n,offset:s}:{tile:i,offset:o}}}class nn extends Zl{constructor(e,r){super(e),this.wrapper=r}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,r){let n=new nn(r||document.createElement(e.tagName),e);return r||(n.flags|=4),n}}class Zs extends Zl{constructor(e,r){super(e),this.attrs=r}isLine(){return!0}static start(e,r,n){let s=new Zs(r||document.createElement("div"),e);return(!r||!n)&&(s.flags|=4),s}get domAttrs(){return this.attrs}resolveInline(e,r,n){let s=null,i=-1,o=null,a=-1;function l(u,h){for(let d=0,f=0;d=h&&(p.isComposite()?l(p,h-f):(!o||o.isHidden&&(r>0&&!(o.flags&32)||n&&YL(o,p)))&&(y>h||p.flags&32&&r<=1)?(o=p,a=h-f):(f=-1)&&(s=p,i=h-f)),f=y}}l(this,e);let c=(r<0?s:o)||s||o;return c?{tile:c,offset:c==s?i:a}:null}coordsIn(e,r,n){let s=this.resolveInline(e,r,!0);return s?s.tile.coordsIn(Math.max(0,s.offset),r,n):JL(this)}domIn(e,r){let n=this.resolveInline(e,r);if(n){let{tile:s,offset:i}=n;if(this.dom.contains(s.dom))return s.isText()?new dr(s.dom,Math.min(s.dom.nodeValue.length,i)):s.domPosFor(i,s.flags&16?1:s.flags&32?-1:r);let o=n.tile.parent,a=!1;for(let l of o.children){if(a)return new dr(l.dom,0);l==n.tile&&(a=!0)}}return new dr(this.dom,0)}}function JL(t){let e=t.dom.lastChild;if(!e)return t.dom.getBoundingClientRect();let r=Pa(e);return r[r.length-1]||null}function YL(t,e){let r=t.coordsIn(0,1),n=e.coordsIn(0,1);return r&&n&&n.tops&&(e=s);let i=e,o=e,a=0;e==0&&r<0||e==s&&r>=0?Y.chrome||Y.gecko||(e?(i--,a=1):o=0)?0:l.length-1];return Y.safari&&!a&&c.width==0&&(c=Array.prototype.find.call(l,u=>u.width)||c),n==null?c:nl(c,(a?a>0:r<0)==n)}static of(e,r){let n=new Xn(r||document.createTextNode(e),e);return r||(n.flags|=2),n}}class hs extends Ye{constructor(e,r,n,s){super(e,r,s),this.widget=n}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,r){return this.coordsInWidget(e,r,!1)}coordsInWidget(e,r,n){let s=this.widget.coordsAt(this.dom,e,r);if(s)return s;if(n)return nl(this.dom.getBoundingClientRect(),this.length?e==0:r<=0);{let i=this.dom.getClientRects(),o=null;if(!i.length)return null;let a=this.flags&16?!0:this.flags&32?!1:e>0;for(let l=a?i.length-1:0;o=i[l],!(e>0?l==0:l==i.length-1||o.top0==n)}}class QL{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,r,n){let{tile:s,index:i,beforeBreak:o,parents:a}=this;for(;e||r>0;)if(s.isComposite())if(o){if(!e)break;n&&n.break(),e--,o=!1}else if(i==s.children.length){if(!e&&!a.length)break;n&&n.leave(s),o=!!s.breakAfter,{tile:s,index:i}=a.pop(),i++}else{let l=s.children[i],c=l.breakAfter;(r>0?l.length<=e:l.length=0;a--){let l=r.marks[a],c=s.lastChild;if(c instanceof Ft&&c.mark.eq(l.mark))c.dom!=l.dom&&c.setDOM(Ec(l.dom)),s=c;else{if(this.cache.reused.get(l)){let h=Ye.get(l.dom);h&&h.setDOM(Ec(l.dom))}let u=Ft.of(l.mark,l.dom);s.append(u),s=u}this.cache.reused.set(l,2)}let i=Ye.get(e.text);i&&this.cache.reused.set(i,2);let o=new Xn(e.text,e.text.nodeValue);o.flags|=8,this.pos=e.range.toB,s.append(o)}addInlineWidget(e,r,n){let s=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);s||this.flushBuffer();let i=this.ensureMarks(r,n);!s&&!(e.flags&16)&&i.append(this.getBuffer(1)),i.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,r,n){this.flushBuffer(),this.ensureMarks(r,n).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let r=this.afterWidget||this.lastBlock;r.length+=e,this.pos+=e}addLineStart(e,r){var n;e||(e=C_);let s=Zs.start(e,r||((n=this.cache.find(Zs))===null||n===void 0?void 0:n.dom),!!r);this.getBlockPos().append(this.lastBlock=this.curLine=s)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,r){var n;let s=this.curLine;for(let i=e.length-1;i>=0;i--){let o=e[i],a;if(r>0&&(a=s.lastChild)&&a instanceof Ft&&a.mark.eq(o))s=a,r--;else{let l=Ft.of(o,(n=this.cache.find(Ft,c=>c.mark.eq(o)))===null||n===void 0?void 0:n.dom);s.append(l),s=l,r=0}}return s}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!lg(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(Y.ios&&lg(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Cc,0,32)||new hs(Cc.toDOM(),0,Cc,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to=this.pos){let r=e.rank*102+e.value.rank,n=new XL(e.from,e.to,e.value,r),s=this.wrappers.length;for(;s>0&&(this.wrappers[s-1].rank-n.rank||this.wrappers[s-1].to-n.to)<0;)s--;this.wrappers.splice(s,0,n)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let r=this.root;for(let n of this.wrappers){let s=r.lastChild;if(n.fromo.wrapper.eq(n.wrapper)))===null||e===void 0?void 0:e.dom);r.append(i),r=i}}return r}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let r=2|(e<0?16:32),n=this.cache.find(il,void 0,1);return n&&(n.flags=r),n||new il(r)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}}class tz{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:s,lineBreak:i,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=s;let a=this.textOff=Math.min(e,s.length);return i?null:s.slice(0,a)}let r=Math.min(this.text.length,this.textOff+e),n=this.text.slice(this.textOff,r);return this.textOff=r,n}}const ol=[hs,Zs,Xn,Ft,il,nn,Gl];for(let t=0;t[]),this.index=ol.map(()=>0),this.reused=new Map}add(e){let r=e.constructor.bucket,n=this.buckets[r];n.length<6?n.push(e):n[this.index[r]=(this.index[r]+1)%6]=e}find(e,r,n=2){let s=e.bucket,i=this.buckets[s],o=this.index[s];for(let a=0;a{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,r){let n=r&&this.getCompositionContext(r.text);for(let s=0,i=0,o=0;;){let a=os){let c=l-s;this.preserve(c,!o,!a),s=l,i+=c}if(!a)break;r&&a.fromA<=r.range.fromA&&a.toA>=r.range.toA?(this.forward(a.fromA,r.range.fromA,r.range.fromA{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(l-a);else{let c=l>0||a{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof Ft&&s.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?s.length&&(s.length=i=0):o instanceof Ft&&(s.shift(),i=Math.min(i,s.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,r){let n=null,s=this.builder,i=-1,o=Ae.spans(this.decorations,e,r,{point:(a,l,c,u,h,d)=>{if(c instanceof cs){if(this.disallowBlockEffectsFor[d]){if(c.block)throw new RangeError("Block decorations may not be specified via plugins");if(l>this.view.state.doc.lineAt(a).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(i=u.length,h>u.length)s.continueWidget(l-a);else{let f=c.widget||(c.block?Gs.block:Gs.inline),p=sz(c),y=this.cache.findWidget(f,l-a,p)||hs.of(f,this.view,l-a,p);c.block?(c.startSide>0&&s.addLineStartIfNotCovered(n),s.addBlockWidget(y)):(s.ensureLine(n),s.addInlineWidget(y,u,h))}n=null}else n=iz(n,c);l>a&&this.text.skip(l-a)},span:(a,l,c,u)=>{for(let h=a;h-1&&(this.openWidget=o>i),this.openWidget||s.addLineStartIfNotCovered(n),this.openMarks=o}forward(e,r,n=1){r-e<=10?this.old.advance(r-e,n,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(r-e-10,-1),this.old.advance(5,n,this.reuseWalker))}getCompositionContext(e){let r=[],n=null;for(let s=e.parentNode;;s=s.parentNode){let i=Ye.get(s);if(s==this.view.contentDOM)break;i instanceof Ft?r.push(i):i!=null&&i.isLine()?n=i:i instanceof nn||(s.nodeName=="DIV"&&!n&&s!=this.view.contentDOM?n=new Zs(s,C_):n||r.push(Ft.of(new Co({tagName:s.nodeName.toLowerCase(),attributes:ML(s)}),s)))}return{line:n,marks:r}}}function lg(t,e){let r=n=>{for(let s of n.children)if((e?s.isText():s.length)||r(s))return!0;return!1};return r(t)}function sz(t){let e=t.isReplace?(t.startSide<0?64:0)|(t.endSide>0?128:0):t.startSide>0?32:16;return t.block&&(e|=256),e}const C_={class:"cm-line"};function iz(t,e){let r=e.spec.attributes,n=e.spec.class;return!r&&!n||(t||(t={class:"cm-line"}),r&&Wf(r,t),n&&(t.class+=" "+n)),t}function oz(t){let e=[];for(let r=t.parents.length;r>1;r--){let n=r==t.parents.length?t.tile:t.parents[r].tile;n instanceof Ft&&e.push(n.mark)}return e}function Ec(t){let e=Ye.get(t);return e&&e.setDOM(t.cloneNode()),t}class Gs extends Wl{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}Gs.inline=new Gs("span");Gs.block=new Gs("div");const Cc=new class extends Wl{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}};class cg{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=Ce.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new Gl(e,e.contentDOM),this.updateInner([new Xt(0,0,0,e.state.doc.length)],null)}update(e){var r;let n=e.changedRanges;this.minWidth>0&&n.length&&(n.every(({fromA:u,toA:h})=>hthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let s=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((r=this.domChanged)===null||r===void 0)&&r.newSel?s=this.domChanged.newSel.head:!mz(e.changes,this.hasComposition)&&!e.selectionSet&&(s=e.state.selection.main.head));let i=s>-1?lz(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){let{from:u,to:h}=this.hasComposition;n=new Xt(u,h,e.changes.mapPos(u,-1),e.changes.mapPos(h,1)).addToSet(n.slice())}this.hasComposition=i?{from:i.range.fromB,to:i.range.toB}:null,(Y.ie||Y.chrome)&&!i&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,a=this.blockWrappers;this.updateDeco();let l=hz(o,this.decorations,e.changes);l.length&&(n=Xt.extendWithRanges(n,l));let c=fz(a,this.blockWrappers,e.changes);return c.length&&(n=Xt.extendWithRanges(n,c)),i&&!n.some(u=>u.fromA<=i.range.fromA&&u.toA>=i.range.toA)&&(n=i.range.addToSet(n.slice())),this.tile.flags&2&&n.length==0?!1:(this.updateInner(n,i),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,r){this.view.viewState.mustMeasureContent=!0;let{observer:n}=this.view;n.ignore(()=>{if(r||e.length){let o=this.tile,a=new nz(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);r&&Ye.get(r.text)&&a.cache.reused.set(Ye.get(r.text),2),this.tile=a.run(e,r),Xu(o,a.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let i=Y.chrome||Y.ios?{node:n.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(i),i&&(i.written||n.selectionRange.focusNode!=i.node||!this.tile.dom.contains(i.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to-1)&&Vi(n,this.view.observer.selectionRange)&&!(s&&n.contains(s));if(!(i||r||o))return;let a=this.forceSelection;this.forceSelection=!1;let l=this.view.state.selection.main,c,u;if(l.empty?u=c=this.inlineDOMNearPos(l.anchor,l.assoc||1):(u=this.inlineDOMNearPos(l.head,l.head==l.from?1:-1),c=this.inlineDOMNearPos(l.anchor,l.anchor==l.from?1:-1)),Y.gecko&&l.empty&&!this.hasComposition&&az(c)){let d=document.createTextNode("");this.view.observer.ignore(()=>c.node.insertBefore(d,c.node.childNodes[c.offset]||null)),c=u=new dr(d,0),a=!0}let h=this.view.observer.selectionRange;(a||!h.focusNode||(!Hi(c.node,c.offset,h.anchorNode,h.anchorOffset)||!Hi(u.node,u.offset,h.focusNode,h.focusOffset))&&!this.suppressWidgetCursorChange(h,l))&&(this.view.observer.ignore(()=>{Y.android&&Y.chrome&&n.contains(h.focusNode)&&pz(h.focusNode,n)&&(n.blur(),n.focus({preventScroll:!0}));let d=so(this.view.root);if(d)if(l.empty){if(Y.gecko){let f=cz(c.node,c.offset);if(f&&f!=3){let p=(f==1?i_:o_)(c.node,c.offset);p&&(c=new dr(p.node,p.offset))}}d.collapse(c.node,c.offset),l.bidiLevel!=null&&d.caretBidiLevel!==void 0&&(d.caretBidiLevel=l.bidiLevel)}else if(d.extend){d.collapse(c.node,c.offset);try{d.extend(u.node,u.offset)}catch{}}else{let f=document.createRange();l.anchor>l.head&&([c,u]=[u,c]),f.setEnd(u.node,u.offset),f.setStart(c.node,c.offset),d.removeAllRanges(),d.addRange(f)}o&&this.view.root.activeElement==n&&(n.blur(),s&&s.focus())}),this.view.observer.setSelectionRange(c,u)),this.impreciseAnchor=c.precise?null:new dr(h.anchorNode,h.anchorOffset),this.impreciseHead=u.precise?null:new dr(h.focusNode,h.focusOffset)}suppressWidgetCursorChange(e,r){return this.hasComposition&&r.empty&&Hi(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==r.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,r=e.state.selection.main,n=so(e.root),{anchorNode:s,anchorOffset:i}=e.observer.selectionRange;if(!n||!r.empty||!r.assoc||!n.modify)return;let o=this.lineAt(r.head,r.assoc);if(!o)return;let a=o.posAtStart;if(r.head==a||r.head==a+o.length)return;let l=this.coordsAt(r.head,-1),c=this.coordsAt(r.head,1);if(!l||!c||l.bottom>c.top)return;let u=this.domAtPos(r.head+r.assoc,r.assoc);n.collapse(u.node,u.offset),n.modify("move",r.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let h=e.observer.selectionRange;e.docView.posFromDOM(h.anchorNode,h.anchorOffset)!=r.from&&n.collapse(s,i)}posFromDOM(e,r){let n=this.tile.nearest(e);if(!n)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let s=n.posAtStart;if(n.isComposite()){let i;if(e==n.dom)i=n.dom.childNodes[r];else{let o=sn(e)==0?0:r==0?-1:1;for(;;){let a=e.parentNode;if(a==n.dom)break;o==0&&a.firstChild!=a.lastChild&&(e==a.firstChild?o=-1:o=1),e=a}o<0?i=e:i=e.nextSibling}if(i==n.dom.firstChild)return s;for(;i&&!Ye.get(i);)i=i.nextSibling;if(!i)return s+n.length;for(let o=0,a=s;;o++){let l=n.children[o];if(l.dom==i)return a;a+=l.length+l.breakAfter}}else return n.isText()?e==n.dom?s+r:s+(r?n.length:0):s}domAtPos(e,r){let{tile:n,offset:s}=this.tile.resolveBlock(e,r);return n.isWidget()?n.domPosFor(s,r):n.domIn(s,r)}inlineDOMNearPos(e,r){let n,s=-1,i=!1,o,a=-1,l=!1;return this.tile.blockTiles((c,u)=>{if(c.isWidget()){if(c.flags&32&&u>=e)return!0;c.flags&16&&(i=!0)}else{let h=u+c.length;if(u<=e&&(n=c,s=e-u,i=h=e&&!o&&(o=c,a=e-u,l=u>e),u>e&&o)return!0}}),!n&&!o?this.domAtPos(e,r):(i&&o?n=null:l&&n&&(o=null),n&&r<0||!o?n.domIn(s,r):o.domIn(a,r))}coordsAt(e,r,n){let{tile:s,offset:i}=this.tile.resolveBlock(e,r);return s.isWidget()?s.widget instanceof Pc?null:s.coordsInWidget(i,r,!0):s.coordsIn(i,r,n)}lineAt(e,r){let{tile:n}=this.tile.resolveBlock(e,r);return n.isLine()?n:null}coordsForChar(e){let{tile:r,offset:n}=this.tile.resolveBlock(e,1);if(!r.isLine())return null;function s(i,o){if(i.isComposite())for(let a of i.children){if(a.length>=o){let l=s(a,o);if(l)return l}if(o-=a.length,o<0)break}else if(i.isText()&&oMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,a=-1,l=this.view.textDirection==We.LTR,c=0,u=(h,d,f)=>{for(let p=0;ps);p++){let y=h.children[p],v=d+y.length,m=y.dom.getBoundingClientRect(),{height:_}=m;if(f&&!p&&(c+=m.top-f.top),y instanceof nn)v>n&&u(y,d,m);else if(d>=n&&(c>0&&r.push(-c),r.push(_+c),c=0,o)){let $=y.dom.lastChild,E=$?Pa($):[];if(E.length){let x=E[E.length-1],P=l?x.right-m.left:m.right-x.left;P>a&&(a=P,this.minWidth=i,this.minWidthFrom=d,this.minWidthTo=v)}}f&&p==h.children.length-1&&(c+=f.bottom-m.bottom),d=v+y.breakAfter}};return u(this.tile,0,null),r}textDirectionAt(e){let{tile:r}=this.tile.resolveBlock(e,1);return getComputedStyle(r.dom).direction=="rtl"?We.RTL:We.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let a=0,l;for(let c of o.children){if(!c.isText()||/[^ -~]/.test(c.text))return;let u=Pa(c.dom);if(u.length!=1)return;a+=u[0].width,l=u[0].height}if(a)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:a/o.length,textHeight:l}}});if(e)return e;let r=document.createElement("div"),n,s,i;return r.className="cm-line",r.style.width="99999px",r.style.position="absolute",r.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(r);let o=Pa(r.firstChild)[0];n=r.getBoundingClientRect().height,s=o&&o.width?o.width/27:7,i=o&&o.height?o.height:n,r.remove()}),{lineHeight:n,charWidth:s,textHeight:i}}computeBlockGapDeco(){let e=[],r=this.view.viewState;for(let n=0,s=0;;s++){let i=s==r.viewports.length?null:r.viewports[s],o=i?i.from-1:this.view.state.doc.length;if(o>n){let a=(r.lineBlockAt(o).bottom-r.lineBlockAt(n).top)/this.view.scaleY;e.push(Ce.replace({widget:new Pc(a),block:!0,inclusive:!0,isBlockGap:!0}).range(n,o))}if(!i)break;n=i.to+1}return Ce.set(e)}updateDeco(){let e=1,r=this.view.state.facet(Kl).map(i=>(this.dynamicDecorationMap[e++]=typeof i=="function")?i(this.view):i),n=!1,s=this.view.state.facet(Qf).map((i,o)=>{let a=typeof i=="function";return a&&(n=!0),a?i(this.view):i});for(s.length&&(this.dynamicDecorationMap[e++]=n,r.push(Ae.join(s))),this.decorations=[this.editContextFormatting,...r,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];etypeof i=="function"?i(this.view):i)}scrollIntoView(e){if(e.isSnapshot){let c=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=c.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let c of this.view.state.facet(__))try{if(c(this.view,e.range,e))return!0}catch(u){jr(this.view.state,u,"scroll handler")}let{range:r}=e,n=this.coordsAt(r.head,r.assoc||(r.head>r.anchor?-1:1)),s;if(!n)return;!r.empty&&(s=this.coordsAt(r.anchor,r.anchor>r.head?-1:1))&&(n={left:Math.min(n.left,s.left),top:Math.min(n.top,s.top),right:Math.max(n.right,s.right),bottom:Math.max(n.bottom,s.bottom)});let i=E_(this.view),o={left:n.left-i.left,top:n.top-i.top,right:n.right+i.right,bottom:n.bottom+i.bottom},{offsetWidth:a,offsetHeight:l}=this.view.scrollDOM;if(NL(this.view.scrollDOM,o,r.head1&&(n.top>window.visualViewport.offsetTop+window.visualViewport.height||n.bottomn.isWidget()||n.children.some(r);return r(this.tile.resolveBlock(e,1).tile)}destroy(){Xu(this.tile)}}function Xu(t,e){let r=e==null?void 0:e.get(t);if(r!=1){r==null&&t.destroy();for(let n of t.children)Xu(n,e)}}function az(t){return t.node.nodeType==1&&t.node.firstChild&&(t.offset==0||t.node.childNodes[t.offset-1].contentEditable=="false")&&(t.offset==t.node.childNodes.length||t.node.childNodes[t.offset].contentEditable=="false")}function P_(t,e){let r=t.observer.selectionRange;if(!r.focusNode)return null;let n=i_(r.focusNode,r.focusOffset),s=o_(r.focusNode,r.focusOffset),i=n||s;if(s&&n&&s.node!=n.node){let a=Ye.get(s.node);if(!a||a.isText()&&a.text!=s.node.nodeValue)i=s;else if(t.docView.lastCompositionAfterCursor){let l=Ye.get(n.node);!l||l.isText()&&l.text!=n.node.nodeValue||(i=s)}}if(t.docView.lastCompositionAfterCursor=i!=n,!i)return null;let o=e-i.offset;return{from:o,to:o+i.node.nodeValue.length,node:i.node}}function lz(t,e,r){let n=P_(t,r);if(!n)return null;let{node:s,from:i,to:o}=n,a=s.nodeValue;if(/[\n\r]/.test(a)||t.state.doc.sliceString(n.from,n.to)!=a)return null;let l=e.invertedDesc;return{range:new Xt(l.mapPos(i),l.mapPos(o),i,o),text:s}}function cz(t,e){return t.nodeType!=1?0:(e&&t.childNodes[e-1].contentEditable=="false"?1:0)|(e{ne.from&&(r=!0)}),r}class Pc extends Wl{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}}function gz(t,e,r=1){let n=t.charCategorizer(e),s=t.doc.lineAt(e),i=e-s.from;if(s.length==0)return W.cursor(e);i==0?r=1:i==s.length&&(r=-1);let o=i,a=i;r<0?o=ht(s.text,i,!1):a=ht(s.text,i);let l=n(s.text.slice(o,a));for(;o>0;){let c=ht(s.text,o,!1);if(n(s.text.slice(c,o))!=l)break;o=c}for(;at.defaultLineHeight*1.5){let a=t.viewState.heightOracle.textHeight,l=Math.floor((s-r.top-(t.defaultLineHeight-a)*.5)/a);i+=l*t.viewState.heightOracle.lineLength}let o=t.state.sliceDoc(r.from,r.to);return r.from+EL(o,i,t.state.tabSize)}function eh(t,e,r){let n=t.lineBlockAt(e);if(Array.isArray(n.type)){let s;for(let i of n.type){if(i.from>e)break;if(!(i.toe)return i;(!s||i.type==bt.Text&&(s.type!=i.type||(r<0?i.frome)))&&(s=i)}}return s||n}return n}function vz(t,e,r,n){let s=eh(t,e.head,e.assoc||-1),i=!n||s.type!=bt.Text||!(t.lineWrapping||s.widgetLineBreaks)?null:t.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(i){let o=t.dom.getBoundingClientRect(),a=t.textDirectionAt(s.from),l=t.posAtCoords({x:r==(a==We.LTR)?o.right-1:o.left+1,y:(i.top+i.bottom)/2});if(l!=null)return W.cursor(l,r?-1:1)}return W.cursor(r?s.to:s.from,r?-1:1)}function ug(t,e,r,n){let s=t.state.doc.lineAt(e.head),i=t.bidiSpans(s),o=t.textDirectionAt(s.from);for(let a=e,l=null;;){let c=WL(s,i,o,a,r),u=h_;if(!c){if(s.number==(r?t.state.doc.lines:1))return a;u=` +`,s=t.state.doc.line(s.number+(r?1:-1)),i=t.bidiSpans(s),c=t.visualLineSide(s,!r)}if(l){if(!l(u))return a}else{if(!n)return c;l=n(u)}a=c}}function wz(t,e,r){let n=t.state.charCategorizer(e),s=n(r);return i=>{let o=n(i);return s==nt.Space&&(s=o),s==o}}function _z(t,e,r,n){let s=e.head,i=r?1:-1;if(s==(r?t.state.doc.length:0))return W.cursor(s,e.assoc);let o=e.goalColumn,a,l=t.contentDOM.getBoundingClientRect(),c=t.coordsAtPos(s,e.assoc||((e.empty?r:e.head==e.from)?1:-1)),u=t.documentTop;if(c)o==null&&(o=c.left-l.left),a=i<0?c.top:c.bottom;else{let p=t.viewState.lineBlockAt(s);o==null&&(o=Math.min(l.right-l.left,t.defaultCharacterWidth*(s-p.from))),a=(i<0?p.top:p.bottom)+u}let h=l.left+o,d=t.viewState.heightOracle.textHeight>>1,f=n??d;for(let p=0;;p+=d){let y=a+(f+p)*i,v=th(t,{x:h,y},!1,i);if(r?y>l.bottom:ya:_{if(e>i&&es(t)),r.from,e.head>r.from?-1:1);return n==r.from?r:W.cursor(n,nt.viewState.docHeight)return new Mr(t.state.doc.length,-1);if(c=t.elementAtHeight(l),n==null)break;if(c.type==bt.Text){if(n<0?c.tot.viewport.to)break;let d=t.docView.coordsAt(n<0?c.from:c.to,n>0?-1:1);if(d&&(n<0?d.top<=l+i:d.bottom>=l+i))break}let h=t.viewState.heightOracle.textHeight/2;l=n>0?c.bottom+h:c.top-h}if(t.viewport.from>=c.to||t.viewport.to<=c.from){if(r)return null;if(c.type==bt.Text){let h=yz(t,s,c,o,a);return new Mr(h,h==c.from?1:-1)}}if(c.type!=bt.Text)return l<(c.top+c.bottom)/2?new Mr(c.from,1):new Mr(c.to,-1);let u=t.docView.lineAt(c.from,2);return(!u||u.length!=c.length)&&(u=t.docView.lineAt(c.from,-2)),new bz(t,o,a,t.textDirectionAt(c.from)).scanTile(u,c.from)}class bz{constructor(e,r,n,s){this.view=e,this.x=r,this.y=n,this.baseDir=s,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to1||n.length&&(n[0].level!=this.baseDir||n[0].to+s.from>1;t:if(o.has(y)){for(let _=1;_=i&&($-=p),!o.has($)){y=$;break t}}break e}o.add(y);let v=r(y),m=0;if(v)for(let _=0;_1))if($.bottomthis.y)(!c||c.top>$.top)&&(c=$),m=-1;else{let E=$.left>this.x?this.x-$.left:$.right(p+p+y)/3)return this.y=l.bottom-1,this.scan(e,r,!0);if(c&&c.top<(p+y+y)/3)return this.y=c.top+1,this.scan(e,r,!0)}let f=(a?this.dirAt(e[u],1):this.baseDir)==We.LTR;return{i:u,after:this.x>(d.left+d.right)/2==f}}scanText(e,r){let n=[];for(let i=0;i{let o=n[i]-r,a=n[i+1]-r;return io(e.dom,o,a).getClientRects()});return s.after?new Mr(n[s.i+1],-1):new Mr(n[s.i],1)}scanTile(e,r){if(!e.length)return new Mr(r,1);if(e.children.length==1){let a=e.children[0];if(a.isText())return this.scanText(a,r);if(a.isComposite())return this.scanTile(a,r)}let n=[r];for(let a=0,l=r;a{let l=e.children[a];return l.flags&48?null:(l.dom.nodeType==1?l.dom:io(l.dom,0,l.length)).getClientRects()}),i=e.children[s.i],o=n[s.i];return i.isText()?this.scanText(i,o):i.isComposite()?this.scanTile(i,o):s.after?new Mr(n[s.i+1],-1):new Mr(o,1)}}const Ss="￿";class $z{constructor(e,r){this.points=e,this.view=r,this.text="",this.lineSeparator=r.state.facet(Me.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=Ss}readRange(e,r){if(!e)return this;let n=e.parentNode;for(let s=e;;){this.findPointBefore(n,s);let i=this.text.length;this.readNode(s);let o=Ye.get(s),a=s.nextSibling;if(a==r){o!=null&&o.breakAfter&&!a&&n!=this.view.contentDOM&&this.lineBreak();break}let l=Ye.get(a);(o&&l?o.breakAfter:(o?o.breakAfter:rl(s))||rl(a)&&(s.nodeName!="BR"||o!=null&&o.isWidget())&&this.text.length>i)&&!kz(a,r)&&this.lineBreak(),s=a}return this.findPointBefore(n,r),this}readTextNode(e){let r=e.nodeValue;for(let n of this.points)n.node==e&&(n.pos=this.text.length+Math.min(n.offset,r.length));for(let n=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let i=-1,o=1,a;if(this.lineSeparator?(i=r.indexOf(this.lineSeparator,n),o=this.lineSeparator.length):(a=s.exec(r))&&(i=a.index,o=a[0].length),this.append(r.slice(n,i<0?r.length:i)),i<0)break;if(this.lineBreak(),o>1)for(let l of this.points)l.node==e&&l.pos>this.text.length&&(l.pos-=o-1);n=i+o}}readNode(e){let r=Ye.get(e),n=r&&r.overrideDOMText;if(n!=null){this.findPointInside(e,n.length);for(let s=n.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,r){for(let n of this.points)n.node==e&&e.childNodes[n.offset]==r&&(n.pos=this.text.length)}findPointInside(e,r){for(let n of this.points)(e.nodeType==3?n.node==e:e.contains(n.node))&&(n.pos=this.text.length+(Sz(e,n.node,n.offset)?r:0))}}function Sz(t,e,r){for(;;){if(!e||r-1;let{impreciseHead:i,impreciseAnchor:o}=e.docView,a=e.state.selection;if(e.state.readOnly&&r>-1)this.newSel=null;else if(r>-1&&(this.bounds=R_(e.docView.tile,r,n,0))){let l=i||o?[]:Cz(e),c=new $z(l,e);c.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=c.text,this.newSel=Pz(l,this.bounds.from)}else{let l=e.observer.selectionRange,c=i&&i.node==l.focusNode&&i.offset==l.focusOffset||!Zu(e.contentDOM,l.focusNode)?a.main.head:e.docView.posFromDOM(l.focusNode,l.focusOffset),u=o&&o.node==l.anchorNode&&o.offset==l.anchorOffset||!Zu(e.contentDOM,l.anchorNode)?a.main.anchor:e.docView.posFromDOM(l.anchorNode,l.anchorOffset),h=e.viewport;if((Y.ios||Y.chrome)&&c!=u&&Math.min(c,u)<=a.main.from&&Math.max(c,u)>=a.main.to&&(h.from>0||h.to-1&&a.ranges.length>1)this.newSel=a.replaceRange(W.range(u,c));else if(e.lineWrapping&&u==c&&!(a.main.empty&&a.main.head==c)&&e.inputState.lastTouchTime>Date.now()-100){let d=e.coordsAtPos(c,-1),f=0;d&&(f=e.inputState.lastTouchY<=d.bottom?-1:1),this.newSel=W.create([W.cursor(c,f)])}else this.newSel=W.single(u,c)}}}function R_(t,e,r,n){if(t.isComposite()){let s=-1,i=-1,o=-1,a=-1;for(let l=0,c=n,u=n;lr)return R_(h,e,r,c);if(d>=e&&s==-1&&(s=l,i=c),c>r&&h.dom.parentNode==t.dom){o=l,a=u;break}u=d,c=d+h.breakAfter}return{from:i,to:a<0?n+t.length:a,startDOM:(s?t.children[s-1].dom.nextSibling:null)||t.dom.firstChild,endDOM:o=0?t.children[o].dom:null}}else return t.isText()?{from:n,to:n+t.length,startDOM:t.dom,endDOM:t.dom.nextSibling}:null}function A_(t,e){let r,{newSel:n}=e,{state:s}=t,i=s.selection.main,o=t.inputState.lastKeyTime>Date.now()-100?t.inputState.lastKeyCode:-1;if(e.bounds){let{from:a,to:l}=e.bounds,c=i.from,u=null;(o===8||Y.android&&e.text.length=a&&i.to<=l&&(e.typeOver||h!=e.text)&&h.slice(0,i.from-a)==e.text.slice(0,i.from-a)&&h.slice(i.to-a)==e.text.slice(d=e.text.length-(h.length-(i.to-a)))?r={from:i.from,to:i.to,insert:Ie.of(e.text.slice(i.from-a,d).split(Ss))}:(f=M_(h,e.text,c-a,u))&&(Y.chrome&&o==13&&f.toB==f.from+2&&e.text.slice(f.from,f.toB)==Ss+Ss&&f.toB--,r={from:a+f.from,to:a+f.toA,insert:Ie.of(e.text.slice(f.from,f.toB).split(Ss))})}else n&&(!t.hasFocus&&s.facet(Qr)||al(n,i))&&(n=null);if(!r&&!n)return!1;if((Y.mac||Y.android)&&r&&r.from==r.to&&r.from==i.head-1&&/^\. ?$/.test(r.insert.toString())&&t.contentDOM.getAttribute("autocorrect")=="off"?(n&&r.insert.length==2&&(n=W.single(n.main.anchor-1,n.main.head-1)),r={from:r.from,to:r.to,insert:Ie.of([r.insert.toString().replace("."," ")])}):s.doc.lineAt(i.from).toDate.now()-50?r={from:i.from,to:i.to,insert:s.toText(t.inputState.insertingText)}:Y.chrome&&r&&r.from==r.to&&r.from==i.head&&r.insert.toString()==` + `&&t.lineWrapping&&(n&&(n=W.single(n.main.anchor-1,n.main.head-1)),r={from:i.from,to:i.to,insert:Ie.of([" "])}),r)return Xf(t,r,n,o);if(n&&!al(n,i)){let a=!1,l="select";return t.inputState.lastSelectionTime>Date.now()-50&&(t.inputState.lastSelectionOrigin=="select"&&(a=!0),l=t.inputState.lastSelectionOrigin,l=="select.pointer"&&(n=T_(s.facet(To).map(c=>c(t)),n))),t.dispatch({selection:n,scrollIntoView:a,userEvent:l}),!0}else return!1}function Xf(t,e,r,n=-1){if(Y.ios&&t.inputState.flushIOSKey(e))return!0;let s=t.state.selection.main;if(Y.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&t.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&Ds(t.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||n==8&&e.insert.lengths.head)&&Ds(t.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&Ds(t.contentDOM,"Delete",46)))return!0;let i=e.insert.toString();t.inputState.composing>=0&&t.inputState.composing++;let o,a=()=>o||(o=Ez(t,e,r));return t.state.facet(g_).some(l=>l(t,e.from,e.to,i,a))||t.dispatch(a()),!0}function Ez(t,e,r){let n,s=t.state,i=s.selection.main,o=-1;if(e.from==e.to&&e.fromi.to){let l=e.fromh(t)),c,l);e.from==u&&(o=u)}if(o>-1)n={changes:e,selection:W.cursor(e.from+e.insert.length,-1)};else if(e.from>=i.from&&e.to<=i.to&&e.to-e.from>=(i.to-i.from)/3&&(!r||r.main.empty&&r.main.from==e.from+e.insert.length)&&t.inputState.composing<0){let l=i.frome.to?s.sliceDoc(e.to,i.to):"";n=s.replaceSelection(t.state.toText(l+e.insert.sliceString(0,void 0,t.state.lineBreak)+c))}else{let l=s.changes(e),c=r&&r.main.to<=l.newLength?r.main:void 0;if(s.selection.ranges.length>1&&(t.inputState.composing>=0||t.inputState.compositionPendingChange)&&e.to<=i.to+10&&e.to>=i.to-10){let u=t.state.sliceDoc(e.from,e.to),h,d=r&&P_(t,r.main.head);if(d){let p=e.insert.length-(e.to-e.from);h={from:d.from,to:d.to-p}}else h=t.state.doc.lineAt(i.head);let f=i.to-e.to;n=s.changeByRange(p=>{if(p.from==i.from&&p.to==i.to)return{changes:l,range:c||p.map(l)};let y=p.to-f,v=y-u.length;if(t.state.sliceDoc(v,y)!=u||y>=h.from&&v<=h.to)return{range:p};let m=s.changes({from:v,to:y,insert:e.insert}),_=p.to-i.to;return{changes:m,range:c?W.range(Math.max(0,c.anchor+_),Math.max(0,c.head+_)):p.map(m)}})}else n={changes:l,selection:c&&s.selection.replaceRange(c)}}let a="input.type";return(t.composing||t.inputState.compositionPendingChange&&t.inputState.compositionEndedAt>Date.now()-50)&&(t.inputState.compositionPendingChange=!1,a+=".compose",t.inputState.compositionFirstChange&&(a+=".start",t.inputState.compositionFirstChange=!1)),s.update(n,{userEvent:a,scrollIntoView:!0})}function M_(t,e,r,n){let s=Math.min(t.length,e.length),i=0;for(;i0&&a>0&&t.charCodeAt(o-1)==e.charCodeAt(a-1);)o--,a--;if(n=="end"){let l=Math.max(0,i-Math.min(o,a));r-=o+l-i}if(o=o?i-r:0;i-=l,a=i+(a-o),o=i}else if(a=a?i-r:0;i-=l,o=i+(o-a),a=i}return{from:i,toA:o,toB:a}}function Cz(t){let e=[];if(t.root.activeElement!=t.contentDOM)return e;let{anchorNode:r,anchorOffset:n,focusNode:s,focusOffset:i}=t.observer.selectionRange;return r&&(e.push(new hg(r,n)),(s!=r||i!=n)&&e.push(new hg(s,i))),e}function Pz(t,e){if(t.length==0)return null;let r=t[0].pos,n=t.length==2?t[1].pos:r;return r>-1&&n>-1?W.single(r+e,n+e):null}function al(t,e){return e.head==t.main.head&&e.anchor==t.main.anchor}class Tz{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.touchActive=!1,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.lastIOSMomentumScroll=0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,Y.safari&&e.contentDOM.addEventListener("input",()=>null),Y.gecko&&Uz(e.contentDOM.ownerDocument)}handleEvent(e){!Lz(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,r){let n=this.handlers[e];if(n){for(let s of n.observers)s(this.view,r);for(let s of n.handlers){if(r.defaultPrevented)break;if(s(this.view,r)){r.preventDefault();break}}}}ensureHandlers(e){let r=Az(e),n=this.handlers,s=this.view.contentDOM;for(let i in r)if(i!="scroll"){let o=!r[i].handlers.length,a=n[i];a&&o!=!a.handlers.length&&(s.removeEventListener(i,this.handleEvent),a=null),a||s.addEventListener(i,this.handleEvent,{passive:o})}for(let i in n)i!="scroll"&&!r[i]&&s.removeEventListener(i,this.handleEvent);this.handlers=r}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&O_.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),Y.android&&Y.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;if(Y.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&(I_.some(r=>r.keyCode==e.keyCode)&&!e.ctrlKey||Mz.indexOf(e.key)>-1&&e.ctrlKey)){let r={ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey};return r.shiftKey&&Y.ios&&!/^(off|none)$/.test(this.view.contentDOM.autocapitalize)&&Rz(this.view.win)&&(r.shiftKey=!1),this.pendingIOSKey={key:e.key,keyCode:e.keyCode,mods:r},setTimeout(()=>this.flushIOSKey(),250),!0}return e.keyCode!=229&&this.view.observer.forceFlush(),!1}flushIOSKey(e){let r=this.pendingIOSKey;return!r||r.key=="Enter"&&e&&e.from0?!0:Y.safari&&!Y.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function Rz(t){return t.visualViewport?t.visualViewport.height*t.visualViewport.scale/t.document.documentElement.clientHeight<.85:!1}function dg(t,e){return(r,n)=>{try{return e.call(t,n,r)}catch(s){jr(r.state,s)}}}function Az(t){let e=Object.create(null);function r(n){return e[n]||(e[n]={observers:[],handlers:[]})}for(let n of t){let s=n.spec,i=s&&s.plugin.domEventHandlers,o=s&&s.plugin.domEventObservers;if(i)for(let a in i){let l=i[a];l&&r(a).handlers.push(dg(n.value,l))}if(o)for(let a in o){let l=o[a];l&&r(a).observers.push(dg(n.value,l))}}for(let n in mr)r(n).handlers.push(mr[n]);for(let n in Ot)r(n).observers.push(Ot[n]);return e}const I_=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],Mz="dthko",O_=[16,17,18,20,91,92,224,225],Xo=6;function ea(t){return Math.max(0,t)*.7+8}function Iz(t,e){return Math.max(Math.abs(t.clientX-e.clientX),Math.abs(t.clientY-e.clientY))}class Oz{constructor(e,r,n,s){this.view=e,this.startEvent=r,this.style=n,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=r,this.scrollParents=e_(e.contentDOM),this.atoms=e.state.facet(To).map(o=>o(e));let i=e.contentDOM.ownerDocument;i.addEventListener("mousemove",this.move=this.move.bind(this)),i.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=r.shiftKey,this.multiple=e.state.facet(Me.allowMultipleSelections)&&Nz(e,r),this.dragging=Dz(e,r)&&D_(r)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&Iz(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let r=0,n=0,s=0,i=0,o=this.view.win.innerWidth,a=this.view.win.innerHeight;this.scrollParents.x&&({left:s,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:i,bottom:a}=this.scrollParents.y.getBoundingClientRect());let l=E_(this.view);e.clientX-l.left<=s+Xo?r=-ea(s-e.clientX):e.clientX+l.right>=o-Xo&&(r=ea(e.clientX-o)),e.clientY-l.top<=i+Xo?n=-ea(i-e.clientY):e.clientY+l.bottom>=a-Xo&&(n=ea(e.clientY-a)),this.setScrollSpeed(r,n)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,r){this.scrollSpeed={x:e,y:r},e||r?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:r}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),r&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=r,r=0),(e||r)&&this.view.win.scrollBy(e,r),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:r}=this,n=T_(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!n.eq(r.state.selection,this.dragging===!1))&&this.view.dispatch({selection:n,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(r=>r.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}}function Nz(t,e){let r=t.state.facet(d_);return r.length?r[0](e):Y.mac?e.metaKey:e.ctrlKey}function jz(t,e){let r=t.state.facet(f_);return r.length?r[0](e):Y.mac?!e.altKey:!e.ctrlKey}function Dz(t,e){let{main:r}=t.state.selection;if(r.empty)return!1;let n=so(t.root);if(!n||n.rangeCount==0)return!0;let s=n.getRangeAt(0).getClientRects();for(let i=0;i=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Lz(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let r=e.target,n;r!=t.contentDOM;r=r.parentNode)if(!r||r.nodeType==11||(n=Ye.get(r))&&n.isWidget()&&!n.isHidden&&n.widget.ignoreEvent(e))return!1;return!0}const mr=Object.create(null),Ot=Object.create(null),N_=Y.ie&&Y.ie_version<15||Y.ios&&Y.webkit_version<604;function zz(t){let e=t.dom.parentNode;if(!e)return;let r=e.appendChild(document.createElement("textarea"));r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus(),setTimeout(()=>{t.focus(),r.remove(),j_(t,r.value)},50)}function Jl(t,e,r){for(let n of t.facet(e))r=n(r,t);return r}function j_(t,e){e=Jl(t.state,Gf,e);let{state:r}=t,n,s=1,i=r.toText(e),o=i.lines==r.selection.ranges.length;if(rh!=null&&r.selection.ranges.every(l=>l.empty)&&rh==i.toString()){let l=-1;n=r.changeByRange(c=>{let u=r.doc.lineAt(c.from);if(u.from==l)return{range:c};l=u.from;let h=r.toText((o?i.line(s++).text:e)+r.lineBreak);return{changes:{from:u.from,insert:h},range:W.cursor(c.from+h.length)}})}else o?n=r.changeByRange(l=>{let c=i.line(s++);return{changes:{from:l.from,to:l.to,insert:c.text},range:W.cursor(l.from+c.length)}}):n=r.replaceSelection(i);t.dispatch(n,{userEvent:"input.paste",scrollIntoView:!0})}Ot.scroll=t=>{let e=t.inputState;e.lastScrollTop=t.scrollDOM.scrollTop,e.lastScrollLeft=t.scrollDOM.scrollLeft,Y.ios&&!e.touchActive&&(e.lastIOSMomentumScroll=Date.now())};Ot.wheel=Ot.mousewheel=t=>{t.inputState.lastWheelEvent=Date.now()};mr.keydown=(t,e)=>(t.inputState.setSelectionOrigin("select"),e.keyCode==27&&t.inputState.tabFocusMode!=0&&(t.inputState.tabFocusMode=Date.now()+2e3),!1);Ot.touchstart=(t,e)=>{let r=t.inputState,n=e.targetTouches[0];r.touchActive=!0,r.lastTouchTime=Date.now(),n&&(r.lastTouchX=n.clientX,r.lastTouchY=n.clientY),r.setSelectionOrigin("select.pointer")};Ot.touchmove=t=>{t.inputState.setSelectionOrigin("select.pointer")};Ot.touchend=(t,e)=>{t.inputState.touchActive=!1};mr.mousedown=(t,e)=>{if(t.observer.flush(),t.inputState.lastTouchTime>Date.now()-2e3)return!1;let r=null;for(let n of t.state.facet(p_))if(r=n(t,e),r)break;if(!r&&e.button==0&&(r=qz(t,e)),r){let n=!t.hasFocus;t.inputState.startMouseSelection(new Oz(t,e,r,n)),n&&t.observer.ignore(()=>{n_(t.contentDOM);let i=t.root.activeElement;i&&!i.contains(t.contentDOM)&&i.blur()});let s=t.inputState.mouseSelection;if(s)return s.start(e),s.dragging===!1}else t.inputState.setSelectionOrigin("select.pointer");return!1};function fg(t,e,r,n){if(n==1)return W.cursor(e,r);if(n==2)return gz(t.state,e,r);{let s=t.docView.lineAt(e,r),i=t.state.doc.lineAt(s?s.posAtEnd:e),o=s?s.posAtStart:i.from,a=s?s.posAtEnd:i.to;return aDate.now()-400&&Math.abs(e.clientX-t.clientX)<2&&Math.abs(e.clientY-t.clientY)<2?(mg+1)%3:1}function qz(t,e){let r=t.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),n=D_(e),s=t.state.selection;return{update(i){i.docChanged&&(r.pos=i.changes.mapPos(r.pos),s=s.map(i.changes))},get(i,o,a){let l=t.posAndSideAtCoords({x:i.clientX,y:i.clientY},!1),c,u=fg(t,l.pos,l.assoc,n);if(r.pos!=l.pos&&!o){let h=fg(t,r.pos,r.assoc,n),d=Math.min(h.from,u.from),f=Math.max(h.to,u.to);u=d1&&(c=Bz(s,l.pos))?c:a?s.addRange(u):W.create([u])}}}function Bz(t,e){for(let r=0;r=e)return W.create(t.ranges.slice(0,r).concat(t.ranges.slice(r+1)),t.mainIndex==r?0:t.mainIndex-(t.mainIndex>r?1:0))}return null}mr.dragstart=(t,e)=>{let{selection:{main:r}}=t.state;if(e.target.draggable){let s=t.docView.tile.nearest(e.target);if(s&&s.isWidget()){let i=s.posAtStart,o=i+s.length;(i>=r.to||o<=r.from)&&(r=W.undirectionalRange(i,o))}}let{inputState:n}=t;return n.mouseSelection&&(n.mouseSelection.dragging=!0),n.draggedContent=r,e.dataTransfer&&(e.dataTransfer.setData("Text",Jl(t.state,Jf,t.state.sliceDoc(r.from,r.to))),e.dataTransfer.effectAllowed="copyMove"),!1};mr.dragend=t=>(t.inputState.draggedContent=null,!1);function yg(t,e,r,n){if(r=Jl(t.state,Gf,r),!r)return;let s=t.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:i}=t.inputState,o=n&&i&&jz(t,e)?{from:i.from,to:i.to}:null,a={from:s,insert:r},l=t.state.changes(o?[o,a]:a);t.focus(),t.dispatch({changes:l,selection:{anchor:l.mapPos(s,-1),head:l.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),t.inputState.draggedContent=null}mr.drop=(t,e)=>{if(!e.dataTransfer)return!1;if(t.state.readOnly)return!0;let r=e.dataTransfer.files;if(r&&r.length){let n=Array(r.length),s=0,i=()=>{++s==r.length&&yg(t,e,n.filter(o=>o!=null).join(t.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(a.result)||(n[o]=a.result),i()},a.readAsText(r[o])}return!0}else{let n=e.dataTransfer.getData("Text");if(n)return yg(t,e,n,!0),!0}return!1};mr.paste=(t,e)=>{if(t.state.readOnly)return!0;t.observer.flush();let r=N_?null:e.clipboardData;return r?(j_(t,r.getData("text/plain")||r.getData("text/uri-list")),!0):(zz(t),!1)};function Vz(t,e){let r=t.dom.parentNode;if(!r)return;let n=r.appendChild(document.createElement("textarea"));n.style.cssText="position: fixed; left: -10000px; top: 10px",n.value=e,n.focus(),n.selectionEnd=e.length,n.selectionStart=0,setTimeout(()=>{n.remove(),t.focus()},50)}function Hz(t){let e=[],r=[],n=!1;for(let s of t.selection.ranges)s.empty||(e.push(t.sliceDoc(s.from,s.to)),r.push(s));if(!e.length){let s=-1;for(let{from:i}of t.selection.ranges){let o=t.doc.lineAt(i);o.number>s&&(e.push(o.text),r.push({from:o.from,to:Math.min(t.doc.length,o.to+1)})),s=o.number}n=!0}return{text:Jl(t,Jf,e.join(t.lineBreak)),ranges:r,linewise:n}}let rh=null;mr.copy=mr.cut=(t,e)=>{if(!Vi(t.contentDOM,t.observer.selectionRange))return!1;let{text:r,ranges:n,linewise:s}=Hz(t.state);if(!r&&!s)return!1;rh=s?r:null,e.type=="cut"&&!t.state.readOnly&&t.dispatch({changes:n,scrollIntoView:!0,userEvent:"delete.cut"});let i=N_?null:e.clipboardData;return i?(i.clearData(),i.setData("text/plain",r),!0):(Vz(t,r),!1)};const L_=On.define();function z_(t,e){let r=[];for(let n of t.facet(y_)){let s=n(t,e);s&&r.push(s)}return r.length?t.update({effects:r,annotations:L_.of(!0)}):null}function F_(t){setTimeout(()=>{let e=t.hasFocus;if(e!=t.inputState.notifiedFocused){let r=z_(t.state,e);r?t.dispatch(r):t.update([])}},10)}Ot.focus=t=>{t.inputState.lastFocusTime=Date.now(),!t.scrollDOM.scrollTop&&(t.inputState.lastScrollTop||t.inputState.lastScrollLeft)&&(t.scrollDOM.scrollTop=t.inputState.lastScrollTop,t.scrollDOM.scrollLeft=t.inputState.lastScrollLeft),F_(t)};Ot.blur=t=>{t.observer.clearSelectionRange(),F_(t)};Ot.compositionstart=Ot.compositionupdate=t=>{t.observer.editContext||(t.inputState.compositionFirstChange==null&&(t.inputState.compositionFirstChange=!0),t.inputState.composing<0&&(t.inputState.composing=0))};Ot.compositionend=t=>{t.observer.editContext||(t.inputState.composing=-1,t.inputState.compositionEndedAt=Date.now(),t.inputState.compositionPendingKey=!0,t.inputState.compositionPendingChange=t.observer.pendingRecords().length>0,t.inputState.compositionFirstChange=null,Y.chrome&&Y.android?t.observer.flushSoon():t.inputState.compositionPendingChange?Promise.resolve().then(()=>t.observer.flush()):setTimeout(()=>{t.inputState.composing<0&&t.docView.hasComposition&&t.update([])},50))};Ot.contextmenu=t=>{t.inputState.lastContextMenu=Date.now()};mr.beforeinput=(t,e)=>{var r,n;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(t.inputState.insertingText=e.data,t.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&t.observer.editContext){let i=(r=e.dataTransfer)===null||r===void 0?void 0:r.getData("text/plain"),o=e.getTargetRanges();if(i&&o.length){let a=o[0],l=t.posAtDOM(a.startContainer,a.startOffset),c=t.posAtDOM(a.endContainer,a.endOffset);return Xf(t,{from:l,to:c,insert:t.state.toText(i)},null),!0}}let s;if(Y.chrome&&Y.android&&(s=I_.find(i=>i.inputType==e.inputType))&&(t.observer.delayAndroidKey(s.key,s.keyCode),s.key=="Backspace"||s.key=="Delete")){let i=((n=window.visualViewport)===null||n===void 0?void 0:n.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>i+10&&t.hasFocus&&(t.contentDOM.blur(),t.focus())},100)}return Y.ios&&e.inputType=="deleteContentForward"&&t.observer.flushSoon(),Y.safari&&e.inputType=="insertText"&&t.inputState.composing>=0&&setTimeout(()=>Ot.compositionend(t,e),20),!1};const vg=new Set;function Uz(t){vg.has(t)||(vg.add(t),t.addEventListener("copy",()=>{}),t.addEventListener("cut",()=>{}))}const wg=["pre-wrap","normal","pre-line","break-spaces"];let Js=!1;function _g(){Js=!1}class Wz{constructor(e){this.lineWrapping=e,this.doc=Ie.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,r){let n=this.doc.lineAt(r).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(n+=Math.max(0,Math.ceil((r-e-n*this.lineLength*.5)/this.lineLength))),this.lineHeight*n}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return wg.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let r=!1;for(let n=0;n-1,l=Math.abs(r-this.lineHeight)>.3||this.lineWrapping!=a;if(this.lineWrapping=a,this.lineHeight=r,this.charWidth=n,this.textHeight=s,this.lineLength=i,l){this.heightSamples={};for(let c=0;c0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>Ta&&(Js=!0),this.height=e)}replace(e,r,n){return It.of(n)}decomposeLeft(e,r){r.push(this)}decomposeRight(e,r){r.push(this)}applyChanges(e,r,n,s){let i=this,o=n.doc;for(let a=s.length-1;a>=0;a--){let{fromA:l,toA:c,fromB:u,toB:h}=s[a],d=i.lineAt(l,qe.ByPosNoHeight,n.setDoc(r),0,0),f=d.to>=c?d:i.lineAt(c,qe.ByPosNoHeight,n,0,0);for(h+=f.to-c,c=f.to;a>0&&d.from<=s[a-1].toA;)l=s[a-1].fromA,u=s[a-1].fromB,a--,li*2){let a=e[r-1];a.break?e.splice(--r,1,a.left,null,a.right):e.splice(--r,1,a.left,a.right),n+=1+a.break,s-=a.size}else if(i>s*2){let a=e[n];a.break?e.splice(n,1,a.left,null,a.right):e.splice(n,1,a.left,a.right),n+=2+a.break,i-=a.size}else break;else if(s=i&&o(this.lineAt(0,qe.ByPos,n,s,i))}setMeasuredHeight(e){let r=e.heights[e.index++];r<0?(this.spaceAbove=-r,r=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(r)}updateHeight(e,r=0,n=!1,s){return s&&s.from<=r&&s.more&&this.setMeasuredHeight(s),this.outdated=!1,this}toString(){return`block(${this.length})`}}class Ut extends q_{constructor(e,r,n){super(e,r,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=n}mainBlock(e,r){return new hr(r,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,r,n){let s=n[0];return n.length==1&&(s instanceof Ut||s instanceof mt&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof mt?s=new Ut(s.length,this.height,this.spaceAbove):s.height=this.height,this.outdated||(s.outdated=!1),s):It.of(n)}updateHeight(e,r=0,n=!1,s){return s&&s.from<=r&&s.more?this.setMeasuredHeight(s):(n||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class mt extends It{constructor(e){super(e,0)}heightMetrics(e,r){let n=e.doc.lineAt(r).number,s=e.doc.lineAt(r+this.length).number,i=s-n+1,o,a=0;if(e.lineWrapping){let l=Math.min(this.height,e.lineHeight*i);o=l/i,this.length>i+1&&(a=(this.height-l)/(this.length-i-1))}else o=this.height/i;return{firstLine:n,lastLine:s,perLine:o,perChar:a}}blockAt(e,r,n,s){let{firstLine:i,lastLine:o,perLine:a,perChar:l}=this.heightMetrics(r,s);if(r.lineWrapping){let c=s+(e0){let i=n[n.length-1];i instanceof mt?n[n.length-1]=new mt(i.length+s):n.push(null,new mt(s-1))}if(e>0){let i=n[0];i instanceof mt?n[0]=new mt(e+i.length):n.unshift(new mt(e-1),null)}return It.of(n)}decomposeLeft(e,r){r.push(new mt(e-1),null)}decomposeRight(e,r){r.push(null,new mt(this.length-e-1))}updateHeight(e,r=0,n=!1,s){let i=r+this.length;if(s&&s.from<=r+this.length&&s.more){let o=[],a=Math.max(r,s.from),l=-1;for(s.from>r&&o.push(new mt(s.from-r-1).updateHeight(e,r));a<=i&&s.more;){let u=e.doc.lineAt(a).length;o.length&&o.push(null);let h=s.heights[s.index++],d=0;h<0&&(d=-h,h=s.heights[s.index++]),l==-1?l=h:Math.abs(h-l)>=Ta&&(l=-2);let f=new Ut(u,h,d);f.outdated=!1,o.push(f),a+=u+1}a<=i&&o.push(null,new mt(i-a).updateHeight(e,a));let c=It.of(o);return(l<0||Math.abs(c.height-this.height)>=Ta||Math.abs(l-this.heightMetrics(e,r).perLine)>=Ta)&&(Js=!0),ll(this,c)}else(n||this.outdated)&&(this.setHeight(e.heightForGap(r,r+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class Gz extends It{constructor(e,r,n){super(e.length+r+n.length,e.height+n.height,r|(e.outdated||n.outdated?2:0)),this.left=e,this.right=n,this.size=e.size+n.size}get break(){return this.flags&1}blockAt(e,r,n,s){let i=n+this.left.height;return ea))return c;let u=r==qe.ByPosNoHeight?qe.ByPosNoHeight:qe.ByPos;return l?c.join(this.right.lineAt(a,u,n,o,a)):this.left.lineAt(a,u,n,s,i).join(c)}forEachLine(e,r,n,s,i,o){let a=s+this.left.height,l=i+this.left.length+this.break;if(this.break)e=l&&this.right.forEachLine(e,r,n,a,l,o);else{let c=this.lineAt(l,qe.ByPos,n,s,i);e=e&&c.from<=r&&o(c),r>c.to&&this.right.forEachLine(c.to+1,r,n,a,l,o)}}replace(e,r,n){let s=this.left.length+this.break;if(rthis.left.length)return this.balanced(this.left,this.right.replace(e-s,r-s,n));let i=[];e>0&&this.decomposeLeft(e,i);let o=i.length;for(let a of n)i.push(a);if(e>0&&bg(i,o-1),r=n&&r.push(null)),e>n&&this.right.decomposeLeft(e-n,r)}decomposeRight(e,r){let n=this.left.length,s=n+this.break;if(e>=s)return this.right.decomposeRight(e-s,r);e2*r.size||r.size>2*e.size?It.of(this.break?[e,null,r]:[e,r]):(this.left=ll(this.left,e),this.right=ll(this.right,r),this.setHeight(e.height+r.height),this.outdated=e.outdated||r.outdated,this.size=e.size+r.size,this.length=e.length+this.break+r.length,this)}updateHeight(e,r=0,n=!1,s){let{left:i,right:o}=this,a=r+i.length+this.break,l=null;return s&&s.from<=r+i.length&&s.more?l=i=i.updateHeight(e,r,n,s):i.updateHeight(e,r,n),s&&s.from<=a+o.length&&s.more?l=o=o.updateHeight(e,a,n,s):o.updateHeight(e,a,n),l?this.balanced(i,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function bg(t,e){let r,n;t[e]==null&&(r=t[e-1])instanceof mt&&(n=t[e+1])instanceof mt&&t.splice(e-1,3,new mt(r.length+1+n.length))}const Jz=5;class ep{constructor(e,r){this.pos=e,this.oracle=r,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,r){if(this.lineStart>-1){let n=Math.min(r,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof Ut?s.length+=n-this.pos:(n>this.pos||!this.isCovered)&&this.nodes.push(new Ut(n-this.pos,-1,0)),this.writtenTo=n,r>n&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=r}point(e,r,n){if(e=Jz)&&this.addLineDeco(s,i,o)}else r>e&&this.span(e,r);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:r}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=r,this.writtenToe&&this.nodes.push(new Ut(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,r){let n=new mt(r-e);return this.oracle.doc.lineAt(e).to==r&&(n.flags|=4),n}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof Ut)return e;let r=new Ut(0,-1,0);return this.nodes.push(r),r}addBlock(e){this.enterLine();let r=e.deco;r&&r.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,r&&r.endSide>0&&(this.covering=e)}addLineDeco(e,r,n){let s=this.ensureLine();s.length+=n,s.collapsed+=n,s.widgetHeight=Math.max(s.widgetHeight,e),s.breaks+=r,this.writtenTo=this.pos=this.pos+n}finish(e){let r=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(r instanceof Ut)&&!this.isCovered?this.nodes.push(new Ut(0,-1,0)):(this.writtenTou.clientHeight||u.scrollWidth>u.clientWidth)&&h.overflow!="visible"){let d=u.getBoundingClientRect();i=Math.max(i,d.left),o=Math.min(o,d.right),a=Math.max(a,d.top),l=Math.min(c==t.parentNode?s.innerHeight:l,d.bottom)}c=h.position=="absolute"||h.position=="fixed"?u.offsetParent:u.parentNode}else if(c.nodeType==11)c=c.host;else break;return{left:i-r.left,right:Math.max(i,o)-r.left,top:a-(r.top+e),bottom:Math.max(a,l)-(r.top+e)}}function eF(t){let e=t.getBoundingClientRect(),r=t.ownerDocument.defaultView||window;return e.left0&&e.top0}function tF(t,e){let r=t.getBoundingClientRect();return{left:0,right:r.right-r.left,top:e,bottom:r.bottom-(r.top+e)}}class Rc{constructor(e,r,n,s){this.from=e,this.to=r,this.size=n,this.displaySize=s}static same(e,r){if(e.length!=r.length)return!1;for(let n=0;ntypeof s!="function"&&s.class=="cm-lineWrapping");this.heightOracle=new Wz(n),this.stateDeco=kg(r),this.heightMap=It.empty().applyChanges(this.stateDeco,Ie.empty,this.heightOracle.setDoc(r.doc),[new Xt(0,0,0,r.doc.length)]);for(let s=0;s<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());s++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Ce.set(this.lineGaps.map(s=>s.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:r}=this.state.selection;for(let n=0;n<=1;n++){let s=n?r.head:r.anchor;if(!e.some(({from:i,to:o})=>s>=i&&s<=o)){let{from:i,to:o}=this.lineBlockAt(s);e.push(new ta(i,o))}}return this.viewports=e.sort((n,s)=>n.from-s.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?Sg:new tp(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(Pi(e,this.scaler))})}update(e,r=null){this.state=e.state;let n=this.stateDeco;this.stateDeco=kg(this.state);let s=e.changedRanges,i=Xt.extendWithRanges(s,Yz(n,this.stateDeco,e?e.changes:at.empty(this.state.doc.length))),o=this.heightMap.height,a=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);_g(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),i),(this.heightMap.height!=o||Js)&&(e.flags|=2),a?(this.scrollAnchorPos=e.changes.mapPos(a.from,-1),this.scrollAnchorHeight=a.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let l=i.length?this.mapViewport(this.viewport,e.changes):this.viewport;(r&&(r.range.headl.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,r));let c=l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,e.flags|=this.updateForViewport(),(c||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),r&&(this.scrollTarget=r),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(w_)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,r=e.contentDOM,n=window.getComputedStyle(r),s=this.heightOracle,i=n.whiteSpace;this.defaultTextDirection=n.direction=="rtl"?We.RTL:We.LTR;let o=this.heightOracle.mustRefreshForWrapping(i)||this.mustMeasureContent==="refresh",a=r.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let c=0,u=0;if(a.width&&a.height){let{scaleX:x,scaleY:P}=Xw(r,a);(x>.005&&Math.abs(this.scaleX-x)>.005||P>.005&&Math.abs(this.scaleY-P)>.005)&&(this.scaleX=x,this.scaleY=P,c|=16,o=l=!0)}let h=(parseInt(n.paddingTop)||0)*this.scaleY,d=(parseInt(n.paddingBottom)||0)*this.scaleY;(this.paddingTop!=h||this.paddingBottom!=d)&&(this.paddingTop=h,this.paddingBottom=d,c|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,c|=16);let f=e_(this.view.contentDOM,!1).y;f!=this.scrollParent&&(this.scrollParent=f,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=s_(this.scrollParent||e.win);let y=(this.printing?tF:Xz)(r,this.paddingTop),v=y.top-this.pixelViewport.top,m=y.bottom-this.pixelViewport.bottom;this.pixelViewport=y;let _=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(_!=this.inView&&(this.inView=_,_&&(l=!0)),!this.inView&&!this.scrollTarget&&!eF(e.dom))return 0;let $=a.width;if((this.contentDOMWidth!=$||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=a.width,this.editorHeight=e.scrollDOM.clientHeight,c|=16),l){let x=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(x)&&(o=!0),o||s.lineWrapping&&Math.abs($-this.contentDOMWidth)>s.charWidth){let{lineHeight:P,charWidth:R,textHeight:z}=e.docView.measureTextSize();o=P>0&&s.refresh(i,P,R,z,Math.max(5,$/R),x),o&&(e.docView.minWidth=0,c|=16)}v>0&&m>0?u=Math.max(v,m):v<0&&m<0&&(u=Math.min(v,m)),_g();for(let P of this.viewports){let R=P.from==this.viewport.from?x:e.docView.measureVisibleLineHeights(P);this.heightMap=(o?It.empty().applyChanges(this.stateDeco,Ie.empty,this.heightOracle,[new Xt(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new Kz(P.from,R))}Js&&(c|=2)}let E=!this.viewportIsAppropriate(this.viewport,u)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return E&&(c&2&&(c|=this.updateScaler()),this.viewport=this.getViewport(u,this.scrollTarget),c|=this.updateForViewport()),(c&2||E)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),c|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),c}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,r){let n=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,i=this.heightOracle,{visibleTop:o,visibleBottom:a}=this,l=new ta(s.lineAt(o-n*1e3,qe.ByHeight,i,0,0).from,s.lineAt(a+(1-n)*1e3,qe.ByHeight,i,0,0).to);if(r){let{head:c}=r.range;if(cl.to){let u=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),h=s.lineAt(c,qe.ByPos,i,0,0),d;r.y=="center"?d=(h.top+h.bottom)/2-u/2:r.y=="start"||r.y=="nearest"&&c=a+Math.max(10,Math.min(n,250)))&&s>o-2*1e3&&i>1,o=s<<1;if(this.defaultTextDirection!=We.LTR&&!n)return[];let a=[],l=(u,h,d,f)=>{if(h-uu&&mm.from>=d.from&&m.to<=d.to&&Math.abs(m.from-u)m.from<_&&m.to>_));if(!v){if(h$.from<=h&&$.to>=h)){let $=r.moveToLineBoundary(W.cursor(h),!1,!0).head;$>u&&(h=$)}let m=this.gapSize(d,u,h,f),_=n||m<2e6?m:2e6;v=new Rc(u,h,m,_)}a.push(v)},c=u=>{if(u.length2e6)for(let P of e)P.from>=u.from&&P.fromu.from&&l(u.from,f,u,h),pr.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let r=this.stateDeco;this.lineGaps.length&&(r=r.concat(this.lineGapDeco));let n=[];Ae.spans(r,this.viewport.from,this.viewport.to,{span(i,o){n.push({from:i,to:o})},point(){}},20);let s=0;if(n.length!=this.visibleRanges.length)s=12;else for(let i=0;i=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(r=>r.from<=e&&r.to>=e)||Pi(this.heightMap.lineAt(e,qe.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(r=>r.top<=e&&r.bottom>=e)||Pi(this.heightMap.lineAt(this.scaler.fromDOM(e),qe.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}scrollAnchorAt(e){let r=this.lineBlockAtHeight(e+8);return r.from>=this.viewport.from||this.viewportLines[0].top-e>200?r:this.viewportLines[0]}elementAtHeight(e){return Pi(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class ta{constructor(e,r){this.from=e,this.to=r}}function nF(t,e,r){let n=[],s=t,i=0;return Ae.spans(r,t,e,{span(){},point(o,a){o>s&&(n.push({from:s,to:o}),i+=o-s),s=a}},20),s=1)return e[e.length-1].to;let n=Math.floor(t*r);for(let s=0;;s++){let{from:i,to:o}=e[s],a=o-i;if(n<=a)return i+n;n-=a}}function na(t,e){let r=0;for(let{from:n,to:s}of t.ranges){if(e<=s){r+=e-n;break}r+=s-n}return r/t.total}function sF(t,e){for(let r of t)if(e(r))return r}const Sg={toDOM(t){return t},fromDOM(t){return t},scale:1,eq(t){return t==this}};function kg(t){let e=t.facet(Kl).filter(n=>typeof n!="function"),r=t.facet(Qf).filter(n=>typeof n!="function");return r.length&&e.push(Ae.join(r)),e}class tp{constructor(e,r,n){let s=0,i=0,o=0;this.viewports=n.map(({from:a,to:l})=>{let c=r.lineAt(a,qe.ByPos,e,0,0).top,u=r.lineAt(l,qe.ByPos,e,0,0).bottom;return s+=u-c,{from:a,to:l,top:c,bottom:u,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(r.height-s);for(let a of this.viewports)a.domTop=o+(a.top-i)*this.scale,o=a.domBottom=a.domTop+(a.bottom-a.top),i=a.bottom}toDOM(e){for(let r=0,n=0,s=0;;r++){let i=rr.from==e.viewports[n].from&&r.to==e.viewports[n].to):!1}}function Pi(t,e){if(e.scale==1)return t;let r=e.toDOM(t.top),n=e.toDOM(t.bottom);return new hr(t.from,t.length,r,n-r,Array.isArray(t._content)?t._content.map(s=>Pi(s,e)):t._content)}const sa=ie.define({combine:t=>t.join(" ")}),nh=ie.define({combine:t=>t.indexOf(!0)>-1}),sh=Ks.newName(),B_=Ks.newName(),V_=Ks.newName(),H_={"&light":"."+B_,"&dark":"."+V_};function ih(t,e,r){return new Ks(e,{finish(n){return/&/.test(n)?n.replace(/&\w*/,s=>{if(s=="&")return t;if(!r||!r[s])throw new RangeError(`Unsupported selector: ${s}`);return r[s]}):t+" "+n}})}const iF=ih("."+sh,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{userSelect:"none",position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},".cm-panels-top":{top:"0"},".cm-panels-bottom":{bottom:"0"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},H_),oF={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Ac=Y.ie&&Y.ie_version<=11;class aF{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new jL,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(r=>{for(let n of r)this.queue.push(n);(Y.ie&&Y.ie_version<=11||Y.ios&&e.composing)&&r.some(n=>n.type=="childList"&&n.removedNodes.length||n.type=="characterData"&&n.oldValue.length>n.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&Y.android&&e.constructor.EDIT_CONTEXT!==!1&&!(Y.chrome&&Y.chrome_version<126)&&(this.editContext=new cF(e),e.state.facet(Qr)&&(e.contentDOM.editContext=this.editContext.editContext)),Ac&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var r;((r=this.view.docView)===null||r===void 0?void 0:r.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),r.length>0&&r[r.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(r=>{r.length>0&&r[r.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((r,n)=>r!=e[n]))){this.gapIntersection.disconnect();for(let r of e)this.gapIntersection.observe(r);this.gaps=e}}onSelectionChange(e){let r=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:n}=this,s=this.selectionRange;if(n.state.facet(Qr)?n.root.activeElement!=this.dom:!Vi(this.dom,s))return;let i=s.anchorNode&&n.docView.tile.nearest(s.anchorNode);if(i&&i.isWidget()&&i.widget.ignoreEvent(e)){r||(this.selectionChanged=!1);return}(Y.ie&&Y.ie_version<=11||Y.android&&Y.chrome)&&!n.state.selection.main.empty&&s.focusNode&&Hi(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,r=so(e.root);if(!r)return!1;let n=Y.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&lF(this.view,r)||r;if(!n||this.selectionRange.eq(n))return!1;let s=Vi(this.dom,n);return s&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let i=this.delayedAndroidKey;i&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=i.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&i.force&&Ds(this.dom,i.key,i.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:r,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let r=-1,n=-1,s=!1;for(let i of e){let o=this.readMutation(i);o&&(o.typeOver&&(s=!0),r==-1?{from:r,to:n}=o:(r=Math.min(o.from,r),n=Math.max(o.to,n)))}return{from:r,to:n,typeOver:s}}readChange(){let{from:e,to:r,typeOver:n}=this.processRecords(),s=this.selectionChanged&&Vi(this.dom,this.selectionRange);if(e<0&&!s)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let i=new xz(this.view,e,r,n);return this.view.docView.domChanged={newSel:i.newSel?i.newSel.main:null},i}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let r=this.readChange();if(!r)return this.view.requestMeasure(),!1;let n=this.view.state,s=A_(this.view,r);return this.view.state==n&&(r.domChanged||r.newSel&&!al(this.view.state.selection,r.newSel.main))&&this.view.update([]),s}readMutation(e){let r=this.view.docView.tile.nearest(e.target);if(!r||r.isWidget())return null;if(r.markDirty(e.type=="attributes"),e.type=="childList"){let n=xg(r,e.previousSibling||e.target.previousSibling,-1),s=xg(r,e.nextSibling||e.target.nextSibling,1);return{from:n?r.posAfter(n):r.posAtStart,to:s?r.posBefore(s):r.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:r.posAtStart,to:r.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(Qr)!=e.state.facet(Qr)&&(e.view.contentDOM.editContext=e.state.facet(Qr)?this.editContext.editContext:null))}destroy(){var e,r,n;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(r=this.gapIntersection)===null||r===void 0||r.disconnect(),(n=this.resizeScroll)===null||n===void 0||n.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}}function xg(t,e,r){for(;e;){let n=Ye.get(e);if(n&&n.parent==t)return n;let s=e.parentNode;e=s!=t.dom?s:r>0?e.nextSibling:e.previousSibling}return null}function Eg(t,e){let r=e.startContainer,n=e.startOffset,s=e.endContainer,i=e.endOffset,o=t.docView.domAtPos(t.state.selection.main.anchor,1);return Hi(o.node,o.offset,s,i)&&([r,n,s,i]=[s,i,r,n]),{anchorNode:r,anchorOffset:n,focusNode:s,focusOffset:i}}function lF(t,e){if(e.getComposedRanges){let s=e.getComposedRanges(t.root)[0];if(s)return Eg(t,s)}let r=null;function n(s){s.preventDefault(),s.stopImmediatePropagation(),r=s.getTargetRanges()[0]}return t.contentDOM.addEventListener("beforeinput",n,!0),t.dom.ownerDocument.execCommand("indent"),t.contentDOM.removeEventListener("beforeinput",n,!0),r?Eg(t,r):null}class cF{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let r=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=n=>{let s=e.state.selection.main,{anchor:i,head:o}=s,a=this.toEditorPos(n.updateRangeStart),l=this.toEditorPos(n.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:n.updateRangeStart,editorBase:a,drifted:!1});let c=l-a>n.text.length;a==this.from&&ithis.to&&(l=i);let u=M_(e.state.sliceDoc(a,l),n.text,(c?s.from:s.to)-a,c?"end":null);if(!u){let d=W.single(this.toEditorPos(n.selectionStart),this.toEditorPos(n.selectionEnd));al(d,s)||e.dispatch({selection:d,userEvent:"select"});return}let h={from:u.from+a,to:u.toA+a,insert:Ie.of(n.text.slice(u.from,u.toB).split(` +`))};if((Y.mac||Y.android)&&h.from==o-1&&/^\. ?$/.test(n.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(h={from:a,to:l,insert:Ie.of([n.text.replace("."," ")])}),this.pendingContextChange=h,!e.state.readOnly){let d=this.to-this.from+(h.to-h.from+h.insert.length);Xf(e,h,W.single(this.toEditorPos(n.selectionStart,d),this.toEditorPos(n.selectionEnd,d)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),h.from=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(r.text.slice(Math.max(0,n.updateRangeStart-1),Math.min(r.text.length,n.updateRangeStart+1)))&&this.handlers.compositionend(n)},this.handlers.characterboundsupdate=n=>{let s=[],i=null;for(let o=this.toEditorPos(n.rangeStart),a=this.toEditorPos(n.rangeEnd);o{let s=[];for(let i of n.getTextFormats()){let o=i.underlineStyle,a=i.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(a)){let l=this.toEditorPos(i.rangeStart),c=this.toEditorPos(i.rangeEnd);if(l{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:n}=this.composing;this.composing=null,n&&this.reset(e.state)}};for(let n in this.handlers)r.addEventListener(n,this.handlers[n]);this.measureReq={read:n=>{let s=so(n.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let r=0,n=!1,s=this.pendingContextChange;return e.changes.iterChanges((i,o,a,l,c)=>{if(n)return;let u=c.length-(o-i);if(s&&o>=s.to)if(s.from==i&&s.to==o&&s.insert.eq(c)){s=this.pendingContextChange=null,r+=u,this.to+=u;return}else s=null,this.revertPending(e.state);if(i+=r,o+=r,o<=this.from)this.from+=u,this.to+=u;else if(ithis.to||this.to-this.from+c.length>3e4){n=!0;return}this.editContext.updateText(this.toContextPos(i),this.toContextPos(o),c.toString()),this.to+=u}r+=u}),s&&!n&&this.revertPending(e.state),!n}update(e){let r=this.pendingContextChange,n=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(n.from,n.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||r)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:r}=e.selection.main;this.from=Math.max(0,r-1e4),this.to=Math.min(e.doc.length,r+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let r=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(r.from),this.toContextPos(r.from+r.insert.length),e.doc.sliceString(r.from,r.to))}setSelection(e){let{main:r}=e.selection,n=this.toContextPos(Math.max(this.from,Math.min(this.to,r.anchor))),s=this.toContextPos(r.head);(this.editContext.selectionStart!=n||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(n,s)}rangeIsValid(e){let{head:r}=e.selection.main;return!(this.from>0&&r-this.from<500||this.to1e4*3)}toEditorPos(e,r=this.to-this.from){e=Math.min(e,r);let n=this.composing;return n&&n.drifted?n.editorBase+(e-n.contextBase):e+this.from}toContextPos(e){let r=this.composing;return r&&r.drifted?r.contextBase+(e-r.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}}class le{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var r;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:n}=e;this.dispatchTransactions=e.dispatchTransactions||n&&(s=>s.forEach(i=>n(i,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||DL(e.parent)||document,this.viewState=new $g(this,e.state||Me.create(e)),e.scrollTo&&e.scrollTo.is(Qo)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Ts).map(s=>new xc(s));for(let s of this.plugins)s.update(this);this.observer=new aF(this),this.inputState=new Tz(this),this.inputState.ensureHandlers(this.plugins),this.docView=new cg(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((r=document.fonts)===null||r===void 0)&&r.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let r=e.length==1&&e[0]instanceof ct?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(r,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let r=!1,n=!1,s,i=this.state;for(let d of e){if(d.startState!=i)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");i=d.state}if(this.destroyed){this.viewState.state=i;return}let o=this.hasFocus,a=0,l=null;e.some(d=>d.annotation(L_))?(this.inputState.notifiedFocused=o,a=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=z_(i,o),l||(a=1));let c=this.observer.delayedAndroidKey,u=null;if(c?(this.observer.clearDelayedAndroidKey(),u=this.observer.readChange(),(u&&!this.state.doc.eq(i.doc)||!this.state.selection.eq(i.selection))&&(u=null)):this.observer.clear(),i.facet(Me.phrases)!=this.state.facet(Me.phrases))return this.setState(i);s=sl.create(this,i,e),s.flags|=a;let h=this.viewState.scrollTarget;try{this.updateState=2;for(let d of e){if(h&&(h=h.map(d.changes)),d.scrollIntoView){let{main:f}=d.state.selection,{x:p,y}=this.state.facet(le.cursorScrollMargin);h=new Ls(f.empty?f:W.cursor(f.head,f.head>f.anchor?-1:1),"nearest","nearest",y,p)}for(let f of d.effects)f.is(Qo)&&(h=f.value.clip(this.state))}this.viewState.update(s,h),this.bidiCache=cl.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),r=this.docView.update(s),this.state.facet(Ci)!=this.styleModules&&this.mountStyles(),n=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(r,e.some(d=>d.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(sa)!=s.state.facet(sa)&&(this.viewState.mustMeasureContent=!0),(r||n||h||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),r&&this.docViewUpdate(),!s.empty)for(let d of this.state.facet(Qu))try{d(s)}catch(f){jr(this.state,f,"update listener")}(l||u)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),u&&!A_(this,u)&&c.force&&Ds(this.contentDOM,c.key,c.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let r=this.hasFocus;try{for(let n of this.plugins)n.destroy(this);this.viewState=new $g(this,e),this.plugins=e.facet(Ts).map(n=>new xc(n)),this.pluginMap.clear();for(let n of this.plugins)n.update(this);this.docView.destroy(),this.docView=new cg(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}r&&this.focus(),this.requestMeasure()}updatePlugins(e){let r=e.startState.facet(Ts),n=e.state.facet(Ts);if(r!=n){let s=[];for(let i of n){let o=r.indexOf(i);if(o<0)s.push(new xc(i));else{let a=this.plugins[o];a.mustUpdate=e,s.push(a)}}for(let i of this.plugins)i.mustUpdate!=e&&i.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let r=null,n=this.viewState.scrollParent,s=this.viewState.getScrollOffset(),{scrollAnchorPos:i,scrollAnchorHeight:o}=this.viewState;Math.abs(s-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0)if(s_(n||this.win))i=-1,o=this.viewState.heightMap.height;else{let f=this.viewState.scrollAnchorAt(s);i=f.from,o=f.top}this.updateState=1;let l=this.viewState.measure();if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let c=[];l&4||([this.measureRequests,c]=[c,this.measureRequests]);let u=c.map(f=>{try{return f.read(this)}catch(p){return jr(this.state,p),Cg}}),h=sl.create(this,this.state,[]),d=!1;h.flags|=l,r?r.flags|=l:r=h,this.updateState=2,h.empty||(this.updatePlugins(h),this.inputState.update(h),this.updateAttrs(),d=this.docView.update(h),d&&this.docViewUpdate());for(let f=0;f1||p<-1)&&!(Y.ios&&this.inputState.lastIOSMomentumScroll>Date.now()-100)&&(n==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){s=s+p,n?i<0?n.scrollTop=n.scrollHeight:n.scrollTop+=p:this.win.scrollBy(0,p),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(r&&!r.empty)for(let a of this.state.facet(Qu))a(r)}get themeClasses(){return sh+" "+(this.state.facet(nh)?V_:B_)+" "+this.state.facet(sa)}updateAttrs(){let e=Pg(this,$_,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),r={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(Qr)?"true":"false",class:"cm-content",style:`${Y.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(r["aria-readonly"]="true"),Pg(this,Yf,r);let n=this.observer.ignore(()=>{let s=ng(this.contentDOM,this.contentAttrs,r),i=ng(this.dom,this.editorAttrs,e);return s||i});return this.editorAttrs=e,this.contentAttrs=r,n}showAnnouncements(e){let r=!0;for(let n of e)for(let s of n.effects)if(s.is(le.announce)){r&&(this.announceDOM.textContent=""),r=!1;let i=this.announceDOM.appendChild(document.createElement("div"));i.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(Ci);let e=this.state.facet(le.cspNonce);Ks.mount(this.root,this.styleModules.concat(iF).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let r=0;rn.plugin==e)||null),r&&r.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,r,n){return Tc(this,e,ug(this,e,r,n))}moveByGroup(e,r){return Tc(this,e,ug(this,e,r,n=>wz(this,e.head,n)))}visualLineSide(e,r){let n=this.bidiSpans(e),s=this.textDirectionAt(e.from),i=n[r?n.length-1:0];return W.cursor(i.side(r,s)+e.from,i.forward(!r,s)?1:-1)}moveToLineBoundary(e,r,n=!0){return vz(this,e,r,n)}moveVertically(e,r,n){return Tc(this,e,_z(this,e,r,n))}domAtPos(e,r=1){return this.docView.domAtPos(e,r)}posAtDOM(e,r=0){return this.docView.posFromDOM(e,r)}posAtCoords(e,r=!0){this.readMeasured();let n=th(this,e,r);return n&&n.pos}posAndSideAtCoords(e,r=!0){return this.readMeasured(),th(this,e,r)}coordsAtPos(e,r=1){this.readMeasured();let n=this.state.doc.lineAt(e),s=this.bidiSpans(n),i=s[Nr.find(s,e-n.from,-1,r)];return this.docView.coordsAt(e,r,i.dir==We.RTL)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(v_)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>uF)return u_(e.length);let r=this.textDirectionAt(e.from),n;for(let i of this.bidiCache)if(i.from==e.from&&i.dir==r&&(i.fresh||c_(i.isolates,n=og(this,e))))return i.order;n||(n=og(this,e));let s=UL(e.text,r,n);return this.bidiCache.push(new cl(e.from,e.to,r,n,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||Y.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{n_(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,r={}){var n,s,i,o;return Qo.of(new Ls(typeof e=="number"?W.cursor(e):e,(n=r.y)!==null&&n!==void 0?n:"nearest",(s=r.x)!==null&&s!==void 0?s:"nearest",(i=r.yMargin)!==null&&i!==void 0?i:5,(o=r.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:r}=this.scrollDOM,n=this.viewState.scrollAnchorAt(e);return Qo.of(new Ls(W.cursor(n.from),"start","start",n.top-e,r,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return Kt.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return Kt.define(()=>({}),{eventObservers:e})}static theme(e,r){let n=Ks.newName(),s=[sa.of(n),Ci.of(ih(`.${n}`,e))];return r&&r.dark&&s.push(nh.of(!0)),s}static baseTheme(e){return Vl.lowest(Ci.of(ih("."+sh,e,H_)))}static findFromDOM(e){var r;let n=e.querySelector(".cm-content"),s=n&&Ye.get(n)||Ye.get(e);return((r=s==null?void 0:s.root)===null||r===void 0?void 0:r.view)||null}}le.styleModule=Ci;le.inputHandler=g_;le.clipboardInputFilter=Gf;le.clipboardOutputFilter=Jf;le.scrollHandler=__;le.focusChangeEffect=y_;le.perLineTextDirection=v_;le.exceptionSink=m_;le.updateListener=Qu;le.editable=Qr;le.mouseSelectionStyle=p_;le.dragMovesSelection=f_;le.clickAddsSelectionRange=d_;le.decorations=Kl;le.blockWrappers=S_;le.outerDecorations=Qf;le.atomicRanges=To;le.bidiIsolatedRanges=k_;le.cursorScrollMargin=ie.define({combine:t=>{let e=5,r=5;for(let n of t)typeof n=="number"?e=r=n:{x:e,y:r}=n;return{x:e,y:r}}});le.scrollMargins=x_;le.darkTheme=nh;le.cspNonce=ie.define({combine:t=>t.length?t[0]:""});le.contentAttributes=Yf;le.editorAttributes=$_;le.lineWrapping=le.contentAttributes.of({class:"cm-lineWrapping"});le.announce=Le.define();const uF=4096,Cg={};class cl{constructor(e,r,n,s,i,o){this.from=e,this.to=r,this.dir=n,this.isolates=s,this.fresh=i,this.order=o}static update(e,r){if(r.empty&&!e.some(i=>i.fresh))return e;let n=[],s=e.length?e[e.length-1].dir:We.LTR;for(let i=Math.max(0,e.length-10);i=0;s--){let i=n[s],o=typeof i=="function"?i(t):i;o&&Wf(o,r)}return r}const hF=Y.mac?"mac":Y.windows?"win":Y.linux?"linux":"key";function dF(t,e){const r=t.split(/-(?!$)/);let n=r[r.length-1];n=="Space"&&(n=" ");let s,i,o,a;for(let l=0;ln.concat(s),[]))),r}function pF(t,e,r){return K_(W_(t.state),e,t,r)}let yn=null;const mF=4e3;function gF(t,e=hF){let r=Object.create(null),n=Object.create(null),s=(o,a)=>{let l=n[o];if(l==null)n[o]=a;else if(l!=a)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},i=(o,a,l,c,u)=>{var h,d;let f=r[o]||(r[o]=Object.create(null)),p=a.split(/ (?!$)/).map(m=>dF(m,e));for(let m=1;m{let E=yn={view:$,prefix:_,scope:o};return setTimeout(()=>{yn==E&&(yn=null)},mF),!0}]})}let y=p.join(" ");s(y,!1);let v=f[y]||(f[y]={preventDefault:!1,stopPropagation:!1,run:((d=(h=f._any)===null||h===void 0?void 0:h.run)===null||d===void 0?void 0:d.slice())||[]});l&&v.run.push(l),c&&(v.preventDefault=!0),u&&(v.stopPropagation=!0)};for(let o of t){let a=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let c of a){let u=r[c]||(r[c]=Object.create(null));u._any||(u._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:h}=o;for(let d in u)u[d].run.push(f=>h(f,oh))}let l=o[e]||o.key;if(l)for(let c of a)i(c,l,o.run,o.preventDefault,o.stopPropagation),o.shift&&i(c,"Shift-"+l,o.shift,o.preventDefault,o.stopPropagation)}return r}let oh=null;function K_(t,e,r,n){oh=e;let s=RL(e),i=Nw(s,0),o=jw(i)==s.length&&s!=" ",a="",l=!1,c=!1,u=!1;yn&&yn.view==r&&yn.scope==n&&(a=yn.prefix+" ",O_.indexOf(e.keyCode)<0&&(c=!0,yn=null));let h=new Set,d=v=>{if(v){for(let m of v.run)if(!h.has(m)&&(h.add(m),m(r)))return v.stopPropagation&&(u=!0),!0;v.preventDefault&&(v.stopPropagation&&(u=!0),c=!0)}return!1},f=t[n],p,y;return f&&(d(f[a+ia(s,e,!o)])?l=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(Y.windows&&e.ctrlKey&&e.altKey)&&!(Y.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=Rn[e.keyCode])&&p!=s?(d(f[a+ia(p,e,!0)])||e.shiftKey&&(y=ro[e.keyCode])!=s&&y!=p&&d(f[a+ia(y,e,!1)]))&&(l=!0):o&&e.shiftKey&&d(f[a+ia(s,e,!0)])&&(l=!0),!l&&d(f._any)&&(l=!0)),c&&(l=!0),l&&u&&e.stopPropagation(),oh=null,l}class es{constructor(e,r,n,s,i){this.className=e,this.left=r,this.top=n,this.width=s,this.height=i}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,r){return r.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,r,n){if(n.empty){let s=e.coordsAtPos(n.head,n.assoc||1);if(!s)return[];let i=Z_(e);return[new es(r,s.left-i.left,s.top-i.top,null,s.bottom-s.top)]}else return yF(e,r,n)}}function Z_(t){let e=t.scrollDOM.getBoundingClientRect();return{left:(t.textDirection==We.LTR?e.left:e.right-t.scrollDOM.clientWidth*t.scaleX)-t.scrollDOM.scrollLeft*t.scaleX,top:e.top-t.scrollDOM.scrollTop*t.scaleY}}function Rg(t,e,r,n){let s=t.coordsAtPos(e,r*2);if(!s)return n;let i=t.dom.getBoundingClientRect(),o=(s.top+s.bottom)/2,a=t.posAtCoords({x:i.left+1,y:o}),l=t.posAtCoords({x:i.right-1,y:o});return a==null||l==null?n:{from:Math.max(n.from,Math.min(a,l)),to:Math.min(n.to,Math.max(a,l))}}function yF(t,e,r){if(r.to<=t.viewport.from||r.from>=t.viewport.to)return[];let n=Math.max(r.from,t.viewport.from),s=Math.min(r.to,t.viewport.to),i=t.textDirection==We.LTR,o=t.contentDOM,a=o.getBoundingClientRect(),l=Z_(t),c=o.querySelector(".cm-line"),u=c&&window.getComputedStyle(c),h=a.left+(u?parseInt(u.paddingLeft)+Math.min(0,parseInt(u.textIndent)):0),d=a.right-(u?parseInt(u.paddingRight):0),f=eh(t,n,1),p=eh(t,s,-1),y=f.type==bt.Text?f:null,v=p.type==bt.Text?p:null;if(y&&(t.lineWrapping||f.widgetLineBreaks)&&(y=Rg(t,n,1,y)),v&&(t.lineWrapping||p.widgetLineBreaks)&&(v=Rg(t,s,-1,v)),y&&v&&y.from==v.from&&y.to==v.to)return _($(r.from,r.to,y));{let x=y?$(r.from,null,y):E(f,!1),P=v?$(null,r.to,v):E(p,!0),R=[];return(y||f).to<(v||p).from-(y&&v?1:0)||f.widgetLineBreaks>1&&x.bottom+t.defaultLineHeight/2B&&I.from=G)break;M>Q&&O(Math.max(Ee,Q),x==null&&Ee<=B,Math.min(M,G),P==null&&M>=Z,Oe.dir)}if(Q=re.to+1,Q>=G)break}return H.length==0&&O(B,x==null,Z,P==null,t.textDirection),{top:z,bottom:L,horizontal:H}}function E(x,P){let R=a.top+(P?x.top:x.bottom);return{top:R,bottom:R,horizontal:[]}}}function vF(t,e){return t.constructor==e.constructor&&t.eq(e)}class wF{constructor(e,r){this.view=e,this.layer=r,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),r.above&&this.dom.classList.add("cm-layer-above"),r.class&&this.dom.classList.add(r.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),r.mount&&r.mount(this.dom,e)}update(e){e.startState.facet(Ra)!=e.state.facet(Ra)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let r=0,n=e.facet(Ra);for(;r!vF(r,this.drawn[n]))){let r=this.dom.firstChild,n=0;for(let s of e)s.update&&r&&s.constructor&&this.drawn[n].constructor&&s.update(r,this.drawn[n])?(r=r.nextSibling,n++):this.dom.insertBefore(s.draw(),r);for(;r;){let s=r.nextSibling;r.remove(),r=s}this.drawn=e,Y.webkit&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const Ra=ie.define();function G_(t){return[Kt.define(e=>new wF(e,t)),Ra.of(t)]}const Ys=ie.define({combine(t){return ci(t,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,r)=>Math.min(e,r),drawRangeCursor:(e,r)=>e||r})}});function _F(t={}){return[Ys.of(t),bF,$F,kF,w_.of(!0)]}function J_(t){return t.startState.facet(Ys)!=t.state.facet(Ys)}const bF=G_({above:!0,markers(t){let{state:e}=t,r=e.facet(Ys),n=[];for(let s of e.selection.ranges){let i=s==e.selection.main;if(s.empty||r.drawRangeCursor&&!(i&&Y.ios&&r.iosSelectionHandles)){let o=i?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",a=s.empty?s:W.cursor(s.head,s.assoc);for(let l of es.forRange(t,o,a))n.push(l)}}return n},update(t,e){t.transactions.some(n=>n.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let r=J_(t);return r&&Ag(t.state,e),t.docChanged||t.selectionSet||r},mount(t,e){Ag(e.state,t)},class:"cm-cursorLayer"});function Ag(t,e){e.style.animationDuration=t.facet(Ys).cursorBlinkRate+"ms"}const $F=G_({above:!1,markers(t){let e=[],{main:r,ranges:n}=t.state.selection;for(let s of n)if(!s.empty)for(let i of es.forRange(t,"cm-selectionBackground",s))e.push(i);if(Y.ios&&!r.empty&&t.state.facet(Ys).iosSelectionHandles){for(let s of es.forRange(t,"cm-selectionHandle cm-selectionHandle-start",W.cursor(r.from,1)))e.push(s);for(let s of es.forRange(t,"cm-selectionHandle cm-selectionHandle-end",W.cursor(r.to,1)))e.push(s)}return e},update(t,e){return t.docChanged||t.selectionSet||t.viewportChanged||J_(t)},class:"cm-selectionLayer"}),SF=Y.gecko&&Y.gecko_version==153?"#ffffff01":"transparent",kF=Vl.highest(le.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:`${SF} !important`},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}}));function xF(){return CF}const EF=Ce.line({class:"cm-activeLine"}),CF=Kt.fromClass(class{constructor(t){this.decorations=this.getDeco(t)}update(t){(t.docChanged||t.selectionSet)&&(this.decorations=this.getDeco(t.view))}getDeco(t){let e=-1,r=[];for(let n of t.state.selection.ranges){let s=t.lineBlockAt(n.head);s.from>e&&(r.push(EF.range(s.from)),e=s.from)}return Ce.set(r)}},{decorations:t=>t.decorations}),Mg=ie.define({combine(t){let e,r;for(let n of t)e=e||n.topContainer,r=r||n.bottomContainer;return{topContainer:e,bottomContainer:r}}});function Y_(t,e){let r=t.plugin(Q_),n=r?r.specs.indexOf(e):-1;return n>-1?r.panels[n]:null}const Q_=Kt.fromClass(class{constructor(t){this.input=t.state.facet(ul),this.specs=this.input.filter(r=>r),this.panels=this.specs.map(r=>r(t));let e=t.state.facet(Mg);this.top=new oa(t,!0,e.topContainer),this.bottom=new oa(t,!1,e.bottomContainer),this.top.sync(this.panels.filter(r=>r.top)),this.bottom.sync(this.panels.filter(r=>!r.top));for(let r of this.panels)r.dom.classList.add("cm-panel"),r.mount&&r.mount()}update(t){let e=t.state.facet(Mg);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new oa(t.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new oa(t.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let r=t.state.facet(ul);if(r!=this.input){let n=r.filter(l=>l),s=[],i=[],o=[],a=[];for(let l of n){let c=this.specs.indexOf(l),u;c<0?(u=l(t.view),a.push(u)):(u=this.panels[c],u.update&&u.update(t)),s.push(u),(u.top?i:o).push(u)}this.specs=n,this.panels=s,this.top.sync(i),this.bottom.sync(o);for(let l of a)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let n of this.panels)n.update&&n.update(t)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:t=>le.scrollMargins.of(e=>{let r=e.plugin(t);return r&&{top:r.top.scrollMargin(),bottom:r.bottom.scrollMargin()}})});class oa{constructor(e,r,n){this.view=e,this.top=r,this.container=n,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let r of this.panels)r.destroy&&e.indexOf(r)<0&&r.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom";let r=this.container||this.view.dom;r.insertBefore(this.dom,this.top?r.firstChild:null)}let e=this.dom.firstChild;for(let r of this.panels)if(r.dom.parentNode==this.dom){for(;e!=r.dom;)e=Ig(e);e=e.nextSibling}else this.dom.insertBefore(r.dom,e);for(;e;)e=Ig(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}}function Ig(t){let e=t.nextSibling;return t.remove(),e}const ul=ie.define({enables:Q_});function PF(t,e){let r,n=new Promise(o=>r=o),s=o=>TF(o,e,r);t.state.field(Mc,!1)?t.dispatch({effects:X_.of(s)}):t.dispatch({effects:Le.appendConfig.of(Mc.init(()=>[s]))});let i=eb.of(s);return{close:i,result:n.then(o=>((t.win.queueMicrotask||(l=>t.win.setTimeout(l,10)))(()=>{t.state.field(Mc).indexOf(s)>-1&&t.dispatch({effects:i})}),o))}}const Mc=Vr.define({create(){return[]},update(t,e){for(let r of e.effects)r.is(X_)?t=[r.value].concat(t):r.is(eb)&&(t=t.filter(n=>n!=r.value));return t},provide:t=>ul.computeN([t],e=>e.field(t))}),X_=Le.define(),eb=Le.define();function TF(t,e,r){let n=e.content?e.content(t,()=>o(null)):null;if(!n){if(n=ut("form"),e.input){let a=ut("input",e.input);/^(text|password|number|email|tel|url)$/.test(a.type)&&a.classList.add("cm-textfield"),a.name||(a.name="input"),n.appendChild(ut("label",(e.label||"")+": ",a))}else n.appendChild(document.createTextNode(e.label||""));n.appendChild(document.createTextNode(" ")),n.appendChild(ut("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let s=n.nodeName=="FORM"?[n]:n.querySelectorAll("form");for(let a=0;a{c.keyCode==27?(c.preventDefault(),o(null)):c.keyCode==13&&(c.preventDefault(),o(l))}),l.addEventListener("submit",c=>{c.preventDefault(),o(l)})}let i=ut("div",n,ut("button",{onclick:()=>o(null),"aria-label":t.state.phrase("close"),class:"cm-dialog-close",type:"button"},["×"]));e.class&&(i.className=e.class),i.classList.add("cm-dialog");function o(a){i.contains(i.ownerDocument.activeElement)&&t.focus(),r(a)}return{dom:i,top:e.top,mount:()=>{if(e.focus){let a;typeof e.focus=="string"?a=n.querySelector(e.focus):a=n.querySelector("input")||n.querySelector("button"),a&&"select"in a?a.select():a&&"focus"in a&&a.focus()}}}}class ds extends ls{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}ds.prototype.elementClass="";ds.prototype.toDOM=void 0;ds.prototype.mapMode=Wt.TrackBefore;ds.prototype.startSide=ds.prototype.endSide=-1;ds.prototype.point=!0;const Ic=ie.define(),RF=ie.define(),Aa=ie.define(),Og=ie.define({combine:t=>t.some(e=>e)});function AF(t){return[MF]}const MF=Kt.fromClass(class{constructor(t){this.view=t,this.domAfter=null,this.prevViewport=t.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=t.state.facet(Aa).map(e=>new jg(t,e)),this.fixed=!t.state.facet(Og);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),t.scrollDOM.insertBefore(this.dom,t.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(t){if(this.updateGutters(t)){let e=this.prevViewport,r=t.view.viewport,n=Math.min(e.to,r.to)-Math.max(e.from,r.from);this.syncGutters(n<(r.to-r.from)*.8)}if(t.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(Og)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=t.view.viewport}syncGutters(t){let e=this.dom.nextSibling;t&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let r=Ae.iter(this.view.state.facet(Ic),this.view.viewport.from),n=[],s=this.gutters.map(i=>new IF(i,this.view.viewport,-this.view.documentPadding.top));for(let i of this.view.viewportLineBlocks)if(n.length&&(n=[]),Array.isArray(i.type)){let o=!0;for(let a of i.type)if(a.type==bt.Text&&o){ah(r,n,a.from);for(let l of s)l.line(this.view,a,n);o=!1}else if(a.widget)for(let l of s)l.widget(this.view,a)}else if(i.type==bt.Text){ah(r,n,i.from);for(let o of s)o.line(this.view,i,n)}else if(i.widget)for(let o of s)o.widget(this.view,i);for(let i of s)i.finish();t&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(t){let e=t.startState.facet(Aa),r=t.state.facet(Aa),n=t.docChanged||t.heightChanged||t.viewportChanged||!Ae.eq(t.startState.facet(Ic),t.state.facet(Ic),t.view.viewport.from,t.view.viewport.to);if(e==r)for(let s of this.gutters)s.update(t)&&(n=!0);else{n=!0;let s=[];for(let i of r){let o=e.indexOf(i);o<0?s.push(new jg(this.view,i)):(this.gutters[o].update(t),s.push(this.gutters[o]))}for(let i of this.gutters)i.dom.remove(),s.indexOf(i)<0&&i.destroy();for(let i of s)i.config.side=="after"?this.getDOMAfter().appendChild(i.dom):this.dom.appendChild(i.dom);this.gutters=s}return n}destroy(){for(let t of this.gutters)t.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:t=>le.scrollMargins.of(e=>{let r=e.plugin(t);if(!r||r.gutters.length==0||!r.fixed)return null;let n=r.dom.offsetWidth*e.scaleX,s=r.domAfter?r.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==We.LTR?{left:n,right:s}:{right:n,left:s}})});function Ng(t){return Array.isArray(t)?t:[t]}function ah(t,e,r){for(;t.value&&t.from<=r;)t.from==r&&e.push(t.value),t.next()}class IF{constructor(e,r,n){this.gutter=e,this.height=n,this.i=0,this.cursor=Ae.iter(e.markers,r.from)}addElement(e,r,n){let{gutter:s}=this,i=(r.top-this.height)/e.scaleY,o=r.height/e.scaleY;if(this.i==s.elements.length){let a=new tb(e,o,i,n);s.elements.push(a),s.dom.appendChild(a.dom)}else s.elements[this.i].update(e,o,i,n);this.height=r.bottom,this.i++}line(e,r,n){let s=[];ah(this.cursor,s,r.from),n.length&&(s=s.concat(n));let i=this.gutter.config.lineMarker(e,r,s);i&&s.unshift(i);let o=this.gutter;s.length==0&&!o.config.renderEmptyElements||this.addElement(e,r,s)}widget(e,r){let n=this.gutter.config.widgetMarker(e,r.widget,r),s=n?[n]:null;for(let i of e.state.facet(RF)){let o=i(e,r.widget,r);o&&(s||(s=[])).push(o)}s&&this.addElement(e,r,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let r=e.elements.pop();e.dom.removeChild(r.dom),r.destroy()}}}class jg{constructor(e,r){this.view=e,this.config=r,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let n in r.domEventHandlers)this.dom.addEventListener(n,s=>{let i=s.target,o;if(i!=this.dom&&this.dom.contains(i)){for(;i.parentNode!=this.dom;)i=i.parentNode;let l=i.getBoundingClientRect();o=(l.top+l.bottom)/2}else o=s.clientY;let a=e.lineBlockAtHeight(o-e.documentTop);r.domEventHandlers[n](e,a,s)&&s.preventDefault()});this.markers=Ng(r.markers(e)),r.initialSpacer&&(this.spacer=new tb(e,0,0,[r.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let r=this.markers;if(this.markers=Ng(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let n=e.view.viewport;return!Ae.eq(this.markers,r,n.from,n.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class tb{constructor(e,r,n,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,r,n,s)}update(e,r,n,s){this.height!=r&&(this.height=r,this.dom.style.height=r+"px"),this.above!=n&&(this.dom.style.marginTop=(this.above=n)?n+"px":""),OF(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,r){let n="cm-gutterElement",s=this.dom.firstChild;for(let i=0,o=0;;){let a=o,l=ii(a,l,c)||o(a,l,c):o}return n}})}});class Oc extends ds{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function Nc(t,e){return t.state.facet(Rs).formatNumber(e,t.state)}const DF=Aa.compute([Rs],t=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(NF)},lineMarker(e,r,n){return n.some(s=>s.toDOM)?null:new Oc(Nc(e,e.state.doc.lineAt(r.from).number))},widgetMarker:(e,r,n)=>{for(let s of e.state.facet(jF)){let i=s(e,r,n);if(i)return i}return null},lineMarkerChange:e=>e.startState.facet(Rs)!=e.state.facet(Rs),initialSpacer(e){return new Oc(Nc(e,Dg(e.state.doc.lines)))},updateSpacer(e,r){let n=Nc(r.view,Dg(r.view.state.doc.lines));return n==e.number?e:new Oc(n)},domEventHandlers:t.facet(Rs).domEventHandlers,side:"before"}));function LF(t={}){return[Rs.of(t),AF(),DF]}function Dg(t){let e=9;for(;e{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=Bt.match(e)),r=>{let n=e(r);return n===void 0?null:[this,n]}}}Re.closedBy=new Re({deserialize:t=>t.split(" ")});Re.openedBy=new Re({deserialize:t=>t.split(" ")});Re.group=new Re({deserialize:t=>t.split(" ")});Re.isolate=new Re({deserialize:t=>{if(t&&t!="rtl"&&t!="ltr"&&t!="auto")throw new RangeError("Invalid value for isolate: "+t);return t||"auto"}});Re.contextHash=new Re({perNode:!0});Re.lookAhead=new Re({perNode:!0});Re.mounted=new Re({perNode:!0});class Wi{constructor(e,r,n,s=!1){this.tree=e,this.overlay=r,this.parser=n,this.bracketed=s}static get(e){return e&&e.props&&e.props[Re.mounted.id]}}const qF=Object.create(null);class Bt{constructor(e,r,n,s=0){this.name=e,this.props=r,this.id=n,this.flags=s}static define(e){let r=e.props&&e.props.length?Object.create(null):qF,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new Bt(e.name||"",r,e.id,n);if(e.props){for(let i of e.props)if(Array.isArray(i)||(i=i(s)),i){if(i[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");r[i[0].id]=i[1]}}return s}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let r=this.prop(Re.group);return r?r.indexOf(e)>-1:!1}return this.id==e}static match(e){let r=Object.create(null);for(let n in e)for(let s of n.split(" "))r[s]=e[n];return n=>{for(let s=n.prop(Re.group),i=-1;i<(s?s.length:0);i++){let o=r[i<0?n.name:s[i]];if(o)return o}}}}Bt.none=new Bt("",Object.create(null),0,8);class rp{constructor(e){this.types=e;for(let r=0;r0;for(let l=this.cursor(o|rt.IncludeAnonymous);;){let c=!1;if(l.from<=i&&l.to>=s&&(!a&&l.type.isAnonymous||r(l)!==!1)){if(l.firstChild())continue;c=!0}for(;c&&n&&(a||!l.type.isAnonymous)&&n(l),!l.nextSibling();){if(!l.parent())return;c=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let r in this.props)e.push([+r,this.props[r]]);return e}balance(e={}){return this.children.length<=8?this:ip(Bt.none,this.children,this.positions,0,this.children.length,0,this.length,(r,n,s)=>new Ke(this.type,r,n,s,this.propValues),e.makeTree||((r,n,s)=>new Ke(Bt.none,r,n,s)))}static build(e){return UF(e)}}Ke.empty=new Ke(Bt.none,[],[],0);class np{constructor(e,r){this.buffer=e,this.index=r}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new np(this.buffer,this.index)}}class Mn{constructor(e,r,n){this.buffer=e,this.length=r,this.set=n}get type(){return Bt.none}toString(){let e=[];for(let r=0;r0));l=o[l+3]);return a}slice(e,r,n){let s=this.buffer,i=new Uint16Array(r-e),o=0;for(let a=e,l=0;a=e&&re;case 1:return r<=e&&n>e;case 2:return n>e;case 4:return!0}}function oo(t,e,r,n){for(var s;t.from==t.to||(r<1?t.from>=e:t.from>e)||(r>-1?t.to<=e:t.to0?a.length:-1;e!=c;e+=r){let u=a[e],h=l[e]+o.from,d;if(!(!(i&rt.EnterBracketed&&u instanceof Ke&&(d=Wi.get(u))&&!d.overlay&&d.bracketed&&n>=h&&n<=h+u.length)&&!rb(s,n,h,h+u.length))){if(u instanceof Mn){if(i&rt.ExcludeBuffers)continue;let f=u.findChild(0,u.buffer.length,r,n-h,s);if(f>-1)return new kn(new BF(o,u,e,h),null,f)}else if(i&rt.IncludeAnonymous||!u.type.isAnonymous||sp(u)){let f;if(!(i&rt.IgnoreMounts)&&(f=Wi.get(u))&&!f.overlay)return new tr(f.tree,h,e,o);let p=new tr(u,h,e,o);return i&rt.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(r<0?u.children.length-1:0,r,n,s,i)}}}if(i&rt.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+r:e=r<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,r,n=0){let s;if(!(n&rt.IgnoreOverlays)&&(s=Wi.get(this._tree))&&s.overlay){let i=e-this.from,o=n&rt.EnterBracketed&&s.bracketed;for(let{from:a,to:l}of s.overlay)if((r>0||o?a<=i:a=i:l>i))return new tr(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,r,n)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function zg(t,e,r,n){let s=t.cursor(),i=[];if(!s.firstChild())return i;if(r!=null){for(let o=!1;!o;)if(o=s.type.is(r),!s.nextSibling())return i}for(;;){if(n!=null&&s.type.is(n))return i;if(s.type.is(e)&&i.push(s.node),!s.nextSibling())return n==null?i:[]}}function lh(t,e,r=e.length-1){for(let n=t;r>=0;n=n.parent){if(!n)return!1;if(!n.type.isAnonymous){if(e[r]&&e[r]!=n.name)return!1;r--}}return!0}class BF{constructor(e,r,n,s){this.parent=e,this.buffer=r,this.index=n,this.start=s}}class kn extends nb{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,r,n){super(),this.context=e,this._parent=r,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}child(e,r,n){let{buffer:s}=this.context,i=s.findChild(this.index+4,s.buffer[this.index+3],e,r-this.context.start,n);return i<0?null:new kn(this.context,this,i)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,r,n=0){if(n&rt.ExcludeBuffers)return null;let{buffer:s}=this.context,i=s.findChild(this.index+4,s.buffer[this.index+3],r>0?1:-1,e-this.context.start,r);return i<0?null:new kn(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,r=e.buffer[this.index+3];return r<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new kn(this.context,this._parent,r):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,r=this._parent?this._parent.index+4:0;return this.index==r?this.externalSibling(-1):new kn(this.context,this._parent,e.findChild(r,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],r=[],{buffer:n}=this.context,s=this.index+4,i=n.buffer[this.index+3];if(i>s){let o=n.buffer[this.index+1];e.push(n.slice(s,i,o)),r.push(0)}return new Ke(this.type,e,r,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function sb(t){if(!t.length)return null;let e=0,r=t[0];for(let i=1;ir.from||o.to=e){let a=new tr(o.tree,o.overlay[0].from+i.from,-1,i);(s||(s=[n])).push(oo(a,e,r,!1))}}return s?sb(s):n}class ch{get name(){return this.type.name}constructor(e,r=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=r&~rt.EnterBracketed,e instanceof tr)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let n=e._parent;n;n=n._parent)this.stack.unshift(n.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,r){this.index=e;let{start:n,buffer:s}=this.buffer;return this.type=r||s.set.types[s.buffer[e]],this.from=n+s.buffer[e+1],this.to=n+s.buffer[e+2],!0}yield(e){return e?e instanceof tr?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,r,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,r,n,this.mode));let{buffer:s}=this.buffer,i=s.findChild(this.index+4,s.buffer[this.index+3],e,r-this.buffer.start,n);return i<0?!1:(this.stack.push(this.index),this.yieldBuf(i))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,r,n=this.mode){return this.buffer?n&rt.ExcludeBuffers?!1:this.enterChild(1,e,r):this.yield(this._tree.enter(e,r,n))}parent(){if(!this.buffer)return this.yieldNode(this.mode&rt.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&rt.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:r}=this.buffer,n=this.stack.length-1;if(e<0){let s=n<0?0:this.stack[n]+4;if(this.index!=s)return this.yieldBuf(r.findChild(s,this.index,-1,0,4))}else{let s=r.buffer[this.index+3];if(s<(n<0?r.buffer.length:r.buffer[this.stack[n]+3]))return this.yieldBuf(s)}return n<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let r,n,{buffer:s}=this;if(s){if(e>0){if(this.index-1)for(let i=r+e,o=e<0?-1:n._tree.children.length;i!=o;i+=e){let a=n._tree.children[i];if(this.mode&rt.IncludeAnonymous||a instanceof Mn||!a.type.isAnonymous||sp(a))return!1}return!0}move(e,r){if(r&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,r=0){for(;(this.from==this.to||(r<1?this.from>=e:this.from>e)||(r>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==s){if(s==this.index)return o;r=o,n=i+1;break e}s=this.stack[--i]}for(let s=n;s=0;i--){if(i<0)return lh(this._tree,e,s);let o=n[r.buffer[this.stack[i]]];if(!o.isAnonymous){if(e[s]&&e[s]!=o.name)return!1;s--}}return!0}}function sp(t){return t.children.some(e=>e instanceof Mn||!e.type.isAnonymous||sp(e))}function UF(t){var e;let{buffer:r,nodeSet:n,maxBufferLength:s=zF,reused:i=[],minRepeatType:o=n.types.length}=t,a=Array.isArray(r)?new np(r,r.length):r,l=n.types,c=0,u=0;function h(x,P,R,z,L,H){let{id:O,start:B,end:Z,size:I}=a,Q=u,G=c;if(I<0)if(a.next(),I==-1){let S=i[O];R.push(S),z.push(B-x);return}else if(I==-3){c=O;return}else if(I==-4){u=O;return}else throw new RangeError(`Unrecognized record size: ${I}`);let re=l[O],Oe,Ee,M=B-x;if(Z-B<=s&&(Ee=v(a.pos-P,L))){let S=new Uint16Array(Ee.size-Ee.skip),A=a.pos-Ee.size,k=S.length;for(;a.pos>A;)k=m(Ee.start,S,k);Oe=new Mn(S,Z-Ee.start,n),M=Ee.start-x}else{let S=a.pos-I;a.next();let A=[],k=[],g=O>=o?O:-1,w=0,C=Z;for(;a.pos>S;)g>=0&&a.id==g&&a.size>=0?(a.end<=C-s&&(p(A,k,B,w,a.end,C,g,Q,G),w=A.length,C=a.end),a.next()):H>2500?d(B,S,A,k):h(B,S,A,k,g,H+1);if(g>=0&&w>0&&w-1&&w>0){let V=f(re,G);Oe=ip(re,A,k,0,A.length,0,Z-B,V,V)}else Oe=y(re,A,k,Z-B,Q-Z,G)}R.push(Oe),z.push(M)}function d(x,P,R,z){let L=[],H=0,O=-1;for(;a.pos>P;){let{id:B,start:Z,end:I,size:Q}=a;if(Q>4)a.next();else{if(O>-1&&Z=0;I-=3)B[Q++]=L[I],B[Q++]=L[I+1]-Z,B[Q++]=L[I+2]-Z,B[Q++]=Q;R.push(new Mn(B,L[2]-Z,n)),z.push(Z-x)}}function f(x,P){return(R,z,L)=>{let H=0,O=R.length-1,B,Z;if(O>=0&&(B=R[O])instanceof Ke){if(!O&&B.type==x&&B.length==L)return B;(Z=B.prop(Re.lookAhead))&&(H=z[O]+B.length+Z)}return y(x,R,z,L,H,P)}}function p(x,P,R,z,L,H,O,B,Z){let I=[],Q=[];for(;x.length>z;)I.push(x.pop()),Q.push(P.pop()+R-L);x.push(y(n.types[O],I,Q,H-L,B-H,Z)),P.push(L-R)}function y(x,P,R,z,L,H,O){if(H){let B=[Re.contextHash,H];O=O?[B].concat(O):[B]}if(L>25){let B=[Re.lookAhead,L];O=O?[B].concat(O):[B]}return new Ke(x,P,R,z,O)}function v(x,P){let R=a.fork(),z=0,L=0,H=0,O=R.end-s,B={size:0,start:0,skip:0};e:for(let Z=R.pos-x;R.pos>Z;){let I=R.size;if(R.id==P&&I>=0){B.size=z,B.start=L,B.skip=H,H+=4,z+=4,R.next();continue}let Q=R.pos-I;if(I<0||Q=o?4:0,re=R.start;for(R.next();R.pos>Q;){if(R.size<0)if(R.size==-3||R.size==-4)G+=4;else break e;else R.id>=o&&(G+=4);R.next()}L=re,z+=I,H+=G}return(P<0||z==x)&&(B.size=z,B.start=L,B.skip=H),B.size>4?B:void 0}function m(x,P,R){let{id:z,start:L,end:H,size:O}=a;if(a.next(),O>=0&&z4){let Z=a.pos-(O-4);for(;a.pos>Z;)R=m(x,P,R)}P[--R]=B,P[--R]=H-x,P[--R]=L-x,P[--R]=z}else O==-3?c=z:O==-4&&(u=z);return R}let _=[],$=[];for(;a.pos>0;)h(t.start||0,t.bufferStart||0,_,$,-1,0);let E=(e=t.length)!==null&&e!==void 0?e:_.length?$[0]+_[0].length:0;return new Ke(l[t.topID],_.reverse(),$.reverse(),E)}const Fg=new WeakMap;function Ma(t,e){if(!t.isAnonymous||e instanceof Mn||e.type!=t)return 1;let r=Fg.get(e);if(r==null){r=1;for(let n of e.children){if(n.type!=t||!(n instanceof Ke)){r=1;break}r+=Ma(t,n)}Fg.set(e,r)}return r}function ip(t,e,r,n,s,i,o,a,l){let c=0;for(let p=n;p=u)break;P+=R}if($==E+1){if(P>u){let R=p[E];f(R.children,R.positions,0,R.children.length,y[E]+_);continue}h.push(p[E])}else{let R=y[$-1]+p[$-1].length-x;h.push(ip(t,p,y,E,$,x,R,null,l))}d.push(x+_-i)}}return f(e,r,n,s,0),(a||l)(h,d,o)}class ts{constructor(e,r,n,s,i=!1,o=!1){this.from=e,this.to=r,this.tree=n,this.offset=s,this.open=(i?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,r=[],n=!1){let s=[new ts(0,e.length,e,0,!1,n)];for(let i of r)i.to>e.length&&s.push(i);return s}static applyChanges(e,r,n=128){if(!r.length)return e;let s=[],i=1,o=e.length?e[0]:null;for(let a=0,l=0,c=0;;a++){let u=a=n)for(;o&&o.from=d.from||h<=d.to||c){let f=Math.max(d.from,l)-c,p=Math.min(d.to,h)-c;d=f>=p?null:new ts(f,p,d.tree,d.offset+c,a>0,!!u)}if(d&&s.push(d),o.to>h)break;o=inew jc(s.from,s.to)):[new jc(0,0)]:[new jc(0,e.length)],this.createParse(e,r||[],n)}parse(e,r,n){let s=this.startParse(e,r,n);for(;;){let i=s.advance();if(i)return i}}}class WF{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,r){return this.string.slice(e,r)}}new Re({perNode:!0});let KF=0;class Qt{constructor(e,r,n,s){this.name=e,this.set=r,this.base=n,this.modified=s,this.id=KF++}toString(){let{name:e}=this;for(let r of this.modified)r.name&&(e=`${r.name}(${e})`);return e}static define(e,r){let n=typeof e=="string"?e:"?";if(e instanceof Qt&&(r=e),r!=null&&r.base)throw new Error("Can not derive from a modified tag");let s=new Qt(n,[],null,[]);if(s.set.push(s),r)for(let i of r.set)s.set.push(i);return s}static defineModifier(e){let r=new hl(e);return n=>n.modified.indexOf(r)>-1?n:hl.get(n.base||n,n.modified.concat(r).sort((s,i)=>s.id-i.id))}}let ZF=0;class hl{constructor(e){this.name=e,this.instances=[],this.id=ZF++}static get(e,r){if(!r.length)return e;let n=r[0].instances.find(a=>a.base==e&&GF(r,a.modified));if(n)return n;let s=[],i=new Qt(e.name,s,e,r);for(let a of r)a.instances.push(i);let o=JF(r);for(let a of e.set)if(!a.modified.length)for(let l of o)s.push(hl.get(a,l));return i}}function GF(t,e){return t.length==e.length&&t.every((r,n)=>r==e[n])}function JF(t){let e=[[]];for(let r=0;rn.length-r.length)}function YF(t){let e=Object.create(null);for(let r in t){let n=t[r];Array.isArray(n)||(n=[n]);for(let s of r.split(" "))if(s){let i=[],o=2,a=s;for(let h=0;;){if(a=="..."&&h>0&&h+3==s.length){o=1;break}let d=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!d)throw new RangeError("Invalid path: "+s);if(i.push(d[0]=="*"?"":d[0][0]=='"'?JSON.parse(d[0]):d[0]),h+=d[0].length,h==s.length)break;let f=s[h++];if(h==s.length&&f=="!"){o=0;break}if(f!="/")throw new RangeError("Invalid path: "+s);a=s.slice(h)}let l=i.length-1,c=i[l];if(!c)throw new RangeError("Invalid path: "+s);let u=new dl(n,o,l>0?i.slice(0,l):null);e[c]=u.sort(e[c])}}return QF.add(e)}const QF=new Re({combine(t,e){let r,n,s;for(;t||e;){if(!t||e&&t.depth>=e.depth?(s=e,e=e.next):(s=t,t=t.next),r&&r.mode==s.mode&&!s.context&&!r.context)continue;let i=new dl(s.tags,s.mode,s.context);r?r.next=i:n=i,r=i}return n}});class dl{constructor(e,r,n,s){this.tags=e,this.mode=r,this.context=n,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=s;for(let a of i)for(let l of a.set){let c=r[l.id];if(c){o=o?o+" "+c:c;break}}return o},scope:n}}const J=Qt.define,la=J(),pn=J(),qg=J(pn),Bg=J(pn),mn=J(),ca=J(mn),Dc=J(mn),Cr=J(),qn=J(Cr),xr=J(),Er=J(),uh=J(),_i=J(uh),ua=J(),we={comment:la,lineComment:J(la),blockComment:J(la),docComment:J(la),name:pn,variableName:J(pn),typeName:qg,tagName:J(qg),propertyName:Bg,attributeName:J(Bg),className:J(pn),labelName:J(pn),namespace:J(pn),macroName:J(pn),literal:mn,string:ca,docString:J(ca),character:J(ca),attributeValue:J(ca),number:Dc,integer:J(Dc),float:J(Dc),bool:J(mn),regexp:J(mn),escape:J(mn),color:J(mn),url:J(mn),keyword:xr,self:J(xr),null:J(xr),atom:J(xr),unit:J(xr),modifier:J(xr),operatorKeyword:J(xr),controlKeyword:J(xr),definitionKeyword:J(xr),moduleKeyword:J(xr),operator:Er,derefOperator:J(Er),arithmeticOperator:J(Er),logicOperator:J(Er),bitwiseOperator:J(Er),compareOperator:J(Er),updateOperator:J(Er),definitionOperator:J(Er),typeOperator:J(Er),controlOperator:J(Er),punctuation:uh,separator:J(uh),bracket:_i,angleBracket:J(_i),squareBracket:J(_i),paren:J(_i),brace:J(_i),content:Cr,heading:qn,heading1:J(qn),heading2:J(qn),heading3:J(qn),heading4:J(qn),heading5:J(qn),heading6:J(qn),contentSeparator:J(Cr),list:J(Cr),quote:J(Cr),emphasis:J(Cr),strong:J(Cr),link:J(Cr),monospace:J(Cr),strikethrough:J(Cr),inserted:J(),deleted:J(),changed:J(),invalid:J(),meta:ua,documentMeta:J(ua),annotation:J(ua),processingInstruction:J(ua),definition:Qt.defineModifier("definition"),constant:Qt.defineModifier("constant"),function:Qt.defineModifier("function"),standard:Qt.defineModifier("standard"),local:Qt.defineModifier("local"),special:Qt.defineModifier("special")};for(let t in we){let e=we[t];e instanceof Qt&&(e.name=t)}XF([{tag:we.link,class:"tok-link"},{tag:we.heading,class:"tok-heading"},{tag:we.emphasis,class:"tok-emphasis"},{tag:we.strong,class:"tok-strong"},{tag:we.keyword,class:"tok-keyword"},{tag:we.atom,class:"tok-atom"},{tag:we.bool,class:"tok-bool"},{tag:we.url,class:"tok-url"},{tag:we.labelName,class:"tok-labelName"},{tag:we.inserted,class:"tok-inserted"},{tag:we.deleted,class:"tok-deleted"},{tag:we.literal,class:"tok-literal"},{tag:we.string,class:"tok-string"},{tag:we.number,class:"tok-number"},{tag:[we.regexp,we.escape,we.special(we.string)],class:"tok-string2"},{tag:we.variableName,class:"tok-variableName"},{tag:we.local(we.variableName),class:"tok-variableName tok-local"},{tag:we.definition(we.variableName),class:"tok-variableName tok-definition"},{tag:we.special(we.variableName),class:"tok-variableName2"},{tag:we.definition(we.propertyName),class:"tok-propertyName tok-definition"},{tag:we.typeName,class:"tok-typeName"},{tag:we.namespace,class:"tok-namespace"},{tag:we.className,class:"tok-className"},{tag:we.macroName,class:"tok-macroName"},{tag:we.propertyName,class:"tok-propertyName"},{tag:we.operator,class:"tok-operator"},{tag:we.comment,class:"tok-comment"},{tag:we.meta,class:"tok-meta"},{tag:we.invalid,class:"tok-invalid"},{tag:we.punctuation,class:"tok-punctuation"}]);var Lc;const Ti=new Re;function eq(t){return ie.define({combine:t?e=>e.concat(t):void 0})}const tq=new Re;class Dr{constructor(e,r,n=[],s=""){this.data=e,this.name=s,Me.prototype.hasOwnProperty("tree")||Object.defineProperty(Me.prototype,"tree",{get(){return In(this)}}),this.parser=r,this.extension=[ei.of(this),Me.languageData.of((i,o,a)=>{let l=Vg(i,o,a),c=l.type.prop(Ti);if(!c)return[];let u=i.facet(c),h=l.type.prop(tq);if(h){let d=l.resolve(o-l.from,a);for(let f of h)if(f.test(d,i)){let p=i.facet(f.facet);return f.type=="replace"?p:p.concat(u)}}return u})].concat(n)}isActiveAt(e,r,n=-1){return Vg(e,r,n).type.prop(Ti)==this.data}findRegions(e){let r=e.facet(ei);if((r==null?void 0:r.data)==this.data)return[{from:0,to:e.doc.length}];if(!r||!r.allowsNesting)return[];let n=[],s=(i,o)=>{if(i.prop(Ti)==this.data){n.push({from:o,to:o+i.length});return}let a=i.prop(Re.mounted);if(a){if(a.tree.prop(Ti)==this.data){if(a.overlay)for(let l of a.overlay)n.push({from:l.from+o,to:l.to+o});else n.push({from:o,to:o+i.length});return}else if(a.overlay){let l=n.length;if(s(a.tree,a.overlay[0].from+o),n.length>l)return}}for(let l=0;l=this.cursorPos?this.doc.sliceString(e,r):this.string.slice(e-n,r-n)}}let bi=null;class Qs{constructor(e,r,n=[],s,i,o,a,l){this.parser=e,this.state=r,this.fragments=n,this.tree=s,this.treeLen=i,this.viewport=o,this.skipped=a,this.scheduleOn=l,this.parse=null,this.tempSkipped=[]}static create(e,r,n){return new Qs(e,r,[],Ke.empty,0,n,[],null)}startParse(){return this.parser.startParse(new rq(this.state.doc),this.fragments)}work(e,r){return r!=null&&r>=this.state.doc.length&&(r=void 0),this.tree!=Ke.empty&&this.isDone(r??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var n;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}for(this.parse||(this.parse=this.startParse()),r!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>r)&&r=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(r=this.parse.advance()););}),this.treeLen=e,this.tree=r,this.fragments=this.withoutTempSkipped(ts.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let r=bi;bi=this;try{return e()}finally{bi=r}}withoutTempSkipped(e){for(let r;r=this.tempSkipped.pop();)e=Hg(e,r.from,r.to);return e}changes(e,r){let{fragments:n,tree:s,treeLen:i,viewport:o,skipped:a}=this;if(this.takeTree(),!e.empty){let l=[];if(e.iterChangedRanges((c,u,h,d)=>l.push({fromA:c,toA:u,fromB:h,toB:d})),n=ts.applyChanges(n,l),s=Ke.empty,i=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){a=[];for(let c of this.skipped){let u=e.mapPos(c.from,1),h=e.mapPos(c.to,-1);ue.from&&(this.fragments=Hg(this.fragments,s,i),this.skipped.splice(n--,1))}return this.skipped.length>=r?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,r){this.skipped.push({from:e,to:r})}static getSkippingParser(e){return new class extends ib{createParse(r,n,s){let i=s[0].from,o=s[s.length-1].to;return{parsedPos:i,advance(){let l=bi;if(l){for(let c of s)l.tempSkipped.push(c);e&&(l.scheduleOn=l.scheduleOn?Promise.all([l.scheduleOn,e]):e)}return this.parsedPos=o,new Ke(Bt.none,[],[],o-i)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let r=this.fragments;return this.treeLen>=e&&r.length&&r[0].from==0&&r[0].to>=e}static get(){return bi}}function Hg(t,e,r){return ts.applyChanges(t,[{fromA:e,toA:r,fromB:e,toB:r}])}class Xs{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let r=this.context.changes(e.changes,e.state),n=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),r.viewport.to);return r.work(20,n)||r.takeTree(),new Xs(r)}static init(e){let r=Math.min(3e3,e.doc.length),n=Qs.create(e.facet(ei).parser,e,{from:0,to:r});return n.work(20,r)||n.takeTree(),new Xs(n)}}Dr.state=Vr.define({create:Xs.init,update(t,e){for(let r of e.effects)if(r.is(Dr.setState))return r.value;return e.startState.facet(ei)!=e.state.facet(ei)?Xs.init(e.state):t.apply(e)}});let ob=t=>{let e=setTimeout(()=>t(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(ob=t=>{let e=-1,r=setTimeout(()=>{e=requestIdleCallback(t,{timeout:400})},100);return()=>e<0?clearTimeout(r):cancelIdleCallback(e)});const zc=typeof navigator<"u"&&(!((Lc=navigator.scheduling)===null||Lc===void 0)&&Lc.isInputPending)?()=>navigator.scheduling.isInputPending():null,nq=Kt.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let r=this.view.state.field(Dr.state).context;(r.updateViewport(e.view.viewport)||this.view.viewport.to>r.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(r)}scheduleWork(){if(this.working)return;let{state:e}=this.view,r=e.field(Dr.state);(r.tree!=r.context.tree||!r.context.isDone(e.doc.length))&&(this.working=ob(this.work))}work(e){this.working=null;let r=Date.now();if(this.chunkEnds+1e3,l=i.context.work(()=>zc&&zc()||Date.now()>o,s+(a?0:1e5));this.chunkBudget-=Date.now()-r,(l||this.chunkBudget<=0)&&(i.context.takeTree(),this.view.dispatch({effects:Dr.setState.of(new Xs(i.context))})),this.chunkBudget>0&&!(l&&!a)&&this.scheduleWork(),this.checkAsyncSchedule(i.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(r=>jr(this.view.state,r)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),ei=ie.define({combine(t){return t.length?t[0]:null},enables:t=>[Dr.state,nq,le.contentAttributes.compute([t],e=>{let r=e.facet(t);return r&&r.name?{"data-language":r.name}:{}})]}),sq=ie.define(),op=ie.define({combine:t=>{if(!t.length)return" ";let e=t[0];if(!e||/\S/.test(e)||Array.from(e).some(r=>r!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(t[0]));return e}});function fs(t){let e=t.facet(op);return e.charCodeAt(0)==9?t.tabSize*e.length:e.length}function fl(t,e){let r="",n=t.tabSize,s=t.facet(op)[0];if(s==" "){for(;e>=n;)r+=" ",e-=n;s=" "}for(let i=0;i=e?iq(t,r,e):null}class Yl{constructor(e,r={}){this.state=e,this.options=r,this.unit=fs(e)}lineAt(e,r=1){let n=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:i}=this.options;return s!=null&&s>=n.from&&s<=n.to?i&&s==e?{text:"",from:e}:(r<0?s-1&&(i+=o-this.countColumn(n,n.search(/\S|$/))),i}countColumn(e,r=e.length){return Hl(e,this.state.tabSize,r)}lineIndent(e,r=1){let{text:n,from:s}=this.lineAt(e,r),i=this.options.overrideIndentation;if(i){let o=i(s);if(o>-1)return o}return this.countColumn(n,n.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const lb=new Re;function iq(t,e,r){let n=e.resolveStack(r),s=e.resolveInner(r,-1).resolve(r,0).enterUnfinishedNodesBefore(r);if(s!=n.node){let i=[];for(let o=s;o&&!(o.fromn.node.to||o.from==n.node.from&&o.type==n.node.type);o=o.parent)i.push(o);for(let o=i.length-1;o>=0;o--)n={node:i[o],next:n}}return cb(n,t,r)}function cb(t,e,r){for(let n=t;n;n=n.next){let s=aq(n.node);if(s)return s(ap.create(e,r,n))}return 0}function oq(t){return t.pos==t.options.simulateBreak&&t.options.simulateDoubleBreak}function aq(t){let e=t.type.prop(lb);if(e)return e;let r=t.firstChild,n;if(r&&(n=r.type.prop(Re.closedBy))){let s=t.lastChild,i=s&&n.indexOf(s.name)>-1;return o=>hq(o,!0,1,void 0,i&&!oq(o)?s.from:void 0)}return t.parent==null?lq:null}function lq(){return 0}class ap extends Yl{constructor(e,r,n){super(e.state,e.options),this.base=e,this.pos=r,this.context=n}get node(){return this.context.node}static create(e,r,n){return new ap(e,r,n)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let r=this.state.doc.lineAt(e.from);for(;;){let n=e.resolve(r.from);for(;n.parent&&n.parent.from==n.from;)n=n.parent;if(cq(n,e))break;r=this.state.doc.lineAt(n.from)}return this.lineIndent(r.from)}continue(){return cb(this.context.next,this.base,this.pos)}}function cq(t,e){for(let r=e;r;r=r.parent)if(t==r)return!0;return!1}function uq(t){let e=t.node,r=e.childAfter(e.from),n=e.lastChild;if(!r)return null;let s=t.options.simulateBreak,i=t.state.doc.lineAt(r.from),o=s==null||s<=i.from?i.to:Math.min(i.to,s);for(let a=r.to;;){let l=e.childAfter(a);if(!l||l==n)return null;if(!l.type.isSkipped){if(l.from>=o)return null;let c=/^ */.exec(i.text.slice(r.to-i.from))[0].length;return{from:r.from,to:r.to+c}}a=l.to}}function hq(t,e,r,n,s){let i=t.textAfter,o=i.match(/^\s*/)[0].length,a=n&&i.slice(o,o+n.length)==n||s==t.pos+o,l=uq(t);return l?a?t.column(l.from):t.column(l.to):t.baseIndent+(a?0:t.unit*r)}const dq=le.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),ub=1e4,hb="()[]{}",db=ie.define({combine(t){return ci(t,{afterCursor:!0,brackets:hb,maxScanDistance:ub,renderMatch:mq})}}),fq=Ce.mark({class:"cm-matchingBracket"}),pq=Ce.mark({class:"cm-nonmatchingBracket"});function mq(t){let e=[],r=t.matched?fq:pq;return e.push(r.range(t.start.from,t.start.to)),t.end&&e.push(r.range(t.end.from,t.end.to)),e}function Ug(t){let e=[],r=t.facet(db);for(let n of t.selection.ranges){if(!n.empty)continue;let s=Lr(t,n.head,-1,r)||n.head>0&&Lr(t,n.head-1,1,r)||r.afterCursor&&(Lr(t,n.head,1,r)||n.headt.decorations}),yq=[gq,dq];function vq(t={}){return[db.of(t),yq]}const wq=new Re;function hh(t,e,r){let n=t.prop(e<0?Re.openedBy:Re.closedBy);if(n)return n;if(t.name.length==1){let s=r.indexOf(t.name);if(s>-1&&s%2==(e<0?1:0))return[r[s+e]]}return null}function dh(t){let e=t.type.prop(wq);return e?e(t.node):t}function Lr(t,e,r,n={}){let s=n.maxScanDistance||ub,i=n.brackets||hb,o=In(t),a=o.resolveInner(e,r);for(let l=a;l;l=l.parent){let c=hh(l.type,r,i);if(c&&l.from0?e>=u.from&&eu.from&&e<=u.to))return _q(t,e,r,l,u,c,i)}}return bq(t,e,r,o,a.type,s,i)}function _q(t,e,r,n,s,i,o){let a=n.parent,l={from:s.from,to:s.to},c=0,u=a==null?void 0:a.cursor();if(u&&(r<0?u.childBefore(n.from):u.childAfter(n.to)))do if(r<0?u.to<=n.from:u.from>=n.to){if(c==0&&i.indexOf(u.type.name)>-1&&u.from0)return null;let c={from:r<0?e-1:e,to:r>0?e+1:e},u=t.doc.iterRange(e,r>0?t.doc.length:0),h=0;for(let d=0;!u.next().done&&d<=i;){let f=u.value;r<0&&(d+=f.length);let p=e+d*r;for(let y=r>0?0:f.length-1,v=r>0?f.length:-1;y!=v;y+=r){let m=o.indexOf(f[y]);if(!(m<0||n.resolveInner(p+y,1).type!=s))if(m%2==0==r>0)h++;else{if(h==1)return{start:c,end:{from:p+y,to:p+y+1},matched:m>>1==l>>1};h--}}r>0&&(d+=f.length)}return u.done?{start:c,matched:!1}:null}function Wg(t,e,r,n=0,s=0){e==null&&(e=t.search(/[^\s\u00a0]/),e==-1&&(e=t.length));let i=s;for(let o=n;o=this.string.length}sol(){return this.pos==0}peek(){return this.string.charAt(this.pos)||void 0}next(){if(this.posr}eatSpace(){let e=this.pos;for(;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e}skipToEnd(){this.pos=this.string.length}skipTo(e){let r=this.string.indexOf(e,this.pos);if(r>-1)return this.pos=r,!0}backUp(e){this.pos-=e}column(){return this.lastColumnPosn?o.toLowerCase():o,i=this.string.substr(this.pos,e.length);return s(i)==s(e)?(r!==!1&&(this.pos+=e.length),!0):null}else{let s=this.string.slice(this.pos).match(e);return s&&s.index>0?null:(s&&r!==!1&&(this.pos+=s[0].length),s)}}current(){return this.string.slice(this.start,this.pos)}}function $q(t){return{name:t.name||"",token:t.token,blankLine:t.blankLine||(()=>{}),startState:t.startState||(()=>!0),copyState:t.copyState||Sq,indent:t.indent||(()=>null),languageData:t.languageData||{},tokenTable:t.tokenTable||up,mergeTokens:t.mergeTokens!==!1}}function Sq(t){if(typeof t!="object")return t;let e={};for(let r in t){let n=t[r];e[r]=n instanceof Array?n.slice():n}return e}const Kg=new WeakMap;class lp extends Dr{constructor(e){let r=eq(e.languageData),n=$q(e),s,i=new class extends ib{createParse(o,a,l){return new xq(s,o,a,l)}};super(r,i,[],e.name),this.topNode=Pq(r,this),s=this,this.streamParser=n,this.stateAfter=new Re({perNode:!0}),this.tokenTable=e.tokenTable?new yb(n.tokenTable):Cq}static define(e){return new lp(e)}getIndent(e){let r,{overrideIndentation:n}=e.options;n&&(r=Kg.get(e.state),r!=null&&r1e4)return null;for(;i=n&&r+e.length<=s&&e.prop(t.stateAfter);if(i)return{state:t.streamParser.copyState(i),pos:r+e.length};for(let o=e.children.length-1;o>=0;o--){let a=e.children[o],l=r+e.positions[o],c=a instanceof Ke&&l=e.length)return e;!s&&r==0&&e.type==t.topNode&&(s=!0);for(let i=e.children.length-1;i>=0;i--){let o=e.positions[i],a=e.children[i],l;if(or&&cp(t,i.tree,0-i.offset,r,a),c;if(l&&l.pos<=n&&(c=pb(t,i.tree,r+i.offset,l.pos+i.offset,!1)))return{state:l.state,tree:c}}return{state:t.streamParser.startState(s?fs(s):4),tree:Ke.empty}}class xq{constructor(e,r,n,s){this.lang=e,this.input=r,this.fragments=n,this.ranges=s,this.stoppedAt=null,this.chunks=[],this.chunkPos=[],this.chunk=[],this.chunkReused=void 0,this.rangeIndex=0,this.to=s[s.length-1].to;let i=Qs.get(),o=s[0].from,{state:a,tree:l}=kq(e,n,o,this.to,i==null?void 0:i.state);this.state=a,this.parsedPos=this.chunkStart=o+l.length;for(let c=0;cc.from<=i.viewport.from&&c.to>=i.viewport.from)&&(this.state=this.lang.streamParser.startState(fs(i.state)),i.skipUntilInView(this.parsedPos,i.viewport.from),this.parsedPos=i.viewport.from),this.moveRangeIndex()}advance(){let e=Qs.get(),r=this.stoppedAt==null?this.to:Math.min(this.to,this.stoppedAt),n=Math.min(r,this.chunkStart+512);for(e&&(n=Math.min(n,e.viewport.to));this.parsedPos=r?this.finish():e&&this.parsedPos>=e.viewport.to?(e.skipUntilInView(this.parsedPos,r),this.finish()):null}stopAt(e){this.stoppedAt=e}lineAfter(e){let r=this.input.chunk(e);if(this.input.lineChunks)r==` +`&&(r="");else{let n=r.indexOf(` +`);n>-1&&(r=r.slice(0,n))}return e+r.length<=this.to?r:r.slice(0,this.to-e)}nextLine(){let e=this.parsedPos,r=this.lineAfter(e),n=e+r.length;for(let s=this.rangeIndex;;){let i=this.ranges[s].to;if(i>=n||(r=r.slice(0,i-(n-r.length)),s++,s==this.ranges.length))break;let o=this.ranges[s].from,a=this.lineAfter(o);r+=a,n=o+a.length}return{line:r,end:n}}skipGapsTo(e,r,n){for(;;){let s=this.ranges[this.rangeIndex].to,i=e+r;if(n>0?s>i:s>=i)break;let o=this.ranges[++this.rangeIndex].from;r+=o-s}return r}moveRangeIndex(){for(;this.ranges[this.rangeIndex].to1){s=this.skipGapsTo(r,s,1),r+=s;let a=this.chunk.length;s=this.skipGapsTo(n,s,-1),n+=s,i+=this.chunk.length-a}let o=this.chunk.length-4;return this.lang.streamParser.mergeTokens&&i==4&&o>=0&&this.chunk[o]==e&&this.chunk[o+2]==r?this.chunk[o+2]=n:this.chunk.push(e,r,n,i),s}parseLine(e){let{line:r,end:n}=this.nextLine(),s=0,{streamParser:i}=this.lang,o=new fb(r,e?e.state.tabSize:4,e?fs(e.state):2);if(o.eol())i.blankLine(this.state,o.indentUnit);else for(;!o.eol();){let a=mb(i.token,o,this.state);if(a&&(s=this.emitToken(this.lang.tokenTable.resolve(a),this.parsedPos+o.start,this.parsedPos+o.pos,s)),o.start>1e4)break}this.parsedPos=n,this.moveRangeIndex(),this.parsedPose.start)return s}throw new Error("Stream parser failed to advance stream.")}const up=Object.create(null),ao=[Bt.none],Eq=new rp(ao),Zg=[],Gg=Object.create(null),gb=Object.create(null);for(let[t,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])gb[t]=vb(up,e);class yb{constructor(e){this.extra=e,this.table=Object.assign(Object.create(null),gb)}resolve(e){return e?this.table[e]||(this.table[e]=vb(this.extra,e)):0}}const Cq=new yb(up);function Fc(t,e){Zg.indexOf(t)>-1||(Zg.push(t),console.warn(e))}function vb(t,e){let r=[];for(let a of e.split(" ")){let l=[];for(let c of a.split(".")){let u=t[c]||we[c];u?typeof u=="function"?l.length?l=l.map(u):Fc(c,`Modifier ${c} used at start of tag`):l.length?Fc(c,`Tag ${c} used as modifier`):l=Array.isArray(u)?u:[u]:Fc(c,`Unknown highlighting tag ${c}`)}for(let c of l)r.push(c)}if(!r.length)return 0;let n=e.replace(/ /g,"_"),s=n+" "+r.map(a=>a.id),i=Gg[s];if(i)return i.id;let o=Gg[s]=Bt.define({id:ao.length,name:n,props:[YF({[n]:r})]});return ao.push(o),o.id}function Pq(t,e){let r=Bt.define({id:ao.length,name:"Document",props:[Ti.add(()=>t),lb.add(()=>n=>e.getIndent(n))],top:!0});return ao.push(r),r}We.RTL,We.LTR;const Tq=t=>{let{state:e}=t,r=e.doc.lineAt(e.selection.main.from),n=dp(t.state,r.from);return n.line?Rq(t):n.block?Mq(t):!1};function hp(t,e){return({state:r,dispatch:n})=>{if(r.readOnly)return!1;let s=t(e,r);return s?(n(r.update(s)),!0):!1}}const Rq=hp(Nq,0),Aq=hp(wb,0),Mq=hp((t,e)=>wb(t,e,Oq(e)),0);function dp(t,e){let r=t.languageDataAt("commentTokens",e,1);return r.length?r[0]:{}}const $i=50;function Iq(t,{open:e,close:r},n,s){let i=t.sliceDoc(n-$i,n),o=t.sliceDoc(s,s+$i),a=/\s*$/.exec(i)[0].length,l=/^\s*/.exec(o)[0].length,c=i.length-a;if(i.slice(c-e.length,c)==e&&o.slice(l,l+r.length)==r)return{open:{pos:n-a,margin:a&&1},close:{pos:s+l,margin:l&&1}};let u,h;s-n<=2*$i?u=h=t.sliceDoc(n,s):(u=t.sliceDoc(n,n+$i),h=t.sliceDoc(s-$i,s));let d=/^\s*/.exec(u)[0].length,f=/\s*$/.exec(h)[0].length,p=h.length-f-r.length;return u.slice(d,d+e.length)==e&&h.slice(p,p+r.length)==r?{open:{pos:n+d+e.length,margin:/\s/.test(u.charAt(d+e.length))?1:0},close:{pos:s-f-r.length,margin:/\s/.test(h.charAt(p-1))?1:0}}:null}function Oq(t){let e=[];for(let r of t.selection.ranges){let n=t.doc.lineAt(r.from),s=r.to<=n.to?n:t.doc.lineAt(r.to);s.from>n.from&&s.from==r.to&&(s=r.to==n.to+1?n:t.doc.lineAt(r.to-1));let i=e.length-1;i>=0&&e[i].to>n.from?e[i].to=s.to:e.push({from:n.from+/^\s*/.exec(n.text)[0].length,to:s.to})}return e}function wb(t,e,r=e.selection.ranges){let n=r.map(i=>dp(e,i.from).block);if(!n.every(i=>i))return null;let s=r.map((i,o)=>Iq(e,n[o],i.from,i.to));if(t!=2&&!s.every(i=>i))return{changes:e.changes(r.map((i,o)=>s[o]?[]:[{from:i.from,insert:n[o].open+" "},{from:i.to,insert:" "+n[o].close}]))};if(t!=1&&s.some(i=>i)){let i=[];for(let o=0,a;os&&(i==o||o>h.from)){s=h.from;let d=/^\s*/.exec(h.text)[0].length,f=d==h.length,p=h.text.slice(d,d+c.length)==c?d:-1;di.comment<0&&(!i.empty||i.single))){let i=[];for(let{line:a,token:l,indent:c,empty:u,single:h}of n)(h||!u)&&i.push({from:a.from+c,insert:l+" "});let o=e.changes(i);return{changes:o,selection:e.selection.map(o,1)}}else if(t!=1&&n.some(i=>i.comment>=0)){let i=[];for(let{line:o,comment:a,token:l}of n)if(a>=0){let c=o.from+a,u=c+l.length;o.text[u-o.from]==" "&&u++,i.push({from:c,to:u})}return{changes:i}}return null}const fh=On.define(),jq=On.define(),Dq=ie.define(),_b=ie.define({combine(t){return ci(t,{minDepth:100,newGroupDelay:500,joinToEvent:(e,r)=>r},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,r)=>(n,s)=>e(n,s)||r(n,s)})}}),bb=Vr.define({create(){return zr.empty},update(t,e){let r=e.state.facet(_b),n=e.annotation(fh);if(n){let l=qt.fromTransaction(e,n.selection),c=n.side,u=c==0?t.undone:t.done;return l?u=pl(u,u.length,r.minDepth,l):u=kb(u,e.startState.selection),new zr(c==0?n.rest:u,c==0?u:n.rest)}let s=e.annotation(jq);if((s=="full"||s=="before")&&(t=t.isolate()),e.annotation(ct.addToHistory)===!1)return e.changes.empty?t:t.addMapping(e.changes.desc);let i=qt.fromTransaction(e),o=e.annotation(ct.time),a=e.annotation(ct.userEvent);return i?t=t.addChanges(i,o,a,r,e):e.selection&&(t=t.addSelection(e.startState.selection,o,a,r.newGroupDelay)),(s=="full"||s=="after")&&(t=t.isolate()),t},toJSON(t){return{done:t.done.map(e=>e.toJSON()),undone:t.undone.map(e=>e.toJSON())}},fromJSON(t){return new zr(t.done.map(qt.fromJSON),t.undone.map(qt.fromJSON))}});function Lq(t={}){return[bb,_b.of(t),le.domEventHandlers({beforeinput(e,r){let n=e.inputType=="historyUndo"?$b:e.inputType=="historyRedo"?ph:null;return n?(e.preventDefault(),n(r)):!1}})]}function Ql(t,e){return function({state:r,dispatch:n}){if(!e&&r.readOnly)return!1;let s=r.field(bb,!1);if(!s)return!1;let i=s.pop(t,r,e);return i?(n(i),!0):!1}}const $b=Ql(0,!1),ph=Ql(1,!1),zq=Ql(0,!0),Fq=Ql(1,!0);class qt{constructor(e,r,n,s,i){this.changes=e,this.effects=r,this.mapped=n,this.startSelection=s,this.selectionsAfter=i}setSelAfter(e){return new qt(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,r,n;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(r=this.mapped)===null||r===void 0?void 0:r.toJSON(),startSelection:(n=this.startSelection)===null||n===void 0?void 0:n.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new qt(e.changes&&at.fromJSON(e.changes),[],e.mapped&&Fr.fromJSON(e.mapped),e.startSelection&&W.fromJSON(e.startSelection),e.selectionsAfter.map(W.fromJSON))}static fromTransaction(e,r){let n=er;for(let s of e.startState.facet(Dq)){let i=s(e);i.length&&(n=n.concat(i))}return!n.length&&e.changes.empty?null:new qt(e.changes.invert(e.startState.doc),n,void 0,r||e.startState.selection,er)}static selection(e){return new qt(void 0,er,void 0,void 0,e)}}function pl(t,e,r,n){let s=e+1>r+20?e-r-1:0,i=t.slice(s,e);return i.push(n),i}function qq(t,e){let r=[],n=!1;return t.iterChangedRanges((s,i)=>r.push(s,i)),e.iterChangedRanges((s,i,o,a)=>{for(let l=0;l=c&&o<=u&&(n=!0)}}),n}function Bq(t,e){return t.ranges.length==e.ranges.length&&t.ranges.filter((r,n)=>r.empty!=e.ranges[n].empty).length===0}function Sb(t,e){return t.length?e.length?t.concat(e):t:e}const er=[],Vq=200;function kb(t,e){if(t.length){let r=t[t.length-1],n=r.selectionsAfter.slice(Math.max(0,r.selectionsAfter.length-Vq));return n.length&&n[n.length-1].eq(e)?t:(n.push(e),pl(t,t.length-1,1e9,r.setSelAfter(n)))}else return[qt.selection([e])]}function Hq(t){let e=t[t.length-1],r=t.slice();return r[t.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),r}function qc(t,e){if(!t.length)return t;let r=t.length,n=er;for(;r;){let s=Uq(t[r-1],e,n);if(s.changes&&!s.changes.empty||s.effects.length){let i=t.slice(0,r);return i[r-1]=s,i}else e=s.mapped,r--,n=s.selectionsAfter}return n.length?[qt.selection(n)]:er}function Uq(t,e,r){let n=Sb(t.selectionsAfter.length?t.selectionsAfter.map(a=>a.map(e)):er,r);if(!t.changes)return qt.selection(n);let s=t.changes.map(e),i=e.mapDesc(t.changes,!0),o=t.mapped?t.mapped.composeDesc(i):i;return new qt(s,Le.mapEffects(t.effects,e),o,t.startSelection.map(i),n)}const Wq=/^(input\.type|delete)($|\.)/;class zr{constructor(e,r,n=0,s=void 0){this.done=e,this.undone=r,this.prevTime=n,this.prevUserEvent=s}isolate(){return this.prevTime?new zr(this.done,this.undone):this}addChanges(e,r,n,s,i){let o=this.done,a=o[o.length-1];return a&&a.changes&&!a.changes.empty&&e.changes&&(!n||Wq.test(n))&&(!a.selectionsAfter.length&&r-this.prevTime0&&r-this.prevTimer.empty?t.moveByChar(r,e):Xl(r,e))}function Pt(t){return t.textDirectionAt(t.state.selection.main.head)==We.LTR}const Eb=t=>xb(t,!Pt(t)),Cb=t=>xb(t,Pt(t));function Pb(t,e){return yr(t,r=>r.empty?t.moveByGroup(r,e):Xl(r,e))}const Zq=t=>Pb(t,!Pt(t)),Gq=t=>Pb(t,Pt(t));function Jq(t,e,r){if(e.type.prop(r))return!0;let n=e.to-e.from;return n&&(n>2||/[^\s,.;:]/.test(t.sliceDoc(e.from,e.to)))||e.firstChild}function ec(t,e,r){let n=In(t).resolveInner(e.head),s=r?Re.closedBy:Re.openedBy;for(let l=e.head;;){let c=r?n.childAfter(l):n.childBefore(l);if(!c)break;Jq(t,c,s)?n=c:l=r?c.to:c.from}let i=n.type.prop(s),o,a;return i&&(o=r?Lr(t,n.from,1):Lr(t,n.to,-1))&&o.matched?a=r?o.end.to:o.end.from:a=r?n.to:n.from,W.cursor(a,r?-1:1)}const Yq=t=>yr(t,e=>ec(t.state,e,!Pt(t))),Qq=t=>yr(t,e=>ec(t.state,e,Pt(t)));function Tb(t,e){return yr(t,r=>{if(!r.empty)return Xl(r,e);let n=t.moveVertically(r,e);return n.head!=r.head?n:t.moveToLineBoundary(r,e)})}const Rb=t=>Tb(t,!1),Ab=t=>Tb(t,!0);function Mb(t){let e=t.scrollDOM.clientHeighto.empty?t.moveVertically(o,e,r.height):Xl(o,e));if(s.eq(n.selection))return!1;let i;if(r.selfScroll){let o=t.coordsAtPos(n.selection.main.head),a=t.scrollDOM.getBoundingClientRect(),l=a.top+r.marginTop,c=a.bottom-r.marginBottom;o&&o.top>l&&o.bottomIb(t,!1),mh=t=>Ib(t,!0);function Nn(t,e,r){let n=t.lineBlockAt(e.head),s=t.moveToLineBoundary(e,r);if(s.head==e.head&&s.head!=(r?n.to:n.from)&&(s=t.moveToLineBoundary(e,r,!1)),!r&&s.head==n.from&&n.length){let i=/^\s*/.exec(t.state.sliceDoc(n.from,Math.min(n.from+100,n.to)))[0].length;i&&e.head!=n.from+i&&(s=W.cursor(n.from+i))}return s}const Xq=t=>yr(t,e=>Nn(t,e,!0)),eB=t=>yr(t,e=>Nn(t,e,!1)),tB=t=>yr(t,e=>Nn(t,e,!Pt(t))),rB=t=>yr(t,e=>Nn(t,e,Pt(t))),nB=t=>yr(t,e=>W.cursor(t.lineBlockAt(e.head).from,1)),sB=t=>yr(t,e=>W.cursor(t.lineBlockAt(e.head).to,-1));function iB(t,e,r){let n=!1,s=ui(t.selection,i=>{let o=Lr(t,i.head,-1)||Lr(t,i.head,1)||i.head>0&&Lr(t,i.head-1,1)||i.headiB(t,e);function sr(t,e,r){let n=ui(t.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=e&&(s=W.range(s.head,s.anchor));let i=r(s);return W.range(s.anchor,i.head,i.goalColumn,i.bidiLevel||void 0,i.assoc)});return n.eq(t.state.selection)?!1:(t.dispatch(gr(t.state,n)),!0)}function Ob(t,e){return sr(t,e,r=>t.moveByChar(r,e))}const Nb=t=>Ob(t,!Pt(t)),jb=t=>Ob(t,Pt(t));function Db(t,e){return sr(t,e,r=>t.moveByGroup(r,e))}const aB=t=>Db(t,!Pt(t)),lB=t=>Db(t,Pt(t)),cB=t=>{let e=!Pt(t);return sr(t,e,r=>ec(t.state,r,e))},uB=t=>{let e=Pt(t);return sr(t,e,r=>ec(t.state,r,e))};function Lb(t,e){return sr(t,e,r=>t.moveVertically(r,e))}const zb=t=>Lb(t,!1),Fb=t=>Lb(t,!0);function qb(t,e){return sr(t,e,r=>t.moveVertically(r,e,Mb(t).height))}const Yg=t=>qb(t,!1),Qg=t=>qb(t,!0),hB=t=>sr(t,!0,e=>Nn(t,e,!0)),dB=t=>sr(t,!1,e=>Nn(t,e,!1)),fB=t=>{let e=!Pt(t);return sr(t,e,r=>Nn(t,r,e))},pB=t=>{let e=Pt(t);return sr(t,e,r=>Nn(t,r,e))},mB=t=>sr(t,!1,e=>W.cursor(t.lineBlockAt(e.head).from)),gB=t=>sr(t,!0,e=>W.cursor(t.lineBlockAt(e.head).to)),Xg=({state:t,dispatch:e})=>(e(gr(t,{anchor:0})),!0),ey=({state:t,dispatch:e})=>(e(gr(t,{anchor:t.doc.length})),!0),ty=({state:t,dispatch:e})=>(e(gr(t,{anchor:t.selection.main.anchor,head:0})),!0),ry=({state:t,dispatch:e})=>(e(gr(t,{anchor:t.selection.main.anchor,head:t.doc.length})),!0),yB=({state:t,dispatch:e})=>(e(t.update({selection:{anchor:0,head:t.doc.length},userEvent:"select"})),!0),vB=({state:t,dispatch:e})=>{let r=tc(t).map(({from:n,to:s})=>W.undirectionalRange(n,Math.min(s+1,t.doc.length)));return e(t.update({selection:W.create(r),userEvent:"select"})),!0},wB=({state:t,dispatch:e})=>{let r=ui(t.selection,n=>{let s=In(t),i=s.resolveStack(n.from,1);if(n.empty){let o=s.resolveStack(n.from,-1);o.node.from>=i.node.from&&o.node.to<=i.node.to&&(i=o)}for(let o=i;o;o=o.next){let{node:a}=o;if((a.from=n.to||a.to>n.to&&a.from<=n.from)&&o.next)return W.undirectionalRange(a.from,a.to)}return n});return r.eq(t.selection)?!1:(e(gr(t,r)),!0)};function Bb(t,e){let{state:r}=t,n=r.selection,s=r.selection.ranges.slice();for(let i of r.selection.ranges){let o=r.doc.lineAt(i.head);if(e?o.to0)for(let a=i;;){let l=t.moveVertically(a,e);if(l.heado.to){s.some(c=>c.head==l.head)||s.push(l);break}else{if(l.head==a.head)break;a=l}}}return s.length==n.ranges.length?!1:(t.dispatch(gr(r,W.create(s,s.length-1))),!0)}const _B=t=>Bb(t,!1),bB=t=>Bb(t,!0),$B=({state:t,dispatch:e})=>{let r=t.selection,n=null;return r.ranges.length>1?n=W.create([r.main]):r.main.empty||(n=W.create([W.cursor(r.main.head)])),n?(e(gr(t,n)),!0):!1};function Ro(t,e){if(t.state.readOnly)return!1;let r="delete.selection",{state:n}=t,s=n.changeByRange(i=>{let{from:o,to:a}=i;if(o==a){let l=e(i);lo&&(r="delete.forward",l=ha(t,l,!0)),o=Math.min(o,l),a=Math.max(a,l)}else o=ha(t,o,!1),a=ha(t,a,!0);return o==a?{range:i}:{changes:{from:o,to:a},range:W.cursor(o,os(t)))n.between(e,e,(s,i)=>{se&&(e=r?i:s)});return e}const Vb=(t,e,r)=>Ro(t,n=>{let s=n.from,{state:i}=t,o=i.doc.lineAt(s),a,l;if(r&&!e&&s>o.from&&sVb(t,!1,!0),Hb=t=>Vb(t,!0,!1),Ub=(t,e)=>Ro(t,r=>{let n=r.head,{state:s}=t,i=s.doc.lineAt(n),o=s.charCategorizer(n);for(let a=null;;){if(n==(e?i.to:i.from)){n==r.head&&i.number!=(e?s.doc.lines:1)&&(n+=e?1:-1);break}let l=ht(i.text,n-i.from,e)+i.from,c=i.text.slice(Math.min(n,l)-i.from,Math.max(n,l)-i.from),u=o(c);if(a!=null&&u!=a)break;(c!=" "||n!=r.head)&&(a=u),n=l}return n}),Wb=t=>Ub(t,!1),SB=t=>Ub(t,!0),kB=t=>Ro(t,e=>{let r=t.lineBlockAt(e.head).to;return e.headRo(t,e=>{let r=t.moveToLineBoundary(e,!1).head;return e.head>r?r:Math.max(0,e.head-1)}),EB=t=>Ro(t,e=>{let r=t.moveToLineBoundary(e,!0).head;return e.head{if(t.readOnly)return!1;let r=t.changeByRange(n=>({changes:{from:n.from,to:n.to,insert:Ie.of(["",""])},range:W.cursor(n.from)}));return e(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0},PB=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let r=t.changeByRange(n=>{if(!n.empty||n.from==0||n.from==t.doc.length)return{range:n};let s=n.from,i=t.doc.lineAt(s),o=s==i.from?s-1:ht(i.text,s-i.from,!1)+i.from,a=s==i.to?s+1:ht(i.text,s-i.from,!0)+i.from;return{changes:{from:o,to:a,insert:t.doc.slice(s,a).append(t.doc.slice(o,s))},range:W.cursor(a)}});return r.changes.empty?!1:(e(t.update(r,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function tc(t){let e=[],r=-1;for(let n of t.selection.ranges){let s=t.doc.lineAt(n.from),i=t.doc.lineAt(n.to);if(!n.empty&&n.to==i.from&&(i=t.doc.lineAt(n.to-1)),r>=s.number){let o=e[e.length-1];o.to=i.to,o.ranges.push(n)}else e.push({from:s.from,to:i.to,ranges:[n]});r=i.number+1}return e}function Kb(t,e,r){if(t.readOnly)return!1;let n=[],s=[];for(let i of tc(t)){if(r?i.to==t.doc.length:i.from==0)continue;let o=t.doc.lineAt(r?i.to+1:i.from-1),a=o.length+1;if(r){n.push({from:i.to,to:o.to},{from:i.from,insert:o.text+t.lineBreak});for(let l of i.ranges)s.push(W.range(Math.min(t.doc.length,l.anchor+a),Math.min(t.doc.length,l.head+a)))}else{n.push({from:o.from,to:i.from},{from:i.to,insert:t.lineBreak+o.text});for(let l of i.ranges)s.push(W.range(l.anchor-a,l.head-a))}}return n.length?(e(t.update({changes:n,scrollIntoView:!0,selection:W.create(s,t.selection.mainIndex),userEvent:"move.line"})),!0):!1}const TB=({state:t,dispatch:e})=>Kb(t,e,!1),RB=({state:t,dispatch:e})=>Kb(t,e,!0);function Zb(t,e,r){if(t.readOnly)return!1;let n=[];for(let i of tc(t))r?n.push({from:i.from,insert:t.doc.slice(i.from,i.to)+t.lineBreak}):n.push({from:i.to,insert:t.lineBreak+t.doc.slice(i.from,i.to)});let s=t.changes(n);return e(t.update({changes:s,selection:t.selection.map(s,r?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const AB=({state:t,dispatch:e})=>Zb(t,e,!1),MB=({state:t,dispatch:e})=>Zb(t,e,!0),IB=t=>{if(t.state.readOnly)return!1;let{state:e}=t,r=e.changes(tc(e).map(({from:s,to:i})=>(s>0?s--:i{let i;if(t.lineWrapping){let o=t.lineBlockAt(s.head),a=t.coordsAtPos(s.head,s.assoc||1);a&&(i=o.bottom+t.documentTop-a.bottom+t.defaultLineHeight/2)}return t.moveVertically(s,!0,i)}).map(r);return t.dispatch({changes:r,selection:n,scrollIntoView:!0,userEvent:"delete.line"}),!0};function OB(t,e){if(/\(\)|\[\]|\{\}/.test(t.sliceDoc(e-1,e+1)))return{from:e,to:e};let r=In(t).resolveInner(e),n=r.childBefore(e),s=r.childAfter(e),i;return n&&s&&n.to<=e&&s.from>=e&&(i=n.type.prop(Re.closedBy))&&i.indexOf(s.name)>-1&&t.doc.lineAt(n.to).from==t.doc.lineAt(s.from).from&&!/\S/.test(t.sliceDoc(n.to,s.from))?{from:n.to,to:s.from}:null}const ny=Gb(!1),NB=Gb(!0);function Gb(t){return({state:e,dispatch:r})=>{if(e.readOnly)return!1;let n=e.changeByRange(s=>{let{from:i,to:o}=s,a=e.doc.lineAt(i),l=!t&&i==o&&OB(e,i);t&&(i=o=(o<=a.to?a:e.doc.lineAt(o)).to);let c=new Yl(e,{simulateBreak:i,simulateDoubleBreak:!!l}),u=ab(c,i);for(u==null&&(u=Hl(/^\s*/.exec(e.doc.lineAt(i).text)[0],e.tabSize));oa.from&&i{let s=[];for(let o=n.from;o<=n.to;){let a=t.doc.lineAt(o);a.number>r&&(n.empty||n.to>a.from)&&(e(a,s,n),r=a.number),o=a.to+1}let i=t.changes(s);return{changes:s,range:W.range(i.mapPos(n.anchor,1),i.mapPos(n.head,1))}})}const jB=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let r=Object.create(null),n=new Yl(t,{overrideIndentation:i=>{let o=r[i];return o??-1}}),s=fp(t,(i,o,a)=>{let l=ab(n,i.from);if(l==null)return;/\S/.test(i.text)||(l=0);let c=/^\s*/.exec(i.text)[0],u=fl(t,l);(c!=u||a.fromt.readOnly?!1:(e(t.update(fp(t,(r,n)=>{n.push({from:r.from,insert:t.facet(op)})}),{userEvent:"input.indent"})),!0),Yb=({state:t,dispatch:e})=>t.readOnly?!1:(e(t.update(fp(t,(r,n)=>{let s=/^\s*/.exec(r.text)[0];if(!s)return;let i=Hl(s,t.tabSize),o=0,a=fl(t,Math.max(0,i-fs(t)));for(;o(t.setTabFocusMode(),!0),LB=[{key:"Ctrl-b",run:Eb,shift:Nb,preventDefault:!0},{key:"Ctrl-f",run:Cb,shift:jb},{key:"Ctrl-p",run:Rb,shift:zb},{key:"Ctrl-n",run:Ab,shift:Fb},{key:"Ctrl-a",run:nB,shift:mB},{key:"Ctrl-e",run:sB,shift:gB},{key:"Ctrl-d",run:Hb},{key:"Ctrl-h",run:gh},{key:"Ctrl-k",run:kB},{key:"Ctrl-Alt-h",run:Wb},{key:"Ctrl-o",run:CB},{key:"Ctrl-t",run:PB},{key:"Ctrl-v",run:mh}],zB=[{key:"ArrowLeft",run:Eb,shift:Nb,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:Zq,shift:aB,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:tB,shift:fB,preventDefault:!0},{key:"ArrowRight",run:Cb,shift:jb,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:Gq,shift:lB,preventDefault:!0},{mac:"Cmd-ArrowRight",run:rB,shift:pB,preventDefault:!0},{key:"ArrowUp",run:Rb,shift:zb,preventDefault:!0},{mac:"Cmd-ArrowUp",run:Xg,shift:ty},{mac:"Ctrl-ArrowUp",run:Jg,shift:Yg},{key:"ArrowDown",run:Ab,shift:Fb,preventDefault:!0},{mac:"Cmd-ArrowDown",run:ey,shift:ry},{mac:"Ctrl-ArrowDown",run:mh,shift:Qg},{key:"PageUp",run:Jg,shift:Yg},{key:"PageDown",run:mh,shift:Qg},{key:"Home",run:eB,shift:dB,preventDefault:!0},{key:"Mod-Home",run:Xg,shift:ty},{key:"End",run:Xq,shift:hB,preventDefault:!0},{key:"Mod-End",run:ey,shift:ry},{key:"Enter",run:ny,shift:ny},{key:"Mod-a",run:yB},{key:"Backspace",run:gh,shift:gh,preventDefault:!0},{key:"Delete",run:Hb,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Wb,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:SB,preventDefault:!0},{mac:"Mod-Backspace",run:xB,preventDefault:!0},{mac:"Mod-Delete",run:EB,preventDefault:!0}].concat(LB.map(t=>({mac:t.key,run:t.run,shift:t.shift}))),FB=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Yq,shift:cB},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:Qq,shift:uB},{key:"Alt-ArrowUp",run:TB},{key:"Shift-Alt-ArrowUp",run:AB},{key:"Alt-ArrowDown",run:RB},{key:"Shift-Alt-ArrowDown",run:MB},{key:"Mod-Alt-ArrowUp",run:_B},{key:"Mod-Alt-ArrowDown",run:bB},{key:"Escape",run:$B},{key:"Mod-Enter",run:NB},{key:"Alt-l",mac:"Ctrl-l",run:vB},{key:"Mod-i",run:wB,preventDefault:!0},{key:"Mod-[",run:Yb},{key:"Mod-]",run:Jb},{key:"Mod-Alt-\\",run:jB},{key:"Shift-Mod-k",run:IB},{key:"Shift-Mod-\\",run:oB},{key:"Mod-/",run:Tq},{key:"Alt-A",mac:"Ctrl-A",run:Aq},{key:"Ctrl-m",mac:"Shift-Alt-m",run:DB}].concat(zB),qB={key:"Tab",run:Jb,shift:Yb};function Qb(t){function e(h,d){h.cmdState.push(d)}function r(h){return h.cmdState.length>0?h.cmdState[h.cmdState.length-1]:null}function n(h){var d=h.cmdState.pop();d&&d.closeBracket()}function s(h){for(var d=h.cmdState,f=d.length-1;f>=0;f--){var p=d[f];if(p.name!="DEFAULT")return p}return{styleIdentifier:function(){return null}}}function i(h,d,f){return function(){this.name=h,this.bracketNo=0,this.style=d,this.styles=f,this.argument=null,this.styleIdentifier=function(){return this.styles[this.bracketNo-1]||null},this.openBracket=function(){return this.bracketNo++,"bracket"},this.closeBracket=function(){}}}var o={};o.importmodule=i("importmodule","tag",["string","builtin"]),o.documentclass=i("documentclass","tag",["","atom"]),o.usepackage=i("usepackage","tag",["atom"]),o.begin=i("begin","tag",["atom"]),o.end=i("end","tag",["atom"]),o.label=i("label","tag",["atom"]),o.ref=i("ref","tag",["atom"]),o.eqref=i("eqref","tag",["atom"]),o.cite=i("cite","tag",["atom"]),o.bibitem=i("bibitem","tag",["atom"]),o.Bibitem=i("Bibitem","tag",["atom"]),o.RBibitem=i("RBibitem","tag",["atom"]),o.DEFAULT=function(){this.name="DEFAULT",this.style="tag",this.styleIdentifier=this.openBracket=this.closeBracket=function(){}};function a(h,d){h.f=d}function l(h,d){var f;if(h.match(/^\\[a-zA-Z@\xc0-\u1fff\u2060-\uffff]+/)){var p=h.current().slice(1);return f=o.hasOwnProperty(p)?o[p]:o.DEFAULT,f=new f,e(d,f),a(d,u),f.style}if(h.match(/^\\[$&%#{}_]/)||h.match(/^\\[,;!\/\\]/))return"tag";if(h.match("\\["))return a(d,function(v,m){return c(v,m,"\\]")}),"keyword";if(h.match("\\("))return a(d,function(v,m){return c(v,m,"\\)")}),"keyword";if(h.match("$$"))return a(d,function(v,m){return c(v,m,"$$")}),"keyword";if(h.match("$"))return a(d,function(v,m){return c(v,m,"$")}),"keyword";var y=h.next();if(y=="%")return h.skipToEnd(),"comment";if(y=="}"||y=="]"){if(f=r(d),f)f.closeBracket(y),a(d,u);else return"error";return"bracket"}else return y=="{"||y=="["?(f=o.DEFAULT,f=new f,e(d,f),"bracket"):/\d/.test(y)?(h.eatWhile(/[\w.%]/),"atom"):(h.eatWhile(/[\w\-_]/),f=s(d),f.name=="begin"&&(f.argument=h.current()),f.styleIdentifier())}function c(h,d,f){if(h.eatSpace())return null;if(f&&h.match(f))return a(d,l),"keyword";if(h.match(/^\\[a-zA-Z@]+/))return"tag";if(h.match(/^[a-zA-Z]+/))return"variableName.special";if(h.match(/^\\[$&%#{}_]/)||h.match(/^\\[,;!\/]/)||h.match(/^[\^_&]/))return"tag";if(h.match(/^[+\-<>|=,\/@!*:;'"`~#?]/))return null;if(h.match(/^(\d+\.\d*|\d*\.\d+|\d+)/))return"number";var p=h.next();return p=="{"||p=="}"||p=="["||p=="]"||p=="("||p==")"?"bracket":p=="%"?(h.skipToEnd(),"comment"):"error"}function u(h,d){var f=h.peek(),p;return f=="{"||f=="["?(p=r(d),p.openBracket(f),h.eat(f),a(d,l),"bracket"):/[ \t\r]/.test(f)?(h.eat(f),null):(a(d,l),n(d),l(h,d))}return{name:"stex",startState:function(){var h=t?function(d,f){return c(d,f)}:l;return{cmdState:[],f:h}},copyState:function(h){return{cmdState:h.cmdState.slice(),f:h.f}},token:function(h,d){return d.f(h,d)},blankLine:function(h){h.f=l,h.cmdState.length=0},languageData:{commentTokens:{line:"%"}}}}const BB=Qb(!1);Qb(!0);const sy=typeof String.prototype.normalize=="function"?t=>t.normalize("NFKD"):t=>t;class ti{constructor(e,r,n=0,s=e.length,i,o){this.test=o,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(n,s),this.bufferStart=n,this.normalize=i?a=>i(sy(a)):sy,this.query=this.normalize(r)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return Nw(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let r=fL(e),n=this.bufferStart+this.bufferPos;this.bufferPos+=jw(e);let s=this.normalize(r);if(s.length)for(let i=0,o=n,a=!0;;i++){let l=s.charCodeAt(i),c=this.match(l,o,a,this.bufferPos+this.bufferStart,i==s.length-1);if(c)return this.value=c,this;if(i==s.length-1)break;a&&ithis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let r=this.matchPos<=this.to&&this.re.exec(this.curLine);if(r){let n=this.curLineStart+r.index,s=n+r[0].length;if(this.matchPos=ml(this.text,s+(n==s?1:0)),n==this.curLineStart+this.curLine.length&&this.nextLine(),(nthis.value.to)&&(!this.test||this.test(n,s,r)))return this.value={from:n,to:s,precise:!0,match:r},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=n||s.to<=r){let a=new zs(r,e.sliceString(r,n));return Bc.set(e,a),a}if(s.from==r&&s.to==n)return s;let{text:i,from:o}=s;return o>r&&(i=e.sliceString(r,o)+i,o=r),s.to=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,r=this.re.exec(this.flat.text);if(r&&!r[0]&&r.index==e&&(this.re.lastIndex=e+1,r=this.re.exec(this.flat.text)),r){let n=this.flat.from+r.index,s=n+r[0].length;if((this.flat.to>=this.to||r.index+r[0].length<=this.flat.text.length-10)&&(!this.test||this.test(n,s,r)))return this.value={from:n,to:s,precise:!0,match:r},this.matchPos=ml(this.text,s+(n==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=zs.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(e$.prototype[Symbol.iterator]=t$.prototype[Symbol.iterator]=function(){return this});function VB(t){try{return new RegExp(t,pp),!0}catch{return!1}}function ml(t,e){if(e>=t.length)return e;let r=t.lineAt(e),n;for(;e=56320&&n<57344;)e++;return e}const HB=t=>{let{state:e}=t,r=String(e.doc.lineAt(t.state.selection.main.head).number),{close:n,result:s}=PF(t,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:r},focus:!0,submitLabel:e.phrase("go")});return s.then(i=>{let o=i&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(i.elements.line.value);if(!o){t.dispatch({effects:n});return}let a=e.doc.lineAt(e.selection.main.head),[,l,c,u,h]=o,d=u?+u.slice(1):0,f=c?+c:a.number;if(c&&h){let v=f/100;l&&(v=v*(l=="-"?-1:1)+a.number/e.doc.lines),f=Math.round(e.doc.lines*v)}else c&&l&&(f=f*(l=="-"?-1:1)+a.number);let p=e.doc.line(Math.max(1,Math.min(e.doc.lines,f))),y=W.cursor(p.from+Math.max(0,Math.min(d,p.length)));t.dispatch({effects:[n,le.scrollIntoView(y.from,{y:"center"})],selection:y})}),!0},UB={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},WB=ie.define({combine(t){return ci(t,UB,{highlightWordAroundCursor:(e,r)=>e||r,minSelectionLength:Math.min,maxMatches:Math.min})}});function KB(t){return[QB,YB]}const ZB=Ce.mark({class:"cm-selectionMatch"}),GB=Ce.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function iy(t,e,r,n){return(r==0||t(e.sliceDoc(r-1,r))!=nt.Word)&&(n==e.doc.length||t(e.sliceDoc(n,n+1))!=nt.Word)}function JB(t,e,r,n){return t(e.sliceDoc(r,r+1))==nt.Word&&t(e.sliceDoc(n-1,n))==nt.Word}const YB=Kt.fromClass(class{constructor(t){this.decorations=this.getDeco(t)}update(t){(t.selectionSet||t.docChanged||t.viewportChanged)&&(this.decorations=this.getDeco(t.view))}getDeco(t){let e=t.state.facet(WB),{state:r}=t,n=r.selection;if(n.ranges.length>1)return Ce.none;let s=n.main,i,o=null;if(s.empty){if(!e.highlightWordAroundCursor)return Ce.none;let l=r.wordAt(s.head);if(!l)return Ce.none;o=r.charCategorizer(s.head),i=r.sliceDoc(l.from,l.to)}else{let l=s.to-s.from;if(l200)return Ce.none;if(e.wholeWords){if(i=r.sliceDoc(s.from,s.to),o=r.charCategorizer(s.head),!(iy(o,r,s.from,s.to)&&JB(o,r,s.from,s.to)))return Ce.none}else if(i=r.sliceDoc(s.from,s.to),!i)return Ce.none}let a=[];for(let l of t.visibleRanges){let c=new ti(r.doc,i,l.from,l.to);for(;!c.next().done;){let{from:u,to:h}=c.value;if((!o||iy(o,r,u,h))&&(s.empty&&u<=s.from&&h>=s.to?a.push(GB.range(u,h)):(u>=s.to||h<=s.from)&&a.push(ZB.range(u,h)),a.length>e.maxMatches))return Ce.none}}return Ce.set(a)}},{decorations:t=>t.decorations}),QB=le.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),XB=({state:t,dispatch:e})=>{let{selection:r}=t,n=W.create(r.ranges.map(s=>t.wordAt(s.head)||W.cursor(s.head)),r.mainIndex);return n.eq(r)?!1:(e(t.update({selection:n})),!0)};function eV(t,e){let{main:r,ranges:n}=t.selection,s=t.wordAt(r.head),i=s&&s.from==r.from&&s.to==r.to;for(let o=!1,a=new ti(t.doc,e,n[n.length-1].to);;)if(a.next(),a.done){if(o)return null;a=new ti(t.doc,e,0,Math.max(0,n[n.length-1].from-1)),o=!0}else{if(o&&n.some(l=>l.from==a.value.from))continue;if(i){let l=t.wordAt(a.value.from);if(!l||l.from!=a.value.from||l.to!=a.value.to)continue}return a.value}}const tV=({state:t,dispatch:e})=>{let{ranges:r}=t.selection;if(r.some(i=>i.from===i.to))return XB({state:t,dispatch:e});let n=t.sliceDoc(r[0].from,r[0].to);if(t.selection.ranges.some(i=>t.sliceDoc(i.from,i.to)!=n))return!1;let s=eV(t,n);return s?(e(t.update({selection:t.selection.addRange(W.range(s.from,s.to),!1),effects:le.scrollIntoView(s.to)})),!0):!1},hi=ie.define({combine(t){return ci(t,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new mV(e),scrollToMatch:e=>le.scrollIntoView(e)})}});class r${constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||VB(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(r,n)=>n=="n"?` +`:n=="r"?"\r":n=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new aV(this):new sV(this)}getCursor(e,r=0,n){let s=e.doc?e:Me.create({doc:e});return n==null&&(n=s.doc.length),this.regexp?xs(this,s,r,n):ks(this,s,r,n)}}class n${constructor(e){this.spec=e}}function rV(t,e,r){return(n,s,i,o)=>{if(r&&!r(n,s,i,o))return!1;let a=n>=o&&s<=o+i.length?i.slice(n-o,s-o):e.doc.sliceString(n,s);return t(a,e,n,s)}}function ks(t,e,r,n){let s;return t.wholeWord&&(s=nV(e.doc,e.charCategorizer(e.selection.main.head))),t.test&&(s=rV(t.test,e,s)),new ti(e.doc,t.unquoted,r,n,t.caseSensitive?void 0:i=>i.toLowerCase(),s)}function nV(t,e){return(r,n,s,i)=>((i>r||i+s.length=r)return null;s.push(n.value)}return s}highlight(e,r,n,s){let i=ks(this.spec,e,Math.max(0,r-this.spec.unquoted.length),Math.min(n+this.spec.unquoted.length,e.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}function iV(t,e,r){return(n,s,i)=>(!r||r(n,s,i))&&t(i[0],e,n,s)}function xs(t,e,r,n){let s;return t.wholeWord&&(s=oV(e.charCategorizer(e.selection.main.head))),t.test&&(s=iV(t.test,e,s)),new e$(e.doc,t.search,{ignoreCase:!t.caseSensitive,test:s},r,n)}function gl(t,e){return t.slice(ht(t,e,!1),e)}function yl(t,e){return t.slice(e,ht(t,e))}function oV(t){return(e,r,n)=>!n[0].length||(t(gl(n.input,n.index))!=nt.Word||t(yl(n.input,n.index))!=nt.Word)&&(t(yl(n.input,n.index+n[0].length))!=nt.Word||t(gl(n.input,n.index+n[0].length))!=nt.Word)}class aV extends n${nextMatch(e,r,n){let s=xs(this.spec,e,n,e.doc.length).next();return s.done&&(s=xs(this.spec,e,0,r).next()),s.done?null:s.value}prevMatchInRange(e,r,n){for(let s=1;;s++){let i=Math.max(r,n-s*1e4),o=xs(this.spec,e,i,n),a=null;for(;!o.next().done;)a=o.value;if(a&&(i==r||a.from>i+10))return a;if(i==r)return null}}prevMatch(e,r,n){return this.prevMatchInRange(e,0,r)||this.prevMatchInRange(e,n,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(r,n)=>{if(n=="&")return e.match[0];if(n=="$")return"$";for(let s=n.length;s>0;s--){let i=+n.slice(0,s);if(i>0&&i=r)return null;s.push(n.value)}return s}highlight(e,r,n,s){let i=xs(this.spec,e,Math.max(0,r-250),Math.min(n+250,e.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}const lo=Le.define(),mp=Le.define(),Cn=Vr.define({create(t){return new Vc(yh(t).create(),null)},update(t,e){for(let r of e.effects)r.is(lo)?t=new Vc(r.value.create(),t.panel):r.is(mp)&&(t=new Vc(t.query,r.value?gp:null));return t},provide:t=>ul.from(t,e=>e.panel)});class Vc{constructor(e,r){this.query=e,this.panel=r}}const lV=Ce.mark({class:"cm-searchMatch"}),cV=Ce.mark({class:"cm-searchMatch cm-searchMatch-selected"}),uV=Kt.fromClass(class{constructor(t){this.view=t,this.decorations=this.highlight(t.state.field(Cn))}update(t){let e=t.state.field(Cn);(e!=t.startState.field(Cn)||t.docChanged||t.selectionSet||t.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:t,panel:e}){if(!e||!t.spec.valid)return Ce.none;let{view:r}=this,n=new eo;for(let s=0,i=r.visibleRanges,o=i.length;si[s+1].from-2*250;)l=i[++s].to;t.highlight(r.state,a,l,(c,u)=>{let h=r.state.selection.ranges.some(d=>d.from==c&&d.to==u);n.add(c,u,h?cV:lV)})}return n.finish()}},{decorations:t=>t.decorations});function Ao(t){return e=>{let r=e.state.field(Cn,!1);return r&&r.query.spec.valid?t(e,r):o$(e)}}const vl=Ao((t,{query:e})=>{let{to:r}=t.state.selection.main,n=e.nextMatch(t.state,r,r);if(!n)return!1;let s=W.single(n.from,n.to),i=t.state.facet(hi);return t.dispatch({selection:s,effects:[yp(t,n),i.scrollToMatch(s.main,t)],userEvent:"select.search"}),i$(t),!0}),wl=Ao((t,{query:e})=>{let{state:r}=t,{from:n}=r.selection.main,s=e.prevMatch(r,n,n);if(!s)return!1;let i=W.single(s.from,s.to),o=t.state.facet(hi);return t.dispatch({selection:i,effects:[yp(t,s),o.scrollToMatch(i.main,t)],userEvent:"select.search"}),i$(t),!0}),hV=Ao((t,{query:e})=>{let r=e.matchAll(t.state,1e3);return!r||!r.length?!1:(t.dispatch({selection:W.create(r.map(n=>W.range(n.from,n.to))),userEvent:"select.search.matches"}),!0)}),dV=({state:t,dispatch:e})=>{let r=t.selection;if(r.ranges.length>1||r.main.empty)return!1;let{from:n,to:s}=r.main,i=[],o=0;for(let a=new ti(t.doc,t.sliceDoc(n,s));!a.next().done;){if(i.length>1e3)return!1;a.value.from==n&&(o=i.length),i.push(W.range(a.value.from,a.value.to))}return e(t.update({selection:W.create(i,o),userEvent:"select.search.matches"})),!0},oy=Ao((t,{query:e})=>{let{state:r}=t,{from:n,to:s}=r.selection.main;if(r.readOnly)return!1;let i=e.nextMatch(r,n,n);if(!i)return!1;let o=i,a=[],l,c,u=[];o.precise?o.from==n&&o.to==s&&(c=r.toText(e.getReplacement(o)),a.push({from:o.from,to:o.to,insert:c}),o=e.nextMatch(r,o.from,o.to),u.push(le.announce.of(r.phrase("replaced match on line $",r.doc.lineAt(n).number)+"."))):o=e.nextMatch(r,o.from,o.to);let h=t.state.changes(a);return o&&(l=W.single(o.from,o.to).map(h),u.push(yp(t,o)),u.push(r.facet(hi).scrollToMatch(l.main,t))),t.dispatch({changes:h,selection:l,effects:u,userEvent:"input.replace"}),!0}),fV=Ao((t,{query:e})=>{if(t.state.readOnly)return!1;let r=[];for(let s of e.matchAll(t.state,1e9)){let{from:i,to:o,precise:a}=s;a&&r.push({from:i,to:o,insert:e.getReplacement(s)})}if(!r.length)return!1;let n=t.state.phrase("replaced $ matches",r.length)+".";return t.dispatch({changes:r,effects:le.announce.of(n),userEvent:"input.replace.all"}),!0});function gp(t){return t.state.facet(hi).createPanel(t)}function yh(t,e){var r,n,s,i,o;let a=t.selection.main,l=a.empty||a.to>a.from+100?"":t.sliceDoc(a.from,a.to);if(e&&!l)return e;let c=t.facet(hi);return new r$({search:((r=e==null?void 0:e.literal)!==null&&r!==void 0?r:c.literal)?l:l.replace(/\n/g,"\\n"),caseSensitive:(n=e==null?void 0:e.caseSensitive)!==null&&n!==void 0?n:c.caseSensitive,literal:(s=e==null?void 0:e.literal)!==null&&s!==void 0?s:c.literal,regexp:(i=e==null?void 0:e.regexp)!==null&&i!==void 0?i:c.regexp,wholeWord:(o=e==null?void 0:e.wholeWord)!==null&&o!==void 0?o:c.wholeWord})}function s$(t){let e=Y_(t,gp);return e&&e.dom.querySelector("[main-field]")}function i$(t){let e=s$(t);e&&e==t.root.activeElement&&e.select()}const o$=t=>{let e=t.state.field(Cn,!1);if(e&&e.panel){let r=s$(t);if(r&&r!=t.root.activeElement){let n=yh(t.state,e.query.spec);n.valid&&t.dispatch({effects:lo.of(n)}),r.focus(),r.select()}}else t.dispatch({effects:[mp.of(!0),e?lo.of(yh(t.state,e.query.spec)):Le.appendConfig.of(yV)]});return!0},a$=t=>{let e=t.state.field(Cn,!1);if(!e||!e.panel)return!1;let r=Y_(t,gp);return r&&r.dom.contains(t.root.activeElement)&&t.focus(),t.dispatch({effects:mp.of(!1)}),!0},pV=[{key:"Mod-f",run:o$,scope:"editor search-panel"},{key:"F3",run:vl,shift:wl,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:vl,shift:wl,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:a$,scope:"editor search-panel"},{key:"Mod-Shift-l",run:dV},{key:"Mod-Alt-g",run:HB},{key:"Mod-d",run:tV,preventDefault:!0}];class mV{constructor(e){this.view=e;let r=this.query=e.state.field(Cn).query.spec;this.commit=this.commit.bind(this),this.searchField=ut("input",{value:r.search,placeholder:Ht(e,"Find"),"aria-label":Ht(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=ut("input",{value:r.replace,placeholder:Ht(e,"Replace"),"aria-label":Ht(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=ut("input",{type:"checkbox",name:"case",form:"",checked:r.caseSensitive,onchange:this.commit}),this.reField=ut("input",{type:"checkbox",name:"re",form:"",checked:r.regexp,onchange:this.commit}),this.wordField=ut("input",{type:"checkbox",name:"word",form:"",checked:r.wholeWord,onchange:this.commit});function n(s,i,o){return ut("button",{class:"cm-button",name:s,onclick:i,type:"button"},o)}this.dom=ut("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,n("next",()=>vl(e),[Ht(e,"next")]),n("prev",()=>wl(e),[Ht(e,"previous")]),n("select",()=>hV(e),[Ht(e,"all")]),ut("label",null,[this.caseField,Ht(e,"match case")]),ut("label",null,[this.reField,Ht(e,"regexp")]),ut("label",null,[this.wordField,Ht(e,"by word")]),...e.state.readOnly?[]:[ut("br"),this.replaceField,n("replace",()=>oy(e),[Ht(e,"replace")]),n("replaceAll",()=>fV(e),[Ht(e,"replace all")])],ut("button",{name:"close",onclick:()=>a$(e),"aria-label":Ht(e,"close"),type:"button"},["×"])])}commit(){let e=new r$({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:lo.of(e)}))}keydown(e){pF(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?wl:vl)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),oy(this.view))}update(e){for(let r of e.transactions)for(let n of r.effects)n.is(lo)&&!n.value.eq(this.query)&&this.setQuery(n.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(hi).top}}function Ht(t,e){return t.state.phrase(e)}const da=30,fa=/[\s\.,:;?!]/;function yp(t,{from:e,to:r}){let n=t.state.doc.lineAt(e),s=t.state.doc.lineAt(r).to,i=Math.max(n.from,e-da),o=Math.min(s,r+da),a=t.state.sliceDoc(i,o);if(i!=n.from){for(let l=0;la.length-da;l--)if(!fa.test(a[l-1])&&fa.test(a[l])){a=a.slice(0,l);break}}return le.announce.of(`${t.state.phrase("current match")}. ${a} ${t.state.phrase("on line")} ${n.number}.`)}const gV=le.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),yV=[Cn,Vl.low(uV),gV],vV=({path:t,value:e,readOnly:r,onChange:n})=>{const s=U.useRef(null),i=U.useRef(null),o=U.useRef(new Eo),a=U.useRef(n);return a.current=n,U.useEffect(()=>{if(!s.current)return;const l=Me.create({doc:e,extensions:[LF(),_F(),xF(),Lq(),KB(),vq(),lp.define(BB),U_.of([...FB,...Kq,...pV,qB]),o.current.of(le.editable.of(!r)),le.updateListener.of(c=>{c.docChanged&&a.current(c.state.doc.toString())})]});return i.current=new le({state:l,parent:s.current}),()=>{var c;return(c=i.current)==null?void 0:c.destroy()}},[t]),U.useEffect(()=>{const l=i.current;!l||l.state.doc.toString()===e||l.dispatch({changes:{from:0,to:l.state.doc.length,insert:e}})},[e]),U.useEffect(()=>{var l;(l=i.current)==null||l.dispatch({effects:o.current.reconfigure(le.editable.of(!r))})},[r]),b.jsx("div",{className:"latex-source-editor","data-testid":"latex-source-editor",ref:s})},l$=()=>({open:!1,selectedKey:null,selected:null,selectedVersionId:null,tab:"preview",sourceFile:null,panelPercent:55,requestNonce:0,registry:{},autoOpened:{},manuallyClosed:{}});function wV(t,e){if(e.type==="reset")return{...l$(),panelPercent:t.panelPercent};if(e.type==="register"){const r=t.registry[e.key];if(r&&JSON.stringify(r)===JSON.stringify(e.block))return t;const n={...t.registry,[e.key]:e.block},s=t.selectedKey===e.key?e.block:t.selected,i=(r==null?void 0:r.status)==="generating"&&e.block.status==="ready",o=e.autoOpenOnMount&&!r&&e.block.status==="ready"&&!Object.values(t.autoOpened).some(Boolean);return(i||o)&&!t.autoOpened[e.key]&&!t.manuallyClosed[e.key]?{...t,registry:n,open:!0,selectedKey:e.key,selected:e.block,selectedVersionId:e.block.version_id??null,tab:"preview",sourceFile:null,requestNonce:t.requestNonce+1,autoOpened:{...t.autoOpened,[e.key]:!0}}:{...t,registry:n,selected:s}}return e.type==="unregister"?t:e.type==="open"?{...t,open:!0,selectedKey:e.key,selected:e.block,selectedVersionId:e.block.version_id??null,tab:"preview",sourceFile:null,requestNonce:t.requestNonce+1,manuallyClosed:{...t.manuallyClosed,[e.key]:!1}}:e.type==="close"?{...t,open:!1,manuallyClosed:t.selectedKey?{...t.manuallyClosed,[t.selectedKey]:!0}:t.manuallyClosed}:e.type==="tab"?{...t,tab:e.tab}:e.type==="source"?{...t,sourceFile:e.path}:e.type==="version"?{...t,selectedVersionId:e.versionId,tab:"preview",sourceFile:null}:{...t,panelPercent:e.percent}}function vh(t){return t.publication_id||t.public_capability||t.version_id||`${t.scope}:${t.identifier}:${t.version??"pending"}`}const c$=U.createContext(null),pH=({children:t,workspaceKey:e,autoOpenOnMount:r=!1,onAskAiFix:n})=>{const[s,i]=U.useReducer(wV,void 0,l$),o=U.useRef(null),a=U.useRef(e);U.useEffect(()=>{a.current!==e&&(a.current=e,o.current=null,i({type:"reset"}))},[e]);const l=U.useCallback(()=>{i({type:"close"}),window.setTimeout(()=>{var $;return($=o.current)==null?void 0:$.focus()},0)},[]),c=U.useCallback($=>i({type:"register",key:vh($),block:$,autoOpenOnMount:r}),[r]),u=U.useCallback($=>i({type:"unregister",key:$}),[]),h=U.useCallback(($,E)=>{o.current=E??null,i({type:"open",key:vh($),block:$})},[]),d=U.useCallback($=>i({type:"tab",tab:$}),[]),f=U.useCallback($=>i({type:"source",path:$}),[]),p=U.useCallback($=>i({type:"version",versionId:$}),[]),y=U.useCallback($=>i({type:"width",percent:$}),[]),v=U.useCallback($=>n==null?void 0:n($),[n]),m=U.useCallback(()=>i({type:"reset"}),[]),_=U.useMemo(()=>({state:s,autoOpenOnMount:r,register:c,unregister:u,open:h,close:l,setTab:d,setSourceFile:f,setVersion:p,setPanelPercent:y,askAiToFix:v,reset:m}),[v,r,l,h,c,m,y,f,d,p,s,u]);return b.jsx(c$.Provider,{value:_,children:t})};function Mo(){const t=U.useContext(c$);if(!t)throw new Error("Poster artifacts require an ArtifactPanelProvider");return t}function _V(t,e,r){return st(`/api/v1/chat/artifacts/${encodeURIComponent(t)}/versions/${encodeURIComponent(e)}/source/${r.split("/").map(encodeURIComponent).join("/")}`)}function bV(t,e,r){return st(`/api/v1/chat/artifacts/${encodeURIComponent(t)}/versions/${encodeURIComponent(e)}/figures/${r.split("/").map(encodeURIComponent).join("/")}`)}function $V(t){return st(`/api/v1/chat/artifacts/${encodeURIComponent(t)}/export/pdf`)}function ay(t,e){return st(`/api/v1/chat/artifacts/${encodeURIComponent(t)}/versions/${encodeURIComponent(e)}/export/source.zip`)}function pa(t){return`pwc:latex-paper-draft:${t}`}function SV(t,e){const r=Object.keys(t).sort(),n=Object.keys(e).sort();return r.length===n.length&&r.every((s,i)=>s===n[i]&&t[s]===e[s])}function ly(t){return!t.includes("\\")&&/^(?!\/)(?!.*(?:^|\/)\.\.?\/)[^\0]{1,300}\.(?:tex|bib)$/iu.test(t)}function kV(t){var n,s;const e=((n=t.provenance)==null?void 0:n.action)??(t.actor_type==="restore"?"restore":t.actor_type==="ai"?"ai_draft":"human_save"),r={human_save:"Human save",ai_draft:"AI draft",ai_repair:"AI repair",restore:"Restore"}[e];return(s=t.provenance)!=null&&s.model_identity?`${r} · ${t.provenance.model_identity}`:r}const xV=({block:t,forceDialog:e=!1})=>{var vr,wr,_r,br,$r,Nt,Sr,an,ln;const r=Mo(),n=g$(),s=r.close,[i,o]=U.useState(()=>{var j;return typeof window<"u"&&((j=window.matchMedia)==null?void 0:j.call(window,"(max-width: 760px)").matches)}),[a,l]=U.useState({}),[c,u]=U.useState({}),[h,d]=U.useState(null),[f,p]=U.useState(!1),[y,v]=U.useState(!1),[m,_]=U.useState(null),[$,E]=U.useState(!1),[x,P]=U.useState(null),R=U.useRef(null),z=U.useRef(null),L=U.useRef(!1),H=e||i,O=h!==null&&!SV(a,c);U.useEffect(()=>{var ke,Qe;const j=(ke=window.matchMedia)==null?void 0:ke.call(window,"(max-width: 760px)");if(!j)return;const ce=()=>o(j.matches);return ce(),(Qe=j.addEventListener)==null||Qe.call(j,"change",ce),()=>{var kt;return(kt=j.removeEventListener)==null?void 0:kt.call(j,"change",ce)}},[]),U.useEffect(()=>{var ke,Qe;if(!H)return;(Qe=(ke=z.current)==null?void 0:ke.querySelector("[data-artifact-close]"))==null||Qe.focus(),window.history.pushState({...window.history.state,pwcArtifactPanel:!0},""),L.current=!0;const j=()=>{if(O&&!window.confirm("Discard unsaved paper edits?")){window.history.pushState({...window.history.state,pwcArtifactPanel:!0},""),L.current=!0;return}L.current=!1,s()},ce=kt=>{kt.key==="Escape"&&(kt.preventDefault(),!(O&&!window.confirm("Discard unsaved paper edits?"))&&(s(),L.current&&(L.current=!1,window.history.back())))};return window.addEventListener("popstate",j),document.addEventListener("keydown",ce),()=>{window.removeEventListener("popstate",j),document.removeEventListener("keydown",ce)}},[s,H,O]),U.useEffect(()=>{const j=ce=>{O&&(ce.preventDefault(),ce.returnValue="")};return window.addEventListener("beforeunload",j),()=>window.removeEventListener("beforeunload",j)},[O]);const Z=vn({queryKey:["chat-latex-paper",t.artifact_id],queryFn:async()=>{const j=await fetch(st(`/api/v1/chat/artifacts/${encodeURIComponent(t.artifact_id)}`),{credentials:"include",cache:"no-store"});if(!j.ok)throw new Error("Could not load paper details");return j.json()},enabled:!!t.artifact_id,staleTime:5e3}).data,I=Z==null?void 0:Z.source_head,Q=Z==null?void 0:Z.preview_head,G=vn({queryKey:["chat-latex-paper-history",t.artifact_id,x],queryFn:async()=>{const j=new URLSearchParams({limit:"20"});x&&j.set("cursor",x);const ce=await fetch(st(`/api/v1/chat/artifacts/${encodeURIComponent(t.artifact_id)}/versions?${j}`),{credentials:"include",cache:"no-store"});if(!ce.ok)throw new Error("Could not load paper history");return ce.json()},enabled:$&&!!t.artifact_id,staleTime:Number.POSITIVE_INFINITY}),re=vn({queryKey:["chat-latex-paper-manifest",t.artifact_id,I==null?void 0:I.version_id],queryFn:async()=>{const j=await fetch(st(`/api/v1/chat/artifacts/${encodeURIComponent(t.artifact_id)}/versions/${encodeURIComponent(I.version_id)}/manifest`),{credentials:"include",cache:"no-store"});if(!j.ok)throw new Error("Could not load paper files");return j.json()},enabled:r.state.tab==="files"&&!!(I!=null&&I.version_id),staleTime:Number.POSITIVE_INFINITY}),Oe=((vr=re.data)==null?void 0:vr.files.filter(j=>j.media_type==="text/x-tex"||j.media_type==="application/x-bibtex"))??[],Ee=((wr=re.data)==null?void 0:wr.files.filter(j=>j.media_type==="image/png"||j.media_type==="image/jpeg"||j.media_type==="application/pdf"))??[],M=vn({queryKey:["chat-latex-paper-source-files",t.artifact_id,I==null?void 0:I.version_id],queryFn:async()=>Object.fromEntries(await Promise.all(Oe.map(async j=>{const ce=await fetch(_V(t.artifact_id,I.version_id,j.path),{credentials:"include",cache:"no-store"});if(!ce.ok)throw new Error("Could not load paper source");return[j.path,await ce.text()]}))),enabled:r.state.tab==="files"&&!!(I!=null&&I.version_id&&Oe.length),staleTime:Number.POSITIVE_INFINITY});U.useEffect(()=>{p(!1)},[I==null?void 0:I.version_id]),U.useEffect(()=>{var kt;if(!(I!=null&&I.version_id)||!M.data||R.current===I.version_id)return;const j=M.data;let ce=j,ke=!1,Qe=I.version_id;try{const di=window.localStorage.getItem(pa(t.artifact_id)),jn=di?JSON.parse(di):null;jn!=null&&jn.files&&typeof jn.files=="object"&&(ce=jn.files,ke=jn.parentVersionId!==I.version_id,Qe=jn.parentVersionId)}catch{}R.current=I.version_id,l(ce),u(j),d(Qe),v(ke),p(!0),ke&&_("This local draft is based on an older paper version. Copy or discard it before saving the latest version."),(!r.state.sourceFile||!ce[r.state.sourceFile])&&r.setSourceFile(((kt=re.data)==null?void 0:kt.root_document)??null)},[t.artifact_id,(_r=re.data)==null?void 0:_r.root_document,r,I==null?void 0:I.version_id,M.data]),U.useEffect(()=>{if(!h||!t.artifact_id)return;const j=pa(t.artifact_id);if(!O){window.localStorage.removeItem(j);return}window.localStorage.setItem(j,JSON.stringify({parentVersionId:h,files:a}))},[t.artifact_id,O,h,a]);const S=Io({mutationFn:async()=>{var ke;if(!(I!=null&&I.version_id))throw new Error("Paper source is not ready to save");const j=await fetch(st(`/api/v1/chat/artifacts/${encodeURIComponent(t.artifact_id)}/save-compile`),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({expected_parent_version_id:I.version_id,files:Object.entries(a).map(([Qe,kt])=>({path:Qe,content:kt}))})}),ce=await j.json().catch(()=>null);if(!j.ok)throw new Error(((ke=ce==null?void 0:ce.detail)==null?void 0:ke.message)??"Could not save paper");return ce},onSuccess:j=>{var ce,ke;n.setQueryData(["chat-latex-paper",t.artifact_id],j),n.invalidateQueries({queryKey:["chat-latex-paper-manifest",t.artifact_id]}),n.invalidateQueries({queryKey:["chat-latex-paper-source-files",t.artifact_id]}),R.current=((ce=j.source_head)==null?void 0:ce.version_id)??null,u(a),d(((ke=j.source_head)==null?void 0:ke.version_id)??null),window.localStorage.removeItem(pa(t.artifact_id)),_(null),v(!1),r.setTab("preview")},onError:j=>_(j instanceof Error?j.message:"Could not save paper")}),A=Io({mutationFn:async j=>{var Qe;if(!(I!=null&&I.version_id))throw new Error("Paper source is not ready to restore");const ce=await fetch(st(`/api/v1/chat/artifacts/${encodeURIComponent(t.artifact_id)}/versions/restore`),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({source_version_id:j,expected_parent_version_id:I.version_id})}),ke=await ce.json().catch(()=>null);if(!ce.ok)throw new Error(((Qe=ke==null?void 0:ke.detail)==null?void 0:Qe.message)??"Could not restore paper version");return ke},onSuccess:j=>{n.setQueryData(["chat-latex-paper",t.artifact_id],j),n.invalidateQueries({queryKey:["chat-latex-paper-history",t.artifact_id]}),n.invalidateQueries({queryKey:["chat-latex-paper-manifest",t.artifact_id]}),n.invalidateQueries({queryKey:["chat-latex-paper-source-files",t.artifact_id]}),R.current=null,p(!1),P(null),_(null),r.setTab("preview")},onError:j=>_(j instanceof Error?j.message:"Could not restore paper version")}),k=Io({mutationFn:async j=>{var kt;if(!(I!=null&&I.version_id))throw new Error("Paper source is not ready to upload a figure");if(O)throw new Error("Save or discard text edits before uploading a figure");const ce=new FormData;ce.set("expected_parent_version_id",I.version_id),ce.set("path",`figures/${j.name}`),ce.set("figure",j);const ke=await fetch(st(`/api/v1/chat/artifacts/${encodeURIComponent(t.artifact_id)}/figures`),{method:"POST",credentials:"include",body:ce}),Qe=await ke.json().catch(()=>null);if(!ke.ok)throw new Error(((kt=Qe==null?void 0:Qe.detail)==null?void 0:kt.message)??"Could not upload figure");return Qe},onSuccess:j=>{n.setQueryData(["chat-latex-paper",t.artifact_id],j),n.invalidateQueries({queryKey:["chat-latex-paper-manifest",t.artifact_id]}),n.invalidateQueries({queryKey:["chat-latex-paper-source-files",t.artifact_id]}),_(null)},onError:j=>_(j instanceof Error?j.message:"Could not upload figure")}),w=Io({mutationFn:async()=>{const j=await fetch(st(`/api/v1/chat/artifacts/${encodeURIComponent(t.artifact_id)}/refresh-compile`),{method:"POST",credentials:"include"});if(!j.ok)throw new Error("Could not refresh paper compilation");return j.json()},onSuccess:j=>n.setQueryData(["chat-latex-paper",t.artifact_id],j)}).mutate,C=I==null?void 0:I.version_id,V=I==null?void 0:I.compile_status;U.useEffect(()=>{if(!C||!t.artifact_id||!["queued","compiling"].includes(V??""))return;const j=window.setTimeout(()=>w(),2e3);return()=>window.clearTimeout(j)},[t.artifact_id,w,V,C]);const F=r.state.sourceFile??((br=re.data)==null?void 0:br.root_document)??null,ne=(Z==null?void 0:Z.editing_enabled)===!0&&!!(I!=null&&I.version_id)&&f&&!y&&!S.isPending,te=new Map((($r=G.data)==null?void 0:$r.items.map(j=>[j.version_id,j.version]))??[]),ve=Q?st(`/api/v1/chat/artifacts/${encodeURIComponent(t.artifact_id)}/versions/${encodeURIComponent(Q.version_id)}/preview`):null,Tt=!!(I&&Q&&I.version_id!==Q.version_id),Hr=()=>!O||window.confirm("Discard unsaved paper edits?"),Ur=j=>{j!==F&&O&&!window.confirm("Switch files? Unsaved edits stay in this browser.")||r.setSourceFile(j)},Wr=()=>{const j=window.prompt("New TeX or BibTeX file name","section.tex");if(j){if(!ly(j)||a[j]){_("Choose a new safe .tex or .bib filename.");return}if(Object.keys(a).length>=100){_("A paper can contain at most 100 files.");return}l({...a,[j]:""}),_(null),r.setSourceFile(j)}},Kr=()=>{var ke;if(!F||F===((ke=re.data)==null?void 0:ke.root_document))return;const j=window.prompt("Rename file",F);if(!j||j===F)return;if(!ly(j)||a[j]){_("Choose a new safe .tex or .bib filename.");return}const ce={...a,[j]:a[F]};delete ce[F],l(ce),r.setSourceFile(j)},Zr=()=>{var ce,ke;if(!F||F===((ce=re.data)==null?void 0:ce.root_document)||!window.confirm(`Delete ${F}?`))return;const j={...a};delete j[F],l(j),r.setSourceFile(((ke=re.data)==null?void 0:ke.root_document)??null)},Gr=()=>{!y||!window.confirm("Discard this stale local draft?")||(window.localStorage.removeItem(pa(t.artifact_id)),l(c),d((I==null?void 0:I.version_id)??null),v(!1),_(null))},Jr=()=>{Hr()&&(s(),H&&L.current&&(L.current=!1,window.history.back()))},Yr=()=>{if(!I||I.compile_status!=="failed"||I.repair_exhausted)return;const j=(I.compile_diagnostics??[]).slice(0,20).map(ce=>`${ce.file??"project"}${ce.line?`:${ce.line}`:""}: ${ce.message}`).join(` +`);r.askAiToFix(`Repair the failed paper source version ${I.version_id}. Use pwc-paper to inspect and repair it; make no more than three attempts. Compiler diagnostics: +${j||"No compiler diagnostic was available."}`)};return b.jsxs("section",{ref:z,className:`chat-artifact-panel${H?" is-dialog":" is-docked"}`,role:H?"dialog":"complementary","aria-modal":H?!0:void 0,"aria-label":t.title,"data-testid":"latex-paper-panel",children:[b.jsxs("header",{children:[b.jsxs("div",{children:[b.jsx("span",{children:"Private paper"}),b.jsx("h2",{children:t.title}),b.jsx("p",{children:"This paper is private to this chat. Source, figures, and PDFs are stored privately; AI-authored text needs your review."})]}),b.jsx("button",{type:"button","data-artifact-close":!0,"aria-label":H?"Back to conversation":"Close paper",onClick:Jr,children:b.jsx(hy,{})})]}),b.jsxs("nav",{"aria-label":"Paper views",children:[b.jsx("button",{type:"button","aria-pressed":r.state.tab==="preview",className:r.state.tab==="preview"?"active":"",onClick:()=>r.setTab("preview"),children:"Preview"}),b.jsx("button",{type:"button","aria-pressed":r.state.tab==="files",className:r.state.tab==="files"?"active":"",onClick:()=>r.setTab("files"),children:"Files"})]}),b.jsxs("div",{className:"chat-artifact-panel-body",children:[r.state.tab==="preview"?ve?b.jsx("iframe",{title:`Preview of ${t.title}`,src:ve,className:"h-full w-full border-0"},Q==null?void 0:Q.version_id):b.jsx("p",{children:"Preview is compiling. The stored source is available in Files."}):b.jsxs("div",{className:"chat-artifact-source-workspace",children:[b.jsxs("nav",{"aria-label":"Paper source files",children:[Oe.map(j=>b.jsx("button",{type:"button","aria-pressed":F===j.path,onClick:()=>Ur(j.path),children:j.path},j.path)),ne&&b.jsxs("button",{type:"button",className:"latex-file-action","aria-label":"Add TeX file",onClick:Wr,children:[b.jsx(j$,{})," Add file"]}),ne&&b.jsxs("label",{className:"latex-file-action",children:["Upload figure",b.jsx("input",{"aria-label":"Upload figure",type:"file",accept:"image/png,image/jpeg,application/pdf,.png,.jpg,.jpeg,.pdf",disabled:k.isPending,onChange:j=>{var ke;const ce=(ke=j.currentTarget.files)==null?void 0:ke[0];j.currentTarget.value="",ce&&k.mutate(ce)}})]}),Ee.map(j=>I&&b.jsx("a",{href:bV(t.artifact_id,I.version_id,j.path),download:!0,children:j.path},j.path))]}),b.jsxs("div",{className:"latex-editor-column",children:[F&&a[F]!==void 0?b.jsx(vV,{path:F,value:a[F],readOnly:!ne,onChange:j=>l({...a,[F]:j})}):b.jsx("p",{children:M.isError?"Source could not be loaded.":"Loading source…"}),ne&&F&&F!==((Nt=re.data)==null?void 0:Nt.root_document)&&b.jsxs("div",{className:"latex-file-buttons",children:[b.jsxs("button",{type:"button",onClick:Kr,children:[b.jsx(yy,{})," Rename"]}),b.jsxs("button",{type:"button",onClick:Zr,children:[b.jsx(C$,{})," Delete"]})]})]})]}),$&&b.jsxs("section",{className:"chat-artifact-history","aria-label":"Paper version history",children:[b.jsx("h3",{children:"Version history"}),G.isLoading&&b.jsx("p",{children:"Loading history…"}),G.isError&&b.jsx("p",{role:"alert",children:"Paper history could not be loaded."}),(Sr=G.data)==null?void 0:Sr.items.map(j=>{var ce,ke,Qe,kt;return b.jsxs("article",{children:[b.jsxs("strong",{children:["v",j.version," · ",j.compile_status]}),b.jsx("span",{children:kV(j)}),j.created_at&&b.jsx("time",{dateTime:j.created_at,children:j.created_at}),j.parent_version_id&&b.jsxs("span",{children:["Parent ",te.has(j.parent_version_id)?`v${te.get(j.parent_version_id)}`:j.parent_version_id]}),(ce=j.provenance)!=null&&ce.changed_files.length?b.jsxs("span",{children:["Changed: ",j.provenance.changed_files.join(", ")]}):null,((ke=j.provenance)==null?void 0:ke.restored_from_version_id)&&b.jsxs("span",{children:["Restored from ",j.provenance.restored_from_version_id]}),((Qe=j.provenance)==null?void 0:Qe.change_summary)&&b.jsx("p",{children:j.provenance.change_summary}),(kt=j.provenance)==null?void 0:kt.reference_changes.map(di=>b.jsx("p",{children:di},di)),b.jsx("a",{href:ay(t.artifact_id,j.version_id),download:!0,children:"Source ZIP"}),(Z==null?void 0:Z.editing_enabled)&&(I==null?void 0:I.version_id)&&j.version_id!==I.version_id&&b.jsxs("button",{type:"button",disabled:A.isPending||O,onClick:()=>A.mutate(j.version_id),children:["Restore version ",j.version]})]},j.version_id)}),((an=G.data)==null?void 0:an.next_cursor)&&b.jsx("button",{type:"button",onClick:()=>P(G.data.next_cursor??null),children:"Load older versions"})]})]}),b.jsxs("footer",{children:[b.jsxs("div",{className:"chat-artifact-metadata","aria-live":"polite",children:[Tt&&b.jsx("strong",{children:"Out of date"}),I&&b.jsxs("span",{children:["Source v",I.version," · ",I.compile_status]}),(ln=I==null?void 0:I.compile_diagnostics)==null?void 0:ln.map((j,ce)=>b.jsxs("button",{type:"button",onClick:()=>j.file&&r.setSourceFile(j.file),className:"latex-compile-diagnostic",children:[j.file?`${j.file}${j.line?`:${j.line}`:""}: `:"",j.message]},`${j.file??"global"}:${j.line??""}:${ce}`)),m&&b.jsx("span",{role:"alert",children:m}),y&&b.jsx("button",{type:"button",onClick:Gr,children:"Discard stale local draft"})]}),b.jsxs("div",{className:"chat-artifact-actions",children:[(I==null?void 0:I.compile_status)==="failed"&&!I.repair_exhausted&&b.jsx("button",{type:"button",onClick:Yr,children:"Ask AI to fix"}),(I==null?void 0:I.compile_status)==="failed"&&I.repair_exhausted&&b.jsx("span",{role:"status",children:"AI repair attempts exhausted"}),b.jsx("button",{type:"button",onClick:()=>{P(null),E(!$)},children:"Version history"}),r.state.tab==="files"&&ne&&b.jsxs("button",{type:"button",disabled:!O,onClick:()=>S.mutate(),children:[b.jsx(L$,{}),S.isPending?"Saving…":"Save & Compile"]}),Q&&b.jsxs("a",{href:$V(t.artifact_id),download:!0,children:[b.jsx(Hc,{})," PDF"]}),I&&b.jsxs("a",{href:ay(t.artifact_id,I.version_id),download:!0,children:[b.jsx(bh,{})," Source ZIP"]})]})]})]})},EV="https://github.com/Chenruishuo/posterly/tree/b9f42e5578a49a27525a68f85376bb3bb25af86f";function CV(){if(typeof window>"u")return null;const t=window.location.pathname.match(/^\/share\/([^/]+)/u);return t?decodeURIComponent(t[1]):null}function u$(t){if(t.scope==="public"){const n=CV();if(!n||!t.public_capability)return null;const s=`/api/v1/chat/shares/${encodeURIComponent(n)}/artifacts/${encodeURIComponent(t.public_capability)}`;return{preview:st(`${s}/preview`),png:st(`${s}/download/png`),pdf:st(`${s}/download/pdf`),manifest:null,source:null,gate:null,download:null}}if(!t.artifact_id||!t.version_id)return null;const e=`/api/v1/chat/artifacts/${encodeURIComponent(t.artifact_id)}/versions/${encodeURIComponent(t.version_id)}`,r=(n,s)=>st(`${e}/${n}/${s.split("/").map(encodeURIComponent).join("/")}`);return{preview:st(`${e}/preview`),png:r("download","poster.png"),pdf:null,manifest:st(`${e}/manifest`),source:n=>r("source",n),gate:n=>r("source",n),download:n=>r("download",n)}}const h$=t=>({passed:"Passed",warnings:"Passed with warnings",failed:"Draft—checks failed"})[t??"passed"];function PV(){const[t,e]=U.useState(()=>{var r;return typeof window<"u"&&((r=window.matchMedia)==null?void 0:r.call(window,"(max-width: 760px)").matches)});return U.useEffect(()=>{var s,i;const r=(s=window.matchMedia)==null?void 0:s.call(window,"(max-width: 760px)");if(!r)return;const n=()=>e(r.matches);return n(),(i=r.addEventListener)==null||i.call(r,"change",n),()=>{var o;return(o=r.removeEventListener)==null?void 0:o.call(r,"change",n)}},[]),t}const TV=({forceDialog:t=!1,readerFallback:e=!1})=>{var x,P,R,z;const r=Mo(),n=r.close,{state:s}=r,i=s.selected,o=PV(),a=t||o,l=U.useRef(null),c=U.useRef(!1),u=vn({queryKey:["chat-artifact-versions",i==null?void 0:i.artifact_id],queryFn:async()=>{const L=await fetch(st(`/api/v1/chat/artifacts/${encodeURIComponent(i.artifact_id)}`),{credentials:"include",cache:"no-store"});if(!L.ok)throw new Error("Could not load poster versions");return(await L.json()).versions},enabled:s.open&&(i==null?void 0:i.scope)==="owner"&&!!i.artifact_id,staleTime:Number.POSITIVE_INFINITY}),h=(x=u.data)==null?void 0:x.find(L=>L.version_id===s.selectedVersionId),d=i&&h?{...i,version_id:h.version_id,version:h.version,gate_status:h.gate_status,total_bytes:h.total_bytes}:i,f=d?u$(d):null,y=vn({queryKey:["chat-artifact-manifest",d==null?void 0:d.version_id],queryFn:async()=>{const L=await fetch(f.manifest,{credentials:"include",cache:"no-store"});if(!L.ok)throw new Error("Could not load poster details");return L.json()},enabled:s.open&&(d==null?void 0:d.scope)==="owner"&&!!(f!=null&&f.manifest),staleTime:Number.POSITIVE_INFINITY}).data,v=s.sourceFile??(y==null?void 0:y.entrypoint)??null,m=vn({queryKey:["chat-artifact-source",d==null?void 0:d.version_id,v],queryFn:async()=>{const L=await fetch(f.source(v),{credentials:"include",cache:"no-store"});if(!L.ok)throw new Error("Source could not be loaded");return L.text()},enabled:s.open&&s.tab==="source"&&(d==null?void 0:d.scope)==="owner"&&!!(v&&(f!=null&&f.source)),staleTime:Number.POSITIVE_INFINITY});if(U.useEffect(()=>{var H,O;if(!s.open||!a)return;(O=(H=l.current)==null?void 0:H.querySelector("[data-artifact-close]"))==null||O.focus(),window.history.pushState({...window.history.state,pwcArtifactPanel:!0},""),c.current=!0;const L=()=>{c.current=!1,n()};return window.addEventListener("popstate",L),()=>window.removeEventListener("popstate",L)},[n,a,s.open]),U.useEffect(()=>{if(!s.open||!a)return;const L=H=>{if(H.key==="Escape"){H.preventDefault(),n(),c.current&&(c.current=!1,window.history.back());return}if(H.key!=="Tab"||!l.current)return;const O=[...l.current.querySelectorAll('button:not([disabled]), a[href], select:not([disabled]), [tabindex]:not([tabindex="-1"])')];if(!O.length)return;const B=O[0],Z=O.at(-1);H.shiftKey&&document.activeElement===B?(H.preventDefault(),Z.focus()):!H.shiftKey&&document.activeElement===Z&&(H.preventDefault(),B.focus())};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[n,a,s.open]),!s.open||!d||!f)return null;const _=()=>{n(),a&&c.current&&(c.current=!1,window.history.back())},$=(P=y==null?void 0:y.downloads[0])==null?void 0:P.path,E=d.scope==="public"?f.pdf:$&&f.download?f.download($):null;return b.jsxs("section",{ref:l,className:`chat-artifact-panel${a?" is-dialog":" is-docked"}${e?" is-reader-fallback":""}`,role:a?"dialog":"complementary","aria-modal":a?!0:void 0,"aria-label":d.title,"data-testid":"artifact-panel",children:[b.jsxs("header",{children:[b.jsxs("div",{children:[b.jsx("span",{children:"Posterly artifact"}),b.jsx("h2",{children:d.title})]}),(((R=u.data)==null?void 0:R.length)??0)>1&&b.jsxs("label",{className:"chat-artifact-version",children:["Version",b.jsx("select",{"aria-label":"Poster version",value:d.version_id,onChange:L=>r.setVersion(L.target.value),children:[...u.data??[]].reverse().map(L=>b.jsxs("option",{value:L.version_id,children:["v",L.version]},L.version_id))})]}),b.jsx("button",{type:"button","data-artifact-close":!0,"aria-label":a?"Back to conversation":"Close poster",onClick:_,children:b.jsx(hy,{})})]}),b.jsxs("nav",{"aria-label":"Poster views",children:[b.jsx("button",{type:"button","aria-pressed":s.tab==="preview",className:s.tab==="preview"?"active":"",onClick:()=>r.setTab("preview"),children:"Preview"}),d.scope==="owner"&&b.jsx("button",{type:"button","aria-pressed":s.tab==="source",className:s.tab==="source"?"active":"",onClick:()=>r.setTab("source"),children:"Source"})]}),b.jsx("div",{className:"chat-artifact-panel-body",children:s.tab==="preview"?b.jsx("img",{src:f.preview,alt:`Full preview of ${d.title}`}):b.jsxs("div",{className:"chat-artifact-source-workspace",children:[(((z=y==null?void 0:y.source_files)==null?void 0:z.length)??0)>1&&b.jsx("nav",{"aria-label":"Poster source files",children:y.source_files.map(L=>b.jsx("button",{type:"button","aria-pressed":v===L,onClick:()=>r.setSourceFile(L),children:L},L))}),b.jsx("pre",{children:b.jsx("code",{children:m.isError?"Source could not be loaded.":m.data??"Loading source…"})})]})}),b.jsxs("footer",{children:[b.jsxs("div",{className:"chat-artifact-metadata",children:[b.jsx("strong",{children:h$(d.gate_status)}),y&&b.jsxs("span",{children:[y.canvas.width," × ",y.canvas.height," ",y.canvas.unit," · ",y.canvas.orientation," · ",y.direction]}),y==null?void 0:y.gate_summary.map(L=>b.jsx("span",{children:L},L))]}),b.jsxs("div",{className:"chat-artifact-actions",children:[b.jsxs("a",{href:f.png,download:!0,children:[b.jsx(Hc,{})," PNG"]}),d.gate_status!=="failed"&&E&&b.jsxs("a",{href:E,download:!0,children:[b.jsx(Hc,{})," PDF"]}),d.scope==="owner"&&y&&f.source&&b.jsxs("a",{href:f.source(y.entrypoint),download:!0,children:[b.jsx(bh,{})," HTML"]}),d.scope==="owner"&&y&&f.gate&&b.jsx("a",{href:f.gate(y.gate_report),download:!0,children:"Gate report"}),b.jsxs("a",{href:EV,target:"_blank",rel:"noreferrer",children:[b.jsx(O$,{})," Posterly source · AGPL-3.0"]})]})]})]})},cy=t=>{var r;const{state:e}=Mo();return((r=e.selected)==null?void 0:r.artifact_kind)==="latex_paper"?b.jsx(xV,{block:e.selected,...t}):b.jsx(TV,{...t})},RV=({block:t})=>{const e=Mo(),r=e.register,n=e.unregister,s=vh(t);if(U.useEffect(()=>{r(t)},[t,r]),U.useEffect(()=>()=>n(s),[s,n]),t.status==="generating")return b.jsxs("div",{className:"chat-artifact-card chat-artifact-generating",role:"status",children:[b.jsx("span",{className:"chat-artifact-pulse","aria-hidden":"true"}),b.jsxs("span",{children:[b.jsx("strong",{children:t.title}),b.jsx("small",{children:"Publishing Posterly preview…"})]})]});if(t.status==="error")return b.jsxs("div",{className:"chat-artifact-card chat-artifact-error",role:"alert",children:[b.jsx(bh,{"aria-hidden":"true"}),b.jsxs("span",{children:[b.jsx("strong",{children:t.title}),b.jsx("small",{children:t.error_message??"Poster publication failed."})]})]});const i=u$(t);if(!i)return null;const o=e.state.open&&e.state.selectedKey===s;return b.jsxs("button",{type:"button",className:`chat-artifact-card${o?" is-selected":""}`,"aria-pressed":o,onClick:a=>e.open(t,a.currentTarget),children:[b.jsx("img",{src:i.preview,alt:`Preview of ${t.title}`}),b.jsxs("span",{className:"chat-artifact-card-copy",children:[b.jsxs("span",{className:"chat-artifact-kicker",children:[b.jsx(D$,{"aria-hidden":"true"})," Posterly · v",t.version]}),b.jsx("strong",{children:t.title}),b.jsx("small",{className:`chat-artifact-gate chat-artifact-gate-${t.gate_status}`,children:h$(t.gate_status)})]})]})};function AV(t){if(!t.authors.length)return"";const e=t.authors.slice(0,3).map(r=>r.name).join(", ");return t.authors.length>3?`${e}, et al.`:e}function MV(t){var r;if(t.conference)return t.conference;const e=(r=t.published)==null?void 0:r.slice(0,4);if(t.arxiv_id)return e?`arXiv ${e}`:"arXiv";if(t.source_url)try{return new URL(t.source_url).hostname.replace(/^www\./,"")}catch{}return e??"external"}function IV(t,e=240){const r=t.content.trim();return r.length<=e?r:`${r.slice(0,e).trimEnd()}…`}const OV="https://huggingface.co/pro",NV="https://huggingface.co/docs/inference-providers/pricing",jV="https://paperswithcode.co/chat",d$=()=>b.jsx("span",{className:"chat-caret"}),DV=t=>{var r;if(!t.streaming)return!1;const e=(r=t.blocks)==null?void 0:r.at(-1);return e?e.kind==="reasoning"?!e.active:e.kind==="tool"?e.status!=="running":!1:!0},LV=t=>{var f,p;const e=t.currentTarget,r=e.ownerDocument,n=(f=r.caretPositionFromPoint)==null?void 0:f.call(r,t.clientX,t.clientY),s=n?null:(p=r.caretRangeFromPoint)==null?void 0:p.call(r,t.clientX,t.clientY),i=(n==null?void 0:n.offsetNode)??(s==null?void 0:s.startContainer),o=(n==null?void 0:n.offset)??(s==null?void 0:s.startOffset);if(!(i instanceof Text)||o===void 0||!e.contains(i))return;const a=i.data,l=/[\p{L}\p{M}\p{N}_'-]/u;let c=Math.min(o,a.length),u=c;for(;c>0&&l.test(a[c-1]);)c-=1;for(;u{const r=[];let n=0;for(const s of[...e].sort((i,o)=>i.start-o.start)){const i=t.slice(s.start,s.end);s.startt.length||i!==s.title&&i!==`@${s.title}`||(r.push(t.slice(n,s.start)),r.push(b.jsxs("span",{className:"chat-inline-paper-mention",children:[b.jsx(I$,{size:13,"aria-hidden":"true"}),b.jsx(gy,{routeId:s.route_id,className:"chat-inline-paper-link",children:i.startsWith("@")?i.slice(1):i})]},s.key)),n=s.end)}return r.push(t.slice(n)),b.jsx(b.Fragment,{children:r})},FV=({block:t,papers:e,citations:r,webCitations:n,onToggle:s})=>t.active?b.jsxs("div",{className:"chat-reason-live",children:[b.jsxs("div",{className:"chat-reason-live-head",children:[b.jsx(wh,{})," ",b.jsx("span",{children:"Thinking…"})]}),b.jsxs("div",{className:"chat-reason-live-body chat-answer chat-reason-markdown",children:[b.jsx(Uc,{text:t.text,streaming:!0,papers:e,citations:r,webCitations:n}),b.jsx(d$,{})]})]}):b.jsxs("div",{className:"chat-reason-done",children:[b.jsxs("button",{type:"button",className:"chat-reason-done-head",onClick:s,"aria-expanded":t.open,children:[b.jsx(S$,{}),b.jsx("span",{children:"Thought for a few seconds"}),b.jsx(my,{open:t.open})]}),t.open&&b.jsx("div",{className:"chat-reason-done-body chat-answer chat-reason-markdown",children:b.jsx(Uc,{text:t.text,papers:e,citations:r,webCitations:n})})]}),qV=({block:t,papers:e,onToggle:r})=>{var h,d,f,p;const n=t.status==="running",s=n&&t.argumentState==="streaming",i=t.schema_version===2||!!t.content,o=t.status==="error"||t.status==="denied",a=typeof t.args.query=="string"?t.args.query:"",l=typeof t.args.command=="string"?t.args.command:typeof t.args.file_path=="string"?t.args.file_path:a,c=((h=t.content)==null?void 0:h.map(y=>y.text).join(""))??"",u=s?"streaming arguments…":n?"running…":i?`${t.status} · ${t.took_ms??0} ms`:`${t.hits} results · ${t.took_ms} ms`;return b.jsxs("div",{className:`chat-tool${n?" chat-tool-running":""}${o?" chat-tool-failed":""}`,children:[b.jsxs("button",{type:"button",className:"chat-tool-head",onClick:r,"aria-expanded":t.open,children:[b.jsxs("span",{className:"chat-tool-head-left",children:[n?b.jsx(wh,{}):b.jsx(k$,{}),b.jsx("code",{className:"chat-tool-name",children:t.name}),b.jsx("span",{className:"chat-tool-query",children:i?l:`("${a}")`})]}),b.jsxs("span",{className:"chat-tool-head-right",children:[b.jsx("span",{className:"chat-tool-status",children:u}),b.jsx(my,{open:t.open})]})]}),t.open&&b.jsxs("div",{className:"chat-tool-body",children:[b.jsxs("div",{className:"chat-tool-args",children:[b.jsxs("span",{className:"chat-tool-label",children:["arguments",t.arguments_redacted?" · redacted":""]}),b.jsx("pre",{children:t.argumentState==="streaming"&&!t.arguments_redacted&&t.argumentText||JSON.stringify(t.args,null,2)})]}),!n&&i?b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"chat-tool-output-head",children:[b.jsx("span",{className:"chat-tool-label",children:"result"}),b.jsx("button",{type:"button",className:"chat-tool-copy",onClick:()=>void navigator.clipboard.writeText(c),children:"Copy"})]}),b.jsx("pre",{className:"chat-tool-output",children:b.jsx("code",{children:c})}),((d=t.metadata)==null?void 0:d.output_truncated)&&b.jsx("div",{className:"chat-tool-truncated",children:"Output was truncated."})]}):n?null:b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"chat-tool-label chat-tool-results-label",children:["returned ",((f=t.results)==null?void 0:f.length)??0," papers"]}),b.jsx("ol",{className:"chat-tool-results",children:(p=t.results)==null?void 0:p.map(y=>b.jsxs("li",{className:"chat-hit",children:[b.jsx("div",{className:"chat-hit-top",children:b.jsx(wy,{routeId:y.route_id,paper:e[y.route_id],className:"chat-hit-title",children:y.title})}),b.jsx("div",{className:"chat-hit-meta",children:[AV(y.metadata),MV(y.metadata)].filter(Boolean).join(" · ")}),b.jsxs("div",{className:"chat-hit-snippet",children:[IV(y),y.content_truncated&&b.jsx("span",{className:"chat-hit-truncated",children:" (truncated)"})]})]},y.route_id))})]})]})]})},BV=({block:t,papers:e,citations:r,webCitations:n,streaming:s})=>b.jsxs("div",{className:"chat-answer",children:[b.jsx(Uc,{text:t.text,streaming:s,papers:e,citations:r,webCitations:n}),s&&!!t.text.trim()&&b.jsx(d$,{})]}),VV=({block:t})=>b.jsx(iL,{block:t}),f$=t=>{const e=U.useRef(null),r=U.useCallback(()=>{const n=e.current;if(!n)return;n.style.height="auto";const s=Math.max(120,window.innerHeight*.4);n.style.height=`${Math.min(n.scrollHeight,s)}px`,n.style.overflowY=n.scrollHeight>s?"auto":"hidden"},[]);return U.useLayoutEffect(()=>{var n,s;(n=e.current)==null||n.focus(),(s=e.current)==null||s.setSelectionRange(t.length,t.length),r()},[r,t.length]),{textareaRef:e,resize:r}},HV=({id:t,text:e,paperSelection:r,editNotice:n,onCancel:s,onResend:i,onResendDraft:o})=>{const[a,l]=U.useState(e),[c,u]=U.useState(r),[h,d]=U.useState(!1),{textareaRef:f,resize:p}=f$(e);U.useLayoutEffect(p,[p,a]);const y=!!a.trim()&&a.length<=8e3,v=()=>{if(!y||h)return;d(!0),((o==null?void 0:o({text:a,paperMentions:[],...c?{paperSelection:c}:{}}))??(i==null?void 0:i(a))??!1)||d(!1)};return b.jsx("div",{className:"chat-msg chat-msg-user chat-msg-user-editing","data-message-id":t,children:b.jsxs("div",{className:"chat-inline-editor",children:[c&&b.jsx(Sl,{selection:c,editable:!0,onRemove:()=>u(void 0)}),b.jsx("textarea",{ref:f,className:"chat-inline-editor-textarea","aria-label":"Edit message",value:a,maxLength:8e3,onChange:m=>l(m.target.value),onKeyDown:m=>{m.key==="Escape"?(m.preventDefault(),s==null||s()):m.key==="Enter"&&!m.shiftKey&&!m.nativeEvent.isComposing&&(m.preventDefault(),v())}}),n&&b.jsx("div",{className:"chat-inline-editor-notice",children:n}),b.jsxs("div",{className:"chat-inline-editor-actions",children:[b.jsx("button",{type:"button",onClick:s,children:"Cancel"}),b.jsx("button",{type:"button",className:"chat-inline-editor-send",disabled:!y||h,onClick:v,children:"Send"})]})]})})},UV=({id:t,text:e,paperMentions:r,paperSelection:n,enabled:s,editNotice:i,onCancel:o,onResend:a,onResendDraft:l})=>{const[c,u]=U.useState({text:e,paperMentions:r,...n?{paperSelection:n}:{}}),[h,d]=U.useState(!1),[f,p]=U.useState(0),{textareaRef:y,resize:v}=f$(e),m=dy({draft:c,onChange:u,enabled:s,textareaRef:y});U.useLayoutEffect(v,[v,c.text]);const _=!!c.text.trim()&&c.text.length<=8e3&&(s||c.paperMentions.length===0),$=()=>{if(!_||h)return;d(!0),((l==null?void 0:l(c))??(a==null?void 0:a(c.text))??!1)||d(!1)};return b.jsx("div",{className:"chat-msg chat-msg-user chat-msg-user-editing","data-message-id":t,children:b.jsxs("div",{className:"chat-inline-editor",children:[c.paperSelection&&b.jsx(Sl,{selection:c.paperSelection,editable:!0,onRemove:()=>u({text:c.text,paperMentions:c.paperMentions})}),b.jsxs("div",{className:"chat-inline-editor-textarea-wrap",children:[b.jsx(fy,{text:c.text,mentions:c.paperMentions,scrollTop:f,variant:"editor"}),b.jsx("textarea",{ref:y,className:"chat-inline-editor-textarea","aria-label":"Edit message",value:c.text,maxLength:8e3,role:"combobox","aria-autocomplete":"list","aria-expanded":m.open,"aria-controls":m.open?m.pickerId:void 0,"aria-activedescendant":m.open&&m.results.length?`${m.optionIdPrefix}-${m.activeIndex}`:void 0,onChange:E=>m.updateText(E.target.value,E.target.selectionStart),onSelect:E=>m.refresh(E.currentTarget.selectionStart),onScroll:E=>p(E.currentTarget.scrollTop),onKeyDown:E=>{m.keyDown(E)||(E.key==="Escape"?(E.preventDefault(),o==null||o()):E.key==="Enter"&&!E.shiftKey&&!E.nativeEvent.isComposing&&(E.preventDefault(),$()))}}),b.jsx(py,{open:m.open,query:m.query,results:m.results,activeIndex:m.activeIndex,loading:m.loading,error:m.error,onSelect:m.select,id:m.pickerId,optionIdPrefix:m.optionIdPrefix})]}),!s&&c.paperMentions.length>0&&b.jsx("div",{className:"chat-inline-editor-notice",role:"status",children:"Paper mentions are currently disabled. Remove them before sending."}),i&&b.jsx("div",{className:"chat-inline-editor-notice",children:i}),b.jsxs("div",{className:"chat-inline-editor-actions",children:[b.jsx("button",{type:"button",onClick:o,children:"Cancel"}),b.jsx("button",{type:"button",className:"chat-inline-editor-send",disabled:!_||h,onClick:$,children:"Send"})]})]})})},mH=({id:t,text:e,paperMentions:r=[],paperSelection:n,paperMentionsEnabled:s=!1,editingAllowed:i=!1,editing:o=!1,editNotice:a,onEdit:l,onCancel:c,onResend:u,onResendDraft:h})=>{const[d,f]=U.useState(!1),p=U.useRef(null);U.useEffect(()=>()=>{p.current!==null&&window.clearTimeout(p.current)},[]);const y=async()=>{var v;if((v=navigator.clipboard)!=null&&v.writeText)try{await navigator.clipboard.writeText(e),f(!0),p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>f(!1),1500)}catch{}};return o?!s&&r.length===0?b.jsx(HV,{id:t,text:e,paperSelection:n,editNotice:a,onCancel:c,onResend:u,onResendDraft:h}):b.jsx(UV,{id:t,text:e,paperMentions:r,paperSelection:n,enabled:s,editNotice:a,onCancel:c,onResend:u,onResendDraft:h}):b.jsx("div",{className:"chat-msg chat-msg-user","data-message-id":t,children:b.jsxs("div",{className:"chat-user-message-wrap",children:[n&&b.jsx(Sl,{selection:n}),b.jsx("div",{className:"chat-bubble",onDoubleClick:LV,children:b.jsx(zV,{text:e,mentions:r})}),b.jsxs("div",{className:"chat-user-actions",children:[b.jsx("button",{type:"button",className:"chat-user-action","aria-label":d?"Message copied":"Copy message",title:d?"Copied":"Copy",onClick:()=>void y(),children:d?b.jsx(y$,{"aria-hidden":"true"}):b.jsx(N$,{"aria-hidden":"true"})}),i&&b.jsx("button",{type:"button",className:"chat-user-action","aria-label":"Edit message",title:"Edit",onClick:l,children:b.jsx(yy,{"aria-hidden":"true"})})]})]})})},gH=({msg:t,papers:e,onToggleBlock:r,onArchiveOldChats:n,onArchiveOldestChats:s,archivePending:i=null,hfBilling:o=null,openRouterFallbackEnabled:a=!1,feedbackEnabled:l=!1})=>{var R,z,L;const[c,u]=U.useState(null),[h,d]=U.useState(!1),[f,p]=U.useState(!1),[y,v]=U.useState(!1),[m,_]=U.useState(""),$=U.useRef(null),E=`chat-feedback-panel-${t.id}`,x=l&&!t.streaming&&!t.error&&!!((R=t.blocks)!=null&&R.some(H=>H.kind==="answer"&&H.text.trim()));U.useEffect(()=>{var H;y&&((H=$.current)==null||H.focus())},[y]);const P=async(H,O)=>{if(!h){d(!0),p(!1);try{O===void 0?await vp.reportFeedback(t.id,H):await vp.reportFeedback(t.id,H,O),u(H),v(!1),_("")}catch{p(!0)}finally{d(!1)}}};return b.jsx("div",{className:"chat-msg chat-msg-assistant",children:b.jsxs("div",{className:"chat-msg-blocks",children:[(z=t.blocks)==null?void 0:z.map((H,O)=>{var G;const B=`${t.id}-${O}`,Z="citations"in H&&H.citations!==void 0?H.citations:t.citations??[],I=Object.fromEntries(Z.filter(re=>(re.kind==="catalog_paper"||re.kind==="paper"||!re.kind&&re.route_id)&&re.route_id).map(re=>[re.route_id,re])),Q=Object.fromEntries(Z.filter(re=>(re.kind==="external_source"||re.kind==="web")&&re.url).map(re=>[re.url,re]));return H.kind==="reasoning"?b.jsx(FV,{block:H,papers:e,citations:I,webCitations:Q,onToggle:()=>r(t.id,O)},B):H.kind==="tool"?b.jsx(qV,{block:H,papers:e,onToggle:()=>r(t.id,O)},B):H.kind==="app"?b.jsx(VV,{block:H},H.instance_id||B):H.kind==="artifact"?b.jsx(RV,{block:H},H.publication_id||H.version_id||B):b.jsx(BV,{block:H,papers:e,citations:I,webCitations:Q,streaming:!!(t.streaming&&O===(((G=t.blocks)==null?void 0:G.length)??0)-1)},B)}),DV(t)&&b.jsx("div",{className:"chat-waiting",role:"status","aria-live":"polite",children:b.jsx("span",{className:"chat-thinking",children:(((L=t.blocks)==null?void 0:L.length)??0)===0?t.status??"Thinking…":"Thinking…"})}),t.error&&b.jsxs("div",{className:"chat-error",children:[b.jsx("span",{children:t.errorCode==="chat_disabled_interrupted"?"Chat was disabled while this response was running. The partial response is saved. Please try again later.":t.errorCode==="chat_session_quota_exceeded"?t.error:`The assistant hit an error: ${t.error}`}),["hf_inference_billing_required","hf_inference_credential_expired"].includes(t.errorCode??"")&&b.jsx("a",{href:"/settings",children:"Re-sign in with Hugging Face"}),t.errorCode==="hf_inference_billing_exhausted"&&b.jsxs(b.Fragment,{children:[(o==null?void 0:o.account_type)==="Free"&&!o.bill_to?b.jsx("a",{href:OV,target:"_blank",rel:"noreferrer",children:"Upgrade to Hugging Face PRO — $9/month for 20× more included credits"}):b.jsx("a",{href:(o==null?void 0:o.usage_url)??"/settings",target:o?"_blank":void 0,rel:o?"noreferrer":void 0,children:"Review Hugging Face usage and billing"}),b.jsx("a",{href:NV,target:"_blank",rel:"noreferrer",children:"Inference Providers pricing and billing details"})]}),t.errorCode==="openrouter_monthly_budget_exhausted"&&b.jsxs(b.Fragment,{children:[a?b.jsx("span",{children:"This response started on the shared allowance. Your connected OpenRouter key will be used when you explicitly retry."}):b.jsx("a",{href:"/settings#openrouter-byok",children:"Connect your own OpenRouter key"}),b.jsx("span",{children:"Or select a Hugging Face-backed model and explicitly retry."})]}),t.errorCode==="openrouter_staging_funding_disabled"&&b.jsx("a",{href:jV,children:"Continue on paperswithcode.co"}),t.errorCode==="openrouter_unavailable"&&b.jsxs(b.Fragment,{children:[b.jsx("a",{href:"/settings#openrouter-byok",children:"Bring your own key in Settings"}),b.jsx("a",{href:"https://github.com/huggingface/paperswithcode-feedback",target:"_blank",rel:"noreferrer",children:"File an issue"})]}),t.errorCode==="openrouter_byok_billing_error"&&b.jsx("a",{href:"https://openrouter.ai/settings/credits",target:"_blank",rel:"noreferrer",children:"Review OpenRouter billing"}),["openrouter_byok_credential_invalid","openrouter_byok_rate_limit"].includes(t.errorCode??"")&&b.jsx("a",{href:"/settings#openrouter-byok",children:"Review OpenRouter settings"}),t.errorCode==="chat_session_quota_exceeded"&&(n||s)&&b.jsxs("span",{className:"chat-error-actions",children:[n&&b.jsx("button",{type:"button",disabled:i!==null,onClick:n,children:i==="old"?"Archiving…":"Archive chats older than 30 days"}),s&&b.jsx("button",{type:"button",disabled:i!==null,onClick:s,children:i==="oldest"?"Archiving…":"Archive oldest 50 chats"})]})]}),!t.streaming&&t.finishReason&&t.finishReason!=="success"&&b.jsx("div",{className:"chat-finish-note",children:["tool_limit","max_turns"].includes(t.finishReason)?"The assistant stopped at the execution limit.":`The assistant stopped early (${t.finishReason.replace(/_/g," ")}).`}),x&&b.jsxs("div",{className:"chat-feedback","aria-label":"Rate this response",children:[b.jsx("span",{className:"chat-feedback-label",children:c===null?"Was this helpful?":"Thanks for your feedback"}),b.jsx("button",{type:"button",className:`chat-feedback-action${c===!0?" chat-feedback-action-selected":""}`,"aria-label":"Helpful response","aria-pressed":c===!0,disabled:h,onClick:()=>{v(!1),P(!0)},children:b.jsx(F$,{"aria-hidden":"true"})}),b.jsx("button",{type:"button",className:`chat-feedback-action${c===!1?" chat-feedback-action-selected":""}`,"aria-label":"Unhelpful response","aria-pressed":c===!1,"aria-expanded":y,"aria-controls":E,disabled:h,onClick:()=>{p(!1),v(!0)},children:b.jsx(z$,{"aria-hidden":"true"})}),f&&b.jsx("span",{className:"chat-feedback-error",role:"status",children:"Couldn’t send feedback."})]}),x&&y&&b.jsxs("div",{className:"chat-feedback-panel",id:E,role:"group","aria-labelledby":`${E}-title`,children:[b.jsx("div",{className:"chat-feedback-panel-title",id:`${E}-title`,children:"Additional feedback"}),b.jsx("label",{className:"chat-feedback-panel-label",htmlFor:`${E}-comment`,children:"Tell us what went wrong (optional)"}),b.jsx("textarea",{ref:$,id:`${E}-comment`,className:"chat-feedback-comment",value:m,maxLength:500,rows:4,disabled:h,onChange:H=>_(H.target.value),onKeyDown:H=>{H.key==="Escape"&&(H.preventDefault(),v(!1))}}),b.jsxs("div",{className:"chat-feedback-panel-actions",children:[b.jsx("button",{type:"button",className:"chat-feedback-skip",disabled:h,onClick:()=>void P(!1),children:"Skip"}),b.jsx("button",{type:"button",className:"chat-feedback-submit",disabled:h,onClick:()=>void P(!1,m.trim()||void 0),children:h?"Submitting…":"Submit"})]})]})]})})},WV={chat:{breakpoint:760,left:360,right:360},shared:{breakpoint:760,left:360,right:360},reader:{breakpoint:1260,left:840,right:420}};function Bn(t,e,r,n){if(!t)return Math.max(25,Math.min(75,e));const s=Math.max(25,n/t*100),i=Math.min(75,(t-r)/t*100);return Math.max(s,Math.min(i,e))}const yH=({children:t,variant:e})=>{const r=Mo(),n=WV[e],s=U.useRef(null),i=U.useRef(null),o=U.useRef(null),a=U.useRef(null),[l,c]=U.useState(0),u=U.useRef(!1),h=U.useRef(r.state.panelPercent);U.useLayoutEffect(()=>{const m=s.current;if(!m)return;const _=()=>c(m.clientWidth||window.innerWidth);if(_(),typeof ResizeObserver>"u")return;const $=new ResizeObserver(_);return $.observe(m),()=>$.disconnect()},[]);const d=r.state.open&&l>=n.breakpoint,f=Bn(l,r.state.panelPercent,n.left,n.right),p=m=>{var $;const _=Bn(l,m,n.left,n.right);h.current=_,i.current&&(i.current.style.width=`${100-_}%`),o.current&&(o.current.style.width=`${_}%`),($=a.current)==null||$.setAttribute("aria-valuenow",String(Math.round(_)))},y=m=>{var $;const _=($=s.current)==null?void 0:$.getBoundingClientRect();_!=null&&_.width&&p((_.right-m)/_.width*100)},v=()=>{u.current&&(u.current=!1,r.setPanelPercent(h.current))};return b.jsxs("div",{ref:s,className:`chat-artifact-workspace chat-artifact-workspace-${e}${d?" has-docked-artifact":""}`,"data-artifact-layout":d?"split":r.state.open?"dialog":"closed",children:[b.jsx("div",{ref:i,className:"chat-artifact-workspace-content",style:d?{width:`${100-f}%`}:void 0,children:t}),d&&b.jsxs(b.Fragment,{children:[b.jsx("div",{ref:a,className:"chat-artifact-resize-handle",role:"separator","aria-label":"Resize conversation and poster panels","aria-orientation":"vertical","aria-valuemin":Math.ceil(Bn(l,0,n.left,n.right)),"aria-valuemax":Math.floor(Bn(l,100,n.left,n.right)),"aria-valuenow":Math.round(f),tabIndex:0,onPointerDown:m=>{u.current=!0,m.currentTarget.setPointerCapture(m.pointerId),y(m.clientX)},onPointerMove:m=>{u.current&&y(m.clientX)},onPointerUp:v,onPointerCancel:v,onLostPointerCapture:v,onDoubleClick:()=>r.setPanelPercent(55),onKeyDown:m=>{(m.key==="ArrowLeft"||m.key==="ArrowRight")&&(m.preventDefault(),r.setPanelPercent(Bn(l,f+(m.key==="ArrowLeft"?2:-2),n.left,n.right))),m.key==="Home"&&r.setPanelPercent(Bn(l,25,n.left,n.right)),m.key==="End"&&r.setPanelPercent(Bn(l,75,n.left,n.right))}}),b.jsx("div",{ref:o,className:"chat-artifact-workspace-pane",style:{width:`${f}%`},children:b.jsx(cy,{})})]}),r.state.open&&!d&&b.jsx(cy,{forceDialog:!0,readerFallback:e==="reader"})]})};export{pH as A,aH as C,mH as U,yH as a,gH as b,vh as c,Mo as u};