@phtngyn/cms 0.2.0-beta.4 → 0.2.0-beta.6

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 (116) hide show
  1. package/README.md +31 -13
  2. package/package.json +7 -7
  3. package/src/ApplicationTypes.d.ts +3 -3
  4. package/src/Authoring.d.ts +11 -3
  5. package/src/{Configuration-BU-UyGoH.js → Configuration-JQ1qyaU0.js} +347 -189
  6. package/src/Configuration-JQ1qyaU0.js.map +1 -0
  7. package/src/Configuration.d.ts +1 -1
  8. package/src/Content.d.ts +7 -6
  9. package/src/Content.js +106 -47
  10. package/src/Content.js.map +1 -1
  11. package/src/ContentTransfer-BxwswWn3.js +86 -0
  12. package/src/ContentTransfer-BxwswWn3.js.map +1 -0
  13. package/src/{ContentTransfer-CRQet3QJ.d.ts → ContentTransfer-Z9FHyLez.d.ts} +33 -9
  14. package/src/{DocumentEngine-ClhFXW9M.js → DocumentEngine-j6Vi7nQo.js} +279 -178
  15. package/src/DocumentEngine-j6Vi7nQo.js.map +1 -0
  16. package/src/DocumentModel.d.ts +9 -2
  17. package/src/DocumentModel.js +17 -4
  18. package/src/DocumentModel.js.map +1 -1
  19. package/src/{Forms-DoB56hfe.js → Forms-CX-hwmJF.js} +18 -11
  20. package/src/Forms-CX-hwmJF.js.map +1 -0
  21. package/src/{Forms-BbkE7QfC.js → Forms-CfNPTiCr.js} +2 -2
  22. package/src/{Forms-BbkE7QfC.js.map → Forms-CfNPTiCr.js.map} +1 -1
  23. package/src/Media-j1bTritO.js +112 -0
  24. package/src/Media-j1bTritO.js.map +1 -0
  25. package/src/Module.js +0 -4
  26. package/src/Module.js.map +1 -1
  27. package/src/References-CCPDAPve.js +45 -0
  28. package/src/References-CCPDAPve.js.map +1 -0
  29. package/src/{S3MediaObjects-CR3p1WTg.js → S3MediaObjects-BRuPQbxl.js} +454 -516
  30. package/src/S3MediaObjects-BRuPQbxl.js.map +1 -0
  31. package/src/cli/content.js +6 -5
  32. package/src/cli/content.js.map +1 -1
  33. package/src/cli.js +16 -3
  34. package/src/cli.js.map +1 -1
  35. package/src/{connection-D5S9Iph-.js → connection-BP80q4d-.js} +2 -2
  36. package/src/{connection-D5S9Iph-.js.map → connection-BP80q4d-.js.map} +1 -1
  37. package/src/{dev-lifecycle-D3f9-upa.js → dev-lifecycle-CExksm2R.js} +27 -7
  38. package/src/dev-lifecycle-CExksm2R.js.map +1 -0
  39. package/src/{installation-fZtNxtoW.js → installation-BoG8E3nJ.js} +7982 -7155
  40. package/src/installation-BoG8E3nJ.js.map +1 -0
  41. package/src/internal/authoring-catalog.js +2 -2
  42. package/src/internal/authoring-compiler.js +35 -9
  43. package/src/internal/authoring-compiler.js.map +1 -1
  44. package/src/internal/authoring-metadata.js +14 -5
  45. package/src/internal/authoring-metadata.js.map +1 -1
  46. package/src/internal/configuration.js +27 -3
  47. package/src/internal/configuration.js.map +1 -1
  48. package/src/internal/dev-lifecycle.js +2 -2
  49. package/src/internal/document-model.js +134 -43
  50. package/src/internal/document-model.js.map +1 -1
  51. package/src/internal/field-metadata.js +2 -1
  52. package/src/internal/field-metadata.js.map +1 -1
  53. package/src/internal/form-capabilities.js +1 -1
  54. package/src/{location-CPX7oj0o.js → location-CMNGO3lU.js} +2 -2
  55. package/src/{location-CPX7oj0o.js.map → location-CMNGO3lU.js.map} +1 -1
  56. package/src/{metadata-BEZPWh-3.js → metadata-UzZmjwxM.js} +2 -2
  57. package/src/{metadata-BEZPWh-3.js.map → metadata-UzZmjwxM.js.map} +1 -1
  58. package/src/{models-C9kF9JlQ.js → models-5j67LMqW.js} +4 -4
  59. package/src/{models-C9kF9JlQ.js.map → models-5j67LMqW.js.map} +1 -1
  60. package/src/{models-ChRxBChy.js → models-VmGmG19-.js} +42 -130
  61. package/src/models-VmGmG19-.js.map +1 -0
  62. package/src/runtime/delivery/DocumentRenderer.js +5 -1
  63. package/src/runtime/delivery/DocumentRenderer.js.map +1 -1
  64. package/src/runtime/delivery/context.js +1 -1
  65. package/src/runtime/delivery/plugin.js +2 -2
  66. package/src/runtime/delivery/preview.d.ts +1 -1
  67. package/src/runtime/delivery/types.d.ts +1 -1
  68. package/src/runtime/delivery/useCmsDocumentSeo.d.ts +1 -1
  69. package/src/runtime/forms/document.js +2 -2
  70. package/src/runtime/forms/useCmsForm.js +2 -2
  71. package/src/runtime/installation.js +1 -1
  72. package/src/runtime/plugin.js +1 -1
  73. package/src/runtime/preview/CmsStudioPreviewMarker.js +18 -4
  74. package/src/runtime/preview/CmsStudioPreviewMarker.js.map +1 -1
  75. package/src/runtime/preview/connection.js +1 -1
  76. package/src/runtime/preview/controller.js +65 -74
  77. package/src/runtime/preview/controller.js.map +1 -1
  78. package/src/runtime/preview/overlay.js +85 -28
  79. package/src/runtime/preview/overlay.js.map +1 -1
  80. package/src/runtime/preview/plugin.client.js +4 -4
  81. package/src/runtime/preview/preview.css +50 -36
  82. package/src/runtime/preview/protocol.d.ts +11 -5
  83. package/src/runtime/preview/protocol.js +17 -5
  84. package/src/runtime/preview/protocol.js.map +1 -1
  85. package/src/runtime/preview/regions.js +142 -0
  86. package/src/runtime/preview/regions.js.map +1 -0
  87. package/src/runtime/preview/store.js +1 -1
  88. package/src/runtime/sitemap.js +9 -10
  89. package/src/runtime/sitemap.js.map +1 -1
  90. package/src/{scalars-B2lgGUnj.js → scalars-CVZqT3L0.js} +2 -6
  91. package/src/scalars-CVZqT3L0.js.map +1 -0
  92. package/src/{store-CCsjHaZm.js → store-PKKB8xa2.js} +49 -66
  93. package/src/store-PKKB8xa2.js.map +1 -0
  94. package/src/{types-DutFRtaG.d.ts → types-DZ0IV-Ow.d.ts} +14 -3
  95. package/studio/CreateDocumentDialog-DqvusuGU.js +335 -0
  96. package/studio/{documentPlanning-CDb31mnl.js → SelectMenu-BgikeouH.js} +16292 -12303
  97. package/studio/{editor-Bzlh3zXt.js → editor-P2rB7Csp.js} +11228 -11927
  98. package/studio/host.css +1 -1
  99. package/studio/host.js +28987 -34295
  100. package/studio/rolldown-runtime-Dy4uBu1J.js +11 -0
  101. package/src/Configuration-BU-UyGoH.js.map +0 -1
  102. package/src/ContentTransfer-BhF9G56s.js +0 -57
  103. package/src/ContentTransfer-BhF9G56s.js.map +0 -1
  104. package/src/DocumentEngine-ClhFXW9M.js.map +0 -1
  105. package/src/Forms-DoB56hfe.js.map +0 -1
  106. package/src/S3MediaObjects-CR3p1WTg.js.map +0 -1
  107. package/src/dev-lifecycle-D3f9-upa.js.map +0 -1
  108. package/src/installation-fZtNxtoW.js.map +0 -1
  109. package/src/models-ChRxBChy.js.map +0 -1
  110. package/src/runtime/preview/targets.js +0 -101
  111. package/src/runtime/preview/targets.js.map +0 -1
  112. package/src/scalars-B2lgGUnj.js.map +0 -1
  113. package/src/store-CCsjHaZm.js.map +0 -1
  114. package/studio/CreateDocumentDialog-DJ8c0WZb.js +0 -256
  115. package/studio/dom-to-image-more.min-D6jGGdrW.js +0 -877
  116. package/studio/rolldown-runtime-B0aSnxlc.js +0 -20
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Configuration-JQ1qyaU0.js","names":["isJsonObject","jsonObject","comarkToEditor","isJsonObject","isElementNode","isJsonObject"],"sources":["../../../../document/src/internal/editor/attributes.ts","../../../../document/src/internal/editor/image.ts","../../../../document/src/internal/editor/marks.ts","../../../../document/src/internal/comark/to-editor.ts","../../../../document/src/internal/comark/source-mapping.ts","../../../../document/src/internal/comark/grammar.ts","../../../../document/src/internal/editor/errors.ts","../../../../document/src/StructuredFields.ts","../../../../document/src/AuthoringSchema.ts","../../../../protocol/src/StructuredFields.ts","../../../../protocol/src/Authoring.ts","../../../../protocol/src/Configuration.ts"],"sourcesContent":["import { Predicate, Schema } from 'effect'\n\nexport function compactJsonAttributes(\n attributes: Readonly<Record<string, Schema.Json | undefined>>,\n): Schema.JsonObject {\n return Object.fromEntries(\n Object.entries(attributes).filter((entry): entry is [string, Schema.Json] => entry[1] !== undefined),\n )\n}\n\nexport function nonEmptyStringAttribute(value: Schema.Json | undefined): string | undefined {\n return Predicate.isString(value) && value ? value : undefined\n}\n\nexport function finiteNumberAttribute(value: Schema.Json | undefined, fallback: number): number {\n const number = Predicate.isNumber(value) ? value : Number(value)\n\n return Number.isFinite(number) ? number : fallback\n}\n","import { Predicate, Schema } from 'effect'\nimport { compactJsonAttributes } from './attributes'\n\nconst isJsonObject = Schema.is(Schema.JsonObject)\n\nconst EDITOR_IMAGE_LAYOUTS = ['natural', 'content', 'full'] as const\n\nexport type EditorImageLayout = (typeof EDITOR_IMAGE_LAYOUTS)[number]\n\nconst EditorImageLayout = Schema.Literals(EDITOR_IMAGE_LAYOUTS)\n\nconst isEditorImageLayout = Schema.is(EditorImageLayout)\n\nexport const EDITOR_IMAGE_LAYOUT_ATTRIBUTE = 'data-cms-layout'\n\nconst IMAGE_DECORATIVE_ATTRIBUTE = 'data-cms-decorative'\n\nconst IMAGE_SEMANTIC_ATTRIBUTES = new Set([\n 'alt',\n IMAGE_DECORATIVE_ATTRIBUTE,\n EDITOR_IMAGE_LAYOUT_ATTRIBUTE,\n 'src',\n 'title',\n])\n\nexport function decodeEditorImageAttributes(attributes: Schema.JsonObject): Schema.JsonObject {\n const cmsProps = Object.fromEntries(\n Object.entries(attributes).filter(([name]) => !IMAGE_SEMANTIC_ATTRIBUTES.has(name)),\n )\n\n return compactJsonAttributes({\n alt:\n attributes[IMAGE_DECORATIVE_ATTRIBUTE] !== undefined\n ? ''\n : Predicate.isString(attributes.alt)\n ? attributes.alt\n : null,\n cmsProps: Object.keys(cmsProps).length ? cmsProps : null,\n layout: normalizeEditorImageLayout(attributes[EDITOR_IMAGE_LAYOUT_ATTRIBUTE]),\n src: stringValue(attributes.src) || null,\n title: stringValue(attributes.title) || null,\n })\n}\n\nexport function encodeEditorImageAttributes(value: Schema.JsonObject | undefined): Schema.JsonObject {\n const attributes = jsonObject(value)\n const alt = attributes.alt\n const layout = normalizeEditorImageLayout(attributes.layout)\n\n return compactJsonAttributes(\n Object.assign({}, jsonObject(attributes.cmsProps), {\n alt: Predicate.isString(alt) ? alt : undefined,\n [IMAGE_DECORATIVE_ATTRIBUTE]: alt === '' ? 'true' : undefined,\n [EDITOR_IMAGE_LAYOUT_ATTRIBUTE]: layout === 'natural' ? undefined : layout,\n src: stringValue(attributes.src) || undefined,\n title: stringValue(attributes.title) || undefined,\n }),\n )\n}\n\nexport function normalizeEditorImageLayout(value: Schema.Json | undefined): EditorImageLayout {\n return isEditorImageLayout(value) ? value : 'natural'\n}\n\nfunction jsonObject(value: Schema.Json | undefined): Schema.JsonObject {\n return isJsonObject(value) ? value : {}\n}\n\nfunction stringValue(value: Schema.Json | undefined): string {\n return Predicate.isString(value) || Predicate.isNumber(value) ? String(value) : ''\n}\n","const EDITOR_MARKS = [\n ['bold', 'strong'],\n ['code', 'code'],\n ['italic', 'em'],\n ['link', 'a'],\n ['strike', 'del'],\n ['underline', 'u'],\n] as const\n\nexport const EDITOR_MARK_TYPES = EDITOR_MARKS.map(([type]) => type)\n\nconst editorToComark = new Map<string, string>(EDITOR_MARKS)\n\nconst comarkToEditor = new Map<string, string>(EDITOR_MARKS.map(([type, tag]) => [tag, type]))\n\nexport function comarkTagForEditorMark(type: string): string | undefined {\n return editorToComark.get(type)\n}\n\nexport function editorMarkForComarkTag(tag: string): string | undefined {\n return comarkToEditor.get(tag)\n}\n\nexport function isEditorMark(type: string): boolean {\n return editorToComark.has(type)\n}\n\nexport function isComarkMark(tag: string): boolean {\n return comarkToEditor.has(tag)\n}\n","import type { MarkdownNode } from '@internal/protocol/Documents'\nimport type { EditorNodeId } from '@internal/protocol/Documents'\nimport type { JSONContent } from '@tiptap/core'\nimport type { NodeRenderData } from 'comark'\nimport { Predicate, Schema } from 'effect'\nimport { projectCmsEditorComponentAttributes, resolveCmsComarkAttributes, withCmsComarkProps } from './bindings'\nimport { editorNodeId, createEditorNodeId } from '../editor/identity'\nimport { decodeEditorImageAttributes } from '../editor/image'\nimport { editorMetadata } from '../editor/metadata'\nimport { compactJsonAttributes, finiteNumberAttribute, nonEmptyStringAttribute } from '../editor/attributes'\nimport { editorMarkForComarkTag, isComarkMark } from '../editor/marks'\n\nconst isJsonObject = Schema.is(Schema.JsonObject)\n\ntype ElementMarkdownNode = Extract<MarkdownNode, readonly [string, Schema.JsonObject, ...MarkdownNode[]]>\n\ninterface DecodeContext {\n readonly usedIds: Set<EditorNodeId>\n}\n\nconst OPAQUE_BLOCK_TAGS = new Set(['math', 'table', 'tbody', 'td', 'th', 'thead', 'tr'])\n\nexport function comarkToEditor(\n nodes: ReadonlyArray<MarkdownNode>,\n renderData: NodeRenderData = { data: {}, frontmatter: {}, meta: {}, props: {} },\n): JSONContent[] {\n return decodeBlocks(\n nodes,\n {\n usedIds: new Set(),\n },\n renderData,\n )\n}\n\nfunction decodeBlocks(\n nodes: ReadonlyArray<MarkdownNode>,\n context: DecodeContext,\n renderData: NodeRenderData,\n wrapInlineContent = false,\n): JSONContent[] {\n const content: JSONContent[] = []\n let inlineNodes: MarkdownNode[] = []\n\n const flushInlineNodes = () => {\n const inline = decodeInlines(inlineNodes, context, renderData)\n\n if (inline.length) {\n content.push({\n type: 'paragraph',\n attrs: wrapInlineContent ? { cmsSynthetic: true } : { cmsNodeId: claimIdentity(context) },\n content: inline,\n })\n }\n\n inlineNodes = []\n }\n\n for (const node of nodes) {\n if (Predicate.isString(node) || isInlineElement(node)) {\n inlineNodes.push(node)\n continue\n }\n\n flushInlineNodes()\n content.push(decodeBlock(node, context, renderData))\n }\n\n flushInlineNodes()\n\n return content\n}\n\nfunction decodeBlock(\n node: Exclude<MarkdownNode, string>,\n context: DecodeContext,\n renderData: NodeRenderData,\n): JSONContent {\n if (node[0] === null) {\n return opaqueBlock(node, 'Comment', claimIdentity(context, node[1]))\n }\n\n const [tag, rawAttributes, ...children] = node\n const attrs = cleanAttrs(rawAttributes)\n const childRenderData = withCmsComarkProps(renderData, resolveCmsComarkAttributes(rawAttributes, renderData))\n const metadata = editorMetadata(rawAttributes)\n const cmsNodeId = claimIdentity(context, rawAttributes)\n\n const commonAttrs = compactJsonAttributes({\n cmsNodeId,\n cmsProps: attrs,\n })\n\n if (/^h[1-6]$/u.test(tag)) {\n return {\n type: 'heading',\n attrs: mergeJsonAttributes(commonAttrs, { level: Number(tag.slice(1)) }),\n content: decodeInlines(children, context, childRenderData),\n }\n }\n\n switch (tag) {\n case 'p':\n return { type: 'paragraph', attrs: commonAttrs, content: decodeInlines(children, context, childRenderData) }\n case 'blockquote':\n return {\n type: 'blockquote',\n attrs: commonAttrs,\n content: decodeBlocks(children, context, childRenderData),\n }\n case 'ul':\n return {\n type: 'bulletList',\n attrs: commonAttrs,\n content: decodeListItems(children, context, childRenderData),\n }\n case 'ol':\n return {\n type: 'orderedList',\n attrs: mergeJsonAttributes(commonAttrs, { start: finiteNumberAttribute(attrs.start, 1) }),\n content: decodeListItems(children, context, childRenderData),\n }\n case 'li':\n return {\n type: 'listItem',\n attrs: commonAttrs,\n content: decodeBlocks(children, context, childRenderData),\n }\n case 'pre': {\n const code = children.find(isElementNode)\n\n const language =\n nonEmptyStringAttribute(attrs.language) ?? nonEmptyStringAttribute(code?.[1].class)?.replace(/^language-/u, '')\n\n return {\n type: 'codeBlock',\n attrs: mergeJsonAttributes(commonAttrs, { language }),\n content: textContent(code ? elementChildren(code) : children),\n }\n }\n\n case 'hr':\n return { type: 'horizontalRule', attrs: commonAttrs }\n default:\n if (OPAQUE_BLOCK_TAGS.has(tag)) return opaqueBlock(node, tag, cmsNodeId)\n const projection = projectCmsEditorComponentAttributes(rawAttributes, renderData)\n\n return {\n type: 'cmsBlock',\n attrs: compactJsonAttributes({\n bindings: projection.bindings,\n cmsNodeId,\n props: projection.props,\n tag,\n }),\n content: decodeComponentSlots(children, context, projection.renderData, metadata?.implicitSlotId),\n }\n }\n}\n\nfunction decodeComponentSlots(\n children: ReadonlyArray<MarkdownNode>,\n context: DecodeContext,\n renderData: NodeRenderData,\n implicitSlotId?: EditorNodeId,\n): JSONContent[] {\n const templates = children.filter(isSlotTemplate)\n const regular = children.filter((node) => !isSlotTemplate(node))\n const slots = templates.map((node) => decodeSlot(node, context, renderData))\n\n if (!regular.length) return slots\n\n const defaultContent = slotContent(decodeBlocks(regular, context, renderData, true))\n const explicitDefault = slots.find((slot) => slot.attrs?.name === 'default')\n\n if (explicitDefault) {\n explicitDefault.content = [...(explicitDefault.content ?? []), ...defaultContent]\n\n return slots\n }\n\n return [\n {\n type: 'cmsSlot',\n attrs: {\n cmsNodeId: claimIdentityValue(context, implicitSlotId),\n implicit: true,\n name: 'default',\n props: {},\n },\n content: defaultContent,\n },\n ...slots,\n ]\n}\n\nfunction decodeSlot(node: ElementMarkdownNode, context: DecodeContext, renderData: NodeRenderData): JSONContent {\n const attrs = cleanAttrs(node[1])\n const childRenderData = withCmsComarkProps(renderData, resolveCmsComarkAttributes(node[1], renderData))\n const name = slotName(attrs)\n const { name: _name, ...slotProps } = attrs\n\n return {\n type: 'cmsSlot',\n attrs: {\n cmsNodeId: claimIdentity(context, node[1]),\n implicit: false,\n name,\n props: slotProps,\n },\n content: slotContent(decodeBlocks(elementChildren(node), context, childRenderData, true)),\n }\n}\n\nfunction decodeListItems(\n nodes: ReadonlyArray<MarkdownNode>,\n context: DecodeContext,\n renderData: NodeRenderData,\n): JSONContent[] {\n return nodes.flatMap((node) =>\n isElementNode(node) && node[0] === 'li' ? [decodeBlock(node, context, renderData)] : [],\n )\n}\n\nfunction decodeInlines(\n nodes: ReadonlyArray<MarkdownNode>,\n context: DecodeContext,\n renderData: NodeRenderData,\n inheritedMarks: NonNullable<JSONContent['marks']> = [],\n): JSONContent[] {\n const result: JSONContent[] = []\n\n for (const node of nodes) {\n if (Predicate.isString(node)) {\n if (node) {\n result.push(withMarks({ type: 'text', text: node }, inheritedMarks))\n }\n\n continue\n }\n\n if (node[0] === null) {\n result.push(\n withMarks(\n {\n type: 'cmsInlineOpaque',\n attrs: { label: 'Comment', node: stripInternalMetadata(node) },\n },\n inheritedMarks,\n ),\n )\n continue\n }\n\n const markType = editorMarkForComarkTag(node[0])\n\n if (markType) {\n const attrs = cleanAttrs(node[1])\n const childRenderData = withCmsComarkProps(renderData, resolveCmsComarkAttributes(node[1], renderData))\n\n const markAttrs =\n markType === 'link'\n ? mergeJsonAttributes(attrs, { cmsProps: attrs })\n : Object.keys(attrs).length\n ? { cmsProps: attrs }\n : undefined\n\n const mark = markAttrs === undefined ? { type: markType } : { attrs: markAttrs, type: markType }\n result.push(...decodeInlines(elementChildren(node), context, childRenderData, [...inheritedMarks, mark]))\n continue\n }\n\n if (node[0] === 'br') {\n result.push(withMarks({ type: 'hardBreak' }, inheritedMarks))\n continue\n }\n\n if (node[0] === 'img') {\n result.push(\n withMarks(\n {\n type: 'image',\n attrs: mergeJsonAttributes(decodeEditorImageAttributes(cleanAttrs(node[1])), {\n cmsNodeId: claimIdentity(context, node[1]),\n }),\n },\n inheritedMarks,\n ),\n )\n continue\n }\n\n result.push(\n withMarks(\n {\n type: 'cmsInlineOpaque',\n attrs: {\n label: node[0],\n node: stripInternalMetadata(node),\n },\n },\n inheritedMarks,\n ),\n )\n }\n\n return result\n}\n\nfunction claimIdentity(context: DecodeContext, attributes?: Schema.JsonObject): EditorNodeId {\n return claimIdentityValue(context, attributes ? editorMetadata(attributes)?.nodeId : undefined)\n}\n\nfunction claimIdentityValue(context: DecodeContext, candidate?: Schema.Json): EditorNodeId {\n const existing = editorNodeId(candidate)\n\n if (existing !== undefined && !context.usedIds.has(existing)) {\n context.usedIds.add(existing)\n\n return existing\n }\n\n for (let attempt = 0; attempt < 100; attempt++) {\n const created = createEditorNodeId()\n\n if (!context.usedIds.has(created)) {\n context.usedIds.add(created)\n\n return created\n }\n }\n\n throw new Error('The editor identity factory did not produce a unique identity.')\n}\n\nfunction opaqueBlock(node: Exclude<MarkdownNode, string>, label: string, cmsNodeId: EditorNodeId): JSONContent {\n return {\n type: 'cmsOpaque',\n attrs: {\n cmsNodeId,\n label,\n node: stripInternalMetadata(node),\n },\n }\n}\n\nfunction stripInternalMetadata(node: Exclude<MarkdownNode, string>): Exclude<MarkdownNode, string> {\n if (node[0] === null) return [null, cleanAttrs(node[1]), node[2]]\n const [tag, attributes, ...children] = node\n const clean = cleanAttrs(attributes)\n\n return [tag, clean, ...children.map((child) => (Predicate.isString(child) ? child : stripInternalMetadata(child)))]\n}\n\nfunction slotContent(content: JSONContent[]): JSONContent[] {\n return content.length ? content : [{ type: 'paragraph', attrs: { cmsSynthetic: true } }]\n}\n\nfunction slotName(attrs: Schema.JsonObject): string {\n return nonEmptyStringAttribute(attrs.name) ?? 'default'\n}\n\nfunction cleanAttrs(attrs: Schema.JsonObject): Schema.JsonObject {\n const { $: _internal, 'data-cms-node': _marker, ...clean } = attrs\n\n return structuredClone(clean)\n}\n\nfunction textContent(nodes: ReadonlyArray<MarkdownNode>): JSONContent[] | undefined {\n const text = nodes\n .map((node) =>\n Predicate.isString(node)\n ? node\n : node[0] === null\n ? node[2]\n : (textContent(elementChildren(node))\n ?.map((child) => child.text ?? '')\n .join('') ?? ''),\n )\n .join('')\n\n return text ? [{ type: 'text', text }] : undefined\n}\n\nfunction isInlineElement(node: Exclude<MarkdownNode, string>): boolean {\n return (\n node[0] !== null &&\n (isComarkMark(node[0]) || node[0] === 'br' || node[0] === 'img' || jsonObject(node[1].$).block === 0)\n )\n}\n\nfunction isSlotTemplate(node: MarkdownNode): node is ElementMarkdownNode {\n return isElementNode(node) && node[0] === 'template'\n}\n\nfunction isElementNode(node: MarkdownNode | undefined): node is ElementMarkdownNode {\n return Array.isArray(node) && Predicate.isString(node[0])\n}\n\nfunction elementChildren(node: ElementMarkdownNode): MarkdownNode[] {\n const [, , ...children] = node\n\n return children\n}\n\nfunction jsonObject(value: Schema.Json | undefined): Schema.JsonObject {\n return isJsonObject(value) ? value : {}\n}\n\nfunction mergeJsonAttributes(\n attributes: Schema.JsonObject,\n additions: Readonly<Record<string, Schema.Json | undefined>>,\n): Schema.JsonObject {\n return compactJsonAttributes(Object.assign({}, attributes, additions))\n}\n\nfunction withMarks(content: JSONContent, marks: NonNullable<JSONContent['marks']>): JSONContent {\n return marks.length ? Object.assign({}, content, { marks }) : content\n}\n","import type { DocumentSourceMapping, DocumentSourcePoint, DocumentSourceRange } from '@internal/protocol/Documents'\nimport type { ComarkParsePostState, ComarkParsePreState, ComarkPlugin, ElementNode, Node } from 'comark'\nimport { Option, Predicate, Schema } from 'effect'\n\nexport const SOURCE_MAPPINGS_META_KEY = '__cmsSourceMappings'\n\ninterface SourceMapParseState {\n __cmsOriginalMarkdown?: string\n parsedLines?: number\n}\n\ninterface ComarkToken extends Schema.Schema.Type<typeof ComarkToken> {}\n\ninterface BlockDescriptor {\n readonly children: BlockDescriptor[]\n range: DocumentSourceRange\n readonly tag: string\n}\n\nconst BLOCK_TAGS = new Map([\n ['blockquote_open', 'blockquote'],\n ['bullet_list_open', 'ul'],\n ['list_item_open', 'li'],\n ['ordered_list_open', 'ol'],\n ['paragraph_open', 'p'],\n ['table_open', 'table'],\n ['tbody_open', 'tbody'],\n ['td_open', 'td'],\n ['th_open', 'th'],\n ['thead_open', 'thead'],\n ['tr_open', 'tr'],\n])\n\nconst ComarkToken = Schema.Struct({\n attrs: Schema.optionalKey(Schema.NullOr(Schema.Array(Schema.Tuple([Schema.String, Schema.String])))),\n hidden: Schema.optionalKey(Schema.Boolean),\n level: Schema.optionalKey(Schema.Finite),\n map: Schema.optionalKey(Schema.NullOr(Schema.Tuple([Schema.Finite, Schema.Finite]))),\n nesting: Schema.optionalKey(Schema.Finite),\n tag: Schema.optionalKey(Schema.String),\n type: Schema.optionalKey(Schema.String),\n})\n\nconst WRAPPER_TAGS = new Set(['blockquote', 'ol', 'pre', 'table', 'ul'])\n\nexport function sourceCapturePlugin(): ComarkPlugin {\n return {\n name: 'cms-source-capture',\n pre(state: ComarkParsePreState & SourceMapParseState) {\n state.__cmsOriginalMarkdown = state.markdown\n },\n }\n}\n\nexport function sourceMappingPlugin(): ComarkPlugin {\n return {\n name: 'cms-source-mapping',\n post(state: ComarkParsePostState & SourceMapParseState) {\n const source = state.__cmsOriginalMarkdown ?? state.markdown\n\n const descriptors = createBlockDescriptors(\n state.tokens.flatMap((token) => {\n const decoded = Schema.decodeUnknownOption(ComarkToken)(token)\n\n return Option.isSome(decoded) ? [decoded.value] : []\n }),\n source,\n state.markdown,\n state.parsedLines ?? 0,\n )\n\n const mappings: DocumentSourceMapping[] = []\n mapNodes(state.tree.nodes, descriptors, [], mappings)\n state.tree.meta[SOURCE_MAPPINGS_META_KEY] = mappings\n },\n }\n}\n\nfunction createBlockDescriptors(\n tokens: ReadonlyArray<ComarkToken>,\n source: string,\n parsedMarkdown: string,\n parsedLines: number,\n): BlockDescriptor[] {\n const roots: BlockDescriptor[] = []\n const stack: Array<{ descriptor: BlockDescriptor; level: number }> = []\n const sourceLineStarts = indexLineStarts(source)\n const parsedLineStarts = indexLineStarts(parsedMarkdown)\n const parsedOffset = source.lastIndexOf(parsedMarkdown)\n const slotMaps = createSlotTokenMaps(tokens, parsedMarkdown)\n\n for (let tokenIndex = 0; tokenIndex < tokens.length; tokenIndex++) {\n const token = tokens[tokenIndex]\n\n if (!token) continue\n const tag = blockTag(token)\n const tokenMap = token.map ?? slotMaps.get(tokenIndex)\n\n if (!tag || !tokenMap) continue\n\n const level = token.level ?? 0\n\n while (true) {\n const current = stack.at(-1)\n\n if (!current || current.level < level) break\n stack.pop()\n }\n\n const descriptor: BlockDescriptor = {\n children: [],\n range: rangeFromParsedLines(\n source,\n sourceLineStarts,\n parsedMarkdown,\n parsedLineStarts,\n parsedOffset,\n tokenMap[0],\n tokenMap[1] + (token.type === 'mdc_block_open' ? 1 : 0),\n parsedLines,\n ),\n tag,\n }\n\n const parent = stack.at(-1)?.descriptor\n\n ;(parent?.children ?? roots).push(descriptor)\n\n if (token.nesting === 1) stack.push({ descriptor, level })\n }\n\n return roots.map(collapseComarkWrapper).map(groupProjectedSlotContent)\n}\n\nfunction blockTag(token: ComarkToken): string | undefined {\n if (token.hidden || !token.type) return undefined\n\n if (token.type === 'heading_open') return token.tag\n\n if (token.type === 'mdc_block_open' || (token.type === 'mdc_block_shorthand' && token.nesting !== -1))\n return token.tag || 'component'\n\n if (token.type === 'mdc_block_slot' && token.nesting === 1) return 'template'\n\n if (['fence', 'fenced_code_block', 'code_block'].includes(token.type)) return 'pre'\n\n if (token.type === 'math_block') return 'math'\n\n if (token.type === 'html_block') return '*'\n\n if (token.type === 'hr') return 'hr'\n\n return BLOCK_TAGS.get(token.type)\n}\n\nfunction createSlotTokenMaps(\n tokens: ReadonlyArray<ComarkToken>,\n parsedMarkdown: string,\n): Map<number, [number, number]> {\n const maps = new Map<number, [number, number]>()\n const markers = slotMarkers(parsedMarkdown)\n const stack: Array<{ index: number; marker: number }> = []\n let nextMarker = 0\n\n for (let index = 0; index < tokens.length; index++) {\n const token = tokens[index]\n\n if (!token || token.type !== 'mdc_block_slot') continue\n\n if (token.nesting === 1) {\n const name = token.attrs?.[0]?.[0]?.replace(/^#/u, '')\n let markerIndex = nextMarker\n\n while (markerIndex < markers.length && markers[markerIndex]?.name !== name) markerIndex++\n const marker = markers[markerIndex]\n\n if (marker) {\n stack.push({ index, marker: marker.line })\n nextMarker = markerIndex + 1\n }\n\n continue\n }\n\n if (token.nesting !== -1) continue\n const open = stack.pop()\n\n if (!open) continue\n let endLine = open.marker + 1\n\n for (let childIndex = open.index + 1; childIndex < index; childIndex++) {\n const child = tokens[childIndex]\n const map = child?.map ?? maps.get(childIndex)\n\n if (child && map) {\n endLine = Math.max(endLine, map[1] + (child.type === 'mdc_block_open' ? 1 : 0))\n }\n }\n\n maps.set(open.index, [open.marker, endLine])\n }\n\n return maps\n}\n\nfunction slotMarkers(source: string): Array<{ line: number; name: string }> {\n return source.split(/\\r?\\n/u).flatMap((line, index) => {\n const name = line.match(/^\\s*#([^\\s{]+)/u)?.[1]\n\n return name ? [{ line: index, name }] : []\n })\n}\n\nfunction collapseComarkWrapper(descriptor: BlockDescriptor): BlockDescriptor {\n const children = descriptor.children.map(collapseComarkWrapper)\n\n if (WRAPPER_TAGS.has(descriptor.tag) && children.length === 1 && children[0]?.tag === descriptor.tag) {\n return { ...descriptor, children: children[0].children }\n }\n\n return { ...descriptor, children }\n}\n\n/** Comark projects siblings after a named slot into that active slot. */\nfunction groupProjectedSlotContent(descriptor: BlockDescriptor): BlockDescriptor {\n const grouped: BlockDescriptor[] = []\n let activeSlot: BlockDescriptor | undefined\n\n for (const rawChild of descriptor.children) {\n const child = groupProjectedSlotContent(rawChild)\n\n if (child.tag === 'template') {\n activeSlot = child\n grouped.push(child)\n continue\n }\n\n if (!activeSlot) {\n grouped.push(child)\n continue\n }\n\n activeSlot.children.push(child)\n\n if (child.range.end.offset > activeSlot.range.end.offset) {\n activeSlot.range = { start: activeSlot.range.start, end: child.range.end }\n }\n }\n\n return { ...descriptor, children: grouped }\n}\n\nfunction mapNodes(\n nodes: ReadonlyArray<Node>,\n descriptors: ReadonlyArray<BlockDescriptor>,\n parentPath: ReadonlyArray<number>,\n mappings: DocumentSourceMapping[],\n): void {\n let descriptorIndex = 0\n\n for (let nodeIndex = 0; nodeIndex < nodes.length; nodeIndex++) {\n const node = nodes[nodeIndex]\n\n if (!node || !isElementNode(node)) continue\n\n let matchIndex = descriptorIndex\n\n while (\n matchIndex < descriptors.length &&\n descriptors[matchIndex]?.tag !== '*' &&\n descriptors[matchIndex]?.tag !== node[0]\n ) {\n matchIndex++\n }\n\n const descriptor = descriptors[matchIndex]\n\n if (!descriptor) continue\n\n descriptorIndex = matchIndex + 1\n const nodePath = [...parentPath, nodeIndex]\n mappings.push({ nodePath, range: descriptor.range })\n const [, , ...children] = node\n mapNodes(children, descriptor.children, nodePath, mappings)\n }\n}\n\nfunction isElementNode(node: Node): node is ElementNode {\n return Array.isArray(node) && Predicate.isString(node[0])\n}\n\nfunction indexLineStarts(source: string): number[] {\n const starts = [0]\n\n for (let offset = 0; offset < source.length; offset++) {\n if (source.charCodeAt(offset) === 10) starts.push(offset + 1)\n }\n\n return starts\n}\n\nfunction rangeFromParsedLines(\n source: string,\n sourceLineStarts: ReadonlyArray<number>,\n parsedMarkdown: string,\n parsedLineStarts: ReadonlyArray<number>,\n parsedOffset: number,\n startLine: number,\n endLine: number,\n fallbackLineOffset: number,\n): DocumentSourceRange {\n const startOffset =\n parsedOffset >= 0\n ? parsedOffset + (parsedLineStarts[startLine] ?? parsedMarkdown.length)\n : (sourceLineStarts[startLine + fallbackLineOffset] ?? source.length)\n\n const endOffset =\n parsedOffset >= 0\n ? parsedOffset + (parsedLineStarts[endLine] ?? parsedMarkdown.length)\n : (sourceLineStarts[endLine + fallbackLineOffset] ?? source.length)\n\n return {\n start: pointAt(source, sourceLineStarts, startOffset),\n end: pointAt(source, sourceLineStarts, Math.max(startOffset, endOffset)),\n }\n}\n\nfunction pointAt(source: string, lineStarts: ReadonlyArray<number>, rawOffset: number): DocumentSourcePoint {\n const offset = Math.min(Math.max(rawOffset, 0), source.length)\n let low = 0\n let high = lineStarts.length - 1\n\n while (low < high) {\n const middle = Math.ceil((low + high) / 2)\n\n if ((lineStarts[middle] ?? source.length) <= offset) low = middle\n else high = middle - 1\n }\n\n return {\n offset,\n line: low + 1,\n column: offset - (lineStarts[low] ?? 0) + 1,\n }\n}\n","import type { ComarkParseFn } from 'comark'\nimport { createMarkdownParser } from 'comark/parse'\nimport alert from 'comark/plugins/alert'\nimport attributes from 'comark/plugins/attributes'\nimport components from 'comark/plugins/components'\nimport frontmatter from 'comark/plugins/frontmatter'\nimport headings from 'comark/plugins/headings'\nimport security from 'comark/plugins/security'\nimport taskList from 'comark/plugins/task-list'\nimport toc from 'comark/plugins/toc'\nimport { sourceCapturePlugin, sourceMappingPlugin } from './source-mapping'\n\n/**\n * Changes when parsing, normalization, or projection semantics change. Stored\n * with compiled documents so migrations can identify stale derived content.\n */\nexport const DOCUMENT_ENGINE_FINGERPRINT =\n 'comark@0.6.2/frontmatter+alert+task-list+components+attributes+security+headings+toc+source-mapping/v1'\n\nexport function createDocumentParser(): ComarkParseFn {\n return createMarkdownParser({\n autoClose: false,\n registerDefaultPlugins: false,\n plugins: [\n sourceCapturePlugin(),\n frontmatter(),\n alert(),\n taskList(),\n components(),\n attributes(),\n // Security mutates the tree before metadata and source paths are derived.\n security(),\n headings(),\n toc({ depth: 5, searchDepth: 6 }),\n sourceMappingPlugin(),\n ],\n })\n}\n","import { Schema } from 'effect'\n\nexport class EditorDocumentInvalid extends Schema.TaggedError<EditorDocumentInvalid>()('EditorDocument.Invalid', {\n message: Schema.NonEmptyString,\n cause: Schema.Defect(),\n}) {}\n\nexport class EditorRenderFailed extends Schema.TaggedError<EditorRenderFailed>()('EditorDocument.RenderFailed', {\n cause: Schema.Defect(),\n}) {}\n","import type { StructuredField } from '@internal/protocol/StructuredFields'\nimport { decodeAuthoredDocumentReference, decodeManagedMediaReference } from '@internal/protocol/References'\nimport { Predicate, Schema } from 'effect'\nimport { createEditorNodeId } from './internal/editor/identity'\n\nexport type StructuredFieldValidationPurpose = 'working' | 'publish'\n\nexport interface StructuredFieldValidationIssue {\n readonly message: string\n readonly path: ReadonlyArray<string | number>\n}\n\nexport interface StructuredFieldIdentityIssue extends StructuredFieldValidationIssue {}\n\nexport interface StructuredFields {\n readonly create: () => Schema.JsonObject\n readonly set: (current: Schema.JsonObject, name: string, value: Schema.Json | undefined) => Schema.JsonObject\n readonly validate: (value: Schema.JsonObject, purpose: StructuredFieldValidationPurpose) => ReadonlyArray<string>\n readonly validateDetailed: (\n value: Schema.JsonObject,\n purpose: StructuredFieldValidationPurpose,\n ) => ReadonlyArray<StructuredFieldValidationIssue>\n readonly validateIdentities: (value: Schema.JsonObject) => ReadonlyArray<StructuredFieldIdentityIssue>\n readonly createListItem: (name: string) => Schema.JsonObject\n readonly duplicateListItem: (name: string, item: Schema.JsonObject) => Schema.JsonObject\n readonly moveListItem: (\n items: ReadonlyArray<Schema.JsonObject>,\n id: Schema.Json | undefined,\n offset: -1 | 1,\n ) => ReadonlyArray<Schema.JsonObject>\n readonly removeListItem: (\n items: ReadonlyArray<Schema.JsonObject>,\n id: Schema.Json | undefined,\n ) => ReadonlyArray<Schema.JsonObject>\n}\n\nexport function compileStructuredFields(definitions: ReadonlyArray<StructuredField>): StructuredFields {\n const fields = new Map(definitions.map((field) => [field.name, field]))\n\n if (fields.size !== definitions.length) throw new Error('Structured field names must be unique.')\n\n for (const field of definitions) {\n if (field.defaultValue === undefined) continue\n const issue = fieldIssue(field, field.defaultValue, 'working')\n\n if (issue) throw new Error(`Invalid default for ${field.label}: ${issue.message}`)\n }\n\n const listField = (name: string): StructuredField => {\n const field = fields.get(name)\n\n if (!field || field.type !== 'array' || field.input !== 'list')\n throw new Error(`Structured field \"${name}\" is not a repeatable object.`)\n\n return field\n }\n\n const validateDetailed = (\n value: Schema.JsonObject,\n purpose: StructuredFieldValidationPurpose,\n ): ReadonlyArray<StructuredFieldValidationIssue> => {\n const issues: StructuredFieldValidationIssue[] = []\n\n for (const name of Object.keys(value))\n if (!fields.has(name)) issues.push({ message: `${name} is not editable.`, path: [name] })\n\n for (const field of definitions) {\n const current = value[field.name] ?? (value[field.name] === null ? null : field.defaultValue)\n const issue = fieldIssue(field, current, purpose, [field.name])\n\n if (issue) issues.push(issue)\n }\n\n return issues\n }\n\n return {\n create: () => createObject(definitions),\n set(current, name, value) {\n const field = fields.get(name)\n\n if (!field) throw new Error(`Structured field \"${name}\" is unavailable.`)\n const issue = fieldIssue(field, value, 'working')\n\n if (issue) throw new Error(issue.message)\n const next = Object.fromEntries(Object.entries(current))\n\n if (value === undefined) delete next[name]\n else next[name] = structuredClone(value)\n\n return next\n },\n validate: (value, purpose) => validateDetailed(value, purpose).map((issue) => issue.message),\n validateDetailed,\n validateIdentities: (value) => identityIssues(definitions, value),\n createListItem(name) {\n return createObject(listField(name).fields ?? [], true)\n },\n duplicateListItem(name, item) {\n const field = listField(name)\n const copied = cloneWithFreshIdentities(item, field.fields ?? [])\n\n return Object.assign(createObject(field.fields ?? [], true), copied, { id: createEditorNodeId() })\n },\n moveListItem(items, id, offset) {\n const index = items.findIndex((item) => item.id === id)\n const target = index + offset\n\n if (index < 0 || target < 0 || target >= items.length) return items\n const next = [...items]\n const item = next.splice(index, 1)[0]\n\n if (!item) return items\n next.splice(target, 0, item)\n\n return next\n },\n removeListItem: (items, id) => items.filter((item) => item.id !== id),\n }\n}\n\nfunction identityIssues(\n fields: ReadonlyArray<StructuredField>,\n value: Schema.JsonObject,\n parent: ReadonlyArray<string | number> = [],\n): ReadonlyArray<StructuredFieldIdentityIssue> {\n return fields.flatMap((field) => {\n const current = value[field.name]\n const path = [...parent, field.name]\n\n if (field.type === 'object' && isJsonObject(current)) return identityIssues(field.fields ?? [], current, path)\n\n if (field.type !== 'array' || !Array.isArray(current)) return []\n const seen = new Set<string>()\n\n return current.flatMap((item, index) => {\n if (!isJsonObject(item)) return []\n const id = item.id\n\n const issue =\n !Predicate.isString(id) || !id || seen.has(id)\n ? [{ message: `${field.label} items need unique identities.`, path: [...path, index, 'id'] }]\n : []\n\n if (Predicate.isString(id) && id) seen.add(id)\n\n return [...issue, ...identityIssues(field.fields ?? [], item, [...path, index])]\n })\n })\n}\n\nfunction createObject(fields: ReadonlyArray<StructuredField>, listItem = false): Schema.JsonObject {\n return {\n ...(listItem ? { id: createEditorNodeId() } : undefined),\n ...Object.fromEntries(\n fields.flatMap((field) =>\n field.required || field.defaultValue !== undefined\n ? [[field.name, structuredClone(field.defaultValue ?? defaultValue(field))]]\n : [],\n ),\n ),\n }\n}\n\nfunction defaultValue(field: StructuredField): Schema.Json {\n if (field.type === 'object') return createObject(field.fields ?? [])\n\n if (field.type === 'array') return []\n\n if (field.type === 'string[]') return []\n\n if (field.type === 'number') return 0\n\n if (field.type === 'boolean') return false\n\n return field.options[0]?.value ?? ''\n}\n\nfunction cloneWithFreshIdentities(value: Schema.JsonObject, fields: ReadonlyArray<StructuredField>): Schema.JsonObject {\n const byName = new Map(fields.map((field) => [field.name, field]))\n const copy: Record<string, Schema.Json> = {}\n\n for (const [name, child] of Object.entries(value)) {\n if (name === 'id') continue\n const field = byName.get(name)\n\n if (field?.type === 'object' && isJsonObject(child)) {\n copy[name] = cloneWithFreshIdentities(child, field.fields ?? [])\n } else if (field?.type === 'array' && Array.isArray(child)) {\n copy[name] = child.map((item) =>\n isJsonObject(item)\n ? Object.assign(cloneWithFreshIdentities(item, field.fields ?? []), { id: createEditorNodeId() })\n : structuredClone(item),\n )\n } else copy[name] = structuredClone(child)\n }\n\n return copy\n}\n\nfunction fieldIssue(\n field: StructuredField,\n value: Schema.Json | undefined,\n purpose: StructuredFieldValidationPurpose,\n path: ReadonlyArray<string | number> = [field.name],\n): StructuredFieldValidationIssue | undefined {\n const issue = (message: string, issuePath = path): StructuredFieldValidationIssue => ({ message, path: issuePath })\n\n if (value === undefined)\n return field.required && purpose === 'publish' ? issue(`${field.label} is required.`) : undefined\n\n if (value === null && field.nullable) return undefined\n\n const valid =\n field.type === 'string' || field.type === 'date'\n ? Predicate.isString(value)\n : field.type === 'number'\n ? Predicate.isNumber(value) && Number.isFinite(value)\n : field.type === 'boolean'\n ? Predicate.isBoolean(value)\n : field.type === 'string[]'\n ? Array.isArray(value) && value.every(Predicate.isString)\n : field.type === 'array'\n ? Array.isArray(value)\n : isJsonObject(value)\n\n if (!valid) return issue(`${field.label} must be ${field.type}.`)\n\n if (field.type === 'object' || field.type === 'array') {\n const entries = Array.isArray(value) ? value : [value]\n const ids = new Set<string>()\n\n for (const [index, entry] of entries.entries()) {\n const entryPath = field.type === 'array' ? [...path, index] : path\n\n if (!isJsonObject(entry)) return issue(`${field.label} must contain objects.`, entryPath)\n\n if (field.type === 'array') {\n const id = entry.id\n\n if (!Predicate.isString(id) || !id || ids.has(id))\n return issue(`${field.label} items need unique identities.`, [...entryPath, 'id'])\n ids.add(id)\n }\n\n for (const key of Object.keys(entry))\n if (!(field.type === 'array' && key === 'id') && !field.fields?.some((child) => child.name === key))\n return issue(`${field.label} contains an unavailable field.`, [...entryPath, key])\n\n for (const child of field.fields ?? []) {\n const childIssue = fieldIssue(child, entry[child.name], purpose, [...entryPath, child.name])\n\n if (childIssue) return { ...childIssue, message: `${field.label}: ${childIssue.message}` }\n }\n }\n }\n\n if (\n purpose === 'publish' &&\n field.required &&\n value === '' &&\n ['image', 'link', 'document', 'media'].includes(field.input)\n )\n return issue(`${field.label} is required.`)\n\n if (\n purpose === 'publish' &&\n Predicate.isString(value) &&\n value &&\n (field.input === 'image' || field.input === 'link') &&\n !(field.input === 'link' && decodeAuthoredDocumentReference(value)) &&\n !validAuthoringUrl(value, field.input)\n )\n return issue(`${field.label} needs a valid ${field.input === 'image' ? 'image URL' : 'link'}.`)\n\n if (\n purpose === 'publish' &&\n Predicate.isString(value) &&\n value &&\n field.input === 'document' &&\n !decodeAuthoredDocumentReference(value)\n )\n return issue(`${field.label} needs a valid document reference.`)\n\n if (\n purpose === 'publish' &&\n Predicate.isString(value) &&\n value &&\n field.input === 'media' &&\n !decodeManagedMediaReference(value)\n )\n return issue(`${field.label} needs a valid managed-media reference.`)\n\n if (field.options.length) {\n const selected = Array.isArray(value) ? value : [value]\n\n if (selected.some((entry) => !field.options.some((option) => option.value === entry)))\n return issue(`${field.label} must use only available choices.`)\n }\n\n return undefined\n}\n\nfunction isJsonObject(value: Schema.Json | undefined): value is Schema.JsonObject {\n return Schema.is(Schema.JsonObject)(value)\n}\n\n/** URL values remain ordinary strings; identity-backed references use dedicated field inputs. */\nexport function validAuthoringUrl(value: string, input: 'image' | 'link'): boolean {\n if (value.trim() !== value || value.includes('\\\\')) return false\n\n for (const character of value) if (character.charCodeAt(0) <= 32) return false\n\n if (value.startsWith('/') && !value.startsWith('//')) return true\n\n if (input === 'link' && value.startsWith('#')) return true\n\n try {\n const url = new URL(value)\n\n return ['https:', 'http:', ...(input === 'link' ? ['mailto:', 'tel:'] : [])].includes(url.protocol)\n } catch {\n return false\n }\n}\n","import { formStructureIssues } from './Forms'\nimport type { BlockAuthoring, BlockSlot } from '@internal/protocol/Authoring'\nimport type { Editor, JSONContent } from '@tiptap/core'\nimport type { CollectionBody, ComponentDefinition } from '@internal/protocol/Configuration'\nimport { Extension, isNodeSelection } from '@tiptap/core'\nimport { Plugin } from '@tiptap/pm/state'\nimport { ySyncPluginKey } from '@tiptap/y-tiptap'\nimport { CmsMarkdownDocument } from '@internal/protocol/Documents'\nimport { Effect, Schema } from 'effect'\nimport { comarkToEditor } from './internal/comark/to-editor'\nimport { createCmsComarkRenderData } from './internal/comark/document-adapter'\nimport { createDocumentParser } from './internal/comark/grammar'\nimport { EditorDocumentInvalid } from './internal/editor/errors'\nimport { createEditorNodeId } from './internal/editor/identity'\nimport { compileStructuredFields } from './StructuredFields'\n\nexport interface AuthoringValidationIssue {\n readonly component: string\n readonly field?: ReadonlyArray<string | number>\n readonly message: string\n}\n\nexport const parseAuthoringContent = Effect.fn('AuthoringSchema.parseContent')(function* (markdown: string) {\n const body = yield* Effect.tryPromise({\n try: () => createDocumentParser()(markdown),\n catch: (cause) => new EditorDocumentInvalid({ cause, message: 'Invalid initial Markdown content.' }),\n })\n\n const decoded = yield* Schema.decodeUnknownEffect(CmsMarkdownDocument)(body)\n\n return decoded.nodes\n})\n\nconst isJsonObject = Schema.is(Schema.JsonObject)\n\nexport function collectionComponents(\n components: ReadonlyArray<ComponentDefinition>,\n body: CollectionBody | undefined,\n): ReadonlyArray<ComponentDefinition> {\n if (!body) return components\n\n return components.filter(\n (component) =>\n body.blocks?.includes(component.name) ||\n (component.authoring.group !== undefined && body.groups?.includes(component.authoring.group)),\n )\n}\n\n/** Configuration errors belong to developers, before an installation adopts the catalog. */\nexport function validateCollectionBody(\n components: ReadonlyArray<ComponentDefinition>,\n body: CollectionBody | undefined,\n): ReadonlyArray<string> {\n return [\n ...components.flatMap((component) =>\n component.authoring.slots.flatMap((slot) =>\n slot.input === 'blocks'\n ? [\n ...(slot.blocks ?? [])\n .filter((name) => !components.some((candidate) => candidate.name === name))\n .map((name) => `Unknown block \"${name}\" in ${slot.label}.`),\n ...(slot.groups ?? [])\n .filter((group) => !components.some((candidate) => candidate.authoring.group === group))\n .map((group) => `Unknown block group \"${group}\" in ${slot.label}.`),\n ]\n : [],\n ),\n ),\n ...(body?.blocks ?? [])\n .filter((name) => !components.some((component) => component.name === name))\n .map((name) => `Unknown block \"${name}\".`),\n ...(body?.groups ?? [])\n .filter((group) => !components.some((component) => component.authoring.group === group))\n .map((group) => `Unknown block group \"${group}\".`),\n ]\n}\n\nfunction contentIssues(\n node: JSONContent,\n schemas: ReadonlyMap<string, AuthoringSchema>,\n allowed: ReadonlySet<string>,\n purpose: 'working' | 'publish',\n collectionAllowed: ReadonlySet<string> = allowed,\n): AuthoringValidationIssue[] {\n const issues: AuthoringValidationIssue[] = []\n\n if (node.type === 'cmsBlock') {\n const name = String(node.attrs?.tag ?? 'unknown').toLowerCase() || 'unknown'\n const schema = schemas.get(name)\n\n if (!schema)\n issues.push({\n component: name,\n message: 'This block is unavailable. Ask your site developer to restore its definition.',\n })\n else {\n if (!allowed.has(name))\n issues.push({ component: name, message: `${schema.definition.label} is not allowed in this content region.` })\n issues.push(...schema.validateDetailed(node, purpose))\n\n if (purpose === 'publish' && schema.definition.form)\n issues.push(\n ...formStructureIssues(node.attrs?.props?.steps, schema.definition.form, name).map((message) => ({\n component: name,\n message,\n })),\n )\n }\n }\n\n if (node.type === 'cmsOpaque' || node.type === 'cmsInlineOpaque')\n issues.push({\n component: String(node.attrs?.tag ?? node.type),\n message: 'This content is unsupported. Ask your site developer to update it before publishing.',\n })\n\n if (node.type === 'cmsBlock') {\n const schema = schemas.get(String(node.attrs?.tag).toLowerCase())\n\n for (const region of node.content ?? []) {\n const slot = schema?.definition.slots.find((candidate) => candidate.name === region.attrs?.name)\n\n const permitted =\n slot?.input === 'blocks'\n ? new Set(\n collectionComponents(\n [...schemas].map(([name, schema]) => ({ name, authoring: schema.definition })),\n slot.blocks === undefined && slot.groups === undefined ? undefined : slot,\n )\n .map((component) => component.name)\n .filter((name) => collectionAllowed.has(name)),\n )\n : collectionAllowed\n\n issues.push(...contentIssues(region, schemas, permitted, purpose, collectionAllowed))\n }\n\n return issues\n }\n\n return [\n ...issues,\n ...(node.content ?? []).flatMap((child) => contentIssues(child, schemas, allowed, purpose, collectionAllowed)),\n ]\n}\n\nexport function validateAuthoringDocument(\n body: CmsMarkdownDocument,\n components: ReadonlyMap<string, ComponentDefinition> | undefined,\n bodyPolicy?: CollectionBody,\n): ReadonlyArray<string> {\n return components ? createAuthoringDocumentValidator(components)(body, bodyPolicy).map((issue) => issue.message) : []\n}\n\n/** Resolves a component catalog once so document compilation can reuse its authoring rules. */\nexport function createAuthoringDocumentValidator(components: ReadonlyMap<string, ComponentDefinition>) {\n const definitions = [...components.values()]\n\n const schemas = new Map(\n definitions.map((component) => [component.name, createAuthoringSchema(component.name, component.authoring)]),\n )\n\n return (body: CmsMarkdownDocument, bodyPolicy?: CollectionBody): ReadonlyArray<AuthoringValidationIssue> => {\n const allowed = new Set(collectionComponents(definitions, bodyPolicy).map((component) => component.name))\n\n return comarkToEditor(body.nodes, createCmsComarkRenderData(body)).flatMap((node) =>\n contentIssues(node, schemas, allowed, 'publish'),\n )\n }\n}\n\nexport interface AuthoringSchema {\n readonly definition: BlockAuthoring\n readonly createContent: () => JSONContent\n readonly createSlot: (name: string) => JSONContent\n readonly setProperty: (current: Schema.JsonObject, name: string, value: Schema.Json | undefined) => Schema.JsonObject\n readonly validate: (node: JSONContent, purpose: 'working' | 'publish') => ReadonlyArray<string>\n readonly validateDetailed: (\n node: JSONContent,\n purpose: 'working' | 'publish',\n ) => ReadonlyArray<AuthoringValidationIssue>\n}\n\nexport function createAuthoringSchema(name: string, definition: BlockAuthoring): AuthoringSchema {\n const structuredFields = compileStructuredFields(definition.props)\n const fields = new Map(definition.props.map((field) => [field.name, field]))\n const slots = new Map(definition.slots.map((slot) => [slot.name, slot]))\n\n if (fields.size !== definition.props.length || slots.size !== definition.slots.length) {\n throw new Error(`${definition.label}: authoring names must be unique.`)\n }\n\n const initialProps = Object.assign({}, structuredFields.create(), definition.initialProps)\n\n function createSlot(slotName: string): JSONContent {\n const slot = slots.get(slotName)\n\n if (!slot) throw new Error(`${definition.label}: unknown content region ${slotName}.`)\n const content = slot.initial ? comarkToEditor(slot.initial) : []\n\n return {\n type: 'cmsSlot',\n attrs: { cmsNodeId: createEditorNodeId(), name: slotName, implicit: slotName === 'default', props: {} },\n content: content.length ? content : [{ type: 'paragraph', attrs: { cmsNodeId: createEditorNodeId() } }],\n }\n }\n\n function createContent(): JSONContent {\n return {\n type: 'cmsBlock',\n attrs: { cmsNodeId: createEditorNodeId(), tag: name, props: structuredClone(initialProps) },\n content: definition.slots\n .filter((slot) => slot.required || slot.initial !== undefined)\n .map((slot) => createSlot(slot.name)),\n }\n }\n\n function validateDetailed(\n node: JSONContent,\n purpose: 'working' | 'publish',\n ): ReadonlyArray<AuthoringValidationIssue> {\n const issues: AuthoringValidationIssue[] = []\n const attributes = node.attrs?.props\n const values = isJsonObject(attributes) ? attributes : {}\n\n issues.push(\n ...structuredFields.validateDetailed(values, purpose).map((issue) => ({\n component: name,\n field: issue.path,\n message: issue.message,\n })),\n )\n\n const used = new Set<string>()\n\n for (const region of node.content ?? []) {\n const key = String(region.attrs?.name ?? 'default')\n const slot = slots.get(key)\n\n if (!slot || region.type !== 'cmsSlot') {\n issues.push({ component: name, message: `${definition.label}: unsupported content region ${key}.` })\n continue\n }\n\n if (used.has(key)) issues.push({ component: name, message: `${slot.label} can only appear once.` })\n used.add(key)\n\n if (!validRegion(slot, region.content ?? []))\n issues.push({ component: name, message: `${slot.label} contains unsupported formatting or blocks.` })\n }\n\n for (const slot of definition.slots)\n if (slot.required && !used.has(slot.name)) issues.push({ component: name, message: `${slot.label} is required.` })\n\n return issues\n }\n\n const validate = (node: JSONContent, purpose: 'working' | 'publish'): ReadonlyArray<string> =>\n validateDetailed(node, purpose).map((issue) => issue.message)\n\n const schema: AuthoringSchema = {\n definition,\n createContent,\n createSlot,\n validate,\n validateDetailed,\n setProperty(current: Schema.JsonObject, key: string, value: Schema.Json | undefined) {\n return structuredFields.set(current, key, value)\n },\n }\n\n const issues = validate(createContent(), 'publish')\n\n if (issues.length) throw new Error(`Invalid initial content for ${definition.label}: ${issues.join(' ')}`)\n\n return schema\n}\n\nexport type AuthoringSelection =\n | { readonly kind: 'content'; readonly slot?: BlockSlot }\n | { readonly kind: 'structure' }\n\nexport function selectedAuthoringSelection(\n editor: Editor,\n components: ReadonlyArray<ComponentDefinition>,\n): AuthoringSelection {\n if (isNodeSelection(editor.state.selection)) return { kind: 'structure' }\n\n const position = editor.state.selection.$from\n\n for (let depth = position.depth; depth > 0; depth--) {\n const region = position.node(depth)\n\n if (region.type.name !== 'cmsSlot') continue\n const block = position.node(depth - 1)\n\n return {\n kind: 'content',\n slot: components\n .find((component) => component.name === block.attrs.tag)\n ?.authoring.slots.find((slot) => slot.name === region.attrs.name),\n }\n }\n\n return { kind: 'content' }\n}\n\n/** Applies authoring rules to local edits. Remote CRDT updates always converge; publication validates them. */\nexport function createAuthoringExtension(\n components: () => ReadonlyArray<ComponentDefinition>,\n body: () => CollectionBody | undefined = () => undefined,\n): Extension {\n let previousComponents: ReadonlyArray<ComponentDefinition> | undefined\n let schemas = new Map<string, ReturnType<typeof createAuthoringSchema>>()\n\n function refresh() {\n const current = components()\n\n if (current === previousComponents) return\n previousComponents = current\n schemas = new Map(\n current.map((component) => [component.name, createAuthoringSchema(component.name, component.authoring)]),\n )\n }\n\n function issues(content: JSONContent): string[] {\n const allowed = new Set(collectionComponents(components(), body()).map((component) => component.name))\n\n return contentIssues(content, schemas, allowed, 'working').map((issue) => issue.message)\n }\n\n return Extension.create({\n name: 'cmsAuthoringPolicy',\n addProseMirrorPlugins() {\n return [\n new Plugin({\n filterTransaction(transaction, state) {\n if (!transaction.docChanged || transaction.getMeta(ySyncPluginKey)?.isChangeOrigin) return true\n refresh()\n const previous = issues(state.doc.toJSON())\n\n return issues(transaction.doc.toJSON()).every((issue) => {\n const index = previous.indexOf(issue)\n\n if (index < 0) return false\n previous.splice(index, 1)\n\n return true\n })\n },\n }),\n ]\n },\n })\n}\n\nfunction validRegion(slot: BlockSlot, content: ReadonlyArray<JSONContent>): boolean {\n if (slot.input === 'blocks')\n return content.every((node) => node.type === 'cmsBlock' || (node.type === 'paragraph' && !node.content?.length))\n const types = new Set(['paragraph', 'text', 'hardBreak'])\n const marks = new Set<string>()\n\n if (slot.input !== 'rich-text' && content.length > 1) return false\n\n if (slot.input === 'inline-text' || slot.input === 'rich-text')\n for (const feature of slot.features) {\n if (feature === 'bullet-list') {\n types.add('bulletList')\n types.add('listItem')\n } else marks.add(feature)\n }\n\n const valid = (node: JSONContent): boolean =>\n types.has(node.type ?? '') &&\n (node.marks ?? []).every((mark) => marks.has(mark.type)) &&\n (node.content ?? []).every(valid)\n\n return content.every(valid)\n}\n","import { Schema } from 'effect'\n\nexport interface StructuredField {\n readonly name: string\n readonly label: string\n readonly description?: string\n readonly type: 'string' | 'number' | 'boolean' | 'date' | 'string[]' | 'object' | 'array'\n readonly input:\n | 'text'\n | 'textarea'\n | 'select'\n | 'number'\n | 'toggle'\n | 'date'\n | 'multiselect'\n | 'image'\n | 'link'\n | 'document'\n | 'media'\n | 'object'\n | 'list'\n readonly required: boolean\n readonly nullable: boolean\n readonly defaultValue?: Schema.Json\n readonly options: ReadonlyArray<{ readonly value: string | number; readonly label: string }>\n readonly fields?: ReadonlyArray<StructuredField>\n}\n\nconst presentation = {\n name: Schema.NonEmptyString,\n label: Schema.NonEmptyString,\n description: Schema.optionalKey(Schema.String),\n defaultValue: Schema.optionalKey(Schema.Json),\n required: Schema.Boolean,\n nullable: Schema.Boolean,\n}\n\nconst stringOptions = Schema.Array(Schema.Struct({ value: Schema.String, label: Schema.String }))\n\nconst numberOptions = Schema.Array(Schema.Struct({ value: Schema.Finite, label: Schema.String }))\n\nconst noOptions = Schema.Tuple([])\n\nexport const StructuredField: Schema.Codec<StructuredField> = Schema.Union([\n Schema.Struct({ ...presentation, type: Schema.tag('boolean'), input: Schema.Literal('toggle'), options: noOptions }),\n Schema.Struct({ ...presentation, type: Schema.tag('date'), input: Schema.Literal('date'), options: noOptions }),\n Schema.Struct({\n ...presentation,\n type: Schema.tag('number'),\n input: Schema.Literals(['number', 'select']),\n options: numberOptions,\n }),\n Schema.Struct({\n ...presentation,\n type: Schema.tag('string'),\n input: Schema.Literals(['select', 'text', 'textarea', 'image', 'link', 'document', 'media']),\n options: stringOptions,\n }),\n Schema.Struct({\n ...presentation,\n type: Schema.tag('string[]'),\n input: Schema.Literal('multiselect'),\n options: stringOptions,\n }),\n Schema.Struct({\n ...presentation,\n type: Schema.tag('object'),\n input: Schema.Literal('object'),\n options: noOptions,\n fields: Schema.Array(Schema.suspend(() => StructuredField)),\n }),\n Schema.Struct({\n ...presentation,\n type: Schema.tag('array'),\n input: Schema.Literal('list'),\n options: noOptions,\n fields: Schema.Array(Schema.suspend(() => StructuredField)),\n }),\n])\n","import { Schema } from 'effect'\nimport { FormCapabilities } from './Forms'\nimport { MarkdownNode } from './internal/documents/models'\nimport { StructuredField } from './StructuredFields'\n\nconst inlineTextFeature = Schema.Literals(['bold', 'italic', 'link', 'code'])\n\nconst richTextFeature = Schema.Union([inlineTextFeature, Schema.Literal('bullet-list')])\n\nexport type InlineTextFeature = Schema.Schema.Type<typeof inlineTextFeature>\n\nexport type RichTextFeature = Schema.Schema.Type<typeof richTextFeature>\n\nconst slotBase = {\n name: Schema.NonEmptyString,\n label: Schema.NonEmptyString,\n help: Schema.optionalKey(Schema.String),\n required: Schema.Boolean,\n initial: Schema.optionalKey(Schema.Array(MarkdownNode)),\n}\n\nconst noFeatures = Schema.Tuple([])\n\nexport const BlockSlot = Schema.Union([\n Schema.Struct({ ...slotBase, input: Schema.Literal('text'), features: noFeatures }),\n Schema.Struct({ ...slotBase, input: Schema.Literal('inline-text'), features: Schema.Array(inlineTextFeature) }),\n Schema.Struct({\n ...slotBase,\n input: Schema.Literal('rich-text'),\n features: Schema.Array(richTextFeature),\n }),\n Schema.Struct({\n ...slotBase,\n input: Schema.Literal('blocks'),\n features: noFeatures,\n blocks: Schema.optionalKey(Schema.Array(Schema.NonEmptyString)),\n groups: Schema.optionalKey(Schema.Array(Schema.NonEmptyString)),\n }),\n])\n\nexport type BlockSlot = Schema.Schema.Type<typeof BlockSlot>\n\nexport const BlockAuthoring = Schema.Struct({\n version: Schema.Literal(1),\n form: Schema.optionalKey(FormCapabilities),\n label: Schema.NonEmptyString,\n description: Schema.optionalKey(Schema.String),\n group: Schema.optionalKey(Schema.String),\n icon: Schema.optionalKey(Schema.String),\n props: Schema.Array(StructuredField),\n slots: Schema.Array(BlockSlot),\n initialProps: Schema.JsonObject,\n})\n\nexport interface BlockAuthoring extends Schema.Schema.Type<typeof BlockAuthoring> {}\n","import { Schema } from 'effect'\nimport { BlockAuthoring } from './Authoring'\nimport { CollectionName, Locale, RoutePattern } from './internal/configuration/scalars'\nimport { StructuredField } from './StructuredFields'\n\nexport { CollectionName, Locale, RoutePattern } from './internal/configuration/scalars'\n\nexport const CollectionBody = Schema.Struct({\n blocks: Schema.optionalKey(Schema.Array(Schema.NonEmptyString)),\n groups: Schema.optionalKey(Schema.Array(Schema.NonEmptyString)),\n})\n\nexport interface CollectionBody extends Schema.Schema.Type<typeof CollectionBody> {}\n\nexport const CollectionRoutes = Schema.Struct({\n home: RoutePattern,\n entry: RoutePattern,\n}).annotate({ identifier: 'CollectionRoutes' })\n\nexport interface CollectionRoutes extends Schema.Schema.Type<typeof CollectionRoutes> {}\n\nexport const CollectionDefinition = Schema.Struct({\n collection: CollectionName,\n body: Schema.optionalKey(CollectionBody),\n label: Schema.NonEmptyString,\n description: Schema.String,\n routes: CollectionRoutes,\n hierarchy: Schema.Boolean,\n canCreate: Schema.Boolean,\n authoringFields: Schema.Array(StructuredField),\n}).annotate({ identifier: 'CollectionDefinition' })\n\nexport interface CollectionDefinition extends Schema.Schema.Type<typeof CollectionDefinition> {}\n\nexport const LocaleConfiguration = Schema.Struct({\n locales: Schema.Array(Locale),\n defaultLocale: Locale,\n fallbackLocale: Schema.NullOr(Locale),\n prefixDefaultLocale: Schema.Boolean,\n}).annotate({ identifier: 'LocaleConfiguration' })\n\nexport interface LocaleConfiguration extends Schema.Schema.Type<typeof LocaleConfiguration> {}\n\nexport const DocumentConfiguration = Schema.Struct({\n types: Schema.Array(CollectionDefinition),\n locales: Schema.optionalKey(LocaleConfiguration),\n}).annotate({ identifier: 'DocumentConfiguration' })\n\nexport interface DocumentConfiguration extends Schema.Schema.Type<typeof DocumentConfiguration> {}\n\nexport const ComponentDefinition = Schema.Struct({\n authoring: BlockAuthoring,\n name: Schema.NonEmptyString,\n}).annotate({ identifier: 'ComponentDefinition' })\n\nexport interface ComponentDefinition extends Schema.Schema.Type<typeof ComponentDefinition> {}\n\nexport const AuthoringCatalog = Schema.Struct({\n revision: Schema.NonEmptyString,\n components: Schema.Array(ComponentDefinition),\n})\n\nexport interface AuthoringCatalog extends Schema.Schema.Type<typeof AuthoringCatalog> {}\n\nexport const MediaConfiguration = Schema.Struct({\n enabled: Schema.Boolean,\n maxUploadBytes: Schema.Int.check(Schema.isGreaterThan(0)),\n})\n\nexport interface MediaConfiguration extends Schema.Schema.Type<typeof MediaConfiguration> {}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAEA,SAAgB,sBACd,YACmB;CACnB,OAAO,OAAO,YACZ,OAAO,QAAQ,UAAU,CAAC,CAAC,QAAQ,UAA0C,MAAM,OAAO,MAAS,CACrG;AACF;AAEA,SAAgB,wBAAwB,OAAoD;CAC1F,OAAO,UAAU,SAAS,KAAK,KAAK,QAAQ,QAAQ;AACtD;AAEA,SAAgB,sBAAsB,OAAgC,UAA0B;CAC9F,MAAM,SAAS,UAAU,SAAS,KAAK,IAAI,QAAQ,OAAO,KAAK;CAE/D,OAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC5C;;;;ACfA,MAAMA,iBAAe,OAAO,GAAG,OAAO,UAAU;AAMhD,MAAM,oBAAoB,OAAO,SAAS;CAJZ;CAAW;CAAW;AAIS,CAAC;A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AAC,CAAC,SAAS,EAAE,YAAY,mBAAmB,CAAC;AAI9C,MAAa,uBAAuB,OAAO,OAAO;CAChD,YAAY;CACZ,MAAM,OAAO,YAAY,cAAc;CACvC,OAAO,OAAO;CACd,aAAa,OAAO;CACpB,QAAQ;CACR,WAAW,OAAO;CAClB,WAAW,OAAO;CAClB,iBAAiB,OAAO,MAAM,eAAe;AAC/C,CAAC,CAAC,CAAC,SAAS,EAAE,YAAY,uBAAuB,CAAC;AAIlD,MAAa,sBAAsB,OAAO,OAAO;CAC/C,SAAS,OAAO,MAAM,MAAM;CAC5B,eAAe;CACf,gBAAgB,OAAO,OAAO,MAAM;CACpC,qBAAqB,OAAO;AAC9B,CAAC,CAAC,CAAC,SAAS,EAAE,YAAY,sBAAsB,CAAC;AAIjD,MAAa,wBAAwB,OAAO,OAAO;CACjD,OAAO,OAAO,MAAM,oBAAoB;CACxC,SAAS,OAAO,YAAY,mBAAmB;AACjD,CAAC,CAAC,CAAC,SAAS,EAAE,YAAY,wBAAwB,CAAC;AAInD,MAAa,sBAAsB,OAAO,OAAO;CAC/C,WAAW;CACX,MAAM,OAAO;AACf,CAAC,CAAC,CAAC,SAAS,EAAE,YAAY,sBAAsB,CAAC;AAIjD,MAAa,mBAAmB,OAAO,OAAO;CAC5C,UAAU,OAAO;CACjB,YAAY,OAAO,MAAM,mBAAmB;AAC9C,CAAC;AAID,MAAa,qBAAqB,OAAO,OAAO;CAC9C,SAAS,OAAO;CAChB,gBAAgB,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AAC1D,CAAC"}
@@ -1,7 +1,7 @@
1
1
  import { n as FormDefinition, s as FormValues, t as FormCapabilities } from "./Forms-R0HoTR-o.js";
2
2
  import { t as CmsI18nOptions } from "./I18n-zbqpWxki.js";
3
3
  import { r as SeoConfiguration } from "./Seo-402YumpT.js";
4
- import "./ContentTransfer-CRQet3QJ.js";
4
+ import "./ContentTransfer-Z9FHyLez.js";
5
5
  import { CmsDocumentModelOptions } from "./DocumentModel.js";
6
6
  import { Cause, Context, Crypto, DateTime, Effect, Layer, Option, Result, Schema, Scope, Stream } from "effect";
7
7
  import { Extension, Node } from "@tiptap/core";
package/src/Content.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as DocumentIssue, i as ContentSource, n as ContentPlanEntry, r as ContentSnapshotSource, t as ContentApplyResult } from "./ContentTransfer-CRQet3QJ.js";
1
+ import { a as DocumentIssue, i as ContentSource, n as ContentPlanEntry, r as ContentSnapshotSource, t as ContentApplyResult } from "./ContentTransfer-Z9FHyLez.js";
2
2
  //#region src/Content.d.ts
3
3
  export type CmsContentErrorCode = 'authentication-required' | 'content-conflict' | 'filesystem-error' | 'generation-changed' | 'invalid-document' | 'document-not-found' | 'invalid-response' | 'network-error';
4
4
  export declare class CmsContentError extends Error {
@@ -30,10 +30,11 @@ export interface CmsContentPlan {
30
30
  readonly creates: ReadonlyArray<CmsContentPlanEntry>;
31
31
  readonly updates: ReadonlyArray<CmsContentPlanEntry>;
32
32
  readonly publications: ReadonlyArray<CmsContentPlanEntry>;
33
+ readonly unpublications: ReadonlyArray<CmsContentPlanEntry>;
33
34
  readonly conflicts: ReadonlyArray<CmsContentPlanEntry>;
34
35
  readonly unchanged: ReadonlyArray<CmsContentPlanEntry>;
35
36
  readonly issues: ReadonlyArray<DocumentIssue>;
36
- readonly targetOnly: ReadonlyArray<ContentSource>;
37
+ readonly targetOnly: ReadonlyArray<ContentSnapshotSource>;
37
38
  readonly valid: boolean;
38
39
  }
39
40
  export interface CmsContentImportOptions {
@@ -42,13 +43,13 @@ export interface CmsContentImportOptions {
42
43
  }
43
44
  export interface CmsContentDiff {
44
45
  readonly changes: ReadonlyArray<{
45
- readonly sourcePath: string;
46
+ readonly filePath: string;
46
47
  readonly local?: ContentSource;
47
- readonly target?: ContentSource;
48
+ readonly target?: ContentSource | ContentSnapshotSource;
48
49
  readonly markdownChanged: boolean;
49
50
  readonly publicationChanged: boolean;
50
51
  }>;
51
- readonly targetOnly: ReadonlyArray<ContentSource>;
52
+ readonly targetOnly: ReadonlyArray<ContentSource | ContentSnapshotSource>;
52
53
  }
53
54
  export interface CmsContentClient {
54
55
  readonly plan: (source: CmsContentSourceSet, options?: CmsContentImportOptions) => Promise<CmsContentPlan>;
@@ -61,7 +62,7 @@ export interface CmsContentClient {
61
62
  }
62
63
  export declare function createCmsContentClient(options: CmsContentClientOptions): CmsContentClient;
63
64
  export declare function readCmsContentDirectory(directory: string): Promise<CmsContentSourceSet>;
64
- export declare function diffCmsContentSources(local: ReadonlyArray<ContentSource>, target: ReadonlyArray<ContentSource>): CmsContentDiff;
65
+ export declare function diffCmsContentSources(local: ReadonlyArray<ContentSource>, target: ReadonlyArray<ContentSource | ContentSnapshotSource>): CmsContentDiff;
65
66
  //#endregion
66
67
  export type { ContentApplyResult, ContentSource };
67
68
  //# sourceMappingURL=Content.d.ts.map
package/src/Content.js CHANGED
@@ -1,4 +1,5 @@
1
- import { a as ContentSource, i as ContentSnapshot, n as ContentApplyResult, r as ContentPlan } from "./ContentTransfer-BhF9G56s.js";
1
+ import { c as DocumentIdentity, p as DocumentPlacement } from "./models-VmGmG19-.js";
2
+ import { a as ContentSnapshot, i as ContentPlan, n as ContentApplyResult, o as ContentSnapshotSource, p as DocumentValidationFailed, r as ContentFilePath, s as ContentSource } from "./ContentTransfer-BxwswWn3.js";
2
3
  import { t as CMS_AUTHENTICATION_PATH, u as STUDIO_API_PATH } from "./HttpPaths-c9nLZ9H2.js";
3
4
  import { Result, Schema } from "effect";
4
5
  import { createHash } from "node:crypto";
@@ -56,22 +57,22 @@ function createCmsContentClient(options) {
56
57
  if (!response.ok) {
57
58
  if (response.status === 401 || response.status === 403) throw new CmsContentError("authentication-required", `CMS content request was rejected (${response.status}).`);
58
59
  if (response.status === 409) throw new CmsContentError("generation-changed", "The CMS changed after this content plan was created.");
60
+ if (response.status === 422) {
61
+ const failure = await decodeResponse(response, DocumentValidationFailed, "document validation failure");
62
+ throw new CmsContentError("invalid-document", "The CMS rejected an invalid document.", { issues: failure.issues });
63
+ }
59
64
  throw new CmsContentError("network-error", `CMS content request failed (${response.status}).`);
60
65
  }
61
- let payload;
62
- try {
63
- payload = await response.json();
64
- } catch (cause) {
65
- throw new CmsContentError("invalid-response", "CMS returned an invalid JSON response.", { cause });
66
- }
67
- return decode(schema, payload, label);
66
+ return decodeResponse(response, schema, label);
68
67
  };
69
68
  const snapshot = async () => contentRequest("snapshot", ContentSnapshot, "content snapshot");
70
69
  return {
71
70
  plan: async (source, authoredOptions = {}) => {
72
71
  const sources = Object.freeze(source.sources.map((entry) => Object.freeze(ContentSource.make({
73
- sourcePath: entry.sourcePath,
72
+ filePath: entry.filePath,
73
+ ...entry.identity === void 0 ? void 0 : { identity: entry.identity },
74
74
  markdown: entry.markdown,
75
+ ...entry.placement === void 0 ? void 0 : { placement: entry.placement },
75
76
  published: entry.published
76
77
  }))));
77
78
  const input = Object.freeze({
@@ -80,17 +81,18 @@ function createCmsContentClient(options) {
80
81
  publish: authoredOptions.publish ?? false
81
82
  });
82
83
  const [protocol, current] = await Promise.all([contentRequest("plan", ContentPlan, "content plan", input), snapshot()]);
83
- const sourcePaths = new Set(sources.map((entry) => entry.sourcePath));
84
+ const documentIds = new Set(sources.flatMap((entry) => entry.identity ? [entry.identity.documentId] : []));
84
85
  const entries = (action) => protocol.entries.filter((entry) => entry.action === action);
85
86
  const plan = Object.freeze({
86
87
  generation: protocol.generation,
87
88
  creates: entries("create"),
88
89
  updates: entries("update"),
89
90
  publications: entries("publish"),
91
+ unpublications: entries("unpublish"),
90
92
  conflicts: entries("conflict"),
91
93
  unchanged: entries("unchanged"),
92
94
  issues: protocol.issues,
93
- targetOnly: current.sources.filter((entry) => !sourcePaths.has(entry.sourcePath)),
95
+ targetOnly: current.sources.filter((entry) => !documentIds.has(entry.identity.documentId)),
94
96
  valid: protocol.valid
95
97
  });
96
98
  plans.set(plan, {
@@ -116,12 +118,10 @@ function createCmsContentClient(options) {
116
118
  },
117
119
  diff: async (source) => diffSources(source.sources, (await snapshot()).sources),
118
120
  export: async ({ directory }) => {
119
- const value = await snapshot();
120
- await writeContentDirectory(directory, value.sources);
121
- return { sources: value.sources };
121
+ return writeContentDirectory(directory, (await snapshot()).sources);
122
122
  },
123
123
  readDocument: async (documentId) => {
124
- const document = (await snapshot()).sources.find((source) => source.documentId === documentId);
124
+ const document = (await snapshot()).sources.find((source) => source.identity.documentId === documentId);
125
125
  if (!document) throw new CmsContentError("document-not-found", `CMS document ${documentId} was not found.`);
126
126
  return document;
127
127
  }
@@ -138,14 +138,17 @@ async function readCmsContentDirectory(directory) {
138
138
  if (!isMissingFile(cause)) throw cause;
139
139
  }
140
140
  if (index) return { sources: await Promise.all(index.sources.map(async (entry) => decode(ContentSource, {
141
- sourcePath: entry.sourcePath,
142
- markdown: await readFile(await safeContentFile(root, entry.sourcePath), "utf8"),
143
- published: entry.published
141
+ filePath: entry.filePath,
142
+ identity: entry.identity,
143
+ markdown: await readFile(await safeContentFile(root, entry.filePath), "utf8"),
144
+ placement: entry.placement,
145
+ published: entry.published,
146
+ revisionId: entry.revisionId
144
147
  }, "content source"))) };
145
148
  const files = await markdownFiles(root);
146
149
  if (!files.length) throw new CmsContentError("filesystem-error", `No Markdown files found in ${root}.`);
147
150
  return { sources: await Promise.all(files.map(async (file) => decode(ContentSource, {
148
- sourcePath: relative(root, file).replaceAll("\\", "/"),
151
+ filePath: relative(root, file).replaceAll("\\", "/"),
149
152
  markdown: await readFile(file, "utf8"),
150
153
  published: true
151
154
  }, "content source"))) };
@@ -159,12 +162,15 @@ function diffCmsContentSources(local, target) {
159
162
  }
160
163
  const ContentHash = Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/u));
161
164
  const ContentIndexEntry = Schema.Struct({
162
- sourcePath: ContentSource.fields.sourcePath,
165
+ filePath: ContentSource.fields.filePath,
166
+ identity: DocumentIdentity,
167
+ placement: DocumentPlacement,
163
168
  published: Schema.Boolean,
169
+ revisionId: ContentSnapshotSource.fields.revisionId,
164
170
  sha256: ContentHash
165
171
  });
166
172
  const ContentIndex = Schema.Struct({
167
- version: Schema.Literal(1),
173
+ version: Schema.Literal(2),
168
174
  sources: Schema.Array(ContentIndexEntry),
169
175
  exportSha256: ContentHash
170
176
  });
@@ -172,45 +178,54 @@ async function writeContentDirectory(directory, sources) {
172
178
  try {
173
179
  const root = resolve(directory);
174
180
  const indexPath = await safeContentFile(root, ".cms-content.json");
175
- await Promise.all(sources.map((source) => safeContentFile(root, source.sourcePath)));
176
181
  let previous;
177
182
  try {
178
183
  previous = parseIndex(await readFile(indexPath, "utf8"));
179
184
  } catch (cause) {
180
185
  if (!isMissingFile(cause)) throw cause;
181
186
  }
182
- const previousByPath = new Map(previous?.sources.map((entry) => [entry.sourcePath, entry]));
187
+ const previousById = new Map(previous?.sources.map((entry) => [entry.identity.documentId, entry]));
188
+ const paths = exportPaths(sources, previousById);
183
189
  if (previous) {
184
190
  const metadata = {
185
191
  version: previous.version,
186
192
  sources: previous.sources
187
193
  };
188
194
  if (sha256(JSON.stringify(metadata)) !== previous.exportSha256) throw new CmsContentError("filesystem-error", "The local .cms-content.json file has been edited.");
189
- const incomingPaths = new Set(sources.map((source) => source.sourcePath));
190
- for (const entry of previous.sources) if (!incomingPaths.has(entry.sourcePath)) throw new CmsContentError("filesystem-error", `CMS document ${entry.sourcePath} no longer exists; resolve the local file before exporting again.`);
195
+ const incomingIds = new Set(sources.map((source) => source.identity.documentId));
196
+ for (const entry of previous.sources) if (!incomingIds.has(entry.identity.documentId)) throw new CmsContentError("filesystem-error", `CMS document ${entry.filePath} no longer exists; resolve the local file before exporting again.`);
191
197
  }
192
- for (const source of sources) try {
193
- const local = await readFile(await safeContentFile(root, source.sourcePath), "utf8");
194
- const before = previousByPath.get(source.sourcePath);
195
- if (before ? sha256(local) !== before.sha256 : local !== source.markdown) throw new CmsContentError("filesystem-error", `Local edits in ${source.sourcePath}; export was stopped.`);
196
- } catch (cause) {
197
- if (!isMissingFile(cause)) throw cause;
198
+ for (const source of sources) {
199
+ const filePath = paths.get(source.identity.documentId);
200
+ if (!filePath) throw new CmsContentError("filesystem-error", `Could not allocate an export path for ${source.identity.documentId}.`);
201
+ try {
202
+ const local = await readFile(await safeContentFile(root, filePath), "utf8");
203
+ const before = previousById.get(source.identity.documentId);
204
+ if (before ? sha256(local) !== before.sha256 : local !== source.markdown) throw new CmsContentError("filesystem-error", `Local edits in ${filePath}; export was stopped.`);
205
+ } catch (cause) {
206
+ if (!isMissingFile(cause)) throw cause;
207
+ }
198
208
  }
199
209
  await mkdir(root, { recursive: true });
200
210
  const entries = [];
201
211
  for (const source of sources) {
202
- const file = await safeContentFile(root, source.sourcePath);
212
+ const filePath = paths.get(source.identity.documentId);
213
+ if (!filePath) throw new CmsContentError("filesystem-error", `Could not allocate an export path for ${source.identity.documentId}.`);
214
+ const file = await safeContentFile(root, filePath);
203
215
  await mkdir(dirname(file), { recursive: true });
204
- await safeContentFile(root, source.sourcePath);
216
+ await safeContentFile(root, filePath);
205
217
  await writeFile(file, source.markdown);
206
218
  entries.push({
207
- sourcePath: source.sourcePath,
219
+ filePath,
220
+ identity: source.identity,
221
+ placement: source.placement,
208
222
  published: source.published,
223
+ revisionId: source.revisionId,
209
224
  sha256: sha256(source.markdown)
210
225
  });
211
226
  }
212
227
  const metadata = {
213
- version: 1,
228
+ version: 2,
214
229
  sources: entries
215
230
  };
216
231
  const index = {
@@ -219,28 +234,64 @@ async function writeContentDirectory(directory, sources) {
219
234
  };
220
235
  await safeContentFile(root, ".cms-content.json");
221
236
  await writeFile(indexPath, `${JSON.stringify(index, void 0, 2)}\n`);
237
+ return { sources: sources.map((source) => ContentSource.make({
238
+ filePath: paths.get(source.identity.documentId),
239
+ identity: source.identity,
240
+ markdown: source.markdown,
241
+ placement: source.placement,
242
+ published: source.published,
243
+ revisionId: source.revisionId
244
+ })) };
222
245
  } catch (cause) {
223
246
  throw new CmsContentError("filesystem-error", `Could not export CMS content to ${directory}.`, { cause });
224
247
  }
225
248
  }
226
249
  function diffSources(local, target) {
227
- const targetByPath = new Map(target.map((source) => [source.sourcePath, source]));
228
- const localPaths = new Set(local.map((source) => source.sourcePath));
250
+ const targetById = new Map(target.flatMap((source) => source.identity ? [[source.identity.documentId, source]] : []));
251
+ const targetByFile = new Map(target.flatMap((source) => "filePath" in source ? [[source.filePath, source]] : []));
252
+ const localIds = new Set(local.flatMap((source) => source.identity ? [source.identity.documentId] : []));
253
+ const localFiles = new Set(local.map((source) => source.filePath));
229
254
  return {
230
255
  changes: local.flatMap((source) => {
231
- const current = targetByPath.get(source.sourcePath);
256
+ const current = source.identity ? targetById.get(source.identity.documentId) : targetByFile.get(source.filePath);
232
257
  const markdownChanged = current?.markdown !== source.markdown;
233
258
  const publicationChanged = current !== void 0 && current.published !== source.published;
234
259
  return markdownChanged || publicationChanged ? [{
235
- sourcePath: source.sourcePath,
260
+ filePath: source.filePath,
236
261
  local: source,
237
262
  target: current,
238
263
  markdownChanged,
239
264
  publicationChanged
240
265
  }] : [];
241
266
  }),
242
- targetOnly: target.filter((source) => !localPaths.has(source.sourcePath))
267
+ targetOnly: target.filter((source) => source.identity ? !localIds.has(source.identity.documentId) : "filePath" in source && !localFiles.has(source.filePath))
268
+ };
269
+ }
270
+ function exportPaths(sources, previous) {
271
+ const byId = new Map(sources.map((source) => [source.identity.documentId, source]));
272
+ const allocated = /* @__PURE__ */ new Set();
273
+ const result = /* @__PURE__ */ new Map();
274
+ const segmentsFor = (source, visited = /* @__PURE__ */ new Set()) => {
275
+ if (source.placement.kind === "home") return [];
276
+ if (visited.has(source.identity.documentId)) return [source.placement.slug];
277
+ const parent = byId.get(source.placement.parentDocumentId);
278
+ return parent ? [...segmentsFor(parent, /* @__PURE__ */ new Set([...visited, source.identity.documentId])), source.placement.slug] : [source.placement.slug];
243
279
  };
280
+ for (const source of sources) {
281
+ const retained = previous.get(source.identity.documentId)?.filePath;
282
+ const base = [source.identity.collection, ...source.identity.locale ? [source.identity.locale] : []];
283
+ const placement = segmentsFor(source);
284
+ const generated = source.placement.kind === "home" ? [...base, "index.md"].join("/") : [
285
+ ...base,
286
+ ...placement.slice(0, -1),
287
+ `${placement.at(-1) ?? "document"}.md`
288
+ ].join("/");
289
+ let candidate = retained ?? ContentFilePath.make(generated);
290
+ if (allocated.has(candidate)) candidate = ContentFilePath.make(generated.replace(/\.md$/u, `-${source.identity.documentId.slice(0, 8)}.md`));
291
+ allocated.add(candidate);
292
+ result.set(source.identity.documentId, candidate);
293
+ }
294
+ return result;
244
295
  }
245
296
  async function markdownFiles(directory) {
246
297
  const entries = await readdir(directory, { withFileTypes: true });
@@ -250,19 +301,19 @@ async function markdownFiles(directory) {
250
301
  return entry.isFile() && [".md", ".mdc"].includes(extname(path)) ? [path] : [];
251
302
  }))).flat().sort((left, right) => left.localeCompare(right));
252
303
  }
253
- function safeContentPath(root, sourcePath) {
254
- const path = resolve(root, sourcePath);
255
- if (!path.startsWith(`${root}${sep}`)) throw new CmsContentError("filesystem-error", `Unsafe content path: ${sourcePath}`);
304
+ function safeContentPath(root, filePath) {
305
+ const path = resolve(root, filePath);
306
+ if (!path.startsWith(`${root}${sep}`)) throw new CmsContentError("filesystem-error", `Unsafe content path: ${filePath}`);
256
307
  return path;
257
308
  }
258
- async function safeContentFile(root, sourcePath) {
259
- const path = safeContentPath(root, sourcePath);
309
+ async function safeContentFile(root, filePath) {
310
+ const path = safeContentPath(root, filePath);
260
311
  const segments = relative(root, path).split(sep);
261
312
  let current = root;
262
313
  for (const segment of ["", ...segments]) {
263
314
  current = segment ? resolve(current, segment) : current;
264
315
  try {
265
- if ((await lstat(current)).isSymbolicLink()) throw new CmsContentError("filesystem-error", `Symlinks are not allowed in CMS content paths: ${sourcePath}`);
316
+ if ((await lstat(current)).isSymbolicLink()) throw new CmsContentError("filesystem-error", `Symlinks are not allowed in CMS content paths: ${filePath}`);
266
317
  } catch (cause) {
267
318
  if (!isMissingFile(cause)) throw cause;
268
319
  }
@@ -291,6 +342,14 @@ async function request(fetch, input, init) {
291
342
  throw new CmsContentError("network-error", `Could not reach ${input.origin}.`, { cause });
292
343
  }
293
344
  }
345
+ async function decodeResponse(response, schema, label) {
346
+ try {
347
+ return decode(schema, await response.json(), label);
348
+ } catch (cause) {
349
+ if (cause instanceof CmsContentError) throw cause;
350
+ throw new CmsContentError("invalid-response", "CMS returned an invalid JSON response.", { cause });
351
+ }
352
+ }
294
353
  function decode(schema, value, label) {
295
354
  const decoded = Schema.decodeUnknownResult(schema)(value);
296
355
  if (Result.isFailure(decoded)) throw new CmsContentError("invalid-response", `CMS returned an invalid ${label}.`, { cause: decoded.failure });
@@ -302,7 +361,7 @@ function sha256(value) {
302
361
  function parseIndex(value) {
303
362
  const decoded = Schema.decodeUnknownResult(ContentIndex)(JSON.parse(value));
304
363
  if (Result.isFailure(decoded)) throw new CmsContentError("filesystem-error", "The .cms-content.json index is invalid.");
305
- if (new Set(decoded.success.sources.map((entry) => entry.sourcePath)).size !== decoded.success.sources.length) throw new CmsContentError("filesystem-error", "The .cms-content.json index contains duplicate source paths.");
364
+ if (new Set(decoded.success.sources.map((entry) => entry.filePath)).size !== decoded.success.sources.length) throw new CmsContentError("filesystem-error", "The .cms-content.json index contains duplicate file paths.");
306
365
  return decoded.success;
307
366
  }
308
367
  function isMissingFile(cause) {