@blocknote/xl-ai 0.42.3 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,39 @@
1
- "use strict";var ot=Object.defineProperty;var rt=(e,t,o)=>t in e?ot(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o;var L=(e,t,o)=>rt(e,typeof t!="symbol"?t+"":t,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const nt=require("@ai-sdk/react"),b=require("@blocknote/core"),$=require("@blocknote/prosemirror-suggest-changes"),H=require("prosemirror-model"),U=require("prosemirror-state"),st=require("prosemirror-tables"),J=require("prosemirror-view"),it=require("y-prosemirror"),at=require("lodash.isequal"),re=require("@ai-sdk/provider-utils"),T=require("ai"),x=require("prosemirror-transform"),ee=require("prosemirror-changeset"),y=require("react/jsx-runtime"),_=require("@blocknote/react"),w=require("react"),Ie=require("zustand"),te=require("@floating-ui/react"),Oe=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},lt=Oe(at),j=Oe(w),me=e=>{let t;const o=new Set,r=(c,u)=>{const m=typeof c=="function"?c(t):c;if(!Object.is(m,t)){const p=t;t=u??(typeof m!="object"||m===null)?m:Object.assign({},t,m),o.forEach(d=>d(t,p))}},n=()=>t,i={setState:r,getState:n,getInitialState:()=>l,subscribe:c=>(o.add(c),()=>o.delete(c))},l=t=e(r,n,i);return i},fe=e=>e?me(e):me;function ct(e){const{properties:t,required:o,$defs:r,...n}=e.inputSchema;return{schema:{type:"object",description:e.description,properties:{type:{type:"string",enum:[e.name]},...t},required:["type",...o??[]],additionalProperties:!1,...n},$defs:r}}function Me(e){const t=e.map(r=>ct(r)),o={};for(const r of t)for(const n in r.$defs){if(o[n]&&!lt.default(o[n],r.$defs[n]))throw new Error(`Duplicate, but different definition for ${n}`);o[n]=r.$defs[n]}return{type:"object",properties:{operations:{type:"array",items:{anyOf:t.map(r=>r.schema)}}},additionalProperties:!1,required:["operations"],$defs:Object.keys(o).length>0?o:void 0}}function Be(e,t){return{async sendAIRequest(o,r){const n=await t(o);return await e(o.chat.messages,n),o.chat.sendMessage(void 0,{...r,body:{...(r==null?void 0:r.body)??{},toolDefinitions:{applyDocumentOperations:{name:"applyDocumentOperations",inputSchema:Me(o.streamTools),outputSchema:{type:"object"}}}},metadata:{promptData:n}})}}}class ne extends Error{constructor(t,o,r){super(t,r),this.chunk=o,this.name="ChunkExecutionError"}}class Ee{constructor(t){L(this,"stream");this.streamTools=t,this.stream=this.createStream()}createStream(){let t;const o=new TransformStream({transform:async(i,l)=>{const c=typeof i=="string"?await ut(i,(t==null?void 0:t.isPossiblyPartial)??!1,this.streamTools):i;c&&(t=c,l.enqueue(c))},flush:i=>{t!=null&&t.isPossiblyPartial&&i.error(new Error("stream ended with a partial operation"))}}),r=o.readable.pipeThrough(this.createExecutor()),[n,s]=r.tee(),a=n.pipeTo(new WritableStream);return{writable:o.writable,readable:s,finishPromise:a}}createExecutor(){const t=this.streamTools.map(o=>o.executor());return new TransformStream({transform:async(o,r)=>{var s;let n=!1;for(const a of t)try{if(await a.execute(o)){r.enqueue({status:"ok",chunk:o}),n=!0;break}}catch(i){throw new ne(`Tool execution failed: ${re.getErrorMessage(i)}`,o,{cause:i})}if(!n){const a=((s=o.operation)==null?void 0:s.type)||"unknown";throw new Error(`No tool could handle operation of type: ${a}`)}}})}get writable(){return this.stream.writable}get readable(){return this.stream.readable}async finish(){await this.stream.finishPromise}async executeOperationsArray(t){const o=this.writable.getWriter();for await(const r of t){const n=await T.parsePartialJson(r);if(n.state==="undefined-input"||n.state==="failed-parse"||!n)return;await o.write(r)}await o.close(),await this.finish()}async execute(t){const o=this.writable.getWriter();for await(const r of t)await o.write(r);await o.close(),await this.finish()}async executeOne(t){await this.execute(async function*(){yield{operation:t,isUpdateToPreviousOperation:!1,isPossiblyPartial:!1,metadata:{}}}())}}async function ut(e,t,o){const r=await T.parsePartialJson(e);if(r.state==="undefined-input"||r.state==="failed-parse"||!r)return;const n=o.find(a=>{var i;return a.name===((i=r.value)==null?void 0:i.type)}),s=n&&n.validate(r.value);if(s!=null&&s.ok)return{operation:s.value,isPossiblyPartial:r.state==="repaired-parse",isUpdateToPreviousOperation:t,metadata:void 0}}function dt(e){return new ReadableStream({async start(t){try{for await(const o of e)t.enqueue(o);t.close()}catch(o){t.error(o)}}})}function _e(e){if(e.locked)throw new Error("Stream (source) is already locked and cannot be iterated.");const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=()=>{if(t.locked)throw new Error("Stream is already locked and cannot be iterated again.");const o=t.getReader();return{async next(){const{done:r,value:n}=await o.read();return r?{done:!0,value:void 0}:{done:!1,value:n}}}},t}function pt(e){return _e(dt(e))}async function*mt(e,t){var s;let o=0,r=!0,n;for await(const a of e)if((s=a.operations)!=null&&s.length){for(let i=o;i<a.operations.length;i++){const l=a.operations[i];n=l,yield{partialOperation:l,isUpdateToPreviousOperation:i===o&&!r,isPossiblyPartial:i===a.operations.length-1,metadata:t},r=!1}o=a.operations.length-1}if(!n)throw new Error("No operations seen");yield{partialOperation:n,isUpdateToPreviousOperation:!0,isPossiblyPartial:!1,metadata:t}}async function*ft(e,t){let o=!1;for await(const r of e){const n=r.operation;n.ok?(yield{operation:n.value,isUpdateToPreviousOperation:o?!1:r.isUpdateToPreviousOperation,isPossiblyPartial:r.isPossiblyPartial,metadata:r.metadata},o=!1):(o=o||!r.isUpdateToPreviousOperation,t==null||t({...r,operation:n}))}}async function*ht(e,t){for await(const o of e){const r=t.find(s=>s.name===o.partialOperation.type);if(!r){yield{operation:{ok:!1,error:`No matching function for ${o.partialOperation.type}`},isUpdateToPreviousOperation:o.isUpdateToPreviousOperation,isPossiblyPartial:o.isPossiblyPartial,metadata:o.metadata};continue}yield{operation:r.validate(o.partialOperation),isUpdateToPreviousOperation:o.isUpdateToPreviousOperation,isPossiblyPartial:o.isPossiblyPartial,metadata:o.metadata}}}async function*yt(e,t){const o=ht(e,t);yield*ft(o,n=>{if(!n.isPossiblyPartial)throw new Error("invalid operation: "+n.operation.error)})}function Ae(e,t,o){return pt(yt(mt(_e(e),o),t))}async function gt(e,t,o){const r=new Ee(e),n=bt();n.output.pipeTo(r.writable);const s=new Map;let a=!0;const i=t["~registerMessagesCallback"](()=>{St(t,d=>{if(!s.has(d.toolCallId)){const h=kt(e,d.toolName,d.toolCallId);n.append(h.operationsStream),s.set(d.toolCallId,h),a&&(a=!1,o==null||o())}return s.get(d.toolCallId)})});await new Promise(d=>{const h=t["~registerStatusCallback"](()=>{(t.status==="ready"||t.status==="error")&&(i(),h(),t.status!=="error"&&f(),d())}),f=t["~registerErrorCallback"](()=>{if(t.error){f();for(const k of s.values())k.complete||k.writer.abort(t.error)}})}),await n.finalize();const c=(await Promise.allSettled([r.finish()]))[0];let u;if(c.status==="rejected"){if(c.reason instanceof ne)u=c.reason;else if(!t.error)throw new Error("Unexpected: no ChunkExecutionError but also no chat.error (network error?)")}let m=!1;const p=Array.from(s.values().filter(d=>d.complete));if(p.forEach((d,h)=>{const f=d.toolCallId===(u==null?void 0:u.chunk.metadata.toolCallId);f&&(m=!0),t.addToolResult({tool:p[h].toolName,toolCallId:p[h].toolCallId,output:m===!1?{status:"ok"}:f?{status:"error",error:re.getErrorMessage(u)}:{status:"not-executed-previous-tool-errored"}})}),u)throw u;if(t.error)throw t.error}function bt(){let e,t=Promise.resolve(),o=!1;const r=new ReadableStream({start(a){e=a},cancel(a){o=!0,e.error(a)}});async function n(a){if(o)throw new Error("Appendable stream canceled, can't append");const i=a.getReader();return t=t.then(async()=>{for(;;)try{const{done:l,value:c}=await i.read();if(l||o)break;e.enqueue(c)}catch(l){o=!0,e.error(l);break}}),t}async function s(){await t,o||e.close()}return{output:r,append:n,finalize:s}}function St(e,t){var o;for(const r of((o=e.lastMessage)==null?void 0:o.parts)??[]){if(!T.isToolUIPart(r)||r.type.replace("tool-","")!=="applyDocumentOperations")continue;const s=r.toolCallId,a=t({toolName:r.type.replace("tool-",""),toolCallId:s});wt(r,a)}}function kt(e,t,o){const r=new TransformStream,n=Ae(r.readable,e,{toolCallId:o});return{writer:r.writable.getWriter(),complete:!1,operationsStream:n,toolName:t,toolCallId:o}}function wt(e,t){if(e.state==="input-streaming"){const o=e.input;o!==void 0&&t.writer.write(o)}else if(e.state==="input-available"){const o=e.input;if(o===void 0)throw new Error("input is undefined");t.complete||(t.complete=!0,t.writer.write(o),t.writer.close())}}function se(e){return(e.type==="paragraph"||!e.type)&&!e.content||Array.isArray(e.content)&&e.content.length===0}function xt(e,t,o=!0,r=!0){let n=0,s=e.length;if(o)for(;n<s&&t(e[n]);)n++;if(r)for(;s>n&&t(e[s-1]);)s--;return e.slice(n,s)}function P(e,t){return xt(e,r=>se(r)&&(t==null?void 0:t.cursorBlockId)!==r.id,(t==null?void 0:t.trimStart)??!1,(t==null?void 0:t.trimEnd)??!0)}function Ne(e){const{useSelection:t,deleteEmptyCursorBlock:o,streamToolsProvider:r}={useSelection:e.useSelection??!1,deleteEmptyCursorBlock:e.deleteEmptyCursorBlock??!0,streamToolsProvider:e.streamToolsProvider??M.html.getStreamToolsProvider()},n=t?void 0:e.editor.getTextCursorPosition().block,s=n&&o&&se(n)&&P(e.editor.document).length>0?n.id:void 0,a=t?e.editor.getSelectionCutBlocks():void 0,i=r.getStreamTools(e.editor,a?{from:a._meta.startPos,to:a._meta.endPos}:void 0,e.onBlockUpdated);return{editor:e.editor,chat:e.chat,userPrompt:e.userPrompt,selectedBlocks:a==null?void 0:a.blocks,streamTools:i,emptyCursorBlockToDelete:s}}async function Le(e){const{aiRequest:t,sender:o,chatRequestOptions:r,onStart:n}=e,s=gt(t.streamTools,t.chat,()=>{n==null||n(),t.emptyCursorBlockToDelete&&t.editor.getBlock(t.emptyCursorBlockToDelete)&&t.editor.removeBlocks([t.emptyCursorBlockToDelete])});await o.sendAIRequest(t,r),await s}function Tt(e,t){e.length>0&&e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the selection (ignore previous selections, you MUST issue operations against this latest version of the selection):"},{type:"text",text:JSON.stringify(t.htmlSelectedBlocks)},{type:"text",text:"This is the latest state of the document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.htmlDocument)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:"The user asks you to do the following:"},{type:"text",text:t.userPrompt}]}),e.push({role:"system",id:"document-state-intro",parts:[{type:"text",text:"You're manipulating a selected part of a text document using HTML blocks. \n Make sure to follow the json schema provided and always include the trailing $ in ids.\n List items are 1 block with 1 list item each, so block content `<ul><li>item1</li></ul>` is valid, but `<ul><li>item1</li><li>item2</li></ul>` is invalid. We'll merge them automatically.\n This is the selection as an array of html blocks:"}]},{role:"system",id:"document-state-selection",parts:[{type:"text",text:JSON.stringify(t.htmlSelectedBlocks)}]},{role:"system",id:"document-state-context",parts:[{type:"text",text:"This is the entire document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.htmlDocument)}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}function vt(e,t){if(e.length>0){e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the document (ignore previous documents, you MUST issue operations against this latest version of the document):"},{type:"text",text:JSON.stringify(t.htmlBlocks)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:t.userPrompt}]});return}e.push({role:"system",id:"document-state-intro",parts:[{type:"text",text:"You're manipulating a text document using HTML blocks. \n Make sure to follow the json schema provided. When referencing ids they MUST be EXACTLY the same (including the trailing $). \n List items are 1 block with 1 list item each, so block content `<ul><li>item1</li></ul>` is valid, but `<ul><li>item1</li><li>item2</li></ul>` is invalid. We'll merge them automatically.\n For code blocks, you can use the `data-language` attribute on a <code> block (wrapped with <pre>) to specify the language.\n This is the initial document as an array of html blocks (the cursor is BETWEEN two blocks as indicated by cursor: true):"}]},{role:"system",id:"document-state-data",parts:[{type:"text",text:JSON.stringify(t.htmlBlocks)}]},{role:"system",id:"extended-instructions",parts:[{type:"text",text:'First, determine what part of the document the user is talking about. You SHOULD probably take cursor info into account if needed.\n EXAMPLE: if user says "below" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor. \n EXAMPLE: If you want to insert content AT the cursor position (UNLESS indicated otherwise by the user), \n then you need `referenceId` to point to the block before the cursor with position `after` (or block below and `before`).\n \n '+(t.isEmptyDocument?"Because the document is empty, first update the empty block before adding new blocks.":"Prefer updating existing blocks over removing and adding (but this also depends on the user's question).")}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}const Pt=async(e,t)=>{t.selection?Tt(e,t):vt(e,t)};function X(e,t){const o=e.getTextCursorPosition(),r=[];for(const n of t){const s=n.id===o.block.id;r.push({id:n.id,block:n.block}),s&&r.push({cursor:!0})}return r}async function B(e,t){return await Promise.all(e.map(async o=>({id:o.id,block:await t(o)})))}function C(e){return e.flatMap(t=>[{...t,children:[]},...C(t.children)])}function D(e){return e.map(t=>typeof t=="object"&&t&&"id"in t?{...t,id:`${t.id}$`}:t)}async function Ct(e){return e.selectedBlocks?{...await De(e.editor,{selectedBlocks:e.selectedBlocks}),userPrompt:e.userPrompt}:{...await je(e.editor,{excludeBlockIds:e.emptyCursorBlockToDelete?[e.emptyCursorBlockToDelete]:void 0}),userPrompt:e.userPrompt}}async function je(e,t){const o=P(e.document).length===0,r=e.getTextCursorPosition().block.id,n=P(e.document,{cursorBlockId:r}),s=await B(C(n),async c=>e.blocksToHTMLLossy([c])),i=X(e,s).filter(c=>"cursor"in c||!(t.excludeBlockIds||[]).includes(c.id));return{selection:!1,htmlBlocks:D(i),isEmptyDocument:o}}async function De(e,t){const o=P(e.document).length===0,r=await B(C(t.selectedBlocks),async s=>e.blocksToHTMLLossy([s])),n=D(r);return{isEmptyDocument:o,selection:!0,htmlSelectedBlocks:n,htmlDocument:(await B(C(e.document),async s=>e.blocksToHTMLLossy([s]))).map(({block:s})=>({block:s}))}}function It(e){let t,o=!1;return e.descendants((r,n)=>o?!1:(r.isText&&(o=!0,t=n),!0)),t}function Z(e){var s;const t=b.getPmSchema(e),{modification:o}=t.marks,r=[],n=new x.Transform(e.before);for(let a=0;a<e.steps.length;a++){const i=e.steps[a],l=new x.Mapping(e.mapping.maps.slice(0,a)).invert();if(i.structure){if(i instanceof x.ReplaceStep){if(i.to!==i.from+1||i.slice.openStart!==0||i.slice.openEnd!==1||i.slice.content.size!==2)throw new Error("Structure change is not in expected format (ReplaceStep)")}else if(i instanceof x.ReplaceAroundStep){if(i.insert!==1||i.slice.size!==2||i.gapTo!==i.to-1||i.gapFrom!==i.from+1)throw new Error("Structure change is not in expected format (ReplaceAroundStep)")}else throw new Error("Step is not a ReplaceStep or ReplaceAroundStep");const S=l.map(i.from),g=i.slice.content.firstChild,O=n.doc.resolve(n.mapping.map(S)).nodeAfter;let v=g.marks||[];g.type!==O.type&&(v=o.create({type:"nodeType",previousValue:O.type.name,newValue:g.type.name}).addToSet(v));const z=new Set([...Object.keys(g.attrs),...Object.keys(O.attrs)]);for(const E of z)g.attrs[E]!==O.attrs[E]&&(v=o.create({type:"attr",attrName:E,previousValue:O.attrs[E],newValue:g.attrs[E]}).addToSet(v));const N=n.steps.length;n.setNodeMarkup(n.mapping.map(S),g.type,g.attrs,v),r.push({prosemirrorSteps:n.steps.slice(N),selection:void 0,type:"replace"});continue}if(!(i instanceof x.ReplaceStep))throw new Error("Step is not a ReplaceStep");const c=l.map(i.from),u=l.map(i.to);if(i.slice.openStart>0||i.slice.openEnd>0)throw new Error("Slice has openStart or openEnd > 0, but structure=false");r.push({prosemirrorSteps:[],selection:{anchor:n.mapping.map(c),head:n.mapping.map(u)},type:"select"});const m=i.slice.content.textBetween(0,i.slice.size),p=m===n.doc.textBetween(n.mapping.map(c),n.mapping.map(u));let d;if(p)d=i.slice.content.size;else if(m.length===0)d=i.slice.content.size;else{const S=It(i.slice.content);if(S===void 0)throw new Error("unexpected: no first character found");d=S+1}let h=n.mapping.map(u);const f=n.mapping.map(u);let k=!0;for(let S=d;S<=i.slice.content.size;S++){const g=k&&c!==u,O=n.steps.length;if(g){const N=n.doc.resolve(n.mapping.map(c));(s=N.nodeAfter)!=null&&s.isBlock&&n.addNodeMark(N.pos,t.mark("deletion",{})),n.addMark(N.pos,h,t.mark("deletion",{})),h=n.mapping.map(u)}const v=new H.Slice(i.slice.content.cut(0,S),0,0);n.replace(f,h,v).addMark(f,f+v.content.size,t.mark("insertion",{})),n.doc.nodesBetween(f,f+v.content.size,(N,E)=>E<f||E>f+v.content.size?!0:(N.isBlock&&n.addNodeMark(E,t.mark("insertion",{})),!1)),h=n.mapping.slice(O).map(h);const z=U.TextSelection.near(n.doc.resolve(f+v.content.size),-1);r.push({prosemirrorSteps:n.steps.slice(O),selection:{anchor:z.from,head:z.from},type:g?"replace":"insert"}),k=!1}}return r}async function ie(e){const t=Math.random()*.3+.85;if(e.type==="select")await new Promise(o=>setTimeout(o,100*t));else if(e.type==="insert")await new Promise(o=>setTimeout(o,10*t));else if(e.type==="replace")await new Promise(o=>setTimeout(o,200*t));else throw new b.UnreachableCaseError(e.type)}function ae(e,t){e.setMeta("addToHistory",!1),t.selection&&e.setMeta("aiAgent",{selection:{anchor:t.selection.anchor,head:t.selection.head}});for(const o of t.prosemirrorSteps)if(e.maybeStep(o).failed)throw new Error("failed to apply step");return e}function Ot(e,t,o){const r=new x.Transform(t);for(const a of e){const i=new x.ReplaceStep(r.mapping.map(a.fromA),r.mapping.map(a.toA),o.slice(a.fromB,a.toB));r.step(i)}const n=r.mapping.invert();let s=r.doc.content.findDiffStart(o.content);for(;s!==null;){const a=o.resolve(s).nodeAfter,i=r.doc.resolve(s).nodeAfter;if(!a||!i)throw new Error("diffNode not found");const l=!a.isLeaf&&a.content.eq(i.content),c=l?1:Math.min(a.nodeSize,i.nodeSize),u=s+c,m=n.map(s),p=n.map(u);let d=e.length;for(let f=0;f<e.length;f++)if(e[f].fromA>=p){d=f;break}e.splice(d,0,{fromA:m,toA:p,fromB:s,toB:u,deleted:[],inserted:[],type:l?"node-type-or-attr-update":"mark-update"}),r.step(new x.ReplaceStep(s,u,o.slice(s,u),l));const h=r.doc.content.findDiffStart(o.content);if(h===s)throw new Error("diffStart not moving");s=h}return e}const he=(e,t)=>{const o=new Set,r=new Set;e.descendants(a=>{a.type.name==="tableCell"&&o.add(JSON.stringify(a.toJSON()))}),t.descendants(a=>{a.type.name==="tableCell"&&r.add(JSON.stringify(a.toJSON()))});const n=new Set([...o].filter(a=>r.has(a)));return{encodeCharacter:a=>a,encodeNodeStart:a=>{if(a.type.name==="tableCell"){const i=JSON.stringify(a.toJSON());return n.has(i)?i:a.type.name}return a.type.name},encodeNodeEnd:a=>{if(a.type.name==="tableCell"){const i=JSON.stringify(a.toJSON());return n.has(i)?i:-1}return-1},compareTokens:(a,i)=>a===i}};function Q(e,t,o=!1,r,n){const s=b.getNodeById(e.id,t),a=new x.Transform(t);b.updateBlockTr(a,s.posBeforeNode,e.block,r,n);let i=a.doc,l=ee.ChangeSet.create(t,void 0,he(t,i));if(l=l.addSteps(i,a.mapping.maps,0),o&&l.changes.length>0){const m=l.changes[l.changes.length-1],p=m.toA-m.fromA,d=m.toB-m.fromB;if(p>d){const h=t.slice(m.fromA+d,m.toA);a.step(new x.ReplaceStep(m.toB,m.toB,h)),i=a.doc,l=ee.ChangeSet.create(l.startDoc,void 0,he(l.startDoc,i)),l=l.addSteps(i,a.mapping.maps,0)}}const c=[],u=ee.simplifyChanges(l.changes,i);for(let m=0;m<u.length;m++){const p=u[m],d=i.slice(p.fromB,p.toB);if(d.openEnd===1&&d.openStart===0&&(p.type="node-type-or-attr-update",d.size>2)){const h={fromA:p.fromA,toA:p.fromA+1,fromB:p.fromB,toB:p.fromB+1,deleted:[],inserted:[],type:"node-type-or-attr-update"},f={fromA:p.fromA+1,toA:p.toA,fromB:p.fromB+1,toB:p.toB,deleted:[],inserted:[]};u.splice(m,1,h,f),m++}}Ot(u,t,i);for(let m=0;m<u.length;m++){const p=u[m],d=i.slice(p.fromB,p.toB);if(d.openEnd>0&&d.size>1)throw new Error("unexpected, openEnd > 0 and size > 1, this should have been split into two steps");m===u.length-1&&o&&p.type==="mark-update"||c.push(new x.ReplaceStep(p.fromA,p.toA,d,p.type==="node-type-or-attr-update"))}return c}function Mt(e,t){if(!e||!Array.isArray(e)||e.length===0)return{ok:!1,error:"blocks is required"};const o=[];for(const r of e){const n=t(r);if(!n.ok)return{ok:!1,error:`Invalid block: ${n.error}`};o.push(n.value)}return{ok:!0,value:o}}function le(e){return(t,o)=>{const r=typeof e.schema=="function"?e.schema(t):e.schema;return{name:"add",description:e.description,inputSchema:{type:"object",properties:{referenceId:{type:"string",description:"MUST be an id of a block in the document"},position:{type:"string",enum:["before","after"],description:"`after` to add blocks AFTER (below) the block with `referenceId`, `before` to add the block BEFORE (above)"},blocks:{items:r.block,type:"array"}},required:["referenceId","position","blocks"],$defs:r.$defs},validate:n=>{if(n.type!=="add")return{ok:!1,error:"invalid operation type"};if(n.position!=="before"&&n.position!=="after")return{ok:!1,error:"invalid position"};if(!n.referenceId||!n.blocks)return{ok:!1,error:"referenceId and blocks are required"};let s=n.referenceId;if(o.idsSuffixed){if(!(s!=null&&s.endsWith("$")))return{ok:!1,error:"referenceId must end with $"};s=s.slice(0,-1)}if(!t.getBlock(s))return{ok:!1,error:"referenceId not found"};const i=Mt(n.blocks,l=>e.validateBlock(l,t));return i.ok?{ok:!0,value:{type:n.type,referenceId:s,position:n.position,blocks:i.value}}:i},executor:()=>{let n=[];const s={};return{execute:async a=>{var c;if(a.isUpdateToPreviousOperation||(n=[]),a.operation.type!=="add")return!1;const i=a.operation,l=await e.toJSONToolCall(t,{...a,operation:i});if(!l||a.isPossiblyPartial&&se(l.blocks[l.blocks.length-1]))return!0;for(let u=0;u<l.blocks.length;u++){const m=l.blocks[u],p=t.prosemirrorState.tr;let d=[];if(u<n.length){const h=await e.rebaseTool(n[u],t),k=Q({id:n[u],block:m},h.doc,!1).map(S=>S.map(h.invertMap));for(const S of k)p.step(S.map(p.mapping));d=Z(p),d=d.filter(S=>S.type!=="select")}else{const h=i.position==="after"?s[i.referenceId]:void 0,f=b.insertBlocks(p,[m],u>0?n[u-1]:h||i.referenceId,u>0?"after":i.position);n.push(...f.map(k=>k.id)),d=Z(p)}for(const h of d)o.withDelays&&await ie(h),t.transact(f=>{ae(f,h)}),(c=o.onBlockUpdate)==null||c.call(o,n[u])}return a.isPossiblyPartial||i.position==="after"&&(s[i.referenceId]=n[n.length-1]),!0}}}}}}function ce(e){return(t,o)=>{const r=typeof e.schema=="function"?e.schema(t):e.schema;return{name:"update",description:e.description,inputSchema:{type:"object",properties:{id:{type:"string",description:"id of block to update"},block:r.block},required:["id","block"],$defs:r.$defs},validate:n=>{if(n.type!=="update")return{ok:!1,error:"invalid operation type"};if(!n.id)return{ok:!1,error:"id is required"};let s=n.id;if(o.idsSuffixed){if(!(s!=null&&s.endsWith("$")))return{ok:!1,error:"id must end with $"};s=s.slice(0,-1)}if(!n.block)return{ok:!1,error:"block is required"};const a=t.getBlock(s);if(!a)return console.error("BLOCK NOT FOUND",s),{ok:!1,error:"block not found"};const i=e.validateBlock(n.block,t,a.type);return i.ok?{ok:!0,value:{type:n.type,id:s,block:i.value}}:i},executor:()=>{let s=50;const a=o.updateSelection?{from:b.trackPosition(t,o.updateSelection.from),to:b.trackPosition(t,o.updateSelection.to)}:void 0;return{execute:async i=>{var S;if(i.operation.type!=="update")return!1;const l=i.operation;if(i.isPossiblyPartial){const g=JSON.stringify(l.block).length;if(g<s)return!0;s=g+50}else s=50;const c=await e.rebaseTool(l.id,t),u=a?c.invertMap.invert().map(a.from()):void 0,m=a?c.invertMap.invert().map(a.to()):void 0,p=await e.toJSONToolCall(t,{...i,operation:l});if(!p)return!0;const d=Q(p,c.doc,i.isPossiblyPartial,u,m);if(d.length===1&&i.isPossiblyPartial)return!0;const h=d.map(g=>g.map(c.invertMap)),f=new x.Transform(t.prosemirrorState.doc);for(const g of h)f.step(g.map(f.mapping));const k=Z(f);for(const g of k)o.withDelays&&await ie(g),t.transact(O=>{ae(O,g)}),(S=o.onBlockUpdate)==null||S.call(o,l.id);return!0}}}}}}const ue=(e,t)=>({name:"delete",description:"Delete a block",inputSchema:{type:"object",properties:{id:{type:"string",description:"id of block to delete"}},required:["id"]},validate:o=>{if(o.type!=="delete")return{ok:!1,error:"invalid operation type"};if(!o.id)return{ok:!1,error:"id is required"};let r=o.id;if(t.idsSuffixed){if(!(r!=null&&r.endsWith("$")))return{ok:!1,error:"id must end with $"};r=r.slice(0,-1)}return e.getBlock(r)?{ok:!0,value:{type:"delete",id:r}}:{ok:!1,error:"block not found"}},executor:()=>({execute:async o=>{var a;if(o.operation.type!=="delete")return!1;const r=o.operation,n=e.prosemirrorState.tr;b.removeAndInsertBlocks(n,[r.id],[]);const s=Z(n);for(const i of s)t.withDelays&&await ie(i),e.transact(l=>{ae(l,i)}),(a=t.onBlockUpdate)==null||a.call(t,r.id);return!0}})});function ye(e){const t=e.lastIndexOf("<"),o=e.lastIndexOf(">");let r=e;if(t>o&&(r=e.substring(0,t),!r.trim()))return;const n=r.match(/&[a-zA-Z0-9]*$/);n&&(r=r.substring(0,r.length-n[0].length));const i=new DOMParser().parseFromString(`<div>${r}</div>`,"text/html").body.firstChild;return i?i.innerHTML:""}function W(e){let t;if($.applySuggestions(e.prosemirrorState,o=>{t=o}),!t)throw new Error("applySuggestionsTr is not set");return t}function Y(e,t){const o=t.mapping.invert();return{doc:t.doc,tr:()=>new x.Transform(t.doc),invertMap:o,rebaseTr:r=>{if(r.steps.length===0)throw new Error("No steps to apply");let n=e.prosemirrorState.tr;for(const s of r.steps){const a=s.map(o);if(!a)throw new Error("Step is not mapped");n=n.step(a)}return n}}}async function ge(e,t){var c;const o=W(t),r=b.getBlock(o.doc,e);if(!r)throw new Error("block not found");const n=await t.blocksToHTMLLossy([{...r,children:[]}]),s=(c=window.__TEST_OPTIONS)==null?void 0:c.mockID,a=await t.tryParseHTMLToBlocks(n);if(window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=s),a.length!==1)throw new Error("html diff invalid block count");const i=a[0];if(i.id=e,Q({id:e,block:i},o.doc).length)throw new Error("html diff");return Y(t,o)}function be(e){return typeof e!="string"?{ok:!1,error:"block must be a string"}:{ok:!0,value:e}}const R={add:le({description:"Insert new blocks",schema:{block:{type:"string",description:"html of block (MUST be a single, VALID HTML element)"}},validateBlock:be,rebaseTool:ge,toJSONToolCall:async(e,t)=>{var n;const o=(n=window.__TEST_OPTIONS)==null?void 0:n.mockID,r=(await Promise.all(t.operation.blocks.map(async s=>{const a=t.isPossiblyPartial?ye(s):s;return a?(await e.tryParseHTMLToBlocks(a)).map(i=>(delete i.id,i)):[]}))).flat();if(window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=o),r.length!==0)return{...t.operation,blocks:r}}}),update:ce({description:"Update a block",schema:{block:{type:"string",description:"html of block (MUST be a single HTML element)"}},validateBlock:be,rebaseTool:ge,toJSONToolCall:async(e,t)=>{const o=t.isPossiblyPartial?ye(t.operation.block):t.operation.block;if(!o)return;const r=(await e.tryParseHTMLToBlocks(o))[0];return window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=void 0),delete r.id,{...t.operation,block:r}}}),delete:ue};function Bt(e,t,o,r,n){if(typeof r=="boolean"){const i=r?e.getSelectionCutBlocks():void 0;r=i?{from:i._meta.startPos,to:i._meta.endPos}:void 0}const s=o??{add:!0,update:!0,delete:!0};return[...s.update?[R.update(e,{idsSuffixed:!0,withDelays:t,updateSelection:r,onBlockUpdate:n})]:[],...s.add?[R.add(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:n})]:[],...s.delete?[R.delete(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:n})]:[]]}const Et={getStreamToolsProvider:(e={})=>({getStreamTools:(t,o,r)=>Bt(t,e.withDelays??!0,e.defaultStreamTools,o,r)}),tools:R,defaultPromptBuilder:Pt,defaultPromptInputDataBuilder:Ct,promptHelpers:{getDataForPromptNoSelection:je,getDataForPromptWithSelection:De}};async function _t(e){return e.selectedBlocks?{...await $e(e.editor,{selectedBlocks:e.selectedBlocks}),userPrompt:e.userPrompt}:{...await qe(e.editor,{excludeBlockIds:e.emptyCursorBlockToDelete?[e.emptyCursorBlockToDelete]:void 0}),userPrompt:e.userPrompt}}async function qe(e,t){const o=P(e.document).length===0,r=e.getTextCursorPosition().block.id,n=P(e.document,{cursorBlockId:r}),s=await B(C(n),async c=>({...c,children:void 0})),i=X(e,s).filter(c=>"cursor"in c||!(t.excludeBlockIds||[]).includes(c.id));return{selection:!1,jsonBlocks:D(i),isEmptyDocument:o}}async function $e(e,t){const o=P(e.document).length===0,r=await B(C(t.selectedBlocks),async s=>s),n=D(r);return{isEmptyDocument:o,selection:!0,jsonSelectedBlocks:n,jsonDocument:(await B(C(e.document),async s=>({...s,id:void 0,children:void 0}))).map(({block:s})=>({block:s}))}}function At(e){const t={},o={};return e.forEach(n=>{const{type:s,...a}=n.properties,i=JSON.stringify(a);t[i]?t[i].push(s.enum[0]):(t[i]=[s.enum[0]],o[i]=n)}),Object.keys(t).map(n=>{const s=o[n];return{...s,properties:{...s.properties,type:{type:"string",enum:t[n]}}}})}function Nt(e){return{type:"object",properties:Object.fromEntries(Object.entries(e).map(([t,o])=>[t,{type:o.propSchema}])),additionalProperties:!1}}function Lt(){return{type:"object",properties:{type:{type:"string",enum:["text"]},text:{type:"string"},styles:{$ref:"#/$defs/styles"}},additionalProperties:!1,required:["type","text"]}}function He(e){return{type:"object",properties:Object.fromEntries(Object.entries(e).filter(([t,o])=>o.default!==void 0).map(([t,o])=>[t,{type:typeof o.default,enum:o.values}])),additionalProperties:!1}}function jt(e){return{type:"array",items:{anyOf:Object.entries(e).map(([t,o])=>o==="text"?{$ref:"#/$defs/styledtext"}:o==="link"?{type:"object",properties:{type:{type:"string",enum:["link"]},content:{type:"array",items:{$ref:"#/$defs/styledtext"}},href:{type:"string"}},additionalProperties:!1,required:["type","href","content"]}:{type:"object",properties:{type:{type:"string",enum:[o.type]},content:o.content==="styled"?{type:"array",items:{$ref:"#/$defs/styledtext"}}:void 0,props:He(o.propSchema)},additionalProperties:!1,required:["type",...o.content==="styled"?["content"]:[]]})}}}function Dt(e){return{anyOf:At(Object.entries(e).map(([t,o])=>({type:"object",properties:{type:{type:"string",enum:[o.type]},content:o.content==="inline"?{$ref:"#/$defs/inlinecontent"}:o.content==="table"?{type:"object",properties:{}}:void 0,props:He(o.propSchema)},additionalProperties:!1,required:["type"]})))}}function qt(e){const t=JSON.parse(JSON.stringify({blockSchema:e.blockSchema,inlineContentSchema:e.inlineContentSchema,styleSchema:e.styleSchema}));return{removeFileBlocks(){return t.blockSchema=Object.fromEntries(Object.entries(t.blockSchema).filter(([o,r])=>{var n;return!((n=e.blockSpecs[r.type].implementation.meta)!=null&&n.fileBlockAccept)})),this},removeDefaultProps(){return t.blockSchema=Object.fromEntries(Object.entries(t.blockSchema).map(([o,r])=>[o,{...r,propSchema:Object.fromEntries(Object.entries(r.propSchema).filter(n=>typeof b.defaultProps[n[0]]>"u"))}])),this},get(){return t}}}function Se(e){return e=qt(e).removeFileBlocks().removeDefaultProps().get(),{$defs:{styles:Nt(e.styleSchema),styledtext:Lt(),inlinecontent:jt(e.inlineContentSchema),block:Dt(e.blockSchema)}}}function Ue(e,t){return!t.schema.inlineContentSchema[e.type]||b.isStyledTextInlineContent(e)&&!("text"in e)?!1:b.isLinkInlineContent(e)?!("content"in e)||!("href"in e)?!1:Ue(e.content,t):!0}function ke(e,t,o){const r=e.type||o,n=t.schema.blockSchema[r];if(!n)return{ok:!1,error:"block type not found in editor"};if(e.children,n.content==="none"){if(e.content)return{ok:!1,error:"block content not expected for this block type"}}else{if(!e.content)return{ok:!0,value:e};if(!Array.isArray(e.content))return{ok:!1,error:"block content must be an array"};if(n.content==="table")return{ok:!0,value:e};if(!e.content.every(s=>Ue(s,t)))return{ok:!1,error:"block content must be an array of inline content"}}return{ok:!0,value:e}}const V={add:le({description:"Insert new blocks",schema:e=>({block:{$ref:"#/$defs/block"},...Se(e.schema)}),validateBlock:ke,rebaseTool:async(e,t)=>Y(t,W(t)),toJSONToolCall:async(e,t)=>t.operation}),update:ce({description:"Update a block, the new block will replace the existing block.",schema:e=>({block:{$ref:"#/$defs/block"},...Se(e.schema)}),validateBlock:ke,rebaseTool:async(e,t)=>Y(t,W(t)),toJSONToolCall:async(e,t)=>{const o=Object.fromEntries(Object.entries(b.defaultProps).map(([r,n])=>[r,n.default]));return{...t.operation,block:{...t.operation.block,props:{...o,...t.operation.block.props}}}}}),delete:ue};function $t(e,t){e.length>0&&e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the selection (ignore previous selections, you MUST issue operations against this latest version of the selection):"},{type:"text",text:JSON.stringify(t.jsonSelectedBlocks)},{type:"text",text:"This is the latest state of the document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.jsonDocument)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:"The user asks you to do the following:"},{type:"text",text:t.userPrompt}]}),e.push({role:"system",id:"document-state-intro",parts:[{type:"text",text:`You're manipulating a selected part of a text document using JSON blocks.
1
+ "use strict";var Gh=Object.defineProperty;var Kh=(e,t,n)=>t in e?Gh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Qo=(e,t,n)=>Kh(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xh=require("@ai-sdk/react"),ee=require("@blocknote/core"),D=require("prosemirror-state"),v=require("@tiptap/core"),X=require("prosemirror-model"),te=require("prosemirror-tables"),G=require("prosemirror-view"),oe=require("prosemirror-transform"),Ie=require("y-prosemirror"),Qh=require("remark-stringify"),Jh=require("unified"),Nn=require("@blocknote/prosemirror-suggest-changes"),Zh=require("lodash.isequal"),Vi=require("@ai-sdk/provider-utils"),Le=require("ai"),Ds=require("prosemirror-changeset"),q=require("react/jsx-runtime"),me=require("@blocknote/react"),Te=require("react"),Jo=require("@floating-ui/react"),Yi=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},ef=Yi(Qh),tf=Yi(Zh),Nt=Yi(Te);function nf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var rf=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,s,i;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(s=r;s--!==0;)if(!e(t[s],n[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(i=Object.keys(t),r=i.length,r!==Object.keys(n).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[s]))return!1;for(s=r;s--!==0;){var o=i[s];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n};const sf=nf(rf);var hr,of=new Uint8Array(16);function af(){if(!hr&&(hr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!hr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return hr(of)}const uf=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function lf(e){return typeof e=="string"&&uf.test(e)}var ce=[];for(var vs=0;vs<256;++vs)ce.push((vs+256).toString(16).substr(1));function cf(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=(ce[e[t+0]]+ce[e[t+1]]+ce[e[t+2]]+ce[e[t+3]]+"-"+ce[e[t+4]]+ce[e[t+5]]+"-"+ce[e[t+6]]+ce[e[t+7]]+"-"+ce[e[t+8]]+ce[e[t+9]]+"-"+ce[e[t+10]]+ce[e[t+11]]+ce[e[t+12]]+ce[e[t+13]]+ce[e[t+14]]+ce[e[t+15]]).toLowerCase();if(!lf(n))throw TypeError("Stringified UUID is invalid");return n}function al(e,t,n){e=e||{};var r=e.random||(e.rng||af)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,cf(r)}function df(e,t=JSON.stringify){const n={};return e.filter(r=>{const s=t(r);return Object.prototype.hasOwnProperty.call(n,s)?!1:n[s]=!0})}function hf(e){const t=e.filter((n,r)=>e.indexOf(n)!==r);return df(t)}const ul=v.Extension.create({name:"uniqueID",priority:1e4,addOptions(){return{attributeName:"id",types:[],setIdAttribute:!1,generateID:()=>{if(typeof window<"u"&&window.__TEST_OPTIONS){const e=window.__TEST_OPTIONS;return e.mockID===void 0?e.mockID=0:e.mockID++,e.mockID.toString()}return al()},filterTransaction:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{[this.options.attributeName]:{default:null,parseHTML:e=>e.getAttribute(`data-${this.options.attributeName}`),renderHTML:e=>{const t={[`data-${this.options.attributeName}`]:e[this.options.attributeName]};return this.options.setIdAttribute?{...t,id:e[this.options.attributeName]}:t}}}}]},addProseMirrorPlugins(){let e=null,t=!1;return[new D.Plugin({key:new D.PluginKey("uniqueID"),appendTransaction:(n,r,s)=>{const i=n.some(p=>p.docChanged)&&!r.doc.eq(s.doc),o=this.options.filterTransaction&&n.some(p=>{var m,E;return!((E=(m=this.options).filterTransaction)!=null&&E.call(m,p))});if(!i||o)return;const{tr:a}=s,{types:u,attributeName:c,generateID:d}=this.options,h=v.combineTransactionSteps(r.doc,n),{mapping:f}=h;if(v.getChangedRanges(h).forEach(({newRange:p})=>{const m=v.findChildrenInRange(s.doc,p,k=>u.includes(k.type.name)),E=m.map(({node:k})=>k.attrs[c]).filter(k=>k!==null),C=hf(E);m.forEach(({node:k,pos:_})=>{var N;const L=(N=a.doc.nodeAt(_))==null?void 0:N.attrs[c];if(L===null){const O=r.doc.type.createAndFill().content;if(r.doc.content.findDiffStart(O)===null){const j=JSON.parse(JSON.stringify(s.doc.toJSON()));if(j.content[0].content[0].attrs.id="initialBlockId",JSON.stringify(j.content)===JSON.stringify(O.toJSON())){a.setNodeMarkup(_,void 0,{...k.attrs,[c]:"initialBlockId"});return}}a.setNodeMarkup(_,void 0,{...k.attrs,[c]:d()});return}const{deleted:U}=f.invert().mapResult(_);U&&C.includes(L)&&a.setNodeMarkup(_,void 0,{...k.attrs,[c]:d()})})}),!!a.steps.length)return a.setMeta("uniqueID",!0),a},view(n){const r=s=>{let i;e=!((i=n.dom.parentElement)===null||i===void 0)&&i.contains(s.target)?n.dom.parentElement:null};return window.addEventListener("dragstart",r),{destroy(){window.removeEventListener("dragstart",r)}}},props:{handleDOMEvents:{drop:(n,r)=>{let s;return e!==n.dom.parentElement||((s=r.dataTransfer)===null||s===void 0?void 0:s.effectAllowed)==="copy"?t=!0:t=!1,e=null,!1},paste:()=>(t=!0,!1)},transformPasted:n=>{if(!t)return n;const{types:r,attributeName:s}=this.options,i=o=>{const a=[];return o.forEach(u=>{if(u.isText){a.push(u);return}if(!r.includes(u.type.name)){a.push(u.copy(i(u.content)));return}const c=u.type.create({...u.attrs,[s]:null},i(u.content),u.marks);a.push(c)}),X.Fragment.from(a)};return t=!1,new X.Slice(i(n.content),n.openStart,n.openEnd)}}})]}});function Zo(e){return e.type==="link"}function ll(e){return typeof e!="string"&&e.type==="link"}function an(e){return typeof e!="string"&&e.type==="text"}function hi(e){var t,n,r,s,i;return $i(e)?{...e}:Hn(e)?{type:"tableCell",content:[].concat(e.content),props:{backgroundColor:((t=e.props)==null?void 0:t.backgroundColor)??"default",textColor:((n=e.props)==null?void 0:n.textColor)??"default",textAlignment:((r=e.props)==null?void 0:r.textAlignment)??"left",colspan:((s=e.props)==null?void 0:s.colspan)??1,rowspan:((i=e.props)==null?void 0:i.rowspan)??1}}:{type:"tableCell",content:[].concat(e),props:{backgroundColor:"default",textColor:"default",textAlignment:"left",colspan:1,rowspan:1}}}function Hn(e){return e!=null&&typeof e!="string"&&!Array.isArray(e)&&e.type==="tableCell"}function $i(e){return Hn(e)&&e.props!==void 0&&e.content!==void 0}function Fn(e){return $i(e)?e.props.colspan??1:1}function fi(e){return $i(e)?e.props.rowspan??1:1}class gn extends Error{constructor(t){super(`Unreachable case: ${t}`)}}function ji(e,t){const n=e.resolve(t);if(n.nodeAfter&&n.nodeAfter.type.isInGroup("bnBlock"))return{posBeforeNode:n.pos,node:n.nodeAfter};let r=n.depth,s=n.node(r);for(;r>0;){if(s.type.isInGroup("bnBlock"))return{posBeforeNode:n.before(r),node:s};r--,s=n.node(r)}const i=[];e.descendants((a,u)=>{a.type.isInGroup("bnBlock")&&i.push(u)}),console.warn(`Position ${t} is not within a blockContainer node.`);const o=e.resolve(i.find(a=>a>=t)||i[i.length-1]);return{posBeforeNode:o.pos,node:o.nodeAfter}}function qi(e,t){if(!e.type.isInGroup("bnBlock"))throw new Error(`Attempted to get bnBlock node at position but found node of different type ${e.type.name}`);const n=e,r=t,s=r+n.nodeSize,i={node:n,beforePos:r,afterPos:s};if(n.type.name==="blockContainer"){let o,a;if(n.forEach((u,c)=>{if(u.type.spec.group==="blockContent"){const d=u,h=r+c+1,f=h+u.nodeSize;o={node:d,beforePos:h,afterPos:f}}else if(u.type.name==="blockGroup"){const d=u,h=r+c+1,f=h+u.nodeSize;a={node:d,beforePos:h,afterPos:f}}}),!o)throw new Error(`blockContainer node does not contain a blockContent node in its children: ${n}`);return{isBlockContainer:!0,bnBlock:i,blockContent:o,childContainer:a,blockNoteType:o.node.type.name}}else{if(!i.node.type.isInGroup("childContainer"))throw new Error(`bnBlock node is not in the childContainer group: ${i.node}`);return{isBlockContainer:!1,bnBlock:i,childContainer:i,blockNoteType:i.node.type.name}}}function Vn(e){return qi(e.node,e.posBeforeNode)}function ff(e){if(!e.nodeAfter)throw new Error(`Attempted to get blockContainer node at position ${e.pos} but a node at this position does not exist`);return qi(e.nodeAfter,e.pos)}function cl(e){const t=ji(e.doc,e.selection.anchor);return Vn(t)}function pf(e){const t=ji(e.doc,e.selection.anchor);return Vn(t)}function bt(e){return"doc"in e?e.doc.type.schema:e.type.schema}function dl(e){return e.cached.blockNoteEditor}function zi(e){return dl(e).schema}function mf(e){return zi(e).blockSchema}function gf(e){return zi(e).inlineContentSchema}function as(e){return zi(e).styleSchema}function bf(e){return dl(e).blockCache}function Ef(e,t,n){var r,s;const i={type:"tableContent",columnWidths:[],headerRows:void 0,headerCols:void 0,rows:[]},o=[];e.content.forEach((a,u,c)=>{const d={cells:[]};c===0&&a.content.forEach(h=>{let f=h.attrs.colwidth;f==null&&(f=new Array(h.attrs.colspan??1).fill(void 0)),i.columnWidths.push(...f)}),d.cells=a.content.content.map((h,f)=>(o[c]||(o[c]=[]),o[c][f]=h.type.name==="tableHeader",{type:"tableCell",content:h.content.content.map(p=>Wi(p,t,n)).reduce((p,m)=>{if(!p.length)return m;const E=p[p.length-1],C=m[0];return C&&an(E)&&an(C)&&JSON.stringify(E.styles)===JSON.stringify(C.styles)?(E.text+=`
2
+ `+C.text,p.push(...m.slice(1)),p):(p.push(...m),p)},[]),props:{colspan:h.attrs.colspan,rowspan:h.attrs.rowspan,backgroundColor:h.attrs.backgroundColor,textColor:h.attrs.textColor,textAlignment:h.attrs.textAlignment}})),i.rows.push(d)});for(let a=0;a<o.length;a++)(r=o[a])!=null&&r.every(u=>u)&&(i.headerRows=(i.headerRows??0)+1);for(let a=0;a<((s=o[0])==null?void 0:s.length);a++)o!=null&&o.every(u=>u[a])&&(i.headerCols=(i.headerCols??0)+1);return i}function Wi(e,t,n){const r=[];let s;return e.content.forEach(i=>{if(i.type.name==="hardBreak"){if(s)if(an(s))s.text+=`
3
+ `;else if(Zo(s))s.content[s.content.length-1].text+=`
4
+ `;else throw new Error("unexpected");else s={type:"text",text:`
5
+ `,styles:{}};return}if(i.type.name!=="link"&&i.type.name!=="text"){if(!t[i.type.name]){console.warn("unrecognized inline content type",i.type.name);return}s&&(r.push(s),s=void 0),r.push(hl(i,t,n));return}const o={};let a;for(const u of i.marks)if(u.type.name==="link")a=u;else{const c=n[u.type.name];if(!c){if(u.type.spec.blocknoteIgnore)continue;throw new Error(`style ${u.type.name} not found in styleSchema`)}if(c.propSchema==="boolean")o[c.type]=!0;else if(c.propSchema==="string")o[c.type]=u.attrs.stringValue;else throw new gn(c.propSchema)}s?an(s)?a?(r.push(s),s={type:"link",href:a.attrs.href,content:[{type:"text",text:i.textContent,styles:o}]}):JSON.stringify(s.styles)===JSON.stringify(o)?s.text+=i.textContent:(r.push(s),s={type:"text",text:i.textContent,styles:o}):Zo(s)&&(a?s.href===a.attrs.href?JSON.stringify(s.content[s.content.length-1].styles)===JSON.stringify(o)?s.content[s.content.length-1].text+=i.textContent:s.content.push({type:"text",text:i.textContent,styles:o}):(r.push(s),s={type:"link",href:a.attrs.href,content:[{type:"text",text:i.textContent,styles:o}]}):(r.push(s),s={type:"text",text:i.textContent,styles:o})):a?s={type:"link",href:a.attrs.href,content:[{type:"text",text:i.textContent,styles:o}]}:s={type:"text",text:i.textContent,styles:o}}),s&&r.push(s),r}function hl(e,t,n){if(e.type.name==="text"||e.type.name==="link")throw new Error("unexpected");const r={},s=t[e.type.name];for(const[o,a]of Object.entries(e.attrs)){if(!s)throw Error("ic node is of an unrecognized type: "+e.type.name);const u=s.propSchema;o in u&&(r[o]=a)}let i;return s.content==="styled"?i=Wi(e,t,n):i=void 0,{type:e.type.name,props:r,content:i}}function un(e,t,n=mf(t),r=gf(t),s=as(t),i=bf(t)){var o;if(!e.type.isInGroup("bnBlock"))throw Error("Node should be a bnBlock, but is instead: "+e.type.name);const a=i==null?void 0:i.get(e);if(a)return a;const u=qi(e,0);let c=u.bnBlock.node.attrs.id;c===null&&(c=ul.options.generateID());const d=n[u.blockNoteType];if(!d)throw Error("Block is of an unrecognized type: "+u.blockNoteType);const h={};for(const[C,k]of Object.entries({...e.attrs,...u.isBlockContainer?u.blockContent.node.attrs:{}})){const _=d.propSchema;C in _&&!(_[C].default===void 0&&k===void 0)&&(h[C]=k)}const f=n[u.blockNoteType],p=[];(o=u.childContainer)==null||o.node.forEach(C=>{p.push(un(C,t,n,r,s,i))});let m;if(f.content==="inline"){if(!u.isBlockContainer)throw new Error("impossible");m=Wi(u.blockContent.node,r,s)}else if(f.content==="table"){if(!u.isBlockContainer)throw new Error("impossible");m=Ef(u.blockContent.node,r,s)}else if(f.content==="none")m=void 0;else throw new gn(f.content);const E={id:c,type:f.type,props:h,content:m,children:p};return i==null||i.set(e,E),E}function At(e){const{height:t,width:n}=Gi(e),r=new Array(t).fill(!1).map(()=>new Array(n).fill(null)),s=(i,o)=>{for(let a=i;a<t;a++)for(let u=o;u<n;u++)if(!r[a][u])return{row:a,col:u};throw new Error("Unable to create occupancy grid for table, no more available cells")};for(let i=0;i<e.content.rows.length;i++)for(let o=0;o<e.content.rows[i].cells.length;o++){const a=hi(e.content.rows[i].cells[o]),u=fi(a),c=Fn(a),{row:d,col:h}=s(i,o);for(let f=d;f<d+u;f++)for(let p=h;p<h+c;p++){if(r[f][p])throw new Error(`Unable to create occupancy grid for table, cell at ${f},${p} is already occupied`);r[f][p]={row:i,col:o,rowspan:u,colspan:c,cell:a}}}return r}function Yn(e){const t=new Set;return e.map(n=>({cells:n.map(r=>t.has(r.row+":"+r.col)?!1:(t.add(r.row+":"+r.col),r.cell)).filter(r=>r!==!1)}))}function Mt(e,t,n=At(t)){for(let r=0;r<n.length;r++)for(let s=0;s<n[r].length;s++){const i=n[r][s];if(i.row===e.row&&i.col===e.col)return{row:r,col:s,cell:i.cell}}throw new Error(`Unable to resolve relative table cell indices for table, cell at ${e.row},${e.col} is not occupied`)}function Gi(e){const t=e.content.rows.length;let n=0;return e.content.rows.forEach(r=>{let s=0;r.cells.forEach(i=>{s+=Fn(i)}),n=Math.max(n,s)}),{height:t,width:n}}function fl(e,t,n=At(t)){var r;const s=(r=n[e.row])==null?void 0:r[e.col];if(s)return{row:s.row,col:s.col,cell:s.cell}}function pi(e,t){var n;const r=At(e);if(t<0||t>=r.length)return[];let s=0;for(let o=0;o<t;o++){const a=(n=r[s])==null?void 0:n[0];if(!a)return[];s+=a.rowspan}const i=new Array(r[0].length).fill(!1).map((o,a)=>fl({row:s,col:a},e,r)).filter(o=>o!==void 0);return i.filter((o,a)=>i.findIndex(u=>u.row===o.row&&u.col===o.col)===a)}function mi(e,t){var n;const r=At(e);if(t<0||t>=r[0].length)return[];let s=0;for(let o=0;o<t;o++){const a=(n=r[0])==null?void 0:n[s];if(!a)return[];s+=a.colspan}const i=new Array(r.length).fill(!1).map((o,a)=>fl({row:a,col:s},e,r)).filter(o=>o!==void 0);return i.filter((o,a)=>i.findIndex(u=>u.row===o.row&&u.col===o.col)===a)}function Tf(e,t,n,r=At(e)){const{col:s}=Mt({row:0,col:t},e,r),{col:i}=Mt({row:0,col:n},e,r);return r.forEach(o=>{const[a]=o.splice(s,1);o.splice(i,0,a)}),Yn(r)}function yf(e,t,n,r=At(e)){const{row:s}=Mt({row:t,col:0},e,r),{row:i}=Mt({row:n,col:0},e,r),[o]=r.splice(s,1);return r.splice(i,0,o),Yn(r)}function gi(e){return e?Hn(e)?gi(e.content):typeof e=="string"?e.length===0:Array.isArray(e)?e.every(t=>typeof t=="string"?t.length===0:an(t)?t.text.length===0:ll(t)?typeof t.content=="string"?t.content.length===0:t.content.every(n=>n.text.length===0):!1):!1:!0}function Cf(e,t,n=At(e)){if(t==="columns"){let i=0;for(let o=n[0].length-1;o>=0&&n.every(a=>gi(a[o].cell)&&a[o].colspan===1);o--)i++;for(let o=n.length-1;o>=0;o--){const a=Math.max(n[o].length-i,1);n[o]=n[o].slice(0,a)}return Yn(n)}let r=0;for(let i=n.length-1;i>=0&&n[i].every(o=>gi(o.cell)&&o.rowspan===1);i--)r++;const s=Math.min(r,n.length-1);return n.splice(n.length-s,s),Yn(n)}function kf(e,t,n,r=At(e)){const{width:s,height:i}=Gi(e);if(t==="columns")r.forEach((o,a)=>{if(n>=0)for(let u=0;u<n;u++)o.push({row:a,col:Math.max(...o.map(c=>c.col))+1,rowspan:1,colspan:1,cell:hi("")});else o.splice(s+n,-1*n)});else if(n>0)for(let o=0;o<n;o++){const a=new Array(s).fill(null).map((u,c)=>({row:i+o,col:c,rowspan:1,colspan:1,cell:hi("")}));r.push(a)}else n<0&&r.splice(i+n,-1*n);return Yn(r)}function pl(e,t,n){const r=pi(e,n);if(!r.some(o=>fi(o.cell)>1))return!0;let s=n,i=n;return r.forEach(o=>{const a=fi(o.cell);s=Math.max(s,o.row+a-1),i=Math.min(i,o.row)}),t<n?n===s:n===i}function ml(e,t,n){const r=mi(e,n);if(!r.some(o=>Fn(o.cell)>1))return!0;let s=n,i=n;return r.forEach(o=>{const a=Fn(o.cell);s=Math.max(s,o.col+a-1),i=Math.min(i,o.col)}),t<n?n===s:n===i}function Sf(e,t,n){const r=Mt(e,n),s=Mt(t,n);return r.col===s.col}function ea(e,t,n,r){const s=[];for(const[i,o]of Object.entries(e.styles||{})){const a=n[i];if(!a)throw new Error(`style ${i} not found in styleSchema`);if(a.propSchema==="boolean")o&&s.push(t.mark(i));else if(a.propSchema==="string")o&&s.push(t.mark(i,{stringValue:o}));else throw new gn(a.propSchema)}return!r||!t.nodes[r].spec.code?e.text.split(/(\n)/g).filter(i=>i.length>0).map(i=>i===`
6
+ `?t.nodes.hardBreak.createChecked():t.text(i,s)):e.text.length>0?[t.text(e.text,s)]:[]}function Af(e,t,n){const r=t.marks.link.create({href:e.href});return bi(e.content,t,n).map(s=>{if(s.type.name==="text")return s.mark([...s.marks,r]);if(s.type.name==="hardBreak")return s;throw new Error("unexpected node type")})}function bi(e,t,n,r){const s=[];if(typeof e=="string")return s.push(...ea({text:e,styles:{}},t,n,r)),s;for(const i of e)s.push(...ea(i,t,n,r));return s}function Et(e,t,n,r=as(t)){const s=[];for(const i of e)typeof i=="string"?s.push(...bi(i,t,r,n)):ll(i)?s.push(...Af(i,t,r)):an(i)?s.push(...bi([i],t,r,n)):s.push(gl(i,t,r));return s}function Ki(e,t,n=as(t)){const r=[],s=new Array(e.headerRows??0).fill(!0),i=new Array(e.headerCols??0).fill(!0),o=e.columnWidths??[];for(let a=0;a<e.rows.length;a++){const u=e.rows[a],c=[],d=s[a];for(let f=0;f<u.cells.length;f++){const p=u.cells[f],m=i[f],E=void 0;let C=null;const k=Mt({row:a,col:f},{content:e});let _=o[k.col]?[o[k.col]]:null;if(p)if(typeof p=="string")C=t.text(p);else if(Hn(p)){p.content&&(C=Et(p.content,t,"tableParagraph",n));const L=Fn(p);L>1&&(_=new Array(L).fill(!1).map((U,O)=>o[k.col+O]??void 0))}else C=Et(p,t,"tableParagraph",n);const N=t.nodes[m||d?"tableHeader":"tableCell"].createChecked({...Hn(p)?p.props:{},colwidth:_},t.nodes.tableParagraph.createChecked(E,C));c.push(N)}const h=t.nodes.tableRow.createChecked({},c);r.push(h)}return r}function gl(e,t,n){let r,s=e.type;if(s===void 0&&(s="paragraph"),!t.nodes[s])throw new Error(`node type ${s} not found in schema`);if(!e.content)r=t.nodes[s].createChecked(e.props);else if(typeof e.content=="string"){const i=Et([e.content],t,s,n);r=t.nodes[s].createChecked(e.props,i)}else if(Array.isArray(e.content)){const i=Et(e.content,t,s,n);r=t.nodes[s].createChecked(e.props,i)}else if(e.content.type==="tableContent"){const i=Ki(e.content,t,n);r=t.nodes[s].createChecked(e.props,i)}else throw new gn(e.content.type);return r}function us(e,t,n=as(t)){let r=e.id;r===void 0&&(r=ul.options.generateID());const s=[];if(e.children)for(const i of e.children)s.push(us(i,t,n));if(!e.type||t.nodes[e.type].isInGroup("blockContent")){const i=gl(e,t,n),o=s.length>0?t.nodes.blockGroup.createChecked({},s):void 0;return t.nodes.blockContainer.createChecked({id:r,...e.props},o?[i,o]:i)}else{if(t.nodes[e.type].isInGroup("bnBlock"))return t.nodes[e.type].createChecked({id:r,...e.props},s);throw new Error(`block type ${e.type} doesn't match blockContent or bnBlock group`)}}const Zt=new WeakMap,_r=new WeakMap,Ur={current:[]};let Ms=!1;const fr=new Set,ta=new Map;function bl(e){const t=Array.from(e).sort((n,r)=>n instanceof en&&n.options.deps.includes(r)?1:r instanceof en&&r.options.deps.includes(n)?-1:0);for(const n of t){if(Ur.current.includes(n))continue;Ur.current.push(n),n.recompute();const r=_r.get(n);if(r)for(const s of r){const i=Zt.get(s);i&&bl(i)}}}function _f(e){const t={prevVal:e.prevState,currentVal:e.state};for(const n of e.listeners)n(t)}function wf(e){const t={prevVal:e.prevState,currentVal:e.state};for(const n of e.listeners)n(t)}function If(e){if(fr.add(e),!Ms)try{for(Ms=!0;fr.size>0;){const t=Array.from(fr);fr.clear();for(const n of t){const r=ta.get(n)??n.prevState;n.prevState=r,_f(n)}for(const n of t){const r=Zt.get(n);r&&(Ur.current.push(n),bl(r))}for(const n of t){const r=Zt.get(n);if(r)for(const s of r)wf(s)}}}finally{Ms=!1,Ur.current=[],ta.clear()}}function xf(e){return typeof e=="function"}class Ei{constructor(t,n){this.listeners=new Set,this.subscribe=r=>{var s,i;this.listeners.add(r);const o=(i=(s=this.options)==null?void 0:s.onSubscribe)==null?void 0:i.call(s,r,this);return()=>{this.listeners.delete(r),o==null||o()}},this.prevState=t,this.state=t,this.options=n}setState(t){var n,r,s;this.prevState=this.state,(n=this.options)!=null&&n.updateFn?this.state=this.options.updateFn(this.prevState)(t):xf(t)?this.state=t(this.prevState):this.state=t,(s=(r=this.options)==null?void 0:r.onUpdate)==null||s.call(r),If(this)}}class en{constructor(t){this.listeners=new Set,this._subscriptions=[],this.lastSeenDepValues=[],this.getDepVals=()=>{const n=this.options.deps.length,r=new Array(n),s=new Array(n);for(let i=0;i<n;i++){const o=this.options.deps[i];r[i]=o.prevState,s[i]=o.state}return this.lastSeenDepValues=s,{prevDepVals:r,currDepVals:s,prevVal:this.prevState??void 0}},this.recompute=()=>{var n,r;this.prevState=this.state;const s=this.getDepVals();this.state=this.options.fn(s),(r=(n=this.options).onUpdate)==null||r.call(n)},this.checkIfRecalculationNeededDeeply=()=>{for(const i of this.options.deps)i instanceof en&&i.checkIfRecalculationNeededDeeply();let n=!1;const r=this.lastSeenDepValues,{currDepVals:s}=this.getDepVals();for(let i=0;i<s.length;i++)if(s[i]!==r[i]){n=!0;break}n&&this.recompute()},this.mount=()=>(this.registerOnGraph(),this.checkIfRecalculationNeededDeeply(),()=>{this.unregisterFromGraph();for(const n of this._subscriptions)n()}),this.subscribe=n=>{var r,s;this.listeners.add(n);const i=(s=(r=this.options).onSubscribe)==null?void 0:s.call(r,n,this);return()=>{this.listeners.delete(n),i==null||i()}},this.options=t,this.state=t.fn({prevDepVals:void 0,prevVal:void 0,currDepVals:this.getDepVals().currDepVals})}registerOnGraph(t=this.options.deps){for(const n of t)if(n instanceof en)n.registerOnGraph(),this.registerOnGraph(n.options.deps);else if(n instanceof Ei){let r=Zt.get(n);r||(r=new Set,Zt.set(n,r)),r.add(this);let s=_r.get(this);s||(s=new Set,_r.set(this,s)),s.add(n)}}unregisterFromGraph(t=this.options.deps){for(const n of t)if(n instanceof en)this.unregisterFromGraph(n.options.deps);else if(n instanceof Ei){const r=Zt.get(n);r&&r.delete(this);const s=_r.get(this);s&&s.delete(n)}}}const na=Symbol("originalFactory");function $(e){if(typeof e=="object"&&"key"in e)return function t(){return e[na]=t,e};if(typeof e!="function")throw new Error("factory must be a function");return function t(n){return r=>{const s=e({editor:r.editor,options:n});return s[na]=t,s}}}function Ht(e,t){return new Ei(e,t)}var ra=(e,t)=>{if(e==="slot")return 0;if(e instanceof Function)return e(t);const{children:n,...r}=t??{};if(e==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[e,r,n]},Nf=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,Lf=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,Of=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,Df=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,vf=v.Mark.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:e=>e.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:e=>e.type.name===this.name},{style:"font-weight",getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}]},renderHTML({HTMLAttributes:e}){return ra("strong",{...v.mergeAttributes(this.options.HTMLAttributes,e),children:ra("slot",{})})},markdownTokenName:"strong",parseMarkdown:(e,t)=>t.applyMark("bold",t.parseInline(e.tokens||[])),renderMarkdown:(e,t)=>`**${t.renderChildren(e)}**`,addCommands(){return{setBold:()=>({commands:e})=>e.setMark(this.name),toggleBold:()=>({commands:e})=>e.toggleMark(this.name),unsetBold:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[v.markInputRule({find:Nf,type:this.type}),v.markInputRule({find:Of,type:this.type})]},addPasteRules(){return[v.markPasteRule({find:Lf,type:this.type}),v.markPasteRule({find:Df,type:this.type})]}}),Mf=vf,Rf=/(^|[^`])`([^`]+)`(?!`)$/,Pf=/(^|[^`])`([^`]+)`(?!`)/g,Bf=v.Mark.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:e}){return["code",v.mergeAttributes(this.options.HTMLAttributes,e),0]},markdownTokenName:"codespan",parseMarkdown:(e,t)=>t.applyMark("code",[{type:"text",text:e.text||""}]),renderMarkdown:(e,t)=>e.content?`\`${t.renderChildren(e.content)}\``:"",addCommands(){return{setCode:()=>({commands:e})=>e.setMark(this.name),toggleCode:()=>({commands:e})=>e.toggleMark(this.name),unsetCode:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[v.markInputRule({find:Rf,type:this.type})]},addPasteRules(){return[v.markPasteRule({find:Pf,type:this.type})]}}),Uf=Bf,Hf=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Ff=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Vf=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Yf=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,$f=v.Mark.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:e=>e.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:e=>e.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:e}){return["em",v.mergeAttributes(this.options.HTMLAttributes,e),0]},addCommands(){return{setItalic:()=>({commands:e})=>e.setMark(this.name),toggleItalic:()=>({commands:e})=>e.toggleMark(this.name),unsetItalic:()=>({commands:e})=>e.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(e,t)=>t.applyMark("italic",t.parseInline(e.tokens||[])),renderMarkdown:(e,t)=>`*${t.renderChildren(e)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[v.markInputRule({find:Hf,type:this.type}),v.markInputRule({find:Vf,type:this.type})]},addPasteRules(){return[v.markPasteRule({find:Ff,type:this.type}),v.markPasteRule({find:Yf,type:this.type})]}}),jf=$f,qf=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,zf=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Wf=v.Mark.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:e=>e.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:e}){return["s",v.mergeAttributes(this.options.HTMLAttributes,e),0]},markdownTokenName:"del",parseMarkdown:(e,t)=>t.applyMark("strike",t.parseInline(e.tokens||[])),renderMarkdown:(e,t)=>`~~${t.renderChildren(e)}~~`,addCommands(){return{setStrike:()=>({commands:e})=>e.setMark(this.name),toggleStrike:()=>({commands:e})=>e.toggleMark(this.name),unsetStrike:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[v.markInputRule({find:qf,type:this.type})]},addPasteRules(){return[v.markPasteRule({find:zf,type:this.type})]}}),Gf=Wf,Kf=v.Mark.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:e=>e.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:e}){return["u",v.mergeAttributes(this.options.HTMLAttributes,e),0]},parseMarkdown(e,t){return t.applyMark(this.name||"underline",t.parseInline(e.tokens||[]))},renderMarkdown(e,t){return`++${t.renderChildren(e)}++`},markdownTokenizer:{name:"underline",level:"inline",start(e){return e.indexOf("++")},tokenize(e,t,n){const s=/^(\+\+)([\s\S]+?)(\+\+)/.exec(e);if(!s)return;const i=s[2].trim();return{type:"underline",raw:s[0],text:i,tokens:n.inlineTokens(i)}}},addCommands(){return{setUnderline:()=>({commands:e})=>e.setMark(this.name),toggleUnderline:()=>({commands:e})=>e.toggleMark(this.name),unsetUnderline:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}}),Xf=Kf,Qf=class El{constructor(t){this.cache=new Map(t)}get(t){return this.cache.get(t)}set(t,n,r){t<0||this.cache.set(t,[n,r])}replace(t,n,r,s){this.remove(t),this.set(n,r,s)}remove(t){this.cache.delete(t)}invalidate(t){const n=new El(this.cache),r=t.mapping;return this.cache.forEach(([s,i],o)=>{if(o<0)return;const a=r.mapResult(o),u=t.doc.nodeAt(a.pos);if(a.deleted||!(u!=null&&u.eq(s)))n.remove(o);else if(o!==a.pos){const c=i.map(d=>d.map(r,0,0)).filter(d=>d!=null);n.replace(o,a.pos,u,c)}}),n}};function Jf({parser:e,nodeTypes:t=["code_block","codeBlock"],languageExtractor:n=r=>r.attrs.language}){const r=new D.PluginKey("prosemirror-highlight");return new D.Plugin({key:r,state:{init(s,i){const o=new Qf,[a,u]=sa(i.doc,e,t,n,o);return{cache:o,decorations:a,promises:u}},apply:(s,i)=>{const o=i.cache.invalidate(s),a=!!s.getMeta("prosemirror-highlight-refresh");if(!s.docChanged&&!a){const d=i.decorations.map(s.mapping,s.doc),h=i.promises;return{cache:o,decorations:d,promises:h}}const[u,c]=sa(s.doc,e,t,n,o);return{cache:o,decorations:u,promises:c}}},view:s=>{const i=new Set,o=()=>{if(i.size>0)return;const u=s.state.tr.setMeta("prosemirror-highlight-refresh",!0);s.dispatch(u)},a=()=>{var u;const c=r.getState(s.state);for(const d of(u=c==null?void 0:c.promises)!=null?u:[])i.add(d),d.then(()=>{i.delete(d),o()}).catch(()=>{i.delete(d)})};return a(),{update:()=>{a()}}},props:{decorations(s){var i;return(i=this.getState(s))==null?void 0:i.decorations}}})}function sa(e,t,n,r,s){const i=[],o=[];return e.descendants((a,u)=>{if(!a.type.isTextblock)return!0;if(n.includes(a.type.name)){const c=r(a),d=s.get(u);if(d){const[h,f]=d;i.push(...f)}else{const h=t({content:a.textContent,language:c||void 0,pos:u,size:a.nodeSize});h&&Array.isArray(h)?(s.set(u,a,h),i.push(...h)):h instanceof Promise&&(s.remove(u),o.push(h))}}return!1}),[G.DecorationSet.create(e,i),o]}function Zf(e,t){return function({content:r,language:s,pos:i,size:o}){var a;const u=[],{tokens:c,fg:d,bg:h,rootStyle:f}=e.codeToTokens(r,{lang:s,theme:e.getLoadedThemes()[0]}),p=f||(d&&h?`--prosemirror-highlight:${d};--prosemirror-highlight-bg:${h}`:"");if(p){const E=G.Decoration.node(i,i+o,{style:p});u.push(E)}let m=i+1;for(const E of c){for(const C of E){const k=m+C.content.length,_=G.Decoration.inline(m,k,{style:ep((a=C.htmlStyle)!=null?a:`color: ${C.color}`),class:"shiki"});u.push(_),m=k}m+=1}return u}}function ep(e){return typeof e=="string"?e:Object.entries(e).map(([t,n])=>`${t}:${n}`).join(";")}var tp=Object.defineProperty,np=(e,t,n)=>t in e?tp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wt=(e,t,n)=>np(e,typeof t!="symbol"?t+"":t,n);function $n(...e){return[...new Set(e.filter(t=>t).join(" ").split(" "))].join(" ")}function rp(e,t,n,r){const s=document.createElement("div");s.className=$n("bn-block-content",n.class),s.setAttribute("data-content-type",e);for(const[o,a]of Object.entries(n))o!=="class"&&s.setAttribute(o,a);const i=document.createElement(t);i.className=$n("bn-inline-content",r.class);for(const[o,a]of Object.entries(r))o!=="class"&&i.setAttribute(o,a);return s.appendChild(i),{dom:s,contentDOM:i}}const ia=(e,t)=>{let n=us(e,t.pmSchema);n.type.name==="blockContainer"&&(n=n.firstChild);const r=t.pmSchema.nodes[n.type.name].spec.toDOM;if(r===void 0)throw new Error("This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`.");const s=r(n);if(typeof s!="object"||!("dom"in s))throw new Error("Cannot use this block's default HTML serialization as its corresponding TipTap node's `renderHTML` function does not return an object with the `dom` property.");return s};function sp(e){return"data-"+e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function oa(e,t,n,r,s=!1,i){const o=document.createElement("div");if(i!==void 0)for(const[a,u]of Object.entries(i))a!=="class"&&o.setAttribute(a,u);o.className=$n("bn-block-content",(i==null?void 0:i.class)||""),o.setAttribute("data-content-type",t);for(const[a,u]of Object.entries(n)){const c=r[a].default;u!==c&&o.setAttribute(sp(a),u)}return s&&o.setAttribute("data-file-block",""),o.appendChild(e.dom),e.contentDOM&&(e.contentDOM.className=$n("bn-inline-content",e.contentDOM.className)),{...e,dom:o}}function ip(e,t,n){return{config:{type:e.type,content:e.content,propSchema:t},implementation:{node:e.node,render:ia,toExternalHTML:ia},extensions:n}}function Ne(e,t,n){return(r={})=>{const s=typeof e=="function"?e(r):e,i=typeof t=="function"?t(r):t,o=n?typeof n=="function"?n(r):n:void 0;return{config:s,implementation:{...i,toExternalHTML(a,u){var c,d;const h=(c=i.toExternalHTML)==null?void 0:c.call({blockContentDOMAttributes:this.blockContentDOMAttributes},a,u);if(h!==void 0)return oa(h,a.type,a.props,s.propSchema,((d=i.meta)==null?void 0:d.fileBlockAccept)!==void 0)},render(a,u){var c;const d=i.render.call({blockContentDOMAttributes:this.blockContentDOMAttributes,renderType:this.renderType,props:this.props},a,u);return oa(d,a.type,a.props,s.propSchema,((c=i.meta)==null?void 0:c.fileBlockAccept)!==void 0,this.blockContentDOMAttributes)}},extensions:o}}}function op(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.config]))}function ap(e){return e==="boolean"?{}:{stringValue:{default:void 0,keepOnSplit:!0,parseHTML:t=>t.getAttribute("data-value"),renderHTML:t=>t.stringValue!==void 0?{"data-value":t.stringValue}:{}}}}function pr(e,t,n,r){return e.dom.setAttribute("data-style-type",t),r==="string"&&e.dom.setAttribute("data-value",n),e.contentDOM&&e.contentDOM.setAttribute("data-editable",""),e}function Tl(e,t){return{config:e,implementation:t}}function An(e,t){return Tl({type:e.name,propSchema:t},{mark:e,render(n,r){const s=r.pmSchema.marks[e.name].spec.toDOM;if(s===void 0)throw new Error("This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`.");const i=r.pmSchema.mark(e.name,{stringValue:n}),o=X.DOMSerializer.renderSpec(document,s(i,!0));if(typeof o!="object"||!("dom"in o))throw new Error("Cannot use this block's default HTML serialization as its corresponding TipTap mark's `renderHTML` function does not return an object with the `dom` property.");return o},toExternalHTML(n,r){const s=r.pmSchema.marks[e.name].spec.toDOM;if(s===void 0)throw new Error("This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`.");const i=r.pmSchema.mark(e.name,{stringValue:n}),o=X.DOMSerializer.renderSpec(document,s(i,!0));if(typeof o!="object"||!("dom"in o))throw new Error("Cannot use this block's default HTML serialization as its corresponding TipTap mark's `renderHTML` function does not return an object with the `dom` property.");return o}})}function up(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.config]))}function lp(e,t){const n=[{tag:`[data-style-type="${e.type}"]`,contentElement:r=>{const s=r;return s.matches("[data-editable]")?s:s.querySelector("[data-editable]")||s}}];return t&&n.push({tag:"*",consuming:!1,getAttrs(r){if(typeof r=="string")return!1;const s=t==null?void 0:t(r);return s===void 0?!1:{stringValue:s}}}),n}function yl(e,t){const n=v.Mark.create({name:e.type,addAttributes(){return ap(e.propSchema)},parseHTML(){return lp(e,t.parse)},renderHTML({mark:r}){const s=(t.toExternalHTML||t.render)(r.attrs.stringValue);return pr(s,e.type,r.attrs.stringValue,e.propSchema)},addMarkView(){return({mark:r})=>{const s=t.render(r.attrs.stringValue);return pr(s,e.type,r.attrs.stringValue,e.propSchema)}}});return Tl(e,{...t,mark:n,render:r=>{const s=t.render(r);return pr(s,e.type,r,e.propSchema)},toExternalHTML:r=>{const s=(t.toExternalHTML||t.render)(r);return pr(s,e.type,r,e.propSchema)}})}function Cl(e,t){let n,r;if(t.firstChild.descendants((s,i)=>n?!1:!Xi(s)||s.attrs.id!==e?!0:(n=s,r=i+1,!1)),!(n===void 0||r===void 0))return{node:n,posBeforeNode:r}}function Xi(e){return e.type.isInGroup("bnBlock")}function cp(e,t,n,r,s){const i=ff(e.doc.resolve(t));let o=null;i.blockNoteType==="table"&&(o=hp(e));const a=bt(e),u=a.nodes[i.blockNoteType],c=a.nodes[n.type||i.blockNoteType],d=c.isInGroup("bnBlock")?c:a.nodes.blockContainer;if(i.isBlockContainer&&c.isInGroup("blockContent"))aa(n,e,i),dp(n,e,u,c,i);else if(!i.isBlockContainer&&c.isInGroup("bnBlock"))aa(n,e,i);else{const h=un(i.bnBlock.node,a);e.replaceWith(i.bnBlock.beforePos,i.bnBlock.afterPos,us({children:h.children,...n},a));return}e.setNodeMarkup(i.bnBlock.beforePos,d,{...i.bnBlock.node.attrs,...n.props}),o&&fp(e,i,o)}function dp(e,t,n,r,s,i,o){const a=bt(t);let u="keep";if(e.content)if(typeof e.content=="string")u=Et([e.content],a,r.name);else if(Array.isArray(e.content))u=Et(e.content,a,r.name);else if(e.content.type==="tableContent")u=Ki(e.content,a);else throw new gn(e.content.type);else n.spec.content===""||r.spec.content!==n.spec.content&&(u=[]);u==="keep"?t.setNodeMarkup(s.blockContent.beforePos,r,{...s.blockContent.node.attrs,...e.props}):t.replaceWith(s.blockContent.beforePos,s.blockContent.afterPos,r.createChecked({...s.blockContent.node.attrs,...e.props},u))}function aa(e,t,n){const r=bt(t);if(e.children!==void 0&&e.children.length>0){const s=e.children.map(i=>us(i,r));if(n.childContainer)t.step(new oe.ReplaceStep(n.childContainer.beforePos+1,n.childContainer.afterPos-1,new X.Slice(X.Fragment.from(s),0,0)));else{if(!n.isBlockContainer)throw new Error("impossible");t.insert(n.blockContent.afterPos,r.nodes.blockGroup.createChecked({},s))}}}function hp(e){const t="selection"in e?e.selection:null;if(!(t instanceof D.TextSelection))return null;const n=e.doc.resolve(t.head);let r=-1,s=-1;for(let E=n.depth;E>=0;E--){const C=n.node(E).type.name;if(r<0&&(C==="tableCell"||C==="tableHeader")&&(r=E),C==="table"){s=E;break}}if(r<0||s<0)return null;const i=n.before(r),o=n.before(s),a=e.doc.nodeAt(o);if(!a||a.type.name!=="table")return null;const u=te.TableMap.get(a),c=i-(o+1),d=u.map.indexOf(c);if(d<0)return null;const h=Math.floor(d/u.width),f=d%u.width,p=i+1+1,m=Math.max(0,t.head-p);return{row:h,col:f,offset:m}}function fp(e,t,n){var r;if(t.blockNoteType!=="table")return!1;let s=-1;if(t.isBlockContainer)s=e.mapping.map(t.blockContent.beforePos);else{const C=e.mapping.map(t.bnBlock.beforePos),k=C+(((r=e.doc.nodeAt(C))==null?void 0:r.nodeSize)||0);e.doc.nodesBetween(C,k,(_,N)=>_.type.name==="table"?(s=N,!1):!0)}const i=s>=0?e.doc.nodeAt(s):null;if(!i||i.type.name!=="table")return!1;const o=te.TableMap.get(i),a=Math.max(0,Math.min(n.row,o.height-1)),u=Math.max(0,Math.min(n.col,o.width-1)),c=a*o.width+u,d=o.map[c];if(d==null)return!1;const h=s+1+d+1,f=e.doc.nodeAt(h),p=h+1,m=f?f.content.size:0,E=p+Math.max(0,Math.min(n.offset,m));return"selection"in e&&e.setSelection(D.TextSelection.create(e.doc,E)),!0}const pt={gray:{text:"#9b9a97",background:"#ebeced"},brown:{text:"#64473a",background:"#e9e5e3"},red:{text:"#e03e3e",background:"#fbe4e4"},orange:{text:"#d9730d",background:"#f6e9d9"},yellow:{text:"#dfab01",background:"#fbf3db"},green:{text:"#4d6461",background:"#ddedea"},blue:{text:"#0b6e99",background:"#ddebf1"},purple:{text:"#6940a5",background:"#eae4f2"},pink:{text:"#ad1a72",background:"#f4dfeb"}},Q={backgroundColor:{default:"default"},textColor:{default:"default"},textAlignment:{default:"left",values:["left","center","right","justify"]}},Ce=e=>{const t={};return e.hasAttribute("data-background-color")?t.backgroundColor=e.getAttribute("data-background-color"):e.style.backgroundColor&&(t.backgroundColor=e.style.backgroundColor),e.hasAttribute("data-text-color")?t.textColor=e.getAttribute("data-text-color"):e.style.color&&(t.textColor=e.style.color),t.textAlignment=Q.textAlignment.values.includes(e.style.textAlign)?e.style.textAlign:void 0,t},Ft=(e,t)=>{e.backgroundColor&&e.backgroundColor!==Q.backgroundColor.default&&(t.style.backgroundColor=e.backgroundColor in pt?pt[e.backgroundColor].background:e.backgroundColor),e.textColor&&e.textColor!==Q.textColor.default&&(t.style.color=e.textColor in pt?pt[e.textColor].text:e.textColor),e.textAlignment&&e.textAlignment!==Q.textAlignment.default&&(t.style.textAlign=e.textAlignment)},ls=(e,t)=>{const n=e.querySelector(t);if(!n)return;const r=e.querySelector("figcaption"),s=(r==null?void 0:r.textContent)??void 0;return{targetElement:n,caption:s}},pp=$(({editor:e})=>{const t=Ht(void 0);function n(){t.setState(void 0)}return{key:"filePanel",store:t,mount({signal:r}){const s=e.onChange(n,!1),i=e.onSelectionChange(n,!1);r.addEventListener("abort",()=>{s(),i()})},closeMenu:n,showMenu(r){t.setState(r)}}}),mp=(e,t,n)=>{const r=document.createElement("div");r.className="bn-add-file-button";const s=document.createElement("div");s.className="bn-add-file-button-icon",n?s.appendChild(n):s.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M3 8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8ZM10 4V9H5V20H19V4H10Z"></path></svg>',r.appendChild(s);const i=document.createElement("p");i.className="bn-add-file-button-text",i.innerHTML=e.type in t.dictionary.file_blocks.add_button_text?t.dictionary.file_blocks.add_button_text[e.type]:t.dictionary.file_blocks.add_button_text.file,r.appendChild(i);const o=u=>{u.preventDefault(),u.stopPropagation()},a=()=>{var u;t.isEditable&&((u=t.getExtension(pp))==null||u.showMenu(e.id))};return r.addEventListener("mousedown",o,!0),r.addEventListener("click",a,!0),{dom:r,destroy:()=>{r.removeEventListener("mousedown",o,!0),r.removeEventListener("click",a,!0)}}},gp='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M3 8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8ZM10 4V9H5V20H19V4H10Z"></path></svg>',bp=e=>{const t=document.createElement("div");t.className="bn-file-name-with-icon";const n=document.createElement("div");n.className="bn-file-icon",n.innerHTML=gp,t.appendChild(n);const r=document.createElement("p");return r.className="bn-file-name",r.textContent=e.props.name,t.appendChild(r),{dom:t}},Qi=(e,t,n,r)=>{const s=document.createElement("div");if(s.className="bn-file-block-content-wrapper",e.props.url===""){const o=mp(e,t,r);s.appendChild(o.dom);const a=t.onUploadStart(u=>{if(u===e.id){s.removeChild(o.dom);const c=document.createElement("div");c.className="bn-file-loading-preview",c.textContent="Loading...",s.appendChild(c)}});return{dom:s,destroy:()=>{a(),o.destroy()}}}const i={dom:s};if(e.props.showPreview===!1||!n){const o=bp(e);s.appendChild(o.dom),i.destroy=()=>{var a;(a=o.destroy)==null||a.call(o)}}else s.appendChild(n.dom);if(e.props.caption){const o=document.createElement("p");o.className="bn-file-caption",o.textContent=e.props.caption,s.appendChild(o)}return i},Ji=(e,t)=>{const n=document.createElement("figure"),r=document.createElement("figcaption");return r.textContent=t,n.appendChild(e),n.appendChild(r),{dom:n}},cs=(e,t)=>{const n=document.createElement("div"),r=document.createElement("p");return r.textContent=t,n.appendChild(e),n.appendChild(r),{dom:n}},ua=e=>({url:e.src||void 0}),Ep='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M2 16.0001H5.88889L11.1834 20.3319C11.2727 20.405 11.3846 20.4449 11.5 20.4449C11.7761 20.4449 12 20.2211 12 19.9449V4.05519C12 3.93977 11.9601 3.8279 11.887 3.73857C11.7121 3.52485 11.3971 3.49335 11.1834 3.66821L5.88889 8.00007H2C1.44772 8.00007 1 8.44778 1 9.00007V15.0001C1 15.5524 1.44772 16.0001 2 16.0001ZM23 12C23 15.292 21.5539 18.2463 19.2622 20.2622L17.8445 18.8444C19.7758 17.1937 21 14.7398 21 12C21 9.26016 19.7758 6.80629 17.8445 5.15557L19.2622 3.73779C21.5539 5.75368 23 8.70795 23 12ZM18 12C18 10.0883 17.106 8.38548 15.7133 7.28673L14.2842 8.71584C15.3213 9.43855 16 10.64 16 12C16 13.36 15.3213 14.5614 14.2842 15.2841L15.7133 16.7132C17.106 15.6145 18 13.9116 18 12Z"></path></svg>',Tp=e=>({type:"audio",propSchema:{backgroundColor:Q.backgroundColor,name:{default:""},url:{default:""},caption:{default:""},showPreview:{default:!0}},content:"none"}),yp=(e={})=>t=>{if(t.tagName==="AUDIO"){if(t.closest("figure"))return;const{backgroundColor:n}=Ce(t);return{...ua(t),backgroundColor:n}}if(t.tagName==="FIGURE"){const n=ls(t,"audio");if(!n)return;const{targetElement:r,caption:s}=n,{backgroundColor:i}=Ce(t);return{...ua(r),backgroundColor:i,caption:s}}},Cp=(e={})=>(t,n)=>{const r=document.createElement("div");r.innerHTML=e.icon??Ep;const s=document.createElement("audio");return s.className="bn-audio",n.resolveFileUrl?n.resolveFileUrl(t.props.url).then(i=>{s.src=i}):s.src=t.props.url,s.controls=!0,s.contentEditable="false",s.draggable=!1,Qi(t,n,{dom:s},r.firstElementChild)},kp=(e={})=>(t,n)=>{if(!t.props.url){const s=document.createElement("p");return s.textContent="Add audio",{dom:s}}let r;return t.props.showPreview?(r=document.createElement("audio"),r.src=t.props.url):(r=document.createElement("a"),r.href=t.props.url,r.textContent=t.props.name||t.props.url),t.props.caption?t.props.showPreview?Ji(r,t.props.caption):cs(r,t.props.caption):{dom:r}},Sp=Ne(Tp,e=>({meta:{fileBlockAccept:["audio/*"]},parse:yp(e),render:Cp(e),toExternalHTML:kp(e),runsBefore:["file"]})),la=Symbol.for("blocknote.shikiParser"),Rs=Symbol.for("blocknote.shikiHighlighterPromise");function Ap(e){const t=globalThis;let n,r,s=!1;return Jf({parser:i=>{if(!e.createHighlighter)return process.env.NODE_ENV==="development"&&!s&&(console.log("For syntax highlighting of code blocks, you must provide a `createCodeBlockSpec({ createHighlighter: () => ... })` function"),s=!0),[];if(!n)return t[Rs]=t[Rs]||e.createHighlighter(),t[Rs].then(a=>{n=a});const o=kl(e,i.language);return!o||o==="text"||o==="none"||o==="plaintext"||o==="txt"?[]:n.getLoadedLanguages().includes(o)?(r||(r=t[la]||Zf(n),t[la]=r),r(i)):n.loadLanguage(o)},languageExtractor:i=>i.attrs.language,nodeTypes:["codeBlock"]})}const _p=({defaultLanguage:e="text"})=>({type:"codeBlock",propSchema:{language:{default:e}},content:"inline"}),wp=Ne(_p,e=>({meta:{code:!0,defining:!0,isolating:!1},parse:t=>{var n,r;if(t.tagName!=="PRE"||t.childElementCount!==1||((n=t.firstElementChild)==null?void 0:n.tagName)!=="CODE")return;const s=t.firstElementChild;return{language:s.getAttribute("data-language")||((r=s.className.split(" ").find(i=>i.includes("language-")))==null?void 0:r.replace("language-",""))}},parseContent:({el:t,schema:n})=>{const r=X.DOMParser.fromSchema(n),s=t.firstElementChild;return r.parse(s,{preserveWhitespace:"full",topNode:n.nodes.codeBlock.create()}).content},render(t,n){const r=document.createDocumentFragment(),s=document.createElement("pre"),i=document.createElement("code");s.appendChild(i);let o;if(e.supportedLanguages){const a=document.createElement("select");Object.entries(e.supportedLanguages??{}).forEach(([d,{name:h}])=>{const f=document.createElement("option");f.value=d,f.text=h,a.appendChild(f)}),a.value=t.props.language||e.defaultLanguage||"text";const u=d=>{const h=d.target.value;n.updateBlock(t.id,{props:{language:h}})};a.addEventListener("change",u),o=()=>a.removeEventListener("change",u);const c=document.createElement("div");c.contentEditable="false",c.appendChild(a),r.appendChild(c)}return r.appendChild(s),{dom:r,contentDOM:i,destroy:()=>{o==null||o()}}},toExternalHTML(t){const n=document.createElement("pre"),r=document.createElement("code");return r.className=`language-${t.props.language}`,r.dataset.language=t.props.language,n.appendChild(r),{dom:n,contentDOM:r}}}),e=>[$({key:"code-block-highlighter",prosemirrorPlugins:[Ap(e)]}),$({key:"code-block-keyboard-shortcuts",keyboardShortcuts:{Delete:({editor:t})=>t.transact(n=>{const{block:r}=t.getTextCursorPosition();if(r.type!=="codeBlock")return!1;const{$from:s}=n.selection;return s.parent.textContent?!1:(t.removeBlocks([r]),!0)}),Tab:({editor:t})=>e.indentLineWithTab===!1?!1:t.transact(n=>{const{block:r}=t.getTextCursorPosition();return r.type==="codeBlock"?(n.insertText(" "),!0):!1}),Enter:({editor:t})=>t.transact(n=>{const{block:r,nextBlock:s}=t.getTextCursorPosition();if(r.type!=="codeBlock")return!1;const{$from:i}=n.selection,o=i.parentOffset===i.parent.nodeSize-2,a=i.parent.textContent.endsWith(`
7
+
8
+ `);if(o&&a){if(n.delete(i.pos-2,i.pos),s)return t.setTextCursorPosition(s,"start"),!0;const[u]=t.insertBlocks([{type:"paragraph"}],r,"after");return t.setTextCursorPosition(u,"start"),!0}return n.insertText(`
9
+ `),!0}),"Shift-Enter":({editor:t})=>t.transact(()=>{const{block:n}=t.getTextCursorPosition();if(n.type!=="codeBlock")return!1;const[r]=t.insertBlocks([{type:"paragraph"}],n,"after");return t.setTextCursorPosition(r,"start"),!0})},inputRules:[{find:/^```(.*?)\s$/,replace:({match:t})=>{const n=t[1].trim();return{type:"codeBlock",props:{language:{language:kl(e,n)??n}.language},content:[]}}}]})]);function kl(e,t){var n;return(n=Object.entries(e.supportedLanguages??{}).find(([r,{aliases:s}])=>(s==null?void 0:s.includes(t))||r===t))==null?void 0:n[0]}const Ip=()=>({type:"divider",propSchema:{},content:"none"}),xp=Ne(Ip,{meta:{isolating:!1},parse(e){if(e.tagName==="HR")return{}},render(){return{dom:document.createElement("hr")}}},[$({key:"divider-block-shortcuts",inputRules:[{find:new RegExp("^---$"),replace(){return{type:"divider",props:{},content:[]}}}]})]),ca=e=>({url:e.src||void 0}),Np=()=>({type:"file",propSchema:{backgroundColor:Q.backgroundColor,name:{default:""},url:{default:""},caption:{default:""}},content:"none"}),Lp=()=>e=>{if(e.tagName==="EMBED"){if(e.closest("figure"))return;const{backgroundColor:t}=Ce(e);return{...ca(e),backgroundColor:t}}if(e.tagName==="FIGURE"){const t=ls(e,"embed");if(!t)return;const{targetElement:n,caption:r}=t,{backgroundColor:s}=Ce(e);return{...ca(n),backgroundColor:s,caption:r}}},Op=Ne(Np,{meta:{fileBlockAccept:["*/*"]},parse:Lp(),render(e,t){return Qi(e,t)},toExternalHTML(e){if(!e.props.url){const n=document.createElement("p");return n.textContent="Add file",{dom:n}}const t=document.createElement("a");return t.href=e.props.url,t.textContent=e.props.name||e.props.url,e.props.caption?cs(t,e.props.caption):{dom:t}}}),Dp={set:(e,t)=>window.localStorage.setItem(`toggle-${e.id}`,t?"true":"false"),get:e=>window.localStorage.getItem(`toggle-${e.id}`)==="true"},Sl=(e,t,n,r=Dp)=>{if("isToggleable"in e.props&&!e.props.isToggleable)return{dom:n};const s=document.createElement("div"),i=document.createElement("div");i.className="bn-toggle-wrapper";const o=document.createElement("button");o.className="bn-toggle-button",o.type="button",o.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="CURRENTCOLOR"><path d="M320-200v-560l440 280-440 280Z"/></svg>';const a=m=>m.preventDefault();o.addEventListener("mousedown",a);const u=()=>{var m;i.getAttribute("data-show-children")==="true"?(i.setAttribute("data-show-children","false"),r.set(t.getBlock(e),!1),s.contains(c)&&s.removeChild(c)):(i.setAttribute("data-show-children","true"),r.set(t.getBlock(e),!0),t.isEditable&&((m=t.getBlock(e))==null?void 0:m.children.length)===0&&!s.contains(c)&&s.appendChild(c))};o.addEventListener("click",u),i.appendChild(o),i.appendChild(n);const c=document.createElement("button");c.className="bn-toggle-add-block-button",c.type="button",c.textContent=t.dictionary.toggle_blocks.add_block_button;const d=m=>m.preventDefault();c.addEventListener("mousedown",d);const h=()=>{t.transact(()=>{const m=t.updateBlock(e,{children:[{}]});t.setTextCursorPosition(m.children[0].id,"end"),t.focus()})};c.addEventListener("click",h),s.appendChild(i);let f=e.children.length;const p=t.onChange(()=>{var m;const E=((m=t.getBlock(e))==null?void 0:m.children.length)??0;E>f?(i.getAttribute("data-show-children")==="false"&&(i.setAttribute("data-show-children","true"),r.set(t.getBlock(e),!0)),s.contains(c)&&s.removeChild(c)):E===0&&E<f&&(i.getAttribute("data-show-children")==="true"&&(i.setAttribute("data-show-children","false"),r.set(t.getBlock(e),!1)),s.contains(c)&&s.removeChild(c)),f=E});return r.get(e)?(i.setAttribute("data-show-children","true"),t.isEditable&&e.children.length===0&&s.appendChild(c)):i.setAttribute("data-show-children","false"),{dom:s,ignoreMutation:m=>m instanceof MutationRecord&&(m.type==="attributes"&&m.target===i&&m.attributeName==="data-show-children"||m.type==="childList"&&(m.addedNodes[0]===c||m.removedNodes[0]===c)),destroy:()=>{o.removeEventListener("mousedown",a),o.removeEventListener("click",u),c.removeEventListener("mousedown",d),c.removeEventListener("click",h),p==null||p()}}},Al=[1,2,3,4,5,6],vp=e=>({editor:t})=>{const n=t.getTextCursorPosition();return t.schema.blockSchema[n.block.type].content!=="inline"?!1:(t.updateBlock(n.block,{type:"heading",props:{level:e}}),!0)},Mp=({defaultLevel:e=1,levels:t=Al,allowToggleHeadings:n=!0}={})=>({type:"heading",propSchema:{...Q,level:{default:e,values:t},...n?{isToggleable:{default:!1,optional:!0}}:{}},content:"inline"}),Rp=Ne(Mp,({allowToggleHeadings:e=!0}={})=>({meta:{isolating:!1},parse(t){let n;switch(t.tagName){case"H1":n=1;break;case"H2":n=2;break;case"H3":n=3;break;case"H4":n=4;break;case"H5":n=5;break;case"H6":n=6;break;default:return}return{...Ce(t),level:n}},render(t,n){const r=document.createElement(`h${t.props.level}`);return e?{...Sl(t,n,r),contentDOM:r}:{dom:r,contentDOM:r}},toExternalHTML(t){const n=document.createElement(`h${t.props.level}`);return Ft(t.props,n),{dom:n,contentDOM:n}}}),({levels:e=Al}={})=>[$({key:"heading-shortcuts",keyboardShortcuts:Object.fromEntries(e.map(t=>[`Mod-Alt-${t}`,vp(t)])??[]),inputRules:e.map(t=>({find:new RegExp(`^(#{${t}})\\s$`),replace({match:n}){return{type:"heading",props:{level:n[1].length}}}}))})]),_l=(e,t,n,r,s)=>{const{dom:i,destroy:o}=Qi(e,t,n,s),a=i;a.style.position="relative",e.props.url&&e.props.showPreview&&(e.props.previewWidth?a.style.width=`${e.props.previewWidth}px`:a.style.width="fit-content");const u=document.createElement("div");u.className="bn-resize-handle",u.style.left="4px";const c=document.createElement("div");c.className="bn-resize-handle",c.style.right="4px";const d=document.createElement("div");d.style.position="absolute",d.style.height="100%",d.style.width="100%";let h,f=e.props.previewWidth;const p=N=>{var L,U;if(!h){!t.isEditable&&r.contains(u)&&r.contains(c)&&(r.removeChild(u),r.removeChild(c));return}let O;const j="touches"in N?N.touches[0].clientX:N.clientX;e.props.textAlignment==="center"?h.handleUsed==="left"?O=h.initialWidth+(h.initialClientX-j)*2:O=h.initialWidth+(j-h.initialClientX)*2:h.handleUsed==="left"?O=h.initialWidth+h.initialClientX-j:O=h.initialWidth+j-h.initialClientX,f=Math.min(Math.max(O,64),((U=(L=t.domElement)==null?void 0:L.firstElementChild)==null?void 0:U.clientWidth)||Number.MAX_VALUE),a.style.width=`${f}px`},m=N=>{(!N.target||!a.contains(N.target)||!t.isEditable)&&r.contains(u)&&r.contains(c)&&(r.removeChild(u),r.removeChild(c)),h&&(h=void 0,a.contains(d)&&a.removeChild(d),t.updateBlock(e,{props:{previewWidth:f}}))},E=()=>{t.isEditable&&(r.appendChild(u),r.appendChild(c))},C=N=>{N.relatedTarget===u||N.relatedTarget===c||h||t.isEditable&&r.contains(u)&&r.contains(c)&&(r.removeChild(u),r.removeChild(c))},k=N=>{N.preventDefault(),a.contains(d)||a.appendChild(d);const L="touches"in N?N.touches[0].clientX:N.clientX;h={handleUsed:"left",initialWidth:a.clientWidth,initialClientX:L}},_=N=>{N.preventDefault(),a.contains(d)||a.appendChild(d);const L="touches"in N?N.touches[0].clientX:N.clientX;h={handleUsed:"right",initialWidth:a.clientWidth,initialClientX:L}};return window.addEventListener("mousemove",p),window.addEventListener("touchmove",p),window.addEventListener("mouseup",m),window.addEventListener("touchend",m),a.addEventListener("mouseenter",E),a.addEventListener("mouseleave",C),u.addEventListener("mousedown",k),u.addEventListener("touchstart",k),c.addEventListener("mousedown",_),c.addEventListener("touchstart",_),{dom:a,destroy:()=>{o==null||o(),window.removeEventListener("mousemove",p),window.removeEventListener("touchmove",p),window.removeEventListener("mouseup",m),window.removeEventListener("touchend",m),a.removeEventListener("mouseenter",E),a.removeEventListener("mouseleave",C),u.removeEventListener("mousedown",k),u.removeEventListener("touchstart",k),c.removeEventListener("mousedown",_),c.removeEventListener("touchstart",_)}}},da=e=>{const t=e.src||void 0,n=e.width||void 0,r=e.alt||void 0;return{url:t,previewWidth:n,name:r}},Pp='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M5 11.1005L7 9.1005L12.5 14.6005L16 11.1005L19 14.1005V5H5V11.1005ZM4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM15.5 10C14.6716 10 14 9.32843 14 8.5C14 7.67157 14.6716 7 15.5 7C16.3284 7 17 7.67157 17 8.5C17 9.32843 16.3284 10 15.5 10Z"></path></svg>',Bp=(e={})=>({type:"image",propSchema:{textAlignment:Q.textAlignment,backgroundColor:Q.backgroundColor,name:{default:""},url:{default:""},caption:{default:""},showPreview:{default:!0},previewWidth:{default:void 0,type:"number"}},content:"none"}),Up=(e={})=>t=>{if(t.tagName==="IMG"){if(t.closest("figure"))return;const{backgroundColor:n}=Ce(t);return{...da(t),backgroundColor:n}}if(t.tagName==="FIGURE"){const n=ls(t,"img");if(!n)return;const{targetElement:r,caption:s}=n,{backgroundColor:i}=Ce(t);return{...da(r),backgroundColor:i,caption:s}}},Hp=(e={})=>(t,n)=>{const r=document.createElement("div");r.innerHTML=e.icon??Pp;const s=document.createElement("div");s.className="bn-visual-media-wrapper";const i=document.createElement("img");return i.className="bn-visual-media",n.resolveFileUrl?n.resolveFileUrl(t.props.url).then(o=>{i.src=o}):i.src=t.props.url,i.alt=t.props.name||t.props.caption||"BlockNote image",i.contentEditable="false",i.draggable=!1,s.appendChild(i),_l(t,n,{dom:s},s,r.firstElementChild)},Fp=(e={})=>(t,n)=>{if(!t.props.url){const s=document.createElement("p");return s.textContent="Add image",{dom:s}}let r;return t.props.showPreview?(r=document.createElement("img"),r.src=t.props.url,r.alt=t.props.name||t.props.caption||"BlockNote image",t.props.previewWidth&&(r.width=t.props.previewWidth)):(r=document.createElement("a"),r.href=t.props.url,r.textContent=t.props.name||t.props.url),t.props.caption?t.props.showPreview?Ji(r,t.props.caption):cs(r,t.props.caption):{dom:r}},Vp=Ne(Bp,e=>({meta:{fileBlockAccept:["image/*"]},parse:Up(e),render:Hp(e),toExternalHTML:Fp(e),runsBefore:["file"]})),Yp=(e,t,n,r)=>{const s=ji(e.doc,t),i=Vn(s);if(!i.isBlockContainer)return!1;bt(e);const o=[{type:i.bnBlock.node.type,attrs:{}},{type:i.blockContent.node.type,attrs:{}}];return e.split(t,2,o),!0},ds=(e,t)=>{const{blockInfo:n,selectionEmpty:r}=e.transact(o=>({blockInfo:pf(o),selectionEmpty:o.selection.anchor===o.selection.head}));if(!n.isBlockContainer)return!1;const{bnBlock:s,blockContent:i}=n;return i.node.type.name!==t||!r?!1:i.node.childCount===0?(e.transact(o=>{cp(o,s.beforePos,{type:"paragraph",props:{}})}),!0):i.node.childCount>0?e.transact(o=>(o.deleteSelection(),Yp(o,o.selection.from))):!1};function Zi(e,t,n){var r,s,i;const o=X.DOMParser.fromSchema(t),a=e,u=document.createElement("div");u.setAttribute("data-node-type","blockGroup");for(const p of Array.from(a.childNodes))u.appendChild(p.cloneNode(!0));let c=o.parse(u,{topNode:t.nodes.blockGroup.create()});((s=(r=c.firstChild)==null?void 0:r.firstChild)==null?void 0:s.type.name)==="checkListItem"&&(c=c.copy(c.content.cut(c.firstChild.firstChild.nodeSize+2)));const d=(i=c.firstChild)==null?void 0:i.firstChild;if(!(d!=null&&d.isTextblock))return X.Fragment.from(c);const h=t.nodes[n].create({},d.content),f=c.content.cut(d.nodeSize+2);if(f.size>0){const p=c.copy(f);return h.content.addToEnd(p)}return h.content}const $p=()=>({type:"bulletListItem",propSchema:{...Q},content:"inline"}),jp=Ne($p,{meta:{isolating:!1},parse(e){var t;if(e.tagName!=="LI")return;const n=e.parentElement;if(n!==null&&(n.tagName==="UL"||n.tagName==="DIV"&&((t=n.parentElement)==null?void 0:t.tagName)==="UL"))return Ce(e)},parseContent:({el:e,schema:t})=>Zi(e,t,"bulletListItem"),render(){const e=document.createElement("p");return{dom:e,contentDOM:e}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("p");return Ft(e.props,t),t.appendChild(n),{dom:t,contentDOM:n}}},[$({key:"bullet-list-item-shortcuts",keyboardShortcuts:{Enter:({editor:e})=>ds(e,"bulletListItem"),"Mod-Shift-8":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"bulletListItem",props:{}}),!0)}},inputRules:[{find:new RegExp("^[-+*]\\s$"),replace({editor:e}){if(cl(e.prosemirrorState).blockNoteType!=="heading")return{type:"bulletListItem",props:{}}}}]})]),qp=()=>({type:"checkListItem",propSchema:{...Q,checked:{default:!1,type:"boolean"}},content:"inline"}),zp=Ne(qp,{meta:{isolating:!1},parse(e){var t;if(e.tagName==="input")return e.closest("[data-content-type]")||e.closest("li")?void 0:e.type==="checkbox"?{checked:e.checked}:void 0;if(e.tagName!=="LI")return;const n=e.parentElement;if(n!==null&&(n.tagName==="UL"||n.tagName==="DIV"&&((t=n.parentElement)==null?void 0:t.tagName)==="UL")){const r=e.querySelector("input[type=checkbox]")||null;return r===null?void 0:{...Ce(e),checked:r.checked}}},parseContent:({el:e,schema:t})=>Zi(e,t,"checkListItem"),render(e,t){const n=document.createDocumentFragment(),r=document.createElement("input");r.type="checkbox",r.checked=e.props.checked,e.props.checked&&r.setAttribute("checked",""),r.addEventListener("change",()=>{t.updateBlock(e,{props:{checked:!e.props.checked}})});const s=document.createElement("p");return n.appendChild(r),n.appendChild(s),{dom:n,contentDOM:s}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("input");n.type="checkbox",n.checked=e.props.checked,e.props.checked&&n.setAttribute("checked","");const r=document.createElement("p");return Ft(e.props,t),t.appendChild(n),t.appendChild(r),{dom:t,contentDOM:r}},runsBefore:["bulletListItem"]},[$({key:"check-list-item-shortcuts",keyboardShortcuts:{Enter:({editor:e})=>ds(e,"checkListItem"),"Mod-Shift-9":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"checkListItem",props:{}}),!0)}},inputRules:[{find:new RegExp("\\[\\s*\\]\\s$"),replace(){return{type:"checkListItem",props:{checked:!1},content:[]}}},{find:new RegExp("\\[[Xx]\\]\\s$"),replace(){return{type:"checkListItem",props:{checked:!0}}}}]})]);function wl(e,t,n,r){let s=e.firstChild.attrs.start||1,i=!0;const o=!!e.firstChild.attrs.start,a=Vn({posBeforeNode:t,node:e});if(!a.isBlockContainer)throw new Error("impossible");const u=n.doc.resolve(a.bnBlock.beforePos).nodeBefore,c=u?r.get(u):void 0;return c!==void 0?(s=c+1,i=!1):u&&Vn({posBeforeNode:a.bnBlock.beforePos-u.nodeSize,node:u}).blockNoteType==="numberedListItem"&&(s=wl(u,a.bnBlock.beforePos-u.nodeSize,n,r).index+1,i=!1),r.set(e,s),{index:s,isFirst:i,hasStart:o}}function ha(e,t){const n=new Map,r=t.decorations.map(e.mapping,e.doc),s=[];e.doc.nodesBetween(0,e.doc.nodeSize-2,(o,a)=>{if(o.type.name==="blockContainer"&&o.firstChild.type.name==="numberedListItem"){const{index:u,isFirst:c,hasStart:d}=wl(o,a,e,n);if(r.find(a,a+o.nodeSize,h=>h.index===u&&h.isFirst===c&&h.hasStart===d).length===0){const h=e.doc.nodeAt(a+1);s.push(G.Decoration.node(a+1,a+1+h.nodeSize,{"data-index":u.toString()}))}}});const i=s.flatMap(o=>r.find(o.from,o.to));return{decorations:r.remove(i).add(e.doc,s)}}const Wp=()=>new D.Plugin({key:new D.PluginKey("numbered-list-indexing-decorations"),state:{init(e,t){return ha(t.tr,{decorations:G.DecorationSet.empty})},apply(e,t){return!e.docChanged&&!e.selectionSet&&t.decorations?t:ha(e,t)}},props:{decorations(e){var t;return((t=this.getState(e))==null?void 0:t.decorations)??G.DecorationSet.empty}}}),Gp=()=>({type:"numberedListItem",propSchema:{...Q,start:{default:void 0,type:"number"}},content:"inline"}),Kp=Ne(Gp,{meta:{isolating:!1},parse(e){var t;if(e.tagName!=="LI")return;const n=e.parentElement;if(n!==null&&(n.tagName==="OL"||n.tagName==="DIV"&&((t=n.parentElement)==null?void 0:t.tagName)==="OL")){const r=parseInt(n.getAttribute("start")||"1"),s=Ce(e);return e.previousElementSibling||r===1?s:{...s,start:r}}},parseContent:({el:e,schema:t})=>Zi(e,t,"numberedListItem"),render(){const e=document.createElement("p");return{dom:e,contentDOM:e}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("p");return Ft(e.props,t),t.appendChild(n),{dom:t,contentDOM:n}}},[$({key:"numbered-list-item-shortcuts",inputRules:[{find:new RegExp("^(\\d+)\\.\\s$"),replace({match:e,editor:t}){if(cl(t.prosemirrorState).blockNoteType==="heading")return;const n=parseInt(e[1]);return{type:"numberedListItem",props:{start:n!==1?n:void 0}}}}],keyboardShortcuts:{Enter:({editor:e})=>ds(e,"numberedListItem"),"Mod-Shift-7":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"numberedListItem",props:{}}),!0)}},prosemirrorPlugins:[Wp()]})]),Xp=()=>({type:"toggleListItem",propSchema:{...Q},content:"inline"}),Qp=Ne(Xp,{meta:{isolating:!1},render(e,t){const n=document.createElement("p");return{...Sl(e,t,n),contentDOM:n}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("p");return Ft(e.props,t),t.appendChild(n),{dom:t,contentDOM:n}}},[$({key:"toggle-list-item-shortcuts",keyboardShortcuts:{Enter:({editor:e})=>ds(e,"toggleListItem"),"Mod-Shift-6":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"toggleListItem",props:{}}),!0)}}})]),Jp=()=>({type:"paragraph",propSchema:Q,content:"inline"}),Zp=Ne(Jp,{meta:{isolating:!1},parse:e=>{var t;if(e.tagName==="P"&&(t=e.textContent)!=null&&t.trim())return Ce(e)},render:()=>{const e=document.createElement("p");return{dom:e,contentDOM:e}},toExternalHTML:e=>{const t=document.createElement("p");return Ft(e.props,t),{dom:t,contentDOM:t}},runsBefore:["default"]},[$({key:"paragraph-shortcuts",keyboardShortcuts:{"Mod-Alt-0":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"paragraph",props:{}}),!0)}}})]),e0=()=>({type:"quote",propSchema:{backgroundColor:Q.backgroundColor,textColor:Q.textColor},content:"inline"}),t0=Ne(e0,{meta:{isolating:!1},parse(e){if(e.tagName==="BLOCKQUOTE"){const{backgroundColor:t,textColor:n}=Ce(e);return{backgroundColor:t,textColor:n}}},render(){const e=document.createElement("blockquote");return{dom:e,contentDOM:e}},toExternalHTML(e){const t=document.createElement("blockquote");return Ft(e.props,t),{dom:t,contentDOM:t}}},[$({key:"quote-block-shortcuts",keyboardShortcuts:{"Mod-Alt-q":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"quote",props:{}}),!0)}},inputRules:[{find:new RegExp("^>\\s$"),replace(){return{type:"quote",props:{}}}}]})]),n0=35,Il=120,r0=v.Extension.create({name:"BlockNoteTableExtension",addProseMirrorPlugins:()=>[te.columnResizing({cellMinWidth:n0,defaultCellMinWidth:Il,View:null}),te.tableEditing()],addKeyboardShortcuts(){return{Enter:()=>this.editor.state.selection.empty&&this.editor.state.selection.$head.parent.type.name==="tableParagraph"?(this.editor.commands.insertContent({type:"hardBreak"}),!0):!1,Backspace:()=>{const e=this.editor.state.selection,t=e.empty,n=e.$head.parentOffset===0,r=e.$head.node().type.name==="tableParagraph";return t&&n&&r},Tab:()=>this.editor.commands.command(({state:e,dispatch:t,view:n})=>te.goToNextCell(1)(e,t,n)),"Shift-Tab":()=>this.editor.commands.command(({state:e,dispatch:t,view:n})=>te.goToNextCell(-1)(e,t,n))}},extendNodeSchema(e){const t={name:e.name,options:e.options,storage:e.storage};return{tableRole:v.callOrReturn(v.getExtensionField(e,"tableRole",t))}}}),s0={textColor:Q.textColor},i0=v.Node.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"tableContent+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{const t=e.getAttribute("colwidth");return t?t.split(",").map(n=>parseInt(n,10)):null}}}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th",getContent:(e,t)=>xl(e,t)}]},renderHTML({HTMLAttributes:e}){return["th",v.mergeAttributes(this.options.HTMLAttributes,e),0]}}),o0=v.Node.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"tableContent+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{const t=e.getAttribute("colwidth");return t?t.split(",").map(n=>parseInt(n,10)):null}}}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td",getContent:(e,t)=>xl(e,t)}]},renderHTML({HTMLAttributes:e}){return["td",v.mergeAttributes(this.options.HTMLAttributes,e),0]}}),a0=v.Node.create({name:"table",content:"tableRow+",group:"blockContent",tableRole:"table",marks:"deletion insertion modification",isolating:!0,parseHTML(){return[{tag:"table"}]},renderHTML({node:e,HTMLAttributes:t}){var n,r,s;const i=rp(this.name,"table",{...((n=this.options.domAttributes)==null?void 0:n.blockContent)||{},...t},((r=this.options.domAttributes)==null?void 0:r.inlineContent)||{}),o=document.createElement("colgroup");for(const a of e.children[0].children)if(a.attrs.colwidth)for(const u of a.attrs.colwidth){const c=document.createElement("col");u&&(c.style=`width: ${u}px`),o.appendChild(c)}else o.appendChild(document.createElement("col"));return(s=i.dom.firstChild)==null||s.appendChild(o),i},addNodeView(){return({node:e,HTMLAttributes:t})=>{var n;class r extends te.TableView{constructor(i,o,a){super(i,o),this.node=i,this.cellMinWidth=o,this.blockContentHTMLAttributes=a;const u=document.createElement("div");u.className=$n("bn-block-content",a.class),u.setAttribute("data-content-type","table");for(const[f,p]of Object.entries(a))f!=="class"&&u.setAttribute(f,p);const c=this.dom,d=document.createElement("div");d.className="tableWrapper-inner",d.appendChild(c.firstChild),c.appendChild(d),u.appendChild(c);const h=document.createElement("div");h.className="table-widgets-container",h.style.position="relative",c.appendChild(h),this.dom=u}ignoreMutation(i){return!i.target.closest(".tableWrapper-inner")||super.ignoreMutation(i)}}return new r(e,Il,{...((n=this.options.domAttributes)==null?void 0:n.blockContent)||{},...t})}}}),u0=v.Node.create({name:"tableParagraph",group:"tableContent",content:"inline*",parseHTML(){return[{tag:"p",getAttrs:e=>{if(typeof e=="string"||!e.textContent||!e.closest("[data-content-type]"))return!1;const t=e.parentElement;return t===null?!1:t.tagName==="TD"||t.tagName==="TH"?{}:!1},node:"tableParagraph"}]},renderHTML({HTMLAttributes:e}){return["p",e,0]}}),l0=v.Node.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)+",tableRole:"row",marks:"deletion insertion modification",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:e}){return["tr",v.mergeAttributes(this.options.HTMLAttributes,e),0]}});function xl(e,t){const n=X.DOMParser.fromSchema(t).parse(e,{topNode:t.nodes.blockGroup.create()}),r=[];return n.content.descendants(s=>{if(s.isInline)return r.push(s),!1}),X.Fragment.fromArray(r)}const c0=()=>ip({node:a0,type:"table",content:"table"},s0,[$({key:"table-extensions",tiptapExtensions:[r0,u0,i0,o0,l0]}),$({key:"table-keyboard-delete",keyboardShortcuts:{Backspace:({editor:e})=>{if(!(e.prosemirrorState.selection instanceof te.CellSelection))return!1;const t=e.getTextCursorPosition().block,n=t.content;let r=0;for(const i of n.rows)for(const o of i.cells){if("type"in o&&o.content.length>0||!("type"in o)&&o.length>0)return!1;r++}let s=0;return e.prosemirrorState.selection.forEachCell(()=>{s++}),s<r?!1:(e.transact(()=>{(e.getPrevBlock(t)||e.getNextBlock(t))&&e.setTextCursorPosition(t),e.removeBlocks([t])}),!0)}}})]),fa=e=>{const t=e.src||void 0,n=e.width||void 0;return{url:t,previewWidth:n}},d0='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M2 3.9934C2 3.44476 2.45531 3 2.9918 3H21.0082C21.556 3 22 3.44495 22 3.9934V20.0066C22 20.5552 21.5447 21 21.0082 21H2.9918C2.44405 21 2 20.5551 2 20.0066V3.9934ZM8 5V19H16V5H8ZM4 5V7H6V5H4ZM18 5V7H20V5H18ZM4 9V11H6V9H4ZM18 9V11H20V9H18ZM4 13V15H6V13H4ZM18 13V15H20V13H18ZM4 17V19H6V17H4ZM18 17V19H20V17H18Z"></path></svg>',h0=e=>({type:"video",propSchema:{textAlignment:Q.textAlignment,backgroundColor:Q.backgroundColor,name:{default:""},url:{default:""},caption:{default:""},showPreview:{default:!0},previewWidth:{default:void 0,type:"number"}},content:"none"}),f0=e=>t=>{if(t.tagName==="VIDEO"){if(t.closest("figure"))return;const{backgroundColor:n}=Ce(t);return{...fa(t),backgroundColor:n}}if(t.tagName==="FIGURE"){const n=ls(t,"video");if(!n)return;const{targetElement:r,caption:s}=n,{backgroundColor:i}=Ce(t);return{...fa(r),backgroundColor:i,caption:s}}},p0=Ne(h0,e=>({meta:{fileBlockAccept:["video/*"]},parse:f0(),render(t,n){const r=document.createElement("div");r.innerHTML=e.icon??d0;const s=document.createElement("div");s.className="bn-visual-media-wrapper";const i=document.createElement("video");return i.className="bn-visual-media",n.resolveFileUrl?n.resolveFileUrl(t.props.url).then(o=>{i.src=o}):i.src=t.props.url,i.controls=!0,i.contentEditable="false",i.draggable=!1,i.width=t.props.previewWidth,s.appendChild(i),_l(t,n,{dom:s},s,r.firstElementChild)},toExternalHTML(t){if(!t.props.url){const r=document.createElement("p");return r.textContent="Add video",{dom:r}}let n;return t.props.showPreview?(n=document.createElement("video"),n.src=t.props.url,t.props.previewWidth&&(n.width=t.props.previewWidth)):(n=document.createElement("a"),n.href=t.props.url,n.textContent=t.props.name||t.props.url),t.props.caption?t.props.showPreview?Ji(n,t.props.caption):cs(n,t.props.caption):{dom:n}},runsBefore:["file"]}));function m0(e,t,n){return t in e.schema.blockSpecs}function pa(e){return e instanceof te.CellSelection}const mr=new Map;function g0(e){if(mr.has(e))return mr.get(e);const t=new oe.Mapping;return e._tiptapEditor.on("transaction",({transaction:n})=>{t.appendMapping(n.mapping)}),e._tiptapEditor.on("destroy",()=>{mr.delete(e)}),mr.set(e,t),t}function b0(e,t,n="left"){const r=Ie.ySyncPluginKey.getState(e.prosemirrorState);if(!r){const i=g0(e),o=i.maps.length;return()=>i.slice(o).map(t,n==="left"?-1:1)}const s=Ie.absolutePositionToRelativePosition(t+(n==="right"?1:-1),r.binding.type,r.binding.mapping);return()=>{const i=Ie.ySyncPluginKey.getState(e.prosemirrorState),o=Ie.relativePositionToAbsolutePosition(i.doc,i.binding.type,s,i.binding.mapping);if(o===null)throw new Error("Position not found, cannot track positions");return o+(n==="right"?-1:1)}}const E0=v.findParentNode(e=>e.type.name==="blockContainer");class T0{constructor(t,n,r){wt(this,"state"),wt(this,"emitUpdate"),wt(this,"rootEl"),wt(this,"pluginState"),wt(this,"handleScroll",()=>{var i,o;if((i=this.state)!=null&&i.show){const a=(o=this.rootEl)==null?void 0:o.querySelector(`[data-decoration-id="${this.pluginState.decorationId}"]`);if(!a)return;this.state.referencePos=a.getBoundingClientRect().toJSON(),this.emitUpdate(this.pluginState.triggerCharacter)}}),wt(this,"closeMenu",()=>{this.editor.transact(i=>i.setMeta(xt,null))}),wt(this,"clearQuery",()=>{this.pluginState!==void 0&&this.editor._tiptapEditor.chain().focus().deleteRange({from:this.pluginState.queryStartPos()-(this.pluginState.deleteTriggerCharacter?this.pluginState.triggerCharacter.length:0),to:this.editor.transact(i=>i.selection.from)}).run()});var s;this.editor=t,this.pluginState=void 0,this.emitUpdate=i=>{var o;if(!this.state)throw new Error("Attempting to update uninitialized suggestions menu");n(i,{...this.state,ignoreQueryLength:(o=this.pluginState)==null?void 0:o.ignoreQueryLength})},this.rootEl=r.root,(s=this.rootEl)==null||s.addEventListener("scroll",this.handleScroll,!0)}update(t,n){var r;const s=xt.getState(n),i=xt.getState(t.state),o=s===void 0&&i!==void 0,a=s!==void 0&&i===void 0;if(!o&&!(s!==void 0&&i!==void 0)&&!a)return;if(this.pluginState=a?s:i,a||!this.editor.isEditable){this.state&&(this.state.show=!1),this.emitUpdate(this.pluginState.triggerCharacter);return}const u=(r=this.rootEl)==null?void 0:r.querySelector(`[data-decoration-id="${this.pluginState.decorationId}"]`);this.editor.isEditable&&u&&(this.state={show:!0,referencePos:u.getBoundingClientRect().toJSON(),query:this.pluginState.query},this.emitUpdate(this.pluginState.triggerCharacter))}destroy(){var t;(t=this.rootEl)==null||t.removeEventListener("scroll",this.handleScroll,!0)}}const xt=new D.PluginKey("SuggestionMenuPlugin");$(({editor:e})=>{const t=[];let n;const r=Ht(void 0);return{key:"suggestionMenu",store:r,addTriggerCharacter:s=>{t.push(s)},removeTriggerCharacter:s=>{t.splice(t.indexOf(s),1)},closeMenu:()=>{n==null||n.closeMenu()},clearQuery:()=>{n==null||n.clearQuery()},shown:()=>{var s;return((s=n==null?void 0:n.state)==null?void 0:s.show)||!1},openSuggestionMenu:(s,i)=>{e.headless||(e.focus(),e.transact(o=>{i!=null&&i.deleteTriggerCharacter&&o.insertText(s),o.scrollIntoView().setMeta(xt,{triggerCharacter:s,deleteTriggerCharacter:(i==null?void 0:i.deleteTriggerCharacter)||!1,ignoreQueryLength:(i==null?void 0:i.ignoreQueryLength)||!1})}))},prosemirrorPlugins:[new D.Plugin({key:xt,view:s=>(n=new T0(e,(i,o)=>{r.setState({...o,triggerCharacter:i})},s),n),state:{init(){},apply:(s,i,o,a)=>{if(s.selection.$from.parent.type.spec.code)return i;const u=s.getMeta(xt);if(typeof u=="object"&&u!==null){i&&(n==null||n.closeMenu());const d=b0(e,a.selection.from-u.triggerCharacter.length);return{triggerCharacter:u.triggerCharacter,deleteTriggerCharacter:u.deleteTriggerCharacter!==!1,queryStartPos:()=>d()+u.triggerCharacter.length,query:"",decorationId:`id_${Math.floor(Math.random()*4294967295)}`,ignoreQueryLength:u==null?void 0:u.ignoreQueryLength}}if(i===void 0)return i;if(a.selection.from!==a.selection.to||u===null||s.getMeta("focus")||s.getMeta("blur")||s.getMeta("pointer")||i.triggerCharacter!==void 0&&a.selection.from<i.queryStartPos()||!a.selection.$from.sameParent(a.doc.resolve(i.queryStartPos())))return;const c={...i};return c.query=a.doc.textBetween(i.queryStartPos(),a.selection.from),c}},props:{handleTextInput(s,i,o,a){if(i===o){const u=s.state.doc;for(const c of t){const d=c.length>1?u.textBetween(i-c.length,i)+a:a;if(c===d)return s.dispatch(s.state.tr.insertText(a)),s.dispatch(s.state.tr.setMeta(xt,{triggerCharacter:d}).scrollIntoView()),!0}}return!1},decorations(s){const i=this.getState(s);if(i===void 0)return null;if(!i.deleteTriggerCharacter){const o=E0(s.selection);if(o)return G.DecorationSet.create(s.doc,[G.Decoration.node(o.pos,o.pos+o.node.nodeSize,{nodeName:"span",class:"bn-suggestion-decorator","data-decoration-id":i.decorationId})])}return G.DecorationSet.create(s.doc,[G.Decoration.inline(i.queryStartPos()-i.triggerCharacter.length,i.queryStartPos(),{nodeName:"span",class:"bn-suggestion-decorator","data-decoration-id":i.decorationId})])}}})]}});function y0(e,t){return e.filter(({title:n,aliases:r})=>n.toLowerCase().includes(t.toLowerCase())||r&&r.filter(s=>s.toLowerCase().includes(t.toLowerCase())).length!==0)}Sp(),jp(),zp(),wp(),xp(),Op(),Rp(),Vp(),Kp(),Zp(),t0(),c0(),Qp(),p0();const C0=yl({type:"textColor",propSchema:"string"},{render:()=>{const e=document.createElement("span");return{dom:e,contentDOM:e}},toExternalHTML:e=>{const t=document.createElement("span");return e!==Q.textColor.default&&(t.style.color=e in pt?pt[e].text:e),{dom:t,contentDOM:t}},parse:e=>{if(e.tagName==="SPAN"&&e.style.color)return e.style.color}}),k0=yl({type:"backgroundColor",propSchema:"string"},{render:()=>{const e=document.createElement("span");return{dom:e,contentDOM:e}},toExternalHTML:e=>{const t=document.createElement("span");return e!==Q.backgroundColor.default&&(t.style.backgroundColor=e in pt?pt[e].background:e),{dom:t,contentDOM:t}},parse:e=>{if(e.tagName==="SPAN"&&e.style.backgroundColor)return e.style.backgroundColor}}),S0={bold:An(Mf,"boolean"),italic:An(jf,"boolean"),underline:An(Xf,"boolean"),strike:An(Gf,"boolean"),code:An(Uf,"boolean"),textColor:C0,backgroundColor:k0};up(S0);const A0={text:{config:"text",implementation:{}},link:{config:"link",implementation:{}}};op(A0);const Be=()=>new Map,Ti=e=>{const t=Be();return e.forEach((n,r)=>{t.set(r,n)}),t},_t=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},_0=(e,t)=>{const n=[];for(const[r,s]of e)n.push(t(s,r));return n},w0=(e,t)=>{for(const[n,r]of e)if(t(r,n))return!0;return!1},ln=()=>new Set,Ps=e=>e[e.length-1],I0=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Tt=Array.from,x0=Array.isArray;class N0{constructor(){this._observers=Be()}on(t,n){return _t(this._observers,t,ln).add(n),n}once(t,n){const r=(...s)=>{this.off(t,r),n(...s)};this.on(t,r)}off(t,n){const r=this._observers.get(t);r!==void 0&&(r.delete(n),r.size===0&&this._observers.delete(t))}emit(t,n){return Tt((this._observers.get(t)||Be()).values()).forEach(r=>r(...n))}destroy(){this._observers=Be()}}const yt=Math.floor,wr=Math.abs,Nl=(e,t)=>e<t?e:t,Vt=(e,t)=>e>t?e:t,Ll=e=>e!==0?e<0:1/e<0,ma=1,ga=2,Bs=4,Us=8,jn=32,ot=64,xe=128,hs=31,yi=63,Lt=127,L0=2147483647,Ol=Number.MAX_SAFE_INTEGER,O0=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&yt(e)===e),D0=e=>e.toLowerCase(),v0=/^\s*/g,M0=e=>e.replace(v0,""),R0=/([A-Z])/g,ba=(e,t)=>M0(e.replace(R0,n=>`${t}${D0(n)}`)),P0=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let s=0;s<n;s++)r[s]=t.codePointAt(s);return r},qn=typeof TextEncoder<"u"?new TextEncoder:null,B0=e=>qn.encode(e),U0=qn?B0:P0;let Dn=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Dn&&Dn.decode(new Uint8Array).length===1&&(Dn=null);class nr{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const fs=()=>new nr,H0=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Ke=e=>{const t=new Uint8Array(H0(e));let n=0;for(let r=0;r<e.bufs.length;r++){const s=e.bufs[r];t.set(s,n),n+=s.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},F0=(e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(Vt(n,t)*2),e.cpos=0)},ie=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ci=ie,H=(e,t)=>{for(;t>Lt;)ie(e,xe|Lt&t),t=yt(t/128);ie(e,Lt&t)},eo=(e,t)=>{const n=Ll(t);for(n&&(t=-t),ie(e,(t>yi?xe:0)|(n?ot:0)|yi&t),t=yt(t/64);t>0;)ie(e,(t>Lt?xe:0)|Lt&t),t=yt(t/128)},ki=new Uint8Array(3e4),V0=ki.length/3,Y0=(e,t)=>{if(t.length<V0){const n=qn.encodeInto(t,ki).written||0;H(e,n);for(let r=0;r<n;r++)ie(e,ki[r])}else _e(e,U0(t))},$0=(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;H(e,r);for(let s=0;s<r;s++)ie(e,n.codePointAt(s))},tn=qn&&qn.encodeInto?Y0:$0,ps=(e,t)=>{const n=e.cbuf.length,r=e.cpos,s=Nl(n-r,t.length),i=t.length-s;e.cbuf.set(t.subarray(0,s),r),e.cpos+=s,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(Vt(n*2,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)},_e=(e,t)=>{H(e,t.byteLength),ps(e,t)},to=(e,t)=>{F0(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},j0=(e,t)=>to(e,4).setFloat32(0,t,!1),q0=(e,t)=>to(e,8).setFloat64(0,t,!1),z0=(e,t)=>to(e,8).setBigInt64(0,t,!1),Ea=new DataView(new ArrayBuffer(4)),W0=e=>(Ea.setFloat32(0,e),Ea.getFloat32(0)===e),zn=(e,t)=>{switch(typeof t){case"string":ie(e,119),tn(e,t);break;case"number":O0(t)&&wr(t)<=L0?(ie(e,125),eo(e,t)):W0(t)?(ie(e,124),j0(e,t)):(ie(e,123),q0(e,t));break;case"bigint":ie(e,122),z0(e,t);break;case"object":if(t===null)ie(e,126);else if(x0(t)){ie(e,117),H(e,t.length);for(let n=0;n<t.length;n++)zn(e,t[n])}else if(t instanceof Uint8Array)ie(e,116),_e(e,t);else{ie(e,118);const n=Object.keys(t);H(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];tn(e,s),zn(e,t[s])}}break;case"boolean":ie(e,t?120:121);break;default:ie(e,127)}};class Ta extends nr{constructor(t){super(),this.w=t,this.s=null,this.count=0}write(t){this.s===t?this.count++:(this.count>0&&H(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const ya=e=>{e.count>0&&(eo(e.encoder,e.count===1?e.s:-e.s),e.count>1&&H(e.encoder,e.count-2))};class Ir{constructor(){this.encoder=new nr,this.s=0,this.count=0}write(t){this.s===t?this.count++:(ya(this),this.count=1,this.s=t)}toUint8Array(){return ya(this),Ke(this.encoder)}}const Ca=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);eo(e.encoder,t),e.count>1&&H(e.encoder,e.count-2)}};class Hs{constructor(){this.encoder=new nr,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Ca(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Ca(this),Ke(this.encoder)}}class G0{constructor(){this.sarr=[],this.s="",this.lensE=new Ir}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new nr;return this.sarr.push(this.s),this.s="",tn(t,this.sarr.join("")),ps(t,this.lensE.toUint8Array()),Ke(t)}}const Ct=e=>new Error(e),Xe=()=>{throw Ct("Method unimplemented")},Je=()=>{throw Ct("Unexpected case")},Dl=Ct("Unexpected end of array"),vl=Ct("Integer out of Range");class ms{constructor(t){this.arr=t,this.pos=0}}const bn=e=>new ms(e),K0=e=>e.pos!==e.arr.length,X0=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},we=e=>X0(e,B(e)),cn=e=>e.arr[e.pos++],B=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const s=e.arr[e.pos++];if(t=t+(s&Lt)*n,n*=128,s<xe)return t;if(t>Ol)throw vl}throw Dl},no=e=>{let t=e.arr[e.pos++],n=t&yi,r=64;const s=(t&ot)>0?-1:1;if(!(t&xe))return s*n;const i=e.arr.length;for(;e.pos<i;){if(t=e.arr[e.pos++],n=n+(t&Lt)*r,r*=128,t<xe)return s*n;if(n>Ol)throw vl}throw Dl},Q0=e=>{let t=B(e);if(t===0)return"";{let n=String.fromCodePoint(cn(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(cn(e));else for(;t>0;){const r=t<1e4?t:1e4,s=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,s),t-=r}return decodeURIComponent(escape(n))}},J0=e=>Dn.decode(we(e)),nn=Dn?J0:Q0,ro=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Z0=e=>ro(e,4).getFloat32(0,!1),em=e=>ro(e,8).getFloat64(0,!1),tm=e=>ro(e,8).getBigInt64(0,!1),nm=[e=>{},e=>null,no,Z0,em,tm,e=>!1,e=>!0,nn,e=>{const t=B(e),n={};for(let r=0;r<t;r++){const s=nn(e);n[s]=Wn(e)}return n},e=>{const t=B(e),n=[];for(let r=0;r<t;r++)n.push(Wn(e));return n},we],Wn=e=>nm[127-cn(e)](e);class ka extends ms{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),K0(this)?this.count=B(this)+1:this.count=-1),this.count--,this.s}}class xr extends ms{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=no(this);const t=Ll(this.s);this.count=1,t&&(this.s=-this.s,this.count=B(this)+2)}return this.count--,this.s}}class Fs extends ms{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=no(this),n=t&1;this.diff=yt(t/2),this.count=1,n&&(this.count=B(this)+2)}return this.s+=this.diff,this.count--,this.s}}class rm{constructor(t){this.decoder=new xr(t),this.str=nn(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const sm=crypto.getRandomValues.bind(crypto),Ml=()=>sm(new Uint32Array(1))[0],im="10000000-1000-4000-8000"+-1e11,om=()=>im.replace(/[018]/g,e=>(e^Ml()&15>>e/4).toString(16)),Sa=e=>new Promise(e);Promise.all.bind(Promise);const Aa=e=>e===void 0?null:e;class am{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let Rl=new am,um=!0;try{typeof localStorage<"u"&&localStorage&&(Rl=localStorage,um=!1)}catch{}const lm=Rl,cm=Object.assign,dm=Object.keys,hm=(e,t)=>{for(const n in e)t(e[n],n)},_a=e=>dm(e).length,fm=e=>{for(const t in e)return!1;return!0},pm=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},mm=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),gm=(e,t)=>e===t||_a(e)===_a(t)&&pm(e,(n,r)=>(n!==void 0||mm(t,r))&&t[r]===n),bm=Object.freeze,Pl=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&Pl(e[t])}return bm(e)},so=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&so(e,t,n+1)}},Em=e=>e,Tm=(e,t)=>t.includes(e),Gn=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";let qe;const ym=()=>{if(qe===void 0)if(Gn){qe=Be();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];r[0]==="-"?(t!==null&&qe.set(t,""),t=r):t!==null&&(qe.set(t,r),t=null)}t!==null&&qe.set(t,"")}else typeof location=="object"?(qe=Be(),(location.search||"?").slice(1).split("&").forEach(e=>{if(e.length!==0){const[t,n]=e.split("=");qe.set(`--${ba(t,"-")}`,n),qe.set(`-${ba(t,"-")}`,n)}})):qe=Be();return qe},Si=e=>ym().has(e),Hr=e=>Aa(Gn?process.env[e.toUpperCase().replaceAll("-","_")]:lm.getItem(e)),Bl=e=>Si("--"+e)||Hr(e)!==null;Bl("production");const Cm=Gn&&Tm(process.env.FORCE_COLOR,["true","1","2"]),km=Cm||!Si("--no-colors")&&!Bl("no-color")&&(!Gn||process.stdout.isTTY)&&(!Gn||Si("--color")||Hr("COLORTERM")!==null||(Hr("TERM")||"").includes("color")),Sm=e=>new Uint8Array(e),Am=e=>{const t=Sm(e.byteLength);return t.set(e),t};class _m{constructor(t,n){this.left=t,this.right=n}}const nt=(e,t)=>new _m(e,t);typeof DOMParser<"u"&&new DOMParser;const wm=e=>_0(e,(t,n)=>`${n}:${t};`).join(""),at=Symbol,Ul=at(),Hl=at(),Im=at(),xm=at(),Nm=at(),Fl=at(),Lm=at(),io=at(),Om=at(),Dm=e=>{var s;e.length===1&&((s=e[0])==null?void 0:s.constructor)===Function&&(e=e[0]());const t=[],n=[];let r=0;for(;r<e.length;r++){const i=e[r];if(i===void 0)break;if(i.constructor===String||i.constructor===Number)t.push(i);else if(i.constructor===Object)break}for(r>0&&n.push(t.join(""));r<e.length;r++){const i=e[r];i instanceof Symbol||n.push(i)}return n},vm={[Ul]:nt("font-weight","bold"),[Hl]:nt("font-weight","normal"),[Im]:nt("color","blue"),[Nm]:nt("color","green"),[xm]:nt("color","grey"),[Fl]:nt("color","red"),[Lm]:nt("color","purple"),[io]:nt("color","orange"),[Om]:nt("color","black")},Mm=e=>{var o;e.length===1&&((o=e[0])==null?void 0:o.constructor)===Function&&(e=e[0]());const t=[],n=[],r=Be();let s=[],i=0;for(;i<e.length;i++){const a=e[i],u=vm[a];if(u!==void 0)r.set(u.left,u.right);else{if(a===void 0)break;if(a.constructor===String||a.constructor===Number){const c=wm(r);i>0||c.length>0?(t.push("%c"+a),n.push(c)):t.push(a)}else break}}for(i>0&&(s=n,s.unshift(t.join("")));i<e.length;i++){const a=e[i];a instanceof Symbol||s.push(a)}return s},Vl=km?Mm:Dm,Rm=(...e)=>{console.log(...Vl(e)),Yl.forEach(t=>t.print(e))},Pm=(...e)=>{console.warn(...Vl(e)),e.unshift(io),Yl.forEach(t=>t.print(e))},Yl=ln(),$l=e=>({[Symbol.iterator](){return this},next:e}),Bm=(e,t)=>$l(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),Vs=(e,t)=>$l(()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});class oo{constructor(t,n){this.clock=t,this.len=n}}class rr{constructor(){this.clients=new Map}}const jl=(e,t,n)=>t.clients.forEach((r,s)=>{const i=e.doc.store.clients.get(s);if(i!=null){const o=i[i.length-1],a=o.id.clock+o.length;for(let u=0,c=r[u];u<r.length&&c.clock<a;c=r[++u])rc(e,i,c.clock,c.len,n)}}),Um=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){const s=yt((n+r)/2),i=e[s],o=i.clock;if(o<=t){if(t<o+i.len)return s;n=s+1}else r=s-1}return null},ql=(e,t)=>{const n=e.clients.get(t.client);return n!==void 0&&Um(n,t.clock)!==null},ao=e=>{e.clients.forEach(t=>{t.sort((s,i)=>s.clock-i.clock);let n,r;for(n=1,r=1;n<t.length;n++){const s=t[r-1],i=t[n];s.clock+s.len>=i.clock?s.len=Vt(s.len,i.clock+i.len-s.clock):(r<n&&(t[r]=i),r++)}t.length=r})},Hm=e=>{const t=new rr;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,s)=>{if(!t.clients.has(s)){const i=r.slice();for(let o=n+1;o<e.length;o++)I0(i,e[o].clients.get(s)||[]);t.clients.set(s,i)}});return ao(t),t},Fr=(e,t,n,r)=>{_t(e.clients,t,()=>[]).push(new oo(n,r))},Fm=()=>new rr,Vm=e=>{const t=Fm();return e.clients.forEach((n,r)=>{const s=[];for(let i=0;i<n.length;i++){const o=n[i];if(o.deleted){const a=o.id.clock;let u=o.length;if(i+1<n.length)for(let c=n[i+1];i+1<n.length&&c.deleted;c=n[++i+1])u+=c.length;s.push(new oo(a,u))}}s.length>0&&t.clients.set(r,s)}),t},En=(e,t)=>{H(e.restEncoder,t.clients.size),Tt(t.clients.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{e.resetDsCurVal(),H(e.restEncoder,n);const s=r.length;H(e.restEncoder,s);for(let i=0;i<s;i++){const o=r[i];e.writeDsClock(o.clock),e.writeDsLen(o.len)}})},uo=e=>{const t=new rr,n=B(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const s=B(e.restDecoder),i=B(e.restDecoder);if(i>0){const o=_t(t.clients,s,()=>[]);for(let a=0;a<i;a++)o.push(new oo(e.readDsClock(),e.readDsLen()))}}return t},wa=(e,t,n)=>{const r=new rr,s=B(e.restDecoder);for(let i=0;i<s;i++){e.resetDsCurVal();const o=B(e.restDecoder),a=B(e.restDecoder),u=n.clients.get(o)||[],c=ue(n,o);for(let d=0;d<a;d++){const h=e.readDsClock(),f=h+e.readDsLen();if(h<c){c<f&&Fr(r,o,c,f-c);let p=Ue(u,h),m=u[p];for(!m.deleted&&m.id.clock<h&&(u.splice(p+1,0,Wr(t,m,h-m.id.clock)),p++);p<u.length&&(m=u[p++],m.id.clock<f);)m.deleted||(f<m.id.clock+m.length&&u.splice(p,0,Wr(t,m,f-m.id.clock)),m.delete(t))}else Fr(r,o,h,f-h)}}if(r.clients.size>0){const i=new Rt;return H(i.restEncoder,0),En(i,r),i.toUint8Array()}return null},zl=Ml;class Tn extends N0{constructor({guid:t=om(),collectionid:n=null,gc:r=!0,gcFilter:s=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:a=!0}={}){super(),this.gc=r,this.gcFilter=s,this.clientID=zl(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new tc,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Sa(c=>{this.on("load",()=>{this.isLoaded=!0,c(this)})});const u=()=>Sa(c=>{const d=h=>{(h===void 0||h===!0)&&(this.off("sync",d),c())};this.on("sync",d)});this.on("sync",c=>{c===!1&&this.isSynced&&(this.whenSynced=u()),this.isSynced=c===void 0||c===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=u()}load(){const t=this._item;t!==null&&!this.shouldLoad&&W(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Tt(this.subdocs).map(t=>t.guid))}transact(t,n=null){return W(this,t,n)}get(t,n=de){const r=_t(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),s=r.constructor;if(n!==de&&s!==n)if(s===de){const i=new n;i._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=r._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=r._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return r}getArray(t=""){return this.get(t,sn)}getText(t=""){return this.get(t,fn)}getMap(t=""){return this.get(t,hn)}getXmlElement(t=""){return this.get(t,St)}getXmlFragment(t=""){return this.get(t,Pt)}toJSON(){const t={};return this.share.forEach((n,r)=>{t[r]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,Tt(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new Tn({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,W(t.parent.doc,r=>{const s=n.doc;t.deleted||r.subdocsAdded.add(s),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Wl{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return B(this.restDecoder)}readDsLen(){return B(this.restDecoder)}}class Gl extends Wl{readLeftID(){return F(B(this.restDecoder),B(this.restDecoder))}readRightID(){return F(B(this.restDecoder),B(this.restDecoder))}readClient(){return B(this.restDecoder)}readInfo(){return cn(this.restDecoder)}readString(){return nn(this.restDecoder)}readParentInfo(){return B(this.restDecoder)===1}readTypeRef(){return B(this.restDecoder)}readLen(){return B(this.restDecoder)}readAny(){return Wn(this.restDecoder)}readBuf(){return Am(we(this.restDecoder))}readJSON(){return JSON.parse(nn(this.restDecoder))}readKey(){return nn(this.restDecoder)}}class Ym{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=B(this.restDecoder),this.dsCurrVal}readDsLen(){const t=B(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class dn extends Ym{constructor(t){super(t),this.keys=[],B(t),this.keyClockDecoder=new Fs(we(t)),this.clientDecoder=new xr(we(t)),this.leftClockDecoder=new Fs(we(t)),this.rightClockDecoder=new Fs(we(t)),this.infoDecoder=new ka(we(t),cn),this.stringDecoder=new rm(we(t)),this.parentInfoDecoder=new ka(we(t),cn),this.typeRefDecoder=new xr(we(t)),this.lenDecoder=new xr(we(t))}readLeftID(){return new rn(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new rn(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Wn(this.restDecoder)}readBuf(){return we(this.restDecoder)}readJSON(){return Wn(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t<this.keys.length)return this.keys[t];{const n=this.stringDecoder.read();return this.keys.push(n),n}}}class Kl{constructor(){this.restEncoder=fs()}toUint8Array(){return Ke(this.restEncoder)}resetDsCurVal(){}writeDsClock(t){H(this.restEncoder,t)}writeDsLen(t){H(this.restEncoder,t)}}class sr extends Kl{writeLeftID(t){H(this.restEncoder,t.client),H(this.restEncoder,t.clock)}writeRightID(t){H(this.restEncoder,t.client),H(this.restEncoder,t.clock)}writeClient(t){H(this.restEncoder,t)}writeInfo(t){Ci(this.restEncoder,t)}writeString(t){tn(this.restEncoder,t)}writeParentInfo(t){H(this.restEncoder,t?1:0)}writeTypeRef(t){H(this.restEncoder,t)}writeLen(t){H(this.restEncoder,t)}writeAny(t){zn(this.restEncoder,t)}writeBuf(t){_e(this.restEncoder,t)}writeJSON(t){tn(this.restEncoder,JSON.stringify(t))}writeKey(t){tn(this.restEncoder,t)}}class Xl{constructor(){this.restEncoder=fs(),this.dsCurrVal=0}toUint8Array(){return Ke(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(t){const n=t-this.dsCurrVal;this.dsCurrVal=t,H(this.restEncoder,n)}writeDsLen(t){t===0&&Je(),H(this.restEncoder,t-1),this.dsCurrVal+=t}}class Rt extends Xl{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Hs,this.clientEncoder=new Ir,this.leftClockEncoder=new Hs,this.rightClockEncoder=new Hs,this.infoEncoder=new Ta(Ci),this.stringEncoder=new G0,this.parentInfoEncoder=new Ta(Ci),this.typeRefEncoder=new Ir,this.lenEncoder=new Ir}toUint8Array(){const t=fs();return H(t,0),_e(t,this.keyClockEncoder.toUint8Array()),_e(t,this.clientEncoder.toUint8Array()),_e(t,this.leftClockEncoder.toUint8Array()),_e(t,this.rightClockEncoder.toUint8Array()),_e(t,Ke(this.infoEncoder)),_e(t,this.stringEncoder.toUint8Array()),_e(t,Ke(this.parentInfoEncoder)),_e(t,this.typeRefEncoder.toUint8Array()),_e(t,this.lenEncoder.toUint8Array()),ps(t,Ke(this.restEncoder)),Ke(t)}writeLeftID(t){this.clientEncoder.write(t.client),this.leftClockEncoder.write(t.clock)}writeRightID(t){this.clientEncoder.write(t.client),this.rightClockEncoder.write(t.clock)}writeClient(t){this.clientEncoder.write(t)}writeInfo(t){this.infoEncoder.write(t)}writeString(t){this.stringEncoder.write(t)}writeParentInfo(t){this.parentInfoEncoder.write(t?1:0)}writeTypeRef(t){this.typeRefEncoder.write(t)}writeLen(t){this.lenEncoder.write(t)}writeAny(t){zn(this.restEncoder,t)}writeBuf(t){_e(this.restEncoder,t)}writeJSON(t){zn(this.restEncoder,t)}writeKey(t){const n=this.keyMap.get(t);n===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(t)):this.keyClockEncoder.write(n)}}const $m=(e,t,n,r)=>{r=Vt(r,t[0].id.clock);const s=Ue(t,r);H(e.restEncoder,t.length-s),e.writeClient(n),H(e.restEncoder,r);const i=t[s];i.write(e,r-i.id.clock);for(let o=s+1;o<t.length;o++)t[o].write(e,0)},lo=(e,t,n)=>{const r=new Map;n.forEach((s,i)=>{ue(t,i)>s&&r.set(i,s)}),gs(t).forEach((s,i)=>{n.has(i)||r.set(i,0)}),H(e.restEncoder,r.size),Tt(r.entries()).sort((s,i)=>i[0]-s[0]).forEach(([s,i])=>{$m(e,t.clients.get(s),s,i)})},jm=(e,t)=>{const n=Be(),r=B(e.restDecoder);for(let s=0;s<r;s++){const i=B(e.restDecoder),o=new Array(i),a=e.readClient();let u=B(e.restDecoder);n.set(a,{i:0,refs:o});for(let c=0;c<i;c++){const d=e.readInfo();switch(hs&d){case 0:{const h=e.readLen();o[c]=new De(F(a,u),h),u+=h;break}case 10:{const h=B(e.restDecoder);o[c]=new ve(F(a,u),h),u+=h;break}default:{const h=(d&(ot|xe))===0,f=new he(F(a,u),null,(d&xe)===xe?e.readLeftID():null,null,(d&ot)===ot?e.readRightID():null,h?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,h&&(d&jn)===jn?e.readString():null,kc(e,d));o[c]=f,u+=f.length}}}}return n},qm=(e,t,n)=>{const r=[];let s=Tt(n.keys()).sort((p,m)=>p-m);if(s.length===0)return null;const i=()=>{if(s.length===0)return null;let p=n.get(s[s.length-1]);for(;p.refs.length===p.i;)if(s.pop(),s.length>0)p=n.get(s[s.length-1]);else return null;return p};let o=i();if(o===null)return null;const a=new tc,u=new Map,c=(p,m)=>{const E=u.get(p);(E==null||E>m)&&u.set(p,m)};let d=o.refs[o.i++];const h=new Map,f=()=>{for(const p of r){const m=p.id.client,E=n.get(m);E?(E.i--,a.clients.set(m,E.refs.slice(E.i)),n.delete(m),E.i=0,E.refs=[]):a.clients.set(m,[p]),s=s.filter(C=>C!==m)}r.length=0};for(;;){if(d.constructor!==ve){const m=_t(h,d.id.client,()=>ue(t,d.id.client))-d.id.clock;if(m<0)r.push(d),c(d.id.client,d.id.clock-1),f();else{const E=d.getMissing(e,t);if(E!==null){r.push(d);const C=n.get(E)||{refs:[],i:0};if(C.refs.length===C.i)c(E,ue(t,E)),f();else{d=C.refs[C.i++];continue}}else(m===0||m<d.length)&&(d.integrate(e,m),h.set(d.id.client,d.id.clock+d.length))}}if(r.length>0)d=r.pop();else if(o!==null&&o.i<o.refs.length)d=o.refs[o.i++];else{if(o=i(),o===null)break;d=o.refs[o.i++]}}if(a.clients.size>0){const p=new Rt;return lo(p,a,new Map),H(p.restEncoder,0),{missing:u,update:p.toUint8Array()}}return null},zm=(e,t)=>lo(e,t.doc.store,t.beforeState),Wm=(e,t,n,r=new dn(e))=>W(t,s=>{s.local=!1;let i=!1;const o=s.doc,a=o.store,u=jm(r,o),c=qm(s,a,u),d=a.pendingStructs;if(d){for(const[f,p]of d.missing)if(p<ue(a,f)){i=!0;break}if(c){for(const[f,p]of c.missing){const m=d.missing.get(f);(m==null||m>p)&&d.missing.set(f,p)}d.update=Vr([d.update,c.update])}}else a.pendingStructs=c;const h=wa(r,s,a);if(a.pendingDs){const f=new dn(bn(a.pendingDs));B(f.restDecoder);const p=wa(f,s,a);h&&p?a.pendingDs=Vr([h,p]):a.pendingDs=h||p}else a.pendingDs=h;if(i){const f=a.pendingStructs.update;a.pendingStructs=null,Ql(s.doc,f)}},n,!1),Ql=(e,t,n,r=dn)=>{const s=bn(t);Wm(s,e,n,new r(s))},Ia=(e,t,n)=>Ql(e,t,n,Gl),Gm=(e,t,n=new Map)=>{lo(e,t.store,n),En(e,Vm(t.store))},Km=(e,t=new Uint8Array([0]),n=new Rt)=>{const r=Jl(t);Gm(n,e,r);const s=[n.toUint8Array()];if(e.store.pendingDs&&s.push(e.store.pendingDs),e.store.pendingStructs&&s.push(cg(e.store.pendingStructs.update,t)),s.length>1){if(n.constructor===sr)return ug(s.map((i,o)=>o===0?i:hg(i)));if(n.constructor===Rt)return Vr(s)}return s[0]},xa=(e,t)=>Km(e,t,new sr),Xm=e=>{const t=new Map,n=B(e.restDecoder);for(let r=0;r<n;r++){const s=B(e.restDecoder),i=B(e.restDecoder);t.set(s,i)}return t},Jl=e=>Xm(new Wl(bn(e))),Zl=(e,t)=>(H(e.restEncoder,t.size),Tt(t.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{H(e.restEncoder,n),H(e.restEncoder,r)}),e),Qm=(e,t)=>Zl(e,gs(t.store)),Jm=(e,t=new Xl)=>(e instanceof Map?Zl(t,e):Qm(t,e),t.toUint8Array()),Zm=e=>Jm(e,new Kl);class eg{constructor(){this.l=[]}}const Na=()=>new eg,La=(e,t)=>e.l.push(t),Oa=(e,t)=>{const n=e.l,r=n.length;e.l=n.filter(s=>t!==s),r===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},ec=(e,t,n)=>so(e.l,[t,n]);class rn{constructor(t,n){this.client=t,this.clock=n}}const gr=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,F=(e,t)=>new rn(e,t),tg=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Je()},Kt=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ql(t.ds,e.id),Ai=(e,t)=>{const n=_t(e.meta,Ai,ln),r=e.doc.store;n.has(t)||(t.sv.forEach((s,i)=>{s<ue(r,i)&&kt(e,F(i,s))}),jl(e,t.ds,s=>{}),n.add(t))};class tc{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const gs=e=>{const t=new Map;return e.clients.forEach((n,r)=>{const s=n[n.length-1];t.set(r,s.id.clock+s.length)}),t},ue=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const r=n[n.length-1];return r.id.clock+r.length},nc=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const r=n[n.length-1];if(r.id.clock+r.length!==t.id.clock)throw Je()}n.push(t)},Ue=(e,t)=>{let n=0,r=e.length-1,s=e[r],i=s.id.clock;if(i===t)return r;let o=yt(t/(i+s.length-1)*r);for(;n<=r;){if(s=e[o],i=s.id.clock,i<=t){if(t<i+s.length)return o;n=o+1}else r=o-1;o=yt((n+r)/2)}throw Je()},ng=(e,t)=>{const n=e.clients.get(t.client);return n[Ue(n,t.clock)]},Ys=ng,_i=(e,t,n)=>{const r=Ue(t,n),s=t[r];return s.id.clock<n&&s instanceof he?(t.splice(r+1,0,Wr(e,s,n-s.id.clock)),r+1):r},kt=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[_i(e,n,t.clock)]},Da=(e,t,n)=>{const r=t.clients.get(n.client),s=Ue(r,n.clock),i=r[s];return n.clock!==i.id.clock+i.length-1&&i.constructor!==De&&r.splice(s+1,0,Wr(e,i,n.clock-i.id.clock+1)),i},rg=(e,t,n)=>{const r=e.clients.get(t.id.client);r[Ue(r,t.id.clock)]=n},rc=(e,t,n,r,s)=>{if(r===0)return;const i=n+r;let o=_i(e,t,n),a;do a=t[o++],i<a.id.clock+a.length&&_i(e,t,i),s(a);while(o<t.length&&t[o].id.clock<i)};class sg{constructor(t,n,r){this.doc=t,this.deleteSet=new rr,this.beforeState=gs(t.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=n,this.meta=new Map,this.local=r,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const va=(e,t)=>t.deleteSet.clients.size===0&&!w0(t.afterState,(n,r)=>t.beforeState.get(r)!==n)?!1:(ao(t.deleteSet),zm(e,t),En(e,t.deleteSet),!0),Ma=(e,t,n)=>{const r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&_t(e.changed,t,ln).add(n)},Nr=(e,t)=>{let n=e[t],r=e[t-1],s=t;for(;s>0;n=r,r=e[--s-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof he&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}const i=t-s;return i&&e.splice(t+1-i,i),i},ig=(e,t,n)=>{for(const[r,s]of e.clients.entries()){const i=t.clients.get(r);for(let o=s.length-1;o>=0;o--){const a=s[o],u=a.clock+a.len;for(let c=Ue(i,a.clock),d=i[c];c<i.length&&d.id.clock<u;d=i[++c]){const h=i[c];if(a.clock+a.len<=h.id.clock)break;h instanceof he&&h.deleted&&!h.keep&&n(h)&&h.gc(t,!1)}}}},og=(e,t)=>{e.clients.forEach((n,r)=>{const s=t.clients.get(r);for(let i=n.length-1;i>=0;i--){const o=n[i],a=Nl(s.length-1,1+Ue(s,o.clock+o.len-1));for(let u=a,c=s[u];u>0&&c.id.clock>=o.clock;c=s[u])u-=1+Nr(s,u)}})},sc=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,s=r.store,i=n.deleteSet,o=n._mergeStructs;try{ao(i),n.afterState=gs(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const a=[];n.changed.forEach((u,c)=>a.push(()=>{(c._item===null||!c._item.deleted)&&c._callObserver(n,u)})),a.push(()=>{n.changedParentTypes.forEach((u,c)=>{c._dEH.l.length>0&&(c._item===null||!c._item.deleted)&&(u=u.filter(d=>d.target._item===null||!d.target._item.deleted),u.forEach(d=>{d.currentTarget=c,d._path=null}),u.sort((d,h)=>d.path.length-h.path.length),ec(c._dEH,u,n))})}),a.push(()=>r.emit("afterTransaction",[n,r])),so(a,[]),n._needFormattingCleanup&&wg(n)}finally{r.gc&&ig(i,s,r.gcFilter),og(i,s),n.afterState.forEach((d,h)=>{const f=n.beforeState.get(h)||0;if(f!==d){const p=s.clients.get(h),m=Vt(Ue(p,f),1);for(let E=p.length-1;E>=m;)E-=1+Nr(p,E)}});for(let d=o.length-1;d>=0;d--){const{client:h,clock:f}=o[d].id,p=s.clients.get(h),m=Ue(p,f);m+1<p.length&&Nr(p,m+1)>1||m>0&&Nr(p,m)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(Rm(io,Ul,"[yjs] ",Hl,Fl,"Changed the client-id because another client seems to be using it."),r.clientID=zl()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const d=new sr;va(d,n)&&r.emit("update",[d.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const d=new Rt;va(d,n)&&r.emit("updateV2",[d.toUint8Array(),n.origin,r,n])}const{subdocsAdded:a,subdocsLoaded:u,subdocsRemoved:c}=n;(a.size>0||c.size>0||u.size>0)&&(a.forEach(d=>{d.clientID=r.clientID,d.collectionid==null&&(d.collectionid=r.collectionid),r.subdocs.add(d)}),c.forEach(d=>r.subdocs.delete(d)),r.emit("subdocs",[{loaded:u,added:a,removed:c},r,n]),c.forEach(d=>d.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):sc(e,t+1)}}},W=(e,t,n=null,r=!0)=>{const s=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new sg(e,n,r),s.push(e._transaction),s.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const a=e._transaction===s[0];e._transaction=null,a&&sc(s,0)}}return o};function*ag(e){const t=B(e.restDecoder);for(let n=0;n<t;n++){const r=B(e.restDecoder),s=e.readClient();let i=B(e.restDecoder);for(let o=0;o<r;o++){const a=e.readInfo();if(a===10){const u=B(e.restDecoder);yield new ve(F(s,i),u),i+=u}else if(hs&a){const u=(a&(ot|xe))===0,c=new he(F(s,i),null,(a&xe)===xe?e.readLeftID():null,null,(a&ot)===ot?e.readRightID():null,u?e.readParentInfo()?e.readString():e.readLeftID():null,u&&(a&jn)===jn?e.readString():null,kc(e,a));yield c,i+=c.length}else{const u=e.readLen();yield new De(F(s,i),u),i+=u}}}}class co{constructor(t,n){this.gen=ag(t),this.curr=null,this.done=!1,this.filterSkips=n,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===ve);return this.curr}}class ho{constructor(t){this.currClient=0,this.startClock=0,this.written=0,this.encoder=t,this.clientStructs=[]}}const ug=e=>Vr(e,Gl,sr),lg=(e,t)=>{if(e.constructor===De){const{client:n,clock:r}=e.id;return new De(F(n,r+t),e.length-t)}else if(e.constructor===ve){const{client:n,clock:r}=e.id;return new ve(F(n,r+t),e.length-t)}else{const n=e,{client:r,clock:s}=n.id;return new he(F(r,s+t),null,F(r,s+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Vr=(e,t=dn,n=Rt)=>{if(e.length===1)return e[0];const r=e.map(d=>new t(bn(d)));let s=r.map(d=>new co(d,!0)),i=null;const o=new n,a=new ho(o);for(;s=s.filter(f=>f.curr!==null),s.sort((f,p)=>{if(f.curr.id.client===p.curr.id.client){const m=f.curr.id.clock-p.curr.id.clock;return m===0?f.curr.constructor===p.curr.constructor?0:f.curr.constructor===ve?1:-1:m}else return p.curr.id.client-f.curr.id.client}),s.length!==0;){const d=s[0],h=d.curr.id.client;if(i!==null){let f=d.curr,p=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=d.next(),p=!0;if(f===null||f.id.client!==h||p&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)ft(a,i.struct,i.offset),i={struct:f,offset:0},d.next();else if(i.struct.id.clock+i.struct.length<f.id.clock)if(i.struct.constructor===ve)i.struct.length=f.id.clock+f.length-i.struct.id.clock;else{ft(a,i.struct,i.offset);const m=f.id.clock-i.struct.id.clock-i.struct.length;i={struct:new ve(F(h,i.struct.id.clock+i.struct.length),m),offset:0}}else{const m=i.struct.id.clock+i.struct.length-f.id.clock;m>0&&(i.struct.constructor===ve?i.struct.length-=m:f=lg(f,m)),i.struct.mergeWith(f)||(ft(a,i.struct,i.offset),i={struct:f,offset:0},d.next())}}else i={struct:d.curr,offset:0},d.next();for(let f=d.curr;f!==null&&f.id.client===h&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==ve;f=d.next())ft(a,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(ft(a,i.struct,i.offset),i=null),fo(a);const u=r.map(d=>uo(d)),c=Hm(u);return En(o,c),o.toUint8Array()},cg=(e,t,n=dn,r=Rt)=>{const s=Jl(t),i=new r,o=new ho(i),a=new n(bn(e)),u=new co(a,!1);for(;u.curr;){const d=u.curr,h=d.id.client,f=s.get(h)||0;if(u.curr.constructor===ve){u.next();continue}if(d.id.clock+d.length>f)for(ft(o,d,Vt(f-d.id.clock,0)),u.next();u.curr&&u.curr.id.client===h;)ft(o,u.curr,0),u.next();else for(;u.curr&&u.curr.id.client===h&&u.curr.id.clock+u.curr.length<=f;)u.next()}fo(o);const c=uo(a);return En(i,c),i.toUint8Array()},ic=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Ke(e.encoder.restEncoder)}),e.encoder.restEncoder=fs(),e.written=0)},ft=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ic(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),H(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},fo=e=>{ic(e);const t=e.encoder.restEncoder;H(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];H(t,r.written),ps(t,r.restEncoder)}},dg=(e,t,n,r)=>{const s=new n(bn(e)),i=new co(s,!1),o=new r,a=new ho(o);for(let c=i.curr;c!==null;c=i.next())ft(a,t(c),0);fo(a);const u=uo(s);return En(o,u),o.toUint8Array()},hg=e=>dg(e,Em,dn,sr),Ra="You must not compute changes after the event-handler fired.";class bs{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=fg(this.currentTarget,this.target))}deletes(t){return ql(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(Ra);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(s=>{if(s!==null){const i=n._map.get(s);let o,a;if(this.adds(i)){let u=i.left;for(;u!==null&&this.adds(u);)u=u.left;if(this.deletes(i))if(u!==null&&this.deletes(u))o="delete",a=Ps(u.content.getContent());else return;else u!==null&&this.deletes(u)?(o="update",a=Ps(u.content.getContent())):(o="add",a=void 0)}else if(this.deletes(i))o="delete",a=Ps(i.content.getContent());else return;t.set(s,{action:o,oldValue:a})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(Ra);const n=this.target,r=ln(),s=ln(),i=[];if(t={added:r,deleted:s,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let a=null;const u=()=>{a&&i.push(a)};for(let c=n._start;c!==null;c=c.right)c.deleted?this.deletes(c)&&!this.adds(c)&&((a===null||a.delete===void 0)&&(u(),a={delete:0}),a.delete+=c.length,s.add(c)):this.adds(c)?((a===null||a.insert===void 0)&&(u(),a={insert:[]}),a.insert=a.insert.concat(c.content.getContent()),r.add(c)):((a===null||a.retain===void 0)&&(u(),a={retain:0}),a.retain+=c.length);a!==null&&a.retain===void 0&&u()}this._changes=t}return t}}const fg=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let r=0,s=t._item.parent._start;for(;s!==t._item&&s!==null;)!s.deleted&&s.countable&&(r+=s.length),s=s.right;n.unshift(r)}t=t._item.parent}return n},fe=()=>{Pm("Invalid access: Add Yjs type to a document before reading data.")},oc=80;let po=0;class pg{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=po++}}const mg=e=>{e.timestamp=po++},ac=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=po++},gg=(e,t,n)=>{if(e.length>=oc){const r=e.reduce((s,i)=>s.timestamp<i.timestamp?s:i);return ac(r,t,n),r}else{const r=new pg(t,n);return e.push(r),r}},Es=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>wr(t-i.index)<wr(t-o.index)?i:o);let r=e._start,s=0;for(n!==null&&(r=n.p,s=n.index,mg(n));r.right!==null&&s<t;){if(!r.deleted&&r.countable){if(t<s+r.length)break;s+=r.length}r=r.right}for(;r.left!==null&&s>t;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);return n!==null&&wr(n.index-s)<r.parent.length/oc?(ac(n,r,s),n):gg(e._searchMarker,r,s)},Kn=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const s=e[r];if(n>0){let i=s.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(s.index-=i.length);if(i===null||i.marker===!0){e.splice(r,1);continue}s.p=i,i.marker=!0}(t<s.index||n>0&&t===s.index)&&(s.index=Vt(t,s.index+n))}},Ts=(e,t,n)=>{const r=e,s=t.changedParentTypes;for(;_t(s,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;ec(r._eH,n,t)};class de{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Na(),this._dEH=Na(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw Xe()}clone(){throw Xe()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){La(this._eH,t)}observeDeep(t){La(this._dEH,t)}unobserve(t){Oa(this._eH,t)}unobserveDeep(t){Oa(this._dEH,t)}toJSON(){}}const uc=(e,t,n)=>{e.doc??fe(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const s=[];let i=e._start;for(;i!==null&&r>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let a=t;a<o.length&&r>0;a++)s.push(o[a]),r--;t=0}}i=i.right}return s},lc=e=>{e.doc??fe();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const r=n.content.getContent();for(let s=0;s<r.length;s++)t.push(r[s])}n=n.right}return t},Xn=(e,t)=>{let n=0,r=e._start;for(e.doc??fe();r!==null;){if(r.countable&&!r.deleted){const s=r.content.getContent();for(let i=0;i<s.length;i++)t(s[i],n++,e)}r=r.right}},cc=(e,t)=>{const n=[];return Xn(e,(r,s)=>{n.push(t(r,s,e))}),n},bg=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const s=n[r++];return n.length<=r&&(n=null),{done:!1,value:s}}}},dc=(e,t)=>{e.doc??fe();const n=Es(e,t);let r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},Yr=(e,t,n,r)=>{let s=n;const i=e.doc,o=i.clientID,a=i.store,u=n===null?t._start:n.right;let c=[];const d=()=>{c.length>0&&(s=new he(F(o,ue(a,o)),s,s&&s.lastId,u,u&&u.id,t,null,new Bt(c)),s.integrate(e,0),c=[])};r.forEach(h=>{if(h===null)c.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:c.push(h);break;default:switch(d(),h.constructor){case Uint8Array:case ArrayBuffer:s=new he(F(o,ue(a,o)),s,s&&s.lastId,u,u&&u.id,t,null,new ir(new Uint8Array(h))),s.integrate(e,0);break;case Tn:s=new he(F(o,ue(a,o)),s,s&&s.lastId,u,u&&u.id,t,null,new or(h)),s.integrate(e,0);break;default:if(h instanceof de)s=new he(F(o,ue(a,o)),s,s&&s.lastId,u,u&&u.id,t,null,new ut(h)),s.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),d()},hc=()=>Ct("Length exceeded!"),fc=(e,t,n,r)=>{if(n>t._length)throw hc();if(n===0)return t._searchMarker&&Kn(t._searchMarker,n,r.length),Yr(e,t,null,r);const s=n,i=Es(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&kt(e,F(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Kn(t._searchMarker,s,r.length),Yr(e,t,o,r)},Eg=(e,t,n)=>{let s=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(s)for(;s.right;)s=s.right;return Yr(e,t,s,n)},pc=(e,t,n,r)=>{if(r===0)return;const s=n,i=r,o=Es(t,n);let a=t._start;for(o!==null&&(a=o.p,n-=o.index);a!==null&&n>0;a=a.right)!a.deleted&&a.countable&&(n<a.length&&kt(e,F(a.id.client,a.id.clock+n)),n-=a.length);for(;r>0&&a!==null;)a.deleted||(r<a.length&&kt(e,F(a.id.client,a.id.clock+r)),a.delete(e),r-=a.length),a=a.right;if(r>0)throw hc();t._searchMarker&&Kn(t._searchMarker,s,-i+r)},$r=(e,t,n)=>{const r=t._map.get(n);r!==void 0&&r.delete(e)},mo=(e,t,n,r)=>{const s=t._map.get(n)||null,i=e.doc,o=i.clientID;let a;if(r==null)a=new Bt([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new Bt([r]);break;case Uint8Array:a=new ir(r);break;case Tn:a=new or(r);break;default:if(r instanceof de)a=new ut(r);else throw new Error("Unexpected content type")}new he(F(o,ue(i.store,o)),s,s&&s.lastId,null,null,t,n,a).integrate(e,0)},go=(e,t)=>{e.doc??fe();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},mc=e=>{const t={};return e.doc??fe(),e._map.forEach((n,r)=>{n.deleted||(t[r]=n.content.getContent()[n.length-1])}),t},gc=(e,t)=>{e.doc??fe();const n=e._map.get(t);return n!==void 0&&!n.deleted},Tg=(e,t)=>{const n={};return e._map.forEach((r,s)=>{let i=r;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&Kt(i,t)&&(n[s]=i.content.getContent()[i.length-1])}),n},br=e=>(e.doc??fe(),Bm(e._map.entries(),t=>!t[1].deleted));class yg extends bs{}class sn extends de{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new sn;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new sn}clone(){const t=new sn;return t.insert(0,this.toArray().map(n=>n instanceof de?n.clone():n)),t}get length(){return this.doc??fe(),this._length}_callObserver(t,n){super._callObserver(t,n),Ts(this,t,new yg(this,t))}insert(t,n){this.doc!==null?W(this.doc,r=>{fc(r,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?W(this.doc,n=>{Eg(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?W(this.doc,r=>{pc(r,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return dc(this,t)}toArray(){return lc(this)}slice(t=0,n=this.length){return uc(this,t,n)}toJSON(){return this.map(t=>t instanceof de?t.toJSON():t)}map(t){return cc(this,t)}forEach(t){Xn(this,t)}[Symbol.iterator](){return bg(this)}_write(t){t.writeTypeRef(qg)}}const Cg=e=>new sn;class kg extends bs{constructor(t,n,r){super(t,n),this.keysChanged=r}}class hn extends de{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((r,s)=>{this.set(s,r)}),this._prelimContent=null}_copy(){return new hn}clone(){const t=new hn;return this.forEach((n,r)=>{t.set(r,n instanceof de?n.clone():n)}),t}_callObserver(t,n){Ts(this,t,new kg(this,t,n))}toJSON(){this.doc??fe();const t={};return this._map.forEach((n,r)=>{if(!n.deleted){const s=n.content.getContent()[n.length-1];t[r]=s instanceof de?s.toJSON():s}}),t}get size(){return[...br(this)].length}keys(){return Vs(br(this),t=>t[0])}values(){return Vs(br(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return Vs(br(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??fe(),this._map.forEach((n,r)=>{n.deleted||t(n.content.getContent()[n.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?W(this.doc,n=>{$r(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?W(this.doc,r=>{mo(r,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return go(this,t)}has(t){return gc(this,t)}clear(){this.doc!==null?W(this.doc,t=>{this.forEach(function(n,r,s){$r(t,s,r)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(zg)}}const Sg=e=>new hn,mt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&gm(e,t);class wi{constructor(t,n,r,s){this.left=t,this.right=n,this.index=r,this.currentAttributes=s}forward(){switch(this.right===null&&Je(),this.right.content.constructor){case ne:this.right.deleted||yn(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const Pa=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case ne:t.right.deleted||yn(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&kt(e,F(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},Er=(e,t,n,r)=>{const s=new Map,i=r?Es(t,n):null;if(i){const o=new wi(i.p.left,i.p,i.index,s);return Pa(e,o,n-i.index)}else{const o=new wi(null,t._start,0,s);return Pa(e,o,n)}},bc=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===ne&&mt(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const s=e.doc,i=s.clientID;r.forEach((o,a)=>{const u=n.left,c=n.right,d=new he(F(i,ue(s.store,i)),u,u&&u.lastId,c,c&&c.id,t,null,new ne(a,o));d.integrate(e,0),n.right=d,n.forward()})},yn=(e,t)=>{const{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},Ec=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===ne&&mt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Tc=(e,t,n,r)=>{const s=e.doc,i=s.clientID,o=new Map;for(const a in r){const u=r[a],c=n.currentAttributes.get(a)??null;if(!mt(c,u)){o.set(a,c);const{left:d,right:h}=n;n.right=new he(F(i,ue(s.store,i)),d,d&&d.lastId,h,h&&h.id,t,null,new ne(a,u)),n.right.integrate(e,0),n.forward()}}return o},$s=(e,t,n,r,s)=>{n.currentAttributes.forEach((f,p)=>{s[p]===void 0&&(s[p]=null)});const i=e.doc,o=i.clientID;Ec(n,s);const a=Tc(e,t,n,s),u=r.constructor===String?new Ze(r):r instanceof de?new ut(r):new Yt(r);let{left:c,right:d,index:h}=n;t._searchMarker&&Kn(t._searchMarker,n.index,u.getLength()),d=new he(F(o,ue(i.store,o)),c,c&&c.lastId,d,d&&d.id,t,null,u),d.integrate(e,0),n.right=d,n.index=h,n.forward(),bc(e,t,n,a)},Ba=(e,t,n,r,s)=>{const i=e.doc,o=i.clientID;Ec(n,s);const a=Tc(e,t,n,s);e:for(;n.right!==null&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===ne));){if(!n.right.deleted)switch(n.right.content.constructor){case ne:{const{key:u,value:c}=n.right.content,d=s[u];if(d!==void 0){if(mt(d,c))a.delete(u);else{if(r===0)break e;a.set(u,c)}n.right.delete(e)}else n.currentAttributes.set(u,c);break}default:r<n.right.length&&kt(e,F(n.right.id.client,n.right.id.clock+r)),r-=n.right.length;break}n.forward()}if(r>0){let u="";for(;r>0;r--)u+=`
10
+ `;n.right=new he(F(o,ue(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Ze(u)),n.right.integrate(e,0),n.forward()}bc(e,t,n,a)},yc=(e,t,n,r,s)=>{let i=t;const o=Be();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===ne){const c=i.content;o.set(c.key,c)}i=i.right}let a=0,u=!1;for(;t!==i;){if(n===t&&(u=!0),!t.deleted){const c=t.content;switch(c.constructor){case ne:{const{key:d,value:h}=c,f=r.get(d)??null;(o.get(d)!==c||f===h)&&(t.delete(e),a++,!u&&(s.get(d)??null)===h&&f!==h&&(f===null?s.delete(d):s.set(d,f))),!u&&!t.deleted&&yn(s,c);break}}}t=t.right}return a},Ag=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===ne){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},_g=e=>{let t=0;return W(e.doc,n=>{let r=e._start,s=e._start,i=Be();const o=Ti(i);for(;s;){if(s.deleted===!1)switch(s.content.constructor){case ne:yn(o,s.content);break;default:t+=yc(n,r,s,i,o),i=Ti(o),r=s;break}s=s.right}}),t},wg=e=>{const t=new Set,n=e.doc;for(const[r,s]of e.afterState.entries()){const i=e.beforeState.get(r)||0;s!==i&&rc(e,n.store.clients.get(r),i,s,o=>{!o.deleted&&o.content.constructor===ne&&o.constructor!==De&&t.add(o.parent)})}W(n,r=>{jl(e,e.deleteSet,s=>{if(s instanceof De||!s.parent._hasFormatting||t.has(s.parent))return;const i=s.parent;s.content.constructor===ne?t.add(i):Ag(r,s)});for(const s of t)_g(s)})},Ua=(e,t,n)=>{const r=n,s=Ti(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case ut:case Yt:case Ze:n<t.right.length&&kt(e,F(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}i&&yc(e,i,t.right,s,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&Kn(o._searchMarker,t.index,-r+n),t};class Ig extends bs{constructor(t,n,r){super(t,n),this.childListChanged=!1,this.keysChanged=new Set,r.forEach(s=>{s===null?this.childListChanged=!0:this.keysChanged.add(s)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];W(t,r=>{const s=new Map,i=new Map;let o=this.target._start,a=null;const u={};let c="",d=0,h=0;const f=()=>{if(a!==null){let p=null;switch(a){case"delete":h>0&&(p={delete:h}),h=0;break;case"insert":(typeof c=="object"||c.length>0)&&(p={insert:c},s.size>0&&(p.attributes={},s.forEach((m,E)=>{m!==null&&(p.attributes[E]=m)}))),c="";break;case"retain":d>0&&(p={retain:d},fm(u)||(p.attributes=cm({},u))),d=0;break}p&&n.push(p),a=null}};for(;o!==null;){switch(o.content.constructor){case ut:case Yt:this.adds(o)?this.deletes(o)||(f(),a="insert",c=o.content.getContent()[0],f()):this.deletes(o)?(a!=="delete"&&(f(),a="delete"),h+=1):o.deleted||(a!=="retain"&&(f(),a="retain"),d+=1);break;case Ze:this.adds(o)?this.deletes(o)||(a!=="insert"&&(f(),a="insert"),c+=o.content.str):this.deletes(o)?(a!=="delete"&&(f(),a="delete"),h+=o.length):o.deleted||(a!=="retain"&&(f(),a="retain"),d+=o.length);break;case ne:{const{key:p,value:m}=o.content;if(this.adds(o)){if(!this.deletes(o)){const E=s.get(p)??null;mt(E,m)?m!==null&&o.delete(r):(a==="retain"&&f(),mt(m,i.get(p)??null)?delete u[p]:u[p]=m)}}else if(this.deletes(o)){i.set(p,m);const E=s.get(p)??null;mt(E,m)||(a==="retain"&&f(),u[p]=E)}else if(!o.deleted){i.set(p,m);const E=u[p];E!==void 0&&(mt(E,m)?E!==null&&o.delete(r):(a==="retain"&&f(),m===null?delete u[p]:u[p]=m))}o.deleted||(a==="insert"&&f(),yn(s,o.content));break}}o=o.right}for(f();n.length>0;){const p=n[n.length-1];if(p.retain!==void 0&&p.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class fn extends de{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??fe(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new fn}clone(){const t=new fn;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const r=new Ig(this,t,n);Ts(this,t,r),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??fe();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Ze&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?W(this.doc,r=>{const s=new wi(null,this._start,0,new Map);for(let i=0;i<t.length;i++){const o=t[i];if(o.insert!==void 0){const a=!n&&typeof o.insert=="string"&&i===t.length-1&&s.right===null&&o.insert.slice(-1)===`
11
+ `?o.insert.slice(0,-1):o.insert;(typeof a!="string"||a.length>0)&&$s(r,this,s,a,o.attributes||{})}else o.retain!==void 0?Ba(r,this,s,o.retain,o.attributes||{}):o.delete!==void 0&&Ua(r,s,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,r){this.doc??fe();const s=[],i=new Map,o=this.doc;let a="",u=this._start;function c(){if(a.length>0){const h={};let f=!1;i.forEach((m,E)=>{f=!0,h[E]=m});const p={insert:a};f&&(p.attributes=h),s.push(p),a=""}}const d=()=>{for(;u!==null;){if(Kt(u,t)||n!==void 0&&Kt(u,n))switch(u.content.constructor){case Ze:{const h=i.get("ychange");t!==void 0&&!Kt(u,t)?(h===void 0||h.user!==u.id.client||h.type!=="removed")&&(c(),i.set("ychange",r?r("removed",u.id):{type:"removed"})):n!==void 0&&!Kt(u,n)?(h===void 0||h.user!==u.id.client||h.type!=="added")&&(c(),i.set("ychange",r?r("added",u.id):{type:"added"})):h!==void 0&&(c(),i.delete("ychange")),a+=u.content.str;break}case ut:case Yt:{c();const h={insert:u.content.getContent()[0]};if(i.size>0){const f={};h.attributes=f,i.forEach((p,m)=>{f[m]=p})}s.push(h);break}case ne:Kt(u,t)&&(c(),yn(i,u.content));break}u=u.right}c()};return t||n?W(o,h=>{t&&Ai(h,t),n&&Ai(h,n),d()},"cleanup"):d(),s}insert(t,n,r){if(n.length<=0)return;const s=this.doc;s!==null?W(s,i=>{const o=Er(i,this,t,!r);r||(r={},o.currentAttributes.forEach((a,u)=>{r[u]=a})),$s(i,this,o,n,r)}):this._pending.push(()=>this.insert(t,n,r))}insertEmbed(t,n,r){const s=this.doc;s!==null?W(s,i=>{const o=Er(i,this,t,!r);$s(i,this,o,n,r||{})}):this._pending.push(()=>this.insertEmbed(t,n,r||{}))}delete(t,n){if(n===0)return;const r=this.doc;r!==null?W(r,s=>{Ua(s,Er(s,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,r){if(n===0)return;const s=this.doc;s!==null?W(s,i=>{const o=Er(i,this,t,!1);o.right!==null&&Ba(i,this,o,n,r)}):this._pending.push(()=>this.format(t,n,r))}removeAttribute(t){this.doc!==null?W(this.doc,n=>{$r(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?W(this.doc,r=>{mo(r,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return go(this,t)}getAttributes(){return mc(this)}_write(t){t.writeTypeRef(Wg)}}const xg=e=>new fn;class js{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??fe()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===St||n.constructor===Pt)&&n._start!==null)t=n._start;else for(;t!==null;){const r=t.next;if(r!==null){t=r;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class Pt extends de{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Pt}clone(){const t=new Pt;return t.insert(0,this.toArray().map(n=>n instanceof de?n.clone():n)),t}get length(){return this.doc??fe(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new js(this,t)}querySelector(t){t=t.toUpperCase();const r=new js(this,s=>s.nodeName&&s.nodeName.toUpperCase()===t).next();return r.done?null:r.value}querySelectorAll(t){return t=t.toUpperCase(),Tt(new js(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){Ts(this,t,new Og(this,n,t))}toString(){return cc(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},r){const s=t.createDocumentFragment();return r!==void 0&&r._createAssociation(s,this),Xn(this,i=>{s.insertBefore(i.toDOM(t,n,r),null)}),s}insert(t,n){this.doc!==null?W(this.doc,r=>{fc(r,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)W(this.doc,r=>{const s=t&&t instanceof de?t._item:t;Yr(r,this,s,n)});else{const r=this._prelimContent,s=t===null?0:r.findIndex(i=>i===t)+1;if(s===0&&t!==null)throw Ct("Reference item not found");r.splice(s,0,...n)}}delete(t,n=1){this.doc!==null?W(this.doc,r=>{pc(r,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return lc(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return dc(this,t)}slice(t=0,n=this.length){return uc(this,t,n)}forEach(t){Xn(this,t)}_write(t){t.writeTypeRef(Kg)}}const Ng=e=>new Pt;class St extends Pt{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((r,s)=>{this.setAttribute(s,r)}),this._prelimAttrs=null}_copy(){return new St(this.nodeName)}clone(){const t=new St(this.nodeName),n=this.getAttributes();return hm(n,(r,s)=>{typeof r=="string"&&t.setAttribute(s,r)}),t.insert(0,this.toArray().map(r=>r instanceof de?r.clone():r)),t}toString(){const t=this.getAttributes(),n=[],r=[];for(const a in t)r.push(a);r.sort();const s=r.length;for(let a=0;a<s;a++){const u=r[a];n.push(u+'="'+t[u]+'"')}const i=this.nodeName.toLocaleLowerCase(),o=n.length>0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}</${i}>`}removeAttribute(t){this.doc!==null?W(this.doc,n=>{$r(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?W(this.doc,r=>{mo(r,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return go(this,t)}hasAttribute(t){return gc(this,t)}getAttributes(t){return t?Tg(this,t):mc(this)}toDOM(t=document,n={},r){const s=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const a=i[o];typeof a=="string"&&s.setAttribute(o,a)}return Xn(this,o=>{s.appendChild(o.toDOM(t,n,r))}),r!==void 0&&r._createAssociation(s,this),s}_write(t){t.writeTypeRef(Gg),t.writeKey(this.nodeName)}}const Lg=e=>new St(e.readKey());class Og extends bs{constructor(t,n,r){super(t,r),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(s=>{s===null?this.childListChanged=!0:this.attributesChanged.add(s)})}}class jr extends hn{constructor(t){super(),this.hookName=t}_copy(){return new jr(this.hookName)}clone(){const t=new jr(this.hookName);return this.forEach((n,r)=>{t.set(r,n)}),t}toDOM(t=document,n={},r){const s=n[this.hookName];let i;return s!==void 0?i=s.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(i,this),i}_write(t){t.writeTypeRef(Xg),t.writeKey(this.hookName)}}const Dg=e=>new jr(e.readKey());class qr extends fn{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new qr}clone(){const t=new qr;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,r){const s=t.createTextNode(this.toString());return r!==void 0&&r._createAssociation(s,this),s}toString(){return this.toDelta().map(t=>{const n=[];for(const s in t.attributes){const i=[];for(const o in t.attributes[s])i.push({key:o,value:t.attributes[s][o]});i.sort((o,a)=>o.key<a.key?-1:1),n.push({nodeName:s,attrs:i})}n.sort((s,i)=>s.nodeName<i.nodeName?-1:1);let r="";for(let s=0;s<n.length;s++){const i=n[s];r+=`<${i.nodeName}`;for(let o=0;o<i.attrs.length;o++){const a=i.attrs[o];r+=` ${a.key}="${a.value}"`}r+=">"}r+=t.insert;for(let s=n.length-1;s>=0;s--)r+=`</${n[s].nodeName}>`;return r}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Qg)}}const vg=e=>new qr;class bo{constructor(t,n){this.id=t,this.length=n}get deleted(){throw Xe()}mergeWith(t){return!1}write(t,n,r){throw Xe()}integrate(t,n){throw Xe()}}const Mg=0;class De extends bo{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),nc(t.doc.store,this)}write(t,n){t.writeInfo(Mg),t.writeLen(this.length-n)}getMissing(t,n){return null}}class ir{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new ir(this.content)}splice(t){throw Xe()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const Rg=e=>new ir(e.readBuf());class Qn{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Qn(this.len)}splice(t){const n=new Qn(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){Fr(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const Pg=e=>new Qn(e.readLen()),Cc=(e,t)=>new Tn({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class or{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new or(Cc(this.doc.guid,this.opts))}splice(t){throw Xe()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const Bg=e=>new or(Cc(e.readString(),e.readAny()));class Yt{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Yt(this.embed)}splice(t){throw Xe()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const Ug=e=>new Yt(e.readJSON());class ne{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new ne(this.key,this.value)}splice(t){throw Xe()}mergeWith(t){return!1}integrate(t,n){const r=n.parent;r._searchMarker=null,r._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const Hg=e=>new ne(e.readKey(),e.readJSON());class zr{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new zr(this.arr)}splice(t){const n=new zr(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const r=this.arr.length;t.writeLen(r-n);for(let s=n;s<r;s++){const i=this.arr[s];t.writeString(i===void 0?"undefined":JSON.stringify(i))}}getRef(){return 2}}const Fg=e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++){const s=e.readString();s==="undefined"?n.push(void 0):n.push(JSON.parse(s))}return new zr(n)},Vg=Hr("node_env")==="development";class Bt{constructor(t){this.arr=t,Vg&&Pl(t)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Bt(this.arr)}splice(t){const n=new Bt(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const r=this.arr.length;t.writeLen(r-n);for(let s=n;s<r;s++){const i=this.arr[s];t.writeAny(i)}}getRef(){return 8}}const Yg=e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Bt(n)};class Ze{constructor(t){this.str=t}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Ze(this.str)}splice(t){const n=new Ze(this.str.slice(t));this.str=this.str.slice(0,t);const r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const $g=e=>new Ze(e.readString()),jg=[Cg,Sg,xg,Lg,Ng,Dg,vg],qg=0,zg=1,Wg=2,Gg=3,Kg=4,Xg=5,Qg=6;class ut{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new ut(this.type._copy())}splice(t){throw Xe()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(t.beforeState.get(r.id.client)||0)&&t._mergeStructs.push(r):r.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(t,!0),r=r.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const Jg=e=>new ut(jg[e.readTypeRef()](e)),Wr=(e,t,n)=>{const{client:r,clock:s}=t.id,i=new he(F(r,s+n),t,F(r,s+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=F(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i};let he=class Ii extends bo{constructor(t,n,r,s,i,o,a,u){super(t,u.getLength()),this.origin=r,this.left=n,this.right=s,this.rightOrigin=i,this.parent=o,this.parentSub=a,this.redone=null,this.content=u,this.info=this.content.isCountable()?ga:0}set marker(t){(this.info&Us)>0!==t&&(this.info^=Us)}get marker(){return(this.info&Us)>0}get keep(){return(this.info&ma)>0}set keep(t){this.keep!==t&&(this.info^=ma)}get countable(){return(this.info&ga)>0}get deleted(){return(this.info&Bs)>0}set deleted(t){this.deleted!==t&&(this.info^=Bs)}markDeleted(){this.info|=Bs}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=ue(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=ue(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===rn&&this.id.client!==this.parent.client&&this.parent.clock>=ue(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Da(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=kt(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===De||this.right&&this.right.constructor===De)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Ii?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Ii&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===rn){const r=Ys(n,this.parent);r.constructor===De?this.parent=null:this.parent=r.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=Da(t,t.doc.store,F(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,s;if(r!==null)s=r.right;else if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start;const i=new Set,o=new Set;for(;s!==null&&s!==this.right;){if(o.add(s),i.add(s),gr(this.origin,s.origin)){if(s.id.client<this.id.client)r=s,i.clear();else if(gr(this.rightOrigin,s.rightOrigin))break}else if(s.origin!==null&&o.has(Ys(t.doc.store,s.origin)))i.has(Ys(t.doc.store,s.origin))||(r=s,i.clear());else break;s=s.right}this.left=r}if(this.left!==null){const r=this.left.right;this.right=r,this.left.right=this}else{let r;if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start,this.parent._start=this;this.right=r}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(t)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),nc(t.doc.store,this),this.content.integrate(t,this),Ma(t,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(t)}else new De(this.id,this.length).integrate(t,0)}get next(){let t=this.right;for(;t!==null&&t.deleted;)t=t.right;return t}get prev(){let t=this.left;for(;t!==null&&t.deleted;)t=t.left;return t}get lastId(){return this.length===1?this.id:F(this.id.client,this.id.clock+this.length-1)}mergeWith(t){if(this.constructor===t.constructor&&gr(t.origin,this.lastId)&&this.right===t&&gr(this.rightOrigin,t.rightOrigin)&&this.id.client===t.id.client&&this.id.clock+this.length===t.id.clock&&this.deleted===t.deleted&&this.redone===null&&t.redone===null&&this.content.constructor===t.content.constructor&&this.content.mergeWith(t.content)){const n=this.parent._searchMarker;return n&&n.forEach(r=>{r.p===t&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),Fr(t.deleteSet,this.id.client,this.id.clock,this.length),Ma(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw Je();this.content.gc(t),n?rg(t,this,new De(this.id,this.length)):this.content=new Qn(this.length)}write(t,n){const r=n>0?F(this.id.client,this.id.clock+n-1):this.origin,s=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&hs|(r===null?0:xe)|(s===null?0:ot)|(i===null?0:jn);if(t.writeInfo(o),r!==null&&t.writeLeftID(r),s!==null&&t.writeRightID(s),r===null&&s===null){const a=this.parent;if(a._item!==void 0){const u=a._item;if(u===null){const c=tg(a);t.writeParentInfo(!0),t.writeString(c)}else t.writeParentInfo(!1),t.writeLeftID(u.id)}else a.constructor===String?(t.writeParentInfo(!0),t.writeString(a)):a.constructor===rn?(t.writeParentInfo(!1),t.writeLeftID(a)):Je();i!==null&&t.writeString(i)}this.content.write(t,n)}};const kc=(e,t)=>Zg[t&hs](e),Zg=[()=>{Je()},Pg,Fg,Rg,$g,Ug,Hg,Jg,Yg,Bg,()=>{Je()}],e1=10;class ve extends bo{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){Je()}write(t,n){t.writeInfo(e1),H(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const Sc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Ac="__ $YJS$ __";Sc[Ac]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Sc[Ac]=!0;function t1(e={}){return new D.Plugin({view(t){return new n1(t,e)}})}class n1{constructor(t,n){var r;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(s=>{let i=o=>{this[s](o)};return t.dom.addEventListener(s,i),{name:s,handler:i}})}destroy(){this.handlers.forEach(({name:t,handler:n})=>this.editorView.dom.removeEventListener(t,n))}update(t,n){this.cursorPos!=null&&n.doc!=t.state.doc&&(this.cursorPos>t.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),n=!t.parent.inlineContent,r,s=this.editorView.dom,i=s.getBoundingClientRect(),o=i.width/s.offsetWidth,a=i.height/s.offsetHeight;if(n){let h=t.nodeBefore,f=t.nodeAfter;if(h||f){let p=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(p){let m=p.getBoundingClientRect(),E=h?m.bottom:m.top;h&&f&&(E=(E+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let C=this.width/2*a;r={left:m.left,right:m.right,top:E-C,bottom:E+C}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),f=this.width/2*o;r={left:h.left-f,right:h.left+f,top:h.top,bottom:h.bottom}}let u=this.editorView.dom.offsetParent;this.element||(this.element=u.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let c,d;if(!u||u==document.body&&getComputedStyle(u).position=="static")c=-pageXOffset,d=-pageYOffset;else{let h=u.getBoundingClientRect(),f=h.width/u.offsetWidth,p=h.height/u.offsetHeight;c=h.left-u.scrollLeft*f,d=h.top-u.scrollTop*p}this.element.style.left=(r.left-c)/o+"px",this.element.style.top=(r.top-d)/a+"px",this.element.style.width=(r.right-r.left)/o+"px",this.element.style.height=(r.bottom-r.top)/a+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}dragover(t){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),s=r&&r.type.spec.disableDropCursor,i=typeof s=="function"?s(this.editorView,n,t):s;if(n&&!i){let o=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let a=oe.dropPoint(this.editorView.state.doc,o,this.editorView.dragging.slice);a!=null&&(o=a)}this.setCursor(o),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(t){this.editorView.dom.contains(t.relatedTarget)||this.setCursor(null)}}var Gr=200,le=function(){};le.prototype.append=function(t){return t.length?(t=le.from(t),!this.length&&t||t.length<Gr&&this.leafAppend(t)||this.length<Gr&&t.leafPrepend(this)||this.appendInner(t)):this};le.prototype.prepend=function(t){return t.length?le.from(t).append(this):this};le.prototype.appendInner=function(t){return new r1(this,t)};le.prototype.slice=function(t,n){return t===void 0&&(t=0),n===void 0&&(n=this.length),t>=n?le.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};le.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};le.prototype.forEach=function(t,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(t,n,r,0):this.forEachInvertedInner(t,n,r,0)};le.prototype.map=function(t,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var s=[];return this.forEach(function(i,o){return s.push(t(i,o))},n,r),s};le.from=function(t){return t instanceof le?t:t&&t.length?new _c(t):le.empty};var _c=function(e){function t(r){e.call(this),this.values=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={length:{configurable:!0},depth:{configurable:!0}};return t.prototype.flatten=function(){return this.values},t.prototype.sliceInner=function(s,i){return s==0&&i==this.length?this:new t(this.values.slice(s,i))},t.prototype.getInner=function(s){return this.values[s]},t.prototype.forEachInner=function(s,i,o,a){for(var u=i;u<o;u++)if(s(this.values[u],a+u)===!1)return!1},t.prototype.forEachInvertedInner=function(s,i,o,a){for(var u=i-1;u>=o;u--)if(s(this.values[u],a+u)===!1)return!1},t.prototype.leafAppend=function(s){if(this.length+s.length<=Gr)return new t(this.values.concat(s.flatten()))},t.prototype.leafPrepend=function(s){if(this.length+s.length<=Gr)return new t(s.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(t.prototype,n),t}(le);le.empty=new _c([]);var r1=function(e){function t(n,r){e.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},t.prototype.getInner=function(r){return r<this.left.length?this.left.get(r):this.right.get(r-this.left.length)},t.prototype.forEachInner=function(r,s,i,o){var a=this.left.length;if(s<a&&this.left.forEachInner(r,s,Math.min(i,a),o)===!1||i>a&&this.right.forEachInner(r,Math.max(s-a,0),Math.min(this.length,i)-a,o+a)===!1)return!1},t.prototype.forEachInvertedInner=function(r,s,i,o){var a=this.left.length;if(s>a&&this.right.forEachInvertedInner(r,s-a,Math.max(i,a)-a,o+a)===!1||i<a&&this.left.forEachInvertedInner(r,Math.min(s,a),i,o)===!1)return!1},t.prototype.sliceInner=function(r,s){if(r==0&&s==this.length)return this;var i=this.left.length;return s<=i?this.left.slice(r,s):r>=i?this.right.slice(r-i,s-i):this.left.slice(r,i).append(this.right.slice(0,s-i))},t.prototype.leafAppend=function(r){var s=this.right.leafAppend(r);if(s)return new t(this.left,s)},t.prototype.leafPrepend=function(r){var s=this.left.leafPrepend(r);if(s)return new t(s,this.right)},t.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new t(this.left,new t(this.right,r)):new t(this,r)},t}(le);const s1=500;class Pe{constructor(t,n){this.items=t,this.eventCount=n}popEvent(t,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let s,i;n&&(s=this.remapping(r,this.items.length),i=s.maps.length);let o=t.tr,a,u,c=[],d=[];return this.items.forEach((h,f)=>{if(!h.step){s||(s=this.remapping(r,f+1),i=s.maps.length),i--,d.push(h);return}if(s){d.push(new ze(h.map));let p=h.step.map(s.slice(i)),m;p&&o.maybeStep(p).doc&&(m=o.mapping.maps[o.mapping.maps.length-1],c.push(new ze(m,void 0,void 0,c.length+d.length))),i--,m&&s.appendMap(m,i)}else o.maybeStep(h.step);if(h.selection)return a=s?h.selection.map(s.slice(i)):h.selection,u=new Pe(this.items.slice(0,r).append(d.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:u,transform:o,selection:a}}addTransform(t,n,r,s){let i=[],o=this.eventCount,a=this.items,u=!s&&a.length?a.get(a.length-1):null;for(let d=0;d<t.steps.length;d++){let h=t.steps[d].invert(t.docs[d]),f=new ze(t.mapping.maps[d],h,n),p;(p=u&&u.merge(f))&&(f=p,d?i.pop():a=a.slice(0,a.length-1)),i.push(f),n&&(o++,n=void 0),s||(u=f)}let c=o-r.depth;return c>o1&&(a=i1(a,c),o-=c),new Pe(a.append(i),o)}remapping(t,n){let r=new oe.Mapping;return this.items.forEach((s,i)=>{let o=s.mirrorOffset!=null&&i-s.mirrorOffset>=t?r.maps.length-s.mirrorOffset:void 0;r.appendMap(s.map,o)},t,n),r}addMaps(t){return this.eventCount==0?this:new Pe(this.items.append(t.map(n=>new ze(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],s=Math.max(0,this.items.length-n),i=t.mapping,o=t.steps.length,a=this.eventCount;this.items.forEach(f=>{f.selection&&a--},s);let u=n;this.items.forEach(f=>{let p=i.getMirror(--u);if(p==null)return;o=Math.min(o,p);let m=i.maps[p];if(f.step){let E=t.steps[p].invert(t.docs[p]),C=f.selection&&f.selection.map(i.slice(u+1,p));C&&a++,r.push(new ze(m,E,C))}else r.push(new ze(m))},s);let c=[];for(let f=n;f<o;f++)c.push(new ze(i.maps[f]));let d=this.items.slice(0,s).append(c).append(r),h=new Pe(d,a);return h.emptyItemCount()>s1&&(h=h.compress(this.items.length-r.length)),h}emptyItemCount(){let t=0;return this.items.forEach(n=>{n.step||t++}),t}compress(t=this.items.length){let n=this.remapping(0,t),r=n.maps.length,s=[],i=0;return this.items.forEach((o,a)=>{if(a>=t)s.push(o),o.selection&&i++;else if(o.step){let u=o.step.map(n.slice(r)),c=u&&u.getMap();if(r--,c&&n.appendMap(c,r),u){let d=o.selection&&o.selection.map(n.slice(r));d&&i++;let h=new ze(c.invert(),u,d),f,p=s.length-1;(f=s.length&&s[p].merge(h))?s[p]=f:s.push(h)}}else o.map&&r--},this.items.length,0),new Pe(le.from(s.reverse()),i)}}Pe.empty=new Pe(le.empty,0);function i1(e,t){let n;return e.forEach((r,s)=>{if(r.selection&&t--==0)return n=s,!1}),e.slice(n)}class ze{constructor(t,n,r,s){this.map=t,this.step=n,this.selection=r,this.mirrorOffset=s}merge(t){if(this.step&&t.step&&!t.selection){let n=t.step.merge(this.step);if(n)return new ze(n.getMap().invert(),n,this.selection)}}}class ht{constructor(t,n,r,s,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=s,this.prevComposition=i}}const o1=20;function a1(e,t,n,r){let s=n.getMeta(Ot),i;if(s)return s.historyState;n.getMeta(c1)&&(e=new ht(e.done,e.undone,null,0,-1));let o=n.getMeta("appendedTransaction");if(n.steps.length==0)return e;if(o&&o.getMeta(Ot))return o.getMeta(Ot).redo?new ht(e.done.addTransform(n,void 0,r,Lr(t)),e.undone,Ha(n.mapping.maps),e.prevTime,e.prevComposition):new ht(e.done,e.undone.addTransform(n,void 0,r,Lr(t)),null,e.prevTime,e.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let a=n.getMeta("composition"),u=e.prevTime==0||!o&&e.prevComposition!=a&&(e.prevTime<(n.time||0)-r.newGroupDelay||!u1(n,e.prevRanges)),c=o?qs(e.prevRanges,n.mapping):Ha(n.mapping.maps);return new ht(e.done.addTransform(n,u?t.selection.getBookmark():void 0,r,Lr(t)),Pe.empty,c,n.time,a??e.prevComposition)}else return(i=n.getMeta("rebased"))?new ht(e.done.rebased(n,i),e.undone.rebased(n,i),qs(e.prevRanges,n.mapping),e.prevTime,e.prevComposition):new ht(e.done.addMaps(n.mapping.maps),e.undone.addMaps(n.mapping.maps),qs(e.prevRanges,n.mapping),e.prevTime,e.prevComposition)}function u1(e,t){if(!t)return!1;if(!e.docChanged)return!0;let n=!1;return e.mapping.maps[0].forEach((r,s)=>{for(let i=0;i<t.length;i+=2)r<=t[i+1]&&s>=t[i]&&(n=!0)}),n}function Ha(e){let t=[];for(let n=e.length-1;n>=0&&t.length==0;n--)e[n].forEach((r,s,i,o)=>t.push(i,o));return t}function qs(e,t){if(!e)return null;let n=[];for(let r=0;r<e.length;r+=2){let s=t.map(e[r],1),i=t.map(e[r+1],-1);s<=i&&n.push(s,i)}return n}function l1(e,t,n){let r=Lr(t),s=Ot.get(t).spec.config,i=(n?e.undone:e.done).popEvent(t,r);if(!i)return null;let o=i.selection.resolve(i.transform.doc),a=(n?e.done:e.undone).addTransform(i.transform,t.selection.getBookmark(),s,r),u=new ht(n?a:i.remaining,n?i.remaining:a,null,0,-1);return i.transform.setSelection(o).setMeta(Ot,{redo:n,historyState:u})}let zs=!1,Fa=null;function Lr(e){let t=e.plugins;if(Fa!=t){zs=!1,Fa=t;for(let n=0;n<t.length;n++)if(t[n].spec.historyPreserveItems){zs=!0;break}}return zs}const Ot=new D.PluginKey("history"),c1=new D.PluginKey("closeHistory");function d1(e={}){return e={depth:e.depth||100,newGroupDelay:e.newGroupDelay||500},new D.Plugin({key:Ot,state:{init(){return new ht(Pe.empty,Pe.empty,null,0,-1)},apply(t,n,r){return a1(n,r,t,e)}},config:e,props:{handleDOMEvents:{beforeinput(t,n){let r=n.inputType,s=r=="historyUndo"?Ic:r=="historyRedo"?xc:null;return s?(n.preventDefault(),s(t.state,t.dispatch)):!1}}}})}function wc(e,t){return(n,r)=>{let s=Ot.getState(n);if(!s||(e?s.undone:s.done).eventCount==0)return!1;if(r){let i=l1(s,n,e);i&&r(t?i.scrollIntoView():i)}return!0}}const Ic=wc(!1,!0),xc=wc(!0,!0);class ar{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}ar.prototype.normal={};ar.prototype.property={};ar.prototype.space=void 0;function Nc(e,t){const n={},r={};for(const s of e)Object.assign(n,s.property),Object.assign(r,s.normal);return new ar(n,r,t)}function Jn(e){return e.toLowerCase()}class Se{constructor(t,n){this.attribute=n,this.property=t}}Se.prototype.attribute="";Se.prototype.booleanish=!1;Se.prototype.boolean=!1;Se.prototype.commaOrSpaceSeparated=!1;Se.prototype.commaSeparated=!1;Se.prototype.defined=!1;Se.prototype.mustUseProperty=!1;Se.prototype.number=!1;Se.prototype.overloadedBoolean=!1;Se.prototype.property="";Se.prototype.spaceSeparated=!1;Se.prototype.space=void 0;let h1=0;const M=$t(),Z=$t(),xi=$t(),x=$t(),z=$t(),on=$t(),Ae=$t();function $t(){return 2**++h1}const Ni=Object.freeze(Object.defineProperty({__proto__:null,boolean:M,booleanish:Z,commaOrSpaceSeparated:Ae,commaSeparated:on,number:x,overloadedBoolean:xi,spaceSeparated:z},Symbol.toStringTag,{value:"Module"})),Ws=Object.keys(Ni);class Eo extends Se{constructor(t,n,r,s){let i=-1;if(super(t,n),Va(this,"space",s),typeof r=="number")for(;++i<Ws.length;){const o=Ws[i];Va(this,Ws[i],(r&Ni[o])===Ni[o])}}}Eo.prototype.defined=!0;function Va(e,t,n){n&&(e[t]=n)}function Cn(e){const t={},n={};for(const[r,s]of Object.entries(e.properties)){const i=new Eo(r,e.transform(e.attributes||{},r),s,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(i.mustUseProperty=!0),t[r]=i,n[Jn(r)]=r,n[Jn(i.attribute)]=r}return new ar(t,n,e.space)}const Lc=Cn({properties:{ariaActiveDescendant:null,ariaAtomic:Z,ariaAutoComplete:null,ariaBusy:Z,ariaChecked:Z,ariaColCount:x,ariaColIndex:x,ariaColSpan:x,ariaControls:z,ariaCurrent:null,ariaDescribedBy:z,ariaDetails:null,ariaDisabled:Z,ariaDropEffect:z,ariaErrorMessage:null,ariaExpanded:Z,ariaFlowTo:z,ariaGrabbed:Z,ariaHasPopup:null,ariaHidden:Z,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:z,ariaLevel:x,ariaLive:null,ariaModal:Z,ariaMultiLine:Z,ariaMultiSelectable:Z,ariaOrientation:null,ariaOwns:z,ariaPlaceholder:null,ariaPosInSet:x,ariaPressed:Z,ariaReadOnly:Z,ariaRelevant:null,ariaRequired:Z,ariaRoleDescription:z,ariaRowCount:x,ariaRowIndex:x,ariaRowSpan:x,ariaSelected:Z,ariaSetSize:x,ariaSort:null,ariaValueMax:x,ariaValueMin:x,ariaValueNow:x,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function Oc(e,t){return t in e?e[t]:t}function Dc(e,t){return Oc(e,t.toLowerCase())}const f1=Cn({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:on,acceptCharset:z,accessKey:z,action:null,allow:null,allowFullScreen:M,allowPaymentRequest:M,allowUserMedia:M,alt:null,as:null,async:M,autoCapitalize:null,autoComplete:z,autoFocus:M,autoPlay:M,blocking:z,capture:null,charSet:null,checked:M,cite:null,className:z,cols:x,colSpan:null,content:null,contentEditable:Z,controls:M,controlsList:z,coords:x|on,crossOrigin:null,data:null,dateTime:null,decoding:null,default:M,defer:M,dir:null,dirName:null,disabled:M,download:xi,draggable:Z,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:M,formTarget:null,headers:z,height:x,hidden:xi,high:x,href:null,hrefLang:null,htmlFor:z,httpEquiv:z,id:null,imageSizes:null,imageSrcSet:null,inert:M,inputMode:null,integrity:null,is:null,isMap:M,itemId:null,itemProp:z,itemRef:z,itemScope:M,itemType:z,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:M,low:x,manifest:null,max:null,maxLength:x,media:null,method:null,min:null,minLength:x,multiple:M,muted:M,name:null,nonce:null,noModule:M,noValidate:M,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:M,optimum:x,pattern:null,ping:z,placeholder:null,playsInline:M,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:M,referrerPolicy:null,rel:z,required:M,reversed:M,rows:x,rowSpan:x,sandbox:z,scope:null,scoped:M,seamless:M,selected:M,shadowRootClonable:M,shadowRootDelegatesFocus:M,shadowRootMode:null,shape:null,size:x,sizes:null,slot:null,span:x,spellCheck:Z,src:null,srcDoc:null,srcLang:null,srcSet:null,start:x,step:null,style:null,tabIndex:x,target:null,title:null,translate:null,type:null,typeMustMatch:M,useMap:null,value:Z,width:x,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:z,axis:null,background:null,bgColor:null,border:x,borderColor:null,bottomMargin:x,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:M,declare:M,event:null,face:null,frame:null,frameBorder:null,hSpace:x,leftMargin:x,link:null,longDesc:null,lowSrc:null,marginHeight:x,marginWidth:x,noResize:M,noHref:M,noShade:M,noWrap:M,object:null,profile:null,prompt:null,rev:null,rightMargin:x,rules:null,scheme:null,scrolling:Z,standby:null,summary:null,text:null,topMargin:x,valueType:null,version:null,vAlign:null,vLink:null,vSpace:x,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:M,disableRemotePlayback:M,prefix:null,property:null,results:x,security:null,unselectable:null},space:"html",transform:Dc}),p1=Cn({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ae,accentHeight:x,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:x,amplitude:x,arabicForm:null,ascent:x,attributeName:null,attributeType:null,azimuth:x,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:x,by:null,calcMode:null,capHeight:x,className:z,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:x,diffuseConstant:x,direction:null,display:null,dur:null,divisor:x,dominantBaseline:null,download:M,dx:null,dy:null,edgeMode:null,editable:null,elevation:x,enableBackground:null,end:null,event:null,exponent:x,externalResourcesRequired:null,fill:null,fillOpacity:x,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:on,g2:on,glyphName:on,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:x,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:x,horizOriginX:x,horizOriginY:x,id:null,ideographic:x,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:x,k:x,k1:x,k2:x,k3:x,k4:x,kernelMatrix:Ae,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:x,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:x,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:x,overlineThickness:x,paintOrder:null,panose1:null,path:null,pathLength:x,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:z,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:x,pointsAtY:x,pointsAtZ:x,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ae,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ae,rev:Ae,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ae,requiredFeatures:Ae,requiredFonts:Ae,requiredFormats:Ae,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:x,specularExponent:x,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:x,strikethroughThickness:x,string:null,stroke:null,strokeDashArray:Ae,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:x,strokeOpacity:x,strokeWidth:null,style:null,surfaceScale:x,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ae,tabIndex:x,tableValues:null,target:null,targetX:x,targetY:x,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ae,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:x,underlineThickness:x,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:x,values:null,vAlphabetic:x,vMathematical:x,vectorEffect:null,vHanging:x,vIdeographic:x,version:null,vertAdvY:x,vertOriginX:x,vertOriginY:x,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:x,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Oc}),vc=Cn({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),Mc=Cn({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Dc}),Rc=Cn({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),m1=/[A-Z]/g,Ya=/-[a-z]/g,g1=/^data[-\w.:]+$/i;function Pc(e,t){const n=Jn(t);let r=t,s=Se;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&g1.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Ya,E1);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Ya.test(i)){let o=i.replace(m1,b1);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}s=Eo}return new s(r,t)}function b1(e){return"-"+e.toLowerCase()}function E1(e){return e.charAt(1).toUpperCase()}const To=Nc([Lc,f1,vc,Mc,Rc],"html"),yo=Nc([Lc,p1,vc,Mc,Rc],"svg");function $a(e){const t=[],n=String(e||"");let r=n.indexOf(","),s=0,i=!1;for(;!i;){r===-1&&(r=n.length,i=!0);const o=n.slice(s,r).trim();(o||!i)&&t.push(o),s=r+1,r=n.indexOf(",",s)}return t}const ja=/[#.]/g;function T1(e,t){const n=e||"",r={};let s=0,i,o;for(;s<n.length;){ja.lastIndex=s;const a=ja.exec(n),u=n.slice(s,a?a.index:n.length);u&&(i?i==="#"?r.id=u:Array.isArray(r.className)?r.className.push(u):r.className=[u]:o=u,s+=u.length),a&&(i=a[0],s++)}return{type:"element",tagName:o||t||"div",properties:r,children:[]}}function qa(e){const t=String(e||"").trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function Bc(e,t,n){const r=n?S1(n):void 0;function s(i,o,...a){let u;if(i==null){u={type:"root",children:[]};const c=o;a.unshift(c)}else{u=T1(i,t);const c=u.tagName.toLowerCase(),d=r?r.get(c):void 0;if(u.tagName=d||c,y1(o))a.unshift(o);else for(const[h,f]of Object.entries(o))C1(e,u.properties,h,f)}for(const c of a)Li(u.children,c);return u.type==="element"&&u.tagName==="template"&&(u.content={type:"root",children:u.children},u.children=[]),u}return s}function y1(e){if(e===null||typeof e!="object"||Array.isArray(e))return!0;if(typeof e.type!="string")return!1;const t=e,n=Object.keys(e);for(const r of n){const s=t[r];if(s&&typeof s=="object"){if(!Array.isArray(s))return!0;const i=s;for(const o of i)if(typeof o!="number"&&typeof o!="string")return!0}}return!!("children"in e&&Array.isArray(e.children))}function C1(e,t,n,r){const s=Pc(e,n);let i;if(r!=null){if(typeof r=="number"){if(Number.isNaN(r))return;i=r}else typeof r=="boolean"?i=r:typeof r=="string"?s.spaceSeparated?i=qa(r):s.commaSeparated?i=$a(r):s.commaOrSpaceSeparated?i=qa($a(r).join(" ")):i=za(s,s.property,r):Array.isArray(r)?i=[...r]:i=s.property==="style"?k1(r):String(r);if(Array.isArray(i)){const o=[];for(const a of i)o.push(za(s,s.property,a));i=o}s.property==="className"&&Array.isArray(t.className)&&(i=t.className.concat(i)),t[s.property]=i}}function Li(e,t){if(t!=null)if(typeof t=="number"||typeof t=="string")e.push({type:"text",value:String(t)});else if(Array.isArray(t))for(const n of t)Li(e,n);else if(typeof t=="object"&&"type"in t)t.type==="root"?Li(e,t.children):e.push(t);else throw new Error("Expected node, nodes, or string, got `"+t+"`")}function za(e,t,n){if(typeof n=="string"){if(e.number&&n&&!Number.isNaN(Number(n)))return Number(n);if((e.boolean||e.overloadedBoolean)&&(n===""||Jn(n)===Jn(t)))return!0}return n}function k1(e){const t=[];for(const[n,r]of Object.entries(e))t.push([n,r].join(": "));return t.join("; ")}function S1(e){const t=new Map;for(const n of e)t.set(n.toLowerCase(),n);return t}const A1=["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","solidColor","textArea","textPath"],Uc=Bc(To,"div"),Hc=Bc(yo,"g",A1);function _1(e){const t=String(e),n=[];return{toOffset:s,toPoint:r};function r(i){if(typeof i=="number"&&i>-1&&i<=t.length){let o=0;for(;;){let a=n[o];if(a===void 0){const u=Wa(t,n[o-1]);a=u===-1?t.length+1:u+1,n[o]=a}if(a>i)return{line:o+1,column:i-(o>0?n[o-1]:0)+1,offset:i};o++}}}function s(i){if(i&&typeof i.line=="number"&&typeof i.column=="number"&&!Number.isNaN(i.line)&&!Number.isNaN(i.column)){for(;n.length<i.line;){const a=n[n.length-1],u=Wa(t,a),c=u===-1?t.length+1:u+1;if(a===c)break;n.push(c)}const o=(i.line>1?n[i.line-2]:0)+i.column-1;if(o<n[i.line-1])return o}}}function Wa(e,t){const n=e.indexOf("\r",t),r=e.indexOf(`
12
+ `,t);return r===-1?n:n===-1||n+1===r?r:n<r?n:r}const Or={html:"http://www.w3.org/1999/xhtml",svg:"http://www.w3.org/2000/svg"},Fc={}.hasOwnProperty,w1=Object.prototype;function I1(e,t){const n=t||{};return Co({file:n.file||void 0,location:!1,schema:n.space==="svg"?yo:To,verbose:n.verbose||!1},e)}function Co(e,t){let n;switch(t.nodeName){case"#comment":{const r=t;return n={type:"comment",value:r.data},Dr(e,r,n),n}case"#document":case"#document-fragment":{const r=t,s="mode"in r?r.mode==="quirks"||r.mode==="limited-quirks":!1;if(n={type:"root",children:Vc(e,t.childNodes),data:{quirksMode:s}},e.file&&e.location){const i=String(e.file),o=_1(i),a=o.toPoint(0),u=o.toPoint(i.length);n.position={start:a,end:u}}return n}case"#documentType":{const r=t;return n={type:"doctype"},Dr(e,r,n),n}case"#text":{const r=t;return n={type:"text",value:r.value},Dr(e,r,n),n}default:return n=x1(e,t),n}}function Vc(e,t){let n=-1;const r=[];for(;++n<t.length;){const s=Co(e,t[n]);r.push(s)}return r}function x1(e,t){const n=e.schema;e.schema=t.namespaceURI===Or.svg?yo:To;let r=-1;const s={};for(;++r<t.attrs.length;){const a=t.attrs[r],u=(a.prefix?a.prefix+":":"")+a.name;Fc.call(w1,u)||(s[u]=a.value)}const o=(e.schema.space==="svg"?Hc:Uc)(t.tagName,s,Vc(e,t.childNodes));if(Dr(e,t,o),o.tagName==="template"){const a=t,u=a.sourceCodeLocation,c=u&&u.startTag&&Qt(u.startTag),d=u&&u.endTag&&Qt(u.endTag),h=Co(e,a.content);c&&d&&e.file&&(h.position={start:c.end,end:d.start}),o.content=h}return e.schema=n,o}function Dr(e,t,n){if("sourceCodeLocation"in t&&t.sourceCodeLocation&&e.file){const r=N1(e,n,t.sourceCodeLocation);r&&(e.location=!0,n.position=r)}}function N1(e,t,n){const r=Qt(n);if(t.type==="element"){const s=t.children[t.children.length-1];if(r&&!n.endTag&&s&&s.position&&s.position.end&&(r.end=Object.assign({},s.position.end)),e.verbose){const i={};let o;if(n.attrs)for(o in n.attrs)Fc.call(n.attrs,o)&&(i[Pc(e.schema,o).property]=Qt(n.attrs[o]));n.startTag;const a=Qt(n.startTag),u=n.endTag?Qt(n.endTag):void 0,c={opening:a};u&&(c.closing=u),c.properties=i,t.data={position:c}}}return r}function Qt(e){const t=Ga({line:e.startLine,column:e.startCol,offset:e.startOffset}),n=Ga({line:e.endLine,column:e.endCol,offset:e.endOffset});return t||n?{start:t,end:n}:void 0}function Ga(e){return e.line&&e.column?e:void 0}const L1=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),K="�";var g;(function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z"})(g||(g={}));const be={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function Yc(e){return e>=55296&&e<=57343}function O1(e){return e>=56320&&e<=57343}function D1(e,t){return(e-55296)*1024+9216+t}function $c(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function jc(e){return e>=64976&&e<=65007||L1.has(e)}var S;(function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text"})(S||(S={}));const v1=65536;class M1{constructor(t){this.handler=t,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=v1,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(t,n){const{line:r,col:s,offset:i}=this,o=s+n,a=i+n;return{code:t,startLine:r,endLine:r,startCol:o,endCol:o,startOffset:a,endOffset:a}}_err(t){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(t,0)))}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos}_processSurrogate(t){if(this.pos!==this.html.length-1){const n=this.html.charCodeAt(this.pos+1);if(O1(n))return this.pos++,this._addGap(),D1(t,n)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,g.EOF;return this._err(S.surrogateInInputStream),t}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0)}write(t,n){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=!1,this.lastChunkWritten=n}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(t,n){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(n)return this.html.startsWith(t,this.pos);for(let r=0;r<t.length;r++)if((this.html.charCodeAt(this.pos+r)|32)!==t.charCodeAt(r))return!1;return!0}peek(t){const n=this.pos+t;if(n>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,g.EOF;const r=this.html.charCodeAt(n);return r===g.CARRIAGE_RETURN?g.LINE_FEED:r}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,g.EOF;let t=this.html.charCodeAt(this.pos);return t===g.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,g.LINE_FEED):t===g.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,Yc(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===g.LINE_FEED||t===g.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){$c(t)?this._err(S.controlCharacterInInputStream):jc(t)&&this._err(S.noncharacterInInputStream)}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}}var V;(function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION"})(V||(V={}));function qc(e,t){for(let n=e.attrs.length-1;n>=0;n--)if(e.attrs[n].name===t)return e.attrs[n].value;return null}const R1=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),P1=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);function B1(e){var t;return e>=55296&&e<=57343||e>1114111?65533:(t=P1.get(e))!==null&&t!==void 0?t:e}var ae;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"})(ae||(ae={}));const U1=32;var gt;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})(gt||(gt={}));function Oi(e){return e>=ae.ZERO&&e<=ae.NINE}function H1(e){return e>=ae.UPPER_A&&e<=ae.UPPER_F||e>=ae.LOWER_A&&e<=ae.LOWER_F}function F1(e){return e>=ae.UPPER_A&&e<=ae.UPPER_Z||e>=ae.LOWER_A&&e<=ae.LOWER_Z||Oi(e)}function V1(e){return e===ae.EQUALS||F1(e)}var se;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(se||(se={}));var rt;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(rt||(rt={}));class Y1{constructor(t,n,r){this.decodeTree=t,this.emitCodePoint=n,this.errors=r,this.state=se.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=rt.Strict}startEntity(t){this.decodeMode=t,this.state=se.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(t,n){switch(this.state){case se.EntityStart:return t.charCodeAt(n)===ae.NUM?(this.state=se.NumericStart,this.consumed+=1,this.stateNumericStart(t,n+1)):(this.state=se.NamedEntity,this.stateNamedEntity(t,n));case se.NumericStart:return this.stateNumericStart(t,n);case se.NumericDecimal:return this.stateNumericDecimal(t,n);case se.NumericHex:return this.stateNumericHex(t,n);case se.NamedEntity:return this.stateNamedEntity(t,n)}}stateNumericStart(t,n){return n>=t.length?-1:(t.charCodeAt(n)|U1)===ae.LOWER_X?(this.state=se.NumericHex,this.consumed+=1,this.stateNumericHex(t,n+1)):(this.state=se.NumericDecimal,this.stateNumericDecimal(t,n))}addToNumericResult(t,n,r,s){if(n!==r){const i=r-n;this.result=this.result*Math.pow(s,i)+Number.parseInt(t.substr(n,i),s),this.consumed+=i}}stateNumericHex(t,n){const r=n;for(;n<t.length;){const s=t.charCodeAt(n);if(Oi(s)||H1(s))n+=1;else return this.addToNumericResult(t,r,n,16),this.emitNumericEntity(s,3)}return this.addToNumericResult(t,r,n,16),-1}stateNumericDecimal(t,n){const r=n;for(;n<t.length;){const s=t.charCodeAt(n);if(Oi(s))n+=1;else return this.addToNumericResult(t,r,n,10),this.emitNumericEntity(s,2)}return this.addToNumericResult(t,r,n,10),-1}emitNumericEntity(t,n){var r;if(this.consumed<=n)return(r=this.errors)===null||r===void 0||r.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===ae.SEMI)this.consumed+=1;else if(this.decodeMode===rt.Strict)return 0;return this.emitCodePoint(B1(this.result),this.consumed),this.errors&&(t!==ae.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,n){const{decodeTree:r}=this;let s=r[this.treeIndex],i=(s&gt.VALUE_LENGTH)>>14;for(;n<t.length;n++,this.excess++){const o=t.charCodeAt(n);if(this.treeIndex=$1(r,s,this.treeIndex+Math.max(1,i),o),this.treeIndex<0)return this.result===0||this.decodeMode===rt.Attribute&&(i===0||V1(o))?0:this.emitNotTerminatedNamedEntity();if(s=r[this.treeIndex],i=(s&gt.VALUE_LENGTH)>>14,i!==0){if(o===ae.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==rt.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var t;const{result:n,decodeTree:r}=this,s=(r[n]&gt.VALUE_LENGTH)>>14;return this.emitNamedEntityData(n,s,this.consumed),(t=this.errors)===null||t===void 0||t.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,n,r){const{decodeTree:s}=this;return this.emitCodePoint(n===1?s[t]&~gt.VALUE_LENGTH:s[t+1],r),n===3&&this.emitCodePoint(s[t+2],r),r}end(){var t;switch(this.state){case se.NamedEntity:return this.result!==0&&(this.decodeMode!==rt.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case se.NumericDecimal:return this.emitNumericEntity(0,2);case se.NumericHex:return this.emitNumericEntity(0,3);case se.NumericStart:return(t=this.errors)===null||t===void 0||t.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case se.EntityStart:return 0}}}function $1(e,t,n,r){const s=(t&gt.BRANCH_LENGTH)>>7,i=t&gt.JUMP_TABLE;if(s===0)return i!==0&&r===i?n:-1;if(i){const u=r-i;return u<0||u>=s?-1:e[n+u]-1}let o=n,a=o+s-1;for(;o<=a;){const u=o+a>>>1,c=e[u];if(c<r)o=u+1;else if(c>r)a=u-1;else return e[u+s]}return-1}var w;(function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/"})(w||(w={}));var Dt;(function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size"})(Dt||(Dt={}));var Oe;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"})(Oe||(Oe={}));var y;(function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp"})(y||(y={}));var l;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP"})(l||(l={}));const j1=new Map([[y.A,l.A],[y.ADDRESS,l.ADDRESS],[y.ANNOTATION_XML,l.ANNOTATION_XML],[y.APPLET,l.APPLET],[y.AREA,l.AREA],[y.ARTICLE,l.ARTICLE],[y.ASIDE,l.ASIDE],[y.B,l.B],[y.BASE,l.BASE],[y.BASEFONT,l.BASEFONT],[y.BGSOUND,l.BGSOUND],[y.BIG,l.BIG],[y.BLOCKQUOTE,l.BLOCKQUOTE],[y.BODY,l.BODY],[y.BR,l.BR],[y.BUTTON,l.BUTTON],[y.CAPTION,l.CAPTION],[y.CENTER,l.CENTER],[y.CODE,l.CODE],[y.COL,l.COL],[y.COLGROUP,l.COLGROUP],[y.DD,l.DD],[y.DESC,l.DESC],[y.DETAILS,l.DETAILS],[y.DIALOG,l.DIALOG],[y.DIR,l.DIR],[y.DIV,l.DIV],[y.DL,l.DL],[y.DT,l.DT],[y.EM,l.EM],[y.EMBED,l.EMBED],[y.FIELDSET,l.FIELDSET],[y.FIGCAPTION,l.FIGCAPTION],[y.FIGURE,l.FIGURE],[y.FONT,l.FONT],[y.FOOTER,l.FOOTER],[y.FOREIGN_OBJECT,l.FOREIGN_OBJECT],[y.FORM,l.FORM],[y.FRAME,l.FRAME],[y.FRAMESET,l.FRAMESET],[y.H1,l.H1],[y.H2,l.H2],[y.H3,l.H3],[y.H4,l.H4],[y.H5,l.H5],[y.H6,l.H6],[y.HEAD,l.HEAD],[y.HEADER,l.HEADER],[y.HGROUP,l.HGROUP],[y.HR,l.HR],[y.HTML,l.HTML],[y.I,l.I],[y.IMG,l.IMG],[y.IMAGE,l.IMAGE],[y.INPUT,l.INPUT],[y.IFRAME,l.IFRAME],[y.KEYGEN,l.KEYGEN],[y.LABEL,l.LABEL],[y.LI,l.LI],[y.LINK,l.LINK],[y.LISTING,l.LISTING],[y.MAIN,l.MAIN],[y.MALIGNMARK,l.MALIGNMARK],[y.MARQUEE,l.MARQUEE],[y.MATH,l.MATH],[y.MENU,l.MENU],[y.META,l.META],[y.MGLYPH,l.MGLYPH],[y.MI,l.MI],[y.MO,l.MO],[y.MN,l.MN],[y.MS,l.MS],[y.MTEXT,l.MTEXT],[y.NAV,l.NAV],[y.NOBR,l.NOBR],[y.NOFRAMES,l.NOFRAMES],[y.NOEMBED,l.NOEMBED],[y.NOSCRIPT,l.NOSCRIPT],[y.OBJECT,l.OBJECT],[y.OL,l.OL],[y.OPTGROUP,l.OPTGROUP],[y.OPTION,l.OPTION],[y.P,l.P],[y.PARAM,l.PARAM],[y.PLAINTEXT,l.PLAINTEXT],[y.PRE,l.PRE],[y.RB,l.RB],[y.RP,l.RP],[y.RT,l.RT],[y.RTC,l.RTC],[y.RUBY,l.RUBY],[y.S,l.S],[y.SCRIPT,l.SCRIPT],[y.SEARCH,l.SEARCH],[y.SECTION,l.SECTION],[y.SELECT,l.SELECT],[y.SOURCE,l.SOURCE],[y.SMALL,l.SMALL],[y.SPAN,l.SPAN],[y.STRIKE,l.STRIKE],[y.STRONG,l.STRONG],[y.STYLE,l.STYLE],[y.SUB,l.SUB],[y.SUMMARY,l.SUMMARY],[y.SUP,l.SUP],[y.TABLE,l.TABLE],[y.TBODY,l.TBODY],[y.TEMPLATE,l.TEMPLATE],[y.TEXTAREA,l.TEXTAREA],[y.TFOOT,l.TFOOT],[y.TD,l.TD],[y.TH,l.TH],[y.THEAD,l.THEAD],[y.TITLE,l.TITLE],[y.TR,l.TR],[y.TRACK,l.TRACK],[y.TT,l.TT],[y.U,l.U],[y.UL,l.UL],[y.SVG,l.SVG],[y.VAR,l.VAR],[y.WBR,l.WBR],[y.XMP,l.XMP]]);function ys(e){var t;return(t=j1.get(e))!==null&&t!==void 0?t:l.UNKNOWN}const I=l,q1={[w.HTML]:new Set([I.ADDRESS,I.APPLET,I.AREA,I.ARTICLE,I.ASIDE,I.BASE,I.BASEFONT,I.BGSOUND,I.BLOCKQUOTE,I.BODY,I.BR,I.BUTTON,I.CAPTION,I.CENTER,I.COL,I.COLGROUP,I.DD,I.DETAILS,I.DIR,I.DIV,I.DL,I.DT,I.EMBED,I.FIELDSET,I.FIGCAPTION,I.FIGURE,I.FOOTER,I.FORM,I.FRAME,I.FRAMESET,I.H1,I.H2,I.H3,I.H4,I.H5,I.H6,I.HEAD,I.HEADER,I.HGROUP,I.HR,I.HTML,I.IFRAME,I.IMG,I.INPUT,I.LI,I.LINK,I.LISTING,I.MAIN,I.MARQUEE,I.MENU,I.META,I.NAV,I.NOEMBED,I.NOFRAMES,I.NOSCRIPT,I.OBJECT,I.OL,I.P,I.PARAM,I.PLAINTEXT,I.PRE,I.SCRIPT,I.SECTION,I.SELECT,I.SOURCE,I.STYLE,I.SUMMARY,I.TABLE,I.TBODY,I.TD,I.TEMPLATE,I.TEXTAREA,I.TFOOT,I.TH,I.THEAD,I.TITLE,I.TR,I.TRACK,I.UL,I.WBR,I.XMP]),[w.MATHML]:new Set([I.MI,I.MO,I.MN,I.MS,I.MTEXT,I.ANNOTATION_XML]),[w.SVG]:new Set([I.TITLE,I.FOREIGN_OBJECT,I.DESC]),[w.XLINK]:new Set,[w.XML]:new Set,[w.XMLNS]:new Set},Di=new Set([I.H1,I.H2,I.H3,I.H4,I.H5,I.H6]);y.STYLE,y.SCRIPT,y.XMP,y.IFRAME,y.NOEMBED,y.NOFRAMES,y.PLAINTEXT;var b;(function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND"})(b||(b={}));const ye={DATA:b.DATA,RCDATA:b.RCDATA,RAWTEXT:b.RAWTEXT,SCRIPT_DATA:b.SCRIPT_DATA,PLAINTEXT:b.PLAINTEXT,CDATA_SECTION:b.CDATA_SECTION};function z1(e){return e>=g.DIGIT_0&&e<=g.DIGIT_9}function Ln(e){return e>=g.LATIN_CAPITAL_A&&e<=g.LATIN_CAPITAL_Z}function W1(e){return e>=g.LATIN_SMALL_A&&e<=g.LATIN_SMALL_Z}function ct(e){return W1(e)||Ln(e)}function Ka(e){return ct(e)||z1(e)}function Tr(e){return e+32}function zc(e){return e===g.SPACE||e===g.LINE_FEED||e===g.TABULATION||e===g.FORM_FEED}function Xa(e){return zc(e)||e===g.SOLIDUS||e===g.GREATER_THAN_SIGN}function G1(e){return e===g.NULL?S.nullCharacterReference:e>1114111?S.characterReferenceOutsideUnicodeRange:Yc(e)?S.surrogateCharacterReference:jc(e)?S.noncharacterCharacterReference:$c(e)||e===g.CARRIAGE_RETURN?S.controlCharacterReference:null}class K1{constructor(t,n){this.options=t,this.handler=n,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName="",this.active=!1,this.state=b.DATA,this.returnState=b.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new M1(n),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new Y1(R1,(r,s)=>{this.preprocessor.pos=this.entityStartPos+s-1,this._flushCodePointConsumedAsCharacterReference(r)},n.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(S.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:r=>{this._err(S.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+r)},validateNumericCharacterReference:r=>{const s=G1(r);s&&this._err(s,1)}}:void 0)}_err(t,n=0){var r,s;(s=(r=this.handler).onParseError)===null||s===void 0||s.call(r,this.preprocessor.getError(t,n))}getCurrentLocation(t){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-t,startOffset:this.preprocessor.offset-t,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;const t=this._consume();this._ensureHibernation()||this._callState(t)}this.inLoop=!1}}pause(){this.paused=!0}resume(t){if(!this.paused)throw new Error("Parser was already resumed");this.paused=!1,!this.inLoop&&(this._runParsingLoop(),this.paused||t==null||t())}write(t,n,r){this.active=!0,this.preprocessor.write(t,n),this._runParsingLoop(),this.paused||r==null||r()}insertHtmlAtCurrentPos(t){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(t),this._runParsingLoop()}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0):!1}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(t){this.consumedAfterSnapshot+=t;for(let n=0;n<t;n++)this.preprocessor.advance()}_consumeSequenceIfMatch(t,n){return this.preprocessor.startsWith(t,n)?(this._advanceBy(t.length-1),!0):!1}_createStartTagToken(){this.currentToken={type:V.START_TAG,tagName:"",tagID:l.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:V.END_TAG,tagName:"",tagID:l.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(t){this.currentToken={type:V.COMMENT,data:"",location:this.getCurrentLocation(t)}}_createDoctypeToken(t){this.currentToken={type:V.DOCTYPE,name:t,forceQuirks:!1,publicId:null,systemId:null,location:this.currentLocation}}_createCharacterToken(t,n){this.currentCharacterToken={type:t,chars:n,location:this.currentLocation}}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0)}_leaveAttrName(){var t,n;const r=this.currentToken;if(qc(r,this.currentAttr.name)===null){if(r.attrs.push(this.currentAttr),r.location&&this.currentLocation){const s=(t=(n=r.location).attrs)!==null&&t!==void 0?t:n.attrs=Object.create(null);s[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(S.duplicateAttribute)}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset)}prepareToken(t){this._emitCurrentCharacterToken(t.location),this.currentToken=null,t.location&&(t.location.endLine=this.preprocessor.line,t.location.endCol=this.preprocessor.col+1,t.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1)}emitCurrentTagToken(){const t=this.currentToken;this.prepareToken(t),t.tagID=ys(t.tagName),t.type===V.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(S.endTagWithAttributes),t.selfClosing&&this._err(S.endTagWithTrailingSolidus),this.handler.onEndTag(t)),this.preprocessor.dropParsedChunk()}emitCurrentComment(t){this.prepareToken(t),this.handler.onComment(t),this.preprocessor.dropParsedChunk()}emitCurrentDoctype(t){this.prepareToken(t),this.handler.onDoctype(t),this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(t){if(this.currentCharacterToken){switch(t&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=t.startLine,this.currentCharacterToken.location.endCol=t.startCol,this.currentCharacterToken.location.endOffset=t.startOffset),this.currentCharacterToken.type){case V.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case V.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case V.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null}}_emitEOFToken(){const t=this.getCurrentLocation(0);t&&(t.endLine=t.startLine,t.endCol=t.startCol,t.endOffset=t.startOffset),this._emitCurrentCharacterToken(t),this.handler.onEof({type:V.EOF,location:t}),this.active=!1}_appendCharToCurrentCharacterToken(t,n){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=n;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,n)}_emitCodePoint(t){const n=zc(t)?V.WHITESPACE_CHARACTER:t===g.NULL?V.NULL_CHARACTER:V.CHARACTER;this._appendCharToCurrentCharacterToken(n,String.fromCodePoint(t))}_emitChars(t){this._appendCharToCurrentCharacterToken(V.CHARACTER,t)}_startCharacterReference(){this.returnState=this.state,this.state=b.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?rt.Attribute:rt.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===b.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===b.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===b.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t)}_callState(t){switch(this.state){case b.DATA:{this._stateData(t);break}case b.RCDATA:{this._stateRcdata(t);break}case b.RAWTEXT:{this._stateRawtext(t);break}case b.SCRIPT_DATA:{this._stateScriptData(t);break}case b.PLAINTEXT:{this._statePlaintext(t);break}case b.TAG_OPEN:{this._stateTagOpen(t);break}case b.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case b.TAG_NAME:{this._stateTagName(t);break}case b.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case b.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case b.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case b.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case b.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case b.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case b.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case b.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case b.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case b.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case b.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case b.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case b.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case b.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case b.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case b.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case b.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case b.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case b.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case b.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case b.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case b.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case b.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case b.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case b.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case b.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case b.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case b.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case b.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case b.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case b.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case b.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case b.BOGUS_COMMENT:{this._stateBogusComment(t);break}case b.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case b.COMMENT_START:{this._stateCommentStart(t);break}case b.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case b.COMMENT:{this._stateComment(t);break}case b.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case b.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case b.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case b.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case b.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case b.COMMENT_END:{this._stateCommentEnd(t);break}case b.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case b.DOCTYPE:{this._stateDoctype(t);break}case b.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case b.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case b.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case b.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case b.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case b.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case b.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case b.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case b.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case b.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case b.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case b.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case b.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case b.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case b.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case b.CDATA_SECTION:{this._stateCdataSection(t);break}case b.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case b.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case b.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case b.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case g.LESS_THAN_SIGN:{this.state=b.TAG_OPEN;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err(S.unexpectedNullCharacter),this._emitCodePoint(t);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRcdata(t){switch(t){case g.AMPERSAND:{this._startCharacterReference();break}case g.LESS_THAN_SIGN:{this.state=b.RCDATA_LESS_THAN_SIGN;break}case g.NULL:{this._err(S.unexpectedNullCharacter),this._emitChars(K);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRawtext(t){switch(t){case g.LESS_THAN_SIGN:{this.state=b.RAWTEXT_LESS_THAN_SIGN;break}case g.NULL:{this._err(S.unexpectedNullCharacter),this._emitChars(K);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptData(t){switch(t){case g.LESS_THAN_SIGN:{this.state=b.SCRIPT_DATA_LESS_THAN_SIGN;break}case g.NULL:{this._err(S.unexpectedNullCharacter),this._emitChars(K);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_statePlaintext(t){switch(t){case g.NULL:{this._err(S.unexpectedNullCharacter),this._emitChars(K);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateTagOpen(t){if(ct(t))this._createStartTagToken(),this.state=b.TAG_NAME,this._stateTagName(t);else switch(t){case g.EXCLAMATION_MARK:{this.state=b.MARKUP_DECLARATION_OPEN;break}case g.SOLIDUS:{this.state=b.END_TAG_OPEN;break}case g.QUESTION_MARK:{this._err(S.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=b.BOGUS_COMMENT,this._stateBogusComment(t);break}case g.EOF:{this._err(S.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(S.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=b.DATA,this._stateData(t)}}_stateEndTagOpen(t){if(ct(t))this._createEndTagToken(),this.state=b.TAG_NAME,this._stateTagName(t);else switch(t){case g.GREATER_THAN_SIGN:{this._err(S.missingEndTagName),this.state=b.DATA;break}case g.EOF:{this._err(S.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(S.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=b.BOGUS_COMMENT,this._stateBogusComment(t)}}_stateTagName(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=b.BEFORE_ATTRIBUTE_NAME;break}case g.SOLIDUS:{this.state=b.SELF_CLOSING_START_TAG;break}case g.GREATER_THAN_SIGN:{this.state=b.DATA,this.emitCurrentTagToken();break}case g.NULL:{this._err(S.unexpectedNullCharacter),n.tagName+=K;break}case g.EOF:{this._err(S.eofInTag),this._emitEOFToken();break}default:n.tagName+=String.fromCodePoint(Ln(t)?Tr(t):t)}}_stateRcdataLessThanSign(t){t===g.SOLIDUS?this.state=b.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=b.RCDATA,this._stateRcdata(t))}_stateRcdataEndTagOpen(t){ct(t)?(this.state=b.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=b.RCDATA,this._stateRcdata(t))}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,!1))return!this._ensureHibernation();this._createEndTagToken();const n=this.currentToken;switch(n.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=b.BEFORE_ATTRIBUTE_NAME,!1;case g.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=b.SELF_CLOSING_START_TAG,!1;case g.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=b.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=b.RCDATA,this._stateRcdata(t))}_stateRawtextLessThanSign(t){t===g.SOLIDUS?this.state=b.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=b.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagOpen(t){ct(t)?(this.state=b.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=b.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=b.RAWTEXT,this._stateRawtext(t))}_stateScriptDataLessThanSign(t){switch(t){case g.SOLIDUS:{this.state=b.SCRIPT_DATA_END_TAG_OPEN;break}case g.EXCLAMATION_MARK:{this.state=b.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=b.SCRIPT_DATA,this._stateScriptData(t)}}_stateScriptDataEndTagOpen(t){ct(t)?(this.state=b.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=b.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=b.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStart(t){t===g.HYPHEN_MINUS?(this.state=b.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=b.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStartDash(t){t===g.HYPHEN_MINUS?(this.state=b.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=b.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscaped(t){switch(t){case g.HYPHEN_MINUS:{this.state=b.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=b.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.NULL:{this._err(S.unexpectedNullCharacter),this._emitChars(K);break}case g.EOF:{this._err(S.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataEscapedDash(t){switch(t){case g.HYPHEN_MINUS:{this.state=b.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=b.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.NULL:{this._err(S.unexpectedNullCharacter),this.state=b.SCRIPT_DATA_ESCAPED,this._emitChars(K);break}case g.EOF:{this._err(S.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=b.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedDashDash(t){switch(t){case g.HYPHEN_MINUS:{this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=b.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.GREATER_THAN_SIGN:{this.state=b.SCRIPT_DATA,this._emitChars(">");break}case g.NULL:{this._err(S.unexpectedNullCharacter),this.state=b.SCRIPT_DATA_ESCAPED,this._emitChars(K);break}case g.EOF:{this._err(S.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=b.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedLessThanSign(t){t===g.SOLIDUS?this.state=b.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:ct(t)?(this._emitChars("<"),this.state=b.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=b.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagOpen(t){ct(t)?(this.state=b.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=b.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=b.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(be.SCRIPT,!1)&&Xa(this.preprocessor.peek(be.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<be.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=b.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscaped(t){switch(t){case g.HYPHEN_MINUS:{this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.NULL:{this._err(S.unexpectedNullCharacter),this._emitChars(K);break}case g.EOF:{this._err(S.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDash(t){switch(t){case g.HYPHEN_MINUS:{this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.NULL:{this._err(S.unexpectedNullCharacter),this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(K);break}case g.EOF:{this._err(S.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case g.HYPHEN_MINUS:{this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.GREATER_THAN_SIGN:{this.state=b.SCRIPT_DATA,this._emitChars(">");break}case g.NULL:{this._err(S.unexpectedNullCharacter),this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(K);break}case g.EOF:{this._err(S.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedLessThanSign(t){t===g.SOLIDUS?(this.state=b.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(be.SCRIPT,!1)&&Xa(this.preprocessor.peek(be.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<be.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=b.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=b.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateBeforeAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.SOLIDUS:case g.GREATER_THAN_SIGN:case g.EOF:{this.state=b.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case g.EQUALS_SIGN:{this._err(S.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=b.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=b.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:case g.SOLIDUS:case g.GREATER_THAN_SIGN:case g.EOF:{this._leaveAttrName(),this.state=b.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case g.EQUALS_SIGN:{this._leaveAttrName(),this.state=b.BEFORE_ATTRIBUTE_VALUE;break}case g.QUOTATION_MARK:case g.APOSTROPHE:case g.LESS_THAN_SIGN:{this._err(S.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case g.NULL:{this._err(S.unexpectedNullCharacter),this.currentAttr.name+=K;break}default:this.currentAttr.name+=String.fromCodePoint(Ln(t)?Tr(t):t)}}_stateAfterAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.SOLIDUS:{this.state=b.SELF_CLOSING_START_TAG;break}case g.EQUALS_SIGN:{this.state=b.BEFORE_ATTRIBUTE_VALUE;break}case g.GREATER_THAN_SIGN:{this.state=b.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err(S.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=b.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateBeforeAttributeValue(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{this.state=b.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this.state=b.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(S.missingAttributeValue),this.state=b.DATA,this.emitCurrentTagToken();break}default:this.state=b.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t)}}_stateAttributeValueDoubleQuoted(t){switch(t){case g.QUOTATION_MARK:{this.state=b.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err(S.unexpectedNullCharacter),this.currentAttr.value+=K;break}case g.EOF:{this._err(S.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueSingleQuoted(t){switch(t){case g.APOSTROPHE:{this.state=b.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err(S.unexpectedNullCharacter),this.currentAttr.value+=K;break}case g.EOF:{this._err(S.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueUnquoted(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this._leaveAttrValue(),this.state=b.BEFORE_ATTRIBUTE_NAME;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=b.DATA,this.emitCurrentTagToken();break}case g.NULL:{this._err(S.unexpectedNullCharacter),this.currentAttr.value+=K;break}case g.QUOTATION_MARK:case g.APOSTROPHE:case g.LESS_THAN_SIGN:case g.EQUALS_SIGN:case g.GRAVE_ACCENT:{this._err(S.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case g.EOF:{this._err(S.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAfterAttributeValueQuoted(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this._leaveAttrValue(),this.state=b.BEFORE_ATTRIBUTE_NAME;break}case g.SOLIDUS:{this._leaveAttrValue(),this.state=b.SELF_CLOSING_START_TAG;break}case g.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=b.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err(S.eofInTag),this._emitEOFToken();break}default:this._err(S.missingWhitespaceBetweenAttributes),this.state=b.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateSelfClosingStartTag(t){switch(t){case g.GREATER_THAN_SIGN:{const n=this.currentToken;n.selfClosing=!0,this.state=b.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err(S.eofInTag),this._emitEOFToken();break}default:this._err(S.unexpectedSolidusInTag),this.state=b.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateBogusComment(t){const n=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.state=b.DATA,this.emitCurrentComment(n);break}case g.EOF:{this.emitCurrentComment(n),this._emitEOFToken();break}case g.NULL:{this._err(S.unexpectedNullCharacter),n.data+=K;break}default:n.data+=String.fromCodePoint(t)}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(be.DASH_DASH,!0)?(this._createCommentToken(be.DASH_DASH.length+1),this.state=b.COMMENT_START):this._consumeSequenceIfMatch(be.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(be.DOCTYPE.length+1),this.state=b.DOCTYPE):this._consumeSequenceIfMatch(be.CDATA_START,!0)?this.inForeignNode?this.state=b.CDATA_SECTION:(this._err(S.cdataInHtmlContent),this._createCommentToken(be.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=b.BOGUS_COMMENT):this._ensureHibernation()||(this._err(S.incorrectlyOpenedComment),this._createCommentToken(2),this.state=b.BOGUS_COMMENT,this._stateBogusComment(t))}_stateCommentStart(t){switch(t){case g.HYPHEN_MINUS:{this.state=b.COMMENT_START_DASH;break}case g.GREATER_THAN_SIGN:{this._err(S.abruptClosingOfEmptyComment),this.state=b.DATA;const n=this.currentToken;this.emitCurrentComment(n);break}default:this.state=b.COMMENT,this._stateComment(t)}}_stateCommentStartDash(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=b.COMMENT_END;break}case g.GREATER_THAN_SIGN:{this._err(S.abruptClosingOfEmptyComment),this.state=b.DATA,this.emitCurrentComment(n);break}case g.EOF:{this._err(S.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=b.COMMENT,this._stateComment(t)}}_stateComment(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=b.COMMENT_END_DASH;break}case g.LESS_THAN_SIGN:{n.data+="<",this.state=b.COMMENT_LESS_THAN_SIGN;break}case g.NULL:{this._err(S.unexpectedNullCharacter),n.data+=K;break}case g.EOF:{this._err(S.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+=String.fromCodePoint(t)}}_stateCommentLessThanSign(t){const n=this.currentToken;switch(t){case g.EXCLAMATION_MARK:{n.data+="!",this.state=b.COMMENT_LESS_THAN_SIGN_BANG;break}case g.LESS_THAN_SIGN:{n.data+="<";break}default:this.state=b.COMMENT,this._stateComment(t)}}_stateCommentLessThanSignBang(t){t===g.HYPHEN_MINUS?this.state=b.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=b.COMMENT,this._stateComment(t))}_stateCommentLessThanSignBangDash(t){t===g.HYPHEN_MINUS?this.state=b.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=b.COMMENT_END_DASH,this._stateCommentEndDash(t))}_stateCommentLessThanSignBangDashDash(t){t!==g.GREATER_THAN_SIGN&&t!==g.EOF&&this._err(S.nestedComment),this.state=b.COMMENT_END,this._stateCommentEnd(t)}_stateCommentEndDash(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=b.COMMENT_END;break}case g.EOF:{this._err(S.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=b.COMMENT,this._stateComment(t)}}_stateCommentEnd(t){const n=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.state=b.DATA,this.emitCurrentComment(n);break}case g.EXCLAMATION_MARK:{this.state=b.COMMENT_END_BANG;break}case g.HYPHEN_MINUS:{n.data+="-";break}case g.EOF:{this._err(S.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--",this.state=b.COMMENT,this._stateComment(t)}}_stateCommentEndBang(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{n.data+="--!",this.state=b.COMMENT_END_DASH;break}case g.GREATER_THAN_SIGN:{this._err(S.incorrectlyClosedComment),this.state=b.DATA,this.emitCurrentComment(n);break}case g.EOF:{this._err(S.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--!",this.state=b.COMMENT,this._stateComment(t)}}_stateDoctype(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=b.BEFORE_DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this.state=b.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case g.EOF:{this._err(S.eofInDoctype),this._createDoctypeToken(null);const n=this.currentToken;n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(S.missingWhitespaceBeforeDoctypeName),this.state=b.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t)}}_stateBeforeDoctypeName(t){if(Ln(t))this._createDoctypeToken(String.fromCharCode(Tr(t))),this.state=b.DOCTYPE_NAME;else switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.NULL:{this._err(S.unexpectedNullCharacter),this._createDoctypeToken(K),this.state=b.DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this._err(S.missingDoctypeName),this._createDoctypeToken(null);const n=this.currentToken;n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=b.DATA;break}case g.EOF:{this._err(S.eofInDoctype),this._createDoctypeToken(null);const n=this.currentToken;n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=b.DOCTYPE_NAME}}_stateDoctypeName(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=b.AFTER_DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this.state=b.DATA,this.emitCurrentDoctype(n);break}case g.NULL:{this._err(S.unexpectedNullCharacter),n.name+=K;break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.name+=String.fromCodePoint(Ln(t)?Tr(t):t)}}_stateAfterDoctypeName(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.state=b.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(be.PUBLIC,!1)?this.state=b.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(be.SYSTEM,!1)?this.state=b.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(S.invalidCharacterSequenceAfterDoctypeName),n.forceQuirks=!0,this.state=b.BOGUS_DOCTYPE,this._stateBogusDoctype(t))}}_stateAfterDoctypePublicKeyword(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=b.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.QUOTATION_MARK:{this._err(S.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=b.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(S.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=b.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(S.missingDoctypePublicIdentifier),n.forceQuirks=!0,this.state=b.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(S.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=!0,this.state=b.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypePublicIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{n.publicId="",this.state=b.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{n.publicId="",this.state=b.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(S.missingDoctypePublicIdentifier),n.forceQuirks=!0,this.state=b.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(S.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=!0,this.state=b.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypePublicIdentifierDoubleQuoted(t){const n=this.currentToken;switch(t){case g.QUOTATION_MARK:{this.state=b.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.NULL:{this._err(S.unexpectedNullCharacter),n.publicId+=K;break}case g.GREATER_THAN_SIGN:{this._err(S.abruptDoctypePublicIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=b.DATA;break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t)}}_stateDoctypePublicIdentifierSingleQuoted(t){const n=this.currentToken;switch(t){case g.APOSTROPHE:{this.state=b.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.NULL:{this._err(S.unexpectedNullCharacter),n.publicId+=K;break}case g.GREATER_THAN_SIGN:{this._err(S.abruptDoctypePublicIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=b.DATA;break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t)}}_stateAfterDoctypePublicIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=b.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case g.GREATER_THAN_SIGN:{this.state=b.DATA,this.emitCurrentDoctype(n);break}case g.QUOTATION_MARK:{this._err(S.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=b.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(S.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=b.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(S.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=b.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=b.DATA;break}case g.QUOTATION_MARK:{n.systemId="",this.state=b.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{n.systemId="",this.state=b.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(S.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=b.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateAfterDoctypeSystemKeyword(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=b.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.QUOTATION_MARK:{this._err(S.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=b.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(S.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=b.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(S.missingDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=b.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(S.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=b.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypeSystemIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{n.systemId="",this.state=b.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{n.systemId="",this.state=b.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(S.missingDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=b.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(S.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=b.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypeSystemIdentifierDoubleQuoted(t){const n=this.currentToken;switch(t){case g.QUOTATION_MARK:{this.state=b.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.NULL:{this._err(S.unexpectedNullCharacter),n.systemId+=K;break}case g.GREATER_THAN_SIGN:{this._err(S.abruptDoctypeSystemIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=b.DATA;break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t)}}_stateDoctypeSystemIdentifierSingleQuoted(t){const n=this.currentToken;switch(t){case g.APOSTROPHE:{this.state=b.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.NULL:{this._err(S.unexpectedNullCharacter),n.systemId+=K;break}case g.GREATER_THAN_SIGN:{this._err(S.abruptDoctypeSystemIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=b.DATA;break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t)}}_stateAfterDoctypeSystemIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=b.DATA;break}case g.EOF:{this._err(S.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(S.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=b.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBogusDoctype(t){const n=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=b.DATA;break}case g.NULL:{this._err(S.unexpectedNullCharacter);break}case g.EOF:{this.emitCurrentDoctype(n),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case g.RIGHT_SQUARE_BRACKET:{this.state=b.CDATA_SECTION_BRACKET;break}case g.EOF:{this._err(S.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateCdataSectionBracket(t){t===g.RIGHT_SQUARE_BRACKET?this.state=b.CDATA_SECTION_END:(this._emitChars("]"),this.state=b.CDATA_SECTION,this._stateCdataSection(t))}_stateCdataSectionEnd(t){switch(t){case g.GREATER_THAN_SIGN:{this.state=b.DATA;break}case g.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=b.CDATA_SECTION,this._stateCdataSection(t)}}_stateCharacterReference(){let t=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(t<0)if(this.preprocessor.lastChunkWritten)t=this.entityDecoder.end();else{this.active=!1,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=!0;return}t===0?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(g.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&Ka(this.preprocessor.peek(1))?b.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(t){Ka(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===g.SEMICOLON&&this._err(S.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t))}}const Wc=new Set([l.DD,l.DT,l.LI,l.OPTGROUP,l.OPTION,l.P,l.RB,l.RP,l.RT,l.RTC]),Qa=new Set([...Wc,l.CAPTION,l.COLGROUP,l.TBODY,l.TD,l.TFOOT,l.TH,l.THEAD,l.TR]),Kr=new Set([l.APPLET,l.CAPTION,l.HTML,l.MARQUEE,l.OBJECT,l.TABLE,l.TD,l.TEMPLATE,l.TH]),X1=new Set([...Kr,l.OL,l.UL]),Q1=new Set([...Kr,l.BUTTON]),Ja=new Set([l.ANNOTATION_XML,l.MI,l.MN,l.MO,l.MS,l.MTEXT]),Za=new Set([l.DESC,l.FOREIGN_OBJECT,l.TITLE]),J1=new Set([l.TR,l.TEMPLATE,l.HTML]),Z1=new Set([l.TBODY,l.TFOOT,l.THEAD,l.TEMPLATE,l.HTML]),eb=new Set([l.TABLE,l.TEMPLATE,l.HTML]),tb=new Set([l.TD,l.TH]);class nb{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,n,r){this.treeAdapter=n,this.handler=r,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=l.UNKNOWN,this.current=t}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===l.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===w.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop]}push(t,n){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=n,this.currentTagId=n,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,n,!0)}pop(){const t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!0)}replace(t,n){const r=this._indexOf(t);this.items[r]=n,r===this.stackTop&&(this.current=n)}insertAfter(t,n,r){const s=this._indexOf(t)+1;this.items.splice(s,0,n),this.tagIDs.splice(s,0,r),this.stackTop++,s===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,s===this.stackTop)}popUntilTagNamePopped(t){let n=this.stackTop+1;do n=this.tagIDs.lastIndexOf(t,n-1);while(n>0&&this.treeAdapter.getNamespaceURI(this.items[n])!==w.HTML);this.shortenToLength(Math.max(n,0))}shortenToLength(t){for(;this.stackTop>=t;){const n=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(n,this.stackTop<t)}}popUntilElementPopped(t){const n=this._indexOf(t);this.shortenToLength(Math.max(n,0))}popUntilPopped(t,n){const r=this._indexOfTagNames(t,n);this.shortenToLength(Math.max(r,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(Di,w.HTML)}popUntilTableCellPopped(){this.popUntilPopped(tb,w.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(t,n){for(let r=this.stackTop;r>=0;r--)if(t.has(this.tagIDs[r])&&this.treeAdapter.getNamespaceURI(this.items[r])===n)return r;return-1}clearBackTo(t,n){const r=this._indexOfTagNames(t,n);this.shortenToLength(r+1)}clearBackToTableContext(){this.clearBackTo(eb,w.HTML)}clearBackToTableBodyContext(){this.clearBackTo(Z1,w.HTML)}clearBackToTableRowContext(){this.clearBackTo(J1,w.HTML)}remove(t){const n=this._indexOf(t);n>=0&&(n===this.stackTop?this.pop():(this.items.splice(n,1),this.tagIDs.splice(n,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===l.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){const n=this._indexOf(t)-1;return n>=0?this.items[n]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===l.HTML}hasInDynamicScope(t,n){for(let r=this.stackTop;r>=0;r--){const s=this.tagIDs[r];switch(this.treeAdapter.getNamespaceURI(this.items[r])){case w.HTML:{if(s===t)return!0;if(n.has(s))return!1;break}case w.SVG:{if(Za.has(s))return!1;break}case w.MATHML:{if(Ja.has(s))return!1;break}}}return!0}hasInScope(t){return this.hasInDynamicScope(t,Kr)}hasInListItemScope(t){return this.hasInDynamicScope(t,X1)}hasInButtonScope(t){return this.hasInDynamicScope(t,Q1)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){const n=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case w.HTML:{if(Di.has(n))return!0;if(Kr.has(n))return!1;break}case w.SVG:{if(Za.has(n))return!1;break}case w.MATHML:{if(Ja.has(n))return!1;break}}}return!0}hasInTableScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===w.HTML)switch(this.tagIDs[n]){case t:return!0;case l.TABLE:case l.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===w.HTML)switch(this.tagIDs[t]){case l.TBODY:case l.THEAD:case l.TFOOT:return!0;case l.TABLE:case l.HTML:return!1}return!0}hasInSelectScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===w.HTML)switch(this.tagIDs[n]){case t:return!0;case l.OPTION:case l.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&Wc.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&Qa.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&Qa.has(this.currentTagId);)this.pop()}}const Gs=3;var Ge;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"})(Ge||(Ge={}));const eu={type:Ge.Marker};class rb{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(t,n){const r=[],s=n.length,i=this.treeAdapter.getTagName(t),o=this.treeAdapter.getNamespaceURI(t);for(let a=0;a<this.entries.length;a++){const u=this.entries[a];if(u.type===Ge.Marker)break;const{element:c}=u;if(this.treeAdapter.getTagName(c)===i&&this.treeAdapter.getNamespaceURI(c)===o){const d=this.treeAdapter.getAttrList(c);d.length===s&&r.push({idx:a,attrs:d})}}return r}_ensureNoahArkCondition(t){if(this.entries.length<Gs)return;const n=this.treeAdapter.getAttrList(t),r=this._getNoahArkConditionCandidates(t,n);if(r.length<Gs)return;const s=new Map(n.map(o=>[o.name,o.value]));let i=0;for(let o=0;o<r.length;o++){const a=r[o];a.attrs.every(u=>s.get(u.name)===u.value)&&(i+=1,i>=Gs&&this.entries.splice(a.idx,1))}}insertMarker(){this.entries.unshift(eu)}pushElement(t,n){this._ensureNoahArkCondition(t),this.entries.unshift({type:Ge.Element,element:t,token:n})}insertElementAfterBookmark(t,n){const r=this.entries.indexOf(this.bookmark);this.entries.splice(r,0,{type:Ge.Element,element:t,token:n})}removeEntry(t){const n=this.entries.indexOf(t);n!==-1&&this.entries.splice(n,1)}clearToLastMarker(){const t=this.entries.indexOf(eu);t===-1?this.entries.length=0:this.entries.splice(0,t+1)}getElementEntryInScopeWithTagName(t){const n=this.entries.find(r=>r.type===Ge.Marker||this.treeAdapter.getTagName(r.element)===t);return n&&n.type===Ge.Element?n:null}getElementEntry(t){return this.entries.find(n=>n.type===Ge.Element&&n.element===t)}}const dt={createDocument(){return{nodeName:"#document",mode:Oe.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return{nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,n){return{nodeName:e,tagName:e,attrs:n,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return{nodeName:"#comment",data:e,parentNode:null}},createTextNode(e){return{nodeName:"#text",value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e},insertBefore(e,t,n){const r=e.childNodes.indexOf(n);e.childNodes.splice(r,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent(e){return e.content},setDocumentType(e,t,n,r){const s=e.childNodes.find(i=>i.nodeName==="#documentType");if(s)s.name=t,s.publicId=n,s.systemId=r;else{const i={nodeName:"#documentType",name:t,publicId:n,systemId:r,parentNode:null};dt.appendChild(e,i)}},setDocumentMode(e,t){e.mode=t},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){const t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null}},insertText(e,t){if(e.childNodes.length>0){const n=e.childNodes[e.childNodes.length-1];if(dt.isTextNode(n)){n.value+=t;return}}dt.appendChild(e,dt.createTextNode(t))},insertTextBefore(e,t,n){const r=e.childNodes[e.childNodes.indexOf(n)-1];r&&dt.isTextNode(r)?r.value+=t:dt.insertBefore(e,dt.createTextNode(t),n)},adoptAttributes(e,t){const n=new Set(e.attrs.map(r=>r.name));for(let r=0;r<t.length;r++)n.has(t[r].name)||e.attrs.push(t[r])},getFirstChild(e){return e.childNodes[0]},getChildNodes(e){return e.childNodes},getParentNode(e){return e.parentNode},getAttrList(e){return e.attrs},getTagName(e){return e.tagName},getNamespaceURI(e){return e.namespaceURI},getTextNodeContent(e){return e.value},getCommentNodeContent(e){return e.data},getDocumentTypeNodeName(e){return e.name},getDocumentTypeNodePublicId(e){return e.publicId},getDocumentTypeNodeSystemId(e){return e.systemId},isTextNode(e){return e.nodeName==="#text"},isCommentNode(e){return e.nodeName==="#comment"},isDocumentTypeNode(e){return e.nodeName==="#documentType"},isElementNode(e){return Object.prototype.hasOwnProperty.call(e,"tagName")},setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t},getNodeSourceCodeLocation(e){return e.sourceCodeLocation},updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t}}},Gc="html",sb="about:legacy-compat",ib="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",Kc=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],ob=[...Kc,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],ab=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),Xc=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],ub=[...Xc,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function tu(e,t){return t.some(n=>e.startsWith(n))}function lb(e){return e.name===Gc&&e.publicId===null&&(e.systemId===null||e.systemId===sb)}function cb(e){if(e.name!==Gc)return Oe.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===ib)return Oe.QUIRKS;let{publicId:n}=e;if(n!==null){if(n=n.toLowerCase(),ab.has(n))return Oe.QUIRKS;let r=t===null?ob:Kc;if(tu(n,r))return Oe.QUIRKS;if(r=t===null?Xc:ub,tu(n,r))return Oe.LIMITED_QUIRKS}return Oe.NO_QUIRKS}const nu={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},db="definitionurl",hb="definitionURL",fb=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),pb=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:w.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:w.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:w.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:w.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:w.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:w.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:w.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:w.XML}],["xml:space",{prefix:"xml",name:"space",namespace:w.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:w.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:w.XMLNS}]]),mb=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),gb=new Set([l.B,l.BIG,l.BLOCKQUOTE,l.BODY,l.BR,l.CENTER,l.CODE,l.DD,l.DIV,l.DL,l.DT,l.EM,l.EMBED,l.H1,l.H2,l.H3,l.H4,l.H5,l.H6,l.HEAD,l.HR,l.I,l.IMG,l.LI,l.LISTING,l.MENU,l.META,l.NOBR,l.OL,l.P,l.PRE,l.RUBY,l.S,l.SMALL,l.SPAN,l.STRONG,l.STRIKE,l.SUB,l.SUP,l.TABLE,l.TT,l.U,l.UL,l.VAR]);function bb(e){const t=e.tagID;return t===l.FONT&&e.attrs.some(({name:r})=>r===Dt.COLOR||r===Dt.SIZE||r===Dt.FACE)||gb.has(t)}function Qc(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===db){e.attrs[t].name=hb;break}}function Jc(e){for(let t=0;t<e.attrs.length;t++){const n=fb.get(e.attrs[t].name);n!=null&&(e.attrs[t].name=n)}}function ko(e){for(let t=0;t<e.attrs.length;t++){const n=pb.get(e.attrs[t].name);n&&(e.attrs[t].prefix=n.prefix,e.attrs[t].name=n.name,e.attrs[t].namespace=n.namespace)}}function Eb(e){const t=mb.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=ys(e.tagName))}function Tb(e,t){return t===w.MATHML&&(e===l.MI||e===l.MO||e===l.MN||e===l.MS||e===l.MTEXT)}function yb(e,t,n){if(t===w.MATHML&&e===l.ANNOTATION_XML){for(let r=0;r<n.length;r++)if(n[r].name===Dt.ENCODING){const s=n[r].value.toLowerCase();return s===nu.TEXT_HTML||s===nu.APPLICATION_XML}}return t===w.SVG&&(e===l.FOREIGN_OBJECT||e===l.DESC||e===l.TITLE)}function Cb(e,t,n,r){return(!r||r===w.HTML)&&yb(e,t,n)||(!r||r===w.MATHML)&&Tb(e,t)}const kb="hidden",Sb=8,Ab=3;var T;(function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET"})(T||(T={}));const _b={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Zc=new Set([l.TABLE,l.TBODY,l.TFOOT,l.THEAD,l.TR]),ru={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:dt,onParseError:null};class ed{constructor(t,n,r=null,s=null){this.fragmentContext=r,this.scriptHandler=s,this.currentToken=null,this.stopped=!1,this.insertionMode=T.INITIAL,this.originalInsertionMode=T.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...ru,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=n??this.treeAdapter.createDocument(),this.tokenizer=new K1(this.options,this),this.activeFormattingElements=new rb(this.treeAdapter),this.fragmentContextID=r?ys(this.treeAdapter.getTagName(r)):l.UNKNOWN,this._setContextModes(r??this.document,this.fragmentContextID),this.openElements=new nb(this.document,this.treeAdapter,this)}static parse(t,n){const r=new this(n);return r.tokenizer.write(t,!0),r.document}static getFragmentParser(t,n){const r={...ru,...n};t??(t=r.treeAdapter.createElement(y.TEMPLATE,w.HTML,[]));const s=r.treeAdapter.createElement("documentmock",w.HTML,[]),i=new this(r,s,t);return i.fragmentContextID===l.TEMPLATE&&i.tmplInsertionModeStack.unshift(T.IN_TEMPLATE),i._initTokenizerForFragmentParsing(),i._insertFakeRootElement(),i._resetInsertionMode(),i._findFormInFragmentContext(),i}getFragment(){const t=this.treeAdapter.getFirstChild(this.document),n=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,n),n}_err(t,n,r){var s;if(!this.onParseError)return;const i=(s=t.location)!==null&&s!==void 0?s:_b,o={code:n,startLine:i.startLine,startCol:i.startCol,startOffset:i.startOffset,endLine:r?i.startLine:i.endLine,endCol:r?i.startCol:i.endCol,endOffset:r?i.startOffset:i.endOffset};this.onParseError(o)}onItemPush(t,n,r){var s,i;(i=(s=this.treeAdapter).onItemPush)===null||i===void 0||i.call(s,t),r&&this.openElements.stackTop>0&&this._setContextModes(t,n)}onItemPop(t,n){var r,s;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(s=(r=this.treeAdapter).onItemPop)===null||s===void 0||s.call(r,t,this.openElements.current),n){let i,o;this.openElements.stackTop===0&&this.fragmentContext?(i=this.fragmentContext,o=this.fragmentContextID):{current:i,currentTagId:o}=this.openElements,this._setContextModes(i,o)}}_setContextModes(t,n){const r=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===w.HTML;this.currentNotInHTML=!r,this.tokenizer.inForeignNode=!r&&t!==void 0&&n!==void 0&&!this._isIntegrationPoint(n,t)}_switchToTextParsing(t,n){this._insertElement(t,w.HTML),this.tokenizer.state=n,this.originalInsertionMode=this.insertionMode,this.insertionMode=T.TEXT}switchToPlaintextParsing(){this.insertionMode=T.TEXT,this.originalInsertionMode=T.IN_BODY,this.tokenizer.state=ye.PLAINTEXT}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let t=this.fragmentContext;for(;t;){if(this.treeAdapter.getTagName(t)===y.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==w.HTML))switch(this.fragmentContextID){case l.TITLE:case l.TEXTAREA:{this.tokenizer.state=ye.RCDATA;break}case l.STYLE:case l.XMP:case l.IFRAME:case l.NOEMBED:case l.NOFRAMES:case l.NOSCRIPT:{this.tokenizer.state=ye.RAWTEXT;break}case l.SCRIPT:{this.tokenizer.state=ye.SCRIPT_DATA;break}case l.PLAINTEXT:{this.tokenizer.state=ye.PLAINTEXT;break}}}_setDocumentType(t){const n=t.name||"",r=t.publicId||"",s=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,n,r,s),t.location){const o=this.treeAdapter.getChildNodes(this.document).find(a=>this.treeAdapter.isDocumentTypeNode(a));o&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location)}}_attachElementToTree(t,n){if(this.options.sourceCodeLocationInfo){const r=n&&{...n,startTag:n};this.treeAdapter.setNodeSourceCodeLocation(t,r)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else{const r=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(r??this.document,t)}}_appendElement(t,n){const r=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(r,t.location)}_insertElement(t,n){const r=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(r,t.location),this.openElements.push(r,t.tagID)}_insertFakeElement(t,n){const r=this.treeAdapter.createElement(t,w.HTML,[]);this._attachElementToTree(r,null),this.openElements.push(r,n)}_insertTemplate(t){const n=this.treeAdapter.createElement(t.tagName,w.HTML,t.attrs),r=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(n,r),this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(r,null)}_insertFakeRootElement(){const t=this.treeAdapter.createElement(y.HTML,w.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,l.HTML)}_appendCommentNode(t,n){const r=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(n,r),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(r,t.location)}_insertCharacters(t){let n,r;if(this._shouldFosterParentOnInsertion()?({parent:n,beforeElement:r}=this._findFosterParentingLocation(),r?this.treeAdapter.insertTextBefore(n,t.chars,r):this.treeAdapter.insertText(n,t.chars)):(n=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(n,t.chars)),!t.location)return;const s=this.treeAdapter.getChildNodes(n),i=r?s.lastIndexOf(r):s.length,o=s[i-1];if(this.treeAdapter.getNodeSourceCodeLocation(o)){const{endLine:u,endCol:c,endOffset:d}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(o,{endLine:u,endCol:c,endOffset:d})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location)}_adoptNodes(t,n){for(let r=this.treeAdapter.getFirstChild(t);r;r=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(r),this.treeAdapter.appendChild(n,r)}_setEndLocation(t,n){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&n.location){const r=n.location,s=this.treeAdapter.getTagName(t),i=n.type===V.END_TAG&&s===n.tagName?{endTag:{...r},endLine:r.endLine,endCol:r.endCol,endOffset:r.endOffset}:{endLine:r.startLine,endCol:r.startCol,endOffset:r.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,i)}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return!1;let n,r;return this.openElements.stackTop===0&&this.fragmentContext?(n=this.fragmentContext,r=this.fragmentContextID):{current:n,currentTagId:r}=this.openElements,t.tagID===l.SVG&&this.treeAdapter.getTagName(n)===y.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(n)===w.MATHML?!1:this.tokenizer.inForeignNode||(t.tagID===l.MGLYPH||t.tagID===l.MALIGNMARK)&&r!==void 0&&!this._isIntegrationPoint(r,n,w.HTML)}_processToken(t){switch(t.type){case V.CHARACTER:{this.onCharacter(t);break}case V.NULL_CHARACTER:{this.onNullCharacter(t);break}case V.COMMENT:{this.onComment(t);break}case V.DOCTYPE:{this.onDoctype(t);break}case V.START_TAG:{this._processStartTag(t);break}case V.END_TAG:{this.onEndTag(t);break}case V.EOF:{this.onEof(t);break}case V.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,n,r){const s=this.treeAdapter.getNamespaceURI(n),i=this.treeAdapter.getAttrList(n);return Cb(t,s,i,r)}_reconstructActiveFormattingElements(){const t=this.activeFormattingElements.entries.length;if(t){const n=this.activeFormattingElements.entries.findIndex(s=>s.type===Ge.Marker||this.openElements.contains(s.element)),r=n===-1?t-1:n-1;for(let s=r;s>=0;s--){const i=this.activeFormattingElements.entries[s];this._insertElement(i.token,this.treeAdapter.getNamespaceURI(i.element)),i.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=T.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(l.P),this.openElements.popUntilTagNamePopped(l.P)}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case l.TR:{this.insertionMode=T.IN_ROW;return}case l.TBODY:case l.THEAD:case l.TFOOT:{this.insertionMode=T.IN_TABLE_BODY;return}case l.CAPTION:{this.insertionMode=T.IN_CAPTION;return}case l.COLGROUP:{this.insertionMode=T.IN_COLUMN_GROUP;return}case l.TABLE:{this.insertionMode=T.IN_TABLE;return}case l.BODY:{this.insertionMode=T.IN_BODY;return}case l.FRAMESET:{this.insertionMode=T.IN_FRAMESET;return}case l.SELECT:{this._resetInsertionModeForSelect(t);return}case l.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case l.HTML:{this.insertionMode=this.headElement?T.AFTER_HEAD:T.BEFORE_HEAD;return}case l.TD:case l.TH:{if(t>0){this.insertionMode=T.IN_CELL;return}break}case l.HEAD:{if(t>0){this.insertionMode=T.IN_HEAD;return}break}}this.insertionMode=T.IN_BODY}_resetInsertionModeForSelect(t){if(t>0)for(let n=t-1;n>0;n--){const r=this.openElements.tagIDs[n];if(r===l.TEMPLATE)break;if(r===l.TABLE){this.insertionMode=T.IN_SELECT_IN_TABLE;return}}this.insertionMode=T.IN_SELECT}_isElementCausesFosterParenting(t){return Zc.has(t)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let t=this.openElements.stackTop;t>=0;t--){const n=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case l.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(n)===w.HTML)return{parent:this.treeAdapter.getTemplateContent(n),beforeElement:null};break}case l.TABLE:{const r=this.treeAdapter.getParentNode(n);return r?{parent:r,beforeElement:n}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){const n=this._findFosterParentingLocation();n.beforeElement?this.treeAdapter.insertBefore(n.parent,t,n.beforeElement):this.treeAdapter.appendChild(n.parent,t)}_isSpecialElement(t,n){const r=this.treeAdapter.getNamespaceURI(t);return q1[r].has(n)}onCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){tT(this,t);return}switch(this.insertionMode){case T.INITIAL:{_n(this,t);break}case T.BEFORE_HTML:{vn(this,t);break}case T.BEFORE_HEAD:{Mn(this,t);break}case T.IN_HEAD:{Rn(this,t);break}case T.IN_HEAD_NO_SCRIPT:{Pn(this,t);break}case T.AFTER_HEAD:{Bn(this,t);break}case T.IN_BODY:case T.IN_CAPTION:case T.IN_CELL:case T.IN_TEMPLATE:{nd(this,t);break}case T.TEXT:case T.IN_SELECT:case T.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case T.IN_TABLE:case T.IN_TABLE_BODY:case T.IN_ROW:{Ks(this,t);break}case T.IN_TABLE_TEXT:{ud(this,t);break}case T.IN_COLUMN_GROUP:{Xr(this,t);break}case T.AFTER_BODY:{Qr(this,t);break}case T.AFTER_AFTER_BODY:{vr(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){eT(this,t);return}switch(this.insertionMode){case T.INITIAL:{_n(this,t);break}case T.BEFORE_HTML:{vn(this,t);break}case T.BEFORE_HEAD:{Mn(this,t);break}case T.IN_HEAD:{Rn(this,t);break}case T.IN_HEAD_NO_SCRIPT:{Pn(this,t);break}case T.AFTER_HEAD:{Bn(this,t);break}case T.TEXT:{this._insertCharacters(t);break}case T.IN_TABLE:case T.IN_TABLE_BODY:case T.IN_ROW:{Ks(this,t);break}case T.IN_COLUMN_GROUP:{Xr(this,t);break}case T.AFTER_BODY:{Qr(this,t);break}case T.AFTER_AFTER_BODY:{vr(this,t);break}}}onComment(t){if(this.skipNextNewLine=!1,this.currentNotInHTML){vi(this,t);return}switch(this.insertionMode){case T.INITIAL:case T.BEFORE_HTML:case T.BEFORE_HEAD:case T.IN_HEAD:case T.IN_HEAD_NO_SCRIPT:case T.AFTER_HEAD:case T.IN_BODY:case T.IN_TABLE:case T.IN_CAPTION:case T.IN_COLUMN_GROUP:case T.IN_TABLE_BODY:case T.IN_ROW:case T.IN_CELL:case T.IN_SELECT:case T.IN_SELECT_IN_TABLE:case T.IN_TEMPLATE:case T.IN_FRAMESET:case T.AFTER_FRAMESET:{vi(this,t);break}case T.IN_TABLE_TEXT:{wn(this,t);break}case T.AFTER_BODY:{Db(this,t);break}case T.AFTER_AFTER_BODY:case T.AFTER_AFTER_FRAMESET:{vb(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=!1,this.insertionMode){case T.INITIAL:{Mb(this,t);break}case T.BEFORE_HEAD:case T.IN_HEAD:case T.IN_HEAD_NO_SCRIPT:case T.AFTER_HEAD:{this._err(t,S.misplacedDoctype);break}case T.IN_TABLE_TEXT:{wn(this,t);break}}}onStartTag(t){this.skipNextNewLine=!1,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,S.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?nT(this,t):this._startTagOutsideForeignContent(t)}_startTagOutsideForeignContent(t){switch(this.insertionMode){case T.INITIAL:{_n(this,t);break}case T.BEFORE_HTML:{Rb(this,t);break}case T.BEFORE_HEAD:{Bb(this,t);break}case T.IN_HEAD:{Ye(this,t);break}case T.IN_HEAD_NO_SCRIPT:{Fb(this,t);break}case T.AFTER_HEAD:{Yb(this,t);break}case T.IN_BODY:{pe(this,t);break}case T.IN_TABLE:{pn(this,t);break}case T.IN_TABLE_TEXT:{wn(this,t);break}case T.IN_CAPTION:{UE(this,t);break}case T.IN_COLUMN_GROUP:{_o(this,t);break}case T.IN_TABLE_BODY:{Ss(this,t);break}case T.IN_ROW:{As(this,t);break}case T.IN_CELL:{VE(this,t);break}case T.IN_SELECT:{dd(this,t);break}case T.IN_SELECT_IN_TABLE:{$E(this,t);break}case T.IN_TEMPLATE:{qE(this,t);break}case T.AFTER_BODY:{WE(this,t);break}case T.IN_FRAMESET:{GE(this,t);break}case T.AFTER_FRAMESET:{XE(this,t);break}case T.AFTER_AFTER_BODY:{JE(this,t);break}case T.AFTER_AFTER_FRAMESET:{ZE(this,t);break}}}onEndTag(t){this.skipNextNewLine=!1,this.currentToken=t,this.currentNotInHTML?rT(this,t):this._endTagOutsideForeignContent(t)}_endTagOutsideForeignContent(t){switch(this.insertionMode){case T.INITIAL:{_n(this,t);break}case T.BEFORE_HTML:{Pb(this,t);break}case T.BEFORE_HEAD:{Ub(this,t);break}case T.IN_HEAD:{Hb(this,t);break}case T.IN_HEAD_NO_SCRIPT:{Vb(this,t);break}case T.AFTER_HEAD:{$b(this,t);break}case T.IN_BODY:{ks(this,t);break}case T.TEXT:{xE(this,t);break}case T.IN_TABLE:{Zn(this,t);break}case T.IN_TABLE_TEXT:{wn(this,t);break}case T.IN_CAPTION:{HE(this,t);break}case T.IN_COLUMN_GROUP:{FE(this,t);break}case T.IN_TABLE_BODY:{Mi(this,t);break}case T.IN_ROW:{cd(this,t);break}case T.IN_CELL:{YE(this,t);break}case T.IN_SELECT:{hd(this,t);break}case T.IN_SELECT_IN_TABLE:{jE(this,t);break}case T.IN_TEMPLATE:{zE(this,t);break}case T.AFTER_BODY:{pd(this,t);break}case T.IN_FRAMESET:{KE(this,t);break}case T.AFTER_FRAMESET:{QE(this,t);break}case T.AFTER_AFTER_BODY:{vr(this,t);break}}}onEof(t){switch(this.insertionMode){case T.INITIAL:{_n(this,t);break}case T.BEFORE_HTML:{vn(this,t);break}case T.BEFORE_HEAD:{Mn(this,t);break}case T.IN_HEAD:{Rn(this,t);break}case T.IN_HEAD_NO_SCRIPT:{Pn(this,t);break}case T.AFTER_HEAD:{Bn(this,t);break}case T.IN_BODY:case T.IN_TABLE:case T.IN_CAPTION:case T.IN_COLUMN_GROUP:case T.IN_TABLE_BODY:case T.IN_ROW:case T.IN_CELL:case T.IN_SELECT:case T.IN_SELECT_IN_TABLE:{od(this,t);break}case T.TEXT:{NE(this,t);break}case T.IN_TABLE_TEXT:{wn(this,t);break}case T.IN_TEMPLATE:{fd(this,t);break}case T.AFTER_BODY:case T.IN_FRAMESET:case T.AFTER_FRAMESET:case T.AFTER_AFTER_BODY:case T.AFTER_AFTER_FRAMESET:{Ao(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,t.chars.charCodeAt(0)===g.LINE_FEED)){if(t.chars.length===1)return;t.chars=t.chars.substr(1)}if(this.tokenizer.inForeignNode){this._insertCharacters(t);return}switch(this.insertionMode){case T.IN_HEAD:case T.IN_HEAD_NO_SCRIPT:case T.AFTER_HEAD:case T.TEXT:case T.IN_COLUMN_GROUP:case T.IN_SELECT:case T.IN_SELECT_IN_TABLE:case T.IN_FRAMESET:case T.AFTER_FRAMESET:{this._insertCharacters(t);break}case T.IN_BODY:case T.IN_CAPTION:case T.IN_CELL:case T.IN_TEMPLATE:case T.AFTER_BODY:case T.AFTER_AFTER_BODY:case T.AFTER_AFTER_FRAMESET:{td(this,t);break}case T.IN_TABLE:case T.IN_TABLE_BODY:case T.IN_ROW:{Ks(this,t);break}case T.IN_TABLE_TEXT:{ad(this,t);break}}}}function wb(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return n?e.openElements.contains(n.element)?e.openElements.hasInScope(t.tagID)||(n=null):(e.activeFormattingElements.removeEntry(n),n=null):id(e,t),n}function Ib(e,t){let n=null,r=e.openElements.stackTop;for(;r>=0;r--){const s=e.openElements.items[r];if(s===t.element)break;e._isSpecialElement(s,e.openElements.tagIDs[r])&&(n=s)}return n||(e.openElements.shortenToLength(Math.max(r,0)),e.activeFormattingElements.removeEntry(t)),n}function xb(e,t,n){let r=t,s=e.openElements.getCommonAncestor(t);for(let i=0,o=s;o!==n;i++,o=s){s=e.openElements.getCommonAncestor(o);const a=e.activeFormattingElements.getElementEntry(o),u=a&&i>=Ab;!a||u?(u&&e.activeFormattingElements.removeEntry(a),e.openElements.remove(o)):(o=Nb(e,a),r===t&&(e.activeFormattingElements.bookmark=a),e.treeAdapter.detachNode(r),e.treeAdapter.appendChild(o,r),r=o)}return r}function Nb(e,t){const n=e.treeAdapter.getNamespaceURI(t.element),r=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,r),t.element=r,r}function Lb(e,t,n){const r=e.treeAdapter.getTagName(t),s=ys(r);if(e._isElementCausesFosterParenting(s))e._fosterParentElement(n);else{const i=e.treeAdapter.getNamespaceURI(t);s===l.TEMPLATE&&i===w.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n)}}function Ob(e,t,n){const r=e.treeAdapter.getNamespaceURI(n.element),{token:s}=n,i=e.treeAdapter.createElement(s.tagName,r,s.attrs);e._adoptNodes(t,i),e.treeAdapter.appendChild(t,i),e.activeFormattingElements.insertElementAfterBookmark(i,s),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,i,s.tagID)}function So(e,t){for(let n=0;n<Sb;n++){const r=wb(e,t);if(!r)break;const s=Ib(e,r);if(!s)break;e.activeFormattingElements.bookmark=r;const i=xb(e,s,r.element),o=e.openElements.getCommonAncestor(r.element);e.treeAdapter.detachNode(i),o&&Lb(e,o,i),Ob(e,s,r)}}function vi(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function Db(e,t){e._appendCommentNode(t,e.openElements.items[0])}function vb(e,t){e._appendCommentNode(t,e.document)}function Ao(e,t){if(e.stopped=!0,t.location){const n=e.fragmentContext?0:2;for(let r=e.openElements.stackTop;r>=n;r--)e._setEndLocation(e.openElements.items[r],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){const r=e.openElements.items[0],s=e.treeAdapter.getNodeSourceCodeLocation(r);if(s&&!s.endTag&&(e._setEndLocation(r,t),e.openElements.stackTop>=1)){const i=e.openElements.items[1],o=e.treeAdapter.getNodeSourceCodeLocation(i);o&&!o.endTag&&e._setEndLocation(i,t)}}}}function Mb(e,t){e._setDocumentType(t);const n=t.forceQuirks?Oe.QUIRKS:cb(t);lb(t)||e._err(t,S.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=T.BEFORE_HTML}function _n(e,t){e._err(t,S.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,Oe.QUIRKS),e.insertionMode=T.BEFORE_HTML,e._processToken(t)}function Rb(e,t){t.tagID===l.HTML?(e._insertElement(t,w.HTML),e.insertionMode=T.BEFORE_HEAD):vn(e,t)}function Pb(e,t){const n=t.tagID;(n===l.HTML||n===l.HEAD||n===l.BODY||n===l.BR)&&vn(e,t)}function vn(e,t){e._insertFakeRootElement(),e.insertionMode=T.BEFORE_HEAD,e._processToken(t)}function Bb(e,t){switch(t.tagID){case l.HTML:{pe(e,t);break}case l.HEAD:{e._insertElement(t,w.HTML),e.headElement=e.openElements.current,e.insertionMode=T.IN_HEAD;break}default:Mn(e,t)}}function Ub(e,t){const n=t.tagID;n===l.HEAD||n===l.BODY||n===l.HTML||n===l.BR?Mn(e,t):e._err(t,S.endTagWithoutMatchingOpenElement)}function Mn(e,t){e._insertFakeElement(y.HEAD,l.HEAD),e.headElement=e.openElements.current,e.insertionMode=T.IN_HEAD,e._processToken(t)}function Ye(e,t){switch(t.tagID){case l.HTML:{pe(e,t);break}case l.BASE:case l.BASEFONT:case l.BGSOUND:case l.LINK:case l.META:{e._appendElement(t,w.HTML),t.ackSelfClosing=!0;break}case l.TITLE:{e._switchToTextParsing(t,ye.RCDATA);break}case l.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,ye.RAWTEXT):(e._insertElement(t,w.HTML),e.insertionMode=T.IN_HEAD_NO_SCRIPT);break}case l.NOFRAMES:case l.STYLE:{e._switchToTextParsing(t,ye.RAWTEXT);break}case l.SCRIPT:{e._switchToTextParsing(t,ye.SCRIPT_DATA);break}case l.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=T.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(T.IN_TEMPLATE);break}case l.HEAD:{e._err(t,S.misplacedStartTagForHeadElement);break}default:Rn(e,t)}}function Hb(e,t){switch(t.tagID){case l.HEAD:{e.openElements.pop(),e.insertionMode=T.AFTER_HEAD;break}case l.BODY:case l.BR:case l.HTML:{Rn(e,t);break}case l.TEMPLATE:{jt(e,t);break}default:e._err(t,S.endTagWithoutMatchingOpenElement)}}function jt(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==l.TEMPLATE&&e._err(t,S.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(l.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,S.endTagWithoutMatchingOpenElement)}function Rn(e,t){e.openElements.pop(),e.insertionMode=T.AFTER_HEAD,e._processToken(t)}function Fb(e,t){switch(t.tagID){case l.HTML:{pe(e,t);break}case l.BASEFONT:case l.BGSOUND:case l.HEAD:case l.LINK:case l.META:case l.NOFRAMES:case l.STYLE:{Ye(e,t);break}case l.NOSCRIPT:{e._err(t,S.nestedNoscriptInHead);break}default:Pn(e,t)}}function Vb(e,t){switch(t.tagID){case l.NOSCRIPT:{e.openElements.pop(),e.insertionMode=T.IN_HEAD;break}case l.BR:{Pn(e,t);break}default:e._err(t,S.endTagWithoutMatchingOpenElement)}}function Pn(e,t){const n=t.type===V.EOF?S.openElementsLeftAfterEof:S.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=T.IN_HEAD,e._processToken(t)}function Yb(e,t){switch(t.tagID){case l.HTML:{pe(e,t);break}case l.BODY:{e._insertElement(t,w.HTML),e.framesetOk=!1,e.insertionMode=T.IN_BODY;break}case l.FRAMESET:{e._insertElement(t,w.HTML),e.insertionMode=T.IN_FRAMESET;break}case l.BASE:case l.BASEFONT:case l.BGSOUND:case l.LINK:case l.META:case l.NOFRAMES:case l.SCRIPT:case l.STYLE:case l.TEMPLATE:case l.TITLE:{e._err(t,S.abandonedHeadElementChild),e.openElements.push(e.headElement,l.HEAD),Ye(e,t),e.openElements.remove(e.headElement);break}case l.HEAD:{e._err(t,S.misplacedStartTagForHeadElement);break}default:Bn(e,t)}}function $b(e,t){switch(t.tagID){case l.BODY:case l.HTML:case l.BR:{Bn(e,t);break}case l.TEMPLATE:{jt(e,t);break}default:e._err(t,S.endTagWithoutMatchingOpenElement)}}function Bn(e,t){e._insertFakeElement(y.BODY,l.BODY),e.insertionMode=T.IN_BODY,Cs(e,t)}function Cs(e,t){switch(t.type){case V.CHARACTER:{nd(e,t);break}case V.WHITESPACE_CHARACTER:{td(e,t);break}case V.COMMENT:{vi(e,t);break}case V.START_TAG:{pe(e,t);break}case V.END_TAG:{ks(e,t);break}case V.EOF:{od(e,t);break}}}function td(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function nd(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function jb(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function qb(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(n,t.attrs))}function zb(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,w.HTML),e.insertionMode=T.IN_FRAMESET)}function Wb(e,t){e.openElements.hasInButtonScope(l.P)&&e._closePElement(),e._insertElement(t,w.HTML)}function Gb(e,t){e.openElements.hasInButtonScope(l.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&Di.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,w.HTML)}function Kb(e,t){e.openElements.hasInButtonScope(l.P)&&e._closePElement(),e._insertElement(t,w.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function Xb(e,t){const n=e.openElements.tmplCount>0;(!e.formElement||n)&&(e.openElements.hasInButtonScope(l.P)&&e._closePElement(),e._insertElement(t,w.HTML),n||(e.formElement=e.openElements.current))}function Qb(e,t){e.framesetOk=!1;const n=t.tagID;for(let r=e.openElements.stackTop;r>=0;r--){const s=e.openElements.tagIDs[r];if(n===l.LI&&s===l.LI||(n===l.DD||n===l.DT)&&(s===l.DD||s===l.DT)){e.openElements.generateImpliedEndTagsWithExclusion(s),e.openElements.popUntilTagNamePopped(s);break}if(s!==l.ADDRESS&&s!==l.DIV&&s!==l.P&&e._isSpecialElement(e.openElements.items[r],s))break}e.openElements.hasInButtonScope(l.P)&&e._closePElement(),e._insertElement(t,w.HTML)}function Jb(e,t){e.openElements.hasInButtonScope(l.P)&&e._closePElement(),e._insertElement(t,w.HTML),e.tokenizer.state=ye.PLAINTEXT}function Zb(e,t){e.openElements.hasInScope(l.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(l.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,w.HTML),e.framesetOk=!1}function eE(e,t){const n=e.activeFormattingElements.getElementEntryInScopeWithTagName(y.A);n&&(So(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,w.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function tE(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,w.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function nE(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(l.NOBR)&&(So(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,w.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function rE(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,w.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function sE(e,t){e.treeAdapter.getDocumentMode(e.document)!==Oe.QUIRKS&&e.openElements.hasInButtonScope(l.P)&&e._closePElement(),e._insertElement(t,w.HTML),e.framesetOk=!1,e.insertionMode=T.IN_TABLE}function rd(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,w.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function sd(e){const t=qc(e,Dt.TYPE);return t!=null&&t.toLowerCase()===kb}function iE(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,w.HTML),sd(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function oE(e,t){e._appendElement(t,w.HTML),t.ackSelfClosing=!0}function aE(e,t){e.openElements.hasInButtonScope(l.P)&&e._closePElement(),e._appendElement(t,w.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function uE(e,t){t.tagName=y.IMG,t.tagID=l.IMG,rd(e,t)}function lE(e,t){e._insertElement(t,w.HTML),e.skipNextNewLine=!0,e.tokenizer.state=ye.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=T.TEXT}function cE(e,t){e.openElements.hasInButtonScope(l.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,ye.RAWTEXT)}function dE(e,t){e.framesetOk=!1,e._switchToTextParsing(t,ye.RAWTEXT)}function su(e,t){e._switchToTextParsing(t,ye.RAWTEXT)}function hE(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,w.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===T.IN_TABLE||e.insertionMode===T.IN_CAPTION||e.insertionMode===T.IN_TABLE_BODY||e.insertionMode===T.IN_ROW||e.insertionMode===T.IN_CELL?T.IN_SELECT_IN_TABLE:T.IN_SELECT}function fE(e,t){e.openElements.currentTagId===l.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,w.HTML)}function pE(e,t){e.openElements.hasInScope(l.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,w.HTML)}function mE(e,t){e.openElements.hasInScope(l.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(l.RTC),e._insertElement(t,w.HTML)}function gE(e,t){e._reconstructActiveFormattingElements(),Qc(t),ko(t),t.selfClosing?e._appendElement(t,w.MATHML):e._insertElement(t,w.MATHML),t.ackSelfClosing=!0}function bE(e,t){e._reconstructActiveFormattingElements(),Jc(t),ko(t),t.selfClosing?e._appendElement(t,w.SVG):e._insertElement(t,w.SVG),t.ackSelfClosing=!0}function iu(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,w.HTML)}function pe(e,t){switch(t.tagID){case l.I:case l.S:case l.B:case l.U:case l.EM:case l.TT:case l.BIG:case l.CODE:case l.FONT:case l.SMALL:case l.STRIKE:case l.STRONG:{tE(e,t);break}case l.A:{eE(e,t);break}case l.H1:case l.H2:case l.H3:case l.H4:case l.H5:case l.H6:{Gb(e,t);break}case l.P:case l.DL:case l.OL:case l.UL:case l.DIV:case l.DIR:case l.NAV:case l.MAIN:case l.MENU:case l.ASIDE:case l.CENTER:case l.FIGURE:case l.FOOTER:case l.HEADER:case l.HGROUP:case l.DIALOG:case l.DETAILS:case l.ADDRESS:case l.ARTICLE:case l.SEARCH:case l.SECTION:case l.SUMMARY:case l.FIELDSET:case l.BLOCKQUOTE:case l.FIGCAPTION:{Wb(e,t);break}case l.LI:case l.DD:case l.DT:{Qb(e,t);break}case l.BR:case l.IMG:case l.WBR:case l.AREA:case l.EMBED:case l.KEYGEN:{rd(e,t);break}case l.HR:{aE(e,t);break}case l.RB:case l.RTC:{pE(e,t);break}case l.RT:case l.RP:{mE(e,t);break}case l.PRE:case l.LISTING:{Kb(e,t);break}case l.XMP:{cE(e,t);break}case l.SVG:{bE(e,t);break}case l.HTML:{jb(e,t);break}case l.BASE:case l.LINK:case l.META:case l.STYLE:case l.TITLE:case l.SCRIPT:case l.BGSOUND:case l.BASEFONT:case l.TEMPLATE:{Ye(e,t);break}case l.BODY:{qb(e,t);break}case l.FORM:{Xb(e,t);break}case l.NOBR:{nE(e,t);break}case l.MATH:{gE(e,t);break}case l.TABLE:{sE(e,t);break}case l.INPUT:{iE(e,t);break}case l.PARAM:case l.TRACK:case l.SOURCE:{oE(e,t);break}case l.IMAGE:{uE(e,t);break}case l.BUTTON:{Zb(e,t);break}case l.APPLET:case l.OBJECT:case l.MARQUEE:{rE(e,t);break}case l.IFRAME:{dE(e,t);break}case l.SELECT:{hE(e,t);break}case l.OPTION:case l.OPTGROUP:{fE(e,t);break}case l.NOEMBED:case l.NOFRAMES:{su(e,t);break}case l.FRAMESET:{zb(e,t);break}case l.TEXTAREA:{lE(e,t);break}case l.NOSCRIPT:{e.options.scriptingEnabled?su(e,t):iu(e,t);break}case l.PLAINTEXT:{Jb(e,t);break}case l.COL:case l.TH:case l.TD:case l.TR:case l.HEAD:case l.FRAME:case l.TBODY:case l.TFOOT:case l.THEAD:case l.CAPTION:case l.COLGROUP:break;default:iu(e,t)}}function EE(e,t){if(e.openElements.hasInScope(l.BODY)&&(e.insertionMode=T.AFTER_BODY,e.options.sourceCodeLocationInfo)){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t)}}function TE(e,t){e.openElements.hasInScope(l.BODY)&&(e.insertionMode=T.AFTER_BODY,pd(e,t))}function yE(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n))}function CE(e){const t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(l.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(l.FORM):n&&e.openElements.remove(n))}function kE(e){e.openElements.hasInButtonScope(l.P)||e._insertFakeElement(y.P,l.P),e._closePElement()}function SE(e){e.openElements.hasInListItemScope(l.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(l.LI),e.openElements.popUntilTagNamePopped(l.LI))}function AE(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n))}function _E(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function wE(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker())}function IE(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(y.BR,l.BR),e.openElements.pop(),e.framesetOk=!1}function id(e,t){const n=t.tagName,r=t.tagID;for(let s=e.openElements.stackTop;s>0;s--){const i=e.openElements.items[s],o=e.openElements.tagIDs[s];if(r===o&&(r!==l.UNKNOWN||e.treeAdapter.getTagName(i)===n)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.stackTop>=s&&e.openElements.shortenToLength(s);break}if(e._isSpecialElement(i,o))break}}function ks(e,t){switch(t.tagID){case l.A:case l.B:case l.I:case l.S:case l.U:case l.EM:case l.TT:case l.BIG:case l.CODE:case l.FONT:case l.NOBR:case l.SMALL:case l.STRIKE:case l.STRONG:{So(e,t);break}case l.P:{kE(e);break}case l.DL:case l.UL:case l.OL:case l.DIR:case l.DIV:case l.NAV:case l.PRE:case l.MAIN:case l.MENU:case l.ASIDE:case l.BUTTON:case l.CENTER:case l.FIGURE:case l.FOOTER:case l.HEADER:case l.HGROUP:case l.DIALOG:case l.ADDRESS:case l.ARTICLE:case l.DETAILS:case l.SEARCH:case l.SECTION:case l.SUMMARY:case l.LISTING:case l.FIELDSET:case l.BLOCKQUOTE:case l.FIGCAPTION:{yE(e,t);break}case l.LI:{SE(e);break}case l.DD:case l.DT:{AE(e,t);break}case l.H1:case l.H2:case l.H3:case l.H4:case l.H5:case l.H6:{_E(e);break}case l.BR:{IE(e);break}case l.BODY:{EE(e,t);break}case l.HTML:{TE(e,t);break}case l.FORM:{CE(e);break}case l.APPLET:case l.OBJECT:case l.MARQUEE:{wE(e,t);break}case l.TEMPLATE:{jt(e,t);break}default:id(e,t)}}function od(e,t){e.tmplInsertionModeStack.length>0?fd(e,t):Ao(e,t)}function xE(e,t){var n;t.tagID===l.SCRIPT&&((n=e.scriptHandler)===null||n===void 0||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function NE(e,t){e._err(t,S.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function Ks(e,t){if(e.openElements.currentTagId!==void 0&&Zc.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=T.IN_TABLE_TEXT,t.type){case V.CHARACTER:{ud(e,t);break}case V.WHITESPACE_CHARACTER:{ad(e,t);break}}else ur(e,t)}function LE(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,w.HTML),e.insertionMode=T.IN_CAPTION}function OE(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,w.HTML),e.insertionMode=T.IN_COLUMN_GROUP}function DE(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(y.COLGROUP,l.COLGROUP),e.insertionMode=T.IN_COLUMN_GROUP,_o(e,t)}function vE(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,w.HTML),e.insertionMode=T.IN_TABLE_BODY}function ME(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(y.TBODY,l.TBODY),e.insertionMode=T.IN_TABLE_BODY,Ss(e,t)}function RE(e,t){e.openElements.hasInTableScope(l.TABLE)&&(e.openElements.popUntilTagNamePopped(l.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function PE(e,t){sd(t)?e._appendElement(t,w.HTML):ur(e,t),t.ackSelfClosing=!0}function BE(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,w.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function pn(e,t){switch(t.tagID){case l.TD:case l.TH:case l.TR:{ME(e,t);break}case l.STYLE:case l.SCRIPT:case l.TEMPLATE:{Ye(e,t);break}case l.COL:{DE(e,t);break}case l.FORM:{BE(e,t);break}case l.TABLE:{RE(e,t);break}case l.TBODY:case l.TFOOT:case l.THEAD:{vE(e,t);break}case l.INPUT:{PE(e,t);break}case l.CAPTION:{LE(e,t);break}case l.COLGROUP:{OE(e,t);break}default:ur(e,t)}}function Zn(e,t){switch(t.tagID){case l.TABLE:{e.openElements.hasInTableScope(l.TABLE)&&(e.openElements.popUntilTagNamePopped(l.TABLE),e._resetInsertionMode());break}case l.TEMPLATE:{jt(e,t);break}case l.BODY:case l.CAPTION:case l.COL:case l.COLGROUP:case l.HTML:case l.TBODY:case l.TD:case l.TFOOT:case l.TH:case l.THEAD:case l.TR:break;default:ur(e,t)}}function ur(e,t){const n=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,Cs(e,t),e.fosterParentingEnabled=n}function ad(e,t){e.pendingCharacterTokens.push(t)}function ud(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function wn(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)ur(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}const ld=new Set([l.CAPTION,l.COL,l.COLGROUP,l.TBODY,l.TD,l.TFOOT,l.TH,l.THEAD,l.TR]);function UE(e,t){const n=t.tagID;ld.has(n)?e.openElements.hasInTableScope(l.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(l.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=T.IN_TABLE,pn(e,t)):pe(e,t)}function HE(e,t){const n=t.tagID;switch(n){case l.CAPTION:case l.TABLE:{e.openElements.hasInTableScope(l.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(l.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=T.IN_TABLE,n===l.TABLE&&Zn(e,t));break}case l.BODY:case l.COL:case l.COLGROUP:case l.HTML:case l.TBODY:case l.TD:case l.TFOOT:case l.TH:case l.THEAD:case l.TR:break;default:ks(e,t)}}function _o(e,t){switch(t.tagID){case l.HTML:{pe(e,t);break}case l.COL:{e._appendElement(t,w.HTML),t.ackSelfClosing=!0;break}case l.TEMPLATE:{Ye(e,t);break}default:Xr(e,t)}}function FE(e,t){switch(t.tagID){case l.COLGROUP:{e.openElements.currentTagId===l.COLGROUP&&(e.openElements.pop(),e.insertionMode=T.IN_TABLE);break}case l.TEMPLATE:{jt(e,t);break}case l.COL:break;default:Xr(e,t)}}function Xr(e,t){e.openElements.currentTagId===l.COLGROUP&&(e.openElements.pop(),e.insertionMode=T.IN_TABLE,e._processToken(t))}function Ss(e,t){switch(t.tagID){case l.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,w.HTML),e.insertionMode=T.IN_ROW;break}case l.TH:case l.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(y.TR,l.TR),e.insertionMode=T.IN_ROW,As(e,t);break}case l.CAPTION:case l.COL:case l.COLGROUP:case l.TBODY:case l.TFOOT:case l.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE,pn(e,t));break}default:pn(e,t)}}function Mi(e,t){const n=t.tagID;switch(t.tagID){case l.TBODY:case l.TFOOT:case l.THEAD:{e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE);break}case l.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE,Zn(e,t));break}case l.BODY:case l.CAPTION:case l.COL:case l.COLGROUP:case l.HTML:case l.TD:case l.TH:case l.TR:break;default:Zn(e,t)}}function As(e,t){switch(t.tagID){case l.TH:case l.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,w.HTML),e.insertionMode=T.IN_CELL,e.activeFormattingElements.insertMarker();break}case l.CAPTION:case l.COL:case l.COLGROUP:case l.TBODY:case l.TFOOT:case l.THEAD:case l.TR:{e.openElements.hasInTableScope(l.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE_BODY,Ss(e,t));break}default:pn(e,t)}}function cd(e,t){switch(t.tagID){case l.TR:{e.openElements.hasInTableScope(l.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE_BODY);break}case l.TABLE:{e.openElements.hasInTableScope(l.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE_BODY,Mi(e,t));break}case l.TBODY:case l.TFOOT:case l.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(l.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE_BODY,Mi(e,t));break}case l.BODY:case l.CAPTION:case l.COL:case l.COLGROUP:case l.HTML:case l.TD:case l.TH:break;default:Zn(e,t)}}function VE(e,t){const n=t.tagID;ld.has(n)?(e.openElements.hasInTableScope(l.TD)||e.openElements.hasInTableScope(l.TH))&&(e._closeTableCell(),As(e,t)):pe(e,t)}function YE(e,t){const n=t.tagID;switch(n){case l.TD:case l.TH:{e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=T.IN_ROW);break}case l.TABLE:case l.TBODY:case l.TFOOT:case l.THEAD:case l.TR:{e.openElements.hasInTableScope(n)&&(e._closeTableCell(),cd(e,t));break}case l.BODY:case l.CAPTION:case l.COL:case l.COLGROUP:case l.HTML:break;default:ks(e,t)}}function dd(e,t){switch(t.tagID){case l.HTML:{pe(e,t);break}case l.OPTION:{e.openElements.currentTagId===l.OPTION&&e.openElements.pop(),e._insertElement(t,w.HTML);break}case l.OPTGROUP:{e.openElements.currentTagId===l.OPTION&&e.openElements.pop(),e.openElements.currentTagId===l.OPTGROUP&&e.openElements.pop(),e._insertElement(t,w.HTML);break}case l.HR:{e.openElements.currentTagId===l.OPTION&&e.openElements.pop(),e.openElements.currentTagId===l.OPTGROUP&&e.openElements.pop(),e._appendElement(t,w.HTML),t.ackSelfClosing=!0;break}case l.INPUT:case l.KEYGEN:case l.TEXTAREA:case l.SELECT:{e.openElements.hasInSelectScope(l.SELECT)&&(e.openElements.popUntilTagNamePopped(l.SELECT),e._resetInsertionMode(),t.tagID!==l.SELECT&&e._processStartTag(t));break}case l.SCRIPT:case l.TEMPLATE:{Ye(e,t);break}}}function hd(e,t){switch(t.tagID){case l.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===l.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===l.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===l.OPTGROUP&&e.openElements.pop();break}case l.OPTION:{e.openElements.currentTagId===l.OPTION&&e.openElements.pop();break}case l.SELECT:{e.openElements.hasInSelectScope(l.SELECT)&&(e.openElements.popUntilTagNamePopped(l.SELECT),e._resetInsertionMode());break}case l.TEMPLATE:{jt(e,t);break}}}function $E(e,t){const n=t.tagID;n===l.CAPTION||n===l.TABLE||n===l.TBODY||n===l.TFOOT||n===l.THEAD||n===l.TR||n===l.TD||n===l.TH?(e.openElements.popUntilTagNamePopped(l.SELECT),e._resetInsertionMode(),e._processStartTag(t)):dd(e,t)}function jE(e,t){const n=t.tagID;n===l.CAPTION||n===l.TABLE||n===l.TBODY||n===l.TFOOT||n===l.THEAD||n===l.TR||n===l.TD||n===l.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(l.SELECT),e._resetInsertionMode(),e.onEndTag(t)):hd(e,t)}function qE(e,t){switch(t.tagID){case l.BASE:case l.BASEFONT:case l.BGSOUND:case l.LINK:case l.META:case l.NOFRAMES:case l.SCRIPT:case l.STYLE:case l.TEMPLATE:case l.TITLE:{Ye(e,t);break}case l.CAPTION:case l.COLGROUP:case l.TBODY:case l.TFOOT:case l.THEAD:{e.tmplInsertionModeStack[0]=T.IN_TABLE,e.insertionMode=T.IN_TABLE,pn(e,t);break}case l.COL:{e.tmplInsertionModeStack[0]=T.IN_COLUMN_GROUP,e.insertionMode=T.IN_COLUMN_GROUP,_o(e,t);break}case l.TR:{e.tmplInsertionModeStack[0]=T.IN_TABLE_BODY,e.insertionMode=T.IN_TABLE_BODY,Ss(e,t);break}case l.TD:case l.TH:{e.tmplInsertionModeStack[0]=T.IN_ROW,e.insertionMode=T.IN_ROW,As(e,t);break}default:e.tmplInsertionModeStack[0]=T.IN_BODY,e.insertionMode=T.IN_BODY,pe(e,t)}}function zE(e,t){t.tagID===l.TEMPLATE&&jt(e,t)}function fd(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(l.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):Ao(e,t)}function WE(e,t){t.tagID===l.HTML?pe(e,t):Qr(e,t)}function pd(e,t){var n;if(t.tagID===l.HTML){if(e.fragmentContext||(e.insertionMode=T.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===l.HTML){e._setEndLocation(e.openElements.items[0],t);const r=e.openElements.items[1];r&&!(!((n=e.treeAdapter.getNodeSourceCodeLocation(r))===null||n===void 0)&&n.endTag)&&e._setEndLocation(r,t)}}else Qr(e,t)}function Qr(e,t){e.insertionMode=T.IN_BODY,Cs(e,t)}function GE(e,t){switch(t.tagID){case l.HTML:{pe(e,t);break}case l.FRAMESET:{e._insertElement(t,w.HTML);break}case l.FRAME:{e._appendElement(t,w.HTML),t.ackSelfClosing=!0;break}case l.NOFRAMES:{Ye(e,t);break}}}function KE(e,t){t.tagID===l.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==l.FRAMESET&&(e.insertionMode=T.AFTER_FRAMESET))}function XE(e,t){switch(t.tagID){case l.HTML:{pe(e,t);break}case l.NOFRAMES:{Ye(e,t);break}}}function QE(e,t){t.tagID===l.HTML&&(e.insertionMode=T.AFTER_AFTER_FRAMESET)}function JE(e,t){t.tagID===l.HTML?pe(e,t):vr(e,t)}function vr(e,t){e.insertionMode=T.IN_BODY,Cs(e,t)}function ZE(e,t){switch(t.tagID){case l.HTML:{pe(e,t);break}case l.NOFRAMES:{Ye(e,t);break}}}function eT(e,t){t.chars=K,e._insertCharacters(t)}function tT(e,t){e._insertCharacters(t),e.framesetOk=!1}function md(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==w.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function nT(e,t){if(bb(t))md(e),e._startTagOutsideForeignContent(t);else{const n=e._getAdjustedCurrentElement(),r=e.treeAdapter.getNamespaceURI(n);r===w.MATHML?Qc(t):r===w.SVG&&(Eb(t),Jc(t)),ko(t),t.selfClosing?e._appendElement(t,r):e._insertElement(t,r),t.ackSelfClosing=!0}}function rT(e,t){if(t.tagID===l.P||t.tagID===l.BR){md(e),e._endTagOutsideForeignContent(t);return}for(let n=e.openElements.stackTop;n>0;n--){const r=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(r)===w.HTML){e._endTagOutsideForeignContent(t);break}const s=e.treeAdapter.getTagName(r);if(s.toLowerCase()===t.tagName){t.tagName=s,e.openElements.shortenToLength(n);break}}}y.AREA,y.BASE,y.BASEFONT,y.BGSOUND,y.BR,y.COL,y.EMBED,y.FRAME,y.HR,y.IMG,y.INPUT,y.KEYGEN,y.LINK,y.META,y.PARAM,y.SOURCE,y.TRACK,y.WBR;function sT(e,t){return ed.parse(e,t)}function iT(e,t,n){typeof e=="string"&&(n=t,t=e,e=null);const r=ed.getFragmentParser(e,n);return r.tokenizer.write(t,!0),r.getFragment()}function oT(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?ou(e.position):"start"in e||"end"in e?ou(e):"line"in e||"column"in e?Ri(e):""}function Ri(e){return au(e&&e.line)+":"+au(e&&e.column)}function ou(e){return Ri(e&&e.start)+"-"+Ri(e&&e.end)}function au(e){return e&&typeof e=="number"?e:1}class ge extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let s="",i={},o=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?s=t:!i.cause&&t&&(o=!0,s=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const u=r.indexOf(":");u===-1?i.ruleId=r:(i.source=r.slice(0,u),i.ruleId=r.slice(u+1))}if(!i.place&&i.ancestors&&i.ancestors){const u=i.ancestors[i.ancestors.length-1];u&&(i.place=u.position)}const a=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=s,this.line=a?a.line:void 0,this.name=oT(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=o&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}ge.prototype.file="";ge.prototype.name="";ge.prototype.reason="";ge.prototype.message="";ge.prototype.stack="";ge.prototype.column=void 0;ge.prototype.line=void 0;ge.prototype.ancestors=void 0;ge.prototype.cause=void 0;ge.prototype.fatal=void 0;ge.prototype.place=void 0;ge.prototype.ruleId=void 0;ge.prototype.source=void 0;const We={basename:aT,dirname:uT,extname:lT,join:cT,sep:"/"};function aT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');lr(e);let n=0,r=-1,s=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else r<0&&(i=!0,r=s+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let o=-1,a=t.length-1;for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else o<0&&(i=!0,o=s+1),a>-1&&(e.codePointAt(s)===t.codePointAt(a--)?a<0&&(r=s):(a=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function uT(e){if(lr(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function lT(e){lr(e);let t=e.length,n=-1,r=0,s=-1,i=0,o;for(;t--;){const a=e.codePointAt(t);if(a===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),a===46?s<0?s=t:i!==1&&(i=1):s>-1&&(i=-1)}return s<0||n<0||i===0||i===1&&s===n-1&&s===r+1?"":e.slice(s,n)}function cT(...e){let t=-1,n;for(;++t<e.length;)lr(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":dT(n)}function dT(e){lr(e);const t=e.codePointAt(0)===47;let n=hT(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function hT(e,t){let n="",r=0,s=-1,i=0,o=-1,a,u;for(;++o<=e.length;){if(o<e.length)a=e.codePointAt(o);else{if(a===47)break;a=47}if(a===47){if(!(s===o-1||i===1))if(s!==o-1&&i===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(u=n.lastIndexOf("/"),u!==n.length-1){u<0?(n="",r=0):(n=n.slice(0,u),r=n.length-1-n.lastIndexOf("/")),s=o,i=0;continue}}else if(n.length>0){n="",r=0,s=o,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(s+1,o):n=e.slice(s+1,o),r=o-s-1;s=o,i=0}else a===46&&i>-1?i++:i=-1}return n}function lr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const fT={cwd:pT};function pT(){return"/"}function Pi(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function mT(e){if(typeof e=="string")e=new URL(e);else if(!Pi(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return gT(e)}function gT(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const s=new TypeError("File URL path must not include encoded / characters");throw s.code="ERR_INVALID_FILE_URL_PATH",s}}return decodeURIComponent(t)}const Xs=["history","path","basename","stem","extname","dirname"];class uu{constructor(t){let n;t?Pi(t)?n={path:t}:typeof t=="string"||bT(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":fT.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Xs.length;){const i=Xs[r];i in n&&n[i]!==void 0&&n[i]!==null&&(this[i]=i==="history"?[...n[i]]:n[i])}let s;for(s in n)Xs.includes(s)||(this[s]=n[s])}get basename(){return typeof this.path=="string"?We.basename(this.path):void 0}set basename(t){Js(t,"basename"),Qs(t,"basename"),this.path=We.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?We.dirname(this.path):void 0}set dirname(t){lu(this.basename,"dirname"),this.path=We.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?We.extname(this.path):void 0}set extname(t){if(Qs(t,"extname"),lu(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=We.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Pi(t)&&(t=mT(t)),Js(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?We.basename(this.path,this.extname):void 0}set stem(t){Js(t,"stem"),Qs(t,"stem"),this.path=We.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const s=this.message(t,n,r);throw s.fatal=!0,s}info(t,n,r){const s=this.message(t,n,r);return s.fatal=void 0,s}message(t,n,r){const s=new ge(t,n,r);return this.path&&(s.name=this.path+":"+s.name,s.file=this.path),s.fatal=!1,this.messages.push(s),s}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Qs(e,t){if(e&&e.includes(We.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+We.sep+"`")}function Js(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function lu(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function bT(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const ET={abandonedHeadElementChild:{reason:"Unexpected metadata element after head",description:"Unexpected element after head. Expected the element before `</head>`",url:!1},abruptClosingOfEmptyComment:{reason:"Unexpected abruptly closed empty comment",description:"Unexpected `>` or `->`. Expected `-->` to close comments"},abruptDoctypePublicIdentifier:{reason:"Unexpected abruptly closed public identifier",description:"Unexpected `>`. Expected a closing `\"` or `'` after the public identifier"},abruptDoctypeSystemIdentifier:{reason:"Unexpected abruptly closed system identifier",description:"Unexpected `>`. Expected a closing `\"` or `'` after the identifier identifier"},absenceOfDigitsInNumericCharacterReference:{reason:"Unexpected non-digit at start of numeric character reference",description:"Unexpected `%c`. Expected `[0-9]` for decimal references or `[0-9a-fA-F]` for hexadecimal references"},cdataInHtmlContent:{reason:"Unexpected CDATA section in HTML",description:"Unexpected `<![CDATA[` in HTML. Remove it, use a comment, or encode special characters instead"},characterReferenceOutsideUnicodeRange:{reason:"Unexpected too big numeric character reference",description:"Unexpectedly high character reference. Expected character references to be at most hexadecimal 10ffff (or decimal 1114111)"},closingOfElementWithOpenChildElements:{reason:"Unexpected closing tag with open child elements",description:"Unexpectedly closing tag. Expected other tags to be closed first",url:!1},controlCharacterInInputStream:{reason:"Unexpected control character",description:"Unexpected control character `%x`. Expected a non-control code point, 0x00, or ASCII whitespace"},controlCharacterReference:{reason:"Unexpected control character reference",description:"Unexpectedly control character in reference. Expected a non-control code point, 0x00, or ASCII whitespace"},disallowedContentInNoscriptInHead:{reason:"Disallowed content inside `<noscript>` in `<head>`",description:"Unexpected text character `%c`. Only use text in `<noscript>`s in `<body>`",url:!1},duplicateAttribute:{reason:"Unexpected duplicate attribute",description:"Unexpectedly double attribute. Expected attributes to occur only once"},endTagWithAttributes:{reason:"Unexpected attribute on closing tag",description:"Unexpected attribute. Expected `>` instead"},endTagWithTrailingSolidus:{reason:"Unexpected slash at end of closing tag",description:"Unexpected `%c-1`. Expected `>` instead"},endTagWithoutMatchingOpenElement:{reason:"Unexpected unopened end tag",description:"Unexpected end tag. Expected no end tag or another end tag",url:!1},eofBeforeTagName:{reason:"Unexpected end of file",description:"Unexpected end of file. Expected tag name instead"},eofInCdata:{reason:"Unexpected end of file in CDATA",description:"Unexpected end of file. Expected `]]>` to close the CDATA"},eofInComment:{reason:"Unexpected end of file in comment",description:"Unexpected end of file. Expected `-->` to close the comment"},eofInDoctype:{reason:"Unexpected end of file in doctype",description:"Unexpected end of file. Expected a valid doctype (such as `<!doctype html>`)"},eofInElementThatCanContainOnlyText:{reason:"Unexpected end of file in element that can only contain text",description:"Unexpected end of file. Expected text or a closing tag",url:!1},eofInScriptHtmlCommentLikeText:{reason:"Unexpected end of file in comment inside script",description:"Unexpected end of file. Expected `-->` to close the comment"},eofInTag:{reason:"Unexpected end of file in tag",description:"Unexpected end of file. Expected `>` to close the tag"},incorrectlyClosedComment:{reason:"Incorrectly closed comment",description:"Unexpected `%c-1`. Expected `-->` to close the comment"},incorrectlyOpenedComment:{reason:"Incorrectly opened comment",description:"Unexpected `%c`. Expected `<!--` to open the comment"},invalidCharacterSequenceAfterDoctypeName:{reason:"Invalid sequence after doctype name",description:"Unexpected sequence at `%c`. Expected `public` or `system`"},invalidFirstCharacterOfTagName:{reason:"Invalid first character in tag name",description:"Unexpected `%c`. Expected an ASCII letter instead"},misplacedDoctype:{reason:"Misplaced doctype",description:"Unexpected doctype. Expected doctype before head",url:!1},misplacedStartTagForHeadElement:{reason:"Misplaced `<head>` start tag",description:"Unexpected start tag `<head>`. Expected `<head>` directly after doctype",url:!1},missingAttributeValue:{reason:"Missing attribute value",description:"Unexpected `%c-1`. Expected an attribute value or no `%c-1` instead"},missingDoctype:{reason:"Missing doctype before other content",description:"Expected a `<!doctype html>` before anything else",url:!1},missingDoctypeName:{reason:"Missing doctype name",description:"Unexpected doctype end at `%c`. Expected `html` instead"},missingDoctypePublicIdentifier:{reason:"Missing public identifier in doctype",description:"Unexpected `%c`. Expected identifier for `public` instead"},missingDoctypeSystemIdentifier:{reason:"Missing system identifier in doctype",description:'Unexpected `%c`. Expected identifier for `system` instead (suggested: `"about:legacy-compat"`)'},missingEndTagName:{reason:"Missing name in end tag",description:"Unexpected `%c`. Expected an ASCII letter instead"},missingQuoteBeforeDoctypePublicIdentifier:{reason:"Missing quote before public identifier in doctype",description:"Unexpected `%c`. Expected `\"` or `'` instead"},missingQuoteBeforeDoctypeSystemIdentifier:{reason:"Missing quote before system identifier in doctype",description:"Unexpected `%c`. Expected `\"` or `'` instead"},missingSemicolonAfterCharacterReference:{reason:"Missing semicolon after character reference",description:"Unexpected `%c`. Expected `;` instead"},missingWhitespaceAfterDoctypePublicKeyword:{reason:"Missing whitespace after public identifier in doctype",description:"Unexpected `%c`. Expected ASCII whitespace instead"},missingWhitespaceAfterDoctypeSystemKeyword:{reason:"Missing whitespace after system identifier in doctype",description:"Unexpected `%c`. Expected ASCII whitespace instead"},missingWhitespaceBeforeDoctypeName:{reason:"Missing whitespace before doctype name",description:"Unexpected `%c`. Expected ASCII whitespace instead"},missingWhitespaceBetweenAttributes:{reason:"Missing whitespace between attributes",description:"Unexpected `%c`. Expected ASCII whitespace instead"},missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers:{reason:"Missing whitespace between public and system identifiers in doctype",description:"Unexpected `%c`. Expected ASCII whitespace instead"},nestedComment:{reason:"Unexpected nested comment",description:"Unexpected `<!--`. Expected `-->`"},nestedNoscriptInHead:{reason:"Unexpected nested `<noscript>` in `<head>`",description:"Unexpected `<noscript>`. Expected a closing tag or a meta element",url:!1},nonConformingDoctype:{reason:"Unexpected non-conforming doctype declaration",description:'Expected `<!doctype html>` or `<!doctype html system "about:legacy-compat">`',url:!1},nonVoidHtmlElementStartTagWithTrailingSolidus:{reason:"Unexpected trailing slash on start tag of non-void element",description:"Unexpected `/`. Expected `>` instead"},noncharacterCharacterReference:{reason:"Unexpected noncharacter code point referenced by character reference",description:"Unexpected code point. Do not use noncharacters in HTML"},noncharacterInInputStream:{reason:"Unexpected noncharacter character",description:"Unexpected code point `%x`. Do not use noncharacters in HTML"},nullCharacterReference:{reason:"Unexpected NULL character referenced by character reference",description:"Unexpected code point. Do not use NULL characters in HTML"},openElementsLeftAfterEof:{reason:"Unexpected end of file",description:"Unexpected end of file. Expected closing tag instead",url:!1},surrogateCharacterReference:{reason:"Unexpected surrogate character referenced by character reference",description:"Unexpected code point. Do not use lone surrogate characters in HTML"},surrogateInInputStream:{reason:"Unexpected surrogate character",description:"Unexpected code point `%x`. Do not use lone surrogate characters in HTML"},unexpectedCharacterAfterDoctypeSystemIdentifier:{reason:"Invalid character after system identifier in doctype",description:"Unexpected character at `%c`. Expected `>`"},unexpectedCharacterInAttributeName:{reason:"Unexpected character in attribute name",description:"Unexpected `%c`. Expected whitespace, `/`, `>`, `=`, or probably an ASCII letter"},unexpectedCharacterInUnquotedAttributeValue:{reason:"Unexpected character in unquoted attribute value",description:"Unexpected `%c`. Quote the attribute value to include it"},unexpectedEqualsSignBeforeAttributeName:{reason:"Unexpected equals sign before attribute name",description:"Unexpected `%c`. Add an attribute name before it"},unexpectedNullCharacter:{reason:"Unexpected NULL character",description:"Unexpected code point `%x`. Do not use NULL characters in HTML"},unexpectedQuestionMarkInsteadOfTagName:{reason:"Unexpected question mark instead of tag name",description:"Unexpected `%c`. Expected an ASCII letter instead"},unexpectedSolidusInTag:{reason:"Unexpected slash in tag",description:"Unexpected `%c-1`. Expected it followed by `>` or in a quoted attribute value"},unknownNamedCharacterReference:{reason:"Unexpected unknown named character reference",description:"Unexpected character reference. Expected known named character references"}},TT="https://html.spec.whatwg.org/multipage/parsing.html#parse-error-",yT=/-[a-z]/g,CT=/%c(?:([-+])(\d+))?/g,kT=/%x/g,ST={2:!0,1:!1,0:null},AT={};function _T(e,t){const n=t||AT,r=n.onerror,s=e instanceof uu?e:new uu(e),i=n.fragment?iT:sT,o=String(s),a=i(o,{sourceCodeLocationInfo:!0,onParseError:n.onerror?u:null,scriptingEnabled:!1});return I1(a,{file:s,space:n.space,verbose:n.verbose});function u(c){const d=c.code,h=wT(d),f=n[h],p=f??!0,m=typeof p=="number"?p:p?1:0;if(m){const C=ET[h],k=new ge(E(C.reason),{place:{start:{line:c.startLine,column:c.startCol,offset:c.startOffset},end:{line:c.endLine,column:c.endCol,offset:c.endOffset}},ruleId:d,source:"hast-util-from-html"});s.path&&(k.file=s.path,k.name=s.path+":"+k.name),k.fatal=ST[m],k.note=E(C.description),k.url=C.url===!1?void 0:TT+d,r(k)}function E(C){return C.replace(CT,k).replace(kT,_);function k(N,L,U){const O=(U?Number.parseInt(U,10):0)*(L==="-"?-1:1),j=o.charAt(c.startOffset+O);return xT(j)}function _(){return NT(o.charCodeAt(c.startOffset))}}}}function wT(e){return e.replace(yT,IT)}function IT(e){return e.charAt(1).toUpperCase()}function xT(e){return e==="`"?"` ` `":e}function NT(e){return"0x"+e.toString(16).toUpperCase()}function LT(e){const t=this,{emitParseErrors:n,...r}={...t.data("settings"),...e};t.parser=s;function s(i,o){return _T(i,{...r,onerror:n?function(a){o.path&&(a.name=o.path+":"+a.name,a.file=o.path),o.messages.push(a)}:void 0})}}const gd=-1,_s=0,Un=1,Jr=2,wo=3,Io=4,xo=5,No=6,bd=7,Ed=8,cu=typeof self=="object"?self:globalThis,OT=(e,t)=>{const n=(s,i)=>(e.set(i,s),s),r=s=>{if(e.has(s))return e.get(s);const[i,o]=t[s];switch(i){case _s:case gd:return n(o,s);case Un:{const a=n([],s);for(const u of o)a.push(r(u));return a}case Jr:{const a=n({},s);for(const[u,c]of o)a[r(u)]=r(c);return a}case wo:return n(new Date(o),s);case Io:{const{source:a,flags:u}=o;return n(new RegExp(a,u),s)}case xo:{const a=n(new Map,s);for(const[u,c]of o)a.set(r(u),r(c));return a}case No:{const a=n(new Set,s);for(const u of o)a.add(r(u));return a}case bd:{const{name:a,message:u}=o;return n(new cu[a](u),s)}case Ed:return n(BigInt(o),s);case"BigInt":return n(Object(BigInt(o)),s);case"ArrayBuffer":return n(new Uint8Array(o).buffer,o);case"DataView":{const{buffer:a}=new Uint8Array(o);return n(new DataView(a),o)}}return n(new cu[i](o),s)};return r},du=e=>OT(new Map,e)(0),Wt="",{toString:DT}={},{keys:vT}=Object,In=e=>{const t=typeof e;if(t!=="object"||!e)return[_s,t];const n=DT.call(e).slice(8,-1);switch(n){case"Array":return[Un,Wt];case"Object":return[Jr,Wt];case"Date":return[wo,Wt];case"RegExp":return[Io,Wt];case"Map":return[xo,Wt];case"Set":return[No,Wt];case"DataView":return[Un,n]}return n.includes("Array")?[Un,n]:n.includes("Error")?[bd,n]:[Jr,n]},yr=([e,t])=>e===_s&&(t==="function"||t==="symbol"),MT=(e,t,n,r)=>{const s=(o,a)=>{const u=r.push(o)-1;return n.set(a,u),u},i=o=>{if(n.has(o))return n.get(o);let[a,u]=In(o);switch(a){case _s:{let d=o;switch(u){case"bigint":a=Ed,d=o.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);d=null;break;case"undefined":return s([gd],o)}return s([a,d],o)}case Un:{if(u){let f=o;return u==="DataView"?f=new Uint8Array(o.buffer):u==="ArrayBuffer"&&(f=new Uint8Array(o)),s([u,[...f]],o)}const d=[],h=s([a,d],o);for(const f of o)d.push(i(f));return h}case Jr:{if(u)switch(u){case"BigInt":return s([u,o.toString()],o);case"Boolean":case"Number":case"String":return s([u,o.valueOf()],o)}if(t&&"toJSON"in o)return i(o.toJSON());const d=[],h=s([a,d],o);for(const f of vT(o))(e||!yr(In(o[f])))&&d.push([i(f),i(o[f])]);return h}case wo:return s([a,o.toISOString()],o);case Io:{const{source:d,flags:h}=o;return s([a,{source:d,flags:h}],o)}case xo:{const d=[],h=s([a,d],o);for(const[f,p]of o)(e||!(yr(In(f))||yr(In(p))))&&d.push([i(f),i(p)]);return h}case No:{const d=[],h=s([a,d],o);for(const f of o)(e||!yr(In(f)))&&d.push(i(f));return h}}const{message:c}=o;return s([a,{name:u,message:c}],o)};return i},hu=(e,{json:t,lossy:n}={})=>{const r=[];return MT(!(t||n),!!t,new Map,r)(e),r},Td=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?du(hu(e,t)):structuredClone(e):(e,t)=>du(hu(e,t)),Lo=function(e,t,n,r,s){const i=$e(t);return yd(e)?i.call(s,e,n,r):!1},$e=function(e){if(e==null)return BT;if(typeof e=="string")return PT(e);if(typeof e=="object")return RT(e);if(typeof e=="function")return Oo(e);throw new Error("Expected function, string, or array as `test`")};function RT(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=$e(e[n]);return Oo(r);function r(...s){let i=-1;for(;++i<t.length;)if(t[i].apply(this,s))return!0;return!1}}function PT(e){return Oo(t);function t(n){return n.tagName===e}}function Oo(e){return t;function t(n,r,s){return!!(yd(n)&&e.call(this,n,typeof r=="number"?r:void 0,s||void 0))}}function BT(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="element"&&"tagName"in e&&typeof e.tagName=="string")}function yd(e){return e!==null&&typeof e=="object"&&"type"in e&&"tagName"in e}const Cd=$e(function(e){return e.tagName==="audio"||e.tagName==="canvas"||e.tagName==="embed"||e.tagName==="iframe"||e.tagName==="img"||e.tagName==="math"||e.tagName==="object"||e.tagName==="picture"||e.tagName==="svg"||e.tagName==="video"}),UT=/[ \t\n\f\r]/g;function kd(e){return typeof e=="object"?e.type==="text"?fu(e.value):!1:fu(e)}function fu(e){return e.replace(UT,"")===""}const kn=function(e){if(e==null)return YT;if(typeof e=="function")return ws(e);if(typeof e=="object")return Array.isArray(e)?HT(e):FT(e);if(typeof e=="string")return VT(e);throw new Error("Expected function, string, or object as test")};function HT(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=kn(e[n]);return ws(r);function r(...s){let i=-1;for(;++i<t.length;)if(t[i].apply(this,s))return!0;return!1}}function FT(e){const t=e;return ws(n);function n(r){const s=r;let i;for(i in e)if(s[i]!==t[i])return!1;return!0}}function VT(e){return ws(t);function t(n){return n&&n.type===e}}function ws(e){return t;function t(n,r,s){return!!($T(n)&&e.call(this,n,typeof r=="number"?r:void 0,s||void 0))}}function YT(){return!0}function $T(e){return e!==null&&typeof e=="object"&&"type"in e}const jT=["address","article","aside","blockquote","body","br","caption","center","col","colgroup","dd","dialog","dir","div","dl","dt","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","legend","li","li","listing","main","menu","nav","ol","optgroup","option","p","plaintext","pre","section","summary","table","tbody","td","td","tfoot","th","th","thead","tr","ul","wbr","xmp"],qT=["button","input","select","textarea"],zT=["area","base","basefont","dialog","datalist","head","link","meta","noembed","noframes","param","rp","script","source","style","template","track","title"],WT={},Do=kn(["comment","doctype"]);function GT(e,t){Sd(e,{collapse:t2((t||WT).newlines?ZT:e2),whitespace:"normal"})}function Sd(e,t){if("children"in e){const n={...t};return(e.type==="root"||wd(e))&&(n.before=!0,n.after=!0),n.whitespace=n2(e,t),XT(e,n)}if(e.type==="text"){if(t.whitespace==="normal")return KT(e,t);t.whitespace==="nowrap"&&(e.value=t.collapse(e.value))}return{ignore:Do(e),stripAtStart:!1,remove:!1}}function KT(e,t){const n=t.collapse(e.value),r={ignore:!1,stripAtStart:!1,remove:!1};let s=0,i=n.length;return t.before&&pu(n.charAt(0))&&s++,s!==i&&pu(n.charAt(i-1))&&(t.after?i--:r.stripAtStart=!0),s===i?r.remove=!0:e.value=n.slice(s,i),r}function XT(e,t){let n=t.before;const r=t.after,s=e.children;let i=s.length,o=-1;for(;++o<i;){const a=Sd(s[o],{...t,after:Ad(s,o,r),before:n});a.remove?(s.splice(o,1),o--,i--):a.ignore||(n=a.stripAtStart),_d(s[o])&&(n=!1)}return{ignore:!1,stripAtStart:!!(n||r),remove:!1}}function Ad(e,t,n){for(;++t<e.length;){const r=e[t];let s=QT(r);if(s===void 0&&"children"in r&&!JT(r)&&(s=Ad(r.children,-1)),typeof s=="boolean")return s}return n}function QT(e){if(e.type==="element"){if(_d(e))return!1;if(wd(e))return!0}else if(e.type==="text"){if(!kd(e))return!1}else if(!Do(e))return!1}function _d(e){return Cd(e)||Lo(e,qT)}function wd(e){return Lo(e,jT)}function JT(e){return!!(e.type==="element"&&e.properties.hidden)||Do(e)||Lo(e,zT)}function pu(e){return e===" "||e===`
13
+ `}function ZT(e){const t=/\r?\n|\r/.exec(e);return t?t[0]:" "}function e2(){return" "}function t2(e){return t;function t(n){return String(n).replace(/[\t\n\v\f\r ]+/g,e)}}function n2(e,t){if("tagName"in e&&e.properties)switch(e.tagName){case"listing":case"plaintext":case"script":case"style":case"xmp":return"pre";case"nobr":return"nowrap";case"pre":return e.properties.wrap?"pre-wrap":"pre";case"td":case"th":return e.properties.noWrap?"nowrap":t.whitespace;case"textarea":return"pre-wrap"}return t.whitespace}function r2(e){return function(t){GT(t,e)}}const Id=[],s2=!0,Zr=!1,xd="skip";function Nd(e,t,n,r){let s;typeof t=="function"&&typeof n!="function"?(r=n,n=t):s=t;const i=kn(s),o=r?-1:1;a(e,void 0,[])();function a(u,c,d){const h=u&&typeof u=="object"?u:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=Id,m,E,C;if((!t||i(u,c,d[d.length-1]||void 0))&&(p=i2(n(u,d)),p[0]===Zr))return p;if("children"in u&&u.children){const k=u;if(k.children&&p[0]!==xd)for(E=(r?k.children.length:-1)+o,C=d.concat(k);E>-1&&E<k.children.length;){const _=k.children[E];if(m=a(_,E,C)(),m[0]===Zr)return m;E=typeof m[1]=="number"?m[1]:E+o}}return p}}}function i2(e){return Array.isArray(e)?e:typeof e=="number"?[s2,e]:e==null?Id:[e]}function mn(e,t,n,r){let s,i,o;typeof t=="function"&&typeof n!="function"?(i=void 0,o=t,s=n):(i=t,o=n,s=r),Nd(e,i,a,s);function a(u,c){const d=c[c.length-1],h=d?d.children.indexOf(u):void 0;return o(u,h,d)}}const o2=Ld("end"),a2=Ld("start");function Ld(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function u2(e){const t=a2(e),n=o2(e);if(t&&n)return{start:t,end:n}}function l2(e,t){const n=t.properties||{},r=e.all(t),s={type:"link",url:e.resolve(String(n.href||"")||null),title:n.title?String(n.title):null,children:r};return e.patch(t,s),s}function c2(e,t){e.baseFound||(e.frozenBaseUrl=String(t.properties&&t.properties.href||"")||void 0,e.baseFound=!0)}function d2(e,t){const n={type:"blockquote",children:e.toFlow(e.all(t))};return e.patch(t,n),n}function h2(e,t){const n={type:"break"};return e.patch(t,n),n}const mu=function(e,t,n){const r=kn(n);if(!e||!e.type||!e.children)throw new Error("Expected parent node");if(typeof t=="number"){if(t<0||t===Number.POSITIVE_INFINITY)throw new Error("Expected positive finite number as index")}else if(t=e.children.indexOf(t),t<0)throw new Error("Expected child node or index");for(;++t<e.children.length;)if(r(e.children[t],t,e))return e.children[t]},gu=/\n/g,bu=/[\t ]+/g,Bi=$e("br"),Eu=$e(T2),f2=$e("p"),Tu=$e("tr"),p2=$e(["datalist","head","noembed","noframes","noscript","rp","script","style","template","title",E2,y2]),Od=$e(["address","article","aside","blockquote","body","caption","center","dd","dialog","dir","dl","dt","div","figure","figcaption","footer","form,","h1","h2","h3","h4","h5","h6","header","hgroup","hr","html","legend","li","listing","main","menu","nav","ol","p","plaintext","pre","section","ul","xmp"]);function cr(e,t){const n={},r="children"in e?e.children:[],s=Od(e),i=Md(e,{whitespace:n.whitespace||"normal"}),o=[];(e.type==="text"||e.type==="comment")&&o.push(...vd(e,{breakBefore:!0,breakAfter:!0}));let a=-1;for(;++a<r.length;)o.push(...Dd(r[a],e,{whitespace:i,breakBefore:a?void 0:s,breakAfter:a<r.length-1?Bi(r[a+1]):s}));const u=[];let c;for(a=-1;++a<o.length;){const d=o[a];typeof d=="number"?c!==void 0&&d>c&&(c=d):d&&(c!==void 0&&c>-1&&u.push(`
14
+ `.repeat(c)||" "),c=-1,u.push(d))}return u.join("")}function Dd(e,t,n){return e.type==="element"?m2(e,t,n):e.type==="text"?n.whitespace==="normal"?vd(e,n):g2(e):[]}function m2(e,t,n){const r=Md(e,n),s=e.children||[];let i=-1,o=[];if(p2(e))return o;let a,u;for(Bi(e)||Tu(e)&&mu(t,e,Tu)?u=`
15
+ `:f2(e)?(a=2,u=2):Od(e)&&(a=1,u=1);++i<s.length;)o=o.concat(Dd(s[i],e,{whitespace:r,breakBefore:i?void 0:a,breakAfter:i<s.length-1?Bi(s[i+1]):u}));return Eu(e)&&mu(t,e,Eu)&&o.push(" "),a&&o.unshift(a),u&&o.push(u),o}function vd(e,t){const n=String(e.value),r=[],s=[];let i=0;for(;i<=n.length;){gu.lastIndex=i;const u=gu.exec(n),c=u&&"index"in u?u.index:n.length;r.push(b2(n.slice(i,c).replace(/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g,""),i===0?t.breakBefore:!0,c===n.length?t.breakAfter:!0)),i=c+1}let o=-1,a;for(;++o<r.length;)r[o].charCodeAt(r[o].length-1)===8203||o<r.length-1&&r[o+1].charCodeAt(0)===8203?(s.push(r[o]),a=void 0):r[o]?(typeof a=="number"&&s.push(a),s.push(r[o]),a=0):(o===0||o===r.length-1)&&s.push(0);return s}function g2(e){return[String(e.value)]}function b2(e,t,n){const r=[];let s=0,i;for(;s<e.length;){bu.lastIndex=s;const o=bu.exec(e);i=o?o.index:e.length,!s&&!i&&o&&!t&&r.push(""),s!==i&&r.push(e.slice(s,i)),s=o?i+o[0].length:i}return s!==i&&!n&&r.push(""),r.join(" ")}function Md(e,t){if(e.type==="element"){const n=e.properties||{};switch(e.tagName){case"listing":case"plaintext":case"xmp":return"pre";case"nobr":return"nowrap";case"pre":return n.wrap?"pre-wrap":"pre";case"td":case"th":return n.noWrap?"nowrap":t.whitespace;case"textarea":return"pre-wrap"}}return t.whitespace}function E2(e){return!!(e.properties||{}).hidden}function T2(e){return e.tagName==="td"||e.tagName==="th"}function y2(e){return e.tagName==="dialog"&&!(e.properties||{}).open}function C2(e){const t=String(e);let n=t.length;for(;n>0;){const r=t.codePointAt(n-1);if(r!==void 0&&(r===10||r===13))n--;else break}return t.slice(0,n)}const Zs="language-";function Cr(e,t){const n=t.children;let r=-1,s,i;if(t.tagName==="pre")for(;++r<n.length;){const a=n[r];if(a.type==="element"&&a.tagName==="code"&&a.properties&&a.properties.className&&Array.isArray(a.properties.className)){s=a.properties.className;break}}if(s){for(r=-1;++r<s.length;)if(String(s[r]).slice(0,Zs.length)===Zs){i=String(s[r]).slice(Zs.length);break}}const o={type:"code",lang:i||null,meta:null,value:C2(cr(t))};return e.patch(t,o),o}function k2(e,t){const n={type:"html",value:"<!--"+t.value+"-->"};return e.patch(t,n),n}function ei(e,t){const r={type:"delete",children:e.all(t)};return e.patch(t,r),r}function vo(e){let t=-1;if(e.length>1){for(;++t<e.length;)if(e[t].spread)return!0}return!1}function S2(e,t){const n=[],r=[];let s=-1;for(;++s<t.children.length;){const a=t.children[s];a.type==="element"&&a.tagName==="div"?n.push(...a.children):n.push(a)}let i={definitions:[],titles:[]};for(s=-1;++s<n.length;){const a=n[s];if(a.type==="element"&&a.tagName==="dt"){const u=n[s-1];u&&u.type==="element"&&u.tagName==="dd"&&(r.push(i),i={definitions:[],titles:[]}),i.titles.push(a)}else i.definitions.push(a)}r.push(i),s=-1;const o=[];for(;++s<r.length;){const a=[...yu(e,r[s].titles),...yu(e,r[s].definitions)];a.length>0&&o.push({type:"listItem",spread:a.length>1,checked:null,children:a})}if(o.length>0){const a={type:"list",ordered:!1,start:null,spread:vo(o),children:o};return e.patch(t,a),a}}function yu(e,t){const n=e.all({type:"root",children:t}),r=e.toSpecificContent(n,A2);return r.length===0?[]:r.length===1?r[0].children:[{type:"list",ordered:!1,start:null,spread:vo(r),children:r}]}function A2(){return{type:"listItem",spread:!1,checked:null,children:[]}}function kr(e,t){const r={type:"emphasis",children:e.all(t)};return e.patch(t,r),r}function Mo(e){let t=0,n=e.length;for(;t<n&&e[t].type==="break";)t++;for(;n>t&&e[n-1].type==="break";)n--;return t===0&&n===e.length?e:e.slice(t,n)}function Gt(e,t){const n=Number(t.tagName.charAt(1))||1,r=Mo(e.all(t)),s={type:"heading",depth:n,children:r};return e.patch(t,s),s}function _2(e,t){const n={type:"thematicBreak"};return e.patch(t,n),n}function w2(e,t){const n=t.properties||{},r=String(n.src||""),s=String(n.title||"");if(r&&s){const i={type:"link",title:null,url:e.resolve(r),children:[{type:"text",value:s}]};return e.patch(t,i),i}}function Cu(e,t){const n=t.properties||{},r={type:"image",url:e.resolve(String(n.src||"")||null),title:n.title?String(n.title):null,alt:n.alt?String(n.alt):""};return e.patch(t,r),r}function xn(e,t){const n={type:"inlineCode",value:cr(t)};return e.patch(t,n),n}function Rd(e,t){const n=[],r=[],s=t||e.properties||{},i=Pd(e),o=Math.min(Number.parseInt(String(s.size),10),0)||(s.multiple?4:1);let a=-1;for(;++a<i.length;){const d=i[a];d&&d.properties&&d.properties.selected&&n.push(d)}const u=n.length>0?n:i,c=Math.min(u.length,o);for(a=-1;++a<c;){const d=u[a],h=d.properties||{},f=cr(d),p=f||String(h.label||""),m=String(h.value||"")||f;r.push([m,p===m?void 0:p])}return r}function Pd(e){const t=[];let n=-1;for(;++n<e.children.length;){const r=e.children[n];"children"in r&&Array.isArray(r.children)&&t.push(...Pd(r)),r.type==="element"&&r.tagName==="option"&&(!r.properties||!r.properties.disabled)&&t.push(r)}return t}const I2="[x]",x2="[ ]";function N2(e,t){const n=t.properties||{},r=String(n.value||n.placeholder||"");if(n.disabled||n.type==="hidden"||n.type==="file")return;if(n.type==="checkbox"||n.type==="radio"){const u={type:"text",value:n.checked?e.options.checked||I2:e.options.unchecked||x2};return e.patch(t,u),u}if(n.type==="image"){const u=n.alt||r;if(u){const c={type:"image",url:e.resolve(String(n.src||"")||null),title:String(n.title||"")||null,alt:String(u)};return e.patch(t,c),c}return}let s=[];if(r)s=[[r,void 0]];else if(n.type!=="button"&&n.type!=="file"&&n.type!=="password"&&n.type!=="reset"&&n.type!=="submit"&&n.list){const u=String(n.list),c=e.elementById.get(u);c&&c.tagName==="datalist"&&(s=Rd(c,n))}if(s.length===0)return;if(n.type==="password"&&(s[0]=["•".repeat(s[0][0].length),void 0]),n.type==="email"||n.type==="url"){const u=[];let c=-1;for(;++c<s.length;){const d=e.resolve(s[c][0]),h={type:"link",title:null,url:n.type==="email"?"mailto:"+d:d,children:[{type:"text",value:s[c][1]||d}]};u.push(h),c!==s.length-1&&u.push({type:"text",value:", "})}return u}const i=[];let o=-1;for(;++o<s.length;)i.push(s[o][1]?s[o][1]+" ("+s[o][0]+")":s[o][0]);const a={type:"text",value:i.join(", ")};return e.patch(t,a),a}const L2={}.hasOwnProperty;function O2(e,t){const n=e.type==="element"&&L2.call(e.properties,t)&&e.properties[t];return n!=null&&n!==!1}const D2=new Set(["pingback","prefetch","stylesheet"]);function v2(e){if(e.type!=="element"||e.tagName!=="link")return!1;if(e.properties.itemProp)return!0;const t=e.properties.rel;let n=-1;if(!Array.isArray(t)||t.length===0)return!1;for(;++n<t.length;)if(!D2.has(String(t[n])))return!1;return!0}const M2=$e(["a","abbr","area","b","bdi","bdo","br","button","cite","code","data","datalist","del","dfn","em","i","input","ins","kbd","keygen","label","map","mark","meter","noscript","output","progress","q","ruby","s","samp","script","select","small","span","strong","sub","sup","template","textarea","time","u","var","wbr"]),R2=$e("meta");function Bd(e){return!!(e.type==="text"||M2(e)||Cd(e)||v2(e)||R2(e)&&O2(e,"itemProp"))}function ti(e,t){const{rest:n,checkbox:r}=Hd(t),s=r?!!r.properties.checked:null,i=Ud(n),o=e.toFlow(e.all(n)),a={type:"listItem",spread:i,checked:s,children:o};return e.patch(t,a),a}function Ud(e){let t=-1,n=!1;for(;++t<e.children.length;){const r=e.children[t];if(r.type==="element"){if(Bd(r))continue;if(r.tagName==="p"||n||Ud(r))return!0;n=!0}}return!1}function Hd(e){const t=e.children[0];if(t&&t.type==="element"&&t.tagName==="input"&&t.properties&&(t.properties.type==="checkbox"||t.properties.type==="radio")){const n={...e,children:e.children.slice(1)};return{checkbox:t,rest:n}}if(t&&t.type==="element"&&t.tagName==="p"){const{checkbox:n,rest:r}=Hd(t);if(n){const s={...e,children:[r,...e.children.slice(1)]};return{checkbox:n,rest:s}}}return{checkbox:void 0,rest:e}}function ni(e,t){const n=t.tagName==="ol",r=e.toSpecificContent(e.all(t),P2);let s=null;n&&(s=t.properties&&t.properties.start?Number.parseInt(String(t.properties.start),10):1);const i={type:"list",ordered:n,start:s,spread:vo(r),children:r};return e.patch(t,i),i}function P2(){return{type:"listItem",spread:!1,checked:null,children:[]}}const B2={};function Ro(e,t){const n=B2,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,s=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return Fd(e,r,s)}function Fd(e,t,n){if(U2(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return ku(e.children,t,n)}return Array.isArray(e)?ku(e,t,n):""}function ku(e,t,n){const r=[];let s=-1;for(;++s<e.length;)r[s]=Fd(e[s],t,n);return r.join("")}function U2(e){return!!(e&&typeof e=="object")}const Vd=kn(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Is(e){let t=-1;for(;++t<e.length;){const n=e[t];if(!jd(n)||"children"in n&&Is(n.children))return!0}return!1}function Yd(e){return $d(e,t,function(n){return n});function t(n){return n.every(function(r){return r.type==="text"?kd(r.value):!1})?[]:[{type:"paragraph",children:Mo(n)}]}}function H2(e){return $d(e.children,t,n);function t(r){const s=ri(e);return s.children=r,[s]}function n(r){if("children"in r&&"children"in e){const s=ri(e),i=ri(r);return s.children=r.children,i.children.push(s),i}return{...r}}}function $d(e,t,n){const r=F2(e),s=[];let i=[],o=-1;for(;++o<r.length;){const a=r[o];jd(a)?i.push(a):(i.length>0&&(s.push(...t(i)),i=[]),s.push(n(a)))}return i.length>0&&(s.push(...t(i)),i=[]),s}function F2(e){const t=[];let n=-1;for(;++n<e.length;){const r=e[n];(r.type==="delete"||r.type==="link")&&Is(r.children)?t.push(...H2(r)):t.push(r)}return t}function jd(e){const t=e.data&&e.data.hName;return t?Bd({type:"element",tagName:t,properties:{},children:[]}):Vd(e)}function ri(e){return Td({...e,children:[]})}function Su(e,t){const n=t.properties||{},r=t.tagName==="video"?String(n.poster||""):"";let s=String(n.src||""),i=-1,o=!1,a=e.all(t);if(mn({type:"root",children:a},function(h){if(h.type==="link")return o=!0,Zr}),o||Is(a))return a;for(;!s&&++i<t.children.length;){const h=t.children[i];h.type==="element"&&h.tagName==="source"&&h.properties&&(s=String(h.properties.src||""))}if(r){const h={type:"image",title:null,url:e.resolve(r),alt:Ro(a)};e.patch(t,h),a=[h]}const c=a,d={type:"link",title:n.title?String(n.title):null,url:e.resolve(s),children:c};return e.patch(t,d),d}function Au(e,t){const n=Mo(e.all(t));if(n.length>0){const r={type:"paragraph",children:n};return e.patch(t,r),r}}const V2=['"'];function Y2(e,t){const n=e.options.quotes||V2;e.qNesting++;const r=e.all(t);e.qNesting--;const s=n[e.qNesting%n.length],i=r[0],o=r[r.length-1],a=s.charAt(0),u=s.length>1?s.charAt(1):s;return i&&i.type==="text"?i.value=a+i.value:r.unshift({type:"text",value:a}),o&&o.type==="text"?o.value+=u:r.push({type:"text",value:u}),r}function $2(e,t){let n=e.all(t);(e.options.document||Is(n))&&(n=Yd(n));const r={type:"root",children:n};return e.patch(t,r),r}function j2(e,t){const n=Rd(t);let r=-1;const s=[];for(;++r<n.length;){const i=n[r];s.push(i[1]?i[1]+" ("+i[0]+")":i[0])}if(s.length>0){const i={type:"text",value:s.join(", ")};return e.patch(t,i),i}}function _u(e,t){const r={type:"strong",children:e.all(t)};return e.patch(t,r),r}function wu(e,t){const r={type:"tableCell",children:e.all(t)};if(e.patch(t,r),t.properties){const s=t.properties.rowSpan,i=t.properties.colSpan;if(s||i){const o=r.data||(r.data={});s&&(o.hastUtilToMdastTemporaryRowSpan=s),i&&(o.hastUtilToMdastTemporaryColSpan=i)}}return r}function q2(e,t){const r={type:"tableRow",children:e.toSpecificContent(e.all(t),z2)};return e.patch(t,r),r}function z2(){return{type:"tableCell",children:[]}}function W2(e,t){if(e.inTable){const c={type:"text",value:cr(t)};return e.patch(t,c),c}e.inTable=!0;const{align:n,headless:r}=G2(t),s=e.toSpecificContent(e.all(t),Iu);r&&s.unshift(Iu());let i=-1;for(;++i<s.length;){const c=s[i],d=e.toSpecificContent(c.children,K2);c.children=d}let o=1;for(i=-1;++i<s.length;){const c=s[i].children;let d=-1;for(;++d<c.length;){const h=c[d];if(h.data){const f=h.data,p=Number.parseInt(String(f.hastUtilToMdastTemporaryColSpan),10)||1,m=Number.parseInt(String(f.hastUtilToMdastTemporaryRowSpan),10)||1;if(p>1||m>1){let E=i-1;for(;++E<i+m;){let C=d-1;for(;++C<d+p&&s[E];){const k=[];(E!==i||C!==d)&&k.push({type:"tableCell",children:[]}),s[E].children.splice(C,0,...k)}}}"hastUtilToMdastTemporaryColSpan"in h.data&&delete h.data.hastUtilToMdastTemporaryColSpan,"hastUtilToMdastTemporaryRowSpan"in h.data&&delete h.data.hastUtilToMdastTemporaryRowSpan,Object.keys(h.data).length===0&&delete h.data}}c.length>o&&(o=c.length)}for(i=-1;++i<s.length;){const c=s[i].children;let d=c.length-1;for(;++d<o;)c.push({type:"tableCell",children:[]})}let a=n.length-1;for(;++a<o;)n.push(null);e.inTable=!1;const u={type:"table",align:n,children:s};return e.patch(t,u),u}function G2(e){const t={align:[null],headless:!0};let n=0,r=0;return mn(e,function(s){if(s.type==="element"){if(s.tagName==="table"&&e!==s)return xd;if((s.tagName==="th"||s.tagName==="td")&&s.properties){if(!t.align[r]){const i=String(s.properties.align||"")||null;(i==="center"||i==="left"||i==="right"||i===null)&&(t.align[r]=i)}t.headless&&n<2&&s.tagName==="th"&&(t.headless=!1),r++}else s.tagName==="thead"?t.headless=!1:s.tagName==="tr"&&(n++,r=0)}}),t}function K2(){return{type:"tableCell",children:[]}}function Iu(){return{type:"tableRow",children:[]}}function X2(e,t){const n={type:"text",value:t.value};return e.patch(t,n),n}function Q2(e,t){const n={type:"text",value:cr(t)};return e.patch(t,n),n}function J2(e,t){const n={type:"text",value:"​"};return e.patch(t,n),n}const Z2={comment:k2,doctype:P,root:$2,text:X2},ey={applet:P,area:P,basefont:P,bgsound:P,caption:P,col:P,colgroup:P,command:P,content:P,datalist:P,dialog:P,element:P,embed:P,frame:P,frameset:P,isindex:P,keygen:P,link:P,math:P,menu:P,menuitem:P,meta:P,nextid:P,noembed:P,noframes:P,optgroup:P,option:P,param:P,script:P,shadow:P,source:P,spacer:P,style:P,svg:P,template:P,title:P,track:P,abbr:R,acronym:R,bdi:R,bdo:R,big:R,blink:R,button:R,canvas:R,cite:R,data:R,details:R,dfn:R,font:R,ins:R,label:R,map:R,marquee:R,meter:R,nobr:R,noscript:R,object:R,output:R,progress:R,rb:R,rbc:R,rp:R,rt:R,rtc:R,ruby:R,slot:R,small:R,span:R,sup:R,sub:R,tbody:R,tfoot:R,thead:R,time:R,address:J,article:J,aside:J,body:J,center:J,div:J,fieldset:J,figcaption:J,figure:J,form:J,footer:J,header:J,hgroup:J,html:J,legend:J,main:J,multicol:J,nav:J,picture:J,section:J,a:l2,audio:Su,b:_u,base:c2,blockquote:d2,br:h2,code:xn,dir:ni,dl:S2,dt:ti,dd:ti,del:ei,em:kr,h1:Gt,h2:Gt,h3:Gt,h4:Gt,h5:Gt,h6:Gt,hr:_2,i:kr,iframe:w2,img:Cu,image:Cu,input:N2,kbd:xn,li:ti,listing:Cr,mark:kr,ol:ni,p:Au,plaintext:Cr,pre:Cr,q:Y2,s:ei,samp:xn,select:j2,strike:ei,strong:_u,summary:Au,table:W2,td:wu,textarea:Q2,th:wu,tr:q2,tt:xn,u:kr,ul:ni,var:xn,video:Su,wbr:J2,xmp:Cr};function R(e,t){return e.all(t)}function J(e,t){return e.toFlow(e.all(t))}function P(){}const xu={}.hasOwnProperty;function ty(e){return{all:ny,baseFound:!1,elementById:new Map,frozenBaseUrl:void 0,handlers:{...ey,...e.handlers},inTable:!1,nodeHandlers:{...Z2,...e.nodeHandlers},one:ry,options:e,patch:sy,qNesting:0,resolve:iy,toFlow:oy,toSpecificContent:ay}}function ny(e){const t=e.children||[],n=[];let r=-1;for(;++r<t.length;){const s=t[r],i=this.one(s,e);Array.isArray(i)?n.push(...i):i&&n.push(i)}return n}function ry(e,t){if(e.type==="element"){if(e.properties&&e.properties.dataMdast==="ignore")return;if(xu.call(this.handlers,e.tagName))return this.handlers[e.tagName](this,e,t)||void 0}else if(xu.call(this.nodeHandlers,e.type))return this.nodeHandlers[e.type](this,e,t)||void 0;if("value"in e&&typeof e.value=="string"){const n={type:"text",value:e.value};return this.patch(e,n),n}if("children"in e)return this.all(e)}function sy(e,t){e.position&&(t.position=u2(e))}function iy(e){const t=this.frozenBaseUrl;return e==null?"":t?String(new URL(e,t)):e}function oy(e){return Yd(e)}function ay(e,t){const n=t(),r=[];let s=[],i=-1;for(;++i<e.length;){const a=e[i];if(o(a))s.length>0&&(a.children.unshift(...s),s=[]),r.push(a);else{const u=a;s.push(u)}}if(s.length>0){let a=r[r.length-1];a||(a=t(),r.push(a)),a.children.push(...s),s=[]}return r;function o(a){return a.type===n.type}}const uy={};function Nu(e,t){const n=Td(e),r=t||uy,s=r2({newlines:r.newlines===!0}),i=ty(r);let o;s(n),mn(n,function(u){if(u&&u.type==="element"&&u.properties){const c=String(u.properties.id||"")||void 0;c&&!i.elementById.has(c)&&i.elementById.set(c,u)}});const a=i.one(n,void 0);return a?Array.isArray(a)?o={type:"root",children:a}:o=a:o={type:"root",children:[]},mn(o,function(u,c,d){if(u.type==="text"&&c!==void 0&&d){const h=d.children[c-1];if(h&&h.type===u.type)return h.value+=u.value,d.children.splice(c,1),h.position&&u.position&&(h.position.end=u.position.end),c-1;if(u.value=u.value.replace(/[\t ]*(\r?\n|\r)[\t ]*/,"$1"),d&&(d.type==="heading"||d.type==="paragraph"||d.type==="root")&&(c||(u.value=u.value.replace(/^[\t ]+/,"")),c===d.children.length-1&&(u.value=u.value.replace(/[\t ]+$/,""))),!u.value)return d.children.splice(c,1),c}}),o}const Lu={document:!0};function ly(e,t){return e&&"run"in e?async function(n,r){const s=Nu(n,{...Lu,...t});await e.run(s,r)}:function(n){return Nu(n,{...Lu,...e})}}function Ou(e,t){const n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,s=n.indexOf(t);for(;s!==-1;)r++,s=n.indexOf(t,s+t.length);return r}const er=Ns(/[A-Za-z]/),Po=Ns(/[\dA-Za-z]/);function cy(e){return e!==null&&(e<32||e===127)}function Jt(e){return e!==null&&e<-2}function ke(e){return e!==null&&(e<0||e===32)}function st(e){return e===-2||e===-1||e===32}const xs=Ns(new RegExp("\\p{P}|\\p{S}","u")),Ut=Ns(/\s/);function Ns(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function dy(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function hy(e,t,n){const s=kn((n||{}).ignore||[]),i=fy(t);let o=-1;for(;++o<i.length;)Nd(e,"text",a);function a(c,d){let h=-1,f;for(;++h<d.length;){const p=d[h],m=f?f.children:void 0;if(s(p,m?m.indexOf(p):void 0,f))return;f=p}if(f)return u(c,d)}function u(c,d){const h=d[d.length-1],f=i[o][0],p=i[o][1];let m=0;const C=h.children.indexOf(c);let k=!1,_=[];f.lastIndex=0;let N=f.exec(c.value);for(;N;){const L=N.index,U={index:N.index,input:N.input,stack:[...d,c]};let O=p(...N,U);if(typeof O=="string"&&(O=O.length>0?{type:"text",value:O}:void 0),O===!1?f.lastIndex=L+1:(m!==L&&_.push({type:"text",value:c.value.slice(m,L)}),Array.isArray(O)?_.push(...O):O&&_.push(O),m=L+N[0].length,k=!0),!f.global)break;N=f.exec(c.value)}return k?(m<c.value.length&&_.push({type:"text",value:c.value.slice(m)}),h.children.splice(C,1,..._)):_=[c],C+_.length}}function fy(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const n=!e[0]||Array.isArray(e[0])?e:[e];let r=-1;for(;++r<n.length;){const s=n[r];t.push([py(s[0]),my(s[1])])}return t}function py(e){return typeof e=="string"?new RegExp(dy(e),"g"):e}function my(e){return typeof e=="function"?e:function(){return e}}const si="phrasing",ii=["autolink","link","image","label"];function gy(){return{transforms:[Sy],enter:{literalAutolink:Ey,literalAutolinkEmail:oi,literalAutolinkHttp:oi,literalAutolinkWww:oi},exit:{literalAutolink:ky,literalAutolinkEmail:Cy,literalAutolinkHttp:Ty,literalAutolinkWww:yy}}}function by(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:si,notInConstruct:ii},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:si,notInConstruct:ii},{character:":",before:"[ps]",after:"\\/",inConstruct:si,notInConstruct:ii}]}}function Ey(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function oi(e){this.config.enter.autolinkProtocol.call(this,e)}function Ty(e){this.config.exit.autolinkProtocol.call(this,e)}function yy(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function Cy(e){this.config.exit.autolinkEmail.call(this,e)}function ky(e){this.exit(e)}function Sy(e){hy(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Ay],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),_y]],{ignore:["link","linkReference"]})}function Ay(e,t,n,r,s){let i="";if(!qd(s)||(/^w/i.test(t)&&(n=t+n,t="",i="http://"),!wy(n)))return!1;const o=Iy(n+r);if(!o[0])return!1;const a={type:"link",title:null,url:i+t+o[0],children:[{type:"text",value:t+o[0]}]};return o[1]?[a,{type:"text",value:o[1]}]:a}function _y(e,t,n,r){return!qd(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function wy(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function Iy(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const s=Ou(e,"(");let i=Ou(e,")");for(;r!==-1&&s>i;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),i++;return[e,n]}function qd(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||Ut(n)||xs(n))&&(!t||n!==47)}function dr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}zd.peek=Py;function xy(){this.buffer()}function Ny(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function Ly(){this.buffer()}function Oy(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Dy(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=dr(this.sliceSerialize(e)).toLowerCase(),n.label=t}function vy(e){this.exit(e)}function My(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=dr(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Ry(e){this.exit(e)}function Py(){return"["}function zd(e,t,n,r){const s=n.createTracker(r);let i=s.move("[^");const o=n.enter("footnoteReference"),a=n.enter("reference");return i+=s.move(n.safe(n.associationId(e),{after:"]",before:i})),a(),o(),i+=s.move("]"),i}function By(){return{enter:{gfmFootnoteCallString:xy,gfmFootnoteCall:Ny,gfmFootnoteDefinitionLabelString:Ly,gfmFootnoteDefinition:Oy},exit:{gfmFootnoteCallString:Dy,gfmFootnoteCall:vy,gfmFootnoteDefinitionLabelString:My,gfmFootnoteDefinition:Ry}}}function Uy(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:zd},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,s,i,o){const a=i.createTracker(o);let u=a.move("[^");const c=i.enter("footnoteDefinition"),d=i.enter("label");return u+=a.move(i.safe(i.associationId(r),{before:u,after:"]"})),d(),u+=a.move("]:"),r.children&&r.children.length>0&&(a.shift(4),u+=a.move((t?`
16
+ `:" ")+i.indentLines(i.containerFlow(r,a.current()),t?Wd:Hy))),c(),u}}function Hy(e,t,n){return t===0?e:Wd(e,t,n)}function Wd(e,t,n){return(n?"":" ")+e}const Fy=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Gd.peek=qy;function Vy(){return{canContainEols:["delete"],enter:{strikethrough:$y},exit:{strikethrough:jy}}}function Yy(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:Fy}],handlers:{delete:Gd}}}function $y(e){this.enter({type:"delete",children:[]},e)}function jy(e){this.exit(e)}function Gd(e,t,n,r){const s=n.createTracker(r),i=n.enter("strikethrough");let o=s.move("~~");return o+=n.containerPhrasing(e,{...s.current(),before:o,after:"~"}),o+=s.move("~~"),i(),o}function qy(){return"~"}function zy(e){return e.length}function Wy(e,t){const n=t||{},r=(n.align||[]).concat(),s=n.stringLength||zy,i=[],o=[],a=[],u=[];let c=0,d=-1;for(;++d<e.length;){const E=[],C=[];let k=-1;for(e[d].length>c&&(c=e[d].length);++k<e[d].length;){const _=Gy(e[d][k]);if(n.alignDelimiters!==!1){const N=s(_);C[k]=N,(u[k]===void 0||N>u[k])&&(u[k]=N)}E.push(_)}o[d]=E,a[d]=C}let h=-1;if(typeof r=="object"&&"length"in r)for(;++h<c;)i[h]=Du(r[h]);else{const E=Du(r);for(;++h<c;)i[h]=E}h=-1;const f=[],p=[];for(;++h<c;){const E=i[h];let C="",k="";E===99?(C=":",k=":"):E===108?C=":":E===114&&(k=":");let _=n.alignDelimiters===!1?1:Math.max(1,u[h]-C.length-k.length);const N=C+"-".repeat(_)+k;n.alignDelimiters!==!1&&(_=C.length+_+k.length,_>u[h]&&(u[h]=_),p[h]=_),f[h]=N}o.splice(1,0,f),a.splice(1,0,p),d=-1;const m=[];for(;++d<o.length;){const E=o[d],C=a[d];h=-1;const k=[];for(;++h<c;){const _=E[h]||"";let N="",L="";if(n.alignDelimiters!==!1){const U=u[h]-(C[h]||0),O=i[h];O===114?N=" ".repeat(U):O===99?U%2?(N=" ".repeat(U/2+.5),L=" ".repeat(U/2-.5)):(N=" ".repeat(U/2),L=N):L=" ".repeat(U)}n.delimiterStart!==!1&&!h&&k.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&_==="")&&(n.delimiterStart!==!1||h)&&k.push(" "),n.alignDelimiters!==!1&&k.push(N),k.push(_),n.alignDelimiters!==!1&&k.push(L),n.padding!==!1&&k.push(" "),(n.delimiterEnd!==!1||h!==c-1)&&k.push("|")}m.push(n.delimiterEnd===!1?k.join("").replace(/ +$/,""):k.join(""))}return m.join(`
17
+ `)}function Gy(e){return e==null?"":String(e)}function Du(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function Ky(e,t,n,r){const s=n.enter("blockquote"),i=n.createTracker(r);i.move("> "),i.shift(2);const o=n.indentLines(n.containerFlow(e,i.current()),Xy);return s(),o}function Xy(e,t,n){return">"+(n?"":" ")+e}function Qy(e,t){return vu(e,t.inConstruct,!0)&&!vu(e,t.notInConstruct,!1)}function vu(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++r<t.length;)if(e.includes(t[r]))return!0;return!1}function Mu(e,t,n,r){let s=-1;for(;++s<n.unsafe.length;)if(n.unsafe[s].character===`
18
+ `&&Qy(n.stack,n.unsafe[s]))return/[ \t]/.test(r.before)?"":" ";return`\\
19
+ `}function Jy(e,t){const n=String(e);let r=n.indexOf(t),s=r,i=0,o=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;r!==-1;)r===s?++i>o&&(o=i):i=1,s=r+t.length,r=n.indexOf(t,s);return o}function Zy(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function eC(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function tC(e,t,n,r){const s=eC(n),i=e.value||"",o=s==="`"?"GraveAccent":"Tilde";if(Zy(e,n)){const h=n.enter("codeIndented"),f=n.indentLines(i,nC);return h(),f}const a=n.createTracker(r),u=s.repeat(Math.max(Jy(i,s)+1,3)),c=n.enter("codeFenced");let d=a.move(u);if(e.lang){const h=n.enter(`codeFencedLang${o}`);d+=a.move(n.safe(e.lang,{before:d,after:" ",encode:["`"],...a.current()})),h()}if(e.lang&&e.meta){const h=n.enter(`codeFencedMeta${o}`);d+=a.move(" "),d+=a.move(n.safe(e.meta,{before:d,after:`
20
+ `,encode:["`"],...a.current()})),h()}return d+=a.move(`
21
+ `),i&&(d+=a.move(i+`
22
+ `)),d+=a.move(u),c(),d}function nC(e,t,n){return(n?"":" ")+e}function Bo(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function rC(e,t,n,r){const s=Bo(n),i=s==='"'?"Quote":"Apostrophe",o=n.enter("definition");let a=n.enter("label");const u=n.createTracker(r);let c=u.move("[");return c+=u.move(n.safe(n.associationId(e),{before:c,after:"]",...u.current()})),c+=u.move("]: "),a(),!e.url||/[\0- \u007F]/.test(e.url)?(a=n.enter("destinationLiteral"),c+=u.move("<"),c+=u.move(n.safe(e.url,{before:c,after:">",...u.current()})),c+=u.move(">")):(a=n.enter("destinationRaw"),c+=u.move(n.safe(e.url,{before:c,after:e.title?" ":`
23
+ `,...u.current()}))),a(),e.title&&(a=n.enter(`title${i}`),c+=u.move(" "+s),c+=u.move(n.safe(e.title,{before:c,after:s,...u.current()})),c+=u.move(s),a()),o(),c}function sC(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function tr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function es(e){if(e===null||ke(e)||Ut(e))return 1;if(xs(e))return 2}function ts(e,t,n){const r=es(e),s=es(t);return r===void 0?s===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Kd.peek=iC;function Kd(e,t,n,r){const s=sC(n),i=n.enter("emphasis"),o=n.createTracker(r),a=o.move(s);let u=o.move(n.containerPhrasing(e,{after:s,before:a,...o.current()}));const c=u.charCodeAt(0),d=ts(r.before.charCodeAt(r.before.length-1),c,s);d.inside&&(u=tr(c)+u.slice(1));const h=u.charCodeAt(u.length-1),f=ts(r.after.charCodeAt(0),h,s);f.inside&&(u=u.slice(0,-1)+tr(h));const p=o.move(s);return i(),n.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},a+u+p}function iC(e,t,n){return n.options.emphasis||"*"}function oC(e,t){let n=!1;return mn(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,Zr}),!!((!e.depth||e.depth<3)&&Ro(e)&&(t.options.setext||n))}function aC(e,t,n,r){const s=Math.max(Math.min(6,e.depth||1),1),i=n.createTracker(r);if(oC(e,n)){const d=n.enter("headingSetext"),h=n.enter("phrasing"),f=n.containerPhrasing(e,{...i.current(),before:`
24
+ `,after:`
25
+ `});return h(),d(),f+`
26
+ `+(s===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
27
+ `))+1))}const o="#".repeat(s),a=n.enter("headingAtx"),u=n.enter("phrasing");i.move(o+" ");let c=n.containerPhrasing(e,{before:"# ",after:`
28
+ `,...i.current()});return/^[\t ]/.test(c)&&(c=tr(c.charCodeAt(0))+c.slice(1)),c=c?o+" "+c:o,n.options.closeAtx&&(c+=" "+o),u(),a(),c}Xd.peek=uC;function Xd(e){return e.value||""}function uC(){return"<"}Qd.peek=lC;function Qd(e,t,n,r){const s=Bo(n),i=s==='"'?"Quote":"Apostrophe",o=n.enter("image");let a=n.enter("label");const u=n.createTracker(r);let c=u.move("![");return c+=u.move(n.safe(e.alt,{before:c,after:"]",...u.current()})),c+=u.move("]("),a(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(a=n.enter("destinationLiteral"),c+=u.move("<"),c+=u.move(n.safe(e.url,{before:c,after:">",...u.current()})),c+=u.move(">")):(a=n.enter("destinationRaw"),c+=u.move(n.safe(e.url,{before:c,after:e.title?" ":")",...u.current()}))),a(),e.title&&(a=n.enter(`title${i}`),c+=u.move(" "+s),c+=u.move(n.safe(e.title,{before:c,after:s,...u.current()})),c+=u.move(s),a()),c+=u.move(")"),o(),c}function lC(){return"!"}Jd.peek=cC;function Jd(e,t,n,r){const s=e.referenceType,i=n.enter("imageReference");let o=n.enter("label");const a=n.createTracker(r);let u=a.move("![");const c=n.safe(e.alt,{before:u,after:"]",...a.current()});u+=a.move(c+"]["),o();const d=n.stack;n.stack=[],o=n.enter("reference");const h=n.safe(n.associationId(e),{before:u,after:"]",...a.current()});return o(),n.stack=d,i(),s==="full"||!c||c!==h?u+=a.move(h+"]"):s==="shortcut"?u=u.slice(0,-1):u+=a.move("]"),u}function cC(){return"!"}Zd.peek=dC;function Zd(e,t,n){let r=e.value||"",s="`",i=-1;for(;new RegExp("(^|[^`])"+s+"([^`]|$)").test(r);)s+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++i<n.unsafe.length;){const o=n.unsafe[i],a=n.compilePattern(o);let u;if(o.atBreak)for(;u=a.exec(r);){let c=u.index;r.charCodeAt(c)===10&&r.charCodeAt(c-1)===13&&c--,r=r.slice(0,c)+" "+r.slice(u.index+1)}}return s+r+s}function dC(){return"`"}function eh(e,t){const n=Ro(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}th.peek=hC;function th(e,t,n,r){const s=Bo(n),i=s==='"'?"Quote":"Apostrophe",o=n.createTracker(r);let a,u;if(eh(e,n)){const d=n.stack;n.stack=[],a=n.enter("autolink");let h=o.move("<");return h+=o.move(n.containerPhrasing(e,{before:h,after:">",...o.current()})),h+=o.move(">"),a(),n.stack=d,h}a=n.enter("link"),u=n.enter("label");let c=o.move("[");return c+=o.move(n.containerPhrasing(e,{before:c,after:"](",...o.current()})),c+=o.move("]("),u(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(u=n.enter("destinationLiteral"),c+=o.move("<"),c+=o.move(n.safe(e.url,{before:c,after:">",...o.current()})),c+=o.move(">")):(u=n.enter("destinationRaw"),c+=o.move(n.safe(e.url,{before:c,after:e.title?" ":")",...o.current()}))),u(),e.title&&(u=n.enter(`title${i}`),c+=o.move(" "+s),c+=o.move(n.safe(e.title,{before:c,after:s,...o.current()})),c+=o.move(s),u()),c+=o.move(")"),a(),c}function hC(e,t,n){return eh(e,n)?"<":"["}nh.peek=fC;function nh(e,t,n,r){const s=e.referenceType,i=n.enter("linkReference");let o=n.enter("label");const a=n.createTracker(r);let u=a.move("[");const c=n.containerPhrasing(e,{before:u,after:"]",...a.current()});u+=a.move(c+"]["),o();const d=n.stack;n.stack=[],o=n.enter("reference");const h=n.safe(n.associationId(e),{before:u,after:"]",...a.current()});return o(),n.stack=d,i(),s==="full"||!c||c!==h?u+=a.move(h+"]"):s==="shortcut"?u=u.slice(0,-1):u+=a.move("]"),u}function fC(){return"["}function Uo(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function pC(e){const t=Uo(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function mC(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function rh(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function gC(e,t,n,r){const s=n.enter("list"),i=n.bulletCurrent;let o=e.ordered?mC(n):Uo(n);const a=e.ordered?o==="."?")":".":pC(n);let u=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){const d=e.children?e.children[0]:void 0;if((o==="*"||o==="-")&&d&&(!d.children||!d.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(u=!0),rh(n)===o&&d){let h=-1;for(;++h<e.children.length;){const f=e.children[h];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(o=a),n.bulletCurrent=o;const c=n.containerFlow(e,r);return n.bulletLastUsed=o,n.bulletCurrent=i,s(),c}function bC(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function EC(e,t,n,r){const s=bC(n);let i=n.bulletCurrent||Uo(n);t&&t.type==="list"&&t.ordered&&(i=(typeof t.start=="number"&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let o=i.length+1;(s==="tab"||s==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);const a=n.createTracker(r);a.move(i+" ".repeat(o-i.length)),a.shift(o);const u=n.enter("listItem"),c=n.indentLines(n.containerFlow(e,a.current()),d);return u(),c;function d(h,f,p){return f?(p?"":" ".repeat(o))+h:(p?i:i+" ".repeat(o-i.length))+h}}function TC(e,t,n,r){const s=n.enter("paragraph"),i=n.enter("phrasing"),o=n.containerPhrasing(e,r);return i(),s(),o}function yC(e,t,n,r){return(e.children.some(function(o){return Vd(o)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function CC(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}sh.peek=kC;function sh(e,t,n,r){const s=CC(n),i=n.enter("strong"),o=n.createTracker(r),a=o.move(s+s);let u=o.move(n.containerPhrasing(e,{after:s,before:a,...o.current()}));const c=u.charCodeAt(0),d=ts(r.before.charCodeAt(r.before.length-1),c,s);d.inside&&(u=tr(c)+u.slice(1));const h=u.charCodeAt(u.length-1),f=ts(r.after.charCodeAt(0),h,s);f.inside&&(u=u.slice(0,-1)+tr(h));const p=o.move(s+s);return i(),n.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},a+u+p}function kC(e,t,n){return n.options.strong||"*"}function SC(e,t,n,r){return n.safe(e.value,r)}function AC(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function _C(e,t,n){const r=(rh(n)+(n.options.ruleSpaces?" ":"")).repeat(AC(n));return n.options.ruleSpaces?r.slice(0,-1):r}const ih={blockquote:Ky,break:Mu,code:tC,definition:rC,emphasis:Kd,hardBreak:Mu,heading:aC,html:Xd,image:Qd,imageReference:Jd,inlineCode:Zd,link:th,linkReference:nh,list:gC,listItem:EC,paragraph:TC,root:yC,strong:sh,text:SC,thematicBreak:_C};function wC(){return{enter:{table:IC,tableData:Ru,tableHeader:Ru,tableRow:NC},exit:{codeText:LC,table:xC,tableData:ai,tableHeader:ai,tableRow:ai}}}function IC(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function xC(e){this.exit(e),this.data.inTable=void 0}function NC(e){this.enter({type:"tableRow",children:[]},e)}function ai(e){this.exit(e)}function Ru(e){this.enter({type:"tableCell",children:[]},e)}function LC(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,OC));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function OC(e,t){return t==="|"?t:e}function DC(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,s=t.stringLength,i=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
29
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:o,tableCell:u,tableRow:a}};function o(p,m,E,C){return c(d(p,E,C),p.align)}function a(p,m,E,C){const k=h(p,E,C),_=c([k]);return _.slice(0,_.indexOf(`
30
+ `))}function u(p,m,E,C){const k=E.enter("tableCell"),_=E.enter("phrasing"),N=E.containerPhrasing(p,{...C,before:i,after:i});return _(),k(),N}function c(p,m){return Wy(p,{align:m,alignDelimiters:r,padding:n,stringLength:s})}function d(p,m,E){const C=p.children;let k=-1;const _=[],N=m.enter("table");for(;++k<C.length;)_[k]=h(C[k],m,E);return N(),_}function h(p,m,E){const C=p.children;let k=-1;const _=[],N=m.enter("tableRow");for(;++k<C.length;)_[k]=u(C[k],p,m,E);return N(),_}function f(p,m,E){let C=ih.inlineCode(p,m,E);return E.stack.includes("tableCell")&&(C=C.replace(/\|/g,"\\$&")),C}}function vC(){return{exit:{taskListCheckValueChecked:Pu,taskListCheckValueUnchecked:Pu,paragraph:RC}}}function MC(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:PC}}}function Pu(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function RC(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const r=n.children[0];if(r&&r.type==="text"){const s=t.children;let i=-1,o;for(;++i<s.length;){const a=s[i];if(a.type==="paragraph"){o=a;break}}o===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(e)}function PC(e,t,n,r){const s=e.children[0],i=typeof e.checked=="boolean"&&s&&s.type==="paragraph",o="["+(e.checked?"x":" ")+"] ",a=n.createTracker(r);i&&a.move(o);let u=ih.listItem(e,t,n,{...r,...a.current()});return i&&(u=u.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,c)),u;function c(d){return d+o}}function BC(){return[gy(),By(),Vy(),wC(),vC()]}function UC(e){return{extensions:[by(),Uy(e),Yy(),DC(e),MC()]}}function Mr(e,t,n,r){const s=e.length;let i=0,o;if(t<0?t=-t>s?0:s+t:t=t>s?s:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);i<r.length;)o=r.slice(i,i+1e4),o.unshift(t,0),e.splice(...o),i+=1e4,t+=1e4}const Bu={}.hasOwnProperty;function HC(e){const t={};let n=-1;for(;++n<e.length;)FC(t,e[n]);return t}function FC(e,t){let n;for(n in t){const s=(Bu.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let o;if(i)for(o in i){Bu.call(s,o)||(s[o]=[]);const a=i[o];VC(s[o],Array.isArray(a)?a:a?[a]:[])}}}function VC(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);Mr(e,0,0,r)}const YC={tokenize:GC,partial:!0},oh={tokenize:KC,partial:!0},ah={tokenize:XC,partial:!0},uh={tokenize:QC,partial:!0},$C={tokenize:JC,partial:!0},lh={name:"wwwAutolink",tokenize:zC,previous:dh},ch={name:"protocolAutolink",tokenize:WC,previous:hh},lt={name:"emailAutolink",tokenize:qC,previous:fh},tt={};function jC(){return{text:tt}}let It=48;for(;It<123;)tt[It]=lt,It++,It===58?It=65:It===91&&(It=97);tt[43]=lt;tt[45]=lt;tt[46]=lt;tt[95]=lt;tt[72]=[lt,ch];tt[104]=[lt,ch];tt[87]=[lt,lh];tt[119]=[lt,lh];function qC(e,t,n){const r=this;let s,i;return o;function o(h){return!Ui(h)||!fh.call(r,r.previous)||Ho(r.events)?n(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),a(h))}function a(h){return Ui(h)?(e.consume(h),a):h===64?(e.consume(h),u):n(h)}function u(h){return h===46?e.check($C,d,c)(h):h===45||h===95||Po(h)?(i=!0,e.consume(h),u):d(h)}function c(h){return e.consume(h),s=!0,u}function d(h){return i&&s&&er(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(h)):n(h)}}function zC(e,t,n){const r=this;return s;function s(o){return o!==87&&o!==119||!dh.call(r,r.previous)||Ho(r.events)?n(o):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(YC,e.attempt(oh,e.attempt(ah,i),n),n)(o))}function i(o){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(o)}}function WC(e,t,n){const r=this;let s="",i=!1;return o;function o(h){return(h===72||h===104)&&hh.call(r,r.previous)&&!Ho(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),s+=String.fromCodePoint(h),e.consume(h),a):n(h)}function a(h){if(er(h)&&s.length<5)return s+=String.fromCodePoint(h),e.consume(h),a;if(h===58){const f=s.toLowerCase();if(f==="http"||f==="https")return e.consume(h),u}return n(h)}function u(h){return h===47?(e.consume(h),i?c:(i=!0,u)):n(h)}function c(h){return h===null||cy(h)||ke(h)||Ut(h)||xs(h)?n(h):e.attempt(oh,e.attempt(ah,d),n)(h)}function d(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(h)}}function GC(e,t,n){let r=0;return s;function s(o){return(o===87||o===119)&&r<3?(r++,e.consume(o),s):o===46&&r===3?(e.consume(o),i):n(o)}function i(o){return o===null?n(o):t(o)}}function KC(e,t,n){let r,s,i;return o;function o(c){return c===46||c===95?e.check(uh,u,a)(c):c===null||ke(c)||Ut(c)||c!==45&&xs(c)?u(c):(i=!0,e.consume(c),o)}function a(c){return c===95?r=!0:(s=r,r=void 0),e.consume(c),o}function u(c){return s||r||!i?n(c):t(c)}}function XC(e,t){let n=0,r=0;return s;function s(o){return o===40?(n++,e.consume(o),s):o===41&&r<n?i(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?e.check(uh,t,i)(o):o===null||ke(o)||Ut(o)?t(o):(e.consume(o),s)}function i(o){return o===41&&r++,e.consume(o),s}}function QC(e,t,n){return r;function r(a){return a===33||a===34||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===63||a===95||a===126?(e.consume(a),r):a===38?(e.consume(a),i):a===93?(e.consume(a),s):a===60||a===null||ke(a)||Ut(a)?t(a):n(a)}function s(a){return a===null||a===40||a===91||ke(a)||Ut(a)?t(a):r(a)}function i(a){return er(a)?o(a):n(a)}function o(a){return a===59?(e.consume(a),r):er(a)?(e.consume(a),o):n(a)}}function JC(e,t,n){return r;function r(i){return e.consume(i),s}function s(i){return Po(i)?n(i):t(i)}}function dh(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||ke(e)}function hh(e){return!er(e)}function fh(e){return!(e===47||Ui(e))}function Ui(e){return e===43||e===45||e===46||e===95||Po(e)}function Ho(e){let t=e.length,n=!1;for(;t--;){const r=e[t][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}function ZC(e,t,n){const r=[];let s=-1;for(;++s<e.length;){const i=e[s].resolveAll;i&&!r.includes(i)&&(t=i(t,n),r.push(i))}return t}function it(e,t,n,r){const s=r?r-1:Number.POSITIVE_INFINITY;let i=0;return o;function o(u){return st(u)?(e.enter(n),a(u)):t(u)}function a(u){return st(u)&&i++<s?(e.consume(u),a):(e.exit(n),t(u))}}const ek={partial:!0,tokenize:tk};function tk(e,t,n){return r;function r(i){return st(i)?it(e,s,"linePrefix")(i):s(i)}function s(i){return i===null||Jt(i)?t(i):n(i)}}const nk={tokenize:ck,partial:!0};function rk(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:ak,continuation:{tokenize:uk},exit:lk}},text:{91:{name:"gfmFootnoteCall",tokenize:ok},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:sk,resolveTo:ik}}}}function sk(e,t,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o;for(;s--;){const u=r.events[s][1];if(u.type==="labelImage"){o=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return a;function a(u){if(!o||!o._balanced)return n(u);const c=dr(r.sliceSerialize({start:o.end,end:r.now()}));return c.codePointAt(0)!==94||!i.includes(c.slice(1))?n(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),t(u))}}function ik(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},a=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",s,t],["exit",s,t],["enter",i,t],["enter",o,t],["exit",o,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...a),e}function ok(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,o;return a;function a(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),u}function u(h){return h!==94?n(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",c)}function c(h){if(i>999||h===93&&!o||h===null||h===91||ke(h))return n(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return s.includes(dr(r.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(h)}return ke(h)||(o=!0),i++,e.consume(h),h===92?d:c}function d(h){return h===91||h===92||h===93?(e.consume(h),i++,c):c(h)}}function ak(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,o=0,a;return u;function u(m){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),c}function c(m){return m===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):n(m)}function d(m){if(o>999||m===93&&!a||m===null||m===91||ke(m))return n(m);if(m===93){e.exit("chunkString");const E=e.exit("gfmFootnoteDefinitionLabelString");return i=dr(r.sliceSerialize(E)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return ke(m)||(a=!0),o++,e.consume(m),m===92?h:d}function h(m){return m===91||m===92||m===93?(e.consume(m),o++,d):d(m)}function f(m){return m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),s.includes(i)||s.push(i),it(e,p,"gfmFootnoteDefinitionWhitespace")):n(m)}function p(m){return t(m)}}function uk(e,t,n){return e.check(ek,t,e.attempt(nk,t,n))}function lk(e){e.exit("gfmFootnoteDefinition")}function ck(e,t,n){const r=this;return it(e,s,"gfmFootnoteDefinitionIndent",5);function s(i){const o=r.events[r.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?t(i):n(i)}}function dk(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:i,resolveAll:s};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function s(o,a){let u=-1;for(;++u<o.length;)if(o[u][0]==="enter"&&o[u][1].type==="strikethroughSequenceTemporary"&&o[u][1]._close){let c=u;for(;c--;)if(o[c][0]==="exit"&&o[c][1].type==="strikethroughSequenceTemporary"&&o[c][1]._open&&o[u][1].end.offset-o[u][1].start.offset===o[c][1].end.offset-o[c][1].start.offset){o[u][1].type="strikethroughSequence",o[c][1].type="strikethroughSequence";const d={type:"strikethrough",start:Object.assign({},o[c][1].start),end:Object.assign({},o[u][1].end)},h={type:"strikethroughText",start:Object.assign({},o[c][1].end),end:Object.assign({},o[u][1].start)},f=[["enter",d,a],["enter",o[c][1],a],["exit",o[c][1],a],["enter",h,a]],p=a.parser.constructs.insideSpan.null;p&&Mr(f,f.length,0,ZC(p,o.slice(c+1,u),a)),Mr(f,f.length,0,[["exit",h,a],["enter",o[u][1],a],["exit",o[u][1],a],["exit",d,a]]),Mr(o,c-1,u-c+3,f),u=c+f.length-2;break}}for(u=-1;++u<o.length;)o[u][1].type==="strikethroughSequenceTemporary"&&(o[u][1].type="data");return o}function i(o,a,u){const c=this.previous,d=this.events;let h=0;return f;function f(m){return c===126&&d[d.length-1][1].type!=="characterEscape"?u(m):(o.enter("strikethroughSequenceTemporary"),p(m))}function p(m){const E=es(c);if(m===126)return h>1?u(m):(o.consume(m),h++,p);if(h<2&&!n)return u(m);const C=o.exit("strikethroughSequenceTemporary"),k=es(m);return C._open=!k||k===2&&!!E,C._close=!E||E===2&&!!k,a(m)}}}class hk{constructor(){this.map=[]}add(t,n,r){fk(this,t,n,r)}consume(t){if(this.map.sort(function(i,o){return i[0]-o[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let s=r.pop();for(;s;){for(const i of s)t.push(i);s=r.pop()}this.map.length=0}}function fk(e,t,n,r){let s=0;if(!(n===0&&r.length===0)){for(;s<e.map.length;){if(e.map[s][0]===t){e.map[s][1]+=n,e.map[s][2].push(...r);return}s+=1}e.map.push([t,n,r])}}function pk(e,t){let n=!1;const r=[];for(;t<e.length;){const s=e[t];if(n){if(s[0]==="enter")s[1].type==="tableContent"&&r.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(s[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const i=r.length-1;r[i]=r[i]==="left"?"center":"right"}}else if(s[1].type==="tableDelimiterRow")break}else s[0]==="enter"&&s[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return r}function mk(){return{flow:{null:{name:"table",tokenize:gk,resolveAll:bk}}}}function gk(e,t,n){const r=this;let s=0,i=0,o;return a;function a(A){let Sn=r.events.length-1;for(;Sn>-1;){const Xo=r.events[Sn][1].type;if(Xo==="lineEnding"||Xo==="linePrefix")Sn--;else break}const Go=Sn>-1?r.events[Sn][1].type:null,Ko=Go==="tableHead"||Go==="tableRow"?O:u;return Ko===O&&r.parser.lazy[r.now().line]?n(A):Ko(A)}function u(A){return e.enter("tableHead"),e.enter("tableRow"),c(A)}function c(A){return A===124||(o=!0,i+=1),d(A)}function d(A){return A===null?n(A):Jt(A)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),p):n(A):st(A)?it(e,d,"whitespace")(A):(i+=1,o&&(o=!1,s+=1),A===124?(e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),o=!0,d):(e.enter("data"),h(A)))}function h(A){return A===null||A===124||ke(A)?(e.exit("data"),d(A)):(e.consume(A),A===92?f:h)}function f(A){return A===92||A===124?(e.consume(A),h):h(A)}function p(A){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(A):(e.enter("tableDelimiterRow"),o=!1,st(A)?it(e,m,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):m(A))}function m(A){return A===45||A===58?C(A):A===124?(o=!0,e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),E):U(A)}function E(A){return st(A)?it(e,C,"whitespace")(A):C(A)}function C(A){return A===58?(i+=1,o=!0,e.enter("tableDelimiterMarker"),e.consume(A),e.exit("tableDelimiterMarker"),k):A===45?(i+=1,k(A)):A===null||Jt(A)?L(A):U(A)}function k(A){return A===45?(e.enter("tableDelimiterFiller"),_(A)):U(A)}function _(A){return A===45?(e.consume(A),_):A===58?(o=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(A),e.exit("tableDelimiterMarker"),N):(e.exit("tableDelimiterFiller"),N(A))}function N(A){return st(A)?it(e,L,"whitespace")(A):L(A)}function L(A){return A===124?m(A):A===null||Jt(A)?!o||s!==i?U(A):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(A)):U(A)}function U(A){return n(A)}function O(A){return e.enter("tableRow"),j(A)}function j(A){return A===124?(e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),j):A===null||Jt(A)?(e.exit("tableRow"),t(A)):st(A)?it(e,j,"whitespace")(A):(e.enter("data"),Me(A))}function Me(A){return A===null||A===124||ke(A)?(e.exit("data"),j(A)):(e.consume(A),A===92?re:Me)}function re(A){return A===92||A===124?(e.consume(A),Me):Me(A)}}function bk(e,t){let n=-1,r=!0,s=0,i=[0,0,0,0],o=[0,0,0,0],a=!1,u=0,c,d,h;const f=new hk;for(;++n<e.length;){const p=e[n],m=p[1];p[0]==="enter"?m.type==="tableHead"?(a=!1,u!==0&&(Uu(f,t,u,c,d),d=void 0,u=0),c={type:"table",start:Object.assign({},m.start),end:Object.assign({},m.end)},f.add(n,0,[["enter",c,t]])):m.type==="tableRow"||m.type==="tableDelimiterRow"?(r=!0,h=void 0,i=[0,0,0,0],o=[0,n+1,0,0],a&&(a=!1,d={type:"tableBody",start:Object.assign({},m.start),end:Object.assign({},m.end)},f.add(n,0,[["enter",d,t]])),s=m.type==="tableDelimiterRow"?2:d?3:1):s&&(m.type==="data"||m.type==="tableDelimiterMarker"||m.type==="tableDelimiterFiller")?(r=!1,o[2]===0&&(i[1]!==0&&(o[0]=o[1],h=Sr(f,t,i,s,void 0,h),i=[0,0,0,0]),o[2]=n)):m.type==="tableCellDivider"&&(r?r=!1:(i[1]!==0&&(o[0]=o[1],h=Sr(f,t,i,s,void 0,h)),i=o,o=[i[1],n,0,0])):m.type==="tableHead"?(a=!0,u=n):m.type==="tableRow"||m.type==="tableDelimiterRow"?(u=n,i[1]!==0?(o[0]=o[1],h=Sr(f,t,i,s,n,h)):o[1]!==0&&(h=Sr(f,t,o,s,n,h)),s=0):s&&(m.type==="data"||m.type==="tableDelimiterMarker"||m.type==="tableDelimiterFiller")&&(o[3]=n)}for(u!==0&&Uu(f,t,u,c,d),f.consume(t.events),n=-1;++n<t.events.length;){const p=t.events[n];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=pk(t.events,n))}return e}function Sr(e,t,n,r,s,i){const o=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",a="tableContent";n[0]!==0&&(i.end=Object.assign({},Xt(t.events,n[0])),e.add(n[0],0,[["exit",i,t]]));const u=Xt(t.events,n[1]);if(i={type:o,start:Object.assign({},u),end:Object.assign({},u)},e.add(n[1],0,[["enter",i,t]]),n[2]!==0){const c=Xt(t.events,n[2]),d=Xt(t.events,n[3]),h={type:a,start:Object.assign({},c),end:Object.assign({},d)};if(e.add(n[2],0,[["enter",h,t]]),r!==2){const f=t.events[n[2]],p=t.events[n[3]];if(f[1].end=Object.assign({},p[1].end),f[1].type="chunkText",f[1].contentType="text",n[3]>n[2]+1){const m=n[2]+1,E=n[3]-n[2]-1;e.add(m,E,[])}}e.add(n[3]+1,0,[["exit",h,t]])}return s!==void 0&&(i.end=Object.assign({},Xt(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function Uu(e,t,n,r,s){const i=[],o=Xt(t.events,n);s&&(s.end=Object.assign({},o),i.push(["exit",s,t])),r.end=Object.assign({},o),i.push(["exit",r,t]),e.add(n+1,0,i)}function Xt(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const Ek={name:"tasklistCheck",tokenize:yk};function Tk(){return{text:{91:Ek}}}function yk(e,t,n){const r=this;return s;function s(u){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),i)}function i(u){return ke(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),o):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),o):n(u)}function o(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),a):n(u)}function a(u){return Jt(u)?t(u):st(u)?e.check({tokenize:Ck},t,n)(u):n(u)}}function Ck(e,t,n){return it(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function kk(e){return HC([jC(),rk(),dk(e),mk(),Tk()])}const Sk={};function Ak(e){const t=this,n=e||Sk,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),o=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(kk(n)),i.push(BC()),o.push(UC(n))}function _k(e,t){return ph(e,{})||{type:"root",children:[]}}function ph(e,t){const n=wk(e,t);return n&&t.afterTransform&&t.afterTransform(e,n),n}function wk(e,t){switch(e.nodeType){case 1:return Lk(e,t);case 3:return xk(e);case 8:return Nk(e);case 9:return Hu(e,t);case 10:return Ik();case 11:return Hu(e,t);default:return}}function Hu(e,t){return{type:"root",children:mh(e,t)}}function Ik(){return{type:"doctype"}}function xk(e){return{type:"text",value:e.nodeValue||""}}function Nk(e){return{type:"comment",value:e.nodeValue||""}}function Lk(e,t){const n=e.namespaceURI,r=n===Or.svg?Hc:Uc,s=n===Or.html?e.tagName.toLowerCase():e.tagName,i=n===Or.html&&s==="template"?e.content:e,o=e.getAttributeNames(),a={};let u=-1;for(;++u<o.length;)a[o[u]]=e.getAttribute(o[u])||"";return r(s,a,mh(i,t))}function mh(e,t){const n=e.childNodes,r=[];let s=-1;for(;++s<n.length;){const i=ph(n[s],t);i!==void 0&&r.push(i)}return r}var Ok=Object.defineProperty,Dk=(e,t,n)=>t in e?Ok(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Y=(e,t,n)=>Dk(e,typeof t!="symbol"?t+"":t,n);function gh(e){const t=Array.from(e.classList).filter(n=>!n.startsWith("bn-"))||[];t.length>0?e.className=t.join(" "):e.removeAttribute("class")}function bh(e,t,n,r){var s;let i;if(t)if(typeof t=="string")i=Et([t],e.pmSchema);else if(Array.isArray(t))i=Et(t,e.pmSchema);else if(t.type==="tableContent")i=Ki(t,e.pmSchema);else throw new gn(t.type);else throw new Error("blockContent is required");const o=((r==null?void 0:r.document)??document).createDocumentFragment();for(const a of i)if(a.type.name!=="text"&&e.schema.inlineContentSchema[a.type.name]){const u=e.schema.inlineContentSpecs[a.type.name].implementation;if(u){const c=hl(a,e.schema.inlineContentSchema,e.schema.styleSchema),d=u.toExternalHTML?u.toExternalHTML(c,e):u.render.call({renderType:"dom",props:void 0},c,()=>{},e);if(d){if(o.appendChild(d.dom),d.contentDOM){const h=n.serializeFragment(a.content,r);d.contentDOM.dataset.editable="",d.contentDOM.appendChild(h)}continue}}}else if(a.type.name==="text"){let u=document.createTextNode(a.textContent);for(const c of a.marks.toReversed())if(c.type.name in e.schema.styleSpecs){const d=(e.schema.styleSpecs[c.type.name].implementation.toExternalHTML??e.schema.styleSpecs[c.type.name].implementation.render)(c.attrs.stringValue,e);d.contentDOM.appendChild(u),u=d.dom}else{const d=c.type.spec.toDOM(c,!0),h=X.DOMSerializer.renderSpec(document,d);h.contentDOM.appendChild(u),u=h.dom}o.appendChild(u)}else{const u=n.serializeFragment(X.Fragment.from([a]),r);o.appendChild(u)}return o.childNodes.length===1&&((s=o.firstChild)==null?void 0:s.nodeType)===1&&gh(o.firstChild),o}function vk(e,t,n,r,s,i,o){var a,u,c,d,h,f,p,m,E;const C=(o==null?void 0:o.document)??document,k=t.pmSchema.nodes.blockContainer,_=n.props||{};for(const[re,A]of Object.entries(t.schema.blockSchema[n.type].propSchema))!(re in _)&&A.default!==void 0&&(_[re]=A.default);const N=(u=(a=k.spec)==null?void 0:a.toDOM)==null?void 0:u.call(a,k.create({id:n.id,..._})),L=Array.from(N.dom.attributes),U=t.blockImplementations[n.type].implementation,O=((c=U.toExternalHTML)==null?void 0:c.call({},{...n,props:_},t))||U.render.call({},{...n,props:_},t),j=C.createDocumentFragment();if(O.dom.classList.contains("bn-block-content")){const re=[...L,...Array.from(O.dom.attributes)].filter(A=>A.name.startsWith("data")&&A.name!=="data-content-type"&&A.name!=="data-file-block"&&A.name!=="data-node-view-wrapper"&&A.name!=="data-node-type"&&A.name!=="data-id"&&A.name!=="data-editable");for(const A of re)O.dom.firstChild.setAttribute(A.name,A.value);gh(O.dom.firstChild),j.append(...Array.from(O.dom.childNodes))}else j.append(O.dom);if(O.contentDOM&&n.content){const re=bh(t,n.content,r,o);O.contentDOM.appendChild(re)}let Me;if(s.has(n.type)?Me="OL":i.has(n.type)&&(Me="UL"),Me){if(((d=e.lastChild)==null?void 0:d.nodeName)!==Me){const re=C.createElement(Me);Me==="OL"&&"start"in _&&_.start&&(_==null?void 0:_.start)!==1&&re.setAttribute("start",_.start+""),e.append(re)}e.lastChild.appendChild(j)}else e.append(j);if(n.children&&n.children.length>0){const re=C.createDocumentFragment();if(Eh(re,t,n.children,r,s,i,o),((h=e.lastChild)==null?void 0:h.nodeName)==="UL"||((f=e.lastChild)==null?void 0:f.nodeName)==="OL")for(;((p=re.firstChild)==null?void 0:p.nodeName)==="UL"||((m=re.firstChild)==null?void 0:m.nodeName)==="OL";)e.lastChild.lastChild.appendChild(re.firstChild);t.pmSchema.nodes[n.type].isInGroup("blockContent")?e.append(re):(E=O.contentDOM)==null||E.append(re)}}const Eh=(e,t,n,r,s,i,o)=>{for(const a of n)vk(e,t,a,r,s,i,o)},Mk=(e,t,n,r,s,i)=>{const o=((i==null?void 0:i.document)??document).createDocumentFragment();return Eh(o,e,t,n,r,s,i),o},Rk=(e,t)=>{const n=X.DOMSerializer.fromSchema(e);return{exportBlocks:(r,s)=>{const i=Mk(t,r,n,new Set(["numberedListItem"]),new Set(["bulletListItem","checkListItem","toggleListItem"]),s),o=document.createElement("div");return o.append(i),o.innerHTML},exportInlineContent:(r,s)=>{const i=bh(t,r,n,s),o=document.createElement("div");return o.append(i.cloneNode(!0)),o.innerHTML}}};function Pk(e,t){if(t===0)return;const n=e.resolve(t);for(let r=n.depth;r>0;r--){const s=n.node(r);if(Xi(s))return s.attrs.id}}function Bk(e){return e.getMeta("paste")?{type:"paste"}:e.getMeta("uiEvent")==="drop"?{type:"drop"}:e.getMeta("history$")?{type:e.getMeta("history$").redo?"redo":"undo"}:e.getMeta("y-sync$")?e.getMeta("y-sync$").isUndoRedoOperation?{type:"undo-redo"}:{type:"yjs-remote"}:{type:"local"}}function Fu(e){const t="__root__",n={},r={},s=bt(e);return e.descendants((i,o)=>{if(!Xi(i))return!0;const a=Pk(e,o),u=a??t;r[u]||(r[u]=[]);const c=un(i,s);return n[i.attrs.id]={block:c,parentId:a},r[u].push(i.attrs.id),!0}),{byId:n,childrenByParent:r}}function Uk(e,t){const n=new Set;if(!e||!t)return n;const r=new Set(e),s=t.filter(E=>r.has(E)),i=e.filter(E=>s.includes(E));if(i.length<=1||s.length<=1)return n;const o={};for(let E=0;E<i.length;E++)o[i[E]]=E;const a=s.map(E=>o[E]),u=a.length,c=[],d=[],h=new Array(u).fill(-1),f=(E,C)=>{let k=0,_=E.length;for(;k<_;){const N=k+_>>>1;E[N]<C?k=N+1:_=N}return k};for(let E=0;E<u;E++){const C=a[E],k=f(c,C);k>0&&(h[E]=d[k-1]),k===c.length?(c.push(C),d.push(E)):(c[k]=C,d[k]=E)}const p=new Set;let m=d[d.length-1]??-1;for(;m!==-1;)p.add(m),m=h[m];for(let E=0;E<s.length;E++)p.has(E)||n.add(s[E]);return n}function Hk(e,t=[]){const n=Bk(e),r=v.combineTransactionSteps(e.before,[e,...t]),s=Fu(r.before),i=Fu(r.doc),o=[],a=new Set;Object.keys(i.byId).filter(p=>!(p in s.byId)).forEach(p=>{o.push({type:"insert",block:i.byId[p].block,source:n,prevBlock:void 0}),a.add(p)}),Object.keys(s.byId).filter(p=>!(p in i.byId)).forEach(p=>{o.push({type:"delete",block:s.byId[p].block,source:n,prevBlock:void 0}),a.add(p)}),Object.keys(i.byId).filter(p=>p in s.byId).forEach(p=>{var m,E;const C=s.byId[p],k=i.byId[p];C.parentId!==k.parentId?(o.push({type:"move",block:k.block,prevBlock:C.block,source:n,prevParent:C.parentId?(m=s.byId[C.parentId])==null?void 0:m.block:void 0,currentParent:k.parentId?(E=i.byId[k.parentId])==null?void 0:E.block:void 0}),a.add(p)):sf({...C.block,children:void 0},{...k.block,children:void 0})||(o.push({type:"update",block:k.block,prevBlock:C.block,source:n}),a.add(p))});const u=s.childrenByParent,c=i.childrenByParent,d="__root__",h=new Set([...Object.keys(u),...Object.keys(c)]),f=new Set;return h.forEach(p=>{const m=Uk(u[p],c[p]);m.size!==0&&m.forEach(E=>{var C,k;const _=s.byId[E],N=i.byId[E];!_||!N||_.parentId!==N.parentId||a.has(E)||(_.parentId??d)!==p||f.has(E)||(f.add(E),o.push({type:"move",block:N.block,prevBlock:_.block,source:n,prevParent:_.parentId?(C=s.byId[_.parentId])==null?void 0:C.block:void 0,currentParent:N.parentId?(k=i.byId[N.parentId])==null?void 0:k.block:void 0}),a.add(E))})}),o}function Fk(){const e=t=>{let n=t.children.length;for(let r=0;r<n;r++){const s=t.children[r];if(s.type==="element"&&(e(s),s.tagName==="u"))if(s.children.length>0){t.children.splice(r,1,...s.children);const i=s.children.length-1;n+=i,r+=i}else t.children.splice(r,1),n--,r--}};return e}function Vk(){const e=t=>{var n;if(t.children&&"length"in t.children&&t.children.length)for(let r=t.children.length-1;r>=0;r--){const s=t.children[r],i=r+1<t.children.length?t.children[r+1]:void 0;s.type==="element"&&s.tagName==="input"&&((n=s.properties)==null?void 0:n.type)==="checkbox"&&(i==null?void 0:i.type)==="element"&&i.tagName==="p"?(i.tagName="span",i.children.splice(0,0,_k(document.createTextNode(" ")))):e(s)}};return e}function Yk(){return e=>{mn(e,"element",(t,n,r)=>{var s,i,o,a;if(r&&t.tagName==="video"){const u=((s=t.properties)==null?void 0:s.src)||((i=t.properties)==null?void 0:i["data-url"])||"",c=((o=t.properties)==null?void 0:o.title)||((a=t.properties)==null?void 0:a["data-name"])||"";r.children[n]={type:"text",value:`![${c}](${u})`}}})}}function $k(e){return Jh.unified().use(LT,{fragment:!0}).use(Yk).use(Fk).use(Vk).use(ly).use(Ak).use(ef.default,{handlers:{text:t=>t.value}}).processSync(e).value}function jk(e){const t=[];return e.descendants(n=>{var r,s;const i=bt(n);return n.type.name==="blockContainer"&&((r=n.firstChild)==null?void 0:r.type.name)==="blockGroup"?!0:n.type.name==="columnList"&&n.childCount===1?((s=n.firstChild)==null||s.forEach(o=>{t.push(un(o,i))}),!1):n.type.isInGroup("bnBlock")?(t.push(un(n,i)),!1):!0}),t}$(()=>{const e=[];return{key:"blockChange",prosemirrorPlugins:[new D.Plugin({key:new D.PluginKey("blockChange"),filterTransaction:t=>{let n;return e.reduce((r,s)=>r===!1?r:s({getChanges(){return n||(n=Hk(t),n)},tr:t})!==!1,!0)}})],subscribe(t){return e.push(t),()=>{e.splice(e.indexOf(t),1)}}}});function Vu(e){const t=e.charAt(0)==="#"?e.substring(1,7):e,n=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),s=parseInt(t.substring(4,6),16),i=[n/255,r/255,s/255].map(o=>o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4));return .2126*i[0]+.7152*i[1]+.0722*i[2]<=.179}function qk(e){const t=document.createElement("span");t.classList.add("bn-collaboration-cursor__base");const n=document.createElement("span");n.setAttribute("contentedEditable","false"),n.classList.add("bn-collaboration-cursor__caret"),n.setAttribute("style",`background-color: ${e.color}; color: ${Vu(e.color)?"white":"black"}`);const r=document.createElement("span");return r.classList.add("bn-collaboration-cursor__label"),r.setAttribute("style",`background-color: ${e.color}; color: ${Vu(e.color)?"white":"black"}`),r.insertBefore(document.createTextNode(e.name),null),n.insertBefore(r,null),t.insertBefore(document.createTextNode("⁠"),null),t.insertBefore(n,null),t.insertBefore(document.createTextNode("⁠"),null),t}const Yu=$(({options:e})=>{const t=new Map;return e.provider&&"awareness"in e.provider&&typeof e.provider.awareness=="object"&&("setLocalStateField"in e.provider.awareness&&typeof e.provider.awareness.setLocalStateField=="function"&&e.provider.awareness.setLocalStateField("user",e.user),"on"in e.provider.awareness&&typeof e.provider.awareness.on=="function"&&e.showCursorLabels!=="always"&&e.provider.awareness.on("change",({updated:n})=>{for(const r of n){const s=t.get(r);s&&(s.element.setAttribute("data-active",""),s.hideTimeout&&clearTimeout(s.hideTimeout),t.set(r,{element:s.element,hideTimeout:setTimeout(()=>{s.element.removeAttribute("data-active")},2e3)}))}})),{key:"yCursor",prosemirrorPlugins:[Ie.yCursorPlugin(e.provider.awareness,{selectionBuilder:Ie.defaultSelectionBuilder,cursorBuilder(n,r){let s=t.get(r);if(!s){const i=(e.renderCursor??qk)(n);e.showCursorLabels!=="always"&&(i.addEventListener("mouseenter",()=>{const o=t.get(r);o.element.setAttribute("data-active",""),o.hideTimeout&&(clearTimeout(o.hideTimeout),t.set(r,{element:o.element,hideTimeout:void 0}))}),i.addEventListener("mouseleave",()=>{const o=t.get(r);t.set(r,{element:o.element,hideTimeout:setTimeout(()=>{o.element.removeAttribute("data-active")},2e3)})})),s={element:i,hideTimeout:void 0},t.set(r,s)}return s.element}})],dependsOn:["ySync"],updateUser(n){e.provider.awareness.setLocalStateField("user",n)}}}),ui=$(({options:e})=>({key:"ySync",prosemirrorPlugins:[Ie.ySyncPlugin(e.fragment)],runsBefore:["default"]})),li=$(({editor:e})=>({key:"yUndo",prosemirrorPlugins:[Ie.yUndoPlugin({trackedOrigins:[e]})],dependsOn:["yCursor","ySync"],undoCommand:Ie.undoCommand,redoCommand:Ie.redoCommand}));function zk(e,t){const n=e.doc;if(e._item===null){const r=Array.from(n.share.keys()).find(s=>n.share.get(s)===e);if(r==null)throw new Error("type does not exist in other ydoc");return t.get(r,e.constructor)}else{const r=e._item,s=t.store.clients.get(r.id.client)??[],i=Ue(s,r.id.clock);return s[i].content.type}}const ci=$(({editor:e,options:t})=>{let n;const r=Ht({isForked:!1});return{key:"yForkDoc",store:r,fork(){if(n)return;const s=t.fragment;if(!s)throw new Error("No fragment to fork from");const i=new Tn;Ia(i,xa(s.doc));const o=zk(s,i);n={undoStack:Ie.yUndoPluginKey.getState(e.prosemirrorState).undoManager.undoStack,originalFragment:s,forkedFragment:o},e.unregisterExtension([li,Yu,ui]);const a={...t,fragment:o};e.registerExtension([ui(a),li({})]),r.setState({isForked:!0})},merge({keepChanges:s}){if(!n)return;e.unregisterExtension(["ySync","yCursor","yUndo"]);const{originalFragment:i,forkedFragment:o,undoStack:a}=n;if(e.registerExtension([ui(t),Yu(t),li({})]),Ie.yUndoPluginKey.getState(e.prosemirrorState).undoManager.undoStack=a,s){const u=xa(o.doc,Zm(i.doc));Ia(i.doc,u,e)}n=void 0,r.setState({isForked:!1})}}}),Th=(e,t)=>{t(e),e.forEach(n=>{n instanceof St&&Th(n,t)})},Wk=(e,t)=>{const n=new Map;return e.forEach(r=>{r instanceof St&&Th(r,s=>{if(s.nodeName==="blockContainer"&&s.hasAttribute("id")){const i=s.getAttribute("textColor"),o=s.getAttribute("backgroundColor"),a={textColor:i===Q.textColor.default?void 0:i,backgroundColor:o===Q.backgroundColor.default?void 0:o};(a.textColor||a.backgroundColor)&&n.set(s.getAttribute("id"),a)}})}),n.size===0?!1:(t.doc.descendants((r,s)=>{if(r.type.name==="blockContainer"&&n.has(r.attrs.id)){const i=t.doc.nodeAt(s+1);if(!i)throw new Error("No element found");t.setNodeMarkup(s+1,void 0,{...i.attrs,...n.get(r.attrs.id)})}}),!0)},Gk=[Wk];$(({options:e})=>{let t=!1;const n=new D.PluginKey("schemaMigration");return{key:"schemaMigration",prosemirrorPlugins:[new D.Plugin({key:n,appendTransaction:(r,s,i)=>{if(t||!r.some(a=>a.getMeta("y-sync$"))||r.every(a=>!a.docChanged)||!e.fragment.firstChild)return;const o=i.tr;for(const a of Gk)a(e.fragment,o);if(t=!0,!!o.docChanged)return o}})]}});$(({editor:e,options:t})=>({key:"dropCursor",prosemirrorPlugins:[(t.dropCursor??t1)({width:5,color:"#ddeeff",editor:e})]}));const Kk=$(({editor:e})=>{const t=Ht(!1),n=()=>e.transact(r=>{var s;if(r.selection.empty||r.selection instanceof D.NodeSelection&&(r.selection.node.type.spec.content==="inline*"||((s=r.selection.node.firstChild)==null?void 0:s.type.spec.content)==="inline*")||r.selection instanceof D.TextSelection&&r.doc.textBetween(r.selection.from,r.selection.to).length===0)return!1;let i=!1;return r.selection.content().content.descendants(o=>(o.type.spec.code&&(i=!0),!i)),!i});return{key:"formattingToolbar",store:t,mount({dom:r,signal:s}){let i=!1;const o=e.onChange(()=>{i||t.setState(n())}),a=e.onSelectionChange(()=>{i||t.setState(n())});r.addEventListener("pointerdown",()=>{i=!0,t.setState(!1)},{signal:s}),e.prosemirrorView.root.addEventListener("pointerup",()=>{i=!1,e.isFocused()&&t.setState(n())},{signal:s,capture:!0}),r.addEventListener("pointercancel",()=>{i=!1},{signal:s,capture:!0}),s.addEventListener("abort",()=>{o(),a()})}}});$(()=>({key:"history",prosemirrorPlugins:[d1()],undoCommand:Ic,redoCommand:xc}));$(({editor:e})=>{function t(s){let i=e.prosemirrorView.nodeDOM(s);for(;i&&i.parentElement;){if(i.nodeName==="A")return i;i=i.parentElement}return null}function n(s,i){return e.transact(o=>{const a=o.doc.resolve(s),u=a.marks().find(d=>d.type.name===i);if(!u)return;const c=v.getMarkRange(a,u.type);if(c)return{range:c,mark:u,get text(){return o.doc.textBetween(c.from,c.to)},get position(){return v.posToDOMRect(e.prosemirrorView,c.from,c.to).toJSON()}}})}function r(){return e.transact(s=>{const i=s.selection;if(i.empty)return n(i.anchor,"link")})}return{key:"linkToolbar",getLinkAtSelection:r,getLinkElementAtPos:t,getMarkAtPos:n,getLinkAtElement(s){return e.transact(()=>{const i=e.prosemirrorView.posAtDOM(s,0)+1;return n(i,"link")})},editLink(s,i,o=e.transact(a=>a.selection.anchor)){e.transact(a=>{const u=bt(a),{range:c}=n(o+1,"link")||{range:{from:a.selection.from,to:a.selection.to}};c&&(a.insertText(i,c.from,c.to),a.addMark(c.from,c.from+i.length,u.mark("link",{href:s})))}),e.prosemirrorView.focus()},deleteLink(s=e.transact(i=>i.selection.anchor)){e.transact(i=>{const o=bt(i),{range:a}=n(s+1,"link")||{range:{from:i.selection.from,to:i.selection.to}};a&&i.removeMark(a.from,a.to,o.marks.link).setMeta("preventAutolink",!0)}),e.prosemirrorView.focus()}}});const Xk=new D.PluginKey("node-selection-keyboard");$(()=>({key:"nodeSelectionKeyboard",prosemirrorPlugins:[new D.Plugin({key:Xk,props:{handleKeyDown:(e,t)=>{if("node"in e.state.selection){if(t.ctrlKey||t.metaKey)return!1;if(t.key.length===1)return t.preventDefault(),!0;if(t.key==="Enter"&&!t.shiftKey&&!t.altKey&&!t.ctrlKey&&!t.metaKey){const n=e.state.tr;return e.dispatch(n.insert(e.state.tr.selection.$to.after(),e.state.schema.nodes.paragraph.createChecked()).setSelection(new D.TextSelection(n.doc.resolve(e.state.tr.selection.$to.after()+1)))),!0}}return!1}}})]}));const Qk=new D.PluginKey("blocknote-placeholder");$(({editor:e,options:t})=>{const n=t.placeholders;return{key:"placeholder",prosemirrorPlugins:[new D.Plugin({key:Qk,view:r=>{const s=`placeholder-selector-${al()}`;r.dom.classList.add(s);const i=document.createElement("style"),o=e._tiptapEditor.options.injectNonce;o&&i.setAttribute("nonce",o),r.root instanceof window.ShadowRoot?r.root.append(i):r.root.head.appendChild(i);const a=i.sheet,u=(c="")=>`.${s} .bn-block-content${c} .bn-inline-content:has(> .ProseMirror-trailingBreak:only-child):before`;try{const{default:c,emptyDocument:d,...h}=n||{};for(const[m,E]of Object.entries(h)){const C=`[data-content-type="${m}"]`;a.insertRule(`${u(C)} { content: ${JSON.stringify(E)}; }`)}a.insertRule(`${u("[data-is-only-empty-block]")} { content: ${JSON.stringify(d)}; }`),a.insertRule(`${u("[data-is-empty-and-focused]")} { content: ${JSON.stringify(c)}; }`)}catch(c){console.warn("Failed to insert placeholder CSS rule - this is likely due to the browser not supporting certain CSS pseudo-element selectors (:has, :only-child:, or :before)",c)}return{destroy:()=>{r.root instanceof window.ShadowRoot?r.root.removeChild(i):r.root.head.removeChild(i)}}},props:{decorations:r=>{const{doc:s,selection:i}=r;if(!e.isEditable||!i.empty||i.$from.parent.type.spec.code)return;const o=[];r.doc.content.size===6&&o.push(G.Decoration.node(2,4,{"data-is-only-empty-block":"true"}));const a=i.$anchor,u=a.parent;if(u.content.size===0){const c=a.before();o.push(G.Decoration.node(c,c+u.nodeSize,{"data-is-empty-and-focused":"true"}))}return G.DecorationSet.create(s,o)}}})]}});const $u=new D.PluginKey("previous-blocks"),Jk={index:"index",level:"level",type:"type",depth:"depth","depth-change":"depth-change"};$(()=>{let e;return{key:"previousBlockType",prosemirrorPlugins:[new D.Plugin({key:$u,view(t){return{update:async(n,r)=>{var s;((s=this.key)==null?void 0:s.getState(n.state).updatedBlocks.size)>0&&(e=setTimeout(()=>{n.dispatch(n.state.tr.setMeta($u,{clearUpdate:!0}))},0))},destroy:()=>{e&&clearTimeout(e)}}},state:{init(){return{prevTransactionOldBlockAttrs:{},currentTransactionOldBlockAttrs:{},updatedBlocks:new Set}},apply(t,n,r,s){if(n.currentTransactionOldBlockAttrs={},n.updatedBlocks.clear(),!t.docChanged||r.doc.eq(s.doc))return n;const i={},o=v.findChildren(r.doc,c=>c.attrs.id),a=new Map(o.map(c=>[c.node.attrs.id,c])),u=v.findChildren(s.doc,c=>c.attrs.id);for(const c of u){const d=a.get(c.node.attrs.id),h=d==null?void 0:d.node.firstChild,f=c.node.firstChild;if(d&&h&&f){const p={index:f.attrs.index,level:f.attrs.level,type:f.type.name,depth:s.doc.resolve(c.pos).depth},m={index:h.attrs.index,level:h.attrs.level,type:h.type.name,depth:r.doc.resolve(d.pos).depth};i[c.node.attrs.id]=m,n.currentTransactionOldBlockAttrs[c.node.attrs.id]=m,JSON.stringify(m)!==JSON.stringify(p)&&(m["depth-change"]=m.depth-p.depth,n.updatedBlocks.add(c.node.attrs.id))}}return n.prevTransactionOldBlockAttrs=i,n}},props:{decorations(t){const n=this.getState(t);if(n.updatedBlocks.size===0)return;const r=[];return t.doc.descendants((s,i)=>{if(!s.attrs.id||!n.updatedBlocks.has(s.attrs.id))return;const o=n.currentTransactionOldBlockAttrs[s.attrs.id],a={};for(const[c,d]of Object.entries(o))a["data-prev-"+Jk[c]]=d||"none";const u=G.Decoration.node(i,i+s.nodeSize,{...a});r.push(u)}),G.DecorationSet.create(t.doc,r)}}})]}});function yh(e,t){for(var n,r;e&&e.parentElement&&e.parentElement!==t.dom&&((n=e.getAttribute)==null?void 0:n.call(e,"data-node-type"))!=="blockContainer";)e=e.parentElement;if(((r=e.getAttribute)==null?void 0:r.call(e,"data-node-type"))==="blockContainer")return{node:e,id:e.getAttribute("data-id")}}class vt extends D.Selection{constructor(t,n){super(t,n),Y(this,"nodes");const r=t.node();this.nodes=[],t.doc.nodesBetween(t.pos,n.pos,(s,i,o)=>{if(o!==null&&o.eq(r))return this.nodes.push(s),!1})}static create(t,n,r=n){return new vt(t.resolve(n),t.resolve(r))}content(){return new X.Slice(X.Fragment.from(this.nodes),0,0)}eq(t){if(!(t instanceof vt)||this.nodes.length!==t.nodes.length||this.from!==t.from||this.to!==t.to)return!1;for(let n=0;n<this.nodes.length;n++)if(!this.nodes[n].eq(t.nodes[n]))return!1;return!0}map(t,n){const r=n.mapResult(this.from),s=n.mapResult(this.to);return s.deleted?D.Selection.near(t.resolve(r.pos)):r.deleted?D.Selection.near(t.resolve(s.pos)):new vt(t.resolve(r.pos),t.resolve(s.pos))}toJSON(){return{type:"multiple-node",anchor:this.anchor,head:this.head}}}D.Selection.jsonID("multiple-node",vt);let Re;function Zk(e,t){let n,r;const s=t.resolve(e.from).node().type.spec.group==="blockContent",i=t.resolve(e.to).node().type.spec.group==="blockContent",o=Math.min(e.$anchor.depth,e.$head.depth);if(s&&i){const a=e.$from.start(o-1),u=e.$to.end(o-1);n=t.resolve(a-1).pos,r=t.resolve(u+1).pos}else n=e.from,r=e.to;return{from:n,to:r}}function ju(e,t,n=t){t===n&&(n+=e.state.doc.resolve(t+1).node().nodeSize);const r=e.domAtPos(t).node.cloneNode(!0),s=e.domAtPos(t).node,i=(d,h)=>Array.prototype.indexOf.call(d.children,h),o=i(s,e.domAtPos(t+1).node.parentElement),a=i(s,e.domAtPos(n-1).node.parentElement);for(let d=s.childElementCount-1;d>=0;d--)(d>a||d<o)&&r.removeChild(r.children[d]);Ch(e.root),Re=r;const u=Re.getElementsByTagName("iframe");for(let d=0;d<u.length;d++){const h=u[d],f=h.parentElement;f&&f.removeChild(h)}const c=e.dom.className.split(" ").filter(d=>d!=="ProseMirror"&&d!=="bn-root"&&d!=="bn-editor").join(" ");Re.className=Re.className+" bn-drag-preview "+c,e.root instanceof ShadowRoot?e.root.appendChild(Re):e.root.body.appendChild(Re)}function Ch(e){Re!==void 0&&(e instanceof ShadowRoot?e.removeChild(Re):e.body.removeChild(Re),Re=void 0)}function eS(e,t,n){if(!e.dataTransfer||n.headless)return;const r=n.prosemirrorView,s=Cl(t.id,r.state.doc);if(!s)throw new Error(`Block with ID ${t.id} not found`);const i=s.posBeforeNode;if(i!=null){const o=r.state.selection,a=r.state.doc,{from:u,to:c}=Zk(o,a),d=u<=i&&i<c,h=o.$anchor.node()!==o.$head.node()||o instanceof vt;d&&h?(r.dispatch(r.state.tr.setSelection(vt.create(a,u,c))),ju(r,u,c)):(r.dispatch(r.state.tr.setSelection(D.NodeSelection.create(r.state.doc,i))),ju(r,i));const f=r.state.selection.content(),p=n.pmSchema,m=r.serializeForClipboard(f).dom.innerHTML,E=Rk(p,n),C=jk(f.content),k=E.exportBlocks(C,{}),_=$k(k);e.dataTransfer.clearData(),e.dataTransfer.setData("blocknote/html",m),e.dataTransfer.setData("text/html",k),e.dataTransfer.setData("text/plain",_),e.dataTransfer.effectAllowed="move",e.dataTransfer.setDragImage(Re,0,0)}}const qu=250;function Hi(e,t,n=!0){const r=e.root.elementsFromPoint(t.left,t.top);for(const s of r)if(e.dom.contains(s))return n&&s.closest("[data-node-type=columnList]")?Hi(e,{left:t.left+50,top:t.top},!1):yh(s,e)}function tS(e,t){if(!t.dom.firstChild)return;const n=t.dom.firstChild.getBoundingClientRect(),r={left:Math.min(Math.max(n.left+10,e.x),n.right-10),top:e.y},s=Hi(t,r);if(!s)return;const i=s.node.getBoundingClientRect();return Hi(t,{left:i.right-10,top:e.y},!1)}class nS{constructor(t,n,r){Y(this,"state"),Y(this,"emitUpdate"),Y(this,"mousePos"),Y(this,"hoveredBlock"),Y(this,"menuFrozen",!1),Y(this,"isDragOrigin",!1),Y(this,"updateState",s=>{this.state=s,this.emitUpdate(this.state)}),Y(this,"updateStateFromMousePos",()=>{var s,i,o,a,u;if(this.menuFrozen||!this.mousePos)return;const c=this.findClosestEditorElement({clientX:this.mousePos.x,clientY:this.mousePos.y});if((c==null?void 0:c.element)!==this.pmView.dom||c.distance>qu){(s=this.state)!=null&&s.show&&(this.state.show=!1,this.updateState(this.state));return}const d=tS(this.mousePos,this.pmView);if(!d||!this.editor.isEditable){(i=this.state)!=null&&i.show&&(this.state.show=!1,this.updateState(this.state));return}if(!((o=this.state)!=null&&o.show&&(a=this.hoveredBlock)!=null&&a.hasAttribute("data-id")&&((u=this.hoveredBlock)==null?void 0:u.getAttribute("data-id"))===d.id)&&(this.hoveredBlock=d.node,this.editor.isEditable)){const h=d.node.getBoundingClientRect(),f=d.node.closest("[data-node-type=column]");this.state={show:!0,referencePos:new DOMRect(f?f.firstElementChild.getBoundingClientRect().x:this.pmView.dom.firstChild.getBoundingClientRect().x,h.y,h.width,h.height),block:this.editor.getBlock(this.hoveredBlock.getAttribute("data-id"))},this.updateState(this.state)}}),Y(this,"onDragStart",s=>{var i;const o=(i=s.dataTransfer)==null?void 0:i.getData("blocknote/html");if(!o||this.pmView.dragging)return;const a=document.createElement("div");a.innerHTML=o;const u=X.DOMParser.fromSchema(this.pmView.state.schema).parse(a,{topNode:this.pmView.state.schema.nodes.blockGroup.create()});this.pmView.dragging={slice:new X.Slice(u.content,0,0),move:!0}}),Y(this,"findClosestEditorElement",s=>{const i=Array.from(this.pmView.root.querySelectorAll(".bn-editor"));if(i.length===0)return null;let o=i[0],a=Number.MAX_VALUE;return i.forEach(u=>{const c=u.querySelector(".bn-block-group").getBoundingClientRect(),d=s.clientX<c.left?c.left-s.clientX:s.clientX>c.right?s.clientX-c.right:0,h=s.clientY<c.top?c.top-s.clientY:s.clientY>c.bottom?s.clientY-c.bottom:0,f=Math.sqrt(Math.pow(d,2)+Math.pow(h,2));f<a&&(a=f,o=u)}),{element:o,distance:a}}),Y(this,"onDragOver",s=>{if(s.synthetic)return;const i=this.getDragEventContext(s);if(!i||!i.isDropPoint){this.closeDropCursor();return}i.isDropPoint&&!i.isDropWithinEditorBounds&&this.dispatchSyntheticEvent(s)}),Y(this,"closeDropCursor",()=>{const s=new Event("dragleave",{bubbles:!1});s.synthetic=!0,this.pmView.dom.dispatchEvent(s)}),Y(this,"getDragEventContext",s=>{var i;const o=!((i=s.dataTransfer)!=null&&i.types.includes("blocknote/html"))&&!!this.pmView.dragging,a=!!this.isDragOrigin,u=o||a,c=this.findClosestEditorElement(s);if(!c||c.distance>qu)return;const d=c.element===this.pmView.dom,h=d&&c.distance===0;if(!(!d&&!u))return{isDropPoint:d,isDropWithinEditorBounds:h,isDragOrigin:u}}),Y(this,"onDrop",s=>{if(s.synthetic)return;const i=this.getDragEventContext(s);if(!i){this.closeDropCursor();return}const{isDropPoint:o,isDropWithinEditorBounds:a,isDragOrigin:u}=i;if(!a&&o&&this.dispatchSyntheticEvent(s),o){if(this.pmView.dragging)return;this.pmView.dispatch(this.pmView.state.tr.setSelection(D.TextSelection.create(this.pmView.state.tr.doc,this.pmView.state.tr.selection.anchor)));return}else if(u){setTimeout(()=>this.pmView.dispatch(this.pmView.state.tr.deleteSelection()),0);return}}),Y(this,"onDragEnd",s=>{s.synthetic||(this.pmView.dragging=null)}),Y(this,"onKeyDown",s=>{var i;(i=this.state)!=null&&i.show&&this.editor.isFocused()&&(this.state.show=!1,this.emitUpdate(this.state))}),Y(this,"onMouseMove",s=>{var i;if(this.menuFrozen)return;this.mousePos={x:s.clientX,y:s.clientY};const o=this.pmView.dom.getBoundingClientRect(),a=this.mousePos.x>o.left&&this.mousePos.x<o.right&&this.mousePos.y>o.top&&this.mousePos.y<o.bottom,u=this.pmView.dom.parentElement;if(a&&s&&s.target&&!(u===s.target||u.contains(s.target))){(i=this.state)!=null&&i.show&&(this.state.show=!1,this.emitUpdate(this.state));return}this.updateStateFromMousePos()}),this.editor=t,this.pmView=n,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized side menu");r(this.state)},this.pmView.root.addEventListener("dragstart",this.onDragStart),this.pmView.root.addEventListener("dragover",this.onDragOver),this.pmView.root.addEventListener("drop",this.onDrop,!0),this.pmView.root.addEventListener("dragend",this.onDragEnd,!0),this.pmView.root.addEventListener("mousemove",this.onMouseMove,!0),this.pmView.root.addEventListener("keydown",this.onKeyDown,!0)}dispatchSyntheticEvent(t){const n=new Event(t.type,t),r=this.pmView.dom.firstChild.getBoundingClientRect();n.clientX=t.clientX,n.clientY=t.clientY,n.clientX=Math.min(Math.max(t.clientX,r.left),r.left+r.width),n.clientY=Math.min(Math.max(t.clientY,r.top),r.top+r.height),n.dataTransfer=t.dataTransfer,n.preventDefault=()=>t.preventDefault(),n.synthetic=!0,this.pmView.dom.dispatchEvent(n)}update(t,n){var r;!n.doc.eq(this.pmView.state.doc)&&(r=this.state)!=null&&r.show&&this.updateStateFromMousePos()}destroy(){var t;(t=this.state)!=null&&t.show&&(this.state.show=!1,this.emitUpdate(this.state)),this.pmView.root.removeEventListener("mousemove",this.onMouseMove,!0),this.pmView.root.removeEventListener("dragstart",this.onDragStart),this.pmView.root.removeEventListener("dragover",this.onDragOver),this.pmView.root.removeEventListener("drop",this.onDrop,!0),this.pmView.root.removeEventListener("dragend",this.onDragEnd,!0),this.pmView.root.removeEventListener("keydown",this.onKeyDown,!0)}}const rS=new D.PluginKey("SideMenuPlugin");$(({editor:e})=>{let t;const n=Ht(void 0);return{key:"sideMenu",store:n,prosemirrorPlugins:[new D.Plugin({key:rS,view:r=>(t=new nS(e,r,s=>{n.setState({...s})}),t)})],blockDragStart(r,s){t&&(t.isDragOrigin=!0),eS(r,s,e)},blockDragEnd(){Ch(e.prosemirrorView.root),t&&(t.isDragOrigin=!1),e.blur()},freezeMenu(){t.menuFrozen=!0,t.state.show=!0,t.emitUpdate(t.state)},unfreezeMenu(){t.menuFrozen=!1,t.state.show=!1,t.emitUpdate(t.state)}}});let Ee;function zu(e){Ee||(Ee=document.createElement("div"),Ee.innerHTML="_",Ee.style.opacity="0",Ee.style.height="1px",Ee.style.width="1px",e instanceof Document?e.body.appendChild(Ee):e.appendChild(Ee))}function sS(e){Ee&&(e instanceof Document?e.body.removeChild(Ee):e.removeChild(Ee),Ee=void 0)}function Ar(e){return Array.prototype.indexOf.call(e.parentElement.childNodes,e)}function iS(e){let t=e;for(;t&&t.nodeName!=="TD"&&t.nodeName!=="TH"&&!t.classList.contains("tableWrapper");){if(t.classList.contains("ProseMirror"))return;const n=t.parentNode;if(!n||!(n instanceof Element))return;t=n}return t.nodeName==="TD"||t.nodeName==="TH"?{type:"cell",domNode:t,tbodyNode:t.closest("tbody")}:{type:"wrapper",domNode:t,tbodyNode:t.querySelector("tbody")}}function oS(e,t){const n=t.querySelectorAll(e);for(let r=0;r<n.length;r++)n[r].style.visibility="hidden"}class aS{constructor(t,n,r){Y(this,"state"),Y(this,"emitUpdate"),Y(this,"tableId"),Y(this,"tablePos"),Y(this,"tableElement"),Y(this,"menuFrozen",!1),Y(this,"mouseState","up"),Y(this,"prevWasEditable",null),Y(this,"viewMousedownHandler",()=>{this.mouseState="down"}),Y(this,"mouseUpHandler",s=>{this.mouseState="up",this.mouseMoveHandler(s)}),Y(this,"mouseMoveHandler",s=>{var i,o,a,u,c,d,h;if(this.menuFrozen||this.mouseState==="selecting"||!(s.target instanceof Element)||!this.pmView.dom.contains(s.target))return;const f=iS(s.target);if((f==null?void 0:f.type)==="cell"&&this.mouseState==="down"&&!((i=this.state)!=null&&i.draggingState)){this.mouseState="selecting",(o=this.state)!=null&&o.show&&(this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate());return}if(!f||!this.editor.isEditable){(a=this.state)!=null&&a.show&&(this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate());return}if(!f.tbodyNode)return;const p=f.tbodyNode.getBoundingClientRect(),m=yh(f.domNode,this.pmView);if(!m)return;this.tableElement=m.node;let E;const C=this.editor.transact(N=>Cl(m.id,N.doc));if(!C)throw new Error(`Block with ID ${m.id} not found`);const k=un(C.node,this.editor.pmSchema,this.editor.schema.blockSchema,this.editor.schema.inlineContentSchema,this.editor.schema.styleSchema);if(m0(this.editor,"table")&&(this.tablePos=C.posBeforeNode+1,E=k),!E)return;this.tableId=m.id;const _=(u=f.domNode.closest(".tableWrapper"))==null?void 0:u.querySelector(".table-widgets-container");if((f==null?void 0:f.type)==="wrapper"){const N=s.clientY>=p.bottom-1&&s.clientY<p.bottom+20,L=s.clientX>=p.right-1&&s.clientX<p.right+20,U=s.clientX>p.right||s.clientY>p.bottom;this.state={...this.state,show:!0,showAddOrRemoveRowsButton:N,showAddOrRemoveColumnsButton:L,referencePosTable:p,block:E,widgetContainer:_,colIndex:U||(c=this.state)==null?void 0:c.colIndex,rowIndex:U||(d=this.state)==null?void 0:d.rowIndex,referencePosCell:U||(h=this.state)==null?void 0:h.referencePosCell}}else{const N=Ar(f.domNode),L=Ar(f.domNode.parentElement),U=f.domNode.getBoundingClientRect();if(this.state!==void 0&&this.state.show&&this.tableId===m.id&&this.state.rowIndex===L&&this.state.colIndex===N)return;this.state={show:!0,showAddOrRemoveColumnsButton:N===E.content.rows[0].cells.length-1,showAddOrRemoveRowsButton:L===E.content.rows.length-1,referencePosTable:p,block:E,draggingState:void 0,referencePosCell:U,colIndex:N,rowIndex:L,widgetContainer:_}}return this.emitUpdate(),!1}),Y(this,"dragOverHandler",s=>{var i;if(((i=this.state)==null?void 0:i.draggingState)===void 0)return;s.preventDefault(),s.dataTransfer.dropEffect="move",oS(".prosemirror-dropcursor-block, .prosemirror-dropcursor-inline",this.pmView.root);const o={left:Math.min(Math.max(s.clientX,this.state.referencePosTable.left+1),this.state.referencePosTable.right-1),top:Math.min(Math.max(s.clientY,this.state.referencePosTable.top+1),this.state.referencePosTable.bottom-1)},a=this.pmView.root.elementsFromPoint(o.left,o.top).filter(E=>E.tagName==="TD"||E.tagName==="TH");if(a.length===0)return;const u=a[0];let c=!1;const d=Ar(u.parentElement),h=Ar(u),f=this.state.draggingState.draggedCellOrientation==="row"?this.state.rowIndex:this.state.colIndex,p=(this.state.draggingState.draggedCellOrientation==="row"?d:h)!==f;(this.state.rowIndex!==d||this.state.colIndex!==h)&&(this.state.rowIndex=d,this.state.colIndex=h,this.state.referencePosCell=u.getBoundingClientRect(),c=!0);const m=this.state.draggingState.draggedCellOrientation==="row"?o.top:o.left;this.state.draggingState.mousePos!==m&&(this.state.draggingState.mousePos=m,c=!0),c&&this.emitUpdate(),p&&this.editor.transact(E=>E.setMeta(On,!0))}),Y(this,"dropHandler",s=>{if(this.mouseState="up",this.state===void 0||this.state.draggingState===void 0)return!1;if(this.state.rowIndex===void 0||this.state.colIndex===void 0)throw new Error("Attempted to drop table row or column, but no table block was hovered prior.");s.preventDefault();const{draggingState:i,colIndex:o,rowIndex:a}=this.state,u=this.state.block.content.columnWidths;if(i.draggedCellOrientation==="row"){if(!pl(this.state.block,i.originalIndex,a))return!1;const c=yf(this.state.block,i.originalIndex,a);this.editor.updateBlock(this.state.block,{type:"table",content:{...this.state.block.content,rows:c}})}else{if(!ml(this.state.block,i.originalIndex,o))return!1;const c=Tf(this.state.block,i.originalIndex,o),[d]=u.splice(i.originalIndex,1);u.splice(o,0,d),this.editor.updateBlock(this.state.block,{type:"table",content:{...this.state.block.content,columnWidths:u,rows:c}})}return this.editor.setTextCursorPosition(this.state.block.id),!0}),this.editor=t,this.pmView=n,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized image toolbar");r(this.state)},n.dom.addEventListener("mousemove",this.mouseMoveHandler),n.dom.addEventListener("mousedown",this.viewMousedownHandler),window.addEventListener("mouseup",this.mouseUpHandler),n.root.addEventListener("dragover",this.dragOverHandler),n.root.addEventListener("drop",this.dropHandler)}update(){var t;if(!this.state||!this.state.show)return;if(this.state.block=this.editor.getBlock(this.state.block.id),!this.state.block||this.state.block.type!=="table"||!((t=this.tableElement)!=null&&t.isConnected)){this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate();return}const{height:n,width:r}=Gi(this.state.block);this.state.rowIndex!==void 0&&this.state.colIndex!==void 0&&(this.state.rowIndex>=n&&(this.state.rowIndex=n-1),this.state.colIndex>=r&&(this.state.colIndex=r-1));const s=this.tableElement.querySelector("tbody");if(!s)throw new Error("Table block does not contain a 'tbody' HTML element. This should never happen.");if(this.state.rowIndex!==void 0&&this.state.colIndex!==void 0){const i=s.children[this.state.rowIndex].children[this.state.colIndex];i?this.state.referencePosCell=i.getBoundingClientRect():(this.state.rowIndex=void 0,this.state.colIndex=void 0)}this.state.referencePosTable=s.getBoundingClientRect(),this.emitUpdate()}destroy(){this.pmView.dom.removeEventListener("mousemove",this.mouseMoveHandler),window.removeEventListener("mouseup",this.mouseUpHandler),this.pmView.dom.removeEventListener("mousedown",this.viewMousedownHandler),this.pmView.root.removeEventListener("dragover",this.dragOverHandler),this.pmView.root.removeEventListener("drop",this.dropHandler)}}const On=new D.PluginKey("TableHandlesPlugin");$(({editor:e})=>{let t;const n=Ht(void 0);return{key:"tableHandles",store:n,prosemirrorPlugins:[new D.Plugin({key:On,view:r=>(t=new aS(e,r,s=>{n.setState({...s,draggingState:s.draggingState?{...s.draggingState}:void 0})}),t),props:{decorations:r=>{if(t===void 0||t.state===void 0||t.state.draggingState===void 0||t.tablePos===void 0)return;const s=t.state.draggingState.draggedCellOrientation==="row"?t.state.rowIndex:t.state.colIndex;if(s===void 0)return;const i=[],{block:o,draggingState:a}=t.state,{originalIndex:u,draggedCellOrientation:c}=a;if(s===u||!o||c==="row"&&!pl(o,u,s)||c==="col"&&!ml(o,u,s))return G.DecorationSet.create(r.doc,i);const d=r.doc.resolve(t.tablePos+1);return t.state.draggingState.draggedCellOrientation==="row"?pi(t.state.block,s).forEach(({row:h,col:f})=>{const p=r.doc.resolve(d.posAtIndex(h)+1),m=r.doc.resolve(p.posAtIndex(f)+1),E=m.node(),C=m.pos+(s>u?E.nodeSize-2:0);i.push(G.Decoration.widget(C,()=>{const k=document.createElement("div");return k.className="bn-table-drop-cursor",k.style.left="0",k.style.right="0",s>u?k.style.bottom="-2px":k.style.top="-3px",k.style.height="4px",k}))}):mi(t.state.block,s).forEach(({row:h,col:f})=>{const p=r.doc.resolve(d.posAtIndex(h)+1),m=r.doc.resolve(p.posAtIndex(f)+1),E=m.node(),C=m.pos+(s>u?E.nodeSize-2:0);i.push(G.Decoration.widget(C,()=>{const k=document.createElement("div");return k.className="bn-table-drop-cursor",k.style.top="0",k.style.bottom="0",s>u?k.style.right="-2px":k.style.left="-3px",k.style.width="4px",k}))}),G.DecorationSet.create(r.doc,i)}}})],colDragStart(r){if(t===void 0||t.state===void 0||t.state.colIndex===void 0)throw new Error("Attempted to drag table column, but no table block was hovered prior.");t.state.draggingState={draggedCellOrientation:"col",originalIndex:t.state.colIndex,mousePos:r.clientX},t.emitUpdate(),e.transact(s=>s.setMeta(On,{draggedCellOrientation:t.state.draggingState.draggedCellOrientation,originalIndex:t.state.colIndex,newIndex:t.state.colIndex,tablePos:t.tablePos})),!e.headless&&(zu(e.prosemirrorView.root),r.dataTransfer.setDragImage(Ee,0,0),r.dataTransfer.effectAllowed="move")},rowDragStart(r){if(t.state===void 0||t.state.rowIndex===void 0)throw new Error("Attempted to drag table row, but no table block was hovered prior.");t.state.draggingState={draggedCellOrientation:"row",originalIndex:t.state.rowIndex,mousePos:r.clientY},t.emitUpdate(),e.transact(s=>s.setMeta(On,{draggedCellOrientation:t.state.draggingState.draggedCellOrientation,originalIndex:t.state.rowIndex,newIndex:t.state.rowIndex,tablePos:t.tablePos})),!e.headless&&(zu(e.prosemirrorView.root),r.dataTransfer.setDragImage(Ee,0,0),r.dataTransfer.effectAllowed="copyMove")},dragEnd(){if(t.state===void 0)throw new Error("Attempted to drag table row, but no table block was hovered prior.");t.state.draggingState=void 0,t.emitUpdate(),e.transact(r=>r.setMeta(On,null)),!e.headless&&sS(e.prosemirrorView.root)},freezeHandles(){t.menuFrozen=!0},unfreezeHandles(){t.menuFrozen=!1},getCellsAtRowHandle(r,s){return pi(r,s)},getCellsAtColumnHandle(r,s){return mi(r,s)},setCellSelection(r,s,i=s){if(!t)throw new Error("Table handles view not initialized");const o=r.doc.resolve(t.tablePos+1),a=r.doc.resolve(o.posAtIndex(s.row)+1),u=r.doc.resolve(a.posAtIndex(s.col)),c=r.doc.resolve(o.posAtIndex(i.row)+1),d=r.doc.resolve(c.posAtIndex(i.col)),h=r.tr;return h.setSelection(new te.CellSelection(u,d)),r.apply(h)},addRowOrColumn(r,s){e.exec((i,o)=>{const a=this.setCellSelection(i,s.orientation==="row"?{row:r,col:0}:{row:0,col:r});return s.orientation==="row"?s.side==="above"?te.addRowBefore(a,o):te.addRowAfter(a,o):s.side==="left"?te.addColumnBefore(a,o):te.addColumnAfter(a,o)})},removeRowOrColumn(r,s){return s==="row"?e.exec((i,o)=>{const a=this.setCellSelection(i,{row:r,col:0});return te.deleteRow(a,o)}):e.exec((i,o)=>{const a=this.setCellSelection(i,{row:0,col:r});return te.deleteColumn(a,o)})},mergeCells(r){return e.exec((s,i)=>{const o=r?this.setCellSelection(s,r.relativeStartCell,r.relativeEndCell):s;return te.mergeCells(o,i)})},splitCell(r){return e.exec((s,i)=>{const o=r?this.setCellSelection(s,r):s;return te.splitCell(o,i)})},getCellSelection(){return e.transact(r=>{const s=r.selection;let i=s.$from,o=s.$to;if(pa(s)){const{ranges:E}=s;E.forEach(C=>{i=C.$from.min(i??C.$from),o=C.$to.max(o??C.$to)})}else if(i=r.doc.resolve(s.$from.pos-s.$from.parentOffset-1),o=r.doc.resolve(s.$to.pos-s.$to.parentOffset-1),i.pos===0||o.pos===0)return;const a=r.doc.resolve(i.pos-i.parentOffset-1),u=r.doc.resolve(o.pos-o.parentOffset-1),c=r.doc.resolve(a.pos-a.parentOffset-1),d=i.index(a.depth),h=a.index(c.depth),f=o.index(u.depth),p=u.index(c.depth),m=[];for(let E=h;E<=p;E++)for(let C=d;C<=f;C++)m.push({row:E,col:C});return{from:{row:h,col:d},to:{row:p,col:f},cells:m}})},getMergeDirection(r){return e.transact(s=>{const i=pa(s.selection)?s.selection:void 0;if(!i||!r||i.ranges.length<=1)return;const o=this.getCellSelection();if(o)return Sf(o.from,o.to,r)?"vertical":"horizontal"})},cropEmptyRowsOrColumns(r,s){return Cf(r,s)},addRowsOrColumns(r,s,i){return kf(r,s,i)}}});const Wu=new D.PluginKey("trailingNode");$(()=>({key:"trailingNode",prosemirrorPlugins:[new D.Plugin({key:Wu,appendTransaction:(e,t,n)=>{const{doc:r,tr:s,schema:i}=n,o=Wu.getState(n),a=r.content.size-2,u=i.nodes.blockContainer,c=i.nodes.paragraph;if(o)return s.insert(a,u.create(void 0,c.create()))},state:{init:(e,t)=>{},apply:(e,t)=>{if(!e.docChanged)return t;let n=e.doc.lastChild;if(!n||n.type.name!=="blockGroup")throw new Error("Expected blockGroup");if(n=n.lastChild,!n||n.type.name!=="blockContainer")return!0;const r=n.firstChild;if(!r)throw new Error("Expected blockContent");return n.nodeSize>4||r.type.spec.content!=="inline*"}}})]}));const Gu=new D.PluginKey("blocknote-show-selection"),di=$(({editor:e})=>{const t=Ht({enabled:!1},{onUpdate(){e.transact(n=>n.setMeta(Gu,{}))}});return{key:"showSelection",store:t,prosemirrorPlugins:[new D.Plugin({key:Gu,props:{decorations:n=>{const{doc:r,selection:s}=n;if(!t.state.enabled)return G.DecorationSet.empty;const i=G.Decoration.inline(s.from,s.to,{"data-show-selection":"true"});return G.DecorationSet.create(r,[i])}}})],showSelection(n){t.setState({enabled:n})}}});function uS(e){const{properties:t,required:n,$defs:r,...s}=e.inputSchema;return{schema:{type:"object",description:e.description,properties:{type:{type:"string",enum:[e.name]},...t},required:["type",...n??[]],additionalProperties:!1,...s},$defs:r}}function kh(e){const t=e.map(r=>uS(r)),n={};for(const r of t)for(const s in r.$defs){if(n[s]&&!tf.default(n[s],r.$defs[s]))throw new Error(`Duplicate, but different definition for ${s}`);n[s]=r.$defs[s]}return{type:"object",properties:{operations:{type:"array",items:{anyOf:t.map(r=>r.schema)}}},additionalProperties:!1,required:["operations"],$defs:Object.keys(n).length>0?n:void 0}}function Sh(e,t){return{async sendAIRequest(n,r){const s=await t(n);return await e(n.chat.messages,s),n.chat.sendMessage(void 0,{...r,body:{...(r==null?void 0:r.body)??{},toolDefinitions:{applyDocumentOperations:{name:"applyDocumentOperations",inputSchema:kh(n.streamTools),outputSchema:{type:"object"}}}},metadata:{promptData:s}})}}}class Fo extends Error{constructor(t,n,r){super(t,r),this.chunk=n,this.name="ChunkExecutionError"}}class Ah{constructor(t){Qo(this,"stream");this.streamTools=t,this.stream=this.createStream()}createStream(){let t;const n=new TransformStream({transform:async(a,u)=>{const c=typeof a=="string"?await lS(a,(t==null?void 0:t.isPossiblyPartial)??!1,this.streamTools):a;c&&(t=c,u.enqueue(c))},flush:a=>{t!=null&&t.isPossiblyPartial&&a.error(new Error("stream ended with a partial operation"))}}),r=n.readable.pipeThrough(this.createExecutor()),[s,i]=r.tee(),o=s.pipeTo(new WritableStream);return{writable:n.writable,readable:i,finishPromise:o}}createExecutor(){const t=this.streamTools.map(n=>n.executor());return new TransformStream({transform:async(n,r)=>{var i;let s=!1;for(const o of t)try{if(await o.execute(n)){r.enqueue({status:"ok",chunk:n}),s=!0;break}}catch(a){throw new Fo(`Tool execution failed: ${Vi.getErrorMessage(a)}`,n,{cause:a})}if(!s){const o=((i=n.operation)==null?void 0:i.type)||"unknown";throw new Error(`No tool could handle operation of type: ${o}`)}}})}get writable(){return this.stream.writable}get readable(){return this.stream.readable}async finish(){await this.stream.finishPromise}async executeOperationsArray(t){const n=this.writable.getWriter();for await(const r of t){const s=await Le.parsePartialJson(r);if(s.state==="undefined-input"||s.state==="failed-parse"||!s)return;await n.write(r)}await n.close(),await this.finish()}async execute(t){const n=this.writable.getWriter();for await(const r of t)await n.write(r);await n.close(),await this.finish()}async executeOne(t){await this.execute(async function*(){yield{operation:t,isUpdateToPreviousOperation:!1,isPossiblyPartial:!1,metadata:{}}}())}}async function lS(e,t,n){const r=await Le.parsePartialJson(e);if(r.state==="undefined-input"||r.state==="failed-parse"||!r)return;const s=n.find(o=>{var a;return o.name===((a=r.value)==null?void 0:a.type)}),i=s&&s.validate(r.value);if(i!=null&&i.ok)return{operation:i.value,isPossiblyPartial:r.state==="repaired-parse",isUpdateToPreviousOperation:t,metadata:void 0}}function cS(e){return new ReadableStream({async start(t){try{for await(const n of e)t.enqueue(n);t.close()}catch(n){t.error(n)}}})}function _h(e){if(e.locked)throw new Error("Stream (source) is already locked and cannot be iterated.");const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=()=>{if(t.locked)throw new Error("Stream is already locked and cannot be iterated again.");const n=t.getReader();return{async next(){const{done:r,value:s}=await n.read();return r?{done:!0,value:void 0}:{done:!1,value:s}}}},t}function dS(e){return _h(cS(e))}async function*hS(e,t){var i;let n=0,r=!0,s;for await(const o of e)if((i=o.operations)!=null&&i.length){for(let a=n;a<o.operations.length;a++){const u=o.operations[a];s=u,yield{partialOperation:u,isUpdateToPreviousOperation:a===n&&!r,isPossiblyPartial:a===o.operations.length-1,metadata:t},r=!1}n=o.operations.length-1}if(!s)throw new Error("No operations seen");yield{partialOperation:s,isUpdateToPreviousOperation:!0,isPossiblyPartial:!1,metadata:t}}async function*fS(e,t){let n=!1;for await(const r of e){const s=r.operation;s.ok?(yield{operation:s.value,isUpdateToPreviousOperation:n?!1:r.isUpdateToPreviousOperation,isPossiblyPartial:r.isPossiblyPartial,metadata:r.metadata},n=!1):(n=n||!r.isUpdateToPreviousOperation,t==null||t({...r,operation:s}))}}async function*pS(e,t){for await(const n of e){const r=t.find(i=>i.name===n.partialOperation.type);if(!r){yield{operation:{ok:!1,error:`No matching function for ${n.partialOperation.type}`},isUpdateToPreviousOperation:n.isUpdateToPreviousOperation,isPossiblyPartial:n.isPossiblyPartial,metadata:n.metadata};continue}yield{operation:r.validate(n.partialOperation),isUpdateToPreviousOperation:n.isUpdateToPreviousOperation,isPossiblyPartial:n.isPossiblyPartial,metadata:n.metadata}}}async function*mS(e,t){const n=pS(e,t);yield*fS(n,s=>{if(!s.isPossiblyPartial)throw new Error("invalid operation: "+s.operation.error)})}function wh(e,t,n){return dS(mS(hS(_h(e),n),t))}async function gS(e,t,n){const r=new Ah(e),s=bS();s.output.pipeTo(r.writable);const i=new Map;let o=!0;const a=t["~registerMessagesCallback"](()=>{ES(t,p=>{if(!i.has(p.toolCallId)){const m=TS(e,p.toolName,p.toolCallId);s.append(m.operationsStream),i.set(p.toolCallId,m),o&&(o=!1,n==null||n())}return i.get(p.toolCallId)})});await new Promise(p=>{const m=t["~registerStatusCallback"](()=>{(t.status==="ready"||t.status==="error")&&(a(),m(),t.status!=="error"&&E(),p())}),E=t["~registerErrorCallback"](()=>{if(t.error){E();for(const C of i.values())C.complete||C.writer.abort(t.error)}})}),await s.finalize();const c=(await Promise.allSettled([r.finish()]))[0];let d;if(c.status==="rejected"){if(c.reason instanceof Fo)d=c.reason;else if(!t.error)throw new Error("Unexpected: no ChunkExecutionError but also no chat.error (network error?)")}let h=!1;const f=Array.from(i.values().filter(p=>p.complete));if(f.forEach((p,m)=>{const E=p.toolCallId===(d==null?void 0:d.chunk.metadata.toolCallId);E&&(h=!0),t.addToolResult({tool:f[m].toolName,toolCallId:f[m].toolCallId,output:h===!1?{status:"ok"}:E?{status:"error",error:Vi.getErrorMessage(d)}:{status:"not-executed-previous-tool-errored"}})}),d)throw d;if(t.error)throw t.error}function bS(){let e,t=Promise.resolve(),n=!1;const r=new ReadableStream({start(o){e=o},cancel(o){n=!0,e.error(o)}});async function s(o){if(n)throw new Error("Appendable stream canceled, can't append");const a=o.getReader();return t=t.then(async()=>{for(;;)try{const{done:u,value:c}=await a.read();if(u||n)break;e.enqueue(c)}catch(u){n=!0,e.error(u);break}}),t}async function i(){await t,n||e.close()}return{output:r,append:s,finalize:i}}function ES(e,t){var n;for(const r of((n=e.lastMessage)==null?void 0:n.parts)??[]){if(!Le.isToolUIPart(r)||r.type.replace("tool-","")!=="applyDocumentOperations")continue;const i=r.toolCallId,o=t({toolName:r.type.replace("tool-",""),toolCallId:i});yS(r,o)}}function TS(e,t,n){const r=new TransformStream,s=wh(r.readable,e,{toolCallId:n});return{writer:r.writable.getWriter(),complete:!1,operationsStream:s,toolName:t,toolCallId:n}}function yS(e,t){if(e.state==="input-streaming"){const n=e.input;n!==void 0&&t.writer.write(n)}else if(e.state==="input-available"){const n=e.input;if(n===void 0)throw new Error("input is undefined");t.complete||(t.complete=!0,t.writer.write(n),t.writer.close())}}function Vo(e){return(e.type==="paragraph"||!e.type)&&!e.content||Array.isArray(e.content)&&e.content.length===0}function CS(e,t,n=!0,r=!0){let s=0,i=e.length;if(n)for(;s<i&&t(e[s]);)s++;if(r)for(;i>s&&t(e[i-1]);)i--;return e.slice(s,i)}function He(e,t){return CS(e,r=>Vo(r)&&(t==null?void 0:t.cursorBlockId)!==r.id,(t==null?void 0:t.trimStart)??!1,(t==null?void 0:t.trimEnd)??!0)}function Ih(e){const{useSelection:t,deleteEmptyCursorBlock:n,streamToolsProvider:r}={useSelection:e.useSelection??!1,deleteEmptyCursorBlock:e.deleteEmptyCursorBlock??!0,streamToolsProvider:e.streamToolsProvider??Qe.html.getStreamToolsProvider()},s=t?void 0:e.editor.getTextCursorPosition().block,i=s&&n&&Vo(s)&&He(e.editor.document).length>0?s.id:void 0,o=t?e.editor.getSelectionCutBlocks():void 0,a=r.getStreamTools(e.editor,o?{from:o._meta.startPos,to:o._meta.endPos}:void 0,e.onBlockUpdated);return{editor:e.editor,chat:e.chat,userPrompt:e.userPrompt,selectedBlocks:o==null?void 0:o.blocks,streamTools:a,emptyCursorBlockToDelete:i}}async function xh(e){const{aiRequest:t,sender:n,chatRequestOptions:r,onStart:s}=e,i=gS(t.streamTools,t.chat,()=>{s==null||s(),t.emptyCursorBlockToDelete&&t.editor.getBlock(t.emptyCursorBlockToDelete)&&t.editor.removeBlocks([t.emptyCursorBlockToDelete])});await n.sendAIRequest(t,r),await i}function kS(e,t){e.length>0&&e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the selection (ignore previous selections, you MUST issue operations against this latest version of the selection):"},{type:"text",text:JSON.stringify(t.htmlSelectedBlocks)},{type:"text",text:"This is the latest state of the document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.htmlDocument)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:"The user asks you to do the following:"},{type:"text",text:t.userPrompt}]}),e.push({role:"system",id:"document-state-intro",parts:[{type:"text",text:"You're manipulating a selected part of a text document using HTML blocks. \n Make sure to follow the json schema provided and always include the trailing $ in ids.\n List items are 1 block with 1 list item each, so block content `<ul><li>item1</li></ul>` is valid, but `<ul><li>item1</li><li>item2</li></ul>` is invalid. We'll merge them automatically.\n This is the selection as an array of html blocks:"}]},{role:"system",id:"document-state-selection",parts:[{type:"text",text:JSON.stringify(t.htmlSelectedBlocks)}]},{role:"system",id:"document-state-context",parts:[{type:"text",text:"This is the entire document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.htmlDocument)}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}function SS(e,t){if(e.length>0){e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the document (ignore previous documents, you MUST issue operations against this latest version of the document):"},{type:"text",text:JSON.stringify(t.htmlBlocks)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:t.userPrompt}]});return}e.push({role:"system",id:"document-state-intro",parts:[{type:"text",text:"You're manipulating a text document using HTML blocks. \n Make sure to follow the json schema provided. When referencing ids they MUST be EXACTLY the same (including the trailing $). \n List items are 1 block with 1 list item each, so block content `<ul><li>item1</li></ul>` is valid, but `<ul><li>item1</li><li>item2</li></ul>` is invalid. We'll merge them automatically.\n For code blocks, you can use the `data-language` attribute on a <code> block (wrapped with <pre>) to specify the language.\n This is the initial document as an array of html blocks (the cursor is BETWEEN two blocks as indicated by cursor: true):"}]},{role:"system",id:"document-state-data",parts:[{type:"text",text:JSON.stringify(t.htmlBlocks)}]},{role:"system",id:"extended-instructions",parts:[{type:"text",text:'First, determine what part of the document the user is talking about. You SHOULD probably take cursor info into account if needed.\n EXAMPLE: if user says "below" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor. \n EXAMPLE: If you want to insert content AT the cursor position (UNLESS indicated otherwise by the user), \n then you need `referenceId` to point to the block before the cursor with position `after` (or block below and `before`).\n \n '+(t.isEmptyDocument?"Because the document is empty, first update the empty block before adding new blocks.":"Prefer updating existing blocks over removing and adding (but this also depends on the user's question).")}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}const AS=async(e,t)=>{t.selection?kS(e,t):SS(e,t)};function Ls(e,t){const n=e.getTextCursorPosition(),r=[];for(const s of t){const i=s.id===n.block.id;r.push({id:s.id,block:s.block}),i&&r.push({cursor:!0})}return r}async function et(e,t){return await Promise.all(e.map(async n=>({id:n.id,block:await t(n)})))}function Fe(e){return e.flatMap(t=>[{...t,children:[]},...Fe(t.children)])}function qt(e){return e.map(t=>typeof t=="object"&&t&&"id"in t?{...t,id:`${t.id}$`}:t)}async function _S(e){return e.selectedBlocks?{...await Lh(e.editor,{selectedBlocks:e.selectedBlocks}),userPrompt:e.userPrompt}:{...await Nh(e.editor,{excludeBlockIds:e.emptyCursorBlockToDelete?[e.emptyCursorBlockToDelete]:void 0}),userPrompt:e.userPrompt}}async function Nh(e,t){const n=He(e.document).length===0,r=e.getTextCursorPosition().block.id,s=He(e.document,{cursorBlockId:r}),i=await et(Fe(s),async c=>e.blocksToHTMLLossy([c])),a=Ls(e,i).filter(c=>"cursor"in c||!(t.excludeBlockIds||[]).includes(c.id));return{selection:!1,htmlBlocks:qt(a),isEmptyDocument:n}}async function Lh(e,t){const n=He(e.document).length===0,r=await et(Fe(t.selectedBlocks),async i=>e.blocksToHTMLLossy([i])),s=qt(r);return{isEmptyDocument:n,selection:!0,htmlSelectedBlocks:s,htmlDocument:(await et(Fe(e.document),async i=>e.blocksToHTMLLossy([i]))).map(({block:i})=>({block:i}))}}function wS(e){let t,n=!1;return e.descendants((r,s)=>n?!1:(r.isText&&(n=!0,t=s),!0)),t}function ns(e){var i;const t=ee.getPmSchema(e),{modification:n}=t.marks,r=[],s=new oe.Transform(e.before);for(let o=0;o<e.steps.length;o++){const a=e.steps[o],u=new oe.Mapping(e.mapping.maps.slice(0,o)).invert();if(a.structure){if(a instanceof oe.ReplaceStep){if(a.to!==a.from+1||a.slice.openStart!==0||a.slice.openEnd!==1||a.slice.content.size!==2)throw new Error("Structure change is not in expected format (ReplaceStep)")}else if(a instanceof oe.ReplaceAroundStep){if(a.insert!==1||a.slice.size!==2||a.gapTo!==a.to-1||a.gapFrom!==a.from+1)throw new Error("Structure change is not in expected format (ReplaceAroundStep)")}else throw new Error("Step is not a ReplaceStep or ReplaceAroundStep");const k=u.map(a.from),_=a.slice.content.firstChild,N=s.doc.resolve(s.mapping.map(k)).nodeAfter;let L=_.marks||[];_.type!==N.type&&(L=n.create({type:"nodeType",previousValue:N.type.name,newValue:_.type.name}).addToSet(L));const U=new Set([...Object.keys(_.attrs),...Object.keys(N.attrs)]);for(const j of U)_.attrs[j]!==N.attrs[j]&&(L=n.create({type:"attr",attrName:j,previousValue:N.attrs[j],newValue:_.attrs[j]}).addToSet(L));const O=s.steps.length;s.setNodeMarkup(s.mapping.map(k),_.type,_.attrs,L),r.push({prosemirrorSteps:s.steps.slice(O),selection:void 0,type:"replace"});continue}if(!(a instanceof oe.ReplaceStep))throw new Error("Step is not a ReplaceStep");const c=u.map(a.from),d=u.map(a.to);if(a.slice.openStart>0||a.slice.openEnd>0)throw new Error("Slice has openStart or openEnd > 0, but structure=false");r.push({prosemirrorSteps:[],selection:{anchor:s.mapping.map(c),head:s.mapping.map(d)},type:"select"});const h=a.slice.content.textBetween(0,a.slice.size),f=h===s.doc.textBetween(s.mapping.map(c),s.mapping.map(d));let p;if(f)p=a.slice.content.size;else if(h.length===0)p=a.slice.content.size;else{const k=wS(a.slice.content);if(k===void 0)throw new Error("unexpected: no first character found");p=k+1}let m=s.mapping.map(d);const E=s.mapping.map(d);let C=!0;for(let k=p;k<=a.slice.content.size;k++){const _=C&&c!==d,N=s.steps.length;if(_){const O=s.doc.resolve(s.mapping.map(c));(i=O.nodeAfter)!=null&&i.isBlock&&s.addNodeMark(O.pos,t.mark("deletion",{})),s.addMark(O.pos,m,t.mark("deletion",{})),m=s.mapping.map(d)}const L=new X.Slice(a.slice.content.cut(0,k),0,0);s.replace(E,m,L).addMark(E,E+L.content.size,t.mark("insertion",{})),s.doc.nodesBetween(E,E+L.content.size,(O,j)=>j<E||j>E+L.content.size?!0:(O.isBlock&&s.addNodeMark(j,t.mark("insertion",{})),!1)),m=s.mapping.slice(N).map(m);const U=D.TextSelection.near(s.doc.resolve(E+L.content.size),-1);r.push({prosemirrorSteps:s.steps.slice(N),selection:{anchor:U.from,head:U.from},type:_?"replace":"insert"}),C=!1}}return r}async function Yo(e){const t=Math.random()*.3+.85;if(e.type==="select")await new Promise(n=>setTimeout(n,100*t));else if(e.type==="insert")await new Promise(n=>setTimeout(n,10*t));else if(e.type==="replace")await new Promise(n=>setTimeout(n,200*t));else throw new ee.UnreachableCaseError(e.type)}function $o(e,t){e.setMeta("addToHistory",!1),t.selection&&e.setMeta("aiAgent",{selection:{anchor:t.selection.anchor,head:t.selection.head}});for(const n of t.prosemirrorSteps)if(e.maybeStep(n).failed)throw new Error("failed to apply step");return e}function IS(e,t,n){const r=new oe.Transform(t);for(const o of e){const a=new oe.ReplaceStep(r.mapping.map(o.fromA),r.mapping.map(o.toA),n.slice(o.fromB,o.toB));r.step(a)}const s=r.mapping.invert();let i=r.doc.content.findDiffStart(n.content);for(;i!==null;){const o=n.resolve(i).nodeAfter,a=r.doc.resolve(i).nodeAfter;if(!o||!a)throw new Error("diffNode not found");const u=!o.isLeaf&&o.content.eq(a.content),c=u?1:Math.min(o.nodeSize,a.nodeSize),d=i+c,h=s.map(i),f=s.map(d);let p=e.length;for(let E=0;E<e.length;E++)if(e[E].fromA>=f){p=E;break}e.splice(p,0,{fromA:h,toA:f,fromB:i,toB:d,deleted:[],inserted:[],type:u?"node-type-or-attr-update":"mark-update"}),r.step(new oe.ReplaceStep(i,d,n.slice(i,d),u));const m=r.doc.content.findDiffStart(n.content);if(m===i)throw new Error("diffStart not moving");i=m}return e}const Ku=(e,t)=>{const n=new Set,r=new Set;e.descendants(o=>{o.type.name==="tableCell"&&n.add(JSON.stringify(o.toJSON()))}),t.descendants(o=>{o.type.name==="tableCell"&&r.add(JSON.stringify(o.toJSON()))});const s=new Set([...n].filter(o=>r.has(o)));return{encodeCharacter:o=>o,encodeNodeStart:o=>{if(o.type.name==="tableCell"){const a=JSON.stringify(o.toJSON());return s.has(a)?a:o.type.name}return o.type.name},encodeNodeEnd:o=>{if(o.type.name==="tableCell"){const a=JSON.stringify(o.toJSON());return s.has(a)?a:-1}return-1},compareTokens:(o,a)=>o===a}};function Os(e,t,n=!1,r,s){const i=ee.getNodeById(e.id,t),o=new oe.Transform(t);ee.updateBlockTr(o,i.posBeforeNode,e.block,r,s);let a=o.doc,u=Ds.ChangeSet.create(t,void 0,Ku(t,a));if(u=u.addSteps(a,o.mapping.maps,0),n&&u.changes.length>0){const h=u.changes[u.changes.length-1],f=h.toA-h.fromA,p=h.toB-h.fromB;if(f>p){const m=t.slice(h.fromA+p,h.toA);o.step(new oe.ReplaceStep(h.toB,h.toB,m)),a=o.doc,u=Ds.ChangeSet.create(u.startDoc,void 0,Ku(u.startDoc,a)),u=u.addSteps(a,o.mapping.maps,0)}}const c=[],d=Ds.simplifyChanges(u.changes,a);for(let h=0;h<d.length;h++){const f=d[h],p=a.slice(f.fromB,f.toB);if(p.openEnd===1&&p.openStart===0&&(f.type="node-type-or-attr-update",p.size>2)){const m={fromA:f.fromA,toA:f.fromA+1,fromB:f.fromB,toB:f.fromB+1,deleted:[],inserted:[],type:"node-type-or-attr-update"},E={fromA:f.fromA+1,toA:f.toA,fromB:f.fromB+1,toB:f.toB,deleted:[],inserted:[]};d.splice(h,1,m,E),h++}}IS(d,t,a);for(let h=0;h<d.length;h++){const f=d[h],p=a.slice(f.fromB,f.toB);if(p.openEnd>0&&p.size>1)throw new Error("unexpected, openEnd > 0 and size > 1, this should have been split into two steps");h===d.length-1&&n&&f.type==="mark-update"||c.push(new oe.ReplaceStep(f.fromA,f.toA,p,f.type==="node-type-or-attr-update"))}return c}function xS(e,t){if(!e||!Array.isArray(e)||e.length===0)return{ok:!1,error:"blocks is required"};const n=[];for(const r of e){const s=t(r);if(!s.ok)return{ok:!1,error:`Invalid block: ${s.error}`};n.push(s.value)}return{ok:!0,value:n}}function jo(e){return(t,n)=>{const r=typeof e.schema=="function"?e.schema(t):e.schema;return{name:"add",description:e.description,inputSchema:{type:"object",properties:{referenceId:{type:"string",description:"MUST be an id of a block in the document"},position:{type:"string",enum:["before","after"],description:"`after` to add blocks AFTER (below) the block with `referenceId`, `before` to add the block BEFORE (above)"},blocks:{items:r.block,type:"array"}},required:["referenceId","position","blocks"],$defs:r.$defs},validate:s=>{if(s.type!=="add")return{ok:!1,error:"invalid operation type"};if(s.position!=="before"&&s.position!=="after")return{ok:!1,error:"invalid position"};if(!s.referenceId||!s.blocks)return{ok:!1,error:"referenceId and blocks are required"};let i=s.referenceId;if(n.idsSuffixed){if(!(i!=null&&i.endsWith("$")))return{ok:!1,error:"referenceId must end with $"};i=i.slice(0,-1)}if(!t.getBlock(i))return{ok:!1,error:"referenceId not found"};const a=xS(s.blocks,u=>e.validateBlock(u,t));return a.ok?{ok:!0,value:{type:s.type,referenceId:i,position:s.position,blocks:a.value}}:a},executor:()=>{let s=[];const i={};return{execute:async o=>{var c;if(o.isUpdateToPreviousOperation||(s=[]),o.operation.type!=="add")return!1;const a=o.operation,u=await e.toJSONToolCall(t,{...o,operation:a});if(!u||o.isPossiblyPartial&&Vo(u.blocks[u.blocks.length-1]))return!0;for(let d=0;d<u.blocks.length;d++){const h=u.blocks[d],f=t.prosemirrorState.tr;let p=[];if(d<s.length){const m=await e.rebaseTool(s[d],t),C=Os({id:s[d],block:h},m.doc,!1).map(k=>k.map(m.invertMap));for(const k of C)f.step(k.map(f.mapping));p=ns(f),p=p.filter(k=>k.type!=="select")}else{const m=a.position==="after"?i[a.referenceId]:void 0,E=ee.insertBlocks(f,[h],d>0?s[d-1]:m||a.referenceId,d>0?"after":a.position);s.push(...E.map(C=>C.id)),p=ns(f)}for(const m of p)n.withDelays&&await Yo(m),t.transact(E=>{$o(E,m)}),(c=n.onBlockUpdate)==null||c.call(n,s[d])}return o.isPossiblyPartial||a.position==="after"&&(i[a.referenceId]=s[s.length-1]),!0}}}}}}function qo(e){return(t,n)=>{const r=typeof e.schema=="function"?e.schema(t):e.schema;return{name:"update",description:e.description,inputSchema:{type:"object",properties:{id:{type:"string",description:"id of block to update"},block:r.block},required:["id","block"],$defs:r.$defs},validate:s=>{if(s.type!=="update")return{ok:!1,error:"invalid operation type"};if(!s.id)return{ok:!1,error:"id is required"};let i=s.id;if(n.idsSuffixed){if(!(i!=null&&i.endsWith("$")))return{ok:!1,error:"id must end with $"};i=i.slice(0,-1)}if(!s.block)return{ok:!1,error:"block is required"};const o=t.getBlock(i);if(!o)return console.error("BLOCK NOT FOUND",i),{ok:!1,error:"block not found"};const a=e.validateBlock(s.block,t,o.type);return a.ok?{ok:!0,value:{type:s.type,id:i,block:a.value}}:a},executor:()=>{let i=50;const o=n.updateSelection?{from:ee.trackPosition(t,n.updateSelection.from),to:ee.trackPosition(t,n.updateSelection.to)}:void 0;return{execute:async a=>{var k;if(a.operation.type!=="update")return!1;const u=a.operation;if(a.isPossiblyPartial){const _=JSON.stringify(u.block).length;if(_<i)return!0;i=_+50}else i=50;const c=await e.rebaseTool(u.id,t),d=o?c.invertMap.invert().map(o.from()):void 0,h=o?c.invertMap.invert().map(o.to()):void 0,f=await e.toJSONToolCall(t,{...a,operation:u});if(!f)return!0;const p=Os(f,c.doc,a.isPossiblyPartial,d,h);if(p.length===1&&a.isPossiblyPartial)return!0;const m=p.map(_=>_.map(c.invertMap)),E=new oe.Transform(t.prosemirrorState.doc);for(const _ of m)E.step(_.map(E.mapping));const C=ns(E);for(const _ of C)n.withDelays&&await Yo(_),t.transact(N=>{$o(N,_)}),(k=n.onBlockUpdate)==null||k.call(n,u.id);return!0}}}}}}const zo=(e,t)=>({name:"delete",description:"Delete a block",inputSchema:{type:"object",properties:{id:{type:"string",description:"id of block to delete"}},required:["id"]},validate:n=>{if(n.type!=="delete")return{ok:!1,error:"invalid operation type"};if(!n.id)return{ok:!1,error:"id is required"};let r=n.id;if(t.idsSuffixed){if(!(r!=null&&r.endsWith("$")))return{ok:!1,error:"id must end with $"};r=r.slice(0,-1)}return e.getBlock(r)?{ok:!0,value:{type:"delete",id:r}}:{ok:!1,error:"block not found"}},executor:()=>({execute:async n=>{var o;if(n.operation.type!=="delete")return!1;const r=n.operation,s=e.prosemirrorState.tr;ee.removeAndInsertBlocks(s,[r.id],[]);const i=ns(s);for(const a of i)t.withDelays&&await Yo(a),e.transact(u=>{$o(u,a)}),(o=t.onBlockUpdate)==null||o.call(t,r.id);return!0}})});function Xu(e){const t=e.lastIndexOf("<"),n=e.lastIndexOf(">");let r=e;if(t>n&&(r=e.substring(0,t),!r.trim()))return;const s=r.match(/&[a-zA-Z0-9]*$/);s&&(r=r.substring(0,r.length-s[0].length));const a=new DOMParser().parseFromString(`<div>${r}</div>`,"text/html").body.firstChild;return a?a.innerHTML:""}function rs(e){let t;if(Nn.applySuggestions(e.prosemirrorState,n=>{t=n}),!t)throw new Error("applySuggestionsTr is not set");return t}function ss(e,t){const n=t.mapping.invert();return{doc:t.doc,tr:()=>new oe.Transform(t.doc),invertMap:n,rebaseTr:r=>{if(r.steps.length===0)throw new Error("No steps to apply");let s=e.prosemirrorState.tr;for(const i of r.steps){const o=i.map(n);if(!o)throw new Error("Step is not mapped");s=s.step(o)}return s}}}async function Qu(e,t){var c;const n=rs(t),r=ee.getBlock(n.doc,e);if(!r)throw new Error("block not found");const s=await t.blocksToHTMLLossy([{...r,children:[]}]),i=(c=window.__TEST_OPTIONS)==null?void 0:c.mockID,o=await t.tryParseHTMLToBlocks(s);if(window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=i),o.length!==1)throw new Error("html diff invalid block count");const a=o[0];if(a.id=e,Os({id:e,block:a},n.doc).length)throw new Error("html diff");return ss(t,n)}function Ju(e){return typeof e!="string"?{ok:!1,error:"block must be a string"}:{ok:!0,value:e}}const Rr={add:jo({description:"Insert new blocks",schema:{block:{type:"string",description:"html of block (MUST be a single, VALID HTML element)"}},validateBlock:Ju,rebaseTool:Qu,toJSONToolCall:async(e,t)=>{var s;const n=(s=window.__TEST_OPTIONS)==null?void 0:s.mockID,r=(await Promise.all(t.operation.blocks.map(async i=>{const o=t.isPossiblyPartial?Xu(i):i;return o?(await e.tryParseHTMLToBlocks(o)).map(a=>(delete a.id,a)):[]}))).flat();if(window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=n),r.length!==0)return{...t.operation,blocks:r}}}),update:qo({description:"Update a block",schema:{block:{type:"string",description:"html of block (MUST be a single HTML element)"}},validateBlock:Ju,rebaseTool:Qu,toJSONToolCall:async(e,t)=>{const n=t.isPossiblyPartial?Xu(t.operation.block):t.operation.block;if(!n)return;const r=(await e.tryParseHTMLToBlocks(n))[0];return window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=void 0),delete r.id,{...t.operation,block:r}}}),delete:zo};function NS(e,t,n,r,s){if(typeof r=="boolean"){const a=r?e.getSelectionCutBlocks():void 0;r=a?{from:a._meta.startPos,to:a._meta.endPos}:void 0}const i=n??{add:!0,update:!0,delete:!0};return[...i.update?[Rr.update(e,{idsSuffixed:!0,withDelays:t,updateSelection:r,onBlockUpdate:s})]:[],...i.add?[Rr.add(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:s})]:[],...i.delete?[Rr.delete(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:s})]:[]]}const LS={getStreamToolsProvider:(e={})=>({getStreamTools:(t,n,r)=>NS(t,e.withDelays??!0,e.defaultStreamTools,n,r)}),tools:Rr,defaultPromptBuilder:AS,defaultPromptInputDataBuilder:_S,promptHelpers:{getDataForPromptNoSelection:Nh,getDataForPromptWithSelection:Lh}};async function OS(e){return e.selectedBlocks?{...await Dh(e.editor,{selectedBlocks:e.selectedBlocks}),userPrompt:e.userPrompt}:{...await Oh(e.editor,{excludeBlockIds:e.emptyCursorBlockToDelete?[e.emptyCursorBlockToDelete]:void 0}),userPrompt:e.userPrompt}}async function Oh(e,t){const n=He(e.document).length===0,r=e.getTextCursorPosition().block.id,s=He(e.document,{cursorBlockId:r}),i=await et(Fe(s),async c=>({...c,children:void 0})),a=Ls(e,i).filter(c=>"cursor"in c||!(t.excludeBlockIds||[]).includes(c.id));return{selection:!1,jsonBlocks:qt(a),isEmptyDocument:n}}async function Dh(e,t){const n=He(e.document).length===0,r=await et(Fe(t.selectedBlocks),async i=>i),s=qt(r);return{isEmptyDocument:n,selection:!0,jsonSelectedBlocks:s,jsonDocument:(await et(Fe(e.document),async i=>({...i,id:void 0,children:void 0}))).map(({block:i})=>({block:i}))}}function DS(e){const t={},n={};return e.forEach(s=>{const{type:i,...o}=s.properties,a=JSON.stringify(o);t[a]?t[a].push(i.enum[0]):(t[a]=[i.enum[0]],n[a]=s)}),Object.keys(t).map(s=>{const i=n[s];return{...i,properties:{...i.properties,type:{type:"string",enum:t[s]}}}})}function vS(e){return{type:"object",properties:Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{type:n.propSchema}])),additionalProperties:!1}}function MS(){return{type:"object",properties:{type:{type:"string",enum:["text"]},text:{type:"string"},styles:{$ref:"#/$defs/styles"}},additionalProperties:!1,required:["type","text"]}}function vh(e){return{type:"object",properties:Object.fromEntries(Object.entries(e).filter(([t,n])=>n.default!==void 0).map(([t,n])=>[t,{type:typeof n.default,enum:n.values}])),additionalProperties:!1}}function RS(e){return{type:"array",items:{anyOf:Object.entries(e).map(([t,n])=>n==="text"?{$ref:"#/$defs/styledtext"}:n==="link"?{type:"object",properties:{type:{type:"string",enum:["link"]},content:{type:"array",items:{$ref:"#/$defs/styledtext"}},href:{type:"string"}},additionalProperties:!1,required:["type","href","content"]}:{type:"object",properties:{type:{type:"string",enum:[n.type]},content:n.content==="styled"?{type:"array",items:{$ref:"#/$defs/styledtext"}}:void 0,props:vh(n.propSchema)},additionalProperties:!1,required:["type",...n.content==="styled"?["content"]:[]]})}}}function PS(e){return{anyOf:DS(Object.entries(e).map(([t,n])=>({type:"object",properties:{type:{type:"string",enum:[n.type]},content:n.content==="inline"?{$ref:"#/$defs/inlinecontent"}:n.content==="table"?{type:"object",properties:{}}:void 0,props:vh(n.propSchema)},additionalProperties:!1,required:["type"]})))}}function BS(e){const t=JSON.parse(JSON.stringify({blockSchema:e.blockSchema,inlineContentSchema:e.inlineContentSchema,styleSchema:e.styleSchema}));return{removeFileBlocks(){return t.blockSchema=Object.fromEntries(Object.entries(t.blockSchema).filter(([n,r])=>{var s;return!((s=e.blockSpecs[r.type].implementation.meta)!=null&&s.fileBlockAccept)})),this},removeDefaultProps(){return t.blockSchema=Object.fromEntries(Object.entries(t.blockSchema).map(([n,r])=>[n,{...r,propSchema:Object.fromEntries(Object.entries(r.propSchema).filter(s=>typeof ee.defaultProps[s[0]]>"u"))}])),this},get(){return t}}}function Zu(e){return e=BS(e).removeFileBlocks().removeDefaultProps().get(),{$defs:{styles:vS(e.styleSchema),styledtext:MS(),inlinecontent:RS(e.inlineContentSchema),block:PS(e.blockSchema)}}}function Mh(e,t){return!t.schema.inlineContentSchema[e.type]||ee.isStyledTextInlineContent(e)&&!("text"in e)?!1:ee.isLinkInlineContent(e)?!("content"in e)||!("href"in e)?!1:Mh(e.content,t):!0}function el(e,t,n){const r=e.type||n,s=t.schema.blockSchema[r];if(!s)return{ok:!1,error:"block type not found in editor"};if(e.children,s.content==="none"){if(e.content)return{ok:!1,error:"block content not expected for this block type"}}else{if(!e.content)return{ok:!0,value:e};if(!Array.isArray(e.content))return{ok:!1,error:"block content must be an array"};if(s.content==="table")return{ok:!0,value:e};if(!e.content.every(i=>Mh(i,t)))return{ok:!1,error:"block content must be an array of inline content"}}return{ok:!0,value:e}}const Pr={add:jo({description:"Insert new blocks",schema:e=>({block:{$ref:"#/$defs/block"},...Zu(e.schema)}),validateBlock:el,rebaseTool:async(e,t)=>ss(t,rs(t)),toJSONToolCall:async(e,t)=>t.operation}),update:qo({description:"Update a block, the new block will replace the existing block.",schema:e=>({block:{$ref:"#/$defs/block"},...Zu(e.schema)}),validateBlock:el,rebaseTool:async(e,t)=>ss(t,rs(t)),toJSONToolCall:async(e,t)=>{const n=Object.fromEntries(Object.entries(ee.defaultProps).map(([r,s])=>[r,s.default]));return{...t.operation,block:{...t.operation.block,props:{...n,...t.operation.block.props}}}}}),delete:zo};function US(e,t){e.length>0&&e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the selection (ignore previous selections, you MUST issue operations against this latest version of the selection):"},{type:"text",text:JSON.stringify(t.jsonSelectedBlocks)},{type:"text",text:"This is the latest state of the document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.jsonDocument)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:"The user asks you to do the following:"},{type:"text",text:t.userPrompt}]}),e.push({role:"system",id:"document-state-intro",parts:[{type:"text",text:`You're manipulating a selected part of a text document using JSON blocks.
2
31
  Make sure to follow the json schema provided and always include the trailing $ in ids.
3
- This is the selection as an array of JSON blocks:`},{type:"text",text:JSON.stringify(t.jsonSelectedBlocks)},{type:"text",text:"This is the entire document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.jsonDocument)}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}function Ht(e,t){if(e.length>0){e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the document (ignore previous documents, you MUST issue operations against this latest version of the document):"},{type:"text",text:JSON.stringify(t.jsonBlocks)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:t.userPrompt}]});return}e.push({role:"system",id:"document-state",parts:[{type:"text",text:`You're manipulating a text document using JSON blocks.
32
+ This is the selection as an array of JSON blocks:`},{type:"text",text:JSON.stringify(t.jsonSelectedBlocks)},{type:"text",text:"This is the entire document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.jsonDocument)}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}function HS(e,t){if(e.length>0){e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the document (ignore previous documents, you MUST issue operations against this latest version of the document):"},{type:"text",text:JSON.stringify(t.jsonBlocks)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:t.userPrompt}]});return}e.push({role:"system",id:"document-state",parts:[{type:"text",text:`You're manipulating a text document using JSON blocks.
4
33
  Make sure to follow the json schema provided. When referencing ids they MUST be EXACTLY the same (including the trailing $).
5
- This is the initial document as an array of JSON blocks (the cursor is BETWEEN two blocks as indicated by cursor: true):`},{type:"text",text:JSON.stringify(t.jsonBlocks)},{type:"text",text:'First, determine what part of the document the user is talking about. You SHOULD probably take cursor info into account if needed.\n EXAMPLE: if user says "below" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor. \n EXAMPLE: If you want to insert content AT the cursor position (UNLESS indicated otherwise by the user), \n then you need `referenceId` to point to the block before the cursor with position `after` (or block below and `before`).\n \n '+(t.isEmptyDocument?"Because the document is empty, first update the empty block before adding new blocks.":"Prefer updating existing blocks over removing and adding (but this also depends on the user's question).")}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}const Ut=async(e,t)=>{t.selection?$t(e,t):Ht(e,t)};function zt(e,t,o,r,n){if(typeof r=="boolean"){const i=r?e.getSelectionCutBlocks():void 0;r=i?{from:i._meta.startPos,to:i._meta.endPos}:void 0}const s=o??{add:!0,update:!0,delete:!0};return[...s.update?[V.update(e,{idsSuffixed:!0,withDelays:t,updateSelection:r,onBlockUpdate:n})]:[],...s.add?[V.add(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:n})]:[],...s.delete?[V.delete(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:n})]:[]]}const Jt={getStreamToolsProvider:(e={})=>({getStreamTools:(t,o,r)=>zt(t,e.withDelays??!0,e.defaultStreamTools,o,r)}),tools:V,defaultPromptBuilder:Ut,defaultPromptInputDataBuilder:_t,promptHelpers:{getDataForPromptNoSelection:qe,getDataForPromptWithSelection:$e}};async function Rt(e){return e.selectedBlocks?{...await Je(e.editor,{selectedBlocks:e.selectedBlocks}),userPrompt:e.userPrompt}:{...await ze(e.editor,{excludeBlockIds:e.emptyCursorBlockToDelete?[e.emptyCursorBlockToDelete]:void 0}),userPrompt:e.userPrompt}}async function ze(e,t){const o=P(e.document).length===0,r=e.getTextCursorPosition().block.id,n=P(e.document,{cursorBlockId:r}),s=await B(C(n),async c=>e.blocksToMarkdownLossy([c])),i=X(e,s).filter(c=>"cursor"in c||!(t.excludeBlockIds||[]).includes(c.id));return{selection:!1,markdownBlocks:D(i),isEmptyDocument:o}}async function Je(e,t){const o=P(e.document).length===0,r=await B(C(t.selectedBlocks),async s=>e.blocksToMarkdownLossy([s])),n=D(r);return{isEmptyDocument:o,selection:!0,markdownSelectedBlocks:n,markdownDocument:(await B(C(e.document),async s=>e.blocksToMarkdownLossy([s]))).map(({block:s})=>({block:s}))}}async function we(e,t){const o=W(t),r=await t.blocksToMarkdownLossy([b.getBlock(o.doc,e)]),n=await t.tryParseMarkdownToBlocks(r),s=Q({id:e,block:n[0]},o.doc),a=new x.Mapping;for(const i of s){const l=i.map(a);if(!l)throw new Error("Failed to map step");o.step(l),a.appendMap(l.getMap())}return Y(t,o)}function xe(e){return typeof e!="string"?{ok:!1,error:"block must be a string"}:{ok:!0,value:e}}const F={add:le({description:"Insert new blocks",schema:{block:{$ref:"#/$defs/block"},$defs:{block:{type:"string",description:"markdown of block"}}},validateBlock:xe,rebaseTool:we,toJSONToolCall:async(e,t)=>{const o=await Promise.all(t.operation.blocks.map(async r=>{const n=(await e.tryParseMarkdownToBlocks(r.trim()))[0];return delete n.id,n}));return window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=void 0),{...t.operation,blocks:o}}}),update:ce({description:"Update a block, the new block will replace the existing block.",schema:{block:{$ref:"#/$defs/block"},$defs:{block:{type:"string",description:"markdown of block"}}},validateBlock:xe,rebaseTool:we,toJSONToolCall:async(e,t)=>{const o=(await e.tryParseMarkdownToBlocks(t.operation.block.trim()))[0];return delete o.id,window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=void 0),{...t.operation,block:o}}}),delete:ue};function Vt(e,t){e.length>0&&e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the selection (ignore previous selections, you MUST issue operations against this latest version of the selection):"},{type:"text",text:JSON.stringify(t.markdownSelectedBlocks)},{type:"text",text:"This is the latest state of the document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.markdownDocument)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:"The user asks you to do the following:"},{type:"text",text:t.userPrompt}]}),e.push({role:"system",id:"document-state-intro",parts:[{type:"text",text:`You're manipulating a selected part of a text document using Markdown blocks.
34
+ This is the initial document as an array of JSON blocks (the cursor is BETWEEN two blocks as indicated by cursor: true):`},{type:"text",text:JSON.stringify(t.jsonBlocks)},{type:"text",text:'First, determine what part of the document the user is talking about. You SHOULD probably take cursor info into account if needed.\n EXAMPLE: if user says "below" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor. \n EXAMPLE: If you want to insert content AT the cursor position (UNLESS indicated otherwise by the user), \n then you need `referenceId` to point to the block before the cursor with position `after` (or block below and `before`).\n \n '+(t.isEmptyDocument?"Because the document is empty, first update the empty block before adding new blocks.":"Prefer updating existing blocks over removing and adding (but this also depends on the user's question).")}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}const FS=async(e,t)=>{t.selection?US(e,t):HS(e,t)};function VS(e,t,n,r,s){if(typeof r=="boolean"){const a=r?e.getSelectionCutBlocks():void 0;r=a?{from:a._meta.startPos,to:a._meta.endPos}:void 0}const i=n??{add:!0,update:!0,delete:!0};return[...i.update?[Pr.update(e,{idsSuffixed:!0,withDelays:t,updateSelection:r,onBlockUpdate:s})]:[],...i.add?[Pr.add(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:s})]:[],...i.delete?[Pr.delete(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:s})]:[]]}const YS={getStreamToolsProvider:(e={})=>({getStreamTools:(t,n,r)=>VS(t,e.withDelays??!0,e.defaultStreamTools,n,r)}),tools:Pr,defaultPromptBuilder:FS,defaultPromptInputDataBuilder:OS,promptHelpers:{getDataForPromptNoSelection:Oh,getDataForPromptWithSelection:Dh}};async function $S(e){return e.selectedBlocks?{...await Ph(e.editor,{selectedBlocks:e.selectedBlocks}),userPrompt:e.userPrompt}:{...await Rh(e.editor,{excludeBlockIds:e.emptyCursorBlockToDelete?[e.emptyCursorBlockToDelete]:void 0}),userPrompt:e.userPrompt}}async function Rh(e,t){const n=He(e.document).length===0,r=e.getTextCursorPosition().block.id,s=He(e.document,{cursorBlockId:r}),i=await et(Fe(s),async c=>e.blocksToMarkdownLossy([c])),a=Ls(e,i).filter(c=>"cursor"in c||!(t.excludeBlockIds||[]).includes(c.id));return{selection:!1,markdownBlocks:qt(a),isEmptyDocument:n}}async function Ph(e,t){const n=He(e.document).length===0,r=await et(Fe(t.selectedBlocks),async i=>e.blocksToMarkdownLossy([i])),s=qt(r);return{isEmptyDocument:n,selection:!0,markdownSelectedBlocks:s,markdownDocument:(await et(Fe(e.document),async i=>e.blocksToMarkdownLossy([i]))).map(({block:i})=>({block:i}))}}async function tl(e,t){const n=rs(t),r=await t.blocksToMarkdownLossy([ee.getBlock(n.doc,e)]),s=await t.tryParseMarkdownToBlocks(r),i=Os({id:e,block:s[0]},n.doc),o=new oe.Mapping;for(const a of i){const u=a.map(o);if(!u)throw new Error("Failed to map step");n.step(u),o.appendMap(u.getMap())}return ss(t,n)}function nl(e){return typeof e!="string"?{ok:!1,error:"block must be a string"}:{ok:!0,value:e}}const Br={add:jo({description:"Insert new blocks",schema:{block:{$ref:"#/$defs/block"},$defs:{block:{type:"string",description:"markdown of block"}}},validateBlock:nl,rebaseTool:tl,toJSONToolCall:async(e,t)=>{const n=await Promise.all(t.operation.blocks.map(async r=>{const s=(await e.tryParseMarkdownToBlocks(r.trim()))[0];return delete s.id,s}));return window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=void 0),{...t.operation,blocks:n}}}),update:qo({description:"Update a block, the new block will replace the existing block.",schema:{block:{$ref:"#/$defs/block"},$defs:{block:{type:"string",description:"markdown of block"}}},validateBlock:nl,rebaseTool:tl,toJSONToolCall:async(e,t)=>{const n=(await e.tryParseMarkdownToBlocks(t.operation.block.trim()))[0];return delete n.id,window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=void 0),{...t.operation,block:n}}}),delete:zo};function jS(e,t){e.length>0&&e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the selection (ignore previous selections, you MUST issue operations against this latest version of the selection):"},{type:"text",text:JSON.stringify(t.markdownSelectedBlocks)},{type:"text",text:"This is the latest state of the document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.markdownDocument)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:"The user asks you to do the following:"},{type:"text",text:t.userPrompt}]}),e.push({role:"system",id:"document-state-intro",parts:[{type:"text",text:`You're manipulating a selected part of a text document using Markdown blocks.
6
35
  Make sure to follow the json schema provided and always include the trailing $ in ids.
7
- This is the selection as an array of Markdown blocks:`},{type:"text",text:JSON.stringify(t.markdownSelectedBlocks)},{type:"text",text:"This is the entire document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.markdownDocument)}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}function Ft(e,t){if(e.length>0){e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the document (ignore previous documents, you MUST issue operations against this latest version of the document):"},{type:"text",text:JSON.stringify(t.markdownBlocks)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:t.userPrompt}]});return}e.push({role:"system",id:"document-state",parts:[{type:"text",text:`You're manipulating a text document using Markdown blocks.
36
+ This is the selection as an array of Markdown blocks:`},{type:"text",text:JSON.stringify(t.markdownSelectedBlocks)},{type:"text",text:"This is the entire document (INCLUDING the selected text), find the selected text in there to understand the context:"},{type:"text",text:JSON.stringify(t.markdownDocument)}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}function qS(e,t){if(e.length>0){e.push({role:"assistant",id:"document-state-"+e.length,parts:[{type:"text",text:"This is the latest state of the document (ignore previous documents, you MUST issue operations against this latest version of the document):"},{type:"text",text:JSON.stringify(t.markdownBlocks)}]},{role:"user",id:"user-prompt-"+e.length,parts:[{type:"text",text:t.userPrompt}]});return}e.push({role:"system",id:"document-state",parts:[{type:"text",text:`You're manipulating a text document using Markdown blocks.
8
37
  Make sure to follow the json schema provided. When referencing ids they MUST be EXACTLY the same (including the trailing $).
9
- This is the initial document as an array of Markdown blocks (the cursor is BETWEEN two blocks as indicated by cursor: true):`},{type:"text",text:JSON.stringify(t.markdownBlocks)},{type:"text",text:'First, determine what part of the document the user is talking about. You SHOULD probably take cursor info into account if needed.\n EXAMPLE: if user says "below" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor. \n EXAMPLE: If you want to insert content AT the cursor position (UNLESS indicated otherwise by the user), \n then you need `referenceId` to point to the block before the cursor with position `after` (or block below and `before`).\n \n '+(t.isEmptyDocument?"Because the document is empty, first update the empty block before adding new blocks.":"Prefer updating existing blocks over removing and adding (but this also depends on the user's question).")}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}const Zt=async(e,t)=>{t.selection?Vt(e,t):Ft(e,t)};function Wt(e,t,o,r,n){if(typeof r=="boolean"){const i=r?e.getSelectionCutBlocks():void 0;r=i?{from:i._meta.startPos,to:i._meta.endPos}:void 0}const s=o??{add:!0,update:!0,delete:!0};return[...s.update?[F.update(e,{idsSuffixed:!0,withDelays:t,updateSelection:r,onBlockUpdate:n})]:[],...s.add?[F.add(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:n})]:[],...s.delete?[F.delete(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:n})]:[]]}const Yt={getStreamToolsProvider:(e={})=>({getStreamTools:(t,o,r)=>Wt(t,e.withDelays??!0,e.defaultStreamTools,o,r)}),tools:F,defaultPromptBuilder:Zt,defaultPromptInputDataBuilder:Rt,promptHelpers:{getDataForPromptNoSelection:ze,getDataForPromptWithSelection:Je}},M={_experimental_json:Jt,_experimental_markdown:Yt,html:Et},Gt={addCursorPosition:X,flattenBlocks:C,suffixIDs:D,trimEmptyBlocks:P,convertBlocks:B},Te=new U.PluginKey("blocknote-agent-cursor");function Kt(e){return new U.Plugin({key:Te,view:t=>({}),state:{init:()=>({selection:void 0}),apply:(t,o)=>{const r=t.getMeta("aiAgent");return r?{selection:r.selection}:{selection:void 0}}},props:{decorations:t=>{const{doc:o}=t,{selection:r}=Te.getState(t),n=[];if(!r)return J.DecorationSet.create(o,[]);n.push(J.Decoration.widget(r.head,()=>Xt(e),{key:"agent-cursor",side:10}));const s=Math.min(r.anchor,r.head),a=Math.max(r.anchor,r.head);return n.push(J.Decoration.inline(s,a,it.defaultSelectionBuilder(e),{inclusiveEnd:!0,inclusiveStart:!1})),J.DecorationSet.create(o,n)}}})}const Xt=e=>{const t=document.createElement("span");t.classList.add("bn-collaboration-cursor__base"),t.setAttribute("data-active","true");const o=document.createElement("span");o.setAttribute("contentedEditable","false"),o.classList.add("bn-collaboration-cursor__caret"),o.setAttribute("style",`background-color: ${e.color}`);const r=document.createElement("span");return r.classList.add("bn-collaboration-cursor__label"),r.setAttribute("style",`background-color: ${e.color}`),r.insertBefore(document.createTextNode(e.name),null),o.insertBefore(r,null),t.insertBefore(document.createTextNode("⁠"),null),t.insertBefore(o,null),t.insertBefore(document.createTextNode("⁠"),null),t},Qt=new U.PluginKey("blocknote-ai-plugin");class de extends b.BlockNoteExtension{constructor(o,r){super();L(this,"chatSession");L(this,"scrollInProgress",!1);L(this,"autoScroll",!1);L(this,"_store",fe()(o=>({aiMenuState:"closed"})));L(this,"options");this.editor=o,this.options=fe()(n=>({...r})),this.addProsemirrorPlugin(new U.Plugin({key:Qt,filterTransaction:n=>{var a;const s=this.store.getState().aiMenuState;return!(s!=="closed"&&s.status==="ai-writing"&&(a=n.getMeta(st.fixTablesKey))!=null&&a.fixTables)}})),this.addProsemirrorPlugin($.suggestChanges()),this.addProsemirrorPlugin(Kt(r.agentCursor||{name:"AI",color:"#8bc6ff"})),document.addEventListener("scroll",()=>{this.scrollInProgress&&(this.autoScroll=!1),this.scrollInProgress=!0},!0),document.addEventListener("scrollend",()=>{this.scrollInProgress=!1},!0)}static key(){return"ai"}get store(){return this._store}openAIMenuAtBlock(o){var n;this.editor.setForceSelectionVisible(!0),this.editor.isEditable=!1,this._store.setState({aiMenuState:{blockId:o,status:"user-input"}});const r=(n=this.editor.domElement)==null?void 0:n.querySelector(`[data-node-type="blockContainer"][data-id="${o}"]`);r==null||r.scrollIntoView({block:"center"})}closeAIMenu(){this._store.setState({aiMenuState:"closed"}),this.chatSession=void 0,this.editor.setForceSelectionVisible(!1),this.editor.isEditable=!0,this.editor.focus()}acceptChanges(){var r;const o=this.editor.prosemirrorState.doc;this.editor.exec((n,s)=>$.revertSuggestions(n,a=>{s==null||s(a.setMeta("addToHistory",!1))})),this.editor.exec((n,s)=>{const a=n.tr;a.replace(0,a.doc.content.size,new H.Slice(H.Fragment.from(o),0,0));const i=n.apply(a);return $.applySuggestions(i,l=>{s==null||s(a.replace(0,a.doc.content.size,new H.Slice(H.Fragment.from(l.doc),0,0)))})}),(r=this.editor.forkYDocPlugin)==null||r.merge({keepChanges:!0}),this.closeAIMenu()}rejectChanges(){var o;this.editor.exec((r,n)=>$.revertSuggestions(r,s=>{n==null||n(s.setMeta("addToHistory",!1))})),(o=this.editor.forkYDocPlugin)==null||o.merge({keepChanges:!1}),this.closeAIMenu()}async retry(){var r;const{aiMenuState:o}=this.store.getState();if(o==="closed"||o.status!=="error"||!this.chatSession)throw new Error("retry() is only valid when a previous response failed");return((r=this.chatSession)==null?void 0:r.chat.status)==="error"?this.invokeAI({...this.chatSession.previousRequestOptions,userPrompt:"An error occured in the previous request. Please retry to accomplish the last user prompt."}):this.invokeAI({...this.chatSession.previousRequestOptions,userPrompt:"An error occured while executing the previous tool call. Please retry to accomplish the last user prompt."})}setAIResponseStatus(o){const r=this.store.getState().aiMenuState;if(r!=="closed")if(o==="ai-writing"&&this.editor.setForceSelectionVisible(!1),typeof o=="object"){if(o.status!=="error")throw new b.UnreachableCaseError(o.status);this._store.setState({aiMenuState:{status:o.status,error:o.error,blockId:r.blockId}})}else this._store.setState({aiMenuState:{status:o,blockId:r.blockId}})}async callLLM(o){return this.invokeAI(o)}async invokeAI(o){var r,n;this.setAIResponseStatus("thinking"),(r=this.editor.forkYDocPlugin)==null||r.fork();try{this.chatSession?this.chatSession.previousRequestOptions=o:this.chatSession={previousRequestOptions:o,chat:new nt.Chat({sendAutomaticallyWhen:()=>!1,transport:o.transport||this.options.getState().transport})};const s=this.chatSession.chat;o={...this.options.getState(),...o};const i=o.aiRequestSender??Be(M.html.defaultPromptBuilder,M.html.defaultPromptInputDataBuilder),l=Ne({editor:this.editor,chat:s,userPrompt:o.userPrompt,useSelection:o.useSelection,deleteEmptyCursorBlock:o.deleteEmptyCursorBlock,streamToolsProvider:o.streamToolsProvider,onBlockUpdated:c=>{if(this._store.setState({aiMenuState:{blockId:c,status:"ai-writing"}}),!this.autoScroll)return;const u=this._store.getState().aiMenuState,m=u==="closed"?void 0:u;if(!m||m.status!=="ai-writing")return;const p=b.getNodeById(m.blockId,this.editor.prosemirrorState.doc);if(!p)return;this.editor.prosemirrorView.domAtPos(p.posBeforeNode+1).node.scrollIntoView({block:"center"})}});await Le({aiRequest:l,sender:i,chatRequestOptions:o.chatRequestOptions,onStart:()=>{this.autoScroll=!0,this.setAIResponseStatus("ai-writing")}}),this.setAIResponseStatus("user-reviewing")}catch(s){this.setAIResponseStatus({status:"error",error:s}),console.warn("Error calling LLM",s,(n=this.chatSession)==null?void 0:n.chat.messages)}}}function eo(e){return t=>new de(t,e)}function A(e){return e.extension(de)}const to=e=>async(t,o)=>{const r=new Request(t,o),n=e(r.url),s=new Request(n,{headers:r.headers,body:(o==null?void 0:o.body)||r.body,method:r.method,duplex:"half"});return await fetch(s)};var Re={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},ve=j.default.createContext&&j.default.createContext(Re),oo=["attr","size","title"];function ro(e,t){if(e==null)return{};var o=no(e,t),r,n;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n<s.length;n++)r=s[n],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}function no(e,t){if(e==null)return{};var o={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;o[r]=e[r]}return o}function G(){return G=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},G.apply(this,arguments)}function Pe(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),o.push.apply(o,r)}return o}function K(e){for(var t=1;t<arguments.length;t++){var o=arguments[t]!=null?arguments[t]:{};t%2?Pe(Object(o),!0).forEach(function(r){so(e,r,o[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):Pe(Object(o)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(o,r))})}return e}function so(e,t,o){return t=io(t),t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function io(e){var t=ao(e,"string");return typeof t=="symbol"?t:t+""}function ao(e,t){if(typeof e!="object"||!e)return e;var o=e[Symbol.toPrimitive];if(o!==void 0){var r=o.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Ve(e){return e&&e.map((t,o)=>j.default.createElement(t.tag,K({key:o},t.attr),Ve(t.child)))}function I(e){return t=>j.default.createElement(lo,G({attr:K({},e.attr)},t),Ve(e.child))}function lo(e){var t=o=>{var{attr:r,size:n,title:s}=e,a=ro(e,oo),i=n||o.size||"1em",l;return o.className&&(l=o.className),e.className&&(l=(l?l+" ":"")+e.className),j.default.createElement("svg",G({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},o.attr,r,a,{className:l,style:K(K({color:e.color||o.color},o.style),e.style),height:i,width:i,xmlns:"http://www.w3.org/2000/svg"}),s&&j.default.createElement("title",null,s),e.children)};return ve!==void 0?j.default.createElement(ve.Consumer,null,o=>t(o)):t(Re)}function Fe(e){return I({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M8 7V11L2 6L8 1V5H13C17.4183 5 21 8.58172 21 13C21 17.4183 17.4183 21 13 21H4V19H13C16.3137 19 19 16.3137 19 13C19 9.68629 16.3137 7 13 7H8Z"},child:[]}]})(e)}function Ce(e){return I({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M17.8492 11.6983L17.1421 10.9912L7.24264 20.8907H3V16.648L14.3137 5.33432L19.9706 10.9912C20.3611 11.3817 20.3611 12.0149 19.9706 12.4054L12.8995 19.4765L11.4853 18.0622L17.8492 11.6983ZM15.7279 9.57696L14.3137 8.16274L5 17.4765V18.8907H6.41421L15.7279 9.57696ZM18.5563 2.50589L21.3848 5.33432C21.7753 5.72484 21.7753 6.35801 21.3848 6.74853L19.9706 8.16274L15.7279 3.9201L17.1421 2.50589C17.5327 2.11537 18.1658 2.11537 18.5563 2.50589Z"},child:[]}]})(e)}function co(e){return I({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M15.1986 9.94447C14.7649 9.5337 14.4859 8.98613 14.4085 8.39384L14.0056 5.31138L11.275 6.79724C10.7503 7.08274 10.1433 7.17888 9.55608 7.06948L6.49998 6.50015L7.06931 9.55625C7.17871 10.1435 7.08257 10.7505 6.79707 11.2751L5.31121 14.0057L8.39367 14.4086C8.98596 14.4861 9.53353 14.7651 9.94431 15.1987L12.0821 17.4557L13.4178 14.6486C13.6745 14.1092 14.109 13.6747 14.6484 13.418L17.4555 12.0823L15.1986 9.94447ZM15.2238 15.5079L13.0111 20.1581C12.8687 20.4573 12.5107 20.5844 12.2115 20.442C12.1448 20.4103 12.0845 20.3665 12.0337 20.3129L8.49229 16.5741C8.39749 16.474 8.27113 16.4096 8.13445 16.3918L3.02816 15.7243C2.69958 15.6814 2.46804 15.3802 2.51099 15.0516C2.52056 14.9784 2.54359 14.9075 2.5789 14.8426L5.04031 10.3192C5.1062 10.1981 5.12839 10.058 5.10314 9.92253L4.16 4.85991C4.09931 4.53414 4.3142 4.22086 4.63997 4.16017C4.7126 4.14664 4.78711 4.14664 4.85974 4.16017L9.92237 5.10331C10.0579 5.12855 10.198 5.10637 10.319 5.04048L14.8424 2.57907C15.1335 2.42068 15.4979 2.52825 15.6562 2.81931C15.6916 2.88421 15.7146 2.95507 15.7241 3.02833L16.3916 8.13462C16.4095 8.2713 16.4739 8.39766 16.5739 8.49245L20.3127 12.0338C20.5533 12.2617 20.5636 12.6415 20.3357 12.8821C20.2849 12.9357 20.2246 12.9795 20.1579 13.0112L15.5078 15.224C15.3833 15.2832 15.283 15.3835 15.2238 15.5079ZM16.0206 17.435L17.4348 16.0208L21.6775 20.2634L20.2633 21.6776L16.0206 17.435Z"},child:[]}]})(e)}function uo(e){return I({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M8.00008 6V9H5.00008V6H8.00008ZM3.00008 4V11H10.0001V4H3.00008ZM13.0001 4H21.0001V6H13.0001V4ZM13.0001 11H21.0001V13H13.0001V11ZM13.0001 18H21.0001V20H13.0001V18ZM10.7072 16.2071L9.29297 14.7929L6.00008 18.0858L4.20718 16.2929L2.79297 17.7071L6.00008 20.9142L10.7072 16.2071Z"},child:[]}]})(e)}function po(e){return I({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M15 18H16.5C17.8807 18 19 16.8807 19 15.5C19 14.1193 17.8807 13 16.5 13H3V11H16.5C18.9853 11 21 13.0147 21 15.5C21 17.9853 18.9853 20 16.5 20H15V22L11 19L15 16V18ZM3 4H21V6H3V4ZM9 18V20H3V18H9Z"},child:[]}]})(e)}function mo(e){return I({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M13 6V21H11V6H5V4H19V6H13Z"},child:[]}]})(e)}function fo(e){return I({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M6.23509 6.45329C4.85101 7.89148 4 9.84636 4 12C4 16.4183 7.58172 20 12 20C13.0808 20 14.1116 19.7857 15.0521 19.3972C15.1671 18.6467 14.9148 17.9266 14.8116 17.6746C14.582 17.115 13.8241 16.1582 12.5589 14.8308C12.2212 14.4758 12.2429 14.2035 12.3636 13.3943L12.3775 13.3029C12.4595 12.7486 12.5971 12.4209 14.4622 12.1248C15.4097 11.9746 15.6589 12.3533 16.0043 12.8777C16.0425 12.9358 16.0807 12.9928 16.1198 13.0499C16.4479 13.5297 16.691 13.6394 17.0582 13.8064C17.2227 13.881 17.428 13.9751 17.7031 14.1314C18.3551 14.504 18.3551 14.9247 18.3551 15.8472V15.9518C18.3551 16.3434 18.3168 16.6872 18.2566 16.9859C19.3478 15.6185 20 13.8854 20 12C20 8.70089 18.003 5.8682 15.1519 4.64482C14.5987 5.01813 13.8398 5.54726 13.575 5.91C13.4396 6.09538 13.2482 7.04166 12.6257 7.11976C12.4626 7.14023 12.2438 7.12589 12.012 7.11097C11.3905 7.07058 10.5402 7.01606 10.268 7.75495C10.0952 8.2232 10.0648 9.49445 10.6239 10.1543C10.7134 10.2597 10.7307 10.4547 10.6699 10.6735C10.59 10.9608 10.4286 11.1356 10.3783 11.1717C10.2819 11.1163 10.0896 10.8931 9.95938 10.7412C9.64554 10.3765 9.25405 9.92233 8.74797 9.78176C8.56395 9.73083 8.36166 9.68867 8.16548 9.64736C7.6164 9.53227 6.99443 9.40134 6.84992 9.09302C6.74442 8.8672 6.74488 8.55621 6.74529 8.22764C6.74529 7.8112 6.74529 7.34029 6.54129 6.88256C6.46246 6.70541 6.35689 6.56446 6.23509 6.45329ZM12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22Z"},child:[]}]})(e)}function ho(e){return I({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M9.9997 15.1709L19.1921 5.97852L20.6063 7.39273L9.9997 17.9993L3.63574 11.6354L5.04996 10.2212L9.9997 15.1709Z"},child:[]}]})(e)}function yo(e){return I({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M9.9997 15.1709L19.1921 5.97852L20.6063 7.39273L9.9997 17.9993L3.63574 11.6354L5.04996 10.2212L9.9997 15.1709Z"},child:[]}]})(e)}function go(e){return I({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M12 4C9.4095 4 7.10606 5.23053 5.64274 7.14274L8 9.5H2V3.5L4.21863 5.71863C6.05061 3.452 8.85558 2 12 2 17.5228 2 22 6.47715 22 12H20C20 7.58172 16.4183 4 12 4ZM4 12C4 16.4183 7.58172 20 12 20 14.5905 20 16.894 18.7695 18.3573 16.8573L16 14.5 22 14.5V20.5L19.7814 18.2814C17.9494 20.548 15.1444 22 12 22 6.47715 22 2 17.5228 2 12H4Z"},child:[]}]})(e)}function pe(e){return I({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M17.0007 1.20825 18.3195 3.68108 20.7923 4.99992 18.3195 6.31876 17.0007 8.79159 15.6818 6.31876 13.209 4.99992 15.6818 3.68108 17.0007 1.20825ZM8.00065 4.33325 10.6673 9.33325 15.6673 11.9999 10.6673 14.6666 8.00065 19.6666 5.33398 14.6666.333984 11.9999 5.33398 9.33325 8.00065 4.33325ZM19.6673 16.3333 18.0007 13.2083 16.334 16.3333 13.209 17.9999 16.334 19.6666 18.0007 22.7916 19.6673 19.6666 22.7923 17.9999 19.6673 16.3333Z"},child:[]}]})(e)}function q(e){if(!e.dictionary.ai)throw new Error("AI dictionary not found");return e.dictionary.ai}function Ze(){const e=_.useBlockNoteContext();return q(e.editor)}const We=e=>{const t=_.useComponentsContext(),{onManualPromptSubmit:o,promptText:r,onPromptTextChange:n}=e,[s,a]=w.useState(""),i=r||s,l=w.useCallback(async f=>{f.key==="Enter"&&o(i)},[i,o]),c=w.useCallback(f=>{const k=f.currentTarget.value;n&&n(k),r===void 0&&a(k)},[n,a,r]),u=w.useMemo(()=>b.filterSuggestionItems(e.items,i),[i,e.items]),{selectedIndex:m,setSelectedIndex:p,handler:d}=_.useSuggestionMenuKeyboardHandler(u,f=>f.onItemClick()),h=w.useCallback(f=>{f.key==="Enter"?u.length>0?d(f):l(f):d(f)},[l,d,u.length]);return w.useEffect(()=>{p(0)},[i,p]),y.jsxs("div",{className:"bn-combobox",children:[y.jsx(t.Generic.Form.Root,{children:y.jsx(t.Generic.Form.TextInput,{className:"bn-combobox-input",name:"ai-prompt",variant:"large",icon:e.icon,value:i||"",autoFocus:!0,placeholder:e.placeholder,disabled:e.disabled,onKeyDown:h,onChange:c,autoComplete:"off",rightSection:e.rightSection},"input-"+e.disabled)}),y.jsx(t.SuggestionMenu.Root,{className:"bn-combobox-items",id:"ai-suggestion-menu",children:u.map((f,k)=>y.jsx(t.SuggestionMenu.Item,{className:b.mergeCSSClasses("bn-suggestion-menu-item",f.size==="small"?"bn-suggestion-menu-item-small":""),id:`bn-suggestion-menu-item-${k}`,isSelected:k===m,onClick:f.onItemClick,item:f},f.title))})]})};function bo(e){const t=q(e),o=A(e);return[{key:"continue_writing",title:t.ai_default_commands.continue_writing.title,aliases:t.ai_default_commands.continue_writing.aliases,icon:y.jsx(Ce,{size:18}),onItemClick:async()=>{await o.invokeAI({userPrompt:"Continue writing at the current cursor position related to the previous text. Add multiple blocks if needed. If the document looks like a template / draft, follow the template. Be extensive if needed.",streamToolsProvider:M.html.getStreamToolsProvider({defaultStreamTools:{add:!0,delete:!1,update:!1}})})},size:"small"},{key:"summarize",title:t.ai_default_commands.summarize.title,aliases:t.ai_default_commands.summarize.aliases,icon:y.jsx(po,{size:18}),onItemClick:async()=>{await o.invokeAI({userPrompt:"Summarize",streamToolsProvider:M.html.getStreamToolsProvider({defaultStreamTools:{add:!0,delete:!1,update:!1}})})},size:"small"},{key:"action_items",title:t.ai_default_commands.add_action_items.title,aliases:t.ai_default_commands.add_action_items.aliases,icon:y.jsx(uo,{size:18}),onItemClick:async()=>{await o.invokeAI({userPrompt:"Add action items",streamToolsProvider:M.html.getStreamToolsProvider({defaultStreamTools:{add:!0,delete:!1,update:!1}})})},size:"small"},{key:"write_anything",title:t.ai_default_commands.write_anything.title,aliases:t.ai_default_commands.write_anything.aliases,icon:y.jsx(Ce,{size:18}),onItemClick:r=>{r(t.ai_default_commands.write_anything.prompt_placeholder)},size:"small"}]}function So(e){const t=q(e),o=A(e);return[{key:"improve_writing",title:t.ai_default_commands.improve_writing.title,aliases:t.ai_default_commands.improve_writing.aliases,icon:y.jsx(mo,{size:18}),onItemClick:async()=>{await o.invokeAI({useSelection:!0,userPrompt:"Improve writing",streamToolsProvider:M.html.getStreamToolsProvider({defaultStreamTools:{add:!1,delete:!1,update:!0}})})},size:"small"},{key:"fix_spelling",title:t.ai_default_commands.fix_spelling.title,aliases:t.ai_default_commands.fix_spelling.aliases,icon:y.jsx(yo,{size:18}),onItemClick:async()=>{await o.invokeAI({useSelection:!0,userPrompt:"Fix spelling",streamToolsProvider:M.html.getStreamToolsProvider({defaultStreamTools:{add:!1,delete:!1,update:!0}})})},size:"small"},{key:"translate",title:t.ai_default_commands.translate.title,aliases:t.ai_default_commands.translate.aliases,icon:y.jsx(fo,{size:18}),onItemClick:r=>{r(t.ai_default_commands.translate.prompt_placeholder)},size:"small"},{key:"simplify",title:t.ai_default_commands.simplify.title,aliases:t.ai_default_commands.simplify.aliases,icon:y.jsx(co,{size:18}),onItemClick:async()=>{await o.invokeAI({useSelection:!0,userPrompt:"Simplify",streamToolsProvider:M.html.getStreamToolsProvider({defaultStreamTools:{add:!1,delete:!1,update:!0}})})},size:"small"}]}function ko(e){const t=q(e),o=A(e);return[{key:"accept",title:t.ai_menu.actions.accept.title,aliases:t.ai_menu.actions.accept.aliases,icon:y.jsx(ho,{size:18}),onItemClick:()=>{o.acceptChanges()},size:"small"},{key:"revert",title:t.ai_menu.actions.revert.title,aliases:t.ai_menu.actions.revert.aliases,icon:y.jsx(Fe,{size:18}),onItemClick:()=>{o.rejectChanges()},size:"small"}]}function wo(e){const t=q(e),o=A(e);return[{key:"retry",title:t.ai_menu.actions.retry.title,aliases:t.ai_menu.actions.retry.aliases,icon:y.jsx(go,{size:18}),onItemClick:async()=>{await o.retry()},size:"small"},{key:"cancel",title:t.ai_menu.actions.cancel.title,aliases:t.ai_menu.actions.cancel.aliases,icon:y.jsx(Fe,{size:18}),onItemClick:()=>{o.rejectChanges()},size:"small"}]}function Ye(e,t){return t==="user-input"?e.getSelection()?So(e):bo(e):t==="user-reviewing"?ko(e):t==="error"?wo(e):[]}const Ge=e=>{const t=_.useBlockNoteEditor(),[o,r]=w.useState(""),n=Ze(),s=_.useComponentsContext(),a=A(t),i=Ie.useStore(a.store,d=>d.aiMenuState!=="closed"?d.aiMenuState.status:"closed"),{items:l}=e,c=w.useMemo(()=>{let d=[];return l?d=l(t,i):d=Ye(t,i),d.map(h=>({...h,onItemClick:()=>{h.onItemClick(r)}}))},[l,i,t]),u=w.useCallback(async d=>{await a.invokeAI({userPrompt:d,useSelection:t.getSelection()!==void 0})},[a,t]);w.useEffect(()=>{(i==="user-reviewing"||i==="error")&&r("")},[i]);const m=w.useMemo(()=>i==="thinking"?n.ai_menu.status.thinking:i==="ai-writing"?n.ai_menu.status.editing:i==="error"?n.ai_menu.status.error:n.ai_menu.input_placeholder,[i,n]),p=w.useMemo(()=>{if(i==="thinking"||i==="ai-writing")return y.jsx(s.SuggestionMenu.Loader,{className:"bn-suggestion-menu-loader bn-combobox-right-section"});if(i==="error")return y.jsx("div",{className:"bn-combobox-right-section bn-combobox-error",children:y.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",fill:"currentColor",children:y.jsx("path",{d:"M480-280q17 0 28.5-11.5T520-320q0-17-11.5-28.5T480-360q-17 0-28.5 11.5T440-320q0 17 11.5 28.5T480-280Zm0-160q17 0 28.5-11.5T520-480v-160q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640v160q0 17 11.5 28.5T480-440Zm0 360q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"})})})},[s,i]);return y.jsx(We,{onManualPromptSubmit:e.onManualPromptSubmit||u,items:c,promptText:o,onPromptTextChange:r,placeholder:m,disabled:i==="thinking"||i==="ai-writing",icon:y.jsx("div",{className:"bn-combobox-icon",children:y.jsx(pe,{})}),rightSection:p})},Ke=e=>{const t=e.blockID?document.querySelector(`[data-id="${e.blockID}"]`):void 0,o=w.useMemo(()=>t?{getBoundingClientRect:()=>t.getBoundingClientRect(),contextElement:t}:null,[t]),{isMounted:r,ref:n,style:s,getFloatingProps:a,isPositioned:i}=_.useUIElementPositioning(!!t,o,3e3,{canDismiss:{enabled:!0,escapeKey:!0,outsidePress:e.canDismissViaOutsidePress},placement:"bottom",middleware:[te.offset(10),te.size({apply({rects:l,elements:c}){Object.assign(c.floating.style,{width:`${l.reference.width}px`})}})],onOpenChange:e.onOpenChange,whileElementsMounted:(l,c,u)=>te.autoUpdate(l,c,u,{animationFrame:!0}),...e.floatingOptions});return r?y.jsx("div",{ref:n,style:{...s},...a(),children:i&&e.children}):null},xo=e=>{const t=_.useBlockNoteEditor(),o=A(t),r=Ie.useStore(o.store,a=>a.aiMenuState),n=r==="closed"?void 0:r.blockId,s=e.aiMenu||Ge;return y.jsx(Ke,{canDismissViaOutsidePress:r==="closed"||r.status==="user-input",blockID:n,onOpenChange:a=>{a||r==="closed"||(r.status==="user-input"?o.closeAIMenu():(r.status==="user-reviewing"||r.status==="error")&&o.rejectChanges())},children:y.jsx(s,{})})},To=()=>{const e=Ze(),t=_.useComponentsContext(),o=_.useBlockNoteEditor(),r=A(o),n=()=>{o.formattingToolbar.closeMenu();const s=o.getSelection();if(!s)throw new Error("No selection");const a=s.blocks[s.blocks.length-1].id;r.openAIMenuAtBlock(a)};return o.isEditable?y.jsx(t.Generic.Toolbar.Button,{className:"bn-button",label:e.formatting_toolbar.ai.tooltip,mainTooltip:e.formatting_toolbar.ai.tooltip,icon:y.jsx(pe,{}),onClick:n}):null},vo={AI:pe};function Po(e){const t=A(e);return[{key:"ai",onItemClick:()=>{const r=e.getTextCursorPosition();r.block.content&&Array.isArray(r.block.content)&&r.block.content.length===0&&r.prevBlock?t.openAIMenuAtBlock(r.prevBlock.id):t.openAIMenuAtBlock(r.block.id)},...q(e).slash_menu.ai,icon:y.jsx(vo.AI,{})}]}function Xe(e){return Object.fromEntries(Object.entries(e).map(([t,o])=>[t,T.tool({...o,inputSchema:T.jsonSchema(o.inputSchema),outputSchema:T.jsonSchema(o.outputSchema)})]))}function Qe(e,t){let o="";return e.pipeThrough(new TransformStream({start(r){r.enqueue({type:"start"}),r.enqueue({type:"start-step"}),r.enqueue({type:"tool-input-start",toolCallId:"call_object_1",toolName:t})},transform(r,n){switch(r.type){case"text-delta":o+=r.textDelta,n.enqueue({type:"tool-input-delta",toolCallId:"call_object_1",inputTextDelta:r.textDelta});break;case"object":case"finish":break;case"error":n.enqueue({type:"error",errorText:re.getErrorMessage(r.error)});break;default:{const s=r;throw new Error(`Unsupported chunk type: ${s}`)}}},async flush(r){r.enqueue({type:"tool-input-available",toolCallId:"call_object_1",toolName:t,input:JSON.parse(o)}),r.enqueue({type:"finish-step"}),r.enqueue({type:"finish"})}}))}function et(e,t){return new ReadableStream({start(r){r.enqueue({type:"start"}),r.enqueue({type:"start-step"}),r.enqueue({type:"tool-input-start",toolCallId:"call_object_1",toolName:t}),r.enqueue({type:"tool-input-delta",toolCallId:"call_object_1",inputTextDelta:JSON.stringify(e)}),r.enqueue({type:"tool-input-available",toolCallId:"call_object_1",toolName:t,input:e}),r.enqueue({type:"finish-step"}),r.enqueue({type:"finish"}),r.close()}})}const tt={"mistral.chat":{mode:"auto"},"google.generative-ai":{mode:"auto"},"groq.chat":{providerOptions:{groq:{structuredOutputs:!1}}}};function oe(e){return tt[e.provider]||{}}class Co{constructor(t){this.opts=t}async generateObject(t,o){const{model:r,_additionalOptions:n}=this.opts;if(typeof r=="string")throw new Error("model must be a LanguageModelV2");const s=Object.keys(o)[0],a=o[s].inputSchema,i=await T.generateObject({output:"object",schema:a,model:r,mode:"tool",messages:T.convertToModelMessages(t),...oe(r),...n??{}});return et(i.object,s)}async streamObject(t,o){const{model:r,_additionalOptions:n}=this.opts;if(typeof r=="string")throw new Error("model must be a LanguageModelV2");const s=Object.keys(o)[0],a=o[s].inputSchema,i=T.streamObject({output:"object",schema:a,model:r,mode:"tool",messages:T.convertToModelMessages(t),...oe(r),...n??{}});return Qe(i.fullStream,s)}async streamText(t,o){const{model:r,_additionalOptions:n}=this.opts;return T.streamText({model:r,messages:T.convertToModelMessages(t),tools:o,toolChoice:"required",...n??{}}).toUIMessageStream()}async sendMessages({messages:t,body:o}){const r=this.opts.stream??!0,n=o.toolDefinitions,s=Xe(n);if(this.opts.objectGeneration)return r?this.streamObject(t,s):this.generateObject(t,s);if(r)return await this.streamText(t,s);throw new Error("Not implemented (generateText)")}reconnectToStream(){throw new Error("Not implemented")}}exports.AIExtension=de;exports.AIMenu=Ge;exports.AIMenuController=xo;exports.AIToolbarButton=To;exports.BlockPositioner=Ke;exports.ChunkExecutionError=ne;exports.ClientSideTransport=Co;exports.PROVIDER_OVERRIDES=tt;exports.PromptSuggestionMenu=We;exports.StreamToolExecutor=Ee;exports.aiDocumentFormats=M;exports.buildAIRequest=Ne;exports.createAIExtension=eo;exports.createStreamToolsArraySchema=Me;exports.defaultAIRequestSender=Be;exports.executeAIRequest=Le;exports.fetchViaProxy=to;exports.getAIDictionary=q;exports.getAIExtension=A;exports.getAISlashMenuItems=Po;exports.getDefaultAIMenuItems=Ye;exports.getProviderOverrides=oe;exports.objectAsToolCallInUIMessageStream=et;exports.objectStreamToOperationsResult=Ae;exports.partialObjectStreamAsToolCallInUIMessageStream=Qe;exports.promptHelpers=Gt;exports.toolDefinitionsToToolSet=Xe;
38
+ This is the initial document as an array of Markdown blocks (the cursor is BETWEEN two blocks as indicated by cursor: true):`},{type:"text",text:JSON.stringify(t.markdownBlocks)},{type:"text",text:'First, determine what part of the document the user is talking about. You SHOULD probably take cursor info into account if needed.\n EXAMPLE: if user says "below" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor. \n EXAMPLE: If you want to insert content AT the cursor position (UNLESS indicated otherwise by the user), \n then you need `referenceId` to point to the block before the cursor with position `after` (or block below and `before`).\n \n '+(t.isEmptyDocument?"Because the document is empty, first update the empty block before adding new blocks.":"Prefer updating existing blocks over removing and adding (but this also depends on the user's question).")}]},{role:"user",id:"user-prompt",parts:[{type:"text",text:t.userPrompt}]})}const zS=async(e,t)=>{t.selection?jS(e,t):qS(e,t)};function WS(e,t,n,r,s){if(typeof r=="boolean"){const a=r?e.getSelectionCutBlocks():void 0;r=a?{from:a._meta.startPos,to:a._meta.endPos}:void 0}const i=n??{add:!0,update:!0,delete:!0};return[...i.update?[Br.update(e,{idsSuffixed:!0,withDelays:t,updateSelection:r,onBlockUpdate:s})]:[],...i.add?[Br.add(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:s})]:[],...i.delete?[Br.delete(e,{idsSuffixed:!0,withDelays:t,onBlockUpdate:s})]:[]]}const GS={getStreamToolsProvider:(e={})=>({getStreamTools:(t,n,r)=>WS(t,e.withDelays??!0,e.defaultStreamTools,n,r)}),tools:Br,defaultPromptBuilder:zS,defaultPromptInputDataBuilder:$S,promptHelpers:{getDataForPromptNoSelection:Rh,getDataForPromptWithSelection:Ph}},Qe={_experimental_json:YS,_experimental_markdown:GS,html:LS},KS={addCursorPosition:Ls,flattenBlocks:Fe,suffixIDs:qt,trimEmptyBlocks:He,convertBlocks:et},rl=new D.PluginKey("blocknote-agent-cursor");function XS(e){return new D.Plugin({key:rl,view:t=>({}),state:{init:()=>({selection:void 0}),apply:(t,n)=>{const r=t.getMeta("aiAgent");return r?{selection:r.selection}:{selection:void 0}}},props:{decorations:t=>{const{doc:n}=t,{selection:r}=rl.getState(t),s=[];if(!r)return G.DecorationSet.create(n,[]);s.push(G.Decoration.widget(r.head,()=>QS(e),{key:"agent-cursor",side:10}));const i=Math.min(r.anchor,r.head),o=Math.max(r.anchor,r.head);return s.push(G.Decoration.inline(i,o,Ie.defaultSelectionBuilder(e),{inclusiveEnd:!0,inclusiveStart:!1})),G.DecorationSet.create(n,s)}}})}const QS=e=>{const t=document.createElement("span");t.classList.add("bn-collaboration-cursor__base"),t.setAttribute("data-active","true");const n=document.createElement("span");n.setAttribute("contentedEditable","false"),n.classList.add("bn-collaboration-cursor__caret"),n.setAttribute("style",`background-color: ${e.color}`);const r=document.createElement("span");return r.classList.add("bn-collaboration-cursor__label"),r.setAttribute("style",`background-color: ${e.color}`),r.insertBefore(document.createTextNode(e.name),null),n.insertBefore(r,null),t.insertBefore(document.createTextNode("⁠"),null),t.insertBefore(n,null),t.insertBefore(document.createTextNode("⁠"),null),t},JS=new D.PluginKey("blocknote-ai-plugin"),Ve=ee.createExtension(({editor:e,options:t})=>{const n=ee.createStore(t??{}),r=ee.createStore({aiMenuState:"closed"});let s,i=!1;return{key:"ai",options:n,store:r,mount({signal:o}){let a=!1;document.addEventListener("scroll",()=>{a&&(i=!1),a=!0},{capture:!0,signal:o}),document.addEventListener("scrollend",()=>{a=!1},{capture:!0,signal:o})},prosemirrorPlugins:[new D.Plugin({key:JS,filterTransaction:o=>{var u;const a=r.state.aiMenuState;return!(a!=="closed"&&a.status==="ai-writing"&&(u=o.getMeta(te.fixTablesKey))!=null&&u.fixTables)}}),Nn.suggestChanges(),XS((t==null?void 0:t.agentCursor)||{name:"AI",color:"#8bc6ff"})],openAIMenuAtBlock(o){var u,c;(u=e.getExtension(di))==null||u.showSelection(!0),e.isEditable=!1,r.setState({aiMenuState:{blockId:o,status:"user-input"}});const a=(c=e.domElement)==null?void 0:c.querySelector(`[data-node-type="blockContainer"][data-id="${o}"]`);a==null||a.scrollIntoView({block:"center"})},closeAIMenu(){var o;r.setState({aiMenuState:"closed"}),s=void 0,(o=e.getExtension(di))==null||o.showSelection(!1),e.isEditable=!0,e.focus()},acceptChanges(){var a;const o=e.prosemirrorState.doc;e.exec((u,c)=>Nn.revertSuggestions(u,d=>{c==null||c(d.setMeta("addToHistory",!1))})),e.exec((u,c)=>{const d=u.tr;d.replace(0,d.doc.content.size,new X.Slice(X.Fragment.from(o),0,0));const h=u.apply(d);return Nn.applySuggestions(h,f=>{c==null||c(d.replace(0,d.doc.content.size,new X.Slice(X.Fragment.from(f.doc),0,0)))})}),(a=e.getExtension(ci))==null||a.merge({keepChanges:!0}),this.closeAIMenu()},rejectChanges(){var o;e.exec((a,u)=>Nn.revertSuggestions(a,c=>{u==null||u(c.setMeta("addToHistory",!1))})),(o=e.getExtension(ci))==null||o.merge({keepChanges:!1}),this.closeAIMenu()},async retry(){const{aiMenuState:o}=r.state;if(o==="closed"||o.status!=="error"||!s)throw new Error("retry() is only valid when a previous response failed");return(s==null?void 0:s.chat.status)==="error"?this.invokeAI({...s.previousRequestOptions,userPrompt:"An error occured in the previous request. Please retry to accomplish the last user prompt."}):this.invokeAI({...s.previousRequestOptions,userPrompt:"An error occured while executing the previous tool call. Please retry to accomplish the last user prompt."})},setAIResponseStatus(o){var u;const a=r.state.aiMenuState;if(a!=="closed")if(o==="ai-writing"&&((u=e.getExtension(di))==null||u.showSelection(!1)),typeof o=="object"){if(o.status!=="error")throw new ee.UnreachableCaseError(o.status);r.setState({aiMenuState:{status:o.status,error:o.error,blockId:a.blockId}})}else r.setState({aiMenuState:{status:o,blockId:a.blockId}})},async callLLM(o){return this.invokeAI(o)},async invokeAI(o){var a;this.setAIResponseStatus("thinking"),(a=e.getExtension(ci))==null||a.fork();try{s?s.previousRequestOptions=o:s={previousRequestOptions:o,chat:new Xh.Chat({sendAutomaticallyWhen:()=>!1,transport:o.transport||n.state.transport})};const u=s.chat;o={...n.state,...o};const d=o.aiRequestSender??Sh(Qe.html.defaultPromptBuilder,Qe.html.defaultPromptInputDataBuilder),h=Ih({editor:e,chat:u,userPrompt:o.userPrompt,useSelection:o.useSelection,deleteEmptyCursorBlock:o.deleteEmptyCursorBlock,streamToolsProvider:o.streamToolsProvider,onBlockUpdated:f=>{const p=r.state.aiMenuState,m=p==="closed"?void 0:p;if(!m||m.status!=="ai-writing")return;const E=ee.getNodeById(f,e.prosemirrorState.doc);E&&(r.setState({aiMenuState:{blockId:f,status:"ai-writing"}}),i&&e.prosemirrorView.domAtPos(E.posBeforeNode+1).node.scrollIntoView({block:"center"}))}});await xh({aiRequest:h,sender:d,chatRequestOptions:o.chatRequestOptions,onStart:()=>{i=!0,this.setAIResponseStatus("ai-writing")}}),this.setAIResponseStatus("user-reviewing")}catch(u){this.setAIResponseStatus({status:"error",error:u}),console.warn("Error calling LLM",u,s==null?void 0:s.chat.messages)}}}}),ZS=e=>async(t,n)=>{const r=new Request(t,n),s=e(r.url),i=new Request(s,{headers:r.headers,body:(n==null?void 0:n.body)||r.body,method:r.method,duplex:"half"});return await fetch(i)};var Bh={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},sl=Nt.default.createContext&&Nt.default.createContext(Bh),eA=["attr","size","title"];function tA(e,t){if(e==null)return{};var n=nA(e,t),r,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)r=i[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function nA(e,t){if(e==null)return{};var n={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;n[r]=e[r]}return n}function is(){return is=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},is.apply(this,arguments)}function il(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function os(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?il(Object(n),!0).forEach(function(r){rA(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):il(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function rA(e,t,n){return t=sA(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function sA(e){var t=iA(e,"string");return typeof t=="symbol"?t:t+""}function iA(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Uh(e){return e&&e.map((t,n)=>Nt.default.createElement(t.tag,os({key:n},t.attr),Uh(t.child)))}function je(e){return t=>Nt.default.createElement(oA,is({attr:os({},e.attr)},t),Uh(e.child))}function oA(e){var t=n=>{var{attr:r,size:s,title:i}=e,o=tA(e,eA),a=s||n.size||"1em",u;return n.className&&(u=n.className),e.className&&(u=(u?u+" ":"")+e.className),Nt.default.createElement("svg",is({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,o,{className:u,style:os(os({color:e.color||n.color},n.style),e.style),height:a,width:a,xmlns:"http://www.w3.org/2000/svg"}),i&&Nt.default.createElement("title",null,i),e.children)};return sl!==void 0?Nt.default.createElement(sl.Consumer,null,n=>t(n)):t(Bh)}function Hh(e){return je({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M8 7V11L2 6L8 1V5H13C17.4183 5 21 8.58172 21 13C21 17.4183 17.4183 21 13 21H4V19H13C16.3137 19 19 16.3137 19 13C19 9.68629 16.3137 7 13 7H8Z"},child:[]}]})(e)}function ol(e){return je({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M17.8492 11.6983L17.1421 10.9912L7.24264 20.8907H3V16.648L14.3137 5.33432L19.9706 10.9912C20.3611 11.3817 20.3611 12.0149 19.9706 12.4054L12.8995 19.4765L11.4853 18.0622L17.8492 11.6983ZM15.7279 9.57696L14.3137 8.16274L5 17.4765V18.8907H6.41421L15.7279 9.57696ZM18.5563 2.50589L21.3848 5.33432C21.7753 5.72484 21.7753 6.35801 21.3848 6.74853L19.9706 8.16274L15.7279 3.9201L17.1421 2.50589C17.5327 2.11537 18.1658 2.11537 18.5563 2.50589Z"},child:[]}]})(e)}function aA(e){return je({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M15.1986 9.94447C14.7649 9.5337 14.4859 8.98613 14.4085 8.39384L14.0056 5.31138L11.275 6.79724C10.7503 7.08274 10.1433 7.17888 9.55608 7.06948L6.49998 6.50015L7.06931 9.55625C7.17871 10.1435 7.08257 10.7505 6.79707 11.2751L5.31121 14.0057L8.39367 14.4086C8.98596 14.4861 9.53353 14.7651 9.94431 15.1987L12.0821 17.4557L13.4178 14.6486C13.6745 14.1092 14.109 13.6747 14.6484 13.418L17.4555 12.0823L15.1986 9.94447ZM15.2238 15.5079L13.0111 20.1581C12.8687 20.4573 12.5107 20.5844 12.2115 20.442C12.1448 20.4103 12.0845 20.3665 12.0337 20.3129L8.49229 16.5741C8.39749 16.474 8.27113 16.4096 8.13445 16.3918L3.02816 15.7243C2.69958 15.6814 2.46804 15.3802 2.51099 15.0516C2.52056 14.9784 2.54359 14.9075 2.5789 14.8426L5.04031 10.3192C5.1062 10.1981 5.12839 10.058 5.10314 9.92253L4.16 4.85991C4.09931 4.53414 4.3142 4.22086 4.63997 4.16017C4.7126 4.14664 4.78711 4.14664 4.85974 4.16017L9.92237 5.10331C10.0579 5.12855 10.198 5.10637 10.319 5.04048L14.8424 2.57907C15.1335 2.42068 15.4979 2.52825 15.6562 2.81931C15.6916 2.88421 15.7146 2.95507 15.7241 3.02833L16.3916 8.13462C16.4095 8.2713 16.4739 8.39766 16.5739 8.49245L20.3127 12.0338C20.5533 12.2617 20.5636 12.6415 20.3357 12.8821C20.2849 12.9357 20.2246 12.9795 20.1579 13.0112L15.5078 15.224C15.3833 15.2832 15.283 15.3835 15.2238 15.5079ZM16.0206 17.435L17.4348 16.0208L21.6775 20.2634L20.2633 21.6776L16.0206 17.435Z"},child:[]}]})(e)}function uA(e){return je({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M8.00008 6V9H5.00008V6H8.00008ZM3.00008 4V11H10.0001V4H3.00008ZM13.0001 4H21.0001V6H13.0001V4ZM13.0001 11H21.0001V13H13.0001V11ZM13.0001 18H21.0001V20H13.0001V18ZM10.7072 16.2071L9.29297 14.7929L6.00008 18.0858L4.20718 16.2929L2.79297 17.7071L6.00008 20.9142L10.7072 16.2071Z"},child:[]}]})(e)}function lA(e){return je({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M15 18H16.5C17.8807 18 19 16.8807 19 15.5C19 14.1193 17.8807 13 16.5 13H3V11H16.5C18.9853 11 21 13.0147 21 15.5C21 17.9853 18.9853 20 16.5 20H15V22L11 19L15 16V18ZM3 4H21V6H3V4ZM9 18V20H3V18H9Z"},child:[]}]})(e)}function cA(e){return je({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M13 6V21H11V6H5V4H19V6H13Z"},child:[]}]})(e)}function dA(e){return je({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M6.23509 6.45329C4.85101 7.89148 4 9.84636 4 12C4 16.4183 7.58172 20 12 20C13.0808 20 14.1116 19.7857 15.0521 19.3972C15.1671 18.6467 14.9148 17.9266 14.8116 17.6746C14.582 17.115 13.8241 16.1582 12.5589 14.8308C12.2212 14.4758 12.2429 14.2035 12.3636 13.3943L12.3775 13.3029C12.4595 12.7486 12.5971 12.4209 14.4622 12.1248C15.4097 11.9746 15.6589 12.3533 16.0043 12.8777C16.0425 12.9358 16.0807 12.9928 16.1198 13.0499C16.4479 13.5297 16.691 13.6394 17.0582 13.8064C17.2227 13.881 17.428 13.9751 17.7031 14.1314C18.3551 14.504 18.3551 14.9247 18.3551 15.8472V15.9518C18.3551 16.3434 18.3168 16.6872 18.2566 16.9859C19.3478 15.6185 20 13.8854 20 12C20 8.70089 18.003 5.8682 15.1519 4.64482C14.5987 5.01813 13.8398 5.54726 13.575 5.91C13.4396 6.09538 13.2482 7.04166 12.6257 7.11976C12.4626 7.14023 12.2438 7.12589 12.012 7.11097C11.3905 7.07058 10.5402 7.01606 10.268 7.75495C10.0952 8.2232 10.0648 9.49445 10.6239 10.1543C10.7134 10.2597 10.7307 10.4547 10.6699 10.6735C10.59 10.9608 10.4286 11.1356 10.3783 11.1717C10.2819 11.1163 10.0896 10.8931 9.95938 10.7412C9.64554 10.3765 9.25405 9.92233 8.74797 9.78176C8.56395 9.73083 8.36166 9.68867 8.16548 9.64736C7.6164 9.53227 6.99443 9.40134 6.84992 9.09302C6.74442 8.8672 6.74488 8.55621 6.74529 8.22764C6.74529 7.8112 6.74529 7.34029 6.54129 6.88256C6.46246 6.70541 6.35689 6.56446 6.23509 6.45329ZM12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22Z"},child:[]}]})(e)}function hA(e){return je({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M9.9997 15.1709L19.1921 5.97852L20.6063 7.39273L9.9997 17.9993L3.63574 11.6354L5.04996 10.2212L9.9997 15.1709Z"},child:[]}]})(e)}function fA(e){return je({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M9.9997 15.1709L19.1921 5.97852L20.6063 7.39273L9.9997 17.9993L3.63574 11.6354L5.04996 10.2212L9.9997 15.1709Z"},child:[]}]})(e)}function pA(e){return je({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M12 4C9.4095 4 7.10606 5.23053 5.64274 7.14274L8 9.5H2V3.5L4.21863 5.71863C6.05061 3.452 8.85558 2 12 2 17.5228 2 22 6.47715 22 12H20C20 7.58172 16.4183 4 12 4ZM4 12C4 16.4183 7.58172 20 12 20 14.5905 20 16.894 18.7695 18.3573 16.8573L16 14.5 22 14.5V20.5L19.7814 18.2814C17.9494 20.548 15.1444 22 12 22 6.47715 22 2 17.5228 2 12H4Z"},child:[]}]})(e)}function Wo(e){return je({attr:{viewBox:"0 0 24 24",fill:"currentColor"},child:[{tag:"path",attr:{d:"M17.0007 1.20825 18.3195 3.68108 20.7923 4.99992 18.3195 6.31876 17.0007 8.79159 15.6818 6.31876 13.209 4.99992 15.6818 3.68108 17.0007 1.20825ZM8.00065 4.33325 10.6673 9.33325 15.6673 11.9999 10.6673 14.6666 8.00065 19.6666 5.33398 14.6666.333984 11.9999 5.33398 9.33325 8.00065 4.33325ZM19.6673 16.3333 18.0007 13.2083 16.334 16.3333 13.209 17.9999 16.334 19.6666 18.0007 22.7916 19.6673 19.6666 22.7923 17.9999 19.6673 16.3333Z"},child:[]}]})(e)}function zt(e){if(!e.dictionary.ai)throw new Error("AI dictionary not found");return e.dictionary.ai}function Fh(){const e=me.useBlockNoteContext();return zt(e.editor)}const Vh=e=>{const t=me.useComponentsContext(),{onManualPromptSubmit:n,promptText:r,onPromptTextChange:s}=e,[i,o]=Te.useState(""),a=r||i,u=Te.useCallback(async E=>{E.key==="Enter"&&n(a)},[a,n]),c=Te.useCallback(E=>{const C=E.currentTarget.value;s&&s(C),r===void 0&&o(C)},[s,o,r]),d=Te.useMemo(()=>y0(e.items,a),[a,e.items]),{selectedIndex:h,setSelectedIndex:f,handler:p}=me.useSuggestionMenuKeyboardHandler(d,E=>E.onItemClick()),m=Te.useCallback(E=>{E.key==="Enter"?d.length>0?p(E):u(E):p(E)},[u,p,d.length]);return Te.useEffect(()=>{f(0)},[a,f]),q.jsxs("div",{className:"bn-combobox",children:[q.jsx(t.Generic.Form.Root,{children:q.jsx(t.Generic.Form.TextInput,{className:"bn-combobox-input",name:"ai-prompt",variant:"large",icon:e.icon,value:a||"",autoFocus:!0,placeholder:e.placeholder,disabled:e.disabled,onKeyDown:m,onChange:c,autoComplete:"off",rightSection:e.rightSection},"input-"+e.disabled)}),q.jsx(t.SuggestionMenu.Root,{className:"bn-combobox-items",id:"ai-suggestion-menu",children:d.map((E,C)=>q.jsx(t.SuggestionMenu.Item,{className:ee.mergeCSSClasses("bn-suggestion-menu-item",E.size==="small"?"bn-suggestion-menu-item-small":""),id:`bn-suggestion-menu-item-${C}`,isSelected:C===h,onClick:E.onItemClick,item:E},E.title))})]})};function mA(e){const t=zt(e),n=e.getExtension(Ve);return n?[{key:"continue_writing",title:t.ai_default_commands.continue_writing.title,aliases:t.ai_default_commands.continue_writing.aliases,icon:q.jsx(ol,{size:18}),onItemClick:async()=>{await n.invokeAI({userPrompt:"Continue writing at the current cursor position related to the previous text. Add multiple blocks if needed. If the document looks like a template / draft, follow the template. Be extensive if needed.",streamToolsProvider:Qe.html.getStreamToolsProvider({defaultStreamTools:{add:!0,delete:!1,update:!1}})})},size:"small"},{key:"summarize",title:t.ai_default_commands.summarize.title,aliases:t.ai_default_commands.summarize.aliases,icon:q.jsx(lA,{size:18}),onItemClick:async()=>{await n.invokeAI({userPrompt:"Summarize",streamToolsProvider:Qe.html.getStreamToolsProvider({defaultStreamTools:{add:!0,delete:!1,update:!1}})})},size:"small"},{key:"action_items",title:t.ai_default_commands.add_action_items.title,aliases:t.ai_default_commands.add_action_items.aliases,icon:q.jsx(uA,{size:18}),onItemClick:async()=>{await n.invokeAI({userPrompt:"Add action items",streamToolsProvider:Qe.html.getStreamToolsProvider({defaultStreamTools:{add:!0,delete:!1,update:!1}})})},size:"small"},{key:"write_anything",title:t.ai_default_commands.write_anything.title,aliases:t.ai_default_commands.write_anything.aliases,icon:q.jsx(ol,{size:18}),onItemClick:r=>{r(t.ai_default_commands.write_anything.prompt_placeholder)},size:"small"}]:[]}function gA(e){const t=zt(e),n=e.getExtension(Ve);return n?[{key:"improve_writing",title:t.ai_default_commands.improve_writing.title,aliases:t.ai_default_commands.improve_writing.aliases,icon:q.jsx(cA,{size:18}),onItemClick:async()=>{await n.invokeAI({useSelection:!0,userPrompt:"Improve writing",streamToolsProvider:Qe.html.getStreamToolsProvider({defaultStreamTools:{add:!1,delete:!1,update:!0}})})},size:"small"},{key:"fix_spelling",title:t.ai_default_commands.fix_spelling.title,aliases:t.ai_default_commands.fix_spelling.aliases,icon:q.jsx(fA,{size:18}),onItemClick:async()=>{await n.invokeAI({useSelection:!0,userPrompt:"Fix spelling",streamToolsProvider:Qe.html.getStreamToolsProvider({defaultStreamTools:{add:!1,delete:!1,update:!0}})})},size:"small"},{key:"translate",title:t.ai_default_commands.translate.title,aliases:t.ai_default_commands.translate.aliases,icon:q.jsx(dA,{size:18}),onItemClick:r=>{r(t.ai_default_commands.translate.prompt_placeholder)},size:"small"},{key:"simplify",title:t.ai_default_commands.simplify.title,aliases:t.ai_default_commands.simplify.aliases,icon:q.jsx(aA,{size:18}),onItemClick:async()=>{await n.invokeAI({useSelection:!0,userPrompt:"Simplify",streamToolsProvider:Qe.html.getStreamToolsProvider({defaultStreamTools:{add:!1,delete:!1,update:!0}})})},size:"small"}]:[]}function bA(e){const t=zt(e),n=e.getExtension(Ve);return n?[{key:"accept",title:t.ai_menu.actions.accept.title,aliases:t.ai_menu.actions.accept.aliases,icon:q.jsx(hA,{size:18}),onItemClick:()=>{n.acceptChanges()},size:"small"},{key:"revert",title:t.ai_menu.actions.revert.title,aliases:t.ai_menu.actions.revert.aliases,icon:q.jsx(Hh,{size:18}),onItemClick:()=>{n.rejectChanges()},size:"small"}]:[]}function EA(e){const t=zt(e),n=e.getExtension(Ve);return n?[{key:"retry",title:t.ai_menu.actions.retry.title,aliases:t.ai_menu.actions.retry.aliases,icon:q.jsx(pA,{size:18}),onItemClick:async()=>{await n.retry()},size:"small"},{key:"cancel",title:t.ai_menu.actions.cancel.title,aliases:t.ai_menu.actions.cancel.aliases,icon:q.jsx(Hh,{size:18}),onItemClick:()=>{n.rejectChanges()},size:"small"}]:[]}function Yh(e,t){return t==="user-input"?e.getSelection()?gA(e):mA(e):t==="user-reviewing"?bA(e):t==="error"?EA(e):[]}const $h=e=>{const t=me.useBlockNoteEditor(),[n,r]=Te.useState(""),s=Fh(),i=me.useComponentsContext(),o=me.useExtension(Ve),a=me.useExtensionState(Ve,{selector:p=>p.aiMenuState!=="closed"?p.aiMenuState.status:"closed"}),{items:u}=e,c=Te.useMemo(()=>{let p=[];return u?p=u(t,a):p=Yh(t,a),p.map(m=>({...m,onItemClick:()=>{m.onItemClick(r)}}))},[u,a,t]),d=Te.useCallback(async p=>{await o.invokeAI({userPrompt:p,useSelection:t.getSelection()!==void 0})},[o,t]);Te.useEffect(()=>{(a==="ai-writing"||a==="user-reviewing"||a==="error")&&r("")},[a]);const h=Te.useMemo(()=>a==="thinking"?s.ai_menu.status.thinking:a==="ai-writing"?s.ai_menu.status.editing:a==="error"?s.ai_menu.status.error:s.ai_menu.input_placeholder,[a,s]),f=Te.useMemo(()=>{if(a==="thinking"||a==="ai-writing")return q.jsx(i.SuggestionMenu.Loader,{className:"bn-suggestion-menu-loader bn-combobox-right-section"});if(a==="error")return q.jsx("div",{className:"bn-combobox-right-section bn-combobox-error",children:q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",fill:"currentColor",children:q.jsx("path",{d:"M480-280q17 0 28.5-11.5T520-320q0-17-11.5-28.5T480-360q-17 0-28.5 11.5T440-320q0 17 11.5 28.5T480-280Zm0-160q17 0 28.5-11.5T520-480v-160q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640v160q0 17 11.5 28.5T480-440Zm0 360q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"})})})},[i,a]);return q.jsx(Vh,{onManualPromptSubmit:e.onManualPromptSubmit||d,items:c,promptText:n,onPromptTextChange:r,placeholder:h,disabled:a==="thinking"||a==="ai-writing",icon:q.jsx("div",{className:"bn-combobox-icon",children:q.jsx(Wo,{})}),rightSection:f})},TA=e=>{const t=me.useBlockNoteEditor(),n=me.useExtension(Ve),r=me.useExtensionState(Ve,{editor:t,selector:a=>a.aiMenuState}),s=r==="closed"?void 0:r.blockId,i=Te.useMemo(()=>({useFloatingOptions:{open:r!=="closed",placement:"bottom",middleware:[Jo.offset(10),Jo.size({apply({rects:a,elements:u}){Object.assign(u.floating.style,{width:`${a.reference.width}px`})}})],onOpenChange:a=>{a||r==="closed"||(r.status==="user-input"?n.closeAIMenu():(r.status==="user-reviewing"||r.status==="error")&&n.rejectChanges())}},useDismissProps:{enabled:r==="closed"||r.status==="user-input",outsidePress:a=>{if(a.target instanceof Element){const u=a.target.closest(".bn-block");u&&u.getAttribute("data-id")===s&&n.closeAIMenu()}return!0}},elementProps:{style:{zIndex:100}},...e.floatingUIOptions}),[n,r,s,e.floatingUIOptions]),o=e.aiMenu||$h;return q.jsx(me.BlockPopover,{blockId:s,...i,children:r!=="closed"&&q.jsx(o,{})})},yA=()=>{const e=Fh(),t=me.useComponentsContext(),n=me.useBlockNoteEditor(),r=me.useExtension(Ve),s=me.useExtension(Kk),i=()=>{const o=n.getSelection();if(!o)throw new Error("No selection");const a=o.blocks[o.blocks.length-1].id;r.openAIMenuAtBlock(a),s.store.setState(!1)};return n.isEditable?q.jsx(t.Generic.Toolbar.Button,{className:"bn-button",label:e.formatting_toolbar.ai.tooltip,mainTooltip:e.formatting_toolbar.ai.tooltip,icon:q.jsx(Wo,{}),onClick:i}):null},CA={AI:Wo};function kA(e){const t=e.getExtension(Ve);return t?[{key:"ai",onItemClick:()=>{const r=e.getTextCursorPosition();r.block.content&&Array.isArray(r.block.content)&&r.block.content.length===0&&r.prevBlock?t.openAIMenuAtBlock(r.prevBlock.id):t.openAIMenuAtBlock(r.block.id)},...zt(e).slash_menu.ai,icon:q.jsx(CA.AI,{})}]:[]}function jh(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Le.tool({...n,inputSchema:Le.jsonSchema(n.inputSchema),outputSchema:Le.jsonSchema(n.outputSchema)})]))}function qh(e,t){let n="";return e.pipeThrough(new TransformStream({start(r){r.enqueue({type:"start"}),r.enqueue({type:"start-step"}),r.enqueue({type:"tool-input-start",toolCallId:"call_object_1",toolName:t})},transform(r,s){switch(r.type){case"text-delta":n+=r.textDelta,s.enqueue({type:"tool-input-delta",toolCallId:"call_object_1",inputTextDelta:r.textDelta});break;case"object":case"finish":break;case"error":s.enqueue({type:"error",errorText:Vi.getErrorMessage(r.error)});break;default:{const i=r;throw new Error(`Unsupported chunk type: ${i}`)}}},async flush(r){r.enqueue({type:"tool-input-available",toolCallId:"call_object_1",toolName:t,input:JSON.parse(n)}),r.enqueue({type:"finish-step"}),r.enqueue({type:"finish"})}}))}function zh(e,t){return new ReadableStream({start(r){r.enqueue({type:"start"}),r.enqueue({type:"start-step"}),r.enqueue({type:"tool-input-start",toolCallId:"call_object_1",toolName:t}),r.enqueue({type:"tool-input-delta",toolCallId:"call_object_1",inputTextDelta:JSON.stringify(e)}),r.enqueue({type:"tool-input-available",toolCallId:"call_object_1",toolName:t,input:e}),r.enqueue({type:"finish-step"}),r.enqueue({type:"finish"}),r.close()}})}const Wh={"mistral.chat":{mode:"auto"},"google.generative-ai":{mode:"auto"},"groq.chat":{providerOptions:{groq:{structuredOutputs:!1}}}};function Fi(e){return Wh[e.provider]||{}}class SA{constructor(t){this.opts=t}async generateObject(t,n){const{model:r,_additionalOptions:s}=this.opts;if(typeof r=="string")throw new Error("model must be a LanguageModelV2");const i=Object.keys(n)[0],o=n[i].inputSchema,a=await Le.generateObject({output:"object",schema:o,model:r,mode:"tool",messages:Le.convertToModelMessages(t),...Fi(r),...s??{}});return zh(a.object,i)}async streamObject(t,n){const{model:r,_additionalOptions:s}=this.opts;if(typeof r=="string")throw new Error("model must be a LanguageModelV2");const i=Object.keys(n)[0],o=n[i].inputSchema,a=Le.streamObject({output:"object",schema:o,model:r,mode:"tool",messages:Le.convertToModelMessages(t),...Fi(r),...s??{}});return qh(a.fullStream,i)}async streamText(t,n){const{model:r,_additionalOptions:s}=this.opts;return Le.streamText({model:r,messages:Le.convertToModelMessages(t),tools:n,toolChoice:"required",...s??{}}).toUIMessageStream()}async sendMessages({messages:t,body:n}){const r=this.opts.stream??!0,s=n.toolDefinitions,i=jh(s);if(this.opts.objectGeneration)return r?this.streamObject(t,i):this.generateObject(t,i);if(r)return await this.streamText(t,i);throw new Error("Not implemented (generateText)")}reconnectToStream(){throw new Error("Not implemented")}}exports.AIExtension=Ve;exports.AIMenu=$h;exports.AIMenuController=TA;exports.AIToolbarButton=yA;exports.ChunkExecutionError=Fo;exports.ClientSideTransport=SA;exports.PROVIDER_OVERRIDES=Wh;exports.PromptSuggestionMenu=Vh;exports.StreamToolExecutor=Ah;exports.aiDocumentFormats=Qe;exports.buildAIRequest=Ih;exports.createStreamToolsArraySchema=kh;exports.defaultAIRequestSender=Sh;exports.executeAIRequest=xh;exports.fetchViaProxy=ZS;exports.getAIDictionary=zt;exports.getAISlashMenuItems=kA;exports.getDefaultAIMenuItems=Yh;exports.getProviderOverrides=Fi;exports.objectAsToolCallInUIMessageStream=zh;exports.objectStreamToOperationsResult=wh;exports.partialObjectStreamAsToolCallInUIMessageStream=qh;exports.promptHelpers=KS;exports.toolDefinitionsToToolSet=jh;
10
39
  //# sourceMappingURL=blocknote-xl-ai.cjs.map