@barocss/editor-view-react 0.1.0 → 0.1.1
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.
- package/CHANGELOG.md +17 -0
- package/dist/editor-view-react/src/EditorViewContentLayer.d.ts.map +1 -1
- package/dist/editor-view-react/src/EditorViewContext.d.ts +2 -0
- package/dist/editor-view-react/src/EditorViewContext.d.ts.map +1 -1
- package/dist/editor-view-react/src/input-handler.d.ts +16 -1
- package/dist/editor-view-react/src/input-handler.d.ts.map +1 -1
- package/dist/editor-view-react/src/selection-handler.d.ts +2 -0
- package/dist/editor-view-react/src/selection-handler.d.ts.map +1 -1
- package/dist/index.cjs +10 -4
- package/dist/index.js +5453 -1713
- package/docs/ime-composition-stability-checklist.md +40 -0
- package/docs/layers-spec.md +1 -1
- package/package.json +4 -4
- package/src/EditorViewContentLayer.tsx +90 -4
- package/src/EditorViewContext.tsx +3 -0
- package/src/input-handler.ts +215 -27
- package/src/selection-handler.ts +43 -9
- package/test/EditorView.test.tsx +287 -1
- package/test/input-handler-ims.test.ts +330 -0
- package/test/selection-handler.test.ts +202 -0
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
"use strict";var At=Object.defineProperty;var Dt=(c,t,e)=>t in c?At(c,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[t]=e;var S=(c,t,e)=>Dt(c,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("react/jsx-runtime"),T=require("react");function Rt(c){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(c){for(const e in c)if(e!=="default"){const r=Object.getOwnPropertyDescriptor(c,e);Object.defineProperty(t,e,r.get?r:{enumerable:!0,get:()=>c[e]})}}return t.default=c,Object.freeze(t)}const Q=Rt(T);class $t{constructor(t={}){S(this,"_renderers",new Map);S(this,"_components",new Map);S(this,"_options");this._options={global:!0,...t}}register(t){if(t.template&&typeof t.template=="object"&&"managesDOM"in t.template){this.registerComponent(t.nodeType,t.template);return}if(t.template&&typeof t.template=="object"&&"type"in t.template&&t.template.type==="component"){const e=t.template;if(e.component&&typeof e.component=="function"){this.registerContextComponent(t.nodeType,e.component),this._renderers.set(t.nodeType,t);return}}this._renderers.set(t.nodeType,t)}get(t){const e=this._renderers.get(t);if(e)return e;const r=this.getComponent(t);if(r)return{type:"renderer",nodeType:t,template:r}}getAll(){return Array.from(this._renderers.values())}remove(t){return this._renderers.delete(t)}has(t){return this._renderers.has(t)?!0:this._options.global?!1:V().has(t)}clear(){this._renderers.clear()}registerComponent(t,e){this._components.set(t,e)}getComponent(t){const e=this._components.get(t);if(e)return e;if(this._options.global===!1)return V().getComponent(t)}removeComponent(t){return this._components.delete(t)}hasComponent(t){return this._components.has(t)?!0:this._options.global===!1?V().hasComponent(t):!1}clearComponents(){this._components.clear()}getMarkRenderer(t){const e=this._renderers.get(`mark:${t}`);if(e&&e.template)return e.template;const r=this.getComponent(`mark:${t}`);if(r&&r.template)return r.template}registerContextComponent(t,e){const r={template:e,managesDOM:!1,mount:(n,o)=>o,update:()=>{},unmount:()=>{}};this._components.set(t,r)}}const Lt=new $t({global:!0});function V(){return Lt}function J(c,t,e){return Math.max(t,Math.min(e,c))}function lt(c,t){const e=(c==null?void 0:c.length)??0;if(!c||e===0)return[];const r=Array.isArray(t)?t:[],n=r.filter(d=>d&&!d.range),o=r.filter(d=>d&&d.range),s=new Set;s.add(0),s.add(e);for(const d of o){if(!(d!=null&&d.range))continue;const l=J(d.range[0]??0,0,e),u=J(d.range[1]??0,0,e);u<=l||(s.add(l),s.add(u))}const i=Array.from(s.values()).sort((d,l)=>d-l),a=[];for(let d=0;d<i.length-1;d++){const l=i[d],u=i[d+1];if(u<=l)continue;const f=c.slice(l,u),h=[];for(const g of n){const y=g.stype;y&&h.push(y)}for(const g of o){const y=J(g.range[0]??0,0,e),p=J(g.range[1]??0,0,e);if(!(p<=y)&&y<u&&p>l){const N=g.stype;N&&h.push(N)}}a.push({start:l,end:u,text:f,types:Array.from(new Set(h))})}return a}function Y(c){return c.target?"sid"in c.target?{start:c.target.startOffset,end:c.target.endOffset}:{start:c.target.startOffset,end:c.target.endOffset}:{}}function Bt(c,t){return!c||!(t!=null&&t.length)?[]:t.filter(e=>e!=null&&e.target?"sid"in e.target?e.target.sid===c:e.target.startSid===c||e.target.endSid===c:!1)}function Ft(c,t){return!c||!(t!=null&&t.length)?[]:t.filter(e=>e.category!=="inline"||!e.target?!1:"sid"in e.target?e.target.sid===c:e.target.startSid===c||e.target.endSid===c)}function Pt(c){const t={block:[],layer:[],inline:[]};for(const e of c){if(!(e!=null&&e.category))continue;const r=e.category;Array.isArray(t[r])&&t[r].push(e)}return t}function Ut(c,t){const e=c.length;if(e===0||t.length===0)return[{text:c,start:0,end:e}];const r=new Set([0,e]),n=new Map;for(const a of t){if(a.category!=="inline")continue;const d=Y(a);if(d.start===void 0||d.end===void 0)continue;const l=Math.max(0,Math.min(d.start,e)),u=Math.max(l,Math.min(d.end,e));u<=l||(r.add(l),r.add(u),n.has(l)||n.set(l,[]),n.get(l).push(a))}const o=Array.from(r).sort((a,d)=>a-d),s=[],i=Array.from(n.keys()).sort((a,d)=>a-d);for(let a=0;a<o.length-1;a++){const d=o[a],l=o[a+1];if(l<=d)continue;const u=c.slice(d,l),f=[];for(const y of i){if(y>d)break;const p=n.get(y)??[];for(const N of p){const I=Y(N);I.start===void 0||I.end===void 0||I.start<=d&&I.end>=l&&f.push(N)}}if(f.length===0){const y=t.find(p=>{if(p.category!=="inline")return!1;const N=Y(p);return N.start!==void 0&&N.end!==void 0&&N.start<=d&&N.end>=l});y&&f.push(y)}const h=f[0],g=f.length>1?f:void 0;s.push({text:u,decorator:h,decorators:g,start:d,end:l})}return s}function jt(c,t){return c.map(e=>{const r=Y(e);if(r.start==null||r.end==null)return e;if(r.end<=t.start||r.start>=t.end)return null;const n=Math.max(0,r.start-t.start),o=Math.min(t.text.length,r.end-t.start);return{...e,target:{...e.target,startOffset:n,endOffset:o}}}).filter(e=>e!==null)}const{createElement:j,cloneElement:Wt}=Q;function nt(c,t){return t.split(".").reduce((e,r)=>e==null?void 0:e[r],c)}function G(c){return!!c&&typeof c=="object"&&c.type==="element"}function qt(c){return!!c&&typeof c=="object"&&c.type==="data"}function mt(c){return!!c&&typeof c=="object"&&c.type==="component"}function zt(c){return!!c&&typeof c=="object"&&c.__attrData===!0}function St(c,t){return typeof c=="function"?c(t):c}function It(c,t){if(typeof c=="function")return c(t);if(zt(c)){const e=nt(t,c.path);return e??c.defaultValue}if(qt(c)){const e=c.getter?c.getter(t):c.path?nt(t,c.path):void 0;return e??c.defaultValue}return c}function Vt(c,t){const e={};for(const[r,n]of Object.entries(c)){const o=It(n,t);o!=null&&(e[r]=o)}return e}function wt(c,t){if(!c)return{};const e={};for(const[r,n]of Object.entries(c)){const o=It(n,t);o!=null&&(r==="className"||r==="class"?e.className=typeof o=="object"&&o!==null&&!Array.isArray(o)?Object.entries(o).filter(([,s])=>s).map(([s])=>s).join(" "):Array.isArray(o)?o.filter(Boolean).join(" "):String(o):r==="style"&&typeof o=="object"&&o!==null&&!Array.isArray(o)?e.style=Vt(o,t):e[r]=o)}return e}function ot(c,t){const e=[];for(const r of c)if(Array.isArray(r))e.push(...ot(r,t));else if(typeof r=="function"){const n=r(t);Array.isArray(n)?e.push(...ot(n,t)):e.push(n)}else e.push(r);return e}function vt(c,t,e,r){var a;const n=(a=c.get)==null?void 0:a.call(c,t);if(!n||!n.template)throw new Error(`[renderer-react] No renderer for node type '${t}'. Register with define().`);const o=n.template;if((o==null?void 0:o.managesDOM)===!0)return j("div",{key:e.sid,"data-bc-sid":e.sid,"data-bc-stype":t,className:"react-renderer-external-placeholder"},"Component");const s={...r,sid:e.sid};let i=o;if(typeof i=="function"){const d=s.contextStub??Z(c);i=i({},e,d)}if(G(i))return tt(c,i,e,s);if(mt(i)&&typeof i.component=="function"){const d=s.contextStub??Z(c),l=i.component({},e,d);if(G(l))return tt(c,l,e,s)}return null}function Z(c){return{registry:{get:()=>{},getComponent:t=>{var e;return(e=c.getComponent)==null?void 0:e.call(c,t)},register:()=>{},setState:()=>!1,getState:()=>({}),toggleState:()=>!1},getState:()=>{},setState:()=>{},toggleState:()=>{},initState:()=>{}}}function tt(c,t,e,r){const n=St(t.tag,e),o=wt(t.attributes,e),s=Kt(c,t.children??[],e,r),i={...o,key:e.sid,"data-bc-sid":e.sid,"data-bc-stype":e.stype};return j(n,i,...s)}function K(c,t){var l,u;const e=(l=c.get)==null?void 0:l.call(c,t.stype),r=(u=c.getComponent)==null?void 0:u.call(c,t.stype),n=(e==null?void 0:e.template)??r;if(!n)return j("div",{key:t.sid,"data-decorator-sid":t.sid,"data-decorator-stype":t.stype,"data-decorator-category":t.category,"data-decorator-missing-renderer":t.stype});const o=t.data??{};let s=n;if(typeof s=="function"){const f=Z(c);s=s({},o,f)}if(!G(s))return j("div",{key:t.sid,"data-decorator-sid":t.sid,"data-decorator-stype":t.stype,"data-decorator-category":t.category});const i=tt(c,s,o,{decorators:[]}),a=t.position??(t.category!=="inline"?"after":void 0),d={key:t.sid,"data-decorator-sid":t.sid,"data-decorator-stype":t.stype,"data-decorator-category":t.category};return a&&(d["data-decorator-position"]=a),Q.isValidElement(i)&&typeof i=="object"&&i.props?Wt(i,d):j("span",d,i)}function Ht(c,t,e){if(t&&G(t))return t;if(t&&mt(t)){const r=t.component;if(typeof r=="function"){const n=Z(c),o=r({},e,n);if(o&&G(o))return o}}return null}function ut(c,t,e,r){var i;const n={text:t.text,run:t,model:e};let o=t.text;const s=t.types??[];for(let a=s.length-1;a>=0;a--){const d=s[a],l=(i=c.getMarkRenderer)==null?void 0:i.call(c,d),u=l?Ht(c,l,n):null;if(!u)continue;const f=`${r}_${d}_${a}`,h=St(u.tag,n),g=wt(u.attributes,n);o=j(h,{...g,key:f},o)}return o}function Kt(c,t,e,r){var a;const n=ot(t,e),o=[],s=(r==null?void 0:r.decorators)??[],i=(r==null?void 0:r.sid)??e.sid;for(const d of n){if(typeof d=="string"||typeof d=="number"){o.push(d);continue}if(!d||typeof d!="object")continue;const l=d.type;if(l==="slot"){const u=e.content;if(Array.isArray(u))for(const f of u){const h=f.stype,g=f.sid;if(h){const y=vt(c,h,f,{...r,decorators:s});if(g&&s.length>0){const p=Bt(g,s),N=Pt(p),I=[...N.block,...N.layer];if(I.length>0){const m=[],_=[];for(const v of I){const w=K(c,v);(v.position??"after")==="before"?m.push(w):_.push(w)}o.push(...m,y,..._)}else o.push(y)}else o.push(y)}}continue}if(l==="data"){const u=d,f=u.getter?u.getter(e):u.path?nt(e,u.path):void 0,h=f??u.defaultValue,g=h!=null?String(h):"",y=e.marks,p=u.path==="text"||u.path==null&&typeof h=="string",N=i?Ft(i,s):[];if(p&&(Array.isArray(y)&&y.length>0||N.length>0)){const I=Array.isArray(y)&&y.length>0?lt(g,y):[{start:0,end:g.length,text:g,types:[]}],m=e.sid??"";for(let _=0;_<I.length;_++){const v=I[_],w=jt(N,{start:v.start,end:v.end,text:v.text}),E=Ut(v.text,w);for(const A of E){if(!A.text)continue;const F=(a=v.types)!=null&&a.length?ut(c,{...v,text:A.text,start:A.start,end:A.end},e,`${m}_r${_}`):A.text,x=A.decorators??(A.decorator?[A.decorator]:[]);if(x.length===0){o.push(F);continue}const M=x.filter(k=>k.category==="inline"&&k.position==="before"),O=x.filter(k=>k.category==="inline"&&k.position==="after"),C=x.filter(k=>!(k.category==="inline"&&(k.position==="before"||k.position==="after")));for(const k of M)o.push(K(c,k));let D=F;for(const k of C){const R=K(c,k);D=Q.isValidElement(R)?Q.cloneElement(R,{},D):j("span",{key:k.sid,"data-decorator-sid":k.sid},D)}o.push(D);for(const k of O)o.push(K(c,k))}}}else if(Array.isArray(y)&&y.length>0&&p){const I=lt(g,y),m=e.sid??"";for(let _=0;_<I.length;_++){const v=I[_];!v.types||v.types.length===0?o.push(v.text):o.push(ut(c,v,e,`${m}_r${_}`))}}else o.push(g);continue}if(l==="element"){o.push(tt(c,d,e,r));continue}}return o}function Qt(c,t){return t!=null&&t.length?j(Q.Fragment,null,...t.map(e=>K(c,e))):null}class xt{constructor(t,e){S(this,"registry");if(this.registry=t??V(),!this.registry)throw new Error("[ReactRenderer] Registry is required. Pass a RendererRegistry or ensure getGlobalRegistry() is available.")}getRegistry(){return this.registry}build(t,e=[]){if(!t||!t.stype)throw new Error("[ReactRenderer] build: model must have stype property");return vt(this.registry,t.stype,t,{decorators:e})}buildOverlayDecorators(t){return Qt(this.registry,t??[])}}const _t=(()=>{if(typeof navigator>"u")return!1;const c=navigator.platform.toUpperCase(),t=navigator.userAgent.toUpperCase();return c.indexOf("MAC")>=0||t.indexOf("MAC")>=0})(),Gt=typeof navigator>"u"?!1:navigator.platform.toUpperCase().indexOf("LINUX")>=0,Jt=(()=>{if(typeof navigator>"u")return!1;const c=navigator.platform.toUpperCase(),t=navigator.userAgent.toUpperCase();return c.indexOf("WIN")>=0||t.indexOf("WIN")>=0})();function Xt(c){const t={" ":"Space",ArrowUp:"Up",ArrowDown:"Down",ArrowLeft:"Left",ArrowRight:"Right"};return t[c]?t[c]:c.length===1&&/[A-Za-z]/.test(c)?c.toLowerCase():c}function Yt(c){const t=[];_t?(c.metaKey&&t.push("Cmd"),c.ctrlKey&&t.push("Ctrl")):(c.ctrlKey&&t.push("Ctrl"),c.metaKey&&t.push("Meta")),c.altKey&&t.push("Alt"),c.shiftKey&&t.push("Shift");let e=c.key;if(!e||e==="Unidentified")if(c.code)e=Zt(c.code);else return"";const r=Xt(e);return t.push(r),t.join("+")}function Zt(c){return c.startsWith("Key")?c.substring(3).toLowerCase():c.startsWith("Digit")?c.substring(5):c.startsWith("Numpad")?c.substring(6):c}function te(c){const t=c.split("+"),e=[];for(let r=0;r<t.length;r++){const n=t[r].trim();if(!n)continue;const o={ctrl:"Ctrl",cmd:"Cmd",alt:"Alt",shift:"Shift",meta:"Meta",mod:"Mod"},s=n.toLowerCase();o[s]?e.push(o[s]):n.length===1&&/[A-Za-z]/.test(n)?e.push(n.toLowerCase()):e.push(n)}return e.join("+")}function ee(c){const t=[c];if(c.startsWith("Mod+")){const e=c.substring(4);t.push(`Ctrl+${e}`),t.push(`Cmd+${e}`)}else if(c.startsWith("Ctrl+")){const e=c.substring(5);t.push(`Mod+${e}`)}else if(c.startsWith("Cmd+")){const e=c.substring(4);t.push(`Mod+${e}`)}return t}let bt=class{constructor(){this.listeners=new Map}on(t,e){this.listeners.has(t)||this.listeners.set(t,[]),this.listeners.get(t).push(e)}off(t,e){const r=this.listeners.get(t);if(r){const n=r.indexOf(e);n!==-1&&r.splice(n,1)}}emit(t,...e){const r=this.listeners.get(t);r&&r.forEach(n=>{try{n(...e)}catch(o){console.error(`Error in event listener for ${String(t)}:`,o)}})}removeAllListeners(){this.listeners.clear()}};class re extends bt{constructor(t){super(),this.decorators=new Map,this.validator=t}add(t){if(this.validator){const e=this.validator.validateDecorator(t);if(!e.valid)throw new Error(`Invalid decorator: ${e.errors.join(", ")}`);const r=this.validator.applyDefaults(t);if(this.decorators.has(r.sid))throw new Error(`Decorator with id '${r.sid}' already exists`);this.decorators.set(r.sid,r),this.emit("decorator:added",r)}else{if(this.decorators.has(t.sid))throw new Error(`Decorator with id '${t.sid}' already exists`);this.decorators.set(t.sid,t),this.emit("decorator:added",t)}}update(t,e,r={}){const n=this.decorators.get(t);if(!n)throw new Error(`Decorator with id '${t}' not found`);const o=r.partial!==!1?{...n,...e}:{...e};if(o.sid=n.sid,this.validator){const s=this.validator.validateDecorator(o);if(!s.valid)throw new Error(`Invalid decorator update: ${s.errors.join(", ")}`);const i=this.validator.applyDefaults(o);this.decorators.set(t,i),this.emit("decorator:updated",i)}else this.decorators.set(t,o),this.emit("decorator:updated",o)}remove(t){if(!this.decorators.get(t))throw new Error(`Decorator with id '${t}' not found`);this.decorators.delete(t),this.emit("decorator:removed",t)}setEnabled(t,e){return this.decorators.get(t)?(this.update(t,{enabled:e},{partial:!0}),!0):!1}isEnabled(t){const e=this.decorators.get(t);return(e==null?void 0:e.enabled)!==!1}get(t){return this.decorators.get(t)}getAll(t={}){let e=Array.from(this.decorators.values());if(t.enabledOnly!==!1&&(e=e.filter(r=>r.enabled!==!1)),t.type&&(e=e.filter(r=>r.stype===t.type)),t.category&&(e=e.filter(r=>r.category===t.category)),t.nodeId&&(e=e.filter(r=>r.target&&"sid"in r.target?r.target.sid===t.nodeId:!1)),t.sortBy){const r=t.sortOrder??"asc";e.sort((n,o)=>{let s,i;switch(t.sortBy){case"id":s=n.sid,i=o.sid;break;case"type":s=n.stype,i=o.stype;break;case"category":s=n.category,i=o.category;break;default:return 0}return s<i?r==="asc"?-1:1:s>i?r==="asc"?1:-1:0})}return e}getByType(t){return this.getAll({type:t})}getByCategory(t){return this.getAll({category:t})}getByNode(t){return this.getAll({nodeId:t})}getLayerDecorators(){return this.getByCategory("layer")}getInlineDecorators(){return this.getByCategory("inline")}getBlockDecorators(){return this.getByCategory("block")}has(t){return this.decorators.has(t)}size(){return this.decorators.size}clear(){const t=Array.from(this.decorators.keys());this.decorators.clear(),t.forEach(e=>this.emit("decorator:removed",e))}clearByNode(t){this.getByNode(t).forEach(e=>this.remove(e.sid))}clearByType(t){this.getByType(t).forEach(e=>this.remove(e.sid))}clearByCategory(t){this.getByCategory(t).forEach(e=>this.remove(e.sid))}updateData(t,e){const r=this.decorators.get(t);if(!r)throw new Error(`Decorator with id '${t}' not found`);this.update(t,{data:{...r.data,...e}})}addMany(t){t.forEach(e=>this.add(e))}removeMany(t){t.forEach(e=>this.remove(e))}}class ne extends bt{constructor(){super(...arguments),this.remoteDecorators=new Map,this.ownerMap=new Map}setRemoteDecorator(t,e){const r=t.sid;this.remoteDecorators.set(r,{...t,data:{...t.data||{},_remoteOwner:{userId:e.userId,agentId:e.agentId,sessionId:e.sessionId}}}),this.ownerMap.set(r,e),this.emit("change")}removeRemoteDecorator(t){this.remoteDecorators.delete(t),this.ownerMap.delete(t),this.emit("change")}removeByOwner(t){const e=[];for(const[r,n]of this.ownerMap.entries())(n==null?void 0:n.userId)===t&&e.push(r);e.length>0&&(e.forEach(r=>{this.remoteDecorators.delete(r),this.ownerMap.delete(r)}),this.emit("change"))}removeByAgent(t){const e=[];for(const[r,n]of this.ownerMap.entries())(n==null?void 0:n.agentId)===t&&e.push(r);e.length>0&&(e.forEach(r=>{this.remoteDecorators.delete(r),this.ownerMap.delete(r)}),this.emit("change"))}removeBySession(t){const e=[];for(const[r,n]of this.ownerMap.entries())(n==null?void 0:n.sessionId)===t&&e.push(r);e.length>0&&(e.forEach(r=>{this.remoteDecorators.delete(r),this.ownerMap.delete(r)}),this.emit("change"))}getAll(){return Array.from(this.remoteDecorators.values())}getByOwner(t){return this.getAll().filter(e=>{var r;return((r=this.ownerMap.get(e.sid))==null?void 0:r.userId)===t})}getByAgent(t){return this.getAll().filter(e=>{var r;return((r=this.ownerMap.get(e.sid))==null?void 0:r.agentId)===t})}getOwner(t){return this.ownerMap.get(t)}get(t){return this.remoteDecorators.get(t)}has(t){return this.remoteDecorators.has(t)}size(){return this.remoteDecorators.size}clear(){(this.remoteDecorators.size>0||this.ownerMap.size>0)&&(this.remoteDecorators.clear(),this.ownerMap.clear(),this.emit("change"))}}class oe{constructor(){this.configs=[]}setConfigs(t){this.configs=[...t]}addConfig(t){const e=this.configs.findIndex(r=>r.sid===t.sid);e>=0?this.configs[e]=t:this.configs.push(t)}removeConfig(t){const e=this.configs.findIndex(r=>r.sid===t);return e>=0?(this.configs.splice(e,1),!0):!1}getConfigs(t=!1){const e=[...this.configs];return t?e.filter(r=>r.enabled!==!1):e}setConfigEnabled(t,e){const r=this.configs.find(n=>n.sid===t);return r?(r.enabled=e,!0):!1}isConfigEnabled(t){const e=this.configs.find(r=>r.sid===t);return(e==null?void 0:e.enabled)!==!1}clear(){this.configs=[]}}function se(c,t,e){if(!t||!c||e.length===0)return[];const r=[...e].sort((o,s)=>(o.priority??100)-(s.priority??100)),n=[];for(const o of r){if(o.enabled===!1)continue;let s;typeof o.pattern=="function"?s=o.pattern(t):s=Array.from(t.matchAll(o.pattern)).map(a=>({match:a[0],index:a.index??-1,groups:a.groups,...Object.fromEntries(Array.from({length:a.length},(d,l)=>[l,a[l]]))}));for(const i of s){if(i.index===void 0||i.index<0)continue;const a=i.index,d=a+i.match.length,l={0:i.match,index:i.index,input:t,groups:i.groups,length:1,...Object.fromEntries(Object.entries(i).filter(([g])=>!isNaN(Number(g))))},u=o.extractData(l),f=o.createDecorator(c,a,d,u),h=Array.isArray(f)?f:[f];for(const g of h)n.push({sid:g.sid,stype:o.stype,category:g.category??o.category,layerTarget:g.layerTarget,target:g.target,data:g.data??{}})}}return n}function ie(c,t){if(!c||t.length===0)return[];const e=[];function r(n){const o=n.sid??n.id,s=typeof n.text=="string"?n.text:void 0;o&&s&&e.push(...se(o,s,t));const i=n.content??n.children;if(Array.isArray(i))for(const a of i)a&&typeof a=="object"&&r(a)}return r(c),e}class ae{constructor(){this.generators=new Map,this.changeCallbacks=new Map}registerGenerator(t,e){if(this.generators.set(t.sid,t),t.onDidChange&&e){const r=t.onDidChange(e);this.changeCallbacks.set(t.sid,r)}}unregisterGenerator(t){const e=this.changeCallbacks.get(t);return e&&(e(),this.changeCallbacks.delete(t)),this.generators.delete(t)}getGenerator(t){return this.generators.get(t)}getAllGenerators(t=!1){const e=Array.from(this.generators.values());return t?e.filter(r=>r.enabled!==!1):e}setGeneratorEnabled(t,e){const r=this.generators.get(t);return r?(r.enabled=e,!0):!1}isGeneratorEnabled(t){var e;return((e=this.generators.get(t))==null?void 0:e.enabled)!==!1}clear(){for(const t of this.changeCallbacks.values())t();this.changeCallbacks.clear(),this.generators.clear()}generateDecorators(t,e,r){const n=this.getAllGenerators(!0).sort((s,i)=>(s.priority??100)-(i.priority??100)),o=[];for(const s of n)try{o.push(...s.generate(t,e,r))}catch(i){console.error(`[DecoratorGeneratorManager] Error in generator '${s.sid}':`,i)}return o}}class de{constructor(){this.typeSchemas=new Map}registerLayerType(t,e){this.typeSchemas.set(`layer:${t}`,{...e,description:e.description??`Layer decorator: ${t}`})}registerInlineType(t,e){this.typeSchemas.set(`inline:${t}`,{...e,description:e.description??`Inline decorator: ${t}`})}registerBlockType(t,e){this.typeSchemas.set(`block:${t}`,{...e,description:e.description??`Block decorator: ${t}`})}getTypeSchema(t,e){return this.typeSchemas.get(`${t}:${e}`)}validateDecorator(t){const e=[];t.sid||e.push("Decorator id is required"),t.category||e.push("Decorator category is required"),t.stype||e.push("Decorator type is required");const r=this.getTypeSchema(t.category,t.stype);if(r!=null&&r.dataSchema){const n=this.validateData(t.data??{},r.dataSchema);e.push(...n)}return{valid:e.length===0,errors:e}}validateData(t,e){const r=[];for(const[n,o]of Object.entries(e)){if(o.required&&!(n in t)){r.push(`Required field '${n}' is missing`);continue}const s=t[n];if(s!=null){const i=Array.isArray(s)?"array":typeof s;i!==o.type&&r.push(`Field '${n}' should be ${o.type}, got ${i}`)}}return r}applyDefaults(t){const e=this.getTypeSchema(t.category,t.stype);if(!(e!=null&&e.dataSchema))return t;const r={...t.data??{}};for(const[n,o]of Object.entries(e.dataSchema))if(o.default!==void 0&&!(n in r)){const s=typeof o.default=="function"?o.default():o.default;r[n]=s}return{...t,data:r}}}const ce=new WeakMap,le=new Map;function ft(c){return!!(c.hasAttribute("data-decorator-sid")||c.hasAttribute("data-bc-decorator")||c.hasAttribute("data-decorator-category"))}function st(c,t,e){const r=[];let n=0;const o=e!=null&&e.buildReverseMap?new Map:void 0,s=Array.from(c.childNodes);for(const a of s){if(a.nodeType===Node.TEXT_NODE){const d=a,l=d.textContent??"",u=(e==null?void 0:e.normalizeWhitespace)!==!1?l.trim():l;if(u.length>0){const f=u.length,h=n,g=h+f,y={domTextNode:d,start:h,end:g};r.push(y),o&&o.set(d,{start:h,end:g}),n=g}continue}if(a.nodeType===Node.ELEMENT_NODE){const d=a;if(ft(d)||e!=null&&e.excludePredicate&&e.excludePredicate(d))continue;const l=document.createTreeWalker(d,NodeFilter.SHOW_TEXT,{acceptNode:f=>{let h=f.parentNode;for(;h&&h!==d;){if(h.nodeType===Node.ELEMENT_NODE&&ft(h))return NodeFilter.FILTER_REJECT;h=h.parentNode}return NodeFilter.FILTER_ACCEPT}});let u;for(;u=l.nextNode();){const f=u.textContent??"",h=(e==null?void 0:e.normalizeWhitespace)!==!1?f.trim():f;if(h.length>0){const g=h.length,y=n,p=y+g,N={domTextNode:u,start:y,end:p};r.push(N),o&&o.set(u,{start:y,end:p}),n=p}}}}const i={runs:r,total:n,byNode:o};return ce.set(c,i),t&&le.set(t,i),i}function ht(c,t){let e=0,r=c.length-1,n=-1;for(;e<=r;){const o=e+r>>1,s=c[o];if(t<s.start)r=o-1;else if(t>=s.end)e=o+1;else{n=o;break}}return n}function ue(c,t,e,r,n="range"){if(c===e){const o=t<=r,s=Math.min(t,r),i=Math.max(t,r);return{type:n,startNodeId:c,startOffset:s,endNodeId:e,endOffset:i,collapsed:s===i,direction:s===i?"none":o?"forward":"backward"}}return{type:n,startNodeId:c,startOffset:t,endNodeId:e,endOffset:r,collapsed:!1,direction:"forward"}}class fe{constructor(){S(this,"operations",new Map)}register(t,e){this.operations.set(t,e)}get(t){return this.operations.get(t)}getAll(){return new Map(this.operations)}clear(){this.operations.clear()}}const kt=new fe;function b(c,t,e){kt.register(c,{name:c,execute:t,mapSelection:e})}class he{constructor(t){S(this,"_dataStore");S(this,"_currentTransaction",null);S(this,"_schema");S(this,"_editor");S(this,"_isUndoRedoOperation",!1);this._editor=t,this._dataStore=t.dataStore,this._schema=t.dataStore.getActiveSchema()}setSchema(t){this._schema=t}async execute(t,e){var n,o,s,i,a,d,l;let r=null;try{r=await this._dataStore.acquireLock("transaction-execution"),this._beginTransaction("DSL Transaction"),this._dataStore.begin();const u=pe(this._dataStore,this._editor.selectionManager.clone(),this._schema),f=u.selection.before,h=[],g=[];let y=null;for(const _ of t){const v=await this._executeOperation(_,u);if(Array.isArray(v)){for(const w of v){if(w.result&&w.result.ok===!1)return this._dataStore.end(),{success:!1,errors:[w.result.error||"Operation failed"],operations:h,selectionBefore:f,selectionAfter:u.selection.current};(n=w.result)!=null&&n.selectionAfter&&(y=w.result.selectionAfter)}h.push(...v),v.forEach(w=>{var E;(E=w.result)!=null&&E.inverse&&g.push(w.result.inverse)})}else if(v){const w=v;if(w.result&&w.result.ok===!1)return this._dataStore.end(),{success:!1,errors:[w.result.error||"Operation failed"],operations:h,selectionBefore:f,selectionAfter:u.selection.current};(o=w.result)!=null&&o.selectionAfter&&(y=w.result.selectionAfter),h.push(w),(s=w.result)!=null&&s.inverse&&g.push(w.result.inverse)}}if(u.selection.current){if(y){const _=this._dataStore.resolveAlias(y.nodeId);u.selection.setCaret(_,y.offset)}else if(u.lastCreatedBlock){const _=u.lastCreatedBlock.firstTextNodeId??u.lastCreatedBlock.blockId;u.selection.setCaret(_,0)}}this._dataStore.end(),this._dataStore.commit();const p=u.selection.current;h.length>0&&this._shouldAddToHistory(h)&&this._editor.historyManager.push({operations:h,inverseOperations:g.reverse(),description:(i=this._currentTransaction)==null?void 0:i.description});const N={success:!0,errors:[],transactionId:this._currentTransaction.sid,operations:h,selectionBefore:f,selectionAfter:p};this._editor.emit("editor:content.change",{content:this._editor.document,transaction:N});const I=((d=(a=this._editor).getSortedExtensions)==null?void 0:d.call(a))||[];if(I.length>0){const _={sid:this._currentTransaction.sid,operations:h,timestamp:this._currentTransaction.timestamp,description:this._currentTransaction.description};I.forEach(v=>{var w;(w=v.onTransaction)==null||w.call(v,this._editor,_)})}const m=(e==null?void 0:e.applySelectionToView)!==!1;return p&&m&&this._editor.updateSelection(p),this._currentTransaction=null,N}catch(u){try{this._dataStore.rollback()}catch{}const f=(l=this._currentTransaction)==null?void 0:l.sid,h=this._editor.selectionManager.getCurrentSelection();return this._currentTransaction=null,{success:!1,errors:[u instanceof Error?u.message:"Unknown error"],transactionId:f,operations:[],selectionBefore:h,selectionAfter:h}}finally{r&&this._dataStore.releaseLock(r)}}_beginTransaction(t){if(this._currentTransaction)throw new Error("Transaction already in progress");const e=`tx-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return this._currentTransaction={sid:e,operations:[],timestamp:new Date,description:t},e}async _executeOpFunction(t,e){const r=await t.execute(e);if(r&&typeof r=="object"&&"success"in r){const n=r;if(!n.success)throw new Error(n.error||"OpFunction failed");return[]}return[]}async _executeOperation(t,e){if(t&&typeof t=="object"&&"type"in t&&t.type==="op-function")return await this._executeOpFunction(t,e);const r=kt.get(t.type);if(!r)throw new Error(`Unknown operation type: ${t.type}`);const n=JSON.parse(JSON.stringify(t)),o=await r.execute(n,e);return{...n,result:o}}_shouldAddToHistory(t){return!(t.length===0||this._isUndoRedoOperation)}}class ge{constructor(t){S(this,"before");S(this,"current");this.before=t,this.current=t?{...t}:null}setSelection(t){this.current?Object.assign(this.current,t):this.current={...t}}setCaret(t,e){this.current?(this.current.type="range",this.current.startNodeId=t,this.current.startOffset=e,this.current.endNodeId=t,this.current.endOffset=e,this.current.collapsed=!0,this.current.direction="none"):this.current={type:"range",startNodeId:t,startOffset:e,endNodeId:t,endOffset:e,collapsed:!0,direction:"none"}}setRange(t,e,r,n){this.current?(this.current.type="range",this.current.startNodeId=t,this.current.startOffset=e,this.current.endNodeId=r,this.current.endOffset=n,this.current.collapsed=t===r&&e===n,this.current.direction="forward"):this.current={type:"range",startNodeId:t,startOffset:e,endNodeId:r,endOffset:n,collapsed:t===r&&e===n,direction:"forward"}}clear(){this.current=null}}function pe(c,t,e){c.registerSchema(e);const r=t.getCurrentSelection(),n=new ge(r);return{dataStore:c,selectionManager:t,selection:n,schema:e,lastCreatedBlock:void 0}}b("setNode",async(c,t)=>{const{node:e,validate:r=!0}=c;if(!e.sid)throw new Error("Node must have an id");return t.dataStore.setNode(e,r),t.dataStore.getNode(e.sid)});b("moveNode",async(c,t)=>{var l;const e=c.payload,{nodeId:r,newParentId:n,position:o}=e,s=t.dataStore.getNode(r);if(!s)throw new Error(`Node not found: ${r}`);if(!t.dataStore.getNode(n))throw new Error(`Parent not found: ${n}`);const a=s.parentId,d=Array.isArray((l=t.dataStore.getNode(a))==null?void 0:l.content)?t.dataStore.getNode(a).content.indexOf(r):void 0;return t.dataStore.content.moveNode(r,n,o),{ok:!0,data:t.dataStore.getNode(r),inverse:{type:"moveNode",payload:{nodeId:r,newParentId:a,position:d}}}});b("reorderChildren",async(c,t)=>{const{parentId:e,childIds:r}=c.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Parent not found: ${e}`);const o=Array.isArray(n.content)?[...n.content]:[];return t.dataStore.content.reorderChildren(e,r),{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"reorderChildren",payload:{parentId:e,childIds:o}}}});b("addChild",async(c,t)=>{const{parentId:e,nodeId:r,child:n,position:o}=c.payload,s=e||r;if(!t.dataStore.getNode(s))throw new Error(`Parent not found: ${s}`);const a=t.dataStore.content.addChild(s,n,o),d=t.dataStore.getNode(a),l=d&&Array.isArray(d.content)&&d.content[0]?d.content[0]:null;return t.lastCreatedBlock={blockId:a,firstTextNodeId:l},{ok:!0,data:d,inverse:{type:"removeChild",payload:{parentId:s,childId:a}},selectionAfter:{nodeId:l??a,offset:0}}});function ye(c,t,e){if(!e||e.type!=="range")return null;const r=c.getNode(e.startNodeId);if(!r)return null;if(typeof r.text=="string"){const d=r.text,l=typeof e.startOffset=="number"&&e.startOffset>=0?Math.min(e.startOffset,d.length):0,u=c.getParent(e.startNodeId);return!u||!Array.isArray(u.content)?null:{textNodeId:e.startNodeId,offset:l,textLength:d.length,parentBlock:u}}const n=t==null?void 0:t.getNodeType(r.stype);if((n==null?void 0:n.group)!=="block")return null;const o=r,s=Ne(c,o.sid);if(!s)return null;const i=typeof s.text=="string"?s.text.length:0,a=c.getParent(o.sid);return!a||!Array.isArray(a.content)?null:{textNodeId:s.sid,offset:i,textLength:i,parentBlock:o}}function Ne(c,t){const e=c.getNode(t);if(!e||!Array.isArray(e.content))return null;const r=e.content;let n=null;const o=s=>{const i=c.getNode(s);if(!i)return;if(typeof i.text=="string"){n={sid:i.sid,text:i.text};return}const a=i.content;if(Array.isArray(a))for(const d of a)o(d)};for(const s of r)o(s);return n}b("insertParagraph",async(c,t)=>{const{blockType:e="same",selectionAlias:r="insertedBlock"}=c.payload,n=t.dataStore,o=t.schema,s=t.selection.current,i=ye(n,o,s);if(!i)throw new Error("insertParagraph: no selection or selection does not resolve to a block text position");const{textNodeId:a,offset:d,textLength:l,parentBlock:u}=i,f=Math.max(0,Math.min(d,l));if(u.content.length===1&&u.content[0]===a&&f>0&&f<l){n.splitTextNode(a,f);const w=n.splitBlockNode(u.sid,1),E=n.getNode(w),A=E&&Array.isArray(E.content)&&E.content[0]?E.content[0]:null;if(t.lastCreatedBlock={blockId:w,firstTextNodeId:A},!A)throw new Error("insertParagraph: splitBlockNode did not yield a text node");return{ok:!0,data:E,inverse:{type:"mergeBlockNodes",payload:{leftNodeId:u.sid,rightNodeId:w}},selectionAfter:{nodeId:A,offset:0}}}const g=u.parentId?n.getNode(n.resolveAlias(u.parentId)):null;if(!g||!Array.isArray(g.content))throw new Error("insertParagraph: parent block has no parent");const y=g.content.indexOf(u.sid);if(y===-1)throw new Error("insertParagraph: block not in parent content");const p=f===l?y+1:y,I={stype:e==="paragraph"?"paragraph":u.stype,attributes:{...u.attributes||{},$alias:r},content:[]},m=n.content.addChild(g.sid,I,p),_=n.content.addChild(m,{stype:"inline-text",text:""},0);return t.lastCreatedBlock={blockId:m,firstTextNodeId:_},{ok:!0,data:n.getNode(m),inverse:{type:"removeChild",payload:{parentId:g.sid,childId:m}},selectionAfter:{nodeId:_,offset:0}}});b("removeChild",async(c,t)=>{const e=c.payload.parentId||c.payload.nodeId,r=c.payload.childId;if(!t.dataStore.getNode(e))throw new Error(`Parent not found: ${e}`);const o=t.dataStore.getNode(r);if(!o)throw new Error(`Child not found: ${r}`);if(!t.dataStore.content.removeChild(e,r))throw new Error(`Failed to remove child ${r}`);return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"addChild",payload:{parentId:e,child:o}}}});b("moveChildren",async(c,t)=>{var d;const{fromParentId:e,toParentId:r,childIds:n,position:o}=c.payload,s=t.dataStore.getNode(e),i=t.dataStore.getNode(r);if(!s)throw new Error(`Parent not found: ${e}`);if(!i)throw new Error(`Parent not found: ${r}`);const a=(n||[]).map(l=>{var g;const u=(g=t.dataStore.getNode(l))==null?void 0:g.parentId,f=u?t.dataStore.getNode(u):void 0,h=Array.isArray(f==null?void 0:f.content)?f.content.indexOf(l):void 0;return{childId:l,prevParentId:u,prevPosition:h}});return t.dataStore.content.moveChildren(e,r,n,o),{ok:!0,data:{fromParent:t.dataStore.getNode(e),toParent:t.dataStore.getNode(r)},inverse:{type:"moveChildren",payload:{fromParentId:r,toParentId:e,childIds:n,position:(d=a[0])==null?void 0:d.prevPosition}}}});b("removeChildren",async(c,t)=>{const{parentId:e,childIds:r}=c.payload;if(!t.dataStore.getNode(e))throw new Error(`Parent not found: ${e}`);const o=(r||[]).map(i=>t.dataStore.getNode(i));return{ok:!0,data:t.dataStore.content.removeChildren(e,r),inverse:{type:"addChild",payload:{parentId:e,children:o}}}});b("copyNode",async(c,t)=>{const{nodeId:e,newParentId:r}=c.payload;if(!t.dataStore.getNode(e))throw new Error(`Node not found: ${e}`);const o=t.dataStore.content.copyNode(e,r);return{ok:!0,data:t.dataStore.getNode(o),inverse:{type:"delete",payload:{nodeId:o}}}});b("cloneNodeWithChildren",async(c,t)=>{const{nodeId:e,newParentId:r}=c.payload;if(!t.dataStore.getNode(e))throw new Error(`Node not found: ${e}`);const o=t.dataStore.content.cloneNodeWithChildren(e,r);return{ok:!0,data:t.dataStore.getNode(o),inverse:{type:"delete",payload:{nodeId:o}}}});b("replacePattern",async(c,t)=>{try{if("range"in c){const{range:l,pattern:u,replacement:f}=c,{startNodeId:h,endNodeId:g,startOffset:y,endOffset:p}=l,N=t.dataStore.getNode(h),I=t.dataStore.getNode(g);if(!N)throw new Error(`Node not found: ${h}`);if(!I)throw new Error(`Node not found: ${g}`);if(typeof N.text!="string"||typeof I.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof y!="number"||typeof p!="number")throw new Error("Invalid range");const m=t.dataStore.range.extractText(l);let _=0,v=m;if(m.length>0){if(u instanceof RegExp){const w=u.flags.includes("g")?u:new RegExp(u.source,u.flags+"g");v=m.replace(w,()=>(_+=1,f))}else{const w=new RegExp(u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");v=m.replace(w,()=>(_+=1,f))}_>0&&t.dataStore.range.replaceText(l,v)}return{ok:!0,data:_}}const{nodeId:e,start:r,end:n,pattern:o,replacement:s}=c,i=t.dataStore.getNode(e);if(!i)throw new Error(`Node not found: ${e}`);if(typeof i.text!="string")throw new Error(`Node ${e} is not a text node`);if(typeof r!="number"||typeof n!="number"||r>n||r<0||n>i.text.length)throw new Error("Invalid range");const a=i.text.substring(r,n);let d=0;if(a.length>0){if(o instanceof RegExp){const l=o.flags.includes("g")?o:new RegExp(o.source,o.flags+"g");a.replace(l,()=>(d+=1,s))}else{const l=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");a.replace(l,()=>(d+=1,s))}d>0&&t.dataStore.range.replaceText({type:"range",startNodeId:e,startOffset:r,endNodeId:e,endOffset:n},a.replace(o,s))}return{ok:!0,data:d}}catch(e){throw new Error(`Failed to replace by pattern: ${e instanceof Error?e.message:"Unknown error"}`)}});b("mergeTextNodes",async(c,t)=>{const{leftNodeId:e,rightNodeId:r}=c.payload,n=t.dataStore.getNode(e),o=t.dataStore.getNode(r);if(!n)throw new Error(`Node not found: ${e}`);if(!o)throw new Error(`Node not found: ${r}`);const s=n.stype,i=o.stype;if(typeof n.text!="string")throw new Error(`Left node is not a text node: ${s||"unknown"}`);if(typeof o.text!="string")throw new Error(`Right node is not a text node: ${i||"unknown"}`);const a=n.text.length,d=t.dataStore.splitMerge.mergeTextNodes(e,r);return{ok:!0,data:d,inverse:{type:"splitTextNode",payload:{nodeId:d,splitPosition:a}}}});b("mergeBlockNodes",async(c,t)=>{const{leftNodeId:e,rightNodeId:r}=c.payload,n=t.dataStore.getNode(e),o=t.dataStore.getNode(r);if(!n)throw new Error(`Node not found: ${e}`);if(!o)throw new Error(`Node not found: ${r}`);if(n.stype!==o.stype)throw new Error(`Cannot merge different node types: ${n.stype} and ${o.stype}`);const s=Array.isArray(n.content)?n.content.length:0,i=t.dataStore.splitMerge.mergeBlockNodes(e,r);return{ok:!0,data:i,inverse:{type:"splitBlockNode",payload:{nodeId:i,splitPosition:s}}}});b("splitBlockNode",async(c,t)=>{const{nodeId:e,splitPosition:r}=c.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Node not found: ${e}`);if(!Array.isArray(n.content))throw new Error("Node has no content to split");const o=t.dataStore.splitMerge.splitBlockNode(e,r),s=t.dataStore.getNode(o),i=s&&Array.isArray(s.content)&&s.content[0]?s.content[0]:null;return t.lastCreatedBlock={blockId:o,firstTextNodeId:i},{ok:!0,data:o,inverse:{type:"mergeBlockNodes",payload:{leftNodeId:e,rightNodeId:o}},selectionAfter:{nodeId:i??o,offset:0}}});b("splitTextNode",async(c,t)=>{const{nodeId:e,splitPosition:r}=c.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Node not found: ${e}`);if(typeof n.text!="string")throw new Error(`Node ${e} is not a text node`);const o=t.dataStore.splitMerge.splitTextNode(e,r);return{ok:!0,data:o,inverse:{type:"mergeTextNodes",payload:{leftNodeId:e,rightNodeId:o}}}});b("autoMergeTextNodes",async(c,t)=>{const{nodeId:e}=c.payload;if(!t.dataStore.getNode(e))throw new Error(`Node not found: ${e}`);return{ok:!0,data:t.dataStore.splitMerge.autoMergeTextNodes(e),inverse:void 0}});b("setText",async(c,t)=>{var s;const{nodeId:e,text:r}=c.payload;if(r==null)throw new Error("Text is required for setText operation");if(typeof r!="string")throw new Error("Text must be a string");const n=t.dataStore.getNode(e);if(!n)throw new Error(`Node not found: ${e}`);const o=t.dataStore.updateNode(e,{text:r});if(!o||o.valid!==!0){const i=((s=o==null?void 0:o.errors)==null?void 0:s[0])||"Update failed";throw new Error(i)}return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"setText",payload:{nodeId:e,text:n.text}}}});b("setAttrs",async(c,t)=>{var s;const{nodeId:e,attrs:r}=c.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Node not found: ${e}`);const o=t.dataStore.updateNode(e,{attributes:{...n.attributes||{},...r}});if(!o||o.valid!==!0){const i=((s=o==null?void 0:o.errors)==null?void 0:s[0])||"Update failed";throw new Error(i)}return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"setAttrs",payload:{nodeId:e,attrs:n.attributes}}}});b("setMarks",async(c,t)=>{var s;const{nodeId:e,marks:r}=c.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Node not found: ${e}`);const o=t.dataStore.marks.setMarks(e,r);if(!o||o.valid!==!0){const i=((s=o==null?void 0:o.errors)==null?void 0:s[0])||"Update marks failed";throw new Error(i)}return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"setMarks",payload:{nodeId:e,marks:n.marks}}}});b("insertText",async(c,t)=>{var o;const{nodeId:e,pos:r,text:n}=c.payload;try{if(!t.dataStore.getNode(e))throw new Error(`Node not found: ${e}`);const i=t.dataStore.range.insertText({type:"range",startNodeId:e,startOffset:r,endNodeId:e,endOffset:r},n);if((o=t.selection)!=null&&o.current){const a=t.selection.current,d=n.length;a.startNodeId===e&&a.startOffset>=r&&(a.startOffset+=d),a.endNodeId===e&&a.endOffset>=r&&(a.endOffset+=d)}return{ok:!0,data:i,inverse:{type:"deleteTextRange",payload:{nodeId:e,startPosition:r,endPosition:r+n.length}}}}catch(s){throw new Error(`Failed to insert text into node ${e}: ${s instanceof Error?s.message:"Unknown error"}`)}});b("deleteTextRange",async(c,t)=>{var o,s;const{nodeId:e,start:r,end:n}=c.payload;try{if(!t.dataStore.getNode(e))throw new Error(`Node not found: ${e}`);const a=t.dataStore.range.deleteText({type:"range",startNodeId:e,startOffset:r,endNodeId:e,endOffset:n});if((o=t.selection)!=null&&o.current){const d=t.selection.current,l=n-r;d.startNodeId===e&&(d.startOffset>=r&&d.startOffset<n||d.startOffset===n?d.startOffset=r:d.startOffset>n&&(d.startOffset-=l)),d.endNodeId===e&&(d.endOffset>=r&&d.endOffset<n||d.endOffset===n?d.endOffset=r:d.endOffset>n&&(d.endOffset-=l)),"collapsed"in d&&(d.collapsed=d.startNodeId===d.endNodeId&&d.startOffset===d.endOffset)}return{ok:!0,data:a,inverse:{type:"insertText",payload:{nodeId:e,pos:r,text:a}},selection:(s=t.selection)!=null&&s.current?{startNodeId:t.selection.current.startNodeId,startOffset:t.selection.current.startOffset,endNodeId:t.selection.current.endNodeId,endOffset:t.selection.current.endOffset}:null}}catch(i){throw new Error(`Failed to delete text range for node ${e}: ${i instanceof Error?i.message:"Unknown error"}`)}});b("deleteRange",async(c,t)=>{const e=c.payload;if(!(e!=null&&e.range))throw new Error("[deleteRange] payload.range is required");const{startNodeId:r,startOffset:n,endNodeId:o,endOffset:s}=e.range,i={type:"range",startNodeId:r,startOffset:n,endNodeId:o,endOffset:s};if(!t.dataStore.range||typeof t.dataStore.range.deleteText!="function")throw new Error("DataStore.range.deleteText is not available");return{ok:!0,data:t.dataStore.range.deleteText(i),inverse:{type:"deleteRange",payload:{range:i}}}});b("replaceText",async(c,t)=>{try{const e=c.payload;if(!e)throw new Error("Payload is required for replaceText operation");if("range"in e){const{range:l,newText:u}=e,{startNodeId:f,endNodeId:h,startOffset:g,endOffset:y}=l,p=t.dataStore.getNode(f),N=t.dataStore.getNode(h);if(!p)throw new Error(`Node not found: ${f}`);if(!N)throw new Error(`Node not found: ${h}`);if(typeof p.text!="string"||typeof N.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof g!="number"||typeof y!="number")throw new Error("Invalid range");const I=t.dataStore.range.extractText(l),m={type:"range",...l};return{ok:!0,data:t.dataStore.range.replaceText(m,u),inverse:{type:"replaceText",payload:{range:{startNodeId:l.startNodeId,startOffset:l.startOffset,endNodeId:l.endNodeId,endOffset:l.endOffset+u.length},newText:I}}}}const{nodeId:r,start:n,end:o,newText:s}=e,i=t.dataStore.getNode(r);if(!i)throw new Error(`Node not found: ${r}`);if(typeof i.text!="string")throw new Error(`Node ${r} is not a text node`);if(typeof n!="number"||typeof o!="number"||n>o||n<0||o>i.text.length)throw new Error("Invalid range");const a=i.text.substring(n,o);return{ok:!0,data:t.dataStore.range.replaceText({type:"range",startNodeId:r,startOffset:n,endNodeId:r,endOffset:o},s),inverse:{type:"replaceText",payload:{nodeId:r,start:n,end:n+s.length,newText:a}}}}catch(e){throw console.log("replaceText error:",e),new Error(`Failed to replace text: ${e instanceof Error?e.message:"Unknown error"}`)}});function Et(c){if(!(c==null||typeof c!="object")&&(c.id!==void 0&&c.sid===void 0&&(c.sid=c.id),c.type!==void 0&&c.stype===void 0&&(c.stype=c.type),Array.isArray(c.content)))for(const t of c.content)t&&typeof t=="object"&&Et(t)}b("create",async(c,t)=>{const{node:e,options:r}=c.payload,n=JSON.parse(JSON.stringify(e));Et(n);try{const o=t.dataStore.getActiveSchema(),s=JSON.parse(JSON.stringify(n)),i=t.dataStore.createNodeWithChildren(s,o);return t.dataStore.getRootNode()||t.dataStore.setRootNodeId(i.sid),{ok:!0,data:JSON.parse(JSON.stringify(i)),inverse:{type:"delete",payload:{nodeId:i.sid}}}}catch(o){throw new Error(`Failed to create node: ${o instanceof Error?o.message:"Unknown error"}`)}});b("delete",async(c,t)=>{var r,n,o,s,i,a,d;const{nodeId:e}=c.payload;try{let l=t.dataStore.getNode(e);if(!l)throw((n=(r=t.dataStore).getRootNodeId)==null?void 0:n.call(r))===e?new Error("Cannot delete root node"):new Error(`Node with id '${e}' not found`);const u=(s=(o=t.dataStore).getRootNodeId)==null?void 0:s.call(o);if(u&&u===e)throw new Error("Cannot delete root node");const h=t.dataStore.getAllDescendants(e).map(p=>p.sid);for(const p of h.reverse())t.dataStore.deleteNode(p)||console.warn(`Failed to delete descendant node: ${p}`);if(l.parentId&&t.dataStore.getNode(l.parentId)&&(t.dataStore.removeChild(l.parentId,e)||console.warn(`Failed to remove child reference from parent: ${l.parentId}`)),(i=t.selection)!=null&&i.current){const p=t.selection.current;(p.startNodeId===e||p.endNodeId===e)&&t.selection.clear()}if(!t.dataStore.deleteNode(e))throw new Error(`Failed to delete node: ${e}`);if(((d=(a=t.dataStore).getRootNodeId)==null?void 0:d.call(a))===e){const N=t.dataStore.getAllNodes().find(I=>I.sid!==e);N?t.dataStore.setRootNodeId(N.sid):t.dataStore.setRootNodeId(void 0)}return{ok:!0,data:!0,inverse:{type:"create",payload:{node:l}}}}catch(l){throw new Error(`Failed to delete node ${e}: ${l instanceof Error?l.message:"Unknown error"}`)}});b("update",async(c,t)=>{const{nodeId:e,data:r}=c.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Node with id '${e}' not found`);const o=t.dataStore.updateNode(e,r);if(o&&!o.valid)throw new Error(`Update failed: ${o.errors.join(", ")}`);return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"update",payload:{nodeId:e,data:n}}}});b("selectRange",async(c,t)=>{var o,s;const e=c.nodeId??(c.payload&&"nodeId"in c.payload?c.payload.nodeId:void 0),r=c.start??((o=c.payload)==null?void 0:o.anchor)??0,n=c.end??((s=c.payload)==null?void 0:s.focus)??0;e&&await t.selectionManager.setSelection({type:"range",startNodeId:e,startOffset:Math.min(r,n),endNodeId:e,endOffset:Math.max(r,n)})});b("selectNode",async(c,t)=>{var r;const e=c.nodeId??((r=c.payload)==null?void 0:r.nodeId);e&&await t.selectionManager.setSelection({type:"node",startNodeId:e,startOffset:0,endNodeId:e,endOffset:0})});b("clearSelection",async(c,t)=>{await t.selectionManager.clearSelection()});b("setSelection",async(c,t)=>{const{anchor:e,head:r}=c.payload,n=e.nodeId===r.nodeId&&e.offset===r.offset;return t.selection.current={type:"range",startNodeId:e.nodeId,startOffset:e.offset,endNodeId:r.nodeId,endOffset:r.offset,collapsed:n},{ok:!0,data:t.selection.current}});b("removeMark",async(c,t)=>{var i;const{nodeId:e,markType:r,range:n}=c.payload;if(!t.dataStore.getNode(e))throw new Error(`Node ${e} not found`);if(!t.dataStore.marks||typeof t.dataStore.marks.removeMark!="function")throw new Error("DataStore.marks.removeMark is not available");const s=t.dataStore.marks.removeMark(e,r,n);if(!s||s.valid!==!0){const a=((i=s==null?void 0:s.errors)==null?void 0:i[0])||"Remove mark failed";throw new Error(a)}return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"applyMark",payload:{nodeId:e,start:n[0],end:n[1],markType:r}}}});b("toggleMark",async(c,t)=>{var d;const e=c.payload,r=e.markType,n=e.attrs;if(e.range&&"startNodeId"in e.range&&"endNodeId"in e.range){const l=e.range;let{startNodeId:u,startOffset:f,endNodeId:h,endOffset:g}=l;if(u===h&&f===g){const p=t.dataStore.getNode(u);p&&typeof p.text=="string"&&(g=Math.min(f+1,p.text.length))}if(!t.dataStore.range||typeof t.dataStore.range.toggleMark!="function")throw new Error("DataStore.range.toggleMark is not available");const y={type:"range",startNodeId:u,startOffset:f,endNodeId:h,endOffset:g};return t.dataStore.range.toggleMark(y,r,n),{ok:!0,inverse:{type:"toggleMark",payload:{range:y,markType:r,attrs:n}}}}const{nodeId:o,range:s}=e;if(!t.dataStore.getNode(o))throw new Error(`Node ${o} not found`);if(!t.dataStore.marks||typeof t.dataStore.marks.toggleMark!="function")throw new Error("DataStore.marks.toggleMark is not available");const a=t.dataStore.marks.toggleMark(o,r,s,n);if(!a||a.valid!==!0){const l=((d=a==null?void 0:a.errors)==null?void 0:d[0])||"Toggle mark failed";throw new Error(l)}return{ok:!0,data:t.dataStore.getNode(o),inverse:{type:"toggleMark",payload:{nodeId:o,markType:r,range:s,attrs:n}}}});b("updateMark",async(c,t)=>{var a;const{nodeId:e,markType:r,range:n,newAttrs:o}=c.payload;if(!t.dataStore.getNode(e))throw new Error(`Node ${e} not found`);if(!t.dataStore.marks||typeof t.dataStore.marks.updateMark!="function")throw new Error("DataStore.marks.updateMark is not available");const i=t.dataStore.marks.updateMark(e,r,n,o);if(!i||i.valid!==!0){const d=((a=i==null?void 0:i.errors)==null?void 0:a[0])||"Update mark failed";throw new Error(d)}return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"updateMark",payload:{nodeId:e,markType:r,range:n,newAttrs:me(t.dataStore.getNode(e),r,n)}}}});function me(c,t,e){const n=((c==null?void 0:c.marks)||[]).find(o=>o.type===t&&Array.isArray(o.range)&&o.range[0]===e[0]&&o.range[1]===e[1]);return n==null?void 0:n.attrs}b("applyMark",async(c,t)=>{var e;try{const r=c.payload;if(!r)throw new Error("Operation payload is required");const n=r.markType,o=r.attrs;if("range"in r){const{range:u}=r,{startNodeId:f,endNodeId:h,startOffset:g,endOffset:y}=u,p=t.dataStore.getNode(f),N=t.dataStore.getNode(h);if(!p)throw new Error(`Node not found: ${f}`);if(!N)throw new Error(`Node not found: ${h}`);if(typeof p.text!="string"||typeof N.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof g!="number"||typeof y!="number")throw new Error("Invalid range");if(!t.dataStore.range||typeof t.dataStore.range.applyMark!="function")throw new Error("DataStore.range.applyMark is not available");const I={type:"range",startNodeId:f,startOffset:g,endNodeId:h,endOffset:y},m={stype:n,attrs:o};return t.dataStore.range.applyMark(I,m),t.dataStore.getNode(f===h?f:h)}const{nodeId:s,start:i,end:a}=r,d=t.dataStore.getNode(s);if(!d)throw new Error(`Node not found: ${s}`);if(typeof d.text!="string")throw new Error(`Node ${s} is not a text node`);if(typeof i!="number"||typeof a!="number"||i>=a||i<0||a>d.text.length)throw new Error("Invalid range");const l=t.dataStore.marks.setMarks(s,[...d.marks||[],{stype:n,attrs:o,range:[i,a]}]);if(!l||l.valid!==!0)throw new Error(((e=l==null?void 0:l.errors)==null?void 0:e[0])||"Apply mark failed");return{ok:!0,data:t.dataStore.getNode(s),inverse:{type:"removeMark",payload:{nodeId:s,markType:n,range:[i,a]}}}}catch(r){throw new Error(`Failed to apply mark: ${r instanceof Error?r.message:"Unknown error"}`)}});b("wrap",async(c,t)=>{try{const e=c.payload;if("range"in e){const{range:f,prefix:h,suffix:g}=e,{startNodeId:y,endNodeId:p,startOffset:N,endOffset:I}=f,m=t.dataStore.getNode(y),_=t.dataStore.getNode(p);if(!m)throw new Error(`Node not found: ${y}`);if(!_)throw new Error(`Node not found: ${p}`);if(typeof m.text!="string"||typeof _.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof N!="number"||typeof I!="number")throw new Error("Invalid range");return{ok:!0,data:t.dataStore.range.wrap(f,h,g),inverse:{type:"unwrap",payload:{range:{startNodeId:f.startNodeId,startOffset:f.startOffset,endNodeId:f.endNodeId,endOffset:f.endOffset+h.length+g.length},prefix:h,suffix:g}}}}const{nodeId:r,start:n,end:o,prefix:s,suffix:i}=e,a=t.dataStore.getNode(r);if(!a)throw new Error(`Node not found: ${r}`);if(typeof a.text!="string")throw new Error(`Node ${r} is not a text node`);if(typeof n!="number"||typeof o!="number"||n>o||n<0||o>a.text.length)throw new Error("Invalid range");const d=a.text.substring(n,o),l=`${s}${d}${i}`,u=t.dataStore.range.replaceText({type:"range",startNodeId:r,startOffset:n,endNodeId:r,endOffset:o},l);return{ok:!0,data:`${s}${u}${i}`,inverse:{type:"unwrap",payload:{nodeId:r,start:n,end:n+l.length,prefix:s,suffix:i}}}}catch(e){throw new Error(`Failed to wrap text: ${e instanceof Error?e.message:"Unknown error"}`)}});b("unwrap",async(c,t)=>{try{const e=c.payload;if("range"in e){const{range:l,prefix:u,suffix:f}=e,{startNodeId:h,endNodeId:g,startOffset:y,endOffset:p}=l,N=t.dataStore.getNode(h),I=t.dataStore.getNode(g);if(!N)throw new Error(`Node not found: ${h}`);if(!I)throw new Error(`Node not found: ${g}`);if(typeof N.text!="string"||typeof I.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof y!="number"||typeof p!="number")throw new Error("Invalid range");let m=t.dataStore.range.extractText(l);return m.startsWith(u)&&(m=m.substring(u.length)),m.endsWith(f)&&(m=m.substring(0,m.length-f.length)),t.dataStore.range.replaceText(l,m),{ok:!0,data:m,inverse:{type:"wrap",payload:{range:{startNodeId:l.startNodeId,startOffset:l.startOffset,endNodeId:l.endNodeId,endOffset:l.endOffset+u.length+f.length},prefix:u,suffix:f}}}}const{nodeId:r,start:n,end:o,prefix:s,suffix:i}=e,a=t.dataStore.getNode(r);if(!a)throw new Error(`Node not found: ${r}`);if(typeof a.text!="string")throw new Error(`Node ${r} is not a text node`);if(typeof n!="number"||typeof o!="number"||n>o||n<0||o>a.text.length)throw new Error("Invalid range");let d=a.text.substring(n,o);return d.startsWith(s)&&(d=d.substring(s.length)),d.endsWith(i)&&(d=d.substring(0,d.length-i.length)),t.dataStore.range.replaceText({type:"range",startNodeId:r,startOffset:n,endNodeId:r,endOffset:o},d),{ok:!0,data:d,inverse:{type:"wrap",payload:{nodeId:r,start:n,end:n+d.length,prefix:s,suffix:i}}}}catch(e){throw new Error(`Failed to unwrap text: ${e instanceof Error?e.message:"Unknown error"}`)}});function Se(c,t,e){if(!e||e.type!=="range")return null;const r=c.getNode(e.startNodeId);if(!r)return null;if(typeof r.text=="string"){const d=c.getParent(e.startNodeId);if(!d||!Array.isArray(d.content))return null;const l=d.parentId?c.getNode(c.resolveAlias(d.parentId)):null;if(!l||!Array.isArray(l.content))return null;const u=l.content.indexOf(d.sid);return u===-1?null:{blockId:d.sid,block:d,parentId:l.sid,parent:l,blockIndex:u}}const n=t==null?void 0:t.getNodeType(r.stype);if((n==null?void 0:n.group)!=="block")return null;const o=r,s=c.getParent(o.sid);if(!s||!Array.isArray(s.content))return null;const i=s.parentId?c.getNode(c.resolveAlias(s.parentId)):null;if(!i||!Array.isArray(i.content))return null;const a=i.content.indexOf(s.sid);return a===-1?null:{blockId:s.sid,block:s,parentId:i.sid,parent:i,blockIndex:a}}b("wrapInList",async(c,t)=>{const e=c.payload.listType??"bullet",r=t.dataStore,n=t.schema,o=t.selection.current,s=Se(r,n,o);if(!s)throw new Error("wrapInList: no selection or selection does not resolve to a block");const{blockId:i,block:a,parentId:d,parent:l,blockIndex:u}=s,f=(o==null?void 0:o.startNodeId)??null,h=typeof(o==null?void 0:o.startOffset)=="number"?o.startOffset:0;if(l.stype==="listItem"){const I=l.parentId;if(I==null)throw new Error("wrapInList: listItem has no parent");const m=r.getNode(r.resolveAlias(I));if(!m||m.stype!=="list"||!Array.isArray(m.content))throw new Error("wrapInList: listItem parent is not a list");const _=m.parentId;if(_==null)throw new Error("wrapInList: list has no parent");const v=r.resolveAlias(_),w=r.getNode(v);if(!w||!Array.isArray(w.content))throw new Error("wrapInList: list has no document parent");const E=m.sid;if(E==null)throw new Error("wrapInList: list has no sid");const A=w.content.indexOf(E);if(A===-1)throw new Error("wrapInList: list not in document");const F=m.content;let x=A;for(const M of F){const O=r.getNode(M);if(!O||!Array.isArray(O.content))continue;const C=O.content;for(const D of C)r.content.removeChild(M,D),r.content.addChild(v,D,x),x+=1}return r.content.removeChild(v,E),{ok:!0,data:{unwrapped:!0},selectionAfter:f?{nodeId:f,offset:h}:void 0}}const g={stype:"list",attributes:{type:e},content:[]},y=r.content.addChild(d,g,u),p={stype:"listItem",content:[]},N=r.content.addChild(y,p,0);return r.content.moveNode(i,N,0),{ok:!0,data:r.getNode(y),selectionAfter:f?{nodeId:f,offset:h}:void 0}});function Ie(c,t,e){if(!e||e.type!=="range")return null;const r=c.getNode(e.startNodeId);if(!r)return null;let n,o,s,i;if(typeof r.text=="string"){n=e.startNodeId;const u=r.text;o=typeof e.startOffset=="number"&&e.startOffset>=0?Math.min(e.startOffset,u.length):0,s=u.length,i=c.getParent(n)}else{const u=t==null?void 0:t.getNodeType(r.stype);if((u==null?void 0:u.group)!=="block")return null;i=r;const f=we(c,i.sid);if(!f)return null;n=f.sid,s=f.text.length,o=s}if(!i||!Array.isArray(i.content))return null;const a=c.getParent(i.sid);if(!a||a.stype!=="listItem")return null;const d=c.getNode(c.resolveAlias(a.parentId));if(!d||d.stype!=="list"||!Array.isArray(d.content))return null;const l=d.content.indexOf(a.sid);return l===-1?null:{blockId:i.sid,block:i,listItemId:a.sid,listItem:a,listId:d.sid,list:d,listItemIndex:l,textNodeId:n,offset:o,textLength:s}}function we(c,t){const e=c.getNode(t);if(!e||!Array.isArray(e.content))return null;const r=e.content;let n=null;const o=s=>{const i=c.getNode(s);if(!i)return;if(typeof i.text=="string"){n={sid:i.sid,text:i.text};return}const a=i.content;if(Array.isArray(a))for(const d of a)o(d)};for(const s of r)o(s);return n}b("splitListItem",async(c,t)=>{const e=t.dataStore,r=t.schema,n=t.selection.current,o=Ie(e,r,n);if(!o)return{ok:!0,data:null};const{listId:s,listItem:i,listItemIndex:a,textNodeId:d,offset:l,textLength:u}=o,f=Math.max(0,Math.min(l,u));if(i.content.length===1&&i.content[0]===d&&f>0&&f<u){e.splitTextNode(d,f);const m=e.splitBlockNode(o.blockId,1),_=e.getNode(m),v=_&&Array.isArray(_.content)&&_.content[0]?_.content[0]:null;if(!v)throw new Error("splitListItem: splitBlockNode did not yield a text node");const w={stype:"listItem",content:[]},E=e.content.addChild(s,w,a+1);return e.content.moveNode(m,E,0),t.lastCreatedBlock={blockId:m,firstTextNodeId:v},{ok:!0,data:e.getNode(E),selectionAfter:{nodeId:v,offset:0}}}const g={stype:"paragraph",attributes:{},content:[]},y=e.content.addChild(i.sid,g,i.content.length),p=e.content.addChild(y,{stype:"inline-text",text:""},0),N={stype:"listItem",content:[]},I=e.content.addChild(s,N,a+1);return e.content.moveNode(y,I,0),t.lastCreatedBlock={blockId:y,firstTextNodeId:p},{ok:!0,data:e.getNode(I),selectionAfter:{nodeId:p,offset:0}}});function ve(c,t,e){if(!e||e.type!=="range")return null;const r=c.getNode(e.startNodeId);if(!r)return null;if(typeof r.text=="string"){const d=c.getParent(e.startNodeId);if(!d||!Array.isArray(d.content))return null;const l=d.parentId?c.getNode(c.resolveAlias(d.parentId)):null;if(!l||!Array.isArray(l.content))return null;const u=l.content.indexOf(d.sid);return u===-1?null:{blockId:d.sid,block:d,parentId:l.sid,parent:l,blockIndex:u}}const n=t==null?void 0:t.getNodeType(r.stype);if((n==null?void 0:n.group)!=="block")return null;const o=r,s=c.getParent(o.sid);if(!s||!Array.isArray(s.content))return null;const i=s.parentId?c.getNode(c.resolveAlias(s.parentId)):null;if(!i||!Array.isArray(i.content))return null;const a=i.content.indexOf(s.sid);return a===-1?null:{blockId:s.sid,block:s,parentId:i.sid,parent:i,blockIndex:a}}b("wrapInBlockquote",async(c,t)=>{const e=t.dataStore,r=t.schema,n=t.selection.current,o=ve(e,r,n);if(!o)throw new Error("wrapInBlockquote: no selection or selection does not resolve to a block");const{blockId:s,block:i,parentId:a,parent:d,blockIndex:l}=o,u=(n==null?void 0:n.startNodeId)??null,f=typeof(n==null?void 0:n.startOffset)=="number"?n.startOffset:0;if(d.stype==="blockQuote"){const y=e.resolveAlias(d.parentId),p=e.getNode(y);if(!p||!Array.isArray(p.content))throw new Error("wrapInBlockquote: blockQuote has no document parent");const N=p.content.indexOf(d.sid);if(N===-1)throw new Error("wrapInBlockquote: blockQuote not in document");const I=d.content;let m=N;for(const _ of I)e.content.removeChild(d.sid,_),e.content.addChild(y,_,m),m+=1;return e.content.removeChild(y,d.sid),{ok:!0,data:{unwrapped:!0},selectionAfter:u?{nodeId:u,offset:f}:void 0}}const h={stype:"blockQuote",content:[]},g=e.content.addChild(a,h,l);return e.content.moveNode(s,g,0),{ok:!0,data:e.getNode(g),selectionAfter:u?{nodeId:u,offset:f}:void 0}});b("indentNode",async(c,t)=>{const e=c.payload.nodeId;if(!e)throw new Error("[indentNode] nodeId is required in payload");if(!t.dataStore.getNode(e))throw new Error(`[indentNode] Node not found: ${e}`);return t.dataStore.indentNode(e)?{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"outdentNode",payload:{nodeId:e}}}:{ok:!0,data:t.dataStore.getNode(e)}});b("outdentNode",async(c,t)=>{const e=c.payload.nodeId;if(!e)throw new Error("[outdentNode] nodeId is required in payload");if(!t.dataStore.getNode(e))throw new Error(`[outdentNode] Node not found: ${e}`);return t.dataStore.outdentNode(e)?{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"indentNode",payload:{nodeId:e}}}:{ok:!0,data:t.dataStore.getNode(e)}});b("indentText",async(c,t)=>{try{const e=c.payload,r=e.indent??" ";if("range"in e){const{range:l}=e,{startNodeId:u,endNodeId:f,startOffset:h,endOffset:g}=l,y=t.dataStore.getNode(u),p=t.dataStore.getNode(f);if(!y)throw new Error(`Node not found: ${u}`);if(!p)throw new Error(`Node not found: ${f}`);if(typeof y.text!="string"||typeof p.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof h!="number"||typeof g!="number")throw new Error("Invalid range");return{ok:!0,data:t.dataStore.range.indent(l,r),inverse:{type:"outdentText",payload:{range:l,indent:r}}}}const{nodeId:n,start:o,end:s}=e,i=t.dataStore.getNode(n);if(!i)throw new Error(`Node not found: ${n}`);if(typeof i.text!="string")throw new Error(`Node ${n} is not a text node`);if(typeof o!="number"||typeof s!="number"||o>s||o<0||s>i.text.length)throw new Error("Invalid range");const a={type:"range",startNodeId:n,startOffset:o,endNodeId:n,endOffset:s,collapsed:!1,direction:"forward"};return{ok:!0,data:t.dataStore.range.indent(a,r),inverse:{type:"outdentText",payload:{nodeId:n,start:o,end:s,indent:r}}}}catch(e){throw new Error(`Failed to indent text: ${e instanceof Error?e.message:"Unknown error"}`)}});b("outdentText",async(c,t)=>{try{const e=c.payload,r=e.indent??" ";if("range"in e){const{range:l}=e,{startNodeId:u,endNodeId:f,startOffset:h,endOffset:g}=l,y=t.dataStore.getNode(u),p=t.dataStore.getNode(f);if(!y)throw new Error(`Node not found: ${u}`);if(!p)throw new Error(`Node not found: ${f}`);if(typeof y.text!="string"||typeof p.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof h!="number"||typeof g!="number")throw new Error("Invalid range");return{ok:!0,data:t.dataStore.range.outdent(l,r),inverse:{type:"indentText",payload:{range:l,indent:r}}}}const{nodeId:n,start:o,end:s}=e,i=t.dataStore.getNode(n);if(!i)throw new Error(`Node not found: ${n}`);if(typeof i.text!="string")throw new Error(`Node ${n} is not a text node`);if(typeof o!="number"||typeof s!="number"||o>s||o<0||s>i.text.length)throw new Error("Invalid range");const a={type:"range",startNodeId:n,startOffset:o,endNodeId:n,endOffset:s,collapsed:!1,direction:"forward"};return{ok:!0,data:t.dataStore.range.outdent(a,r),inverse:{type:"indentText",payload:{nodeId:n,start:o,end:s,indent:r}}}}catch(e){throw new Error(`Failed to outdent text: ${e instanceof Error?e.message:"Unknown error"}`)}});b("copy",async(c,t)=>{const{range:e}=c.payload;if(!e)throw new Error("[copy] range is required");const r=t.dataStore.serializeRange(e),n=t.dataStore.range.extractText(e);return{json:r,text:n}});b("paste",async(c,t)=>{const{range:e,data:r}=c.payload;if(!e||!r||!Array.isArray(r.nodes))throw new Error("[paste] range and data.nodes are required");const n=t.dataStore.getNode(e.startNodeId);if(!n||!n.parentId)throw new Error("[paste] startNode or its parent not found");const o=n.parentId,s=t.dataStore.getNode(o);if(!s||!Array.isArray(s.content))throw new Error("[paste] parent node or its content not found");const i=s.content.indexOf(e.startNodeId),a=i>=0?i+1:s.content.length,d=t.dataStore.deserializeNodes(r.nodes,o,a),l=d.length?{type:"range",startNodeId:d[d.length-1],startOffset:0,endNodeId:d[d.length-1],endOffset:0,collapsed:!0,direction:"forward"}:null;return{insertedNodeIds:d,newSelection:l}});b("cut",async(c,t)=>{const{range:e}=c.payload;if(!e)throw new Error("[cut] range is required");const r=t.dataStore.serializeRange(e),n=t.dataStore.range.extractText(e);return t.dataStore.range.deleteRange(e),{json:r,text:n,deletedRange:e}});b("transformNode",async(c,t)=>{var i;const{nodeId:e,newType:r,newAttrs:n}=c.payload;if(!e)throw new Error("Node ID is required for transformNode operation");if(!r)throw new Error("New type is required for transformNode operation");const o=t.dataStore.getNode(e);if(!o)throw new Error(`Node not found: ${e}`);const s=t.dataStore.transformNode(e,r,n);if(!s||s.valid!==!0){const a=((i=s==null?void 0:s.errors)==null?void 0:i[0])||"Transform node failed";throw new Error(a)}return{ok:!0,data:t.dataStore.getNode(s.newNodeId||e),inverse:{type:"transformNode",payload:{nodeId:s.newNodeId||e,newType:o.stype,newAttrs:o.attributes}}}});b("moveBlockUp",async(c,t)=>{const{nodeId:e}=c.payload;if(!e)throw new Error("Node ID is required for moveBlockUp operation");const r=t.dataStore.getNode(e);if(!r)throw new Error(`Node not found: ${e}`);if(!r.parentId)throw new Error(`Node ${e} has no parent`);const n=t.dataStore.getNode(r.parentId);if(!n||!Array.isArray(n.content))throw new Error(`Parent node not found or has no content: ${r.parentId}`);const o=n.content.indexOf(e);if(o===-1)throw new Error(`Node ${e} not found in parent content`);return o===0?{ok:!1,data:null,error:"Cannot move block up: already at first position"}:t.dataStore.moveBlockUp(e)?{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"moveBlockDown",payload:{nodeId:e}}}:{ok:!1,data:null,error:"Failed to move block up"}});b("moveBlockDown",async(c,t)=>{const{nodeId:e}=c.payload;if(!e)throw new Error("Node ID is required for moveBlockDown operation");const r=t.dataStore.getNode(e);if(!r)throw new Error(`Node not found: ${e}`);if(!r.parentId)throw new Error(`Node ${e} has no parent`);const n=t.dataStore.getNode(r.parentId);if(!n||!Array.isArray(n.content))throw new Error(`Parent node not found or has no content: ${r.parentId}`);const o=n.content.indexOf(e);if(o===-1)throw new Error(`Node ${e} not found in parent content`);return o===n.content.length-1?{ok:!1,data:null,error:"Cannot move block down: already at last position"}:t.dataStore.moveBlockDown(e)?{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"moveBlockUp",payload:{nodeId:e}}}:{ok:!1,data:null,error:"Failed to move block down"}});const P={NODE_REQUIRED:"NODE_REQUIRED",NODE_ID_REQUIRED:"NODE_ID_REQUIRED",NODE_TYPE_REQUIRED:"NODE_TYPE_REQUIRED",TEXT_CONTENT_REQUIRED:"TEXT_CONTENT_REQUIRED",DOCUMENT_REQUIRED:"DOCUMENT_REQUIRED",DOCUMENT_ID_REQUIRED:"DOCUMENT_ID_REQUIRED",DOCUMENT_SCHEMA_REQUIRED:"DOCUMENT_SCHEMA_REQUIRED",DOCUMENT_CONTENT_REQUIRED:"DOCUMENT_CONTENT_REQUIRED",NODE_TYPE_UNKNOWN:"NODE_TYPE_UNKNOWN",CONTENT_REQUIRED_BUT_EMPTY:"CONTENT_REQUIRED_BUT_EMPTY",ATTRIBUTE_INVALID:"ATTRIBUTE_INVALID",INVALID_SCHEMA_INSTANCE:"INVALID_SCHEMA_INSTANCE"};class xe{static validateNodeStructure(t){var o;const e=[],r=[];if(!t)return e.push("Node is required"),r.push(P.NODE_REQUIRED),{valid:!1,errors:e,errorCodes:r};if(t.sid||(e.push("Node ID is required"),r.push(P.NODE_ID_REQUIRED)),(t==null?void 0:t.stype)||(e.push("Node stype is required"),r.push(P.NODE_TYPE_REQUIRED)),(t==null?void 0:t.stype)==="text"){const s=t.text&&t.text!==void 0&&t.text!=="",i=((o=t.attributes)==null?void 0:o.content)&&t.attributes.content!==void 0&&t.attributes.content!=="";!s&&!i&&(e.push("Text content or content attribute is required for text nodes"),r.push(P.TEXT_CONTENT_REQUIRED))}return{valid:e.length===0,errors:e,errorCodes:r}}static validateDocumentStructure(t){const e=[],r=[];return t?(t.sid||(e.push("Document ID is required"),r.push(P.DOCUMENT_ID_REQUIRED)),t.schema||(e.push("Document schema is required"),r.push(P.DOCUMENT_SCHEMA_REQUIRED)),(!t.content||t.content.length===0)&&(e.push("Document content is required"),r.push(P.DOCUMENT_CONTENT_REQUIRED)),t.content&&Array.isArray(t.content)&&t.content.forEach((n,o)=>{const s=this.validateNodeStructure(n);s.valid||(s.errors.forEach(i=>{e.push(`Node ${o}: ${i}`)}),s.errorCodes&&s.errorCodes.forEach(i=>{r.push(i)}))}),{valid:e.length===0,errors:e,errorCodes:r}):(e.push("Document is required"),r.push(P.DOCUMENT_REQUIRED),{valid:!1,errors:e,errorCodes:r})}static validateNode(t,e){const r=[],n=[];if(!t||typeof t.hasNodeType!="function")return console.error("Invalid schema passed to validateNode:",t),r.push("Invalid schema instance"),n.push(P.INVALID_SCHEMA_INSTANCE),{valid:!1,errors:r,errorCodes:n};const o=e==null?void 0:e.stype;if(!t.hasNodeType(o))return r.push(`Unknown node type: ${o}`),n.push(P.NODE_TYPE_UNKNOWN),{valid:!1,errors:r,errorCodes:n};const s=t.validateAttributes(o,e.attrs||{});if(s.valid||(r.push(...s.errors),n.push(P.ATTRIBUTE_INVALID)),e.content){const a=t.validateContent(o,e.content);a.valid||(r.push(...a.errors),n.push(P.CONTENT_REQUIRED_BUT_EMPTY))}const i=t.getNodeType(o);if(i&&(i.indentable&&i.group&&i.group!=="block"&&r.push(`Node type '${o}' is indentable but its group is '${i.group}'. Indentable nodes are expected to be in the 'block' group.`),typeof i.maxIndentLevel=="number"&&i.maxIndentLevel<=0&&r.push(`Node type '${o}' has invalid maxIndentLevel '${i.maxIndentLevel}'. Expected a positive integer or undefined.`),!i.indentable&&Array.isArray(i.indentParentTypes)&&i.indentParentTypes.length>0&&r.push(`Node type '${o}' defines indentParentTypes but is not indentable. Either set indentable: true or remove indentParentTypes.`),Array.isArray(i.indentParentTypes)))for(const a of i.indentParentTypes)t.hasNodeType(a)||r.push(`Node type '${o}' has indentParentTypes entry '${a}' which is not defined in the schema.`);return{valid:r.length===0,errors:r,errorCodes:n}}static validateDocument(t,e){const r=[];e.stype!==t.topNode&&r.push(`Document stype '${e.stype}' does not match schema topNode '${t.topNode}'`);const n=t.validateAttributes(t.topNode,e.attrs||{});if(n.valid||r.push(...n.errors),e.content){const o=t.validateContent(t.topNode,e.content);o.valid||r.push(...o.errors),e.content.forEach((s,i)=>{const a=this.validateNode(t,s);a.valid||r.push(...a.errors.map(d=>`Child node ${i}: ${d}`))})}return{valid:r.length===0,errors:r}}static validateType(t,e){switch(e){case"string":return typeof t=="string";case"number":return typeof t=="number";case"boolean":return typeof t=="boolean";case"array":return Array.isArray(t);case"object":return typeof t=="object"&&t!==null&&!Array.isArray(t);case"custom":return!0;default:return!1}}static validateObjectSchema(t,e){const r=[];if(!t||typeof t!="object"||Array.isArray(t))return{valid:!1,errors:["Value must be a valid object"]};for(const[i,a]of Object.entries(e)){if((typeof a.required=="function"?a.required(t):a.required)&&(t[i]===void 0||t[i]===null)){r.push(`Required object property '${i}' is missing`);continue}if(t[i]!==void 0&&t[i]!==null){if(!this.validateType(t[i],a.type)){r.push(`Object property '${i}' has invalid type. Expected ${a.type}, got ${typeof t[i]}`);continue}if(a.type==="object"&&a.objectSchema){const l=this.validateObjectSchema(t[i],a.objectSchema);l.valid||r.push(...l.errors.map(u=>`Object property '${i}': ${u}`))}a.validator&&!a.validator(t[i],t)&&r.push(`Object property '${i}' failed custom validation`)}}const n=new Set(Object.keys(e)),s=Object.keys(t).filter(i=>!n.has(i));return s.length>0&&r.push(`Object contains undefined properties: ${s.join(", ")}`),{valid:r.length===0,errors:r}}static validateAttributes(t,e){const r=[];for(const n in t){const o=t[n],s=e[n];if((typeof o.required=="function"?o.required(e):o.required)&&(s==null||s==="")){r.push(`Required attribute '${n}' is missing or empty.`);continue}if(s!=null){if(this.validateType(s,o.type)||r.push(`Attribute '${n}' has invalid type. Expected ${o.type}, got ${typeof s}.`),o.type==="object"&&o.objectSchema){const a=this.validateObjectSchema(s,o.objectSchema);a.valid||r.push(...a.errors.map(d=>`Attribute '${n}': ${d}`))}o.validator&&!o.validator(s,e)&&r.push(`Attribute '${n}' failed custom validation.`)}}return{valid:r.length===0,errors:r}}static validateContentModel(t,e,r){const n=[],o=t.getNodeType(e);if(!o)return{valid:!1,errors:[`Unknown node type: ${e}`]};const s=o.content;if(!s)return{valid:!0,errors:[]};const i=s.trim();if(i.endsWith("+")){r.length===0&&n.push(`Content is required but empty for model '${i}'.`);const a=i.slice(0,-1);r.forEach((d,l)=>{if(!t.hasNodeType(d.stype)){n.push(`Node at index ${l} has unknown type '${d.stype}'.`);return}const u=t.getNodeType(d.stype);(u==null?void 0:u.group)!==a&&d.stype!==a&&n.push(`Node at index ${l} of type '${d.stype}' does not match required content model '${a}'.`)})}else if(i.endsWith("*")){const a=i.slice(0,-1);r.forEach((d,l)=>{if(!t.hasNodeType(d.stype)){n.push(`Node at index ${l} has unknown type '${d.stype}'.`);return}const u=t.getNodeType(d.stype);(u==null?void 0:u.group)!==a&&d.stype!==a&&n.push(`Node at index ${l} of type '${d.stype}' does not match required content model '${a}'.`)})}else if(i.endsWith("?")){if(r.length>1&&n.push(`Content for model '${i}' must be 0 or 1 node, but got ${r.length}.`),r.length===1){const a=i.slice(0,-1),d=r[0];if(!t.hasNodeType(d.stype))return n.push(`Node has unknown type '${d.stype}'.`),{valid:n.length===0,errors:n};const l=t.getNodeType(d.stype);(l==null?void 0:l.group)!==a&&d.stype!==a&&n.push(`Node of type '${d.stype}' does not match required content model '${a}'.`)}}else if(i.includes("|")){const a=i.split("|").map(d=>d.trim());r.forEach((d,l)=>{if(!a.includes(d.stype)){const u=t.getNodeType(d.stype),f=u==null?void 0:u.group;a.includes(f||"")||n.push(`Node at index ${l} of type '${d.stype}' does not match any allowed types in '${i}'.`)}})}else i!==""&&r.forEach((a,d)=>{if(!t.hasNodeType(a.stype)){n.push(`Node at index ${d} has unknown type '${a.stype}'.`);return}const l=t.getNodeType(a.stype);a.stype!==i&&(l==null?void 0:l.group)!==i&&n.push(`Node at index ${d} of type '${a.stype}' does not match required type or group '${i}'.`)});return{valid:n.length===0,errors:n}}}class _e{static validateNode(t,e){function r(n){if(!n||typeof n!="object")return n;const o={stype:n.stype,attrs:n.attributes||{},text:n.text,marks:n.marks};return Array.isArray(n.content)&&(o.content=n.content.map(s=>s&&typeof s=="object"&&"stype"in s?r(s):s).filter(s=>s!==void 0)),o}return xe.validateNode(e,r(t))}}function be(c,t){return _e.validateNode(c,t)}class ke{constructor(t){this.dataStore=t}setNode(t,e=!0){this.dataStore.constructor._globalCounter=this.dataStore.getNodes().size,t.sid||(t.sid=this.dataStore.generateId());const r=this.dataStore.getActiveSchema();if(e&&r)if(t.content&&Array.isArray(t.content)&&t.content.some(a=>typeof a=="object"&&a!==null)){const a=this.dataStore.validateNode(t,r);if(!a.valid)throw new Error(`Schema validation failed for node ${t.sid}: ${a.errors.join(", ")}`)}else{const a={...t,content:void 0},d=this.dataStore.validateNode(a,r);if(!d.valid)throw new Error(`Schema validation failed for node ${t.sid}: ${d.errors.join(", ")}`)}this._convertChildrenToDataStore(t);const n=this.dataStore._overlay,s={type:!this.dataStore.getNodes().has(t.sid)?"create":"update",nodeId:t.sid,data:{stype:t.stype,attributes:t.attributes,text:t.text,content:t.content,parentId:t.parentId,marks:t.marks},timestamp:Date.now(),parentId:t.parentId};n&&n.isActive&&n.isActive()?n.upsertNode(t,s.type):this.dataStore.setNodeInternal(t),this.dataStore.emitOperation(s)}getNode(t){const e=this.dataStore._overlay;if(!(e&&typeof e.hasDeleted=="function"&&e.hasDeleted(t)))return e&&typeof e.hasOverlayNode=="function"&&e.hasOverlayNode(t)?e.getOverlayNode(t):this.dataStore.getNodes().get(t)}deleteNode(t){const e=this.dataStore._overlay,r=this.getNode(t);if(!r)return!1;const n=this.dataStore.getRootNodeId&&this.dataStore.getRootNodeId();if(n&&t===n)throw new Error("Cannot delete root node");let o=!1;if(e&&e.isActive&&e.isActive()?(e.markDeleted(t,r.parentId),o=!0):o=this.dataStore.getNodes().delete(t),o){if(r.parentId){const i=this.dataStore.getNodes().get(r.parentId);if(i&&i.content){const a=i.content.indexOf(t);a!==-1&&(i.content.splice(a,1),this.updateNode(r.parentId,{content:i.content},!1))}}const s={type:"delete",nodeId:t,timestamp:Date.now(),parentId:r.parentId};this.dataStore.emitOperation(s)}return o}updateNode(t,e,r=!0){const n=this.getNode(t);if(!n)return{valid:!1,errors:[`Node not found: ${t}`]};if(e.stype&&e.stype!==n.stype)return{valid:!1,errors:[`Cannot change node stype from '${n.stype}' to '${e.stype}'`]};const o={...n,...e};e.attributes&&n.attributes&&(o.attributes={...n.attributes,...e.attributes});const s=e.content!==void 0;if(r&&!s)try{return this.setNode(o,!0),{valid:!0,errors:[]}}catch(i){return{valid:!1,errors:[i instanceof Error?i.message:"Validation failed"]}}else return this.setNode(o,!1),{valid:!0,errors:[]}}createNodeWithChildren(t,e){const r=e||this.dataStore.getActiveSchema();if(t.parentId==null&&(this.dataStore.constructor._globalCounter=this.dataStore.getNodes().size),this._assignIdsRecursively(t),r){const o=this.dataStore.validateNode(t,r);if(!o.valid)throw new Error(`Schema validation failed for node ${t.sid}: ${o.errors.join(", ")}`)}this._createAllNodesRecursively(t);const n=this.dataStore.getNode(t.sid);if(!n)throw new Error(`Failed to retrieve created node ${t.sid}`);return n}_createAllNodesRecursively(t){t.content&&Array.isArray(t.content)&&(t.content=t.content.map(n=>typeof n=="object"&&n!==null?(this._createAllNodesRecursively(n),n.sid):n));const e=this.dataStore._overlay;if(e&&e.isActive&&e.isActive())e.upsertNode(t,"create");else{const n={...t,marks:t.marks};this.dataStore.setNodeInternal(n)}const r={type:"create",nodeId:t.sid,data:{stype:t.stype,attributes:t.attributes,text:t.text,content:t.content,parentId:t.parentId,marks:t.marks},timestamp:Date.now(),parentId:t.parentId};this.dataStore.emitOperation(r)}_assignIdsRecursively(t){t.sid||(t.sid=this.dataStore.generateId()),t.content&&Array.isArray(t.content)&&t.content.forEach(e=>{if(typeof e=="object"&&e!==null){const r=e;r.parentId=t.sid,this._assignIdsRecursively(r)}else if(typeof e=="string"){const r=this.getNode(e);r&&(r.parentId=t.sid)}})}_convertChildrenToDataStore(t){t.content&&Array.isArray(t.content)&&(t.content=t.content.map(e=>{if(typeof e=="object"&&e!==null){const r=e;this._convertChildrenToDataStore(r);const n=this.dataStore._overlay;return n&&n.isActive&&n.isActive()?n.upsertNode(r,"create"):this.dataStore.setNodeInternal(r),r.sid}return e}))}transformNode(t,e,r){const n=this.dataStore.getNode(t);if(!n)return{valid:!1,errors:[`Node not found: ${t}`]};if(n.stype===e)return{valid:!0,errors:[],newNodeId:t};const o=n.parentId;let s;if(o){const d=this.dataStore.getNode(o);d&&Array.isArray(d.content)&&(s=d.content.indexOf(t))}const i={...n,stype:e,attributes:{...n.attributes||{},...r||{}}},a=this.dataStore.getActiveSchema();if(a){const d=this.dataStore.validateNode(i,a);if(!d.valid)return{valid:!1,errors:d.errors}}if(o&&s!==void 0){const d=this.dataStore.getNode(o);if(d&&Array.isArray(d.content)){const l=[...d.content];l.splice(s,1),this.dataStore.updateNode(o,{content:l},!1)}}if(this.setNode(i,!0),o&&s!==void 0){const d=this.dataStore.getNode(o);if(d&&Array.isArray(d.content)){const l=[...d.content];l.splice(s,0,t),this.dataStore.updateNode(o,{content:l},!1)}}return{valid:!0,errors:[],newNodeId:t}}}class Ee{constructor(t){this.dataStore=t}findNodes(t){const e=[];for(const[r,n]of this.dataStore.getNodes()){const o=this.dataStore.getNode(r);o&&t(o)&&e.push(o)}return e}findNodesByType(t){const e=[],r=this.dataStore.createDocumentIterator({filter:{stype:t}});for(const n of r){const o=this.dataStore.getNode(n);o&&e.push(o)}return e}findNodesByAttribute(t,e){return this.findNodes(r=>!!(r.attributes&&r.attributes[t]===e))}findNodesByText(t){return!t||t.trim()===""?[]:this.findNodes(e=>!!(e.text&&e.text.includes(t)))}findChildrenByParentId(t){const e=this.dataStore.getNode(t);return!e||!e.content?[]:e.content.map(r=>this.dataStore.getNode(r)).filter(r=>r!==void 0)}findRootNodes(){return this.findNodes(t=>!t.parentId)}searchText(t){if(!t||t.trim()==="")return[];const e=t.toLowerCase(),r=[];for(const[n,o]of this.dataStore.getNodes()){const s=this.dataStore.getNode(n);s&&s.text&&s.text.toLowerCase().includes(e)&&r.push(s)}return r}getNodeChildren(t){const e=this.dataStore.getNode(t);return!e||!e.content?[]:e.content.map(r=>this.dataStore.getNode(r)).filter(r=>r!==void 0)}getNodeChildrenDeep(t){const e=this.dataStore.getNode(t);return!e||!e.content?[]:e.content.map(r=>{const n=this.dataStore.getNode(r);return n?{...n,content:n.content?this.getNodeChildrenDeep(n.sid):n.content}:null}).filter(Boolean)}getNodeWithChildren(t){const e=this.dataStore.getNode(t);return e?{...e,content:this.getNodeChildrenDeep(t)}:null}getAllNodesWithChildren(){const t=[],e=this.dataStore.createDocumentIterator();for(const r of e){const n=this.getNodeWithChildren(r);n&&t.push(n)}return t}findNodesWithVisitor(t,e){const r=[];return this.dataStore.traverse({visit:(n,o)=>{const s=t(o,[n]);return s!==!1&&r.push(o),s}},e),r}findNodesByDepth(t,e){const r=[],n=this.dataStore.createDocumentIterator({maxDepth:t});for(const o of n){const s=this.dataStore.getNode(o);s&&(!e||e(s))&&r.push(s)}return r}}class Oe{constructor(t){this.dataStore=t}addChild(t,e,r){const n=this.dataStore._overlay,o=this.dataStore.getNode(t);if(!o){if(n&&n.isActive&&n.isActive())return typeof e=="string"?e:(e.sid||(e.sid=this.dataStore.generateId()),this.dataStore.setNode(e),e.sid);throw new Error(`Parent node not found: ${t}`)}let s,i;if(typeof e=="string"){s=e;const u=this.dataStore.getNode(s);if(!u)throw new Error(`Child node not found: ${s}`);i=u}else e.sid||(e.sid=this.dataStore.generateId()),s=e.sid,i=e,this.dataStore.setNode(i);const a=Array.isArray(o.content)?o.content:[],d=r!==void 0?r:a.length,l=[...a];return l.splice(d,0,s),this.dataStore.updateNode(t,{content:l},!1),o.content=l,this.dataStore.updateNode(s,{parentId:t},!1),i&&(i.parentId=t),s}removeChild(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Parent node not found: ${t}`);if(!this.dataStore.getNode(e))return!1;if(Array.isArray(r.content)){const o=r.content.indexOf(e);if(o>-1){const s=[...r.content];return s.splice(o,1),this.dataStore.updateNode(t,{content:s},!1),r.content=s,this.dataStore.updateNode(e,{parentId:void 0},!1),!0}}return!1}moveNode(t,e,r){const n=this.dataStore.getNode(t);if(!n)throw new Error(`Node not found: ${t}`);const o=this.dataStore._overlay,s=this.dataStore.getNode(e);if(!s){if(o&&o.isActive&&o.isActive())return;throw new Error(`Parent node not found: ${e}`)}if(n.parentId){const l=this.dataStore.getNode(n.parentId);if(l&&Array.isArray(l.content)){const u=l.content.indexOf(t);if(u>-1){const f=[...l.content];f.splice(u,1),this.dataStore.updateNode(l.sid,{content:f},!1),l.content=f}}}const i=Array.isArray(s.content)?s.content:[],a=r!==void 0?r:i.length,d=[...i];d.splice(a,0,t),this.dataStore.updateNode(e,{content:d},!1),s.content=d,this.dataStore.updateNode(t,{parentId:e},!1),n.parentId=e,this.dataStore.emitOperation({type:"move",nodeId:t,parentId:e,position:a,timestamp:Date.now()})}copyNode(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Node not found: ${t}`);const n=this.dataStore.generateId(),o={...r,sid:n,parentId:e||r.parentId};if(this.dataStore.setNode(o),e){const s=this.dataStore.getNode(e);if(s){const a=[...Array.isArray(s.content)?s.content:[],n];this.dataStore.updateNode(e,{content:a},!1),s.content=a}}return n}cloneNodeWithChildren(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Node not found: ${t}`);const n=this.dataStore.generateId(),o={...r,sid:n,parentId:e||r.parentId,content:[]};if(this.dataStore.setNode(o),r.content&&Array.isArray(r.content)){const s=[];for(const i of r.content)if(typeof i=="string"){const a=this.cloneNodeWithChildren(i,n);s.push(a)}o.content=s,this.dataStore.updateNode(o.sid,{content:s},!1)}if(e){const s=this.dataStore.getNode(e);if(s){const a=[...Array.isArray(s.content)?s.content:[],n];this.dataStore.updateNode(e,{content:a},!1),s.content=a}}return n}reorderChildren(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Parent node not found: ${t}`);for(const s of e)if(!this.dataStore.getNode(s))throw new Error(`Child node not found: ${s}`);const n=Array.isArray(r.content)?[...r.content]:[];this.dataStore.updateNode(t,{content:[...e]},!1),r.content=[...e];const o=new Map;e.forEach((s,i)=>o.set(s,i));for(let s=0;s<e.length;s++){const i=e[s];n.indexOf(i)!==s&&this.dataStore.emitOperation({type:"move",nodeId:i,parentId:t,position:s,timestamp:Date.now()})}}addChildren(t,e,r){var i;const n=this.dataStore.getNode(t);if(!n)throw new Error(`Parent node not found: ${t}`);const o=[],s=r!==void 0?r:((i=n.content)==null?void 0:i.length)||0;for(let a=0;a<e.length;a++){const d=e[a],l=this.addChild(t,d,s+a);o.push(l)}return o}removeChildren(t,e){if(!this.dataStore.getNode(t))throw new Error(`Parent node not found: ${t}`);const n=[];for(const o of e)n.push(this.removeChild(t,o));return n}moveChildren(t,e,r,n){if(!this.dataStore.getNode(t))throw new Error(`From parent node not found: ${t}`);const s=this.dataStore._overlay;if(!this.dataStore.getNode(e)){if(s&&s.isActive&&s.isActive())return;throw new Error(`To parent node not found: ${e}`)}for(const a of r)if(!this.dataStore.getNode(a))throw new Error(`Child node not found: ${a}`);for(let a=0;a<r.length;a++){const d=r[a],l=n!==void 0?n+a:void 0;this.moveNode(d,e,l)}}moveBlockUp(t){const e=this.dataStore.getNode(t);if(!e||!e.parentId)return!1;const r=this.dataStore.getNode(e.parentId);if(!r||!Array.isArray(r.content))return!1;const n=r.content.indexOf(t);if(n===-1||n===0)return!1;const o=[...r.content],[s]=o.splice(n,1);o.splice(n-1,0,s);const i=o.map(a=>typeof a=="string"?a:a.sid??"");return this.reorderChildren(e.parentId,i),!0}moveBlockDown(t){const e=this.dataStore.getNode(t);if(!e||!e.parentId)return!1;const r=this.dataStore.getNode(e.parentId);if(!r||!Array.isArray(r.content))return!1;const n=r.content.indexOf(t);if(n===-1||n===r.content.length-1)return!1;const o=[...r.content],[s]=o.splice(n,1);o.splice(n+1,0,s);const i=o.map(a=>typeof a=="string"?a:a.sid??"");return this.reorderChildren(e.parentId,i),!0}}class Te{constructor(t){this.dataStore=t}splitTextNode(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Node not found: ${t}`);if(typeof r.text!="string")throw new Error(`Node is not a text node: ${r.stype}`);const n=r.text||"";if(e<0||e>n.length)throw new Error(`Invalid split position: ${e}`);if(e===0||e===n.length)throw new Error(`Split position must be between 0 and ${n.length}`);const o=n.substring(0,e),s=n.substring(e),i=[],a=[];if(r.marks)for(const u of r.marks){const[f,h]=u.range||[0,n.length];f<e&&h>e?(i.push({...u,range:[f,e]}),a.push({...u,range:[0,h-e]})):h<=e?i.push({...u,range:[f,h]}):f>=e&&a.push({...u,range:[f-e,h-e]})}this.dataStore.updateNode(t,{text:o,marks:i},!1);const d={stype:r.stype,text:s,attributes:{...r.attributes},marks:a,parentId:r.parentId},l=this.dataStore.generateId();if(d.sid=l,this.dataStore.setNode(d,!1),r.parentId){const u=this.dataStore.getNode(r.parentId);if(u&&u.content){const f=u.content.indexOf(t);if(f!==-1){const h=[...u.content];h.splice(f+1,0,l),this.dataStore.updateNode(u.sid,{content:h},!1)}}}return l}mergeTextNodes(t,e){const r=this.dataStore.getNode(t),n=this.dataStore.getNode(e);if(!r||!n)throw new Error(`Node not found: ${t} or ${e}`);if(typeof r.text!="string")throw new Error(`Left node is not a text node: ${r.stype}`);if(typeof n.text!="string")throw new Error(`Right node is not a text node: ${n.stype}`);const o=r.text||"",s=n.text||"",i=o+s;if(r.marks&&(r.marks=r.marks.map(a=>({...a,range:a.range||[0,o.length]}))),n.marks){const a=o.length,d=n.marks.map(l=>({...l,range:l.range?[l.range[0]+a,l.range[1]+a]:[a,a+s.length]}));r.marks?r.marks.push(...d):r.marks=d}if(this.dataStore.updateNode(t,{text:i,marks:r.marks},!1),r.parentId){const a=this.dataStore.getNode(r.parentId);if(a&&a.content){const d=a.content.indexOf(e);if(d!==-1){const l=[...a.content];l.splice(d,1),this.dataStore.updateNode(a.sid,{content:l},!1)}}}return this.dataStore.deleteNode(e),t}splitBlockNode(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Node not found: ${t}`);if(!r.content||r.content.length===0)throw new Error(`Node has no content to split: ${t}`);if(e<0||e>r.content.length)throw new Error(`Invalid split position: ${e}`);if(e===0||e===r.content.length)throw new Error(`Split position must be between 0 and ${r.content.length}`);const n={stype:r.stype,attributes:{...r.attributes},content:[],parentId:r.parentId},o=this.dataStore.generateId();n.sid=o,this.dataStore.setNode(n,!1);const s=r.content.splice(e);n.content=s,this.dataStore.updateNode(o,{content:s},!1);for(const i of s)this.dataStore.getNode(i)&&this.dataStore.updateNode(i,{parentId:o},!1);if(this.dataStore.updateNode(t,{content:r.content},!1),r.parentId){const i=this.dataStore.getNode(r.parentId);if(i&&i.content){const a=i.content.indexOf(t);if(a!==-1){const d=[...i.content];d.splice(a+1,0,o),this.dataStore.updateNode(i.sid,{content:d},!1)}}}return o}mergeBlockNodes(t,e){const r=this.dataStore.getNode(t),n=this.dataStore.getNode(e);if(!r||!n)throw new Error(`Node not found: ${t} or ${e}`);if(r.stype!==n.stype)throw new Error(`Cannot merge different node types: ${r.stype} and ${n.stype}`);if(n.content&&n.content.length>0){r.content||(r.content=[]);for(const o of n.content)this.dataStore.getNode(o)&&this.dataStore.updateNode(o,{parentId:t},!1);r.content.push(...n.content)}return this.dataStore.updateNode(t,{content:r.content},!1),this.dataStore.deleteNode(e),t}splitTextRange(t,e,r){const n=this.dataStore.getNode(t);if(!n)throw new Error(`Node not found: ${t}`);if(typeof n.text!="string")throw new Error(`Node is not a text node: ${n.stype}`);const o=n.text||"";if(e<0||r>o.length||e>=r)throw new Error(`Invalid range: ${e}-${r}`);const s=this.splitTextNode(t,e);return this.splitTextNode(s,r-e),s}autoMergeTextNodes(t){const e=this.dataStore.getNode(t);if(!e||!e.parentId||typeof e.text!="string")return t;let r=this.dataStore.getNode(e.parentId);if(!r||!r.content)return t;let n=r.content.indexOf(t);if(n===-1)return t;let o=t;for(;n>0;){const s=r.content[n-1],i=this.dataStore.getNode(s);if(i&&typeof i.text=="string")if(o=this.mergeTextNodes(s,o),r=this.dataStore.getNode(e.parentId),r&&r.content){if(n=r.content.indexOf(o),n<=0)break}else break;else break}for(;;){const s=this.dataStore.getNode(e.parentId);if(!s||!s.content)break;const i=s.content.indexOf(o);if(i===-1||i>=s.content.length-1)break;const a=s.content[i+1],d=this.dataStore.getNode(a);if(d&&typeof d.text=="string")o=this.mergeTextNodes(o,a);else break}return o}deleteTextRange(t,e,r){const n=this.dataStore.getNode(t);if(!n)throw new Error(`Node not found: ${t}`);if(typeof n.text!="string")throw new Error(`Node is not a text node: ${n.stype}`);const o=n.text||"";if(e<0||r>o.length||e>=r)throw new Error(`Invalid range: [${e}, ${r}] for text of length ${o.length}`);const s=o.substring(e,r),i=r-e,a=o.substring(0,e)+o.substring(r);return n.text=a,n.marks&&(n.marks=n.marks.map(d=>{if(!d.range)return d;const[l,u]=d.range;if(l<r&&u>e){if(l>=e&&u<=r)return null;if(l<e&&u>r)return[{...d,range:[l,e]},{...d,range:[u-i,u-i]}];if(l<e&&u<=r)return{...d,range:[l,e]};if(l>=e&&u>r)return{...d,range:[l-i,u-i]}}else return l>=r?{...d,range:[l-i,u-i]}:d}).flat().filter(Boolean)),this.dataStore.setNodeInternal(n),s}replaceTextRange(t,e,r,n){const o=this.dataStore.getNode(t);if(!o)throw new Error(`Node not found: ${t}`);if(typeof o.text!="string")throw new Error(`Node is not a text node: ${o.stype}`);const s=o.text||"";if(e<0||r>s.length||e>r)throw new Error(`Invalid range: [${e}, ${r}] for text of length ${s.length}`);const i=s.substring(e,r),a=n.length-(r-e),d=s.substring(0,e)+n+s.substring(r);return o.text=d,o.marks&&(o.marks=o.marks.map(l=>{if(!l.range)return l;const[u,f]=l.range;if(u<r&&f>e){if(u>=e&&f<=r)return null;if(u<e&&f>r)return[{...l,range:[u,e]},{...l,range:[e+n.length,f-(r-e)+n.length]}];if(u<e&&f<=r)return{...l,range:[u,e]};if(u>=e&&f>r)return{...l,range:[e+n.length,f-(r-e)+n.length]}}else return u>=r?{...l,range:[u+a,f+a]}:l}).flat().filter(Boolean)),this.dataStore.setNodeInternal(o),i}insertText(t,e,r){const n=this.dataStore.getNode(t);if(!n)throw new Error(`Node not found: ${t}`);if(typeof n.text!="string")throw new Error(`Node is not a text node: ${n.stype}`);const o=n.text||"";if(e<0||e>o.length)throw new Error(`Invalid position: ${e} for text of length ${o.length}`);const s=o.substring(0,e)+r+o.substring(e);return n.text=s,n.marks&&(n.marks=n.marks.map(i=>{if(!i.range)return i;const[a,d]=i.range;return a>=e?{...i,range:[a+r.length,d+r.length]}:d>e?{...i,range:[a,d+r.length]}:i})),this.dataStore.setNodeInternal(n),r}}class Ce{constructor(t){this.dataStore=t}normalizeMarks(t){var u;const e=this.dataStore.getNode(t);if(!e)return;if(!e.marks||e.marks.length===0){this.dataStore.updateNode(e.sid,{marks:[]},!1);return}const r=((u=e.text)==null?void 0:u.length)||0;if(r===0){this.dataStore.updateNode(e.sid,{marks:[]},!1);return}const s=e.marks.map(f=>f.range?f:{...f,range:[0,r]}).map(f=>({...f,range:[Math.max(0,Math.min(f.range[0],r)),Math.max(0,Math.min(f.range[1],r))]})).filter(f=>f.range[0]<f.range[1]),i=this.removeDuplicateMarks(s),d=this.mergeOverlappingMarks(i).sort((f,h)=>f.range[0]-h.range[0]);this.dataStore.updateNode(e.sid,{marks:d},!1);const l=this.dataStore.getNode(e.sid);l&&(l.marks=d)}removeDuplicateMarks(t){const e=new Set;return t.filter(r=>{const n=r.range?`${r.stype}:${JSON.stringify(r.attrs||{})}:${r.range[0]}-${r.range[1]}`:`${r.stype}:${JSON.stringify(r.attrs||{})}:global`;return e.has(n)?!1:(e.add(n),!0)})}mergeOverlappingMarks(t){if(t.length<=1)return t;const e=t.filter(o=>o.range);if(e.length<=1)return e;const r=[];let n={...e[0]};for(let o=1;o<e.length;o++){const s=e[o];this.canMergeMarks(n,s)?n.range[1]>=s.range[0]?n.range[1]=Math.max(n.range[1],s.range[1]):(r.push(n),n={...s}):(r.push(n),n={...s})}return r.push(n),r}canMergeMarks(t,e){if(t.stype!==e.stype)return!1;const r=t.attrs||{},n=e.attrs||{},o=Object.keys(r),s=Object.keys(n);if(o.length!==s.length)return!1;for(const i of o)if(r[i]!==n[i])return!1;return!0}normalizeAllMarks(){const t=this.dataStore.getAllNodes();let e=0;for(const r of t)this.isTextNode(r)&&Array.isArray(r.marks)&&(this.normalizeMarks(r.sid),e++);return e}isTextNode(t){return typeof t.text=="string"}getMarkStatistics(t){const e=this.dataStore.getNode(t);if(!e||!e.marks)return{totalMarks:0,markTypes:{},overlappingMarks:0,emptyMarks:0};const r={};let n=0,o=0;for(const a of e.marks)r[a.stype]=(r[a.stype]||0)+1,(!a.range||a.range[0]>=a.range[1])&&o++;const s=e.marks.filter(a=>a.range&&a.range[0]<a.range[1]).sort((a,d)=>a.range[0]-d.range[0]),i=new Map;for(const a of s){const d=`${a.stype}:${JSON.stringify(a.attrs||{})}`;i.has(d)||i.set(d,[]),i.get(d).push(a)}for(const a of i.values())for(let d=0;d<a.length-1;d++){const l=a[d],u=a[d+1];l.range[1]>u.range[0]&&n++}return{totalMarks:e.marks.length,markTypes:r,overlappingMarks:n,emptyMarks:o}}removeEmptyMarks(t){var s;const e=this.dataStore.getNode(t);if(!e||!e.marks)return 0;const r=((s=e.text)==null?void 0:s.length)||0,n=e.marks.length,o=e.marks.filter(i=>i.range?i.range[0]<i.range[1]&&i.range[0]>=0&&i.range[1]<=r:!1);if(o.length!==n){this.dataStore.updateNode(e.sid,{marks:o},!1);const i=this.dataStore.getNode(e.sid);i&&(i.marks=o)}return n-o.length}setMarks(t,e,r={}){var i;const n=this.dataStore.getNode(t);if(!n)return{valid:!1,errors:[`Node not found: ${t}`]};const o=((i=n.text)==null?void 0:i.length)||0,s=r.normalize!==!1;try{let a=Array.isArray(e)?e.slice():[];if(s){const h=a.map(p=>p.range?p:{...p,range:[0,o]}).map(p=>({...p,range:[Math.max(0,Math.min(p.range[0],o)),Math.max(0,Math.min(p.range[1],o))]})).filter(p=>p.range[0]<p.range[1]),g=this.removeDuplicateMarks(h);a=this.mergeOverlappingMarks(g).sort((p,N)=>p.range[0]-N.range[0])}const d=this.dataStore.updateNode(t,{marks:a},!1),l=this.dataStore.getNode(t);return l&&(l.marks=a),!d||d.valid!==!0?{valid:!1,errors:(d==null?void 0:d.errors)||["Update failed"]}:{valid:!0,errors:[]}}catch(a){return{valid:!1,errors:[a instanceof Error?a.message:"Unknown error"]}}}removeMark(t,e,r){var u;const n=this.dataStore.getNode(t);if(!n)return{valid:!1,errors:[`Node not found: ${t}`]};const o=((u=n.text)==null?void 0:u.length)||0,[s,i]=r;if(s<0||i<0||s>o||i>o||s>i)return{valid:!1,errors:["Invalid range"]};const a=(n.marks||[]).filter(f=>f.stype!==e||!f.range?!0:!(f.range[0]===s&&f.range[1]===i)),d=this.dataStore.updateNode(t,{marks:a},!1),l=this.dataStore.getNode(t);return l&&(l.marks=a),!d||d.valid!==!0?{valid:!1,errors:(d==null?void 0:d.errors)||["Update failed"]}:{valid:!0,errors:[]}}updateMark(t,e,r,n){var u;const o=this.dataStore.getNode(t);if(!o)return{valid:!1,errors:[`Node not found: ${t}`]};const s=((u=o.text)==null?void 0:u.length)||0,[i,a]=r;if(i<0||a<0||i>s||a>s||i>=a)return{valid:!1,errors:["Invalid range"]};const d=(o.marks||[]).map(f=>f.stype===e&&f.range&&f.range[0]===i&&f.range[1]===a?{...f,attrs:{...f.attrs||{},...n||{}}}:f),l=this.dataStore.updateNode(t,{marks:d},!1);return!l||l.valid!==!0?{valid:!1,errors:(l==null?void 0:l.errors)||["Update failed"]}:{valid:!0,errors:[]}}toggleMark(t,e,r,n){var m,_;const o=this.dataStore.getNode(t);if(!o)return{valid:!1,errors:[`Node not found: ${t}`]};const s=((m=o.text)==null?void 0:m.length)||0,[i,a]=r;if(i<0||a<0||i>s||a>s||i>=a)return{valid:!1,errors:["Invalid range"]};const d=o.marks||[],[l,u]=r,f=[];let h=!1;for(const v of d){if(v.stype!==e||!v.range){f.push(v);continue}const[w,E]=v.range;if(E<=l||w>=u){f.push(v);continue}if(h=!0,!(w>=l&&E<=u)){if(w<l&&E>u){l>w&&f.push({...v,range:[w,l]}),E>u&&f.push({...v,range:[u,E]});continue}if(w<l&&E>l&&E<=u){f.push({...v,range:[w,l]});continue}if(w>=l&&w<u&&E>u){f.push({...v,range:[u,E]});continue}}}h||f.push({stype:e,attrs:n,range:r});const g=this.mergeOverlappingMarks(this.removeDuplicateMarks(f.filter(v=>!v.range||v.range[0]<v.range[1]).map(v=>{var w,E;return{...v,range:v.range||[0,((E=(w=this.dataStore.getNode(t))==null?void 0:w.text)==null?void 0:E.length)||0]}}))).sort((v,w)=>v.range[0]-w.range[0]),y=((_=this.dataStore.getNode(t))==null?void 0:_.marks)||[];if(JSON.stringify(y)===JSON.stringify(g))return{valid:!0,errors:[]};const N=this.dataStore.updateNode(t,{marks:g},!1),I=this.dataStore.getNode(t);return I&&(I.marks=g),!N||N.valid!==!0?{valid:!1,errors:(N==null?void 0:N.errors)||["Update failed"]}:{valid:!0,errors:[]}}}class Me{constructor(t){}adjustRanges(t,e,r){if(!t||t.length===0)return t;const{editPosition:n,insertedLength:o,deletedLength:s}=r,i=o-s,a=n+s;return t.map(d=>{if(d.target.sid!==e)return d;const{startOffset:l,endOffset:u}=d.target;return n<=l&&a>=u?{...d,target:{...d.target,startOffset:0,endOffset:0}}:n<=l?{...d,target:{...d.target,startOffset:l+i,endOffset:u+i}}:n<u?s>0&&a>l&&a<u?{...d,target:{...d.target,endOffset:u+i}}:{...d,target:{...d.target,endOffset:u+i}}:d}).filter(d=>{const{startOffset:l,endOffset:u}=d.target;return l>=0&&u>l})}}class Ae{constructor(){S(this,"behaviors",new Map)}register(t){(Array.isArray(t.targetType)?t.targetType:[t.targetType]).forEach(r=>{this.behaviors.has(r)||this.behaviors.set(r,[]),this.behaviors.get(r).push(t),this.behaviors.get(r).sort((n,o)=>(o.priority||0)-(n.priority||0))})}get(t,e,r,n,o){const s=this.behaviors.get(t)||[],i=this.behaviors.get("*")||[],a=[...s,...i];for(const d of a){if(d.sourceType){const l=Array.isArray(d.sourceType)?d.sourceType:[d.sourceType];if(!l.includes(e)&&!l.includes("*"))continue}if(typeof d.behavior=="function"){if(r&&n){const l=d.behavior(r,n,o||{});if(l!==null)return l;continue}}else return d.behavior}return null}clear(){this.behaviors.clear()}}const De=new Ae;class Re{constructor(t){this.dataStore=t}hasNode(t){return!!this.dataStore.getNode(t)}getChildCount(t){const e=this.dataStore.getNode(t);return!e||!e.content?0:e.content.length}isLeafNode(t){return this.getChildCount(t)===0}isRootNode(t){return this.dataStore.getRootNodeId()===t}getChildren(t){const e=this.dataStore.getNode(t);return!e||!e.content?[]:e.content.map(r=>this.dataStore.getNode(r)).filter(r=>r!==void 0)}getParent(t){const e=this.dataStore.getNode(t);if(!(!e||!e.parentId))return this.dataStore.getNode(e.parentId)}getSiblings(t){const e=this.getParent(t);return e?this.getChildren(e.sid).filter(r=>r.sid!==t):[]}getSiblingIndex(t){const e=this.getParent(t);return!e||!e.content?-1:e.content.findIndex(r=>r===t)}getPreviousSibling(t){const e=this.getParent(t);if(!e||!e.content)return null;const r=e.content.indexOf(t);return r<=0?null:e.content[r-1]}getNextSibling(t){const e=this.getParent(t);if(!e||!e.content)return null;const r=e.content.indexOf(t);return r===-1||r>=e.content.length-1?null:e.content[r+1]}getFirstChild(t){const e=this.dataStore.getNode(t);return!e||!e.content||e.content.length===0?null:e.content[0]}getLastChild(t){const e=this.dataStore.getNode(t);return!e||!e.content||e.content.length===0?null:e.content[e.content.length-1]}getFirstSibling(t){const e=this.getParent(t);return!e||!e.content||e.content.length===0?null:e.content[0]}getLastSibling(t){const e=this.getParent(t);return!e||!e.content||e.content.length===0?null:e.content[e.content.length-1]}getCommonAncestor(t,e){const r=this.dataStore.getNode(t),n=this.dataStore.getNode(e);if(!r||!n)return null;if(t===e)return t;const o=new Set;let s=t;for(;s;){o.add(s);const i=this.dataStore.getNode(s);s=i==null?void 0:i.parentId}for(s=e;s;){if(o.has(s))return s;const i=this.dataStore.getNode(s);s=i==null?void 0:i.parentId}return null}getDistance(t,e){const r=this.dataStore.getNode(t),n=this.dataStore.getNode(e);if(!r||!n)return-1;if(t===e)return 0;const o=this.getCommonAncestor(t,e);if(!o)return-1;let s=0,i=t;for(;i&&i!==o;){s++;const d=this.dataStore.getNode(i);i=d==null?void 0:d.parentId}let a=0;for(i=e;i&&i!==o;){a++;const d=this.dataStore.getNode(i);i=d==null?void 0:d.parentId}return s+a}getNodePath(t){const e=[];let r=t;for(;r;){const n=this.dataStore.getNode(r);if(!n)return[];e.unshift(r),r=n.parentId}return e}getNodeDepth(t){return this.getNodePath(t).length-1}isDescendant(t,e){return this.getNodePath(t).includes(e)}getAllDescendants(t){const e=[],r=this.getChildren(t);for(const n of r)e.push(n),e.push(...this.getAllDescendants(n.sid));return e}getAllAncestors(t){const e=[];let r=t;for(;r;){const n=this.dataStore.getNode(r);if(n!=null&&n.parentId){const o=this.dataStore.getNode(n.parentId);o&&e.unshift(o)}r=n==null?void 0:n.parentId}return e}getNodeCount(){let t=0;for(const[e,r]of this.dataStore.getNodes())this.dataStore.getNode(e)&&t++;return t}getAllNodes(){const t=[];for(const[e,r]of this.dataStore.getNodes()){const n=this.dataStore.getNode(e);n&&t.push(n)}return t}getAllNodesMap(){if(!this.dataStore.getRootNodeId())return new Map(this.dataStore.getNodes());const e=new Map,r=this.createDocumentIterator();for(const n of r){const o=this.dataStore.getNode(n);o&&e.set(n,o)}return e}restoreFromSnapshot(t,e,r=1){this.dataStore.clear();for(const[n,o]of t)this.dataStore.getNodes().set(n,o);this.dataStore.setRootNodeId(e),this.dataStore.version=r}clone(){const t=this.dataStore._activeSchema,e=typeof this.dataStore.getSessionId=="function"?this.dataStore.getSessionId():0,r=new this.dataStore.constructor(this.dataStore.getRootNodeId(),t,e);for(const[n,o]of this.dataStore.getNodes()){let s;if(typeof globalThis.structuredClone=="function")s=globalThis.structuredClone(o);else{const i=o.marks?o.marks.map(a=>({stype:a.stype,attrs:a.attrs?{...a.attrs}:void 0,range:Array.isArray(a.range)?[a.range[0],a.range[1]]:void 0})):void 0;s={sid:o.sid,stype:o.stype,parentId:o.parentId,text:o.text,attributes:o.attributes?{...o.attributes}:void 0,metadata:o.metadata?{...o.metadata}:void 0,content:o.content?[...o.content]:void 0,marks:i}}r.nodes.set(n,s)}return r}compareDocumentOrder(t,e){if(t===e)return 0;const r=this.getNodePath(t),n=this.getNodePath(e);if(!r.length)throw new Error(`Node not found: ${t}`);if(!n.length)throw new Error(`Node not found: ${e}`);let o=0;const s=Math.min(r.length,n.length);for(let h=0;h<s&&r[h]===n[h];h++)o=h;if(o===0&&r[0]!==n[0])throw new Error("Nodes are not in the same document tree");const i=o+1,a=o+1;if(i>=r.length)return-1;if(a>=n.length)return 1;const d=r[o],l=this.dataStore.getNode(d);if(!l||!l.content)throw new Error(`Parent node not found or has no content: ${d}`);const u=l.content.indexOf(r[i]),f=l.content.indexOf(n[a]);if(u===-1||f===-1)throw new Error("Child node not found in parent content");return u-f}getNextNode(t){const e=this.dataStore.getNode(t);if(!e)throw new Error(`Node not found: ${t}`);if(e.content&&e.content.length>0)return e.content[0];const r=this.getParent(t);if(r&&r.content){const n=r.content.indexOf(t);if(n!==-1&&n<r.content.length-1)return r.content[n+1]}if(r){const n=this._getNextSiblingOnly(r.sid);if(n)return n}return null}_getNextSiblingOnly(t){const e=this.getParent(t);if(e&&e.content){const r=e.content.indexOf(t);if(r!==-1&&r<e.content.length-1)return e.content[r+1]}return e?this._getNextSiblingOnly(e.sid):null}getPreviousNode(t){if(!this.dataStore.getNode(t))throw new Error(`Node not found: ${t}`);const r=this.getParent(t);if(r&&r.content){const n=r.content.indexOf(t);if(n>0){const o=r.content[n-1];return this._getLastDescendant(o)}}return r?r.sid:null}_getLastDescendant(t){const e=this.dataStore.getNode(t);if(!e||!e.content||e.content.length===0)return t;const r=e.content[e.content.length-1];return this._getLastDescendant(r)}getEditableNodes(t){var i;const{filter:e,includeText:r=!0,includeInline:n=!0,includeEditableBlocks:o=!0}=t||{},s=[];for(const[a,d]of this.dataStore.getNodes()){if(!this._isEditableNode(a))continue;const l=this.dataStore._activeSchema;if(l){const u=(i=l.getNodeType)==null?void 0:i.call(l,d.stype);if(u){const f=u.group,h=d.text!==void 0&&typeof d.text=="string",g=f==="block"&&u.editable===!0&&h,y=f==="inline";if(g){if(!o)continue}else if(h&&!r||y&&!h&&!n)continue}}e&&!e(d)||s.push(d)}return s}filterEditableNodes(t){return t.filter(e=>this._isEditableNode(e))}filterSelectableNodes(t){return t.filter(e=>this._isSelectableNode(e))}_isSelectableNode(t){var n;const e=this.dataStore.getNode(t);if(!e)return!1;const r=this.dataStore._activeSchema;if(r)try{const o=(n=r.getNodeType)==null?void 0:n.call(r,e.stype);if(o)return!(o.group==="document"||o.selectable===!1)}catch{}return e.stype!=="document"}getSelectableNodes(t){var i;const{filter:e,includeBlocks:r=!0,includeInline:n=!0,includeEditable:o=!0}=t||{},s=[];for(const[a,d]of this.dataStore.getNodes()){if(!this._isSelectableNode(a))continue;const l=this.dataStore._activeSchema;let u=!0;if(l){const f=(i=l.getNodeType)==null?void 0:i.call(l,d.stype);if(f){const h=f.group,g=h==="block",y=h==="inline",p=this._isEditableNode(a);(r||n||o)&&(u=!1,r&&g&&(u=!0),n&&y&&(u=!0),o&&p&&(u=!0))}}u&&(e&&!e(d)||s.push(d))}return s}_isDraggableNode(t){var n;const e=this.dataStore.getNode(t);if(!e)return!1;const r=this.dataStore._activeSchema;if(r)try{const o=(n=r.getNodeType)==null?void 0:n.call(r,e.stype);if(o)return!(o.group==="document"||o.draggable===!1)}catch{}return e.stype!=="document"}getDraggableNodes(t){var i;const{filter:e,includeBlocks:r=!0,includeInline:n=!0,includeEditable:o=!0}=t||{},s=[];for(const[a,d]of this.dataStore.getNodes()){if(!this._isDraggableNode(a))continue;const l=this.dataStore._activeSchema;let u=!0;if(l){const f=(i=l.getNodeType)==null?void 0:i.call(l,d.stype);if(f){const h=f.group,g=h==="block",y=h==="inline",p=this._isEditableNode(a);(r||n||o)&&(u=!1,r&&g&&(u=!0),n&&y&&(u=!0),o&&p&&(u=!0))}}u&&(e&&!e(d)||s.push(d))}return s}filterDraggableNodes(t){return t.filter(e=>this._isDraggableNode(e))}_isDroppableNode(t){var n;const e=this.dataStore.getNode(t);if(!e)return!1;const r=this.dataStore._activeSchema;if(r)try{const o=(n=r.getNodeType)==null?void 0:n.call(r,e.stype);if(o)return o.droppable===!1?!1:!!o.content}catch{}return e.content!==void 0}canDropNode(t,e){var s,i;if(!this._isDroppableNode(t)||!this._isDraggableNode(e))return!1;const r=this.dataStore._activeSchema;if(!r)return!0;const n=this.dataStore.getNode(t),o=this.dataStore.getNode(e);if(!n||!o)return!1;try{const a=(s=r.getNodeType)==null?void 0:s.call(r,n.stype),d=(i=r.getNodeType)==null?void 0:i.call(r,o.stype);if(!a||!d)return!1;const l=a.content;if(!l)return!1;const u=d.group,f=o.stype,h=l.toLowerCase();return!!(u&&h.includes(u)||h.includes(f))}catch{return!1}}getDroppableNodes(t){var i;const{filter:e,includeBlocks:r=!0,includeInline:n=!1,includeDocument:o=!0}=t||{},s=[];for(const[a,d]of this.dataStore.getNodes()){if(!this._isDroppableNode(a))continue;const l=this.dataStore._activeSchema;let u=!0;if(l){const f=(i=l.getNodeType)==null?void 0:i.call(l,d.stype);if(f){const h=f.group,g=h==="block",y=h==="inline",p=h==="document";(r||n||o)&&(u=!1,r&&g&&(u=!0),n&&y&&(u=!0),o&&p&&(u=!0))}}u&&(e&&!e(d)||s.push(d))}return s}filterDroppableNodes(t){return t.filter(e=>this._isDroppableNode(e))}_isIndentableNode(t){var n;const e=this.dataStore.getNode(t);if(!e)return!1;const r=this.dataStore._activeSchema;if(!r)return!1;try{const o=(n=r.getNodeType)==null?void 0:n.call(r,e.stype);return!o||o.group==="document"?!1:o.indentable===!0}catch{return!1}}getIndentMetadata(t){var o;const e=this.dataStore.getNode(t);if(!e)return null;const r=this.dataStore._activeSchema;if(!r)return null;const n=(o=r.getNodeType)==null?void 0:o.call(r,e.stype);return n?{indentable:n.indentable===!0,indentGroup:n.indentGroup,indentParentTypes:n.indentParentTypes,maxIndentLevel:n.maxIndentLevel}:null}isEditableNode(t){return this._isEditableNode(t)}isSelectableNode(t){return this._isSelectableNode(t)}isDraggableNode(t){return this._isDraggableNode(t)}isDroppableNode(t){return this._isDroppableNode(t)}isIndentableNode(t){return this._isIndentableNode(t)}indentNode(t){var l;if(!this.dataStore.getNode(t))return!1;const r=this.dataStore._activeSchema;if(!r)return!1;const n=this.getIndentMetadata(t);if(!n||!n.indentable||typeof n.maxIndentLevel=="number"&&this._getIndentDepth(t,n.indentGroup)>=n.maxIndentLevel)return!1;const o=this.getPreviousSibling(t);if(!o)return!1;const s=this.dataStore.getNode(o);if(!s||!((l=r.getNodeType)==null?void 0:l.call(r,s.stype))||n.indentParentTypes&&n.indentParentTypes.length>0&&!n.indentParentTypes.includes(s.stype))return!1;const d=(Array.isArray(s.content)?s.content:[]).length;return this.dataStore.moveNode(t,o,d),!0}outdentNode(t){if(!this.dataStore.getNode(t)||!this.dataStore._activeSchema)return!1;const n=this.getIndentMetadata(t);if(!n||!n.indentable)return!1;const o=this.getParent(t);if(!o)return!1;const s=o.parentId?this.dataStore.getNode(o.parentId):void 0;if(!s)return!1;const i=Array.isArray(s.content)?s.content:[],a=i.indexOf(o.sid),d=a>=0?a+1:i.length;return this.dataStore.moveNode(t,s.sid,d),!0}_getIndentDepth(t,e){var s;let r=0,n=this.getParent(t);const o=this.dataStore._activeSchema;for(;n&&o;){const i=(s=o.getNodeType)==null?void 0:s.call(o,n.stype);if(!i)break;(i.indentable||e&&i.indentGroup===e)&&(r+=1),n=n.parentId?this.dataStore.getNode(n.parentId):void 0}return r}_isEditableNode(t){var n;const e=this.dataStore.getNode(t);if(!e)return!1;const r=this.dataStore._activeSchema;if(r)try{const o=(n=r.getNodeType)==null?void 0:n.call(r,e.stype);if(o){const s=o.group;if(s==="block"&&o.editable===!0)return e.text!==void 0&&typeof e.text=="string";if(s==="block"||s==="document")return!1;if(s==="inline")return!0}}catch{}return e.stype&&e.stype.startsWith("inline-")?!0:e.content&&e.text===void 0?!1:(e.text!==void 0&&typeof e.text=="string",!0)}getPreviousEditableNode(t){let e=t;const r=new Set;for(;e;){if(r.has(e))return console.warn("[UtilityOperations] getPreviousEditableNode: Circular reference detected",{nodeId:t,currentId:e}),null;r.add(e);const n=this.getPreviousNode(e);if(!n)return null;if(this._isEditableNode(n))return n;e=n}return null}getNextEditableNode(t){let e=t;const r=new Set;for(;e;){if(r.has(e))return console.warn("[UtilityOperations] getNextEditableNode: Circular reference detected",{nodeId:t,currentId:e}),null;r.add(e);const n=this.getNextNode(e);if(!n)return null;if(this._isEditableNode(n))return n;e=n}return null}createDocumentIterator(t={}){return new gt(this.dataStore,t)}traverse(...t){let e,r={};if(t.length===0)throw new Error("At least one visitor is required");if(Array.isArray(t[0]))e=t[0],r=t[1]||{};else{const n=t[t.length-1];n&&typeof n=="object"&&!("visit"in n)&&(n.context!==void 0||n.filter!==void 0||n.maxDepth!==void 0||n.reverse!==void 0||n.startNodeId!==void 0||n.customFilter!==void 0||n.shouldStop!==void 0||n.range!==void 0)?(e=t.slice(0,-1),r=n):e=t}return e.length===1?this._traverseSingleVisitor(e[0],r):e.map(n=>({visitor:n,result:this._traverseSingleVisitor(n,r)}))}_traverseSingleVisitor(t,e={}){const r=new gt(this.dataStore,e);let n=0,o=0,s=!1;for(const i of r){const a=this.dataStore.getNode(i);if(!a)continue;if(t.enter&&t.enter(i,a,e.context),t.shouldVisitChildren&&!t.shouldVisitChildren(i,a)){o++,t.exit&&t.exit(i,a,e.context);continue}if(t.visit(i,a,e.context)===!1){o++,t.exit&&t.exit(i,a,e.context);continue}if(n++,e.shouldStop&&e.shouldStop(i,a)){s=!0,t.exit&&t.exit(i,a,e.context);break}t.exit&&t.exit(i,a,e.context)}return{visitedCount:n,skippedCount:o,stopped:s}}_getDefaultDropBehavior(t,e,r){var o,s;if(typeof t.text=="string"&&typeof e.text=="string")return"merge";const n=this.dataStore._activeSchema;if(n){const i=(o=n.getNodeType)==null?void 0:o.call(n,t.stype),a=(s=n.getNodeType)==null?void 0:s.call(n,e.stype);if(i&&a){if(i.group==="block"&&a.group==="inline"&&typeof e.text=="string")return"merge";if(i.group==="block"&&a.group==="block"&&t.stype===e.stype)return"move"}}return"move"}getDropBehavior(t,e,r){var l,u,f;const n=this.dataStore.getNode(t),o=this.dataStore.getNode(e);if(!n||!o)return"move";const s=this.dataStore._activeSchema,i=o.stype,a=r||{};if((l=a.modifiers)!=null&&l.ctrlKey||(u=a.modifiers)!=null&&u.metaKey)return"copy";if(a.sourceOrigin==="external")return"insert";const d=De.get(n.stype,i,n,o,a);if(d!==null)return d;if(s){const h=(f=s.getNodeType)==null?void 0:f.call(s,n.stype);if(h!=null&&h.dropBehaviorRules){const g=h.dropBehaviorRules;if(g[i])return g[i];if(g["*"])return g["*"]}}return this._getDefaultDropBehavior(n,o,a)}}class gt{constructor(t,e={}){S(this,"currentId");S(this,"visited",new Set);S(this,"options");S(this,"rangeStartId",null);S(this,"rangeEndId",null);this.dataStore=t,this.options={startNodeId:e.startNodeId||this.dataStore.getRootNodeId(),reverse:e.reverse||!1,maxDepth:e.maxDepth||1/0,filter:e.filter||{},customFilter:e.customFilter||(()=>!0),shouldStop:e.shouldStop||(()=>!1),range:e.range},this.options.range&&(this.rangeStartId=this.options.range.startNodeId,this.rangeEndId=this.options.range.endNodeId),this.options.reverse?this.currentId=this.findLastNode():this.currentId=this.options.startNodeId}[Symbol.iterator](){return this}next(){for(;this.currentId;){const t=this.dataStore.getNode(this.currentId);if(!t){this.currentId=this.getNextNode();continue}if(!this.isInRange(this.currentId)){this.currentId=this.getNextNode();continue}if(this.visited.has(this.currentId)){this.currentId=this.getNextNode();continue}if(this.dataStore.getNodePath(this.currentId).length>this.options.maxDepth){this.currentId=this.getNextNode();continue}if(!this.matchesTypeFilter(t)){this.currentId=this.getNextNode();continue}if(!this.options.customFilter(this.currentId,t)){this.currentId=this.getNextNode();continue}if(this.options.shouldStop(this.currentId,t)){this.currentId=null;break}this.visited.add(this.currentId);const r=this.currentId;return this.currentId=this.getNextNode(),{value:r,done:!1}}return{value:void 0,done:!0}}getNextNode(){return this.currentId?this.options.reverse?this.dataStore.utility.getPreviousNode(this.currentId):this.dataStore.utility.getNextNode(this.currentId):null}matchesTypeFilter(t){const{filter:e}=this.options,r=t.stype,o=(e||{}).stype;return!(o&&r!==o||e.stypes&&!e.stypes.includes(r)||e.excludeStypes&&e.excludeStypes.includes(r))}isInRange(t){if(!this.options.range||!this.rangeStartId||!this.rangeEndId)return!0;const{includeStart:e=!0,includeEnd:r=!0}=this.options.range;if(t===this.rangeStartId)return e;if(t===this.rangeEndId)return r;const n=this.dataStore.utility.compareDocumentOrder(t,this.rangeStartId),o=this.dataStore.utility.compareDocumentOrder(t,this.rangeEndId);return!(n<0||o>0)}reset(){this.currentId=this.options.startNodeId,this.visited.clear()}startFrom(t){this.currentId=t,this.visited.clear()}updateOptions(t){this.options={...this.options,...t}}toArray(){const t=[];for(const e of this)t.push(e);return t}find(t){for(const e of this){const r=this.dataStore.getNode(e);if(t(e,r))return e}return null}findAll(t){const e=[];for(const r of this){const n=this.dataStore.getNode(r);t(r,n)&&e.push(r)}return e}takeWhile(t){const e=[];for(const r of this){const n=this.dataStore.getNode(r);if(!t(r,n))break;e.push(r)}return e}getStats(){const t={total:0,byType:{},byDepth:{}};for(const e of this){const r=this.dataStore.getNode(e),n=this.dataStore.getNodePath(e).length;t.total++;const o=r.stype||"unknown";t.byType[o]=(t.byType[o]||0)+1,t.byDepth[n]=(t.byDepth[n]||0)+1}return t}findLastNode(){let t=this.options.startNodeId,e=t;for(;t;)e=t,t=this.dataStore.utility.getNextNode(t);return e}getNodesInRange(){if(!this.options.range)return this.toArray();const t=[];for(const e of this)t.push(e);return t}getRangeNodeCount(){if(!this.options.range)return this.getStats().total;let t=0;for(const e of this)t++;return t}getRangeInfo(){return this.options.range?{start:this.options.range.startNodeId,end:this.options.range.endNodeId,includeStart:this.options.range.includeStart??!0,includeEnd:this.options.range.includeEnd??!0}:null}}class $e{constructor(t){this.dataStore=t}processNodeInModelSelection(t,e,r){const n=this.dataStore.getNode(t);if(!n||typeof n.text!="string")return null;const o=n.text;let s=0,i=o.length;if(t===e.startNodeId&&(s=e.startOffset),t===e.endNodeId&&(i=e.endOffset),s>=i||s<0||i>o.length)return null;const a=o.substring(s,i);if(r==="delete"){const d=o.substring(0,s)+o.substring(i);this.dataStore.updateNode(t,{text:d})}return a}deleteText(t){if(t.startNodeId===t.endNodeId){const r=t.startNodeId,n=this.dataStore.getNode(r);if(!n||typeof n.text!="string")return"";const o=n.text,s=t.startOffset,i=t.endOffset;if(typeof s!="number"||typeof i!="number"||s>i||s<0||i>o.length)return"";const a=o.substring(s,i),d=o.substring(0,s)+o.substring(i);let l=n.marks?[...n.marks]:[];if(l&&l.length>0){const u=-(i-s),f=[];for(const h of l){const[g,y]=h.range||[0,o.length];if(y<=s){f.push({...h});continue}if(g>=i){f.push({...h,range:[g+u,y+u]});continue}const p=g<s&&y>s&&y<=i,N=g>=s&&g<i&&y>i,I=g>=s&&y<=i,m=g<s&&y>i;if(!I){if(p){f.push({...h,range:[g,s]});continue}if(N){const _=s;f.push({...h,range:[_,y+u]});continue}if(m){f.push({...h,range:[g,s]}),f.push({...h,range:[s,y+u]});continue}}}l=f}return this.dataStore.updateNode(r,{text:d,marks:l}),a}let e="";if(t.startNodeId!==t.endNodeId){const r=this.dataStore.getNode(t.startNodeId);if(r&&typeof r.text=="string"){const n=r.text,o=t.startOffset;if(o<n.length){const s=n.substring(o);e+=s;const i=n.substring(0,o);let a=r.marks?[...r.marks]:[];if(a&&a.length>0){const d=[];for(const l of a){const[u,f]=l.range||[0,n.length];if(f<=o){d.push({...l});continue}u>=o||d.push({...l,range:[u,o]})}a=d}this.dataStore.updateNode(t.startNodeId,{text:i,marks:a})}}}if(t.startNodeId!==t.endNodeId){const r=this.dataStore.getNode(t.startNodeId),n=this.dataStore.getNode(t.endNodeId);if(r&&n&&r.parentId===n.parentId&&r.parentId){const o=this.dataStore.getNode(r.parentId);if(o&&o.content&&Array.isArray(o.content)){const s=o.content.indexOf(t.startNodeId),i=o.content.indexOf(t.endNodeId);if(s!==-1&&i!==-1&&s<i)for(let a=s+1;a<i;a++){const d=o.content[a],l=this.dataStore.getNode(d);l&&typeof l.text=="string"&&(e+=l.text,this.dataStore.updateNode(d,{text:"",marks:[]}))}}}else{const o=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!1,includeEnd:!1});for(const s of o){const i=this.dataStore.getNode(s);i&&typeof i.text=="string"&&(e+=i.text,this.dataStore.updateNode(s,{text:"",marks:[]}))}}}if(t.startNodeId!==t.endNodeId){const r=this.dataStore.getNode(t.endNodeId);if(r&&typeof r.text=="string"){const n=r.text,o=t.endOffset;if(o>0){const s=n.substring(0,o);e+=s;const i=n.substring(o);let a=r.marks?[...r.marks]:[];if(a&&a.length>0){const d=-o,l=[];for(const u of a){const[f,h]=u.range||[0,n.length];if(f>=o){l.push({...u,range:[f+d,h+d]});continue}h<=o||l.push({...u,range:[0,h+d]})}a=l}this.dataStore.updateNode(t.endNodeId,{text:i,marks:a})}}}return e}extractText(t){const e=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let r="";for(const n of e){const o=this.dataStore.getNode(n);if(o&&o.text){const s=this.processNodeInModelSelection(n,t,"extract");s&&(r+=s)}}return r}insertText(t,e){if(t.startNodeId!==t.endNodeId||t.startOffset!==t.endOffset)throw new Error("insertText는 같은 위치 범위에서만 사용할 수 있습니다");const r=t.startNodeId,n=this.dataStore.getNode(r);if(!n||typeof n.text!="string")return e;const o=n.text,s=t.startOffset;if(typeof s!="number"||s<0||s>o.length)return e;const i=o.substring(0,s)+e+o.substring(s);let a=n.marks?[...n.marks]:[];if(a&&a.length>0){const d=e.length,l=[];for(const u of a){const[f,h]=u.range||[0,o.length];if(h<=s){l.push({...u});continue}if(f>=s){l.push({...u,range:[f+d,h+d]});continue}l.push({...u,range:[f,h+d]})}a=l}return this.dataStore.updateNode(r,{text:i,marks:a}),e}deleteRange(t){this.deleteText(t)}replaceText(t,e){if(t.startNodeId===t.endNodeId){const o=t.startNodeId,s=this.dataStore.getNode(o);if(!s||typeof s.text!="string")return console.warn("[RangeOperations.replaceText] Invalid node or not a text node",{nodeId:o,hasNode:!!s,textType:typeof(s==null?void 0:s.text)}),"";const i=s.text,a=t.startOffset,d=t.endOffset;if(typeof a!="number"||typeof d!="number")return console.warn("[RangeOperations.replaceText] Invalid offsets",{start:a,end:d}),"";if(a>d||a<0||d>i.length)return console.warn("[RangeOperations.replaceText] Invalid range",{start:a,end:d,textLength:i.length}),"";const l=i.substring(a,d),u=e.length-(d-a),f=i.substring(0,a)+e+i.substring(d);let h=s.marks?[...s.marks]:[];if(h&&h.length>0){const g=[];for(const y of h){if(!y.range||y.range===null||y.range===void 0){g.push({...y});continue}const[p,N]=y.range;if(N<=a){g.push({...y});continue}if(p>=d){g.push({...y,range:[p+u,N+u]});continue}const I=p<a&&N>a&&N<=d,m=p>=a&&p<d&&N>d,_=p>=a&&N<=d,v=p<a&&N>d;if(!_){if(I){g.push({...y,range:[p,a]});continue}if(m){const w=a+e.length,E=N+u;E>w&&g.push({...y,range:[w,E]});continue}if(v){if(a===d){g.push({...y,range:[p,N+u]});continue}if(u>=-1){g.push({...y,range:[p,N+u]});continue}const w={...y,range:[p,a]},E=a+e.length,A=N+u,F={...y,range:[E,A]};g.push(w),A>E&&g.push(F);continue}}}h=g}return this.dataStore.updateNode(o,{text:f},!1),h.length>0?this.dataStore.marks.setMarks(o,h,{normalize:!0}):this.dataStore.marks.setMarks(o,[],{normalize:!0}),l}const r=this.deleteText(t),n={type:"range",startNodeId:t.startNodeId,startOffset:t.startOffset,endNodeId:t.startNodeId,endOffset:t.startOffset};return this.insertText(n,e),r}copyText(t){return this.extractText(t)}moveText(t,e){const r=this.extractText(t);this.deleteText(t);let n={...e};if(t.startNodeId===t.endNodeId&&e.startNodeId===e.endNodeId&&e.startNodeId===t.startNodeId){const o=Math.max(0,t.endOffset-t.startOffset),s=e.startOffset;let i=s;s>t.endOffset&&(i=s-o);const a=this.dataStore.getNode(e.startNodeId),d=typeof(a==null?void 0:a.text)=="string"?a.text.length:0;i>d&&(i=d),i<0&&(i=0),n={type:"range",startNodeId:e.startNodeId,startOffset:i,endNodeId:e.endNodeId,endOffset:i}}return this.insertText(n,r),r}duplicateText(t){const e=this.extractText(t),r={type:"range",startNodeId:t.endNodeId,startOffset:t.endOffset,endNodeId:t.endNodeId,endOffset:t.endOffset};return this.insertText(r,e),e}applyMark(t,e){const{startNodeId:r,startOffset:n,endNodeId:o,endOffset:s}=t;if(r===o){const l=this.dataStore.getNode(r);if(!l||typeof l.text!="string")return e;const u=l.text,f=Math.max(0,Math.min(n,u.length)),h=Math.max(0,Math.min(s,u.length));if(f>=h)return e;const g={...e,range:[f,h]},y=[...l.marks||[],g];return this.dataStore.marks.setMarks(r,y,{normalize:!0}),e}const a=this.dataStore.getNode(r),d=this.dataStore.getNode(o);if(a&&typeof a.text=="string"){const l=Math.max(0,Math.min(n,a.text.length)),u=a.text.length;if(l<u){const f={...e,range:[l,u]},h=[...a.marks||[],f];this.dataStore.marks.setMarks(r,h,{normalize:!0})}}if(d&&typeof d.text=="string"){const u=Math.max(0,Math.min(s,d.text.length));if(0<u){const f={...e,range:[0,u]},h=[...d.marks||[],f];this.dataStore.marks.setMarks(o,h,{normalize:!0})}}return e}toggleMark(t,e,r){const{startNodeId:n,startOffset:o,endNodeId:s,endOffset:i}=t;if(n===s){this.dataStore.marks.toggleMark(n,e,[o,i],r);return}const a=this.dataStore.getNode(n);a&&typeof a.text=="string"&&this.dataStore.marks.toggleMark(n,e,[o,a.text.length],r);const d=this.dataStore.getNode(s);d&&typeof d.text=="string"&&this.dataStore.marks.toggleMark(s,e,[0,Math.min(i,d.text.length)],r)}removeMark(t,e){const r=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let n=0;for(const o of r){const s=this.dataStore.getNode(o);if(!s||!s.text||!s.marks)continue;const i=s.text;let a=0,d=i.length;if(o===t.startNodeId&&(a=t.startOffset),o===t.endNodeId&&(d=t.endOffset),a>=d)continue;const l=s.marks.filter(f=>{if(f.stype!==e)return!0;const[h,g]=f.range||[0,i.length];return g<=a||h>=d});n+=s.marks.length-l.length,this.dataStore.updateNode(o,{marks:l},!1);const u=this.dataStore.getNode(o);u&&(u.marks=l)}return n}clearFormatting(t){const e=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let r=0;for(const n of e){const o=this.dataStore.getNode(n);if(!o||!o.text||!o.marks)continue;const s=o.text;let i=0,a=s.length;if(n===t.startNodeId&&(i=t.startOffset),n===t.endNodeId&&(a=t.endOffset),i>=a)continue;const d=o.marks.filter(u=>{const[f,h]=u.range||[0,s.length];return h<=i||f>=a});r+=o.marks.length-d.length,this.dataStore.updateNode(n,{marks:d},!1);const l=this.dataStore.getNode(n);l&&(l.marks=d)}return r}constrainMarksToRange(t){const e=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let r=0;for(const n of e){const o=this.dataStore.getNode(n);if(!o||!o.text||!o.marks||o.marks.length===0)continue;const s=o.text;let i=0,a=s.length;if(n===t.startNodeId&&(i=t.startOffset),n===t.endNodeId&&(a=t.endOffset),i>=a)continue;const d=[];for(const u of o.marks){const[f,h]=u.range||[0,s.length],g=Math.max(f,i),y=Math.min(h,a);if(y<=g){r+=1;continue}(g!==f||y!==h)&&(r+=1),d.push({...u,range:[g,y]})}this.dataStore.updateNode(n,{marks:d},!1);const l=this.dataStore.getNode(n);l&&(l.marks=d)}return r}findText(t,e){const r=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let n=0;for(const o of r){const s=this.dataStore.getNode(o);if(s&&s.text){const i=s.text;let a=0,d=i.length;if(o===t.startNodeId&&(a=t.startOffset),o===t.endNodeId&&(d=t.endOffset),a<d){const l=i.substring(a,d).indexOf(e);if(l!==-1)return n+a+l}n+=i.length}}return-1}getTextLength(t){const e=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let r=0;for(const n of e){const o=this.dataStore.getNode(n);if(o&&o.text){const s=o.text;let i=0,a=s.length;n===t.startNodeId&&(i=t.startOffset),n===t.endNodeId&&(a=t.endOffset),i<a&&(r+=a-i)}}return r}trimText(t){const e=this.extractText(t),r=e.trim();if(e===r)return 0;const n=e.length-e.trimStart().length,o=e.length-e.trimEnd().length,s=n+o;return this.replaceText(t,r),s}normalizeWhitespace(t){const e=this.extractText(t),r=e.replace(/\s+/g," ").replace(/^\s+|\s+$/g,"");return e===r||this.replaceText(t,r),r}wrap(t,e,r){const n=this.extractText(t),o=`${e}${n}${r}`;return this.replaceText(t,o),o}unwrap(t,e,r){const n=t.startNodeId===t.endNodeId,o=n?this.dataStore.getNode(t.startNodeId):void 0,s=typeof(o==null?void 0:o.text)=="string"?o.text:"",i=this.extractText(t),a=i.startsWith(e),d=i.endsWith(r);let l=t.startOffset,u=t.endOffset,f=!1,h=!1;if(n&&s){!a&&(l>=e.length&&s.substring(l-e.length,l)===e||l===0&&s.startsWith(e))&&(f=!0);const I=u+(a||f?e.length:0);!d&&I+r.length<=s.length&&s.substring(I,I+r.length)===r&&(h=!0)}let g=l,y=u;if(n&&s){f&&(g=Math.max(0,l-e.length));const I=u+(a||f?e.length:0);y=h?Math.min(s.length,I+r.length):I}const p=n?{type:"range",startNodeId:t.startNodeId,startOffset:g,endNodeId:t.endNodeId,endOffset:y}:t;let N=n&&s?s.substring(p.startOffset,p.endOffset):i;return N.startsWith(e)&&(N=N.substring(e.length)),N.endsWith(r)&&(N=N.substring(0,N.length-r.length)),this.replaceText(p,N),N}replace(t,e,r){const n=this.extractText(t);if(n.length===0)return 0;let o=0,s;if(e instanceof RegExp){const a=e.flags.includes("g")?e:new RegExp(e.source,e.flags+"g");s=n.replace(a,()=>(o+=1,r))}else{const i=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");s=n.replace(i,()=>(o+=1,r))}return o>0&&this.replaceText(t,s),o}findAll(t,e){const r=this.extractText(t),n=[];if(r.length===0)return n;let o;if(e instanceof RegExp){const i=e.flags.includes("g")?e.flags:e.flags+"g";o=new RegExp(e.source,i)}else{const i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");o=new RegExp(i,"g")}let s;for(;(s=o.exec(r))!==null;){const i=s.index,a=i+s[0].length;n.push({start:i,end:a}),s[0].length===0&&o.lastIndex++}return n}indent(t,e=" "){const r=this.extractText(t);if(r.length===0)return"";const n=r.replace(/(^|\n)/g,(o,s)=>s+e);return this.replaceText(t,n),n}outdent(t,e=" "){const r=this.extractText(t);if(r.length===0)return"";const n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(^|\\n)${n}`,"g"),s=r.replace(o,(i,a)=>a);return this.replaceText(t,s),s}expandToWord(t){var o,s;const e=this.extractText(t);if(e.length===0)return t;const r=((o=e.match(/^\s*/))==null?void 0:o[0].length)??0,n=((s=e.match(/\s*$/))==null?void 0:s[0].length)??0;return{...t,startNodeId:t.startNodeId,startOffset:t.startOffset+r,endNodeId:t.endNodeId,endOffset:t.endOffset-n}}expandToLine(t){const r=this.extractText(t).indexOf(`
|
|
2
|
-
`);return{type:"range",startNodeId:t.startNodeId,startOffset:t.startOffset+0,endNodeId:t.endNodeId,endOffset:t.endOffset-0}}normalizeRange(t){const{startNodeId:e,startOffset:r,endNodeId:n,endOffset:o}=t;return e===n&&r>o?{...t,startNodeId:e,startOffset:o,endNodeId:n,endOffset:r}:t}}class Le{constructor(t){this.dataStore=t}serializeRange(t){const e=[];if(t.startNodeId===t.endNodeId){const s=this.dataStore.getNode(t.startNodeId);if(!s)return[];if(typeof s.text=="string"){const i=t.startOffset??0,a=t.endOffset??s.text.length;if(i>=a)return[];const d=s.text.substring(i,a);return e.push({stype:s.stype,text:d,marks:s.marks}),e}return e.push({...s}),e}const r=this.dataStore.getAllNodes(),n=r.findIndex(s=>s.sid===t.startNodeId),o=r.findIndex(s=>s.sid===t.endNodeId);if(n===-1||o===-1||n>o)return[];for(let s=n;s<=o;s++){const i=r[s];!i||typeof i.text!="string"||e.push({...i})}return e}deserializeNodes(t,e,r){const n=[],o=this.dataStore.getNode(e);if(!o)return n;Array.isArray(o.content)||(o.content=[],this.dataStore.updateNode(e,{content:o.content}));const s=o.content,i=typeof r=="number"?Math.min(Math.max(r,0),s.length):s.length,a=[];for(const d of t){const l={...d};l.parentId=e;const u=this.dataStore.core.createNodeWithChildren(l);a.push(u.sid)}return s.splice(i,0,...a),this.dataStore.updateNode(e,{content:s}),n.push(...a),n}}class Be{constructor(t){S(this,"overlayNodes",new Map);S(this,"deletedNodeIds",new Set);S(this,"touchedParents",new Set);S(this,"opBuffer",[]);S(this,"active",!1)}begin(){this.active||(this.active=!0,this.opBuffer=[],this.overlayNodes.clear(),this.deletedNodeIds.clear(),this.touchedParents.clear())}end(){return this.opBuffer.slice()}getCollectedOperations(){return this.opBuffer.slice()}commit(t){if(!this.active)return;const e=this.opBuffer.slice();t(e),this.reset()}rollback(){this.active&&this.reset()}isActive(){return this.active}recordOperation(t){this.active&&this.opBuffer.push(t)}hasDeleted(t){return this.deletedNodeIds.has(t)}hasOverlayNode(t){return this.overlayNodes.has(t)}getOverlayNode(t){return this.overlayNodes.get(t)}reset(){this.active=!1,this.opBuffer=[],this.overlayNodes.clear(),this.deletedNodeIds.clear(),this.touchedParents.clear()}upsertNode(t,e){if(!this.active)return;const r=t.sid;this.overlayNodes.set(r,t)}updateNodeFields(t,e,r){if(!this.active)return;const o={...this.overlayNodes.get(t)||{},...e};this.overlayNodes.set(t,o)}markDeleted(t,e){this.active&&(this.deletedNodeIds.add(t),this.overlayNodes.delete(t))}markParentTouched(t){this.active&&this.touchedParents.add(t)}}class Fe{constructor(){S(this,"listeners",new Map)}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e)}off(t,e){const r=this.listeners.get(t);r&&r.delete(e)}emit(t,...e){const r=this.listeners.get(t);r&&r.forEach(n=>{try{n(...e)}catch(o){console.error(`Error in event listener for ${t}:`,o)}})}}const z=class z{constructor(t,e,r){S(this,"nodes",new Map);S(this,"rootNodeId");S(this,"version",1);S(this,"_registeredSchemas",new Map);S(this,"_activeSchema");S(this,"_eventEmitter",new Fe);S(this,"_sessionId",0);S(this,"_overlay");S(this,"_overlayAliases");S(this,"_tempAliasSet");S(this,"_currentLock",null);S(this,"_transactionQueue",[]);S(this,"_lockTimeout",5e3);S(this,"_lockStats",{totalAcquisitions:0,totalReleases:0,totalTimeouts:0,averageWaitTime:0});S(this,"core");S(this,"query");S(this,"content");S(this,"splitMerge");S(this,"marks");S(this,"decorators");S(this,"utility");S(this,"range");S(this,"serialization");this.rootNodeId=t,this._sessionId=r??0,e&&this.setActiveSchema(e),this.core=new ke(this),this.query=new Ee(this),this.content=new Oe(this),this.splitMerge=new Te(this),this.marks=new Ce(this),this.decorators=new Me(this),this.utility=new Re(this),this.range=new $e(this),this.serialization=new Le(this)}generateId(){return z._globalCounter++,`${this._sessionId}:${z._globalCounter}`}serializeRange(t){return this.serialization.serializeRange(t)}deserializeNodes(t,e,r){return this.serialization.deserializeNodes(t,e,r)}emitOperation(t){this._overlay&&this._overlay.isActive()&&this._overlay.recordOperation(t),this._eventEmitter.emit("operation",t)}onOperation(t){this._eventEmitter.on("operation",t)}offOperation(t){this._eventEmitter.off("operation",t)}begin(){this._overlay||(this._overlay=new Be({getVersion:()=>this.getVersion(),sessionId:this.getSessionId()})),this._overlay.begin(),this._overlayAliases=new Map}getNodes(){return this.nodes}setNodes(t){this.nodes=t}getCollectedOperations(){return this._overlay&&this._overlay.isActive()?this._overlay.getCollectedOperations():[]}end(){return this._overlay&&this._overlay.isActive()?this._overlay.getCollectedOperations():[]}commit(){var o;if(!this._overlay||!this._overlay.isActive())return;const t=this._overlay.getCollectedOperations(),e={create:1,update:2,move:3,delete:4},r=t.slice().sort((s,i)=>e[s.type]-e[i.type]||0);for(const s of r)switch(s.type){case"create":{const a=((o=this._overlay)==null?void 0:o.getOverlayNode(s.nodeId))||s.data;if(a){const d=this.nodes.get(s.nodeId),l=a.marks||(d==null?void 0:d.marks);this._setNodeInternal({...a,marks:l,sid:s.nodeId})}break}case"update":{const i=this.nodes.get(s.nodeId);if(i&&s.data){const a={...i,...s.data};s.data.attributes&&i.attributes&&(a.attributes={...i.attributes,...s.data.attributes}),this._setNodeInternal(a)}break}case"move":{const{nodeId:i,parentId:a,position:d}=s,l=this.nodes.get(i);if(!l)break;if(l.parentId){const u=this.nodes.get(l.parentId);if(u&&u.content){const f=u.content.indexOf(i);f!==-1&&u.content.splice(f,1),this._setNodeInternal(u)}}if(a){const u=this.nodes.get(a);if(u){const f=typeof d=="number"?d:u.content?u.content.length:0;u.content||(u.content=[]),u.content.splice(f,0,i),this._setNodeInternal(u)}l.parentId=a,this._setNodeInternal(l)}break}case"delete":{const{nodeId:i,parentId:a}=s;if(a){const d=this.nodes.get(a);if(d&&d.content){const l=d.content.indexOf(i);l!==-1&&d.content.splice(l,1),this._setNodeInternal(d)}}this.nodes.delete(i);break}}const n=this._overlay.overlayRootNodeId;n&&(this.rootNodeId=n),this._overlay.rollback(),this._overlay=void 0,this._overlayAliases&&this._overlayAliases.clear()}rollback(){this._overlay&&(this._overlay.rollback(),this._overlay=void 0,this._overlayAliases&&this._overlayAliases.clear())}getSessionId(){return this._sessionId}setSessionId(t){this._sessionId=t}findNodes(t){return this.query.findNodes(t)}findNodesByType(t){return this.query.findNodesByType(t)}findNodesByAttribute(t,e){return this.query.findNodesByAttribute(t,e)}findNodesByText(t){return this.query.findNodesByText(t)}findChildrenByParentId(t){return this.query.findChildrenByParentId(t)}findRootNodes(){return this.query.findRootNodes()}getNodeChildren(t){return this.query.getNodeChildren(t)}getNodeChildrenDeep(t){return this.query.getNodeChildrenDeep(t)}getNodeWithChildren(t){return this.query.getNodeWithChildren(t)}getAllNodesWithChildren(){return this.query.getAllNodesWithChildren()}setNode(t,e=!0){const r=this._captureAliasFromNode(t);this.core.setNode(r,e)}setNodeInternal(t){this._setNodeInternal(t)}_setNodeInternal(t){this.nodes.set(t.sid,t)}createNodeWithChildren(t,e){const r=e||this._activeSchema;if(this._tempAliasSet=new Set,z._globalCounter=this.nodes.size,this._assignIdsRecursively(t),r){const n=(r==null?void 0:r.nodes)||void 0,o=i=>{var l;const a=typeof(n==null?void 0:n.get)=="function"?n.get(i.stype):n?n[i.stype]:(l=r==null?void 0:r.getNodeType)==null?void 0:l.call(r,i.stype);if(!a){try{const u=(r==null?void 0:r.name)||"unknown-schema",f=typeof(n==null?void 0:n.keys)=="function"?Array.from(n.keys()):Object.keys(n||{});console.error("[DataStore.createNodeWithChildren] Unknown node type during schema validation",{nodeId:i.sid,nodeType:i.stype,schemaName:u,availableTypes:f})}catch{}throw new Error(`Schema validation failed for node ${i.sid}: unknown type '${i.stype}'`)}const d=a.attrs||{};for(const[u,f]of Object.entries(d))if(f!=null&&f.required&&!(i.attributes&&i.attributes[u]!==void 0))throw new Error(`Schema validation failed for node ${i.sid}: missing required attribute '${u}'`);if(i.content&&Array.isArray(i.content))for(const u of i.content)typeof u=="object"&&u!==null&&o(u)};o(t);const s=this.validateNode(t,r);if(!s.valid)throw new Error(`Schema validation failed for node ${t.sid}: ${s.errors.join(", ")}`)}return this._createAllNodesRecursively(t),this.rootNodeId||(this.rootNodeId=t.sid),this._tempAliasSet=void 0,t}_createAllNodesRecursively(t){if(t.content)for(const r of t.content)typeof r=="object"&&this._createAllNodesRecursively(r);if(t.content&&Array.isArray(t.content)&&(t.content=t.content.map(r=>typeof r=="object"&&r!==null?r.sid:r)),t.attributes&&t.attributes.$alias){const r=t.attributes.$alias;if(this._tempAliasSet){if(this._tempAliasSet.has(r))throw new Error(`Duplicate alias detected in creation: '${r}'`);this._tempAliasSet.add(r)}try{this._overlayAliasMap&&this.setAlias(r,t.sid)}catch{}const n={...t.attributes};delete n.$alias,t.attributes=n}if(this.nodes.has(t.sid))throw new Error(`Node ID already exists: ${t.sid}`);this._setNodeInternal(t);const e={type:"create",nodeId:t.sid,data:{stype:t.stype,attributes:t.attributes,text:t.text,content:t.content,parentId:t.parentId},timestamp:Date.now(),parentId:t.parentId};this.emitOperation(e)}_assignIdsRecursively(t){t.sid||(t.sid=this.generateId()),t.content&&Array.isArray(t.content)&&t.content.forEach(e=>{if(typeof e=="object"&&e!==null){const r=e;r.parentId=t.sid,this._assignIdsRecursively(r)}else if(typeof e=="string"){const r=this.getNode(e);r&&(r.parentId=t.sid)}})}_convertChildrenToDataStore(t){t.content&&Array.isArray(t.content)&&(t.content=t.content.map(e=>{if(typeof e=="object"&&e!==null){const r=e;return this._convertChildrenToDataStore(r),this._setNodeInternal(r),r.sid}return e}))}setRootNodeId(t){this.rootNodeId=t}setRoot(t){if(this._overlay&&this._overlay.isActive()){this._overlay.overlayRootNodeId=t;return}this.rootNodeId=t}getNode(t){const e=this.resolveAlias(t);return this.core.getNode(e)}deleteNode(t){const e=this.resolveAlias(t);return this.core.deleteNode(e)}transformNode(t,e,r){const n=this.resolveAlias(t);return this.core.transformNode(n,e,r)}moveBlockUp(t){const e=this.resolveAlias(t);return this.content.moveBlockUp(e)}moveBlockDown(t){const e=this.resolveAlias(t);return this.content.moveBlockDown(e)}getRootNode(){if(!this.rootNodeId){const t=Array.from(this.nodes.values())[0];return t&&(this.rootNodeId=t.sid),t}return this.getNode(this.rootNodeId)}getChildren(t){return this.utility.getChildren(t)}getParent(t){return this.utility.getParent(t)}getSiblings(t){return this.utility.getSiblings(t)}getSiblingIndex(t){return this.utility.getSiblingIndex(t)}getPreviousSibling(t){return this.utility.getPreviousSibling(t)}getNextSibling(t){return this.utility.getNextSibling(t)}getFirstChild(t){return this.utility.getFirstChild(t)}getLastChild(t){return this.utility.getLastChild(t)}getFirstSibling(t){return this.utility.getFirstSibling(t)}getLastSibling(t){return this.utility.getLastSibling(t)}getCommonAncestor(t,e){return this.utility.getCommonAncestor(t,e)}getDistance(t,e){return this.utility.getDistance(t,e)}getNodePath(t){return this.utility.getNodePath(t)}getNodeDepth(t){return this.utility.getNodeDepth(t)}isDescendant(t,e){return this.utility.isDescendant(t,e)}getAllDescendants(t){return this.utility.getAllDescendants(t)}getAllAncestors(t){return this.utility.getAllAncestors(t)}addChild(t,e,r){return this.content.addChild(t,e,r)}removeChild(t,e){return this.content.removeChild(t,e)}moveNode(t,e,r){this.content.moveNode(t,e,r)}getNodeCount(){return this.utility.getNodeCount()}clone(){return this.utility.clone()}saveNode(t,e=!0){return this.setNode(t,e),null}updateNode(t,e,r=!0){const n=this.resolveAlias(t),o=this.getNode(n);if(!o)return{valid:!1,errors:[`Node not found: ${n}`]};if(e.stype&&e.stype!==o.stype)return{valid:!1,errors:[`Cannot change node stype from '${o.stype}' to '${e.stype}'`]};if(e.attributes&&typeof e.attributes.$alias<"u"){const d=e.attributes.$alias;if(typeof d=="string"&&d)this.setAlias(d,n);else{const f=this._findAliasById(n);f&&this.deleteAlias(f)}const{$alias:l,...u}=e.attributes;e={...e,attributes:u}}const s=Object.keys(e);if(s.length>0){let d=!0;for(const l of s){const u=o[l],f=e[l];if(!(JSON.stringify(u)===JSON.stringify(f))){d=!1;break}}if(d)return{valid:!0,errors:[]}}const i={...o,...e};e.attributes&&o.attributes&&(i.attributes={...o.attributes,...e.attributes});const a=e.content!==void 0;if(r&&!a)try{return this.setNode(i,!0),{valid:!0,errors:[]}}catch(d){return{valid:!1,errors:[d instanceof Error?d.message:"Validation failed"]}}else return this.setNode(i,!1),{valid:!0,errors:[]}}setAlias(t,e){if(this._overlayAliases||(this._overlayAliases=new Map),this._overlayAliases.has(t)&&this._overlayAliases.get(t)!==e)throw new Error(`Alias already in use: ${t}`);this._overlayAliases.set(t,e)}resolveAlias(t){return this._overlayAliases&&this._overlayAliases.get(t)||t}deleteAlias(t){this._overlayAliases&&this._overlayAliases.delete(t)}clearAliases(){this._overlayAliases&&this._overlayAliases.clear()}getAliases(){return this._overlayAliases||new Map}_findAliasById(t){if(this._overlayAliases){for(const[e,r]of this._overlayAliases.entries())if(r===t)return e}}_captureAliasFromNode(t){const e={...t},r=e.attributes&&typeof e.attributes.$alias=="string"?e.attributes.$alias:void 0;if(r&&e.sid){this.setAlias(r,e.sid);const{$alias:n,...o}=e.attributes||{};e.attributes=o}return e}saveNodeRecursively(t,e){const r={...t,parentId:e||"root"};if(this.setNode(r),t.content)for(const n of t.content){const o=typeof n=="string"?this.getNode(n):n;o&&this.saveNodeRecursively(o,t.sid)}}saveDocumentInternal(t,e=!0){var o;let r=[];if(t.content)for(const s of t.content)this.saveNodeRecursively(s,t.sid||"root"),r.push(s.sid);else t.contentIds&&(r=t.contentIds);const n={sid:t.sid||"root",stype:"document",content:r,attributes:{...t.attributes,schema:t.schema||((o=t.attributes)==null?void 0:o.schema)||{}},metadata:t.metadata||{},version:t.version||1,createdAt:new Date,updatedAt:new Date};return this.setNode(n),this.setRootNodeId(n.sid),{valid:!0,errors:[]}}getDocument(t){var o;const e=this.getRootNode();if(!e||t!=="root"&&e.sid!==t)return;const r=[];if(e.content)for(const s of e.content){const i=this.getNode(s);if(i){const{parentId:a,...d}=i;r.push(d)}}return{sid:e.sid,stype:"document",content:r,metadata:{title:"Untitled Document",author:"Unknown",version:"1.0.0",createdAt:new Date,updatedAt:new Date,...e.metadata},schema:((o=e.attributes)==null?void 0:o.schema)||{},version:e.version||1}}updateDocument(t,e,r=!0){const n=this.getDocument(t);if(!n)return{valid:!1,errors:[`Document not found: ${t}`]};const o={...n,...e};return this.saveDocumentInternal(o,r)}deleteDocument(t){const e=this.getRootNode();if(!e||e.sid!==t)return!1;throw new Error("Cannot delete root document")}registerSchema(t){t&&t.name&&this._registeredSchemas.set(t.name,t)}setActiveSchema(t){this._activeSchema=t,this.registerSchema(t)}getActiveSchema(){return this._activeSchema}validateNode(t,e){const r=e||this._activeSchema;if(!r)return{valid:!0,errors:[]};try{return be(t,r)}catch(n){return{valid:!1,errors:[`Validation error: ${n}`]}}}getAllDocuments(){var r;const t=this.getRootNode();if(!t)return[];const e=[];if(t.content)for(const n of t.content){const o=this.getNode(n);if(o){const{parentId:s,...i}=o;e.push(i)}}return[{sid:t.sid,stype:"document",content:e,metadata:{title:"Untitled Document",author:"Unknown",version:"1.0.0",createdAt:new Date,updatedAt:new Date,...t.metadata},schema:((r=t.attributes)==null?void 0:r.schema)||{},version:t.version||1}]}saveDocument(t,e=!0){const r=this.saveDocumentInternal(t,e);return r.valid?null:r}getAllNodes(){return this.utility.getAllNodes()}getAllNodesMap(){return this.utility.getAllNodesMap()}getRootNodeId(){return this.rootNodeId}getVersion(){return this.version}clear(){this.getNodes().clear(),this.setRootNodeId(void 0),this.version=1}restoreFromSnapshot(t,e,r=1){this.utility.restoreFromSnapshot(t,e,r)}copyNode(t,e){return this.content.copyNode(t,e)}cloneNodeWithChildren(t,e){return this.content.cloneNodeWithChildren(t,e)}reorderChildren(t,e){this.content.reorderChildren(t,e)}searchText(t){return this.query.searchText(t)}findByAttribute(t,e){return this.query.findNodesByAttribute(t,e)}addChildren(t,e,r){return this.content.addChildren(t,e,r)}removeChildren(t,e){return this.content.removeChildren(t,e)}moveChildren(t,e,r,n){this.content.moveChildren(t,e,r,n)}hasNode(t){return this.utility.hasNode(t)}getChildCount(t){return this.utility.getChildCount(t)}isLeafNode(t){return this.utility.isLeafNode(t)}isRootNode(t){return this.utility.isRootNode(t)}splitTextNode(t,e){return this.splitMerge.splitTextNode(t,e)}mergeTextNodes(t,e){return this.splitMerge.mergeTextNodes(t,e)}splitBlockNode(t,e){return this.splitMerge.splitBlockNode(t,e)}mergeBlockNodes(t,e){return this.splitMerge.mergeBlockNodes(t,e)}splitTextRange(t,e,r){return this.splitMerge.splitTextRange(t,e,r)}autoMergeTextNodes(t){return this.splitMerge.autoMergeTextNodes(t)}deleteText(t){return this.range.deleteText(t)}extractText(t){return this.range.extractText(t)}copyText(t){return this.range.copyText(t)}moveText(t,e){return this.range.moveText(t,e)}duplicateText(t){return this.range.duplicateText(t)}applyMark(t,e){return this.range.applyMark(t,e)}toggleMark(t,e,r){return this.range.toggleMark(t,e,r)}constrainMarksToRange(t){return this.range.constrainMarksToRange(t)}removeMark(t,e){return this.range.removeMark(t,e)}clearFormatting(t){return this.range.clearFormatting(t)}indent(t,e=" "){return this.range.indent(t,e)}outdent(t,e=" "){return this.range.outdent(t,e)}indentNode(t){return this.utility.indentNode(t)}outdentNode(t){return this.utility.outdentNode(t)}findText(t,e){return this.range.findText(t,e)}getTextLength(t){return this.range.getTextLength(t)}trimText(t){return this.range.trimText(t)}normalizeWhitespace(t){return this.range.normalizeWhitespace(t)}wrap(t,e,r){return this.range.wrap(t,e,r)}unwrap(t,e,r){return this.range.unwrap(t,e,r)}replace(t,e,r){return this.range.replace(t,e,r)}findAll(t,e){return this.range.findAll(t,e)}expandToWord(t){return this.range.expandToWord(t)}expandToLine(t){return this.range.expandToLine(t)}normalizeRange(t){return this.range.normalizeRange(t)}insertText(t,e){return this.range.insertText(t,e)}replaceText(t,e){return this.range.replaceText(t,e)}normalizeMarks(t){this.marks.normalizeMarks(t)}normalizeAllMarks(){return this.marks.normalizeAllMarks()}getMarkStatistics(t){return this.marks.getMarkStatistics(t)}removeEmptyMarks(t){return this.marks.removeEmptyMarks(t)}compareDocumentOrder(t,e){return this.utility.compareDocumentOrder(t,e)}getNextNode(t){return this.utility.getNextNode(t)}getPreviousNode(t){return this.utility.getPreviousNode(t)}isEditableNode(t){return this.utility.isEditableNode(t)}isIndentableNode(t){return this.utility.isIndentableNode(t)}getIndentMetadata(t){return this.utility.getIndentMetadata(t)}getPreviousEditableNode(t){return this.utility.getPreviousEditableNode(t)}getNextEditableNode(t){return this.utility.getNextEditableNode(t)}getDropBehavior(t,e,r){return this.utility.getDropBehavior(t,e,r)}getEditableNodes(t){return this.utility.getEditableNodes(t)}filterEditableNodes(t){return this.utility.filterEditableNodes(t)}isSelectableNode(t){return this.utility.isSelectableNode(t)}getSelectableNodes(t){return this.utility.getSelectableNodes(t)}filterSelectableNodes(t){return this.utility.filterSelectableNodes(t)}isDraggableNode(t){return this.utility.isDraggableNode(t)}getDraggableNodes(t){return this.utility.getDraggableNodes(t)}filterDraggableNodes(t){return this.utility.filterDraggableNodes(t)}isDroppableNode(t){return this.utility.isDroppableNode(t)}canDropNode(t,e){return this.utility.canDropNode(t,e)}getDroppableNodes(t){return this.utility.getDroppableNodes(t)}filterDroppableNodes(t){return this.utility.filterDroppableNodes(t)}createDocumentIterator(t){return this.utility.createDocumentIterator(t)}createRangeIterator(t,e,r){return this.utility.createDocumentIterator({...r,range:{startNodeId:t,endNodeId:e,includeStart:(r==null?void 0:r.includeStart)??!0,includeEnd:(r==null?void 0:r.includeEnd)??!0}})}getNodesInRange(t,e,r){return this.createRangeIterator(t,e,r).getNodesInRange()}getRangeNodeCount(t,e,r){return this.createRangeIterator(t,e,r).getRangeNodeCount()}_generateLockId(){return`lock-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async acquireLock(t="unknown"){const e=Date.now(),r=this._generateLockId();return new Promise((n,o)=>{if(!this._currentLock){this._currentLock={lockId:r,ownerId:t,acquiredAt:Date.now(),timeoutId:setTimeout(()=>{this._forceReleaseLock()},this._lockTimeout*10)},this._lockStats.totalAcquisitions++,n(r);return}const s={lockId:r,ownerId:t,resolve:()=>{const i=Date.now()-e;this._lockStats.averageWaitTime=(this._lockStats.averageWaitTime*(this._lockStats.totalAcquisitions-1)+i)/this._lockStats.totalAcquisitions,this._lockStats.totalAcquisitions++,n(r)},timeoutId:setTimeout(()=>{const i=this._transactionQueue.findIndex(a=>a.lockId===r);i!==-1&&(this._transactionQueue.splice(i,1),this._lockStats.totalTimeouts++,o(new Error(`Lock acquisition timeout after ${this._lockTimeout}ms for owner ${t}`)))},this._lockTimeout)};this._transactionQueue.push(s)})}releaseLock(t){if(!this._currentLock)return;if(t&&this._currentLock.lockId!==t)throw new Error(`Lock ID mismatch: expected ${this._currentLock.lockId}, got ${t}`);clearTimeout(this._currentLock.timeoutId),this._currentLock=null,this._lockStats.totalReleases++;const e=this._transactionQueue.shift();e&&(clearTimeout(e.timeoutId),this._currentLock={lockId:e.lockId,ownerId:e.ownerId,acquiredAt:Date.now(),timeoutId:setTimeout(()=>{this._forceReleaseLock()},this._lockTimeout*10)},e.resolve())}_forceReleaseLock(){this._currentLock&&(console.warn(`Force releasing lock ${this._currentLock.lockId} owned by ${this._currentLock.ownerId}`),clearTimeout(this._currentLock.timeoutId),this._currentLock=null,this._lockStats.totalReleases++)}isLocked(){return this._currentLock!==null}getCurrentLock(){return this._currentLock?{lockId:this._currentLock.lockId,ownerId:this._currentLock.ownerId,acquiredAt:this._currentLock.acquiredAt}:null}getQueueLength(){return this._transactionQueue.length}getQueueInfo(){const t=Date.now();return this._transactionQueue.map(e=>({lockId:e.lockId,ownerId:e.ownerId,waitTime:t-e.startTime||0}))}getLockStats(){return{...this._lockStats,queueLength:this._transactionQueue.length,isLocked:this._currentLock!==null,currentLock:this.getCurrentLock(),queue:this.getQueueInfo()}}setLockTimeout(t){this._lockTimeout=t}resetLockStats(){this._lockStats={totalAcquisitions:0,totalReleases:0,totalTimeouts:0,averageWaitTime:0}}traverse(...t){return this.utility.traverse(...t)}};S(z,"_globalCounter",0);let it=z;class Pe{constructor(t,e){S(this,"_dataStore");S(this,"_nodeIdCounter",0);S(this,"_sessionId");this._dataStore=t,this._sessionId=e}loadDocument(t){const e=this._createNodeFromTree(t);return this._dataStore.setNode(e),this._dataStore.setRootNodeId(e.sid),this._loadChildren(e.sid,t.content||[]),e.sid}loadNodes(t,e){for(const r of t){const n=this._createNodeFromTree(r);e&&(n.parentId=e),this._dataStore.setNode(n),r.content&&r.content.length>0&&this._loadChildren(n.sid,r.content)}}loadFromJSON(t){const e=JSON.parse(t);return this.loadDocument(e)}async loadFromAPI(t){const r=await(await fetch(t)).json();return this.loadDocument(r)}_generateFigmaStyleId(){return this._nodeIdCounter++,`${this._sessionId}:${this._nodeIdCounter}`}_createNodeFromTree(t){const e=t.sid||this._generateFigmaStyleId(),r=t.stype;return{sid:e,stype:r,attributes:t.attributes||{},content:void 0,text:t.text,marks:t.marks,metadata:{...t.metadata,loadedAt:new Date().toISOString()},version:1,createdAt:new Date,updatedAt:new Date}}_loadChildren(t,e){const r=this._dataStore.getNode(t);if(r){r.content||(r.content=[]);for(const n of e){const o=this._createNodeFromTree(n);o.parentId=t,this._dataStore.setNode(o),r.content.push(o.sid),n.content&&n.content.length>0&&this._loadChildren(o.sid,n.content)}this._dataStore.setNode(r)}}clear(){this._dataStore.clear(),this._nodeIdCounter=0}getSessionId(){return this._sessionId}getNodeCounter(){return this._nodeIdCounter}getSessionInfo(){return{sessionId:this._sessionId,nodeCounter:this._nodeIdCounter}}generateId(){return this._generateFigmaStyleId()}generateIdForType(t){return`${t}-${this.generateId()}`}}class pt{constructor(t){S(this,"_dataStore");this._dataStore=t}exportToTree(t){var n;const e=t||((n=this._dataStore.getRootNode())==null?void 0:n.sid);if(!e)throw new Error("No root node found");const r=this._dataStore.getNode(e);if(!r)throw new Error("Root node not found");return this._exportNodeToTree(r)}exportToJSON(t){return JSON.stringify(this.exportToTree(t),null,2)}toProxy(t){var n;const e=t||((n=this._dataStore.getRootNode())==null?void 0:n.sid);if(!e)return null;const r=this._dataStore.getNode(e);return r?this._createProxy(r):null}_createProxy(t){const e=this._dataStore,r=n=>this._createProxy(n);return new Proxy(t,{get(n,o){return o==="content"&&n.content?n.content.map(s=>{if(typeof s=="string"){const i=e.getNode(s);return i?r(i):s}return s&&typeof s=="object"&&s.stype?r(s):s}):n[o]}})}_exportNodeToTree(t){const e=t.content?t.content.map(r=>this._dataStore.getNode(r)).filter(r=>r!==void 0).map(r=>this._exportNodeToTree(r)):void 0;return{sid:t.sid,stype:t.stype,content:e,text:t.text,attributes:t.attributes,marks:t.marks,metadata:t.metadata}}}class at{constructor(t={}){S(this,"_currentSelection",null);S(this,"_dataStore",null);t.dataStore&&(this._dataStore=t.dataStore)}get startNodeId(){var t;return((t=this._currentSelection)==null?void 0:t.startNodeId)||null}get startOffset(){var t;return((t=this._currentSelection)==null?void 0:t.startOffset)||null}get endNodeId(){var t;return((t=this._currentSelection)==null?void 0:t.endNodeId)||null}get endOffset(){var t;return((t=this._currentSelection)==null?void 0:t.endOffset)||null}getCurrentSelection(){return this._currentSelection}setSelection(t){this._currentSelection=t}clearSelection(){this._currentSelection=null}isEmpty(){return this._currentSelection===null}isInNode(t){return this._currentSelection?this._currentSelection.startNodeId===t||this._currentSelection.endNodeId===t:!1}isAtPosition(t,e){return this._currentSelection?this._currentSelection.startNodeId===t&&this._currentSelection.startOffset===e&&this._currentSelection.endNodeId===t&&this._currentSelection.endOffset===e:!1}isInRange(t,e,r){if(!this._currentSelection||this._currentSelection.startNodeId!==t||this._currentSelection.endNodeId!==t)return!1;const n=Math.min(this._currentSelection.startOffset,this._currentSelection.endOffset),o=Math.max(this._currentSelection.startOffset,this._currentSelection.endOffset);return n>=e&&o<=r}overlapsWith(t,e,r){if(!this._currentSelection||this._currentSelection.startNodeId!==t||this._currentSelection.endNodeId!==t)return!1;const n=Math.min(this._currentSelection.startOffset,this._currentSelection.endOffset);return!(Math.max(this._currentSelection.startOffset,this._currentSelection.endOffset)<=e||n>=r)}getLength(){return!this._currentSelection||this._currentSelection.startNodeId!==this._currentSelection.endNodeId?0:Math.abs(this._currentSelection.endOffset-this._currentSelection.startOffset)}isCollapsed(){return this._currentSelection?this._currentSelection.startNodeId===this._currentSelection.endNodeId&&this._currentSelection.startOffset===this._currentSelection.endOffset:!0}moveTo(t,e){this._currentSelection={type:"range",startNodeId:t,startOffset:e,endNodeId:t,endOffset:e}}selectRange(t,e,r){this._currentSelection={type:"range",startNodeId:t,startOffset:e,endNodeId:t,endOffset:r}}selectRangeMulti(t,e,r,n){this._currentSelection={type:"range",startNodeId:t,startOffset:e,endNodeId:r,endOffset:n}}extendTo(t,e){if(!this._currentSelection){this.moveTo(t,e);return}this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:this._currentSelection.startOffset,endNodeId:t,endOffset:e}}collapseToStart(){this._currentSelection&&(this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:this._currentSelection.startOffset,endNodeId:this._currentSelection.startNodeId,endOffset:this._currentSelection.startOffset})}collapseToEnd(){this._currentSelection&&(this._currentSelection={type:"range",startNodeId:this._currentSelection.endNodeId,startOffset:this._currentSelection.endOffset,endNodeId:this._currentSelection.endNodeId,endOffset:this._currentSelection.endOffset})}selectNode(t){if(!this._dataStore)throw new Error("DataStore not set");const e=this._dataStore.getNode(t);if(!e)throw new Error(`Node not found: ${t}`);const r=e.text?e.text.length:0;this._currentSelection={type:"range",startNodeId:t,startOffset:0,endNodeId:t,endOffset:r}}selectAll(){if(!this._dataStore)throw new Error("DataStore not set");if(!this._dataStore.getRootNode())return;const r=this._dataStore.getAllNodes().filter(s=>s.text!==void 0);if(r.length===0)return;const n=r[0],o=r[r.length-1];this._currentSelection={type:"range",startNodeId:n.sid,startOffset:0,endNodeId:o.sid,endOffset:o.text.length}}selectToStart(){this._currentSelection&&(this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:0,endNodeId:this._currentSelection.startNodeId,endOffset:this._currentSelection.startOffset})}selectToEnd(){if(!this._currentSelection||!this._dataStore)return;const t=this._dataStore.getNode(this._currentSelection.startNodeId);!t||!t.text||(this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:this._currentSelection.startOffset,endNodeId:this._currentSelection.startNodeId,endOffset:t.text.length})}moveToStart(t){this.moveTo(t,0)}moveToEnd(t){if(!this._dataStore)throw new Error("DataStore not set");const e=this._dataStore.getNode(t);if(!e||!e.text)throw new Error(`Text node not found: ${t}`);this.moveTo(t,e.text.length)}moveBy(t){if(!this._currentSelection)return;const e=Math.max(0,this._currentSelection.startOffset+t);this.moveTo(this._currentSelection.startNodeId,e)}extendBy(t){if(!this._currentSelection)return;const e=Math.max(0,this._currentSelection.endOffset+t);this.extendTo(this._currentSelection.endNodeId,e)}selectWord(t,e){if(!this._dataStore)throw new Error("DataStore not set");const r=this._dataStore.getNode(t);if(!r||!r.text)throw new Error(`Text node not found: ${t}`);const n=r.text,o=/\w+/g;let s,i=-1,a=-1;for(;(s=o.exec(n))!==null;)if(e>=s.index&&e<s.index+s[0].length){i=s.index,a=s.index+s[0].length;break}i!==-1&&a!==-1?this.selectRange(t,i,a):this._currentSelection={type:"range",startNodeId:t,startOffset:e,endNodeId:t,endOffset:e}}selectLine(t,e){if(!this._dataStore)throw new Error("DataStore not set");const r=this._dataStore.getNode(t);if(!r||!r.text)throw new Error(`Text node not found: ${t}`);const o=r.text.split(`
|
|
3
|
-
`);let s=0,i=0,a=0;for(let d=0;d<o.length;d++){const l=o[d].length;if(a=s+l,e>=s&&e<=a){i=s;break}s=a+1}this.selectRange(t,i,a)}adjustForTextInsert(t,e,r){if(!this._currentSelection)return;let n=this._currentSelection.startOffset,o=this._currentSelection.endOffset;this._currentSelection.startNodeId===t&&this._currentSelection.startOffset>=e&&(n=this._currentSelection.startOffset+r),this._currentSelection.endNodeId===t&&this._currentSelection.endOffset>=e&&(o=this._currentSelection.endOffset+r),this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:n,endNodeId:this._currentSelection.endNodeId,endOffset:o}}adjustForTextDelete(t,e,r){if(!this._currentSelection)return;const n=r-e;let o=this._currentSelection.startOffset,s=this._currentSelection.endOffset;this._currentSelection.startNodeId===t&&(this._currentSelection.startOffset>=r?o=this._currentSelection.startOffset-n:this._currentSelection.startOffset>e&&(o=e)),this._currentSelection.endNodeId===t&&(this._currentSelection.endOffset>=r?s=this._currentSelection.endOffset-n:this._currentSelection.endOffset>e&&(s=e)),this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:o,endNodeId:this._currentSelection.endNodeId,endOffset:s}}adjustForNodeSplit(t,e){this._currentSelection&&this._currentSelection.startNodeId===t&&(this._currentSelection={type:"range",startNodeId:t,startOffset:e,endNodeId:t,endOffset:e})}isFullyInNode(t){return this._currentSelection?this._currentSelection.startNodeId===t&&this._currentSelection.endNodeId===t:!1}overlapsWithNode(t){return this._currentSelection?this._currentSelection.startNodeId===t||this._currentSelection.endNodeId===t:!1}getStartPosition(){if(!this._currentSelection)return null;const t=this._currentSelection.startOffset>this._currentSelection.endOffset||this._currentSelection.startOffset===this._currentSelection.endOffset&&this._currentSelection.startNodeId>this._currentSelection.endNodeId;return{nodeId:t?this._currentSelection.endNodeId:this._currentSelection.startNodeId,offset:t?this._currentSelection.endOffset:this._currentSelection.startOffset}}getEndPosition(){if(!this._currentSelection)return null;const t=this._currentSelection.startOffset>this._currentSelection.endOffset||this._currentSelection.startOffset===this._currentSelection.endOffset&&this._currentSelection.startNodeId>this._currentSelection.endNodeId;return{nodeId:t?this._currentSelection.startNodeId:this._currentSelection.endNodeId,offset:t?this._currentSelection.startOffset:this._currentSelection.endOffset}}isReversed(){return this._currentSelection?this._currentSelection.startOffset>this._currentSelection.endOffset||this._currentSelection.startOffset===this._currentSelection.endOffset&&this._currentSelection.startNodeId>this._currentSelection.endNodeId:!1}normalize(){this._currentSelection&&this.isReversed()&&(this._currentSelection={type:"range",startNodeId:this._currentSelection.endNodeId,startOffset:this._currentSelection.endOffset,endNodeId:this._currentSelection.startNodeId,endOffset:this._currentSelection.startOffset})}getSelectedText(){if(!this._currentSelection||!this._dataStore||this._currentSelection.startNodeId!==this._currentSelection.endNodeId)return null;const t=this._dataStore.getNode(this._currentSelection.startNodeId);if(!t||!t.text)return null;const e=Math.min(this._currentSelection.startOffset,this._currentSelection.endOffset),r=Math.max(this._currentSelection.startOffset,this._currentSelection.endOffset);return t.text.substring(e,r)}setDataStore(t){this._dataStore=t}setRange(t){this.setSelection(t)}setNode(t){if(!t){this.setSelection(null);return}const e=t.nodeId??t.startNodeId;if(!e){this.setSelection(null);return}this.setSelection({type:"node",startNodeId:e,startOffset:0,endNodeId:e,endOffset:0})}setAbsolutePos(t){this.setSelection(t)}setContentEditableElement(t){}isSelectionInContentEditable(){return!this.isEmpty()}destroy(){this.clearSelection()}clone(){const t=new at({dataStore:this._dataStore}),e=this._currentSelection;return e&&t.setSelection(e),t}}class Ue{constructor(t={}){S(this,"history",[]);S(this,"currentIndex",-1);S(this,"maxSize");this.maxSize=t.maxSize||100}push(t){if(!t.operations||t.operations.length===0){console.warn("[HistoryManager] Empty operations array, skipping history entry");return}const e={id:`history-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:new Date,...t};this.history=this.history.slice(0,this.currentIndex+1),this.history.push(e),this.currentIndex=this.history.length-1,this.limit(this.maxSize)}undo(){if(!this.canUndo())return null;const t=this.history[this.currentIndex];return this.currentIndex--,t}redo(){return this.canRedo()?(this.currentIndex++,this.history[this.currentIndex]):null}canUndo(){return this.currentIndex>=0}canRedo(){return this.currentIndex<this.history.length-1}getCurrentIndex(){return this.currentIndex}getHistory(){return[...this.history]}limit(t){if(this.history.length<=t)return;const e=this.history.length-t;this.history=this.history.slice(e),this.currentIndex=Math.max(0,this.currentIndex-e)}resize(t){this.maxSize=t,this.limit(t)}getMemoryUsage(){return this.history.reduce((t,e)=>t+JSON.stringify(e).length,0)}clear(){this.history=[],this.currentIndex=-1}getStats(){return{totalEntries:this.history.length,currentIndex:this.currentIndex,canUndo:this.canUndo(),canRedo:this.canRedo()}}getEntry(t){return t<0||t>=this.history.length?null:this.history[t]}findEntries(t){return this.history.filter(t)}getEntriesByTimeRange(t,e){return this.history.filter(r=>r.timestamp>=t&&r.timestamp<=e)}removeEntry(t){const e=this.history.findIndex(r=>r.id===t);return e===-1?!1:(this.history.splice(e,1),this.currentIndex>=e&&(this.currentIndex=Math.max(0,this.currentIndex-1)),!0)}compress(){if(this.history.length<2)return;const t=[];let e=this.history[0];for(let r=1;r<this.history.length;r++){const n=this.history[r];this._canCompress(e,n)?e={...e,operations:[...e.operations,...n.operations],inverseOperations:[...n.inverseOperations,...e.inverseOperations],description:e.description||n.description}:(t.push(e),e=n)}t.push(e),this.history=t,this.currentIndex=Math.min(this.currentIndex,this.history.length-1)}_canCompress(t,e){var o,s;if(t.operations.length!==1||e.operations.length!==1)return!1;const r=t.operations[0],n=e.operations[0];return r.type==="setText"&&n.type==="setText"&&((o=r.payload)==null?void 0:o.nodeId)===((s=n.payload)==null?void 0:s.nodeId)}validate(){const t=[];return(this.currentIndex<-1||this.currentIndex>=this.history.length)&&t.push(`Invalid currentIndex: ${this.currentIndex}, history length: ${this.history.length}`),this.history.forEach((e,r)=>{(!e.id||!e.timestamp||!e.operations)&&t.push(`Invalid entry at index ${r}: missing required fields`),e.operations.length!==e.inverseOperations.length&&t.push(`Entry at index ${r}: operations and inverseOperations length mismatch`)}),{isValid:t.length===0,errors:t}}}function je(c){const t=[];let e=0;for(;e<c.length;){const r=c[e];if(/\s/.test(r)){e++;continue}if(r==="("){t.push({type:"LPAREN",value:r}),e++;continue}if(r===")"){t.push({type:"RPAREN",value:r}),e++;continue}if(r==="'"||r==='"'){const i=r;let a=e+1,d="",l=!1;for(;a<c.length;)if(l)d+=c[a],l=!1,a++;else if(c[a]==="\\")l=!0,a++;else{if(c[a]===i)break;d+=c[a],a++}t.push({type:"STRING",value:d}),e=a+1;continue}if(r==="/"){let i=e+1,a="",d="",l=!0,u=!1;for(;i<c.length;)if(u)l?a+=c[i]:d+=c[i],u=!1,i++;else if(c[i]==="\\")u=!0,i++;else if(c[i]==="/"&&l)l=!1,i++;else if(l)a+=c[i],i++;else if(/[gimsuvy]/.test(c[i]))d+=c[i],i++;else break;t.push({type:"MATCH",value:a,raw:`/${a}/${d}`}),e=i;continue}if(c.slice(e,e+6)==="not in"&&(e+6>=c.length||/\s/.test(c[e+6]))){t.push({type:"NOT_IN",value:"not in"}),e+=6;continue}if(c.slice(e,e+2)==="in"&&(e===0||/\s/.test(c[e-1]))&&(e+2>=c.length||/\s/.test(c[e+2]))){t.push({type:"IN",value:"in"}),e+=2;continue}const n=c.slice(e,e+4);if(n==="!==="||n==="==="){t.push({type:"OP",value:n==="==="?"==":"!="}),e+=4;continue}const o=c.slice(e,e+3);if(o==="!=="||o==="==="){t.push({type:"OP",value:o==="==="?"==":"!="}),e+=3;continue}const s=c.slice(e,e+2);if(s==="&&"||s==="||"||s==="=="||s==="!="||s==="<="||s===">="||s==="=~"){t.push({type:"OP",value:s}),e+=2;continue}if(r==="!"||r==="="||r==="<"||r===">"){t.push({type:"OP",value:r}),e++;continue}if(/\d/.test(r)||r==="."&&e+1<c.length&&/\d/.test(c[e+1])){let i=e,a="";for(r==="."&&(a="0.",i=e+1);i<c.length&&/[\d.]/.test(c[i]);)a+=c[i++];const d=parseFloat(a);if(!isNaN(d)){t.push({type:"NUMBER",value:String(d)}),e=i;continue}}if(/[a-zA-Z_$]/.test(r)){let i=e,a="";for(;i<c.length&&/[a-zA-Z0-9_$.]/.test(c[i]);)a+=c[i++];t.push({type:"IDENT",value:a}),e=i;continue}e++}return t}class We{constructor(t,e){S(this,"tokens");S(this,"pos",0);S(this,"ctx");this.tokens=t,this.ctx=e}parse(){return!!this.parseOr()}peek(){return this.tokens[this.pos]??null}consume(){return this.tokens[this.pos++]??null}parseOr(){var e;let t=!!this.parseAnd();for(;((e=this.peek())==null?void 0:e.type)==="OP"&&this.peek().value==="||";){this.consume();const r=!!this.parseAnd();t=t||r}return t}parseAnd(){var e;let t=this.parseIn();for(;((e=this.peek())==null?void 0:e.type)==="OP"&&this.peek().value==="&&";){this.consume();const r=this.parseIn();t=!!t&&!!r}return t}parseIn(){let t=this.parseComparison();const e=this.peek();if(e&&(e.type==="IN"||e.type==="NOT_IN")){this.consume();const r=this.parsePrimary(),n=this.toValue(t),o=r;if(Array.isArray(o)){const s=o.includes(n);return e.type==="IN"?s:!s}if(typeof o=="object"&&o!==null){const s=n in o;return e.type==="IN"?s:!s}return!1}return t}parseComparison(){let t=this.parseEquality();const e=this.peek();if(e&&e.type==="OP"&&[">",">=","<","<="].includes(e.value)){this.consume();const r=this.parseEquality(),n=this.toNumber(t),o=this.toNumber(r);if(isNaN(n)||isNaN(o))return!1;switch(e.value){case">":return n>o;case">=":return n>=o;case"<":return n<o;case"<=":return n<=o;default:return!1}}return t}parseEquality(){let t=this.parseMatch();const e=this.peek();if(e&&e.type==="OP"&&(e.value==="=="||e.value==="!=")){this.consume();const r=this.parseMatch(),n=this.toValue(t),o=this.toValue(r),s=n===o;return e.value==="=="?s:!s}return t}parseMatch(){let t=this.parseUnary();const e=this.peek();if(e&&e.type==="OP"&&e.value==="=~"){this.consume();const r=this.peek();if(r&&r.type==="MATCH"){this.consume();try{const n=r.value,s=(r.raw||`/${n}/`).match(/\/([gimsuvy]*)$/),i=((s==null?void 0:s[1])||"").replace(/[gy]/g,""),a=new RegExp(n,i),d=String(this.toValue(t));return a.test(d)}catch(n){return console.warn("[WhenParser] Invalid regex pattern:",r.raw,n),!1}}return!1}return t}parseUnary(){const t=this.peek();return t&&t.type==="OP"&&t.value==="!"?(this.consume(),!this.parseUnary()):this.parsePrimary()}parsePrimary(){var e;const t=this.consume();if(!t)return!1;if(t.type==="LPAREN"){const r=this.parseOr();return((e=this.peek())==null?void 0:e.type)==="RPAREN"&&this.consume(),r}return t.type==="IDENT"?t.value==="true"?!0:t.value==="false"?!1:this.ctx[t.value]:t.type==="STRING"?t.value:t.type==="NUMBER"?parseFloat(t.value):!1}toValue(t){return typeof t=="string"?t:typeof t=="boolean"?t?"true":"false":typeof t=="number"?String(t):t==null?"":String(t)}toNumber(t){if(typeof t=="number")return t;if(typeof t=="string"){const e=parseFloat(t);return isNaN(e)?NaN:e}return typeof t=="boolean"?t?1:0:NaN}}function qe(c,t){if(!c||!c.trim())return!0;const e=je(c);return e.length===0?!0:new We(e,t).parse()}class ze{constructor(){S(this,"_bindings",[]);S(this,"_nextId",1);S(this,"_contextProvider",null);S(this,"_currentSource",null)}setCurrentSource(t){this._currentSource=t}register(t){let e=this._currentSource??t.source??"user";this._currentSource==="extension"&&t.source==="user"&&(console.warn("[KeybindingRegistry] Extension cannot set source to 'user'. It will be set to 'extension'."),e="extension"),this._currentSource==="core"&&t.source&&t.source!=="core"&&(console.warn("[KeybindingRegistry] During Core keybinding registration, source can only be set to 'core'. It will be ignored."),e="core");const r=this._normalizeKeyString(t.key),n={...t,key:r,source:e,id:this._nextId++};this._bindings.push(n)}unregister(t){this._bindings=this._bindings.filter(e=>!(e.key===t.key&&e.command===t.command&&(!t.source||e.source===t.source)))}clear(t){if(!t){this._bindings=[];return}this._bindings=this._bindings.filter(e=>e.source!==t)}setContextProvider(t){this._contextProvider=t}resolve(t,e){var d;const r=e??((d=this._contextProvider)==null?void 0:d.getContext())??{},n=this._normalizeKeyString(t),o=this._expandModKey(n),s=this._bindings.filter(l=>{const u=this._expandModKey(l.key);return o.some(h=>u.includes(h))&&this._matchWhen(l.when,r)});if(!s.length)return[];const i={user:3,extension:2,core:1};return[...s].sort((l,u)=>{const f=i[l.source??"extension"],h=i[u.source??"extension"];return f!==h?h-f:u.id-l.id}).map(l=>({command:l.command,args:l.args}))}_expandModKey(t){return ee(t)}_normalizeKeyString(t){return te(t)}_matchWhen(t,e){if(!t||!t.trim())return!0;try{return qe(t,e)}catch(r){return console.warn("[KeybindingRegistry] Failed to evaluate when expression:",t,r),!1}}}const Ve=[{key:"Enter",command:"insertParagraph",when:"editorFocus && editorEditable"},{key:"Backspace",command:"backspace",when:"editorFocus && editorEditable"},{key:"Delete",command:"deleteForward",when:"editorFocus && editorEditable"},{key:"ArrowLeft",command:"moveCursorLeft",when:"editorFocus"},{key:"ArrowRight",command:"moveCursorRight",when:"editorFocus"},{key:"Shift+ArrowLeft",command:"extendSelectionLeft",when:"editorFocus",args:{}},{key:"Shift+ArrowRight",command:"extendSelectionRight",when:"editorFocus",args:{}},{key:"Alt+ArrowLeft",command:"moveCursorWordLeft",when:"editorFocus && isMac"},{key:"Alt+ArrowRight",command:"moveCursorWordRight",when:"editorFocus && isMac"},{key:"Ctrl+ArrowLeft",command:"moveCursorWordLeft",when:"editorFocus && !isMac"},{key:"Ctrl+ArrowRight",command:"moveCursorWordRight",when:"editorFocus && !isMac"},{key:"Alt+Shift+ArrowLeft",command:"extendSelectionWordLeft",when:"editorFocus && isMac"},{key:"Alt+Shift+ArrowRight",command:"extendSelectionWordRight",when:"editorFocus && isMac"},{key:"Ctrl+Shift+ArrowLeft",command:"extendSelectionWordLeft",when:"editorFocus && !isMac"},{key:"Ctrl+Shift+ArrowRight",command:"extendSelectionWordRight",when:"editorFocus && !isMac"},{key:"Mod+a",command:"selectAll",when:"editorFocus"},{key:"Mod+b",command:"toggleBold",when:"editorFocus && editorEditable"},{key:"Mod+i",command:"toggleItalic",when:"editorFocus && editorEditable"},{key:"Mod+u",command:"toggleUnderline",when:"editorFocus && editorEditable"},{key:"Mod+Shift+s",command:"toggleStrikeThrough",when:"editorFocus && editorEditable"},{key:"Mod+c",command:"copy",when:"editorFocus && editorEditable && !selectionEmpty"},{key:"Mod+v",command:"paste",when:"editorFocus && editorEditable"},{key:"Mod+x",command:"cut",when:"editorFocus && editorEditable && !selectionEmpty"},{key:"Tab",command:"indentText",when:"editorFocus && editorEditable && canIndentText"},{key:"Shift+Tab",command:"outdentText",when:"editorFocus && editorEditable && canIndentText"},{key:"Tab",command:"indentNode",when:"editorFocus && editorEditable && canIndent"},{key:"Shift+Tab",command:"outdentNode",when:"editorFocus && editorEditable && canIndent"},{key:"Mod+z",command:"historyUndo",when:"editorFocus && historyCanUndo"},{key:"Mod+Shift+z",command:"historyRedo",when:"editorFocus && historyCanRedo"},{key:"Mod+y",command:"historyRedo",when:"editorFocus && historyCanRedo"},{key:"Mod+Alt+1",command:"setHeading1",when:"editorFocus && editorEditable"},{key:"Mod+Alt+2",command:"setHeading2",when:"editorFocus && editorEditable"},{key:"Mod+Alt+3",command:"setHeading3",when:"editorFocus && editorEditable"},{key:"Mod+Alt+0",command:"setParagraph",when:"editorFocus && editorEditable"},{key:"Mod+Shift+8",command:"toggleBulletList",when:"editorFocus && editorEditable"},{key:"Mod+Shift+7",command:"toggleOrderedList",when:"editorFocus && editorEditable"},{key:"Mod+Shift+b",command:"toggleBlockquote",when:"editorFocus && editorEditable"},{key:"Alt+ArrowUp",command:"moveBlockUp",when:"editorFocus && editorEditable"},{key:"Alt+ArrowDown",command:"moveBlockDown",when:"editorFocus && editorEditable"},{key:"Escape",command:"escape",when:"editorFocus"}],He={editorFocus:!1,editorEditable:!0,isMac:!1,isLinux:!1,isWindows:!1,selectionEmpty:!0,selectionType:null,selectionDirection:null,canIndent:!1,canIndentText:!1,historyCanUndo:!1,historyCanRedo:!1};class U{constructor(t={}){S(this,"_document");S(this,"_dataStore");S(this,"_transactionManager");S(this,"_selectionManager");S(this,"_historyManager");S(this,"_rootId");S(this,"_extensions",new Map);S(this,"_commands",new Map);S(this,"_eventListeners",new Map);S(this,"_isFocused",!1);S(this,"_isEditable",!0);S(this,"_history",[]);S(this,"_historyIndex",-1);S(this,"_keybindingRegistry");S(this,"_context",{});this._dataStore=t.dataStore||new it,this._document=t.content?this._convertFromDocumentState(t.content):this._createEmptyDocument(),this._historyManager=new Ue(t.history),this._transactionManager=new he(this),this._selectionManager=new at({dataStore:this._dataStore}),this._isEditable=t.editable!==!1,this._keybindingRegistry=new ze,this._keybindingRegistry.setContextProvider(this),this._context={...He},this._updateBuiltinContext(),this._registerCoreCommands(),this._registerDefaultKeybindings(),this._addToHistory(this._document),t.extensions&&t.extensions.forEach(e=>this.use(e)),this._setupModelEventHandling(),this._setupSelectionEventHandling(),this._setupSelectionErrorHandling()}_registerCoreCommands(){this.registerCommand({name:"setContext",execute:(t,e)=>!e||!e.key?(console.warn("[Editor] setContext: key is required"),!1):(t.setContext(e.key,e.value),!0),canExecute:()=>!0})}_registerDefaultKeybindings(){this._keybindingRegistry.setCurrentSource("core"),Ve.forEach(t=>{this.keybindings.register(t)}),this._keybindingRegistry.setCurrentSource(null)}get document(){return this._convertToDocumentState(this._document)}get selection(){return this._selectionManager.getCurrentSelection()||null}get dataStore(){return this._dataStore}get transactionManager(){return this._transactionManager}get isFocused(){return this._isFocused}get isEditable(){return this._isEditable}get keybindings(){return this._keybindingRegistry}get selectionManager(){return this._selectionManager}getRootId(){return this._rootId}setRange(t){this._selectionManager.setRange(t)}loadDocument(t,e="editor-session"){const n=new Pe(this._dataStore,e).loadDocument(t);this._rootId=n,this.emit("editor:content.change",{content:this.document,transaction:null,rootId:n})}exportDocument(t){const e=t??this._rootId;return new pt(this._dataStore).exportToTree(e)}getDocumentProxy(t){const e=t??this._rootId;return new pt(this._dataStore).toProxy(e)}setNode(t){this._selectionManager.setNode(t)}setAbsolutePos(t){this._selectionManager.setAbsolutePos(t)}_setupSelectionErrorHandling(){}clearSelection(){this._selectionManager.clearSelection()}isSelectionInContentEditable(){return this._selectionManager.isSelectionInContentEditable()}chain(){return new Ke(this)}async executeCommand(t,e){var n,o;const r=this._commands.get(t);if(!r)return console.warn(`Command ${t} not found`),!1;try{if(r.canExecute&&!r.canExecute(this,e))return!1;this.emit("editor:command.before",{command:t,payload:e}),(n=r.before)==null||n.call(r,this,e);const s=await r.execute(this,e);return(o=r.after)==null||o.call(r,this,e),this.emit("editor:command.after",{command:t,payload:e,success:s}),this.emit("editor:command.execute",{command:t,payload:e,success:s}),s}catch(s){return console.error(`Error executing command ${t}:`,s),this.emit("error:command",{command:t,payload:e,error:s}),!1}}canExecuteCommand(t,e){const r=this._commands.get(t);return r?r.canExecute?r.canExecute(this,e):!0:!1}setContent(t){let e=t;const r=this.getSortedExtensions();for(const n of r)if(n.onBeforeContentChange){const o=n.onBeforeContentChange(this,e);if(o===null){console.warn(`Content change cancelled by extension: ${n.name}`);return}o&&(e=o)}this._document=this._convertFromDocumentState(e),this.emit("editor:content.change",{content:e,transaction:null}),r.forEach(n=>{var o;(o=n.onContentChange)==null||o.call(n,this,e)})}updateSelection(t){let e=t;const r=this.getSortedExtensions();for(const n of r)if(n.onBeforeSelectionChange){const o=n.onBeforeSelectionChange(this,e);if(o===null){console.warn(`Selection change cancelled by extension: ${n.name}`);return}o&&(e=o)}if(e&&e.type==="range"){this._selectionManager.setSelection(e),this._updateBuiltinContext(),this.emit("editor:selection.model",e),r.forEach(n=>{var o;(o=n.onSelectionChange)==null||o.call(n,this,e)});return}this._updateBuiltinContext(),this.emit("editor:selection.change",{selection:e,oldSelection:this.selection}),r.forEach(n=>{var o;(o=n.onSelectionChange)==null||o.call(n,this,e)})}setContentEditableElement(t){this._selectionManager.setContentEditableElement(t)}setEditable(t){this._isEditable=t,this._updateBuiltinContext(),this.emit("editor:editable.change",{editable:t})}setContext(t,e){const r=this._context[t];e==null?delete this._context[t]:this._context[t]=e,this.emit("editor:context.change",{key:t,value:e,oldValue:r}),this.emit(`editor:context.change:${t}`,{key:t,value:e,oldValue:r})}onContextChange(t,e){const r=`editor:context.change:${t}`;return this.on(r,e),()=>{this.off(r,e)}}getContext(t){return this._updateBuiltinContext(),t!==void 0?this._context[t]:{...this._context}}_updateBuiltinContext(){this._context.editorFocus=this._isFocused,this._context.editorEditable=this._isEditable,this._context.isMac=_t,this._context.isLinux=Gt,this._context.isWindows=Jt;const t=this._selectionManager.getCurrentSelection();if(t){this._context.selectionEmpty=t.collapsed===!0,this._context.selectionType=t.type,this._context.selectionDirection=t.direction;const e=this._getIndentableTargetNodeId(t);if(this._context.canIndent=e!==null&&this._dataStore.isIndentableNode(e),t.type==="range"){const r=this._dataStore.getNode(t.startNodeId);this._context.canIndentText=r!==null&&typeof r.text=="string"}else this._context.canIndentText=!1}else this._context.selectionEmpty=!0,this._context.selectionType=null,this._context.selectionDirection=null,this._context.canIndent=!1,this._context.canIndentText=!1;this._context.historyCanUndo=this._historyManager.canUndo(),this._context.historyCanRedo=this._historyManager.canRedo()}_getIndentableTargetNodeId(t){if(t.type==="node")return t.startNodeId;if(t.type==="range"){const e=this._dataStore.getNode(t.startNodeId);if(!e)return null;const r=this._dataStore.getActiveSchema();if(r){const o=r.getNodeType(e.stype);if((o==null?void 0:o.group)==="block"&&this._dataStore.isIndentableNode(e.sid))return e.sid}let n=e;for(;n&&n.parentId;){const o=this._dataStore.getNode(n.parentId);if(!o)break;const s=r==null?void 0:r.getNodeType(o.stype);if((s==null?void 0:s.group)==="block"&&this._dataStore.isIndentableNode(o.sid))return o.sid;n=o}}return null}on(t,e){this._eventListeners.has(t)||this._eventListeners.set(t,new Set),this._eventListeners.get(t).add(e)}off(t,e){const r=this._eventListeners.get(t);r&&r.delete(e)}emit(t,e){var n;console.log("[Editor] emit:",t,{hasListeners:this._eventListeners.has(t),listenersCount:((n=this._eventListeners.get(t))==null?void 0:n.size)||0,dataKeys:e?Object.keys(e):[]});const r=this._eventListeners.get(t);r?r.forEach(o=>{try{o(e)}catch(s){console.error(`Error in event listener for ${t}:`,s)}}):console.log("[Editor] emit: no listeners for",t)}use(t){var e,r;if(this._extensions.has(t.name)){console.warn(`Extension ${t.name} is already installed`);return}try{(e=t.onBeforeCreate)==null||e.call(t,this),t.commands&&t.commands.forEach(n=>{this._commands.set(n.name,n)}),this._extensions.set(t.name,t),this._keybindingRegistry.setCurrentSource("extension"),(r=t.onCreate)==null||r.call(t,this),this._keybindingRegistry.setCurrentSource(null),this.emit("extension:add",{extension:t})}catch(n){throw console.error(`Error installing extension ${t.name}:`,n),this._keybindingRegistry.setCurrentSource(null),n}}unuse(t){var e;if(!this._extensions.has(t.name)){console.warn(`Extension ${t.name} is not installed`);return}try{(e=t.onDestroy)==null||e.call(t,this),t.commands&&t.commands.forEach(r=>{this._commands.delete(r.name)}),this._extensions.delete(t.name),this.emit("extension:remove",{extension:t})}catch(r){throw console.error(`Error removing extension ${t.name}:`,r),r}}getSortedExtensions(){return Array.from(this._extensions.values()).sort((t,e)=>{const r=t.priority??100,n=e.priority??100;return r-n})}registerCommand(t){this._commands.set(t.name,t)}undo(){try{return this._historyIndex>0?(this._historyIndex--,this._document=this._history[this._historyIndex],this.emit("editor:history.undo",{document:this._document}),this.emit("editor:history.change",{canUndo:this.canUndo(),canRedo:this.canRedo()}),Promise.resolve(!0)):Promise.resolve(!1)}catch(t){return console.error("Undo failed:",t),Promise.resolve(!1)}}redo(){try{return this._historyIndex<this._history.length-1?(this._historyIndex++,this._document=this._history[this._historyIndex],this.emit("editor:history.redo",{document:this._document}),this.emit("editor:history.change",{canUndo:this.canUndo(),canRedo:this.canRedo()}),Promise.resolve(!0)):Promise.resolve(!1)}catch(t){return console.error("Redo failed:",t),Promise.resolve(!1)}}canUndo(){return this._historyIndex>0}canRedo(){return this._historyIndex<this._history.length-1}executeTransaction(t){try{this._applyBasicTransaction(t),this._addToHistory(this._document),this.emit("transactionExecuted",{transaction:t}),this.emit("editor:content.change",{content:this.document,transaction:t});const e=t==null?void 0:t.selectionAfter;e&&this.emit("editor:selection.model",e)}catch(e){console.error("Transaction execution failed:",e),this.emit("transactionError",{transaction:t,error:e})}}_applyBasicTransaction(t){var o,s,i;if(!t||!t.type)return;const e=this._dataStore;if(!e||typeof e.getNode!="function")return;const r=new Date,n=()=>`node-${Date.now()}-${Math.random().toString(36).slice(2,9)}`;if(t.type==="insert_paragraph_after"){const a=t.afterNodeId,d=a?e.getNode(a):void 0;if(!d)return;const l=(d.parentId?e.getNode(d.parentId):e.getNode((o=this.getRootId)==null?void 0:o.call(this)))||((s=e.getRootNode)==null?void 0:s.call(e));if(!l)return;const u=t.newParagraphId||n(),f=t.newTextId||n(),h={id:u,type:"paragraph",attributes:{},content:[f],metadata:{createdAt:r,updatedAt:r},version:1,parentId:l.sid},g={id:f,type:"text",text:"",attributes:{},metadata:{createdAt:r,updatedAt:r},version:1,parentId:u};e.setNode(h),e.setNode(g);const y=Array.isArray(l.content)?[...l.content]:[],p=y.indexOf(a),N=p>=0?p+1:y.length;y.splice(N,0,u),e.setNode({...l,content:y});return}if(t.type==="insert_paragraph_at_root"){const a=(i=e.getRootNode)==null?void 0:i.call(e);if(!a)return;const d=t.newParagraphId||n(),l=t.newTextId||n(),u={id:d,type:"paragraph",attributes:{},content:[l],metadata:{createdAt:r,updatedAt:r},version:1,parentId:a.sid},f={id:l,type:"text",text:"",attributes:{},metadata:{createdAt:r,updatedAt:r},version:1,parentId:d};e.setNode(u),e.setNode(f);const h=Array.isArray(a.content)?[...a.content]:[];h.push(d),e.setNode({...a,content:h});return}if(t.type==="text_replace"){const a=t.nodeId,d=a?e.getNode(a):void 0;if(!d||d.type!=="text")return;const l=d.text||"",u=t.start??0,f=t.end??u,h=t.text??"",g=l.slice(0,u)+h+l.slice(f),y={...d,text:g,metadata:{...d.metadata,updatedAt:r}};t.marks!==void 0&&(y.marks=t.marks),e.setNode(y);return}if(t.type==="update"){const a=t.nodeId,d=a?e.getNode(a):void 0;if(!d)return;const l=t.updates||{},u={...d,...l,metadata:{...d.metadata,updatedAt:r}};e.setNode(u);return}}_setupModelEventHandling(){}_createEmptyDocument(){return{id:`doc-${Date.now()}`,type:"document",content:[],metadata:{title:"Untitled Document",author:"Unknown",version:"1.0.0",createdAt:new Date,updatedAt:new Date},schema:{},version:1}}_convertToDocumentState(t){var e,r;return{type:"document",content:(t.content||[]).map(n=>this._convertNode(n)),version:t.version,createdAt:((e=t.metadata)==null?void 0:e.createdAt)||new Date,updatedAt:((r=t.metadata)==null?void 0:r.updatedAt)||new Date}}_convertFromDocumentState(t){return{id:`doc-${Date.now()}`,type:"document",content:t.content.map(e=>this._convertFromNode(e)),metadata:{title:"Document",author:"Unknown",version:"1.0.0",createdAt:t.createdAt,updatedAt:t.updatedAt},schema:{},version:t.version}}_convertNode(t){return t}_convertFromNode(t){return t}_addToHistory(t){this._history=this._history.slice(0,this._historyIndex+1),this._history.push({...t}),this._historyIndex++,this._history.length>100&&(this._history.shift(),this._historyIndex--)}_setupSelectionEventHandling(){}destroy(){this._selectionManager.clearSelection(),this._selectionManager.destroy(),this._extensions.forEach(t=>{this.unuse(t)}),this._eventListeners.clear(),this.emit("editor:destroy",{editor:this})}}class Ke{constructor(t){S(this,"editor");S(this,"commands",[]);this.editor=t}insertText(t){return this.commands.push({command:"insertText",payload:t}),this}deleteSelection(){return this.commands.push({command:"deleteSelection"}),this}toggleBold(){return this.commands.push({command:"toggleBold"}),this}toggleItalic(){return this.commands.push({command:"toggleItalic"}),this}toggleUnderline(){return this.commands.push({command:"toggleUnderline"}),this}toggleStrikeThrough(){return this.commands.push({command:"toggleStrikeThrough"}),this}setHeading(t){return this.commands.push({command:"setHeading",payload:t}),this}insertParagraph(){return this.commands.push({command:"insertParagraph"}),this}focus(){return this.commands.push({command:"focus"}),this}async run(){let t=!0;for(const{command:e,payload:r}of this.commands)if(!await this.editor.executeCommand(e,r)){t=!1;break}return t}canRun(){return this.commands.every(({command:t,payload:e})=>this.editor.canExecuteCommand(t,e))}}U.prototype.undo=async function(){const c=this.historyManager.undo();if(!c)return!1;try{return this.transactionManager._isUndoRedoOperation=!0,(await this.transactionManager.execute(c.inverseOperations)).success}catch(t){return console.error("[Editor] undo failed:",t),!1}finally{this.transactionManager._isUndoRedoOperation=!1}};U.prototype.redo=async function(){const c=this.historyManager.redo();if(!c)return!1;try{return this.transactionManager._isUndoRedoOperation=!0,(await this.transactionManager.execute(c.operations)).success}catch(t){return console.error("[Editor] redo failed:",t),!1}finally{this.transactionManager._isUndoRedoOperation=!1}};U.prototype.canUndo=function(){return this.historyManager.canUndo()};U.prototype.canRedo=function(){return this.historyManager.canRedo()};U.prototype.getHistoryStats=function(){return this.historyManager.getStats()};U.prototype.clearHistory=function(){this.historyManager.clear()};Object.defineProperty(U.prototype,"historyManager",{get:function(){return this._historyManager}});U.prototype.transaction=function(c){return{commit:async()=>await this.transactionManager.execute(c)}};U.prototype.compressHistory=function(){this.historyManager.compress()};U.prototype.resizeHistory=function(c){this.historyManager.resize(c)};U.prototype.getHistoryMemoryUsage=function(){return this.historyManager.getMemoryUsage()};U.prototype.validateHistory=function(){return this.historyManager.validate()};class Qe{constructor(t,e){S(this,"editor");S(this,"getContentEditableElement");S(this,"_isProgrammaticChange",!1);this.editor=t,this.getContentEditableElement=e}setProgrammaticChange(t){this._isProgrammaticChange=t}isSelectionInsideEditableText(t){const e=t??window.getSelection();if(!e||e.rangeCount===0)return!1;const r=this.getContentEditableElement();if(!r||!e.anchorNode||!r.contains(e.anchorNode)||e.focusNode&&!r.contains(e.focusNode))return!1;const n=this.editor.dataStore;if(!(n!=null&&n.getNode))return!1;const o=s=>{if(!s)return!1;const i=s.nodeType===Node.TEXT_NODE?s.parentElement:s;if(!i)return!1;const a=i.closest("[data-bc-sid]");if(!a)return!1;const d=a.getAttribute("data-bc-sid");if(!d)return!1;const l=n.getNode(d);return l?(l.stype??l.type)==="inline-text":!1};return o(e.anchorNode)&&o(e.focusNode??e.anchorNode)}handleSelectionChange(){var d,l;if(this._isProgrammaticChange)return;const t=window.getSelection();if(!t)return;const e=this.getContentEditableElement();if(!e)return;const r=t.anchorNode,n=t.focusNode;if(!r)return;const o=e.contains(r),s=!n||e.contains(n);if(!o||!s)return;let i=r;for(;i;){if(i instanceof Element&&i.hasAttribute("data-devtool"))return;i=i.parentNode}const a=this.convertDOMSelectionToModel(t);(l=(d=this.editor).updateSelection)==null||l.call(d,a)}convertDOMSelectionToModel(t){if(t.rangeCount===0)return{type:"none"};const e=t.getRangeAt(0),r=this.convertRangeBoundariesToModel(e.startContainer,e.startOffset,e.endContainer,e.endOffset);if(!r)return{type:"none"};const{startNodeId:n,startModelOffset:o,endNodeId:s,endModelOffset:i}=r,a=this.findBestContainer(e.startContainer),d=this.findBestContainer(e.endContainer),l=a&&d?this.determineSelectionDirection(t,a,d,o,i):"forward";return{...ue(n,o,s,i,"range"),direction:l}}convertStaticRangeToModel(t){const e=this.convertRangeBoundariesToModel(t.startContainer,t.startOffset,t.endContainer,t.endOffset);if(!e)return null;const{startNodeId:r,startModelOffset:n,endNodeId:o,endModelOffset:s}=e;return{type:"range",startNodeId:r,startOffset:n,endNodeId:o,endOffset:s,direction:"forward"}}convertRangeBoundariesToModel(t,e,r,n){const o=this.findBestContainer(t),s=this.findBestContainer(r);if(!o||!s)return null;const i=o.getAttribute("data-bc-sid"),a=s.getAttribute("data-bc-sid");if(!i||!a||!this.nodeExistsInModel(i)||!this.nodeExistsInModel(a))return null;const d=this.ensureRuns(o,i),l=o===s?d:this.ensureRuns(s,a),u=this.convertOffsetWithRuns(o,t,e,d,!1),f=this.convertOffsetWithRuns(s,r,n,l,!0);return{startNodeId:i,startModelOffset:u,endNodeId:a,endModelOffset:f}}isTextContainer(t){return t.getAttribute("data-text-container")==="true"}nodeExistsInModel(t){try{const e=this.editor.dataStore;return e?e.getNode(t)!=null:!0}catch{return!1}}findClosestDataNode(t){if(t.nodeType===Node.ELEMENT_NODE){const r=t;if(r.hasAttribute("data-bc-sid"))return r}let e=t.parentElement;for(;e;){if(e.hasAttribute("data-bc-sid"))return e;e=e.parentElement}return null}findBestContainer(t){var o,s,i,a;let e=this.findClosestDataNode(t);if(!e)return null;if(this.isTextContainer(e))return e;let r=e;for(;r;){if(this.isTextContainer(r))return r;r=((s=(o=r.parentElement)==null?void 0:o.closest)==null?void 0:s.call(o,"[data-bc-sid]"))??null}const n=e.getAttribute("data-bc-sid");if(n){const d=(a=(i=this.editor.dataStore)==null?void 0:i.getNode)==null?void 0:a.call(i,n);if((d==null?void 0:d.stype)==="document")return null}return e}ensureRuns(t,e){return st(t,e,{buildReverseMap:!0,excludePredicate:r=>r.hasAttribute("data-bc-decorator")})}convertOffsetWithRuns(t,e,r,n,o){var a,d;if(n.total===0)return 0;if(e.nodeType===Node.TEXT_NODE){const l=e,u=(a=n.byNode)==null?void 0:a.get(l);if(u){const h=u.end-u.start,g=Math.max(0,Math.min(r,h));return u.start+g}const f=ht(n.runs,Math.max(0,Math.min(r,n.total-1)));return f>=0?o?n.runs[f].end:n.runs[f].start:0}const s=e,i=this.findTextAtElementBoundary(t,s,r,o);if(i){const l=(d=n.byNode)==null?void 0:d.get(i);if(l)return o?l.end:l.start}return o?n.total:0}findTextAtElementBoundary(t,e,r,n){const o=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),s=e.childNodes.item(r)??null;let i=null,a=null,d=o.nextNode();for(;d;){if(s){if(d.compareDocumentPosition(s)&Node.DOCUMENT_POSITION_FOLLOWING){a=d;break}i=d}else i=d;d=o.nextNode()}return n?i??a:a??i}determineSelectionDirection(t,e,r,n,o){if(e===r)return n<=o?"forward":"backward";const s=t.anchorNode,i=t.focusNode;if(!s||!i)return e.compareDocumentPosition(r)&Node.DOCUMENT_POSITION_FOLLOWING?"forward":"backward";const a=this.findBestContainer(s),d=this.findBestContainer(i);if(a&&d){const u=e.getAttribute("data-bc-sid"),f=r.getAttribute("data-bc-sid"),h=a.getAttribute("data-bc-sid"),g=d.getAttribute("data-bc-sid");if(h===u&&g===f)return"forward";if(h===f&&g===u)return"backward"}return e.compareDocumentPosition(r)&Node.DOCUMENT_POSITION_FOLLOWING?"forward":"backward"}convertModelSelectionToDOM(t){var e;this._isProgrammaticChange=!0;try{if(!t||t.type==="none"){(e=window.getSelection())==null||e.removeAllRanges();return}t.type==="range"?this.convertRangeSelectionToDOM(t):t.type==="node"&&this.convertNodeSelectionToDOM(t)}finally{setTimeout(()=>{this._isProgrammaticChange=!1},0)}}convertRangeSelectionToDOM(t){var p,N;const{startNodeId:e,startOffset:r,endNodeId:n,endOffset:o}=t,s=document.querySelector(`[data-bc-sid="${e}"]`),i=document.querySelector(`[data-bc-sid="${n}"]`);if(!s||!i)return;const a=this.findBestContainer(s),d=this.findBestContainer(i);if(!a||!d)return;const l=this.getTextRunsForContainer(a),u=this.getTextRunsForContainer(d);let f=(p=l==null?void 0:l.runs)!=null&&p.length?this.findDOMRangeFromModelOffset(l,r):null,h=(N=u==null?void 0:u.runs)!=null&&N.length?this.findDOMRangeFromModelOffset(u,o):null;f||(f={node:s,offset:Math.min(r,s.childNodes.length)}),h||(h={node:i,offset:Math.min(o,i.childNodes.length)});const g=window.getSelection();if(!g)return;g.removeAllRanges();const y=document.createRange();y.setStart(f.node,f.offset),y.setEnd(h.node,h.offset),g.addRange(y)}convertNodeSelectionToDOM(t){const e=document.querySelector(`[data-bc-sid="${t.nodeId}"]`);if(!e)return;const r=window.getSelection();if(!r)return;r.removeAllRanges();const n=document.createRange();n.selectNodeContents(e),r.addRange(n)}getTextRunsForContainer(t){try{const e=t.getAttribute("data-bc-sid");return st(t,e??void 0,{buildReverseMap:!0,excludePredicate:r=>r.hasAttribute("data-decorator-sid")||r.hasAttribute("data-bc-decorator")||r.hasAttribute("data-decorator-category"),normalizeWhitespace:!1})}catch{return null}}findDOMRangeFromModelOffset(t,e){var s,i;if(e<0||e>t.total)return null;if(e===t.total){const a=t.runs[t.runs.length-1];return{node:a.domTextNode,offset:((s=a.domTextNode.textContent)==null?void 0:s.length)??0}}const r=ht(t.runs,e);if(r===-1)return null;const n=t.runs[r],o=e-n.start;return{node:n.domTextNode,offset:Math.min(o,((i=n.domTextNode.textContent)==null?void 0:i.length)??0)}}}function Ge(c,t){if(c===t)return{kind:"none",start:0,end:0,inserted:"",deleted:""};let e=0;const r=Math.min(c.length,t.length);for(;e<r&&c.charCodeAt(e)===t.charCodeAt(e);)e++;let n=0;const o=c.length-e,s=t.length-e;for(;n<o&&n<s&&c.charCodeAt(c.length-1-n)===t.charCodeAt(t.length-1-n);)n++;const i=e,a=c.length-n,d=c.slice(i,a),l=t.slice(e,t.length-n);return!d&&!l?{kind:"none",start:i,end:a,inserted:"",deleted:""}:d?l?{kind:"replace",start:i,end:a,inserted:l,deleted:d}:{kind:"delete",start:i,end:a,inserted:"",deleted:d}:{kind:"insert",start:i,end:i,inserted:l,deleted:""}}function Je(c,t,e,r,n){const{kind:o,start:s,end:i,inserted:a,deleted:d}=e;if(o==="none")return[];const l=n===0,u=r,f=r+n;let h=s,g=i,y=a,p=d;if(o==="replace"&&a.length===1&&d.length===1){const I=l?u:Math.floor((u+f)/2),m=Math.min(3,Math.floor(c.length*.05)),_=Math.max(0,I-m),v=Math.min(c.length-1,I+m);for(let w=_;w<=v;w++){if(!l&&(w<u||w>=f))continue;if(c.slice(0,w)+a+c.slice(w+1)===t){h=w,g=w+1,p=c[w];break}}}else if(o==="delete"){const I=i-s,m=l?u:Math.floor((u+f)/2),_=Math.min(6,Math.floor(c.length*.1));let v=s,w=Math.abs(m-(s+Math.floor(I/2))),E=0;const A=Math.max(0,m-_),F=Math.min(c.length-I,m+_);for(let x=A;x<=F;x++){if(c.slice(0,x)+c.slice(x+I)!==t)continue;const O=x,C=x+I,D=l?m>=O&&m<=C?1:0:Math.max(0,Math.min(C,f)-Math.max(O,u)),k=x+Math.floor(I/2),R=Math.abs(m-k);(D>E||D===E&&R<w)&&(E=D,w=R,v=x)}h=v,g=v+I,p=c.slice(h,g)}const N=[];return o==="insert"?N.push({type:"insert",start:h,end:h,text:y,confidence:1}):o==="delete"?N.push({type:"delete",start:h,end:h+p.length,text:"",confidence:1}):o==="replace"&&N.push({type:"replace",start:h,end:h+p.length,text:y,confidence:1}),N}function yt(c,t){if(t<=0||t>=c.length)return!0;const e=c.codePointAt(t-1),r=c.codePointAt(t);return!e||!r?!0:!(e>=55296&&e<=56319||r>=56320&&r<=57343||r>=768&&r<=879||r>=6832&&r<=6911||r>=7616&&r<=7679||r>=8400&&r<=8447||r>=65056&&r<=65071)}function Nt(c,t,e){let r=Math.max(0,Math.min(c.length,t));if(e==="left")for(;r>0&&!yt(c,r);)r--;else for(;r<c.length&&!yt(c,r);)r++;return r}function Xe(c){const{oldText:t,newText:e,selectionOffset:r,selectionLength:n=0}=c,o=t.normalize("NFC"),s=e.normalize("NFC");if(o===s)return[];const i=Ge(o,s);return Je(o,s,i,r,n).map(l=>({...l,start:Nt(o,l.start,"left"),end:Nt(o,l.end,"right")}))}function Ot(c){let t=c;for(;t;){if(t.nodeType===Node.ELEMENT_NODE){const e=t;if(e.getAttribute("data-bc-sid"))return e}t=t.parentNode}return null}function Tt(c){return st(c,void 0,{normalizeWhitespace:!1}).runs.map(e=>e.domTextNode.textContent??"").join("")}function Ye(c,t){var e,r;if(c.length===0)return null;for(const n of c){const o=n.target,s=Ot(o);if(!s)continue;const i=s.getAttribute("data-bc-sid");if(!i)continue;const a=(r=(e=t.editor.dataStore)==null?void 0:e.getNode)==null?void 0:r.call(e,i);if(!a||a.stype!=="inline-text"||n.type==="childList"&&[...Array.from(n.addedNodes??[]),...Array.from(n.removedNodes??[])].some(N=>{if(N.nodeType!==Node.ELEMENT_NODE)return!1;const I=N.tagName.toLowerCase();return["p","div","li","ul","ol","h1","h2","h3","h4","h5","h6","blockquote"].includes(I)}))continue;const d=a.text??"",l=Tt(s);let u,f,h=!1;const g=t.inputHint;return(g==null?void 0:g.contentRange.startNodeId)===i&&g.contentRange.endNodeId===i&&(u=Math.max(0,Math.min(d.length,g.contentRange.startOffset)),f=Math.max(u,Math.min(d.length,g.contentRange.endOffset)),h=!0),{case:"C1",nodeId:i,prevText:d,newText:l,contentRange:u!==void 0&&f!==void 0?{startNodeId:i,startOffset:u,endNodeId:i,endOffset:f}:void 0,mutations:[n],metadata:h?{usedInputHint:!0}:void 0}}return null}function Ze(c){const t=["insertParagraph","insertLineBreak"],e=["historyUndo","historyRedo"];return t.includes(c)||e.includes(c)}function tr(c){return["formatBold","formatItalic","formatUnderline","formatStrikeThrough"].includes(c)}function er(c){return["deleteContentBackward","deleteContentForward","deleteWordBackward","deleteWordForward","deleteByCut","deleteByDrag"].includes(c)}class rr{constructor(t,e,r){S(this,"editor");S(this,"selectionHandler");S(this,"viewStateRef");S(this,"_isComposing",!1);S(this,"_pendingInsertHint",null);this.editor=t,this.selectionHandler=e,this.viewStateRef=r}setComposing(t){this._isComposing=t,this.viewStateRef.current.isComposing=t}async syncFocusedTextNodeAfterComposition(){var u,f,h,g,y;const t=this.viewStateRef.current;if(t.isModelDrivenChange||t.isRendering)return;const e=window.getSelection();if(!(e!=null&&e.rangeCount)||!e.anchorNode)return;const r=Ot(e.anchorNode);if(!r)return;const n=r.getAttribute("data-bc-sid");if(!n)return;const o=this.editor.dataStore,s=(u=o==null?void 0:o.getNode)==null?void 0:u.call(o,n);if(!s||s.stype!=="inline-text")return;const i=s.text??"",a=Tt(r);if(i===a)return;this.viewStateRef.current.skipNextRenderFromMO=!0;let d=!1;try{d=await this.editor.executeCommand("replaceText",{range:{type:"range",startNodeId:n,startOffset:0,endNodeId:n,endOffset:i.length},text:a})}finally{this.viewStateRef.current.skipNextRenderFromMO=!1}if(!d)return;const l=window.getSelection();if(l!=null&&l.rangeCount){this.viewStateRef.current.skipApplyModelSelectionToDOM=!0;try{const p=this.selectionHandler.convertDOMSelectionToModel(l);if(p.type==="range"){const N={type:"range",startNodeId:p.startNodeId,startOffset:p.startOffset,endNodeId:p.endNodeId,endOffset:p.endOffset,collapsed:p.startNodeId===p.endNodeId&&p.startOffset===p.endOffset};(h=(f=this.editor).updateSelection)==null||h.call(f,N)}}catch{}finally{setTimeout(()=>{this.viewStateRef.current.skipApplyModelSelectionToDOM=!1},0)}}(y=(g=this.editor).emit)==null||y.call(g,"editor:content.change",{skipRender:!0,from:"compositionend-sync",content:this.editor.document,transaction:{type:"text_replace",nodeId:n}})}async handleDomMutations(t){const e=this.viewStateRef.current;if(!(e.isModelDrivenChange||e.isRendering)&&!e.isComposing){this.viewStateRef.current.skipNextRenderFromMO=!0;try{await this.handleDomMutationsInner(t)}finally{this.viewStateRef.current.skipNextRenderFromMO=!1}}}async handleDomMutationsInner(t){const e=this.viewStateRef.current,r=window.getSelection();let n;if(r!=null&&r.rangeCount)try{const i=this.selectionHandler.convertDOMSelectionToModel(r);i.type==="range"&&(n={type:"range",startNodeId:i.startNodeId,startOffset:i.startOffset,endNodeId:i.endNodeId,endOffset:i.endOffset})}catch{}const o=this.getValidInsertHint(e.isComposing),s=Ye(t,{editor:this.editor,inputHint:o??void 0,isComposing:e.isComposing});(s==null?void 0:s.case)==="C1"&&await this.handleC1(s)}getValidInsertHint(t){const e=this._pendingInsertHint;return!e||t||Date.now()-e.timestamp>500?null:e}async handleC1(t){var i,a,d,l,u,f,h;if(!t.nodeId||!t.prevText||t.newText===void 0)return;const e=window.getSelection(),r=e!=null&&e.rangeCount?e.getRangeAt(0).startOffset:0,n=Xe({oldText:t.prevText,newText:t.newText,selectionOffset:r,selectionLength:0});if(n.length===0)return;const o=n[0],s=t.contentRange&&((i=t.metadata)!=null&&i.usedInputHint)?t.contentRange:{startNodeId:t.nodeId,startOffset:o.start,endNodeId:t.nodeId,endOffset:o.end};this.viewStateRef.current.skipApplyModelSelectionToDOM=!0;try{if(o.type==="delete"){if(!(s.startNodeId===s.endNodeId?await this.editor.executeCommand("deleteText",{range:s}):await this.editor.executeCommand("deleteCrossNode",{range:s})))return;const y={type:"range",startNodeId:s.startNodeId,startOffset:s.startOffset,endNodeId:s.startNodeId,endOffset:s.startOffset,collapsed:!0};(d=(a=this.editor).updateSelection)==null||d.call(a,y)}else{if(!await this.editor.executeCommand("replaceText",{range:s,text:o.text??""}))return;const y=(o.text??"").length,p={type:"range",startNodeId:s.startNodeId,startOffset:s.startOffset+y,endNodeId:s.startNodeId,endOffset:s.startOffset+y,collapsed:!0};(u=(l=this.editor).updateSelection)==null||u.call(l,p)}}finally{setTimeout(()=>{this.viewStateRef.current.skipApplyModelSelectionToDOM=!1},0)}(h=(f=this.editor).emit)==null||h.call(f,"editor:content.change",{skipRender:!0,from:"MutationObserver-C1",content:this.editor.document,transaction:{type:"text_replace",nodeId:t.nodeId}}),this._pendingInsertHint=null}handleBeforeInput(t){t.isComposing!==void 0&&(this._isComposing=t.isComposing,this.viewStateRef.current.isComposing=t.isComposing);const e=t.inputType;if(Ze(e)){t.preventDefault(),this.executeStructuralCommand(e);return}if(tr(e)){t.preventDefault(),this.executeFormatCommand(e);return}if(er(e)&&!t.isComposing){t.preventDefault(),this.handleDelete(t);return}if(e==="insertText"){this.updateInsertHintFromBeforeInput(t);return}if(["insertFromPaste","insertReplacementText"].includes(e)){if(this.tryHandleInsertViaGetTargetRanges(t))return;this.updateInsertHintFromBeforeInput(t)}}updateInsertHintFromBeforeInput(t){const e=window.getSelection();if(!(e!=null&&e.rangeCount)){this._pendingInsertHint=null;return}try{const r=this.selectionHandler.convertDOMSelectionToModel(e);if(r.type!=="range"){this._pendingInsertHint=null;return}this._pendingInsertHint={contentRange:{startNodeId:r.startNodeId,startOffset:r.startOffset,endNodeId:r.endNodeId,endOffset:r.endOffset},timestamp:Date.now()}}catch{this._pendingInsertHint=null}}handleKeydown(t){var o,s,i,a;if(this._isComposing)return;if(t.key.length===1&&!["Enter","Tab","Escape"].includes(t.key)&&!t.ctrlKey&&!t.metaKey&&t.keyCode!==229&&!this.selectionHandler.isSelectionInsideEditableText()){t.preventDefault();return}const r=Yt(t);if(r==="Space"&&!t.ctrlKey&&!t.metaKey&&!t.altKey)return;const n=(s=(o=this.editor.keybindings)==null?void 0:o.resolve)==null?void 0:s.call(o,r);if(n!=null&&n.length){const{command:d,args:l}=n[0];t.preventDefault();const u=window.getSelection();if(u&&u.rangeCount>0)try{const f=this.selectionHandler.convertDOMSelectionToModel(u);f&&f.type==="range"&&((a=(i=this.editor).updateSelection)==null||a.call(i,f))}catch{}this.editor.executeCommand(d,l??{})}}insertTextAtSelection(t){const e=window.getSelection();if(!e||e.rangeCount===0)return;const r=this.selectionHandler.convertDOMSelectionToModel(e);if(!r||r.type!=="range")return;const n={type:"range",startNodeId:r.startNodeId,startOffset:r.startOffset,endNodeId:r.endNodeId,endOffset:r.endOffset};this.editor.executeCommand("replaceText",{range:n,text:t}).then(o=>{var i,a;if(!o)return;const s={type:"range",startNodeId:r.startNodeId,startOffset:r.startOffset+t.length,endNodeId:r.startNodeId,endOffset:r.startOffset+t.length};(a=(i=this.editor).updateSelection)==null||a.call(i,s),this.applyModelSelectionAfterRender(s)}).catch(()=>{})}tryHandleInsertViaGetTargetRanges(t){const e=t.inputType;if(!["insertText","insertFromPaste","insertReplacementText"].includes(e)||t.isComposing)return!1;const r=t.getTargetRanges;if(typeof r!="function")return!1;const n=r.call(t);if(!(n!=null&&n.length))return!1;const o=n[0],s=this.selectionHandler.convertStaticRangeToModel(o);if(!s||s.type!=="range")return!1;const i=this.editor.dataStore;if(!i)return!1;const a=i.getNode(s.startNodeId),d=i.getNode(s.endNodeId);if(!((a==null?void 0:a.stype)==="inline-text"&&(d==null?void 0:d.stype)==="inline-text"))return t.preventDefault(),!0;const u=t.data??"",f={type:"range",startNodeId:s.startNodeId,startOffset:s.startOffset,endNodeId:s.endNodeId,endOffset:s.endOffset};return t.preventDefault(),this.editor.executeCommand("replaceText",{range:f,text:u}).then(h=>{var p,N,I,m;if(!h)return;const g=u.length,y={type:"range",startNodeId:s.startNodeId,startOffset:s.startOffset+g,endNodeId:s.startNodeId,endOffset:s.startOffset+g};(N=(p=this.editor).updateSelection)==null||N.call(p,y),(m=(I=this.editor).emit)==null||m.call(I,"editor:content.change",{skipRender:!1,from:"getTargetRanges",content:this.editor.document,transaction:{type:"text_replace",range:f}}),this.applyModelSelectionAfterRender(y)}).catch(()=>{}),!0}applyModelSelectionAfterRender(t){requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.selectionHandler.convertModelSelectionToDOM(t)})})}async handleDelete(t){var a,d,l,u,f,h;const e=window.getSelection();if(!e||e.rangeCount===0)return;let r=null;try{r=this.selectionHandler.convertDOMSelectionToModel(e)}catch{return}if(!r||r.type!=="range")return;const n=r;(d=(a=this.editor).updateSelection)==null||d.call(a,n);const o=this.calculateDeleteRange(n,t.inputType,n.startNodeId);if(!o)return;let s=!1;if(o._deleteNode&&o.nodeId?s=await this.editor.executeCommand("deleteNode",{nodeId:o.nodeId}):o.startNodeId!==o.endNodeId?s=await this.editor.executeCommand("deleteCrossNode",{range:o}):s=await this.editor.executeCommand("deleteText",{range:o}),!s)return;const i={type:"range",startNodeId:o.startNodeId,startOffset:o.startOffset,endNodeId:o.startNodeId,endOffset:o.startOffset,collapsed:!0};(u=(l=this.editor).emit)==null||u.call(l,"editor:selection.change",{selection:i,oldSelection:r}),(h=(f=this.editor).emit)==null||h.call(f,"editor:content.change",{skipRender:!1,from:"beforeinput-delete",content:this.editor.document,transaction:{type:"delete",contentRange:o}}),this.applyModelSelectionAfterRender(i)}calculateDeleteRange(t,e,r){var d,l,u;const{startNodeId:n,startOffset:o,endNodeId:s,endOffset:i}=t;if(!(n===s&&o===i))return{type:"range",startNodeId:n,startOffset:o,endNodeId:s,endOffset:i};switch(e){case"deleteContentBackward":return o>0?{type:"range",startNodeId:n,startOffset:o-1,endNodeId:s,endOffset:o}:this.calculateCrossNodeDeleteRange(n,"backward");case"deleteContentForward":{const f=(l=(d=this.editor.dataStore)==null?void 0:d.getNode)==null?void 0:l.call(d,n),h=((u=f==null?void 0:f.text)==null?void 0:u.length)??0;return o<h?{type:"range",startNodeId:n,startOffset:o,endNodeId:s,endOffset:o+1}:this.calculateCrossNodeDeleteRange(n,"forward")}case"deleteWordBackward":case"deleteWordForward":return this.calculateDeleteRange(t,e==="deleteWordBackward"?"deleteContentBackward":"deleteContentForward",r);case"deleteByCut":case"deleteByDrag":return{type:"range",startNodeId:n,startOffset:o,endNodeId:s,endOffset:i};default:return null}}calculateCrossNodeDeleteRange(t,e){const r=this.editor.dataStore;if(!(r!=null&&r.getNode)||!(r!=null&&r.getParent))return null;const n=r.getNode(t);if(!n||n.text===void 0||typeof n.text!="string")return null;const o=r.getParent(t);if(!(o!=null&&o.content))return null;const s=o.content.indexOf(t);if(s===-1)return null;const i=e==="backward"?s-1:s+1;if(i<0||i>=o.content.length)return null;const a=o.content[i],d=r.getNode(a);if(!d)return null;const l=r.getParent(a);if(!l||l.sid!==o.sid)return null;const u=r.schema;if(u!=null&&u.getNodeType){const h=d.stype??d.type,g=h?u.getNodeType(h):void 0;if((g==null?void 0:g.group)==="block")return null}if(d.text===void 0||typeof d.text!="string")return{type:"range",startNodeId:"",startOffset:0,endNodeId:"",endOffset:0,_deleteNode:!0,nodeId:a};const f=(d.text??"").length;return e==="backward"?f===0?null:{type:"range",startNodeId:a,startOffset:f-1,endNodeId:a,endOffset:f}:f===0?null:{type:"range",startNodeId:a,startOffset:0,endNodeId:a,endOffset:1}}executeStructuralCommand(t){switch(t){case"insertParagraph":this.insertParagraph();break;case"insertLineBreak":this.insertText(`
|
|
4
|
-
`);break;case"historyUndo":this.editor.executeCommand("historyUndo",{});break;case"historyRedo":this.editor.executeCommand("historyRedo",{});break}}insertParagraph(){var r,n;const t=window.getSelection();if(!t||t.rangeCount===0){this.editor.executeCommand("insertParagraph",{}).catch(()=>{});return}let e;try{e=this.selectionHandler.convertDOMSelectionToModel(t)}catch{this.editor.executeCommand("insertParagraph",{}).catch(()=>{});return}if(!e||e.type==="none"){this.editor.executeCommand("insertParagraph",{}).catch(()=>{});return}(n=(r=this.editor).updateSelection)==null||n.call(r,e),this.editor.executeCommand("insertParagraph",{selection:e}).catch(()=>{})}insertText(t){const e=window.getSelection();if(!e||e.rangeCount===0){this.editor.executeCommand("insertText",{text:t});return}const r=this.selectionHandler.convertDOMSelectionToModel(e);if(!r||r.type==="none"){this.editor.executeCommand("insertText",{text:t});return}this.editor.executeCommand("insertText",{text:t,selection:r})}executeFormatCommand(t){var n,o;const r={formatBold:"toggleBold",formatItalic:"toggleItalic",formatUnderline:"toggleUnderline",formatStrikeThrough:"toggleStrikeThrough"}[t];r&&((o=(n=this.editor).emit)==null||o.call(n,"editor:command.execute",{command:r,data:void 0}),this.editor.executeCommand(r,{}))}}function Ct(c){let t=null,e=[],r=null;return{setup(n){t&&(t.disconnect(),t=null),r!=null&&(clearTimeout(r),r=null),e=[],t=new MutationObserver(o=>{e.push(...o),r!=null&&clearTimeout(r),r=window.setTimeout(()=>{e.length>0&&(c([...e]),e=[]),r=null},0)}),t.observe(n,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["data-bc-edit","data-bc-value","data-bc-sid","data-bc-stype"],characterDataOldValue:!0,attributeOldValue:!0})},disconnect(){t&&(t.disconnect(),t=null),r!=null&&(clearTimeout(r),r=null),e=[]}}}const dt=T.createContext(null);function et(){const c=T.useContext(dt);if(!c)throw new Error("useEditorViewContext must be used within EditorViewContext.Provider");return c}function nr(){return T.useContext(dt)}function Mt({editor:c,children:t}){const e=T.useRef({isModelDrivenChange:!1,isRendering:!1,isComposing:!1,skipNextRenderFromMO:!1,skipApplyModelSelectionToDOM:!1}),r=T.useRef(null),n=T.useCallback(()=>r.current,[]),o=T.useRef(null);o.current===null&&(o.current=new de);const s=T.useRef(null);s.current===null&&(s.current=new re(o.current));const i=T.useRef(null);i.current===null&&(i.current=new ne);const a=T.useRef(null);a.current===null&&(a.current=new oe);const d=T.useRef(null);d.current===null&&(d.current=new ae);const[l,u]=T.useState(0),f=T.useCallback(()=>u(m=>m+1),[]);T.useEffect(()=>{const m=s.current;if(m)return m.on("decorator:added",f),m.on("decorator:updated",f),m.on("decorator:removed",f),()=>{m.off("decorator:added",f),m.off("decorator:updated",f),m.off("decorator:removed",f)}},[f]),T.useEffect(()=>{const m=i.current;if(m)return m.on("change",f),()=>m.off("change",f)},[f]);const h=T.useCallback(m=>{var x,M,O;const _=((x=s.current)==null?void 0:x.getAll())??[],v=((M=i.current)==null?void 0:M.getAll())??[],w=((O=a.current)==null?void 0:O.getConfigs(!0))??[],E=ie(m,w),A=d.current;let F=[];if(A&&m&&typeof m=="object"){const C=m,D=k=>{const R=typeof k.text=="string"?k.text:null;F.push(...A.generateDecorators(k,R,{documentModel:C}));const L=k.children??k.content;if(Array.isArray(L))for(const B of L)B&&typeof B=="object"&&D(B)};D(C)}return[..._,...v,...E,...F]},[]),g=T.useMemo(()=>new Qe(c,n),[c,n]),y=T.useMemo(()=>new rr(c,g,e),[c,g]),p=T.useMemo(()=>Ct(m=>{y.handleDomMutations(m)}),[y]),N=T.useCallback(m=>{r.current!==m&&(r.current&&p.disconnect(),r.current=m,m&&p.setup(m))},[p]);T.useEffect(()=>{const m=()=>g.handleSelectionChange();return document.addEventListener("selectionchange",m),()=>document.removeEventListener("selectionchange",m)},[g]);const I=T.useMemo(()=>({editor:c,viewStateRef:e,selectionHandler:g,inputHandler:y,mutationObserverManager:p,setContentEditableElement:N,contentEditableRef:r,decoratorManagerRef:s,decoratorSchemaRegistryRef:o,remoteDecoratorManagerRef:i,patternDecoratorConfigManagerRef:a,decoratorGeneratorManagerRef:d,getMergedDecorators:h,bumpDecoratorVersion:f,decoratorVersion:l}),[c,e,g,y,p,N,r,s,o,i,a,d,h,f,l]);return $.jsx(dt.Provider,{value:I,children:t})}function ct({options:c={}}){const{editor:t,selectionHandler:e,viewStateRef:r,setContentEditableElement:n,getMergedDecorators:o,decoratorVersion:s}=et(),{className:i="",editable:a=!0,registry:d}=c,[l,u]=T.useState(()=>{var p;return((p=t.getDocumentProxy)==null?void 0:p.call(t))??null}),f=T.useRef(null);T.useEffect(()=>{var N,I;const p=m=>{var v,w;if((v=r==null?void 0:r.current)!=null&&v.skipNextRenderFromMO){r.current.skipNextRenderFromMO=!1;return}const _=(m==null?void 0:m.content)??((w=t.getDocumentProxy)==null?void 0:w.call(t))??null;u(_)};return(N=t.on)==null||N.call(t,"editor:content.change",p),u(((I=t.getDocumentProxy)==null?void 0:I.call(t))??null),()=>{var m;(m=t.off)==null||m.call(t,"editor:content.change",p)}},[t,r]),T.useEffect(()=>{const p=f.current;return n(p),()=>n(null)},[n]),T.useEffect(()=>{var N;const p=I=>{var m;(m=r==null?void 0:r.current)!=null&&m.skipApplyModelSelectionToDOM||requestAnimationFrame(()=>{requestAnimationFrame(()=>{e.convertModelSelectionToDOM(I)})})};return(N=t.on)==null||N.call(t,"editor:selection.model",p),()=>{var I;return(I=t.off)==null?void 0:I.call(t,"editor:selection.model",p)}},[t,e,r]);const h=T.useMemo(()=>new xt(d??V()),[d]),g=T.useMemo(()=>o(l),[l,o,s]),y=T.useMemo(()=>{if(l==null)return null;const p=l;return p.stype?h.build(p,g):null},[l,h,g]);return $.jsx("div",{ref:f,className:i,contentEditable:a,suppressContentEditableWarning:!0,"data-bc-layer":"content","data-testid":"editor-content",children:y})}const or={decorator:{className:"barocss-editor-decorators",zIndex:10},selection:{className:"barocss-editor-selection",zIndex:100},context:{className:"barocss-editor-context",zIndex:200},custom:{className:"barocss-editor-custom",zIndex:1e3}};function q({layer:c,className:t,style:e,children:r}){const n=or[c]??{className:"",zIndex:0},o={position:"absolute",top:0,left:0,right:0,bottom:0,pointerEvents:"none",zIndex:n.zIndex};return $.jsx("div",{className:t??n.className,style:e?{...o,...e}:o,"data-bc-layer":c,children:r})}function rt({layer:c,registry:t}){const{editor:e,getMergedDecorators:r,decoratorVersion:n}=et(),[o,s]=T.useState(()=>{var l;return((l=e.getDocumentProxy)==null?void 0:l.call(e))??null});T.useEffect(()=>{var u,f;const l=()=>{var h;return s(((h=e.getDocumentProxy)==null?void 0:h.call(e))??null)};return(u=e.on)==null||u.call(e,"editor:content.change",l),s(((f=e.getDocumentProxy)==null?void 0:f.call(e))??null),()=>{var h;return(h=e.off)==null?void 0:h.call(e,"editor:content.change",l)}},[e]);const i=T.useMemo(()=>new xt(t??V()),[t]),a=T.useMemo(()=>r(o),[o,r,n]),d=T.useMemo(()=>a.filter(l=>(l.layerTarget??"content")===c),[a,c]);return $.jsx($.Fragment,{children:i.buildOverlayDecorators(d)})}function sr({registry:c,className:t,style:e}){return $.jsx(q,{layer:"decorator",className:t,style:e,children:$.jsx(rt,{layer:"decorator",registry:c})})}function ir({registry:c,className:t,style:e}){return $.jsx(q,{layer:"selection",className:t,style:e,children:$.jsx(rt,{layer:"selection",registry:c})})}function ar({registry:c,className:t,style:e}){return $.jsx(q,{layer:"context",className:t,style:e,children:$.jsx(rt,{layer:"context",registry:c})})}function dr({registry:c,className:t,style:e,children:r}){return $.jsxs(q,{layer:"custom",className:t,style:e,children:[$.jsx(rt,{layer:"custom",registry:c}),r]})}const cr=T.forwardRef(function({options:t={},children:e},r){var I,m,_,v,w,E,A,F;const{editor:n,selectionHandler:o,contentEditableRef:s,decoratorManagerRef:i,decoratorSchemaRegistryRef:a,remoteDecoratorManagerRef:d,patternDecoratorConfigManagerRef:l,decoratorGeneratorManagerRef:u,getMergedDecorators:f,bumpDecoratorVersion:h}=et(),g=T.useRef(null);T.useImperativeHandle(r,()=>(g.current||(g.current={addDecorator(x){var M,O;if("generate"in x){(M=u.current)==null||M.registerGenerator(x,h),h();return}(O=i.current)==null||O.add(x)},removeDecorator(x){var M;try{(M=i.current)==null||M.remove(x)}catch{}},updateDecorator(x,M){var O;(O=i.current)==null||O.update(x,M)},getDecorators(x){var k;const M=((k=n.getDocumentProxy)==null?void 0:k.call(n))??null;let O=f(M);(x==null?void 0:x.enabledOnly)!==!1&&(O=O.filter(R=>R.enabled!==!1)),x!=null&&x.category&&(O=O.filter(R=>R.category===x.category)),x!=null&&x.type&&(O=O.filter(R=>R.stype===x.type)),x!=null&&x.nodeId&&(O=O.filter(R=>{const L=R.target;if(!L)return!1;const B="sid"in L?L.sid:void 0,W="startSid"in L?L.startSid:void 0,H="endSid"in L?L.endSid:void 0;return B===x.nodeId||W===x.nodeId||H===x.nodeId}));const C=(x==null?void 0:x.sortBy)??"id",D=(x==null?void 0:x.sortOrder)??"asc";if(C){const R=D==="desc"?-1:1;O=[...O].sort((L,B)=>{const W=C==="id"?L.sid:C==="type"?L.stype:L.category,H=C==="id"?B.sid:C==="type"?B.stype:B.category;return W.localeCompare(H)*R})}return O},getDecorator(x){var D,k,R;const O=f(((D=n.getDocumentProxy)==null?void 0:D.call(n))??null).find(L=>L.sid===x);if(O)return O;const C=(k=i.current)==null?void 0:k.get(x);return C||((R=d.current)==null?void 0:R.get(x))},exportDecorators(){var C,D;const x=(((C=i.current)==null?void 0:C.getAll())??[]).filter(k=>k.decoratorType!=="pattern").map(k=>{const{decoratorType:R,...L}=k;return L}),O=(((D=l.current)==null?void 0:D.getConfigs())??[]).filter(k=>k.pattern instanceof RegExp).map(k=>({sid:k.sid,stype:k.stype,category:k.category,pattern:{source:k.pattern.source,flags:k.pattern.flags},priority:k.priority,enabled:k.enabled}));return{version:"1.0.0",targetDecorators:x,patternDecorators:O}},loadDecorators(x,M){var O,C,D,k,R,L;(O=i.current)==null||O.clear(),(C=d.current)==null||C.clear(),(D=l.current)==null||D.clear(),(k=u.current)==null||k.clear();for(const B of x.targetDecorators)(R=i.current)==null||R.add({...B,decoratorType:"target"});for(const B of x.patternDecorators){const W=M==null?void 0:M[B.sid];if(!W){console.warn(`[EditorView] Pattern '${B.sid}' functions not provided; skipping.`);continue}const H=new RegExp(B.pattern.source,B.pattern.flags);(L=l.current)==null||L.addConfig({sid:B.sid,stype:B.stype,category:B.category,pattern:H,extractData:W.extractData,createDecorator:W.createDecorator,priority:B.priority,enabled:B.enabled})}h()},get contentEditableElement(){return s.current??null},convertModelSelectionToDOM(x){o.convertModelSelectionToDOM(x)},convertDOMSelectionToModel(x){return o.convertDOMSelectionToModel(x)},convertStaticRangeToModel(x){return o.convertStaticRangeToModel(x)},defineDecoratorType(x,M,O){const C=a.current;C&&(M==="layer"?C.registerLayerType(x,O):M==="inline"?C.registerInlineType(x,O):C.registerBlockType(x,O))},get decoratorManager(){return i.current??null},get remoteDecoratorManager(){return d.current??null},get patternDecoratorConfigManager(){return l.current??null},get decoratorGeneratorManager(){return u.current??null}}),g.current),[n,o,s,i,a,d,l,u,f,h]);const{className:y="",layers:p}=t,N={registry:t.registry,className:"barocss-editor-content",editable:!0,...p==null?void 0:p.content};return $.jsxs("div",{className:y,style:{position:"relative",overflow:"hidden"},"data-editor-view":"true",children:[$.jsx(ct,{options:N}),$.jsx(sr,{registry:t.registry,className:(I=p==null?void 0:p.decorator)==null?void 0:I.className,style:(m=p==null?void 0:p.decorator)==null?void 0:m.style}),$.jsx(ir,{registry:t.registry,className:(_=p==null?void 0:p.selection)==null?void 0:_.className,style:(v=p==null?void 0:p.selection)==null?void 0:v.style}),$.jsx(ar,{registry:t.registry,className:(w=p==null?void 0:p.context)==null?void 0:w.className,style:(E=p==null?void 0:p.context)==null?void 0:E.style}),$.jsx(dr,{registry:t.registry,className:(A=p==null?void 0:p.custom)==null?void 0:A.className,style:(F=p==null?void 0:p.custom)==null?void 0:F.style,children:e})]})}),lr=T.forwardRef(function({editor:t,options:e={},children:r},n){return $.jsx(Mt,{editor:t,children:$.jsx(cr,{ref:n,options:e,children:r})})});function X(c){return function({className:e,style:r,children:n}){return $.jsx(q,{layer:c,className:e,style:r,children:n})}}const ur=Object.assign(lr,{ContentLayer:ct,DecoratorLayer:X("decorator"),SelectionLayer:X("selection"),ContextLayer:X("context"),CustomLayer:X("custom"),Layer:q});exports.EditorView=ur;exports.EditorViewContentLayer=ct;exports.EditorViewContextProvider=Mt;exports.EditorViewLayer=q;exports.createMutationObserverManager=Ct;exports.useEditorViewContext=et;exports.useOptionalEditorViewContext=nr;
|
|
1
|
+
"use strict";var ie=Object.defineProperty;var ae=(d,t,e)=>t in d?ie(d,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):d[t]=e;var y=(d,t,e)=>ae(d,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=require("react/jsx-runtime"),O=require("react");function de(d){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(d){for(const e in d)if(e!=="default"){const r=Object.getOwnPropertyDescriptor(d,e);Object.defineProperty(t,e,r.get?r:{enumerable:!0,get:()=>d[e]})}}return t.default=d,Object.freeze(t)}const rt=de(O);class ce{constructor(t={}){y(this,"_renderers",new Map);y(this,"_components",new Map);y(this,"_options");this._options={global:!0,...t}}register(t){const e=t.template;if(e&&typeof e=="object"&&(e.type==="external"||"managesDOM"in e)){this.registerComponent(t.nodeType,e);return}if(t.template&&typeof t.template=="object"&&"type"in t.template&&t.template.type==="component"){const r=t.template;if(r.component&&typeof r.component=="function"){this.registerContextComponent(t.nodeType,r.component),this._renderers.set(t.nodeType,t);return}}this._renderers.set(t.nodeType,t)}get(t){const e=this._renderers.get(t);if(e)return e;const r=this.getComponent(t);if(r)return{type:"renderer",nodeType:t,template:r}}getAll(){return Array.from(this._renderers.values())}remove(t){return this._renderers.delete(t)}has(t){return this._renderers.has(t)?!0:this._options.global?!1:Z().has(t)}clear(){this._renderers.clear()}registerComponent(t,e){this._components.set(t,e)}getComponent(t){const e=this._components.get(t);if(e)return e;if(this._options.global===!1)return Z().getComponent(t)}removeComponent(t){return this._components.delete(t)}hasComponent(t){return this._components.has(t)?!0:this._options.global===!1?Z().hasComponent(t):!1}clearComponents(){this._components.clear()}getMarkRenderer(t){const e=this._renderers.get(`mark:${t}`);if(e&&e.template)return e.template;const r=this.getComponent(`mark:${t}`);if(r&&r.template)return r.template}registerContextComponent(t,e){const r={template:e,managesDOM:!1,mount:(n,o)=>o,update:()=>{},unmount:()=>{}};this._components.set(t,r)}}const le=new ce({global:!0});function Z(){return le}function ot(d,t,e){return Math.max(t,Math.min(e,d))}function kt(d,t){const e=(d==null?void 0:d.length)??0;if(!d||e===0)return[];const r=Array.isArray(t)?t:[],n=r.filter(c=>c&&!c.range),o=r.filter(c=>c&&c.range),s=new Set;s.add(0),s.add(e);for(const c of o){if(!(c!=null&&c.range))continue;const l=ot(c.range[0]??0,0,e),u=ot(c.range[1]??0,0,e);u<=l||(s.add(l),s.add(u))}const i=Array.from(s.values()).sort((c,l)=>c-l),a=[];for(let c=0;c<i.length-1;c++){const l=i[c],u=i[c+1];if(u<=l)continue;const f=d.slice(l,u),h=[];for(const g of n){const m=g.stype;m&&h.push(m)}for(const g of o){const m=ot(g.range[0]??0,0,e),p=ot(g.range[1]??0,0,e);if(!(p<=m)&&m<u&&p>l){const N=g.stype;N&&h.push(N)}}a.push({start:l,end:u,text:f,types:Array.from(new Set(h))})}return a}function dt(d){return d.target?"sid"in d.target?{start:d.target.startOffset,end:d.target.endOffset}:{start:d.target.startOffset,end:d.target.endOffset}:{}}function Ft(d,t){return!d||!(t!=null&&t.length)?[]:t.filter(e=>e!=null&&e.target?"sid"in e.target?e.target.sid===d:e.target.startSid===d||e.target.endSid===d:!1)}function ue(d,t){return!d||!(t!=null&&t.length)?[]:t.filter(e=>e.category!=="inline"||!e.target?!1:"sid"in e.target?e.target.sid===d:e.target.startSid===d||e.target.endSid===d)}function Ut(d){const t={block:[],layer:[],inline:[]};for(const e of d){if(!(e!=null&&e.category))continue;const r=e.category;Array.isArray(t[r])&&t[r].push(e)}return t}function fe(d,t){const e=d.length;if(e===0||t.length===0)return[{text:d,start:0,end:e}];const r=new Set([0,e]),n=new Map;for(const a of t){if(a.category!=="inline")continue;const c=dt(a);if(c.start===void 0||c.end===void 0)continue;const l=Math.max(0,Math.min(c.start,e)),u=Math.max(l,Math.min(c.end,e));u<=l||(r.add(l),r.add(u),n.has(l)||n.set(l,[]),n.get(l).push(a))}const o=Array.from(r).sort((a,c)=>a-c),s=[],i=Array.from(n.keys()).sort((a,c)=>a-c);for(let a=0;a<o.length-1;a++){const c=o[a],l=o[a+1];if(l<=c)continue;const u=d.slice(c,l),f=[];for(const m of i){if(m>c)break;const p=n.get(m)??[];for(const N of p){const x=dt(N);x.start===void 0||x.end===void 0||x.start<=c&&x.end>=l&&f.push(N)}}if(f.length===0){const m=t.find(p=>{if(p.category!=="inline")return!1;const N=dt(p);return N.start!==void 0&&N.end!==void 0&&N.start<=c&&N.end>=l});m&&f.push(m)}const h=f[0],g=f.length>1?f:void 0;s.push({text:u,decorator:h,decorators:g,start:c,end:l})}return s}function he(d,t){return d.map(e=>{const r=dt(e);if(r.start==null||r.end==null)return e;if(r.end<=t.start||r.start>=t.end)return null;const n=Math.max(0,r.start-t.start),o=Math.min(t.text.length,r.end-t.start);return{...e,target:{...e.target,startOffset:n,endOffset:o}}}).filter(e=>e!==null)}const{createElement:K,cloneElement:ge}=rt;function yt(d,t){return t.split(".").reduce((e,r)=>e==null?void 0:e[r],d)}function nt(d){return!!d&&typeof d=="object"&&d.type==="element"}function pe(d){return!!d&&typeof d=="object"&&d.type==="data"}function jt(d){return!!d&&typeof d=="object"&&d.type==="component"}function me(d){return!!d&&typeof d=="object"&&d.__attrData===!0}function Ht(d,t){return typeof d=="function"?d(t):d}function Wt(d,t){if(typeof d=="function")return d(t);if(me(d)){const e=yt(t,d.path);return e??d.defaultValue}if(pe(d)){const e=d.getter?d.getter(t):d.path?yt(t,d.path):void 0;return e??d.defaultValue}return d}function ye(d,t){const e={};for(const[r,n]of Object.entries(d)){const o=Wt(n,t);o!=null&&(e[r]=o)}return e}function qt(d,t){if(!d)return{};const e={};for(const[r,n]of Object.entries(d)){const o=Wt(n,t);o!=null&&(r==="className"||r==="class"?e.className=typeof o=="object"&&o!==null&&!Array.isArray(o)?Object.entries(o).filter(([,s])=>s).map(([s])=>s).join(" "):Array.isArray(o)?o.filter(Boolean).join(" "):String(o):r==="style"&&typeof o=="object"&&o!==null&&!Array.isArray(o)?e.style=ye(o,t):e[r]=o)}return e}function Nt(d,t){const e=[];for(const r of d)if(Array.isArray(r))e.push(...Nt(r,t));else if(typeof r=="function"){const n=r(t);Array.isArray(n)?e.push(...Nt(n,t)):e.push(n)}else e.push(r);return e}function wt(d,t,e,r){var c;const n=(c=d.get)==null?void 0:c.call(d,t);if(!n||!n.template)throw new Error(`[renderer-react] No renderer for node type '${t}'. Register with define().`);const o=n.template,s=o;if(typeof(s==null?void 0:s.reactComponent)=="function"){const l=typeof e=="object"&&e!==null?e:{},u={...r,sid:e.sid},f=(r==null?void 0:r.decorators)??[],h=e.content;let g=[];if(Array.isArray(h))for(const p of h){const N=p.stype,x=p.sid;if(!N)continue;const S=wt(d,N,p,u);if(x&&f.length>0){const b=Ft(x,f),v=Ut(b),I=[...v.block,...v.layer];if(I.length>0){for(const _ of I)(_.position??"after")==="before"&&g.push(J(d,_));g.push(S);for(const _ of I)(_.position??"after")!=="before"&&g.push(J(d,_))}else g.push(S)}else g.push(S)}const m={...l,model:e,sid:e.sid,stype:t,key:e.sid,"data-bc-sid":e.sid,"data-bc-stype":t,children:g.length>0?g:void 0};return K(s.reactComponent,m)}if((s==null?void 0:s.managesDOM)===!0)return K("div",{key:e.sid,"data-bc-sid":e.sid,"data-bc-stype":t,className:"react-renderer-external-placeholder"},"Component");const i={...r,sid:e.sid};let a=o;if(typeof a=="function"){const l=i.contextStub??lt(d);a=a({},e,l)}if(nt(a))return ut(d,a,e,i);if(jt(a)&&typeof a.component=="function"){const l=i.contextStub??lt(d),u=a.component({},e,l);if(nt(u))return ut(d,u,e,i)}return null}function lt(d){return{registry:{get:()=>{},getComponent:t=>{var e;return(e=d.getComponent)==null?void 0:e.call(d,t)},register:()=>{},setState:()=>!1,getState:()=>({}),toggleState:()=>!1},getState:()=>{},setState:()=>{},toggleState:()=>{},initState:()=>{}}}function ut(d,t,e,r){const n=Ht(t.tag,e),o=qt(t.attributes,e),s=Se(d,t.children??[],e,r),i={...o,key:e.sid,"data-bc-sid":e.sid,"data-bc-stype":e.stype};return K(n,i,...s)}function J(d,t){var u,f;const e=(u=d.get)==null?void 0:u.call(d,t.stype),r=(f=d.getComponent)==null?void 0:f.call(d,t.stype),n=(e==null?void 0:e.template)??r;if(!n)return K("div",{key:t.sid,"data-decorator-sid":t.sid,"data-decorator-stype":t.stype,"data-decorator-category":t.category,"data-decorator-missing-renderer":t.stype});const o=n;if(typeof(o==null?void 0:o.reactComponent)=="function"){const h={key:t.sid,"data-decorator-sid":t.sid,"data-decorator-stype":t.stype,"data-decorator-category":t.category,decorator:t,model:t.data??{},sid:t.sid,stype:t.stype,category:t.category,data:t.data};return K(o.reactComponent,h)}const s=t.data??{};let i=n;if(typeof i=="function"){const h=lt(d);i=i({},s,h)}if(!nt(i))return K("div",{key:t.sid,"data-decorator-sid":t.sid,"data-decorator-stype":t.stype,"data-decorator-category":t.category});const a=ut(d,i,s,{decorators:[]}),c=t.position??(t.category!=="inline"?"after":void 0),l={key:t.sid,"data-decorator-sid":t.sid,"data-decorator-stype":t.stype,"data-decorator-category":t.category};return c&&(l["data-decorator-position"]=c),rt.isValidElement(a)&&typeof a=="object"&&a.props?ge(a,l):K("span",l,a)}function Ne(d,t,e){if(t&&nt(t))return t;if(t&&jt(t)){const r=t.component;if(typeof r=="function"){const n=lt(d),o=r({},e,n);if(o&&nt(o))return o}}return null}function Et(d,t,e,r){var i;const n={text:t.text,run:t,model:e};let o=t.text;const s=t.types??[];for(let a=s.length-1;a>=0;a--){const c=s[a],l=(i=d.getMarkRenderer)==null?void 0:i.call(d,c),u=l?Ne(d,l,n):null;if(!u)continue;const f=`${r}_${c}_${a}`,h=Ht(u.tag,n),g=qt(u.attributes,n);o=K(h,{...g,key:f},o)}return o}function Se(d,t,e,r){var a;const n=Nt(t,e),o=[],s=(r==null?void 0:r.decorators)??[],i=(r==null?void 0:r.sid)??e.sid;for(const c of n){if(typeof c=="string"||typeof c=="number"){o.push(c);continue}if(!c||typeof c!="object")continue;const l=c.type;if(l==="slot"){const u=e.content;if(Array.isArray(u))for(const f of u){const h=f.stype,g=f.sid;if(h){const m=wt(d,h,f,{...r,decorators:s});if(g&&s.length>0){const p=Ft(g,s),N=Ut(p),x=[...N.block,...N.layer];if(x.length>0){const S=[],b=[];for(const v of x){const I=J(d,v);(v.position??"after")==="before"?S.push(I):b.push(I)}o.push(...S,m,...b)}else o.push(m)}else o.push(m)}}continue}if(l==="data"){const u=c,f=u.getter?u.getter(e):u.path?yt(e,u.path):void 0,h=f??u.defaultValue,g=h!=null?String(h):"",m=e.marks,p=u.path==="text"||u.path==null&&typeof h=="string",N=i?ue(i,s):[];if(p&&(Array.isArray(m)&&m.length>0||N.length>0)){const x=Array.isArray(m)&&m.length>0?kt(g,m):[{start:0,end:g.length,text:g,types:[]}],S=e.sid??"";for(let b=0;b<x.length;b++){const v=x[b],I=he(N,{start:v.start,end:v.end,text:v.text}),_=fe(v.text,I);for(const C of _){if(!C.text)continue;const D=(a=v.types)!=null&&a.length?Et(d,{...v,text:C.text,start:C.start,end:C.end},e,`${S}_r${b}`):C.text,w=C.decorators??(C.decorator?[C.decorator]:[]);if(w.length===0){o.push(D);continue}const M=w.filter(k=>k.category==="inline"&&k.position==="before"),T=w.filter(k=>k.category==="inline"&&k.position==="after"),A=w.filter(k=>!(k.category==="inline"&&(k.position==="before"||k.position==="after")));for(const k of M)o.push(J(d,k));let R=D;for(const k of A){const L=J(d,k);R=rt.isValidElement(L)?rt.cloneElement(L,{},R):K("span",{key:k.sid,"data-decorator-sid":k.sid},R)}o.push(R);for(const k of T)o.push(J(d,k))}}}else if(Array.isArray(m)&&m.length>0&&p){const x=kt(g,m),S=e.sid??"";for(let b=0;b<x.length;b++){const v=x[b];!v.types||v.types.length===0?o.push(v.text):o.push(Et(d,v,e,`${S}_r${b}`))}}else o.push(g);continue}if(l==="element"){o.push(ut(d,c,e,r));continue}}return o}function xe(d,t){return t!=null&&t.length?K(rt.Fragment,null,...t.map(e=>J(d,e))):null}class zt{constructor(t,e){y(this,"registry");if(this.registry=t??Z(),!this.registry)throw new Error("[ReactRenderer] Registry is required. Pass a RendererRegistry or ensure getGlobalRegistry() is available.")}getRegistry(){return this.registry}build(t,e=[]){if(!t||!t.stype)throw new Error("[ReactRenderer] build: model must have stype property");return wt(this.registry,t.stype,t,{decorators:e})}buildOverlayDecorators(t){return xe(this.registry,t??[])}}const Vt=(()=>{if(typeof navigator>"u")return!1;const d=navigator.platform.toUpperCase(),t=navigator.userAgent.toUpperCase();return d.indexOf("MAC")>=0||t.indexOf("MAC")>=0})(),Ie=typeof navigator>"u"?!1:navigator.platform.toUpperCase().indexOf("LINUX")>=0,we=(()=>{if(typeof navigator>"u")return!1;const d=navigator.platform.toUpperCase(),t=navigator.userAgent.toUpperCase();return d.indexOf("WIN")>=0||t.indexOf("WIN")>=0})();function ve(d){const t={" ":"Space",ArrowUp:"Up",ArrowDown:"Down",ArrowLeft:"Left",ArrowRight:"Right"};return t[d]?t[d]:d.length===1&&/[A-Za-z]/.test(d)?d.toLowerCase():d}function _e(d){const t=[];Vt?(d.metaKey&&t.push("Cmd"),d.ctrlKey&&t.push("Ctrl")):(d.ctrlKey&&t.push("Ctrl"),d.metaKey&&t.push("Meta")),d.altKey&&t.push("Alt"),d.shiftKey&&t.push("Shift");let e=d.key;if(!e||e==="Unidentified")if(d.code)e=be(d.code);else return"";const r=ve(e);return t.push(r),t.join("+")}function be(d){return d.startsWith("Key")?d.substring(3).toLowerCase():d.startsWith("Digit")?d.substring(5):d.startsWith("Numpad")?d.substring(6):d}function ke(d){const t=d.split("+"),e=[];for(let r=0;r<t.length;r++){const n=t[r].trim();if(!n)continue;const o={ctrl:"Ctrl",cmd:"Cmd",alt:"Alt",shift:"Shift",meta:"Meta",mod:"Mod"},s=n.toLowerCase();o[s]?e.push(o[s]):n.length===1&&/[A-Za-z]/.test(n)?e.push(n.toLowerCase()):e.push(n)}return e.join("+")}function Ee(d){const t=[d];if(d.startsWith("Mod+")){const e=d.substring(4);t.push(`Ctrl+${e}`),t.push(`Cmd+${e}`)}else if(d.startsWith("Ctrl+")){const e=d.substring(5);t.push(`Mod+${e}`)}else if(d.startsWith("Cmd+")){const e=d.substring(4);t.push(`Mod+${e}`)}return t}let Kt=class{constructor(){this.listeners=new Map}on(t,e){this.listeners.has(t)||this.listeners.set(t,[]),this.listeners.get(t).push(e)}off(t,e){const r=this.listeners.get(t);if(r){const n=r.indexOf(e);n!==-1&&r.splice(n,1)}}emit(t,...e){const r=this.listeners.get(t);r&&r.forEach(n=>{try{n(...e)}catch(o){console.error(`Error in event listener for ${String(t)}:`,o)}})}removeAllListeners(){this.listeners.clear()}};class Te extends Kt{constructor(t){super(),this.decorators=new Map,this.validator=t}add(t){if(this.validator){const e=this.validator.validateDecorator(t);if(!e.valid)throw new Error(`Invalid decorator: ${e.errors.join(", ")}`);const r=this.validator.applyDefaults(t);if(this.decorators.has(r.sid))throw new Error(`Decorator with id '${r.sid}' already exists`);this.decorators.set(r.sid,r),this.emit("decorator:added",r)}else{if(this.decorators.has(t.sid))throw new Error(`Decorator with id '${t.sid}' already exists`);this.decorators.set(t.sid,t),this.emit("decorator:added",t)}}update(t,e,r={}){const n=this.decorators.get(t);if(!n)throw new Error(`Decorator with id '${t}' not found`);const o=r.partial!==!1?{...n,...e}:{...e};if(o.sid=n.sid,this.validator){const s=this.validator.validateDecorator(o);if(!s.valid)throw new Error(`Invalid decorator update: ${s.errors.join(", ")}`);const i=this.validator.applyDefaults(o);this.decorators.set(t,i),this.emit("decorator:updated",i)}else this.decorators.set(t,o),this.emit("decorator:updated",o)}remove(t){if(!this.decorators.get(t))throw new Error(`Decorator with id '${t}' not found`);this.decorators.delete(t),this.emit("decorator:removed",t)}setEnabled(t,e){return this.decorators.get(t)?(this.update(t,{enabled:e},{partial:!0}),!0):!1}isEnabled(t){const e=this.decorators.get(t);return(e==null?void 0:e.enabled)!==!1}get(t){return this.decorators.get(t)}getAll(t={}){let e=Array.from(this.decorators.values());if(t.enabledOnly!==!1&&(e=e.filter(r=>r.enabled!==!1)),t.type&&(e=e.filter(r=>r.stype===t.type)),t.category&&(e=e.filter(r=>r.category===t.category)),t.nodeId&&(e=e.filter(r=>r.target&&"sid"in r.target?r.target.sid===t.nodeId:!1)),t.sortBy){const r=t.sortOrder??"asc";e.sort((n,o)=>{let s,i;switch(t.sortBy){case"id":s=n.sid,i=o.sid;break;case"type":s=n.stype,i=o.stype;break;case"category":s=n.category,i=o.category;break;default:return 0}return s<i?r==="asc"?-1:1:s>i?r==="asc"?1:-1:0})}return e}getByType(t){return this.getAll({type:t})}getByCategory(t){return this.getAll({category:t})}getByNode(t){return this.getAll({nodeId:t})}getLayerDecorators(){return this.getByCategory("layer")}getInlineDecorators(){return this.getByCategory("inline")}getBlockDecorators(){return this.getByCategory("block")}has(t){return this.decorators.has(t)}size(){return this.decorators.size}clear(){const t=Array.from(this.decorators.keys());this.decorators.clear(),t.forEach(e=>this.emit("decorator:removed",e))}clearByNode(t){this.getByNode(t).forEach(e=>this.remove(e.sid))}clearByType(t){this.getByType(t).forEach(e=>this.remove(e.sid))}clearByCategory(t){this.getByCategory(t).forEach(e=>this.remove(e.sid))}updateData(t,e){const r=this.decorators.get(t);if(!r)throw new Error(`Decorator with id '${t}' not found`);this.update(t,{data:{...r.data,...e}})}addMany(t){t.forEach(e=>this.add(e))}removeMany(t){t.forEach(e=>this.remove(e))}}class Oe extends Kt{constructor(){super(...arguments),this.remoteDecorators=new Map,this.ownerMap=new Map}setRemoteDecorator(t,e){const r=t.sid;this.remoteDecorators.set(r,{...t,data:{...t.data||{},_remoteOwner:{userId:e.userId,agentId:e.agentId,sessionId:e.sessionId}}}),this.ownerMap.set(r,e),this.emit("change")}removeRemoteDecorator(t){this.remoteDecorators.delete(t),this.ownerMap.delete(t),this.emit("change")}removeByOwner(t){const e=[];for(const[r,n]of this.ownerMap.entries())(n==null?void 0:n.userId)===t&&e.push(r);e.length>0&&(e.forEach(r=>{this.remoteDecorators.delete(r),this.ownerMap.delete(r)}),this.emit("change"))}removeByAgent(t){const e=[];for(const[r,n]of this.ownerMap.entries())(n==null?void 0:n.agentId)===t&&e.push(r);e.length>0&&(e.forEach(r=>{this.remoteDecorators.delete(r),this.ownerMap.delete(r)}),this.emit("change"))}removeBySession(t){const e=[];for(const[r,n]of this.ownerMap.entries())(n==null?void 0:n.sessionId)===t&&e.push(r);e.length>0&&(e.forEach(r=>{this.remoteDecorators.delete(r),this.ownerMap.delete(r)}),this.emit("change"))}getAll(){return Array.from(this.remoteDecorators.values())}getByOwner(t){return this.getAll().filter(e=>{var r;return((r=this.ownerMap.get(e.sid))==null?void 0:r.userId)===t})}getByAgent(t){return this.getAll().filter(e=>{var r;return((r=this.ownerMap.get(e.sid))==null?void 0:r.agentId)===t})}getOwner(t){return this.ownerMap.get(t)}get(t){return this.remoteDecorators.get(t)}has(t){return this.remoteDecorators.has(t)}size(){return this.remoteDecorators.size}clear(){(this.remoteDecorators.size>0||this.ownerMap.size>0)&&(this.remoteDecorators.clear(),this.ownerMap.clear(),this.emit("change"))}}class Ce{constructor(){this.configs=[]}setConfigs(t){this.configs=[...t]}addConfig(t){const e=this.configs.findIndex(r=>r.sid===t.sid);e>=0?this.configs[e]=t:this.configs.push(t)}removeConfig(t){const e=this.configs.findIndex(r=>r.sid===t);return e>=0?(this.configs.splice(e,1),!0):!1}getConfigs(t=!1){const e=[...this.configs];return t?e.filter(r=>r.enabled!==!1):e}setConfigEnabled(t,e){const r=this.configs.find(n=>n.sid===t);return r?(r.enabled=e,!0):!1}isConfigEnabled(t){const e=this.configs.find(r=>r.sid===t);return(e==null?void 0:e.enabled)!==!1}clear(){this.configs=[]}}function Ae(d,t,e){if(!t||!d||e.length===0)return[];const r=[...e].sort((o,s)=>(o.priority??100)-(s.priority??100)),n=[];for(const o of r){if(o.enabled===!1)continue;let s;typeof o.pattern=="function"?s=o.pattern(t):s=Array.from(t.matchAll(o.pattern)).map(a=>({match:a[0],index:a.index??-1,groups:a.groups,...Object.fromEntries(Array.from({length:a.length},(c,l)=>[l,a[l]]))}));for(const i of s){if(i.index===void 0||i.index<0)continue;const a=i.index,c=a+i.match.length,l={0:i.match,index:i.index,input:t,groups:i.groups,length:1,...Object.fromEntries(Object.entries(i).filter(([g])=>!isNaN(Number(g))))},u=o.extractData(l),f=o.createDecorator(d,a,c,u),h=Array.isArray(f)?f:[f];for(const g of h)n.push({sid:g.sid,stype:o.stype,category:g.category??o.category,layerTarget:g.layerTarget,target:g.target,data:g.data??{}})}}return n}function Me(d,t){if(!d||t.length===0)return[];const e=[];function r(n){const o=n.sid??n.id,s=typeof n.text=="string"?n.text:void 0;o&&s&&e.push(...Ae(o,s,t));const i=n.content??n.children;if(Array.isArray(i))for(const a of i)a&&typeof a=="object"&&r(a)}return r(d),e}class De{constructor(){this.generators=new Map,this.changeCallbacks=new Map}registerGenerator(t,e){if(this.generators.set(t.sid,t),t.onDidChange&&e){const r=t.onDidChange(e);this.changeCallbacks.set(t.sid,r)}}unregisterGenerator(t){const e=this.changeCallbacks.get(t);return e&&(e(),this.changeCallbacks.delete(t)),this.generators.delete(t)}getGenerator(t){return this.generators.get(t)}getAllGenerators(t=!1){const e=Array.from(this.generators.values());return t?e.filter(r=>r.enabled!==!1):e}setGeneratorEnabled(t,e){const r=this.generators.get(t);return r?(r.enabled=e,!0):!1}isGeneratorEnabled(t){var e;return((e=this.generators.get(t))==null?void 0:e.enabled)!==!1}clear(){for(const t of this.changeCallbacks.values())t();this.changeCallbacks.clear(),this.generators.clear()}generateDecorators(t,e,r){const n=this.getAllGenerators(!0).sort((s,i)=>(s.priority??100)-(i.priority??100)),o=[];for(const s of n)try{o.push(...s.generate(t,e,r))}catch(i){console.error(`[DecoratorGeneratorManager] Error in generator '${s.sid}':`,i)}return o}}class Re{constructor(){this.typeSchemas=new Map}registerLayerType(t,e){this.typeSchemas.set(`layer:${t}`,{...e,description:e.description??`Layer decorator: ${t}`})}registerInlineType(t,e){this.typeSchemas.set(`inline:${t}`,{...e,description:e.description??`Inline decorator: ${t}`})}registerBlockType(t,e){this.typeSchemas.set(`block:${t}`,{...e,description:e.description??`Block decorator: ${t}`})}getTypeSchema(t,e){return this.typeSchemas.get(`${t}:${e}`)}validateDecorator(t){const e=[];t.sid||e.push("Decorator id is required"),t.category||e.push("Decorator category is required"),t.stype||e.push("Decorator type is required");const r=this.getTypeSchema(t.category,t.stype);if(r!=null&&r.dataSchema){const n=this.validateData(t.data??{},r.dataSchema);e.push(...n)}return{valid:e.length===0,errors:e}}validateData(t,e){const r=[];for(const[n,o]of Object.entries(e)){if(o.required&&!(n in t)){r.push(`Required field '${n}' is missing`);continue}const s=t[n];if(s!=null){const i=Array.isArray(s)?"array":typeof s;i!==o.type&&r.push(`Field '${n}' should be ${o.type}, got ${i}`)}}return r}applyDefaults(t){const e=this.getTypeSchema(t.category,t.stype);if(!(e!=null&&e.dataSchema))return t;const r={...t.data??{}};for(const[n,o]of Object.entries(e.dataSchema))if(o.default!==void 0&&!(n in r)){const s=typeof o.default=="function"?o.default():o.default;r[n]=s}return{...t,data:r}}}const $e=new WeakMap,Le=new Map;function Tt(d){return!!(d.hasAttribute("data-decorator-sid")||d.hasAttribute("data-bc-decorator")||d.hasAttribute("data-decorator-category"))}function St(d,t,e){const r=[];let n=0;const o=e!=null&&e.buildReverseMap?new Map:void 0,s=Array.from(d.childNodes);for(const a of s){if(a.nodeType===Node.TEXT_NODE){const c=a,l=c.textContent??"",u=(e==null?void 0:e.normalizeWhitespace)!==!1?l.trim():l;if(u.length>0){const f=u.length,h=n,g=h+f,m={domTextNode:c,start:h,end:g};r.push(m),o&&o.set(c,{start:h,end:g}),n=g}continue}if(a.nodeType===Node.ELEMENT_NODE){const c=a;if(Tt(c)||e!=null&&e.excludePredicate&&e.excludePredicate(c))continue;const l=document.createTreeWalker(c,NodeFilter.SHOW_TEXT,{acceptNode:f=>{let h=f.parentNode;for(;h&&h!==c;){if(h.nodeType===Node.ELEMENT_NODE&&Tt(h))return NodeFilter.FILTER_REJECT;h=h.parentNode}return NodeFilter.FILTER_ACCEPT}});let u;for(;u=l.nextNode();){const f=u.textContent??"",h=(e==null?void 0:e.normalizeWhitespace)!==!1?f.trim():f;if(h.length>0){const g=h.length,m=n,p=m+g,N={domTextNode:u,start:m,end:p};r.push(N),o&&o.set(u,{start:m,end:p}),n=p}}}}const i={runs:r,total:n,byNode:o};return $e.set(d,i),t&&Le.set(t,i),i}function Ot(d,t){let e=0,r=d.length-1,n=-1;for(;e<=r;){const o=e+r>>1,s=d[o];if(t<s.start)r=o-1;else if(t>=s.end)e=o+1;else{n=o;break}}return n}function Be(d,t,e,r,n="range",o){if(d===e){const h=t<=r,g=Math.min(t,r),m=Math.max(t,r);return{type:n,startNodeId:d,startOffset:g,endNodeId:e,endOffset:m,collapsed:g===m,direction:g===m?"none":h?"forward":"backward"}}const a=((h,g)=>h.localeCompare(g))(d,e)<=0;return{type:n,startNodeId:a?d:e,startOffset:a?t:r,endNodeId:a?e:d,endOffset:a?r:t,collapsed:!1,direction:a?"forward":"backward"}}class Pe{constructor(){y(this,"operations",new Map)}register(t,e){this.operations.set(t,e)}get(t){return this.operations.get(t)}getAll(){return new Map(this.operations)}clear(){this.operations.clear()}}const Qt=new Pe;function E(d,t,e){Qt.register(d,{name:d,execute:t,mapSelection:e})}class Gt{constructor(t){y(this,"_dataStore");y(this,"_currentTransaction",null);y(this,"_schema");y(this,"_editor");y(this,"_isUndoRedoOperation",!1);this._editor=t,this._dataStore=t.dataStore,this._schema=t.dataStore.getActiveSchema()}setSchema(t){this._schema=t}async execute(t,e){var n,o,s,i,a,c,l;let r=null;try{r=await this._dataStore.acquireLock("transaction-execution"),this._beginTransaction("DSL Transaction"),this._dataStore.begin();const u=je(this._dataStore,this._editor.selectionManager.clone(),this._schema),f=u.selection.before,h=[],g=[];let m=null;for(const b of t){const v=await this._executeOperation(b,u);if(Array.isArray(v)){for(const I of v){if(I.result&&I.result.ok===!1)return this._dataStore.end(),{success:!1,errors:[I.result.error||"Operation failed"],operations:h,selectionBefore:f,selectionAfter:u.selection.current};(n=I.result)!=null&&n.selectionAfter&&(m=I.result.selectionAfter)}h.push(...v),v.forEach(I=>{var _;(_=I.result)!=null&&_.inverse&&g.push(I.result.inverse)})}else if(v){const I=v;if(I.result&&I.result.ok===!1)return this._dataStore.end(),{success:!1,errors:[I.result.error||"Operation failed"],operations:h,selectionBefore:f,selectionAfter:u.selection.current};(o=I.result)!=null&&o.selectionAfter&&(m=I.result.selectionAfter),h.push(I),(s=I.result)!=null&&s.inverse&&g.push(I.result.inverse)}}if(u.selection.current){if(m){const b=this._dataStore.resolveAlias(m.nodeId);u.selection.setCaret(b,m.offset)}else if(u.lastCreatedBlock){const b=u.lastCreatedBlock.firstTextNodeId??u.lastCreatedBlock.blockId;u.selection.setCaret(b,0)}}this._dataStore.end(),this._dataStore.commit();const p=u.selection.current;if(h.length>0&&this._shouldAddToHistory(h)){const b=(e==null?void 0:e.preserveSelectionInHistory)!==!1;this._editor.historyManager.push({operations:h,inverseOperations:g.reverse(),description:(i=this._currentTransaction)==null?void 0:i.description,...b?{metadata:{selectionBefore:f?{...f}:null,selectionAfter:p?{...p}:null}}:{}})}const N={success:!0,errors:[],transactionId:this._currentTransaction.sid,operations:h,selectionBefore:f,selectionAfter:p};this._editor.emit("editor:content.change",{content:this._editor.document,transaction:N});const x=((c=(a=this._editor).getSortedExtensions)==null?void 0:c.call(a))||[];if(x.length>0){const b={sid:this._currentTransaction.sid,operations:h,timestamp:this._currentTransaction.timestamp,description:this._currentTransaction.description};x.forEach(v=>{var I;(I=v.onTransaction)==null||I.call(v,this._editor,b)})}return(e==null?void 0:e.applySelectionToView)!==!1&&this._editor.updateSelection(p),this._currentTransaction=null,N}catch(u){try{this._dataStore.rollback()}catch{}const f=(l=this._currentTransaction)==null?void 0:l.sid,h=this._editor.selectionManager.getCurrentSelection();return this._currentTransaction=null,{success:!1,errors:[u instanceof Error?u.message:"Unknown error"],transactionId:f,operations:[],selectionBefore:h,selectionAfter:h}}finally{r&&this._dataStore.releaseLock(r)}}_beginTransaction(t){if(this._currentTransaction)throw new Error("Transaction already in progress");const e=`tx-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return this._currentTransaction={sid:e,operations:[],timestamp:new Date,description:t},e}async _executeOpFunction(t,e){const r=await t.execute(e);if(r&&typeof r=="object"&&"success"in r){const n=r;if(!n.success)throw new Error(n.error||"OpFunction failed");return[]}return[]}async _executeOperation(t,e){if(t&&typeof t=="object"&&"type"in t&&t.type==="op-function")return await this._executeOpFunction(t,e);const r=Qt.get(t.type);if(!r)throw new Error(`Unknown operation type: ${t.type}`);const n=JSON.parse(JSON.stringify(t)),o=await r.execute(n,e);return{...n,result:o}}_shouldAddToHistory(t){return!(t.length===0||this._isUndoRedoOperation)}}function z(d,t){return t.map(e=>({type:e.type,payload:{...e.payload,nodeId:d}}))}class Fe{constructor(t,e,r){y(this,"editor");y(this,"ops");y(this,"options");this.editor=t,this.ops=e,this.options=r}async commit(){var n,o;let t=this.ops;const e=((o=(n=this.editor).getSortedExtensions)==null?void 0:o.call(n))||[];for(const s of e)if(s.onBeforeTransaction){const i={sid:`tx-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,operations:t,timestamp:new Date},a=s.onBeforeTransaction(this.editor,i);if(a===null)return{success:!1,errors:[`Transaction cancelled by extension: ${s.name}`],operations:[],data:void 0,transactionId:void 0};a&&a.operations&&(t=a.operations)}return new Gt(this.editor).execute(t,this.options)}}function $(d,t,e){const n=(Array.isArray(t)?t:[t]).flat();return new Fe(d,n,e)}class Ue{constructor(t){y(this,"before");y(this,"current");this.before=t,this.current=t?{...t}:null}setSelection(t){this.current?Object.assign(this.current,t):this.current={...t}}setCaret(t,e){this.current?(this.current.type="range",this.current.startNodeId=t,this.current.startOffset=e,this.current.endNodeId=t,this.current.endOffset=e,this.current.collapsed=!0,this.current.direction="none"):this.current={type:"range",startNodeId:t,startOffset:e,endNodeId:t,endOffset:e,collapsed:!0,direction:"none"}}setRange(t,e,r,n){this.current?(this.current.type="range",this.current.startNodeId=t,this.current.startOffset=e,this.current.endNodeId=r,this.current.endOffset=n,this.current.collapsed=t===r&&e===n,this.current.direction="forward"):this.current={type:"range",startNodeId:t,startOffset:e,endNodeId:r,endOffset:n,collapsed:t===r&&e===n,direction:"forward"}}clear(){this.current=null}}function je(d,t,e){d.registerSchema(e);const r=t.getCurrentSelection(),n=r?{...r}:null,o=new Ue(n);return{dataStore:d,selectionManager:t,selection:o,schema:e,lastCreatedBlock:void 0}}const Ct=new Map;function U(d,t){return(...e)=>{const r=d(...e);if(!r||typeof r.type!="string")throw new Error("defineOperationDSL builder must return { type, payload? }");return Ct.has(r.type)||Ct.set(r.type,{options:t}),r}}E("setNode",async(d,t)=>{const{node:e,validate:r=!0}=d;if(!e.sid)throw new Error("Node must have an id");return t.dataStore.setNode(e,r),t.dataStore.getNode(e.sid)});E("moveNode",async(d,t)=>{var l;const e=d.payload,{nodeId:r,newParentId:n,position:o}=e,s=t.dataStore.getNode(r);if(!s)throw new Error(`Node not found: ${r}`);if(!t.dataStore.getNode(n))throw new Error(`Parent not found: ${n}`);const a=s.parentId,c=Array.isArray((l=t.dataStore.getNode(a))==null?void 0:l.content)?t.dataStore.getNode(a).content.indexOf(r):void 0;return t.dataStore.content.moveNode(r,n,o),{ok:!0,data:t.dataStore.getNode(r),inverse:{type:"moveNode",payload:{nodeId:r,newParentId:a,position:c}}}});E("reorderChildren",async(d,t)=>{const{parentId:e,childIds:r}=d.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Parent not found: ${e}`);const o=Array.isArray(n.content)?[...n.content]:[];return t.dataStore.content.reorderChildren(e,r),{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"reorderChildren",payload:{parentId:e,childIds:o}}}});E("addChild",async(d,t)=>{const{parentId:e,nodeId:r,child:n,position:o}=d.payload,s=e||r;if(!t.dataStore.getNode(s))throw new Error(`Parent not found: ${s}`);const a=t.dataStore.content.addChild(s,n,o),c=t.dataStore.getNode(a),l=c&&Array.isArray(c.content)&&c.content[0]?c.content[0]:null;return t.lastCreatedBlock={blockId:a,firstTextNodeId:l},{ok:!0,data:c,inverse:{type:"removeChild",payload:{parentId:s,childId:a}},selectionAfter:{nodeId:l??a,offset:0}}});function He(d,t,e){if(!e||e.type!=="range")return null;const r=d.getNode(e.startNodeId);if(!r)return null;if(typeof r.text=="string"){const c=r.text,l=typeof e.startOffset=="number"&&e.startOffset>=0?Math.min(e.startOffset,c.length):0,u=d.getParent(e.startNodeId);return!u||!Array.isArray(u.content)?null:{textNodeId:e.startNodeId,offset:l,textLength:c.length,parentBlock:u}}const n=t==null?void 0:t.getNodeType(r.stype);if((n==null?void 0:n.group)!=="block")return null;const o=r,s=We(d,o.sid);if(!s)return null;const i=typeof s.text=="string"?s.text.length:0,a=d.getParent(o.sid);return!a||!Array.isArray(a.content)?null:{textNodeId:s.sid,offset:i,textLength:i,parentBlock:o}}function We(d,t){const e=d.getNode(t);if(!e||!Array.isArray(e.content))return null;const r=e.content;let n=null;const o=s=>{const i=d.getNode(s);if(!i)return;if(typeof i.text=="string"){n={sid:i.sid,text:i.text};return}const a=i.content;if(Array.isArray(a))for(const c of a)o(c)};for(const s of r)o(s);return n}E("insertParagraph",async(d,t)=>{const{blockType:e="same",selectionAlias:r="insertedBlock"}=d.payload,n=t.dataStore,o=t.schema,s=t.selection.current,i=He(n,o,s);if(!i)throw new Error("insertParagraph: no selection or selection does not resolve to a block text position");const{textNodeId:a,offset:c,textLength:l,parentBlock:u}=i,f=Math.max(0,Math.min(c,l));if(u.content.length===1&&u.content[0]===a&&f>0&&f<l){n.splitTextNode(a,f);const I=n.splitBlockNode(u.sid,1),_=n.getNode(I),C=_&&Array.isArray(_.content)&&_.content[0]?_.content[0]:null;if(t.lastCreatedBlock={blockId:I,firstTextNodeId:C},!C)throw new Error("insertParagraph: splitBlockNode did not yield a text node");return{ok:!0,data:_,inverse:{type:"mergeBlockNodes",payload:{leftNodeId:u.sid,rightNodeId:I}},selectionAfter:{nodeId:C,offset:0}}}const g=u.parentId?n.getNode(n.resolveAlias(u.parentId)):null;if(!g||!Array.isArray(g.content))throw new Error("insertParagraph: parent block has no parent");const m=g.content.indexOf(u.sid);if(m===-1)throw new Error("insertParagraph: block not in parent content");const p=f===l?m+1:m,x={stype:e==="paragraph"?"paragraph":u.stype,attributes:{...u.attributes||{},$alias:r},content:[]},S=n.content.addChild(g.sid,x,p),b=n.content.addChild(S,{stype:"inline-text",text:""},0);return t.lastCreatedBlock={blockId:S,firstTextNodeId:b},{ok:!0,data:n.getNode(S),inverse:{type:"removeChild",payload:{parentId:g.sid,childId:S}},selectionAfter:{nodeId:b,offset:0}}});E("removeChild",async(d,t)=>{const e=d.payload.parentId||d.payload.nodeId,r=d.payload.childId;if(!t.dataStore.getNode(e))throw new Error(`Parent not found: ${e}`);const o=t.dataStore.getNode(r);if(!o)throw new Error(`Child not found: ${r}`);if(!t.dataStore.content.removeChild(e,r))throw new Error(`Failed to remove child ${r}`);return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"addChild",payload:{parentId:e,child:o}}}});E("moveChildren",async(d,t)=>{var c;const{fromParentId:e,toParentId:r,childIds:n,position:o}=d.payload,s=t.dataStore.getNode(e),i=t.dataStore.getNode(r);if(!s)throw new Error(`Parent not found: ${e}`);if(!i)throw new Error(`Parent not found: ${r}`);const a=(n||[]).map(l=>{var g;const u=(g=t.dataStore.getNode(l))==null?void 0:g.parentId,f=u?t.dataStore.getNode(u):void 0,h=Array.isArray(f==null?void 0:f.content)?f.content.indexOf(l):void 0;return{childId:l,prevParentId:u,prevPosition:h}});return t.dataStore.content.moveChildren(e,r,n,o),{ok:!0,data:{fromParent:t.dataStore.getNode(e),toParent:t.dataStore.getNode(r)},inverse:{type:"moveChildren",payload:{fromParentId:r,toParentId:e,childIds:n,position:(c=a[0])==null?void 0:c.prevPosition}}}});E("removeChildren",async(d,t)=>{const{parentId:e,childIds:r}=d.payload;if(!t.dataStore.getNode(e))throw new Error(`Parent not found: ${e}`);const o=(r||[]).map(i=>t.dataStore.getNode(i));return{ok:!0,data:t.dataStore.content.removeChildren(e,r),inverse:{type:"addChild",payload:{parentId:e,children:o}}}});E("copyNode",async(d,t)=>{const{nodeId:e,newParentId:r}=d.payload;if(!t.dataStore.getNode(e))throw new Error(`Node not found: ${e}`);const o=t.dataStore.content.copyNode(e,r);return{ok:!0,data:t.dataStore.getNode(o),inverse:{type:"delete",payload:{nodeId:o}}}});E("cloneNodeWithChildren",async(d,t)=>{const{nodeId:e,newParentId:r}=d.payload;if(!t.dataStore.getNode(e))throw new Error(`Node not found: ${e}`);const o=t.dataStore.content.cloneNodeWithChildren(e,r);return{ok:!0,data:t.dataStore.getNode(o),inverse:{type:"delete",payload:{nodeId:o}}}});E("replacePattern",async(d,t)=>{try{if("range"in d){const{range:l,pattern:u,replacement:f}=d,{startNodeId:h,endNodeId:g,startOffset:m,endOffset:p}=l,N=t.dataStore.getNode(h),x=t.dataStore.getNode(g);if(!N)throw new Error(`Node not found: ${h}`);if(!x)throw new Error(`Node not found: ${g}`);if(typeof N.text!="string"||typeof x.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof m!="number"||typeof p!="number")throw new Error("Invalid range");const S=t.dataStore.range.extractText(l);let b=0,v=S;if(S.length>0){if(u instanceof RegExp){const I=u.flags.includes("g")?u:new RegExp(u.source,u.flags+"g");v=S.replace(I,()=>(b+=1,f))}else{const I=new RegExp(u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");v=S.replace(I,()=>(b+=1,f))}b>0&&t.dataStore.range.replaceText(l,v)}return{ok:!0,data:b}}const{nodeId:e,start:r,end:n,pattern:o,replacement:s}=d,i=t.dataStore.getNode(e);if(!i)throw new Error(`Node not found: ${e}`);if(typeof i.text!="string")throw new Error(`Node ${e} is not a text node`);if(typeof r!="number"||typeof n!="number"||r>n||r<0||n>i.text.length)throw new Error("Invalid range");const a=i.text.substring(r,n);let c=0;if(a.length>0){if(o instanceof RegExp){const l=o.flags.includes("g")?o:new RegExp(o.source,o.flags+"g");a.replace(l,()=>(c+=1,s))}else{const l=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");a.replace(l,()=>(c+=1,s))}c>0&&t.dataStore.range.replaceText({type:"range",startNodeId:e,startOffset:r,endNodeId:e,endOffset:n},a.replace(o,s))}return{ok:!0,data:c}}catch(e){throw new Error(`Failed to replace by pattern: ${e instanceof Error?e.message:"Unknown error"}`)}});E("mergeTextNodes",async(d,t)=>{const{leftNodeId:e,rightNodeId:r}=d.payload,n=t.dataStore.getNode(e),o=t.dataStore.getNode(r);if(!n)throw new Error(`Node not found: ${e}`);if(!o)throw new Error(`Node not found: ${r}`);const s=n.stype,i=o.stype;if(typeof n.text!="string")throw new Error(`Left node is not a text node: ${s||"unknown"}`);if(typeof o.text!="string")throw new Error(`Right node is not a text node: ${i||"unknown"}`);const a=n.text.length,c=t.dataStore.splitMerge.mergeTextNodes(e,r);return{ok:!0,data:c,inverse:{type:"splitTextNode",payload:{nodeId:c,splitPosition:a}}}});E("mergeBlockNodes",async(d,t)=>{const{leftNodeId:e,rightNodeId:r}=d.payload,n=t.dataStore.getNode(e),o=t.dataStore.getNode(r);if(!n)throw new Error(`Node not found: ${e}`);if(!o)throw new Error(`Node not found: ${r}`);if(n.stype!==o.stype)throw new Error(`Cannot merge different node types: ${n.stype} and ${o.stype}`);const s=Array.isArray(n.content)?n.content.length:0,i=t.dataStore.splitMerge.mergeBlockNodes(e,r);return{ok:!0,data:i,inverse:{type:"splitBlockNode",payload:{nodeId:i,splitPosition:s}}}});E("splitBlockNode",async(d,t)=>{const{nodeId:e,splitPosition:r}=d.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Node not found: ${e}`);if(!Array.isArray(n.content))throw new Error("Node has no content to split");const o=t.dataStore.splitMerge.splitBlockNode(e,r),s=t.dataStore.getNode(o),i=s&&Array.isArray(s.content)&&s.content[0]?s.content[0]:null;return t.lastCreatedBlock={blockId:o,firstTextNodeId:i},{ok:!0,data:o,inverse:{type:"mergeBlockNodes",payload:{leftNodeId:e,rightNodeId:o}},selectionAfter:{nodeId:i??o,offset:0}}});E("splitTextNode",async(d,t)=>{const{nodeId:e,splitPosition:r}=d.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Node not found: ${e}`);if(typeof n.text!="string")throw new Error(`Node ${e} is not a text node`);const o=t.dataStore.splitMerge.splitTextNode(e,r);return{ok:!0,data:o,inverse:{type:"mergeTextNodes",payload:{leftNodeId:e,rightNodeId:o}}}});E("autoMergeTextNodes",async(d,t)=>{const{nodeId:e}=d.payload;if(!t.dataStore.getNode(e))throw new Error(`Node not found: ${e}`);return{ok:!0,data:t.dataStore.splitMerge.autoMergeTextNodes(e),inverse:void 0}});E("setText",async(d,t)=>{var s;const{nodeId:e,text:r}=d.payload;if(r==null)throw new Error("Text is required for setText operation");if(typeof r!="string")throw new Error("Text must be a string");const n=t.dataStore.getNode(e);if(!n)throw new Error(`Node not found: ${e}`);const o=t.dataStore.updateNode(e,{text:r});if(!o||o.valid!==!0){const i=((s=o==null?void 0:o.errors)==null?void 0:s[0])||"Update failed";throw new Error(i)}return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"setText",payload:{nodeId:e,text:n.text}}}});E("setAttrs",async(d,t)=>{var s;const{nodeId:e,attrs:r}=d.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Node not found: ${e}`);const o=t.dataStore.updateNode(e,{attributes:{...n.attributes||{},...r}});if(!o||o.valid!==!0){const i=((s=o==null?void 0:o.errors)==null?void 0:s[0])||"Update failed";throw new Error(i)}return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"setAttrs",payload:{nodeId:e,attrs:n.attributes}}}});E("setMarks",async(d,t)=>{var s;const{nodeId:e,marks:r}=d.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Node not found: ${e}`);const o=t.dataStore.marks.setMarks(e,r);if(!o||o.valid!==!0){const i=((s=o==null?void 0:o.errors)==null?void 0:s[0])||"Update marks failed";throw new Error(i)}return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"setMarks",payload:{nodeId:e,marks:n.marks}}}});E("insertText",async(d,t)=>{var o;const{nodeId:e,pos:r,text:n}=d.payload;try{if(!t.dataStore.getNode(e))throw new Error(`Node not found: ${e}`);const i=t.dataStore.range.insertText({type:"range",startNodeId:e,startOffset:r,endNodeId:e,endOffset:r},n);if((o=t.selection)!=null&&o.current){const a=t.selection.current,c=n.length;a.startNodeId===e&&a.startOffset>=r&&(a.startOffset+=c),a.endNodeId===e&&a.endOffset>=r&&(a.endOffset+=c)}return{ok:!0,data:i,inverse:{type:"deleteTextRange",payload:{nodeId:e,startPosition:r,endPosition:r+n.length}}}}catch(s){throw new Error(`Failed to insert text into node ${e}: ${s instanceof Error?s.message:"Unknown error"}`)}});E("deleteTextRange",async(d,t)=>{var o,s;const{nodeId:e,start:r,end:n}=d.payload;try{if(!t.dataStore.getNode(e))throw new Error(`Node not found: ${e}`);const a=t.dataStore.range.deleteText({type:"range",startNodeId:e,startOffset:r,endNodeId:e,endOffset:n});if((o=t.selection)!=null&&o.current){const c=t.selection.current,l=n-r;c.startNodeId===e&&(c.startOffset>=r&&c.startOffset<n||c.startOffset===n?c.startOffset=r:c.startOffset>n&&(c.startOffset-=l)),c.endNodeId===e&&(c.endOffset>=r&&c.endOffset<n||c.endOffset===n?c.endOffset=r:c.endOffset>n&&(c.endOffset-=l)),"collapsed"in c&&(c.collapsed=c.startNodeId===c.endNodeId&&c.startOffset===c.endOffset)}return{ok:!0,data:a,inverse:{type:"insertText",payload:{nodeId:e,pos:r,text:a}},selection:(s=t.selection)!=null&&s.current?{startNodeId:t.selection.current.startNodeId,startOffset:t.selection.current.startOffset,endNodeId:t.selection.current.endNodeId,endOffset:t.selection.current.endOffset}:null}}catch(i){throw new Error(`Failed to delete text range for node ${e}: ${i instanceof Error?i.message:"Unknown error"}`)}});E("deleteRange",async(d,t)=>{const e=d.payload;if(!(e!=null&&e.range))throw new Error("[deleteRange] payload.range is required");const{startNodeId:r,startOffset:n,endNodeId:o,endOffset:s}=e.range,i={type:"range",startNodeId:r,startOffset:n,endNodeId:o,endOffset:s};if(!t.dataStore.range||typeof t.dataStore.range.deleteText!="function")throw new Error("DataStore.range.deleteText is not available");return{ok:!0,data:t.dataStore.range.deleteText(i),inverse:{type:"deleteRange",payload:{range:i}}}});E("replaceText",async(d,t)=>{try{const e=d.payload;if(!e)throw new Error("Payload is required for replaceText operation");if("range"in e){const{range:l,newText:u}=e,{startNodeId:f,endNodeId:h,startOffset:g,endOffset:m}=l,p=t.dataStore.getNode(f),N=t.dataStore.getNode(h);if(!p)throw new Error(`Node not found: ${f}`);if(!N)throw new Error(`Node not found: ${h}`);if(typeof p.text!="string"||typeof N.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof g!="number"||typeof m!="number")throw new Error("Invalid range");const x=t.dataStore.range.extractText(l),S={type:"range",...l};return{ok:!0,data:t.dataStore.range.replaceText(S,u),inverse:{type:"replaceText",payload:{range:{startNodeId:l.startNodeId,startOffset:l.startOffset,endNodeId:l.endNodeId,endOffset:l.endOffset+u.length},newText:x}}}}const{nodeId:r,start:n,end:o,newText:s}=e,i=t.dataStore.getNode(r);if(!i)throw new Error(`Node not found: ${r}`);if(typeof i.text!="string")throw new Error(`Node ${r} is not a text node`);if(typeof n!="number"||typeof o!="number"||n>o||n<0||o>i.text.length)throw new Error("Invalid range");const a=i.text.substring(n,o);return{ok:!0,data:t.dataStore.range.replaceText({type:"range",startNodeId:r,startOffset:n,endNodeId:r,endOffset:o},s),inverse:{type:"replaceText",payload:{nodeId:r,start:n,end:n+s.length,newText:a}}}}catch(e){throw console.log("replaceText error:",e),new Error(`Failed to replace text: ${e instanceof Error?e.message:"Unknown error"}`)}});function Jt(d){if(!(d==null||typeof d!="object")&&(d.id!==void 0&&d.sid===void 0&&(d.sid=d.id),d.type!==void 0&&d.stype===void 0&&(d.stype=d.type),Array.isArray(d.content)))for(const t of d.content)t&&typeof t=="object"&&Jt(t)}E("create",async(d,t)=>{const{node:e,options:r}=d.payload,n=JSON.parse(JSON.stringify(e));Jt(n);try{const o=t.dataStore.getActiveSchema(),s=JSON.parse(JSON.stringify(n)),i=t.dataStore.createNodeWithChildren(s,o);return t.dataStore.getRootNode()||t.dataStore.setRootNodeId(i.sid),{ok:!0,data:JSON.parse(JSON.stringify(i)),inverse:{type:"delete",payload:{nodeId:i.sid}}}}catch(o){throw new Error(`Failed to create node: ${o instanceof Error?o.message:"Unknown error"}`)}});E("delete",async(d,t)=>{var r,n,o,s,i,a,c;const{nodeId:e}=d.payload;try{let l=t.dataStore.getNode(e);if(!l)throw((n=(r=t.dataStore).getRootNodeId)==null?void 0:n.call(r))===e?new Error("Cannot delete root node"):new Error(`Node with id '${e}' not found`);const u=(s=(o=t.dataStore).getRootNodeId)==null?void 0:s.call(o);if(u&&u===e)throw new Error("Cannot delete root node");const h=t.dataStore.getAllDescendants(e).map(p=>p.sid);for(const p of h.reverse())t.dataStore.deleteNode(p)||console.warn(`Failed to delete descendant node: ${p}`);if(l.parentId&&t.dataStore.getNode(l.parentId)&&(t.dataStore.removeChild(l.parentId,e)||console.warn(`Failed to remove child reference from parent: ${l.parentId}`)),(i=t.selection)!=null&&i.current){const p=t.selection.current;(p.startNodeId===e||p.endNodeId===e)&&t.selection.clear()}if(!t.dataStore.deleteNode(e))throw new Error(`Failed to delete node: ${e}`);if(((c=(a=t.dataStore).getRootNodeId)==null?void 0:c.call(a))===e){const N=t.dataStore.getAllNodes().find(x=>x.sid!==e);N?t.dataStore.setRootNodeId(N.sid):t.dataStore.setRootNodeId(void 0)}return{ok:!0,data:!0,inverse:{type:"create",payload:{node:l}}}}catch(l){throw new Error(`Failed to delete node ${e}: ${l instanceof Error?l.message:"Unknown error"}`)}});E("update",async(d,t)=>{const{nodeId:e,data:r}=d.payload,n=t.dataStore.getNode(e);if(!n)throw new Error(`Node with id '${e}' not found`);const o=t.dataStore.updateNode(e,r);if(o&&!o.valid)throw new Error(`Update failed: ${o.errors.join(", ")}`);return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"update",payload:{nodeId:e,data:n}}}});E("selectRange",async(d,t)=>{var i,a;const e=d.nodeId??(d.payload&&"nodeId"in d.payload?d.payload.nodeId:void 0),r=d.start??((i=d.payload)==null?void 0:i.anchor)??0,n=d.end??((a=d.payload)==null?void 0:a.focus)??0;if(!e)return;const o=Math.min(r,n),s=Math.max(r,n);await t.selectionManager.setSelection({type:"range",startNodeId:e,startOffset:o,endNodeId:e,endOffset:s}),t.selection.setRange(e,o,e,s)});E("selectNode",async(d,t)=>{var r;const e=d.nodeId??((r=d.payload)==null?void 0:r.nodeId);e&&(await t.selectionManager.setSelection({type:"node",startNodeId:e,startOffset:0,endNodeId:e,endOffset:0}),t.selection.setSelection({type:"node",startNodeId:e,startOffset:0,endNodeId:e,endOffset:0}))});E("clearSelection",async(d,t)=>{await t.selectionManager.clearSelection(),t.selection.clear()});E("setSelection",async(d,t)=>{const{anchor:e,head:r}=d.payload,n=e.nodeId===r.nodeId&&e.offset===r.offset;return t.selection.current={type:"range",startNodeId:e.nodeId,startOffset:e.offset,endNodeId:r.nodeId,endOffset:r.offset,collapsed:n},{ok:!0,data:t.selection.current}});E("removeMark",async(d,t)=>{var i;const{nodeId:e,markType:r,range:n}=d.payload;if(!t.dataStore.getNode(e))throw new Error(`Node ${e} not found`);if(!t.dataStore.marks||typeof t.dataStore.marks.removeMark!="function")throw new Error("DataStore.marks.removeMark is not available");const s=t.dataStore.marks.removeMark(e,r,n);if(!s||s.valid!==!0){const a=((i=s==null?void 0:s.errors)==null?void 0:i[0])||"Remove mark failed";throw new Error(a)}return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"applyMark",payload:{nodeId:e,start:n[0],end:n[1],markType:r}}}});E("toggleMark",async(d,t)=>{var c;const e=d.payload,r=e.markType,n=e.attrs;if(e.range&&"startNodeId"in e.range&&"endNodeId"in e.range){const l=e.range;let{startNodeId:u,startOffset:f,endNodeId:h,endOffset:g}=l;if(u===h&&f===g){const p=t.dataStore.getNode(u);p&&typeof p.text=="string"&&(g=Math.min(f+1,p.text.length))}if(!t.dataStore.range||typeof t.dataStore.range.toggleMark!="function")throw new Error("DataStore.range.toggleMark is not available");const m={type:"range",startNodeId:u,startOffset:f,endNodeId:h,endOffset:g};return t.dataStore.range.toggleMark(m,r,n),{ok:!0,inverse:{type:"toggleMark",payload:{range:m,markType:r,attrs:n}}}}const{nodeId:o,range:s}=e;if(!t.dataStore.getNode(o))throw new Error(`Node ${o} not found`);if(!t.dataStore.marks||typeof t.dataStore.marks.toggleMark!="function")throw new Error("DataStore.marks.toggleMark is not available");const a=t.dataStore.marks.toggleMark(o,r,s,n);if(!a||a.valid!==!0){const l=((c=a==null?void 0:a.errors)==null?void 0:c[0])||"Toggle mark failed";throw new Error(l)}return{ok:!0,data:t.dataStore.getNode(o),inverse:{type:"toggleMark",payload:{nodeId:o,markType:r,range:s,attrs:n}}}});E("updateMark",async(d,t)=>{var a;const{nodeId:e,markType:r,range:n,newAttrs:o}=d.payload;if(!t.dataStore.getNode(e))throw new Error(`Node ${e} not found`);if(!t.dataStore.marks||typeof t.dataStore.marks.updateMark!="function")throw new Error("DataStore.marks.updateMark is not available");const i=t.dataStore.marks.updateMark(e,r,n,o);if(!i||i.valid!==!0){const c=((a=i==null?void 0:i.errors)==null?void 0:a[0])||"Update mark failed";throw new Error(c)}return{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"updateMark",payload:{nodeId:e,markType:r,range:n,newAttrs:qe(t.dataStore.getNode(e),r,n)}}}});function qe(d,t,e){const n=((d==null?void 0:d.marks)||[]).find(o=>o.type===t&&Array.isArray(o.range)&&o.range[0]===e[0]&&o.range[1]===e[1]);return n==null?void 0:n.attrs}E("applyMark",async(d,t)=>{var e;try{const r=d.payload;if(!r)throw new Error("Operation payload is required");const n=r.markType,o=r.attrs;if("range"in r){const{range:u}=r,{startNodeId:f,endNodeId:h,startOffset:g,endOffset:m}=u,p=t.dataStore.getNode(f),N=t.dataStore.getNode(h);if(!p)throw new Error(`Node not found: ${f}`);if(!N)throw new Error(`Node not found: ${h}`);if(typeof p.text!="string"||typeof N.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof g!="number"||typeof m!="number")throw new Error("Invalid range");if(!t.dataStore.range||typeof t.dataStore.range.applyMark!="function")throw new Error("DataStore.range.applyMark is not available");const x={type:"range",startNodeId:f,startOffset:g,endNodeId:h,endOffset:m},S={stype:n,attrs:o};return t.dataStore.range.applyMark(x,S),t.dataStore.getNode(f===h?f:h)}const{nodeId:s,start:i,end:a}=r,c=t.dataStore.getNode(s);if(!c)throw new Error(`Node not found: ${s}`);if(typeof c.text!="string")throw new Error(`Node ${s} is not a text node`);if(typeof i!="number"||typeof a!="number"||i>=a||i<0||a>c.text.length)throw new Error("Invalid range");const l=t.dataStore.marks.setMarks(s,[...c.marks||[],{stype:n,attrs:o,range:[i,a]}]);if(!l||l.valid!==!0)throw new Error(((e=l==null?void 0:l.errors)==null?void 0:e[0])||"Apply mark failed");return{ok:!0,data:t.dataStore.getNode(s),inverse:{type:"removeMark",payload:{nodeId:s,markType:n,range:[i,a]}}}}catch(r){throw new Error(`Failed to apply mark: ${r instanceof Error?r.message:"Unknown error"}`)}});E("wrap",async(d,t)=>{try{const e=d.payload;if("range"in e){const{range:f,prefix:h,suffix:g}=e,{startNodeId:m,endNodeId:p,startOffset:N,endOffset:x}=f,S=t.dataStore.getNode(m),b=t.dataStore.getNode(p);if(!S)throw new Error(`Node not found: ${m}`);if(!b)throw new Error(`Node not found: ${p}`);if(typeof S.text!="string"||typeof b.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof N!="number"||typeof x!="number")throw new Error("Invalid range");return{ok:!0,data:t.dataStore.range.wrap(f,h,g),inverse:{type:"unwrap",payload:{range:{startNodeId:f.startNodeId,startOffset:f.startOffset,endNodeId:f.endNodeId,endOffset:f.endOffset+h.length+g.length},prefix:h,suffix:g}}}}const{nodeId:r,start:n,end:o,prefix:s,suffix:i}=e,a=t.dataStore.getNode(r);if(!a)throw new Error(`Node not found: ${r}`);if(typeof a.text!="string")throw new Error(`Node ${r} is not a text node`);if(typeof n!="number"||typeof o!="number"||n>o||n<0||o>a.text.length)throw new Error("Invalid range");const c=a.text.substring(n,o),l=`${s}${c}${i}`,u=t.dataStore.range.replaceText({type:"range",startNodeId:r,startOffset:n,endNodeId:r,endOffset:o},l);return{ok:!0,data:`${s}${u}${i}`,inverse:{type:"unwrap",payload:{nodeId:r,start:n,end:n+l.length,prefix:s,suffix:i}}}}catch(e){throw new Error(`Failed to wrap text: ${e instanceof Error?e.message:"Unknown error"}`)}});E("unwrap",async(d,t)=>{try{const e=d.payload;if("range"in e){const{range:l,prefix:u,suffix:f}=e,{startNodeId:h,endNodeId:g,startOffset:m,endOffset:p}=l,N=t.dataStore.getNode(h),x=t.dataStore.getNode(g);if(!N)throw new Error(`Node not found: ${h}`);if(!x)throw new Error(`Node not found: ${g}`);if(typeof N.text!="string"||typeof x.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof m!="number"||typeof p!="number")throw new Error("Invalid range");let S=t.dataStore.range.extractText(l);return S.startsWith(u)&&(S=S.substring(u.length)),S.endsWith(f)&&(S=S.substring(0,S.length-f.length)),t.dataStore.range.replaceText(l,S),{ok:!0,data:S,inverse:{type:"wrap",payload:{range:{startNodeId:l.startNodeId,startOffset:l.startOffset,endNodeId:l.endNodeId,endOffset:l.endOffset+u.length+f.length},prefix:u,suffix:f}}}}const{nodeId:r,start:n,end:o,prefix:s,suffix:i}=e,a=t.dataStore.getNode(r);if(!a)throw new Error(`Node not found: ${r}`);if(typeof a.text!="string")throw new Error(`Node ${r} is not a text node`);if(typeof n!="number"||typeof o!="number"||n>o||n<0||o>a.text.length)throw new Error("Invalid range");let c=a.text.substring(n,o);return c.startsWith(s)&&(c=c.substring(s.length)),c.endsWith(i)&&(c=c.substring(0,c.length-i.length)),t.dataStore.range.replaceText({type:"range",startNodeId:r,startOffset:n,endNodeId:r,endOffset:o},c),{ok:!0,data:c,inverse:{type:"wrap",payload:{nodeId:r,start:n,end:n+c.length,prefix:s,suffix:i}}}}catch(e){throw new Error(`Failed to unwrap text: ${e instanceof Error?e.message:"Unknown error"}`)}});function ze(d,t,e){if(!e||e.type!=="range")return null;const r=d.getNode(e.startNodeId);if(!r)return null;if(typeof r.text=="string"){const c=d.getParent(e.startNodeId);if(!c||!Array.isArray(c.content))return null;const l=c.parentId?d.getNode(d.resolveAlias(c.parentId)):null;if(!l||!Array.isArray(l.content))return null;const u=l.content.indexOf(c.sid);return u===-1?null:{blockId:c.sid,block:c,parentId:l.sid,parent:l,blockIndex:u}}const n=t==null?void 0:t.getNodeType(r.stype);if((n==null?void 0:n.group)!=="block")return null;const o=r,s=d.getParent(o.sid);if(!s||!Array.isArray(s.content))return null;const i=s.parentId?d.getNode(d.resolveAlias(s.parentId)):null;if(!i||!Array.isArray(i.content))return null;const a=i.content.indexOf(s.sid);return a===-1?null:{blockId:s.sid,block:s,parentId:i.sid,parent:i,blockIndex:a}}E("wrapInList",async(d,t)=>{const e=d.payload.listType??"bullet",r=t.dataStore,n=t.schema,o=t.selection.current,s=ze(r,n,o);if(!s)throw new Error("wrapInList: no selection or selection does not resolve to a block");const{blockId:i,block:a,parentId:c,parent:l,blockIndex:u}=s,f=(o==null?void 0:o.startNodeId)??null,h=typeof(o==null?void 0:o.startOffset)=="number"?o.startOffset:0;if(l.stype==="listItem"){const x=l.parentId;if(x==null)throw new Error("wrapInList: listItem has no parent");const S=r.getNode(r.resolveAlias(x));if(!S||S.stype!=="list"||!Array.isArray(S.content))throw new Error("wrapInList: listItem parent is not a list");const b=S.parentId;if(b==null)throw new Error("wrapInList: list has no parent");const v=r.resolveAlias(b),I=r.getNode(v);if(!I||!Array.isArray(I.content))throw new Error("wrapInList: list has no document parent");const _=S.sid;if(_==null)throw new Error("wrapInList: list has no sid");const C=I.content.indexOf(_);if(C===-1)throw new Error("wrapInList: list not in document");const D=S.content;let w=C;for(const M of D){const T=r.getNode(M);if(!T||!Array.isArray(T.content))continue;const A=T.content;for(const R of A)r.content.removeChild(M,R),r.content.addChild(v,R,w),w+=1}return r.content.removeChild(v,_),{ok:!0,data:{unwrapped:!0},selectionAfter:f?{nodeId:f,offset:h}:void 0}}const g={stype:"list",attributes:{type:e},content:[]},m=r.content.addChild(c,g,u),p={stype:"listItem",content:[]},N=r.content.addChild(m,p,0);return r.content.moveNode(i,N,0),{ok:!0,data:r.getNode(m),selectionAfter:f?{nodeId:f,offset:h}:void 0}});function Ve(d,t,e){if(!e||e.type!=="range")return null;const r=d.getNode(e.startNodeId);if(!r)return null;let n,o,s,i;if(typeof r.text=="string"){n=e.startNodeId;const u=r.text;o=typeof e.startOffset=="number"&&e.startOffset>=0?Math.min(e.startOffset,u.length):0,s=u.length,i=d.getParent(n)}else{const u=t==null?void 0:t.getNodeType(r.stype);if((u==null?void 0:u.group)!=="block")return null;i=r;const f=Ke(d,i.sid);if(!f)return null;n=f.sid,s=f.text.length,o=s}if(!i||!Array.isArray(i.content))return null;const a=d.getParent(i.sid);if(!a||a.stype!=="listItem")return null;const c=d.getNode(d.resolveAlias(a.parentId));if(!c||c.stype!=="list"||!Array.isArray(c.content))return null;const l=c.content.indexOf(a.sid);return l===-1?null:{blockId:i.sid,block:i,listItemId:a.sid,listItem:a,listId:c.sid,list:c,listItemIndex:l,textNodeId:n,offset:o,textLength:s}}function Ke(d,t){const e=d.getNode(t);if(!e||!Array.isArray(e.content))return null;const r=e.content;let n=null;const o=s=>{const i=d.getNode(s);if(!i)return;if(typeof i.text=="string"){n={sid:i.sid,text:i.text};return}const a=i.content;if(Array.isArray(a))for(const c of a)o(c)};for(const s of r)o(s);return n}E("splitListItem",async(d,t)=>{const e=t.dataStore,r=t.schema,n=t.selection.current,o=Ve(e,r,n);if(!o)return{ok:!0,data:null};const{listId:s,listItem:i,listItemIndex:a,textNodeId:c,offset:l,textLength:u}=o,f=Math.max(0,Math.min(l,u));if(i.content.length===1&&i.content[0]===c&&f>0&&f<u){e.splitTextNode(c,f);const S=e.splitBlockNode(o.blockId,1),b=e.getNode(S),v=b&&Array.isArray(b.content)&&b.content[0]?b.content[0]:null;if(!v)throw new Error("splitListItem: splitBlockNode did not yield a text node");const I={stype:"listItem",content:[]},_=e.content.addChild(s,I,a+1);return e.content.moveNode(S,_,0),t.lastCreatedBlock={blockId:S,firstTextNodeId:v},{ok:!0,data:e.getNode(_),selectionAfter:{nodeId:v,offset:0}}}const g={stype:"paragraph",attributes:{},content:[]},m=e.content.addChild(i.sid,g,i.content.length),p=e.content.addChild(m,{stype:"inline-text",text:""},0),N={stype:"listItem",content:[]},x=e.content.addChild(s,N,a+1);return e.content.moveNode(m,x,0),t.lastCreatedBlock={blockId:m,firstTextNodeId:p},{ok:!0,data:e.getNode(x),selectionAfter:{nodeId:p,offset:0}}});function Qe(d,t,e){if(!e||e.type!=="range")return null;const r=d.getNode(e.startNodeId);if(!r)return null;if(typeof r.text=="string"){const c=d.getParent(e.startNodeId);if(!c||!Array.isArray(c.content))return null;const l=c.parentId?d.getNode(d.resolveAlias(c.parentId)):null;if(!l||!Array.isArray(l.content))return null;const u=l.content.indexOf(c.sid);return u===-1?null:{blockId:c.sid,block:c,parentId:l.sid,parent:l,blockIndex:u}}const n=t==null?void 0:t.getNodeType(r.stype);if((n==null?void 0:n.group)!=="block")return null;const o=r,s=d.getParent(o.sid);if(!s||!Array.isArray(s.content))return null;const i=s.parentId?d.getNode(d.resolveAlias(s.parentId)):null;if(!i||!Array.isArray(i.content))return null;const a=i.content.indexOf(s.sid);return a===-1?null:{blockId:s.sid,block:s,parentId:i.sid,parent:i,blockIndex:a}}E("wrapInBlockquote",async(d,t)=>{const e=t.dataStore,r=t.schema,n=t.selection.current,o=Qe(e,r,n);if(!o)throw new Error("wrapInBlockquote: no selection or selection does not resolve to a block");const{blockId:s,block:i,parentId:a,parent:c,blockIndex:l}=o,u=(n==null?void 0:n.startNodeId)??null,f=typeof(n==null?void 0:n.startOffset)=="number"?n.startOffset:0;if(c.stype==="blockQuote"){const m=e.resolveAlias(c.parentId),p=e.getNode(m);if(!p||!Array.isArray(p.content))throw new Error("wrapInBlockquote: blockQuote has no document parent");const N=p.content.indexOf(c.sid);if(N===-1)throw new Error("wrapInBlockquote: blockQuote not in document");const x=c.content;let S=N;for(const b of x)e.content.removeChild(c.sid,b),e.content.addChild(m,b,S),S+=1;return e.content.removeChild(m,c.sid),{ok:!0,data:{unwrapped:!0},selectionAfter:u?{nodeId:u,offset:f}:void 0}}const h={stype:"blockQuote",content:[]},g=e.content.addChild(a,h,l);return e.content.moveNode(s,g,0),{ok:!0,data:e.getNode(g),selectionAfter:u?{nodeId:u,offset:f}:void 0}});E("indentNode",async(d,t)=>{const e=d.payload.nodeId;if(!e)throw new Error("[indentNode] nodeId is required in payload");if(!t.dataStore.getNode(e))throw new Error(`[indentNode] Node not found: ${e}`);return t.dataStore.indentNode(e)?{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"outdentNode",payload:{nodeId:e}}}:{ok:!0,data:t.dataStore.getNode(e)}});E("outdentNode",async(d,t)=>{const e=d.payload.nodeId;if(!e)throw new Error("[outdentNode] nodeId is required in payload");if(!t.dataStore.getNode(e))throw new Error(`[outdentNode] Node not found: ${e}`);return t.dataStore.outdentNode(e)?{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"indentNode",payload:{nodeId:e}}}:{ok:!0,data:t.dataStore.getNode(e)}});E("indentText",async(d,t)=>{try{const e=d.payload,r=e.indent??" ";if("range"in e){const{range:l}=e,{startNodeId:u,endNodeId:f,startOffset:h,endOffset:g}=l,m=t.dataStore.getNode(u),p=t.dataStore.getNode(f);if(!m)throw new Error(`Node not found: ${u}`);if(!p)throw new Error(`Node not found: ${f}`);if(typeof m.text!="string"||typeof p.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof h!="number"||typeof g!="number")throw new Error("Invalid range");return{ok:!0,data:t.dataStore.range.indent(l,r),inverse:{type:"outdentText",payload:{range:l,indent:r}}}}const{nodeId:n,start:o,end:s}=e,i=t.dataStore.getNode(n);if(!i)throw new Error(`Node not found: ${n}`);if(typeof i.text!="string")throw new Error(`Node ${n} is not a text node`);if(typeof o!="number"||typeof s!="number"||o>s||o<0||s>i.text.length)throw new Error("Invalid range");const a={type:"range",startNodeId:n,startOffset:o,endNodeId:n,endOffset:s,collapsed:!1,direction:"forward"};return{ok:!0,data:t.dataStore.range.indent(a,r),inverse:{type:"outdentText",payload:{nodeId:n,start:o,end:s,indent:r}}}}catch(e){throw new Error(`Failed to indent text: ${e instanceof Error?e.message:"Unknown error"}`)}});E("outdentText",async(d,t)=>{try{const e=d.payload,r=e.indent??" ";if("range"in e){const{range:l}=e,{startNodeId:u,endNodeId:f,startOffset:h,endOffset:g}=l,m=t.dataStore.getNode(u),p=t.dataStore.getNode(f);if(!m)throw new Error(`Node not found: ${u}`);if(!p)throw new Error(`Node not found: ${f}`);if(typeof m.text!="string"||typeof p.text!="string")throw new Error("Range endpoints must be text nodes");if(typeof h!="number"||typeof g!="number")throw new Error("Invalid range");return{ok:!0,data:t.dataStore.range.outdent(l,r),inverse:{type:"indentText",payload:{range:l,indent:r}}}}const{nodeId:n,start:o,end:s}=e,i=t.dataStore.getNode(n);if(!i)throw new Error(`Node not found: ${n}`);if(typeof i.text!="string")throw new Error(`Node ${n} is not a text node`);if(typeof o!="number"||typeof s!="number"||o>s||o<0||s>i.text.length)throw new Error("Invalid range");const a={type:"range",startNodeId:n,startOffset:o,endNodeId:n,endOffset:s,collapsed:!1,direction:"forward"};return{ok:!0,data:t.dataStore.range.outdent(a,r),inverse:{type:"indentText",payload:{nodeId:n,start:o,end:s,indent:r}}}}catch(e){throw new Error(`Failed to outdent text: ${e instanceof Error?e.message:"Unknown error"}`)}});E("copy",async(d,t)=>{const{range:e}=d.payload;if(!e)throw new Error("[copy] range is required");const r=t.dataStore.serializeRange(e),n=t.dataStore.range.extractText(e);return{json:r,text:n}});E("paste",async(d,t)=>{const{range:e,data:r}=d.payload;if(!e||!r||!Array.isArray(r.nodes))throw new Error("[paste] range and data.nodes are required");const n=t.dataStore.getNode(e.startNodeId);if(!n||!n.parentId)throw new Error("[paste] startNode or its parent not found");const o=n.parentId,s=t.dataStore.getNode(o);if(!s||!Array.isArray(s.content))throw new Error("[paste] parent node or its content not found");const i=s.content.indexOf(e.startNodeId),a=i>=0?i+1:s.content.length,c=t.dataStore.deserializeNodes(r.nodes,o,a),l=c.length?{type:"range",startNodeId:c[c.length-1],startOffset:0,endNodeId:c[c.length-1],endOffset:0,collapsed:!0,direction:"forward"}:null;return{insertedNodeIds:c,newSelection:l}});E("cut",async(d,t)=>{const{range:e}=d.payload;if(!e)throw new Error("[cut] range is required");const r=t.dataStore.serializeRange(e),n=t.dataStore.range.extractText(e);return t.dataStore.range.deleteRange(e),{json:r,text:n,deletedRange:e}});const Xt=U((...d)=>{if(d.length>=2&&typeof d[1]=="string"){const[r,n,o]=d;return{type:"transformNode",payload:{nodeId:r,newType:n,newAttrs:o}}}const[t,e]=d;return{type:"transformNode",payload:{newType:t,newAttrs:e}}},{atom:!1,category:"content"});E("transformNode",async(d,t)=>{var i;const{nodeId:e,newType:r,newAttrs:n}=d.payload;if(!e)throw new Error("Node ID is required for transformNode operation");if(!r)throw new Error("New type is required for transformNode operation");const o=t.dataStore.getNode(e);if(!o)throw new Error(`Node not found: ${e}`);const s=t.dataStore.transformNode(e,r,n);if(!s||s.valid!==!0){const a=((i=s==null?void 0:s.errors)==null?void 0:i[0])||"Transform node failed";throw new Error(a)}return{ok:!0,data:t.dataStore.getNode(s.newNodeId||e),inverse:{type:"transformNode",payload:{nodeId:s.newNodeId||e,newType:o.stype,newAttrs:o.attributes}}}});const Ge=U(d=>d?{type:"moveBlockUp",payload:{nodeId:d}}:{type:"moveBlockUp",payload:{}},{atom:!1,category:"content"});E("moveBlockUp",async(d,t)=>{const{nodeId:e}=d.payload;if(!e)throw new Error("Node ID is required for moveBlockUp operation");const r=t.dataStore.getNode(e);if(!r)throw new Error(`Node not found: ${e}`);if(!r.parentId)throw new Error(`Node ${e} has no parent`);const n=t.dataStore.getNode(r.parentId);if(!n||!Array.isArray(n.content))throw new Error(`Parent node not found or has no content: ${r.parentId}`);const o=n.content.indexOf(e);if(o===-1)throw new Error(`Node ${e} not found in parent content`);return o===0?{ok:!1,data:null,error:"Cannot move block up: already at first position"}:t.dataStore.moveBlockUp(e)?{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"moveBlockDown",payload:{nodeId:e}}}:{ok:!1,data:null,error:"Failed to move block up"}});const Je=U(d=>d?{type:"moveBlockDown",payload:{nodeId:d}}:{type:"moveBlockDown",payload:{}},{atom:!1,category:"content"});E("moveBlockDown",async(d,t)=>{const{nodeId:e}=d.payload;if(!e)throw new Error("Node ID is required for moveBlockDown operation");const r=t.dataStore.getNode(e);if(!r)throw new Error(`Node not found: ${e}`);if(!r.parentId)throw new Error(`Node ${e} has no parent`);const n=t.dataStore.getNode(r.parentId);if(!n||!Array.isArray(n.content))throw new Error(`Parent node not found or has no content: ${r.parentId}`);const o=n.content.indexOf(e);if(o===-1)throw new Error(`Node ${e} not found in parent content`);return o===n.content.length-1?{ok:!1,data:null,error:"Cannot move block down: already at last position"}:t.dataStore.moveBlockDown(e)?{ok:!0,data:t.dataStore.getNode(e),inverse:{type:"moveBlockUp",payload:{nodeId:e}}}:{ok:!1,data:null,error:"Failed to move block down"}});const Xe=U((...d)=>{if(d.length===0)return{type:"indentNode",payload:{}};const[t]=d;return{type:"indentNode",payload:{nodeId:t}}},{atom:!1,category:"structure"}),Ye=U((...d)=>{if(d.length===0)return{type:"outdentNode",payload:{}};const[t]=d;return{type:"outdentNode",payload:{nodeId:t}}},{atom:!1,category:"structure"}),At=U((...d)=>{if(d.length>=2&&typeof d[0]=="number"){const[o,s,i]=d;return{type:"indentText",payload:{start:o,end:s,indent:i}}}if(d.length>=4&&typeof d[0]=="string"&&typeof d[2]=="string"){const[o,s,i,a,c]=d;return{type:"indentText",payload:{range:{type:"range",startNodeId:o,startOffset:s,endNodeId:i,endOffset:a,collapsed:!1,direction:"forward"},indent:c}}}const[t,e,r,n]=d;return{type:"indentText",payload:{nodeId:t,start:e,end:r,indent:n}}},{atom:!0,category:"text"}),Mt=U((...d)=>{if(d.length>=2&&typeof d[0]=="number"){const[o,s,i]=d;return{type:"outdentText",payload:{start:o,end:s,indent:i}}}if(d.length>=4&&typeof d[0]=="string"&&typeof d[2]=="string"){const[o,s,i,a,c]=d;return{type:"outdentText",payload:{range:{type:"range",startNodeId:o,startOffset:s,endNodeId:i,endOffset:a,collapsed:!1,direction:"forward"},indent:c}}}const[t,e,r,n]=d;return{type:"outdentText",payload:{nodeId:t,start:e,end:r,indent:n}}},{atom:!0,category:"text"}),Ze=U(d=>({type:"delete",payload:{nodeId:d}}),{atom:!0,category:"structure"}),Yt=U((...d)=>{if(d.length===2){const[n,o]=d;return{type:"deleteTextRange",payload:{start:n,end:o}}}const[t,e,r]=d;return{type:"deleteTextRange",payload:{nodeId:t,start:e,end:r}}},{atom:!0,category:"text"}),tr=U(d=>({type:"deleteRange",payload:{range:d}}),{atom:!1,category:"text"}),er=U((...d)=>{if(d.length===2){const[n,o]=d;return{type:"insertText",payload:{pos:n,text:o}}}const[t,e,r]=d;return{type:"insertText",payload:{nodeId:t,pos:e,text:r}}},{atom:!0,category:"text"}),rr=U((d,t)=>({type:"insertParagraph",payload:{...d!=null&&{blockType:d},...t!=null&&{selectionAlias:t}}}),{atom:!1,category:"content"}),Zt=U((...d)=>{if(d.length>=5&&typeof d[0]=="string"&&typeof d[1]=="number"&&typeof d[2]=="string"&&typeof d[3]=="number"&&typeof d[4]=="string"){const[o,s,i,a,c,l]=d;return{type:"toggleMark",payload:{range:{startNodeId:o,startOffset:s,endNodeId:i,endOffset:a},markType:c,attrs:l}}}if(d.length>=2&&typeof d[0]=="string"&&Array.isArray(d[1])){const[o,s,i]=d;return{type:"toggleMark",payload:{markType:o,range:s,attrs:i}}}const[t,e,r,n]=d;return{type:"toggleMark",payload:{nodeId:t,markType:e,range:r,attrs:n}}},{atom:!1,category:"marks"}),nr=U(d=>({type:"wrapInList",payload:{...d!=null&&{listType:d}}}),{atom:!1,category:"content"}),te=U(()=>({type:"splitListItem",payload:{}}),{atom:!1,category:"content"}),or=U(()=>({type:"wrapInBlockquote",payload:{}}),{atom:!1,category:"content"}),ee=U((...d)=>{if(d.length>=3&&typeof d[0]=="number"&&typeof d[2]=="string"){const[s,i,a,c]=d;return{type:"applyMark",payload:{start:s,end:i,markType:a,attrs:c}}}if(d.length>=5&&typeof d[0]=="string"&&typeof d[2]=="string"&&typeof d[4]=="string"){const[s,i,a,c,l,u]=d;return{type:"applyMark",payload:{range:{type:"range",startNodeId:s,startOffset:i,endNodeId:a,endOffset:c},markType:l,attrs:u}}}const[t,e,r,n,o]=d;return{type:"applyMark",payload:{nodeId:t,start:e,end:r,markType:n,attrs:o}}},{atom:!1,category:"marks"}),sr=U(d=>({type:"copy",payload:{range:d}}),{atom:!0,category:"clipboard"}),ir=U((d,t)=>({type:"paste",payload:{data:{nodes:d},range:t}}),{atom:!0,category:"clipboard"}),ar=U(d=>({type:"cut",payload:{range:d}}),{atom:!0,category:"clipboard"}),W={NODE_REQUIRED:"NODE_REQUIRED",NODE_ID_REQUIRED:"NODE_ID_REQUIRED",NODE_TYPE_REQUIRED:"NODE_TYPE_REQUIRED",TEXT_CONTENT_REQUIRED:"TEXT_CONTENT_REQUIRED",DOCUMENT_REQUIRED:"DOCUMENT_REQUIRED",DOCUMENT_ID_REQUIRED:"DOCUMENT_ID_REQUIRED",DOCUMENT_SCHEMA_REQUIRED:"DOCUMENT_SCHEMA_REQUIRED",DOCUMENT_CONTENT_REQUIRED:"DOCUMENT_CONTENT_REQUIRED",NODE_TYPE_UNKNOWN:"NODE_TYPE_UNKNOWN",CONTENT_REQUIRED_BUT_EMPTY:"CONTENT_REQUIRED_BUT_EMPTY",ATTRIBUTE_INVALID:"ATTRIBUTE_INVALID",INVALID_SCHEMA_INSTANCE:"INVALID_SCHEMA_INSTANCE"};class xt{static validateNodeStructure(t){var o;const e=[],r=[];if(!t)return e.push("Node is required"),r.push(W.NODE_REQUIRED),{valid:!1,errors:e,errorCodes:r};if(t.sid||(e.push("Node ID is required"),r.push(W.NODE_ID_REQUIRED)),(t==null?void 0:t.stype)||(e.push("Node stype is required"),r.push(W.NODE_TYPE_REQUIRED)),(t==null?void 0:t.stype)==="text"){const s=t.text&&t.text!==void 0&&t.text!=="",i=((o=t.attributes)==null?void 0:o.content)&&t.attributes.content!==void 0&&t.attributes.content!=="";!s&&!i&&(e.push("Text content or content attribute is required for text nodes"),r.push(W.TEXT_CONTENT_REQUIRED))}return{valid:e.length===0,errors:e,errorCodes:r}}static validateDocumentStructure(t){const e=[],r=[];return t?(t.sid||(e.push("Document ID is required"),r.push(W.DOCUMENT_ID_REQUIRED)),t.schema||(e.push("Document schema is required"),r.push(W.DOCUMENT_SCHEMA_REQUIRED)),(!t.content||t.content.length===0)&&(e.push("Document content is required"),r.push(W.DOCUMENT_CONTENT_REQUIRED)),t.content&&Array.isArray(t.content)&&t.content.forEach((n,o)=>{const s=this.validateNodeStructure(n);s.valid||(s.errors.forEach(i=>{e.push(`Node ${o}: ${i}`)}),s.errorCodes&&s.errorCodes.forEach(i=>{r.push(i)}))}),{valid:e.length===0,errors:e,errorCodes:r}):(e.push("Document is required"),r.push(W.DOCUMENT_REQUIRED),{valid:!1,errors:e,errorCodes:r})}static validateNode(t,e){const r=[],n=[];if(!t||typeof t.hasNodeType!="function")return console.error("Invalid schema passed to validateNode:",t),r.push("Invalid schema instance"),n.push(W.INVALID_SCHEMA_INSTANCE),{valid:!1,errors:r,errorCodes:n};const o=e==null?void 0:e.stype;if(!t.hasNodeType(o))return r.push(`Unknown node type: ${o}`),n.push(W.NODE_TYPE_UNKNOWN),{valid:!1,errors:r,errorCodes:n};const s=t.validateAttributes(o,e.attrs||{});if(s.valid||(r.push(...s.errors),n.push(W.ATTRIBUTE_INVALID)),e.content){const a=t.validateContent(o,e.content);a.valid||(r.push(...a.errors),n.push(W.CONTENT_REQUIRED_BUT_EMPTY))}const i=t.getNodeType(o);if(i&&(i.indentable&&i.group&&i.group!=="block"&&r.push(`Node type '${o}' is indentable but its group is '${i.group}'. Indentable nodes are expected to be in the 'block' group.`),typeof i.maxIndentLevel=="number"&&i.maxIndentLevel<=0&&r.push(`Node type '${o}' has invalid maxIndentLevel '${i.maxIndentLevel}'. Expected a positive integer or undefined.`),!i.indentable&&Array.isArray(i.indentParentTypes)&&i.indentParentTypes.length>0&&r.push(`Node type '${o}' defines indentParentTypes but is not indentable. Either set indentable: true or remove indentParentTypes.`),Array.isArray(i.indentParentTypes)))for(const a of i.indentParentTypes)t.hasNodeType(a)||r.push(`Node type '${o}' has indentParentTypes entry '${a}' which is not defined in the schema.`);return{valid:r.length===0,errors:r,errorCodes:n}}static validateDocument(t,e){const r=[];e.stype!==t.topNode&&r.push(`Document stype '${e.stype}' does not match schema topNode '${t.topNode}'`);const n=t.validateAttributes(t.topNode,e.attrs||{});if(n.valid||r.push(...n.errors),e.content){const o=t.validateContent(t.topNode,e.content);o.valid||r.push(...o.errors),e.content.forEach((s,i)=>{const a=this.validateNode(t,s);a.valid||r.push(...a.errors.map(c=>`Child node ${i}: ${c}`))})}return{valid:r.length===0,errors:r}}static validateType(t,e){switch(e){case"string":return typeof t=="string";case"number":return typeof t=="number";case"boolean":return typeof t=="boolean";case"array":return Array.isArray(t);case"object":return typeof t=="object"&&t!==null&&!Array.isArray(t);case"custom":return!0;default:return!1}}static validateObjectSchema(t,e){const r=[];if(!t||typeof t!="object"||Array.isArray(t))return{valid:!1,errors:["Value must be a valid object"]};for(const[i,a]of Object.entries(e)){if((typeof a.required=="function"?a.required(t):a.required)&&(t[i]===void 0||t[i]===null)){r.push(`Required object property '${i}' is missing`);continue}if(t[i]!==void 0&&t[i]!==null){if(!this.validateType(t[i],a.type)){r.push(`Object property '${i}' has invalid type. Expected ${a.type}, got ${typeof t[i]}`);continue}if(a.type==="object"&&a.objectSchema){const l=this.validateObjectSchema(t[i],a.objectSchema);l.valid||r.push(...l.errors.map(u=>`Object property '${i}': ${u}`))}a.validator&&!a.validator(t[i],t)&&r.push(`Object property '${i}' failed custom validation`)}}const n=new Set(Object.keys(e)),s=Object.keys(t).filter(i=>!n.has(i));return s.length>0&&r.push(`Object contains undefined properties: ${s.join(", ")}`),{valid:r.length===0,errors:r}}static validateAttributes(t,e){const r=[];for(const n in t){const o=t[n],s=e[n];if((typeof o.required=="function"?o.required(e):o.required)&&(s==null||s==="")){r.push(`Required attribute '${n}' is missing or empty.`);continue}if(s!=null){if(this.validateType(s,o.type)||r.push(`Attribute '${n}' has invalid type. Expected ${o.type}, got ${typeof s}.`),o.type==="object"&&o.objectSchema){const a=this.validateObjectSchema(s,o.objectSchema);a.valid||r.push(...a.errors.map(c=>`Attribute '${n}': ${c}`))}o.validator&&!o.validator(s,e)&&r.push(`Attribute '${n}' failed custom validation.`)}}return{valid:r.length===0,errors:r}}static validateContentModel(t,e,r){const n=[],o=t.getNodeType(e);if(!o)return{valid:!1,errors:[`Unknown node type: ${e}`]};const s=o.content;if(!s)return{valid:!0,errors:[]};const i=s.trim();if(i.endsWith("+")){r.length===0&&n.push(`Content is required but empty for model '${i}'.`);const a=i.slice(0,-1);r.forEach((c,l)=>{if(!t.hasNodeType(c.stype)){n.push(`Node at index ${l} has unknown type '${c.stype}'.`);return}const u=t.getNodeType(c.stype);(u==null?void 0:u.group)!==a&&c.stype!==a&&n.push(`Node at index ${l} of type '${c.stype}' does not match required content model '${a}'.`)})}else if(i.endsWith("*")){const a=i.slice(0,-1);r.forEach((c,l)=>{if(!t.hasNodeType(c.stype)){n.push(`Node at index ${l} has unknown type '${c.stype}'.`);return}const u=t.getNodeType(c.stype);(u==null?void 0:u.group)!==a&&c.stype!==a&&n.push(`Node at index ${l} of type '${c.stype}' does not match required content model '${a}'.`)})}else if(i.endsWith("?")){if(r.length>1&&n.push(`Content for model '${i}' must be 0 or 1 node, but got ${r.length}.`),r.length===1){const a=i.slice(0,-1),c=r[0];if(!t.hasNodeType(c.stype))return n.push(`Node has unknown type '${c.stype}'.`),{valid:n.length===0,errors:n};const l=t.getNodeType(c.stype);(l==null?void 0:l.group)!==a&&c.stype!==a&&n.push(`Node of type '${c.stype}' does not match required content model '${a}'.`)}}else if(i.includes("|")){const a=i.split("|").map(c=>c.trim());r.forEach((c,l)=>{if(!a.includes(c.stype)){const u=t.getNodeType(c.stype),f=u==null?void 0:u.group;a.includes(f||"")||n.push(`Node at index ${l} of type '${c.stype}' does not match any allowed types in '${i}'.`)}})}else i!==""&&r.forEach((a,c)=>{if(!t.hasNodeType(a.stype)){n.push(`Node at index ${c} has unknown type '${a.stype}'.`);return}const l=t.getNodeType(a.stype);a.stype!==i&&(l==null?void 0:l.group)!==i&&n.push(`Node at index ${c} of type '${a.stype}' does not match required type or group '${i}'.`)});return{valid:n.length===0,errors:n}}}class dr{constructor(t,e){y(this,"topNode");y(this,"nodes");y(this,"marks");this.name=t,this.definition=e,this.topNode=e.topNode||"doc",this.nodes=new Map,this.marks=new Map;for(const[r,n]of Object.entries(e.nodes))this.nodes.set(r,{...n,name:r});if(e.marks)for(const[r,n]of Object.entries(e.marks))this.marks.set(r,{...n,name:r})}getAttribute(t,e){var n;const r=this.getNodeType(t);return(n=r==null?void 0:r.attrs)==null?void 0:n[e]}getContentModel(t){const e=this.getNodeType(t);return e==null?void 0:e.content}validateAttributes(t,e){const r=this.getNodeType(t);return r?xt.validateAttributes(r.attrs||{},e):{valid:!1,errors:[`Unknown node type: ${t}`]}}validateContent(t,e){const r=this.getNodeType(t);return r?r.content?xt.validateContentModel(this,t,e):{valid:!0,errors:[]}:{valid:!1,errors:[`Unknown node type: ${t}`]}}transform(t,e){var o;const r=this.getNodeType(t);if(!r)throw new Error(`Unknown node type: ${t}`);const n={...e};if(r.attrs)for(const[s,i]of Object.entries(r.attrs))i.transform&&((o=n.attrs)!=null&&o[s])&&(n.attrs[s]=i.transform(n.attrs[s]));return n}getNodeType(t){return this.nodes.get(t)}hasNodeType(t){return this.nodes.has(t)}getNodeTypesByGroup(t){return Array.from(this.nodes.values()).filter(e=>e.group===t)}getMarkType(t){return this.marks.get(t)}hasMarkType(t){return this.marks.has(t)}getMarkTypesByGroup(t){return Array.from(this.marks.values()).filter(e=>e.group===t)}validateMarks(t){const e=[];for(const r of t){const n=this.getMarkType(r.type);if(!n){e.push(`Unknown mark type: ${r.type}`);continue}if(n.attrs&&r.attrs)for(const[o,s]of Object.entries(n.attrs)){const i=r.attrs[o];if((typeof s.required=="function"?s.required(r.attrs):s.required)&&i==null){e.push(`Required mark attribute '${o}' is missing for mark '${r.type}'`);continue}i!=null&&(this.validateAttributeType(i,s.type)||e.push(`Mark '${r.type}' attribute '${o}' has invalid type. Expected ${s.type}, got ${typeof i}`),s.validator&&!s.validator(i,r.attrs)&&e.push(`Mark '${r.type}' attribute '${o}' failed custom validation`))}if(n.excludes){const o=t.filter(s=>s!==r&&n.excludes.includes(s.type));o.length>0&&e.push(`Mark '${r.type}' cannot be used with: ${o.map(s=>s.type).join(", ")}`)}}return{valid:e.length===0,errors:e}}validateAttributeType(t,e){switch(e){case"string":return typeof t=="string";case"number":return typeof t=="number";case"boolean":return typeof t=="boolean";case"array":return Array.isArray(t);case"object":return typeof t=="object"&&t!==null&&!Array.isArray(t);case"custom":return!0;default:return!1}}doc(t){return{type:this.topNode,content:t||[]}}node(t,e,r){if(!this.getNodeType(t))throw new Error(`Unknown node type: ${t}`);return{type:t,attrs:e||{},content:r||[]}}text(t,e,r){if(!this.getNodeType("text"))throw new Error("Text node type not defined in schema");if(r&&r.length>0){const o=this.validateMarks(r);if(!o.valid)throw new Error(`Invalid marks: ${o.errors.join(", ")}`)}return{type:"text",content:t,attrs:e||{},marks:r||[]}}}function cr(d,t){const e=d,r=t;return new dr(e,r)}function Dt(){return{topNode:"document",nodes:{document:{name:"document",group:"document",content:"block+"},paragraph:{name:"paragraph",group:"block",content:"inline*"},"inline-text":{name:"inline-text",group:"inline"}},marks:{bold:{name:"bold",group:"text-style"},italic:{name:"italic",group:"text-style"}}}}class lr{static validateNode(t,e){function r(n){if(!n||typeof n!="object")return n;const o={stype:n.stype,attrs:n.attributes||{},text:n.text,marks:n.marks};return Array.isArray(n.content)&&(o.content=n.content.map(s=>s&&typeof s=="object"&&"stype"in s?r(s):s).filter(s=>s!==void 0)),o}return xt.validateNode(e,r(t))}}function ur(d,t){return lr.validateNode(d,t)}class fr{constructor(t){this.dataStore=t}setNode(t,e=!0){this.dataStore.constructor._globalCounter=this.dataStore.getNodes().size,t.sid||(t.sid=this.dataStore.generateId());const r=this.dataStore.getActiveSchema();if(e&&r)if(t.content&&Array.isArray(t.content)&&t.content.some(a=>typeof a=="object"&&a!==null)){const a=this.dataStore.validateNode(t,r);if(!a.valid)throw new Error(`Schema validation failed for node ${t.sid}: ${a.errors.join(", ")}`)}else{const a={...t,content:void 0},c=this.dataStore.validateNode(a,r);if(!c.valid)throw new Error(`Schema validation failed for node ${t.sid}: ${c.errors.join(", ")}`)}this._convertChildrenToDataStore(t);const n=this.dataStore._overlay,s={type:!this.dataStore.getNodes().has(t.sid)?"create":"update",nodeId:t.sid,data:{stype:t.stype,attributes:t.attributes,text:t.text,content:t.content,parentId:t.parentId,marks:t.marks},timestamp:Date.now(),parentId:t.parentId};n&&n.isActive&&n.isActive()?n.upsertNode(t,s.type):this.dataStore.setNodeInternal(t),this.dataStore.emitOperation(s)}getNode(t){const e=this.dataStore._overlay;if(!(e&&typeof e.hasDeleted=="function"&&e.hasDeleted(t)))return e&&typeof e.hasOverlayNode=="function"&&e.hasOverlayNode(t)?e.getOverlayNode(t):this.dataStore.getNodes().get(t)}deleteNode(t){const e=this.dataStore._overlay,r=this.getNode(t);if(!r)return!1;const n=this.dataStore.getRootNodeId&&this.dataStore.getRootNodeId();if(n&&t===n)throw new Error("Cannot delete root node");let o=!1;if(e&&e.isActive&&e.isActive()?(e.markDeleted(t,r.parentId),o=!0):o=this.dataStore.getNodes().delete(t),o){if(r.parentId){const i=this.dataStore.getNodes().get(r.parentId);if(i&&i.content){const a=i.content.indexOf(t);a!==-1&&(i.content.splice(a,1),this.updateNode(r.parentId,{content:i.content},!1))}}const s={type:"delete",nodeId:t,timestamp:Date.now(),parentId:r.parentId};this.dataStore.emitOperation(s)}return o}updateNode(t,e,r=!0){const n=this.getNode(t);if(!n)return{valid:!1,errors:[`Node not found: ${t}`]};if(e.stype&&e.stype!==n.stype)return{valid:!1,errors:[`Cannot change node stype from '${n.stype}' to '${e.stype}'`]};const o={...n,...e};e.attributes&&n.attributes&&(o.attributes={...n.attributes,...e.attributes});const s=e.content!==void 0;if(r&&!s)try{return this.setNode(o,!0),{valid:!0,errors:[]}}catch(i){return{valid:!1,errors:[i instanceof Error?i.message:"Validation failed"]}}else return this.setNode(o,!1),{valid:!0,errors:[]}}createNodeWithChildren(t,e){const r=e||this.dataStore.getActiveSchema();if(t.parentId==null&&(this.dataStore.constructor._globalCounter=this.dataStore.getNodes().size),this._assignIdsRecursively(t),r){const o=this.dataStore.validateNode(t,r);if(!o.valid)throw new Error(`Schema validation failed for node ${t.sid}: ${o.errors.join(", ")}`)}this._createAllNodesRecursively(t);const n=this.dataStore.getNode(t.sid);if(!n)throw new Error(`Failed to retrieve created node ${t.sid}`);return n}_createAllNodesRecursively(t){t.content&&Array.isArray(t.content)&&(t.content=t.content.map(n=>typeof n=="object"&&n!==null?(this._createAllNodesRecursively(n),n.sid):n));const e=this.dataStore._overlay;if(e&&e.isActive&&e.isActive())e.upsertNode(t,"create");else{const n={...t,marks:t.marks};this.dataStore.setNodeInternal(n)}const r={type:"create",nodeId:t.sid,data:{stype:t.stype,attributes:t.attributes,text:t.text,content:t.content,parentId:t.parentId,marks:t.marks},timestamp:Date.now(),parentId:t.parentId};this.dataStore.emitOperation(r)}_assignIdsRecursively(t){t.sid||(t.sid=this.dataStore.generateId()),t.content&&Array.isArray(t.content)&&t.content.forEach(e=>{if(typeof e=="object"&&e!==null){const r=e;r.parentId=t.sid,this._assignIdsRecursively(r)}else if(typeof e=="string"){const r=this.getNode(e);r&&(r.parentId=t.sid)}})}_convertChildrenToDataStore(t){t.content&&Array.isArray(t.content)&&(t.content=t.content.map(e=>{if(typeof e=="object"&&e!==null){const r=e;r.sid||(r.sid=this.dataStore.generateId()),r.parentId=t.sid,this._convertChildrenToDataStore(r);const o=this.dataStore.getNode(r.sid)!==void 0?"update":"create",s=this.dataStore._overlay;s&&s.isActive&&s.isActive()?s.upsertNode(r,o):this.dataStore.setNodeInternal(r);const i={type:o,nodeId:r.sid,data:{stype:r.stype,attributes:r.attributes,text:r.text,content:r.content,parentId:r.parentId,marks:r.marks},timestamp:Date.now(),parentId:r.parentId};return this.dataStore.emitOperation(i),r.sid}return e}))}transformNode(t,e,r){const n=this.dataStore.getNode(t);if(!n)return{valid:!1,errors:[`Node not found: ${t}`]};if(n.stype===e)return{valid:!0,errors:[],newNodeId:t};const o=n.parentId;let s;if(o){const c=this.dataStore.getNode(o);c&&Array.isArray(c.content)&&(s=c.content.indexOf(t))}const i={...n,stype:e,attributes:{...n.attributes||{},...r||{}}},a=this.dataStore.getActiveSchema();if(a){const c=this.dataStore.validateNode(i,a);if(!c.valid)return{valid:!1,errors:c.errors}}if(o&&s!==void 0){const c=this.dataStore.getNode(o);if(c&&Array.isArray(c.content)){const l=[...c.content];l.splice(s,1),this.dataStore.updateNode(o,{content:l},!1)}}if(this.setNode(i,!0),o&&s!==void 0){const c=this.dataStore.getNode(o);if(c&&Array.isArray(c.content)){const l=[...c.content];l.splice(s,0,t),this.dataStore.updateNode(o,{content:l},!1)}}return{valid:!0,errors:[],newNodeId:t}}}class hr{constructor(t){this.dataStore=t}findNodes(t){const e=[];for(const[r,n]of this.dataStore.getNodes()){const o=this.dataStore.getNode(r);o&&t(o)&&e.push(o)}return e}findNodesByType(t){const e=[],r=this.dataStore.createDocumentIterator({filter:{stype:t}});for(const n of r){const o=this.dataStore.getNode(n);o&&e.push(o)}return e}findNodesByAttribute(t,e){return this.findNodes(r=>!!(r.attributes&&r.attributes[t]===e))}findNodesByText(t){return!t||t.trim()===""?[]:this.findNodes(e=>!!(e.text&&e.text.includes(t)))}findChildrenByParentId(t){const e=this.dataStore.getNode(t);return!e||!e.content?[]:e.content.map(r=>this.dataStore.getNode(r)).filter(r=>r!==void 0)}findRootNodes(){return this.findNodes(t=>!t.parentId)}searchText(t){if(!t||t.trim()==="")return[];const e=t.toLowerCase(),r=[];for(const[n,o]of this.dataStore.getNodes()){const s=this.dataStore.getNode(n);s&&s.text&&s.text.toLowerCase().includes(e)&&r.push(s)}return r}getNodeChildren(t){const e=this.dataStore.getNode(t);return!e||!e.content?[]:e.content.map(r=>this.dataStore.getNode(r)).filter(r=>r!==void 0)}getNodeChildrenDeep(t){const e=this.dataStore.getNode(t);return!e||!e.content?[]:e.content.map(r=>{const n=this.dataStore.getNode(r);return n?{...n,content:n.content?this.getNodeChildrenDeep(n.sid):n.content}:null}).filter(Boolean)}getNodeWithChildren(t){const e=this.dataStore.getNode(t);return e?{...e,content:this.getNodeChildrenDeep(t)}:null}getAllNodesWithChildren(){const t=[],e=this.dataStore.createDocumentIterator();for(const r of e){const n=this.getNodeWithChildren(r);n&&t.push(n)}return t}findNodesWithVisitor(t,e){const r=[];return this.dataStore.traverse({visit:(n,o)=>{const s=t(o,[n]);return s!==!1&&r.push(o),s}},e),r}findNodesByDepth(t,e){const r=[],n=this.dataStore.createDocumentIterator({maxDepth:t});for(const o of n){const s=this.dataStore.getNode(o);s&&(!e||e(s))&&r.push(s)}return r}}class gr{constructor(t){this.dataStore=t}addChild(t,e,r){const n=this.dataStore._overlay,o=this.dataStore.getNode(t);if(!o){if(n&&n.isActive&&n.isActive())return typeof e=="string"?e:(e.sid||(e.sid=this.dataStore.generateId()),this.dataStore.setNode(e),e.sid);throw new Error(`Parent node not found: ${t}`)}let s,i;if(typeof e=="string"){s=e;const u=this.dataStore.getNode(s);if(!u)throw new Error(`Child node not found: ${s}`);i=u}else e.sid||(e.sid=this.dataStore.generateId()),s=e.sid,i=e,this.dataStore.setNode(i);const a=Array.isArray(o.content)?o.content:[],c=r!==void 0?r:a.length,l=[...a];return l.splice(c,0,s),this.dataStore.updateNode(t,{content:l},!1),o.content=l,this.dataStore.updateNode(s,{parentId:t},!1),i&&(i.parentId=t),s}removeChild(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Parent node not found: ${t}`);if(!this.dataStore.getNode(e))return!1;if(Array.isArray(r.content)){const o=r.content.indexOf(e);if(o>-1){const s=[...r.content];return s.splice(o,1),this.dataStore.updateNode(t,{content:s},!1),r.content=s,this.dataStore.updateNode(e,{parentId:void 0},!1),!0}}return!1}moveNode(t,e,r){const n=this.dataStore.getNode(t);if(!n)throw new Error(`Node not found: ${t}`);const o=this.dataStore._overlay,s=this.dataStore.getNode(e);if(!s){if(o&&o.isActive&&o.isActive())return;throw new Error(`Parent node not found: ${e}`)}if(n.parentId){const l=this.dataStore.getNode(n.parentId);if(l&&Array.isArray(l.content)){const u=l.content.indexOf(t);if(u>-1){const f=[...l.content];f.splice(u,1),this.dataStore.updateNode(l.sid,{content:f},!1),l.content=f}}}const i=Array.isArray(s.content)?s.content:[],a=r!==void 0?r:i.length,c=[...i];c.splice(a,0,t),this.dataStore.updateNode(e,{content:c},!1),s.content=c,this.dataStore.updateNode(t,{parentId:e},!1),n.parentId=e,this.dataStore.emitOperation({type:"move",nodeId:t,parentId:e,position:a,timestamp:Date.now()})}copyNode(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Node not found: ${t}`);const n=this.dataStore.generateId(),o={...r,sid:n,parentId:e||r.parentId};if(this.dataStore.setNode(o),e){const s=this.dataStore.getNode(e);if(s){const a=[...Array.isArray(s.content)?s.content:[],n];this.dataStore.updateNode(e,{content:a},!1),s.content=a}}return n}cloneNodeWithChildren(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Node not found: ${t}`);const n=this.dataStore.generateId(),o={...r,sid:n,parentId:e||r.parentId,content:[]};if(this.dataStore.setNode(o),r.content&&Array.isArray(r.content)){const s=[];for(const i of r.content)if(typeof i=="string"){const a=this.cloneNodeWithChildren(i,n);s.push(a)}o.content=s,this.dataStore.updateNode(o.sid,{content:s},!1)}if(e){const s=this.dataStore.getNode(e);if(s){const a=[...Array.isArray(s.content)?s.content:[],n];this.dataStore.updateNode(e,{content:a},!1),s.content=a}}return n}reorderChildren(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Parent node not found: ${t}`);for(const s of e)if(!this.dataStore.getNode(s))throw new Error(`Child node not found: ${s}`);const n=Array.isArray(r.content)?[...r.content]:[];this.dataStore.updateNode(t,{content:[...e]},!1),r.content=[...e];const o=new Map;e.forEach((s,i)=>o.set(s,i));for(let s=0;s<e.length;s++){const i=e[s];n.indexOf(i)!==s&&this.dataStore.emitOperation({type:"move",nodeId:i,parentId:t,position:s,timestamp:Date.now()})}}addChildren(t,e,r){var i;const n=this.dataStore.getNode(t);if(!n)throw new Error(`Parent node not found: ${t}`);const o=[],s=r!==void 0?r:((i=n.content)==null?void 0:i.length)||0;for(let a=0;a<e.length;a++){const c=e[a],l=this.addChild(t,c,s+a);o.push(l)}return o}removeChildren(t,e){if(!this.dataStore.getNode(t))throw new Error(`Parent node not found: ${t}`);const n=[];for(const o of e)n.push(this.removeChild(t,o));return n}moveChildren(t,e,r,n){if(!this.dataStore.getNode(t))throw new Error(`From parent node not found: ${t}`);const s=this.dataStore._overlay;if(!this.dataStore.getNode(e)){if(s&&s.isActive&&s.isActive())return;throw new Error(`To parent node not found: ${e}`)}for(const a of r)if(!this.dataStore.getNode(a))throw new Error(`Child node not found: ${a}`);for(let a=0;a<r.length;a++){const c=r[a],l=n!==void 0?n+a:void 0;this.moveNode(c,e,l)}}moveBlockUp(t){const e=this.dataStore.getNode(t);if(!e||!e.parentId)return!1;const r=this.dataStore.getNode(e.parentId);if(!r||!Array.isArray(r.content))return!1;const n=r.content.indexOf(t);if(n===-1||n===0)return!1;const o=[...r.content],[s]=o.splice(n,1);o.splice(n-1,0,s);const i=o.map(a=>typeof a=="string"?a:a.sid??"");return this.reorderChildren(e.parentId,i),!0}moveBlockDown(t){const e=this.dataStore.getNode(t);if(!e||!e.parentId)return!1;const r=this.dataStore.getNode(e.parentId);if(!r||!Array.isArray(r.content))return!1;const n=r.content.indexOf(t);if(n===-1||n===r.content.length-1)return!1;const o=[...r.content],[s]=o.splice(n,1);o.splice(n+1,0,s);const i=o.map(a=>typeof a=="string"?a:a.sid??"");return this.reorderChildren(e.parentId,i),!0}}class pr{constructor(t){this.dataStore=t}splitTextNode(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Node not found: ${t}`);if(typeof r.text!="string")throw new Error(`Node is not a text node: ${r.stype}`);const n=r.text||"";if(e<0||e>n.length)throw new Error(`Invalid split position: ${e}`);if(e===0||e===n.length)throw new Error(`Split position must be between 0 and ${n.length}`);const o=n.substring(0,e),s=n.substring(e),i=[],a=[];if(r.marks)for(const u of r.marks){const[f,h]=u.range||[0,n.length];f<e&&h>e?(i.push({...u,range:[f,e]}),a.push({...u,range:[0,h-e]})):h<=e?i.push({...u,range:[f,h]}):f>=e&&a.push({...u,range:[f-e,h-e]})}this.dataStore.updateNode(t,{text:o,marks:i},!1);const c={stype:r.stype,text:s,attributes:{...r.attributes},marks:a,parentId:r.parentId},l=this.dataStore.generateId();if(c.sid=l,this.dataStore.setNode(c,!1),r.parentId){const u=this.dataStore.getNode(r.parentId);if(u&&u.content){const f=u.content.indexOf(t);if(f!==-1){const h=[...u.content];h.splice(f+1,0,l),this.dataStore.updateNode(u.sid,{content:h},!1)}}}return l}mergeTextNodes(t,e){const r=this.dataStore.getNode(t),n=this.dataStore.getNode(e);if(!r||!n)throw new Error(`Node not found: ${t} or ${e}`);if(typeof r.text!="string")throw new Error(`Left node is not a text node: ${r.stype}`);if(typeof n.text!="string")throw new Error(`Right node is not a text node: ${n.stype}`);const o=r.text||"",s=n.text||"",i=o+s;if(r.marks&&(r.marks=r.marks.map(a=>({...a,range:a.range||[0,o.length]}))),n.marks){const a=o.length,c=n.marks.map(l=>({...l,range:l.range?[l.range[0]+a,l.range[1]+a]:[a,a+s.length]}));r.marks?r.marks.push(...c):r.marks=c}if(this.dataStore.updateNode(t,{text:i,marks:r.marks},!1),r.parentId){const a=this.dataStore.getNode(r.parentId);if(a&&a.content){const c=a.content.indexOf(e);if(c!==-1){const l=[...a.content];l.splice(c,1),this.dataStore.updateNode(a.sid,{content:l},!1)}}}return this.dataStore.deleteNode(e),t}splitBlockNode(t,e){const r=this.dataStore.getNode(t);if(!r)throw new Error(`Node not found: ${t}`);if(!r.content||r.content.length===0)throw new Error(`Node has no content to split: ${t}`);if(e<0||e>r.content.length)throw new Error(`Invalid split position: ${e}`);if(e===0||e===r.content.length)throw new Error(`Split position must be between 0 and ${r.content.length}`);const n={stype:r.stype,attributes:{...r.attributes},content:[],parentId:r.parentId},o=this.dataStore.generateId();n.sid=o,this.dataStore.setNode(n,!1);const s=r.content.splice(e);n.content=s,this.dataStore.updateNode(o,{content:s},!1);for(const i of s)this.dataStore.getNode(i)&&this.dataStore.updateNode(i,{parentId:o},!1);if(this.dataStore.updateNode(t,{content:r.content},!1),r.parentId){const i=this.dataStore.getNode(r.parentId);if(i&&i.content){const a=i.content.indexOf(t);if(a!==-1){const c=[...i.content];c.splice(a+1,0,o),this.dataStore.updateNode(i.sid,{content:c},!1)}}}return o}mergeBlockNodes(t,e){const r=this.dataStore.getNode(t),n=this.dataStore.getNode(e);if(!r||!n)throw new Error(`Node not found: ${t} or ${e}`);if(r.stype!==n.stype)throw new Error(`Cannot merge different node types: ${r.stype} and ${n.stype}`);if(n.content&&n.content.length>0){r.content||(r.content=[]);for(const o of n.content)this.dataStore.getNode(o)&&this.dataStore.updateNode(o,{parentId:t},!1);r.content.push(...n.content)}return this.dataStore.updateNode(t,{content:r.content},!1),this.dataStore.deleteNode(e),t}splitTextRange(t,e,r){const n=this.dataStore.getNode(t);if(!n)throw new Error(`Node not found: ${t}`);if(typeof n.text!="string")throw new Error(`Node is not a text node: ${n.stype}`);const o=n.text||"";if(e<0||r>o.length||e>=r)throw new Error(`Invalid range: ${e}-${r}`);const s=this.splitTextNode(t,e);return this.splitTextNode(s,r-e),s}autoMergeTextNodes(t){const e=this.dataStore.getNode(t);if(!e||!e.parentId||typeof e.text!="string")return t;let r=this.dataStore.getNode(e.parentId);if(!r||!r.content)return t;let n=r.content.indexOf(t);if(n===-1)return t;let o=t;for(;n>0;){const s=r.content[n-1],i=this.dataStore.getNode(s);if(i&&typeof i.text=="string")if(o=this.mergeTextNodes(s,o),r=this.dataStore.getNode(e.parentId),r&&r.content){if(n=r.content.indexOf(o),n<=0)break}else break;else break}for(;;){const s=this.dataStore.getNode(e.parentId);if(!s||!s.content)break;const i=s.content.indexOf(o);if(i===-1||i>=s.content.length-1)break;const a=s.content[i+1],c=this.dataStore.getNode(a);if(c&&typeof c.text=="string")o=this.mergeTextNodes(o,a);else break}return o}deleteTextRange(t,e,r){const n=this.dataStore.getNode(t);if(!n)throw new Error(`Node not found: ${t}`);if(typeof n.text!="string")throw new Error(`Node is not a text node: ${n.stype}`);const o=n.text||"";if(e<0||r>o.length||e>=r)throw new Error(`Invalid range: [${e}, ${r}] for text of length ${o.length}`);const s=o.substring(e,r),i=r-e,a=o.substring(0,e)+o.substring(r);return n.text=a,n.marks&&(n.marks=n.marks.map(c=>{if(!c.range)return c;const[l,u]=c.range;if(l<r&&u>e){if(l>=e&&u<=r)return null;if(l<e&&u>r)return[{...c,range:[l,e]},{...c,range:[u-i,u-i]}];if(l<e&&u<=r)return{...c,range:[l,e]};if(l>=e&&u>r)return{...c,range:[l-i,u-i]}}else return l>=r?{...c,range:[l-i,u-i]}:c}).flat().filter(Boolean)),this.dataStore.setNodeInternal(n),s}replaceTextRange(t,e,r,n){const o=this.dataStore.getNode(t);if(!o)throw new Error(`Node not found: ${t}`);if(typeof o.text!="string")throw new Error(`Node is not a text node: ${o.stype}`);const s=o.text||"";if(e<0||r>s.length||e>r)throw new Error(`Invalid range: [${e}, ${r}] for text of length ${s.length}`);const i=s.substring(e,r),a=n.length-(r-e),c=s.substring(0,e)+n+s.substring(r);return o.text=c,o.marks&&(o.marks=o.marks.map(l=>{if(!l.range)return l;const[u,f]=l.range;if(u<r&&f>e){if(u>=e&&f<=r)return null;if(u<e&&f>r)return[{...l,range:[u,e]},{...l,range:[e+n.length,f-(r-e)+n.length]}];if(u<e&&f<=r)return{...l,range:[u,e]};if(u>=e&&f>r)return{...l,range:[e+n.length,f-(r-e)+n.length]}}else return u>=r?{...l,range:[u+a,f+a]}:l}).flat().filter(Boolean)),this.dataStore.setNodeInternal(o),i}insertText(t,e,r){const n=this.dataStore.getNode(t);if(!n)throw new Error(`Node not found: ${t}`);if(typeof n.text!="string")throw new Error(`Node is not a text node: ${n.stype}`);const o=n.text||"";if(e<0||e>o.length)throw new Error(`Invalid position: ${e} for text of length ${o.length}`);const s=o.substring(0,e)+r+o.substring(e);return n.text=s,n.marks&&(n.marks=n.marks.map(i=>{if(!i.range)return i;const[a,c]=i.range;return a>=e?{...i,range:[a+r.length,c+r.length]}:c>e?{...i,range:[a,c+r.length]}:i})),this.dataStore.setNodeInternal(n),r}}class mr{constructor(t){this.dataStore=t}normalizeMarks(t){var u;const e=this.dataStore.getNode(t);if(!e)return;if(!e.marks||e.marks.length===0){this.dataStore.updateNode(e.sid,{marks:[]},!1);return}const r=((u=e.text)==null?void 0:u.length)||0;if(r===0){this.dataStore.updateNode(e.sid,{marks:[]},!1);return}const s=e.marks.map(f=>f.range?f:{...f,range:[0,r]}).map(f=>({...f,range:[Math.max(0,Math.min(f.range[0],r)),Math.max(0,Math.min(f.range[1],r))]})).filter(f=>f.range[0]<f.range[1]),i=this.removeDuplicateMarks(s),c=this.mergeOverlappingMarks(i).sort((f,h)=>f.range[0]-h.range[0]);this.dataStore.updateNode(e.sid,{marks:c},!1);const l=this.dataStore.getNode(e.sid);l&&(l.marks=c)}removeDuplicateMarks(t){const e=new Set;return t.filter(r=>{const n=r.range?`${r.stype}:${JSON.stringify(r.attrs||{})}:${r.range[0]}-${r.range[1]}`:`${r.stype}:${JSON.stringify(r.attrs||{})}:global`;return e.has(n)?!1:(e.add(n),!0)})}mergeOverlappingMarks(t){if(t.length<=1)return t;const e=t.filter(o=>o.range);if(e.length<=1)return e;const r=[];let n={...e[0]};for(let o=1;o<e.length;o++){const s=e[o];this.canMergeMarks(n,s)?n.range[1]>=s.range[0]?n.range[1]=Math.max(n.range[1],s.range[1]):(r.push(n),n={...s}):(r.push(n),n={...s})}return r.push(n),r}canMergeMarks(t,e){if(t.stype!==e.stype)return!1;const r=t.attrs||{},n=e.attrs||{},o=Object.keys(r),s=Object.keys(n);if(o.length!==s.length)return!1;for(const i of o)if(r[i]!==n[i])return!1;return!0}normalizeAllMarks(){const t=this.dataStore.getAllNodes();let e=0;for(const r of t)this.isTextNode(r)&&Array.isArray(r.marks)&&(this.normalizeMarks(r.sid),e++);return e}isTextNode(t){return typeof t.text=="string"}getMarkStatistics(t){const e=this.dataStore.getNode(t);if(!e||!e.marks)return{totalMarks:0,markTypes:{},overlappingMarks:0,emptyMarks:0};const r={};let n=0,o=0;for(const a of e.marks)r[a.stype]=(r[a.stype]||0)+1,(!a.range||a.range[0]>=a.range[1])&&o++;const s=e.marks.filter(a=>a.range&&a.range[0]<a.range[1]).sort((a,c)=>a.range[0]-c.range[0]),i=new Map;for(const a of s){const c=`${a.stype}:${JSON.stringify(a.attrs||{})}`;i.has(c)||i.set(c,[]),i.get(c).push(a)}for(const a of i.values())for(let c=0;c<a.length-1;c++){const l=a[c],u=a[c+1];l.range[1]>u.range[0]&&n++}return{totalMarks:e.marks.length,markTypes:r,overlappingMarks:n,emptyMarks:o}}removeEmptyMarks(t){var s;const e=this.dataStore.getNode(t);if(!e||!e.marks)return 0;const r=((s=e.text)==null?void 0:s.length)||0,n=e.marks.length,o=e.marks.filter(i=>i.range?i.range[0]<i.range[1]&&i.range[0]>=0&&i.range[1]<=r:!1);if(o.length!==n){this.dataStore.updateNode(e.sid,{marks:o},!1);const i=this.dataStore.getNode(e.sid);i&&(i.marks=o)}return n-o.length}setMarks(t,e,r={}){var i;const n=this.dataStore.getNode(t);if(!n)return{valid:!1,errors:[`Node not found: ${t}`]};const o=((i=n.text)==null?void 0:i.length)||0,s=r.normalize!==!1;try{let a=Array.isArray(e)?e.slice():[];if(s){const h=a.map(p=>p.range?p:{...p,range:[0,o]}).map(p=>({...p,range:[Math.max(0,Math.min(p.range[0],o)),Math.max(0,Math.min(p.range[1],o))]})).filter(p=>p.range[0]<p.range[1]),g=this.removeDuplicateMarks(h);a=this.mergeOverlappingMarks(g).sort((p,N)=>p.range[0]-N.range[0])}const c=this.dataStore.updateNode(t,{marks:a},!1),l=this.dataStore.getNode(t);return l&&(l.marks=a),!c||c.valid!==!0?{valid:!1,errors:(c==null?void 0:c.errors)||["Update failed"]}:{valid:!0,errors:[]}}catch(a){return{valid:!1,errors:[a instanceof Error?a.message:"Unknown error"]}}}removeMark(t,e,r){var u;const n=this.dataStore.getNode(t);if(!n)return{valid:!1,errors:[`Node not found: ${t}`]};const o=((u=n.text)==null?void 0:u.length)||0,[s,i]=r;if(s<0||i<0||s>o||i>o||s>i)return{valid:!1,errors:["Invalid range"]};const a=(n.marks||[]).filter(f=>f.stype!==e||!f.range?!0:!(f.range[0]===s&&f.range[1]===i)),c=this.dataStore.updateNode(t,{marks:a},!1),l=this.dataStore.getNode(t);return l&&(l.marks=a),!c||c.valid!==!0?{valid:!1,errors:(c==null?void 0:c.errors)||["Update failed"]}:{valid:!0,errors:[]}}updateMark(t,e,r,n){var u;const o=this.dataStore.getNode(t);if(!o)return{valid:!1,errors:[`Node not found: ${t}`]};const s=((u=o.text)==null?void 0:u.length)||0,[i,a]=r;if(i<0||a<0||i>s||a>s||i>=a)return{valid:!1,errors:["Invalid range"]};const c=(o.marks||[]).map(f=>f.stype===e&&f.range&&f.range[0]===i&&f.range[1]===a?{...f,attrs:{...f.attrs||{},...n||{}}}:f),l=this.dataStore.updateNode(t,{marks:c},!1);return!l||l.valid!==!0?{valid:!1,errors:(l==null?void 0:l.errors)||["Update failed"]}:{valid:!0,errors:[]}}toggleMark(t,e,r,n){var S,b;const o=this.dataStore.getNode(t);if(!o)return{valid:!1,errors:[`Node not found: ${t}`]};const s=((S=o.text)==null?void 0:S.length)||0,[i,a]=r;if(i<0||a<0||i>s||a>s||i>=a)return{valid:!1,errors:["Invalid range"]};const c=o.marks||[],[l,u]=r,f=[];let h=!1;for(const v of c){if(v.stype!==e||!v.range){f.push(v);continue}const[I,_]=v.range;if(_<=l||I>=u){f.push(v);continue}if(h=!0,!(I>=l&&_<=u)){if(I<l&&_>u){l>I&&f.push({...v,range:[I,l]}),_>u&&f.push({...v,range:[u,_]});continue}if(I<l&&_>l&&_<=u){f.push({...v,range:[I,l]});continue}if(I>=l&&I<u&&_>u){f.push({...v,range:[u,_]});continue}}}h||f.push({stype:e,attrs:n,range:r});const g=this.mergeOverlappingMarks(this.removeDuplicateMarks(f.filter(v=>!v.range||v.range[0]<v.range[1]).map(v=>{var I,_;return{...v,range:v.range||[0,((_=(I=this.dataStore.getNode(t))==null?void 0:I.text)==null?void 0:_.length)||0]}}))).sort((v,I)=>v.range[0]-I.range[0]),m=((b=this.dataStore.getNode(t))==null?void 0:b.marks)||[];if(JSON.stringify(m)===JSON.stringify(g))return{valid:!0,errors:[]};const N=this.dataStore.updateNode(t,{marks:g},!1),x=this.dataStore.getNode(t);return x&&(x.marks=g),!N||N.valid!==!0?{valid:!1,errors:(N==null?void 0:N.errors)||["Update failed"]}:{valid:!0,errors:[]}}}class yr{constructor(t){}adjustRanges(t,e,r){if(!t||t.length===0)return t;const{editPosition:n,insertedLength:o,deletedLength:s}=r,i=o-s,a=n+s;return t.map(c=>{if(c.target.sid!==e)return c;const{startOffset:l,endOffset:u}=c.target;return n<=l&&a>=u?{...c,target:{...c.target,startOffset:0,endOffset:0}}:n<=l?{...c,target:{...c.target,startOffset:l+i,endOffset:u+i}}:n<u?s>0&&a>l&&a<u?{...c,target:{...c.target,endOffset:u+i}}:{...c,target:{...c.target,endOffset:u+i}}:c}).filter(c=>{const{startOffset:l,endOffset:u}=c.target;return l>=0&&u>l})}}class Nr{constructor(){y(this,"behaviors",new Map)}register(t){(Array.isArray(t.targetType)?t.targetType:[t.targetType]).forEach(r=>{this.behaviors.has(r)||this.behaviors.set(r,[]),this.behaviors.get(r).push(t),this.behaviors.get(r).sort((n,o)=>(o.priority||0)-(n.priority||0))})}get(t,e,r,n,o){const s=this.behaviors.get(t)||[],i=this.behaviors.get("*")||[],a=[...s,...i];for(const c of a){if(c.sourceType){const l=Array.isArray(c.sourceType)?c.sourceType:[c.sourceType];if(!l.includes(e)&&!l.includes("*"))continue}if(typeof c.behavior=="function"){if(r&&n){const l=c.behavior(r,n,o||{});if(l!==null)return l;continue}}else return c.behavior}return null}clear(){this.behaviors.clear()}}const Sr=new Nr;class xr{constructor(t){this.dataStore=t}hasNode(t){return!!this.dataStore.getNode(t)}getChildCount(t){const e=this.dataStore.getNode(t);return!e||!e.content?0:e.content.length}isLeafNode(t){return this.getChildCount(t)===0}isRootNode(t){return this.dataStore.getRootNodeId()===t}getChildren(t){const e=this.dataStore.getNode(t);return!e||!e.content?[]:e.content.map(r=>this.dataStore.getNode(r)).filter(r=>r!==void 0)}getParent(t){const e=this.dataStore.getNode(t);if(!(!e||!e.parentId))return this.dataStore.getNode(e.parentId)}getSiblings(t){const e=this.getParent(t);return e?this.getChildren(e.sid).filter(r=>r.sid!==t):[]}getSiblingIndex(t){const e=this.getParent(t);return!e||!e.content?-1:e.content.findIndex(r=>r===t)}getPreviousSibling(t){const e=this.getParent(t);if(!e||!e.content)return null;const r=e.content.indexOf(t);return r<=0?null:e.content[r-1]}getNextSibling(t){const e=this.getParent(t);if(!e||!e.content)return null;const r=e.content.indexOf(t);return r===-1||r>=e.content.length-1?null:e.content[r+1]}getFirstChild(t){const e=this.dataStore.getNode(t);return!e||!e.content||e.content.length===0?null:e.content[0]}getLastChild(t){const e=this.dataStore.getNode(t);return!e||!e.content||e.content.length===0?null:e.content[e.content.length-1]}getFirstSibling(t){const e=this.getParent(t);return!e||!e.content||e.content.length===0?null:e.content[0]}getLastSibling(t){const e=this.getParent(t);return!e||!e.content||e.content.length===0?null:e.content[e.content.length-1]}getCommonAncestor(t,e){const r=this.dataStore.getNode(t),n=this.dataStore.getNode(e);if(!r||!n)return null;if(t===e)return t;const o=new Set;let s=t;for(;s;){o.add(s);const i=this.dataStore.getNode(s);s=i==null?void 0:i.parentId}for(s=e;s;){if(o.has(s))return s;const i=this.dataStore.getNode(s);s=i==null?void 0:i.parentId}return null}getDistance(t,e){const r=this.dataStore.getNode(t),n=this.dataStore.getNode(e);if(!r||!n)return-1;if(t===e)return 0;const o=this.getCommonAncestor(t,e);if(!o)return-1;let s=0,i=t;for(;i&&i!==o;){s++;const c=this.dataStore.getNode(i);i=c==null?void 0:c.parentId}let a=0;for(i=e;i&&i!==o;){a++;const c=this.dataStore.getNode(i);i=c==null?void 0:c.parentId}return s+a}getNodePath(t){const e=[];let r=t;for(;r;){const n=this.dataStore.getNode(r);if(!n)return[];e.unshift(r),r=n.parentId}return e}getNodeDepth(t){return this.getNodePath(t).length-1}isDescendant(t,e){return this.getNodePath(t).includes(e)}getAllDescendants(t){const e=[],r=this.getChildren(t);for(const n of r)e.push(n),e.push(...this.getAllDescendants(n.sid));return e}getAllAncestors(t){const e=[];let r=t;for(;r;){const n=this.dataStore.getNode(r);if(n!=null&&n.parentId){const o=this.dataStore.getNode(n.parentId);o&&e.unshift(o)}r=n==null?void 0:n.parentId}return e}getNodeCount(){let t=0;for(const[e,r]of this.dataStore.getNodes())this.dataStore.getNode(e)&&t++;return t}getAllNodes(){const t=[];for(const[e,r]of this.dataStore.getNodes()){const n=this.dataStore.getNode(e);n&&t.push(n)}return t}getAllNodesMap(){if(!this.dataStore.getRootNodeId())return new Map(this.dataStore.getNodes());const e=new Map,r=this.createDocumentIterator();for(const n of r){const o=this.dataStore.getNode(n);o&&e.set(n,o)}return e}restoreFromSnapshot(t,e,r=1){this.dataStore.clear();for(const[n,o]of t)this.dataStore.getNodes().set(n,o);this.dataStore.setRootNodeId(e),this.dataStore.version=r}clone(){const t=this.dataStore._activeSchema,e=typeof this.dataStore.getSessionId=="function"?this.dataStore.getSessionId():0,r=new this.dataStore.constructor(this.dataStore.getRootNodeId(),t,e);for(const[n,o]of this.dataStore.getNodes()){let s;if(typeof globalThis.structuredClone=="function")s=globalThis.structuredClone(o);else{const i=o.marks?o.marks.map(a=>({stype:a.stype,attrs:a.attrs?{...a.attrs}:void 0,range:Array.isArray(a.range)?[a.range[0],a.range[1]]:void 0})):void 0;s={sid:o.sid,stype:o.stype,parentId:o.parentId,text:o.text,attributes:o.attributes?{...o.attributes}:void 0,metadata:o.metadata?{...o.metadata}:void 0,content:o.content?[...o.content]:void 0,marks:i}}r.nodes.set(n,s)}return r}compareDocumentOrder(t,e){if(t===e)return 0;const r=this.getNodePath(t),n=this.getNodePath(e);if(!r.length)throw new Error(`Node not found: ${t}`);if(!n.length)throw new Error(`Node not found: ${e}`);let o=0;const s=Math.min(r.length,n.length);for(let h=0;h<s&&r[h]===n[h];h++)o=h;if(o===0&&r[0]!==n[0])throw new Error("Nodes are not in the same document tree");const i=o+1,a=o+1;if(i>=r.length)return-1;if(a>=n.length)return 1;const c=r[o],l=this.dataStore.getNode(c);if(!l||!l.content)throw new Error(`Parent node not found or has no content: ${c}`);const u=l.content.indexOf(r[i]),f=l.content.indexOf(n[a]);if(u===-1||f===-1)throw new Error("Child node not found in parent content");return u-f}getNextNode(t){const e=this.dataStore.getNode(t);if(!e)throw new Error(`Node not found: ${t}`);if(e.content&&e.content.length>0)return e.content[0];const r=this.getParent(t);if(r&&r.content){const n=r.content.indexOf(t);if(n!==-1&&n<r.content.length-1)return r.content[n+1]}if(r){const n=this._getNextSiblingOnly(r.sid);if(n)return n}return null}_getNextSiblingOnly(t){const e=this.getParent(t);if(e&&e.content){const r=e.content.indexOf(t);if(r!==-1&&r<e.content.length-1)return e.content[r+1]}return e?this._getNextSiblingOnly(e.sid):null}getPreviousNode(t){if(!this.dataStore.getNode(t))throw new Error(`Node not found: ${t}`);const r=this.getParent(t);if(r&&r.content){const n=r.content.indexOf(t);if(n>0){const o=r.content[n-1];return this._getLastDescendant(o)}}return r?r.sid:null}_getLastDescendant(t){const e=this.dataStore.getNode(t);if(!e||!e.content||e.content.length===0)return t;const r=e.content[e.content.length-1];return this._getLastDescendant(r)}getEditableNodes(t){var i;const{filter:e,includeText:r=!0,includeInline:n=!0,includeEditableBlocks:o=!0}=t||{},s=[];for(const[a,c]of this.dataStore.getNodes()){if(!this._isEditableNode(a))continue;const l=this.dataStore._activeSchema;if(l){const u=(i=l.getNodeType)==null?void 0:i.call(l,c.stype);if(u){const f=u.group,h=c.text!==void 0&&typeof c.text=="string",g=f==="block"&&u.editable===!0&&h,m=f==="inline";if(g){if(!o)continue}else if(h&&!r||m&&!h&&!n)continue}}e&&!e(c)||s.push(c)}return s}filterEditableNodes(t){return t.filter(e=>this._isEditableNode(e))}filterSelectableNodes(t){return t.filter(e=>this._isSelectableNode(e))}_isSelectableNode(t){var n;const e=this.dataStore.getNode(t);if(!e)return!1;const r=this.dataStore._activeSchema;if(r)try{const o=(n=r.getNodeType)==null?void 0:n.call(r,e.stype);if(o)return!(o.group==="document"||o.selectable===!1)}catch{}return e.stype!=="document"}getSelectableNodes(t){var i;const{filter:e,includeBlocks:r=!0,includeInline:n=!0,includeEditable:o=!0}=t||{},s=[];for(const[a,c]of this.dataStore.getNodes()){if(!this._isSelectableNode(a))continue;const l=this.dataStore._activeSchema;let u=!0;if(l){const f=(i=l.getNodeType)==null?void 0:i.call(l,c.stype);if(f){const h=f.group,g=h==="block",m=h==="inline",p=this._isEditableNode(a);(r||n||o)&&(u=!1,r&&g&&(u=!0),n&&m&&(u=!0),o&&p&&(u=!0))}}u&&(e&&!e(c)||s.push(c))}return s}_isDraggableNode(t){var n;const e=this.dataStore.getNode(t);if(!e)return!1;const r=this.dataStore._activeSchema;if(r)try{const o=(n=r.getNodeType)==null?void 0:n.call(r,e.stype);if(o)return!(o.group==="document"||o.draggable===!1)}catch{}return e.stype!=="document"}getDraggableNodes(t){var i;const{filter:e,includeBlocks:r=!0,includeInline:n=!0,includeEditable:o=!0}=t||{},s=[];for(const[a,c]of this.dataStore.getNodes()){if(!this._isDraggableNode(a))continue;const l=this.dataStore._activeSchema;let u=!0;if(l){const f=(i=l.getNodeType)==null?void 0:i.call(l,c.stype);if(f){const h=f.group,g=h==="block",m=h==="inline",p=this._isEditableNode(a);(r||n||o)&&(u=!1,r&&g&&(u=!0),n&&m&&(u=!0),o&&p&&(u=!0))}}u&&(e&&!e(c)||s.push(c))}return s}filterDraggableNodes(t){return t.filter(e=>this._isDraggableNode(e))}_isDroppableNode(t){var n;const e=this.dataStore.getNode(t);if(!e)return!1;const r=this.dataStore._activeSchema;if(r)try{const o=(n=r.getNodeType)==null?void 0:n.call(r,e.stype);if(o)return o.droppable===!1?!1:!!o.content}catch{}return e.content!==void 0}canDropNode(t,e){var s,i;if(!this._isDroppableNode(t)||!this._isDraggableNode(e))return!1;const r=this.dataStore._activeSchema;if(!r)return!0;const n=this.dataStore.getNode(t),o=this.dataStore.getNode(e);if(!n||!o)return!1;try{const a=(s=r.getNodeType)==null?void 0:s.call(r,n.stype),c=(i=r.getNodeType)==null?void 0:i.call(r,o.stype);if(!a||!c)return!1;const l=a.content;if(!l)return!1;const u=c.group,f=o.stype,h=l.toLowerCase();return!!(u&&h.includes(u)||h.includes(f))}catch{return!1}}getDroppableNodes(t){var i;const{filter:e,includeBlocks:r=!0,includeInline:n=!1,includeDocument:o=!0}=t||{},s=[];for(const[a,c]of this.dataStore.getNodes()){if(!this._isDroppableNode(a))continue;const l=this.dataStore._activeSchema;let u=!0;if(l){const f=(i=l.getNodeType)==null?void 0:i.call(l,c.stype);if(f){const h=f.group,g=h==="block",m=h==="inline",p=h==="document";(r||n||o)&&(u=!1,r&&g&&(u=!0),n&&m&&(u=!0),o&&p&&(u=!0))}}u&&(e&&!e(c)||s.push(c))}return s}filterDroppableNodes(t){return t.filter(e=>this._isDroppableNode(e))}_isIndentableNode(t){var n;const e=this.dataStore.getNode(t);if(!e)return!1;const r=this.dataStore._activeSchema;if(!r)return!1;try{const o=(n=r.getNodeType)==null?void 0:n.call(r,e.stype);return!o||o.group==="document"?!1:o.indentable===!0}catch{return!1}}getIndentMetadata(t){var o;const e=this.dataStore.getNode(t);if(!e)return null;const r=this.dataStore._activeSchema;if(!r)return null;const n=(o=r.getNodeType)==null?void 0:o.call(r,e.stype);return n?{indentable:n.indentable===!0,indentGroup:n.indentGroup,indentParentTypes:n.indentParentTypes,maxIndentLevel:n.maxIndentLevel}:null}isEditableNode(t){return this._isEditableNode(t)}isSelectableNode(t){return this._isSelectableNode(t)}isDraggableNode(t){return this._isDraggableNode(t)}isDroppableNode(t){return this._isDroppableNode(t)}isIndentableNode(t){return this._isIndentableNode(t)}indentNode(t){var l;if(!this.dataStore.getNode(t))return!1;const r=this.dataStore._activeSchema;if(!r)return!1;const n=this.getIndentMetadata(t);if(!n||!n.indentable||typeof n.maxIndentLevel=="number"&&this._getIndentDepth(t,n.indentGroup)>=n.maxIndentLevel)return!1;const o=this.getPreviousSibling(t);if(!o)return!1;const s=this.dataStore.getNode(o);if(!s||!((l=r.getNodeType)==null?void 0:l.call(r,s.stype))||n.indentParentTypes&&n.indentParentTypes.length>0&&!n.indentParentTypes.includes(s.stype))return!1;const c=(Array.isArray(s.content)?s.content:[]).length;return this.dataStore.moveNode(t,o,c),!0}outdentNode(t){if(!this.dataStore.getNode(t)||!this.dataStore._activeSchema)return!1;const n=this.getIndentMetadata(t);if(!n||!n.indentable)return!1;const o=this.getParent(t);if(!o)return!1;const s=o.parentId?this.dataStore.getNode(o.parentId):void 0;if(!s)return!1;const i=Array.isArray(s.content)?s.content:[],a=i.indexOf(o.sid),c=a>=0?a+1:i.length;return this.dataStore.moveNode(t,s.sid,c),!0}_getIndentDepth(t,e){var s;let r=0,n=this.getParent(t);const o=this.dataStore._activeSchema;for(;n&&o;){const i=(s=o.getNodeType)==null?void 0:s.call(o,n.stype);if(!i)break;(i.indentable||e&&i.indentGroup===e)&&(r+=1),n=n.parentId?this.dataStore.getNode(n.parentId):void 0}return r}_isEditableNode(t){var n;const e=this.dataStore.getNode(t);if(!e)return!1;const r=this.dataStore._activeSchema;if(r)try{const o=(n=r.getNodeType)==null?void 0:n.call(r,e.stype);if(o){const s=o.group;if(s==="block"&&o.editable===!0)return e.text!==void 0&&typeof e.text=="string";if(s==="block"||s==="document")return!1;if(s==="inline")return!0}}catch{}return e.stype&&e.stype.startsWith("inline-")?!0:e.content&&e.text===void 0?!1:(e.text!==void 0&&typeof e.text=="string",!0)}getPreviousEditableNode(t){let e=t;const r=new Set;for(;e;){if(r.has(e))return console.warn("[UtilityOperations] getPreviousEditableNode: Circular reference detected",{nodeId:t,currentId:e}),null;r.add(e);const n=this.getPreviousNode(e);if(!n)return null;if(this._isEditableNode(n))return n;e=n}return null}getNextEditableNode(t){let e=t;const r=new Set;for(;e;){if(r.has(e))return console.warn("[UtilityOperations] getNextEditableNode: Circular reference detected",{nodeId:t,currentId:e}),null;r.add(e);const n=this.getNextNode(e);if(!n)return null;if(this._isEditableNode(n))return n;e=n}return null}createDocumentIterator(t={}){return new Rt(this.dataStore,t)}traverse(...t){let e,r={};if(t.length===0)throw new Error("At least one visitor is required");if(Array.isArray(t[0]))e=t[0],r=t[1]||{};else{const n=t[t.length-1];n&&typeof n=="object"&&!("visit"in n)&&(n.context!==void 0||n.filter!==void 0||n.maxDepth!==void 0||n.reverse!==void 0||n.startNodeId!==void 0||n.customFilter!==void 0||n.shouldStop!==void 0||n.range!==void 0)?(e=t.slice(0,-1),r=n):e=t}return e.length===1?this._traverseSingleVisitor(e[0],r):e.map(n=>({visitor:n,result:this._traverseSingleVisitor(n,r)}))}_traverseSingleVisitor(t,e={}){const r=new Rt(this.dataStore,e);let n=0,o=0,s=!1;for(const i of r){const a=this.dataStore.getNode(i);if(!a)continue;if(t.enter&&t.enter(i,a,e.context),t.shouldVisitChildren&&!t.shouldVisitChildren(i,a)){o++,t.exit&&t.exit(i,a,e.context);continue}if(t.visit(i,a,e.context)===!1){o++,t.exit&&t.exit(i,a,e.context);continue}if(n++,e.shouldStop&&e.shouldStop(i,a)){s=!0,t.exit&&t.exit(i,a,e.context);break}t.exit&&t.exit(i,a,e.context)}return{visitedCount:n,skippedCount:o,stopped:s}}_getDefaultDropBehavior(t,e,r){var o,s;if(typeof t.text=="string"&&typeof e.text=="string")return"merge";const n=this.dataStore._activeSchema;if(n){const i=(o=n.getNodeType)==null?void 0:o.call(n,t.stype),a=(s=n.getNodeType)==null?void 0:s.call(n,e.stype);if(i&&a){if(i.group==="block"&&a.group==="inline"&&typeof e.text=="string")return"merge";if(i.group==="block"&&a.group==="block"&&t.stype===e.stype)return"move"}}return"move"}getDropBehavior(t,e,r){var l,u,f;const n=this.dataStore.getNode(t),o=this.dataStore.getNode(e);if(!n||!o)return"move";const s=this.dataStore._activeSchema,i=o.stype,a=r||{};if((l=a.modifiers)!=null&&l.ctrlKey||(u=a.modifiers)!=null&&u.metaKey)return"copy";if(a.sourceOrigin==="external")return"insert";const c=Sr.get(n.stype,i,n,o,a);if(c!==null)return c;if(s){const h=(f=s.getNodeType)==null?void 0:f.call(s,n.stype);if(h!=null&&h.dropBehaviorRules){const g=h.dropBehaviorRules;if(g[i])return g[i];if(g["*"])return g["*"]}}return this._getDefaultDropBehavior(n,o,a)}}class Rt{constructor(t,e={}){y(this,"currentId");y(this,"visited",new Set);y(this,"options");y(this,"rangeStartId",null);y(this,"rangeEndId",null);this.dataStore=t,this.options={startNodeId:e.startNodeId||this.dataStore.getRootNodeId(),reverse:e.reverse||!1,maxDepth:e.maxDepth||1/0,filter:e.filter||{},customFilter:e.customFilter||(()=>!0),shouldStop:e.shouldStop||(()=>!1),range:e.range},this.options.range&&(this.rangeStartId=this.options.range.startNodeId,this.rangeEndId=this.options.range.endNodeId),this.options.reverse?this.currentId=this.findLastNode():this.currentId=this.options.startNodeId}[Symbol.iterator](){return this}next(){for(;this.currentId;){const t=this.dataStore.getNode(this.currentId);if(!t){this.currentId=this.getNextNode();continue}if(!this.isInRange(this.currentId)){this.currentId=this.getNextNode();continue}if(this.visited.has(this.currentId)){this.currentId=this.getNextNode();continue}if(this.dataStore.getNodePath(this.currentId).length>this.options.maxDepth){this.currentId=this.getNextNode();continue}if(!this.matchesTypeFilter(t)){this.currentId=this.getNextNode();continue}if(!this.options.customFilter(this.currentId,t)){this.currentId=this.getNextNode();continue}if(this.options.shouldStop(this.currentId,t)){this.currentId=null;break}this.visited.add(this.currentId);const r=this.currentId;return this.currentId=this.getNextNode(),{value:r,done:!1}}return{value:void 0,done:!0}}getNextNode(){return this.currentId?this.options.reverse?this.dataStore.utility.getPreviousNode(this.currentId):this.dataStore.utility.getNextNode(this.currentId):null}matchesTypeFilter(t){const{filter:e}=this.options,r=t.stype,o=(e||{}).stype;return!(o&&r!==o||e.stypes&&!e.stypes.includes(r)||e.excludeStypes&&e.excludeStypes.includes(r))}isInRange(t){if(!this.options.range||!this.rangeStartId||!this.rangeEndId)return!0;const{includeStart:e=!0,includeEnd:r=!0}=this.options.range;if(t===this.rangeStartId)return e;if(t===this.rangeEndId)return r;const n=this.dataStore.utility.compareDocumentOrder(t,this.rangeStartId),o=this.dataStore.utility.compareDocumentOrder(t,this.rangeEndId);return!(n<0||o>0)}reset(){this.currentId=this.options.startNodeId,this.visited.clear()}startFrom(t){this.currentId=t,this.visited.clear()}updateOptions(t){this.options={...this.options,...t}}toArray(){const t=[];for(const e of this)t.push(e);return t}find(t){for(const e of this){const r=this.dataStore.getNode(e);if(t(e,r))return e}return null}findAll(t){const e=[];for(const r of this){const n=this.dataStore.getNode(r);t(r,n)&&e.push(r)}return e}takeWhile(t){const e=[];for(const r of this){const n=this.dataStore.getNode(r);if(!t(r,n))break;e.push(r)}return e}getStats(){const t={total:0,byType:{},byDepth:{}};for(const e of this){const r=this.dataStore.getNode(e),n=this.dataStore.getNodePath(e).length;t.total++;const o=r.stype||"unknown";t.byType[o]=(t.byType[o]||0)+1,t.byDepth[n]=(t.byDepth[n]||0)+1}return t}findLastNode(){let t=this.options.startNodeId,e=t;for(;t;)e=t,t=this.dataStore.utility.getNextNode(t);return e}getNodesInRange(){if(!this.options.range)return this.toArray();const t=[];for(const e of this)t.push(e);return t}getRangeNodeCount(){if(!this.options.range)return this.getStats().total;let t=0;for(const e of this)t++;return t}getRangeInfo(){return this.options.range?{start:this.options.range.startNodeId,end:this.options.range.endNodeId,includeStart:this.options.range.includeStart??!0,includeEnd:this.options.range.includeEnd??!0}:null}}class Ir{constructor(t){this.dataStore=t}processNodeInModelSelection(t,e,r){const n=this.dataStore.getNode(t);if(!n||typeof n.text!="string")return null;const o=n.text;let s=0,i=o.length;if(t===e.startNodeId&&(s=e.startOffset),t===e.endNodeId&&(i=e.endOffset),s>=i||s<0||i>o.length)return null;const a=o.substring(s,i);if(r==="delete"){const c=o.substring(0,s)+o.substring(i);this.dataStore.updateNode(t,{text:c})}return a}deleteText(t){if(t.startNodeId===t.endNodeId){const r=t.startNodeId,n=this.dataStore.getNode(r);if(!n||typeof n.text!="string")return"";const o=n.text,s=t.startOffset,i=t.endOffset;if(typeof s!="number"||typeof i!="number"||s>i||s<0||i>o.length)return"";const a=o.substring(s,i),c=o.substring(0,s)+o.substring(i);let l=n.marks?[...n.marks]:[];if(l&&l.length>0){const u=-(i-s),f=[];for(const h of l){const[g,m]=h.range||[0,o.length];if(m<=s){f.push({...h});continue}if(g>=i){f.push({...h,range:[g+u,m+u]});continue}const p=g<s&&m>s&&m<=i,N=g>=s&&g<i&&m>i,x=g>=s&&m<=i,S=g<s&&m>i;if(!x){if(p){f.push({...h,range:[g,s]});continue}if(N){const b=s;f.push({...h,range:[b,m+u]});continue}if(S){f.push({...h,range:[g,s]}),f.push({...h,range:[s,m+u]});continue}}}l=f}return this.dataStore.updateNode(r,{text:c,marks:l}),a}let e="";if(t.startNodeId!==t.endNodeId){const r=this.dataStore.getNode(t.startNodeId);if(r&&typeof r.text=="string"){const n=r.text,o=t.startOffset;if(o<n.length){const s=n.substring(o);e+=s;const i=n.substring(0,o);let a=r.marks?[...r.marks]:[];if(a&&a.length>0){const c=[];for(const l of a){const[u,f]=l.range||[0,n.length];if(f<=o){c.push({...l});continue}u>=o||c.push({...l,range:[u,o]})}a=c}this.dataStore.updateNode(t.startNodeId,{text:i,marks:a})}}}if(t.startNodeId!==t.endNodeId){const r=this.dataStore.getNode(t.startNodeId),n=this.dataStore.getNode(t.endNodeId);if(r&&n&&r.parentId===n.parentId&&r.parentId){const o=this.dataStore.getNode(r.parentId);if(o&&o.content&&Array.isArray(o.content)){const s=o.content.indexOf(t.startNodeId),i=o.content.indexOf(t.endNodeId);if(s!==-1&&i!==-1&&s<i)for(let a=s+1;a<i;a++){const c=o.content[a],l=this.dataStore.getNode(c);l&&typeof l.text=="string"&&(e+=l.text,this.dataStore.updateNode(c,{text:"",marks:[]}))}}}else{const o=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!1,includeEnd:!1});for(const s of o){const i=this.dataStore.getNode(s);i&&typeof i.text=="string"&&(e+=i.text,this.dataStore.updateNode(s,{text:"",marks:[]}))}}}if(t.startNodeId!==t.endNodeId){const r=this.dataStore.getNode(t.endNodeId);if(r&&typeof r.text=="string"){const n=r.text,o=t.endOffset;if(o>0){const s=n.substring(0,o);e+=s;const i=n.substring(o);let a=r.marks?[...r.marks]:[];if(a&&a.length>0){const c=-o,l=[];for(const u of a){const[f,h]=u.range||[0,n.length];if(f>=o){l.push({...u,range:[f+c,h+c]});continue}h<=o||l.push({...u,range:[0,h+c]})}a=l}this.dataStore.updateNode(t.endNodeId,{text:i,marks:a})}}}return e}extractText(t){const e=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let r="";for(const n of e){const o=this.dataStore.getNode(n);if(o&&o.text){const s=this.processNodeInModelSelection(n,t,"extract");s&&(r+=s)}}return r}insertText(t,e){if(t.startNodeId!==t.endNodeId||t.startOffset!==t.endOffset)throw new Error("insertText는 같은 위치 범위에서만 사용할 수 있습니다");const r=t.startNodeId,n=this.dataStore.getNode(r);if(!n||typeof n.text!="string")return e;const o=n.text,s=t.startOffset;if(typeof s!="number"||s<0||s>o.length)return e;const i=o.substring(0,s)+e+o.substring(s);let a=n.marks?[...n.marks]:[];if(a&&a.length>0){const c=e.length,l=[];for(const u of a){const[f,h]=u.range||[0,o.length];if(h<=s){l.push({...u});continue}if(f>=s){l.push({...u,range:[f+c,h+c]});continue}l.push({...u,range:[f,h+c]})}a=l}return this.dataStore.updateNode(r,{text:i,marks:a}),e}deleteRange(t){this.deleteText(t)}replaceText(t,e){if(t.startNodeId===t.endNodeId){const o=t.startNodeId,s=this.dataStore.getNode(o);if(!s||typeof s.text!="string")return console.warn("[RangeOperations.replaceText] Invalid node or not a text node",{nodeId:o,hasNode:!!s,textType:typeof(s==null?void 0:s.text)}),"";const i=s.text,a=t.startOffset,c=t.endOffset;if(typeof a!="number"||typeof c!="number")return console.warn("[RangeOperations.replaceText] Invalid offsets",{start:a,end:c}),"";if(a>c||a<0||c>i.length)return console.warn("[RangeOperations.replaceText] Invalid range",{start:a,end:c,textLength:i.length}),"";const l=i.substring(a,c),u=e.length-(c-a),f=i.substring(0,a)+e+i.substring(c);let h=s.marks?[...s.marks]:[];if(h&&h.length>0){const g=[];for(const m of h){if(!m.range||m.range===null||m.range===void 0){g.push({...m});continue}const[p,N]=m.range;if(N<=a){g.push({...m});continue}if(p>=c){g.push({...m,range:[p+u,N+u]});continue}const x=p<a&&N>a&&N<=c,S=p>=a&&p<c&&N>c,b=p>=a&&N<=c,v=p<a&&N>c;if(!b){if(x){g.push({...m,range:[p,a]});continue}if(S){const I=a+e.length,_=N+u;_>I&&g.push({...m,range:[I,_]});continue}if(v){if(a===c){g.push({...m,range:[p,N+u]});continue}if(u>=-1){g.push({...m,range:[p,N+u]});continue}const I={...m,range:[p,a]},_=a+e.length,C=N+u,D={...m,range:[_,C]};g.push(I),C>_&&g.push(D);continue}}}h=g}return this.dataStore.updateNode(o,{text:f},!1),h.length>0?this.dataStore.marks.setMarks(o,h,{normalize:!0}):this.dataStore.marks.setMarks(o,[],{normalize:!0}),l}const r=this.deleteText(t),n={type:"range",startNodeId:t.startNodeId,startOffset:t.startOffset,endNodeId:t.startNodeId,endOffset:t.startOffset};return this.insertText(n,e),r}copyText(t){return this.extractText(t)}moveText(t,e){const r=this.extractText(t);this.deleteText(t);let n={...e};if(t.startNodeId===t.endNodeId&&e.startNodeId===e.endNodeId&&e.startNodeId===t.startNodeId){const o=Math.max(0,t.endOffset-t.startOffset),s=e.startOffset;let i=s;s>t.endOffset&&(i=s-o);const a=this.dataStore.getNode(e.startNodeId),c=typeof(a==null?void 0:a.text)=="string"?a.text.length:0;i>c&&(i=c),i<0&&(i=0),n={type:"range",startNodeId:e.startNodeId,startOffset:i,endNodeId:e.endNodeId,endOffset:i}}return this.insertText(n,r),r}duplicateText(t){const e=this.extractText(t),r={type:"range",startNodeId:t.endNodeId,startOffset:t.endOffset,endNodeId:t.endNodeId,endOffset:t.endOffset};return this.insertText(r,e),e}applyMark(t,e){const{startNodeId:r,startOffset:n,endNodeId:o,endOffset:s}=t;if(r===o){const l=this.dataStore.getNode(r);if(!l||typeof l.text!="string")return e;const u=l.text,f=Math.max(0,Math.min(n,u.length)),h=Math.max(0,Math.min(s,u.length));if(f>=h)return e;const g={...e,range:[f,h]},m=[...l.marks||[],g];return this.dataStore.marks.setMarks(r,m,{normalize:!0}),e}const a=this.dataStore.getNode(r),c=this.dataStore.getNode(o);if(a&&typeof a.text=="string"){const l=Math.max(0,Math.min(n,a.text.length)),u=a.text.length;if(l<u){const f={...e,range:[l,u]},h=[...a.marks||[],f];this.dataStore.marks.setMarks(r,h,{normalize:!0})}}if(c&&typeof c.text=="string"){const u=Math.max(0,Math.min(s,c.text.length));if(0<u){const f={...e,range:[0,u]},h=[...c.marks||[],f];this.dataStore.marks.setMarks(o,h,{normalize:!0})}}return e}toggleMark(t,e,r){const{startNodeId:n,startOffset:o,endNodeId:s,endOffset:i}=t;if(n===s){this.dataStore.marks.toggleMark(n,e,[o,i],r);return}const a=this.dataStore.getNode(n);a&&typeof a.text=="string"&&this.dataStore.marks.toggleMark(n,e,[o,a.text.length],r);const c=this.dataStore.getNode(s);c&&typeof c.text=="string"&&this.dataStore.marks.toggleMark(s,e,[0,Math.min(i,c.text.length)],r)}removeMark(t,e){const r=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let n=0;for(const o of r){const s=this.dataStore.getNode(o);if(!s||!s.text||!s.marks)continue;const i=s.text;let a=0,c=i.length;if(o===t.startNodeId&&(a=t.startOffset),o===t.endNodeId&&(c=t.endOffset),a>=c)continue;const l=s.marks.filter(f=>{if(f.stype!==e)return!0;const[h,g]=f.range||[0,i.length];return g<=a||h>=c});n+=s.marks.length-l.length,this.dataStore.updateNode(o,{marks:l},!1);const u=this.dataStore.getNode(o);u&&(u.marks=l)}return n}clearFormatting(t){const e=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let r=0;for(const n of e){const o=this.dataStore.getNode(n);if(!o||!o.text||!o.marks)continue;const s=o.text;let i=0,a=s.length;if(n===t.startNodeId&&(i=t.startOffset),n===t.endNodeId&&(a=t.endOffset),i>=a)continue;const c=o.marks.filter(u=>{const[f,h]=u.range||[0,s.length];return h<=i||f>=a});r+=o.marks.length-c.length,this.dataStore.updateNode(n,{marks:c},!1);const l=this.dataStore.getNode(n);l&&(l.marks=c)}return r}constrainMarksToRange(t){const e=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let r=0;for(const n of e){const o=this.dataStore.getNode(n);if(!o||!o.text||!o.marks||o.marks.length===0)continue;const s=o.text;let i=0,a=s.length;if(n===t.startNodeId&&(i=t.startOffset),n===t.endNodeId&&(a=t.endOffset),i>=a)continue;const c=[];for(const u of o.marks){const[f,h]=u.range||[0,s.length],g=Math.max(f,i),m=Math.min(h,a);if(m<=g){r+=1;continue}(g!==f||m!==h)&&(r+=1),c.push({...u,range:[g,m]})}this.dataStore.updateNode(n,{marks:c},!1);const l=this.dataStore.getNode(n);l&&(l.marks=c)}return r}findText(t,e){const r=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let n=0;for(const o of r){const s=this.dataStore.getNode(o);if(s&&s.text){const i=s.text;let a=0,c=i.length;if(o===t.startNodeId&&(a=t.startOffset),o===t.endNodeId&&(c=t.endOffset),a<c){const l=i.substring(a,c).indexOf(e);if(l!==-1)return n+a+l}n+=i.length}}return-1}getTextLength(t){const e=this.dataStore.createRangeIterator(t.startNodeId,t.endNodeId,{includeStart:!0,includeEnd:!0});let r=0;for(const n of e){const o=this.dataStore.getNode(n);if(o&&o.text){const s=o.text;let i=0,a=s.length;n===t.startNodeId&&(i=t.startOffset),n===t.endNodeId&&(a=t.endOffset),i<a&&(r+=a-i)}}return r}trimText(t){const e=this.extractText(t),r=e.trim();if(e===r)return 0;const n=e.length-e.trimStart().length,o=e.length-e.trimEnd().length,s=n+o;return this.replaceText(t,r),s}normalizeWhitespace(t){const e=this.extractText(t),r=e.replace(/\s+/g," ").replace(/^\s+|\s+$/g,"");return e===r||this.replaceText(t,r),r}wrap(t,e,r){const n=this.extractText(t),o=`${e}${n}${r}`;return this.replaceText(t,o),o}unwrap(t,e,r){const n=t.startNodeId===t.endNodeId,o=n?this.dataStore.getNode(t.startNodeId):void 0,s=typeof(o==null?void 0:o.text)=="string"?o.text:"",i=this.extractText(t),a=i.startsWith(e),c=i.endsWith(r);let l=t.startOffset,u=t.endOffset,f=!1,h=!1;if(n&&s){!a&&(l>=e.length&&s.substring(l-e.length,l)===e||l===0&&s.startsWith(e))&&(f=!0);const x=u+(a||f?e.length:0);!c&&x+r.length<=s.length&&s.substring(x,x+r.length)===r&&(h=!0)}let g=l,m=u;if(n&&s){f&&(g=Math.max(0,l-e.length));const x=u+(a||f?e.length:0);m=h?Math.min(s.length,x+r.length):x}const p=n?{type:"range",startNodeId:t.startNodeId,startOffset:g,endNodeId:t.endNodeId,endOffset:m}:t;let N=n&&s?s.substring(p.startOffset,p.endOffset):i;return N.startsWith(e)&&(N=N.substring(e.length)),N.endsWith(r)&&(N=N.substring(0,N.length-r.length)),this.replaceText(p,N),N}replace(t,e,r){const n=this.extractText(t);if(n.length===0)return 0;let o=0,s;if(e instanceof RegExp){const a=e.flags.includes("g")?e:new RegExp(e.source,e.flags+"g");s=n.replace(a,()=>(o+=1,r))}else{const i=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");s=n.replace(i,()=>(o+=1,r))}return o>0&&this.replaceText(t,s),o}findAll(t,e){const r=this.extractText(t),n=[];if(r.length===0)return n;let o;if(e instanceof RegExp){const i=e.flags.includes("g")?e.flags:e.flags+"g";o=new RegExp(e.source,i)}else{const i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");o=new RegExp(i,"g")}let s;for(;(s=o.exec(r))!==null;){const i=s.index,a=i+s[0].length;n.push({start:i,end:a}),s[0].length===0&&o.lastIndex++}return n}indent(t,e=" "){const r=this.extractText(t);if(r.length===0)return"";const n=r.replace(/(^|\n)/g,(o,s)=>s+e);return this.replaceText(t,n),n}outdent(t,e=" "){const r=this.extractText(t);if(r.length===0)return"";const n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(^|\\n)${n}`,"g"),s=r.replace(o,(i,a)=>a);return this.replaceText(t,s),s}expandToWord(t){var o,s;const e=this.extractText(t);if(e.length===0)return t;const r=((o=e.match(/^\s*/))==null?void 0:o[0].length)??0,n=((s=e.match(/\s*$/))==null?void 0:s[0].length)??0;return{...t,startNodeId:t.startNodeId,startOffset:t.startOffset+r,endNodeId:t.endNodeId,endOffset:t.endOffset-n}}expandToLine(t){const r=this.extractText(t).indexOf(`
|
|
2
|
+
`);return{type:"range",startNodeId:t.startNodeId,startOffset:t.startOffset+0,endNodeId:t.endNodeId,endOffset:t.endOffset-0}}normalizeRange(t){const{startNodeId:e,startOffset:r,endNodeId:n,endOffset:o}=t;return e===n&&r>o?{...t,startNodeId:e,startOffset:o,endNodeId:n,endOffset:r}:t}}class wr{constructor(t){this.dataStore=t}serializeRange(t){const e=[];if(t.startNodeId===t.endNodeId){const s=this.dataStore.getNode(t.startNodeId);if(!s)return[];if(typeof s.text=="string"){const i=t.startOffset??0,a=t.endOffset??s.text.length;if(i>=a)return[];const c=s.text.substring(i,a);return e.push({stype:s.stype,text:c,marks:s.marks}),e}return e.push({...s}),e}const r=this.dataStore.getAllNodes(),n=r.findIndex(s=>s.sid===t.startNodeId),o=r.findIndex(s=>s.sid===t.endNodeId);if(n===-1||o===-1||n>o)return[];for(let s=n;s<=o;s++){const i=r[s];!i||typeof i.text!="string"||e.push({...i})}return e}deserializeNodes(t,e,r){const n=[],o=this.dataStore.getNode(e);if(!o)return n;Array.isArray(o.content)||(o.content=[],this.dataStore.updateNode(e,{content:o.content}));const s=o.content,i=typeof r=="number"?Math.min(Math.max(r,0),s.length):s.length,a=[];for(const c of t){const l={...c};l.parentId=e;const u=this.dataStore.core.createNodeWithChildren(l);a.push(u.sid)}return s.splice(i,0,...a),this.dataStore.updateNode(e,{content:s}),n.push(...a),n}}class vr{constructor(t){y(this,"overlayNodes",new Map);y(this,"deletedNodeIds",new Set);y(this,"touchedParents",new Set);y(this,"opBuffer",[]);y(this,"active",!1)}begin(){this.active||(this.active=!0,this.opBuffer=[],this.overlayNodes.clear(),this.deletedNodeIds.clear(),this.touchedParents.clear())}end(){return this.opBuffer.slice()}getCollectedOperations(){return this.opBuffer.slice()}commit(t){if(!this.active)return;const e=this.opBuffer.slice();t(e),this.reset()}rollback(){this.active&&this.reset()}isActive(){return this.active}recordOperation(t){this.active&&this.opBuffer.push(t)}hasDeleted(t){return this.deletedNodeIds.has(t)}hasOverlayNode(t){return this.overlayNodes.has(t)}getOverlayNode(t){return this.overlayNodes.get(t)}reset(){this.active=!1,this.opBuffer=[],this.overlayNodes.clear(),this.deletedNodeIds.clear(),this.touchedParents.clear()}upsertNode(t,e){if(!this.active)return;const r=t.sid;this.overlayNodes.set(r,t)}updateNodeFields(t,e,r){if(!this.active)return;const o={...this.overlayNodes.get(t)||{},...e};this.overlayNodes.set(t,o)}markDeleted(t,e){this.active&&(this.deletedNodeIds.add(t),this.overlayNodes.delete(t))}markParentTouched(t){this.active&&this.touchedParents.add(t)}}class _r{constructor(){y(this,"listeners",new Map)}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e)}off(t,e){const r=this.listeners.get(t);r&&r.delete(e)}emit(t,...e){const r=this.listeners.get(t);r&&r.forEach(n=>{try{n(...e)}catch(o){console.error(`Error in event listener for ${t}:`,o)}})}}const Y=class Y{constructor(t,e,r){y(this,"nodes",new Map);y(this,"rootNodeId");y(this,"version",1);y(this,"_registeredSchemas",new Map);y(this,"_activeSchema");y(this,"_eventEmitter",new _r);y(this,"_sessionId",0);y(this,"_overlay");y(this,"_overlayAliases");y(this,"_tempAliasSet");y(this,"_currentLock",null);y(this,"_transactionQueue",[]);y(this,"_lockTimeout",5e3);y(this,"_lockStats",{totalAcquisitions:0,totalReleases:0,totalTimeouts:0,averageWaitTime:0});y(this,"core");y(this,"query");y(this,"content");y(this,"splitMerge");y(this,"marks");y(this,"decorators");y(this,"utility");y(this,"range");y(this,"serialization");this.rootNodeId=t,this._sessionId=r??0,e&&this.setActiveSchema(e),this.core=new fr(this),this.query=new hr(this),this.content=new gr(this),this.splitMerge=new pr(this),this.marks=new mr(this),this.decorators=new yr(this),this.utility=new xr(this),this.range=new Ir(this),this.serialization=new wr(this)}generateId(){return Y._globalCounter++,`${this._sessionId}:${Y._globalCounter}`}serializeRange(t){return this.serialization.serializeRange(t)}deserializeNodes(t,e,r){return this.serialization.deserializeNodes(t,e,r)}emitOperation(t){this._overlay&&this._overlay.isActive()&&this._overlay.recordOperation(t),this._eventEmitter.emit("operation",t)}onOperation(t){this._eventEmitter.on("operation",t)}offOperation(t){this._eventEmitter.off("operation",t)}begin(){this._overlay||(this._overlay=new vr({getVersion:()=>this.getVersion(),sessionId:this.getSessionId()})),this._overlay.begin(),this._overlayAliases=new Map}getNodes(){return this.nodes}setNodes(t){this.nodes=t}getCollectedOperations(){return this._overlay&&this._overlay.isActive()?this._overlay.getCollectedOperations():[]}end(){return this._overlay&&this._overlay.isActive()?this._overlay.getCollectedOperations():[]}commit(){var o;if(!this._overlay||!this._overlay.isActive())return;const t=this._overlay.getCollectedOperations(),e={create:1,update:2,move:3,delete:4},r=t.slice().sort((s,i)=>e[s.type]-e[i.type]||0);for(const s of r)switch(s.type){case"create":{const a=((o=this._overlay)==null?void 0:o.getOverlayNode(s.nodeId))||s.data;if(a){const c=this.nodes.get(s.nodeId),l=a.marks||(c==null?void 0:c.marks);this._setNodeInternal({...a,marks:l,sid:s.nodeId})}break}case"update":{const i=this.nodes.get(s.nodeId);if(i&&s.data){const a={...i,...s.data};s.data.attributes&&i.attributes&&(a.attributes={...i.attributes,...s.data.attributes}),this._setNodeInternal(a)}break}case"move":{const{nodeId:i,parentId:a,position:c}=s,l=this.nodes.get(i);if(!l)break;if(l.parentId){const u=this.nodes.get(l.parentId);if(u&&u.content){const f=u.content.indexOf(i);f!==-1&&u.content.splice(f,1),this._setNodeInternal(u)}}if(a){const u=this.nodes.get(a);if(u){const f=typeof c=="number"?c:u.content?u.content.length:0;u.content||(u.content=[]),u.content.splice(f,0,i),this._setNodeInternal(u)}l.parentId=a,this._setNodeInternal(l)}break}case"delete":{const{nodeId:i,parentId:a}=s;if(a){const c=this.nodes.get(a);if(c&&c.content){const l=c.content.indexOf(i);l!==-1&&c.content.splice(l,1),this._setNodeInternal(c)}}this.nodes.delete(i);break}}const n=this._overlay.overlayRootNodeId;n&&(this.rootNodeId=n),this._overlay.rollback(),this._overlay=void 0,this._overlayAliases&&this._overlayAliases.clear()}rollback(){this._overlay&&(this._overlay.rollback(),this._overlay=void 0,this._overlayAliases&&this._overlayAliases.clear())}getSessionId(){return this._sessionId}setSessionId(t){this._sessionId=t}findNodes(t){return this.query.findNodes(t)}findNodesByType(t){return this.query.findNodesByType(t)}findNodesByAttribute(t,e){return this.query.findNodesByAttribute(t,e)}findNodesByText(t){return this.query.findNodesByText(t)}findChildrenByParentId(t){return this.query.findChildrenByParentId(t)}findRootNodes(){return this.query.findRootNodes()}getNodeChildren(t){return this.query.getNodeChildren(t)}getNodeChildrenDeep(t){return this.query.getNodeChildrenDeep(t)}getNodeWithChildren(t){return this.query.getNodeWithChildren(t)}getAllNodesWithChildren(){return this.query.getAllNodesWithChildren()}setNode(t,e=!0){const r=this._captureAliasFromNode(t);this.core.setNode(r,e)}setNodeInternal(t){this._setNodeInternal(t)}_setNodeInternal(t){this.nodes.set(t.sid,t)}createNodeWithChildren(t,e){const r=e||this._activeSchema;if(this._tempAliasSet=new Set,Y._globalCounter=this.nodes.size,this._assignIdsRecursively(t),r){const n=(r==null?void 0:r.nodes)||void 0,o=i=>{var l;const a=typeof(n==null?void 0:n.get)=="function"?n.get(i.stype):n?n[i.stype]:(l=r==null?void 0:r.getNodeType)==null?void 0:l.call(r,i.stype);if(!a){try{const u=(r==null?void 0:r.name)||"unknown-schema",f=typeof(n==null?void 0:n.keys)=="function"?Array.from(n.keys()):Object.keys(n||{});console.error("[DataStore.createNodeWithChildren] Unknown node type during schema validation",{nodeId:i.sid,nodeType:i.stype,schemaName:u,availableTypes:f})}catch{}throw new Error(`Schema validation failed for node ${i.sid}: unknown type '${i.stype}'`)}const c=a.attrs||{};for(const[u,f]of Object.entries(c))if(f!=null&&f.required&&!(i.attributes&&i.attributes[u]!==void 0))throw new Error(`Schema validation failed for node ${i.sid}: missing required attribute '${u}'`);if(i.content&&Array.isArray(i.content))for(const u of i.content)typeof u=="object"&&u!==null&&o(u)};o(t);const s=this.validateNode(t,r);if(!s.valid)throw new Error(`Schema validation failed for node ${t.sid}: ${s.errors.join(", ")}`)}return this._createAllNodesRecursively(t),this.rootNodeId||(this.rootNodeId=t.sid),this._tempAliasSet=void 0,t}_createAllNodesRecursively(t){if(t.content)for(const r of t.content)typeof r=="object"&&this._createAllNodesRecursively(r);if(t.content&&Array.isArray(t.content)&&(t.content=t.content.map(r=>typeof r=="object"&&r!==null?r.sid:r)),t.attributes&&t.attributes.$alias){const r=t.attributes.$alias;if(this._tempAliasSet){if(this._tempAliasSet.has(r))throw new Error(`Duplicate alias detected in creation: '${r}'`);this._tempAliasSet.add(r)}try{this._overlayAliasMap&&this.setAlias(r,t.sid)}catch{}const n={...t.attributes};delete n.$alias,t.attributes=n}if(this.nodes.has(t.sid))throw new Error(`Node ID already exists: ${t.sid}`);this._setNodeInternal(t);const e={type:"create",nodeId:t.sid,data:{stype:t.stype,attributes:t.attributes,text:t.text,content:t.content,parentId:t.parentId},timestamp:Date.now(),parentId:t.parentId};this.emitOperation(e)}_assignIdsRecursively(t){t.sid||(t.sid=this.generateId()),t.content&&Array.isArray(t.content)&&t.content.forEach(e=>{if(typeof e=="object"&&e!==null){const r=e;r.parentId=t.sid,this._assignIdsRecursively(r)}else if(typeof e=="string"){const r=this.getNode(e);r&&(r.parentId=t.sid)}})}_convertChildrenToDataStore(t){t.content&&Array.isArray(t.content)&&(t.content=t.content.map(e=>{if(typeof e=="object"&&e!==null){const r=e;return r.sid||(r.sid=this.generateId()),r.parentId=t.sid,this._convertChildrenToDataStore(r),this._setNodeInternal(r),r.sid}return e}))}setRootNodeId(t){this.rootNodeId=t}setRoot(t){if(this._overlay&&this._overlay.isActive()){this._overlay.overlayRootNodeId=t;return}this.rootNodeId=t}getNode(t){const e=this.resolveAlias(t);return this.core.getNode(e)}deleteNode(t){const e=this.resolveAlias(t);return this.core.deleteNode(e)}transformNode(t,e,r){const n=this.resolveAlias(t);return this.core.transformNode(n,e,r)}moveBlockUp(t){const e=this.resolveAlias(t);return this.content.moveBlockUp(e)}moveBlockDown(t){const e=this.resolveAlias(t);return this.content.moveBlockDown(e)}getRootNode(){if(!this.rootNodeId){const t=Array.from(this.nodes.values())[0];return t&&(this.rootNodeId=t.sid),t}return this.getNode(this.rootNodeId)}getChildren(t){return this.utility.getChildren(t)}getParent(t){return this.utility.getParent(t)}getSiblings(t){return this.utility.getSiblings(t)}getSiblingIndex(t){return this.utility.getSiblingIndex(t)}getPreviousSibling(t){return this.utility.getPreviousSibling(t)}getNextSibling(t){return this.utility.getNextSibling(t)}getFirstChild(t){return this.utility.getFirstChild(t)}getLastChild(t){return this.utility.getLastChild(t)}getFirstSibling(t){return this.utility.getFirstSibling(t)}getLastSibling(t){return this.utility.getLastSibling(t)}getCommonAncestor(t,e){return this.utility.getCommonAncestor(t,e)}getDistance(t,e){return this.utility.getDistance(t,e)}getNodePath(t){return this.utility.getNodePath(t)}getNodeDepth(t){return this.utility.getNodeDepth(t)}isDescendant(t,e){return this.utility.isDescendant(t,e)}getAllDescendants(t){return this.utility.getAllDescendants(t)}getAllAncestors(t){return this.utility.getAllAncestors(t)}addChild(t,e,r){return this.content.addChild(t,e,r)}removeChild(t,e){return this.content.removeChild(t,e)}moveNode(t,e,r){this.content.moveNode(t,e,r)}getNodeCount(){return this.utility.getNodeCount()}clone(){return this.utility.clone()}saveNode(t,e=!0){return this.setNode(t,e),null}updateNode(t,e,r=!0){const n=this.resolveAlias(t),o=this.getNode(n);if(!o)return{valid:!1,errors:[`Node not found: ${n}`]};if(e.stype&&e.stype!==o.stype)return{valid:!1,errors:[`Cannot change node stype from '${o.stype}' to '${e.stype}'`]};if(e.attributes&&typeof e.attributes.$alias<"u"){const c=e.attributes.$alias;if(typeof c=="string"&&c)this.setAlias(c,n);else{const f=this._findAliasById(n);f&&this.deleteAlias(f)}const{$alias:l,...u}=e.attributes;e={...e,attributes:u}}const s=Object.keys(e);if(s.length>0){let c=!0;for(const l of s){const u=o[l],f=e[l];if(!(JSON.stringify(u)===JSON.stringify(f))){c=!1;break}}if(c)return{valid:!0,errors:[]}}const i={...o,...e};e.attributes&&o.attributes&&(i.attributes={...o.attributes,...e.attributes});const a=e.content!==void 0;if(r&&!a)try{return this.setNode(i,!0),{valid:!0,errors:[]}}catch(c){return{valid:!1,errors:[c instanceof Error?c.message:"Validation failed"]}}else return this.setNode(i,!1),{valid:!0,errors:[]}}setAlias(t,e){if(this._overlayAliases||(this._overlayAliases=new Map),this._overlayAliases.has(t)&&this._overlayAliases.get(t)!==e)throw new Error(`Alias already in use: ${t}`);this._overlayAliases.set(t,e)}resolveAlias(t){return this._overlayAliases&&this._overlayAliases.get(t)||t}deleteAlias(t){this._overlayAliases&&this._overlayAliases.delete(t)}clearAliases(){this._overlayAliases&&this._overlayAliases.clear()}getAliases(){return this._overlayAliases||new Map}_findAliasById(t){if(this._overlayAliases){for(const[e,r]of this._overlayAliases.entries())if(r===t)return e}}_captureAliasFromNode(t){const e={...t},r=e.attributes&&typeof e.attributes.$alias=="string"?e.attributes.$alias:void 0;if(r&&e.sid){this.setAlias(r,e.sid);const{$alias:n,...o}=e.attributes||{};e.attributes=o}return e}saveNodeRecursively(t,e){const r={...t,parentId:e||"root"};if(this.setNode(r),t.content)for(const n of t.content){const o=typeof n=="string"?this.getNode(n):n;o&&this.saveNodeRecursively(o,t.sid)}}saveDocumentInternal(t,e=!0){var o;let r=[];if(t.content)for(const s of t.content)this.saveNodeRecursively(s,t.sid||"root"),r.push(s.sid);else t.contentIds&&(r=t.contentIds);const n={sid:t.sid||"root",stype:"document",content:r,attributes:{...t.attributes,schema:t.schema||((o=t.attributes)==null?void 0:o.schema)||{}},metadata:t.metadata||{},version:t.version||1,createdAt:new Date,updatedAt:new Date};return this.setNode(n),this.setRootNodeId(n.sid),{valid:!0,errors:[]}}getDocument(t){var o;const e=this.getRootNode();if(!e||t!=="root"&&e.sid!==t)return;const r=[];if(e.content)for(const s of e.content){const i=this.getNode(s);if(i){const{parentId:a,...c}=i;r.push(c)}}return{sid:e.sid,stype:"document",content:r,metadata:{title:"Untitled Document",author:"Unknown",version:"1.0.0",createdAt:new Date,updatedAt:new Date,...e.metadata},schema:((o=e.attributes)==null?void 0:o.schema)||{},version:e.version||1}}updateDocument(t,e,r=!0){const n=this.getDocument(t);if(!n)return{valid:!1,errors:[`Document not found: ${t}`]};const o={...n,...e};return this.saveDocumentInternal(o,r)}deleteDocument(t){const e=this.getRootNode();if(!e||e.sid!==t)return!1;throw new Error("Cannot delete root document")}registerSchema(t){t&&t.name&&this._registeredSchemas.set(t.name,t)}setActiveSchema(t){this._activeSchema=t,this.registerSchema(t)}getActiveSchema(){return this._activeSchema}validateNode(t,e){const r=e||this._activeSchema;if(!r)return{valid:!0,errors:[]};try{return ur(t,r)}catch(n){return{valid:!1,errors:[`Validation error: ${n}`]}}}getAllDocuments(){var r;const t=this.getRootNode();if(!t)return[];const e=[];if(t.content)for(const n of t.content){const o=this.getNode(n);if(o){const{parentId:s,...i}=o;e.push(i)}}return[{sid:t.sid,stype:"document",content:e,metadata:{title:"Untitled Document",author:"Unknown",version:"1.0.0",createdAt:new Date,updatedAt:new Date,...t.metadata},schema:((r=t.attributes)==null?void 0:r.schema)||{},version:t.version||1}]}saveDocument(t,e=!0){const r=this.saveDocumentInternal(t,e);return r.valid?null:r}getAllNodes(){return this.utility.getAllNodes()}getAllNodesMap(){return this.utility.getAllNodesMap()}getRootNodeId(){return this.rootNodeId}getVersion(){return this.version}clear(){this.getNodes().clear(),this.setRootNodeId(void 0),this.version=1}restoreFromSnapshot(t,e,r=1){this.utility.restoreFromSnapshot(t,e,r)}copyNode(t,e){return this.content.copyNode(t,e)}cloneNodeWithChildren(t,e){return this.content.cloneNodeWithChildren(t,e)}reorderChildren(t,e){this.content.reorderChildren(t,e)}searchText(t){return this.query.searchText(t)}findByAttribute(t,e){return this.query.findNodesByAttribute(t,e)}addChildren(t,e,r){return this.content.addChildren(t,e,r)}removeChildren(t,e){return this.content.removeChildren(t,e)}moveChildren(t,e,r,n){this.content.moveChildren(t,e,r,n)}hasNode(t){return this.utility.hasNode(t)}getChildCount(t){return this.utility.getChildCount(t)}isLeafNode(t){return this.utility.isLeafNode(t)}isRootNode(t){return this.utility.isRootNode(t)}splitTextNode(t,e){return this.splitMerge.splitTextNode(t,e)}mergeTextNodes(t,e){return this.splitMerge.mergeTextNodes(t,e)}splitBlockNode(t,e){return this.splitMerge.splitBlockNode(t,e)}mergeBlockNodes(t,e){return this.splitMerge.mergeBlockNodes(t,e)}splitTextRange(t,e,r){return this.splitMerge.splitTextRange(t,e,r)}autoMergeTextNodes(t){return this.splitMerge.autoMergeTextNodes(t)}deleteText(t){return this.range.deleteText(t)}extractText(t){return this.range.extractText(t)}copyText(t){return this.range.copyText(t)}moveText(t,e){return this.range.moveText(t,e)}duplicateText(t){return this.range.duplicateText(t)}applyMark(t,e){return this.range.applyMark(t,e)}toggleMark(t,e,r){return this.range.toggleMark(t,e,r)}constrainMarksToRange(t){return this.range.constrainMarksToRange(t)}removeMark(t,e){return this.range.removeMark(t,e)}clearFormatting(t){return this.range.clearFormatting(t)}indent(t,e=" "){return this.range.indent(t,e)}outdent(t,e=" "){return this.range.outdent(t,e)}indentNode(t){return this.utility.indentNode(t)}outdentNode(t){return this.utility.outdentNode(t)}findText(t,e){return this.range.findText(t,e)}getTextLength(t){return this.range.getTextLength(t)}trimText(t){return this.range.trimText(t)}normalizeWhitespace(t){return this.range.normalizeWhitespace(t)}wrap(t,e,r){return this.range.wrap(t,e,r)}unwrap(t,e,r){return this.range.unwrap(t,e,r)}replace(t,e,r){return this.range.replace(t,e,r)}findAll(t,e){return this.range.findAll(t,e)}expandToWord(t){return this.range.expandToWord(t)}expandToLine(t){return this.range.expandToLine(t)}normalizeRange(t){return this.range.normalizeRange(t)}insertText(t,e){return this.range.insertText(t,e)}replaceText(t,e){return this.range.replaceText(t,e)}normalizeMarks(t){this.marks.normalizeMarks(t)}normalizeAllMarks(){return this.marks.normalizeAllMarks()}getMarkStatistics(t){return this.marks.getMarkStatistics(t)}removeEmptyMarks(t){return this.marks.removeEmptyMarks(t)}compareDocumentOrder(t,e){return this.utility.compareDocumentOrder(t,e)}getNextNode(t){return this.utility.getNextNode(t)}getPreviousNode(t){return this.utility.getPreviousNode(t)}isEditableNode(t){return this.utility.isEditableNode(t)}isIndentableNode(t){return this.utility.isIndentableNode(t)}getIndentMetadata(t){return this.utility.getIndentMetadata(t)}getPreviousEditableNode(t){return this.utility.getPreviousEditableNode(t)}getNextEditableNode(t){return this.utility.getNextEditableNode(t)}getDropBehavior(t,e,r){return this.utility.getDropBehavior(t,e,r)}getEditableNodes(t){return this.utility.getEditableNodes(t)}filterEditableNodes(t){return this.utility.filterEditableNodes(t)}isSelectableNode(t){return this.utility.isSelectableNode(t)}getSelectableNodes(t){return this.utility.getSelectableNodes(t)}filterSelectableNodes(t){return this.utility.filterSelectableNodes(t)}isDraggableNode(t){return this.utility.isDraggableNode(t)}getDraggableNodes(t){return this.utility.getDraggableNodes(t)}filterDraggableNodes(t){return this.utility.filterDraggableNodes(t)}isDroppableNode(t){return this.utility.isDroppableNode(t)}canDropNode(t,e){return this.utility.canDropNode(t,e)}getDroppableNodes(t){return this.utility.getDroppableNodes(t)}filterDroppableNodes(t){return this.utility.filterDroppableNodes(t)}createDocumentIterator(t){return this.utility.createDocumentIterator(t)}createRangeIterator(t,e,r){return this.utility.createDocumentIterator({...r,range:{startNodeId:t,endNodeId:e,includeStart:(r==null?void 0:r.includeStart)??!0,includeEnd:(r==null?void 0:r.includeEnd)??!0}})}getNodesInRange(t,e,r){return this.createRangeIterator(t,e,r).getNodesInRange()}getRangeNodeCount(t,e,r){return this.createRangeIterator(t,e,r).getRangeNodeCount()}_generateLockId(){return`lock-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async acquireLock(t="unknown"){const e=Date.now(),r=this._generateLockId();return new Promise((n,o)=>{if(!this._currentLock){this._currentLock={lockId:r,ownerId:t,acquiredAt:Date.now(),timeoutId:setTimeout(()=>{this._forceReleaseLock()},this._lockTimeout*10)},this._lockStats.totalAcquisitions++,n(r);return}const s={lockId:r,ownerId:t,resolve:()=>{const i=Date.now()-e;this._lockStats.averageWaitTime=(this._lockStats.averageWaitTime*(this._lockStats.totalAcquisitions-1)+i)/this._lockStats.totalAcquisitions,this._lockStats.totalAcquisitions++,n(r)},timeoutId:setTimeout(()=>{const i=this._transactionQueue.findIndex(a=>a.lockId===r);i!==-1&&(this._transactionQueue.splice(i,1),this._lockStats.totalTimeouts++,o(new Error(`Lock acquisition timeout after ${this._lockTimeout}ms for owner ${t}`)))},this._lockTimeout)};this._transactionQueue.push(s)})}releaseLock(t){if(!this._currentLock)return;if(t&&this._currentLock.lockId!==t)throw new Error(`Lock ID mismatch: expected ${this._currentLock.lockId}, got ${t}`);clearTimeout(this._currentLock.timeoutId),this._currentLock=null,this._lockStats.totalReleases++;const e=this._transactionQueue.shift();e&&(clearTimeout(e.timeoutId),this._currentLock={lockId:e.lockId,ownerId:e.ownerId,acquiredAt:Date.now(),timeoutId:setTimeout(()=>{this._forceReleaseLock()},this._lockTimeout*10)},e.resolve())}_forceReleaseLock(){this._currentLock&&(console.warn(`Force releasing lock ${this._currentLock.lockId} owned by ${this._currentLock.ownerId}`),clearTimeout(this._currentLock.timeoutId),this._currentLock=null,this._lockStats.totalReleases++)}isLocked(){return this._currentLock!==null}getCurrentLock(){return this._currentLock?{lockId:this._currentLock.lockId,ownerId:this._currentLock.ownerId,acquiredAt:this._currentLock.acquiredAt}:null}getQueueLength(){return this._transactionQueue.length}getQueueInfo(){const t=Date.now();return this._transactionQueue.map(e=>({lockId:e.lockId,ownerId:e.ownerId,waitTime:t-e.startTime||0}))}getLockStats(){return{...this._lockStats,queueLength:this._transactionQueue.length,isLocked:this._currentLock!==null,currentLock:this.getCurrentLock(),queue:this.getQueueInfo()}}setLockTimeout(t){this._lockTimeout=t}resetLockStats(){this._lockStats={totalAcquisitions:0,totalReleases:0,totalTimeouts:0,averageWaitTime:0}}traverse(...t){return this.utility.traverse(...t)}};y(Y,"_globalCounter",0);let It=Y;class br{constructor(t,e){y(this,"_dataStore");y(this,"_nodeIdCounter",0);y(this,"_sessionId");this._dataStore=t,this._sessionId=e}loadDocument(t){const e=this._createNodeFromTree(t);return this._dataStore.setNode(e),this._dataStore.setRootNodeId(e.sid),this._loadChildren(e.sid,t.content||[]),e.sid}loadNodes(t,e){for(const r of t){const n=this._createNodeFromTree(r);e&&(n.parentId=e),this._dataStore.setNode(n),r.content&&r.content.length>0&&this._loadChildren(n.sid,r.content)}}loadFromJSON(t){const e=JSON.parse(t);return this.loadDocument(e)}async loadFromAPI(t){const r=await(await fetch(t)).json();return this.loadDocument(r)}_generateFigmaStyleId(){return this._nodeIdCounter++,`${this._sessionId}:${this._nodeIdCounter}`}_createNodeFromTree(t){const e=t.sid||this._generateFigmaStyleId(),r=t.stype;return{sid:e,stype:r,attributes:t.attributes||{},content:void 0,text:t.text,marks:t.marks,metadata:{...t.metadata,loadedAt:new Date().toISOString()},version:1,createdAt:new Date,updatedAt:new Date}}_loadChildren(t,e){const r=this._dataStore.getNode(t);if(r){r.content||(r.content=[]);for(const n of e){const o=this._createNodeFromTree(n);o.parentId=t,this._dataStore.setNode(o),r.content.push(o.sid),n.content&&n.content.length>0&&this._loadChildren(o.sid,n.content)}this._dataStore.setNode(r)}}clear(){this._dataStore.clear(),this._nodeIdCounter=0}getSessionId(){return this._sessionId}getNodeCounter(){return this._nodeIdCounter}getSessionInfo(){return{sessionId:this._sessionId,nodeCounter:this._nodeIdCounter}}generateId(){return this._generateFigmaStyleId()}generateIdForType(t){return`${t}-${this.generateId()}`}}class pt{constructor(t){y(this,"_dataStore");this._dataStore=t}exportToTree(t){var n;const e=t||((n=this._dataStore.getRootNode())==null?void 0:n.sid);if(!e)throw new Error("No root node found");const r=this._dataStore.getNode(e);if(!r)throw new Error("Root node not found");return this._exportNodeToTree(r)}exportToJSON(t){return JSON.stringify(this.exportToTree(t),null,2)}toProxy(t){var n;const e=t||((n=this._dataStore.getRootNode())==null?void 0:n.sid);if(!e)return null;const r=this._dataStore.getNode(e);return r?this._createProxy(r):null}_createProxy(t){const e=this._dataStore,r=n=>this._createProxy(n);return new Proxy(t,{get(n,o){return o==="content"&&n.content?n.content.map(s=>{if(typeof s=="string"){const i=e.getNode(s);return i?r(i):s}return s&&typeof s=="object"&&s.stype?r(s):s}):n[o]}})}_exportNodeToTree(t){const e=t.content?t.content.map(r=>this._dataStore.getNode(r)).filter(r=>r!==void 0).map(r=>this._exportNodeToTree(r)):void 0;return{sid:t.sid,stype:t.stype,content:e,text:t.text,attributes:t.attributes,marks:t.marks,metadata:t.metadata}}}class vt{constructor(t={}){y(this,"_currentSelection",null);y(this,"_dataStore",null);t.dataStore&&(this._dataStore=t.dataStore)}get startNodeId(){var t;return((t=this._currentSelection)==null?void 0:t.startNodeId)||null}get startOffset(){var t;return((t=this._currentSelection)==null?void 0:t.startOffset)||null}get endNodeId(){var t;return((t=this._currentSelection)==null?void 0:t.endNodeId)||null}get endOffset(){var t;return((t=this._currentSelection)==null?void 0:t.endOffset)||null}getCurrentSelection(){return this._currentSelection}setSelection(t){this._currentSelection=t}clearSelection(){this._currentSelection=null}isEmpty(){return this._currentSelection===null}isInNode(t){return this._currentSelection?this._currentSelection.startNodeId===t||this._currentSelection.endNodeId===t:!1}isAtPosition(t,e){return this._currentSelection?this._currentSelection.startNodeId===t&&this._currentSelection.startOffset===e&&this._currentSelection.endNodeId===t&&this._currentSelection.endOffset===e:!1}isInRange(t,e,r){if(!this._currentSelection||this._currentSelection.startNodeId!==t||this._currentSelection.endNodeId!==t)return!1;const n=Math.min(this._currentSelection.startOffset,this._currentSelection.endOffset),o=Math.max(this._currentSelection.startOffset,this._currentSelection.endOffset);return n>=e&&o<=r}overlapsWith(t,e,r){if(!this._currentSelection||this._currentSelection.startNodeId!==t||this._currentSelection.endNodeId!==t)return!1;const n=Math.min(this._currentSelection.startOffset,this._currentSelection.endOffset);return!(Math.max(this._currentSelection.startOffset,this._currentSelection.endOffset)<=e||n>=r)}getLength(){return!this._currentSelection||this._currentSelection.startNodeId!==this._currentSelection.endNodeId?0:Math.abs(this._currentSelection.endOffset-this._currentSelection.startOffset)}isCollapsed(){return this._currentSelection?this._currentSelection.startNodeId===this._currentSelection.endNodeId&&this._currentSelection.startOffset===this._currentSelection.endOffset:!0}moveTo(t,e){this._currentSelection={type:"range",startNodeId:t,startOffset:e,endNodeId:t,endOffset:e}}selectRange(t,e,r){this._currentSelection={type:"range",startNodeId:t,startOffset:e,endNodeId:t,endOffset:r}}selectRangeMulti(t,e,r,n){this._currentSelection={type:"range",startNodeId:t,startOffset:e,endNodeId:r,endOffset:n}}extendTo(t,e){if(!this._currentSelection){this.moveTo(t,e);return}this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:this._currentSelection.startOffset,endNodeId:t,endOffset:e}}collapseToStart(){this._currentSelection&&(this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:this._currentSelection.startOffset,endNodeId:this._currentSelection.startNodeId,endOffset:this._currentSelection.startOffset})}collapseToEnd(){this._currentSelection&&(this._currentSelection={type:"range",startNodeId:this._currentSelection.endNodeId,startOffset:this._currentSelection.endOffset,endNodeId:this._currentSelection.endNodeId,endOffset:this._currentSelection.endOffset})}selectNode(t){if(!this._dataStore)throw new Error("DataStore not set");const e=this._dataStore.getNode(t);if(!e)throw new Error(`Node not found: ${t}`);const r=e.text?e.text.length:0;this._currentSelection={type:"range",startNodeId:t,startOffset:0,endNodeId:t,endOffset:r}}selectAll(){if(!this._dataStore)throw new Error("DataStore not set");if(!this._dataStore.getRootNode())return;const r=this._dataStore.getAllNodes().filter(s=>s.text!==void 0);if(r.length===0)return;const n=r[0],o=r[r.length-1];this._currentSelection={type:"range",startNodeId:n.sid,startOffset:0,endNodeId:o.sid,endOffset:o.text.length}}selectToStart(){this._currentSelection&&(this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:0,endNodeId:this._currentSelection.startNodeId,endOffset:this._currentSelection.startOffset})}selectToEnd(){if(!this._currentSelection||!this._dataStore)return;const t=this._dataStore.getNode(this._currentSelection.startNodeId);!t||!t.text||(this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:this._currentSelection.startOffset,endNodeId:this._currentSelection.startNodeId,endOffset:t.text.length})}moveToStart(t){this.moveTo(t,0)}moveToEnd(t){if(!this._dataStore)throw new Error("DataStore not set");const e=this._dataStore.getNode(t);if(!e||!e.text)throw new Error(`Text node not found: ${t}`);this.moveTo(t,e.text.length)}moveBy(t){if(!this._currentSelection)return;const e=Math.max(0,this._currentSelection.startOffset+t);this.moveTo(this._currentSelection.startNodeId,e)}extendBy(t){if(!this._currentSelection)return;const e=Math.max(0,this._currentSelection.endOffset+t);this.extendTo(this._currentSelection.endNodeId,e)}selectWord(t,e){if(!this._dataStore)throw new Error("DataStore not set");const r=this._dataStore.getNode(t);if(!r||!r.text)throw new Error(`Text node not found: ${t}`);const n=r.text,o=/\w+/g;let s,i=-1,a=-1;for(;(s=o.exec(n))!==null;)if(e>=s.index&&e<s.index+s[0].length){i=s.index,a=s.index+s[0].length;break}i!==-1&&a!==-1?this.selectRange(t,i,a):this._currentSelection={type:"range",startNodeId:t,startOffset:e,endNodeId:t,endOffset:e}}selectLine(t,e){if(!this._dataStore)throw new Error("DataStore not set");const r=this._dataStore.getNode(t);if(!r||!r.text)throw new Error(`Text node not found: ${t}`);const o=r.text.split(`
|
|
3
|
+
`);let s=0,i=0,a=0;for(let c=0;c<o.length;c++){const l=o[c].length;if(a=s+l,e>=s&&e<=a){i=s;break}s=a+1}this.selectRange(t,i,a)}adjustForTextInsert(t,e,r){if(!this._currentSelection)return;let n=this._currentSelection.startOffset,o=this._currentSelection.endOffset;this._currentSelection.startNodeId===t&&this._currentSelection.startOffset>=e&&(n=this._currentSelection.startOffset+r),this._currentSelection.endNodeId===t&&this._currentSelection.endOffset>=e&&(o=this._currentSelection.endOffset+r),this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:n,endNodeId:this._currentSelection.endNodeId,endOffset:o}}adjustForTextDelete(t,e,r){if(!this._currentSelection)return;const n=r-e;let o=this._currentSelection.startOffset,s=this._currentSelection.endOffset;this._currentSelection.startNodeId===t&&(this._currentSelection.startOffset>=r?o=this._currentSelection.startOffset-n:this._currentSelection.startOffset>e&&(o=e)),this._currentSelection.endNodeId===t&&(this._currentSelection.endOffset>=r?s=this._currentSelection.endOffset-n:this._currentSelection.endOffset>e&&(s=e)),this._currentSelection={type:"range",startNodeId:this._currentSelection.startNodeId,startOffset:o,endNodeId:this._currentSelection.endNodeId,endOffset:s}}adjustForNodeSplit(t,e){this._currentSelection&&this._currentSelection.startNodeId===t&&(this._currentSelection={type:"range",startNodeId:t,startOffset:e,endNodeId:t,endOffset:e})}isFullyInNode(t){return this._currentSelection?this._currentSelection.startNodeId===t&&this._currentSelection.endNodeId===t:!1}overlapsWithNode(t){return this._currentSelection?this._currentSelection.startNodeId===t||this._currentSelection.endNodeId===t:!1}getStartPosition(){if(!this._currentSelection)return null;const t=this._currentSelection.startOffset>this._currentSelection.endOffset||this._currentSelection.startOffset===this._currentSelection.endOffset&&this._currentSelection.startNodeId>this._currentSelection.endNodeId;return{nodeId:t?this._currentSelection.endNodeId:this._currentSelection.startNodeId,offset:t?this._currentSelection.endOffset:this._currentSelection.startOffset}}getEndPosition(){if(!this._currentSelection)return null;const t=this._currentSelection.startOffset>this._currentSelection.endOffset||this._currentSelection.startOffset===this._currentSelection.endOffset&&this._currentSelection.startNodeId>this._currentSelection.endNodeId;return{nodeId:t?this._currentSelection.startNodeId:this._currentSelection.endNodeId,offset:t?this._currentSelection.startOffset:this._currentSelection.endOffset}}isReversed(){return this._currentSelection?this._currentSelection.startOffset>this._currentSelection.endOffset||this._currentSelection.startOffset===this._currentSelection.endOffset&&this._currentSelection.startNodeId>this._currentSelection.endNodeId:!1}normalize(){this._currentSelection&&this.isReversed()&&(this._currentSelection={type:"range",startNodeId:this._currentSelection.endNodeId,startOffset:this._currentSelection.endOffset,endNodeId:this._currentSelection.startNodeId,endOffset:this._currentSelection.startOffset})}getSelectedText(){if(!this._currentSelection||!this._dataStore||this._currentSelection.startNodeId!==this._currentSelection.endNodeId)return null;const t=this._dataStore.getNode(this._currentSelection.startNodeId);if(!t||!t.text)return null;const e=Math.min(this._currentSelection.startOffset,this._currentSelection.endOffset),r=Math.max(this._currentSelection.startOffset,this._currentSelection.endOffset);return t.text.substring(e,r)}setDataStore(t){this._dataStore=t}setRange(t){this.setSelection(t)}setNode(t){if(!t){this.setSelection(null);return}const e=t.nodeId??t.startNodeId;if(!e){this.setSelection(null);return}this.setSelection({type:"node",startNodeId:e,startOffset:0,endNodeId:e,endOffset:0})}setAbsolutePos(t){this.setSelection(t)}setContentEditableElement(t){}isSelectionInContentEditable(){return!this.isEmpty()}destroy(){this.clearSelection()}clone(){const t=new vt({dataStore:this._dataStore}),e=this._currentSelection;return e&&t.setSelection({...e}),t}}class kr{constructor(t={}){y(this,"history",[]);y(this,"currentIndex",-1);y(this,"maxSize");this.maxSize=t.maxSize||100}push(t){if(!t.operations||t.operations.length===0){console.warn("[HistoryManager] Empty operations array, skipping history entry");return}const e={id:`history-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:new Date,...t};this.history=this.history.slice(0,this.currentIndex+1),this.history.push(e),this.currentIndex=this.history.length-1,this.limit(this.maxSize)}undo(){if(!this.canUndo())return null;const t=this.history[this.currentIndex];return this.currentIndex--,t}redo(){return this.canRedo()?(this.currentIndex++,this.history[this.currentIndex]):null}canUndo(){return this.currentIndex>=0}canRedo(){return this.currentIndex<this.history.length-1}getCurrentIndex(){return this.currentIndex}getHistory(){return[...this.history]}limit(t){if(this.history.length<=t)return;const e=this.history.length-t;this.history=this.history.slice(e),this.currentIndex=Math.max(0,this.currentIndex-e)}resize(t){this.maxSize=t,this.limit(t)}getMemoryUsage(){return this.history.reduce((t,e)=>t+JSON.stringify(e).length,0)}clear(){this.history=[],this.currentIndex=-1}getStats(){return{totalEntries:this.history.length,currentIndex:this.currentIndex,canUndo:this.canUndo(),canRedo:this.canRedo()}}getEntry(t){return t<0||t>=this.history.length?null:this.history[t]}findEntries(t){return this.history.filter(t)}getEntriesByTimeRange(t,e){return this.history.filter(r=>r.timestamp>=t&&r.timestamp<=e)}removeEntry(t){const e=this.history.findIndex(r=>r.id===t);return e===-1?!1:(this.history.splice(e,1),this.currentIndex>=e&&(this.currentIndex=Math.max(0,this.currentIndex-1)),!0)}compress(){if(this.history.length<2)return;const t=[];let e=this.history[0];for(let r=1;r<this.history.length;r++){const n=this.history[r];this._canCompress(e,n)?e={...e,operations:[...e.operations,...n.operations],inverseOperations:[...n.inverseOperations,...e.inverseOperations],description:e.description||n.description}:(t.push(e),e=n)}t.push(e),this.history=t,this.currentIndex=Math.min(this.currentIndex,this.history.length-1)}_canCompress(t,e){var o,s;if(t.operations.length!==1||e.operations.length!==1)return!1;const r=t.operations[0],n=e.operations[0];return r.type==="setText"&&n.type==="setText"&&((o=r.payload)==null?void 0:o.nodeId)===((s=n.payload)==null?void 0:s.nodeId)}validate(){const t=[];return(this.currentIndex<-1||this.currentIndex>=this.history.length)&&t.push(`Invalid currentIndex: ${this.currentIndex}, history length: ${this.history.length}`),this.history.forEach((e,r)=>{(!e.id||!e.timestamp||!e.operations)&&t.push(`Invalid entry at index ${r}: missing required fields`),e.operations.length!==e.inverseOperations.length&&t.push(`Entry at index ${r}: operations and inverseOperations length mismatch`)}),{isValid:t.length===0,errors:t}}}function Er(d){const t=[];let e=0;for(;e<d.length;){const r=d[e];if(/\s/.test(r)){e++;continue}if(r==="("){t.push({type:"LPAREN",value:r}),e++;continue}if(r===")"){t.push({type:"RPAREN",value:r}),e++;continue}if(r==="'"||r==='"'){const i=r;let a=e+1,c="",l=!1;for(;a<d.length;)if(l)c+=d[a],l=!1,a++;else if(d[a]==="\\")l=!0,a++;else{if(d[a]===i)break;c+=d[a],a++}t.push({type:"STRING",value:c}),e=a+1;continue}if(r==="/"){let i=e+1,a="",c="",l=!0,u=!1;for(;i<d.length;)if(u)l?a+=d[i]:c+=d[i],u=!1,i++;else if(d[i]==="\\")u=!0,i++;else if(d[i]==="/"&&l)l=!1,i++;else if(l)a+=d[i],i++;else if(/[gimsuvy]/.test(d[i]))c+=d[i],i++;else break;t.push({type:"MATCH",value:a,raw:`/${a}/${c}`}),e=i;continue}if(d.slice(e,e+6)==="not in"&&(e+6>=d.length||/\s/.test(d[e+6]))){t.push({type:"NOT_IN",value:"not in"}),e+=6;continue}if(d.slice(e,e+2)==="in"&&(e===0||/\s/.test(d[e-1]))&&(e+2>=d.length||/\s/.test(d[e+2]))){t.push({type:"IN",value:"in"}),e+=2;continue}const n=d.slice(e,e+4);if(n==="!==="||n==="==="){t.push({type:"OP",value:n==="==="?"==":"!="}),e+=4;continue}const o=d.slice(e,e+3);if(o==="!=="||o==="==="){t.push({type:"OP",value:o==="==="?"==":"!="}),e+=3;continue}const s=d.slice(e,e+2);if(s==="&&"||s==="||"||s==="=="||s==="!="||s==="<="||s===">="||s==="=~"){t.push({type:"OP",value:s}),e+=2;continue}if(r==="!"||r==="="||r==="<"||r===">"){t.push({type:"OP",value:r}),e++;continue}if(/\d/.test(r)||r==="."&&e+1<d.length&&/\d/.test(d[e+1])){let i=e,a="";for(r==="."&&(a="0.",i=e+1);i<d.length&&/[\d.]/.test(d[i]);)a+=d[i++];const c=parseFloat(a);if(!isNaN(c)){t.push({type:"NUMBER",value:String(c)}),e=i;continue}}if(/[a-zA-Z_$]/.test(r)){let i=e,a="";for(;i<d.length&&/[a-zA-Z0-9_$.]/.test(d[i]);)a+=d[i++];t.push({type:"IDENT",value:a}),e=i;continue}e++}return t}class Tr{constructor(t,e){y(this,"tokens");y(this,"pos",0);y(this,"ctx");this.tokens=t,this.ctx=e}parse(){return!!this.parseOr()}peek(){return this.tokens[this.pos]??null}consume(){return this.tokens[this.pos++]??null}parseOr(){var e;let t=!!this.parseAnd();for(;((e=this.peek())==null?void 0:e.type)==="OP"&&this.peek().value==="||";){this.consume();const r=!!this.parseAnd();t=t||r}return t}parseAnd(){var e;let t=this.parseIn();for(;((e=this.peek())==null?void 0:e.type)==="OP"&&this.peek().value==="&&";){this.consume();const r=this.parseIn();t=!!t&&!!r}return t}parseIn(){let t=this.parseComparison();const e=this.peek();if(e&&(e.type==="IN"||e.type==="NOT_IN")){this.consume();const r=this.parsePrimary(),n=this.toValue(t),o=r;if(Array.isArray(o)){const s=o.includes(n);return e.type==="IN"?s:!s}if(typeof o=="object"&&o!==null){const s=n in o;return e.type==="IN"?s:!s}return!1}return t}parseComparison(){let t=this.parseEquality();const e=this.peek();if(e&&e.type==="OP"&&[">",">=","<","<="].includes(e.value)){this.consume();const r=this.parseEquality(),n=this.toNumber(t),o=this.toNumber(r);if(isNaN(n)||isNaN(o))return!1;switch(e.value){case">":return n>o;case">=":return n>=o;case"<":return n<o;case"<=":return n<=o;default:return!1}}return t}parseEquality(){let t=this.parseMatch();const e=this.peek();if(e&&e.type==="OP"&&(e.value==="=="||e.value==="!=")){this.consume();const r=this.parseMatch(),n=this.toValue(t),o=this.toValue(r),s=n===o;return e.value==="=="?s:!s}return t}parseMatch(){let t=this.parseUnary();const e=this.peek();if(e&&e.type==="OP"&&e.value==="=~"){this.consume();const r=this.peek();if(r&&r.type==="MATCH"){this.consume();try{const n=r.value,s=(r.raw||`/${n}/`).match(/\/([gimsuvy]*)$/),i=((s==null?void 0:s[1])||"").replace(/[gy]/g,""),a=new RegExp(n,i),c=String(this.toValue(t));return a.test(c)}catch(n){return console.warn("[WhenParser] Invalid regex pattern:",r.raw,n),!1}}return!1}return t}parseUnary(){const t=this.peek();return t&&t.type==="OP"&&t.value==="!"?(this.consume(),!this.parseUnary()):this.parsePrimary()}parsePrimary(){var e;const t=this.consume();if(!t)return!1;if(t.type==="LPAREN"){const r=this.parseOr();return((e=this.peek())==null?void 0:e.type)==="RPAREN"&&this.consume(),r}return t.type==="IDENT"?t.value==="true"?!0:t.value==="false"?!1:this.ctx[t.value]:t.type==="STRING"?t.value:t.type==="NUMBER"?parseFloat(t.value):!1}toValue(t){return typeof t=="string"?t:typeof t=="boolean"?t?"true":"false":typeof t=="number"?String(t):t==null?"":String(t)}toNumber(t){if(typeof t=="number")return t;if(typeof t=="string"){const e=parseFloat(t);return isNaN(e)?NaN:e}return typeof t=="boolean"?t?1:0:NaN}}function Or(d,t){if(!d||!d.trim())return!0;const e=Er(d);return e.length===0?!0:new Tr(e,t).parse()}class Cr{constructor(){y(this,"_bindings",[]);y(this,"_nextId",1);y(this,"_contextProvider",null);y(this,"_currentSource",null)}setCurrentSource(t){this._currentSource=t}register(t){let e=this._currentSource??t.source??"user";this._currentSource==="extension"&&t.source==="user"&&(console.warn("[KeybindingRegistry] Extension cannot set source to 'user'. It will be set to 'extension'."),e="extension"),this._currentSource==="core"&&t.source&&t.source!=="core"&&(console.warn("[KeybindingRegistry] During Core keybinding registration, source can only be set to 'core'. It will be ignored."),e="core");const r=this._normalizeKeyString(t.key),n={...t,key:r,source:e,id:this._nextId++};this._bindings.push(n)}unregister(t){this._bindings=this._bindings.filter(e=>!(e.key===t.key&&e.command===t.command&&(!t.source||e.source===t.source)))}clear(t){if(!t){this._bindings=[];return}this._bindings=this._bindings.filter(e=>e.source!==t)}setContextProvider(t){this._contextProvider=t}resolve(t,e){var c;const r=e??((c=this._contextProvider)==null?void 0:c.getContext())??{},n=this._normalizeKeyString(t),o=this._expandModKey(n),s=this._bindings.filter(l=>{const u=this._expandModKey(l.key);return o.some(h=>u.includes(h))&&this._matchWhen(l.when,r)});if(!s.length)return[];const i={user:3,extension:2,core:1};return[...s].sort((l,u)=>{const f=i[l.source??"extension"],h=i[u.source??"extension"];return f!==h?h-f:u.id-l.id}).map(l=>({command:l.command,args:l.args}))}_expandModKey(t){return Ee(t)}_normalizeKeyString(t){return ke(t)}_matchWhen(t,e){if(!t||!t.trim())return!0;try{return Or(t,e)}catch(r){return console.warn("[KeybindingRegistry] Failed to evaluate when expression:",t,r),!1}}}const Ar=[{key:"Enter",command:"insertParagraph",when:"editorFocus && editorEditable"},{key:"Backspace",command:"backspace",when:"editorFocus && editorEditable"},{key:"Delete",command:"deleteForward",when:"editorFocus && editorEditable"},{key:"ArrowLeft",command:"moveCursorLeft",when:"editorFocus"},{key:"ArrowRight",command:"moveCursorRight",when:"editorFocus"},{key:"Shift+ArrowLeft",command:"extendSelectionLeft",when:"editorFocus",args:{}},{key:"Shift+ArrowRight",command:"extendSelectionRight",when:"editorFocus",args:{}},{key:"Alt+ArrowLeft",command:"moveCursorWordLeft",when:"editorFocus && isMac"},{key:"Alt+ArrowRight",command:"moveCursorWordRight",when:"editorFocus && isMac"},{key:"Ctrl+ArrowLeft",command:"moveCursorWordLeft",when:"editorFocus && !isMac"},{key:"Ctrl+ArrowRight",command:"moveCursorWordRight",when:"editorFocus && !isMac"},{key:"Alt+Shift+ArrowLeft",command:"extendSelectionWordLeft",when:"editorFocus && isMac"},{key:"Alt+Shift+ArrowRight",command:"extendSelectionWordRight",when:"editorFocus && isMac"},{key:"Ctrl+Shift+ArrowLeft",command:"extendSelectionWordLeft",when:"editorFocus && !isMac"},{key:"Ctrl+Shift+ArrowRight",command:"extendSelectionWordRight",when:"editorFocus && !isMac"},{key:"Mod+a",command:"selectAll",when:"editorFocus"},{key:"Mod+b",command:"toggleBold",when:"editorFocus && editorEditable"},{key:"Mod+i",command:"toggleItalic",when:"editorFocus && editorEditable"},{key:"Mod+u",command:"toggleUnderline",when:"editorFocus && editorEditable"},{key:"Mod+Shift+s",command:"toggleStrikeThrough",when:"editorFocus && editorEditable"},{key:"Mod+c",command:"copy",when:"editorFocus && editorEditable && !selectionEmpty"},{key:"Mod+v",command:"paste",when:"editorFocus && editorEditable"},{key:"Mod+x",command:"cut",when:"editorFocus && editorEditable && !selectionEmpty"},{key:"Tab",command:"indentText",when:"editorFocus && editorEditable && canIndentText"},{key:"Shift+Tab",command:"outdentText",when:"editorFocus && editorEditable && canIndentText"},{key:"Tab",command:"indentNode",when:"editorFocus && editorEditable && canIndent"},{key:"Shift+Tab",command:"outdentNode",when:"editorFocus && editorEditable && canIndent"},{key:"Mod+z",command:"historyUndo",when:"editorFocus && historyCanUndo"},{key:"Mod+Shift+z",command:"historyRedo",when:"editorFocus && historyCanRedo"},{key:"Mod+y",command:"historyRedo",when:"editorFocus && historyCanRedo"},{key:"Mod+Alt+1",command:"setHeading1",when:"editorFocus && editorEditable"},{key:"Mod+Alt+2",command:"setHeading2",when:"editorFocus && editorEditable"},{key:"Mod+Alt+3",command:"setHeading3",when:"editorFocus && editorEditable"},{key:"Mod+Alt+0",command:"setParagraph",when:"editorFocus && editorEditable"},{key:"Mod+Shift+8",command:"toggleBulletList",when:"editorFocus && editorEditable"},{key:"Mod+Shift+7",command:"toggleOrderedList",when:"editorFocus && editorEditable"},{key:"Mod+Shift+b",command:"toggleBlockquote",when:"editorFocus && editorEditable"},{key:"Alt+ArrowUp",command:"moveBlockUp",when:"editorFocus && editorEditable"},{key:"Alt+ArrowDown",command:"moveBlockDown",when:"editorFocus && editorEditable"},{key:"Escape",command:"escape",when:"editorFocus"}],Mr={editorFocus:!1,editorEditable:!0,isMac:!1,isLinux:!1,isWindows:!1,selectionEmpty:!0,selectionType:null,selectionDirection:null,canIndent:!1,canIndentText:!1,historyCanUndo:!1,historyCanRedo:!1};class Dr{constructor(t={}){y(this,"name","text");y(this,"priority",200);y(this,"_options");this._options={enabled:!0,...t}}onCreate(t){this._options.enabled&&t.registerCommand({name:"replaceText",execute:async(e,r)=>await this._executeReplaceText(e,r.range,r.text),canExecute:(e,r)=>(r==null?void 0:r.range)!=null&&(r==null?void 0:r.text)!=null})}onDestroy(t){}async _executeReplaceText(t,e,r){if(e.startOffset===e.endOffset){const s=this._buildInsertTextOperations(e,r);return(await $(t,s).commit()).success}const n=[...this._buildDeleteTextOperations(e),...this._buildInsertTextOperations({...e,endOffset:e.startOffset},r)];return(await $(t,n).commit()).success}_buildInsertTextOperations(t,e){return z(t.startNodeId,[er(t.startOffset,e)])}_buildDeleteTextOperations(t){return z(t.startNodeId,[Yt(t.startOffset,t.endOffset)])}}class Rr{constructor(t={}){y(this,"name","delete");y(this,"priority",100);y(this,"_options");this._options={enabled:!0,...t}}onCreate(t){this._options.enabled&&(t.registerCommand({name:"deleteNode",execute:async(e,r)=>await this._executeDeleteNode(e,r.nodeId),canExecute:(e,r)=>(r==null?void 0:r.nodeId)!=null}),t.registerCommand({name:"deleteCrossNode",execute:async(e,r)=>await this._executeDeleteCrossNode(e,r.range),canExecute:(e,r)=>(r==null?void 0:r.range)!=null&&r.range.startNodeId!==r.range.endNodeId}),t.registerCommand({name:"deleteText",execute:async(e,r)=>await this._executeDeleteText(e,r.range),canExecute:(e,r)=>(r==null?void 0:r.range)!=null&&r.range.startNodeId===r.range.endNodeId}),t.registerCommand({name:"backspace",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n?await this._executeBackspace(e,n):(console.warn("[DeleteExtension] backspace: No selection available"),!1)},canExecute:(e,r)=>((r==null?void 0:r.selection)||e.selection)!=null}),t.registerCommand({name:"deleteForward",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n?await this._executeDeleteForward(e,n):(console.warn("[DeleteExtension] deleteForward: No selection available"),!1)},canExecute:(e,r)=>((r==null?void 0:r.selection)||e.selection)!=null}))}onDestroy(t){}async _executeDeleteNode(t,e){const r=this._buildDeleteNodeOperations(e);return(await $(t,r).commit()).success}async _executeDeleteCrossNode(t,e){const r=tr({startNodeId:e.startNodeId,startOffset:e.startOffset,endNodeId:e.endNodeId,endOffset:e.endOffset});return(await $(t,[r]).commit()).success}async _executeDeleteText(t,e){const r=this._buildDeleteTextOperations(e);return(await $(t,r).commit()).success}_buildDeleteNodeOperations(t){return[Ze(t)]}_buildDeleteTextOperations(t){return z(t.startNodeId,[Yt(t.startOffset,t.endOffset)])}async _executeBackspace(t,e){if(!e.collapsed)return await this._executeDeleteText(t,e);if(e.startOffset===0)return await this._handleBackspaceAtOffsetZero(t,e);const r={type:"range",startNodeId:e.startNodeId,startOffset:e.startOffset-1,endNodeId:e.startNodeId,endOffset:e.startOffset,collapsed:!1,direction:"forward"};return await this._executeDeleteText(t,r)}async _executeDeleteForward(t,e){const r=t.dataStore;if(!r)return console.error("[DeleteExtension] dataStore not found"),!1;if(!e.collapsed)return await this._executeDeleteText(t,e);const n=r.getNode(e.startNodeId);if(typeof(n==null?void 0:n.text)!="string")return!1;const o=n.text.length;if(e.startOffset<o){const l={type:"range",startNodeId:e.startNodeId,startOffset:e.startOffset,endNodeId:e.startNodeId,endOffset:e.startOffset+1,collapsed:!1,direction:"forward"};return await this._executeDeleteText(t,l)}const s=r.getNextEditableNode(e.startNodeId);if(!s)return!1;const i=r.getNode(s);if(!i)return console.warn("[DeleteExtension] _executeDeleteForward: Next editable node not found",{nextEditableNodeId:s}),!1;const a=r.getParent(e.startNodeId),c=r.getParent(s);if((a==null?void 0:a.sid)!==(c==null?void 0:c.sid))return!a||!c?(console.warn("[DeleteExtension] _executeDeleteForward: Cannot merge blocks - missing parent",{currentParent:a==null?void 0:a.sid,nextParent:c==null?void 0:c.sid}),!1):a.stype!==c.stype?(console.warn("[DeleteExtension] _executeDeleteForward: Cannot merge different block types",{currentParentType:a.stype,nextParentType:c.stype}),!1):await this._executeMergeBlockNodes(t,a.sid,c.sid);if(typeof i.text=="string")if(i.text.length>0){const u={type:"range",startNodeId:s,startOffset:0,endNodeId:s,endOffset:1,collapsed:!1,direction:"forward"};return await this._executeDeleteText(t,u)}else return typeof n.text=="string"?await this._executeMergeTextNodes(t,e.startNodeId,s):(console.warn("[DeleteExtension] _executeDeleteForward: Cannot merge non-text nodes",{currentNodeId:e.startNodeId,nextNodeId:s}),!1);else return await this._executeDeleteNode(t,s)}async _handleBackspaceAtOffsetZero(t,e){const r=t.dataStore;if(!r)return console.error("[DeleteExtension] dataStore not found"),!1;const n=r.getPreviousEditableNode(e.startNodeId);if(!n)return!1;const o=r.getNode(n);if(!o)return console.warn("[DeleteExtension] _handleBackspaceAtOffsetZero: Previous editable node not found",{prevEditableNodeId:n}),!1;const s=r.getNode(e.startNodeId);if(!s)return console.warn("[DeleteExtension] _handleBackspaceAtOffsetZero: Current node not found",{currentNodeId:e.startNodeId}),!1;const i=r.getParent(n),a=r.getParent(e.startNodeId);if((i==null?void 0:i.sid)!==(a==null?void 0:a.sid))return!i||!a?(console.warn("[DeleteExtension] _handleBackspaceAtOffsetZero: Cannot merge blocks - missing parent",{prevParent:i==null?void 0:i.sid,currentParent:a==null?void 0:a.sid}),!1):i.stype!==a.stype?(console.warn("[DeleteExtension] _handleBackspaceAtOffsetZero: Cannot merge different block types",{prevParentType:i.stype,currentParentType:a.stype}),!1):await this._executeMergeBlockNodes(t,i.sid,a.sid);if(o.text!==void 0&&typeof o.text=="string"){const c=o.text.length;if(c>0){const l={type:"range",startNodeId:n,startOffset:c-1,endNodeId:n,endOffset:c,collapsed:!1,direction:"forward"};return await this._executeDeleteText(t,l)}else return s.text!==void 0&&typeof s.text=="string"?await this._executeMergeTextNodes(t,n,e.startNodeId):(console.warn("[DeleteExtension] _handleBackspaceAtOffsetZero: Cannot merge non-text nodes",{prevNodeId:n,currentNodeId:e.startNodeId}),!1)}else return await this._executeDeleteNode(t,n)}async _executeMergeTextNodes(t,e,r){return(await $(t,[{type:"mergeTextNodes",payload:{leftNodeId:e,rightNodeId:r}}]).commit()).success}async _executeMergeBlockNodes(t,e,r){return(await $(t,[{type:"mergeBlockNodes",payload:{leftNodeId:e,rightNodeId:r}}]).commit()).success}}class $r{constructor(t={}){y(this,"name","paragraph");y(this,"priority",100);y(this,"_options");this._options={enabled:!0,...t}}onCreate(t){this._options.enabled&&(t.registerCommand({name:"setParagraph",execute:async(e,r)=>await this._executeSetParagraph(e,r==null?void 0:r.selection),canExecute:(e,r)=>!!(r!=null&&r.selection)}),t.registerCommand({name:"insertParagraph",execute:async(e,r)=>await this._executeInsertParagraph(e,r==null?void 0:r.selection),canExecute:(e,r)=>!!(r!=null&&r.selection)}))}onDestroy(t){}async _executeSetParagraph(t,e){if(!e||e.type!=="range")return!1;const r=t.dataStore;if(!r)return console.error("[ParagraphExtension] dataStore not found"),!1;const n=this._getTargetBlockNodeId(r,e);if(!n)return console.warn("[ParagraphExtension] No target block node found"),!1;const o=r.getNode(n);if(!o)return!1;if(o.stype==="paragraph")return!0;const s=[...z(n,[Xt("paragraph")])];return(await $(t,s,{applySelectionToView:!0}).commit()).success}async _executeInsertParagraph(t,e){if(!e||e.type!=="range")return!1;const r=this._buildInsertParagraphOperations(t,e);return r.length?(await $(t,r,{applySelectionToView:!0}).commit()).success:!1}_getTargetBlockNodeId(t,e){if(e.type!=="range")return null;const r=t.getNode(e.startNodeId);if(!r)return null;const n=t.getActiveSchema();if(n){const s=n.getNodeType(r.stype);if((s==null?void 0:s.group)==="block")return r.sid}let o=r;for(;o&&o.parentId;){const s=t.getNode(o.parentId);if(!s)break;const i=n==null?void 0:n.getNodeType(s.stype);if((i==null?void 0:i.group)==="block")return s.sid;o=s}return null}_buildInsertParagraphOperations(t,e){const r=t.dataStore;if(!r)return[];if(e.type!=="range")return[];const n=[];if(!e.collapsed&&e.startNodeId===e.endNodeId){const o=r.getNode(e.startNodeId);if(!o||typeof o.text!="string")return[];const s=o.text,{startOffset:i,endOffset:a}=e;if(typeof i!="number"||typeof a!="number"||i<0||a>s.length||i>=a)return[];n.push(...z(e.startNodeId,[{type:"deleteTextRange",payload:{start:i,end:a}}]))}else if(!e.collapsed)return[];return this._isSelectionInsideListItem(r,e)?n.push(te()):n.push(rr("same")),n}_isSelectionInsideListItem(t,e){var s,i;if(e.type!=="range")return!1;let r=t.getNode(e.startNodeId);if(!r)return!1;if(r.stype==="inline-text"){const a=r.parentId;if(!a)return!1;r=t.getNode(((s=t.resolveAlias)==null?void 0:s.call(t,a))??a)}if(!r)return!1;const n=r.parentId;if(!n)return!1;const o=t.getNode(((i=t.resolveAlias)==null?void 0:i.call(t,n))??n);return(o==null?void 0:o.stype)==="listItem"}}const Lr="bold";class Br{constructor(t={}){y(this,"name","bold");y(this,"priority",100);y(this,"_options");this._options={enabled:!0,keyboardShortcut:"Mod+b",...t}}onCreate(t){this._options.enabled&&(t.registerCommand({name:"toggleBold",execute:async e=>await this._toggleBold(e),canExecute:()=>this._canToggleBold()}),this._options.keyboardShortcut&&this._registerKeyboardShortcut(t))}onDestroy(t){}async _toggleBold(t){const e=t.selection;if(!e||e.type!=="range")return!1;const r=ee(e.startNodeId,e.startOffset,e.endNodeId,e.endOffset,Lr);return(await $(t,[r]).commit()).success===!0}_canToggleBold(){return!0}_registerKeyboardShortcut(t){}}const Pr="italic";class Fr{constructor(t={}){y(this,"name","italic");y(this,"priority",100);y(this,"_options");this._options={enabled:!0,keyboardShortcut:"Mod+i",...t}}onCreate(t){this._options.enabled&&(t.registerCommand({name:"toggleItalic",execute:async e=>await this._toggleItalic(e),canExecute:()=>this._canToggleItalic()}),this._options.keyboardShortcut&&this._registerKeyboardShortcut(t))}onDestroy(t){}async _toggleItalic(t){const e=t.selection;if(!e||e.type!=="range")return!1;const r=ee(e.startNodeId,e.startOffset,e.endNodeId,e.endOffset,Pr);return(await $(t,[r]).commit()).success===!0}_canToggleItalic(){return!0}_registerKeyboardShortcut(t){}}class Ur{constructor(t={}){y(this,"name","heading");y(this,"priority",100);y(this,"_options");this._options={enabled:!0,levels:[1,2,3,4,5,6],keyboardShortcuts:{1:"Mod+Alt+1",2:"Mod+Alt+2",3:"Mod+Alt+3"},...t}}onCreate(t){var e;this._options.enabled&&((e=this._options.levels)==null||e.forEach(r=>{t.registerCommand({name:`setHeading${r}`,execute:async(n,o)=>await this._executeSetHeading(n,r,o==null?void 0:o.selection),canExecute:(n,o)=>!!(o!=null&&o.selection)&&this._canSetHeading(n,r)})}),t.registerCommand({name:"setHeading",execute:async(r,n)=>{const o=n==null?void 0:n.level;return typeof o!="number"?!1:await this._executeSetHeading(r,o,n==null?void 0:n.selection)},canExecute:(r,n)=>{const o=n==null?void 0:n.level;return typeof o=="number"&&!!(n!=null&&n.selection)&&this._canSetHeading(r,o)}}),t.registerCommand({name:"removeHeading",execute:r=>this._removeHeading(r),canExecute:r=>this._canRemoveHeading(r)}),this._options.keyboardShortcuts&&this._registerKeyboardShortcuts(t))}onDestroy(t){}async _executeSetHeading(t,e,r){var c;if(!r||r.type!=="range")return!1;const n=t.dataStore;if(!n)return console.error("[HeadingExtension] dataStore not found"),!1;const o=this._getTargetBlockNodeId(n,r);if(!o)return console.warn("[HeadingExtension] No target block node found"),!1;const s=n.getNode(o);if(!s)return!1;if(s.stype==="heading"&&((c=s.attributes)==null?void 0:c.level)===e)return!0;const i=[...z(o,[Xt("heading",{level:e})])];return(await $(t,i).commit()).success}_canSetHeading(t,e){var r;return((r=this._options.levels)==null?void 0:r.includes(e))||!1}_canRemoveHeading(t){return!0}_getTargetBlockNodeId(t,e){if(e.type!=="range")return null;const r=t.getNode(e.startNodeId);if(!r)return null;const n=t.getActiveSchema();if(n){const s=n.getNodeType(r.stype);if((s==null?void 0:s.group)==="block")return r.sid}let o=r;for(;o&&o.parentId;){const s=t.getNode(o.parentId);if(!s)break;const i=n==null?void 0:n.getNodeType(s.stype);if((i==null?void 0:i.group)==="block")return s.sid;o=s}return null}_removeHeading(t){try{const e=t.selection;return e.empty?this._removeHeadingAtPosition(t,e.anchor):this._removeHeadingInRange(t,e.from,e.to)}catch(e){return console.error("Remove heading failed:",e),!1}}_removeHeadingAtPosition(t,e){return console.log("Remove heading at position:",e),!0}_removeHeadingInRange(t,e,r){return console.log("Remove heading in range:",e,r),!0}_registerKeyboardShortcuts(t){}}class jr{constructor(){y(this,"name","selectAll");y(this,"priority",100)}onCreate(t){t.registerCommand({name:"selectAll",execute:e=>{const r=e.selectionManager;if(!r||typeof r.selectAll!="function")return console.warn("[SelectAllExtension] selectionManager or selectAll() is not available"),!1;r.selectAll();const n=r.getCurrentSelection();return e.updateSelection(n),!0},canExecute:()=>!0})}onDestroy(t){}}class Hr{constructor(t={}){y(this,"name","indent");y(this,"priority",100);y(this,"_options");this._options={enabled:!0,...t}}onCreate(t){this._options.enabled&&(t.registerCommand({name:"indentNode",execute:async(e,r)=>await this._executeIndentNode(e,r==null?void 0:r.nodeId),canExecute:(e,r)=>{const n=(r==null?void 0:r.nodeId)||this._getTargetNodeId(e);if(!n)return!1;const o=e.dataStore;return o?o.isIndentableNode(n):!1}}),t.registerCommand({name:"outdentNode",execute:async(e,r)=>await this._executeOutdentNode(e,r==null?void 0:r.nodeId),canExecute:(e,r)=>{const n=(r==null?void 0:r.nodeId)||this._getTargetNodeId(e);if(!n)return!1;const o=e.dataStore;if(!o||!o.isIndentableNode(n))return!1;const s=o.getNode(n);return!(!s||!s.parentId)}}),t.registerCommand({name:"indentText",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return!n||n.type!=="range"?(console.warn("[IndentExtension] indentText: No valid range selection"),!1):await this._executeIndentText(e,n,r==null?void 0:r.indent)},canExecute:(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n!=null&&n.type==="range"}}),t.registerCommand({name:"outdentText",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return!n||n.type!=="range"?(console.warn("[IndentExtension] outdentText: No valid range selection"),!1):await this._executeOutdentText(e,n,r==null?void 0:r.indent)},canExecute:(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n!=null&&n.type==="range"}}))}onDestroy(t){}_getTargetNodeId(t){const e=t.selection;if(!e)return null;const r=t.dataStore;if(!r)return null;if(e.type==="node")return e.nodeId;if(e.type==="multi-node"&&e.nodeIds&&e.nodeIds.length>0)return e.nodeIds[0];if(e.type==="range"){const n=r.getNode(e.startNodeId);if(!n)return null;const o=r.getActiveSchema();if(o){const i=o.getNodeType(n.stype);if((i==null?void 0:i.group)==="block"&&r.isIndentableNode(n.sid))return n.sid}let s=n;for(;s&&s.parentId;){const i=r.getNode(s.parentId);if(!i)break;const a=o==null?void 0:o.getNodeType(i.stype);if((a==null?void 0:a.group)==="block"&&r.isIndentableNode(i.sid))return i.sid;s=i}}return null}async _executeIndentNode(t,e){const r=e||this._getTargetNodeId(t);if(!r)return console.warn("[IndentExtension] indentNode: No target node found"),!1;const n=t.dataStore;if(!n)return console.error("[IndentExtension] dataStore not found"),!1;if(!n.isIndentableNode(r))return console.warn("[IndentExtension] indentNode: Node is not indentable",r),!1;const o=this._buildIndentNodeOperations(r);return(await $(t,o).commit()).success}async _executeOutdentNode(t,e){const r=e||this._getTargetNodeId(t);if(!r)return console.warn("[IndentExtension] outdentNode: No target node found"),!1;const n=t.dataStore;if(!n)return console.error("[IndentExtension] dataStore not found"),!1;if(!n.isIndentableNode(r))return console.warn("[IndentExtension] outdentNode: Node is not indentable",r),!1;const o=n.getNode(r);if(!o||!o.parentId)return console.warn("[IndentExtension] outdentNode: Node has no parent",r),!1;const s=this._buildOutdentNodeOperations(r);return(await $(t,s).commit()).success}_buildIndentNodeOperations(t){return[...z(t,[Xe()])]}_buildOutdentNodeOperations(t){return[...z(t,[Ye()])]}async _executeIndentText(t,e,r){if(e.type!=="range")return!1;const n=this._buildIndentTextOperations(e,r);return(await $(t,n).commit()).success}async _executeOutdentText(t,e,r){if(e.type!=="range")return!1;const n=this._buildOutdentTextOperations(e,r);return(await $(t,n).commit()).success}_buildIndentTextOperations(t,e){return t.startNodeId===t.endNodeId?[...z(t.startNodeId,[At(t.startOffset,t.endOffset,e)])]:[At(t.startNodeId,t.startOffset,t.endNodeId,t.endOffset,e)]}_buildOutdentTextOperations(t,e){return t.startNodeId===t.endNodeId?[...z(t.startNodeId,[Mt(t.startOffset,t.endOffset,e)])]:[Mt(t.startNodeId,t.startOffset,t.endNodeId,t.endOffset,e)]}}class Wr{constructor(t={}){y(this,"name","underline");y(this,"priority",100);y(this,"_options");this._options={enabled:!0,...t}}onCreate(t){this._options.enabled&&t.registerCommand({name:"toggleUnderline",execute:async(e,r)=>await this._executeToggleUnderline(e,r==null?void 0:r.selection),canExecute:(e,r)=>!!(r!=null&&r.selection)&&r.selection.type==="range"})}onDestroy(t){}async _executeToggleUnderline(t,e){if(!e||e.type!=="range"||e.startNodeId!==e.endNodeId)return!1;const r=Zt(e.startNodeId,e.startOffset,e.endNodeId,e.endOffset,"underline");return(await $(t,[r]).commit()).success}}class qr{constructor(t={}){y(this,"name","strikethrough");y(this,"priority",100);y(this,"_options");this._options={enabled:!0,...t}}onCreate(t){this._options.enabled&&t.registerCommand({name:"toggleStrikeThrough",execute:async(e,r)=>await this._executeToggleStrikeThrough(e,r==null?void 0:r.selection),canExecute:(e,r)=>!!(r!=null&&r.selection)&&r.selection.type==="range"})}onDestroy(t){}async _executeToggleStrikeThrough(t,e){if(!e||e.type!=="range"||e.startNodeId!==e.endNodeId)return!1;const r=Zt(e.startNodeId,e.startOffset,e.endNodeId,e.endOffset,"strikethrough");return(await $(t,[r]).commit()).success}}class zr{constructor(t={}){y(this,"name","moveBlock");y(this,"priority",100);y(this,"_options");this._options={enabled:!0,...t}}onCreate(t){this._options.enabled&&(t.registerCommand({name:"moveBlockUp",execute:async(e,r)=>await this._executeMoveBlockUp(e,r==null?void 0:r.selection),canExecute:(e,r)=>!!(r!=null&&r.selection)}),t.registerCommand({name:"moveBlockDown",execute:async(e,r)=>await this._executeMoveBlockDown(e,r==null?void 0:r.selection),canExecute:(e,r)=>!!(r!=null&&r.selection)}))}onDestroy(t){}async _executeMoveBlockUp(t,e){if(!e||e.type!=="range")return!1;const r=t.dataStore;if(!r)return console.error("[MoveBlockExtension] dataStore not found"),!1;const n=this._getTargetBlockNodeId(r,e);if(!n)return console.warn("[MoveBlockExtension] No target block node found"),!1;const o=[...z(n,[Ge()])];return(await $(t,o).commit()).success}async _executeMoveBlockDown(t,e){if(!e||e.type!=="range")return!1;const r=t.dataStore;if(!r)return console.error("[MoveBlockExtension] dataStore not found"),!1;const n=this._getTargetBlockNodeId(r,e);if(!n)return console.warn("[MoveBlockExtension] No target block node found"),!1;const o=[...z(n,[Je()])];return(await $(t,o).commit()).success}_getTargetBlockNodeId(t,e){if(e.type!=="range")return null;const r=t.getNode(e.startNodeId);if(!r)return null;const n=t.getActiveSchema();if(n){const s=n.getNodeType(r.stype);if((s==null?void 0:s.group)==="block")return r.sid}let o=r;for(;o&&o.parentId;){const s=t.getNode(o.parentId);if(!s)break;const i=n==null?void 0:n.getNodeType(s.stype);if((i==null?void 0:i.group)==="block")return s.sid;o=s}return null}}class Vr{constructor(t={}){y(this,"name","escape");y(this,"priority",100);y(this,"_options");this._options={enabled:!0,...t}}onCreate(t){this._options.enabled&&t.registerCommand({name:"escape",execute:e=>this._executeEscape(e),canExecute:()=>!0})}onDestroy(t){}_executeEscape(t){const e=t.selection;return e&&!this._isSelectionEmpty(e)?(t.clearSelection(),!0):(t.emit("editor:blur.request",{}),!0)}_isSelectionEmpty(t){return t?t.type==="range"?t.collapsed||t.startNodeId===t.endNodeId&&t.startOffset===t.endOffset:!1:!0}}class Kr{constructor(t={}){y(this,"name","list");y(this,"priority",100);y(this,"_options");this._options={enabled:!0,...t}}onCreate(t){this._options.enabled&&(t.registerCommand({name:"toggleBulletList",execute:async(e,r)=>await this._executeWrapInList(e,"bullet",r==null?void 0:r.selection),canExecute:()=>!0}),t.registerCommand({name:"toggleOrderedList",execute:async(e,r)=>await this._executeWrapInList(e,"ordered",r==null?void 0:r.selection),canExecute:()=>!0}),t.registerCommand({name:"splitListItem",execute:async(e,r)=>await this._executeSplitListItem(e,r==null?void 0:r.selection),canExecute:()=>!0}))}onDestroy(t){}async _executeWrapInList(t,e,r){const n=[nr(e)];return(await $(t,n,{applySelectionToView:!0}).commit()).success}async _executeSplitListItem(t,e){const r=[te()];return(await $(t,r,{applySelectionToView:!0}).commit()).success}}class Qr{constructor(){y(this,"name","blockquote");y(this,"priority",100)}onCreate(t){t.registerCommand({name:"toggleBlockquote",execute:async e=>{const r=[or()];return(await $(e,r,{applySelectionToView:!0}).commit()).success},canExecute:()=>!0})}onDestroy(t){}}class Gr{constructor(t={}){y(this,"name","move-selection");y(this,"priority",90);y(this,"_options");this._options={enabled:!0,...t}}onCreate(t){this._options.enabled&&(t.registerCommand({name:"moveCursorLeft",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n?await this._moveCaretHorizontal(e,n,"left"):!1},canExecute:(e,r)=>!!((r==null?void 0:r.selection)??t.selection)}),t.registerCommand({name:"moveCursorRight",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n?await this._moveCaretHorizontal(e,n,"right"):!1},canExecute:(e,r)=>!!((r==null?void 0:r.selection)??t.selection)}),t.registerCommand({name:"extendSelectionLeft",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n?await this._extendSelectionHorizontal(e,n,"left"):!1},canExecute:(e,r)=>!!((r==null?void 0:r.selection)??t.selection)}),t.registerCommand({name:"extendSelectionRight",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n?await this._extendSelectionHorizontal(e,n,"right"):!1},canExecute:(e,r)=>!!((r==null?void 0:r.selection)??t.selection)}),t.registerCommand({name:"moveCursorWordLeft",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n?await this._moveWordHorizontal(e,n,"left"):!1},canExecute:(e,r)=>!!((r==null?void 0:r.selection)??t.selection)}),t.registerCommand({name:"moveCursorWordRight",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n?await this._moveWordHorizontal(e,n,"right"):!1},canExecute:(e,r)=>!!((r==null?void 0:r.selection)??t.selection)}),t.registerCommand({name:"extendSelectionWordLeft",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n?await this._extendSelectionWordHorizontal(e,n,"left"):!1},canExecute:(e,r)=>!!((r==null?void 0:r.selection)??t.selection)}),t.registerCommand({name:"extendSelectionWordRight",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return n?await this._extendSelectionWordHorizontal(e,n,"right"):!1},canExecute:(e,r)=>!!((r==null?void 0:r.selection)??t.selection)}))}onDestroy(t){}async _moveCaretHorizontal(t,e,r){const n=t.dataStore;if(!n)return console.error("[MoveSelectionExtension] dataStore not found"),!1;if(!e||e.type!=="range"||!e.collapsed)return!1;const o=n.getNode(e.startNodeId),s=typeof(o==null?void 0:o.text)=="string",i=s?o.text.length:0;if(s){if(r==="left"&&e.startOffset>0){const u=e.startOffset-1,f={type:"range",startNodeId:e.startNodeId,startOffset:u,endNodeId:e.startNodeId,endOffset:u,collapsed:!0,direction:"backward"};return t.updateSelection(f),!0}if(r==="right"&&e.startOffset<i){const u=e.startOffset+1,f={type:"range",startNodeId:e.startNodeId,startOffset:u,endNodeId:e.startNodeId,endOffset:u,collapsed:!0,direction:"forward"};return t.updateSelection(f),!0}}const a=r==="left"?n.getPreviousEditableNode(e.startNodeId):n.getNextEditableNode(e.startNodeId);if(!a)return!1;const c=n.getNode(a);if(!c)return console.warn("[MoveSelectionExtension] neighbor node not found",{neighborId:a}),!1;if(typeof c.text=="string"){const u=r==="left"?c.text.length:0,f={type:"range",startNodeId:a,startOffset:u,endNodeId:a,endOffset:u,collapsed:!0,direction:r==="left"?"backward":"forward"};return t.updateSelection(f),!0}if(typeof n.isSelectableNode=="function"?n.isSelectableNode(a):!1){const u={type:"range",startNodeId:a,startOffset:0,endNodeId:a,endOffset:0,collapsed:!0,direction:r==="left"?"backward":"forward"};return t.updateSelection(u),!0}return!1}async _extendSelectionHorizontal(t,e,r){const n=t.dataStore;if(!n)return console.error("[MoveSelectionExtension] dataStore not found"),!1;if(!e||e.type!=="range"||!e.collapsed)return!1;const o=n.getNode(e.startNodeId),s=typeof(o==null?void 0:o.text)=="string",i=s?o.text.length:0;if(s){if(r==="right"&&e.startOffset<i){const l={type:"range",startNodeId:e.startNodeId,startOffset:e.startOffset,endNodeId:e.startNodeId,endOffset:e.startOffset+1,collapsed:!1,direction:"forward"};return t.updateSelection(l),!0}if(r==="left"&&e.startOffset>0){const l={type:"range",startNodeId:e.startNodeId,startOffset:e.startOffset-1,endNodeId:e.startNodeId,endOffset:e.startOffset,collapsed:!1,direction:"backward"};return t.updateSelection(l),!0}}const a=r==="left"?n.getPreviousEditableNode(e.startNodeId):n.getNextEditableNode(e.startNodeId);if(!a)return!1;const c=n.getNode(a);if(!c)return console.warn("[MoveSelectionExtension] neighbor node not found",{neighborId:a}),!1;if(typeof c.text=="string"){if(r==="right"&&s&&e.startOffset===i){const l={type:"range",startNodeId:e.startNodeId,startOffset:e.startOffset,endNodeId:a,endOffset:1,collapsed:!1,direction:"forward"};return t.updateSelection(l),!0}if(r==="left"&&s&&e.startOffset===0){const l=c.text.length;if(l>0){const u={type:"range",startNodeId:a,startOffset:l-1,endNodeId:e.startNodeId,endOffset:0,collapsed:!1,direction:"backward"};return t.updateSelection(u),!0}}}return!1}async _moveWordHorizontal(t,e,r){const n=t.dataStore;if(!n)return console.error("[MoveSelectionExtension] dataStore not found"),!1;if(!e||e.type!=="range"||!e.collapsed)return!1;const o=n.getNode(e.startNodeId),s=o&&typeof o.text=="string"?o.text:void 0;if(typeof s!="string")return!1;const i=s.length,a=e.startOffset;if(r==="left"){if(a===0)return!1;let c=a-1;const l=g=>/\s/.test(g);let u=l(s[c]);for(;c>0;c--){const g=l(s[c-1]);if(g!==u)break;u=g}const f=c,h={type:"range",startNodeId:e.startNodeId,startOffset:f,endNodeId:e.startNodeId,endOffset:f,collapsed:!0,direction:"backward"};return t.updateSelection(h),!0}else{if(a>=i)return!1;const c=h=>/\s/.test(h);let l=a;if(c(s[l]))for(;l<i&&c(s[l]);)l++;else{for(;l<i&&!c(s[l]);)l++;for(;l<i&&c(s[l]);)l++}const u=l>i?i:l,f={type:"range",startNodeId:e.startNodeId,startOffset:u,endNodeId:e.startNodeId,endOffset:u,collapsed:!0,direction:"forward"};return t.updateSelection(f),!0}}async _extendSelectionWordHorizontal(t,e,r){const n=t.dataStore;if(!n)return console.error("[MoveSelectionExtension] dataStore not found"),!1;if(!e||e.type!=="range"||!e.collapsed)return!1;const o=n.getNode(e.startNodeId),s=o&&typeof o.text=="string"?o.text:void 0;if(typeof s!="string")return!1;const i=s.length,a=e.startOffset;if(r==="left"){if(a===0)return!1;const c=g=>/\s/.test(g);let l=a-1,u=c(s[l]);for(;l>0;l--){const g=c(s[l-1]);if(g!==u)break;u=g}const f=l;if(f===a)return!1;const h={type:"range",startNodeId:e.startNodeId,startOffset:f,endNodeId:e.startNodeId,endOffset:a,collapsed:!1,direction:"backward"};return t.updateSelection(h),!0}else{if(a>=i)return!1;const c=h=>/\s/.test(h);let l=a;if(c(s[l]))for(;l<i&&c(s[l]);)l++;else{for(;l<i&&!c(s[l]);)l++;for(;l<i&&c(s[l]);)l++}const u=l>i?i:l;if(u===a)return!1;const f={type:"range",startNodeId:e.startNodeId,startOffset:a,endNodeId:e.startNodeId,endOffset:u,collapsed:!1,direction:"forward"};return t.updateSelection(f),!0}}}class Q{constructor(){this._parserRules=new Map,this._converterRules=new Map,this._astConverterRules=new Map,this._documentParsers=new Map}static getInstance(){return Q._instance||(Q._instance=new Q),Q._instance}registerParser(t,e,r){this._parserRules.has(t)||this._parserRules.set(t,new Map);const n=this._parserRules.get(t);n.has(e)||n.set(e,[]);const o=n.get(e);o.push(r),o.sort((s,i)=>(i.priority||0)-(s.priority||0))}registerConverter(t,e,r){this._converterRules.has(t)||this._converterRules.set(t,new Map);const n=this._converterRules.get(t);n.has(e)||n.set(e,[]);const o=n.get(e);o.push(r),o.sort((s,i)=>(i.priority||0)-(s.priority||0))}registerASTConverter(t,e,r){this._astConverterRules.has(e)||this._astConverterRules.set(e,new Map);const n=this._astConverterRules.get(e);n.has(t)||n.set(t,[]);const o=n.get(t);o.push(r),o.sort((s,i)=>(i.priority||0)-(s.priority||0))}registerDocumentParser(t,e){this._documentParsers.set(t,e)}getParserRules(t,e){var r;return((r=this._parserRules.get(t))==null?void 0:r.get(e))||[]}getConverterRules(t,e){var r;return((r=this._converterRules.get(t))==null?void 0:r.get(e))||[]}getASTConverterRules(t,e){var r;return((r=this._astConverterRules.get(e))==null?void 0:r.get(t))||[]}getDocumentParser(t){return this._documentParsers.get(t)}clear(){this._parserRules.clear(),this._converterRules.clear(),this._astConverterRules.clear(),this._documentParsers.clear()}}const ft=Q.getInstance();function j(d,t,e){ft.registerParser(d,t,e)}function Jr(d,t){ft.registerDocumentParser(d,t)}function et(d,t,e){ft.registerASTConverter(d,t,e)}function H(d,t,e){ft.registerConverter(d,t,e)}const $t=Q.getInstance();class Xr{parse(t,e="html"){if(e!=="html")throw new Error(`HTMLConverter.parse() only supports 'html' format, got '${e}'`);const n=new DOMParser().parseFromString(t,"text/html"),o=[],s=n.body;if(!s)return o;for(const i of Array.from(s.childNodes)){const a=this._parseDOMNode(i);a&&o.push(a)}return o}_parseDOMNode(t){var n;if(t.nodeType===Node.TEXT_NODE){const o=(n=t.textContent)==null?void 0:n.trim();return o?{stype:"inline-text",text:o}:null}if(t.nodeType!==Node.ELEMENT_NODE)return null;const e=t,r=this._getAllParserRules("html");for(const{stype:o,rules:s}of r)for(const i of s)if(i.parseDOM){for(const a of i.parseDOM)if(this._matchesDOMRule(e,a)){const c=this._convertElementToNode(e,o,a);if(c)return c}}return this._defaultElementToNode(e)}_getAllParserRules(t){const e=["paragraph","heading","inline-text","text","link","list","list_item","table","table_row","table_cell","image"],r=[];for(const n of e){const o=$t.getParserRules(n,t);o.length>0&&r.push({stype:n,rules:o})}return r}_matchesDOMRule(t,e){if(e.tag&&t.tagName.toLowerCase()!==e.tag.toLowerCase())return!1;if(e.attrs)for(const[r,n]of Object.entries(e.attrs)){const o=t.getAttribute(r);if(n===null){if(o!==null)return!1}else if(o!==n)return!1}if(e.getAttrs){const r=e.getAttrs(t);if(r===null||r===!1)return!1}return!0}_convertElementToNode(t,e,r){var i;let n;if(r.getAttrs){const a=r.getAttrs(t);a&&typeof a=="object"&&(n=a)}else n=this._extractAttributes(t);const o=[];for(const a of Array.from(t.childNodes)){if(e==="table"&&a.nodeType===Node.ELEMENT_NODE&&["tbody","thead","tfoot"].includes(a.tagName.toLowerCase())){for(const l of Array.from(a.childNodes)){const u=this._parseDOMNode(l);u&&o.push(u)}continue}const c=this._parseDOMNode(a);c&&o.push(c)}let s;return o.length===0&&(s=((i=t.textContent)==null?void 0:i.trim())||void 0),{stype:e,attributes:n,content:o.length>0?o:void 0,text:s}}_defaultElementToNode(t){var n,o;if(["div","p","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","aside"].includes(t.tagName.toLowerCase())){const s=[];for(const i of Array.from(t.childNodes)){const a=this._parseDOMNode(i);a&&s.push(a)}return{stype:"paragraph",content:s.length>0?s:void 0,text:s.length===0?(n=t.textContent)==null?void 0:n.trim():void 0}}else return{stype:"inline-text",text:((o=t.textContent)==null?void 0:o.trim())||""}}_extractAttributes(t){const e={};let r=!1;for(const n of Array.from(t.attributes))if(n.name.startsWith("data-")){const o=n.name;e[o]=n.value,r=!0}return r?e:void 0}convert(t,e="html"){if(e!=="html")throw new Error(`HTMLConverter.convert() only supports 'html' format, got '${e}'`);const r=[];for(const n of t){const o=this._convertNodeToHTML(n);o&&r.push(o)}return r.join(`
|
|
4
|
+
`)}_convertNodeToHTML(t){const e=t.stype,r=$t.getConverterRules(e,"html");if(r.length>0){let o=r[0].convert(t);if(typeof o=="string"){if(o.includes("PLACEHOLDER_CONTENT")){const s=this._convertContentToHTML(t.content);o=o.replace("PLACEHOLDER_CONTENT",s)}return o}}return this._defaultNodeToHTML(t)}_convertContentToHTML(t){if(!t||!Array.isArray(t))return"";const e=[];for(const r of t)typeof r=="string"?e.push(this._escapeHTML(r)):e.push(this._convertNodeToHTML(r));return e.join("")}_defaultNodeToHTML(t){if(t.text!==void 0)return this._escapeHTML(t.text);const e=this._convertContentToHTML(t.content),r=this._getDefaultTag(t.stype);return`<${r}>${e}</${r}>`}_getDefaultTag(t){return{paragraph:"p",heading:"h1","inline-text":"span",text:"span",list:"ul",list_item:"li",table:"table",table_row:"tr",table_cell:"td",image:"img",link:"a"}[t]||"div"}_escapeHTML(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}}const st=Q.getInstance();class Yr{parse(t){const e=t.split(`
|
|
5
|
+
`),r=[];for(let n=0;n<e.length;n++){const o=e[n].trim();if(!o)continue;const s=o.match(/^(#{1,6})\s+(.+)$/);if(s){const i=s[1].length,a=s[2];r.push({type:"heading",level:i,text:a,children:this._parseInline(a)});continue}r.push({type:"paragraph",text:o,children:this._parseInline(o)})}return r}_parseInline(t){const e=[],r=[{regex:/\*\*([^*]+)\*\*/g,type:"bold"},{regex:/\*([^*]+)\*/g,type:"italic"},{regex:/__([^_]+)__/g,type:"bold"},{regex:/_([^_]+)_/g,type:"italic"}],n=[];for(const i of r){let a;for(;(a=i.regex.exec(t))!==null;)n.push({index:a.index,length:a[0].length,text:a[1],type:i.type})}n.sort((i,a)=>i.index-a.index);const o=[];for(const i of n)o.some(c=>i.index>=c.index&&i.index<c.index+c.length||c.index>=i.index&&c.index<i.index+i.length)||o.push(i);let s=0;for(const i of o){if(i.index>s){const a=t.substring(s,i.index);a&&e.push({type:"text",text:a})}e.push({type:i.type,text:i.text}),s=i.index+i.length}if(s<t.length){const i=t.substring(s);i&&e.push({type:"text",text:i})}return e.length===0&&e.push({type:"text",text:t}),e}}class Zr{constructor(){this.parser=new Yr}parse(t,e="markdown"){if(e!=="markdown"&&e!=="markdown-gfm")throw new Error(`MarkdownConverter.parse() only supports 'markdown' or 'markdown-gfm' format, got '${e}'`);const r=st.getDocumentParser(e)||st.getDocumentParser("markdown");if(r){const o=r.parse(t);return this._convertASTToNodes(o)}const n=this.parser.parse(t);return this._convertASTToNodes(n)}_convertASTToNodes(t){const e=[];for(const r of t){const n=this._convertASTNode(r);n&&e.push(n)}return e}_convertASTNode(t){const e=this._getAllASTConverterRules("markdown");for(const{stype:r,rules:n}of e)for(const o of n){const s=o.convert(t,i=>this._convertASTNode(i));if(s)return s}return null}_getAllASTConverterRules(t){const e=["heading","paragraph","inline-text","list","image"],r=[];for(const n of e){const o=st.getASTConverterRules(n,t);o.length>0&&r.push({stype:n,rules:o})}return r}convert(t,e="markdown"){if(e!=="markdown")throw new Error(`MarkdownConverter.convert() only supports 'markdown' format, got '${e}'`);const r=[];for(const n of t){const o=this._convertNodeToMarkdown(n);o&&r.push(o)}return r.join(`
|
|
6
|
+
|
|
7
|
+
`)}_convertNodeToMarkdown(t){const e=t.stype,r=st.getConverterRules(e,"markdown");if(r.length>0){const o=r[0].convert(t);if(typeof o=="string")return o}return this._defaultNodeToMarkdown(t)}_defaultNodeToMarkdown(t){return t.text!==void 0?t.text:this._convertContentToMarkdown(t.content)}_convertContentToMarkdown(t){if(!t||!Array.isArray(t))return"";const e=[];for(const r of t)typeof r=="string"?e.push(r):e.push(this._convertNodeToMarkdown(r));return e.join("")}}Q.getInstance();function tn(){j("paragraph","html",{parseDOM:[{tag:"p",getAttrs:d=>{var n,o;const t=d,e={},r=(n=t.getAttribute)==null?void 0:n.call(t,"data-placeholder");r!=null&&(e.placeholder=r);for(const s of((o=t.getAttributeNames)==null?void 0:o.call(t))??[])if(s.startsWith("data-")){const i=t.getAttribute(s);i!=null&&(e[s]=i)}return e}}]}),j("heading","html",{parseDOM:[{tag:"h1",getAttrs:()=>({level:1})},{tag:"h2",getAttrs:()=>({level:2})},{tag:"h3",getAttrs:()=>({level:3})},{tag:"h4",getAttrs:()=>({level:4})},{tag:"h5",getAttrs:()=>({level:5})},{tag:"h6",getAttrs:()=>({level:6})}]}),j("inline-text","html",{parseDOM:[{tag:"span"}],parseText:d=>d.trim()?{stype:"inline-text",text:d}:null}),j("link","html",{parseDOM:[{tag:"a",getAttrs:d=>{const t=d.getAttribute("href");if(!t)return null;const e=d.getAttribute("title")||void 0,r=d.getAttribute("target")||void 0,n=d.getAttribute("rel")||void 0;return{href:t,title:e,target:r,rel:n}},priority:100}]}),j("inline-text","html",{parseDOM:[{tag:"strong",getAttrs:()=>({markType:"bold"})},{tag:"b",getAttrs:()=>({markType:"bold"})}],priority:100}),j("inline-text","html",{parseDOM:[{tag:"em",getAttrs:()=>({markType:"italic"})},{tag:"i",getAttrs:()=>({markType:"italic"})}],priority:100}),j("list","html",{parseDOM:[{tag:"ul",getAttrs:()=>({ordered:!1})},{tag:"ol",getAttrs:()=>({ordered:!0})}]}),j("list_item","html",{parseDOM:[{tag:"li"}]}),j("table","html",{parseDOM:[{tag:"table"}]}),j("table_row","html",{parseDOM:[{tag:"tr"}]}),j("table_cell","html",{parseDOM:[{tag:"td"},{tag:"th",getAttrs:()=>({header:!0})}]}),j("emoji","html",{parseDOM:[{tag:"span",getAttrs:d=>{var o,s;const t=d;if(!((o=t.getAttribute)!=null&&o.call(t,"data-emoji")))return null;const e=t.getAttribute("data-shortcode")??void 0,r=t.getAttribute("data-unicode")??void 0,n=(s=t.textContent)==null?void 0:s.trim();return{shortcode:e||void 0,unicode:r||n||void 0}},priority:110}]}),j("image","html",{parseDOM:[{tag:"img",getAttrs:d=>{const t=d.getAttribute("src");if(!t)return null;const e=d.getAttribute("alt")||void 0,r=d.getAttribute("title")||void 0;return{src:t,alt:e,title:r}}}]}),H("paragraph","html",{convert:d=>{var r;const t=(r=d.attributes)==null?void 0:r.placeholder;return`<p${t!=null?` data-placeholder="${q(String(t))}"`:""}>PLACEHOLDER_CONTENT</p>`}}),H("heading","html",{convert:d=>{var e;const t=((e=d.attributes)==null?void 0:e.level)||1;return`<h${t}>PLACEHOLDER_CONTENT</h${t}>`}}),H("inline-text","html",{convert:d=>{const t=d.text||"";let r=q(t);if(d.marks&&d.marks.length>0)for(const n of d.marks)n.stype==="bold"?r=`<strong>${r}</strong>`:n.stype==="italic"&&(r=`<em>${r}</em>`);return r}}),H("list","html",{convert:d=>{var r;const e=((r=d.attributes)==null?void 0:r.ordered)===!0?"ol":"ul";return`<${e}>PLACEHOLDER_CONTENT</${e}>`}}),H("list_item","html",{convert:()=>"<li>PLACEHOLDER_CONTENT</li>"}),H("table","html",{convert:()=>"<table>PLACEHOLDER_CONTENT</table>"}),H("table_row","html",{convert:()=>"<tr>PLACEHOLDER_CONTENT</tr>"}),H("table_cell","html",{convert:d=>{var r;const e=((r=d.attributes)==null?void 0:r.header)===!0?"th":"td";return`<${e}>PLACEHOLDER_CONTENT</${e}>`}}),H("emoji","html",{convert:d=>{const t=d.attributes||{},e=t.shortcode!=null?String(t.shortcode):"",r=t.unicode!=null?String(t.unicode):"",n=e?` data-shortcode="${q(e)}"`:"",o=r?` data-unicode="${q(r)}"`:"";return`<span data-emoji${n}${o}>${q(r||e||"")}</span>`}}),H("image","html",{convert:d=>{const t=d.attributes||{},e=t.src||"",r=t.alt||"",n=t.title||"",o=q(String(e)),s=q(String(r)),i=n?q(String(n)):"",a=i?` title="${i}"`:"";return`<img src="${o}" alt="${s}"${a} />`}}),H("link","html",{convert:d=>{const t=d.attributes||{},e=t.href||"",r=t.title||"",n=t.target||"",o=t.rel||"",s=q(String(e)),i=r?q(String(r)):"",a=n?q(String(n)):"",c=o?q(String(o)):"",l=i?` title="${i}"`:"",u=a?` target="${a}"`:"",f=c?` rel="${c}"`:"";return`<a href="${s}"${l}${u}${f}>PLACEHOLDER_CONTENT</a>`}})}function q(d){const t=document.createElement("div");return t.textContent=d,t.innerHTML}function en(){Jr("markdown",{parse(d){const t=d.split(`
|
|
8
|
+
`),e=[];let r=0;for(;r<t.length;){const o=t[r].trim();if(r++,!o)continue;const s=o.match(/^(#{1,6})\s+(.+)$/);if(s){e.push({type:"heading",level:s[1].length,text:s[2],children:it(s[2])});continue}if(o.match(/^[-*+]\s+(.+)$/)){const l=[];let u=r-1;for(;u<t.length;){const f=t[u].trim();if(!f)break;const h=f.match(/^[-*+]\s+(.+)$/);if(!h)break;let g=h[1];const m=g.match(/^\[([ xX])\]\s*(.*)$/),p=!!m,N=p&&m[1].toLowerCase()==="x";m&&(g=m[2]),l.push({type:"list_item",text:g,task:p,checked:N,children:it(g)}),u++}r=u,e.push({type:"list",ordered:!1,items:l});continue}if(o.match(/^\d+[.)]\s+(.+)$/)){const l=[];let u=r-1;for(;u<t.length;){const f=t[u].trim();if(!f)break;const h=f.match(/^\d+[.)]\s+(.+)$/);if(!h)break;let g=h[1];const m=g.match(/^\[([ xX])\]\s*(.*)$/),p=!!m,N=p&&m[1].toLowerCase()==="x";m&&(g=m[2]),l.push({type:"list_item",text:g,task:p,checked:N,children:it(g)}),u++}r=u,e.push({type:"list",ordered:!0,items:l});continue}const c=o.match(/^!\[([^\]]*)\]\(([^)]+)\)$/);if(c){e.push({type:"image",alt:c[1],src:c[2]});continue}e.push({type:"paragraph",text:o,children:it(o)})}return e}}),et("heading","markdown",{convert(d,t){if(d.type==="heading"){const e=[];if(d.children)for(const r of d.children){const n=t(r);n&&e.push(n)}return{stype:"heading",attributes:{level:d.level},content:e.length>0?e:void 0,text:e.length===0?d.text:void 0}}return null}}),et("paragraph","markdown",{convert(d,t){if(d.type==="paragraph"){const e=[];if(d.children)for(const r of d.children){const n=t(r);n&&e.push(n)}return{stype:"paragraph",content:e.length>0?e:void 0,text:e.length===0?d.text:void 0}}return null}}),et("inline-text","markdown",{convert(d){return d.type==="text"?{stype:"inline-text",text:d.text}:d.type==="bold"?{stype:"inline-text",text:d.text,marks:[{stype:"bold",range:[0,d.text.length]}]}:d.type==="italic"?{stype:"inline-text",text:d.text,marks:[{stype:"italic",range:[0,d.text.length]}]}:null}}),et("list","markdown",{convert(d,t){if(d.type==="list"){const e=(d.items||[]).map(r=>{const n=[];if(r.children)for(const o of r.children){const s=t(o);s&&n.push(s)}return{stype:"list_item",attributes:r.task?{task:!0,checked:r.checked===!0}:void 0,content:n.length>0?n:void 0,text:n.length===0?r.text:void 0}});return{stype:"list",attributes:{ordered:d.ordered===!0},content:e}}return null}}),et("image","markdown",{convert(d){return d.type==="image"?{stype:"image",attributes:{src:d.src,alt:d.alt}}:null}}),H("heading","markdown",{convert:d=>{var r;const t=((r=d.attributes)==null?void 0:r.level)||1,e=ct(d.content||[]);return`${"#".repeat(t)} ${e}`}}),H("paragraph","markdown",{convert:d=>ct(d.content||[])}),H("inline-text","markdown",{convert:d=>{let t=d.text||"";if(d.marks&&d.marks.length>0)for(const e of d.marks)e.stype==="bold"?t=`**${t}**`:e.stype==="italic"&&(t=`*${t}*`);return t}}),H("list","markdown",{convert:d=>{var o,s,i;const t=((o=d.attributes)==null?void 0:o.ordered)===!0,e=Array.isArray(d.content)?d.content:[],r=[];let n=1;for(const a of e){const c=ct(a.content||[]);if(!c)continue;const l=((s=a.attributes)==null?void 0:s.task)===!0,u=((i=a.attributes)==null?void 0:i.checked)===!0;if(t)if(l){const f=u?"[x]":"[ ]";r.push(`${n}. ${f} ${c}`)}else r.push(`${n}. ${c}`);else if(l){const f=u?"[x]":"[ ]";r.push(`- ${f} ${c}`)}else r.push(`- ${c}`);n++}return r.join(`
|
|
9
|
+
`)}}),H("image","markdown",{convert:d=>{const t=d.attributes||{},e=t.alt||"",r=t.src||"";return``}})}function it(d){const t=[],e=/\*\*([^*]+)\*\*/g,r=/\*([^*]+)\*/g,n=[];let o;for(;(o=e.exec(d))!==null;)n.push({index:o.index,length:o[0].length,text:o[1],type:"bold"});for(;(o=r.exec(d))!==null;)n.some(a=>o.index>=a.index&&o.index<a.index+a.length||a.index>=o.index&&a.index<o.index+o.length)||n.push({index:o.index,length:o[0].length,text:o[1],type:"italic"});n.sort((i,a)=>i.index-a.index);let s=0;for(const i of n){if(i.index>s){const a=d.substring(s,i.index);a&&t.push({type:"text",text:a})}t.push({type:i.type,text:i.text}),s=i.index+i.length}if(s<d.length){const i=d.substring(s);i&&t.push({type:"text",text:i})}return t.length===0&&t.push({type:"text",text:d}),t}function ct(d){const t=[];for(const e of d)if(typeof e=="string")t.push(e);else if(e&&typeof e=="object"&&"stype"in e)if(e.text!==void 0){let r=e.text;if(e.marks&&e.marks.length>0)for(const n of e.marks)n.stype==="bold"?r=`**${r}**`:n.stype==="italic"&&(r=`*${r}*`);t.push(r)}else e.content&&t.push(ct(e.content));return t.join("")}class rn{clean(t){const r=new DOMParser().parseFromString(t,"text/html");return r.body?(this._removeOfficeAttributes(r.body),this._removeOfficeStyles(r.body),this._removeOfficeElements(r.body),this._cleanOfficeTables(r.body),this._normalizeOfficeFormatting(r.body),r.body.innerHTML):t}_removeOfficeAttributes(t){const e=["mso-","o:","v:","xml:","w:"],r=[];for(const n of Array.from(t.attributes))e.some(o=>n.name.startsWith(o))&&r.push(n.name);for(const n of r)t.removeAttribute(n);for(const n of Array.from(t.children))this._removeOfficeAttributes(n)}_removeOfficeStyles(t){const e=t.getAttribute("style");if(e){const r=e.split(";").filter(n=>{const o=n.trim();return!o.startsWith("mso-")&&!o.startsWith("mso-")&&o.length>0}).join(";");r?t.setAttribute("style",r):t.removeAttribute("style")}for(const r of Array.from(t.children))this._removeOfficeStyles(r)}_removeOfficeElements(t){var n,o;const e=t.getElementsByTagName("o:p");for(let s=e.length-1;s>=0;s--){const i=e[s],a=document.createElement("p");for(const c of Array.from(i.attributes))!c.name.startsWith("mso-")&&!c.name.startsWith("o:")&&!c.name.startsWith("xml:")&&a.setAttribute(c.name,c.value);for(;i.firstChild;)a.appendChild(i.firstChild);(n=i.parentNode)==null||n.replaceChild(a,i)}const r=["o:smarttag","v:shapetype","v:shape","xml","w:worddocument"];for(const s of r){const i=t.getElementsByTagName(s);for(let a=i.length-1;a>=0;a--){const c=i[a];for(;c.firstChild;)(o=c.parentNode)==null||o.insertBefore(c.firstChild,c);c.remove()}}for(const s of Array.from(t.children))this._removeOfficeElements(s)}_cleanOfficeTables(t){const e=t.getElementsByTagName("table");for(const r of Array.from(e)){const n=["border","cellpadding","cellspacing","width","style"];for(const s of n)if(s==="style"){const i=r.getAttribute("style");i&&i.includes("mso-")&&r.removeAttribute("style")}else r.removeAttribute(s);const o=r.getElementsByTagName("td");for(const s of Array.from(o)){s.removeAttribute("width"),s.removeAttribute("height");const i=s.getAttribute("style");i&&i.includes("mso-")&&s.removeAttribute("style")}}}_normalizeOfficeFormatting(t){var s,i,a,c;const e=t.getElementsByTagName("b");for(let l=e.length-1;l>=0;l--){const u=e[l],f=document.createElement("strong");for(;u.firstChild;)f.appendChild(u.firstChild);(s=u.parentNode)==null||s.replaceChild(f,u)}const r=t.getElementsByTagName("i");for(let l=r.length-1;l>=0;l--){const u=r[l],f=document.createElement("em");for(;u.firstChild;)f.appendChild(u.firstChild);(i=u.parentNode)==null||i.replaceChild(f,u)}const n=t.getElementsByTagName("u");for(let l=n.length-1;l>=0;l--){const u=n[l],f=document.createElement("span");for(;u.firstChild;)f.appendChild(u.firstChild);(a=u.parentNode)==null||a.replaceChild(f,u)}const o=t.getElementsByTagName("font");for(let l=o.length-1;l>=0;l--){const u=o[l],f=document.createElement("span");for(;u.firstChild;)f.appendChild(u.firstChild);(c=u.parentNode)==null||c.replaceChild(f,u)}}}const nn=new rn;function on(){j("paragraph","html",{parseDOM:[{tag:"p"},{tag:"o:p",priority:100},{tag:"div",getAttrs:d=>{const t=d.getAttribute("style")||"";return(d.getAttribute("class")||"").includes("Mso")||t.includes("mso-")?{}:null},priority:50}]}),j("heading","html",{parseDOM:[{tag:"h1",getAttrs:()=>({level:1})},{tag:"h2",getAttrs:()=>({level:2})},{tag:"h3",getAttrs:()=>({level:3})},{tag:"h4",getAttrs:()=>({level:4})},{tag:"h5",getAttrs:()=>({level:5})},{tag:"h6",getAttrs:()=>({level:6})},{tag:"p",getAttrs:d=>{const t=d.getAttribute("style")||"",e=d.getAttribute("class")||"";if(e.includes("MsoHeading")){const r=e.match(/MsoHeading(\d)/);if(r)return{level:parseInt(r[1])}}if(e==="MsoTitle")return{level:1};if(e==="MsoSubtitle")return{level:2};if(t.includes("mso-style-name")){const r=t.match(/mso-style-name:\s*["']?Heading\s*(\d)/i);if(r)return{level:parseInt(r[1])};if(t.match(/mso-style-name:\s*["']?Title/i))return{level:1};if(t.match(/mso-style-name:\s*["']?Subtitle/i))return{level:2}}return null},priority:100}]}),j("inline-text","html",{parseDOM:[{tag:"span"},{tag:"a"},{tag:"span",getAttrs:d=>(d.getAttribute("style")||"").includes("mso-")?{}:null,priority:100}]})}function sn(d){return nn.clean(d)}function an(){j("heading","html",{parseDOM:[{tag:"p",getAttrs:d=>{const t=d.getAttribute("data-heading-level")||d.getAttribute("data-heading")||void 0;if(!t)return null;const e=parseInt(t,10);return!Number.isFinite(e)||e<=0?null:{level:e}},priority:50}]})}function dn(){j("paragraph","html",{parseDOM:[{tag:"div",getAttrs:d=>d.getAttribute("data-block-id")?{}:null,priority:10}]})}class cn{constructor(){y(this,"name","copyPaste");y(this,"priority",100);y(this,"_htmlConverter",null)}onCreate(t){this._htmlConverter=new Xr,tn(),on(),an(),dn(),en(),t.registerCommand({name:"copy",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;if(!n||n.type!=="range")return!1;const s=await $(e,[sr(n)]).commit();if(!s||s.success===!1)return!1;const i=e.dataStore;if(i&&this._htmlConverter)try{const a=i.serializeRange(n),c=i.range.extractText(n),l=this._htmlConverter.convert(a,"html");await this._writeClipboard({json:a,text:c,html:l})}catch{}return!0},canExecute:(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return!!n&&n.type==="range"}}),t.registerCommand({name:"paste",execute:async(e,r)=>{let n=(r==null?void 0:r.selection)||e.selection;if(!n||n.type!=="range")return!1;let o=r==null?void 0:r.nodes;if(!o||o.length===0){const a=await this._readClipboard();if(a.json&&Array.isArray(a.json)&&(o=a.json),(!o||o.length===0)&&a.html&&this._htmlConverter)try{const c=this._detectHtmlSource(a.html);let l=a.html;c==="office"&&(l=sn(l)),o=this._htmlConverter.parse(l,"html")}catch{}if((!o||o.length===0)&&a.text)if(this._looksLikeMarkdown(a.text))try{o=new Zr().parse(a.text,"markdown-gfm")}catch{o=this._textToNodes(a.text)}else o=this._textToNodes(a.text)}if(!o||o.length===0)return!1;const i=await $(e,[ir(o,n)]).commit();return!!i&&i.success!==!1},canExecute:(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection,o=r==null?void 0:r.nodes;return!!n&&n.type==="range"&&Array.isArray(o)&&o.length>0}}),t.registerCommand({name:"cut",execute:async(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;if(!n||n.type!=="range"||n.collapsed)return!1;const o=e.dataStore;if(o&&this._htmlConverter)try{const a=o.serializeRange(n),c=o.range.extractText(n),l=this._htmlConverter.convert(a,"html");await this._writeClipboard({json:a,text:c,html:l})}catch{}const i=await $(e,[ar(n)]).commit();return!!i&&i.success!==!1},canExecute:(e,r)=>{const n=(r==null?void 0:r.selection)||e.selection;return!!n&&n.type==="range"&&!n.collapsed}})}_textToNodes(t){const e=t.split(/\r?\n/),r=[];for(const n of e){if(!n){r.push({stype:"paragraph",content:[]});continue}r.push({stype:"paragraph",content:[{stype:"inline-text",text:n}]})}return r}async _writeClipboard(t){var e;try{typeof navigator<"u"&&((e=navigator.clipboard)!=null&&e.writeText)&&t.text&&await navigator.clipboard.writeText(t.text)}catch{}}async _readClipboard(){var t;try{if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.readText))return{text:await navigator.clipboard.readText()}}catch{}return{}}_detectHtmlSource(t){const e=t.toLowerCase();return e.includes('class="msonormal')||e.includes("mso-")||e.includes("<o:p")||e.includes("office:")||e.includes('xmlns:o="urn:schemas-microsoft-com:office')?"office":e.includes("docs-internal")||e.includes("data-docs-")||e.includes('id="docs-internal-guid-')?"google-docs":e.includes("data-block-id")||e.includes('class="notion-')?"notion":"default"}_looksLikeMarkdown(t){const e=t.split(/\r?\n/).slice(0,20);let r=0;for(const n of e){const o=n.trim();o&&(/^#{1,6}\s+/.test(o)&&(r+=2),/^([-*+])\s+/.test(o)&&(r+=1),/^\d+\.\s+/.test(o)&&(r+=1),/^```/.test(o)&&(r+=2),/!\[[^\]]*]\([^)]+\)/.test(o)&&(r+=1),/\[[^\]]+]\([^)]+\)/.test(o)&&(r+=1),/^- \[[ xX]]\s+/.test(o)&&(r+=2))}return r>=3}onDestroy(t){}}function ln(){return[new Dr,new Rr,new $r,new Gr,new jr,new Hr,new cn]}function un(){return[new Br,new Fr,new Ur,new Kr,new Qr]}function mt(d){if(!d||typeof d!="object")return!1;const t=d,e=t.type;return(e==="range"||e==="node"||e==="cell"||e==="table")&&typeof t.startNodeId=="string"&&typeof t.endNodeId=="string"&&Number.isInteger(t.startOffset)&&Number.isInteger(t.endOffset)}function Lt(d,t){const e=d.getNode(t.startNodeId),r=d.getNode(t.endNodeId);return!(!e||!r||t.startOffset<0||t.endOffset<0||typeof e.text=="string"&&t.startOffset>e.text.length||typeof r.text=="string"&&t.endOffset>r.text.length)}function fn(d){const t=d;return!t||typeof t!="object"?{modelSelection:t,applySelectionToView:!0}:Object.prototype.hasOwnProperty.call(t,"selection")?{modelSelection:t.selection,applySelectionToView:t.source==="remote"?!1:t.applySelectionToView!==!1,source:t.source}:{modelSelection:t,applySelectionToView:t.source!=="remote",source:t.source}}class V{constructor(t={}){y(this,"_document");y(this,"_dataStore");y(this,"_transactionManager");y(this,"_selectionManager");y(this,"_historyManager");y(this,"_rootId");y(this,"_extensions",new Map);y(this,"_commands",new Map);y(this,"_eventListeners",new Map);y(this,"_isFocused",!1);y(this,"_isEditable",!0);y(this,"_history",[]);y(this,"_historyIndex",-1);y(this,"_keybindingRegistry");y(this,"_context",{});this._dataStore=t.dataStore||new It,this._ensureSchema(t),this._document=t.content?this._convertFromDocumentState(t.content):this._createEmptyDocument(),this._syncToDataStoreFromDocumentState(t.content||this._document,this._document),this._historyManager=new kr(t.history),this._transactionManager=new Gt(this),this._selectionManager=new vt({dataStore:this._dataStore}),this._isEditable=t.editable!==!1,this._keybindingRegistry=new Cr,this._keybindingRegistry.setContextProvider(this),this._context={...Mr},this._updateBuiltinContext(),this._registerCoreCommands(),this._registerDefaultExtensions(),this._registerDefaultKeybindings(),this._addToHistory(this._document),t.extensions&&t.extensions.forEach(e=>this.use(e)),this._setupModelEventHandling(),this._setupSelectionEventHandling(),this._setupSelectionErrorHandling()}_registerCoreCommands(){this.registerCommand({name:"setContext",execute:(t,e)=>!e||!e.key?(console.warn("[Editor] setContext: key is required"),!1):(t.setContext(e.key,e.value),!0),canExecute:()=>!0}),this.registerCommand({name:"focus",execute:()=>!0,canExecute:()=>!0}),this.registerCommand({name:"insertText",execute:async(t,e)=>{const r=(e==null?void 0:e.selection)||t.selection;return!r||r.type!=="range"||!(e!=null&&e.text)||!t.canExecuteCommand("replaceText")?!1:t.executeCommand("replaceText",{range:r,text:e.text})},canExecute:(t,e)=>{const r=(e==null?void 0:e.selection)||t.selection;return!!r&&r.type==="range"&&!!(e!=null&&e.text)}}),this.registerCommand({name:"deleteSelection",execute:async(t,e)=>{const r=(e==null?void 0:e.selection)||t.selection;return!r||r.type!=="range"||r.collapsed||!t.canExecuteCommand("backspace")?!1:t.executeCommand("backspace",{selection:r})},canExecute:(t,e)=>{const r=(e==null?void 0:e.selection)||t.selection;return!!r&&r.type==="range"&&!r.collapsed}}),this.registerCommand({name:"historyUndo",execute:t=>t.undo(),canExecute:t=>t.canUndo()}),this.registerCommand({name:"historyRedo",execute:t=>t.redo(),canExecute:t=>t.canRedo()}),this.registerCommand({name:"undo",execute:t=>t.undo(),canExecute:t=>t.canUndo()}),this.registerCommand({name:"redo",execute:t=>t.redo(),canExecute:t=>t.canRedo()}),this.registerCommand({name:"setRange",execute:(t,e)=>(t.setRange(e),!0),canExecute:()=>!0}),this.registerCommand({name:"setNode",execute:(t,e)=>(t.setNode(e),!0),canExecute:()=>!0}),this.registerCommand({name:"setAbsolutePos",execute:(t,e)=>(t.setAbsolutePos(e),!0),canExecute:()=>!0}),this.registerCommand({name:"clearSelection",execute:t=>(t.clearSelection(),!0),canExecute:()=>!0})}_registerDefaultExtensions(){const t=[...ln(),...un(),new Wr,new qr,new Vr,new zr];for(const e of t)this._extensions.has(e.name)||this.use(e)}_registerDefaultKeybindings(){this._keybindingRegistry.setCurrentSource("core"),Ar.forEach(t=>{this.keybindings.register(t)}),this._keybindingRegistry.setCurrentSource(null)}get document(){return this._convertToDocumentState(this._document)}get selection(){return this._selectionManager.getCurrentSelection()||null}get dataStore(){return this._dataStore}get transactionManager(){return this._transactionManager}get isFocused(){return this._isFocused}get isEditable(){return this._isEditable}get keybindings(){return this._keybindingRegistry}get selectionManager(){return this._selectionManager}getRootId(){return this._rootId}setRange(t){this.updateSelection(t)}loadDocument(t,e="editor-session"){const n=new br(this._dataStore,e).loadDocument(t);this._rootId=n;const s=new pt(this._dataStore).exportToTree(n);this._document=this._convertToDocumentState(s),this._addToHistory(this._document),this.emit("editor:content.change",{content:this.document,transaction:null,rootId:n})}exportDocument(t){const e=t??this._rootId;return new pt(this._dataStore).exportToTree(e)}getDocumentProxy(t){const e=t??this._rootId;return new pt(this._dataStore).toProxy(e)}setNode(t){if(!t){this.updateSelection(null);return}const e=t.nodeId??t.startNodeId;if(!e){this.updateSelection(null);return}this.updateSelection({type:"node",startNodeId:e,startOffset:0,endNodeId:e,endOffset:0})}setAbsolutePos(t){this.updateSelection(t)}_setupSelectionErrorHandling(){}clearSelection(){this._selectionManager.clearSelection()}isSelectionInContentEditable(){return this._selectionManager.isSelectionInContentEditable()}chain(){return new hn(this)}async executeCommand(t,e){var n,o;const r=this._commands.get(t);if(!r)return console.warn(`Command ${t} not found`),!1;try{if(r.canExecute&&!r.canExecute(this,e))return!1;this.emit("editor:command.before",{command:t,payload:e}),(n=r.before)==null||n.call(r,this,e);const s=await r.execute(this,e);return(o=r.after)==null||o.call(r,this,e),this.emit("editor:command.after",{command:t,payload:e,success:s}),this.emit("editor:command.execute",{command:t,payload:e,success:s}),s}catch(s){return console.error(`Error executing command ${t}:`,s),this.emit("error:command",{command:t,payload:e,error:s}),!1}}canExecuteCommand(t,e){const r=this._commands.get(t);return r?r.canExecute?r.canExecute(this,e):!0:!1}setContent(t){let e=t;const r=this.getSortedExtensions();for(const o of r)if(o.onBeforeContentChange){const s=o.onBeforeContentChange(this,e);if(s===null){console.warn(`Content change cancelled by extension: ${o.name}`);return}s&&(e=s)}const n=this._convertFromDocumentState(e);this._document=n,this._syncToDataStoreFromDocumentState(e,n),this._addToHistory(this._document),this.emit("editor:content.change",{content:e,transaction:null}),r.forEach(o=>{var s;(s=o.onContentChange)==null||s.call(o,this,e)})}updateSelection(t){const e=fn(t);let r=e.modelSelection;const n=e.applySelectionToView,o=e.source,s=this.selection;if(!r){this._selectionManager.clearSelection(),this._updateBuiltinContext(),this.emit("editor:selection.change",{selection:r,oldSelection:s});return}if(mt(r)&&!Lt(this._dataStore,r)){process.env.EDITOR_SELECTION_DEBUG==="1"&&console.warn("[selection-debug] updateSelection skipped due dead selection",{selection:r,startNode:this._dataStore.getNode(r.startNodeId),endNode:this._dataStore.getNode(r.endNodeId)}),this._selectionManager.clearSelection(),this._updateBuiltinContext();return}let i=r;const a=this.getSortedExtensions();for(const c of a)if(c.onBeforeSelectionChange){const l=c.onBeforeSelectionChange(this,i);if(l===null){console.warn(`Selection change cancelled by extension: ${c.name}`);return}l&&(i=l)}if(mt(i)){this._selectionManager.setSelection(i),this._updateBuiltinContext();const c=n?i:{selection:i,applySelectionToView:n,source:o};this.emit("editor:selection.model",c),a.forEach(l=>{var u;(u=l.onSelectionChange)==null||u.call(l,this,i)});return}this._updateBuiltinContext(),this._selectionManager.clearSelection(),this.emit("editor:selection.change",{selection:i,oldSelection:s}),a.forEach(c=>{var l;(l=c.onSelectionChange)==null||l.call(c,this,i)})}setContentEditableElement(t){this._selectionManager.setContentEditableElement(t)}setEditable(t){this._isEditable=t,this._updateBuiltinContext(),this.emit("editor:editable.change",{editable:t})}setContext(t,e){const r=this._context[t];e==null?delete this._context[t]:this._context[t]=e,this.emit("editor:context.change",{key:t,value:e,oldValue:r}),this.emit(`editor:context.change:${t}`,{key:t,value:e,oldValue:r})}onContextChange(t,e){const r=`editor:context.change:${t}`;return this.on(r,e),()=>{this.off(r,e)}}getContext(t){return this._updateBuiltinContext(),t!==void 0?this._context[t]:{...this._context}}_updateBuiltinContext(){this._context.editorFocus=this._isFocused,this._context.editorEditable=this._isEditable,this._context.isMac=Vt,this._context.isLinux=Ie,this._context.isWindows=we;const t=this._selectionManager.getCurrentSelection();if(!t||!mt(t))this._selectionManager.clearSelection(),this._context.selectionEmpty=!0,this._context.selectionType=null,this._context.selectionDirection=null,this._context.canIndent=!1,this._context.canIndentText=!1;else if(!Lt(this._dataStore,t))this._selectionManager.clearSelection(),this._context.selectionEmpty=!0,this._context.selectionType=null,this._context.selectionDirection=null,this._context.canIndent=!1,this._context.canIndentText=!1;else{this._context.selectionEmpty=t.collapsed===!0,this._context.selectionType=t.type,this._context.selectionDirection=t.direction;const e=this._getIndentableTargetNodeId(t);if(this._context.canIndent=e!==null&&this._dataStore.isIndentableNode(e),t.type==="range"){const r=this._dataStore.getNode(t.startNodeId);this._context.canIndentText=r!==null&&typeof r.text=="string"}else this._context.canIndentText=!1}this._context.historyCanUndo=this._historyManager.canUndo(),this._context.historyCanRedo=this._historyManager.canRedo()}_getIndentableTargetNodeId(t){if(t.type==="node")return t.startNodeId;if(t.type==="range"){const e=this._dataStore.getNode(t.startNodeId);if(!e)return null;const r=this._dataStore.getActiveSchema();if(r){const o=r.getNodeType(e.stype);if((o==null?void 0:o.group)==="block"&&this._dataStore.isIndentableNode(e.sid))return e.sid}let n=e;for(;n&&n.parentId;){const o=this._dataStore.getNode(n.parentId);if(!o)break;const s=r==null?void 0:r.getNodeType(o.stype);if((s==null?void 0:s.group)==="block"&&this._dataStore.isIndentableNode(o.sid))return o.sid;n=o}}return null}on(t,e){this._eventListeners.has(t)||this._eventListeners.set(t,new Set),this._eventListeners.get(t).add(e)}off(t,e){const r=this._eventListeners.get(t);r&&r.delete(e)}emit(t,e){var n;console.log("[Editor] emit:",t,{hasListeners:this._eventListeners.has(t),listenersCount:((n=this._eventListeners.get(t))==null?void 0:n.size)||0,dataKeys:e?Object.keys(e):[]});const r=this._eventListeners.get(t);r?r.forEach(o=>{try{o(e)}catch(s){console.error(`Error in event listener for ${t}:`,s)}}):console.log("[Editor] emit: no listeners for",t)}use(t){var e,r;if(this._extensions.has(t.name)){console.warn(`Extension ${t.name} is already installed`);return}try{(e=t.onBeforeCreate)==null||e.call(t,this),t.commands&&t.commands.forEach(n=>{this._commands.set(n.name,n)}),this._extensions.set(t.name,t),this._keybindingRegistry.setCurrentSource("extension"),(r=t.onCreate)==null||r.call(t,this),this._keybindingRegistry.setCurrentSource(null),this.emit("extension:add",{extension:t})}catch(n){throw console.error(`Error installing extension ${t.name}:`,n),this._keybindingRegistry.setCurrentSource(null),n}}unuse(t){var e;if(!this._extensions.has(t.name)){console.warn(`Extension ${t.name} is not installed`);return}try{(e=t.onDestroy)==null||e.call(t,this),t.commands&&t.commands.forEach(r=>{this._commands.delete(r.name)}),this._extensions.delete(t.name),this.emit("extension:remove",{extension:t})}catch(r){throw console.error(`Error removing extension ${t.name}:`,r),r}}getSortedExtensions(){return Array.from(this._extensions.values()).sort((t,e)=>{const r=t.priority??100,n=e.priority??100;return r-n})}registerCommand(t){this._commands.set(t.name,t)}undo(){try{return this._historyIndex>0?(this._historyIndex--,this._document=this._history[this._historyIndex],this.emit("editor:history.undo",{document:this._document}),this.emit("editor:history.change",{canUndo:this.canUndo(),canRedo:this.canRedo()}),Promise.resolve(!0)):Promise.resolve(!1)}catch(t){return console.error("Undo failed:",t),Promise.resolve(!1)}}redo(){try{return this._historyIndex<this._history.length-1?(this._historyIndex++,this._document=this._history[this._historyIndex],this.emit("editor:history.redo",{document:this._document}),this.emit("editor:history.change",{canUndo:this.canUndo(),canRedo:this.canRedo()}),Promise.resolve(!0)):Promise.resolve(!1)}catch(t){return console.error("Redo failed:",t),Promise.resolve(!1)}}canUndo(){return this._historyIndex>0}canRedo(){return this._historyIndex<this._history.length-1}async executeTransaction(t){const e=t==null?void 0:t.operations;if(!Array.isArray(e))return{success:!1,errors:["Unsupported transaction format."],data:void 0,transactionId:t==null?void 0:t.sid,operations:[],selectionBefore:this._selectionManager.getCurrentSelection()||null,selectionAfter:this._selectionManager.getCurrentSelection()||null};try{const r=await this._transactionManager.execute(e,t==null?void 0:t.options);return this.emit("transactionExecuted",{transaction:r}),r}catch(r){return console.error("Transaction execution failed:",r),this.emit("transactionError",{transaction:t,error:r}),{success:!1,errors:[r instanceof Error?r.message:"Unknown error"],data:void 0,transactionId:void 0,operations:e,selectionBefore:this._selectionManager.getCurrentSelection()||null,selectionAfter:this._selectionManager.getCurrentSelection()||null}}}_setupModelEventHandling(){}_createEmptyDocument(){return{id:`doc-${Date.now()}`,type:"document",content:[],metadata:{title:"Untitled Document",author:"Unknown",version:"1.0.0",createdAt:new Date,updatedAt:new Date},schema:this._getDocumentSchemaMetadata(),version:1}}_convertToDocumentState(t){var e,r;return{type:"document",content:(t.content||[]).map(n=>this._convertNode(n)).filter(Boolean),version:t.version,createdAt:((e=t.metadata)==null?void 0:e.createdAt)||new Date,updatedAt:((r=t.metadata)==null?void 0:r.updatedAt)||new Date}}_convertFromDocumentState(t){return{id:this._generateNodeId("doc"),type:"document",content:t.content.map(r=>this._convertFromNode(r)),metadata:{title:"Document",author:"Unknown",version:"1.0.0",createdAt:t.createdAt,updatedAt:t.updatedAt},schema:this._getDocumentSchemaMetadata(),version:t.version}}_ensureSchema(t){var e;if(t.schema){this._dataStore.setActiveSchema(t.schema);return}if((e=t.model)!=null&&e.schema){this._dataStore.setActiveSchema(t.model.schema);return}this._dataStore.getActiveSchema()||this._dataStore.setActiveSchema(cr("default-editor",Dt()))}_getDocumentSchemaMetadata(){const t=this._dataStore.getActiveSchema();return t?{name:t.name,...t.definition||{}}:{name:"default-editor",...Dt()}}_convertNode(t){var n,o;if(!t)return null;if(typeof t=="string"){const s=(o=(n=this._dataStore)==null?void 0:n.getNode)==null?void 0:o.call(n,t);return s?this._convertNode(s):{id:t,type:"text",text:t}}if(typeof t!="object")return null;const e=t;return{id:e.sid||e.id||this._generateNodeId("node"),type:e.type||e.stype||"unknown",attributes:e.attributes||{},text:e.text,content:Array.isArray(e.content)?e.content.map(s=>this._convertNode(s)).filter(Boolean):void 0,marks:Array.isArray(e.marks)?e.marks.map(s=>({type:(s==null?void 0:s.stype)||(s==null?void 0:s.type),attributes:(s==null?void 0:s.attrs)||(s==null?void 0:s.attributes),range:s==null?void 0:s.range})):void 0}}_convertFromNode(t){var n,o;if(!t)return{sid:this._generateNodeId("node"),stype:"unknown",attributes:{}};if(typeof t=="string"){const s=(o=(n=this._dataStore)==null?void 0:n.getNode)==null?void 0:o.call(n,t);return s?this._convertFromNode(s):{sid:t,stype:"text",text:"",attributes:{}}}if(typeof t!="object")return{sid:this._generateNodeId("node"),stype:"unknown",attributes:{}};const e=t;return{sid:e.id||e.sid||this._generateNodeId("node"),stype:e.type||e.stype||"unknown",attributes:e.attributes||{},text:e.text,marks:Array.isArray(e.marks)?e.marks.map(s=>({stype:(s==null?void 0:s.type)||(s==null?void 0:s.stype),attrs:(s==null?void 0:s.attributes)||(s==null?void 0:s.attrs),range:s==null?void 0:s.range})):void 0,content:Array.isArray(e.content)?e.content.map(s=>{var i,a;if(typeof s=="string"){const c=(a=(i=this._dataStore)==null?void 0:i.getNode)==null?void 0:a.call(i,s);return c?this._convertFromNode(c):{sid:s,stype:"text",text:"",attributes:{}}}return this._convertFromNode(s)}):void 0}}_generateNodeId(t="node"){return this._dataStore&&this._dataStore.generateId?this._dataStore.generateId():`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}_syncToDataStoreFromDocumentState(t,e){var s,i,a,c,l,u;const r=e?{...e}:this._convertFromDocumentState(t);!(r!=null&&r.content)&&!((s=r.content)!=null&&s.length)&&(r.content=[]),r.sid=r.id||this._generateNodeId("doc"),delete r.id,Array.isArray(r.content)&&(r.content=r.content.map(f=>({...f,sid:(f==null?void 0:f.sid)||(f==null?void 0:f.id)||this._generateNodeId("node")}))),(i=this._dataStore)!=null&&i.clear&&this._dataStore.clear();const n=(c=(a=this._dataStore)==null?void 0:a.saveDocumentInternal)==null?void 0:c.call(a,r),o=(u=(l=this._dataStore)==null?void 0:l.getRootNode)==null?void 0:u.call(l);(n==null?void 0:n.valid)===!1&&console.warn("[Editor] Failed to sync content to datastore:",n.errors),o!=null&&o.sid?this._rootId=o.sid:r!=null&&r.sid&&(this._rootId=r.sid)}_addToHistory(t){this._history=this._history.slice(0,this._historyIndex+1),this._history.push({...t}),this._historyIndex++,this._history.length>100&&(this._history.shift(),this._historyIndex--)}_setupSelectionEventHandling(){}destroy(){this._selectionManager.clearSelection(),this._selectionManager.destroy(),this._extensions.forEach(t=>{this.unuse(t)}),this._eventListeners.clear(),this._commands.clear(),this._extensions.clear(),this.emit("editor:destroy",{editor:this})}}class hn{constructor(t){y(this,"editor");y(this,"commands",[]);this.editor=t}insertText(t){return this.commands.push({command:"insertText",payload:t}),this}deleteSelection(){return this.commands.push({command:"deleteSelection"}),this}toggleBold(){return this.commands.push({command:"toggleBold"}),this}toggleItalic(){return this.commands.push({command:"toggleItalic"}),this}toggleUnderline(){return this.commands.push({command:"toggleUnderline"}),this}toggleStrikeThrough(){return this.commands.push({command:"toggleStrikeThrough"}),this}setHeading(t){return this.commands.push({command:"setHeading",payload:t}),this}insertParagraph(){return this.commands.push({command:"insertParagraph"}),this}focus(){return this.commands.push({command:"focus"}),this}async run(){let t=!0;for(const{command:e,payload:r}of this.commands)if(!await this.editor.executeCommand(e,r)){t=!1;break}return t}canRun(){return this.commands.every(({command:t,payload:e})=>this.editor.canExecuteCommand(t,e))}}V.prototype.undo=async function(){const d=this.historyManager.undo();if(!d)return!1;const t=d.metadata,e=t&&Object.prototype.hasOwnProperty.call(t,"selectionBefore"),r=e?t.selectionBefore:void 0;try{this.transactionManager._isUndoRedoOperation=!0;const n=await this.transactionManager.execute(d.inverseOperations,{applySelectionToView:!1});return n.success&&e&&(r===null?this.updateSelection(null):r&&this.updateSelection(r)),n.success}catch(n){return console.error("[Editor] undo failed:",n),!1}finally{this.transactionManager._isUndoRedoOperation=!1}};V.prototype.redo=async function(){const d=this.historyManager.redo();if(!d)return!1;const t=d.metadata,e=t&&Object.prototype.hasOwnProperty.call(t,"selectionAfter"),r=e?t.selectionAfter:void 0;try{this.transactionManager._isUndoRedoOperation=!0;const n=await this.transactionManager.execute(d.operations,{applySelectionToView:!1});return n.success&&e&&(r===null?this.updateSelection(null):r&&this.updateSelection(r)),n.success}catch(n){return console.error("[Editor] redo failed:",n),!1}finally{this.transactionManager._isUndoRedoOperation=!1}};V.prototype.canUndo=function(){return this.historyManager.canUndo()};V.prototype.canRedo=function(){return this.historyManager.canRedo()};V.prototype.getHistoryStats=function(){return this.historyManager.getStats()};V.prototype.clearHistory=function(){this.historyManager.clear()};Object.defineProperty(V.prototype,"historyManager",{get:function(){return this._historyManager}});V.prototype.transaction=function(d,t){return{commit:async()=>await this.transactionManager.execute(d,t)}};V.prototype.compressHistory=function(){this.historyManager.compress()};V.prototype.resizeHistory=function(d){this.historyManager.resize(d)};V.prototype.getHistoryMemoryUsage=function(){return this.historyManager.getMemoryUsage()};V.prototype.validateHistory=function(){return this.historyManager.validate()};class gn{constructor(t,e){y(this,"editor");y(this,"getContentEditableElement");y(this,"_isProgrammaticChange",!1);this.editor=t,this.getContentEditableElement=e}_getScopeRoot(){const t=this.getContentEditableElement();return t&&t.querySelector?t:document}setProgrammaticChange(t){this._isProgrammaticChange=t}isSelectionInsideEditableText(t){const e=t??window.getSelection();if(!e||e.rangeCount===0)return!1;const r=this.getContentEditableElement();if(!r||!e.anchorNode||!r.contains(e.anchorNode)||e.focusNode&&!r.contains(e.focusNode))return!1;const n=this.editor.dataStore;if(!(n!=null&&n.getNode))return!1;const o=s=>{if(!s)return!1;const i=s.nodeType===Node.TEXT_NODE?s.parentElement:s;if(!i)return!1;const a=i.closest("[data-bc-sid]");if(!a)return!1;const c=a.getAttribute("data-bc-sid");if(!c)return!1;const l=n.getNode(c);return l?(l.stype??l.type)==="inline-text":!1};return o(e.anchorNode)&&o(e.focusNode??e.anchorNode)}handleSelectionChange(){var c,l;if(this._isProgrammaticChange)return;const t=window.getSelection();if(!t)return;const e=this.getContentEditableElement();if(!e)return;const r=t.anchorNode,n=t.focusNode;if(!r)return;const o=e.contains(r),s=!n||e.contains(n);if(!o||!s)return;let i=r;for(;i;){if(i instanceof Element&&i.hasAttribute("data-devtool"))return;i=i.parentNode}const a=this.convertDOMSelectionToModel(t);(l=(c=this.editor).updateSelection)==null||l.call(c,a)}convertDOMSelectionToModel(t){if(t.rangeCount===0)return{type:"none"};const e=t.getRangeAt(0),r=this.convertRangeBoundariesToModel(e.startContainer,e.startOffset,e.endContainer,e.endOffset);if(!r)return{type:"none"};const{startNodeId:n,startModelOffset:o,endNodeId:s,endModelOffset:i}=r,a=this.findBestContainer(e.startContainer),c=this.findBestContainer(e.endContainer),l=a&&c?this.determineSelectionDirection(t,a,c,o,i):"forward";return{...Be(n,o,s,i,"range"),direction:l}}convertStaticRangeToModel(t){const e=this.convertRangeBoundariesToModel(t.startContainer,t.startOffset,t.endContainer,t.endOffset);if(!e)return null;const{startNodeId:r,startModelOffset:n,endNodeId:o,endModelOffset:s}=e;return{type:"range",startNodeId:r,startOffset:n,endNodeId:o,endOffset:s,direction:"forward"}}convertRangeBoundariesToModel(t,e,r,n){const o=this.findBestContainer(t),s=this.findBestContainer(r);if(!o||!s)return null;const i=o.getAttribute("data-bc-sid"),a=s.getAttribute("data-bc-sid");if(!i||!a||!this.nodeExistsInModel(i)||!this.nodeExistsInModel(a))return null;const c=this.ensureRuns(o,i),l=o===s?c:this.ensureRuns(s,a),u=this.convertOffsetWithRuns(o,t,e,c,!1),f=this.convertOffsetWithRuns(s,r,n,l,!0);return{startNodeId:i,startModelOffset:u,endNodeId:a,endModelOffset:f}}isTextContainer(t){return t.getAttribute("data-text-container")==="true"}nodeExistsInModel(t){try{const e=this.editor.dataStore;return e?e.getNode(t)!=null:!0}catch{return!1}}findClosestDataNode(t){if(t.nodeType===Node.ELEMENT_NODE){const r=t;if(r.hasAttribute("data-bc-sid"))return r}let e=t.parentElement;for(;e;){if(e.hasAttribute("data-bc-sid"))return e;e=e.parentElement}return null}findBestContainer(t){var o,s,i,a;let e=this.findClosestDataNode(t);if(!e)return null;if(this.isTextContainer(e))return e;let r=e;for(;r;){if(this.isTextContainer(r))return r;r=((s=(o=r.parentElement)==null?void 0:o.closest)==null?void 0:s.call(o,"[data-bc-sid]"))??null}const n=e.getAttribute("data-bc-sid");if(n){const c=(a=(i=this.editor.dataStore)==null?void 0:i.getNode)==null?void 0:a.call(i,n);if((c==null?void 0:c.stype)==="document")return null}return e}ensureRuns(t,e){return St(t,e,{buildReverseMap:!0,excludePredicate:r=>this.isDecoratorElement(r)})}convertOffsetWithRuns(t,e,r,n,o){var a,c;if(n.total===0)return 0;if(e.nodeType===Node.TEXT_NODE){const l=e,u=(a=n.byNode)==null?void 0:a.get(l);if(u){const h=u.end-u.start,g=Math.max(0,Math.min(r,h));return u.start+g}const f=Ot(n.runs,Math.max(0,Math.min(r,n.total-1)));return f>=0?o?n.runs[f].end:n.runs[f].start:0}const s=e,i=this.findTextAtElementBoundary(t,s,r,o);if(i){const l=(c=n.byNode)==null?void 0:c.get(i);if(l)return o?l.end:l.start}return o?n.total:0}findTextAtElementBoundary(t,e,r,n){const o=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),s=e.childNodes.item(r)??null;let i=null,a=null,c=o.nextNode();for(;c;){if(s){if(c.compareDocumentPosition(s)&Node.DOCUMENT_POSITION_FOLLOWING){a=c;break}i=c}else i=c;c=o.nextNode()}return n?i??a:a??i}determineSelectionDirection(t,e,r,n,o){if(e===r)return n<=o?"forward":"backward";const s=t.anchorNode,i=t.focusNode;if(!s||!i)return e.compareDocumentPosition(r)&Node.DOCUMENT_POSITION_FOLLOWING?"forward":"backward";const a=this.findBestContainer(s),c=this.findBestContainer(i);if(a&&c){const u=e.getAttribute("data-bc-sid"),f=r.getAttribute("data-bc-sid"),h=a.getAttribute("data-bc-sid"),g=c.getAttribute("data-bc-sid");if(h===u&&g===f)return"forward";if(h===f&&g===u)return"backward"}return e.compareDocumentPosition(r)&Node.DOCUMENT_POSITION_FOLLOWING?"forward":"backward"}convertModelSelectionToDOM(t){var e;this._isProgrammaticChange=!0;try{if(!t||t.type==="none"){(e=window.getSelection())==null||e.removeAllRanges();return}t.type==="range"?this.convertRangeSelectionToDOM(t):t.type==="node"&&this.convertNodeSelectionToDOM(t)}finally{setTimeout(()=>{this._isProgrammaticChange=!1},0)}}convertRangeSelectionToDOM(t){var N,x;const{startNodeId:e,startOffset:r,endNodeId:n,endOffset:o}=t,s=this._getScopeRoot(),i=s.querySelector(`[data-bc-sid="${e}"]`),a=s.querySelector(`[data-bc-sid="${n}"]`);if(!i||!a)return;const c=this.findBestContainer(i),l=this.findBestContainer(a);if(!c||!l)return;const u=this.getTextRunsForContainer(c),f=this.getTextRunsForContainer(l);let h=(N=u==null?void 0:u.runs)!=null&&N.length?this.findDOMRangeFromModelOffset(u,r):null,g=(x=f==null?void 0:f.runs)!=null&&x.length?this.findDOMRangeFromModelOffset(f,o):null;h||(h={node:i,offset:Math.min(r,i.childNodes.length)}),g||(g={node:a,offset:Math.min(o,a.childNodes.length)});const m=window.getSelection();if(!m)return;m.removeAllRanges();const p=document.createRange();p.setStart(h.node,h.offset),p.setEnd(g.node,g.offset),m.addRange(p)}convertNodeSelectionToDOM(t){const r=this._getScopeRoot().querySelector(`[data-bc-sid="${t.nodeId}"]`);if(!r)return;const n=window.getSelection();if(!n)return;n.removeAllRanges();const o=document.createRange();o.selectNodeContents(r),n.addRange(o)}getTextRunsForContainer(t){try{const e=t.getAttribute("data-bc-sid");return St(t,e??void 0,{buildReverseMap:!0,excludePredicate:r=>this.isDecoratorElement(r),normalizeWhitespace:!1})}catch{return null}}isDecoratorElement(t){return t.hasAttribute("data-decorator-sid")||t.hasAttribute("data-bc-decorator-sid")||t.hasAttribute("data-bc-decorator")||t.hasAttribute("data-decorator-category")}findDOMRangeFromModelOffset(t,e){var i,a;if(e<0||e>t.total)return null;if(e===t.total){const c=t.runs[t.runs.length-1];return{node:c.domTextNode,offset:((i=c.domTextNode.textContent)==null?void 0:i.length)??0}}const r=t.runs.length;if(r===0)return null;let n=Ot(t.runs,e);if(n===-1){let c=-1;for(let l=0;l<r;l+=1){const u=t.runs[l];if(e<u.start){c=l;break}if(e===u.end&&l+1<r){c=l+1;break}}if(c===-1)return null;n=c}const o=t.runs[n],s=e-o.start;return{node:o.domTextNode,offset:Math.min(s,((a=o.domTextNode.textContent)==null?void 0:a.length)??0)}}}function pn(d,t){if(d===t)return{kind:"none",start:0,end:0,inserted:"",deleted:""};let e=0;const r=Math.min(d.length,t.length);for(;e<r&&d.charCodeAt(e)===t.charCodeAt(e);)e++;let n=0;const o=d.length-e,s=t.length-e;for(;n<o&&n<s&&d.charCodeAt(d.length-1-n)===t.charCodeAt(t.length-1-n);)n++;const i=e,a=d.length-n,c=d.slice(i,a),l=t.slice(e,t.length-n);return!c&&!l?{kind:"none",start:i,end:a,inserted:"",deleted:""}:c?l?{kind:"replace",start:i,end:a,inserted:l,deleted:c}:{kind:"delete",start:i,end:a,inserted:"",deleted:c}:{kind:"insert",start:i,end:i,inserted:l,deleted:""}}function mn(d,t,e,r,n){const{kind:o,start:s,end:i,inserted:a,deleted:c}=e;if(o==="none")return[];const l=n===0,u=r,f=r+n;let h=s,g=i,m=a,p=c;if(o==="replace"&&a.length===1&&c.length===1){const x=l?u:Math.floor((u+f)/2),S=Math.min(3,Math.floor(d.length*.05)),b=Math.max(0,x-S),v=Math.min(d.length-1,x+S);for(let I=b;I<=v;I++){if(!l&&(I<u||I>=f))continue;if(d.slice(0,I)+a+d.slice(I+1)===t){h=I,g=I+1,p=d[I];break}}}else if(o==="delete"){const x=i-s,S=l?u:Math.floor((u+f)/2),b=Math.min(6,Math.floor(d.length*.1));let v=s,I=Math.abs(S-(s+Math.floor(x/2))),_=0;const C=Math.max(0,S-b),D=Math.min(d.length-x,S+b);for(let w=C;w<=D;w++){if(d.slice(0,w)+d.slice(w+x)!==t)continue;const T=w,A=w+x,R=l?S>=T&&S<=A?1:0:Math.max(0,Math.min(A,f)-Math.max(T,u)),k=w+Math.floor(x/2),L=Math.abs(S-k);(R>_||R===_&&L<I)&&(_=R,I=L,v=w)}h=v,g=v+x,p=d.slice(h,g)}const N=[];return o==="insert"?N.push({type:"insert",start:h,end:h,text:m,confidence:1}):o==="delete"?N.push({type:"delete",start:h,end:h+p.length,text:"",confidence:1}):o==="replace"&&N.push({type:"replace",start:h,end:h+p.length,text:m,confidence:1}),N}function Bt(d,t){if(t<=0||t>=d.length)return!0;const e=d.codePointAt(t-1),r=d.codePointAt(t);return!e||!r?!0:!(e>=55296&&e<=56319||r>=56320&&r<=57343||r>=768&&r<=879||r>=6832&&r<=6911||r>=7616&&r<=7679||r>=8400&&r<=8447||r>=65056&&r<=65071)}function Pt(d,t,e){let r=Math.max(0,Math.min(d.length,t));if(e==="left")for(;r>0&&!Bt(d,r);)r--;else for(;r<d.length&&!Bt(d,r);)r++;return r}function yn(d){const{oldText:t,newText:e,selectionOffset:r,selectionLength:n=0}=d,o=t.normalize("NFC"),s=e.normalize("NFC");if(o===s)return[];const i=pn(o,s);return mn(o,s,i,r,n).map(l=>({...l,start:Pt(o,l.start,"left"),end:Pt(o,l.end,"right")}))}function re(d){let t=d;for(;t;){if(t.nodeType===Node.ELEMENT_NODE){const e=t;if(e.getAttribute("data-bc-sid"))return e}t=t.parentNode}return null}function ne(d){return St(d,void 0,{normalizeWhitespace:!1}).runs.map(e=>e.domTextNode.textContent??"").join("")}function Nn(d,t){var e,r;if(d.length===0)return null;for(const n of d){const o=n.target,s=re(o);if(!s)continue;const i=s.getAttribute("data-bc-sid");if(!i)continue;const a=(r=(e=t.editor.dataStore)==null?void 0:e.getNode)==null?void 0:r.call(e,i);if(!a||a.stype!=="inline-text"||n.type==="childList"&&[...Array.from(n.addedNodes??[]),...Array.from(n.removedNodes??[])].some(N=>{if(N.nodeType!==Node.ELEMENT_NODE)return!1;const x=N.tagName.toLowerCase();return["p","div","li","ul","ol","h1","h2","h3","h4","h5","h6","blockquote"].includes(x)}))continue;const c=a.text??"",l=ne(s);let u,f,h=!1;const g=t.inputHint;return(g==null?void 0:g.contentRange.startNodeId)===i&&g.contentRange.endNodeId===i&&(u=Math.max(0,Math.min(c.length,g.contentRange.startOffset)),f=Math.max(u,Math.min(c.length,g.contentRange.endOffset)),h=!0),{case:"C1",nodeId:i,prevText:c,newText:l,contentRange:u!==void 0&&f!==void 0?{startNodeId:i,startOffset:u,endNodeId:i,endOffset:f}:void 0,mutations:[n],metadata:h?{usedInputHint:!0}:void 0}}return null}function Sn(d){const t=["insertParagraph","insertLineBreak"],e=["historyUndo","historyRedo"];return t.includes(d)||e.includes(d)}function xn(d){return["formatBold","formatItalic","formatUnderline","formatStrikeThrough"].includes(d)}function In(d){return["deleteContentBackward","deleteContentForward","deleteWordBackward","deleteWordForward","deleteByCut","deleteByDrag"].includes(d)}class wn{constructor(t,e,r){y(this,"editor");y(this,"selectionHandler");y(this,"viewStateRef");y(this,"_isComposing",!1);y(this,"_pendingInsertHint",null);y(this,"_compositionWindowMs",120);y(this,"_compositionGeneration",0);y(this,"_compositionSyncToken",0);y(this,"_isCompositionSyncScheduled",!1);y(this,"_contentChangeTxSeq",0);this.editor=t,this.selectionHandler=e,this.viewStateRef=r}_buildDebugTransaction(t=[],e){return{sid:`tx-viewreact-${Date.now()}-${++this._contentChangeTxSeq}`,timestamp:new Date,operations:t,description:e}}markPostCompositionWindow(){this.viewStateRef.current.compositionWindowUntil=Date.now()+this._compositionWindowMs}clearPostCompositionWindow(){this.viewStateRef.current.compositionWindowUntil=0}isPostCompositionWindowActive(){return this.viewStateRef.current.compositionWindowUntil>Date.now()}isImePhase(t){return this._isComposing||this.viewStateRef.current.isComposing||t?!0:this.isPostCompositionWindowActive()}setImeComposingState(t,e=!0){this._isComposing!==t&&(this._compositionGeneration+=1,this._compositionSyncToken=this._compositionGeneration,t?(this._isCompositionSyncScheduled=!1,e&&this.clearPostCompositionWindow()):(this._isCompositionSyncScheduled=!0,this.markPostCompositionWindow())),this._isComposing=t,this.viewStateRef.current.isComposing=t}requestCompositionEndSync(){requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.syncFocusedTextNodeAfterComposition()})})}setComposing(t){const e=this._isComposing;this.setImeComposingState(t),e&&!t&&this.requestCompositionEndSync()}handleInput(t){const e=this._isComposing;t.isComposing!==void 0&&(this.setImeComposingState(t.isComposing),e&&!t.isComposing&&this.requestCompositionEndSync())}handlePaste(t){var r;if(this.isImePhase())return;t.preventDefault();const e=((r=t.clipboardData)==null?void 0:r.getData("text/plain"))??"";e&&this.insertTextAtSelection(e)}handleDrop(t){var r;if(this.isImePhase())return;t.preventDefault();const e=((r=t.dataTransfer)==null?void 0:r.getData("text/plain"))??"";e&&this.insertTextAtSelection(e)}async syncFocusedTextNodeAfterComposition(){var m,p,N,x,S;const t=this._compositionSyncToken,e=this._compositionGeneration,r=()=>{t===this._compositionSyncToken&&e===this._compositionGeneration&&(this._isCompositionSyncScheduled=!1,this._compositionSyncToken+=1)};if(!this._isCompositionSyncScheduled||this._isComposing||this.viewStateRef.current.isComposing)return;const n=this.viewStateRef.current;if(t!==this._compositionSyncToken||e!==this._compositionGeneration||n.isModelDrivenChange||n.isRendering)return;if(this.isPostCompositionWindowActive()){setTimeout(()=>{this.syncFocusedTextNodeAfterComposition()},Math.max(0,n.compositionWindowUntil-Date.now()));return}const o=window.getSelection();if(!(o!=null&&o.rangeCount)||!o.anchorNode){r();return}const s=re(o.anchorNode);if(!s)return;const i=s.getAttribute("data-bc-sid");if(!i){r();return}const a=this.editor.dataStore,c=(m=a==null?void 0:a.getNode)==null?void 0:m.call(a,i);if(!c||c.stype!=="inline-text"){r();return}const l=c.text??"",u=ne(s);if(l===u){r();return}const f={type:"range",startNodeId:i,startOffset:0,endNodeId:i,endOffset:l.length};this.viewStateRef.current.skipNextRenderFromMO=!0;let h=!1;try{h=await this.editor.executeCommand("replaceText",{range:f,text:u})}finally{this.viewStateRef.current.skipNextRenderFromMO=!1}if(!h){r();return}const g=window.getSelection();if(g!=null&&g.rangeCount){this.viewStateRef.current.skipApplyModelSelectionToDOM=!0;try{const b=this.selectionHandler.convertDOMSelectionToModel(g);if(b.type==="range"){const v={type:"range",startNodeId:b.startNodeId,startOffset:b.startOffset,endNodeId:b.endNodeId,endOffset:b.endOffset,collapsed:b.startNodeId===b.endNodeId&&b.startOffset===b.endOffset};(N=(p=this.editor).updateSelection)==null||N.call(p,v)}}catch{}finally{setTimeout(()=>{this.viewStateRef.current.skipApplyModelSelectionToDOM=!1},0)}}(S=(x=this.editor).emit)==null||S.call(x,"editor:content.change",{skipRender:!0,from:"compositionend-sync",content:this.editor.document,transaction:this._buildDebugTransaction([{type:"replaceText",payload:{nodeId:i,range:f}}],"compositionend-sync")}),r()}async handleDomMutations(t){const e=this.viewStateRef.current;if(!(e.isModelDrivenChange||e.isRendering)&&!this.isImePhase()){this.viewStateRef.current.skipNextRenderFromMO=!0;try{await this.handleDomMutationsInner(t)}finally{this.viewStateRef.current.skipNextRenderFromMO=!1}}}async handleDomMutationsInner(t){const e=this.viewStateRef.current,r=window.getSelection();let n;if(r!=null&&r.rangeCount)try{const i=this.selectionHandler.convertDOMSelectionToModel(r);i.type==="range"&&(n={type:"range",startNodeId:i.startNodeId,startOffset:i.startOffset,endNodeId:i.endNodeId,endOffset:i.endOffset})}catch{}const o=this.getValidInsertHint(e.isComposing||this.isPostCompositionWindowActive()),s=Nn(t,{editor:this.editor,inputHint:o??void 0,isComposing:e.isComposing});(s==null?void 0:s.case)==="C1"&&await this.handleC1(s)}getValidInsertHint(t){const e=this._pendingInsertHint;return!e||t||Date.now()-e.timestamp>500?null:e}async handleC1(t){var i,a,c,l,u,f,h;if(!t.nodeId||!t.prevText||t.newText===void 0)return;const e=window.getSelection(),r=e!=null&&e.rangeCount?e.getRangeAt(0).startOffset:0,n=yn({oldText:t.prevText,newText:t.newText,selectionOffset:r,selectionLength:0});if(n.length===0)return;const o=n[0],s=t.contentRange&&((i=t.metadata)!=null&&i.usedInputHint)?t.contentRange:{startNodeId:t.nodeId,startOffset:o.start,endNodeId:t.nodeId,endOffset:o.end};this.viewStateRef.current.skipApplyModelSelectionToDOM=!0;try{if(o.type==="delete"){if(!(s.startNodeId===s.endNodeId?await this.editor.executeCommand("deleteText",{range:s}):await this.editor.executeCommand("deleteCrossNode",{range:s})))return;const m={type:"range",startNodeId:s.startNodeId,startOffset:s.startOffset,endNodeId:s.startNodeId,endOffset:s.startOffset,collapsed:!0};(c=(a=this.editor).updateSelection)==null||c.call(a,m)}else{if(!await this.editor.executeCommand("replaceText",{range:s,text:o.text??""}))return;const m=(o.text??"").length,p={type:"range",startNodeId:s.startNodeId,startOffset:s.startOffset+m,endNodeId:s.startNodeId,endOffset:s.startOffset+m,collapsed:!0};(u=(l=this.editor).updateSelection)==null||u.call(l,p)}}finally{setTimeout(()=>{this.viewStateRef.current.skipApplyModelSelectionToDOM=!1},0)}(h=(f=this.editor).emit)==null||h.call(f,"editor:content.change",{skipRender:!0,from:"MutationObserver-C1",content:this.editor.document,transaction:this._buildDebugTransaction([{type:"replaceText",payload:{nodeId:t.nodeId,range:t.contentRange}}],"MutationObserver-C1")}),this._pendingInsertHint=null}handleBeforeInput(t){const e=t.isComposing,r=this._isComposing;if(e!==void 0){if(this.setImeComposingState(e),e&&!this.selectionHandler.isSelectionInsideEditableText()){t.preventDefault();return}r&&!e&&(this.clearPostCompositionWindow(),this.requestCompositionEndSync())}const n=this.isImePhase(e),o=t.inputType;if(Sn(o)){t.preventDefault(),this.executeStructuralCommand(o);return}if(xn(o)){t.preventDefault(),this.executeFormatCommand(o);return}if(In(o)&&!n){t.preventDefault(),this.handleDelete(t);return}if(o==="insertText"){this.updateInsertHintFromBeforeInput(t);return}if(["insertFromPaste","insertReplacementText"].includes(o)){if(this.tryHandleInsertViaGetTargetRanges(t))return;this.updateInsertHintFromBeforeInput(t)}}updateInsertHintFromBeforeInput(t){if(this.isImePhase(t.isComposing))return;const e=window.getSelection();if(!(e!=null&&e.rangeCount)){this._pendingInsertHint=null;return}try{const r=this.selectionHandler.convertDOMSelectionToModel(e);if(r.type!=="range"){this._pendingInsertHint=null;return}this._pendingInsertHint={contentRange:{startNodeId:r.startNodeId,startOffset:r.startOffset,endNodeId:r.endNodeId,endOffset:r.endOffset},timestamp:Date.now()}}catch{this._pendingInsertHint=null}}handleKeydown(t){var o,s,i,a;if(this._isComposing)return;if(t.keyCode===229){this.markPostCompositionWindow(),this.setImeComposingState(!0,!1);return}if(this.isImePhase())return;if(t.key.length===1&&!["Enter","Tab","Escape"].includes(t.key)&&!t.ctrlKey&&!t.metaKey&&t.keyCode!==229&&!this.selectionHandler.isSelectionInsideEditableText()){t.preventDefault();return}const r=_e(t);if(r==="Space"&&!t.ctrlKey&&!t.metaKey&&!t.altKey)return;const n=(s=(o=this.editor.keybindings)==null?void 0:o.resolve)==null?void 0:s.call(o,r);if(n!=null&&n.length){const{command:c,args:l}=n[0];t.preventDefault();const u=window.getSelection();if(u&&u.rangeCount>0)try{const f=this.selectionHandler.convertDOMSelectionToModel(u);f&&f.type==="range"&&((a=(i=this.editor).updateSelection)==null||a.call(i,f))}catch{}this.editor.executeCommand(c,l??{})}}insertTextAtSelection(t){const e=window.getSelection();if(!e||e.rangeCount===0)return;const r=this.selectionHandler.convertDOMSelectionToModel(e);if(!r||r.type!=="range")return;const n={type:"range",startNodeId:r.startNodeId,startOffset:r.startOffset,endNodeId:r.endNodeId,endOffset:r.endOffset};this.editor.executeCommand("replaceText",{range:n,text:t}).then(o=>{var i,a;if(!o)return;const s={type:"range",startNodeId:r.startNodeId,startOffset:r.startOffset+t.length,endNodeId:r.startNodeId,endOffset:r.startOffset+t.length};(a=(i=this.editor).updateSelection)==null||a.call(i,s),this.applyModelSelectionAfterRender(s)}).catch(()=>{})}tryHandleInsertViaGetTargetRanges(t){const e=t.inputType;if(!["insertText","insertFromPaste","insertReplacementText"].includes(e)||this.isImePhase(t.isComposing))return!1;const r=t.getTargetRanges;if(typeof r!="function")return!1;const n=r.call(t);if(!(n!=null&&n.length))return!1;const o=n[0],s=this.selectionHandler.convertStaticRangeToModel(o);if(!s||s.type!=="range")return!1;const i=this.editor.dataStore;if(!i)return!1;const a=i.getNode(s.startNodeId),c=i.getNode(s.endNodeId);if(!((a==null?void 0:a.stype)==="inline-text"&&(c==null?void 0:c.stype)==="inline-text"))return t.preventDefault(),!0;const u=t.data??"",f={type:"range",startNodeId:s.startNodeId,startOffset:s.startOffset,endNodeId:s.endNodeId,endOffset:s.endOffset};return t.preventDefault(),this.editor.executeCommand("replaceText",{range:f,text:u}).then(h=>{var p,N,x,S;if(!h)return;const g=u.length,m={type:"range",startNodeId:s.startNodeId,startOffset:s.startOffset+g,endNodeId:s.startNodeId,endOffset:s.startOffset+g};(N=(p=this.editor).updateSelection)==null||N.call(p,m),(S=(x=this.editor).emit)==null||S.call(x,"editor:content.change",{skipRender:!1,from:"getTargetRanges",content:this.editor.document,transaction:this._buildDebugTransaction([{type:"replaceText",payload:{...f}}],"getTargetRanges")}),this.applyModelSelectionAfterRender(m)}).catch(()=>{}),!0}applyModelSelectionAfterRender(t){requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.selectionHandler.convertModelSelectionToDOM(t)})})}async handleDelete(t){var a,c,l,u,f,h;const e=window.getSelection();if(!e||e.rangeCount===0)return;let r=null;try{r=this.selectionHandler.convertDOMSelectionToModel(e)}catch{return}if(!r||r.type!=="range")return;const n=r;(c=(a=this.editor).updateSelection)==null||c.call(a,n);const o=this.calculateDeleteRange(n,t.inputType,n.startNodeId);if(!o)return;let s=!1;if(o._deleteNode&&o.nodeId?s=await this.editor.executeCommand("deleteNode",{nodeId:o.nodeId}):o.startNodeId!==o.endNodeId?s=await this.editor.executeCommand("deleteCrossNode",{range:o}):s=await this.editor.executeCommand("deleteText",{range:o}),!s)return;const i={type:"range",startNodeId:o.startNodeId,startOffset:o.startOffset,endNodeId:o.startNodeId,endOffset:o.startOffset,collapsed:!0};(u=(l=this.editor).emit)==null||u.call(l,"editor:selection.change",{selection:i,oldSelection:r}),(h=(f=this.editor).emit)==null||h.call(f,"editor:content.change",{skipRender:!1,from:"beforeinput-delete",content:this.editor.document,transaction:this._buildDebugTransaction([{type:"deleteText",payload:{range:o}}],"beforeinput-delete")}),this.applyModelSelectionAfterRender(i)}calculateDeleteRange(t,e,r){var c,l,u;const{startNodeId:n,startOffset:o,endNodeId:s,endOffset:i}=t;if(!(n===s&&o===i))return{type:"range",startNodeId:n,startOffset:o,endNodeId:s,endOffset:i};switch(e){case"deleteContentBackward":return o>0?{type:"range",startNodeId:n,startOffset:o-1,endNodeId:s,endOffset:o}:this.calculateCrossNodeDeleteRange(n,"backward");case"deleteContentForward":{const f=(l=(c=this.editor.dataStore)==null?void 0:c.getNode)==null?void 0:l.call(c,n),h=((u=f==null?void 0:f.text)==null?void 0:u.length)??0;return o<h?{type:"range",startNodeId:n,startOffset:o,endNodeId:s,endOffset:o+1}:this.calculateCrossNodeDeleteRange(n,"forward")}case"deleteWordBackward":case"deleteWordForward":return this.calculateDeleteRange(t,e==="deleteWordBackward"?"deleteContentBackward":"deleteContentForward",r);case"deleteByCut":case"deleteByDrag":return{type:"range",startNodeId:n,startOffset:o,endNodeId:s,endOffset:i};default:return null}}calculateCrossNodeDeleteRange(t,e){const r=this.editor.dataStore;if(!(r!=null&&r.getNode)||!(r!=null&&r.getParent))return null;const n=r.getNode(t);if(!n||n.text===void 0||typeof n.text!="string")return null;const o=r.getParent(t);if(!(o!=null&&o.content))return null;const s=o.content.indexOf(t);if(s===-1)return null;const i=e==="backward"?s-1:s+1;if(i<0||i>=o.content.length)return null;const a=o.content[i],c=r.getNode(a);if(!c)return null;const l=r.getParent(a);if(!l||l.sid!==o.sid)return null;const u=r.schema;if(u!=null&&u.getNodeType){const h=c.stype??c.type,g=h?u.getNodeType(h):void 0;if((g==null?void 0:g.group)==="block")return null}if(c.text===void 0||typeof c.text!="string")return{type:"range",startNodeId:"",startOffset:0,endNodeId:"",endOffset:0,_deleteNode:!0,nodeId:a};const f=(c.text??"").length;return e==="backward"?f===0?null:{type:"range",startNodeId:a,startOffset:f-1,endNodeId:a,endOffset:f}:f===0?null:{type:"range",startNodeId:a,startOffset:0,endNodeId:a,endOffset:1}}executeStructuralCommand(t){switch(t){case"insertParagraph":this.insertParagraph();break;case"insertLineBreak":this.insertText(`
|
|
10
|
+
`);break;case"historyUndo":this.editor.executeCommand("historyUndo",{});break;case"historyRedo":this.editor.executeCommand("historyRedo",{});break}}insertParagraph(){var r,n;const t=window.getSelection();if(!t||t.rangeCount===0){this.editor.executeCommand("insertParagraph",{}).catch(()=>{});return}let e;try{e=this.selectionHandler.convertDOMSelectionToModel(t)}catch{this.editor.executeCommand("insertParagraph",{}).catch(()=>{});return}if(!e||e.type==="none"){this.editor.executeCommand("insertParagraph",{}).catch(()=>{});return}(n=(r=this.editor).updateSelection)==null||n.call(r,e),this.editor.executeCommand("insertParagraph",{selection:e}).catch(()=>{})}insertText(t){const e=window.getSelection();if(!e||e.rangeCount===0){this.editor.executeCommand("insertText",{text:t});return}const r=this.selectionHandler.convertDOMSelectionToModel(e);if(!r||r.type==="none"){this.editor.executeCommand("insertText",{text:t});return}this.editor.executeCommand("insertText",{text:t,selection:r})}executeFormatCommand(t){var n,o;const r={formatBold:"toggleBold",formatItalic:"toggleItalic",formatUnderline:"toggleUnderline",formatStrikeThrough:"toggleStrikeThrough"}[t];r&&((o=(n=this.editor).emit)==null||o.call(n,"editor:command.execute",{command:r,data:void 0}),this.editor.executeCommand(r,{}))}}function oe(d){let t=null,e=[],r=null;return{setup(n){t&&(t.disconnect(),t=null),r!=null&&(clearTimeout(r),r=null),e=[],t=new MutationObserver(o=>{e.push(...o),r!=null&&clearTimeout(r),r=window.setTimeout(()=>{e.length>0&&(d([...e]),e=[]),r=null},0)}),t.observe(n,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["data-bc-edit","data-bc-value","data-bc-sid","data-bc-stype"],characterDataOldValue:!0,attributeOldValue:!0})},disconnect(){t&&(t.disconnect(),t=null),r!=null&&(clearTimeout(r),r=null),e=[]}}}const _t=O.createContext(null);function ht(){const d=O.useContext(_t);if(!d)throw new Error("useEditorViewContext must be used within EditorViewContext.Provider");return d}function vn(){return O.useContext(_t)}function se({editor:d,children:t}){const e=O.useRef({isModelDrivenChange:!1,isRendering:!1,isComposing:!1,compositionWindowUntil:0,skipNextRenderFromMO:!1,skipApplyModelSelectionToDOM:!1}),r=O.useRef(null),n=O.useCallback(()=>r.current,[]),o=O.useRef(null);o.current===null&&(o.current=new Re);const s=O.useRef(null);s.current===null&&(s.current=new Te(o.current));const i=O.useRef(null);i.current===null&&(i.current=new Oe);const a=O.useRef(null);a.current===null&&(a.current=new Ce);const c=O.useRef(null);c.current===null&&(c.current=new De);const[l,u]=O.useState(0),f=O.useCallback(()=>u(S=>S+1),[]);O.useEffect(()=>{const S=s.current;if(S)return S.on("decorator:added",f),S.on("decorator:updated",f),S.on("decorator:removed",f),()=>{S.off("decorator:added",f),S.off("decorator:updated",f),S.off("decorator:removed",f)}},[f]),O.useEffect(()=>{const S=i.current;if(S)return S.on("change",f),()=>S.off("change",f)},[f]);const h=O.useCallback(S=>{var w,M,T;const b=((w=s.current)==null?void 0:w.getAll())??[],v=((M=i.current)==null?void 0:M.getAll())??[],I=((T=a.current)==null?void 0:T.getConfigs(!0))??[],_=Me(S,I),C=c.current;let D=[];if(C&&S&&typeof S=="object"){const A=S,R=k=>{const L=typeof k.text=="string"?k.text:null;D.push(...C.generateDecorators(k,L,{documentModel:A}));const P=k.children??k.content;if(Array.isArray(P))for(const F of P)F&&typeof F=="object"&&R(F)};R(A)}return[...b,...v,..._,...D]},[]),g=O.useMemo(()=>new gn(d,n),[d,n]),m=O.useMemo(()=>new wn(d,g,e),[d,g]),p=O.useMemo(()=>oe(S=>{m.handleDomMutations(S)}),[m]),N=O.useCallback(S=>{r.current!==S&&(r.current&&p.disconnect(),r.current=S,S&&p.setup(S))},[p]);O.useEffect(()=>{const S=()=>g.handleSelectionChange();return document.addEventListener("selectionchange",S),()=>document.removeEventListener("selectionchange",S)},[g]);const x=O.useMemo(()=>({editor:d,viewStateRef:e,selectionHandler:g,inputHandler:m,mutationObserverManager:p,setContentEditableElement:N,contentEditableRef:r,decoratorManagerRef:s,decoratorSchemaRegistryRef:o,remoteDecoratorManagerRef:i,patternDecoratorConfigManagerRef:a,decoratorGeneratorManagerRef:c,getMergedDecorators:h,bumpDecoratorVersion:f,decoratorVersion:l}),[d,e,g,m,p,N,r,s,o,i,a,c,h,f,l]);return B.jsx(_t.Provider,{value:x,children:t})}function bt({options:d={}}){const{editor:t,inputHandler:e,viewStateRef:r,setContentEditableElement:n,selectionHandler:o,getMergedDecorators:s,decoratorVersion:i}=ht(),{className:a="",editable:c=!0,registry:l}=d,[u,f]=O.useState(()=>{var _;return((_=t.getDocumentProxy)==null?void 0:_.call(t))??null}),h=O.useRef(null),g=O.useRef(null);O.useEffect(()=>{var C,D;const _=w=>{var T,A;if(w!=null&&w.skipRender)return;if((T=r==null?void 0:r.current)!=null&&T.skipNextRenderFromMO){r.current.skipNextRenderFromMO=!1;return}g.current!==null&&window.cancelAnimationFrame(g.current),r.current&&(r.current.isModelDrivenChange=!0,r.current.isRendering=!0);const M=(w==null?void 0:w.content)??((A=t.getDocumentProxy)==null?void 0:A.call(t))??null;f(M),g.current=window.requestAnimationFrame(()=>{g.current=null,r.current&&(r.current.isModelDrivenChange=!1,r.current.isRendering=!1)})};return(C=t.on)==null||C.call(t,"editor:content.change",_),f(((D=t.getDocumentProxy)==null?void 0:D.call(t))??null),()=>{var w;(w=t.off)==null||w.call(t,"editor:content.change",_),g.current!==null&&window.cancelAnimationFrame(g.current),r.current&&(r.current.isModelDrivenChange=!1,r.current.isRendering=!1)}},[t,r]),O.useEffect(()=>{const _=h.current;return n(_),()=>n(null)},[n]),O.useEffect(()=>{var C;const _=D=>{var k;const w=typeof D=="object"&&D!==null&&Object.prototype.hasOwnProperty.call(D,"selection"),M=typeof D=="object"&&D!==null&&Object.prototype.hasOwnProperty.call(D,"source")?D.source:void 0,T=w?D.selection:D,A=w?M==="remote"?!1:D.applySelectionToView!==!1:!0;M!=="remote"&&A&&((k=r==null?void 0:r.current)!=null&&k.skipApplyModelSelectionToDOM||requestAnimationFrame(()=>{requestAnimationFrame(()=>{o.convertModelSelectionToDOM(T)})}))};return(C=t.on)==null||C.call(t,"editor:selection.model",_),()=>{var D;return(D=t.off)==null?void 0:D.call(t,"editor:selection.model",_)}},[t,o,r]);const m=O.useMemo(()=>new zt(l??Z()),[l]),p=O.useMemo(()=>s(u),[u,s,i]),N=O.useMemo(()=>{if(u==null)return null;const _=u;return _.stype?m.build(_,p):null},[u,m,p]),x=_=>{const C=_.nativeEvent;e.handleBeforeInput(C)},S=_=>{const C=_.nativeEvent;e.handleInput(C)},b=_=>{e.handleKeydown(_.nativeEvent)},v=_=>{const C=_.nativeEvent;e.handlePaste(C)},I=_=>{const C=_.nativeEvent;e.handleDrop(C)};return B.jsx("div",{ref:h,className:a,contentEditable:c,suppressContentEditableWarning:!0,"data-bc-layer":"content","data-testid":"editor-content",onInput:S,onBeforeInput:x,onKeyDown:b,onPaste:v,onDrop:I,children:N})}const _n={decorator:{className:"barocss-editor-decorators",zIndex:10},selection:{className:"barocss-editor-selection",zIndex:100},context:{className:"barocss-editor-context",zIndex:200},custom:{className:"barocss-editor-custom",zIndex:1e3}};function X({layer:d,className:t,style:e,children:r}){const n=_n[d]??{className:"",zIndex:0},o={position:"absolute",top:0,left:0,right:0,bottom:0,pointerEvents:"none",zIndex:n.zIndex};return B.jsx("div",{className:t??n.className,style:e?{...o,...e}:o,"data-bc-layer":d,children:r})}function gt({layer:d,registry:t}){const{editor:e,getMergedDecorators:r,decoratorVersion:n}=ht(),[o,s]=O.useState(()=>{var l;return((l=e.getDocumentProxy)==null?void 0:l.call(e))??null});O.useEffect(()=>{var u,f;const l=()=>{var h;return s(((h=e.getDocumentProxy)==null?void 0:h.call(e))??null)};return(u=e.on)==null||u.call(e,"editor:content.change",l),s(((f=e.getDocumentProxy)==null?void 0:f.call(e))??null),()=>{var h;return(h=e.off)==null?void 0:h.call(e,"editor:content.change",l)}},[e]);const i=O.useMemo(()=>new zt(t??Z()),[t]),a=O.useMemo(()=>r(o),[o,r,n]),c=O.useMemo(()=>a.filter(l=>(l.layerTarget??"content")===d),[a,d]);return B.jsx(B.Fragment,{children:i.buildOverlayDecorators(c)})}function bn({registry:d,className:t,style:e}){return B.jsx(X,{layer:"decorator",className:t,style:e,children:B.jsx(gt,{layer:"decorator",registry:d})})}function kn({registry:d,className:t,style:e}){return B.jsx(X,{layer:"selection",className:t,style:e,children:B.jsx(gt,{layer:"selection",registry:d})})}function En({registry:d,className:t,style:e}){return B.jsx(X,{layer:"context",className:t,style:e,children:B.jsx(gt,{layer:"context",registry:d})})}function Tn({registry:d,className:t,style:e,children:r}){return B.jsxs(X,{layer:"custom",className:t,style:e,children:[B.jsx(gt,{layer:"custom",registry:d}),r]})}const On=O.forwardRef(function({options:t={},children:e},r){var x,S,b,v,I,_,C,D;const{editor:n,selectionHandler:o,contentEditableRef:s,decoratorManagerRef:i,decoratorSchemaRegistryRef:a,remoteDecoratorManagerRef:c,patternDecoratorConfigManagerRef:l,decoratorGeneratorManagerRef:u,getMergedDecorators:f,bumpDecoratorVersion:h}=ht(),g=O.useRef(null);O.useImperativeHandle(r,()=>(g.current||(g.current={addDecorator(w){var M,T;if("generate"in w){(M=u.current)==null||M.registerGenerator(w,h),h();return}(T=i.current)==null||T.add(w)},removeDecorator(w){var M;try{(M=i.current)==null||M.remove(w)}catch{}},updateDecorator(w,M){var T;(T=i.current)==null||T.update(w,M)},getDecorators(w){var k;const M=((k=n.getDocumentProxy)==null?void 0:k.call(n))??null;let T=f(M);(w==null?void 0:w.enabledOnly)!==!1&&(T=T.filter(L=>L.enabled!==!1)),w!=null&&w.category&&(T=T.filter(L=>L.category===w.category)),w!=null&&w.type&&(T=T.filter(L=>L.stype===w.type)),w!=null&&w.nodeId&&(T=T.filter(L=>{const P=L.target;if(!P)return!1;const F="sid"in P?P.sid:void 0,G="startSid"in P?P.startSid:void 0,tt="endSid"in P?P.endSid:void 0;return F===w.nodeId||G===w.nodeId||tt===w.nodeId}));const A=(w==null?void 0:w.sortBy)??"id",R=(w==null?void 0:w.sortOrder)??"asc";if(A){const L=R==="desc"?-1:1;T=[...T].sort((P,F)=>{const G=A==="id"?P.sid:A==="type"?P.stype:P.category,tt=A==="id"?F.sid:A==="type"?F.stype:F.category;return G.localeCompare(tt)*L})}return T},getDecorator(w){var R,k,L;const T=f(((R=n.getDocumentProxy)==null?void 0:R.call(n))??null).find(P=>P.sid===w);if(T)return T;const A=(k=i.current)==null?void 0:k.get(w);return A||((L=c.current)==null?void 0:L.get(w))},exportDecorators(){var A,R;const w=(((A=i.current)==null?void 0:A.getAll())??[]).filter(k=>k.decoratorType!=="pattern").map(k=>{const{decoratorType:L,...P}=k;return P}),T=(((R=l.current)==null?void 0:R.getConfigs())??[]).filter(k=>k.pattern instanceof RegExp).map(k=>({sid:k.sid,stype:k.stype,category:k.category,pattern:{source:k.pattern.source,flags:k.pattern.flags},priority:k.priority,enabled:k.enabled}));return{version:"1.0.0",targetDecorators:w,patternDecorators:T}},loadDecorators(w,M){var T,A,R,k,L,P;(T=i.current)==null||T.clear(),(A=c.current)==null||A.clear(),(R=l.current)==null||R.clear(),(k=u.current)==null||k.clear();for(const F of w.targetDecorators)(L=i.current)==null||L.add({...F,decoratorType:"target"});for(const F of w.patternDecorators){const G=M==null?void 0:M[F.sid];if(!G){console.warn(`[EditorView] Pattern '${F.sid}' functions not provided; skipping.`);continue}const tt=new RegExp(F.pattern.source,F.pattern.flags);(P=l.current)==null||P.addConfig({sid:F.sid,stype:F.stype,category:F.category,pattern:tt,extractData:G.extractData,createDecorator:G.createDecorator,priority:F.priority,enabled:F.enabled})}h()},get contentEditableElement(){return s.current??null},convertModelSelectionToDOM(w){o.convertModelSelectionToDOM(w)},convertDOMSelectionToModel(w){return o.convertDOMSelectionToModel(w)},convertStaticRangeToModel(w){return o.convertStaticRangeToModel(w)},defineDecoratorType(w,M,T){const A=a.current;A&&(M==="layer"?A.registerLayerType(w,T):M==="inline"?A.registerInlineType(w,T):A.registerBlockType(w,T))},get decoratorManager(){return i.current??null},get remoteDecoratorManager(){return c.current??null},get patternDecoratorConfigManager(){return l.current??null},get decoratorGeneratorManager(){return u.current??null}}),g.current),[n,o,s,i,a,c,l,u,f,h]);const{className:m="",layers:p}=t,N={registry:t.registry,className:"barocss-editor-content",editable:!0,...p==null?void 0:p.content};return B.jsxs("div",{className:m,style:{position:"relative",overflow:"hidden"},"data-editor-view":"true",children:[B.jsx(bt,{options:N}),B.jsx(bn,{registry:t.registry,className:(x=p==null?void 0:p.decorator)==null?void 0:x.className,style:(S=p==null?void 0:p.decorator)==null?void 0:S.style}),B.jsx(kn,{registry:t.registry,className:(b=p==null?void 0:p.selection)==null?void 0:b.className,style:(v=p==null?void 0:p.selection)==null?void 0:v.style}),B.jsx(En,{registry:t.registry,className:(I=p==null?void 0:p.context)==null?void 0:I.className,style:(_=p==null?void 0:p.context)==null?void 0:_.style}),B.jsx(Tn,{registry:t.registry,className:(C=p==null?void 0:p.custom)==null?void 0:C.className,style:(D=p==null?void 0:p.custom)==null?void 0:D.style,children:e})]})}),Cn=O.forwardRef(function({editor:t,options:e={},children:r},n){return B.jsx(se,{editor:t,children:B.jsx(On,{ref:n,options:e,children:r})})});function at(d){return function({className:e,style:r,children:n}){return B.jsx(X,{layer:d,className:e,style:r,children:n})}}const An=Object.assign(Cn,{ContentLayer:bt,DecoratorLayer:at("decorator"),SelectionLayer:at("selection"),ContextLayer:at("context"),CustomLayer:at("custom"),Layer:X});exports.EditorView=An;exports.EditorViewContentLayer=bt;exports.EditorViewContextProvider=se;exports.EditorViewLayer=X;exports.createMutationObserverManager=oe;exports.useEditorViewContext=ht;exports.useOptionalEditorViewContext=vn;
|