/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

'use strict';

var lexical = require('lexical');
var utils = require('@lexical/utils');

const i=Symbol.for("preact-signals");function t(){if(e>1){e--;return}let i,t=false;!function(){let i=r;r=void 0;while(void 0!==i){if(i.S.v===i.v)i.S.i=i.i;i=i.o;}}();while(void 0!==s){let n=s;s=void 0;u++;while(void 0!==n){const o=n.u;n.u=void 0;n.f&=-3;if(!(8&n.f)&&w(n))try{n.c();}catch(n){if(!t){i=n;t=true;}}n=o;}}u=0;e--;if(t)throw i}function n(i){if(e>0)return i();d=++c;e++;try{return i()}finally{t();}}let o,s;function h(i){const t=o;o=void 0;try{return i()}finally{o=t;}}let r,e=0,u=0,c=0,d=0,v=0;function l(i){if(void 0===o)return;let t=i.n;if(void 0===t||t.t!==o){t={i:0,S:i,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:t};if(void 0!==o.s)o.s.n=t;o.s=t;i.n=t;if(32&o.f)i.S(t);return t}else if(-1===t.i){t.i=0;if(void 0!==t.n){t.n.p=t.p;if(void 0!==t.p)t.p.n=t.n;t.p=o.s;t.n=void 0;o.s.n=t;o.s=t;}return t}}function y(i,t){this.v=i;this.i=0;this.n=void 0;this.t=void 0;this.l=0;this.W=null==t?void 0:t.watched;this.Z=null==t?void 0:t.unwatched;this.name=null==t?void 0:t.name;}y.prototype.brand=i;y.prototype.h=function(){return  true};y.prototype.S=function(i){const t=this.t;if(t!==i&&void 0===i.e){i.x=t;this.t=i;if(void 0!==t)t.e=i;else h(()=>{var i;null==(i=this.W)||i.call(this);});}};y.prototype.U=function(i){if(void 0!==this.t){const t=i.e,n=i.x;if(void 0!==t){t.x=n;i.e=void 0;}if(void 0!==n){n.e=t;i.x=void 0;}if(i===this.t){this.t=n;if(void 0===n)h(()=>{var i;null==(i=this.Z)||i.call(this);});}}};y.prototype.subscribe=function(i){return j(()=>{const t=this.value,n=o;o=void 0;try{i(t);}finally{o=n;}},{name:"sub"})};y.prototype.valueOf=function(){return this.value};y.prototype.toString=function(){return this.value+""};y.prototype.toJSON=function(){return this.value};y.prototype.peek=function(){const i=o;o=void 0;try{return this.value}finally{o=i;}};Object.defineProperty(y.prototype,"value",{get(){const i=l(this);if(void 0!==i)i.i=this.i;return this.v},set(i){if(i!==this.v){if(u>100)throw new Error("Cycle detected");!function(i){if(0!==e&&0===u)if(i.l!==d){i.l=d;r={S:i,v:i.v,i:i.i,o:r};}}(this);this.v=i;this.i++;v++;e++;try{for(let i=this.t;void 0!==i;i=i.x)i.t.N();}finally{t();}}}});function a(i,t){return new y(i,t)}function w(i){for(let t=i.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return  true;return  false}function _(i){for(let t=i.s;void 0!==t;t=t.n){const n=t.S.n;if(void 0!==n)t.r=n;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break}}}function b(i){let t,n=i.s;while(void 0!==n){const i=n.p;if(-1===n.i){n.S.U(n);if(void 0!==i)i.n=n.n;if(void 0!==n.n)n.n.p=i;}else t=n;n.S.n=n.r;if(void 0!==n.r)n.r=void 0;n=i;}i.s=t;}function p(i,t){y.call(this,void 0);this.x=i;this.s=void 0;this.g=v-1;this.f=4;this.W=null==t?void 0:t.watched;this.Z=null==t?void 0:t.unwatched;this.name=null==t?void 0:t.name;}p.prototype=new y;p.prototype.h=function(){this.f&=-3;if(1&this.f)return  false;if(32==(36&this.f))return  true;this.f&=-5;if(this.g===v)return  true;this.g=v;this.f|=1;if(this.i>0&&!w(this)){this.f&=-2;return  true}const i=o;try{_(this);o=this;const i=this.x();if(16&this.f||this.v!==i||0===this.i){this.v=i;this.f&=-17;this.i++;}}catch(i){this.v=i;this.f|=16;this.i++;}o=i;b(this);this.f&=-2;return  true};p.prototype.S=function(i){if(void 0===this.t){this.f|=36;for(let i=this.s;void 0!==i;i=i.n)i.S.S(i);}y.prototype.S.call(this,i);};p.prototype.U=function(i){if(void 0!==this.t){y.prototype.U.call(this,i);if(void 0===this.t){this.f&=-33;for(let i=this.s;void 0!==i;i=i.n)i.S.U(i);}}};p.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(let i=this.t;void 0!==i;i=i.x)i.t.N();}};Object.defineProperty(p.prototype,"value",{get(){if(1&this.f)throw new Error("Cycle detected");const i=l(this);this.h();if(void 0!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v}});function g(i,t){return new p(i,t)}function S(i){const n=i.m;i.m=void 0;if("function"==typeof n){e++;const s=o;o=void 0;try{n();}catch(t){i.f&=-2;i.f|=8;m(i);throw t}finally{o=s;t();}}}function m(i){for(let t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;S(i);}function x(i){if(o!==this)throw new Error("Out-of-order effect");b(this);o=i;this.f&=-2;if(8&this.f)m(this);t();}function E(i,t){this.x=i;this.m=void 0;this.s=void 0;this.u=void 0;this.f=32;this.name=null==t?void 0:t.name;}E.prototype.c=function(){const i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;const t=this.x();if("function"==typeof t)this.m=t;}finally{i();}};E.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1;this.f&=-9;S(this);_(this);e++;const i=o;o=this;return x.bind(this,i)};E.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.u=s;s=this;}};E.prototype.d=function(){this.f|=8;if(!(1&this.f))m(this);};E.prototype.dispose=function(){this.d();};function j(i,t){const n=new E(i,t);try{n.c();}catch(i){n.d();throw i}const o=n.d.bind(n);o[Symbol.dispose]=o;return o}

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */
/**
 * @experimental
 * Return an object with the same shape as `defaults` with a {@link Signal}
 * for each value. If specified, the second `opts` argument is a partial
 * of overrides to the defaults and will be used as the initial value.
 *
 * Typically used to make a reactive version of some subset of the
 * configuration of an extension, so it can be reconfigured at runtime.
 *
 * @param defaults The object with default values
 * @param opts Overrides to those default values
 * @returns An object with signals initialized with the default values
 */
function namedSignals(defaults, opts = {}) {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const initial = {};
  for (const k in defaults) {
    const v = opts[k];
    const store = a(v === undefined ? defaults[k] : v);
    initial[k] = store;
  }
  return initial;
}

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/**
 * An Extension to focus the LexicalEditor when the root element is set
 * (typically only when the editor is first created).
 */
const AutoFocusExtension = lexical.defineExtension({
  build: (editor, config, state) => {
    return namedSignals(config);
  },
  config: lexical.safeCast({
    defaultSelection: 'rootEnd',
    disabled: false
  }),
  name: '@lexical/extension/AutoFocus',
  register(editor, config, state) {
    const stores = state.getOutput();
    return j(() => stores.disabled.value ? undefined : editor.registerRootListener(rootElement => {
      editor.focus(() => {
        // If we try and move selection to the same point with setBaseAndExtent, it won't
        // trigger a re-focus on the element. So in the case this occurs, we'll need to correct it.
        // Normally this is fine, Selection API !== Focus API, but fore the intents of the naming
        // of this plugin, which should preserve focus too.
        const activeElement = document.activeElement;
        if (rootElement !== null && (activeElement === null || !rootElement.contains(activeElement))) {
          // Note: preventScroll won't work in Webkit.
          rootElement.focus({
            preventScroll: true
          });
        }
      }, {
        defaultSelection: stores.defaultSelection.peek()
      });
    }));
  }
});

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

function $defaultOnClear() {
  const root = lexical.$getRoot();
  const selection = lexical.$getSelection();
  const paragraph = lexical.$createParagraphNode();
  root.clear();
  root.append(paragraph);
  if (selection !== null) {
    paragraph.select();
  }
  if (lexical.$isRangeSelection(selection)) {
    selection.format = 0;
  }
}
function registerClearEditor(editor, $onClear = $defaultOnClear) {
  return editor.registerCommand(lexical.CLEAR_EDITOR_COMMAND, payload => {
    editor.update($onClear);
    return true;
  }, lexical.COMMAND_PRIORITY_EDITOR);
}

/**
 * An extension to provide an implementation of {@link CLEAR_EDITOR_COMMAND}
 */
const ClearEditorExtension = lexical.defineExtension({
  build(editor, config, state) {
    return namedSignals(config);
  },
  config: lexical.safeCast({
    $onClear: $defaultOnClear
  }),
  name: '@lexical/extension/ClearEditor',
  register(editor, config, state) {
    const {
      $onClear
    } = state.getOutput();
    return j(() => registerClearEditor(editor, $onClear.value));
  }
});

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/**
 * @experimental
 * Get the sets of nodes and types registered in the
 * {@link InitialEditorConfig}. This is to be used when an extension
 * needs to register optional behavior if some node or type is present.
 *
 * @param config The InitialEditorConfig (accessible from an extension's init)
 * @returns The known types and nodes as Sets
 */
function getKnownTypesAndNodes(config) {
  const types = new Set();
  const nodes = new Set();
  for (const klassOrReplacement of getNodeConfig(config)) {
    const klass = typeof klassOrReplacement === 'function' ? klassOrReplacement : klassOrReplacement.replace;
    types.add(klass.getType());
    nodes.add(klass);
  }
  return {
    nodes,
    types
  };
}
function getNodeConfig(config) {
  return (typeof config.nodes === 'function' ? config.nodes() : config.nodes) || [];
}

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

const formatState = lexical.createState('format', {
  parse: value => typeof value === 'number' ? value : 0
});
class DecoratorTextNode extends lexical.DecoratorNode {
  $config() {
    return this.config('decorator-text', {
      extends: lexical.DecoratorNode,
      stateConfigs: [{
        flat: true,
        stateConfig: formatState
      }]
    });
  }
  getFormat() {
    return lexical.$getState(this, formatState);
  }
  getFormatFlags(type, alignWithFormat) {
    return lexical.toggleTextFormatType(this.getFormat(), type, alignWithFormat);
  }
  hasFormat(type) {
    const formatFlag = lexical.TEXT_TYPE_TO_FORMAT[type];
    return (this.getFormat() & formatFlag) !== 0;
  }
  setFormat(type) {
    return lexical.$setState(this, formatState, type);
  }
  toggleFormat(type) {
    const format = this.getFormat();
    const newFormat = lexical.toggleTextFormatType(format, type, null);
    return this.setFormat(newFormat);
  }
  isInline() {
    return true;
  }
  createDOM() {
    return document.createElement('span');
  }
  updateDOM() {
    return false;
  }
}
function $isDecoratorTextNode(node) {
  return node instanceof DecoratorTextNode;
}

/**
 * Applies formatting to the node based on the properties in the passed style object.
 * By default, properties are checked according to the values set
 * when importing content from Google Docs.
 * This algorithm is identical to the TextNode import.

 * @param lexicalNode The node to which the format will apply
 * @param style CSS style object
 * @param shouldApply format to apply if it is not in style
 * @returns lexicalNode
 */
function applyFormatFromStyle(lexicalNode, style, shouldApply) {
  const fontWeight = style.fontWeight;
  const textDecoration = style.textDecoration.split(' ');
  // Google Docs uses span tags + font-weight for bold text
  const hasBoldFontWeight = fontWeight === '700' || fontWeight === 'bold';
  // Google Docs uses span tags + text-decoration: line-through for strikethrough text
  const hasLinethroughTextDecoration = textDecoration.includes('line-through');
  // Google Docs uses span tags + font-style for italic text
  const hasItalicFontStyle = style.fontStyle === 'italic';
  // Google Docs uses span tags + text-decoration: underline for underline text
  const hasUnderlineTextDecoration = textDecoration.includes('underline');
  // Google Docs uses span tags + vertical-align to specify subscript and superscript
  const verticalAlign = style.verticalAlign;
  if (hasBoldFontWeight && !lexicalNode.hasFormat('bold')) {
    lexicalNode.toggleFormat('bold');
  }
  if (hasLinethroughTextDecoration && !lexicalNode.hasFormat('strikethrough')) {
    lexicalNode.toggleFormat('strikethrough');
  }
  if (hasItalicFontStyle && !lexicalNode.hasFormat('italic')) {
    lexicalNode.toggleFormat('italic');
  }
  if (hasUnderlineTextDecoration && !lexicalNode.hasFormat('underline')) {
    lexicalNode.toggleFormat('underline');
  }
  if (verticalAlign === 'sub' && !lexicalNode.hasFormat('subscript')) {
    lexicalNode.toggleFormat('subscript');
  }
  if (verticalAlign === 'super' && !lexicalNode.hasFormat('superscript')) {
    lexicalNode.toggleFormat('superscript');
  }
  if (shouldApply && !lexicalNode.hasFormat(shouldApply)) {
    lexicalNode.toggleFormat(shouldApply);
  }
  return lexicalNode;
}

/**
 * The function wraps the passed DOM node in semantic tags depending on the node format.
 *
 * @param lexicalNode The node where the format is checked
 * @param domNode DOM that will be wrapped in tags
 * @param tagNameToFormat Tag name and format mapping
 * @returns domNode
 */
function applyFormatToDom(lexicalNode, domNode, tagNameToFormat = DEFAULT_TAG_NAME_TO_FORMAT) {
  for (const [tag, format] of Object.entries(tagNameToFormat)) {
    if (lexicalNode.hasFormat(format)) {
      domNode = wrapElementWith(domNode, tag);
    }
  }
  return domNode;
}
function wrapElementWith(element, tag) {
  const el = document.createElement(tag);
  el.appendChild(element);
  return el;
}
const DEFAULT_TAG_NAME_TO_FORMAT = {
  b: 'bold',
  code: 'code',
  em: 'italic',
  i: 'italic',
  mark: 'highlight',
  s: 'strikethrough',
  strong: 'bold',
  sub: 'subscript',
  sup: 'superscript',
  u: 'underline'
};

/**
 * An extension for DecoratorTextNode that sets the format for the node and CSS classes for the DOM container.
 * The base class is always set, and the focus class is set when the node is selected.
 */
const DecoratorTextExtension = lexical.defineExtension({
  name: '@lexical/extension/DecoratorText',
  nodes: () => [DecoratorTextNode],
  register(editor, config, state) {
    return editor.registerCommand(lexical.FORMAT_TEXT_COMMAND, formatType => {
      const selection = lexical.$getSelection();
      if (lexical.$isNodeSelection(selection) || lexical.$isRangeSelection(selection)) {
        for (const node of selection.getNodes()) {
          if ($isDecoratorTextNode(node)) {
            node.toggleFormat(formatType);
          }
        }
      }
      return false;
    }, lexical.COMMAND_PRIORITY_LOW);
  }
});

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/**
 * @experimental
 * Create a Signal that will subscribe to a value from an external store when watched, similar to
 * React's [useSyncExternalStore](https://react.dev/reference/react/useSyncExternalStore).
 *
 * @param getSnapshot Used to get the initial value of the signal when created and when first watched.
 * @param register A callback that will subscribe to some external store and update the signal, must return a dispose function.
 * @returns The signal
 */
function watchedSignal(getSnapshot, register) {
  let dispose;
  return a(getSnapshot(), {
    unwatched() {
      if (dispose) {
        dispose();
        dispose = undefined;
      }
    },
    watched() {
      this.value = getSnapshot();
      dispose = register(this);
    }
  });
}

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/**
 * An extension to provide the current EditorState as a signal
 */
const EditorStateExtension = lexical.defineExtension({
  build(editor) {
    return watchedSignal(() => editor.getEditorState(), editorStateSignal => editor.registerUpdateListener(payload => {
      editorStateSignal.value = payload.editorState;
    }));
  },
  name: '@lexical/extension/EditorState'
});

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

// Do not require this module directly! Use normal `invariant` calls.

function formatDevErrorMessage(message) {
  throw new Error(message);
}

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/**
 * Recursively merge the given theme configuration in-place.
 *
 * @returns If `a` and `b` are both objects (and `b` is not an Array) then
 * all keys in `b` are merged into `a` then `a` is returned.
 * Otherwise `b` is returned.
 *
 * @example
 * ```ts
 * const a = { a: "a", nested: { a: 1 } };
 * const b = { b: "b", nested: { b: 2 } };
 * const rval = deepThemeMergeInPlace(a, b);
 * expect(a).toBe(rval);
 * expect(a).toEqual({ a: "a", b: "b", nested: { a: 1, b: 2 } });
 * ```
 */
function deepThemeMergeInPlace(a, b) {
  if (a && b && !Array.isArray(b) && typeof a === 'object' && typeof b === 'object') {
    const aObj = a;
    const bObj = b;
    for (const k in bObj) {
      aObj[k] = deepThemeMergeInPlace(aObj[k], bObj[k]);
    }
    return a;
  }
  return b;
}

const ExtensionRepStateIds = {
  /* eslint-disable sort-keys-fix/sort-keys-fix */
  unmarked: 0,
  temporary: 1,
  permanent: 2,
  configured: 3,
  initialized: 4,
  built: 5,
  registered: 6,
  afterRegistration: 7
  /* eslint-enable sort-keys-fix/sort-keys-fix */
};
function isExactlyUnmarkedExtensionRepState(state) {
  return state.id === ExtensionRepStateIds.unmarked;
}
function isExactlyTemporaryExtensionRepState(state) {
  return state.id === ExtensionRepStateIds.temporary;
}
function isExactlyPermanentExtensionRepState(state) {
  return state.id === ExtensionRepStateIds.permanent;
}
function isConfiguredExtensionRepState(state) {
  return state.id >= ExtensionRepStateIds.configured;
}
function isInitializedExtensionRepState(state) {
  return state.id >= ExtensionRepStateIds.initialized;
}
function isBuiltExtensionRepState(state) {
  return state.id >= ExtensionRepStateIds.built;
}
function isAfterRegistrationState(state) {
  return state.id >= ExtensionRepStateIds.afterRegistration;
}
function applyTemporaryMark(state) {
  if (!isExactlyUnmarkedExtensionRepState(state)) {
    formatDevErrorMessage(`LexicalBuilder: Can not apply a temporary mark from state id ${String(state.id)} (expected ${String(ExtensionRepStateIds.unmarked)} unmarked)`);
  }
  return Object.assign(state, {
    id: ExtensionRepStateIds.temporary
  });
}
function applyPermanentMark(state) {
  if (!isExactlyTemporaryExtensionRepState(state)) {
    formatDevErrorMessage(`LexicalBuilder: Can not apply a permanent mark from state id ${String(state.id)} (expected ${String(ExtensionRepStateIds.temporary)} temporary)`);
  }
  return Object.assign(state, {
    id: ExtensionRepStateIds.permanent
  });
}
function applyConfiguredState(state, config, registerState) {
  return Object.assign(state, {
    config,
    id: ExtensionRepStateIds.configured,
    registerState
  });
}
function applyInitializedState(state, initResult, registerState) {
  return Object.assign(state, {
    id: ExtensionRepStateIds.initialized,
    initResult,
    registerState
  });
}
function applyBuiltState(state, output, registerState) {
  return Object.assign(state, {
    id: ExtensionRepStateIds.built,
    output,
    registerState
  });
}
function applyRegisteredState(state) {
  return Object.assign(state, {
    id: ExtensionRepStateIds.registered
  });
}
function applyAfterRegistrationState(state) {
  return Object.assign(state, {
    id: ExtensionRepStateIds.afterRegistration
  });
}
function rollbackToBuiltState(state) {
  return Object.assign(state, {
    id: ExtensionRepStateIds.built
  });
}
const emptySet = new Set();

/**
 * @internal
 */
class ExtensionRep {
  builder;
  configs;
  _dependency;
  _peerNameSet;
  extension;
  state;
  _signal;
  constructor(builder, extension) {
    this.builder = builder;
    this.extension = extension;
    this.configs = new Set();
    this.state = {
      id: ExtensionRepStateIds.unmarked
    };
  }
  mergeConfigs() {
    let config = this.extension.config || {};
    const mergeConfig = this.extension.mergeConfig ? this.extension.mergeConfig.bind(this.extension) : lexical.shallowMergeConfig;
    for (const cfg of this.configs) {
      config = mergeConfig(config, cfg);
    }
    return config;
  }
  init(editorConfig) {
    const initialState = this.state;
    if (!isExactlyPermanentExtensionRepState(initialState)) {
      formatDevErrorMessage(`ExtensionRep: Can not configure from state id ${String(initialState.id)}`);
    }
    const initState = {
      getDependency: this.getInitDependency.bind(this),
      getDirectDependentNames: this.getDirectDependentNames.bind(this),
      getPeer: this.getInitPeer.bind(this),
      getPeerNameSet: this.getPeerNameSet.bind(this)
    };
    const buildState = {
      ...initState,
      getDependency: this.getDependency.bind(this),
      getInitResult: this.getInitResult.bind(this),
      getPeer: this.getPeer.bind(this)
    };
    const state = applyConfiguredState(initialState, this.mergeConfigs(), initState);
    this.state = state;
    let initResult;
    if (this.extension.init) {
      initResult = this.extension.init(editorConfig, state.config, initState);
    }
    this.state = applyInitializedState(state, initResult, buildState);
  }
  build(editor) {
    const state = this.state;
    if (!(state.id === ExtensionRepStateIds.initialized)) {
      formatDevErrorMessage(`ExtensionRep: register called in state id ${String(state.id)} (expected ${String(ExtensionRepStateIds.built)} initialized)`);
    }
    let output;
    if (this.extension.build) {
      output = this.extension.build(editor, state.config, state.registerState);
    }
    const registerState = {
      ...state.registerState,
      getOutput: () => output,
      getSignal: this.getSignal.bind(this)
    };
    this.state = applyBuiltState(state, output, registerState);
  }
  register(editor, signal) {
    this._signal = signal;
    const state = this.state;
    if (!(state.id === ExtensionRepStateIds.built)) {
      formatDevErrorMessage(`ExtensionRep: register called in state id ${String(state.id)} (expected ${String(ExtensionRepStateIds.built)} built)`);
    }
    const cleanup = this.extension.register && this.extension.register(editor, state.config, state.registerState);
    this.state = applyRegisteredState(state);
    return () => {
      const afterRegistrationState = this.state;
      if (!(afterRegistrationState.id === ExtensionRepStateIds.afterRegistration)) {
        formatDevErrorMessage(`ExtensionRep: rollbackToBuiltState called in state id ${String(state.id)} (expected ${String(ExtensionRepStateIds.afterRegistration)} afterRegistration)`);
      }
      this.state = rollbackToBuiltState(afterRegistrationState);
      if (cleanup) {
        cleanup();
      }
    };
  }
  afterRegistration(editor) {
    const state = this.state;
    if (!(state.id === ExtensionRepStateIds.registered)) {
      formatDevErrorMessage(`ExtensionRep: afterRegistration called in state id ${String(state.id)} (expected ${String(ExtensionRepStateIds.registered)} registered)`);
    }
    let rval;
    if (this.extension.afterRegistration) {
      rval = this.extension.afterRegistration(editor, state.config, state.registerState);
    }
    this.state = applyAfterRegistrationState(state);
    return rval;
  }
  getSignal() {
    if (!(this._signal !== undefined)) {
      formatDevErrorMessage(`ExtensionRep.getSignal() called before register`);
    }
    return this._signal;
  }
  getInitResult() {
    if (!(this.extension.init !== undefined)) {
      formatDevErrorMessage(`ExtensionRep: getInitResult() called for Extension ${this.extension.name} that does not define init`);
    }
    const state = this.state;
    if (!isInitializedExtensionRepState(state)) {
      formatDevErrorMessage(`ExtensionRep: getInitResult() called for ExtensionRep in state id ${String(state.id)} < ${String(ExtensionRepStateIds.initialized)} (initialized)`);
    }
    return state.initResult;
  }
  getInitPeer(name) {
    const rep = this.builder.extensionNameMap.get(name);
    return rep ? rep.getExtensionInitDependency() : undefined;
  }
  getExtensionInitDependency() {
    const state = this.state;
    if (!isConfiguredExtensionRepState(state)) {
      formatDevErrorMessage(`ExtensionRep: getExtensionInitDependency called in state id ${String(state.id)} (expected >= ${String(ExtensionRepStateIds.configured)} configured)`);
    }
    return {
      config: state.config
    };
  }
  getPeer(name) {
    const rep = this.builder.extensionNameMap.get(name);
    return rep ? rep.getExtensionDependency() : undefined;
  }
  getInitDependency(dep) {
    const rep = this.builder.getExtensionRep(dep);
    if (!(rep !== undefined)) {
      formatDevErrorMessage(`LexicalExtensionBuilder: Extension ${this.extension.name} missing dependency extension ${dep.name} to be in registry`);
    }
    return rep.getExtensionInitDependency();
  }
  getDependency(dep) {
    const rep = this.builder.getExtensionRep(dep);
    if (!(rep !== undefined)) {
      formatDevErrorMessage(`LexicalExtensionBuilder: Extension ${this.extension.name} missing dependency extension ${dep.name} to be in registry`);
    }
    return rep.getExtensionDependency();
  }
  getState() {
    const state = this.state;
    if (!isAfterRegistrationState(state)) {
      formatDevErrorMessage(`ExtensionRep getState called in state id ${String(state.id)} (expected ${String(ExtensionRepStateIds.afterRegistration)} afterRegistration)`);
    }
    return state;
  }
  getDirectDependentNames() {
    return this.builder.incomingEdges.get(this.extension.name) || emptySet;
  }
  getPeerNameSet() {
    let s = this._peerNameSet;
    if (!s) {
      s = new Set((this.extension.peerDependencies || []).map(([name]) => name));
      this._peerNameSet = s;
    }
    return s;
  }
  getExtensionDependency() {
    if (!this._dependency) {
      const state = this.state;
      if (!isBuiltExtensionRepState(state)) {
        formatDevErrorMessage(`Extension ${this.extension.name} used as a dependency before build`);
      }
      this._dependency = {
        config: state.config,
        init: state.initResult,
        output: state.output
      };
    }
    return this._dependency;
  }
}

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

const HISTORY_MERGE_OPTIONS = {
  tag: lexical.HISTORY_MERGE_TAG
};
function $defaultInitializer() {
  const root = lexical.$getRoot();
  if (root.isEmpty()) {
    root.append(lexical.$createParagraphNode());
  }
}
/**
 * An extension to set the initial state of the editor from
 * a function or serialized JSON EditorState. This is
 * implicitly included with all editors built with
 * Lexical Extension. This happens in the `afterRegistration`
 * phase so your initial state may depend on registered commands,
 * but you should not call `editor.setRootElement` earlier than
 * this phase to avoid rendering an empty editor first.
 */
const InitialStateExtension = lexical.defineExtension({
  config: lexical.safeCast({
    setOptions: HISTORY_MERGE_OPTIONS,
    updateOptions: HISTORY_MERGE_OPTIONS
  }),
  init({
    $initialEditorState = $defaultInitializer
  }) {
    return {
      $initialEditorState,
      initialized: false
    };
  },
  // eslint-disable-next-line sort-keys-fix/sort-keys-fix -- typescript inference is order dependent here for some reason
  afterRegistration(editor, {
    updateOptions,
    setOptions
  }, state) {
    const initResult = state.getInitResult();
    if (!initResult.initialized) {
      initResult.initialized = true;
      const {
        $initialEditorState
      } = initResult;
      if (lexical.$isEditorState($initialEditorState)) {
        editor.setEditorState($initialEditorState, setOptions);
      } else if (typeof $initialEditorState === 'function') {
        editor.update(() => {
          $initialEditorState(editor);
        }, updateOptions);
      } else if ($initialEditorState && (typeof $initialEditorState === 'string' || typeof $initialEditorState === 'object')) {
        const parsedEditorState = editor.parseEditorState($initialEditorState);
        editor.setEditorState(parsedEditorState, setOptions);
      }
    }
    return () => {};
  },
  name: '@lexical/extension/InitialState',
  // These are automatically added by createEditor, we add them here so they are
  // visible during extensionRep.init so extensions can see all known types before the
  // editor is created.
  // (excluding ArtificialNode__DO_NOT_USE because it isn't really public API
  // and shouldn't change anything)
  nodes: [lexical.RootNode, lexical.TextNode, lexical.LineBreakNode, lexical.TabNode, lexical.ParagraphNode]
});

/** @internal Use a well-known symbol for dev tools purposes */
const builderSymbol = Symbol.for('@lexical/extension/LexicalBuilder');
/**
 * Build a LexicalEditor by combining together one or more extensions, optionally
 * overriding some of their configuration.
 *
 * @param extensions - Extension arguments (extensions or extensions with config overrides)
 * @returns An editor handle
 *
 * @example
 * A single root extension with multiple dependencies
 *
 * ```ts
 * const editor = buildEditorFromExtensions(
 *   defineExtension({
 *     name: "[root]",
 *     dependencies: [
 *       RichTextExtension,
 *       configExtension(EmojiExtension, { emojiBaseUrl: "/assets/emoji" }),
 *     ],
 *     register: (editor: LexicalEditor) => {
 *       console.log("Editor Created");
 *       return () => console.log("Editor Disposed");
 *     },
 *   }),
 * );
 * ```
 *
 * @example
 * A very similar minimal configuration without the register hook
 *
 * ```ts
 * const editor = buildEditorFromExtensions(
 *   RichTextExtension,
 *   configExtension(EmojiExtension, { emojiBaseUrl: "/assets/emoji" }),
 * );
 * ```
 */
function buildEditorFromExtensions(...extensions) {
  return LexicalBuilder.fromExtensions(extensions).buildEditor();
}

/** @internal */
function noop() {
  /*empty*/
}

/** Throw the given Error */
function defaultOnError(err) {
  throw err;
}
/** @internal */
function maybeWithBuilder(editor) {
  return editor;
}
function normalizeExtensionArgument(arg) {
  return Array.isArray(arg) ? arg : [arg];
}
const PACKAGE_VERSION = "0.43.0+dev.cjs";

/** @internal */
class LexicalBuilder {
  roots;
  extensionNameMap;
  outgoingConfigEdges;
  incomingEdges;
  conflicts;
  _sortedExtensionReps;
  PACKAGE_VERSION;
  constructor(roots) {
    this.outgoingConfigEdges = new Map();
    this.incomingEdges = new Map();
    this.extensionNameMap = new Map();
    this.conflicts = new Map();
    this.PACKAGE_VERSION = PACKAGE_VERSION;
    this.roots = roots;
    for (const extension of roots) {
      this.addExtension(extension);
    }
  }
  static fromExtensions(extensions) {
    const roots = [normalizeExtensionArgument(InitialStateExtension)];
    for (const extension of extensions) {
      roots.push(normalizeExtensionArgument(extension));
    }
    return new LexicalBuilder(roots);
  }
  static maybeFromEditor(editor) {
    const builder = maybeWithBuilder(editor)[builderSymbol];
    if (builder) {
      // The dev tools variant of this will relax some of these invariants
      if (!(builder.PACKAGE_VERSION === PACKAGE_VERSION)) {
        formatDevErrorMessage(`LexicalBuilder.fromEditor: The given editor was created with LexicalBuilder ${builder.PACKAGE_VERSION} but this version is ${PACKAGE_VERSION}. A project should have exactly one copy of LexicalBuilder`);
      }
      if (!(builder instanceof LexicalBuilder)) {
        formatDevErrorMessage(`LexicalBuilder.fromEditor: There are multiple copies of the same version of LexicalBuilder in your project, and this editor was created with another one. Your project, or one of its dependencies, has its package.json and/or bundler configured incorrectly.`);
      }
    }
    return builder;
  }

  /** Look up the editor that was created by this LexicalBuilder or throw */
  static fromEditor(editor) {
    const builder = LexicalBuilder.maybeFromEditor(editor);
    if (!(builder !== undefined)) {
      formatDevErrorMessage(`LexicalBuilder.fromEditor: The given editor was not created with LexicalBuilder`);
    }
    return builder;
  }
  constructEditor() {
    const {
      $initialEditorState: _$initialEditorState,
      onError,
      ...editorConfig
    } = this.buildCreateEditorArgs();
    const editor = Object.assign(lexical.createEditor({
      ...editorConfig,
      ...(onError ? {
        onError: err => {
          onError(err, editor);
        }
      } : {})
    }), {
      [builderSymbol]: this
    });
    for (const extensionRep of this.sortedExtensionReps()) {
      extensionRep.build(editor);
    }
    return editor;
  }
  buildEditor() {
    let disposeOnce = noop;
    function dispose() {
      try {
        disposeOnce();
      } finally {
        disposeOnce = noop;
      }
    }
    const editor = Object.assign(this.constructEditor(), {
      dispose,
      [Symbol.dispose]: dispose
    });
    disposeOnce = lexical.mergeRegister(this.registerEditor(editor), () => editor.setRootElement(null));
    return editor;
  }
  hasExtensionByName(name) {
    return this.extensionNameMap.has(name);
  }
  getExtensionRep(extension) {
    const rep = this.extensionNameMap.get(extension.name);
    if (rep) {
      if (!(rep.extension === extension)) {
        formatDevErrorMessage(`LexicalBuilder: A registered extension with name ${extension.name} exists but does not match the given extension`);
      }
      return rep;
    }
  }
  addEdge(fromExtensionName, toExtensionName, configs) {
    const outgoing = this.outgoingConfigEdges.get(fromExtensionName);
    if (outgoing) {
      outgoing.set(toExtensionName, configs);
    } else {
      this.outgoingConfigEdges.set(fromExtensionName, new Map([[toExtensionName, configs]]));
    }
    const incoming = this.incomingEdges.get(toExtensionName);
    if (incoming) {
      incoming.add(fromExtensionName);
    } else {
      this.incomingEdges.set(toExtensionName, new Set([fromExtensionName]));
    }
  }
  addExtension(arg) {
    if (!(this._sortedExtensionReps === undefined)) {
      formatDevErrorMessage(`LexicalBuilder: addExtension called after finalization`);
    }
    const normalized = normalizeExtensionArgument(arg);
    const [extension] = normalized;
    if (!(typeof extension.name === 'string')) {
      formatDevErrorMessage(`LexicalBuilder: extension name must be string, not ${typeof extension.name}`);
    }
    let extensionRep = this.extensionNameMap.get(extension.name);
    if (!(extensionRep === undefined || extensionRep.extension === extension)) {
      formatDevErrorMessage(`LexicalBuilder: Multiple extensions registered with name ${extension.name}, names must be unique`);
    }
    if (!extensionRep) {
      extensionRep = new ExtensionRep(this, extension);
      this.extensionNameMap.set(extension.name, extensionRep);
      const hasConflict = this.conflicts.get(extension.name);
      if (typeof hasConflict === 'string') {
        {
          formatDevErrorMessage(`LexicalBuilder: extension ${extension.name} conflicts with ${hasConflict}`);
        }
      }
      for (const name of extension.conflictsWith || []) {
        if (!!this.extensionNameMap.has(name)) {
          formatDevErrorMessage(`LexicalBuilder: extension ${extension.name} conflicts with ${name}`);
        }
        this.conflicts.set(name, extension.name);
      }
      for (const dep of extension.dependencies || []) {
        const normDep = normalizeExtensionArgument(dep);
        this.addEdge(extension.name, normDep[0].name, normDep.slice(1));
        this.addExtension(normDep);
      }
      for (const [depName, config] of extension.peerDependencies || []) {
        this.addEdge(extension.name, depName, config ? [config] : []);
      }
    }
  }
  sortedExtensionReps() {
    if (this._sortedExtensionReps) {
      return this._sortedExtensionReps;
    }
    // depth-first search based topological DAG sort
    // https://en.wikipedia.org/wiki/Topological_sorting
    const sortedExtensionReps = [];
    const visit = (rep, fromExtensionName) => {
      let mark = rep.state;
      if (isExactlyPermanentExtensionRepState(mark)) {
        return;
      }
      const extensionName = rep.extension.name;
      if (!isExactlyUnmarkedExtensionRepState(mark)) {
        formatDevErrorMessage(`LexicalBuilder: Circular dependency detected for Extension ${extensionName} from ${fromExtensionName || '[unknown]'}`);
      }
      mark = applyTemporaryMark(mark);
      rep.state = mark;
      const outgoingConfigEdges = this.outgoingConfigEdges.get(extensionName);
      if (outgoingConfigEdges) {
        for (const toExtensionName of outgoingConfigEdges.keys()) {
          const toRep = this.extensionNameMap.get(toExtensionName);
          // may be undefined for an optional peer dependency
          if (toRep) {
            visit(toRep, extensionName);
          }
        }
      }
      mark = applyPermanentMark(mark);
      rep.state = mark;
      sortedExtensionReps.push(rep);
    };
    for (const rep of this.extensionNameMap.values()) {
      if (isExactlyUnmarkedExtensionRepState(rep.state)) {
        visit(rep);
      }
    }
    for (const rep of sortedExtensionReps) {
      for (const [toExtensionName, configs] of this.outgoingConfigEdges.get(rep.extension.name) || []) {
        if (configs.length > 0) {
          const toRep = this.extensionNameMap.get(toExtensionName);
          if (toRep) {
            for (const config of configs) {
              toRep.configs.add(config);
            }
          }
        }
      }
    }
    for (const [extension, ...configs] of this.roots) {
      if (configs.length > 0) {
        const toRep = this.extensionNameMap.get(extension.name);
        if (!(toRep !== undefined)) {
          formatDevErrorMessage(`LexicalBuilder: Expecting existing ExtensionRep for ${extension.name}`);
        }
        for (const config of configs) {
          toRep.configs.add(config);
        }
      }
    }
    this._sortedExtensionReps = sortedExtensionReps;
    return this._sortedExtensionReps;
  }
  registerEditor(editor) {
    const extensionReps = this.sortedExtensionReps();
    const controller = new AbortController();
    const cleanups = [() => controller.abort()];
    const signal = controller.signal;
    for (const extensionRep of extensionReps) {
      const cleanup = extensionRep.register(editor, signal);
      if (cleanup) {
        cleanups.push(cleanup);
      }
    }
    for (const extensionRep of extensionReps) {
      const cleanup = extensionRep.afterRegistration(editor);
      if (cleanup) {
        cleanups.push(cleanup);
      }
    }
    return lexical.mergeRegister(...cleanups);
  }
  buildCreateEditorArgs() {
    const config = {};
    const nodes = new Set();
    const replacedNodes = new Map();
    const htmlExport = new Map();
    const htmlImport = {};
    const theme = {};
    const extensionReps = this.sortedExtensionReps();
    for (const extensionRep of extensionReps) {
      const {
        extension
      } = extensionRep;
      if (extension.onError !== undefined) {
        config.onError = extension.onError;
      }
      if (extension.disableEvents !== undefined) {
        config.disableEvents = extension.disableEvents;
      }
      if (extension.parentEditor !== undefined) {
        config.parentEditor = extension.parentEditor;
      }
      if (extension.editable !== undefined) {
        config.editable = extension.editable;
      }
      if (extension.namespace !== undefined) {
        config.namespace = extension.namespace;
      }
      if (extension.$initialEditorState !== undefined) {
        config.$initialEditorState = extension.$initialEditorState;
      }
      if (extension.nodes) {
        for (const node of getNodeConfig(extension)) {
          if (typeof node !== 'function') {
            const conflictExtension = replacedNodes.get(node.replace);
            if (conflictExtension) {
              {
                formatDevErrorMessage(`LexicalBuilder: Extension ${extension.name} can not register replacement for node ${node.replace.name} because ${conflictExtension.extension.name} already did`);
              }
            }
            replacedNodes.set(node.replace, extensionRep);
          }
          nodes.add(node);
        }
      }
      if (extension.html) {
        if (extension.html.export) {
          for (const [k, v] of extension.html.export.entries()) {
            htmlExport.set(k, v);
          }
        }
        if (extension.html.import) {
          Object.assign(htmlImport, extension.html.import);
        }
      }
      if (extension.theme) {
        deepThemeMergeInPlace(theme, extension.theme);
      }
    }
    if (Object.keys(theme).length > 0) {
      config.theme = theme;
    }
    if (nodes.size) {
      config.nodes = [...nodes];
    }
    const hasImport = Object.keys(htmlImport).length > 0;
    const hasExport = htmlExport.size > 0;
    if (hasImport || hasExport) {
      config.html = {};
      if (hasImport) {
        config.html.import = htmlImport;
      }
      if (hasExport) {
        config.html.export = htmlExport;
      }
    }
    for (const extensionRep of extensionReps) {
      extensionRep.init(config);
    }
    if (!config.onError) {
      config.onError = defaultOnError;
    }
    return config;
  }
}

/**
 * @experimental
 * Get the finalized config and output of an Extension that was used to build the editor.
 *
 * This is useful in the implementation of a LexicalNode or in other
 * situations where you have an editor reference but it's not easy to
 * pass the config or {@link ExtensionRegisterState} around.
 *
 * It will throw if the Editor was not built using this Extension.
 *
 * @param editor - The editor that was built using extension
 * @param extension - The concrete reference to an Extension used to build this editor
 * @returns The config and output for that Extension
 */
function getExtensionDependencyFromEditor(editor, extension) {
  const builder = LexicalBuilder.fromEditor(editor);
  const rep = builder.getExtensionRep(extension);
  if (!(rep !== undefined)) {
    formatDevErrorMessage(`getExtensionDependencyFromEditor: Extension ${extension.name} was not built when creating this editor`);
  }
  return rep.getExtensionDependency();
}

/**
 * @experimental
 * Get the finalized config and output of an Extension that was used to build the
 * editor by name.
 *
 * This can be used from the implementation of a LexicalNode or in other
 * situation where you have an editor reference but it's not easy to pass the
 * config around. Use this version if you do not have a concrete reference to
 * the Extension for some reason (e.g. it is an optional peer dependency, or you
 * are avoiding a circular import).
 *
 * Both the explicit Extension type and the name are required.
 *
 *  @example
 * ```tsx
 * import type { HistoryExtension } from "@lexical/history";
 * getPeerDependencyFromEditor<typeof HistoryExtension>(editor, "@lexical/history/History");
 * ```

 * @param editor - The editor that may have been built using extension
 * @param extensionName - The name of the Extension
 * @returns The config and output of the Extension or undefined
 */
function getPeerDependencyFromEditor(editor, extensionName) {
  const builder = LexicalBuilder.fromEditor(editor);
  const peer = builder.extensionNameMap.get(extensionName);
  return peer ? peer.getExtensionDependency() : undefined;
}

/**
 * Get the finalized config and output of an Extension that was used to build the
 * editor by name.
 *
 * This can be used from the implementation of a LexicalNode or in other
 * situation where you have an editor reference but it's not easy to pass the
 * config around. Use this version if you do not have a concrete reference to
 * the Extension for some reason (e.g. it is an optional peer dependency, or you
 * are avoiding a circular import).
 *
 * Both the explicit Extension type and the name are required.
 *
 *  @example
 * ```tsx
 * import type { EmojiExtension } from "./EmojiExtension";
 * export class EmojiNode extends TextNode {
 *   // other implementation details not included
 *   createDOM(
 *     config: EditorConfig,
 *     editor?: LexicalEditor | undefined
 *   ): HTMLElement {
 *     const dom = super.createDOM(config, editor);
 *     addClassNamesToElement(
 *       dom,
 *       getPeerDependencyFromEditorOrThrow<typeof EmojiExtension>(
 *         editor || $getEditor(),
 *         "@lexical/playground/emoji",
 *       ).config.emojiClass,
 *     );
 *     return dom;
 *   }
 * }
 * ```

 * @param editor - The editor that may have been built using extension
 * @param extensionName - The name of the Extension
 * @returns The config and output of the Extension
 */
function getPeerDependencyFromEditorOrThrow(editor, extensionName) {
  const dep = getPeerDependencyFromEditor(editor, extensionName);
  if (!(dep !== undefined)) {
    formatDevErrorMessage(`getPeerDependencyFromEditorOrThrow: Editor was not built with Extension ${extensionName}`);
  }
  return dep;
}

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

const EMPTY_SET = new Set();

/**
 * An extension that provides a `watchNodeKey` output that
 * returns a signal for the selection state of a node.
 *
 * Typically used for tracking whether a DecoratorNode is
 * currently selected or not. A framework independent
 * alternative to {@link useLexicalNodeSelection}.
 */
const NodeSelectionExtension = lexical.defineExtension({
  build(editor, config, state) {
    const editorStateStore = state.getDependency(EditorStateExtension).output;
    const watchedNodeStore = a({
      watchedNodeKeys: new Map()
    });
    const selectedNodeKeys = watchedSignal(() => undefined, () => j(() => {
      const prevSelectedNodeKeys = selectedNodeKeys.peek();
      const {
        watchedNodeKeys
      } = watchedNodeStore.value;
      let nextSelectedNodeKeys;
      let didChange = false;
      editorStateStore.value.read(() => {
        const selection = lexical.$getSelection();
        if (selection) {
          for (const [key, listeners] of watchedNodeKeys.entries()) {
            if (listeners.size === 0) {
              // We intentionally mutate this without firing a signal, to
              // avoid re-triggering this effect. There are no subscribers
              // so nothing can observe whether key was in the set or not
              watchedNodeKeys.delete(key);
              continue;
            }
            const node = lexical.$getNodeByKey(key);
            const isSelected = node && node.isSelected() || false;
            didChange = didChange || isSelected !== (prevSelectedNodeKeys ? prevSelectedNodeKeys.has(key) : false);
            if (isSelected) {
              nextSelectedNodeKeys = nextSelectedNodeKeys || new Set();
              nextSelectedNodeKeys.add(key);
            }
          }
        }
      });
      if (!(!didChange && nextSelectedNodeKeys && prevSelectedNodeKeys && nextSelectedNodeKeys.size === prevSelectedNodeKeys.size)) {
        selectedNodeKeys.value = nextSelectedNodeKeys;
      }
    }));
    function watchNodeKey(key) {
      const watcher = g(() => (selectedNodeKeys.value || EMPTY_SET).has(key));
      const {
        watchedNodeKeys
      } = watchedNodeStore.peek();
      let listeners = watchedNodeKeys.get(key);
      const hadListener = listeners !== undefined;
      listeners = listeners || new Set();
      listeners.add(watcher);
      if (!hadListener) {
        watchedNodeKeys.set(key, listeners);
        watchedNodeStore.value = {
          watchedNodeKeys
        };
      }
      return watcher;
    }
    return {
      watchNodeKey
    };
  },
  dependencies: [EditorStateExtension],
  name: '@lexical/extension/NodeSelection'
});

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

const INSERT_HORIZONTAL_RULE_COMMAND = lexical.createCommand('INSERT_HORIZONTAL_RULE_COMMAND');
class HorizontalRuleNode extends lexical.DecoratorNode {
  static getType() {
    return 'horizontalrule';
  }
  static clone(node) {
    return new HorizontalRuleNode(node.__key);
  }
  static importJSON(serializedNode) {
    return $createHorizontalRuleNode().updateFromJSON(serializedNode);
  }
  static importDOM() {
    return {
      hr: () => ({
        conversion: $convertHorizontalRuleElement,
        priority: 0
      })
    };
  }
  exportDOM() {
    return {
      element: document.createElement('hr')
    };
  }
  createDOM(config) {
    const element = document.createElement('hr');
    lexical.addClassNamesToElement(element, config.theme.hr);
    return element;
  }
  getTextContent() {
    return '\n';
  }
  isInline() {
    return false;
  }
  updateDOM() {
    return false;
  }
}
function $convertHorizontalRuleElement() {
  return {
    node: $createHorizontalRuleNode()
  };
}
function $createHorizontalRuleNode() {
  return lexical.$create(HorizontalRuleNode);
}
function $isHorizontalRuleNode(node) {
  return node instanceof HorizontalRuleNode;
}
function $toggleNodeSelection(node, shiftKey = false) {
  const selection = lexical.$getSelection();
  const wasSelected = node.isSelected();
  const key = node.getKey();
  let nodeSelection;
  if (shiftKey && lexical.$isNodeSelection(selection)) {
    nodeSelection = selection;
  } else {
    nodeSelection = lexical.$createNodeSelection();
    lexical.$setSelection(nodeSelection);
  }
  if (wasSelected) {
    nodeSelection.delete(key);
  } else {
    nodeSelection.add(key);
  }
}

/**
 * An extension for HorizontalRuleNode that provides an implementation that
 * works without any React dependency.
 */
const HorizontalRuleExtension = lexical.defineExtension({
  dependencies: [EditorStateExtension, NodeSelectionExtension],
  name: '@lexical/extension/HorizontalRule',
  nodes: () => [HorizontalRuleNode],
  register(editor, config, state) {
    const {
      watchNodeKey
    } = state.getDependency(NodeSelectionExtension).output;
    const nodeSelectionStore = a({
      nodeSelections: new Map()
    });
    const isSelectedClassName = editor._config.theme.hrSelected ?? 'selected';
    return lexical.mergeRegister(editor.registerCommand(INSERT_HORIZONTAL_RULE_COMMAND, type => {
      const selection = lexical.$getSelection();
      if (!lexical.$isRangeSelection(selection)) {
        return false;
      }
      const focusNode = selection.focus.getNode();
      if (focusNode !== null) {
        const horizontalRuleNode = $createHorizontalRuleNode();
        utils.$insertNodeToNearestRoot(horizontalRuleNode);
      }
      return true;
    }, lexical.COMMAND_PRIORITY_EDITOR), editor.registerCommand(lexical.CLICK_COMMAND, event => {
      if (lexical.isDOMNode(event.target)) {
        const node = lexical.$getNodeFromDOMNode(event.target);
        if ($isHorizontalRuleNode(node)) {
          $toggleNodeSelection(node, event.shiftKey);
          return true;
        }
      }
      return false;
    }, lexical.COMMAND_PRIORITY_LOW), editor.registerMutationListener(HorizontalRuleNode, (nodes, payload) => {
      n(() => {
        let didChange = false;
        const {
          nodeSelections
        } = nodeSelectionStore.peek();
        for (const [k, v] of nodes.entries()) {
          if (v === 'destroyed') {
            nodeSelections.delete(k);
            didChange = true;
          } else {
            const prev = nodeSelections.get(k);
            const dom = editor.getElementByKey(k);
            if (prev) {
              prev.domNode.value = dom;
            } else {
              didChange = true;
              nodeSelections.set(k, {
                domNode: a(dom),
                selectedSignal: watchNodeKey(k)
              });
            }
          }
        }
        if (didChange) {
          nodeSelectionStore.value = {
            nodeSelections
          };
        }
      });
    }), j(() => {
      const effects = [];
      for (const {
        domNode,
        selectedSignal
      } of nodeSelectionStore.value.nodeSelections.values()) {
        effects.push(j(() => {
          const dom = domNode.value;
          if (dom) {
            const isSelected = selectedSignal.value;
            if (isSelected) {
              lexical.addClassNamesToElement(dom, isSelectedClassName);
            } else {
              lexical.removeClassNamesFromElement(dom, isSelectedClassName);
            }
          }
        }));
      }
      return lexical.mergeRegister(...effects);
    }));
  }
});

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

function $defaultGetParentEditor() {
  const editor = lexical.$getEditor();
  LexicalBuilder.fromEditor(editor);
  return editor;
}
const NestedEditorExtension = lexical.defineExtension({
  build: (editor, config) => namedSignals({
    inheritEditableFromParent: config.inheritEditableFromParent
  }),
  config: lexical.safeCast({
    $getParentEditor: $defaultGetParentEditor,
    inheritEditableFromParent: false
  }),
  init: (editorConfig, config, state) => {
    const parentEditor = config.$getParentEditor();
    editorConfig.parentEditor = parentEditor;
    editorConfig.theme = editorConfig.theme || parentEditor._config.theme;
  },
  name: '@lexical/extension/NestedEditor',
  register: (editor, config, state) => j(() => {
    const parentEditor = editor._parentEditor;
    if (parentEditor) {
      if (state.getOutput().inheritEditableFromParent.value) {
        editor.setEditable(parentEditor.isEditable());
        return parentEditor.registerEditableListener(editor.setEditable.bind(editor));
      }
    }
  })
});

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

/**
 * An extension that highlights selected content in the Lexical editor
 * even when the editor is not currently focused.
 */
const SelectionAlwaysOnDisplayExtension = lexical.defineExtension({
  build: (editor, config, state) => namedSignals(config),
  config: lexical.safeCast({
    disabled: false,
    onReposition: undefined
  }),
  name: '@lexical/utils/SelectionAlwaysOnDisplay',
  register: (editor, config, state) => {
    const stores = state.getOutput();
    return j(() => {
      if (!stores.disabled.value) {
        return utils.selectionAlwaysOnDisplay(editor, stores.onReposition.value);
      }
    });
  }
});

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

function $indentOverTab(selection) {
  // const handled = new Set();
  const nodes = selection.getNodes();
  const canIndentBlockNodes = nodes.filter(node => lexical.$isBlockElementNode(node) && node.canIndent());
  // 1. If selection spans across canIndent block nodes: indent
  if (canIndentBlockNodes.length > 0) {
    return true;
  }
  // 2. If first (anchor/focus) is at block start: indent
  const anchor = selection.anchor;
  const focus = selection.focus;
  const first = focus.isBefore(anchor) ? focus : anchor;
  const firstNode = first.getNode();
  const firstBlock = utils.$getNearestBlockElementAncestorOrThrow(firstNode);
  if (firstBlock.canIndent()) {
    const firstBlockKey = firstBlock.getKey();
    let selectionAtStart = lexical.$createRangeSelection();
    selectionAtStart.anchor.set(firstBlockKey, 0, 'element');
    selectionAtStart.focus.set(firstBlockKey, 0, 'element');
    selectionAtStart = lexical.$normalizeSelection__EXPERIMENTAL(selectionAtStart);
    if (selectionAtStart.anchor.is(first)) {
      return true;
    }
  }
  // 3. Else: tab
  return false;
}
function $defaultCanIndent(node) {
  return node.canBeEmpty();
}
function registerTabIndentation(editor, maxIndent, $canIndent = $defaultCanIndent) {
  return lexical.mergeRegister(editor.registerCommand(lexical.KEY_TAB_COMMAND, event => {
    const selection = lexical.$getSelection();
    if (!lexical.$isRangeSelection(selection)) {
      return false;
    }
    event.preventDefault();
    const command = $indentOverTab(selection) ? event.shiftKey ? lexical.OUTDENT_CONTENT_COMMAND : lexical.INDENT_CONTENT_COMMAND : lexical.INSERT_TAB_COMMAND;
    return editor.dispatchCommand(command, undefined);
  }, lexical.COMMAND_PRIORITY_EDITOR), editor.registerCommand(lexical.INDENT_CONTENT_COMMAND, () => {
    const currentMaxIndent = typeof maxIndent === 'number' ? maxIndent : maxIndent ? maxIndent.peek() : null;
    const selection = lexical.$getSelection();
    if (!lexical.$isRangeSelection(selection)) {
      return false;
    }
    const $currentCanIndent = typeof $canIndent === 'function' ? $canIndent : $canIndent.peek();
    return utils.$handleIndentAndOutdent(block => {
      if ($currentCanIndent(block)) {
        const newIndent = block.getIndent() + 1;
        if (!currentMaxIndent || newIndent < currentMaxIndent) {
          block.setIndent(newIndent);
        }
      }
    });
  }, lexical.COMMAND_PRIORITY_CRITICAL));
}
/**
 * This extension adds the ability to indent content using the tab key. Generally, we don't
 * recommend using this plugin as it could negatively affect accessibility for keyboard
 * users, causing focus to become trapped within the editor.
 */
const TabIndentationExtension = lexical.defineExtension({
  build(editor, config, state) {
    return namedSignals(config);
  },
  config: lexical.safeCast({
    $canIndent: $defaultCanIndent,
    disabled: false,
    maxIndent: null
  }),
  name: '@lexical/extension/TabIndentation',
  register(editor, config, state) {
    const {
      disabled,
      maxIndent,
      $canIndent
    } = state.getOutput();
    return j(() => {
      if (!disabled.value) {
        return registerTabIndentation(editor, maxIndent, $canIndent);
      }
    });
  }
});

exports.configExtension = lexical.configExtension;
exports.declarePeerDependency = lexical.declarePeerDependency;
exports.defineExtension = lexical.defineExtension;
exports.safeCast = lexical.safeCast;
exports.shallowMergeConfig = lexical.shallowMergeConfig;
exports.$createHorizontalRuleNode = $createHorizontalRuleNode;
exports.$isDecoratorTextNode = $isDecoratorTextNode;
exports.$isHorizontalRuleNode = $isHorizontalRuleNode;
exports.AutoFocusExtension = AutoFocusExtension;
exports.ClearEditorExtension = ClearEditorExtension;
exports.DecoratorTextExtension = DecoratorTextExtension;
exports.DecoratorTextNode = DecoratorTextNode;
exports.EditorStateExtension = EditorStateExtension;
exports.HorizontalRuleExtension = HorizontalRuleExtension;
exports.HorizontalRuleNode = HorizontalRuleNode;
exports.INSERT_HORIZONTAL_RULE_COMMAND = INSERT_HORIZONTAL_RULE_COMMAND;
exports.InitialStateExtension = InitialStateExtension;
exports.LexicalBuilder = LexicalBuilder;
exports.NestedEditorExtension = NestedEditorExtension;
exports.NodeSelectionExtension = NodeSelectionExtension;
exports.SelectionAlwaysOnDisplayExtension = SelectionAlwaysOnDisplayExtension;
exports.TabIndentationExtension = TabIndentationExtension;
exports.applyFormatFromStyle = applyFormatFromStyle;
exports.applyFormatToDom = applyFormatToDom;
exports.batch = n;
exports.buildEditorFromExtensions = buildEditorFromExtensions;
exports.computed = g;
exports.effect = j;
exports.getExtensionDependencyFromEditor = getExtensionDependencyFromEditor;
exports.getKnownTypesAndNodes = getKnownTypesAndNodes;
exports.getPeerDependencyFromEditor = getPeerDependencyFromEditor;
exports.getPeerDependencyFromEditorOrThrow = getPeerDependencyFromEditorOrThrow;
exports.namedSignals = namedSignals;
exports.registerClearEditor = registerClearEditor;
exports.registerTabIndentation = registerTabIndentation;
exports.signal = a;
exports.untracked = h;
exports.watchedSignal = watchedSignal;
