@lupinum/ginko-editor 0.1.0 → 0.18.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.
Files changed (166) hide show
  1. package/CHANGELOG.md +7 -73
  2. package/LICENSE +1 -1
  3. package/README.md +15 -340
  4. package/dist/assets.d.ts +70 -0
  5. package/dist/assets.js +31 -0
  6. package/dist/core/component-props.d.ts +87 -0
  7. package/dist/core/component-props.js +134 -0
  8. package/dist/core/convert.d.ts +24 -0
  9. package/dist/core/convert.js +278 -0
  10. package/dist/core/editor.d.ts +60 -0
  11. package/dist/core/editor.js +85 -0
  12. package/dist/core/extensions.d.ts +38 -0
  13. package/dist/core/extensions.js +444 -0
  14. package/dist/core/file-images.d.ts +9 -0
  15. package/dist/core/file-images.js +54 -0
  16. package/dist/core/image-frame.d.ts +23 -0
  17. package/dist/core/image-frame.js +24 -0
  18. package/dist/core/index.d.ts +17 -0
  19. package/dist/core/index.js +17 -0
  20. package/dist/core/link-card.d.ts +20 -0
  21. package/dist/core/link-card.js +70 -0
  22. package/dist/core/link.d.ts +3 -0
  23. package/dist/core/link.js +8 -0
  24. package/dist/core/move.d.ts +11 -0
  25. package/dist/core/move.js +37 -0
  26. package/dist/core/paste-html.d.ts +6 -0
  27. package/dist/core/paste-html.js +384 -0
  28. package/dist/core/paste.d.ts +21 -0
  29. package/dist/core/paste.js +108 -0
  30. package/dist/core/problems.d.ts +31 -0
  31. package/dist/core/problems.js +54 -0
  32. package/dist/core/search.d.ts +47 -0
  33. package/dist/core/search.js +148 -0
  34. package/dist/core/slash.d.ts +93 -0
  35. package/dist/core/slash.js +215 -0
  36. package/dist/core/table.d.ts +34 -0
  37. package/dist/core/table.js +141 -0
  38. package/dist/core/uploads.d.ts +23 -0
  39. package/dist/core/uploads.js +71 -0
  40. package/dist/core/use-editor.d.ts +19 -0
  41. package/dist/core/use-editor.js +53 -0
  42. package/dist/index.d.ts +6 -15
  43. package/dist/index.js +6 -5668
  44. package/dist/issues.d.ts +49 -0
  45. package/dist/issues.js +9 -0
  46. package/dist/today.d.ts +6 -0
  47. package/dist/today.js +19 -0
  48. package/dist/useUpload.d.ts +48 -0
  49. package/dist/useUpload.js +59 -0
  50. package/dist/values.d.ts +14 -0
  51. package/dist/values.js +36 -0
  52. package/package.json +35 -95
  53. package/dist/GinkoEditor.vue.d.ts +0 -96
  54. package/dist/GinkoImagePicker.vue.d.ts +0 -36
  55. package/dist/agent/AGENTS.md +0 -13
  56. package/dist/agent/pages/docs/getting-started/collaboration.md +0 -435
  57. package/dist/agent/pages/docs/getting-started/component-coverage.md +0 -107
  58. package/dist/agent/pages/docs/getting-started/customize.md +0 -384
  59. package/dist/agent/pages/docs/getting-started/images.md +0 -188
  60. package/dist/agent/pages/docs/getting-started/in-place-editing.md +0 -110
  61. package/dist/agent/pages/docs/getting-started/layout-blocks.md +0 -148
  62. package/dist/agent/pages/docs/getting-started/runtime.md +0 -111
  63. package/dist/agent/pages/docs/getting-started.md +0 -128
  64. package/dist/authoring-D7MJezVG.js +0 -1780
  65. package/dist/authoring-D7MJezVG.js.map +0 -1
  66. package/dist/authoring.d.ts +0 -122
  67. package/dist/authoring.js +0 -2
  68. package/dist/collaboration.d.ts +0 -14
  69. package/dist/collaboration.js +0 -907
  70. package/dist/collaboration.js.map +0 -1
  71. package/dist/composables/useAssetRequests.d.ts +0 -44
  72. package/dist/composables/useCollaborationBinding.d.ts +0 -59
  73. package/dist/composables/useDevice.d.ts +0 -10
  74. package/dist/composables/useInsertMenu.d.ts +0 -67
  75. package/dist/composables/useMarkdownSync.d.ts +0 -96
  76. package/dist/composables/useStableAuthoringKit.d.ts +0 -16
  77. package/dist/documentConfig-Z6LdrWZj.js +0 -2360
  78. package/dist/documentConfig-Z6LdrWZj.js.map +0 -1
  79. package/dist/editorProps.d.ts +0 -124
  80. package/dist/index.js.map +0 -1
  81. package/dist/layout-kit.d.ts +0 -922
  82. package/dist/lib/collaboration/presence-record.d.ts +0 -18
  83. package/dist/lib/collaboration/presence.d.ts +0 -103
  84. package/dist/lib/collaboration/protocol.d.ts +0 -133
  85. package/dist/lib/collaboration/recovery.d.ts +0 -45
  86. package/dist/lib/collaboration/session.d.ts +0 -163
  87. package/dist/lib/collaboration/validation.d.ts +0 -42
  88. package/dist/lib/component-converters.d.ts +0 -119
  89. package/dist/lib/config/documentConfig.d.ts +0 -19
  90. package/dist/lib/config/editorConfig.d.ts +0 -38
  91. package/dist/lib/container-items.d.ts +0 -55
  92. package/dist/lib/conversionInvariants.d.ts +0 -3
  93. package/dist/lib/conversionLogger.d.ts +0 -10
  94. package/dist/lib/conversionPipeline.d.ts +0 -17
  95. package/dist/lib/conversionState.d.ts +0 -10
  96. package/dist/lib/conversionTypes.d.ts +0 -50
  97. package/dist/lib/editor-operations.d.ts +0 -39
  98. package/dist/lib/environment.d.ts +0 -6
  99. package/dist/lib/extensions/code-block.d.ts +0 -18
  100. package/dist/lib/extensions/component-boundary.d.ts +0 -9
  101. package/dist/lib/extensions/container-items.d.ts +0 -29
  102. package/dist/lib/extensions/element.d.ts +0 -19
  103. package/dist/lib/extensions/file.d.ts +0 -24
  104. package/dist/lib/extensions/heading.d.ts +0 -5
  105. package/dist/lib/extensions/image-upload.d.ts +0 -39
  106. package/dist/lib/extensions/image.d.ts +0 -39
  107. package/dist/lib/extensions/index.d.ts +0 -10
  108. package/dist/lib/extensions/inline-element.d.ts +0 -13
  109. package/dist/lib/extensions/markdown-clipboard.d.ts +0 -21
  110. package/dist/lib/extensions/profile.d.ts +0 -11
  111. package/dist/lib/extensions/slot.d.ts +0 -16
  112. package/dist/lib/extensions/span-style.d.ts +0 -15
  113. package/dist/lib/extensions/video.d.ts +0 -15
  114. package/dist/lib/image-properties.d.ts +0 -20
  115. package/dist/lib/input-rules.d.ts +0 -7
  116. package/dist/lib/markdown.d.ts +0 -11
  117. package/dist/lib/marks.d.ts +0 -7
  118. package/dist/lib/mdcToTiptap.d.ts +0 -20
  119. package/dist/lib/mdcTypes.d.ts +0 -20
  120. package/dist/lib/nodes.d.ts +0 -57
  121. package/dist/lib/nodeviews/block-actions.d.ts +0 -7
  122. package/dist/lib/nodeviews/code.d.ts +0 -4
  123. package/dist/lib/nodeviews/columns.d.ts +0 -17
  124. package/dist/lib/nodeviews/component.d.ts +0 -6
  125. package/dist/lib/nodeviews/icons.d.ts +0 -26
  126. package/dist/lib/nodeviews/image.d.ts +0 -9
  127. package/dist/lib/nodeviews/items.d.ts +0 -15
  128. package/dist/lib/nodeviews/lifecycle.d.ts +0 -45
  129. package/dist/lib/nodeviews/popover.d.ts +0 -15
  130. package/dist/lib/nodeviews/settings.d.ts +0 -11
  131. package/dist/lib/nodeviews/table-operations.d.ts +0 -50
  132. package/dist/lib/nodeviews/table.d.ts +0 -4
  133. package/dist/lib/profiles.d.ts +0 -62
  134. package/dist/lib/property-input.d.ts +0 -10
  135. package/dist/lib/property-step.d.ts +0 -77
  136. package/dist/lib/props.d.ts +0 -13
  137. package/dist/lib/stripStyleNodes.d.ts +0 -2
  138. package/dist/lib/tiptapToMdc.d.ts +0 -18
  139. package/dist/presence-record-CLdPZWKC.js +0 -291
  140. package/dist/presence-record-CLdPZWKC.js.map +0 -1
  141. package/dist/runtime.d.ts +0 -13
  142. package/dist/runtime.js +0 -3
  143. package/dist/style.css +0 -2
  144. package/dist/types.d.ts +0 -126
  145. package/dist/ui/GinkoActionButton.vue.d.ts +0 -8
  146. package/dist/ui/GinkoInsertMenu.vue.d.ts +0 -49
  147. package/dist/ui/GinkoKeyboardDock.vue.d.ts +0 -15
  148. package/dist/ui/GinkoNodePopover.vue.d.ts +0 -21
  149. package/dist/ui/GinkoRecipeIcon.vue.d.ts +0 -6
  150. package/dist/ui/GinkoSelectionToolbar.vue.d.ts +0 -10
  151. package/dist/ui/GinkoToolbar.vue.d.ts +0 -26
  152. package/dist/ui/GinkoToolbarIcon.vue.d.ts +0 -6
  153. package/dist/ui/block-shortcuts.d.ts +0 -6
  154. package/dist/ui/commands.d.ts +0 -78
  155. package/dist/ui/context.d.ts +0 -23
  156. package/dist/ui/editor-keyboard.d.ts +0 -15
  157. package/dist/ui/messages.d.ts +0 -214
  158. package/dist/ui/messages.de.d.ts +0 -6
  159. package/dist/ui/recipe-command.d.ts +0 -14
  160. package/dist/ui/recipe-search.d.ts +0 -47
  161. package/dist/ui/slash-command.d.ts +0 -17
  162. package/dist/ui/writingRecipes.d.ts +0 -13
  163. package/skills/ginko-editor/SKILL.md +0 -40
  164. package/skills/ginko-editor/agents/openai.yaml +0 -4
  165. package/skills/ginko-editor/references/in-place-editing.md +0 -50
  166. package/skills/ginko-editor/references/quickstart.md +0 -55
@@ -1 +0,0 @@
1
- {"version":3,"file":"documentConfig-Z6LdrWZj.js","names":[],"sources":["../src/lib/property-step.ts","../src/lib/conversionInvariants.ts","../src/lib/conversionLogger.ts","../src/lib/stripStyleNodes.ts","../src/lib/markdown.ts","../src/lib/nodes.ts","../src/lib/component-converters.ts","../src/lib/marks.ts","../src/lib/props.ts","../src/lib/mdcToTiptap.ts","../src/lib/profiles.ts","../src/lib/image-properties.ts","../src/lib/tiptapToMdc.ts","../src/lib/conversionPipeline.ts","../src/lib/extensions/code-block.ts","../src/lib/extensions/element.ts","../src/lib/extensions/file.ts","../src/lib/extensions/heading.ts","../src/lib/extensions/image.ts","../src/lib/input-rules.ts","../src/lib/extensions/inline-element.ts","../src/lib/extensions/slot.ts","../src/lib/extensions/span-style.ts","../src/lib/extensions/video.ts","../src/lib/config/documentConfig.ts"],"sourcesContent":["import { Fragment, Slice, type Node, type Schema } from '@tiptap/pm/model'\nimport { Step, StepMap, StepResult, type Mappable } from '@tiptap/pm/transform'\nimport type { JsonRecord, JsonValue } from '../types'\n\nconst stepType = 'ginkoSetNodePropertyV1'\nconst variantStepType = 'ginkoSetComponentVariantV1'\nconst propertyNodes = new Set(['element', 'inline-element', 'image', 'file', 'video'])\nconst forbiddenKeys = new Set(['__proto__', 'prototype', 'constructor'])\nconst registration = Symbol.for('@lupinum/ginko-editor/property-steps/v1')\nconst attributeStepType = 'ginkoSetNodeAttributeV1'\nconst attributeRegistration = Symbol.for('@lupinum/ginko-editor/attribute-step/v1')\n\nfunction cloneValue(value: unknown, depth = 0): JsonValue {\n if (depth > 32) throw new RangeError('Property value is too deeply nested.')\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (Array.isArray(value)) return value.map(item => cloneValue(item, depth + 1))\n if (value && typeof value === 'object' && [Object.prototype, null].includes(Object.getPrototypeOf(value))) {\n return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, cloneValue(entry, depth + 1)]))\n }\n throw new RangeError('Property value must be JSON data.')\n}\n\n/** Change one property while keeping other properties from the current document.\n * Whole props-object replacement loses independent edits when steps are rebased.\n */\nexport class SetNodePropertyStep extends Step {\n readonly value: JsonValue | undefined\n\n constructor(readonly pos: number, readonly key: string, value: JsonValue | undefined) {\n super()\n if (!Number.isSafeInteger(pos) || pos < 0 || !key || forbiddenKeys.has(key)) {\n throw new RangeError('Invalid property step position or key.')\n }\n this.value = value === undefined ? undefined : cloneValue(value)\n }\n\n apply(doc: Node) {\n if (this.pos >= doc.content.size) return StepResult.fail('Property position is outside the document.')\n const node = doc.nodeAt(this.pos)\n if (!node || !propertyNodes.has(node.type.name)) return StepResult.fail('No property node at this position.')\n const props: JsonRecord = { ...node.attrs.props }\n if (this.value === undefined) delete props[this.key]\n else props[this.key] = this.value\n const updated = node.type.create({ ...node.attrs, props }, null, node.marks)\n return StepResult.fromReplace(doc, this.pos, this.pos + 1,\n new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1))\n }\n\n getMap() { return StepMap.empty }\n\n invert(doc: Node) {\n const node = doc.nodeAt(this.pos)\n if (!node || !propertyNodes.has(node.type.name)) throw new RangeError('No property node to invert.')\n return new SetNodePropertyStep(this.pos, this.key, node.attrs.props?.[this.key])\n }\n\n map(mapping: Mappable) {\n const pos = mapping.mapResult(this.pos, 1)\n // An insertion immediately before the node sets deletedAfter too. Its\n // associated position survives; only discard an actually deleted target.\n return pos.deleted ? null : new SetNodePropertyStep(pos.pos, this.key, this.value)\n }\n\n merge(other: Step) {\n return other instanceof SetNodePropertyStep && other.pos === this.pos && other.key === this.key\n ? new SetNodePropertyStep(this.pos, this.key, other.value)\n : null\n }\n\n toJSON() {\n return { stepType, pos: this.pos, key: this.key,\n ...(this.value === undefined ? { remove: true } : { value: this.value }) }\n }\n\n static fromJSON(_schema: Schema, json: unknown) {\n if (!json || typeof json !== 'object' || !('pos' in json) || !('key' in json)\n || typeof json.pos !== 'number' || typeof json.key !== 'string') {\n throw new RangeError('Invalid property step.')\n }\n if ('remove' in json) {\n if (json.remove !== true || 'value' in json) throw new RangeError('Invalid property removal.')\n return new SetNodePropertyStep(json.pos, json.key, undefined)\n }\n if (!('value' in json)) throw new RangeError('Property step needs a value.')\n return new SetNodePropertyStep(json.pos, json.key, cloneValue(json.value))\n }\n}\n\n/** Tag and parser source metadata are one change, including when rebased. */\nexport class SetComponentVariantStep extends Step {\n readonly syntax: JsonValue | undefined\n constructor(readonly pos: number, readonly tag: string, syntax: JsonValue | undefined) {\n super()\n if (!Number.isSafeInteger(pos) || pos < 0 || !/^[a-z][a-z0-9-]*$/.test(tag)) {\n throw new RangeError('Invalid component variant step.')\n }\n this.syntax = syntax === undefined ? undefined : cloneValue(syntax)\n }\n apply(doc: Node) {\n if (this.pos >= doc.content.size) return StepResult.fail('Variant position is outside the document.')\n const node = doc.nodeAt(this.pos)\n if (node?.type.name !== 'element') return StepResult.fail('No component at this position.')\n const props: JsonRecord = { ...node.attrs.props }\n if (this.syntax === undefined) delete props.$\n else props.$ = this.syntax\n const updated = node.type.create({ ...node.attrs, tag: this.tag, props }, null, node.marks)\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, 1))\n }\n getMap() { return StepMap.empty }\n invert(doc: Node) {\n const node = doc.nodeAt(this.pos)\n if (node?.type.name !== 'element') throw new RangeError('No component to invert.')\n return new SetComponentVariantStep(this.pos, node.attrs.tag, node.attrs.props?.$)\n }\n map(mapping: Mappable) {\n const pos = mapping.mapResult(this.pos, 1)\n return pos.deleted ? null : new SetComponentVariantStep(pos.pos, this.tag, this.syntax)\n }\n /** A later variant choice for the same component replaces the earlier one. */\n merge(other: Step) {\n return other instanceof SetComponentVariantStep && other.pos === this.pos\n ? new SetComponentVariantStep(this.pos, other.tag, other.syntax) : null\n }\n toJSON() {\n return { stepType: variantStepType, pos: this.pos, tag: this.tag,\n ...(this.syntax === undefined ? { removeSyntax: true } : { syntax: this.syntax }) }\n }\n static fromJSON(_schema: Schema, json: unknown) {\n if (!json || typeof json !== 'object' || !('pos' in json) || !('tag' in json)\n || typeof json.pos !== 'number' || typeof json.tag !== 'string') throw new RangeError('Invalid variant step.')\n if ('removeSyntax' in json) {\n if (json.removeSyntax !== true || 'syntax' in json) throw new RangeError('Invalid variant syntax removal.')\n return new SetComponentVariantStep(json.pos, json.tag, undefined)\n }\n if (!('syntax' in json)) throw new RangeError('Variant step needs source syntax.')\n return new SetComponentVariantStep(json.pos, json.tag, cloneValue(json.syntax))\n }\n}\n\n/** Native AttrStep drops edits after insertion immediately before the node.\n * This field step uses the same surviving-position rule as property changes.\n */\nexport class SetNodeAttributeStep extends Step {\n readonly value: JsonValue\n constructor(readonly pos: number, readonly key: string, value: JsonValue) {\n super()\n if (!Number.isSafeInteger(pos) || pos < 0 || !key || key === 'props' || forbiddenKeys.has(key)) {\n throw new RangeError('Invalid node attribute step.')\n }\n this.value = cloneValue(value)\n }\n apply(doc: Node) {\n if (this.pos >= doc.content.size) return StepResult.fail('Attribute position is outside the document.')\n const node = doc.nodeAt(this.pos)\n if (!node || node.isText || !Object.hasOwn(node.type.spec.attrs ?? {}, this.key)) return StepResult.fail('Unknown node attribute.')\n const updated = node.type.create({ ...node.attrs, [this.key]: this.value }, null, node.marks)\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1))\n }\n getMap() { return StepMap.empty }\n invert(doc: Node) {\n const node = doc.nodeAt(this.pos)\n if (!node || !Object.hasOwn(node.attrs, this.key)) throw new RangeError('No node attribute to invert.')\n return new SetNodeAttributeStep(this.pos, this.key, node.attrs[this.key])\n }\n map(mapping: Mappable) {\n const pos = mapping.mapResult(this.pos, 1)\n return pos.deleted ? null : new SetNodeAttributeStep(pos.pos, this.key, this.value)\n }\n merge(other: Step) {\n return other instanceof SetNodeAttributeStep && other.pos === this.pos && other.key === this.key\n ? new SetNodeAttributeStep(this.pos, this.key, other.value) : null\n }\n toJSON() { return { stepType: attributeStepType, pos: this.pos, key: this.key, value: this.value } }\n static fromJSON(_schema: Schema, json: unknown) {\n if (!json || typeof json !== 'object' || !('pos' in json) || !('key' in json) || !('value' in json)\n || typeof json.pos !== 'number' || typeof json.key !== 'string') throw new RangeError('Invalid node attribute step.')\n return new SetNodeAttributeStep(json.pos, json.key, cloneValue(json.value))\n }\n}\n\n/** Both browser and backend schema creation install the same wire step. */\nexport function registerPropertyStep() {\n // The registry belongs to ProseMirror, which can outlive a reloaded editor\n // module in Nuxt development. Wire changes require a new versioned ID.\n if (Reflect.get(Step, registration) !== true) {\n Step.jsonID(stepType, SetNodePropertyStep)\n Step.jsonID(variantStepType, SetComponentVariantStep)\n Object.defineProperty(Step, registration, { value: true })\n }\n if (Reflect.get(Step, attributeRegistration) !== true) {\n Step.jsonID(attributeStepType, SetNodeAttributeStep)\n Object.defineProperty(Step, attributeRegistration, { value: true })\n }\n}\n","import type { JSONContent } from '@tiptap/core'\n\nimport type { ConversionIssue, ConversionIssueCode, ConversionPhase } from './conversionTypes'\n\nconst INLINE_NODE_TYPES = new Set([\n 'hardBreak',\n 'inline-element',\n 'span-style',\n 'text',\n])\n\nconst BLOCK_NODE_TYPES = new Set([\n 'blockquote',\n 'bulletList',\n 'codeBlock',\n 'comment',\n 'element',\n 'file',\n 'heading',\n 'horizontalRule',\n 'image',\n 'listItem',\n 'orderedList',\n 'paragraph',\n 'slot',\n 'table',\n 'tableCell',\n 'tableHeader',\n 'tableRow',\n 'video',\n])\n\nconst SUPPORTED_MARKS = new Set(['bold', 'code', 'italic', 'strike', 'link'])\n\nfunction issue(\n code: ConversionIssueCode,\n message: string,\n context?: Record<string, unknown>,\n severity: 'error' | 'warn' = 'error',\n phase: ConversionPhase = 'validate',\n): ConversionIssue {\n return {\n code,\n context,\n message,\n phase,\n severity,\n }\n}\n\nfunction isInlineType(type: string) {\n return INLINE_NODE_TYPES.has(type)\n}\n\nfunction isBlockType(type: string) {\n return BLOCK_NODE_TYPES.has(type)\n}\n\nfunction isKnownType(type: string) {\n return isInlineType(type) || isBlockType(type)\n}\n\nfunction validateNode(\n node: JSONContent,\n issues: ConversionIssue[],\n parentType: null | string,\n depth: number,\n) {\n if (!node || typeof node !== 'object') {\n issues.push(issue('invalid_node_shape', 'Node is not a valid object', { depth, parentType }))\n return\n }\n\n if (!node.type || typeof node.type !== 'string') {\n issues.push(issue('missing_node_type', 'Node is missing a valid \"type\"', { depth, parentType }))\n return\n }\n\n if (!isKnownType(node.type)) {\n issues.push(\n issue('unknown_node_type', `Unknown node type \"${node.type}\"`, {\n depth,\n nodeType: node.type,\n parentType,\n }),\n )\n }\n\n if (node.type === 'text') {\n for (const mark of node.marks ?? []) {\n if (!SUPPORTED_MARKS.has(mark.type)) {\n issues.push(issue('unknown_mark_type', `Unsupported text formatting \"${mark.type}\"`, { depth, parentType }))\n }\n }\n if (typeof node.text !== 'string') {\n issues.push(\n issue('invalid_text_node', 'Text node is missing string text', { depth, parentType }),\n )\n }\n if (Array.isArray(node.content) && node.content.length > 0) {\n issues.push(\n issue('text_node_has_children', 'Text node must not contain child content', {\n depth,\n parentType,\n }),\n )\n }\n return\n }\n\n if (node.type === 'paragraph') {\n const content = Array.isArray(node.content) ? node.content : []\n for (const child of content) {\n const childType = child?.type\n if (!childType || !isInlineType(childType)) {\n issues.push(\n issue('block_inside_paragraph', 'Paragraph contains non-inline child node', {\n childType: childType ?? null,\n depth,\n }),\n )\n }\n }\n }\n\n if (node.type === 'listItem') {\n const content = Array.isArray(node.content) ? node.content : []\n if (content.length === 0) {\n issues.push(\n issue('list_item_empty', 'List item must contain at least one child node', { depth }),\n )\n }\n if (content[0]?.type !== 'paragraph') {\n issues.push(\n issue('list_item_first_child_not_paragraph', 'List item must start with paragraph node', {\n depth,\n firstChildType: content[0]?.type ?? null,\n }),\n )\n }\n }\n\n if (!Array.isArray(node.content)) {\n return\n }\n\n for (const child of node.content) {\n validateNode(child, issues, node.type, depth + 1)\n }\n}\n\nexport function validateTiptapDocShape(doc: JSONContent): ConversionIssue[] {\n const issues: ConversionIssue[] = []\n\n if (!doc || typeof doc !== 'object') {\n issues.push(issue('invalid_doc_shape', 'Document payload is not a valid object'))\n return issues\n }\n\n if (doc.type !== 'doc') {\n issues.push(\n issue('invalid_doc_root_type', 'Root document type must be \"doc\"', {\n actual: doc.type ?? null,\n }),\n )\n }\n\n if (!Array.isArray(doc.content)) {\n issues.push(issue('missing_doc_content', 'Root document must contain a content array'))\n return issues\n }\n\n if (doc.content.length === 0) {\n issues.push(issue('empty_doc', 'Root document content is empty', undefined, 'warn'))\n return issues\n }\n\n for (const child of doc.content) {\n if (child?.type && isInlineType(child.type)) {\n issues.push(\n issue('inline_node_at_root', 'Inline node found at document root', {\n childType: child.type,\n }),\n )\n }\n validateNode(child, issues, 'doc', 1)\n }\n\n return issues\n}\n","import type { ConversionIssue, ConversionPhase, ConversionTraceEvent } from './conversionTypes'\n\ninterface ConversionTraceHandle {\n traceId: string\n timeline: ConversionTraceEvent[]\n}\n\nlet traceCounter = 0\n\nfunction nowIso() {\n return new Date().toISOString()\n}\n\nfunction nextTraceId() {\n traceCounter += 1\n return `conv_${Date.now().toString(36)}_${traceCounter.toString(36)}`\n}\n\nexport function startTrace(data?: Record<string, unknown>): ConversionTraceHandle {\n const trace: ConversionTraceHandle = {\n traceId: nextTraceId(),\n timeline: [\n {\n at: nowIso(),\n kind: 'start',\n data,\n },\n ],\n }\n\n\n return trace\n}\n\nexport function logPhase(\n trace: ConversionTraceHandle,\n phase: ConversionPhase,\n data?: Record<string, unknown>,\n) {\n trace.timeline.push({\n at: nowIso(),\n kind: 'phase',\n phase,\n data,\n })\n}\n\nexport function logIssue(trace: ConversionTraceHandle, issue: ConversionIssue) {\n trace.timeline.push({\n at: nowIso(),\n kind: 'issue',\n phase: issue.phase,\n issueCode: issue.code,\n message: issue.message,\n severity: issue.severity,\n data: issue.context,\n })\n\n if (issue.severity === 'error') {\n return\n }\n\n}\n\nexport function finishTrace(\n trace: ConversionTraceHandle,\n data?: Record<string, unknown>,\n): ConversionTraceEvent[] {\n trace.timeline.push({\n at: nowIso(),\n kind: 'finish',\n data,\n })\n return trace.timeline\n}\n","import type { MDCNode, MDCRoot } from './mdcTypes'\n\nexport function stripStyleNodes(root: MDCRoot): MDCRoot {\n\n const walk = (node: MDCNode | MDCRoot): MDCNode | MDCRoot | null => {\n if (node.type === 'element' && node.tag === 'style') {\n return null\n }\n\n if (node.type === 'element') {\n const children = (node.children || [])\n .map((child) => walk(child))\n .filter(Boolean) as MDCNode[]\n return { ...node, children }\n }\n\n if (node.type === 'root') {\n const children = (node.children || [])\n .map((child) => walk(child))\n .filter(Boolean) as MDCNode[]\n return { ...node, children }\n }\n\n return node\n }\n\n return walk(root) as MDCRoot\n}\n","import {\n createHeadingIdGenerator,\n headingSlugText,\n parseMdcDocument,\n serializeMdcDocument,\n} from '@lupinum/ginko-content/cms-contract'\n\nimport type { JsonRecord, JsonValue } from '../types'\nimport type { MDCNode, MDCRoot } from './mdcTypes'\nimport { stripStyleNodes } from './stripStyleNodes'\n\nexport interface StringifyMdcOptions {\n videoOutput?: 'html' | 'mdc'\n}\n\ntype ComarkElementNode = [string, Record<string, unknown>, ...ComarkNode[]]\ntype ComarkCommentNode = [null, Record<string, unknown>, string]\ntype ComarkNode = string | ComarkElementNode | ComarkCommentNode\n\n// Older Editor commands persisted components without source-origin metadata.\n// Preserve their colon default until hosts reseed those rooms from canonical\n// Markdown. Explicit origins on newly inserted or parsed nodes take precedence.\n// The intersection also accepts the older Content candidate's option type.\nconst legacyRoomSerialization: NonNullable<Parameters<typeof serializeMdcDocument>[1]> & { componentSyntax: 'colon' } = {\n componentSyntax: 'colon',\n}\n\nconst TABLE_SECTION_TAGS = new Set(['thead', 'tbody', 'tfoot'])\n\n/** Adapt one canonical parse result to the editor's lossless conversion tree. */\nexport function adaptMdcDocument(\n tree: Awaited<ReturnType<typeof parseMdcDocument>>,\n): MDCRoot {\n const nextHeadingId = createHeadingIdGenerator()\n return stripStyleNodes({\n children: comarkNodesToMdc(tree.nodes, nextHeadingId),\n type: 'root',\n })\n}\n\nconst HEADING_TAG = /^h([1-6])$/\n\n/** Keep a heading id only when it differs from the id the parser generates. */\nfunction headingProps(tag: string, props: JsonRecord, children: ComarkNode[], nextHeadingId: HeadingIds): JsonRecord {\n const level = HEADING_TAG.exec(tag)?.[1]\n if (!level) return props\n const generated = nextHeadingId(headingSlugText(children), Number(level))\n if (props.id !== generated) return props\n const rest = { ...props }\n delete rest.id\n return rest\n}\n\n/**\n * Stringify the Studio MDC object tree back to Comark/MDC-compatible markdown.\n */\nexport async function stringifyMdc(\n ast: MDCRoot,\n options: StringifyMdcOptions = {},\n): Promise<string> {\n if (!ast || !ast.children?.length) {\n return ''\n }\n // Serializer errors reach the caller. An empty document is never a fallback.\n const cleaned = stripStyleNodes(ast)\n const markdown = await serializeMdcDocument({\n frontmatter: {},\n meta: {},\n nodes: mdcNodesToComark(cleaned.children || [], options),\n }, legacyRoomSerialization)\n if (!markdown.trim()) return ''\n return markdown.endsWith('\\n') ? markdown : `${markdown}\\n`\n}\n\ntype HeadingIds = ReturnType<typeof createHeadingIdGenerator>\n\nfunction comarkNodesToMdc(nodes: ComarkNode[], nextHeadingId: HeadingIds): MDCNode[] {\n return nodes.flatMap((node) => comarkNodeToMdc(node, nextHeadingId))\n}\n\nfunction comarkNodeToMdc(node: ComarkNode, nextHeadingId: HeadingIds): MDCNode[] {\n if (typeof node === 'string') {\n return node ? [{ type: 'text', value: node }] : []\n }\n\n const [tag, rawProps, ...children] = node as ComarkElementNode | ComarkCommentNode\n if (tag === null) {\n return [{ type: 'comment', value: String(children[0] ?? '') }]\n }\n\n if (TABLE_SECTION_TAGS.has(tag)) {\n return comarkNodesToMdc(children, nextHeadingId)\n }\n\n // Heading ids are assigned in document order, before nested headings.\n const props = headingProps(tag, cleanComarkProps(rawProps), children, nextHeadingId)\n const childNodes = comarkNodesToMdc(children, nextHeadingId)\n return [\n {\n children: childNodes,\n props,\n tag,\n type: 'element',\n },\n ]\n}\n\nfunction cleanComarkProps(rawProps: Record<string, unknown> = {}): JsonRecord {\n const props: JsonRecord = {}\n for (const [key, value] of Object.entries(rawProps)) {\n if (value === undefined) {\n continue\n }\n props[key] = value as JsonValue\n }\n return props\n}\n\nfunction mdcNodesToComark(nodes: MDCNode[], options: StringifyMdcOptions): ComarkNode[] {\n return nodes.flatMap((node) => {\n const converted = mdcNodeToComark(node, options)\n // Markdown images and links are inline syntax. TipTap media nodes are\n // blocks, so retain that boundary at every structural depth.\n if (node.type === 'element' && node.props?.__mdc_block === true) {\n return [['p', {}, ...converted] satisfies ComarkElementNode]\n }\n return converted\n })\n}\n\nfunction mdcNodeToComark(node: MDCNode, options: StringifyMdcOptions): ComarkNode[] {\n if (node.type === 'text') {\n return [node.value ?? '']\n }\n\n if (node.type === 'comment') {\n return [[null, {}, node.value ?? '']]\n }\n\n const props = cleanMdcProps(node.props || {})\n\n if (node.tag === 'video' && options.videoOutput === 'html') {\n return [\n [\n 'video',\n {\n controls: true,\n ...(props.height !== undefined ? { height: props.height } : {}),\n ...(props.src !== undefined ? { src: props.src } : {}),\n ...(props.title !== undefined ? { title: props.title } : {}),\n ...(props.width !== undefined ? { width: props.width } : {}),\n $: { html: 1 },\n },\n ],\n ]\n }\n\n return [[node.tag, props, ...mdcNodesToComark(node.children || [], options)]]\n}\n\nfunction cleanMdcProps(rawProps: JsonRecord): Record<string, unknown> {\n const props: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(rawProps)) {\n if (value === undefined) continue\n if (key.startsWith('__mdc_')) continue\n props[key] = value\n }\n return props\n}\n\n","/**\n * Node converters for MDC to TipTap transformation\n *\n * Handles document structure: headings, paragraphs, lists, tables, etc.\n */\n\nimport type { JSONContent } from '@tiptap/core'\n\nimport type { JsonRecord } from '../types'\nimport type { MDCElement, MDCNode } from './mdcTypes'\n\n/**\n * Creates a heading node converter for a specific level\n */\nexport function createHeadingNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const element = node as MDCElement\n const level = Number.parseInt(element.tag?.charAt(1) || '1', 10)\n // The adapter keeps `id` only when the author chose it; generated ids stay implicit.\n const { id, ...props } = element.props ?? {}\n const attrs: JsonRecord = { level }\n if (typeof id === 'string' && id) attrs.id = id\n return createTipTapNodeFn({ ...element, props }, 'heading', { attrs })\n}\n\n/**\n * Creates a paragraph node\n */\nexport function createParagraphNode(\n node: MDCElement,\n convertNode: (node: MDCNode, parent?: MDCNode) => JSONContent | JSONContent[],\n options: { allowImageLift?: boolean } = {},\n): JSONContent | JSONContent[] {\n node.children = node.children?.filter((child) => !(child.type === 'text' && !child.value)) || []\n\n // Flatten children if any are arrays (e.g., from createMark)\n // Filter out null/undefined values that may come from empty text nodes\n const content = node.children\n .map((child) => convertNode(child, node))\n .flat()\n .filter(Boolean)\n\n if (options.allowImageLift !== false && content.length === 1 && content[0]?.type === 'image') {\n return content[0]\n }\n\n const paragraphAttrs =\n !node.props || Object.keys(node.props).length === 0 ? undefined : node.props\n\n const inlineTypes = new Set(['hardBreak', 'inline-element', 'span-style', 'text'])\n\n const hasBlockChildren = content.some((child) => {\n const type = child?.type\n return !type || !inlineTypes.has(type)\n })\n\n if (hasBlockChildren) {\n const splitNodes: JSONContent[] = []\n let inlineBuffer: JSONContent[] = []\n\n const flushInlineBuffer = () => {\n if (inlineBuffer.length === 0) {\n return\n }\n splitNodes.push({\n attrs: paragraphAttrs,\n content: inlineBuffer,\n type: 'paragraph',\n })\n inlineBuffer = []\n }\n\n for (const child of content) {\n const type = child?.type\n const isInlineChild = !!type && inlineTypes.has(type)\n\n if (isInlineChild) {\n inlineBuffer.push(child)\n } else {\n flushInlineBuffer()\n if (options.allowImageLift === false && splitNodes.length === 0) {\n // listItem requires first child paragraph; keep an empty one if block comes first.\n splitNodes.push({\n attrs: paragraphAttrs,\n content: [],\n type: 'paragraph',\n })\n }\n splitNodes.push(child)\n }\n }\n\n flushInlineBuffer()\n\n if (splitNodes.length > 0) {\n return splitNodes\n }\n }\n\n return {\n attrs: paragraphAttrs,\n content,\n type: 'paragraph',\n }\n}\n\n/**\n * Creates a list item node\n */\nexport function createListItemNode(\n node: MDCElement,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const children = (node.children || []) as MDCNode[]\n const blockTags = [\n 'blockquote',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'hr',\n 'ol',\n 'p',\n 'pre',\n 'table',\n 'ul',\n ]\n\n const hasBlockChild = children.some((child) => {\n return child.type === 'element' && blockTags.includes(child.tag || '')\n })\n\n let normalizedChildren: MDCNode[]\n if (hasBlockChild) {\n normalizedChildren = children\n } else {\n normalizedChildren = [{ children, props: {}, tag: 'p', type: 'element' } as MDCElement]\n }\n\n return createTipTapNodeFn(node, 'listItem', { children: normalizedChildren })\n}\n\n/**\n * Creates a table cell node (th or td)\n */\nexport function createTableCellNode(\n node: MDCElement,\n type: 'tableCell' | 'tableHeader',\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const children = (node.children || []) as MDCNode[]\n const blockTags = [\n 'blockquote',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'hr',\n 'ol',\n 'p',\n 'pre',\n 'table',\n 'ul',\n ]\n\n const hasBlockChild = children.some((child) => {\n return child.type === 'element' && blockTags.includes(child.tag || '')\n })\n\n let normalizedChildren: MDCNode[]\n if (hasBlockChild) {\n normalizedChildren = children\n } else {\n normalizedChildren = [{ children, props: {}, tag: 'p', type: 'element' } as MDCElement]\n }\n\n const style = typeof node.props?.style === 'string' ? node.props.style : ''\n const align = /(?:^|;)\\s*text-align:\\s*(left|center|right)\\s*(?:;|$)/i.exec(style)?.[1]?.toLowerCase()\n return createTipTapNodeFn(node, type, { attrs: { align }, children: normalizedChildren })\n}\n\n/**\n * Creates a code block (pre) node\n */\nexport function createPreNode(\n node: MDCElement,\n getNodeTextFn: (node: MDCElement) => string,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const tiptapNode = createTipTapNodeFn(node, 'codeBlock', {\n attrs: {\n filename: node.props?.filename,\n language: node.props?.language ?? null,\n },\n })\n\n const rawCodeText = node.props?.code\n const codeText = typeof rawCodeText === 'string' ? rawCodeText : getNodeTextFn(node)\n const initialContent = tiptapNode.content as Array<JSONContent> | undefined\n if ((!initialContent || initialContent.length === 0) && codeText) {\n tiptapNode.content = [{ text: codeText, type: 'text' }]\n }\n\n const content = (tiptapNode.content as Array<JSONContent>) || []\n\n if (content.length === 1 && content[0]?.text === '') {\n tiptapNode.content = []\n }\n\n content.forEach((child: JSONContent) => {\n delete child.marks\n })\n\n return tiptapNode\n}\n\n/**\n * Creates a span-style node (for styled spans)\n */\nexport function createSpanStyleNode(\n node: MDCElement,\n isValidAttrFn: (value?: string | null) => boolean,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const spanStyle = stringProp(node.props?.style)\n const spanClass = stringProp(node.props?.class) || stringProp(node.props?.className)\n const spanAttrs: JsonRecord = {\n class: isValidAttrFn(spanClass) ? String(spanClass).trim() : undefined,\n style: isValidAttrFn(spanStyle) ? String(spanStyle).trim() : undefined,\n }\n const cleanedNode = { ...node, props: { ...node.props } }\n\n delete (cleanedNode.props as JsonRecord).style\n delete (cleanedNode.props as JsonRecord).class\n delete (cleanedNode.props as JsonRecord).className\n\n return createTipTapNodeFn(cleanedNode as MDCElement, 'span-style', { attrs: spanAttrs })\n}\n\nfunction stringProp(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined\n}\n\n/**\n * Creates a template/slot node\n */\nexport function createTemplateNode(\n node: MDCElement,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const props = node.props || {}\n const name = (props.name as string) || (props.slotName as string) || 'default'\n const children = normalizeBlockChildren(node.children || [])\n\n return createTipTapNodeFn(node, 'slot', { attrs: { name }, children })\n}\n\nconst BLOCK_TAGS = new Set([\n 'blockquote',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'hr',\n 'ol',\n 'p',\n 'pre',\n 'table',\n 'template',\n 'ul',\n])\n\nexport function normalizeBlockChildren(children: MDCNode[]): MDCNode[] {\n const result: MDCNode[] = []\n let inlineRun: MDCNode[] = []\n const flushInlineRun = () => {\n if (inlineRun.length === 0) return\n result.push({ children: inlineRun, props: {}, tag: 'p', type: 'element' })\n inlineRun = []\n }\n\n for (const child of children) {\n const metadata = child.type === 'element' ? child.props?.$ : undefined\n const parserSaysBlock = metadata && typeof metadata === 'object' && !Array.isArray(metadata)\n && metadata.block === 1\n const isBlock = child.type === 'element'\n && (BLOCK_TAGS.has(child.tag || '') || parserSaysBlock)\n if (isBlock) {\n flushInlineRun()\n result.push(child)\n } else {\n inlineRun.push(child)\n }\n }\n flushInlineRun()\n return result\n}\n","/**\n * Component converters for MDC to TipTap transformation\n *\n * Handles custom components: file, image, video, template, comment, etc.\n */\n\nimport type { JSONContent } from '@tiptap/core'\n\nimport type { JsonRecord } from '../types'\nimport type { MDCElement, MDCNode } from './mdcTypes'\nimport { normalizeBlockChildren } from './nodes'\n\n/**\n * Creates a file node\n */\nexport function createFileNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const element = node as MDCElement\n return createTipTapNodeFn(element, 'file', {\n attrs: { props: element.props || {} },\n })\n}\n\n/**\n * Creates an image node (handles Image, image, and img tags)\n */\nexport function createImageNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const element = node as MDCElement\n return createTipTapNodeFn(element, 'image', {\n attrs: { props: element.props || {} },\n })\n}\n\n/**\n * Creates a video node\n */\nexport function createVideoNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const element = node as MDCElement\n return createTipTapNodeFn(element, 'video', { attrs: { ...element.props } })\n}\n\n/**\n * Creates a comment node\n */\nexport function createCommentNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const element = node as MDCElement\n return createTipTapNodeFn(element, 'comment', {\n attrs: { text: (node as { value?: string }).value },\n })\n}\n\n/**\n * Creates a blockquote node\n */\nexport function createBlockquoteNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const element = node as MDCElement\n return createTipTapNodeFn(element, 'blockquote', {\n children: element.children?.length\n ? normalizeBlockChildren(element.children)\n : [{ type: 'element', tag: 'p', props: {}, children: [] }],\n })\n}\n\n/**\n * Creates a horizontal rule node\n */\nexport function createHrNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n return createTipTapNodeFn(node as MDCElement, 'horizontalRule')\n}\n\n/**\n * Creates a hard break node\n */\nexport function createBrNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n return createTipTapNodeFn(node as MDCElement, 'hardBreak')\n}\n\n/**\n * Creates a table node\n */\nexport function createTableNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n return createTipTapNodeFn(node as MDCElement, 'table')\n}\n\n/**\n * Creates a table row node\n */\nexport function createTrNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n return createTipTapNodeFn(node as MDCElement, 'tableRow')\n}\n\n/**\n * Creates a table header cell node\n */\nexport function createThNode(\n node: MDCNode,\n createTableCellNodeFn: (node: MDCElement, type: 'tableCell' | 'tableHeader') => JSONContent,\n): JSONContent {\n return createTableCellNodeFn(node as MDCElement, 'tableHeader')\n}\n\n/**\n * Creates a table data cell node\n */\nexport function createTdNode(\n node: MDCNode,\n createTableCellNodeFn: (node: MDCElement, type: 'tableCell' | 'tableHeader') => JSONContent,\n): JSONContent {\n return createTableCellNodeFn(node as MDCElement, 'tableCell')\n}\n\n/**\n * Creates an ordered list node\n */\nexport function createOlNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const element = node as MDCElement\n return createTipTapNodeFn(element, 'orderedList', {\n attrs: { start: element.props?.start },\n children: element.children?.length ? element.children : [{ type: 'element', tag: 'li', props: {}, children: [] }],\n })\n}\n\n/**\n * Creates an unordered list node\n */\nexport function createUlNode(\n node: MDCNode,\n createTipTapNodeFn: (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n ) => JSONContent,\n): JSONContent {\n const element = node as MDCElement\n return createTipTapNodeFn(element, 'bulletList', {\n children: element.children?.length ? element.children : [{ type: 'element', tag: 'li', props: {}, children: [] }],\n })\n}\n\n/**\n * Creates a list item node\n */\nexport function createLiNode(\n node: MDCNode,\n createListItemNodeFn: (node: MDCElement) => JSONContent,\n): JSONContent {\n return createListItemNodeFn(node as MDCElement)\n}\n\n/**\n * Creates a paragraph node\n */\nexport function createPNode(\n node: MDCNode,\n createParagraphNodeFn: (\n node: MDCElement,\n options?: { allowImageLift?: boolean },\n ) => JSONContent | JSONContent[],\n): JSONContent | JSONContent[] {\n return createParagraphNodeFn(node as MDCElement)\n}\n\n/**\n * Creates a pre/code block node\n */\nexport function createPreNodeWrapper(\n node: MDCNode,\n createPreNodeFn: (node: MDCElement) => JSONContent,\n): JSONContent {\n return createPreNodeFn(node as MDCElement)\n}\n\n/**\n * Creates a span-style node\n */\nexport function createSpanNode(\n node: MDCNode,\n createSpanStyleNodeFn: (node: MDCElement) => JSONContent,\n): JSONContent {\n return createSpanStyleNodeFn(node as MDCElement)\n}\n\n/**\n * Creates a template/slot node\n */\nexport function createTemplateNodeWrapper(\n node: MDCNode,\n createTemplateNodeFn: (node: MDCElement) => JSONContent,\n): JSONContent {\n return createTemplateNodeFn(node as MDCElement)\n}\n\n/**\n * Creates a text node. Text is kept verbatim; MDC syntax is handled by the parser.\n */\nexport function createTextNodeWrapper(node: MDCNode): JSONContent {\n return { text: (node as { value: string }).value, type: 'text' }\n}\n","import type { JSONContent } from '@tiptap/core'\n\nimport type { MDCElement, MDCNode } from './mdcTypes'\n\nexport const tagToMark: Record<string, string> = {\n a: 'link',\n code: 'code',\n del: 'strike',\n em: 'italic',\n strong: 'bold',\n}\n\nfunction getNodeContent(node: MDCNode): string {\n if (node.type === 'text') {\n return node.value\n }\n\n let content = ''\n ;(node as MDCElement).children?.forEach((childNode) => {\n content += getNodeContent(childNode)\n })\n\n return content\n}\n\nexport function createMark(\n node: MDCNode,\n mark: string,\n accumulatedMarks: { attrs?: object; type: string }[] = [],\n convertNode?: (node: MDCNode, parent?: MDCNode) => JSONContent,\n): JSONContent[] {\n const attrs = { ...(node as MDCElement).props }\n\n const marks = [...accumulatedMarks, { attrs, type: mark }]\n\n if (node.type === 'element' && node.tag === 'code') {\n const text = getNodeContent(node)\n if (!text) {\n return []\n }\n return [\n {\n marks: [...marks].reverse(),\n text,\n type: 'text',\n },\n ]\n }\n\n const children = (node as MDCElement).children || []\n const result: (JSONContent | null)[] = []\n\n for (const child of children) {\n if (child.type === 'text') {\n const text = getNodeContent(child)\n if (!text) {\n continue\n }\n result.push({\n marks: [...marks].reverse(),\n text,\n type: 'text',\n })\n } else if (child.type === 'element' && child.tag && tagToMark[child.tag]) {\n const markResult = createMark(child, tagToMark[child.tag]!, marks, convertNode)\n result.push(...markResult)\n } else if (child.type === 'element' && convertNode) {\n const tiptapNode = convertNode(child, node)\n if (tiptapNode.content?.length) {\n tiptapNode.content.forEach((contentNode) => {\n if (contentNode.type === 'text') {\n contentNode.marks = [...marks].reverse()\n }\n })\n }\n result.push(tiptapNode)\n } else if (convertNode) {\n result.push(convertNode(child, node))\n }\n }\n\n return result.filter((item): item is JSONContent => item !== null && item !== undefined)\n}\n","import type { JsonRecord, JsonValue } from '../types'\n\nexport function isValidAttr(value?: null | string) {\n if (!value) {\n return false\n }\n const trimmed = String(value).trim()\n if (!trimmed) {\n return false\n }\n const lower = trimmed.toLowerCase()\n return lower !== 'null' && lower !== 'undefined'\n}\n\nexport function sanitizeAssetUrl(url: string): null | string {\n const value = url.trim()\n if (!value) {\n return null\n }\n\n if (\n value.startsWith('./') ||\n value.startsWith('../') ||\n value.startsWith('/')\n ) {\n return value\n }\n\n try {\n const parsed = new URL(value)\n if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {\n return value\n }\n } catch {\n return null\n }\n\n return null\n}\n\nexport function sanitizeImageUrl(url: string): null | string {\n return url.trim().startsWith('data:image/') ? url.trim() : sanitizeAssetUrl(url)\n}\n\nexport function sanitizeResolvedAssetUrl(url: string): null | string {\n const safe = sanitizeAssetUrl(url)\n if (safe) return safe\n const value = url.trim()\n try {\n return new URL(value).protocol === 'blob:' ? value : null\n } catch {\n return null\n }\n}\n\n/** Browser-only display URLs returned by an explicit host asset provider. */\nexport function sanitizeResolvedImageUrl(url: string): null | string {\n return sanitizeImageUrl(url) ?? sanitizeResolvedAssetUrl(url)\n}\n\n/** Preserve canonical media metadata across native rich-text clipboard HTML. */\nexport function readStoredMediaProps(\n element: { getAttribute: (name: string) => string | null },\n): JsonRecord | undefined {\n const source = element.getAttribute('data-ginko-props')\n if (!source) return undefined\n try {\n const value: unknown = JSON.parse(source, (_key: string, entry: unknown) => {\n if (typeof entry === 'number' && !Number.isFinite(entry)) throw new TypeError('Non-finite media property')\n return entry\n })\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n // JSON parsing supplies JSON values; the reviver rejects non-finite numbers.\n return value as JsonRecord\n } catch {\n return undefined\n }\n}\n\nexport function cleanSpanProps(attrs?: Record<string, unknown> | null) {\n const props: Record<string, string> = {}\n if (isValidAttr(attrs?.style as string)) props.style = String(attrs!.style).trim()\n if (isValidAttr((attrs as Record<string, unknown>)?.class as string))\n props.class = String((attrs as Record<string, unknown>).class).trim()\n return props\n}\n\nexport function normalizeProps(\n nodeProps: Record<string, unknown>,\n extraProps: object,\n): Array<[string, JsonValue]> {\n return Object.entries({ ...nodeProps, ...extraProps })\n .map(([key, value]) => {\n if (key === 'className') {\n return [\n 'class',\n typeof value === 'string' ? value : (value as Array<string>).join(' '),\n ] as [string, JsonValue]\n }\n return [key.trim(), value as JsonValue] as [string, JsonValue]\n })\n .filter(([key]) => Boolean(String(key).trim()))\n}\n","/**\n * MDC to TipTap converter\n *\n * Main entry point that combines categorized converters:\n * - marks.ts: Text formatting (bold, italic, link, code, strike)\n * - nodes.ts: Document structure (headings, lists, tables, paragraphs)\n * - component-converters.ts: Custom components (file, image, video)\n */\n\nimport type { JSONContent } from '@tiptap/core'\nimport {\n classifyPortableMarkdownElement,\n type PortableComponentPolicy,\n} from '@lupinum/ginko-content/cms-contract'\n\nimport type { JsonRecord, JsonValue } from '../types'\n// Import categorized converters\nimport {\n createBlockquoteNode,\n createBrNode,\n createCommentNode,\n createFileNode,\n createHrNode,\n createImageNode,\n createLiNode,\n createOlNode,\n createPNode,\n createPreNodeWrapper,\n createSpanNode,\n createTableNode,\n createTdNode,\n createTemplateNodeWrapper,\n createTextNodeWrapper,\n createThNode,\n createTrNode,\n createUlNode,\n createVideoNode,\n} from './component-converters'\nimport { createMark, tagToMark } from './marks'\nimport type { MDCElement, MDCNode, MDCRoot } from './mdcTypes'\nimport {\n createHeadingNode,\n createListItemNode,\n createParagraphNode,\n createPreNode,\n createSpanStyleNode,\n createTableCellNode,\n createTemplateNode,\n} from './nodes'\nimport { isValidAttr } from './props'\nimport { stripStyleNodes } from './stripStyleNodes'\n\ntype MDCToTipTapMap = Record<string, (node: MDCNode | MDCRoot) => JSONContent | JSONContent[]>\ntype MDCToTipTapConverter = (\n node: MDCNode | MDCRoot,\n parent?: MDCNode,\n) => JSONContent | JSONContent[]\ntype TipTapNodeFactory = (\n node: MDCElement,\n type: string,\n extra?: { attrs?: JsonRecord; children?: MDCNode[] },\n) => JSONContent\n\n/**\n * Creates the main MDC to TipTap conversion map\n * Combines entries from marks, nodes, and component categories\n */\nfunction createMdcToTiptapMap(\n convert: MDCToTipTapConverter,\n createNode: TipTapNodeFactory,\n): MDCToTipTapMap {\n // Create mark entries from tagToMark mapping\n const markMapEntries = Object.entries(tagToMark).map(([key, value]) => [\n key,\n (node: MDCNode) => createMark(node, value, [], convert),\n ])\n\n // Component and node converters\n return {\n // Marks (text formatting)\n ...Object.fromEntries(markMapEntries),\n\n // Components (custom elements)\n blockquote: (node: MDCNode) => createBlockquoteNode(node, createNode),\n br: (node: MDCNode) => createBrNode(node, createNode),\n comment: (node: MDCNode) => createCommentNode(node, createNode),\n file: (node: MDCNode) => createFileNode(node, createNode),\n Image: (node: MDCNode) => createImageNode(node, createNode),\n image: (node: MDCNode) => createImageNode(node, createNode),\n img: (node: MDCNode) => createImageNode(node, createNode),\n video: (node: MDCNode) => createVideoNode(node, createNode),\n\n // Structural nodes\n h1: (node: MDCNode) => createHeadingNode(node, createNode),\n h2: (node: MDCNode) => createHeadingNode(node, createNode),\n h3: (node: MDCNode) => createHeadingNode(node, createNode),\n h4: (node: MDCNode) => createHeadingNode(node, createNode),\n h5: (node: MDCNode) => createHeadingNode(node, createNode),\n h6: (node: MDCNode) => createHeadingNode(node, createNode),\n hr: (node: MDCNode) => createHrNode(node, createNode),\n li: (node: MDCNode) => createLiNode(node, (n) => createListItemNode(n, createNode)),\n ol: (node: MDCNode) => createOlNode(node, createNode),\n p: (node: MDCNode) =>\n createPNode(node, (n, opts) => createParagraphNode(n, convert, opts)),\n pre: (node: MDCNode) =>\n createPreNodeWrapper(node, (n) => createPreNode(n, getNodeText, createNode)),\n span: (node: MDCNode) =>\n createSpanNode(node, (n) => createSpanStyleNode(n, isValidAttr, createNode)),\n table: (node: MDCNode) => createTableNode(node, createNode),\n td: (node: MDCNode) =>\n createTdNode(node, (n, t) => createTableCellNode(n, t, createNode)),\n template: (node: MDCNode) =>\n createTemplateNodeWrapper(node, (n) => createTemplateNode(n, createNode)),\n text: createTextNodeWrapper,\n th: (node: MDCNode) =>\n createThNode(node, (n, t) => createTableCellNode(n, t, createNode)),\n tr: (node: MDCNode) => createTrNode(node, createNode),\n ul: (node: MDCNode) => createUlNode(node, createNode),\n\n // Root document\n root: (node: MDCNode | MDCRoot) => createRootNode(node, convert),\n }\n}\n\n/**\n * Creates the root document node\n */\nfunction createRootNode(node: MDCNode | MDCRoot, convert: MDCToTipTapConverter): JSONContent {\n const element = node as MDCElement\n return {\n content: (element.children || []).flatMap((child) => convert(child, node as MDCNode)),\n type: 'doc',\n }\n}\n\n/**\n * Core TipTap node factory\n * Handles attribute cleaning and child conversion\n */\nfunction createTipTapNode(\n node: MDCElement,\n type: string,\n extra: { attrs?: JsonRecord; children?: MDCNode[] } = {},\n convert: MDCToTipTapConverter,\n): JSONContent {\n const { attrs = {}, children } = extra\n const attrsProps = (attrs as JsonRecord).props as JsonRecord | undefined\n const nodeProps = node.props || {}\n const mergedProps = { ...(attrsProps || {}), ...nodeProps }\n\n const cleanProps: Array<[string, JsonValue]> = []\n for (const [key, value] of Object.entries(mergedProps)) {\n if (value === undefined) {\n continue\n }\n if (key.startsWith('__mdc_')) {\n continue\n }\n\n const trimmedKey = key.trim()\n if (trimmedKey === 'class' || trimmedKey === 'className') {\n const classValue = typeof value === 'string' ? value : (value as Array<string>).join(' ')\n cleanProps.push(['class', classValue])\n } else {\n cleanProps.push([trimmedKey, value])\n }\n }\n\n const tiptapNode: JSONContent = { attrs, type }\n\n if (cleanProps.length > 0) {\n ;(tiptapNode.attrs as JsonRecord).props = Object.fromEntries(cleanProps)\n }\n\n const nodeChildren = children || node.children || []\n if (nodeChildren.length > 0) {\n tiptapNode.content = nodeChildren\n .flatMap((child) => convert(child, node))\n .filter(Boolean)\n }\n\n return tiptapNode\n}\n\n/**\n * Extracts text content from an element recursively\n */\nfunction getNodeText(node: MDCElement): string {\n let content = ''\n const walk = (child: MDCNode) => {\n if (child.type === 'text') {\n content += child.value || ''\n return\n }\n if (child.type === 'element') {\n ;(child.children || []).forEach((grandChild) => walk(grandChild))\n }\n }\n\n ;(node.children || []).forEach((child) => walk(child))\n return content\n}\n\n/**\n * Recursively removes empty text nodes from TipTap content\n * TipTap does not allow text nodes with empty strings\n */\nfunction removeEmptyTextNodes(content: JSONContent): JSONContent\nfunction removeEmptyTextNodes(content: JSONContent[]): JSONContent[]\nfunction removeEmptyTextNodes(content: JSONContent | JSONContent[]): JSONContent | JSONContent[] {\n if (Array.isArray(content)) {\n const filtered = content.filter((node) => {\n // Remove empty text nodes\n if (node?.type === 'text' && (!node.text || node.text === '')) {\n return false\n }\n return true\n })\n\n return filtered.map((node) => removeEmptyTextNodes(node))\n }\n\n if (content && typeof content === 'object') {\n const cleaned = { ...content }\n if (cleaned.content) {\n cleaned.content = removeEmptyTextNodes(cleaned.content)\n }\n return cleaned\n }\n\n return content\n}\n\n/**\n * Converts a single Editor node to TipTap format\n * Note: Can return JSONContent[] for text nodes with emojis, which will be flattened by caller\n */\nexport function mdcNodeToTiptap(\n node: MDCNode | MDCRoot,\n parent?: MDCNode,\n policy?: PortableComponentPolicy,\n): JSONContent | JSONContent[] {\n return createMdcToTiptapConverter(policy)(node, parent)\n}\n\nfunction createMdcToTiptapConverter(\n policy?: PortableComponentPolicy,\n): MDCToTipTapConverter {\n function convert(node: MDCNode | MDCRoot, parent?: MDCNode) {\n return convertMdcNode(node, parent, policy, converterMap, convert, createNode)\n }\n const createNode: TipTapNodeFactory = (node, type, extra) =>\n createTipTapNode(node, type, extra, convert)\n const converterMap = createMdcToTiptapMap(convert, createNode)\n return convert\n}\n\n// Native replacement and description controls can write each of these props.\n// Restricted or richer host components must keep their own component controls.\nconst nativeImagePropTypes = {\n src: ['asset'], id: ['string'], filename: ['string'], alt: ['string'], title: ['string'],\n width: ['string', 'number'], height: ['string', 'number'],\n} as const\n\nfunction isNativePolicyImage(node: MDCNode | MDCRoot, policy?: PortableComponentPolicy): boolean {\n if (node.type !== 'element' || node.tag !== 'image' || node.children?.length\n || typeof node.props?.id !== 'string' || !node.props.id || node.props.src !== node.props.id\n || !policy || !('version' in policy) || policy.version !== 2) return false\n const definition = policy.components.image\n const media = definition?.media\n if (!definition || definition.kind !== 'block' || definition.slots.length !== 0\n || definition.allowedChildren?.length !== 0 || media?.sourceProp !== 'src'\n || media.altProp !== 'alt' || media.titleProp !== 'title' || media.filenameProp !== 'filename'\n || Object.keys(definition.props).length !== Object.keys(nativeImagePropTypes).length) return false\n return Object.entries(nativeImagePropTypes).every(([key, types]) => {\n const prop = definition.props[key]\n return prop?.required === (key === 'src') && prop.allowedValues === null\n && prop.types.length === types.length && prop.types.every((type, index) => type === types[index])\n })\n}\n\nfunction convertMdcNode(\n node: MDCNode | MDCRoot,\n parent: MDCNode | undefined,\n policy: PortableComponentPolicy | undefined,\n converterMap: MDCToTipTapMap,\n convert: MDCToTipTapConverter,\n createNode: TipTapNodeFactory,\n): JSONContent | JSONContent[] {\n const type = node.type === 'element' ? node.tag! : node.type\n\n if (type === 'p' && (parent as MDCElement | undefined)?.tag === 'li') {\n return createParagraphNode(node as MDCElement, convert, { allowImageLift: false })\n }\n\n\n const classification = node.type === 'element'\n ? classifyPortableMarkdownElement(node, policy ?? { components: {} })\n : undefined\n const policyComponent = classification?.kind === 'component' && classification.registered\n\n // Canonical uploaded images keep the native image controls after reopening.\n // Other policy-selected collisions retain their authored component identity.\n if ((!policyComponent || isNativePolicyImage(node, policy)) && converterMap[type]) {\n return converterMap[type](node)\n }\n\n\n const authoredInline = classification?.kind === 'component' && classification.form === 'inline'\n if ((parent as MDCElement)?.tag === 'p' || authoredInline) {\n return createNode(node as MDCElement, 'inline-element', { attrs: { tag: type } })\n }\n\n // In tiptap side only, inside element, text must be enclosed in a paragraph\n if (node.type === 'element' && node.children?.[0]?.type === 'text') {\n node = {\n ...node,\n children: [\n {\n children: node.children,\n props: {},\n tag: 'p',\n type: 'element',\n },\n ],\n props: {\n ...node.props,\n __tiptapWrap: true,\n },\n }\n }\n\n return createNode(node as MDCElement, 'element', { attrs: { tag: type } })\n}\n\n/**\n * Convert MDC AST to TipTap JSON (without frontmatter)\n */\nexport function mdcToTiptap(\n body: MDCRoot,\n policy?: PortableComponentPolicy,\n): JSONContent {\n const cleanedBody = stripStyleNodes(body)\n\n // Remove invalid text node which added by table syntax\n cleanedBody.children = (cleanedBody.children || []).filter((child) => child.type !== 'text')\n\n\n\n const tree = createMdcToTiptapConverter(policy)(cleanedBody)\n\n // Handle case where mdcNodeToTiptap returns an array\n let doc: JSONContent\n if (Array.isArray(tree)) {\n doc = { type: 'doc', content: tree }\n } else {\n doc = tree\n }\n\n // Ensure there's at least one paragraph\n if (!doc.content || doc.content.length === 0) {\n doc.content = [{ content: [], type: 'paragraph' }]\n }\n\n // Final cleanup: remove any empty text nodes that may have been created\n const cleanedDoc = removeEmptyTextNodes(doc)\n\n return cleanedDoc\n}\n","import type { JSONContent } from '@tiptap/core'\nimport { Fragment, Slice, type Mark, type Node as ProseMirrorNode, type Schema } from '@tiptap/pm/model'\n\n/**\n * A content profile limits what a writer can create. `full` keeps every\n * supported block and component. The other profiles are closed sets:\n *\n * - `plain`: paragraphs and line breaks, no formatting.\n * - `inline`: `plain` plus bold, italic, and links.\n * - `article`: `inline` plus headings 2–4, lists, quotes, dividers, and images.\n */\nexport type EditorProfileName = 'plain' | 'inline' | 'article' | 'full'\n\nexport interface EditorProfile {\n readonly name: EditorProfileName\n /** Allowed node type names. `undefined` allows every node. */\n readonly nodes?: ReadonlySet<string>\n /** Allowed mark type names. `undefined` allows every mark. */\n readonly marks?: ReadonlySet<string>\n /** Allowed heading levels. Empty when headings are not allowed. */\n readonly headingLevels: readonly number[]\n}\n\n/**\n * Set this transaction meta when trusted content is loaded, for example a\n * document from the host or steps from a collaboration server. The profile\n * guard does not check such a transaction.\n */\nexport const profileExemptMeta = 'ginkoProfileExempt'\n\nconst textNodes = ['doc', 'paragraph', 'text', 'hardBreak']\nconst inlineMarks = ['bold', 'italic', 'link']\n\nexport const editorProfiles: Readonly<Record<EditorProfileName, EditorProfile>> = {\n plain: {\n name: 'plain',\n nodes: new Set(textNodes),\n marks: new Set(),\n headingLevels: [],\n },\n inline: {\n name: 'inline',\n nodes: new Set(textNodes),\n marks: new Set(inlineMarks),\n headingLevels: [],\n },\n article: {\n name: 'article',\n nodes: new Set([\n ...textNodes,\n 'heading',\n 'bulletList',\n 'orderedList',\n 'listItem',\n 'blockquote',\n 'horizontalRule',\n 'image',\n ]),\n marks: new Set(inlineMarks),\n headingLevels: [2, 3, 4],\n },\n full: {\n name: 'full',\n headingLevels: [1, 2, 3, 4, 5, 6],\n },\n}\n\nexport function resolveEditorProfile(profile: EditorProfileName | EditorProfile | undefined): EditorProfile {\n if (!profile) return editorProfiles.full\n return typeof profile === 'string' ? editorProfiles[profile] : profile\n}\n\nexport function isRestrictedProfile(profile: EditorProfile) {\n return !!profile.nodes || !!profile.marks\n}\n\nexport function profileAllowsNode(profile: EditorProfile, name: string, attrs?: Record<string, unknown>) {\n if (profile.nodes && !profile.nodes.has(name)) return false\n if (name === 'heading' && attrs && typeof attrs.level === 'number') {\n return profile.headingLevels.includes(attrs.level)\n }\n return true\n}\n\nexport function profileAllowsMark(profile: EditorProfile, name: string) {\n return !profile.marks || profile.marks.has(name)\n}\n\n/** Whether the profile allows any block other than paragraphs. */\nexport function profileAllowsBlocks(profile: EditorProfile) {\n return !profile.nodes || [...profile.nodes].some(name => !textNodes.includes(name))\n}\n\n/**\n * TipTap extension names whose input and paste rules stay active. `true`\n * keeps every rule. Rules of other extensions would create content that the\n * profile rejects, so they are not registered.\n */\nexport function profileRuleExtensions(profile: EditorProfile): true | string[] {\n if (!profile.nodes) return true\n return [...profile.nodes, ...(profile.marks ?? [])]\n}\n\nexport interface EditorProfileViolation {\n kind: 'node' | 'mark'\n type: string\n /** The heading level for a heading outside the allowed levels. */\n level?: number\n}\n\n/**\n * List every node and mark in a document that the profile does not allow.\n * Accepts a ProseMirror node or TipTap JSON, so servers can check stored\n * documents without an editor.\n */\nexport function findProfileViolations(\n doc: ProseMirrorNode | JSONContent,\n profile: EditorProfileName | EditorProfile,\n): EditorProfileViolation[] {\n const resolved = resolveEditorProfile(profile)\n const violations: EditorProfileViolation[] = []\n if (!isRestrictedProfile(resolved)) return violations\n const visit = (type: string, attrs: Record<string, unknown> | undefined, marks: readonly { type: string }[]) => {\n if (!profileAllowsNode(resolved, type, attrs)) {\n violations.push(type === 'heading' && typeof attrs?.level === 'number'\n ? { kind: 'node', type, level: attrs.level }\n : { kind: 'node', type })\n }\n for (const mark of marks) {\n if (!profileAllowsMark(resolved, mark.type)) violations.push({ kind: 'mark', type: mark.type })\n }\n }\n if (isProseMirrorNode(doc)) {\n doc.descendants(node => visit(node.type.name, node.attrs, node.marks.map(mark => ({ type: mark.type.name }))))\n }\n else {\n const walk = (node: JSONContent) => {\n for (const child of node.content ?? []) {\n visit(child.type ?? '', child.attrs, child.marks ?? [])\n walk(child)\n }\n }\n walk(doc)\n }\n return violations\n}\n\nfunction isProseMirrorNode(value: ProseMirrorNode | JSONContent): value is ProseMirrorNode {\n return typeof (value as ProseMirrorNode).descendants === 'function'\n}\n\n/** The number of violations. A transaction may never raise it. */\nexport function countProfileViolations(doc: ProseMirrorNode, profile: EditorProfile) {\n if (!isRestrictedProfile(profile)) return 0\n let count = 0\n doc.descendants((node) => {\n if (!profileAllowsNode(profile, node.type.name, node.attrs)) count++\n for (const mark of node.marks) if (!profileAllowsMark(profile, mark.type.name)) count++\n })\n return count\n}\n\n/**\n * Reduce pasted or inserted content to what the profile allows. Text is never\n * dropped: disallowed blocks become paragraphs, containers such as lists and\n * tables are unwrapped, and disallowed marks are removed. Media and other\n * atoms that the profile does not allow are removed.\n */\nexport function sanitizeFragment(fragment: Fragment, schema: Schema, profile: EditorProfile): Fragment {\n if (!isRestrictedProfile(profile)) return fragment\n const blocks: ProseMirrorNode[] = []\n let inline: ProseMirrorNode[] = []\n const flushInline = () => {\n if (!inline.length) return\n blocks.push(schema.nodes.paragraph!.create(null, inline))\n inline = []\n }\n fragment.forEach((node) => {\n if (node.isInline) {\n inline.push(...sanitizeInline(node, schema, profile))\n return\n }\n flushInline()\n blocks.push(...sanitizeBlock(node, schema, profile))\n })\n // A fragment of only inline content stays inline so it joins the current paragraph.\n if (!blocks.length) return Fragment.fromArray(inline)\n flushInline()\n return Fragment.fromArray(blocks)\n}\n\n/** Sanitize a clipboard slice and keep it as open as its new structure allows. */\nexport function sanitizeSlice(slice: Slice, schema: Schema, profile: EditorProfile): Slice {\n if (!isRestrictedProfile(profile)) return slice\n const content = sanitizeFragment(slice.content, schema, profile)\n if (content.eq(slice.content)) return slice\n const open = Slice.maxOpen(content)\n return new Slice(content, Math.min(slice.openStart, open.openStart), Math.min(slice.openEnd, open.openEnd))\n}\n\nfunction filterMarks(marks: readonly Mark[], profile: EditorProfile) {\n return marks.filter(mark => profileAllowsMark(profile, mark.type.name))\n}\n\nfunction sanitizeInline(node: ProseMirrorNode, schema: Schema, profile: EditorProfile): ProseMirrorNode[] {\n if (node.isText) return [node.mark(filterMarks(node.marks, profile))]\n if (profileAllowsNode(profile, node.type.name, node.attrs)) {\n return [node.type.create(node.attrs, null, filterMarks(node.marks, profile))]\n }\n // Inline components keep their visible text; media and other atoms go.\n const text: ProseMirrorNode[] = []\n node.content.forEach(child => text.push(...sanitizeInline(child, schema, profile)))\n return text\n}\n\nfunction sanitizeBlock(node: ProseMirrorNode, schema: Schema, profile: EditorProfile): ProseMirrorNode[] {\n const paragraph = schema.nodes.paragraph!\n const name = node.type.name\n if (node.isTextblock) {\n const inline = textblockContent(node, schema, profile)\n if (profileAllowsNode(profile, name, node.attrs)) return [node.type.create(node.attrs, inline, node.marks)]\n if (name === 'heading' && profile.headingLevels.length) {\n const level = nearestLevel(profile.headingLevels, Number(node.attrs.level))\n return [node.type.create({ ...node.attrs, level }, inline, node.marks)]\n }\n return [paragraph.create(null, inline)]\n }\n if (node.isAtom || node.isLeaf) {\n return profileAllowsNode(profile, name, node.attrs) ? [node] : []\n }\n const children = sanitizeFragment(node.content, schema, profile)\n if (profileAllowsNode(profile, name, node.attrs)) {\n const rebuilt = node.type.createAndFill(node.attrs, children, node.marks)\n if (rebuilt) return [rebuilt]\n }\n const unwrapped: ProseMirrorNode[] = []\n children.forEach((child) => {\n unwrapped.push(child.isInline ? paragraph.create(null, child) : child)\n })\n return unwrapped\n}\n\n/** Code keeps its line breaks when it becomes a paragraph. */\nfunction textblockContent(node: ProseMirrorNode, schema: Schema, profile: EditorProfile) {\n const result: ProseMirrorNode[] = []\n const hardBreak = schema.nodes.hardBreak\n const allowsBreak = !!hardBreak && profileAllowsNode(profile, 'hardBreak')\n node.content.forEach((child) => {\n if (!child.isText || !node.type.spec.code || !child.text?.includes('\\n')) {\n result.push(...sanitizeInline(child, schema, profile))\n return\n }\n child.text.split('\\n').forEach((line, index) => {\n if (index) result.push(allowsBreak ? hardBreak.create() : schema.text(' '))\n if (line) result.push(schema.text(line))\n })\n })\n return result\n}\n\nfunction nearestLevel(levels: readonly number[], level: number) {\n return levels.reduce((best, candidate) =>\n Math.abs(candidate - level) < Math.abs(best - level) ? candidate : best, levels[0]!)\n}\n","/** Stored image fields supported by the editor's Content conversion. */\nexport const imageProperties = {\n id: 'text', filename: 'text', src: 'text', alt: 'text', title: 'text',\n width: 'number', height: 'number', fit: 'text', quality: 'number', format: 'text',\n focalX: 'number', focalY: 'number', cropX: 'number', cropY: 'number',\n cropWidth: 'number', cropHeight: 'number', class: 'text',\n} as const\n","import type { JSONContent } from '@tiptap/core'\n\nimport type { JsonRecord, JsonValue } from '../types'\nimport type { MDCComment, MDCElement, MDCNode, MDCRoot, MDCText } from './mdcTypes'\nimport { cleanSpanProps, normalizeProps } from './props'\nimport { stripStyleNodes } from './stripStyleNodes'\nimport { imageProperties } from './image-properties'\n\nexport interface TiptapToMDCOptions {\n fileOutput?: 'markdown' | 'mdc'\n imageOutput?: 'markdown' | 'mdc'\n videoOutput?: 'html' | 'mdc'\n}\n\ninterface TiptapToMDCContext {\n options: TiptapToMDCOptions\n}\n\ntype TiptapToMDCMap = Record<\n string,\n (node: JSONContent, context: TiptapToMDCContext) => MDCNode | MDCNode[] | MDCRoot\n>\n\nconst RE_TEXT_LEADING_SPACE = /^\\s+/\nconst RE_TEXT_TRAILING_SPACE = /\\s+$/\n\nconst markToTag: Record<string, string> = {\n bold: 'strong',\n code: 'code',\n italic: 'em',\n strike: 'del',\n}\n\nfunction isMeaningfulPropValue(value: unknown): boolean {\n if (value === undefined || value === null) {\n return false\n }\n if (typeof value !== 'string') {\n return true\n }\n const trimmed = value.trim()\n if (!trimmed) {\n return false\n }\n const lowered = trimmed.toLowerCase()\n return lowered !== 'undefined' && lowered !== 'null'\n}\n\nfunction sanitizeNumberish(value: unknown): null | number | string {\n if (!isMeaningfulPropValue(value)) {\n return null\n }\n if (typeof value === 'number') {\n return Number.isFinite(value) ? value : null\n }\n if (typeof value !== 'string') {\n return null\n }\n const normalized = value.trim()\n if (!normalized) {\n return null\n }\n const parsed = Number(normalized)\n if (!Number.isFinite(parsed)) {\n return null\n }\n return normalized\n}\n\nfunction createBlockquoteElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'blockquote')\n}\n\nfunction createBoldElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'strong')\n}\n\nfunction createBrElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'br')\n}\n\nfunction createBulletListElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'ul')\n}\n\nfunction createCodeElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'code', { props: (node.attrs || {}) as JsonRecord })\n}\n\nfunction createCommentElement(node: JSONContent): MDCComment {\n return { type: 'comment', value: node.attrs!.text }\n}\n\nfunction createDocElement(node: JSONContent, context: TiptapToMDCContext): MDCRoot {\n return {\n children: (node.content || []).flatMap((child) => tiptapNodeToMDC(child, context)),\n type: 'root',\n } as MDCRoot\n}\n\nfunction createFileElementWrapper(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createFileElement(node, context)\n}\n\nfunction createHardBreakElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'br')\n}\n\nfunction createHeadingElementWrapper(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createHeadingElement(node, context)\n}\n\nfunction createHorizontalRuleElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'hr')\n}\n\nfunction createImageElementWrapper(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createImageElement(node, context)\n}\n\nfunction createItalicElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'em')\n}\n\nfunction createOrderedListElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'ol', { props: { start: node.attrs?.start } })\n}\n\nfunction createParagraphElementWrapper(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'p')\n}\n\nfunction createSlotElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n const slotName = node.attrs?.name || 'default'\n return createElement(node, context, 'template', { props: { name: slotName } })\n}\n\nfunction createSpanStyleElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'span', { props: cleanSpanProps(node.attrs as JsonRecord) })\n}\n\nfunction createStrikeElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'del')\n}\n\nfunction createTableElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'table')\n}\n\nfunction createTableCellElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'td', { props: tableAlignmentProps(node) })\n}\n\nfunction createTableHeaderElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'th', { props: tableAlignmentProps(node) })\n}\n\nfunction tableAlignmentProps(node: JSONContent): JsonRecord {\n const align = node.attrs?.align\n return ['left', 'center', 'right'].includes(align) ? { style: `text-align:${align}` } : {}\n}\n\nfunction createTableRowElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createElement(node, context, 'tr')\n}\n\nfunction createVideoElementWrapper(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n return createVideoElement(node, context)\n}\n\nconst tiptapToMDCMap: TiptapToMDCMap = {\n blockquote: createBlockquoteElement,\n bold: createBoldElement,\n br: createBrElement,\n bulletList: createBulletListElement,\n code: createCodeElement,\n codeBlock: createCodeBlockElement,\n comment: createCommentElement,\n doc: createDocElement,\n element: createElement,\n file: createFileElementWrapper,\n hardBreak: createHardBreakElement,\n heading: createHeadingElementWrapper,\n horizontalRule: createHorizontalRuleElement,\n image: createImageElementWrapper,\n 'inline-element': createElement,\n italic: createItalicElement,\n link: createLinkElement,\n listItem: createListItemElement,\n orderedList: createOrderedListElement,\n paragraph: createParagraphElementWrapper,\n slot: createSlotElement,\n 'span-style': createSpanStyleElement,\n strike: createStrikeElement,\n table: createTableElement,\n tableCell: createTableCellElement,\n tableHeader: createTableHeaderElement,\n tableRow: createTableRowElement,\n text: createTextElement,\n video: createVideoElementWrapper,\n}\n\nexport function tiptapNodeToMDC(\n node: JSONContent,\n context: TiptapToMDCContext,\n): MDCNode | MDCNode[] | MDCRoot {\n if (!node) {\n return {\n children: [],\n props: {},\n tag: 'p',\n type: 'element',\n }\n }\n\n if (node.type && tiptapToMDCMap[node.type]) {\n return tiptapToMDCMap[node.type]!(node, context)\n }\n\n throw new Error(`Cannot convert unknown editor node: ${String(node.type)}`)\n}\n\n/**\n * Convert TipTap JSON to MDC AST (without frontmatter)\n */\nexport async function tiptapToMDC(\n node: JSONContent,\n options?: TiptapToMDCOptions,\n): Promise<MDCRoot> {\n const cleaned = createMdcBodyFromTiptap(node, options)\n\n return cleaned\n}\n\nfunction createMdcBodyFromTiptap(node: JSONContent, options?: TiptapToMDCOptions): MDCRoot {\n const context: TiptapToMDCContext = {\n options: options || {},\n }\n\n const nodeCopy = structuredClone(node)\n\n const body = tiptapNodeToMDC(nodeCopy, context) as MDCRoot\n\n const cleaned = stripStyleNodes(body)\n\n return cleaned\n}\n\nfunction createElement(\n node: JSONContent,\n context: TiptapToMDCContext,\n tag?: string,\n extra: JsonRecord = {},\n): MDCElement {\n const { props = {}, ...rest } = extra as { props: object }\n let children = node.content || []\n\n // Unwrap TipTap wrapper\n if (node.attrs?.props?.__tiptapWrap) {\n if (children.length === 1 && children[0]?.type === 'slot') {\n const slot = children[0]\n slot.content = unwrapParagraph(slot.content || [])\n }\n delete node.attrs.props.__tiptapWrap\n }\n\n const propsArray = normalizeProps(node.attrs?.props || {}, props)\n\n if (node.type === 'paragraph') {\n if (!children || children.length === 0) {\n return { children: [], props: {}, tag: 'p', type: 'element' }\n }\n return createParagraphElement(node, context, propsArray, rest)\n }\n\n children = unwrapDefaultSlot(children)\n children = unwrapParagraph(children)\n\n return {\n children: node.children || children.flatMap((child) => tiptapNodeToMDC(child, context)),\n tag: tag || node.attrs?.tag,\n type: 'element',\n ...rest,\n props: Object.fromEntries(propsArray),\n }\n}\n\nexport function createParagraphElement(\n node: JSONContent,\n context: TiptapToMDCContext,\n propsArray: Array<[string, JsonValue]>,\n rest: object = {},\n): MDCElement {\n type MarkInfo = null | { attrs?: JsonRecord; type: string }\n\n interface Block {\n content: JSONContent[]\n mark: MarkInfo\n }\n\n const blocks: Block[] = []\n let currentBlockContent: JSONContent[] = []\n let currentBlockMark: MarkInfo = null\n\n function getMarkInfo(child: JSONContent): MarkInfo {\n if (child.type === 'text' && child.marks?.length === 1 && child.marks[0]?.type) {\n return child.marks[0] as { attrs?: JsonRecord; type: string }\n }\n\n if (\n child.type === 'link-element' &&\n child.content &&\n child.content.length === 1 &&\n child.content[0] &&\n child.content[0].type === 'text' &&\n child.content[0].marks?.length === 1 &&\n child.content[0].marks[0]?.type\n ) {\n return child.content[0].marks[0] as { attrs?: JsonRecord; type: string }\n }\n\n return null\n }\n\n function sameMark(markA: MarkInfo, markB: MarkInfo): boolean {\n if (!markA && !markB) {\n return true\n }\n if (!markA || !markB) {\n return false\n }\n return (\n markA.type === markB.type &&\n JSON.stringify(markA.attrs || {}) === JSON.stringify(markB.attrs || {})\n )\n }\n\n node.content!.forEach((child) => {\n const mark = getMarkInfo(child)\n\n if (!sameMark(mark, currentBlockMark)) {\n if (currentBlockContent.length > 0) {\n blocks.push({ content: currentBlockContent, mark: currentBlockMark })\n }\n currentBlockContent = []\n currentBlockMark = mark\n }\n\n currentBlockContent.push(child)\n })\n\n if (currentBlockContent.length > 0) {\n blocks.push({ content: currentBlockContent, mark: currentBlockMark })\n }\n\n const children = blocks.map((block) => {\n if (block.content.length > 1 && block.mark && markToTag[block.mark.type]) {\n block.content.forEach((child: JSONContent) => {\n if (child.type === 'text') {\n delete child.marks\n } else if (child.type === 'link-element' && child.content?.[0]) {\n delete child.content[0].marks\n }\n })\n\n const markTag = markToTag[block.mark.type]\n const hasAttrs = block.mark.attrs && Object.keys(block.mark.attrs).length > 0\n\n if (hasAttrs) {\n return {\n children: block.content.flatMap((child) => tiptapNodeToMDC(child, context)),\n tag: markTag,\n type: 'element',\n props: block.mark.attrs,\n } as MDCElement\n }\n\n return {\n children: block.content.flatMap((child) => tiptapNodeToMDC(child, context)),\n tag: markTag,\n type: 'element',\n } as MDCElement\n }\n\n return block.content.flatMap((child) => tiptapNodeToMDC(child, context))\n }) as MDCElement[]\n\n const mergedChildren = mergeSiblingsWithSameTag(children.flat(), Object.values(markToTag))\n\n return {\n tag: 'p',\n type: 'element',\n ...rest,\n children: mergedChildren,\n props: Object.fromEntries(propsArray),\n }\n}\n\nfunction createCodeBlockElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n const mdcNode = createElement(node, context, 'pre')\n const code = node.attrs?.code || getNodeContent(node) || ''\n const language = node.attrs?.language || ''\n const filename = node.attrs?.filename\n\n mdcNode.props!.language = language\n if (filename) {\n mdcNode.props!.filename = filename\n }\n\n mdcNode.children = [\n {\n children: [{ type: 'text', value: code }],\n props: { __ignoreMap: '' },\n tag: 'code',\n type: 'element',\n },\n ]\n\n return mdcNode\n}\n\nfunction createFileElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n const props = node.attrs?.props || {}\n const fileOutput = context.options.fileOutput ?? 'mdc'\n\n const fileProps: JsonRecord = {}\n if (props.id) fileProps.id = props.id\n if (props.filename) fileProps.filename = props.filename\n if (props.title) fileProps.title = props.title\n if (props.type) fileProps.type = props.type\n if (props.size) fileProps.size = props.size\n if (props.src) fileProps.src = props.src\n\n if (fileOutput === 'markdown') {\n const linkText = fileProps.title || fileProps.filename || fileProps.src || 'Download'\n return {\n children: [{ type: 'text', value: String(linkText) }],\n props: { __mdc_block: true, href: fileProps.src, title: fileProps.title },\n tag: 'a',\n type: 'element',\n }\n }\n\n return createElement(node, context, 'file', { props: fileProps })\n}\n\nfunction createHeadingElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n const level = node.attrs?.level || 1\n const mdcNode = createElement(node, context, `h${level}`)\n const id = node.attrs?.id\n if (typeof id === 'string' && id) mdcNode.props!.id = id\n else delete mdcNode.props!.id\n return mdcNode\n}\n\nfunction createImageElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n const props = node.attrs?.props || {}\n const src = props.src || node.attrs?.src\n const imageOutput = context.options.imageOutput ?? 'mdc'\n\n const imageProps: JsonRecord = {}\n for (const [key, kind] of Object.entries(imageProperties)) {\n const value = key === 'src' ? src : key === 'alt' ? props.alt || node.attrs?.alt : props[key]\n if (kind === 'number') {\n const number = sanitizeNumberish(value)\n if (number !== null) imageProps[key] = number\n } else if (key === 'id' || key === 'filename' ? !!value : isMeaningfulPropValue(value)) {\n imageProps[key] = value\n }\n }\n\n const transformKeys = [\n 'fit',\n 'quality',\n 'format',\n 'focalX',\n 'focalY',\n 'cropX',\n 'cropY',\n 'cropWidth',\n 'cropHeight',\n ]\n const hasTransforms = transformKeys.some((key) => {\n const value = props[key]\n return value !== undefined && value !== null && value !== ''\n })\n\n const sanitizedNode: JSONContent = {\n ...node,\n attrs: {\n ...(node.attrs || {}),\n props: {},\n },\n }\n\n if (imageOutput === 'markdown') {\n // Markdown carries the host-owned stable identity in its destination.\n // Host metadata and transforms belong to MDC image output; emitting them\n // as attributes would force HTML-like output and violate Content's native\n // image property policy.\n const markdownProps = {\n ...(imageProps.alt !== undefined ? { alt: imageProps.alt } : {}),\n ...(imageProps.src !== undefined ? { src: imageProps.src } : {}),\n ...(imageProps.title !== undefined ? { title: imageProps.title } : {}),\n }\n return createElement(sanitizedNode, context, 'img', {\n props: { ...markdownProps, __mdc_block: true },\n })\n }\n\n if (props.id || hasTransforms) {\n return createElement(sanitizedNode, context, 'image', { props: imageProps })\n }\n\n const tag = node.attrs?.tag\n if (tag === 'nuxt-img' || tag === 'nuxt-picture') {\n return createElement(sanitizedNode, context, tag, { props: imageProps })\n }\n\n return createElement(sanitizedNode, context, 'img', {\n props: { ...imageProps, __mdc_block: true },\n })\n}\n\nconst defaultLinkRel = 'noopener noreferrer nofollow'\n\nfunction createLinkElement(node: JSONContent): MDCElement {\n const attrs = node.attrs || {}\n const { class: className, href, rel, target, ...otherAttrs } = attrs\n const linkProps: Record<string, string> = {}\n\n if (href) linkProps.href = href\n if (target) linkProps.target = target\n // The schema's default `rel` is a rendering choice, not content the author wrote.\n if (rel && rel !== defaultLinkRel) linkProps.rel = rel\n if (className) linkProps.class = className\n\n for (const [key, value] of Object.entries(otherAttrs)) {\n // Unset attributes (e.g. a null title) must not serialize as \"null\".\n if (value === null || value === undefined || value === '') continue\n linkProps[key] = String(value)\n }\n\n return { children: node.children || [], props: linkProps, tag: 'a', type: 'element' }\n}\n\nfunction createListItemElement(node: JSONContent, context: TiptapToMDCContext) {\n return createElement(node, context, 'li')\n}\n\nfunction createTextElement(node: JSONContent, context: TiptapToMDCContext): MDCText | MDCText[] {\n const textValue = node.text || ''\n const prefix = textValue.match(RE_TEXT_LEADING_SPACE)?.[0] || ''\n const suffix = textValue.match(RE_TEXT_TRAILING_SPACE)?.[0] || ''\n const text = textValue.trim()\n\n if (!node.marks?.length) {\n return { type: 'text', value: textValue }\n }\n\n const res = node.marks.reduce(\n (acc: MDCText, mark: JsonRecord) => {\n const markType = mark.type as string\n if (markType && tiptapToMDCMap[markType]) {\n return tiptapToMDCMap[markType]!({ ...mark, children: [acc] }, context) as MDCText\n }\n return acc\n },\n { type: 'text', value: text },\n )\n\n const result: (MDCText | null)[] = []\n if (prefix) result.push({ type: 'text', value: prefix })\n result.push(res)\n if (suffix) result.push({ type: 'text', value: suffix })\n\n return result.filter(Boolean) as MDCText[]\n}\n\nfunction createVideoElement(node: JSONContent, context: TiptapToMDCContext): MDCElement {\n const props = node.attrs?.props || {}\n const videoProps: JsonRecord = {}\n\n if (node.attrs?.src) videoProps.src = node.attrs.src\n if (node.attrs?.title) videoProps.title = node.attrs.title\n if (node.attrs?.width) videoProps.width = node.attrs.width\n if (node.attrs?.height) videoProps.height = node.attrs.height\n if (props.src) videoProps.src = props.src\n if (props.title) videoProps.title = props.title\n if (props.width) videoProps.width = props.width\n if (props.height) videoProps.height = props.height\n\n return createElement(node, context, 'video', { props: videoProps })\n}\n\nfunction getNodeContent(node: JSONContent) {\n if (node.type === 'text') {\n return node.text\n }\n\n let content = ''\n node.content?.forEach((childNode) => {\n content += getNodeContent(childNode)\n })\n\n return content\n}\n\nfunction mergeSiblingsWithSameTag(children: MDCNode[], allowedTags: string[]): MDCNode[] {\n if (!Array.isArray(children)) {\n return children\n }\n\n const merged: MDCNode[] = []\n let i = 0\n\n while (i < children.length) {\n const current = children[i]\n const next = children[i + 1]\n const afterNext = children[i + 2]\n\n const canMerge =\n current &&\n afterNext &&\n current.type === 'element' &&\n afterNext.type === 'element' &&\n current.tag === afterNext.tag &&\n allowedTags.includes(current.tag) &&\n JSON.stringify(current.props || {}) === JSON.stringify(afterNext.props || {}) &&\n next &&\n next.type === 'text' &&\n next.value === ' '\n\n if (canMerge) {\n merged.push({\n ...current,\n children: [\n ...(current.children || []),\n { type: 'text', value: ' ' },\n ...(afterNext.children || []),\n ],\n })\n i += 3\n } else if (current) {\n merged.push(current)\n i++\n } else {\n i++\n }\n }\n\n return merged\n}\n\nfunction unwrapDefaultSlot(content: JSONContent[]): JSONContent[] {\n if (content.length === 1 && content[0]?.type === 'slot' && content[0].attrs?.name === 'default') {\n return content[0].content || []\n }\n return content\n}\n\nfunction unwrapParagraph(content: JSONContent[]): JSONContent[] {\n if (content.length === 1 && content[0]?.type === 'paragraph') {\n return content[0].content || []\n }\n return content\n}\n","import type { Editor } from '@tiptap/core'\nimport type { Schema } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\nimport type { JSONContent } from '@tiptap/core'\nimport {\n parseMdcDocument,\n projectMdcDocument,\n validateStoredPortableMarkdownAst,\n type PortableComponentPolicy,\n} from '@lupinum/ginko-content/cms-contract'\n\nimport type { AuthoringKit } from '../authoring'\nimport { validateTiptapDocShape } from './conversionInvariants'\nimport { finishTrace, logIssue, logPhase, startTrace } from './conversionLogger'\nimport type {\n ConversionIssue,\n ConversionIssueCode,\n ConversionPhase,\n ConversionResult,\n ConversionSeverity,\n} from './conversionTypes'\nimport { adaptMdcDocument, stringifyMdc } from './markdown'\nimport { mdcToTiptap } from './mdcToTiptap'\nimport { profileExemptMeta } from './profiles'\nimport type { TiptapToMDCOptions } from './tiptapToMdc'\nimport { tiptapToMDC } from './tiptapToMdc'\n\nexport type {\n ConversionErrorPayload,\n ConversionHealthState,\n ConversionIssue,\n ConversionIssueCode,\n ConversionPhase,\n ConversionRecoveredPayload,\n ConversionResult,\n ConversionSeverity,\n ConversionTraceEvent,\n} from './conversionTypes'\n\nfunction buildIssue(\n phase: ConversionPhase,\n code: ConversionIssueCode,\n message: string,\n detail?: unknown,\n context?: Record<string, unknown>,\n severity: ConversionSeverity = 'error',\n): ConversionIssue {\n return {\n code,\n context,\n detail,\n message,\n phase,\n severity,\n }\n}\n\nfunction success<T>(\n traceId: string,\n issues: ConversionIssue[],\n timeline: ReturnType<typeof finishTrace>,\n value: T,\n fallbackUsed = false,\n): ConversionResult<T> {\n return {\n fallbackUsed,\n issues,\n ok: true,\n timeline,\n traceId,\n value,\n }\n}\n\nfunction failure<T>(\n traceId: string,\n issues: ConversionIssue[],\n timeline: ReturnType<typeof finishTrace>,\n fallbackUsed = false,\n): ConversionResult<T> {\n return {\n fallbackUsed,\n issues,\n ok: false,\n timeline,\n traceId,\n }\n}\n\nfunction splitIssues(issues: ConversionIssue[]) {\n const errors = issues.filter((issue) => issue.severity === 'error')\n const warnings = issues.filter((issue) => issue.severity === 'warn')\n return { errors, warnings }\n}\n\nexport async function validateMarkdownForAuthoring(\n markdown: string,\n authoringKit: Pick<AuthoringKit, 'policy'>,\n): Promise<ConversionIssue | undefined> {\n try {\n const sourceDocument = await parseMdcDocument(markdown, { autoClose: false })\n return validateParsedDocumentForAuthoring(sourceDocument, authoringKit)\n } catch (error) {\n return buildIssue(\n 'validate',\n 'authoring_kit_rejected',\n 'This document violates the editor authoring kit.',\n error,\n )\n }\n}\n\nfunction validateParsedDocumentForAuthoring(\n sourceDocument: Awaited<ReturnType<typeof parseMdcDocument>>,\n authoringKit: Pick<AuthoringKit, 'policy'>,\n): ConversionIssue | undefined {\n const validation = validateStoredPortableMarkdownAst(\n projectMdcDocument(sourceDocument).body,\n authoringKit.policy,\n )\n if (validation.ok) return undefined\n const firstIssue = validation.issues[0]\n return buildIssue(\n 'validate',\n 'authoring_kit_rejected',\n 'This document violates the editor authoring kit.',\n new TypeError(\n `Invalid authoring kit: source is outside policy (${firstIssue?.code} at ${firstIssue?.path.join('.')}).`,\n ),\n )\n}\n\nexport async function convertMarkdownToTiptapDoc(\n markdown: string,\n): Promise<ConversionResult<JSONContent>> {\n let sourceDocument: Awaited<ReturnType<typeof parseMdcDocument>>\n try {\n sourceDocument = await parseMdcDocument(markdown, { autoClose: false })\n } catch (error) {\n return markdownParseFailure(markdown, error)\n }\n return convertParsedMdcDocumentToTiptap(markdown, sourceDocument)\n}\n\nfunction markdownParseFailure(\n markdown: string,\n error: unknown,\n): ConversionResult<JSONContent> {\n const trace = startTrace({\n direction: 'markdown_to_tiptap',\n })\n const issues: ConversionIssue[] = []\n logPhase(trace, 'parse_mdc', { inputLength: markdown.length })\n const issue = buildIssue(\n 'parse_mdc',\n 'parse_mdc_failed',\n 'Failed to parse MDC markdown',\n error,\n {\n inputLength: markdown.length,\n preview: markdown.slice(0, 200),\n },\n )\n issues.push(issue)\n logIssue(trace, issue)\n return failure(trace.traceId, issues, finishTrace(trace, { status: 'failed' }))\n}\n\nfunction convertParsedMdcDocumentToTiptap(\n markdown: string,\n sourceDocument: Awaited<ReturnType<typeof parseMdcDocument>>,\n policy?: PortableComponentPolicy,\n): ConversionResult<JSONContent> {\n const trace = startTrace({ direction: 'markdown_to_tiptap' })\n const issues: ConversionIssue[] = []\n logPhase(trace, 'parse_mdc', { inputLength: markdown.length })\n\n let ast: ReturnType<typeof adaptMdcDocument>\n try {\n ast = adaptMdcDocument(sourceDocument)\n } catch (error) {\n return markdownParseFailure(markdown, error)\n }\n\n logPhase(trace, 'mdc_to_tiptap')\n\n let doc: JSONContent\n try {\n doc = mdcToTiptap(ast, policy)\n } catch (error) {\n const issue = buildIssue(\n 'mdc_to_tiptap',\n 'mdc_to_tiptap_failed',\n 'Failed to convert MDC AST to TipTap JSON',\n error,\n )\n issues.push(issue)\n logIssue(trace, issue)\n return failure(trace.traceId, issues, finishTrace(trace, { status: 'failed' }))\n }\n\n logPhase(trace, 'validate')\n const invariantIssues = validateTiptapDocShape(doc)\n for (const invariantIssue of invariantIssues) {\n issues.push(invariantIssue)\n logIssue(trace, invariantIssue)\n }\n\n const { errors } = splitIssues(issues)\n if (errors.length > 0) {\n return failure(trace.traceId, issues, finishTrace(trace, { status: 'failed' }))\n }\n\n return success(trace.traceId, issues, finishTrace(trace, { status: 'ok' }), doc)\n}\n\n/**\n * Checks that visual editing can represent a document before TipTap owns it.\n * Raw markdown remains canonical: a document that would lose meaning stays in\n * source mode instead of being silently normalized into a smaller document.\n */\nexport async function prepareMarkdownForVisualEditing(\n markdown: string,\n options?: TiptapToMDCOptions,\n schema?: Schema,\n authoringKit?: Pick<AuthoringKit, 'policy'>,\n context: 'document' | 'fragment' = 'document',\n): Promise<ConversionResult<JSONContent>> {\n let sourceDocument: Awaited<ReturnType<typeof parseMdcDocument>>\n try {\n sourceDocument = await parseMdcDocument(markdown, { autoClose: false })\n } catch (error) {\n return markdownParseFailure(markdown, error)\n }\n\n const converted = convertParsedMdcDocumentToTiptap(\n markdown,\n sourceDocument,\n authoringKit?.policy,\n )\n if (!converted.ok || !converted.value) return converted\n\n if (authoringKit && context === 'document') {\n const issue = validateParsedDocumentForAuthoring(sourceDocument, authoringKit)\n if (issue) {\n return { ...converted, issues: [...converted.issues, issue], ok: false }\n }\n }\n\n let visualDocument = converted.value\n if (schema) {\n try {\n const document = schema.nodeFromJSON(converted.value)\n document.check()\n // ProseMirror drops unknown attributes without throwing. Verify the\n // document the editor will actually keep, not only the converter output.\n visualDocument = document.toJSON()\n } catch (error) {\n const issue = buildIssue(\n 'validate',\n 'visual_schema_unsupported',\n 'This document contains nodes that the visual editor does not support.',\n error,\n )\n return {\n ...converted,\n issues: [...converted.issues, issue],\n ok: false,\n }\n }\n }\n\n const roundTrip = await convertTiptapDocToMarkdown(visualDocument, options)\n if (!roundTrip.ok || roundTrip.value === undefined) {\n return {\n ...converted,\n issues: [...converted.issues, ...roundTrip.issues],\n ok: false,\n }\n }\n\n try {\n const roundTripTree = await parseMdcDocument(roundTrip.value, { autoClose: false })\n if (stableJson(normalizeVisualSemantics(sourceDocument)) !== stableJson(normalizeVisualSemantics(roundTripTree))) {\n const issue = buildIssue(\n 'validate',\n 'source_only_required',\n 'This document contains content that visual editing cannot preserve.',\n undefined,\n { inputLength: markdown.length },\n )\n return {\n ...converted,\n issues: [...converted.issues, issue],\n ok: false,\n }\n }\n } catch (error) {\n const issue = buildIssue(\n 'validate',\n 'visual_compatibility_failed',\n 'Could not verify that visual editing preserves this document.',\n error,\n )\n return {\n ...converted,\n issues: [...converted.issues, issue],\n ok: false,\n }\n }\n\n return { ...converted, value: visualDocument }\n}\n\nfunction stableJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`\n if (value && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([left], [right]) => left.localeCompare(right))\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`).join(',')}}`\n }\n return JSON.stringify(value)\n}\n\nfunction normalizeVisualSemantics(document: {\n frontmatter?: unknown\n meta?: unknown\n nodes?: unknown[]\n}) {\n return {\n frontmatter: document.frontmatter ?? {},\n meta: document.meta ?? {},\n nodes: normalizeComarkNodes(document.nodes ?? []),\n }\n}\n\nfunction normalizeComarkNodes(nodes: unknown[]): unknown[] {\n return nodes.flatMap((node) => {\n if (!Array.isArray(node) || typeof node[0] !== 'string') return [node]\n const [tag, rawProps, ...children] = node\n const props = { ...((rawProps && typeof rawProps === 'object' ? rawProps : {}) as Record<string, unknown>) }\n const metadata = props.$\n if (\n metadata\n && typeof metadata === 'object'\n && 'syntax' in metadata\n && (metadata.syntax === 'angle' || metadata.syntax === 'colon')\n && 'block' in metadata\n ) {\n // Content may change delimiters to preserve edited property values.\n // Component identity and inline/block placement carry the meaning.\n props.$ = { component: 1, block: metadata.block }\n }\n // The serializer omits the schema's default `rel`.\n if (tag === 'a' && props.rel === 'noopener noreferrer nofollow') delete props.rel\n const normalizedChildren = normalizeComarkNodes(children)\n if (\n tag === 'p' &&\n normalizedChildren.length > 0 &&\n normalizedChildren.every(\n (child) => Array.isArray(child) && (child[0] === 'a' || child[0] === 'img'),\n )\n ) {\n return normalizedChildren\n }\n return [[tag, props, ...normalizedChildren]]\n })\n}\n\nexport async function convertTiptapDocToMarkdown(\n doc: JSONContent,\n options?: TiptapToMDCOptions,\n): Promise<ConversionResult<string>> {\n const trace = startTrace({\n direction: 'tiptap_to_markdown',\n })\n const issues: ConversionIssue[] = []\n\n logPhase(trace, 'validate')\n const invariantIssues = validateTiptapDocShape(doc)\n for (const invariantIssue of invariantIssues) {\n issues.push(invariantIssue)\n logIssue(trace, invariantIssue)\n }\n\n const invariantErrors = invariantIssues.filter((issue) => issue.severity === 'error')\n if (invariantErrors.length > 0) {\n return failure(trace.traceId, issues, finishTrace(trace, { status: 'failed' }))\n }\n\n logPhase(trace, 'tiptap_to_mdc')\n let ast: Awaited<ReturnType<typeof tiptapToMDC>>\n try {\n ast = await tiptapToMDC(doc, options)\n } catch (error) {\n const issue = buildIssue(\n 'tiptap_to_mdc',\n 'tiptap_to_mdc_failed',\n 'Failed to convert TipTap JSON to MDC AST',\n error,\n )\n issues.push(issue)\n logIssue(trace, issue)\n return failure(trace.traceId, issues, finishTrace(trace, { status: 'failed' }))\n }\n\n logPhase(trace, 'stringify_mdc')\n let markdown: string\n try {\n markdown = await stringifyMdc(ast, { videoOutput: options?.videoOutput })\n } catch (error) {\n const issue = buildIssue(\n 'stringify_mdc',\n 'stringify_mdc_failed',\n 'Failed to stringify MDC AST to markdown',\n error,\n )\n issues.push(issue)\n logIssue(trace, issue)\n return failure(trace.traceId, issues, finishTrace(trace, { status: 'failed' }))\n }\n\n return success(trace.traceId, issues, finishTrace(trace, { status: 'ok' }), markdown)\n}\n\nexport function applyTiptapDocToEditor(\n editor: Editor,\n doc: JSONContent,\n): ConversionResult<JSONContent> {\n const trace = startTrace({\n direction: 'tiptap_to_editor',\n })\n const issues: ConversionIssue[] = []\n\n logPhase(trace, 'validate')\n const invariantIssues = validateTiptapDocShape(doc)\n for (const invariantIssue of invariantIssues) {\n issues.push(invariantIssue)\n logIssue(trace, invariantIssue)\n }\n\n const invariantErrors = invariantIssues.filter((issue) => issue.severity === 'error')\n if (invariantErrors.length > 0) {\n return failure(trace.traceId, issues, finishTrace(trace, { status: 'failed' }))\n }\n\n logPhase(trace, 'set_content')\n try {\n // Schema.nodeFromJSON is strict. TipTap's createDocument helper can catch an\n // unknown-node error and return an empty fallback document, which would\n // make unsupported source look successfully applied.\n const nextDoc = editor.schema.nodeFromJSON(doc)\n nextDoc.check()\n\n // Echo guard: applying content that matches the current document (e.g. the\n // autosave round-trip writing our own value back) must not touch the doc,\n // undo history, selection, or focus.\n if (nextDoc.eq(editor.state.doc)) {\n return success(trace.traceId, issues, finishTrace(trace, { status: 'ok' }), doc)\n }\n\n // External content replaces the document outside the undo history, so a\n // single undo never jumps past the reset to an empty editor. Selection and\n // focus are preserved for a writer who is mid-edit.\n const { from, to } = editor.state.selection\n const wasFocused = editor.isFocused\n const tr = editor.state.tr\n .replaceWith(0, editor.state.doc.content.size, nextDoc.content)\n .setMeta('addToHistory', false)\n .setMeta(profileExemptMeta, true)\n tr.setSelection(\n TextSelection.between(\n tr.doc.resolve(Math.min(from, tr.doc.content.size)),\n tr.doc.resolve(Math.min(to, tr.doc.content.size)),\n ),\n )\n editor.view.dispatch(tr)\n if (wasFocused && !editor.isFocused) {\n editor.view.focus()\n }\n } catch (error) {\n const issue = buildIssue(\n 'set_content',\n 'set_content_failed',\n 'Failed to apply TipTap JSON to editor',\n error,\n )\n issues.push(issue)\n logIssue(trace, issue)\n return failure(trace.traceId, issues, finishTrace(trace, { status: 'failed' }))\n }\n\n return success(trace.traceId, issues, finishTrace(trace, { status: 'ok' }), doc)\n}\n","import type { EditorOverlayController } from '../../ui/context'\nimport TiptapCodeBlock from '@tiptap/extension-code-block'\n\nexport interface CodeBlockOptions {\n overlay?: EditorOverlayController\n theme: string\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n codeBlock: {\n setCodeBlock: (attributes?: { language: string }) => ReturnType\n toggleCodeBlock: (attributes?: { language: string }) => ReturnType\n }\n }\n}\n\nexport const CodeBlock = TiptapCodeBlock.extend<CodeBlockOptions>({\n addAttributes() {\n return {\n filename: {\n default: null,\n },\n language: {\n default: null,\n },\n }\n },\n\n addOptions() {\n return {\n ...this.parent?.(),\n theme: 'github-dark',\n }\n },\n\n addStorage() {\n return {\n theme: this.options.theme,\n }\n },\n})\n","import type { Content } from '@tiptap/core'\nimport { InputRule, mergeAttributes, Node } from '@tiptap/core'\n\nimport type { TiptapToMDCOptions } from '../tiptapToMdc'\nimport type { AuthoringKit } from '../../authoring'\nimport type { JsonRecord } from '../../types'\nimport type { EditorOverlayController } from '../../ui/context'\n\nexport interface ElementOptions {\n overlay?: EditorOverlayController\n getOutputOptions?: () => TiptapToMDCOptions\n getAuthoringKit?: () => AuthoringKit | undefined\n HTMLAttributes: JsonRecord\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n Element: {\n setElement: (tag: string, slot?: string) => ReturnType\n }\n }\n}\n\nconst ELEMENT_BLOCK_TRIGGER = /^::([a-z-]+)\\s$/i\n\nexport const Element = Node.create<ElementOptions>({\n name: 'element',\n group: 'block',\n content: 'block*',\n inline: false,\n // Generic component nodes carry distinct tags and properties. Joining them\n // at a text boundary would silently discard one component’s metadata.\n isolating: true,\n selectable: true,\n priority: 1000,\n\n addAttributes() {\n return {\n props: {\n default: {},\n parseHTML(element) {\n return JSON.parse(element.getAttribute('props') || '{}')\n },\n },\n tag: {\n default: 'div',\n },\n }\n },\n\n addCommands() {\n return {\n setElement:\n (tag: string, slot?: string) =>\n ({ chain, state }) => {\n const { from } = state.selection\n const value: Content = {\n attrs: { tag, props: { $: { syntax: 'angle', block: 1, sourceName: tag.charAt(0).toUpperCase() + tag.slice(1) } } },\n type: 'element',\n }\n\n if (slot) {\n value.content = [\n {\n attrs: { name: slot },\n content: [{ content: [], type: 'paragraph' }],\n type: 'slot',\n },\n ]\n }\n\n const command = chain().insertContentAt(from, value)\n if (!slot) {\n command.insertContentAt(from + 1, [{ content: [], type: 'paragraph' }])\n }\n return command.run()\n },\n }\n },\n\n addInputRules() {\n return [\n new InputRule({\n find: ELEMENT_BLOCK_TRIGGER,\n handler: ({ chain, match, range }) => {\n const value: Content = {\n attrs: { tag: match[1], props: { $: { syntax: 'colon', block: 1, sourceName: match[1] } } },\n content: [\n {\n attrs: { name: 'default' },\n content: [{ content: [], type: 'paragraph' }],\n type: 'slot',\n },\n ],\n type: 'element',\n }\n\n chain().deleteRange(range).insertContentAt(range.from, value).run()\n },\n }),\n ]\n },\n\n addOptions() {\n return {\n HTMLAttributes: {},\n }\n },\n\n parseHTML() {\n return [{ tag: 'div[data-type=\"element\"]' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n const mergedAttributes = mergeAttributes(HTMLAttributes, { 'data-type': 'element' })\n const tag = typeof mergedAttributes.tag === 'string' ? mergedAttributes.tag : ''\n const metadata = this.options.getAuthoringKit?.()?.authoring[tag]\n mergedAttributes['data-label'] = metadata?.label ?? tag\n const title = mergedAttributes.props?.title\n if (typeof title === 'string' && title.trim()) mergedAttributes['data-title'] = title\n mergedAttributes.props = JSON.stringify(mergedAttributes.props || {})\n return ['div', mergedAttributes, 0]\n },\n})\n","import type { CommandProps } from '@tiptap/core'\nimport { mergeAttributes, Node } from '@tiptap/core'\n\nimport type { JsonRecord } from '../../types'\nimport { readStoredMediaProps, sanitizeAssetUrl, sanitizeResolvedAssetUrl } from '../props'\n\nexport interface FileOptions {\n HTMLAttributes: JsonRecord\n inline: boolean\n resolveSrc?: (props: JsonRecord) => string | null | undefined\n}\n\nexport interface SetFileOptions {\n filename?: string\n id?: string\n size?: number\n src?: string\n title?: string\n type?: string\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n File: {\n addFile: () => ReturnType\n setFile: (options: SetFileOptions) => ReturnType\n }\n }\n}\n\nexport const File = Node.create<FileOptions>({\n name: 'file',\n draggable: false,\n\n addAttributes() {\n return {\n props: {\n default: {},\n parseHTML: (element) => readStoredMediaProps(element) ?? ({\n filename: element.getAttribute('data-filename') || '',\n id: element.getAttribute('data-file-id') || '',\n size: element.getAttribute('data-size') || '',\n src: element.getAttribute('href') || '',\n title: element.getAttribute('title') || '',\n type: element.getAttribute('data-file-type') || '',\n }),\n },\n }\n },\n\n addCommands() {\n return {\n addFile:\n () =>\n ({ commands }: CommandProps) =>\n commands.insertContent({\n attrs: { props: {} },\n type: this.name,\n }),\n setFile:\n (options: SetFileOptions) =>\n ({ commands }: CommandProps) =>\n commands.insertContent({\n attrs: { props: options },\n type: this.name,\n }),\n }\n },\n\n addOptions() {\n return {\n HTMLAttributes: {},\n inline: false,\n }\n },\n\n group() {\n return this.options.inline ? 'inline' : 'block'\n },\n\n inline() {\n return this.options.inline\n },\n\n parseHTML() {\n // Recognize our file node before the generic anchor mark on paste without\n // changing the schema's default block type.\n return [{ tag: 'a[data-type=\"file\"]', priority: 1100 }]\n },\n\n renderHTML({ node }) {\n const props = node.attrs.props || {}\n const attrs: Record<string, string> = { 'data-type': 'file' }\n const rawSrc = String(props.src || '')\n const displaySrc = sanitizeAssetUrl(rawSrc) ?? sanitizeResolvedAssetUrl(this.options.resolveSrc?.(props) || '')\n if (displaySrc) attrs.href = displaySrc\n attrs['data-ginko-props'] = JSON.stringify(props)\n if (props.title) attrs.title = String(props.title)\n if (props.id) attrs['data-file-id'] = String(props.id)\n if (props.filename) attrs['data-filename'] = String(props.filename)\n if (props.type) attrs['data-file-type'] = String(props.type)\n if (props.size) attrs['data-size'] = String(props.size)\n return [\n 'a',\n mergeAttributes(this.options.HTMLAttributes, attrs),\n props.title || props.filename || props.src || 'File',\n ]\n },\n})\n","import type { Editor } from '@tiptap/core'\nimport TiptapHeading from '@tiptap/extension-heading'\nimport type { ResolvedPos } from '@tiptap/pm/model'\nimport { Plugin, PluginKey, TextSelection, type EditorState } from '@tiptap/pm/state'\n\nexport interface HeadingOptions {\n levels: number[]\n showMarkers: boolean\n}\n\nexport const Heading = TiptapHeading.extend<HeadingOptions>({\n addOptions() {\n return {\n ...this.parent?.(),\n levels: [1, 2, 3, 4, 5, 6],\n showMarkers: false,\n }\n },\n\n // Parse every level, so a profile with fewer levels can still move pasted\n // headings to its nearest level instead of losing them as paragraphs.\n parseHTML() {\n return [1, 2, 3, 4, 5, 6].map(level => ({ tag: `h${level}`, attrs: { level } }))\n },\n\n addStorage() {\n return {\n showMarkers: this.options.showMarkers,\n }\n },\n\n addKeyboardShortcuts() {\n return {\n Backspace: ({ editor }) => handleBackspace(editor),\n }\n },\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('ginkoUniqueHeadingIds'),\n // Split, paste and duplicate can copy a custom anchor. Keep only its first use.\n appendTransaction(transactions, _oldState, state) {\n if (!transactions.some(transaction => transaction.docChanged)) return null\n const seen = new Set<string>()\n const tr = state.tr\n state.doc.descendants((node, pos) => {\n if (node.type.name !== 'heading' || !node.attrs.id) return\n if (seen.has(node.attrs.id)) tr.setNodeAttribute(pos, 'id', null)\n else seen.add(node.attrs.id)\n })\n return tr.docChanged ? tr.setMeta('addToHistory', false) : null\n },\n }),\n ]\n },\n\n addAttributes() {\n return {\n ...this.parent?.(),\n /** A custom anchor id. Null when the parser's generated id applies. */\n id: {\n default: null,\n // Splitting a heading must not create a second anchor with the same id.\n keepOnSplit: false,\n parseHTML: element => element.getAttribute('data-ginko-heading-id'),\n renderHTML: attributes => attributes.id ? { 'data-ginko-heading-id': attributes.id } : {},\n },\n }\n },\n})\n\nfunction handleBackspace(editor: Editor): boolean {\n const { state } = editor\n const { selection } = state\n const { $from, empty } = selection\n\n if ($from.parent.type.name !== 'heading') {\n return false\n }\n\n const headingText = $from.parent.textContent\n const isAtStart = $from.parentOffset === 0\n const textLength = headingText.length\n\n if (textLength === 1 && $from.parentOffset === 1 && empty) {\n return handleSingleCharDeletion(editor, state, $from)\n }\n\n if (textLength === 0 && isAtStart) {\n return handleEmptyHeadingAtStart(editor, state, $from)\n }\n\n return false\n}\n\nfunction handleSingleCharDeletion(editor: Editor, state: EditorState, $from: ResolvedPos): boolean {\n const headingPos = $from.before($from.depth)\n const headingNode = $from.parent\n const tr = state.tr\n const headingType = state.schema.nodes.heading\n if (!headingType) {\n return false\n }\n const level = headingNode.attrs.level\n const emptyHeading = headingType.create({ level, id: headingNode.attrs.id })\n\n tr.replaceWith(headingPos, headingPos + headingNode.nodeSize, emptyHeading)\n tr.setSelection(TextSelection.near(tr.doc.resolve(headingPos + 1)))\n\n editor.view.dispatch(tr)\n return true\n}\n\nfunction handleEmptyHeadingAtStart(\n editor: Editor,\n state: EditorState,\n $from: ResolvedPos,\n): boolean {\n const headingPos = $from.before($from.depth)\n const headingNode = $from.parent\n const tr = state.tr\n const paragraphType = state.schema.nodes.paragraph\n if (!paragraphType) {\n return false\n }\n const emptyParagraph = paragraphType.create()\n\n tr.replaceWith(headingPos, headingPos + headingNode.nodeSize, emptyParagraph)\n tr.setSelection(TextSelection.near(tr.doc.resolve(headingPos + 1)))\n\n editor.view.dispatch(tr)\n return true\n}\n","import type { ImageActions } from '../nodeviews/image'\nimport type { CommandProps } from '@tiptap/core'\nimport { mergeAttributes, Node } from '@tiptap/core'\n\nimport type { JsonRecord } from '../../types'\nimport { readStoredMediaProps, sanitizeImageUrl, sanitizeResolvedImageUrl } from '../props'\nimport type { EditorOverlayController } from '../../ui/context'\n\nexport interface ImageOptions {\n overlay?: EditorOverlayController\n actions?: ImageActions\n allowBase64: boolean\n HTMLAttributes: JsonRecord\n inline: boolean\n resolveSrc?: (props: JsonRecord) => string | null | undefined\n}\n\nexport interface SetImageOptions {\n alt?: string\n class?: string\n cropHeight?: number | string\n cropWidth?: number | string\n cropX?: number | string\n cropY?: number | string\n filename?: string\n fit?: string\n focalX?: number | string\n focalY?: number | string\n format?: string\n height?: number | string\n id?: string\n quality?: number | string\n src?: string\n title?: string\n width?: number | string\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n Image: {\n setImage: (options: SetImageOptions) => ReturnType\n }\n }\n}\n\nexport const Image = Node.create<ImageOptions>({\n name: 'image',\n draggable: false,\n\n addAttributes() {\n return {\n props: {\n default: {},\n parseHTML: (element) => readStoredMediaProps(element) ?? ({\n alt: element.getAttribute('alt') || '',\n class: element.getAttribute('class') || '',\n filename: element.getAttribute('data-filename') || '',\n height: element.getAttribute('height') || '',\n id: element.getAttribute('data-file-id') || '',\n src: element.getAttribute('src') || '',\n title: element.getAttribute('title') || '',\n width: element.getAttribute('width') || '',\n }),\n },\n }\n },\n\n addCommands() {\n return {\n setImage:\n (options: SetImageOptions) =>\n ({ commands }: CommandProps) =>\n commands.insertContent({\n attrs: { props: options },\n type: this.name,\n }),\n }\n },\n\n addOptions() {\n return {\n allowBase64: false,\n HTMLAttributes: {},\n inline: false,\n resolveSrc: undefined,\n }\n },\n\n group() {\n return this.options.inline ? 'inline' : 'block'\n },\n\n inline() {\n return this.options.inline\n },\n\n parseHTML() {\n return [\n {\n tag: 'img[data-ginko-props]',\n getAttrs: element => readStoredMediaProps(element) ? null : false,\n },\n {\n tag: this.options.allowBase64 ? 'img[src]' : 'img[src]:not([src^=\"data:\"])',\n },\n ]\n },\n\n renderHTML({ node }) {\n const props = node.attrs.props || {}\n const attrs: Record<string, string> = {}\n\n const rawSrc = String(props.src || '')\n attrs['data-ginko-props'] = JSON.stringify(props)\n const resolvedSrc = this.options.resolveSrc?.(props)\n const displaySrc =\n sanitizeResolvedImageUrl(String(resolvedSrc || '')) ?? sanitizeImageUrl(rawSrc)\n if (displaySrc) {\n attrs.src = displaySrc\n }\n if (props.alt) {\n attrs.alt = String(props.alt)\n }\n if (props.title) {\n attrs.title = String(props.title)\n }\n if (props.width) {\n attrs.width = String(props.width)\n }\n if (props.height) {\n attrs.height = String(props.height)\n }\n if (props.class) {\n attrs.class = String(props.class)\n }\n if (props.id) {\n attrs['data-file-id'] = String(props.id)\n }\n if (props.filename) {\n attrs['data-filename'] = String(props.filename)\n }\n\n return ['img', mergeAttributes(this.options.HTMLAttributes, attrs)]\n },\n})\n","import type { ExtendedRegExpMatchArray, nodeInputRule } from '@tiptap/core'\nimport { callOrReturn, InputRule } from '@tiptap/core'\n\ntype Config = Parameters<typeof nodeInputRule>[0] & {\n getText?: (match: ExtendedRegExpMatchArray) => string\n}\n\nexport function textInputRule(config: Config) {\n return new InputRule({\n find: config.find,\n handler: ({ match, range, state }) => {\n if (!match[1]) {\n return\n }\n\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n const text = callOrReturn(config.getText, undefined, match) || ''\n const { tr } = state\n const start = range.from\n let end = range.to\n\n const newNode = config.type.create(attributes)\n\n const offset = match[0].lastIndexOf(match[1])\n let matchStart = start + offset\n\n if (matchStart > end) {\n matchStart = end\n } else {\n end = matchStart + match[1].length\n }\n\n const lastChar = match[0].at(-1)\n\n if (lastChar) {\n tr.insertText(lastChar, start + match[0].length - 1)\n }\n\n tr.replaceWith(matchStart, end, newNode)\n tr.insertText(text, matchStart + 1)\n\n tr.scrollIntoView()\n },\n })\n}\n","import { mergeAttributes, Node } from '@tiptap/core'\n\nimport type { JsonRecord } from '../../types'\nimport { textInputRule } from '../input-rules'\n\nexport interface InlineElementOptions {\n HTMLAttributes: JsonRecord\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n InlineElement: {\n setInlineElement: (tag: string) => ReturnType\n }\n }\n}\n\nconst INLINE_ELEMENT_INPUT_RULE_FIND = /(?:^|\\s)(:([a-z-]+)(?:\\[([^\\]]*)\\])?)\\s$/i\n\nexport const InlineElement = Node.create<InlineElementOptions>({\n name: 'inline-element',\n group: 'inline',\n content: 'inline*',\n inline: true,\n priority: 1000,\n\n addAttributes() {\n return {\n props: {\n default: {},\n parseHTML(element) {\n return JSON.parse(element.getAttribute('props') || '{}')\n },\n },\n tag: {\n default: 'div',\n },\n }\n },\n\n addCommands() {\n return {\n setInlineElement:\n (tag: string) =>\n ({ chain, state }) =>\n chain()\n .insertContentAt(state.selection.from, {\n attrs: { tag, props: { $: { syntax: 'angle', block: 0, sourceName: tag.charAt(0).toUpperCase() + tag.slice(1) } } },\n type: 'inline-element',\n })\n .run(),\n }\n },\n\n addInputRules() {\n return [\n textInputRule({\n find: INLINE_ELEMENT_INPUT_RULE_FIND,\n getAttributes: (match: string[]) => ({ tag: match[2], props: { $: { syntax: 'colon', block: 0, sourceName: match[2] } } }),\n getText: (match: string[]) => match[3] ?? '',\n type: this.type,\n }),\n ]\n },\n\n addOptions() {\n return {\n HTMLAttributes: {},\n }\n },\n\n parseHTML() {\n return [{ tag: 'span[data-type=\"inline-element\"]' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n const mergedAttributes = mergeAttributes(HTMLAttributes, { 'data-type': 'inline-element' })\n mergedAttributes.props = JSON.stringify(mergedAttributes.props || {})\n return ['span', mergedAttributes, 0]\n },\n})\n","import { mergeAttributes, Node } from '@tiptap/core'\n\nimport type { AuthoringKit } from '../../authoring'\nimport type { JsonRecord } from '../../types'\n\nexport interface SlotOptions {\n getAuthoringKit?: () => AuthoringKit | undefined\n HTMLAttributes: JsonRecord\n nestable: boolean\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n Slot: {\n handleSlotBackspace: () => ReturnType\n }\n }\n}\n\nexport const Slot = Node.create<SlotOptions>({\n name: 'slot',\n content: 'block*',\n group: 'block',\n inline: false,\n isolating: true,\n selectable: false,\n priority: 1000,\n\n addAttributes() {\n return {\n name: {\n default: 'default',\n },\n props: {\n default: {},\n parseHTML(element) {\n return JSON.parse(element.getAttribute('props') || '{}')\n },\n },\n }\n },\n\n addCommands() {\n return {\n handleSlotBackspace: () => () => false,\n }\n },\n\n addKeyboardShortcuts() {\n return {\n Backspace: ({ editor }) => editor.commands.handleSlotBackspace(),\n }\n },\n\n addOptions() {\n return {\n HTMLAttributes: {},\n nestable: false,\n }\n },\n\n parseHTML() {\n return [{ tag: 'div[data-type=\"Slot\"]' }]\n },\n\n addNodeView() {\n return ({ node, editor, getPos }) => {\n const dom = document.createElement('div')\n dom.dataset.type = 'Slot'\n dom.setAttribute('name', node.attrs.name)\n const pos = getPos()\n const parent = pos === undefined ? undefined : editor.state.doc.resolve(pos).parent\n const label = this.options.getAuthoringKit?.()?.authoring[parent?.attrs.tag]?.slots?.[node.attrs.name]?.label\n dom.dataset.label = label ?? (node.attrs.name === 'default' ? 'Content' : node.attrs.name)\n return { dom, contentDOM: dom }\n }\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'Slot' }), 0]\n },\n})\n","import { mergeAttributes, Node } from '@tiptap/core'\nimport type { NodeType, Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport type { EditorState, Transaction } from '@tiptap/pm/state'\nimport type { JSONContent } from '@tiptap/vue-3'\n\nexport interface SpanStyleAttrs {\n class?: null | string\n style?: null | string\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n SpanStyle: {\n setSpanStyle: (attributes?: SpanStyleAttrs) => ReturnType\n unsetSpanStyle: () => ReturnType\n updateSpanStyle: (attributes?: SpanStyleAttrs) => ReturnType\n }\n }\n}\n\nfunction sanitizeAttributes(attributes?: SpanStyleAttrs) {\n const cleaned: Record<string, string> = {}\n if (attributes?.style?.trim()) cleaned.style = attributes.style.trim()\n if (attributes?.class?.trim()) cleaned.class = attributes.class.trim()\n return cleaned\n}\n\nfunction unwrapCurrentSpan(\n state: EditorState,\n dispatch: ((tr: Transaction) => void) | undefined,\n type?: NodeType,\n) {\n const { from } = state.selection\n let found: null | { node: ProseMirrorNode; pos: number } = null\n state.doc.nodesBetween(from, from, (node: ProseMirrorNode, pos: number) => {\n if (node.type === type) {\n found = { node, pos }\n return false\n }\n return undefined\n })\n\n if (!found) return false\n\n const target = found as { node: ProseMirrorNode; pos: number }\n const tr = state.tr.replaceWith(\n target.pos,\n target.pos + target.node.nodeSize,\n target.node.content,\n )\n dispatch?.(tr)\n return true\n}\n\nexport const SpanStyle = Node.create<SpanStyleAttrs>({\n name: 'span-style',\n inline: true,\n group: 'inline',\n content: 'text*',\n\n addAttributes() {\n return {\n class: {\n default: null,\n parseHTML: (element) => element.getAttribute('class'),\n },\n style: {\n default: null,\n parseHTML: (element) => element.getAttribute('style'),\n },\n }\n },\n\n addCommands() {\n return {\n setSpanStyle:\n (attributes) =>\n ({ chain, state }) => {\n const cleaned = sanitizeAttributes(attributes)\n const { empty, from, to } = state.selection\n\n if (empty) {\n return chain()\n .insertContent({\n attrs: cleaned,\n content: [{ text: '', type: 'text' }],\n type: this.name,\n })\n .focus()\n .run()\n }\n\n const slice = state.doc.slice(from, to)\n const content = slice.content.toJSON() as JSONContent[]\n\n return chain()\n .insertContentAt(\n { from, to },\n {\n attrs: cleaned,\n content,\n type: this.name,\n },\n )\n .focus()\n .run()\n },\n unsetSpanStyle:\n () =>\n ({ dispatch, state }) =>\n unwrapCurrentSpan(state, dispatch, this.type),\n updateSpanStyle:\n (attributes) =>\n ({ chain }) =>\n chain().updateAttributes(this.name, sanitizeAttributes(attributes)).run(),\n }\n },\n\n parseHTML() {\n return [{ tag: 'span:not([data-type])' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n const attrs = { ...HTMLAttributes }\n if (!attrs.style) delete attrs.style\n if (!attrs.class) delete attrs.class\n return ['span', mergeAttributes(attrs), 0]\n },\n})\n","import { mergeAttributes, Node } from '@tiptap/core'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n Video: {\n addVideo: () => ReturnType\n setVideo: (attrs: {\n height?: number | string\n src: string\n title?: string\n width?: number | string\n }) => ReturnType\n }\n }\n}\n\nexport const Video = Node.create({\n name: 'video',\n group: 'block',\n inline: false,\n selectable: false,\n priority: 1000,\n\n addAttributes() {\n return {\n alt: {\n default: null,\n },\n height: {\n default: null,\n },\n key: {\n default: '',\n },\n props: {\n default: null,\n parseHTML(element) {\n return JSON.parse(element.getAttribute('props') || '{}')\n },\n },\n src: {\n default: null,\n },\n title: {\n default: null,\n },\n width: {\n default: null,\n },\n }\n },\n\n addCommands() {\n return {\n addVideo:\n () =>\n ({ chain, state }) => {\n const { selection } = state\n const range = { from: selection.from, to: selection.to }\n const key = `${Date.now() % 1e6}-${Number.parseInt(String(Math.random() * 1e3))}`\n\n return chain()\n .insertContentAt(range, {\n attrs: { key, tag: 'video' },\n type: this.name,\n })\n .run()\n },\n setVideo:\n (attrs) =>\n ({ chain, state }) => {\n const { selection } = state\n const range = { from: selection.from, to: selection.to }\n const key = `${Date.now() % 1e6}-${Number.parseInt(String(Math.random() * 1e3))}`\n\n return chain()\n .insertContentAt(range, {\n attrs: {\n ...attrs,\n key,\n props: attrs,\n tag: 'video',\n },\n type: this.name,\n })\n .run()\n },\n }\n },\n\n addOptions() {\n return {\n HTMLAttributes: {},\n }\n },\n\n parseHTML() {\n return [{ tag: 'div[data-type=\"video\"]' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return [\n 'div',\n mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { 'data-type': 'video' }),\n ]\n },\n})\n","import type { NodeViewRenderer } from '@tiptap/core'\nimport { getSchema } from '@tiptap/core'\nimport { Table } from '@tiptap/extension-table'\nimport { TableCell } from '@tiptap/extension-table-cell'\nimport { TableHeader } from '@tiptap/extension-table-header'\nimport { TableRow } from '@tiptap/extension-table-row'\nimport StarterKit from '@tiptap/starter-kit'\n\nimport type { AuthoringKit } from '../../authoring'\nimport type { JsonRecord } from '../../types'\nimport type { TiptapToMDCOptions } from '../tiptapToMdc'\nimport { CodeBlock } from '../extensions/code-block'\nimport { Element } from '../extensions/element'\nimport { File } from '../extensions/file'\nimport { Heading } from '../extensions/heading'\nimport { Image } from '../extensions/image'\nimport { InlineElement } from '../extensions/inline-element'\nimport { Slot } from '../extensions/slot'\nimport { SpanStyle } from '../extensions/span-style'\nimport { Video } from '../extensions/video'\nimport { registerPropertyStep } from '../property-step'\n\ninterface DocumentExtensionOptions {\n getAuthoringKit?: () => AuthoringKit | undefined\n getOutputOptions?: () => TiptapToMDCOptions\n nodeViews?: Partial<Record<'codeBlock' | 'element' | 'image' | 'table', NodeViewRenderer>>\n resolveAsset?: (props: JsonRecord) => string | null | undefined\n showMarkdownMarkers?: boolean\n codeBlockTheme?: string\n /** Levels that commands and input rules can create. The schema accepts all six. */\n headingLevels?: readonly number[]\n}\n\n/** Schema-affecting definitions are shared by the canvas and server conversion. */\nexport function createDocumentExtensions(options: DocumentExtensionOptions = {}) {\n registerPropertyStep()\n return [\n StarterKit.configure({\n codeBlock: false,\n heading: false,\n underline: false,\n link: { HTMLAttributes: { target: null }, defaultProtocol: 'https', openOnClick: false },\n }),\n Heading.configure({\n levels: [...(options.headingLevels ?? [1, 2, 3, 4, 5, 6])],\n showMarkers: options.showMarkdownMarkers ?? false,\n }),\n Table.extend({\n addNodeView() { return options.nodeViews?.table ?? null },\n }).configure({ renderWrapper: true, resizable: false }),\n TableRow,\n TableHeader.extend({ content: 'paragraph+' }),\n TableCell.extend({ content: 'paragraph+' }),\n Element.extend({\n addNodeView() { return options.nodeViews?.element ?? null },\n }).configure({ getAuthoringKit: options.getAuthoringKit, getOutputOptions: options.getOutputOptions }),\n Slot.configure({ getAuthoringKit: options.getAuthoringKit }),\n InlineElement,\n CodeBlock.extend({\n addNodeView() { return options.nodeViews?.codeBlock ?? null },\n }).configure({ theme: options.codeBlockTheme ?? 'github-dark' }),\n Image.extend({\n addNodeView() { return options.nodeViews?.image ?? null },\n }).configure({ resolveSrc: options.resolveAsset }),\n Video,\n File.configure({ resolveSrc: options.resolveAsset }),\n SpanStyle,\n ]\n}\n\n/** Build the supported document schema without creating an editor or reading the DOM. */\nexport function createEditorSchema() {\n return getSchema(createDocumentExtensions())\n}\n"],"mappings":";;;;;;;;;;;;;AAIA,IAAM,KAAW,0BACX,KAAkB,8BAClB,oBAAgB,IAAI,IAAI;CAAC;CAAW;CAAkB;CAAS;CAAQ;AAAO,CAAC,GAC/E,qBAAgB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAa,CAAC,GACjE,KAAe,OAAO,IAAI,yCAAyC,GACnE,KAAoB,2BACpB,KAAwB,OAAO,IAAI,yCAAyC;AAElF,SAAS,EAAW,GAAgB,IAAQ,GAAc;CACxD,IAAI,IAAQ,IAAI,MAAU,WAAW,sCAAsC;CAE3E,IADI,MAAU,QAAQ,OAAO,KAAU,YAAY,OAAO,KAAU,aAChE,OAAO,KAAU,YAAY,OAAO,SAAS,CAAK,GAAG,OAAO;CAChE,IAAI,MAAM,QAAQ,CAAK,GAAG,OAAO,EAAM,KAAI,MAAQ,EAAW,GAAM,IAAQ,CAAC,CAAC;CAC9E,IAAI,KAAS,OAAO,KAAU,YAAY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AE,iBAAiB,EAAQ,gBAAgB,CAAC;EAC3D;EACA,GAAU,OAAO,EACf,cAAc;GAAE,OAAO,EAAQ,WAAW,aAAa;EAAK,EAC9D,CAAC,CAAC,CAAC,UAAU,EAAE,OAAO,EAAQ,kBAAkB,cAAc,CAAC;EAC/D,GAAM,OAAO,EACX,cAAc;GAAE,OAAO,EAAQ,WAAW,SAAS;EAAK,EAC1D,CAAC,CAAC,CAAC,UAAU,EAAE,YAAY,EAAQ,aAAa,CAAC;EACjD;EACA,GAAK,UAAU,EAAE,YAAY,EAAQ,aAAa,CAAC;EACnD;CACF;AACF;AAGA,SAAgB,KAAqB;CACnC,OAAO,GAAU,GAAyB,CAAC;AAC7C"}
@@ -1,124 +0,0 @@
1
- import type { AuthoringKit } from './authoring.js';
2
- import type { EditorCollaborationSession } from './collaboration.js';
3
- import type { AssetProvider, ImagePicker, ImageUploadHandler } from './types.js';
4
- import type { EditorProfileName } from './lib/profiles.js';
5
- import type { EditorMessages, EditorShortcuts, EditorToolbarGroup } from './ui/commands.js';
6
- /** Props of the `GinkoEditor` component. All props except `collaboration` are reactive. */
7
- export interface GinkoEditorProps {
8
- /** The canonical Markdown (MDC) source. Use with `v-model`. */
9
- modelValue: string;
10
- /**
11
- * `default` is a framed editor with a header. `inline` has no frame, header,
12
- * or source switch and inherits the host's typography, for editing text in place.
13
- */
14
- variant?: 'default' | 'inline';
15
- /** Shows the header with the insert button, mode switch, and status. Defaults to true for the default variant. */
16
- header?: boolean;
17
- /** Shows the switch between visual editing and Markdown source. Defaults to true for the default variant. */
18
- sourceToggle?: boolean;
19
- /**
20
- * Where the formatting row appears. `top` is above the writing surface.
21
- * `keyboard` docks it to the bottom of the visible viewport while the editor
22
- * has focus, so it stays above an on-screen keyboard. `auto` uses `keyboard`
23
- * on touch devices and otherwise `top` (default variant) or no row (inline
24
- * variant). `false` shows no row. Defaults to `top` for the default variant
25
- * and `auto` for the inline variant.
26
- */
27
- toolbarPlacement?: 'top' | 'keyboard' | 'auto' | false;
28
- /**
29
- * The floating toolbar over selected text. `auto` shows it only on devices
30
- * with a precise pointer, because touch devices show their own selection menu.
31
- */
32
- selectionToolbar?: 'auto' | 'always' | false;
33
- /** Groups of commands in the floating selection toolbar. */
34
- selectionToolbarItems?: readonly EditorToolbarGroup[];
35
- /**
36
- * The content that writers can create: `plain`, `inline` (bold, italic,
37
- * link), `article`, or `full`. It limits toolbar, shortcuts, slash menu,
38
- * input rules, and paste. Read once when the editor mounts; remount the
39
- * editor to use another profile. Content loaded from `modelValue` is not
40
- * changed, so also enforce the profile where you store the document.
41
- */
42
- profile?: EditorProfileName;
43
- /** Groups of built-in toolbar commands. */
44
- toolbarItems?: readonly EditorToolbarGroup[];
45
- /** Replacement interface text. Missing keys use the English defaults. */
46
- messages?: EditorMessages;
47
- /** Replacement keyboard shortcuts. `false` turns a shortcut off. */
48
- shortcuts?: EditorShortcuts;
49
- /** The element that receives menus and popovers. Defaults to the editor root. */
50
- overlayContainer?: globalThis.HTMLElement;
51
- /** An outer element that also accepts dropped image files. */
52
- imageDropTarget?: globalThis.HTMLElement;
53
- /** Host-owned persistence for inline image uploads. */
54
- imageUpload?: ImageUploadHandler;
55
- /** Host-owned selection of an existing image. */
56
- imagePicker?: ImagePicker;
57
- /** The largest accepted image upload, in bytes. Defaults to 10 MB. */
58
- imageMaxBytes?: number;
59
- /** The accessible name of the writing surface. Defaults to the `contentLabel` message. */
60
- ariaLabel?: string;
61
- /** Resolves stored asset ids to display URLs, and URLs back to ids. */
62
- assetProvider?: AssetProvider;
63
- /** Component policy, editing metadata, and recipes. Equal new kit objects do not reload the document. */
64
- authoringKit?: AuthoringKit;
65
- /** A shared editing session. Read once when the editor mounts; remount the editor to use another session. */
66
- collaboration?: EditorCollaborationSession;
67
- /** Stored in the code block extension storage for host renderers. */
68
- codeBlockTheme?: 'atom-dark' | 'dark' | 'default' | 'github-dark' | 'github-dim' | 'github-light' | 'visual-studio-dark';
69
- /** Makes the editor read-only. */
70
- disabled?: boolean;
71
- /** Shows file insertion actions. Existing files stay readable and removable. */
72
- enableFiles?: boolean;
73
- /** Shows image insertion actions. Existing images stay readable and removable. */
74
- enableImages?: boolean;
75
- /** Shows the image metadata action, which emits `request-image-metadata`. */
76
- enableImageMetadata?: boolean;
77
- /** Shows video insertion actions. Existing videos stay readable and removable. */
78
- enableVideo?: boolean;
79
- /** File output syntax. */
80
- fileOutput?: 'markdown' | 'mdc';
81
- /** Image output syntax. */
82
- imageOutput?: 'markdown' | 'mdc';
83
- /** Text in an empty document. Defaults to the `startWriting` message. */
84
- placeholder?: string;
85
- /** Stored in the heading extension storage for host renderers. */
86
- showMarkdownMarkers?: boolean;
87
- /** Delay, in milliseconds, before a visual edit is converted and emitted. */
88
- syncDebounceMs?: number;
89
- /** Video output syntax. */
90
- videoOutput?: 'html' | 'mdc';
91
- }
92
- export declare const editorPropDefaults: {
93
- readonly variant: "default";
94
- readonly header: undefined;
95
- readonly sourceToggle: undefined;
96
- readonly toolbarPlacement: undefined;
97
- readonly selectionToolbar: "auto";
98
- readonly selectionToolbarItems: undefined;
99
- readonly profile: "full";
100
- readonly codeBlockTheme: "github-dark";
101
- readonly toolbarItems: undefined;
102
- readonly messages: undefined;
103
- readonly shortcuts: undefined;
104
- readonly overlayContainer: undefined;
105
- readonly imagePicker: undefined;
106
- readonly imageMaxBytes: number;
107
- readonly ariaLabel: undefined;
108
- readonly assetProvider: undefined;
109
- readonly imageUpload: undefined;
110
- readonly imageDropTarget: undefined;
111
- readonly authoringKit: undefined;
112
- readonly collaboration: undefined;
113
- readonly disabled: false;
114
- readonly enableFiles: true;
115
- readonly enableImages: true;
116
- readonly enableImageMetadata: false;
117
- readonly enableVideo: true;
118
- readonly fileOutput: "mdc";
119
- readonly imageOutput: "mdc";
120
- readonly placeholder: undefined;
121
- readonly showMarkdownMarkers: false;
122
- readonly syncDebounceMs: 120;
123
- readonly videoOutput: "mdc";
124
- };