foldkit-richtext 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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["pathKey","pathKey","pathKey"],"sources":["../src/document.ts","../src/marks.ts","../src/rendering.ts","../src/html.ts","../src/clipboard.ts","../src/transform.ts","../src/transaction.ts","../src/command.ts","../src/history.ts","../src/kit.ts","../src/migration.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Caller-assigned identity, unique across blocks and text runs in a document. */\nexport const NodeId = Schema.NonEmptyString.pipe(Schema.brand('foldkit-richtext/NodeId'))\nexport type NodeId = typeof NodeId.Type\n\n/** The mark names this vocabulary defines; a document may hold others verbatim. */\nexport const Mark = Schema.Literals(['Bold', 'Italic', 'Code'])\nexport type Mark = typeof Mark.Type\n\n/** A schema this version can hand to `decodeUnknownSync` at a Kit boundary. */\nexport type PropsSchema = Schema.Codec<any, any, never>\n\n/**\n * A mark with props: which mark, plus the JSON data it carries. Props are JSON\n * here for the same reason a node's are: the document codec cannot know an\n * application's schemas, so a Kit validates them at that boundary (§12).\n */\nexport const MarkValue = Schema.Struct({\n name: Schema.NonEmptyString,\n props: Schema.optionalKey(Schema.JsonObject),\n})\nexport type MarkValue = typeof MarkValue.Type\n\n/**\n * A mark as a text run stores it: a bare name for a mark with no props, or a\n * value when it has them. Loading preserves the form it found, so a names-only\n * document round-trips byte-equal, and because a run carries a name at most once\n * it never holds both forms of one mark.\n */\nexport const RunMark = Schema.Union([Schema.NonEmptyString, MarkValue])\nexport type RunMark = typeof RunMark.Type\n\n/** A mark's name: a bare string is a mark with no props, an object carries them. */\nexport const markName = (mark: RunMark): string => (typeof mark === 'string' ? mark : mark.name)\n\n/**\n * The content a block holds: runs, or nested blocks (§13). A document does not\n * declare which a block kind accepts — its Kit does — so these are the words a\n * declaration and a migration both use.\n */\nexport const textContent = 'text' as const\nexport const blockContent = 'blocks' as const\nexport type ContentMode = typeof textContent | typeof blockContent\n\n/**\n * The wire shape of a value: the same structure with identities unbranded. A\n * branded `NodeId` encodes as a plain string, so an annotated schema whose type\n * mentions one cannot claim its encoded form is the type itself; this names the\n * wire side, which the recursive block schema needs to break its type cycle.\n */\ntype Wire<T> = T extends NodeId\n ? string\n : T extends ReadonlyArray<infer E>\n ? ReadonlyArray<Wire<E>>\n : T extends object\n ? { readonly [K in keyof T]: Wire<T[K]> }\n : T\n\nexport const Text = Schema.Struct({\n type: Schema.Literal('Text'),\n id: NodeId,\n text: Schema.String,\n // A mark name this version does not define loads verbatim; `Edit.addMark`\n // still accepts only what the caller's vocabulary declares. A run carries a\n // name at most once; see `findUnknownMarks` for the publishing gate.\n marks: Schema.Array(RunMark).check(\n Schema.makeFilter(\n marks => new Set(marks.map(markName)).size === marks.length || 'Invalid marks',\n ),\n ),\n})\nexport type Text = typeof Text.Type\n\nexport const Paragraph = Schema.Struct({\n type: Schema.Literal('Paragraph'),\n id: NodeId,\n children: Schema.Array(Text),\n})\nexport type Paragraph = typeof Paragraph.Type\n\nexport const Heading = Schema.Struct({\n type: Schema.Literal('Heading'),\n id: NodeId,\n level: Schema.Literals([1, 2, 3, 4, 5, 6]),\n children: Schema.Array(Text),\n})\nexport type Heading = typeof Heading.Type\n\n/**\n * A block whose `type` this version does not implement, retained verbatim for\n * recovery and migration: the original type, its remaining JSON fields, and no\n * text runs (its subtree lives in `props`, opaque). Unknown blocks are\n * read-only content: address them structurally, never edit their text.\n */\nexport const UnknownBlock = Schema.Struct({\n type: Schema.Literal('Unknown'),\n id: NodeId,\n originalType: Schema.NonEmptyString,\n props: Schema.JsonObject,\n children: Schema.Array(Text).check(\n Schema.makeFilter(runs => runs.length === 0 || 'Unknown blocks keep no text runs'),\n ),\n})\nexport type UnknownBlock = typeof UnknownBlock.Type\n\n/**\n * A block whose kind the application declares: a Callout, an Image, an embed.\n * `props` is JSON at the codec level because the document codec cannot know an\n * application's schemas; a Kit's node definition validates it at that boundary,\n * and runtime declarations stay outside the codec (§12). `children` are text\n * runs, so positions, operations, and selection work on it unchanged.\n *\n * `blocks` holds nested blocks, and its presence is what says the kind accepts\n * them (§116): a List holds ListItems, a Quote holds paragraphs. A kind with\n * nested blocks has no direct runs, which is why `children` stays `Text[]` on\n * every block kind — a container simply leaves it empty, as `UnknownBlock` does.\n *\n * The shape is written by hand because `Block` and this type are mutually\n * recursive, and TypeScript cannot infer through that cycle: the schema's\n * nested field names the interface, and the interface names the union.\n */\nexport interface NodeBlock {\n readonly type: 'Node'\n readonly kind: string\n readonly id: NodeId\n readonly props: Schema.JsonObject\n readonly children: ReadonlyArray<Text>\n readonly blocks?: ReadonlyArray<Block>\n}\n\nexport const NodeBlock = Schema.Struct({\n type: Schema.Literal('Node'),\n kind: Schema.NonEmptyString,\n id: NodeId,\n props: Schema.JsonObject,\n children: Schema.Array(Text),\n blocks: Schema.optionalKey(\n Schema.suspend((): Schema.Codec<ReadonlyArray<Block>, Wire<ReadonlyArray<Block>>> =>\n Schema.Array(Block),\n ),\n ),\n}).check(\n Schema.makeFilter(\n block =>\n block.blocks === undefined ||\n block.children.length === 0 ||\n 'A block with nested blocks keeps no direct runs',\n ),\n)\n\nexport type Block = Paragraph | Heading | NodeBlock | UnknownBlock\nexport const Block = Schema.Union([Paragraph, Heading, NodeBlock, UnknownBlock])\n\n/** Every identity a block subtree owns, block and run alike, in document order. */\nconst subtreeIds = (block: Block): ReadonlyArray<NodeId> => [\n block.id,\n ...block.children.map(run => run.id),\n ...(block.type === 'Node' && block.blocks !== undefined ? block.blocks.flatMap(subtreeIds) : []),\n]\n\n/** Version 1's initial block vocabulary, with document-wide identity validation. */\nexport const Document = Schema.Struct({\n version: Schema.Literal(1),\n children: Schema.Array(Block),\n}).check(\n Schema.makeFilter(document => {\n const ids = new Set<NodeId>()\n for (const block of document.children) {\n for (const id of subtreeIds(block)) {\n if (ids.has(id)) return 'Duplicate node identity'\n ids.add(id)\n }\n }\n return true\n }),\n)\nexport type Document = typeof Document.Type\n\nconst isKnownBlockType = (type: unknown): boolean =>\n type === 'Paragraph' || type === 'Heading' || type === 'Node'\n\n/**\n * Converts a block whose type this version does not implement into an `Unknown`\n * node, and does the same inside a known node block's nested blocks. Everything\n * except `type` and `id` becomes opaque JSON props; the raw subtree is preserved\n * there verbatim.\n */\nconst preserveBlock = (input: unknown): unknown => {\n if (typeof input !== 'object' || input === null) return input\n const block = input as Record<string, unknown>\n if (!isKnownBlockType(block.type) && block.type !== 'Unknown') {\n const { type, id, ...props } = block\n return { type: 'Unknown', id, originalType: type, props, children: [] }\n }\n return Array.isArray(block.blocks) ? { ...block, blocks: block.blocks.map(preserveBlock) } : block\n}\n\n/**\n * Converts blocks whose type this version does not implement into `Unknown`\n * nodes before structural decoding, so persisted content survives a deploy\n * that lost a node implementation. Nested blocks are walked for the same reason.\n */\nconst preserveUnknownBlocks = (input: unknown): unknown => {\n if (typeof input !== 'object' || input === null) return input\n const document = input as { children?: unknown }\n if (!Array.isArray(document.children)) return input\n return { ...document, children: document.children.map(preserveBlock) }\n}\n\n/** Strict boundary for persisted content. Throws a Schema error on invalid input. */\nconst decodeStructure = Schema.decodeUnknownSync(Document, { onExcessProperty: 'error' })\n\nconst PositiveCount = Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0))\n\n/** Bounds for decoded documents: blocks, text runs, and total UTF-16 text units. */\nexport const DocumentLimits = Schema.Struct({\n maxBlocks: PositiveCount,\n maxTextRuns: PositiveCount,\n maxTextLength: PositiveCount,\n})\nexport type DocumentLimits = typeof DocumentLimits.Type\n\n/** Generous DoS guardrails, not application quotas; tighten per document with a spread. */\nexport const DefaultDocumentLimits: DocumentLimits = DocumentLimits.make({\n maxBlocks: 10_000,\n maxTextRuns: 50_000,\n maxTextLength: 5_000_000,\n})\n\n/** Every block a subtree holds, nested ones included. */\nconst countBlocks = (blocks: ReadonlyArray<Block>): number => {\n let count = 0\n eachBlock(blocks, () => {\n count += 1\n })\n return count\n}\n\n/**\n * Strict boundary for persisted content. Decodes structure first, then enforces\n * `limits`. Throws a Schema error on invalid input, or an Error naming the\n * first exceeded bound.\n */\nexport const decodeDocument = (\n input: unknown,\n limits: DocumentLimits = DefaultDocumentLimits,\n): Document => {\n const document = decodeStructure(preserveUnknownBlocks(input))\n const summary = inspect(document)\n const blocks = countBlocks(document.children)\n const runs = summary.nodeCount - blocks\n if (blocks > limits.maxBlocks)\n throw new Error(`Document exceeds maxBlocks: ${blocks} > ${limits.maxBlocks}`)\n if (runs > limits.maxTextRuns)\n throw new Error(`Document exceeds maxTextRuns: ${runs} > ${limits.maxTextRuns}`)\n if (summary.textLength > limits.maxTextLength)\n throw new Error(\n `Document exceeds maxTextLength: ${summary.textLength} > ${limits.maxTextLength}`,\n )\n return document\n}\n\n/**\n * A block's address: root-first container indices. `[2]` is the third top-level\n * block, `[2, 0]` is the first block nested inside it (§116). A block's depth is\n * its path's length.\n */\nexport type BlockPath = ReadonlyArray<number>\n\n/** A stable key for a block path, so paths can key maps and compare cheaply. */\nexport const pathKey = (path: BlockPath): string => path.join('.')\n\n/** Walks every block subtree in document order, visiting each with its path. */\nexport const eachBlock = (\n blocks: ReadonlyArray<Block>,\n visit: (block: Block, path: BlockPath) => void,\n prefix: BlockPath = [],\n): void => {\n for (const [index, block] of blocks.entries()) {\n const path = [...prefix, index]\n visit(block, path)\n if (block.type === 'Node' && block.blocks !== undefined) eachBlock(block.blocks, visit, path)\n }\n}\n\n/** A run's place in document order: its block's path, then its index in that block. */\nexport interface RunPlace {\n readonly path: BlockPath\n readonly index: number\n}\n\n/** A run with the identity it was found by. */\nexport interface LocatedRun extends RunPlace {\n readonly run: Text\n}\n\n/** Document order over run places: path first, then the run's index. */\nexport const compareRunPlaces = (left: RunPlace, right: RunPlace): number => {\n const shared = Math.min(left.path.length, right.path.length)\n for (let index = 0; index < shared; index++) {\n if (left.path[index] !== right.path[index]) return left.path[index]! - right.path[index]!\n }\n if (left.path.length !== right.path.length) return left.path.length - right.path.length\n return left.index - right.index\n}\n\n/** The block a path addresses, or undefined when the path does not resolve. */\nexport const blockAtPath = (document: Document, path: BlockPath): Block | undefined => {\n let blocks: ReadonlyArray<Block> = document.children\n let found: Block | undefined\n for (const index of path) {\n found = blocks[index]\n if (found === undefined) return undefined\n blocks = found.type === 'Node' && found.blocks !== undefined ? found.blocks : []\n }\n return found\n}\n\n/** The block with this identity, wherever it sits. */\nexport const locateBlock = (\n document: Document,\n node: NodeId,\n): { readonly path: BlockPath; readonly block: Block } | undefined => {\n let found: { readonly path: BlockPath; readonly block: Block } | undefined\n eachBlock(document.children, (block, path) => {\n if (found === undefined && block.id === node) found = { path, block }\n })\n return found\n}\n\n/** The run with this identity, wherever it sits. */\nexport const locateRun = (document: Document, node: NodeId): LocatedRun | undefined => {\n let found: LocatedRun | undefined\n eachBlock(document.children, (block, path) => {\n if (found !== undefined) return\n const index = block.children.findIndex(run => run.id === node)\n if (index >= 0) found = { path, index, run: block.children[index]! }\n })\n return found\n}\n\n/** Every node a block subtree owns, block and run alike, keyed by identity. */\nconst indexNodes = (blocks: ReadonlyArray<Block>, nodes: Map<NodeId, Block | Text>): void => {\n eachBlock(blocks, block => {\n nodes.set(block.id, block)\n for (const run of block.children) nodes.set(run.id, run)\n })\n}\n\nconst isKnownMarkName = Schema.is(Mark)\n\n/** A mark this vocabulary does not define, kept verbatim on its text run. */\nexport interface UnknownMark {\n readonly node: NodeId\n /** The mark's name; its props, if any, stay on the run. */\n readonly mark: string\n}\n\n/** Lists unknown marks per text run; empty means the document publishes cleanly. */\nexport const findUnknownMarks = (document: Document): ReadonlyArray<UnknownMark> => {\n const unknown: Array<UnknownMark> = []\n eachBlock(document.children, block => {\n for (const text of block.children) {\n for (const mark of text.marks) {\n const name = markName(mark)\n if (!isKnownMarkName(name)) unknown.push({ node: text.id, mark: name })\n }\n }\n })\n return unknown\n}\n\n/** A block this vocabulary does not implement, retained for migration. */\nexport interface UnknownNode {\n readonly node: NodeId\n readonly originalType: string\n}\n\n/** Lists preserved unknown blocks; empty means the document publishes cleanly. */\nexport const findUnknownNodes = (document: Document): ReadonlyArray<UnknownNode> => {\n const unknown: Array<UnknownNode> = []\n eachBlock(document.children, block => {\n if (block.type === 'Unknown') {\n unknown.push({ node: block.id, originalType: block.originalType })\n }\n })\n return unknown\n}\n\n/** UTF-16 offset in one text run, with insertion affinity at that offset. */\nexport const Position = Schema.Struct({\n node: NodeId,\n offset: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),\n affinity: Schema.Literals(['before', 'after']),\n})\nexport type Position = typeof Position.Type\n\n/** A reusable identity resolved against an explicit document, without owning its content. */\nexport interface NodeReference {\n readonly id: NodeId\n /** Returns the current node, or undefined if this document does not contain it. */\n readonly read: (document: Document) => Block | Text | undefined\n /** Describes a text position; application of an edit checks the target and bounds. */\n readonly at: (offset: number, affinity: Position['affinity']) => Position\n}\n\nexport const Node = {\n /** Declares an immutable reference. Does not insert a node or reserve its ID. */\n make: (id: string): NodeReference => {\n const nodeId = NodeId.make(id)\n return Object.freeze({\n id: nodeId,\n read: (document: Document): Block | Text | undefined => {\n const nodes = new Map<NodeId, Block | Text>()\n indexNodes(document.children, nodes)\n return nodes.get(nodeId)\n },\n at: (offset: number, affinity: Position['affinity']): Position =>\n Position.make({ node: nodeId, offset, affinity }),\n })\n },\n}\n\nexport const Selection = Schema.Union([\n Schema.Struct({ type: Schema.Literal('Range'), anchor: Position, focus: Position }),\n Schema.Struct({ type: Schema.Literal('Node'), node: NodeId }),\n])\nexport type Selection = typeof Selection.Type\n\n/** Validates references without sorting range endpoints or changing direction. */\nexport const selectionIsValid = (document: Document, selection: Selection | null): boolean => {\n if (selection === null) return true\n const nodes = new Map<NodeId, Block | Text>()\n indexNodes(document.children, nodes)\n if (selection.type === 'Node') return nodes.has(selection.node)\n return [selection.anchor, selection.focus].every(position => {\n const node = nodes.get(position.node)\n return (\n node?.type === 'Text' &&\n Number.isInteger(position.offset) &&\n position.offset >= 0 &&\n position.offset <= node.text.length\n )\n })\n}\n\nexport const EditorState = Schema.Struct({\n document: Document,\n selection: Schema.NullOr(Selection),\n}).check(\n Schema.makeFilter(\n state => selectionIsValid(state.document, state.selection) || 'Unresolved selection',\n ),\n)\nexport type EditorState = typeof EditorState.Type\n\n/**\n * Counts semantic nodes and UTF-16 text units, and reports nesting depth. Depth\n * counts levels of content: an empty document is 0, blocks are 1, runs inside a\n * block are 2, and a block nested inside a block adds a level (§116).\n */\nexport const inspect = (document: Document) => {\n let nodeCount = 0\n let textLength = 0\n let depth = 0\n eachBlock(document.children, (block, path) => {\n nodeCount += 1 + block.children.length\n for (const text of block.children) textLength += text.text.length\n depth = Math.max(depth, path.length + (block.children.length > 0 ? 1 : 0))\n })\n return { nodeCount, textLength, depth }\n}\n","import { Equal, Schema } from 'effect'\nimport {\n markName,\n type Document,\n type MarkValue,\n type Position,\n type PropsSchema,\n type RunMark,\n} from './document.js'\n\nexport { markName }\n\n/** Which edges a mark continues across when typing at a run boundary. */\nexport type MarkExpansion = 'before' | 'after' | 'both' | 'none'\n\nconst decodeJsonProps = Schema.decodeUnknownSync(Schema.JsonObject)\n\n/**\n * A mark definition: its name, where it continues across a boundary, and the\n * schema its props must satisfy when it has any. A Kit declares the vocabulary\n * an editor accepts, so an application can say that its own mark behaves like a\n * link (nothing expands, an `href` prop) or like bold (it continues).\n */\nexport interface MarkDef<Props extends PropsSchema | undefined = PropsSchema | undefined> {\n readonly name: string\n readonly expand: MarkExpansion\n /** Validates a mark value's props at the Kit boundary, not in the codec. */\n readonly Props: Props\n /** Encodes decoded props into the JSON value stored on a text run. */\n readonly of: Props extends Schema.Codec<infer A, any, any>\n ? (props: A) => MarkValue\n : () => MarkValue\n}\n\n/**\n * Declares a mark. Expansion defaults to `both`: the conservative choice for a\n * name no policy knows. A definition with `Props` gets an `of` that builds the\n * value; a definition without props builds a value that carries only its name.\n */\nexport const mark = <Props extends PropsSchema | undefined = undefined>(\n name: string,\n options: { readonly Props?: Props; readonly expand?: MarkExpansion } = {},\n): MarkDef<Props> => {\n if (name.length === 0) throw new Error('RichText.mark: a mark needs a name')\n const encodeProps =\n options.Props === undefined\n ? undefined\n : Schema.encodeUnknownSync(options.Props, { onExcessProperty: 'error' })\n return {\n name,\n expand: options.expand ?? 'both',\n Props: options.Props as Props,\n of: ((props?: unknown): MarkValue => {\n if (encodeProps === undefined) return { name }\n // The stored value is the schema's *encoded* form: a transforming codec\n // (`NumberFromString`) must persist `'42'`, which is what Kit validation\n // decodes. Decoding the result against JSON keeps the boundary honest.\n return { name, props: decodeJsonProps(encodeProps(props)) }\n }) as MarkDef<Props>['of'],\n }\n}\n\nexport const Bold: MarkDef = mark('Bold', { expand: 'after' })\nexport const Italic: MarkDef = mark('Italic', { expand: 'after' })\nexport const Code: MarkDef = mark('Code', { expand: 'none' })\n\n/** The marks this vocabulary defines, and the policy a document without a Kit gets. */\nexport const shippedMarks: ReadonlyArray<MarkDef> = [Bold, Italic, Code]\n\n/**\n * The expansion policy of a set of definitions, and which names it declares. A\n * mark the registry does not declare expands both ways: preservation never\n * retargets it away. Declared names are what an edit may add.\n */\nexport interface MarkRegistry {\n readonly expansionOf: (name: string) => MarkExpansion\n readonly declares: (name: string) => boolean\n}\n\nexport const markRegistry = (definitions: ReadonlyArray<MarkDef>): MarkRegistry => {\n const byName = new Map(definitions.map(definition => [definition.name, definition.expand]))\n return {\n expansionOf: name => byName.get(name) ?? 'both',\n declares: name => byName.has(name),\n }\n}\n\n/** The policy of the shipped vocabulary. */\nexport const shippedRegistry: MarkRegistry = markRegistry(shippedMarks)\n\n/** A mark's props, or undefined when it carries none. */\nexport const markProps = (mark: RunMark): MarkValue['props'] | undefined =>\n typeof mark === 'string' ? undefined : mark.props\n\n/**\n * Whether two marks are the same mark with the same props. This is the\n * equivalence normalization merges on, so props compare structurally and key\n * order does not matter.\n */\nexport const sameMark = (left: RunMark, right: RunMark): boolean =>\n markName(left) === markName(right) && Equal.equals(markProps(left), markProps(right))\n\n/** Order-insensitive mark-set equality; a run carries a name at most once. */\nexport const sameMarkSet = (left: ReadonlyArray<RunMark>, right: ReadonlyArray<RunMark>): boolean =>\n left.length === right.length && left.every(mark => right.some(other => sameMark(mark, other)))\n\n/**\n * Retargets a boundary insertion to the neighboring run when the current run\n * carries marks that forbid the edge and the neighbor carries exactly the\n * marks that remain. Interior positions, missing neighbors, and mismatched\n * neighbors return the input reference unchanged; unknown node ids are left\n * for `apply` to diagnose. Never invents runs: mixed-mark edges stay put.\n */\nexport const resolveInsertion = (\n document: Document,\n position: Position,\n registry: MarkRegistry = shippedRegistry,\n): Position => {\n for (const block of document.children) {\n const index = block.children.findIndex(run => run.id === position.node)\n const run = block.children[index]\n if (run === undefined) continue\n const leavingLeft = position.affinity === 'before' && position.offset === 0\n const leavingRight = position.affinity === 'after' && position.offset === run.text.length\n if (!leavingLeft && !leavingRight) return position\n const neighbor = leavingLeft ? block.children[index - 1] : block.children[index + 1]\n if (neighbor === undefined) return position\n const direction = leavingLeft ? 'before' : 'after'\n const desired = run.marks.filter(mark => {\n const expand = registry.expansionOf(markName(mark))\n return expand === 'both' || expand === direction\n })\n if (!sameMarkSet(desired, neighbor.marks)) return position\n return {\n node: neighbor.id,\n offset: leavingLeft ? neighbor.text.length : 0,\n affinity: position.affinity,\n }\n }\n return position\n}\n","import type { NodeBlock, RunMark, Text } from './document.js'\nimport { markName } from './marks.js'\n\n/**\n * How an element is rendered: a tag and its attributes. Data, not a view (§121),\n * so the DOM-free serializer writes it and the DOM interpreters build it without\n * the core learning about Foldkit or the DOM.\n */\nexport interface ElementRendering {\n readonly tag: string\n /** Values are escaped when written; a name that would end the markup is refused. */\n readonly attributes: Readonly<Record<string, string>>\n}\n\n/**\n * A rendering entry: fixed data, or computed from the value being rendered, which\n * is how a mark's attributes reach its props. `undefined` means the entry does not\n * apply, so the name falls back the way an entry-less name does.\n */\nexport type RenderingEntry<Value> =\n ElementRendering | ((value: Value) => ElementRendering | undefined)\n\n/**\n * A vocabulary of renderings built *over* a Kit, never inside it (§34, §121). A\n * name with no entry renders the shipped way: its mark nests in `strong`, `em`, or\n * `code`, an application node keeps its default element, and any other name rides\n * on `data-marks` — which is what keeps the slice format and an HTML round trip\n * lossless rather than lossy.\n */\nexport interface Rendering {\n readonly marks: Readonly<Record<string, RenderingEntry<RunMark>>>\n readonly nodes: Readonly<Record<string, RenderingEntry<NodeBlock>>>\n}\n\n/** The nesting the shipped marks get, innermost first. */\nconst BUILT_IN_MARK_TAGS: ReadonlyArray<readonly [string, string]> = [\n ['Bold', 'strong'],\n ['Italic', 'em'],\n ['Code', 'code'],\n]\n\n/**\n * Own-property lookup: a mark or node name is document content, so a plain or\n * hand-built `Rendering` must not let `__proto__` resolve to a prototype.\n */\nconst entryFor = <Value>(\n entries: Readonly<Record<string, RenderingEntry<Value>>>,\n name: string,\n): RenderingEntry<Value> | undefined => (Object.hasOwn(entries, name) ? entries[name] : undefined)\n\nconst resolve = <Value>(\n entry: RenderingEntry<Value>,\n value: Value,\n): ElementRendering | undefined => (typeof entry === 'function' ? entry(value) : entry)\n\n/** A name's own entry map, with no prototype for a content-chosen name to reach. */\nconst entryMap = <Value>(\n entries: Readonly<Record<string, RenderingEntry<Value>>> | undefined,\n): Readonly<Record<string, RenderingEntry<Value>>> => {\n const map: Record<string, RenderingEntry<Value>> = Object.create(null)\n for (const [name, entry] of Object.entries(entries ?? {})) map[name] = entry\n return Object.freeze(map)\n}\n\nexport const rendering = (\n definition: {\n readonly marks?: Readonly<Record<string, RenderingEntry<RunMark>>>\n readonly nodes?: Readonly<Record<string, RenderingEntry<NodeBlock>>>\n } = {},\n): Rendering =>\n Object.freeze({ marks: entryMap(definition.marks), nodes: entryMap(definition.nodes) })\n\n/** The behaviour without a renderer: shipped tags for shipped marks, names otherwise. */\nexport const noRendering: Rendering = rendering()\n\n/** What a run's marks nest in, and which names nest nowhere. */\nexport interface RunRendering {\n /** Elements to wrap the run's text in, innermost first. */\n readonly nest: ReadonlyArray<ElementRendering>\n /** Names with neither an entry nor a shipped tag, sorted so output is stable. */\n readonly unrendered: ReadonlyArray<string>\n}\n\nconst byName = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0)\n\n/**\n * Resolves a run's marks to elements. Order is the vocabulary's, then names\n * alphabetically, never the order marks happen to be stored in — the same set of\n * marks must serialize the same way however it was assembled. An entry for a\n * shipped name replaces that name's tag but keeps its place in the nesting.\n */\nexport const runRendering = (definition: Rendering, run: Text): RunRendering => {\n const nest: Array<ElementRendering> = []\n const unrendered: Array<string> = []\n for (const [name, tag] of BUILT_IN_MARK_TAGS) {\n const mark = run.marks.find(candidate => markName(candidate) === name)\n if (mark === undefined) continue\n const entry = entryFor(definition.marks, name)\n nest.push(\n entry === undefined\n ? { tag, attributes: {} }\n : (resolve(entry, mark) ?? { tag, attributes: {} }),\n )\n }\n const others = run.marks\n .filter(mark => !BUILT_IN_MARK_TAGS.some(([name]) => name === markName(mark)))\n .sort((left, right) => byName(markName(left), markName(right)))\n for (const mark of others) {\n const name = markName(mark)\n const entry = entryFor(definition.marks, name)\n const element = entry === undefined ? undefined : resolve(entry, mark)\n if (element === undefined) unrendered.push(name)\n else nest.push(element)\n }\n return { nest, unrendered }\n}\n\n/** The element a node kind renders as, or undefined when no entry applies. */\nexport const nodeRendering = (\n definition: Rendering,\n block: NodeBlock,\n): ElementRendering | undefined => {\n const entry = entryFor(definition.nodes, block.kind)\n return entry === undefined ? undefined : resolve(entry, block)\n}\n","import type { Block, Document, Text } from './document.js'\nimport {\n noRendering,\n nodeRendering,\n runRendering,\n type ElementRendering,\n type Rendering,\n} from './rendering.js'\n\n/**\n * HTML is an interchange format, not the document model (§70). This serializer\n * exists so a copy can offer HTML to other applications and a preview can be\n * read by anything; nothing here is ever parsed back into authority. Unknown\n * marks survive as `data-marks` on a span and unknown blocks as a placeholder\n * carrying their original type, so a round trip through HTML cannot silently\n * invent formatting the document never had.\n *\n * A renderer (§121) decides which element a declared mark or node kind produces,\n * which is how a Link's `href` becomes a real attribute. Without one, this\n * fallback still carries mark *names*, and a mark's props travel in the slice\n * format, which is the lossless path.\n */\nexport type BlockList = ReadonlyArray<Block>\n\nconst escapeText = (text: string): string =>\n text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n\nconst escapeAttribute = (value: string): string =>\n escapeText(value).replace(/\"/g, '&quot;').replace(/'/g, '&#39;')\n\nconst TAG = /^[A-Za-z][-A-Za-z0-9]*$/\nconst ATTRIBUTE = /^[A-Za-z_:][-A-Za-z0-9_:.]*$/\n\n/**\n * Writes an element. An attribute *value* is content and is escaped; a tag or\n * attribute *name* is refused rather than written when malformed, because a name\n * cannot be escaped — one holding a quote, a space, or `>` would end the attribute\n * and inject markup. A well-formed but unwise name (an event handler built from a\n * mark's props, say) is the application's own decision to make.\n */\nconst renderElement = (element: ElementRendering, inner: string): string => {\n if (!TAG.test(element.tag)) throw new Error(`RichText.toHtml: invalid tag \"${element.tag}\"`)\n const attributes = Object.entries(element.attributes)\n .map(([name, value]) => {\n if (!ATTRIBUTE.test(name))\n throw new Error(`RichText.toHtml: invalid attribute name \"${name}\"`)\n return ` ${name}=\"${escapeAttribute(value)}\"`\n })\n .join('')\n return `<${element.tag}${attributes}>${inner}</${element.tag}>`\n}\n\nconst renderRun = (run: Text, renderer: Rendering): string => {\n const { nest, unrendered } = runRendering(renderer, run)\n let html = escapeText(run.text)\n for (const element of nest) html = renderElement(element, html)\n return unrendered.length === 0\n ? html\n : `<span data-marks=\"${escapeAttribute(unrendered.join(' '))}\">${html}</span>`\n}\n\nconst blockTag = (block: Block): string => {\n if (block.type === 'Heading') return `h${block.level}`\n return block.type === 'Node' ? 'div' : 'p'\n}\n\nconst renderBlock = (block: Block, renderer: Rendering): string => {\n if (block.type === 'Unknown')\n return `<div data-unknown=\"${escapeAttribute(block.originalType)}\"></div>`\n const runs = block.children.map(run => renderRun(run, renderer)).join('')\n // A node that accepts nested blocks renders them inside it, so a list keeps\n // its items.\n const nested =\n block.type === 'Node' && block.blocks !== undefined ? toHtml(block.blocks, renderer) : ''\n // An application node carries its kind so a stylesheet can reach it; a renderer\n // entry replaces this default element entirely.\n const element = (block.type === 'Node' ? nodeRendering(renderer, block) : undefined) ?? {\n tag: blockTag(block),\n attributes: block.type === 'Node' ? { 'data-node': block.kind } : {},\n }\n return renderElement(element, `${runs}${nested}`)\n}\n\n/** Serializes blocks as HTML, with text and attributes escaped. */\nexport const toHtml = (blocks: BlockList, renderer: Rendering = noRendering): string =>\n blocks.map(block => renderBlock(block, renderer)).join('')\n\n/**\n * Plain text of blocks, one line per text block; unknown blocks keep a\n * placeholder and a container contributes its children's lines.\n */\nexport const toText = (blocks: BlockList): string => {\n const lines: Array<string> = []\n const walk = (current: BlockList): void => {\n for (const block of current) {\n if (block.type === 'Unknown') {\n lines.push(`[${block.originalType}]`)\n continue\n }\n if (block.type === 'Node' && block.blocks !== undefined) {\n walk(block.blocks)\n continue\n }\n lines.push(block.children.map(run => run.text).join(''))\n }\n }\n walk(blocks)\n return lines.join('\\n')\n}\n\n/** Convenience for a whole document, whose blocks are its children. */\nexport const documentToHtml = (document: Document, renderer?: Rendering): string =>\n toHtml(document.children, renderer)\nexport const documentToText = (document: Document): string => toText(document.children)\n","import { Schema } from 'effect'\nimport { toText } from './html.js'\nimport {\n Block,\n NodeId,\n blockAtPath,\n compareRunPlaces,\n eachBlock,\n locateBlock,\n locateRun,\n pathKey,\n type BlockPath,\n type Document,\n type RunPlace,\n type Selection,\n type Text,\n} from './document.js'\n\n/**\n * Clipboard content is semantic, not HTML (§69). A slice is a versioned,\n * identity-carrying fragment of a document: it round-trips through an\n * application's own format, and a paste mints fresh identities so nothing\n * collides with the document it lands in. HTML and plain text are interchange\n * fallbacks the adapter adds; they are not the slice.\n */\nexport const Slice = Schema.Struct({\n version: Schema.Literal(1),\n blocks: Schema.Array(Block),\n}).check(\n Schema.makeFilter(slice => {\n const ids = new Set<NodeId>()\n let duplicate = false\n eachBlock(slice.blocks, block => {\n for (const id of [block.id, ...block.children.map(run => run.id)]) {\n if (ids.has(id)) duplicate = true\n ids.add(id)\n }\n })\n return !duplicate || 'Duplicate slice identity'\n }),\n)\nexport type Slice = typeof Slice.Type\n\nexport const emptySlice: Slice = Object.freeze({ version: 1, blocks: [] })\n\nconst decodeSlice = Schema.decodeUnknownSync(Slice, { onExcessProperty: 'error' })\nconst encodeSlice = Schema.encodeSync(Slice)\n\nconst trim = (run: Text, from: number, to: number): Text => ({\n ...run,\n text: run.text.slice(from, to),\n})\n\n/** A covered span: the two endpoints, ordered, each with its offset in its run. */\ninterface CoveredSpan {\n readonly start: RunPlace & { readonly offset: number }\n readonly end: RunPlace & { readonly offset: number }\n}\n\n/** Whether a block's subtree contains an endpoint, or sits between the two. */\nconst inRange = (blockPath: BlockPath, span: CoveredSpan): boolean => {\n const contains = (place: RunPlace): boolean =>\n blockPath.length <= place.path.length &&\n blockPath.every((index, depth) => place.path[depth] === index)\n if (contains(span.start) || contains(span.end)) return true\n const first = { path: blockPath, index: 0 }\n return compareRunPlaces(first, span.start) > 0 && compareRunPlaces(first, span.end) < 0\n}\n\n/** The runs of one block that the span covers, trimmed to it. */\nconst coveredRuns = (\n block: Block,\n blockPath: BlockPath,\n span: CoveredSpan,\n): ReadonlyArray<Text> => {\n const atStart = pathKey(blockPath) === pathKey(span.start.path)\n const atEnd = pathKey(blockPath) === pathKey(span.end.path)\n if (!atStart && !atEnd) return block.children\n const from = atStart ? span.start.index : 0\n const to = atEnd ? span.end.index : block.children.length - 1\n const children: Array<Text> = []\n for (const [index, run] of block.children.entries()) {\n if (index < from || index > to) continue\n const trimFrom = index === from && atStart ? span.start.offset : 0\n const trimTo = index === to && atEnd ? span.end.offset : run.text.length\n if (trimFrom >= trimTo) continue\n children.push(trim(run, trimFrom, trimTo))\n }\n return children\n}\n\n/**\n * The covered part of a block list: the blocks the span reaches, each trimmed to\n * it. A container is kept with the children the span reaches, so copying across\n * two list items carries the list rather than two loose paragraphs.\n */\nconst coveredBlocks = (\n blocks: ReadonlyArray<Block>,\n prefix: BlockPath,\n span: CoveredSpan,\n): ReadonlyArray<Block> => {\n const covered: Array<Block> = []\n for (const [index, block] of blocks.entries()) {\n const path = [...prefix, index]\n if (!inRange(path, span)) continue\n if (block.type === 'Unknown') {\n covered.push(block)\n continue\n }\n const children = coveredRuns(block, path, span)\n if (block.type === 'Node' && block.blocks !== undefined) {\n const nested = coveredBlocks(block.blocks, path, span)\n if (children.length === 0 && nested.length === 0) continue\n covered.push({ ...block, children, blocks: nested })\n continue\n }\n if (children.length === 0) continue\n covered.push({ ...block, children })\n }\n return covered\n}\n\n/**\n * The semantic content a copy would take: a whole block for a node selection,\n * and for a range only the covered part of what it reaches, with runs trimmed to\n * the selection. Blocks the range never enters are left out, so a partial copy\n * never drags a paragraph along.\n */\nexport const sliceOf = (document: Document, selection: Selection | null): Slice | undefined => {\n if (selection === null) return undefined\n if (selection.type === 'Node') {\n const located = locateBlock(document, selection.node)\n return located === undefined ? undefined : { version: 1, blocks: [located.block] }\n }\n const anchor = locateRun(document, selection.anchor.node)\n const focus = locateRun(document, selection.focus.node)\n if (anchor === undefined || focus === undefined) return undefined\n const anchorPlace = { ...anchor, offset: selection.anchor.offset }\n const focusPlace = { ...focus, offset: selection.focus.offset }\n const span: CoveredSpan =\n compareRunPlaces(anchor, focus) <= 0\n ? { start: anchorPlace, end: focusPlace }\n : { start: focusPlace, end: anchorPlace }\n // A span inside one block copies that block, as it does at the top level; a\n // span across blocks keeps the containers that hold them, so copying across\n // two list items carries the list.\n if (pathKey(span.start.path) === pathKey(span.end.path)) {\n const block = blockAtPath(document, span.start.path)\n if (block === undefined || block.type === 'Unknown') return { version: 1, blocks: [] }\n const children = coveredRuns(block, span.start.path, span)\n return { version: 1, blocks: children.length === 0 ? [] : [{ ...block, children }] }\n }\n return { version: 1, blocks: coveredBlocks(document.children, [], span) }\n}\n\n/**\n * Plain text of a slice, one line per text block. A slice and a block list have\n * the same shape, so the serializer's walk serves both.\n */\nexport const plainTextOf = (slice: Slice): string => toText(slice.blocks)\n\n/**\n * A slice from pasted plain text: one paragraph per line. Identities come from\n * the caller, like every other identity a live edit mints.\n */\nexport const sliceFromText = (text: string, mint: () => string): Slice => ({\n version: 1,\n blocks: text.split(/\\r\\n|\\r|\\n/).map(line => ({\n type: 'Paragraph' as const,\n id: NodeId.make(mint()),\n children: [\n {\n type: 'Text' as const,\n id: NodeId.make(mint()),\n text: line,\n marks: [],\n },\n ],\n })),\n})\n\n/** The same content under fresh identities, so a paste can never collide. */\nexport const withFreshIds = (slice: Slice, mint: () => string): Slice => {\n // Pre-order: a block's identity, then its runs, then its nested blocks.\n const freshBlock = (block: Block): Block => {\n const id = NodeId.make(mint())\n const children = block.children.map(run => ({ ...run, id: NodeId.make(mint()) }))\n if (block.type === 'Node' && block.blocks !== undefined) {\n return { ...block, id, children, blocks: block.blocks.map(freshBlock) }\n }\n return { ...block, id, children }\n }\n return { version: 1, blocks: slice.blocks.map(freshBlock) }\n}\n\n/** Encodes a slice for the clipboard. */\nexport const serializeSlice = (slice: Slice): string => JSON.stringify(encodeSlice(slice))\n\n/** Decodes a slice, or undefined when the payload is not one this version wrote. */\nexport const deserializeSlice = (input: unknown): Slice | undefined => {\n try {\n return decodeSlice(typeof input === 'string' ? JSON.parse(input) : input)\n } catch {\n return undefined\n }\n}\n","import { NodeId, type Block, type Document, type Text } from './document.js'\nimport { sameMarkSet } from './marks.js'\nimport type { CollapseStep, PositionStep, RelocateStep, SplitStep } from './transaction.js'\n\n/**\n * Transforms normalize or derive semantic structure after edits (§23). A\n * transform is a pure function of the document plus what the transaction\n * touched: it returns a whole new document and the position steps and identity\n * bookkeeping that go with it, so `apply` can fold it into the same ChangeSet\n * and position map it was already building.\n *\n * Two rules make a registry safe to run in a loop (§24): a transform must be\n * deterministic, and it must be idempotent on normalized state — so running it\n * again after it has run changes nothing, which is how the loop knows it has\n * settled.\n */\nexport interface TransformContext {\n /** Blocks the transaction touched, plus whatever earlier transforms touched. */\n readonly dirtyNodes: ReadonlySet<NodeId>\n /** Runs already spent, so a transform can bail out rather than spin. */\n readonly pass: number\n}\n\nexport interface TransformReport {\n readonly document: Document\n /** The same step vocabulary a transaction uses, so `apply` can fold either. */\n readonly steps: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>\n readonly insertedNodes: ReadonlySet<NodeId>\n readonly removedNodes: ReadonlySet<NodeId>\n readonly dirtyNodes: ReadonlySet<NodeId>\n /** Runs whose text a transform rewrote, such as a merge's accumulator. */\n readonly textChanged: ReadonlySet<NodeId>\n /** Whether the block list changed shape, not just the runs inside a block. */\n readonly structureChanged: boolean\n}\n\nexport interface Transform {\n readonly name: string\n readonly apply: (document: Document, context: TransformContext) => TransformReport\n}\n\n/** A transform that found nothing to do. */\nexport const unchanged = (document: Document): TransformReport => ({\n document,\n steps: [],\n insertedNodes: new Set(),\n removedNodes: new Set(),\n dirtyNodes: new Set(),\n textChanged: new Set(),\n structureChanged: false,\n})\n\nconst mergeRunInto = (accumulator: Text, run: Text): Text => ({\n ...accumulator,\n text: accumulator.text + run.text,\n})\n\n/**\n * Merges adjacent runs whose mark sets match, within the blocks the transaction\n * touched. Merging strictly reduces the run count, so one pass reaches a stable\n * state and a second pass finds nothing: the rule is idempotent, and only equal\n * mark sets merge, so an unknown mark never drops.\n */\nexport const mergeAdjacentRuns: Transform = {\n name: 'mergeAdjacentRuns',\n apply: (document, context) => {\n const steps: Array<RelocateStep> = []\n const removedNodes = new Set<NodeId>()\n const dirtyNodes = new Set<NodeId>()\n const textChanged = new Set<NodeId>()\n let next: Document = document\n // One index for the whole pass: merging never adds or removes a block, so\n // looking each dirty block up in a Map keeps this linear in the blocks the\n // transaction touched instead of scanning the document per block.\n const blockIndexes = new Map(document.children.map((block, index) => [block.id, index]))\n for (const blockId of context.dirtyNodes) {\n const blockIndex = blockIndexes.get(blockId)\n if (blockIndex === undefined) continue\n const block = next.children[blockIndex]!\n const first = block.children[0]\n if (first === undefined) continue\n let accumulator = first\n let changed = false\n const kept: Array<Text> = [accumulator]\n for (const run of block.children.slice(1)) {\n if (sameMarkSet(accumulator.marks, run.marks)) {\n steps.push({\n node: run.id,\n into: accumulator.id,\n at: 0,\n base: accumulator.text.length,\n })\n accumulator = mergeRunInto(accumulator, run)\n kept[kept.length - 1] = accumulator\n removedNodes.add(run.id)\n dirtyNodes.add(accumulator.id)\n textChanged.add(accumulator.id)\n changed = true\n } else {\n accumulator = run\n kept.push(run)\n }\n }\n if (!changed) continue\n const blocks: Array<Block> = [...next.children]\n blocks[blockIndex] = { ...block, children: kept }\n next = { ...next, children: blocks }\n }\n return {\n document: next,\n steps,\n insertedNodes: new Set(),\n removedNodes,\n dirtyNodes,\n textChanged,\n structureChanged: false,\n }\n },\n}\n\n/** The transforms every transaction runs, in order, unless a caller says otherwise. */\nexport const defaultTransforms: ReadonlyArray<Transform> = [mergeAdjacentRuns]\n","import { Equal, Schema } from 'effect'\nimport { markName, resolveInsertion, sameMark } from './marks.js'\nimport {\n Block,\n eachBlock,\n EditorState,\n NodeId,\n Position,\n RunMark,\n Selection,\n blockAtPath,\n compareRunPlaces,\n selectionIsValid,\n type BlockPath,\n type Document,\n type NodeReference,\n type Text,\n} from './document.js'\nimport { defaultTransforms, type Transform } from './transform.js'\n\n/** How many normalization passes a transaction may spend before it gives up. */\nexport const MAX_NORMALIZATION_PASSES = 10\n\nconst Offset = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\nconst InsertTextOperation = Schema.Struct({\n type: Schema.Literal('InsertText'),\n at: Position,\n text: Schema.String,\n})\nconst DeleteTextOperation = Schema.Struct({\n type: Schema.Literal('DeleteText'),\n node: NodeId,\n from: Offset,\n to: Offset,\n})\nconst AddMarkOperation = Schema.Struct({\n type: Schema.Literal('AddMark'),\n node: NodeId,\n mark: RunMark,\n})\nconst RemoveMarkOperation = Schema.Struct({\n type: Schema.Literal('RemoveMark'),\n node: NodeId,\n mark: Schema.String,\n})\nconst SetSelectionOperation = Schema.Struct({\n type: Schema.Literal('SetSelection'),\n selection: Schema.NullOr(Selection),\n})\nconst SplitNodeOperation = Schema.Struct({\n type: Schema.Literal('SplitNode'),\n block: NodeId,\n node: NodeId,\n offset: Offset,\n blockId: NodeId,\n textId: NodeId,\n})\nconst JoinNodeOperation = Schema.Struct({\n type: Schema.Literal('JoinNode'),\n into: NodeId,\n removed: NodeId,\n})\nconst MoveNodeOperation = Schema.Struct({\n type: Schema.Literal('MoveNode'),\n node: NodeId,\n to: Offset,\n /** The block list to move into: a node block's, or the document's when absent. */\n parent: Schema.optionalKey(NodeId),\n})\nconst SetNodePropsOperation = Schema.Struct({\n type: Schema.Literal('SetNodeProps'),\n node: NodeId,\n level: Schema.Literals([1, 2, 3, 4, 5, 6]),\n})\nconst InsertNodeOperation = Schema.Struct({\n type: Schema.Literal('InsertNode'),\n block: Block,\n at: Offset,\n /** The block list to insert into: a node block's, or the document's when absent. */\n parent: Schema.optionalKey(NodeId),\n})\nconst DeleteNodeOperation = Schema.Struct({\n type: Schema.Literal('DeleteNode'),\n node: NodeId,\n})\nconst SplitRunOperation = Schema.Struct({\n type: Schema.Literal('SplitRun'),\n node: NodeId,\n offset: Offset,\n textId: NodeId,\n})\n\nexport const Operation = Schema.Union([\n InsertTextOperation,\n DeleteTextOperation,\n AddMarkOperation,\n RemoveMarkOperation,\n SetSelectionOperation,\n SplitNodeOperation,\n JoinNodeOperation,\n MoveNodeOperation,\n SetNodePropsOperation,\n InsertNodeOperation,\n DeleteNodeOperation,\n SplitRunOperation,\n])\nexport type Operation = typeof Operation.Type\nexport const Transaction = Schema.Array(Operation)\nexport type Transaction = typeof Transaction.Type\n\n/** A text-run target: a validated id or a reusable node reference. */\nexport type TextTarget = NodeId | NodeReference\n\nconst targetId = (target: TextTarget): NodeId => (typeof target === 'string' ? target : target.id)\n\n/** Accepts a raw string or validated id; empty strings throw via `NodeId`. */\nconst freshId = (id: string | NodeId): NodeId => (typeof id === 'string' ? NodeId.make(id) : id)\n\n/**\n * Typesafe constructors for transaction operations. Each builder accepts a\n * `NodeId` or a `Node.make` reference and validates shape immediately\n * (misuse throws), while document-dependent checks — node kind, existence,\n * bounds, selection resolution — remain `apply` diagnostics. Compose with\n * `Node.at` for positions: `Edit.insertText(Text.at(5, 'after'), '!')`.\n */\nexport const Edit = {\n insertText: (at: Position, text: string): Extract<Operation, { readonly type: 'InsertText' }> =>\n InsertTextOperation.make({ type: 'InsertText', at, text }),\n\n deleteText: (\n node: TextTarget,\n from: number,\n to: number,\n ): Extract<Operation, { readonly type: 'DeleteText' }> => {\n if (from > to) throw new Error(`Edit.deleteText: from (${from}) must not exceed to (${to})`)\n return DeleteTextOperation.make({ type: 'DeleteText', node: targetId(node), from, to })\n },\n\n addMark: (node: TextTarget, mark: RunMark): Extract<Operation, { readonly type: 'AddMark' }> =>\n AddMarkOperation.make({ type: 'AddMark', node: targetId(node), mark }),\n\n removeMark: (\n node: TextTarget,\n mark: string,\n ): Extract<Operation, { readonly type: 'RemoveMark' }> =>\n RemoveMarkOperation.make({ type: 'RemoveMark', node: targetId(node), mark }),\n\n setSelection: (\n selection: Selection | null,\n ): Extract<Operation, { readonly type: 'SetSelection' }> =>\n SetSelectionOperation.make({ type: 'SetSelection', selection }),\n\n splitBlock: (\n block: TextTarget,\n node: TextTarget,\n offset: number,\n newBlock: string | NodeId,\n newRun: string | NodeId,\n ): Extract<Operation, { readonly type: 'SplitNode' }> =>\n SplitNodeOperation.make({\n type: 'SplitNode',\n block: targetId(block),\n node: targetId(node),\n offset,\n blockId: freshId(newBlock),\n textId: freshId(newRun),\n }),\n\n joinBlocks: (\n survivor: TextTarget,\n removed: TextTarget,\n ): Extract<Operation, { readonly type: 'JoinNode' }> =>\n JoinNodeOperation.make({\n type: 'JoinNode',\n into: targetId(survivor),\n removed: targetId(removed),\n }),\n\n moveBlock: (\n node: TextTarget,\n to: number,\n parent?: TextTarget,\n ): Extract<Operation, { readonly type: 'MoveNode' }> =>\n MoveNodeOperation.make({\n type: 'MoveNode',\n node: targetId(node),\n to,\n ...(parent === undefined ? {} : { parent: targetId(parent) }),\n }),\n\n setNodeProps: (\n node: TextTarget,\n level: 1 | 2 | 3 | 4 | 5 | 6,\n ): Extract<Operation, { readonly type: 'SetNodeProps' }> =>\n SetNodePropsOperation.make({ type: 'SetNodeProps', node: targetId(node), level }),\n\n insertBlock: (\n block: Block,\n at: number,\n parent?: TextTarget,\n ): Extract<Operation, { readonly type: 'InsertNode' }> =>\n InsertNodeOperation.make({\n type: 'InsertNode',\n block,\n at,\n ...(parent === undefined ? {} : { parent: targetId(parent) }),\n }),\n\n deleteBlock: (node: TextTarget): Extract<Operation, { readonly type: 'DeleteNode' }> =>\n DeleteNodeOperation.make({ type: 'DeleteNode', node: targetId(node) }),\n\n splitRun: (\n node: TextTarget,\n offset: number,\n newRun: string | NodeId,\n ): Extract<Operation, { readonly type: 'SplitRun' }> =>\n SplitRunOperation.make({\n type: 'SplitRun',\n node: targetId(node),\n offset,\n textId: freshId(newRun),\n }),\n}\n\nexport interface ChangeSet {\n readonly dirtyNodes: ReadonlySet<NodeId>\n readonly insertedNodes: ReadonlySet<NodeId>\n readonly removedNodes: ReadonlySet<NodeId>\n readonly textChanged: ReadonlySet<NodeId>\n readonly structureChanged: boolean\n readonly selectionChanged: boolean\n}\n\n/** One replacement of [from, to) with inserted UTF-16 units, in sequential coordinates. */\nexport interface PositionStep {\n readonly node: NodeId\n readonly from: number\n readonly to: number\n readonly inserted: number\n}\n\n/**\n * Split relocation: offsets > at move to into with offset - at; offset == at\n * follows affinity (before stays, after moves to 0); lower offsets stay.\n */\nexport interface SplitStep {\n readonly node: NodeId\n readonly into: NodeId\n readonly at: number\n}\n\n/**\n * Merge relocation: offsets >= at move to into with base + offset - at;\n * lower offsets stay. Affinity is preserved, not consulted: the source\n * location ceases to exist, so every endpoint must move.\n */\nexport interface RelocateStep {\n readonly node: NodeId\n readonly into: NodeId\n readonly at: number\n readonly base: number\n}\n\n/**\n * Deletion collapse: every offset in node moves to offset 0 of into;\n * affinity is preserved. Emitted per removed run when a surviving run exists;\n * with no text left, positions cannot map and selection clears instead.\n */\nexport interface CollapseStep {\n readonly node: NodeId\n readonly into: NodeId\n}\n\n/** Maps a position through each edit, preserving insertion affinity. */\nexport const mapPosition = (\n position: Position,\n steps: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>,\n): Position =>\n steps.reduce((current, step) => {\n if (current.node !== step.node) return current\n if ('base' in step) {\n if (current.offset < step.at) return current\n return { ...current, node: step.into, offset: step.base + current.offset - step.at }\n }\n if ('at' in step) {\n if (current.offset < step.at) return current\n if (current.offset === step.at && current.affinity === 'before') return current\n return { ...current, node: step.into, offset: current.offset - step.at }\n }\n if ('into' in step) {\n return { ...current, node: step.into, offset: 0 }\n }\n if (current.offset < step.from) return current\n const offset =\n current.offset > step.to\n ? current.offset + step.inserted - (step.to - step.from)\n : step.from + (current.affinity === 'after' ? step.inserted : 0)\n return offset === current.offset ? current : { ...current, offset }\n }, position)\n\n/**\n * Maps a whole selection through steps: both range endpoints, or a node target\n * whose identity a step relocated. Steps that only replace text have no `into`,\n * so a node selection is unaffected by them.\n */\nexport const mapThrough = (\n selection: Selection | null,\n steps: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>,\n): Selection | null => {\n if (selection === null) return null\n if (selection.type === 'Node') {\n const step = steps.find(candidate => 'into' in candidate && candidate.node === selection.node)\n return step === undefined || !('into' in step) ? selection : { ...selection, node: step.into }\n }\n return {\n ...selection,\n anchor: mapPosition(selection.anchor, steps),\n focus: mapPosition(selection.focus, steps),\n }\n}\n\nexport type TransactionResult =\n | {\n readonly ok: true\n readonly state: EditorState\n readonly changeSet: ChangeSet\n readonly positionMap: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>\n }\n | {\n readonly ok: false\n readonly error:\n | 'InvalidInput'\n | 'MissingText'\n | 'MissingNode'\n | 'InvalidRange'\n | 'InvalidSelection'\n | 'InvalidParent'\n | 'UnstableNormalization'\n }\n\nconst decodeState = Schema.decodeUnknownSync(EditorState, { onExcessProperty: 'error' })\nconst decodeTransaction = Schema.decodeUnknownSync(Transaction, { onExcessProperty: 'error' })\nconst sameSelection = (left: Selection | null, right: Selection | null): boolean => {\n if (left === null || right === null) return left === right\n if (left.type === 'Node') return right.type === 'Node' && left.node === right.node\n if (right.type !== 'Range') return false\n return (['anchor', 'focus'] as const).every(\n key =>\n left[key].node === right[key].node &&\n left[key].offset === right[key].offset &&\n left[key].affinity === right[key].affinity,\n )\n}\n\n/** The nested block list of a container, or undefined for any other block. */\nconst nestedOf = (block: Block): ReadonlyArray<Block> | undefined =>\n block.type === 'Node' && block.blocks !== undefined ? block.blocks : undefined\n\n/**\n * A block's address: root-first container indices. `[2]` is the third top-level\n * block; `[2, 0]` is the first block nested inside it (§116). The document's own\n * block list is the container at `[]`.\n */\nconst pathKey = (path: BlockPath): string => path.join('.')\nconst keyToPath = (key: string): BlockPath => (key === '' ? [] : key.split('.').map(Number))\n\n/**\n * Pure, atomic text transaction. Rejection returns no partially edited state.\n * `transforms` defaults to the registry's shipped rules; a Kit's transforms\n * arrive here when Kit support lands.\n */\nexport const apply = (\n state: EditorState,\n transaction: Transaction,\n transforms: ReadonlyArray<Transform> = defaultTransforms,\n): TransactionResult => {\n try {\n decodeState(state)\n decodeTransaction(transaction)\n } catch {\n return { ok: false, error: 'InvalidInput' }\n }\n const indexDocument = (current: Document) => {\n const blockPaths = new Map<NodeId, BlockPath>()\n const runPaths = new Map<NodeId, { readonly path: BlockPath; readonly index: number }>()\n eachBlock(current.children, (block, path) => {\n blockPaths.set(block.id, path)\n for (const [runIndex, run] of block.children.entries()) {\n runPaths.set(run.id, { path, index: runIndex })\n }\n })\n return { blockPaths, runPaths }\n }\n let { blockPaths, runPaths } = indexDocument(state.document)\n const reindex = () => {\n ;({ blockPaths, runPaths } = indexDocument(document))\n }\n // Identities stay reserved for the whole transaction so a reused id can never\n // silently address two nodes across structural edits.\n const usedIds = new Set<NodeId>([...runPaths.keys(), ...blockPaths.keys()])\n let document: Document = state.document\n // Working copies: each touched container is copied once per transaction, so N\n // edits in one paragraph cost O(N) rather than N copies of the same array. A\n // container is a block list — the document's, or a node block's nested blocks —\n // and a block's runs are copied separately, keyed by that block's path.\n const workingBlocks = new Map<string, Array<Block>>()\n const workingRuns = new Map<string, Array<Text>>()\n const blockAt = (path: BlockPath): Block | undefined =>\n blocksAt(path.slice(0, -1))[path[path.length - 1]!]\n /** The block list at a container path, reading through any pending copy. */\n function blocksAt(containerPath: BlockPath): ReadonlyArray<Block> {\n const pending = workingBlocks.get(pathKey(containerPath))\n if (pending !== undefined) return pending\n if (containerPath.length === 0) return document.children\n const parent = blockAt(containerPath)\n return parent?.type === 'Node' && parent.blocks !== undefined ? parent.blocks : []\n }\n /** Copies a container, and its ancestors, once: writes never touch the input. */\n const ensureContainer = (containerPath: BlockPath): Array<Block> => {\n const key = pathKey(containerPath)\n const existing = workingBlocks.get(key)\n if (existing !== undefined) return existing\n if (containerPath.length > 0) ensureContainer(containerPath.slice(0, -1))\n const copy = [...blocksAt(containerPath)]\n workingBlocks.set(key, copy)\n return copy\n }\n /** The block's runs as they stand: a pending copy if one exists, else the document's. */\n const runsAt = (path: BlockPath): ReadonlyArray<Text> =>\n workingRuns.get(pathKey(path)) ?? blockAt(path)?.children ?? []\n /** The block's run array, copied on first write and mutated in place after. */\n const runArray = (path: BlockPath): Array<Text> => {\n const key = pathKey(path)\n const existing = workingRuns.get(key)\n if (existing !== undefined) return existing\n ensureContainer(path.slice(0, -1))\n const copy = [...(blockAt(path)?.children ?? [])]\n workingRuns.set(key, copy)\n return copy\n }\n const writeBlock = (path: BlockPath, block: Block): void => {\n const container = ensureContainer(path.slice(0, -1))\n container[path[path.length - 1]!] = block\n }\n /**\n * The block list a structural operation targets: the document's, or a node\n * block's nested blocks. A parent that cannot hold blocks is `InvalidParent`,\n * one that does not exist is `MissingNode`.\n */\n const containerPathOf = (\n parent: NodeId | undefined,\n ): { readonly path: BlockPath } | { readonly error: 'MissingNode' | 'InvalidParent' } => {\n if (parent === undefined) return { path: [] }\n const path = blockPaths.get(parent)\n if (path === undefined) return { error: 'MissingNode' }\n const block = blockAt(path)\n return block?.type === 'Node' && block.blocks !== undefined\n ? { path }\n : { error: 'InvalidParent' }\n }\n const materialize = (): void => {\n if (workingBlocks.size === 0 && workingRuns.size === 0) return\n // Runs fold into their block, then each container folds into its parent. A\n // container's copy already holds its child's final value, so the order of\n // the second pass does not matter; only touched containers are visited.\n for (const [key, runs] of workingRuns) {\n const path = keyToPath(key)\n const container = workingBlocks.get(pathKey(path.slice(0, -1)))!\n const index = path[path.length - 1]!\n container[index] = { ...container[index]!, children: runs }\n }\n workingRuns.clear()\n for (const [key, blocks] of workingBlocks) {\n const path = keyToPath(key)\n if (path.length === 0) {\n document = { ...document, children: blocks }\n continue\n }\n const parent = workingBlocks.get(pathKey(path.slice(0, -1)))!\n const index = path[path.length - 1]!\n const parentBlock = parent[index]!\n // Only a node block holds nested blocks, and only its path can be a\n // container, so this narrowing always holds.\n if (parentBlock.type === 'Node') parent[index] = { ...parentBlock, blocks }\n }\n workingBlocks.clear()\n }\n let selection = state.selection\n const dirtyNodes = new Set<NodeId>()\n const insertedNodes = new Set<NodeId>()\n const removedNodes = new Set<NodeId>()\n const textChanged = new Set<NodeId>()\n let structureChanged = false\n const positionMap: Array<PositionStep | SplitStep | RelocateStep | CollapseStep> = []\n for (let operationIndex = 0; operationIndex < transaction.length; operationIndex++) {\n const operation = transaction[operationIndex]!\n if (operation.type === 'SetSelection') {\n // A pending edit could change what a position resolves against.\n materialize()\n if (!selectionIsValid(document, operation.selection)) {\n return { ok: false, error: 'InvalidSelection' }\n }\n selection = operation.selection\n continue\n }\n if (operation.type === 'SplitRun') {\n const location = runPaths.get(operation.node)\n if (location === undefined) return { ok: false, error: 'MissingText' }\n const { path, index: textIndex } = location\n const target = blockAt(path)\n if (target === undefined) return { ok: false, error: 'MissingText' }\n const run = runsAt(path)[textIndex]!\n if (operation.offset > run.text.length) return { ok: false, error: 'InvalidRange' }\n if (usedIds.has(operation.textId)) return { ok: false, error: 'InvalidInput' }\n if (operation.offset === 0) {\n // No left remainder: the new run would be an empty duplicate. Splitting\n // at 0 is the caller's no-op, not a silent identity change.\n continue\n }\n const children = runArray(path)\n children[textIndex] = { ...run, text: run.text.slice(0, operation.offset) }\n children.splice(textIndex + 1, 0, {\n ...run,\n id: operation.textId,\n text: run.text.slice(operation.offset),\n })\n usedIds.add(operation.textId)\n materialize()\n reindex()\n const relocate: SplitStep = {\n node: run.id,\n into: operation.textId,\n at: operation.offset,\n }\n positionMap.push(relocate)\n if (selection?.type === 'Range') {\n selection = {\n ...selection,\n anchor: mapPosition(selection.anchor, [relocate]),\n focus: mapPosition(selection.focus, [relocate]),\n }\n }\n dirtyNodes.add(target.id)\n dirtyNodes.add(run.id)\n dirtyNodes.add(operation.textId)\n textChanged.add(run.id)\n textChanged.add(operation.textId)\n insertedNodes.add(operation.textId)\n continue\n }\n if (operation.type === 'SplitNode') {\n materialize()\n const blockPath = blockPaths.get(operation.block)\n if (blockPath === undefined) return { ok: false, error: 'MissingNode' }\n const runLocation = runPaths.get(operation.node)\n if (runLocation === undefined) return { ok: false, error: 'MissingText' }\n const { path: runBlockPath, index: textIndex } = runLocation\n if (pathKey(runBlockPath) !== pathKey(blockPath)) return { ok: false, error: 'InvalidRange' }\n const target = blockAt(blockPath)!\n const run = target.children[textIndex]!\n if (operation.offset > run.text.length) return { ok: false, error: 'InvalidRange' }\n if (\n usedIds.has(operation.blockId) ||\n usedIds.has(operation.textId) ||\n operation.blockId === operation.textId\n ) {\n return { ok: false, error: 'InvalidInput' }\n }\n const leftBlock = {\n ...target,\n children: [\n ...target.children.slice(0, textIndex),\n { ...run, text: run.text.slice(0, operation.offset) },\n ],\n }\n const rightBlock = {\n ...target,\n id: operation.blockId,\n children: [\n { ...run, id: operation.textId, text: run.text.slice(operation.offset) },\n ...target.children.slice(textIndex + 1),\n ],\n }\n // The halves land in the block's own container, so a split inside a\n // container stays inside it.\n const containerPath = blockPath.slice(0, -1)\n const index = blockPath[blockPath.length - 1]!\n const container = ensureContainer(containerPath)\n container[index] = leftBlock\n container.splice(index + 1, 0, rightBlock)\n materialize()\n usedIds.add(operation.blockId)\n usedIds.add(operation.textId)\n reindex()\n const relocate: SplitStep = { node: run.id, into: operation.textId, at: operation.offset }\n positionMap.push(relocate)\n if (selection?.type === 'Range') {\n selection = {\n ...selection,\n anchor: mapPosition(selection.anchor, [relocate]),\n focus: mapPosition(selection.focus, [relocate]),\n }\n }\n dirtyNodes.add(target.id)\n dirtyNodes.add(operation.blockId)\n dirtyNodes.add(run.id)\n dirtyNodes.add(operation.textId)\n for (const moved of target.children.slice(textIndex + 1)) dirtyNodes.add(moved.id)\n textChanged.add(run.id)\n textChanged.add(operation.textId)\n insertedNodes.add(operation.blockId)\n insertedNodes.add(operation.textId)\n structureChanged = true\n continue\n }\n if (operation.type === 'JoinNode') {\n materialize()\n const intoPath = blockPaths.get(operation.into)\n if (intoPath === undefined) return { ok: false, error: 'MissingNode' }\n const removedPath = blockPaths.get(operation.removed)\n if (removedPath === undefined) return { ok: false, error: 'MissingNode' }\n // Siblings only: two blocks in different containers have no boundary\n // between them to remove.\n if (pathKey(intoPath.slice(0, -1)) !== pathKey(removedPath.slice(0, -1))) {\n return { ok: false, error: 'InvalidParent' }\n }\n const containerPath = intoPath.slice(0, -1)\n const intoIndex = intoPath[intoPath.length - 1]!\n const removedIndex = removedPath[removedPath.length - 1]!\n if (removedIndex !== intoIndex + 1) return { ok: false, error: 'InvalidRange' }\n const container = ensureContainer(containerPath)\n const survivor = container[intoIndex]!\n const removedBlocks: Array<Block> = []\n while (operationIndex < transaction.length) {\n const next = transaction[operationIndex]\n if (next?.type !== 'JoinNode' || next.into !== operation.into) break\n const removed = container[intoIndex + removedBlocks.length + 1]\n if (removed?.id !== next.removed) break\n // Opaque content cannot be merged without silently discarding it.\n if (survivor.type === 'Unknown' || removed.type === 'Unknown') {\n return { ok: false, error: 'InvalidRange' }\n }\n if (survivor.type === 'Node' || removed.type === 'Node') {\n if (\n survivor.type !== 'Node' ||\n removed.type !== 'Node' ||\n survivor.kind !== removed.kind ||\n !Equal.equals(survivor.props, removed.props)\n )\n return { ok: false, error: 'InvalidRange' }\n }\n // A container and a run holder merge differently: joining a list with a\n // paragraph would have to drop one side's shape.\n if ((nestedOf(survivor) === undefined) !== (nestedOf(removed) === undefined)) {\n return { ok: false, error: 'InvalidRange' }\n }\n removedBlocks.push(removed)\n operationIndex++\n }\n operationIndex--\n const mergedRuns = [...survivor.children, ...removedBlocks.flatMap(block => block.children)]\n if (survivor.type === 'Node' && survivor.blocks !== undefined) {\n container[intoIndex] = {\n ...survivor,\n children: mergedRuns,\n blocks: [...survivor.blocks, ...removedBlocks.flatMap(block => nestedOf(block) ?? [])],\n }\n } else {\n container[intoIndex] = { ...survivor, children: mergedRuns }\n }\n container.splice(removedIndex, removedBlocks.length)\n materialize()\n reindex()\n for (const removed of removedBlocks) {\n // A Node selection on a retired identity follows the survivor.\n if (selection?.type === 'Node' && selection.node === removed.id) {\n selection = { ...selection, node: operation.into }\n }\n }\n dirtyNodes.add(operation.into)\n for (const removed of removedBlocks) {\n dirtyNodes.add(removed.id)\n removedNodes.add(removed.id)\n for (const moved of removed.children) dirtyNodes.add(moved.id)\n }\n structureChanged = true\n continue\n }\n if (operation.type === 'MoveNode') {\n materialize()\n const fromPath = blockPaths.get(operation.node)\n if (fromPath === undefined) return { ok: false, error: 'MissingNode' }\n const target = containerPathOf(operation.parent)\n if ('error' in target) return { ok: false, error: target.error }\n const sourcePath = fromPath.slice(0, -1)\n const fromIndex = fromPath[fromPath.length - 1]!\n // A move within one container lands at an existing index; a move into\n // another can append, so its bound is that container's length.\n const sameContainer = pathKey(sourcePath) === pathKey(target.path)\n const limit = sameContainer ? blocksAt(target.path).length - 1 : blocksAt(target.path).length\n if (operation.to > limit) return { ok: false, error: 'InvalidRange' }\n if (sameContainer && operation.to === fromIndex) continue\n const source = ensureContainer(sourcePath)\n const [moved] = source.splice(fromIndex, 1)\n const destination = sameContainer ? source : ensureContainer(target.path)\n destination.splice(operation.to, 0, moved!)\n materialize()\n reindex()\n dirtyNodes.add(operation.node)\n structureChanged = true\n continue\n }\n if (operation.type === 'SetNodeProps') {\n const path = blockPaths.get(operation.node)\n if (path === undefined) return { ok: false, error: 'MissingNode' }\n const target = blockAt(path)\n if (target === undefined || target.type !== 'Heading') {\n return { ok: false, error: 'InvalidRange' }\n }\n if (target.level === operation.level) continue\n writeBlock(path, { ...target, level: operation.level })\n dirtyNodes.add(target.id)\n structureChanged = true\n continue\n }\n if (operation.type === 'InsertNode') {\n materialize()\n const target = containerPathOf(operation.parent)\n if ('error' in target) return { ok: false, error: target.error }\n if (operation.at > blocksAt(target.path).length) return { ok: false, error: 'InvalidRange' }\n const carried = [\n operation.block.id,\n ...operation.block.children.map(run => run.id),\n ...(operation.block.type === 'Node' && operation.block.blocks !== undefined\n ? operation.block.blocks.flatMap(block => [\n block.id,\n ...block.children.map(run => run.id),\n ])\n : []),\n ]\n if (new Set(carried).size !== carried.length || carried.some(id => usedIds.has(id))) {\n return { ok: false, error: 'InvalidInput' }\n }\n const container = ensureContainer(target.path)\n container.splice(operation.at, 0, operation.block)\n materialize()\n for (const id of carried) {\n usedIds.add(id)\n dirtyNodes.add(id)\n insertedNodes.add(id)\n }\n reindex()\n structureChanged = true\n continue\n }\n if (operation.type === 'DeleteNode') {\n materialize()\n const path = blockPaths.get(operation.node)\n if (path === undefined) return { ok: false, error: 'MissingNode' }\n const containerPath = path.slice(0, -1)\n const index = path[path.length - 1]!\n const target = blockAt(path)!\n const container = ensureContainer(containerPath)\n container.splice(index, 1)\n materialize()\n reindex()\n // The nearest surviving run in document order — the first at or after the\n // removed block's place, else the last before it — or nothing, which\n // clears the selection. Walking the tree is what lets a delete beside a\n // container collapse into the container's own runs.\n const removedPlace = { path, index: 0 }\n let fallback: { readonly block: Block; readonly run: Text } | undefined\n let after: { readonly block: Block; readonly run: Text } | undefined\n eachBlock(document.children, (block, blockPath) => {\n for (const [runIndex, run] of block.children.entries()) {\n const place = { path: blockPath, index: runIndex }\n if (compareRunPlaces(place, removedPlace) >= 0) after ??= { block, run }\n else fallback = { block, run }\n }\n })\n const landing = after ?? fallback\n const collapses: Array<CollapseStep> = []\n const removedRuns: Array<NodeId> = []\n const collect = (block: Block): void => {\n for (const run of block.children) removedRuns.push(run.id)\n if (block.type === 'Node' && block.blocks !== undefined) block.blocks.forEach(collect)\n }\n collect(target)\n if (landing !== undefined) {\n for (const run of removedRuns) collapses.push({ node: run, into: landing.run.id })\n }\n if (selection?.type === 'Range') {\n selection =\n landing === undefined\n ? null\n : {\n ...selection,\n anchor: mapPosition(selection.anchor, collapses),\n focus: mapPosition(selection.focus, collapses),\n }\n } else if (selection?.type === 'Node') {\n const selectedNode = selection.node\n if (selectedNode === operation.node || removedRuns.includes(selectedNode)) {\n selection = landing === undefined ? null : { ...selection, node: landing.block.id }\n }\n }\n for (const step of collapses) positionMap.push(step)\n const removedIds: Array<NodeId> = []\n const collectIds = (block: Block): void => {\n removedIds.push(block.id, ...block.children.map(run => run.id))\n if (block.type === 'Node' && block.blocks !== undefined) block.blocks.forEach(collectIds)\n }\n collectIds(target)\n for (const id of removedIds) {\n dirtyNodes.add(id)\n removedNodes.add(id)\n }\n structureChanged = true\n continue\n }\n const id = operation.type === 'InsertText' ? operation.at.node : operation.node\n const location = runPaths.get(id)\n if (location === undefined) return { ok: false, error: 'MissingText' }\n const { path, index: textIndex } = location\n const block = blockAt(path)\n if (block === undefined) return { ok: false, error: 'MissingText' }\n const text = runsAt(path)[textIndex]!\n if (operation.type === 'AddMark') {\n // A run carries a mark name at most once, so adding is a *set*: append\n // when the name is absent, replace when its props differ, and no-op when\n // the mark is already exactly this one (which keeps state identity).\n const existing = text.marks.find(mark => markName(mark) === markName(operation.mark))\n if (existing !== undefined && sameMark(existing, operation.mark)) continue\n const children = runArray(path)\n children[textIndex] = {\n ...text,\n marks:\n existing === undefined\n ? [...text.marks, operation.mark]\n : text.marks.map(mark =>\n markName(mark) === markName(operation.mark) ? operation.mark : mark,\n ),\n }\n dirtyNodes.add(block.id)\n dirtyNodes.add(id)\n textChanged.add(id)\n continue\n }\n if (operation.type === 'RemoveMark') {\n if (!text.marks.some(mark => markName(mark) === operation.mark)) continue\n const children = runArray(path)\n children[textIndex] = {\n ...text,\n marks: text.marks.filter(mark => markName(mark) !== operation.mark),\n }\n dirtyNodes.add(block.id)\n dirtyNodes.add(id)\n textChanged.add(id)\n continue\n }\n const from = operation.type === 'InsertText' ? operation.at.offset : operation.from\n const to = operation.type === 'InsertText' ? from : operation.to\n const inserted = operation.type === 'InsertText' ? operation.text : ''\n if (from > to || to > text.text.length) return { ok: false, error: 'InvalidRange' }\n if (from === to && inserted.length === 0) continue\n const children = runArray(path)\n children[textIndex] = {\n ...text,\n text: text.text.slice(0, from) + inserted + text.text.slice(to),\n }\n const step = { node: id, from, to, inserted: inserted.length }\n positionMap.push(step)\n if (selection?.type === 'Range') {\n selection = {\n ...selection,\n anchor: mapPosition(selection.anchor, [step]),\n focus: mapPosition(selection.focus, [step]),\n }\n }\n dirtyNodes.add(block.id)\n dirtyNodes.add(id)\n textChanged.add(id)\n }\n // The op loop accumulates; the document is assembled once, here.\n materialize()\n // Normalization runs as transforms (§23): each is deterministic and idempotent\n // on normalized state, so the loop settles. The pass bound is a diagnostic,\n // not a hang: a transform that keeps changing the document is refused rather\n // than spinning.\n let pass = 0\n for (; pass < MAX_NORMALIZATION_PASSES; pass++) {\n let changed = false\n for (const transform of transforms) {\n const report = transform.apply(document, { dirtyNodes, pass })\n if (report.document === document) continue\n changed = true\n document = report.document\n for (const id of report.insertedNodes) insertedNodes.add(id)\n for (const id of report.removedNodes) removedNodes.add(id)\n for (const id of report.dirtyNodes) dirtyNodes.add(id)\n for (const id of report.textChanged) textChanged.add(id)\n for (const step of report.steps) positionMap.push(step)\n if (report.structureChanged) structureChanged = true\n if (report.steps.length > 0) selection = mapThrough(selection, report.steps)\n reindex()\n }\n if (!changed) break\n }\n if (pass === MAX_NORMALIZATION_PASSES) return { ok: false, error: 'UnstableNormalization' }\n return {\n ok: true,\n state:\n document === state.document && sameSelection(selection, state.selection)\n ? state\n : { document, selection },\n changeSet: {\n dirtyNodes,\n insertedNodes,\n removedNodes,\n textChanged,\n structureChanged,\n selectionChanged: !sameSelection(selection, state.selection),\n },\n positionMap,\n }\n}\n","import {\n NodeId,\n blockAtPath,\n compareRunPlaces,\n eachBlock,\n locateBlock,\n locateRun,\n pathKey,\n type Block,\n type BlockPath,\n type Document,\n type EditorState,\n type Mark,\n type MarkValue,\n type Position,\n type RunMark,\n type Selection,\n type Text as Run,\n} from './document.js'\nimport { withFreshIds, type Slice } from './clipboard.js'\nimport {\n markName,\n resolveInsertion,\n sameMark,\n shippedRegistry,\n type MarkRegistry,\n} from './marks.js'\nimport { Edit, apply, type Operation, type TransactionResult } from './transaction.js'\n\n/**\n * Editor intent: what the user is trying to do. Commands resolve against the\n * current document and selection into a Transaction of low-level operations, so\n * durable history keeps its meaning (§19). Identities a command needs come from\n * the caller's `mint`; nothing here reads a clock or a hidden counter.\n */\nexport type Command =\n | {\n readonly type: 'InsertText'\n readonly text: string\n /** Stored marks: a bare name, or a value when the mark carries props. */\n readonly marks?: ReadonlyArray<string | MarkValue>\n }\n | { readonly type: 'DeleteBackward' }\n | { readonly type: 'DeleteForward' }\n | { readonly type: 'SplitBlock' }\n | { readonly type: 'ToggleMark'; readonly mark: string | MarkValue }\n | { readonly type: 'SetSelection'; readonly selection: Selection | null }\n | { readonly type: 'Paste'; readonly slice: Slice }\n\n/** Caller-owned identity source. Live edits mint; replay applies transactions. */\nexport interface CommandIds {\n readonly mint: () => string\n}\n\n/** What a command needs beyond state and identity, such as a Kit's mark policy. */\nexport interface RunOptions {\n readonly marks?: MarkRegistry | undefined\n}\n\ntype Failure = 'InvalidSelection' | 'MissingText' | 'InvalidInput' | 'InvalidParent'\nconst failure = (error: Failure): TransactionResult => ({ ok: false, error })\n\ninterface Located {\n readonly path: BlockPath\n readonly runIndex: number\n readonly blockId: NodeId\n readonly id: NodeId\n readonly text: string\n readonly marks: ReadonlyArray<RunMark>\n}\n\n/** Document order over a located run, by the shared place rule. */\nconst locatedOrder = (\n left: { readonly path: BlockPath; readonly runIndex: number },\n right: { readonly path: BlockPath; readonly runIndex: number },\n): number =>\n compareRunPlaces(\n { path: left.path, index: left.runIndex },\n { path: right.path, index: right.runIndex },\n )\n\nconst locate = (document: Document, node: NodeId): Located | undefined => {\n const found = locateRun(document, node)\n if (found === undefined) return undefined\n const block = blockAtPath(document, found.path)\n if (block === undefined) return undefined\n return {\n path: found.path,\n runIndex: found.index,\n blockId: block.id,\n id: found.run.id,\n text: found.run.text,\n marks: found.run.marks,\n }\n}\n\nconst isCollapsed = (selection: Extract<Selection, { readonly type: 'Range' }>): boolean =>\n selection.anchor.node === selection.focus.node &&\n selection.anchor.offset === selection.focus.offset\n\n/** A caret is a range whose endpoints coincide; direction is not yet meaningful. */\nconst caretAt = (position: Position): Selection => ({\n type: 'Range',\n anchor: position,\n focus: position,\n})\n\n/** Orders a range's endpoints by document order without losing direction. */\nconst ordered = (\n document: Document,\n selection: Extract<Selection, { readonly type: 'Range' }>,\n): { readonly start: Position; readonly end: Position } | undefined => {\n const anchor = locate(document, selection.anchor.node)\n const focus = locate(document, selection.focus.node)\n if (anchor === undefined || focus === undefined) return undefined\n const byPlace = locatedOrder(anchor, focus)\n const after = byPlace !== 0 ? byPlace > 0 : selection.anchor.offset > selection.focus.offset\n return after\n ? { start: selection.focus, end: selection.anchor }\n : { start: selection.anchor, end: selection.focus }\n}\n\ninterface Span {\n readonly run: Located\n readonly from: number\n readonly to: number\n}\n\n/** Runs intersecting an ordered [start, end), with the covered sub-range. */\nconst covered = (document: Document, start: Position, end: Position): ReadonlyArray<Span> => {\n const startAt = locate(document, start.node)\n const endAt = locate(document, end.node)\n if (startAt === undefined || endAt === undefined) return []\n const spans: Array<Span> = []\n // The walk is document order, so comparing each run's place against the\n // endpoints' places picks out the covered span however deep it sits.\n eachBlock(document.children, (block, path) => {\n for (const [runIndex, run] of block.children.entries()) {\n const place = { path, runIndex }\n if (locatedOrder(place, startAt) < 0 || locatedOrder(place, endAt) > 0) continue\n const from = locatedOrder(place, startAt) === 0 ? start.offset : 0\n const to = locatedOrder(place, endAt) === 0 ? end.offset : run.text.length\n if (from >= to) continue\n spans.push({\n run: {\n path,\n runIndex,\n blockId: block.id,\n id: run.id,\n text: run.text,\n marks: run.marks,\n },\n from,\n to,\n })\n }\n })\n return spans\n}\n\n/** Marks every run in the list carries; empty when there are no runs. */\nconst sharedMarks = (runs: ReadonlyArray<ReadonlyArray<RunMark>>): ReadonlySet<string> => {\n let common: Set<string> | undefined\n for (const marks of runs) {\n const names = new Set(marks.map(markName))\n if (common === undefined) {\n common = names\n continue\n }\n for (const name of common) if (!names.has(name)) common.delete(name)\n }\n return common ?? new Set()\n}\n\n/**\n * The marks every run the selection covers carries: the ones a toggle would\n * remove, which is what an \"active\" toolbar button means. A caret reports its\n * run's marks — an empty run can carry them, which is how a caret holds a format\n * — and a range is not bold when it straddles a bold run and a plain one. A node\n * selection reports what its whole subtree agrees on. A read, not a command:\n * nothing here changes anything.\n */\nexport const marksInRange = (\n document: Document,\n selection: Selection | null,\n): ReadonlySet<string> => {\n if (selection === null) return new Set()\n if (selection.type === 'Node') {\n const found = locateBlock(document, selection.node)\n if (found === undefined) return new Set()\n const runs: Array<ReadonlyArray<RunMark>> = []\n eachBlock([found.block], each => {\n for (const run of each.children) runs.push(run.marks)\n })\n return sharedMarks(runs)\n }\n const bounds = ordered(document, selection)\n if (bounds === undefined) return new Set()\n if (isCollapsed(selection)) {\n const caret = locate(document, selection.anchor.node)\n return caret === undefined ? new Set() : sharedMarks([caret.marks])\n }\n return sharedMarks(covered(document, bounds.start, bounds.end).map(span => span.run.marks))\n}\n\n/** The last run in a block's subtree, or undefined when it holds none. */\nconst lastRunOf = (block: Block): Run | undefined => {\n if (block.type === 'Node' && block.blocks !== undefined) {\n for (let index = block.blocks.length - 1; index >= 0; index--) {\n const found = lastRunOf(block.blocks[index]!)\n if (found !== undefined) return found\n }\n }\n return block.children[block.children.length - 1]\n}\n\n/** The block list a path lives in: the document's, or a container's nested blocks. */\nconst containerBlocks = (document: Document, containerPath: BlockPath): ReadonlyArray<Block> => {\n if (containerPath.length === 0) return document.children\n const container = blockAtPath(document, containerPath)\n return container?.type === 'Node' && container.blocks !== undefined ? container.blocks : []\n}\n\n/**\n * Deletes an ordered [start, end): one operation per covered run, then the\n * blocks the range spanned are joined, so selecting across a paragraph boundary\n * and deleting removes the boundary too. The first block survives, which is\n * where the caret already is. Returns undefined when the range needs a join this\n * version cannot express — one across containers, which has no boundary to\n * remove — so the caller refuses rather than deleting half of what was selected.\n */\nconst deleteRange = (\n document: Document,\n start: Position,\n end: Position,\n): ReadonlyArray<Operation> | undefined => {\n const startAt = locate(document, start.node)\n const endAt = locate(document, end.node)\n const deletions: Array<Operation> = covered(document, start, end).map(span =>\n Edit.deleteText(span.run.id, span.from, span.to),\n )\n if (startAt === undefined || endAt === undefined) return deletions\n // Within one block there is no boundary to remove.\n if (pathKey(startAt.path) === pathKey(endAt.path)) return deletions\n const containerPath = startAt.path.slice(0, -1)\n // The boundary only exists between siblings; a range that leaves its container\n // needs a merge this version does not define.\n if (pathKey(containerPath) !== pathKey(endAt.path.slice(0, -1))) return undefined\n const blocks = containerBlocks(document, containerPath)\n const from = startAt.path[startAt.path.length - 1]!\n const to = endAt.path[endAt.path.length - 1]!\n const survivor = blocks[from]!.id\n for (let index = from + 1; index <= to; index++) {\n const block = blocks[index]\n if (block !== undefined) deletions.push(Edit.joinBlocks(survivor, block.id))\n }\n return deletions\n}\n\nconst segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' })\n\n/** A caret uses UTF-16 offsets, while a deletion removes a whole grapheme. */\nconst graphemeDeletion = (\n block: Block,\n caret: Position,\n runIndex: number,\n backward: boolean,\n): { operations: ReadonlyArray<Operation>; caret: Position } | undefined => {\n const starts: Array<number> = []\n let length = 0\n for (const run of block.children) {\n starts.push(length)\n length += run.text.length\n }\n const at = starts[runIndex]! + caret.offset\n if (backward ? at === 0 : at === length) return undefined\n const text = block.children.map(run => run.text).join('')\n let from = 0\n let to = 0\n for (const segment of segmenter.segment(text)) {\n const end = segment.index + segment.segment.length\n if (backward ? end >= at : end > at) {\n from = segment.index\n to = end\n break\n }\n }\n const operations: Array<Operation> = []\n let graphemeStart: Position | undefined\n for (const [index, run] of block.children.entries()) {\n const start = starts[index]!\n const localFrom = Math.max(0, from - start)\n const localTo = Math.min(run.text.length, to - start)\n if (localFrom >= localTo) continue\n graphemeStart ??= { node: run.id, offset: localFrom, affinity: 'after' }\n operations.push(Edit.deleteText(run.id, localFrom, localTo))\n }\n if (graphemeStart === undefined) return undefined\n // A backward deletion removes what is to the caret's left, so the caret lands\n // where the grapheme began; a forward one removes to its right, and the caret\n // already sits at the surviving boundary.\n return { operations, caret: backward ? graphemeStart : caret }\n}\n\n/**\n * Resolves one intent into a transaction and applies it atomically. Commands\n * describe intent; the returned `positionMap` and `ChangeSet` describe the\n * document effect, and rejection returns no partially edited state.\n */\nexport const run = (\n state: EditorState,\n command: Command,\n ids: CommandIds,\n options: RunOptions = {},\n): TransactionResult => {\n // The vocabulary an edit may add: the caller's Kit, or the shipped marks.\n const declared = options.marks ?? shippedRegistry\n if (command.type === 'SetSelection') {\n return apply(state, [Edit.setSelection(command.selection)])\n }\n const selection = state.selection\n if (selection === null || selection.type === 'Node') return failure('InvalidSelection')\n\n if (command.type === 'InsertText') {\n // Stored marks are explicit: when the command carries them, the inserted\n // text must end up with exactly that set, whatever run it lands in. Without\n // them, the boundary rule decides (typing after bold continues bold).\n const stored = command.marks\n const target = isCollapsed(selection)\n ? stored === undefined\n ? resolveInsertion(state.document, selection.anchor, options.marks)\n : selection.anchor\n : ordered(state.document, selection)?.start\n if (target === undefined) return failure('InvalidSelection')\n const at = locate(state.document, target.node)\n if (at === undefined) return failure('MissingText')\n const marks: Array<RunMark> = []\n if (stored !== undefined) {\n for (const mark of stored) {\n if (!declared.declares(markName(mark))) return failure('InvalidInput')\n marks.push(mark)\n }\n }\n const deletions = isCollapsed(selection)\n ? []\n : deleteRange(state.document, target, ordered(state.document, selection)!.end)\n if (deletions === undefined) return failure('InvalidParent')\n if (command.text.length === 0) {\n return apply(\n state,\n deletions.length === 0 ? [] : [...deletions, Edit.setSelection(caretAt(target))],\n )\n }\n if (stored === undefined) {\n return apply(state, [\n ...deletions,\n Edit.insertText(target, command.text),\n Edit.setSelection(\n caretAt({ ...target, offset: target.offset + command.text.length, affinity: 'after' }),\n ),\n ])\n }\n // Split the inserted span out of its run — at the end first, so the start\n // offset stays valid — then give the span exactly these marks.\n const span = isCollapsed(selection) ? undefined : ordered(state.document, selection)\n // Where the text that survives the range deletion begins in the original\n // run. A range that runs past this run takes its whole tail with it.\n const tailFrom =\n span === undefined\n ? target.offset\n : span.end.node === target.node\n ? span.end.offset\n : at.text.length\n const operations: Array<Operation> = [...deletions, Edit.insertText(target, command.text)]\n const end = target.offset + command.text.length\n if (tailFrom < at.text.length) operations.push(Edit.splitRun(target.node, end, ids.mint()))\n const piece = target.offset > 0 ? NodeId.make(ids.mint()) : target.node\n if (target.offset > 0) operations.push(Edit.splitRun(target.node, target.offset, piece))\n for (const mark of marks) {\n if (!at.marks.some(existing => sameMark(existing, mark))) {\n operations.push(Edit.addMark(piece, mark))\n }\n }\n for (const mark of at.marks) {\n if (!marks.some(kept => markName(kept) === markName(mark))) {\n operations.push(Edit.removeMark(piece, markName(mark)))\n }\n }\n return apply(state, operations)\n }\n\n if (command.type === 'DeleteBackward' || command.type === 'DeleteForward') {\n if (!isCollapsed(selection)) {\n const span = ordered(state.document, selection)\n if (span === undefined) return failure('InvalidSelection')\n const deletions = deleteRange(state.document, span.start, span.end)\n if (deletions === undefined) return failure('InvalidParent')\n return apply(state, [...deletions, Edit.setSelection(caretAt(span.start))])\n }\n const caret = selection.anchor\n const at = locate(state.document, caret.node)\n if (at === undefined) return failure('MissingText')\n const backward = command.type === 'DeleteBackward'\n const block = blockAtPath(state.document, at.path)\n if (block === undefined) return failure('MissingText')\n const deletion = graphemeDeletion(block, caret, at.runIndex, backward)\n if (deletion !== undefined) {\n return apply(state, [...deletion.operations, Edit.setSelection(caretAt(deletion.caret))])\n }\n // A block edge joins the sibling in the same container, wherever it sits.\n const containerPath = at.path.slice(0, -1)\n const siblings = containerBlocks(state.document, containerPath)\n const index = at.path[at.path.length - 1]!\n const neighborBlock = siblings[backward ? index - 1 : index + 1]\n if (neighborBlock === undefined) return apply(state, [])\n const survivor = backward ? neighborBlock : siblings[index]!\n const removed = backward ? siblings[index]! : neighborBlock\n // The caret lands at the junction: the end of what the survivor already had,\n // or the removed block's last run when the survivor holds no runs.\n const lastRun = lastRunOf(survivor) ?? lastRunOf(removed)\n return apply(state, [\n Edit.joinBlocks(survivor.id, removed.id),\n Edit.setSelection(\n caretAt(\n lastRun === undefined\n ? { node: survivor.id, offset: 0, affinity: 'after' }\n : { node: lastRun.id, offset: lastRun.text.length, affinity: 'after' },\n ),\n ),\n ])\n }\n\n if (command.type === 'SplitBlock') {\n const span = isCollapsed(selection) ? undefined : ordered(state.document, selection)\n if (!isCollapsed(selection) && span === undefined) return failure('InvalidSelection')\n const caret = span?.start ?? selection.anchor\n const at = locate(state.document, caret.node)\n if (at === undefined) return failure('MissingText')\n const deletions = span === undefined ? [] : deleteRange(state.document, span.start, span.end)\n if (deletions === undefined) return failure('InvalidParent')\n const textId = ids.mint()\n return apply(state, [\n ...deletions,\n Edit.splitBlock(at.blockId, at.id, caret.offset, ids.mint(), textId),\n Edit.setSelection(caretAt({ node: NodeId.make(textId), offset: 0, affinity: 'after' })),\n ])\n }\n\n if (command.type === 'ToggleMark') {\n if (isCollapsed(selection)) return apply(state, [])\n const span = ordered(state.document, selection)\n if (span === undefined) return failure('InvalidSelection')\n const spans = covered(state.document, span.start, span.end)\n if (spans.length === 0) return apply(state, [])\n // A toggle keys on the name: the mark is present on every covered run, or\n // it is absent everywhere. Props are the mark's own business.\n const mark = command.mark\n const name = markName(mark)\n const adding = !spans.every(entry => entry.run.marks.some(held => markName(held) === name))\n const operations: Array<Operation> = []\n const targets: Array<NodeId> = []\n for (const [index, entry] of spans.entries()) {\n let target = entry.run.id\n let base = 0\n if (index === 0 && entry.from > 0) {\n const textId = ids.mint()\n operations.push(Edit.splitRun(target, entry.from, textId))\n target = NodeId.make(textId)\n base = entry.from\n }\n if (index === spans.length - 1 && entry.to < entry.run.text.length) {\n operations.push(Edit.splitRun(target, entry.to - base, ids.mint()))\n }\n targets.push(target)\n }\n if (adding) {\n // Adding needs the vocabulary to declare the mark; removing a preserved\n // one by name is always allowed.\n if (!declared.declares(name)) return failure('InvalidInput')\n for (const target of targets) operations.push(Edit.addMark(target, mark))\n } else {\n for (const target of targets) operations.push(Edit.removeMark(target, name))\n }\n return apply(state, operations)\n }\n\n if (command.type === 'Paste') {\n const content = command.slice.blocks\n if (content.length === 0) return apply(state, [])\n const span = isCollapsed(selection) ? undefined : ordered(state.document, selection)\n if (!isCollapsed(selection) && span === undefined) return failure('InvalidSelection')\n const caret = span?.start ?? selection.anchor\n const at = locate(state.document, caret.node)\n if (at === undefined) return failure('MissingText')\n const index = at.path[at.path.length - 1]!\n const containerPath = at.path.slice(0, -1)\n // The content lands in the caret's own container, so pasting inside a list\n // item stays inside the list.\n const parent =\n containerPath.length === 0 ? undefined : blockAtPath(state.document, containerPath)?.id\n const replacements = span === undefined ? [] : deleteRange(state.document, span.start, span.end)\n if (replacements === undefined) return failure('InvalidParent')\n const operations: Array<Operation> = [...replacements]\n const inserted = withFreshIds(command.slice, ids.mint).blocks\n const block = blockAtPath(state.document, at.path)\n if (block === undefined) return failure('MissingText')\n const atBlockStart = at.runIndex === 0 && caret.offset === 0\n const atBlockEnd = at.runIndex === block.children.length - 1 && caret.offset === at.text.length\n let trailingRun: NodeId | undefined\n if (atBlockStart) {\n // Pasting at the very start puts the content above this block.\n for (const [offset, piece] of inserted.entries()) {\n operations.push(Edit.insertBlock(piece, index + offset, parent))\n }\n } else if (atBlockEnd) {\n for (const [offset, piece] of inserted.entries()) {\n operations.push(Edit.insertBlock(piece, index + 1 + offset, parent))\n }\n } else {\n // Mid-block: split the block at the caret and land the content between\n // the halves, so the text after the caret stays below what was pasted.\n const textId = ids.mint()\n operations.push(Edit.splitBlock(at.blockId, at.id, caret.offset, ids.mint(), textId))\n trailingRun = NodeId.make(textId)\n for (const [offset, piece] of inserted.entries()) {\n operations.push(Edit.insertBlock(piece, index + 1 + offset, parent))\n }\n }\n const landing = landingAfter(\n inserted,\n trailingRun,\n containerBlocks(state.document, containerPath),\n index,\n atBlockEnd,\n )\n if (landing !== undefined) operations.push(Edit.setSelection(caretAt(landing)))\n return apply(state, operations)\n }\n\n return apply(state, [])\n}\n\n/**\n * Where the caret goes after a paste: the end of the last inserted run, or the\n * start of what follows when the inserted content ends without text — the\n * trailing half a split created, then the next sibling.\n */\nconst landingAfter = (\n inserted: ReadonlyArray<Block>,\n trailingRun: NodeId | undefined,\n siblings: ReadonlyArray<Block>,\n index: number,\n atBlockEnd: boolean,\n): Position | undefined => {\n const last = inserted[inserted.length - 1]!\n const lastRun = last.children[last.children.length - 1]\n if (lastRun !== undefined) {\n return { node: lastRun.id, offset: lastRun.text.length, affinity: 'after' }\n }\n if (trailingRun !== undefined) return { node: trailingRun, offset: 0, affinity: 'after' }\n const following = siblings[index + (atBlockEnd ? 1 : 0)]\n const followingRun = following?.children[0]\n return followingRun === undefined\n ? undefined\n : { node: followingRun.id, offset: 0, affinity: 'after' }\n}\n","import { Schema } from 'effect'\nimport type { Command } from './command.js'\nimport { EditorState } from './document.js'\n\n/**\n * Local undo history over editor snapshots. Snapshots are `EditorState` values\n * (document plus selection), so undo restores what the user saw, including the\n * caret. History is interaction state: it belongs in the application Model\n * beside the selection, never in published content, and collaborative undo is a\n * different operation (§§65–66).\n */\nexport const History = Schema.Struct({\n /** States to return to, oldest first. */\n past: Schema.Array(EditorState),\n /** States undone from, nearest first. */\n future: Schema.Array(EditorState),\n /** The group the last commit joined, if any. */\n group: Schema.optional(Schema.String),\n})\nexport type History = typeof History.Type\n\nexport const emptyHistory: History = Object.freeze({ past: [], future: [] })\n\nexport interface CommitOptions {\n /**\n * Joins the previous step when it used the same group. Consecutive typing\n * shares one undo step; omit the group and every commit stands alone.\n */\n readonly group?: string | undefined\n /** Most steps to keep; the oldest is dropped beyond this. Default 200. */\n readonly capacity?: number\n}\n\n/**\n * Typing continues one undo step; every other command is its own step. Callers\n * pass this to `commit`, so grouping policy lives with the editor vocabulary\n * rather than being reinvented per adapter.\n */\nexport const groupFor = (command: Command): string | undefined =>\n command.type === 'InsertText' ||\n command.type === 'DeleteBackward' ||\n command.type === 'DeleteForward'\n ? 'typing'\n : undefined\n\nconst bounded = (past: ReadonlyArray<EditorState>, capacity: number): ReadonlyArray<EditorState> =>\n past.length > capacity ? past.slice(past.length - capacity) : past\n\n/**\n * Records a committed transition. `previous` is the state before the command\n * and `next` the state after it; only `previous` is stored, because the caller\n * already holds `next`.\n */\nexport const commit = (\n history: History,\n previous: EditorState,\n options: CommitOptions = {},\n): History => {\n const joins = options.group !== undefined && history.group === options.group\n const past = joins ? history.past : bounded([...history.past, previous], options.capacity ?? 200)\n return options.group === undefined\n ? { past, future: [] }\n : { past, future: [], group: options.group }\n}\n\nexport interface Restore {\n readonly history: History\n readonly state: EditorState\n}\n\n/** Steps back one group. Returns undefined when there is nothing to undo. */\nexport const undo = (history: History, current: EditorState): Restore | undefined => {\n const previous = history.past[history.past.length - 1]\n if (previous === undefined) return undefined\n return {\n history: { past: history.past.slice(0, -1), future: [current, ...history.future] },\n state: previous,\n }\n}\n\n/** Steps forward again. Returns undefined when there is nothing to redo. */\nexport const redo = (history: History, current: EditorState): Restore | undefined => {\n const next = history.future[0]\n if (next === undefined) return undefined\n return {\n history: {\n past: [...history.past, current],\n future: history.future.slice(1),\n group: history.group,\n },\n state: next,\n }\n}\n\nexport const canUndo = (history: History): boolean => history.past.length > 0\nexport const canRedo = (history: History): boolean => history.future.length > 0\n\n/** Structural summary for tooling and tests. */\nexport const inspectHistory = (history: History) => ({\n past: history.past.length,\n future: history.future.length,\n group: history.group ?? null,\n})\n","import { Schema } from 'effect'\nimport {\n blockContent,\n eachBlock,\n textContent,\n type Block,\n type ContentMode,\n type Document,\n type NodeBlock,\n type NodeId,\n type PropsSchema,\n type RunMark,\n} from './document.js'\nimport { markName, markProps, type MarkDef } from './marks.js'\n\n/**\n * The node shapes this version can declare: a `block` is one of the built-in\n * text blocks, an `atom` is an addressable node holding nothing, and an\n * application `node` holds runs or nested blocks plus props its own schema\n * validates (§13).\n */\nexport type NodeDefinition =\n | { readonly name: string; readonly kind: 'block'; readonly children: 'text' }\n | { readonly name: string; readonly kind: 'atom'; readonly children: 'none' }\n | {\n readonly name: string\n readonly kind: 'node'\n /** `textContent` holds runs; `blockContent` holds nested blocks, as a list needs. */\n readonly children: ContentMode\n /** Validates a `Node` block's `props` at this boundary, not in the codec. */\n readonly props?: PropsSchema | undefined\n }\n\n/**\n * A declared application node, with the caller's name, prop schema, and content\n * mode kept in the type: the erasure to `any` happens only where heterogeneous\n * definitions are collected, not at the authoring call.\n */\nexport interface NodeDefinitionOf<\n Name extends string,\n Props extends PropsSchema | undefined,\n Children extends ContentMode = typeof textContent,\n> {\n readonly name: Name\n readonly kind: 'node'\n readonly children: Children\n readonly props: Props\n}\n\n/** Declares a block node kind: a top-level node containing text runs. */\nexport const block = (name: string): NodeDefinition => ({\n name,\n kind: 'block',\n children: 'text',\n})\n\n/** Declares an atom: an addressable node with no text content. */\nexport const atom = (name: string): NodeDefinition => ({ name, kind: 'atom', children: 'none' })\n\n/**\n * Declares an application node kind: a `Node` block whose props this schema\n * validates and whose content the `children` mode declares. The document codec\n * keeps those props as JSON; the Kit is where an application's types meet them.\n */\nexport const node = <\n const Name extends string,\n Props extends PropsSchema | undefined = undefined,\n Children extends ContentMode = typeof textContent,\n>(\n name: Name,\n options: { readonly Props?: Props; readonly children?: Children } = {},\n): NodeDefinitionOf<Name, Props, Children> => ({\n name,\n kind: 'node',\n children: (options.children ?? textContent) as Children,\n props: options.Props as Props,\n})\n\n/**\n * The vocabulary one editor accepts: which node kinds and marks are available.\n * A Kit is a definition, never document state, and it never holds renderers or\n * executable code. Transforms and metadata arrive later.\n */\nexport interface Kit {\n readonly nodes: ReadonlyArray<NodeDefinition>\n /** Mark definitions, not just names: a Kit carries each mark's boundary policy. */\n readonly marks: ReadonlyArray<MarkDef>\n}\n\nexport const kit = (definition: {\n readonly nodes: ReadonlyArray<NodeDefinition>\n readonly marks: ReadonlyArray<MarkDef>\n}): Kit => Object.freeze({ nodes: [...definition.nodes], marks: [...definition.marks] })\n\nexport interface Diagnostic {\n readonly code:\n 'UnknownNode' | 'UnsupportedNode' | 'UnknownMark' | 'InvalidProps' | 'MismatchedDefinition'\n readonly message: string\n readonly node?: NodeId\n readonly detail?: string\n}\n\n/** Whether a block is held as a built-in block or as an application node. */\nconst heldShape = (block: Block): 'block' | 'node' => (block.type === 'Node' ? 'node' : 'block')\n\n/**\n * The content a block actually holds. An empty application node is `either`: the\n * document cannot say whether it is an atom or a run holder that happens to have\n * no runs, so a declaration of either kind agrees with it.\n */\nconst heldContent = (block: Block): 'text' | 'blocks' | 'either' => {\n if (block.type !== 'Node') return 'text'\n if (block.blocks !== undefined) return 'blocks'\n return block.children.length > 0 ? 'text' : 'either'\n}\n\n/**\n * Whether a declared definition agrees with the block it is declared for, and\n * why not. A `block` declaration expects a built-in block and a `node` or `atom`\n * one expects an application node; then the declared content mode must match what\n * the block holds, which is what makes an atom's no-children rule real.\n */\nconst definitionMismatch = (definition: NodeDefinition, block: Block): string | undefined => {\n const expected = definition.kind === 'block' ? 'block' : 'node'\n const held = heldShape(block)\n if (held !== expected) {\n return `\"${definition.name}\" is declared as ${definition.kind}, but the document holds it as ${held}`\n }\n const declared = definition.kind === 'atom' ? 'none' : definition.children\n const content = heldContent(block)\n const agrees = content === 'either' ? declared !== 'blocks' : declared === content\n return agrees\n ? undefined\n : `\"${definition.name}\" is declared to hold ${declared}, but the document holds ${content}`\n}\n\n/**\n * Whether a node's props decode against its declared schema, and why not. The\n * diagnostic is deliberately stable: a schema's own message can name internals\n * an API boundary should not leak, so only the verdict travels.\n */\nconst propsFailure = (props: PropsSchema | undefined, node: NodeBlock): boolean => {\n if (props === undefined) return false\n try {\n // Strict, like the persisted-content boundary: a field the schema does not\n // declare is a failure, not something silently kept beside the props.\n Schema.decodeUnknownSync(props, { onExcessProperty: 'error' })(node.props)\n return false\n } catch {\n return true\n }\n}\n\n/** Structural summary of a Kit, for tooling and tests. */\nexport const inspectKit = (definition: Kit) => ({\n blocks: definition.nodes.filter(node => node.kind === 'block').length,\n atoms: definition.nodes.filter(node => node.kind === 'atom').length,\n nodes: definition.nodes.filter(node => node.kind === 'node').length,\n marks: definition.marks.length,\n})\n\n/**\n * Whether a mark's props decode against its declared schema, and why not. The\n * same stability rule as node props: only the verdict travels, not a schema's\n * message. A mark that declares props must carry them.\n */\nconst markPropsFailure = (definition: MarkDef, mark: RunMark): boolean => {\n if (definition.Props === undefined) return false\n try {\n Schema.decodeUnknownSync(definition.Props, { onExcessProperty: 'error' })(markProps(mark))\n return false\n } catch {\n return true\n }\n}\n\n/**\n * Checks a document against a Kit's vocabulary without changing it, walking\n * nested blocks so a container's children are checked too. Reports preserved\n * unknown blocks, known blocks the Kit does not declare, declarations that\n * disagree with how the document holds a block, application nodes whose props\n * their schema refuses, and marks outside the Kit or whose props their definition\n * refuses. Content diagnostics never strip or repair the document; callers decide\n * whether to block publishing or surface a placeholder.\n */\nexport const validate = (document: Document, definition: Kit): ReadonlyArray<Diagnostic> => {\n const byName = new Map(definition.nodes.map(node => [node.name, node]))\n const declaredMarks = new Map(definition.marks.map(mark => [mark.name, mark]))\n const diagnostics: Array<Diagnostic> = []\n eachBlock(document.children, block => {\n if (block.type === 'Unknown') {\n diagnostics.push({\n code: 'UnknownNode',\n node: block.id,\n detail: block.originalType,\n message: `Unimplemented node type \"${block.originalType}\"`,\n })\n } else if (block.type === 'Node') {\n const declared = byName.get(block.kind)\n if (declared === undefined) {\n diagnostics.push({\n code: 'UnsupportedNode',\n node: block.id,\n detail: block.kind,\n message: `The Kit does not declare node \"${block.kind}\"`,\n })\n } else {\n const mismatch = definitionMismatch(declared, block)\n if (mismatch !== undefined) {\n diagnostics.push({\n code: 'MismatchedDefinition',\n node: block.id,\n detail: block.kind,\n message: mismatch,\n })\n } else if (propsFailure(declared.kind === 'node' ? declared.props : undefined, block)) {\n diagnostics.push({\n code: 'InvalidProps',\n node: block.id,\n detail: block.kind,\n message: `\"${block.kind}\" props do not match its declared schema`,\n })\n }\n }\n } else {\n const declared = byName.get(block.type)\n if (declared === undefined) {\n diagnostics.push({\n code: 'UnsupportedNode',\n node: block.id,\n detail: block.type,\n message: `The Kit does not declare \"${block.type}\"`,\n })\n } else {\n const mismatch = definitionMismatch(declared, block)\n if (mismatch !== undefined) {\n diagnostics.push({\n code: 'MismatchedDefinition',\n node: block.id,\n detail: block.type,\n message: mismatch,\n })\n }\n }\n }\n for (const run of block.children) {\n for (const mark of run.marks) {\n const name = markName(mark)\n const declaredMark = declaredMarks.get(name)\n if (declaredMark === undefined) {\n diagnostics.push({\n code: 'UnknownMark',\n node: run.id,\n detail: name,\n message: `The Kit does not declare mark \"${name}\"`,\n })\n } else if (markPropsFailure(declaredMark, mark)) {\n diagnostics.push({\n code: 'InvalidProps',\n node: run.id,\n detail: name,\n message: `\"${name}\" props do not match its declared schema`,\n })\n }\n }\n }\n })\n return diagnostics\n}\n","import { Schema } from 'effect'\nimport {\n Block,\n NodeBlock,\n NodeId,\n Document,\n blockContent,\n textContent,\n type ContentMode,\n} from './document.js'\n\n/**\n * Migrations move semantic data forward when a deployment changes its\n * vocabulary (§73): a preserved node that is now implemented, a prop renamed, a\n * block kind replaced. They operate on blocks, never on DOM, and they run at a\n * boundary the application chooses — loading, publishing, or an explicit\n * upgrade — never automatically on every read.\n *\n * Two rules keep a migration safe to run anywhere:\n *\n * - **Identity survives.** A migration returns the same `id`, so positions,\n * references, and selections keep addressing the same node.\n * - **Declining is allowed.** Returning `undefined` keeps the block as it is,\n * which is what a migration does when the data is not its shape after all.\n */\nexport interface Migration {\n readonly name: string\n /** The type, kind, or preserved `originalType` this migration reads. */\n readonly from: string\n /** The kind it produces, for a report; the returned block is the truth. */\n readonly to?: string | undefined\n readonly migrate: (block: Block) => Block | undefined\n}\n\nexport interface MigrationApplied {\n readonly name: string\n readonly node: NodeId\n}\n\nexport interface MigrationReport {\n readonly document: Document\n /** Every block a migration rewrote, in the order it happened. */\n readonly applied: ReadonlyArray<MigrationApplied>\n /** Migrations that found no block of their `from` in this document. */\n readonly unused: ReadonlyArray<string>\n}\n\nconst matches = (block: Block, from: string): boolean =>\n block.type === 'Unknown'\n ? block.originalType === from\n : block.type === 'Node'\n ? block.kind === from\n : block.type === from\n\nconst decodeMigratedDocument = Schema.decodeUnknownSync(Document, { onExcessProperty: 'error' })\n\n/** Declares a migration, checking at construction that it is shaped like one. */\nexport const migration = (\n name: string,\n from: string,\n migrate: (block: Block) => Block | undefined,\n to?: string,\n): Migration => {\n if (name.length === 0) throw new Error('Migration.make: a migration needs a name')\n if (from.length === 0) throw new Error(`Migration \"${name}\": from must not be empty`)\n return { name, from, migrate, to }\n}\n\n/**\n * Runs one migration over a block list, recursing into containers so a nested\n * block is migrated where it sits. A later migration sees what an earlier one\n * produced, because the caller runs them in list order.\n */\nconst migrateBlocks = (\n blocks: ReadonlyArray<Block>,\n migration: Migration,\n applied: Array<MigrationApplied>,\n): { readonly blocks: ReadonlyArray<Block>; readonly changed: boolean } => {\n let changed = false\n const next = blocks.map(block => {\n let current = block\n if (current.type === 'Node' && current.blocks !== undefined) {\n const nested = migrateBlocks(current.blocks, migration, applied)\n if (nested.changed) {\n changed = true\n current = { ...current, blocks: nested.blocks }\n }\n }\n if (!matches(current, migration.from)) return current\n const migrated = migration.migrate(current)\n if (migrated === undefined) return current\n // A migration that changes a block's identity is a bug: it would silently\n // break every reference to that node.\n if (migrated.id !== current.id) {\n throw new Error(`Migration \"${migration.name}\" changed a block's identity`)\n }\n // What a migration returns becomes persisted content, so it must still\n // decode as a block: a migration cannot write non-JSON props or an\n // unknown shape into the document.\n try {\n Schema.decodeUnknownSync(Block, { onExcessProperty: 'error' })(migrated)\n } catch {\n throw new Error(`Migration \"${migration.name}\" produced an invalid block`)\n }\n applied.push({ name: migration.name, node: current.id })\n changed = true\n return migrated\n })\n return { blocks: changed ? next : blocks, changed }\n}\n\n/**\n * Runs each migration over every block it reads, in list order, descending into\n * containers. A migration that changes a block's identity is a bug and throws\n * rather than silently breaking every reference to that node.\n */\nexport const migrate = (\n document: Document,\n migrations: ReadonlyArray<Migration>,\n): MigrationReport => {\n const applied: Array<MigrationApplied> = []\n const unused: Array<string> = []\n let next = document\n for (const migration of migrations) {\n const result = migrateBlocks(next.children, migration, applied)\n if (!result.changed) {\n unused.push(migration.name)\n continue\n }\n next = { ...next, children: result.blocks }\n try {\n decodeMigratedDocument(next)\n } catch {\n throw new Error(`Migration \"${migration.name}\" produced an invalid document`)\n }\n }\n return { document: next, applied, unused }\n}\n\n/**\n * A migration from a preserved unknown block into a declared node kind: the\n * props are decoded by the target's own schema, and a block whose data does not\n * decode is left alone rather than half-converted. The target's content mode\n * decides whether the promoted node holds runs or (empty) nested blocks, so\n * promoting into a container kind produces a valid block rather than one the\n * Kit will call a mismatch.\n */\nexport const promoteUnknown = (\n name: string,\n from: string,\n to: string,\n Props: Schema.Codec<any, any, never>,\n children: ContentMode = textContent,\n): Migration =>\n migration(\n name,\n from,\n block => {\n if (block.type !== 'Unknown') return undefined\n const decoded = decodeProps(Props, block.props)\n if (decoded === undefined) return undefined\n const promoted: NodeBlock = {\n type: 'Node',\n kind: to,\n id: block.id,\n props: decoded,\n children: [],\n }\n return children === blockContent ? { ...promoted, blocks: [] } : promoted\n },\n to,\n )\n\nconst decodeProps = (\n Props: Schema.Codec<any, any, never>,\n props: Readonly<Record<string, unknown>>,\n): NodeBlock['props'] | undefined => {\n try {\n const decoded: unknown = Schema.decodeUnknownSync(Props)(props)\n // Persisted props stay JSON: a schema that produces something else is\n // declined rather than written into the document.\n return Schema.decodeUnknownSync(Schema.JsonObject)(decoded)\n } catch {\n return undefined\n }\n}\n\n/** A node block's props as the codec stores them: plain JSON, nothing more. */\nexport const nodeProps = (block: NodeBlock): Readonly<Record<string, unknown>> => block.props\n"],"mappings":";;;AAGA,MAAa,SAAS,OAAO,eAAe,KAAK,OAAO,MAAM,yBAAyB,CAAC;;AAIxF,MAAa,OAAO,OAAO,SAAS;CAAC;CAAQ;CAAU;AAAM,CAAC;;;;;;AAW9D,MAAa,YAAY,OAAO,OAAO;CACrC,MAAM,OAAO;CACb,OAAO,OAAO,YAAY,OAAO,UAAU;AAC7C,CAAC;;;;;;;AASD,MAAa,UAAU,OAAO,MAAM,CAAC,OAAO,gBAAgB,SAAS,CAAC;;AAItE,MAAa,YAAY,SAA2B,OAAO,SAAS,WAAW,OAAO,KAAK;;;;;;AAO3F,MAAa,cAAc;AAC3B,MAAa,eAAe;AAiB5B,MAAa,OAAO,OAAO,OAAO;CAChC,MAAM,OAAO,QAAQ,MAAM;CAC3B,IAAI;CACJ,MAAM,OAAO;CAIb,OAAO,OAAO,MAAM,OAAO,CAAC,CAAC,MAC3B,OAAO,YACL,UAAS,IAAI,IAAI,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,SAAS,MAAM,UAAU,eACjE,CACF;AACF,CAAC;AAGD,MAAa,YAAY,OAAO,OAAO;CACrC,MAAM,OAAO,QAAQ,WAAW;CAChC,IAAI;CACJ,UAAU,OAAO,MAAM,IAAI;AAC7B,CAAC;AAGD,MAAa,UAAU,OAAO,OAAO;CACnC,MAAM,OAAO,QAAQ,SAAS;CAC9B,IAAI;CACJ,OAAO,OAAO,SAAS;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC,CAAC;CACzC,UAAU,OAAO,MAAM,IAAI;AAC7B,CAAC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3C;;;;;;;;;AAUA,MAAa,kBACX,MACA,MACA,IACA,OACA,WAAwB,gBAExB,UACE,MACA,OACA,UAAS;CACP,IAAI,MAAM,SAAS,WAAW,OAAO,KAAA;CACrC,MAAM,UAAU,YAAY,OAAO,MAAM,KAAK;CAC9C,IAAI,YAAY,KAAA,GAAW,OAAO,KAAA;CAClC,MAAM,WAAsB;EAC1B,MAAM;EACN,MAAM;EACN,IAAI,MAAM;EACV,OAAO;EACP,UAAU,CAAC;CACb;CACA,OAAO,aAAA,WAA4B;EAAE,GAAG;EAAU,QAAQ,CAAC;CAAE,IAAI;AACnE,GACA,EACF;AAEF,MAAM,eACJ,OACA,UACmC;CACnC,IAAI;EACF,MAAM,UAAmB,OAAO,kBAAkB,KAAK,CAAC,CAAC,KAAK;EAG9D,OAAO,OAAO,kBAAkB,OAAO,UAAU,CAAC,CAAC,OAAO;CAC5D,QAAQ;EACN;CACF;AACF;;AAGA,MAAa,aAAa,UAAwD,MAAM"}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "foldkit-richtext",
3
+ "version": "0.1.0",
4
+ "description": "Pure semantic documents and editing transactions for Foldkit.",
5
+ "keywords": [
6
+ "foldkit",
7
+ "effect",
8
+ "rich-text",
9
+ "editor",
10
+ "document",
11
+ "typescript"
12
+ ],
13
+ "type": "module",
14
+ "license": "MIT",
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "author": "Patrick Glenn <doeixd@gmail.com>",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/doeixd/foldkit-plus.git",
22
+ "directory": "packages/richtext"
23
+ },
24
+ "homepage": "https://github.com/doeixd/foldkit-plus/tree/main/packages/richtext#readme",
25
+ "bugs": {
26
+ "url": "https://github.com/doeixd/foldkit-plus/issues"
27
+ },
28
+ "sideEffects": false,
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.mts",
32
+ "import": "./dist/index.mjs"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "peerDependencies": {
41
+ "effect": "^4.0.0-rc.116"
42
+ },
43
+ "devDependencies": {
44
+ "effect": "4.0.0-rc.116",
45
+ "tsdown": "^0.23.0",
46
+ "typescript": "5.9.3"
47
+ },
48
+ "scripts": {
49
+ "build": "tsdown",
50
+ "typecheck": "tsc -b"
51
+ }
52
+ }