@barocss/editor-view-react 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +23 -0
- package/README.md +89 -0
- package/dist/editor-view-react/src/EditorView.d.ts +14 -0
- package/dist/editor-view-react/src/EditorView.d.ts.map +1 -0
- package/dist/editor-view-react/src/EditorViewContentLayer.d.ts +9 -0
- package/dist/editor-view-react/src/EditorViewContentLayer.d.ts.map +1 -0
- package/dist/editor-view-react/src/EditorViewContext.d.ts +43 -0
- package/dist/editor-view-react/src/EditorViewContext.d.ts.map +1 -0
- package/dist/editor-view-react/src/EditorViewLayer.d.ts +8 -0
- package/dist/editor-view-react/src/EditorViewLayer.d.ts.map +1 -0
- package/dist/editor-view-react/src/EditorViewOverlayLayerContent.d.ts +14 -0
- package/dist/editor-view-react/src/EditorViewOverlayLayerContent.d.ts.map +1 -0
- package/dist/editor-view-react/src/dom-sync/classify-c1.d.ts +45 -0
- package/dist/editor-view-react/src/dom-sync/classify-c1.d.ts.map +1 -0
- package/dist/editor-view-react/src/dom-sync/edit-position.d.ts +6 -0
- package/dist/editor-view-react/src/dom-sync/edit-position.d.ts.map +1 -0
- package/dist/editor-view-react/src/index.d.ts +12 -0
- package/dist/editor-view-react/src/index.d.ts.map +1 -0
- package/dist/editor-view-react/src/input-handler.d.ts +51 -0
- package/dist/editor-view-react/src/input-handler.d.ts.map +1 -0
- package/dist/editor-view-react/src/mutation-observer-manager.d.ts +13 -0
- package/dist/editor-view-react/src/mutation-observer-manager.d.ts.map +1 -0
- package/dist/editor-view-react/src/selection-handler.d.ts +56 -0
- package/dist/editor-view-react/src/selection-handler.d.ts.map +1 -0
- package/dist/editor-view-react/src/types.d.ts +103 -0
- package/dist/editor-view-react/src/types.d.ts.map +1 -0
- package/dist/index.cjs +4 -0
- package/dist/index.js +11882 -0
- package/docs/SPEC_VERIFICATION.md +109 -0
- package/docs/editor-view-react-spec.md +359 -0
- package/docs/improvement-opportunities.md +66 -0
- package/docs/layers-spec.md +97 -0
- package/package.json +53 -0
- package/src/EditorView.tsx +312 -0
- package/src/EditorViewContentLayer.tsx +90 -0
- package/src/EditorViewContext.tsx +228 -0
- package/src/EditorViewLayer.tsx +35 -0
- package/src/EditorViewOverlayLayerContent.tsx +42 -0
- package/src/dom-sync/classify-c1.ts +91 -0
- package/src/dom-sync/edit-position.ts +27 -0
- package/src/index.ts +33 -0
- package/src/input-handler.ts +716 -0
- package/src/mutation-observer-manager.ts +65 -0
- package/src/selection-handler.ts +450 -0
- package/src/types.ts +123 -0
- package/test/EditorView-decorator.test.tsx +198 -0
- package/test/EditorView-layers.test.tsx +352 -0
- package/test/EditorView.test.tsx +218 -0
- package/test/dom-sync.test.ts +49 -0
- package/test/mutation-observer-manager.test.ts +48 -0
- package/test/selection-handler.test.ts +86 -0
- package/tsconfig.json +12 -0
- package/vite.config.ts +26 -0
- package/vitest.config.ts +10 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
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;
|