@beyondwork/docx-react-component 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -104
- package/package.json +50 -30
- package/src/README.md +85 -0
- package/src/api/README.md +22 -0
- package/src/api/public-types.ts +525 -0
- package/src/compare/diff-engine.ts +530 -0
- package/src/compare/export-redlines.ts +162 -0
- package/src/compare/snapshot.ts +37 -0
- package/src/component-inventory.md +99 -0
- package/src/core/README.md +10 -0
- package/src/core/commands/README.md +3 -0
- package/src/core/commands/formatting-commands.ts +161 -0
- package/src/core/commands/image-commands.ts +144 -0
- package/src/core/commands/index.ts +1013 -0
- package/src/core/commands/list-commands.ts +370 -0
- package/src/core/commands/review-commands.ts +108 -0
- package/src/core/commands/text-commands.ts +119 -0
- package/src/core/schema/README.md +3 -0
- package/src/core/schema/text-schema.ts +512 -0
- package/src/core/selection/README.md +3 -0
- package/src/core/selection/mapping.ts +238 -0
- package/src/core/selection/review-anchors.ts +94 -0
- package/src/core/state/README.md +3 -0
- package/src/core/state/editor-state.ts +580 -0
- package/src/core/state/text-transaction.ts +276 -0
- package/src/formats/xlsx/io/parse-shared-strings.ts +41 -0
- package/src/formats/xlsx/io/parse-sheet.ts +289 -0
- package/src/formats/xlsx/io/parse-styles.ts +57 -0
- package/src/formats/xlsx/io/parse-workbook.ts +75 -0
- package/src/formats/xlsx/io/xlsx-session.ts +306 -0
- package/src/formats/xlsx/model/cell.ts +189 -0
- package/src/formats/xlsx/model/sheet.ts +244 -0
- package/src/formats/xlsx/model/styles.ts +118 -0
- package/src/formats/xlsx/model/workbook.ts +449 -0
- package/src/index.ts +45 -0
- package/src/io/README.md +10 -0
- package/src/io/docx-session.ts +1763 -0
- package/src/io/export/README.md +3 -0
- package/src/io/export/export-session.ts +165 -0
- package/src/io/export/minimal-docx.ts +115 -0
- package/src/io/export/reattach-preserved-parts.ts +54 -0
- package/src/io/export/serialize-comments.ts +876 -0
- package/src/io/export/serialize-footnotes.ts +217 -0
- package/src/io/export/serialize-headers-footers.ts +200 -0
- package/src/io/export/serialize-main-document.ts +982 -0
- package/src/io/export/serialize-numbering.ts +97 -0
- package/src/io/export/serialize-revisions.ts +389 -0
- package/src/io/export/serialize-runtime-revisions.ts +265 -0
- package/src/io/export/serialize-tables.ts +147 -0
- package/src/io/export/split-review-boundaries.ts +194 -0
- package/src/io/normalize/README.md +3 -0
- package/src/io/normalize/normalize-text.ts +437 -0
- package/src/io/ooxml/README.md +3 -0
- package/src/io/ooxml/parse-comments.ts +779 -0
- package/src/io/ooxml/parse-complex-content.ts +287 -0
- package/src/io/ooxml/parse-fields.ts +438 -0
- package/src/io/ooxml/parse-footnotes.ts +403 -0
- package/src/io/ooxml/parse-headers-footers.ts +483 -0
- package/src/io/ooxml/parse-inline-media.ts +431 -0
- package/src/io/ooxml/parse-main-document.ts +1846 -0
- package/src/io/ooxml/parse-numbering.ts +425 -0
- package/src/io/ooxml/parse-revisions.ts +658 -0
- package/src/io/ooxml/parse-shapes.ts +271 -0
- package/src/io/ooxml/parse-tables.ts +568 -0
- package/src/io/ooxml/parse-theme.ts +314 -0
- package/src/io/ooxml/part-manifest.ts +136 -0
- package/src/io/ooxml/revision-boundaries.ts +351 -0
- package/src/io/opc/README.md +3 -0
- package/src/io/opc/corrupt-package.ts +166 -0
- package/src/io/opc/docx-package.ts +74 -0
- package/src/io/opc/package-reader.ts +325 -0
- package/src/io/opc/package-writer.ts +273 -0
- package/src/legal/bookmarks.ts +196 -0
- package/src/legal/cross-references.ts +356 -0
- package/src/legal/defined-terms.ts +203 -0
- package/src/model/README.md +3 -0
- package/src/model/canonical-document.ts +1911 -0
- package/src/model/cds-1.0.0.ts +196 -0
- package/src/model/snapshot.ts +393 -0
- package/src/preservation/README.md +3 -0
- package/src/preservation/markup-compatibility.ts +48 -0
- package/src/preservation/opaque-fragment-store.ts +89 -0
- package/src/preservation/opaque-region.ts +233 -0
- package/src/preservation/package-preservation.ts +120 -0
- package/src/preservation/preserved-part-manifest.ts +56 -0
- package/src/preservation/relationship-retention.ts +57 -0
- package/src/preservation/store.ts +185 -0
- package/src/review/README.md +16 -0
- package/src/review/store/README.md +3 -0
- package/src/review/store/comment-anchors.ts +70 -0
- package/src/review/store/comment-remapping.ts +154 -0
- package/src/review/store/comment-store.ts +331 -0
- package/src/review/store/comment-thread.ts +109 -0
- package/src/review/store/revision-actions.ts +394 -0
- package/src/review/store/revision-store.ts +303 -0
- package/src/review/store/revision-types.ts +168 -0
- package/src/review/store/runtime-comment-store.ts +43 -0
- package/src/runtime/README.md +3 -0
- package/src/runtime/ai-action-policy.ts +764 -0
- package/src/runtime/document-runtime.ts +967 -0
- package/src/runtime/read-only-diagnostics-runtime.ts +232 -0
- package/src/runtime/review-runtime.ts +44 -0
- package/src/runtime/revision-runtime.ts +107 -0
- package/src/runtime/session-capabilities.ts +138 -0
- package/src/runtime/surface-projection.ts +570 -0
- package/src/runtime/table-commands.ts +87 -0
- package/src/runtime/table-schema.ts +140 -0
- package/src/runtime/virtualized-rendering.ts +258 -0
- package/src/ui/README.md +30 -0
- package/src/ui/WordReviewEditor.tsx +1506 -0
- package/src/ui/comments/README.md +3 -0
- package/src/ui/compatibility/README.md +3 -0
- package/src/ui/editor-surface/README.md +3 -0
- package/src/ui/headless/comment-decoration-model.ts +124 -0
- package/src/ui/headless/revision-decoration-model.ts +128 -0
- package/src/ui/headless/selection-helpers.ts +34 -0
- package/src/ui/headless/use-editor-keyboard.ts +98 -0
- package/src/ui/review/README.md +3 -0
- package/src/ui/shared/revision-filters.ts +31 -0
- package/src/ui/status/README.md +3 -0
- package/src/ui/theme/README.md +3 -0
- package/src/ui/toolbar/README.md +3 -0
- package/src/ui-tailwind/chrome/tw-alert-banner.tsx +48 -0
- package/src/ui-tailwind/chrome/tw-selection-toolbar.tsx +44 -0
- package/src/ui-tailwind/chrome/tw-unsaved-modal.tsx +58 -0
- package/src/ui-tailwind/chrome/use-before-unload.ts +20 -0
- package/src/ui-tailwind/editor-surface/pm-command-bridge.ts +139 -0
- package/src/ui-tailwind/editor-surface/pm-decorations.ts +98 -0
- package/src/ui-tailwind/editor-surface/pm-position-map.ts +123 -0
- package/src/ui-tailwind/editor-surface/pm-schema.ts +452 -0
- package/src/ui-tailwind/editor-surface/pm-state-from-snapshot.ts +327 -0
- package/src/ui-tailwind/editor-surface/search-plugin.ts +157 -0
- package/src/ui-tailwind/editor-surface/tw-caret.tsx +12 -0
- package/src/ui-tailwind/editor-surface/tw-editor-surface.tsx +150 -0
- package/src/ui-tailwind/editor-surface/tw-inline-token.tsx +118 -0
- package/src/ui-tailwind/editor-surface/tw-opaque-block.tsx +52 -0
- package/src/ui-tailwind/editor-surface/tw-paragraph-block.tsx +151 -0
- package/src/ui-tailwind/editor-surface/tw-prosemirror-surface.tsx +215 -0
- package/src/ui-tailwind/editor-surface/tw-segment-view.tsx +111 -0
- package/src/ui-tailwind/editor-surface/tw-table-node-view.tsx +122 -0
- package/src/ui-tailwind/index.ts +61 -0
- package/src/ui-tailwind/review/tw-comment-sidebar.tsx +276 -0
- package/src/ui-tailwind/review/tw-health-panel.tsx +120 -0
- package/src/ui-tailwind/review/tw-review-rail.tsx +120 -0
- package/src/ui-tailwind/review/tw-revision-sidebar.tsx +164 -0
- package/src/ui-tailwind/status/tw-status-bar.tsx +58 -0
- package/src/ui-tailwind/theme/editor-theme.css +190 -0
- package/src/ui-tailwind/toolbar/tw-toolbar-icon-button.tsx +48 -0
- package/src/ui-tailwind/toolbar/tw-toolbar.tsx +231 -0
- package/src/ui-tailwind/tw-review-workspace.tsx +140 -0
- package/src/validation/README.md +3 -0
- package/src/validation/compatibility-engine.ts +317 -0
- package/src/validation/compatibility-report.ts +160 -0
- package/src/validation/diagnostics.ts +203 -0
- package/src/validation/import-diagnostics.ts +128 -0
- package/src/validation/low-priority-word-surfaces.ts +373 -0
- package/dist/chunk-32W6IVQE.js +0 -7725
- package/dist/chunk-32W6IVQE.js.map +0 -1
- package/dist/index.cjs +0 -23722
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -7
- package/dist/index.d.ts +0 -7
- package/dist/index.js +0 -16011
- package/dist/index.js.map +0 -1
- package/dist/public-types-DqCURAz8.d.cts +0 -1152
- package/dist/public-types-DqCURAz8.d.ts +0 -1152
- package/dist/tailwind.cjs +0 -8295
- package/dist/tailwind.cjs.map +0 -1
- package/dist/tailwind.d.cts +0 -323
- package/dist/tailwind.d.ts +0 -323
- package/dist/tailwind.js +0 -553
- package/dist/tailwind.js.map +0 -1
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/ui/WordReviewEditor.tsx","../src/core/selection/mapping.ts","../src/model/cds-1.0.0.ts","../src/model/canonical-document.ts","../src/model/snapshot.ts","../src/core/state/editor-state.ts","../src/core/commands/review-commands.ts","../src/core/schema/text-schema.ts","../src/core/state/text-transaction.ts","../src/core/commands/text-commands.ts","../src/core/selection/review-anchors.ts","../src/review/store/comment-remapping.ts","../src/review/store/revision-types.ts","../src/review/store/revision-store.ts","../src/review/store/revision-actions.ts","../src/runtime/revision-runtime.ts","../src/core/commands/index.ts","../src/review/store/comment-anchors.ts","../src/review/store/comment-store.ts","../src/review/store/runtime-comment-store.ts","../src/preservation/store.ts","../src/validation/compatibility-engine.ts","../src/runtime/surface-projection.ts","../src/runtime/document-runtime.ts","../src/io/ooxml/part-manifest.ts","../src/io/opc/package-writer.ts","../src/io/opc/docx-package.ts","../src/io/opc/package-reader.ts","../src/io/ooxml/parse-inline-media.ts","../src/io/ooxml/parse-numbering.ts","../src/io/ooxml/parse-main-document.ts","../src/io/normalize/normalize-text.ts","../src/io/opc/corrupt-package.ts","../src/io/export/reattach-preserved-parts.ts","../src/io/export/export-session.ts","../src/preservation/relationship-retention.ts","../src/io/export/serialize-numbering.ts","../src/io/export/serialize-main-document.ts","../src/io/ooxml/revision-boundaries.ts","../src/io/ooxml/parse-revisions.ts","../src/review/store/comment-thread.ts","../src/io/ooxml/parse-comments.ts","../src/io/export/serialize-comments.ts","../src/io/export/split-review-boundaries.ts","../src/io/export/serialize-runtime-revisions.ts","../src/validation/diagnostics.ts","../src/validation/import-diagnostics.ts","../src/runtime/read-only-diagnostics-runtime.ts","../src/io/ooxml/parse-headers-footers.ts","../src/io/ooxml/parse-footnotes.ts","../src/io/ooxml/parse-theme.ts","../src/io/export/serialize-headers-footers.ts","../src/io/export/serialize-footnotes.ts","../src/io/docx-session.ts","../src/io/export/minimal-docx.ts","../src/runtime/session-capabilities.ts","../src/ui-tailwind/editor-surface/tw-prosemirror-surface.tsx","../src/ui/headless/comment-decoration-model.ts","../src/ui/headless/revision-decoration-model.ts","../src/ui-tailwind/editor-surface/pm-state-from-snapshot.ts","../src/ui-tailwind/editor-surface/pm-schema.ts","../src/runtime/table-schema.ts","../src/ui-tailwind/editor-surface/pm-position-map.ts","../src/ui-tailwind/editor-surface/pm-command-bridge.ts","../src/ui/headless/selection-helpers.ts","../src/ui-tailwind/editor-surface/pm-decorations.ts","../src/ui-tailwind/editor-surface/tw-table-node-view.tsx","../node_modules/.pnpm/@radix-ui+react-tooltip@1.2.8_@types+react-dom@19.2.3_@types+react@19.2.14__@types+reac_9074d9fb06315b089b2bee17c4c65951/node_modules/@radix-ui/react-tooltip/src/tooltip.tsx","../node_modules/.pnpm/@radix-ui+primitive@1.1.3/node_modules/@radix-ui/primitive/src/primitive.tsx","../node_modules/.pnpm/@radix-ui+react-compose-refs@1.1.2_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-compose-refs/src/compose-refs.tsx","../node_modules/.pnpm/@radix-ui+react-context@1.1.2_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-context/src/create-context.tsx","../node_modules/.pnpm/@radix-ui+react-dismissable-layer@1.1.11_@types+react-dom@19.2.3_@types+react@19.2.14___3d3960154a4c07d09bb90cb341135fc5/node_modules/@radix-ui/react-dismissable-layer/src/dismissable-layer.tsx","../node_modules/.pnpm/@radix-ui+react-primitive@2.1.3_@types+react-dom@19.2.3_@types+react@19.2.14__@types+re_1181ea5061ec9212248424669240e4ec/node_modules/@radix-ui/react-primitive/src/primitive.tsx","../node_modules/.pnpm/@radix-ui+react-slot@1.2.3_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-slot/src/slot.tsx","../node_modules/.pnpm/@radix-ui+react-use-callback-ref@1.1.1_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-use-callback-ref/src/use-callback-ref.tsx","../node_modules/.pnpm/@radix-ui+react-use-escape-keydown@1.1.1_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-use-escape-keydown/src/use-escape-keydown.tsx","../node_modules/.pnpm/@radix-ui+react-id@1.1.1_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-id/src/id.tsx","../node_modules/.pnpm/@radix-ui+react-use-layout-effect@1.1.1_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-use-layout-effect/src/use-layout-effect.tsx","../node_modules/.pnpm/@radix-ui+react-popper@1.2.8_@types+react-dom@19.2.3_@types+react@19.2.14__@types+react_13e0521d8aea7ebfbfb8bee1fb615c05/node_modules/@radix-ui/react-popper/src/popper.tsx","../node_modules/.pnpm/@floating-ui+utils@0.2.11/node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs","../node_modules/.pnpm/@floating-ui+core@1.7.5/node_modules/@floating-ui/core/dist/floating-ui.core.mjs","../node_modules/.pnpm/@floating-ui+utils@0.2.11/node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs","../node_modules/.pnpm/@floating-ui+dom@1.7.6/node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs","../node_modules/.pnpm/@floating-ui+react-dom@2.1.8_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs","../node_modules/.pnpm/@radix-ui+react-arrow@1.1.7_@types+react-dom@19.2.3_@types+react@19.2.14__@types+react@_e05f2c19a58a99fddf374207b5e3778c/node_modules/@radix-ui/react-arrow/src/arrow.tsx","../node_modules/.pnpm/@radix-ui+react-use-size@1.1.1_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-use-size/src/use-size.tsx","../node_modules/.pnpm/@radix-ui+react-portal@1.1.9_@types+react-dom@19.2.3_@types+react@19.2.14__@types+react_7668895bec2444446faa4e0f4eb5244b/node_modules/@radix-ui/react-portal/src/portal.tsx","../node_modules/.pnpm/@radix-ui+react-presence@1.1.5_@types+react-dom@19.2.3_@types+react@19.2.14__@types+rea_c01c26c80b5ab5e3ecefbda6eca51ad1/node_modules/@radix-ui/react-presence/src/presence.tsx","../node_modules/.pnpm/@radix-ui+react-presence@1.1.5_@types+react-dom@19.2.3_@types+react@19.2.14__@types+rea_c01c26c80b5ab5e3ecefbda6eca51ad1/node_modules/@radix-ui/react-presence/src/use-state-machine.tsx","../node_modules/.pnpm/@radix-ui+react-use-controllable-state@1.2.2_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-use-controllable-state/src/use-controllable-state.tsx","../node_modules/.pnpm/@radix-ui+react-use-controllable-state@1.2.2_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-use-controllable-state/src/use-controllable-state-reducer.tsx","../node_modules/.pnpm/@radix-ui+react-visually-hidden@1.2.3_@types+react-dom@19.2.3_@types+react@19.2.14__@ty_fa89646d7248b32d1762bf88948f6339/node_modules/@radix-ui/react-visually-hidden/src/visually-hidden.tsx","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/shared/src/utils/mergeClasses.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/shared/src/utils/toKebabCase.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/shared/src/utils/toCamelCase.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/shared/src/utils/toPascalCase.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/defaultAttributes.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/shared/src/utils/hasA11yProp.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/context.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/Icon.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/createLucideIcon.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/check.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/circle-x.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/download.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/eye-off.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/eye.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/file-text.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/info.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/message-square-plus.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/message-square.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/monitor.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/redo-2.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/shield-alert.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/shield-check.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/shield.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/triangle-alert.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/undo-2.ts","../node_modules/.pnpm/lucide-react@1.7.0_react@19.2.4/node_modules/lucide-react/src/icons/x.ts","../src/ui-tailwind/chrome/tw-alert-banner.tsx","../src/ui-tailwind/chrome/tw-selection-toolbar.tsx","../node_modules/.pnpm/@radix-ui+react-tabs@1.1.13_@types+react-dom@19.2.3_@types+react@19.2.14__@types+react@_2ad0945e3cb98dc5bbfaaf29c105e977/node_modules/@radix-ui/react-tabs/src/tabs.tsx","../node_modules/.pnpm/@radix-ui+react-roving-focus@1.1.11_@types+react-dom@19.2.3_@types+react@19.2.14__@type_4eeb29c998b846c35358e2f929e7490e/node_modules/@radix-ui/react-roving-focus/src/roving-focus-group.tsx","../node_modules/.pnpm/@radix-ui+react-collection@1.1.7_@types+react-dom@19.2.3_@types+react@19.2.14__@types+r_161926fa2509d0b7370b60b8bb4eb8b0/node_modules/@radix-ui/react-collection/src/collection-legacy.tsx","../node_modules/.pnpm/@radix-ui+react-collection@1.1.7_@types+react-dom@19.2.3_@types+react@19.2.14__@types+r_161926fa2509d0b7370b60b8bb4eb8b0/node_modules/@radix-ui/react-collection/src/collection.tsx","../node_modules/.pnpm/@radix-ui+react-collection@1.1.7_@types+react-dom@19.2.3_@types+react@19.2.14__@types+r_161926fa2509d0b7370b60b8bb4eb8b0/node_modules/@radix-ui/react-collection/src/ordered-dictionary.ts","../node_modules/.pnpm/@radix-ui+react-direction@1.1.1_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-direction/src/direction.tsx","../node_modules/.pnpm/@radix-ui+react-scroll-area@1.2.10_@types+react-dom@19.2.3_@types+react@19.2.14__@types_155614c2fe5222bb9b221068b09efefc/node_modules/@radix-ui/react-scroll-area/src/scroll-area.tsx","../node_modules/.pnpm/@radix-ui+react-scroll-area@1.2.10_@types+react-dom@19.2.3_@types+react@19.2.14__@types_155614c2fe5222bb9b221068b09efefc/node_modules/@radix-ui/react-scroll-area/src/use-state-machine.ts","../node_modules/.pnpm/@radix-ui+number@1.1.1/node_modules/@radix-ui/number/src/number.ts","../src/ui-tailwind/review/tw-comment-sidebar.tsx","../src/ui/shared/revision-filters.ts","../src/ui-tailwind/review/tw-revision-sidebar.tsx","../src/ui-tailwind/review/tw-review-rail.tsx","../src/ui-tailwind/status/tw-status-bar.tsx","../node_modules/.pnpm/@radix-ui+react-popover@1.1.15_@types+react-dom@19.2.3_@types+react@19.2.14__@types+rea_8b5332f8e883134e9d9ab2856fc4395d/node_modules/@radix-ui/react-popover/src/popover.tsx","../node_modules/.pnpm/@radix-ui+react-focus-guards@1.1.3_@types+react@19.2.14_react@19.2.4/node_modules/@radix-ui/react-focus-guards/src/focus-guards.tsx","../node_modules/.pnpm/@radix-ui+react-focus-scope@1.1.7_@types+react-dom@19.2.3_@types+react@19.2.14__@types+_f62f3af4ca2ba305a7aecf04c8534604/node_modules/@radix-ui/react-focus-scope/src/focus-scope.tsx","../node_modules/.pnpm/aria-hidden@1.2.6/node_modules/aria-hidden/dist/es2015/index.js","../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs","../node_modules/.pnpm/react-remove-scroll@2.7.2_@types+react@19.2.14_react@19.2.4/node_modules/react-remove-scroll/dist/es2015/Combination.js","../node_modules/.pnpm/react-remove-scroll@2.7.2_@types+react@19.2.14_react@19.2.4/node_modules/react-remove-scroll/dist/es2015/UI.js","../node_modules/.pnpm/react-remove-scroll-bar@2.3.8_@types+react@19.2.14_react@19.2.4/node_modules/react-remove-scroll-bar/dist/es2015/constants.js","../node_modules/.pnpm/use-callback-ref@1.3.3_@types+react@19.2.14_react@19.2.4/node_modules/use-callback-ref/dist/es2015/assignRef.js","../node_modules/.pnpm/use-callback-ref@1.3.3_@types+react@19.2.14_react@19.2.4/node_modules/use-callback-ref/dist/es2015/useRef.js","../node_modules/.pnpm/use-callback-ref@1.3.3_@types+react@19.2.14_react@19.2.4/node_modules/use-callback-ref/dist/es2015/useMergeRef.js","../node_modules/.pnpm/use-sidecar@1.1.3_@types+react@19.2.14_react@19.2.4/node_modules/use-sidecar/dist/es2015/medium.js","../node_modules/.pnpm/use-sidecar@1.1.3_@types+react@19.2.14_react@19.2.4/node_modules/use-sidecar/dist/es2015/exports.js","../node_modules/.pnpm/react-remove-scroll@2.7.2_@types+react@19.2.14_react@19.2.4/node_modules/react-remove-scroll/dist/es2015/medium.js","../node_modules/.pnpm/react-remove-scroll@2.7.2_@types+react@19.2.14_react@19.2.4/node_modules/react-remove-scroll/dist/es2015/SideEffect.js","../node_modules/.pnpm/react-remove-scroll-bar@2.3.8_@types+react@19.2.14_react@19.2.4/node_modules/react-remove-scroll-bar/dist/es2015/component.js","../node_modules/.pnpm/react-style-singleton@2.2.3_@types+react@19.2.14_react@19.2.4/node_modules/react-style-singleton/dist/es2015/hook.js","../node_modules/.pnpm/get-nonce@1.0.1/node_modules/get-nonce/dist/es2015/index.js","../node_modules/.pnpm/react-style-singleton@2.2.3_@types+react@19.2.14_react@19.2.4/node_modules/react-style-singleton/dist/es2015/singleton.js","../node_modules/.pnpm/react-style-singleton@2.2.3_@types+react@19.2.14_react@19.2.4/node_modules/react-style-singleton/dist/es2015/component.js","../node_modules/.pnpm/react-remove-scroll-bar@2.3.8_@types+react@19.2.14_react@19.2.4/node_modules/react-remove-scroll-bar/dist/es2015/utils.js","../node_modules/.pnpm/react-remove-scroll@2.7.2_@types+react@19.2.14_react@19.2.4/node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js","../node_modules/.pnpm/react-remove-scroll@2.7.2_@types+react@19.2.14_react@19.2.4/node_modules/react-remove-scroll/dist/es2015/handleScroll.js","../node_modules/.pnpm/react-remove-scroll@2.7.2_@types+react@19.2.14_react@19.2.4/node_modules/react-remove-scroll/dist/es2015/sidecar.js","../node_modules/.pnpm/@radix-ui+react-toggle@1.1.10_@types+react-dom@19.2.3_@types+react@19.2.14__@types+reac_63d136f11f5f79b42c1373b9162ffc86/node_modules/@radix-ui/react-toggle/src/toggle.tsx","../node_modules/.pnpm/@radix-ui+react-toggle-group@1.1.11_@types+react-dom@19.2.3_@types+react@19.2.14__@type_0c124bdbaa351e80a671757a596f81ce/node_modules/@radix-ui/react-toggle-group/src/toggle-group.tsx","../src/ui-tailwind/review/tw-health-panel.tsx","../src/ui-tailwind/toolbar/tw-toolbar-icon-button.tsx","../src/ui-tailwind/toolbar/tw-toolbar.tsx","../src/ui-tailwind/tw-review-workspace.tsx"],"sourcesContent":["export { WordReviewEditor } from \"./ui/WordReviewEditor.tsx\";\nexport type {\n WordReviewEditorProps,\n WordReviewEditorRef,\n EditorUser,\n EditorDatastoreAdapter,\n ExternalDocumentSource,\n PersistedEditorSnapshot,\n CompatibilityReport,\n CompatibilityFeatureEntry,\n CompatibilityFeatureClass,\n CompatibilityPanelSnapshot,\n EditorWarning,\n EditorWarningCode,\n EditorError,\n EditorErrorCode,\n WordReviewEditorEvent,\n RuntimeRenderSnapshot,\n SelectionSnapshot,\n EditorAnchorProjection,\n DocumentStats,\n CommentSidebarSnapshot,\n CommentSidebarThreadSnapshot,\n CommentSidebarThreadEntrySnapshot,\n TrackedChangesSnapshot,\n TrackedChangeEntrySnapshot,\n AddCommentParams,\n ExportDocxOptions,\n ExportResult,\n AutosaveConfig,\n AutosaveState,\n EditorTelemetryEvent,\n LoadResult,\n SaveSnapshotParams,\n SaveSnapshotResult,\n SaveExportParams,\n SaveExportResult,\n SurfaceBlockSnapshot,\n SurfaceInlineSegment,\n SurfaceTableCellSnapshot,\n SurfaceTableRowSnapshot,\n SurfaceTextMark,\n EditorSurfaceSnapshot,\n CommandStateSnapshot,\n} from \"./api/public-types.ts\";\n","import React, {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\nimport type {\n AutosaveState,\n EditorDatastoreAdapter,\n CompatibilityReport,\n EditorError,\n EditorWarning,\n ExportDocxOptions,\n PersistedEditorSnapshot,\n RuntimeRenderSnapshot,\n SelectionSnapshot as PublicSelectionSnapshot,\n ExportResult,\n WordReviewEditorEvent,\n WordReviewEditorProps,\n WordReviewEditorRef,\n} from \"../api/public-types\";\nimport {\n createDetachedAnchor,\n createNodeAnchor,\n createRangeAnchor,\n} from \"../core/selection/mapping.ts\";\nimport { createCanonicalDocumentId } from \"../core/state/editor-state.ts\";\nimport {\n createDocumentRuntime,\n type DocumentRuntime,\n} from \"../runtime/document-runtime.ts\";\nimport { loadDocxEditorSession } from \"../io/docx-session.ts\";\nimport { exportSnapshotToMinimalDocx } from \"../io/export/minimal-docx.ts\";\nimport { DOCX_MIME_TYPE } from \"../io/opc/docx-package.ts\";\nimport { deriveCapabilities } from \"../runtime/session-capabilities\";\nimport { TwProseMirrorSurface } from \"../ui-tailwind/editor-surface/tw-prosemirror-surface\";\nimport { TwReviewWorkspace } from \"../ui-tailwind/tw-review-workspace\";\nimport type { ReviewRailTab } from \"../ui-tailwind/review/tw-review-rail\";\nimport type { ViewMode } from \"../ui-tailwind/toolbar/tw-toolbar\";\nimport type { MarkupDisplay } from \"./headless/comment-decoration-model\";\n\ninterface ResolvedSource {\n source: \"docx\" | \"snapshot\" | \"datastore\";\n sourceLabel?: string;\n initialDocx?: Uint8Array | ArrayBuffer;\n initialSnapshot?: PersistedEditorSnapshot;\n}\n\ninterface CreateRuntimeArgs {\n documentId: string;\n readOnly: boolean;\n source: ResolvedSource;\n datastore?: EditorDatastoreAdapter;\n currentUserId?: string;\n}\n\ninterface RuntimeLifecycleHandlers {\n onEvent?: (event: WordReviewEditorEvent) => void;\n onWarning?: (warning: EditorWarning) => void;\n onError?: (error: EditorError) => void;\n}\n\ninterface WordReviewEditorRuntime extends DocumentRuntime {\n getFatalError?(): EditorError | undefined;\n dispose?(): void;\n}\n\nexport function __createWordReviewEditorRefBridge(\n runtime: WordReviewEditorRuntime,\n): WordReviewEditorRef {\n return {\n focus: () => runtime.focus(),\n blur: () => runtime.blur(),\n undo: () => runtime.undo(),\n redo: () => runtime.redo(),\n addComment: (params) => runtime.addComment(params),\n openComment: (commentId) => runtime.openComment(commentId),\n resolveComment: (commentId) => runtime.resolveComment(commentId),\n reopenComment: (commentId) => runtime.reopenComment(commentId),\n addCommentReply: (commentId, body) => runtime.addCommentReply(commentId, body),\n editCommentBody: (commentId, body) => runtime.editCommentBody(commentId, body),\n acceptChange: (changeId) => runtime.acceptChange(changeId),\n rejectChange: (changeId) => runtime.rejectChange(changeId),\n acceptAllChanges: () => runtime.acceptAllChanges(),\n rejectAllChanges: () => runtime.rejectAllChanges(),\n exportDocx: (options) => runtime.exportDocx(options),\n getSnapshot: () => runtime.getPersistedSnapshot(),\n getCompatibilityReport: () => runtime.getCompatibilityReport(),\n getWarnings: () => runtime.getWarnings(),\n };\n}\n\nexport async function __resolveWordReviewEditorSource(\n props: Pick<\n WordReviewEditorProps,\n | \"documentId\"\n | \"datastore\"\n | \"externalDocSource\"\n | \"initialDocx\"\n | \"initialSnapshot\"\n | \"initialSourceLabel\"\n >,\n): Promise<ResolvedSource> {\n const explicitInitialCount =\n Number(Boolean(props.initialDocx)) + Number(Boolean(props.initialSnapshot));\n if (explicitInitialCount > 1) {\n throw new Error(\"Provide exactly one of initialDocx or initialSnapshot.\");\n }\n\n if (props.externalDocSource) {\n return props.externalDocSource.kind === \"docx\"\n ? {\n source: \"docx\",\n initialDocx: props.externalDocSource.bytes,\n sourceLabel: props.externalDocSource.sourceLabel,\n }\n : {\n source: \"snapshot\",\n initialSnapshot: props.externalDocSource.snapshot,\n sourceLabel: props.externalDocSource.sourceLabel,\n };\n }\n\n if (props.initialSnapshot) {\n return {\n source: \"snapshot\",\n initialSnapshot: props.initialSnapshot,\n sourceLabel: props.initialSourceLabel,\n };\n }\n\n if (props.initialDocx) {\n return {\n source: \"docx\",\n initialDocx: props.initialDocx,\n sourceLabel: props.initialSourceLabel,\n };\n }\n\n if (!props.datastore) {\n throw new Error(\n `WordReviewEditor ${props.documentId} needs initialDocx, initialSnapshot, or datastore.load().`,\n );\n }\n\n const loadResult = await props.datastore.load({\n documentId: props.documentId,\n });\n\n if (!loadResult.source) {\n throw new Error(`Datastore did not return a loadable source for ${props.documentId}.`);\n }\n\n return loadResult.source.kind === \"docx\"\n ? {\n source: \"datastore\",\n initialDocx: loadResult.source.bytes,\n sourceLabel: loadResult.source.sourceLabel,\n }\n : {\n source: \"datastore\",\n initialSnapshot: loadResult.source.snapshot,\n sourceLabel: loadResult.source.sourceLabel,\n };\n}\n\nexport function __createFallbackRuntime(args: CreateRuntimeArgs): WordReviewEditorRuntime {\n return createRuntime(args);\n}\n\nfunction createRuntime(\n args: CreateRuntimeArgs,\n handlers: RuntimeLifecycleHandlers = {},\n): WordReviewEditorRuntime {\n const docxSession = args.source.initialDocx\n ? loadDocxEditorSession({\n documentId: args.documentId,\n sourceLabel: args.source.sourceLabel,\n bytes: args.source.initialDocx,\n editorBuild: \"dev\",\n })\n : undefined;\n const initialSnapshot =\n args.source.initialSnapshot ??\n docxSession?.initialSnapshot ??\n createFallbackPersistedSnapshot(\n args.documentId,\n args.source.sourceLabel ?? \"Generated shell snapshot\",\n );\n\n return createDocumentRuntime({\n documentId: args.documentId,\n initialSnapshot,\n sourceKind: args.source.source,\n sourceLabel: args.source.sourceLabel,\n readOnly: args.readOnly || docxSession?.readOnly,\n editorBuild: initialSnapshot.editorBuild,\n fatalError: docxSession?.fatalError,\n exportDocx: async (snapshot, options) =>\n docxSession\n ? docxSession.exportDocx(snapshot, options)\n : {\n bytes: exportSnapshotToMinimalDocx(snapshot),\n mimeType: DOCX_MIME_TYPE,\n fileName: options?.fileName ?? `${args.documentId}.docx`,\n },\n onWarning: handlers.onWarning,\n onError: handlers.onError,\n defaultAuthorId: args.currentUserId,\n });\n}\n\nexport const WordReviewEditor = forwardRef<WordReviewEditorRef, WordReviewEditorProps>(\n function WordReviewEditor(props, ref) {\n const {\n currentUser,\n datastore,\n documentId,\n externalDocSource,\n externalDocumentRevision,\n initialDocx,\n initialSnapshot,\n initialSourceLabel,\n markupDisplay = \"simple\",\n onError,\n onEvent,\n onWarning,\n readOnly = false,\n reviewMode = \"review\",\n } = props;\n\n const [runtime, setRuntime] = useState<WordReviewEditorRuntime | null>(null);\n const [loadError, setLoadError] = useState<EditorError | null>(null);\n const [viewMode, setViewMode] = useState<ViewMode>(\"canvas\");\n const liveMarkupDisplay: MarkupDisplay = viewMode === \"document\" ? \"all\" : \"clean\";\n const [activeRailTab, setActiveRailTab] = useState<ReviewRailTab>(\"comments\");\n const [showTrackedChanges, setShowTrackedChanges] = useState(false);\n const [activeRevisionId, setActiveRevisionId] = useState<string | undefined>();\n const runtimeRef = useRef<WordReviewEditorRuntime | null>(null);\n const autosaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const lastSavedRevisionTokenRef = useRef<string | null>(null);\n const datastoreRef = useRef(datastore);\n const onEventRef = useRef(onEvent);\n const onWarningRef = useRef(onWarning);\n const onErrorRef = useRef(onError);\n const initialSourceRef = useRef<{\n documentId: string;\n initialDocx?: Uint8Array | ArrayBuffer;\n initialSnapshot?: PersistedEditorSnapshot;\n initialSourceLabel?: string;\n } | null>(null);\n\n if (!initialSourceRef.current || initialSourceRef.current.documentId !== documentId) {\n initialSourceRef.current = {\n documentId,\n initialDocx,\n initialSnapshot,\n initialSourceLabel,\n };\n }\n\n const stableInitialSource = initialSourceRef.current;\n const sourceReloadKey = externalDocSource\n ? `external:${externalDocSource.kind}:${externalDocumentRevision ?? \"static\"}`\n : stableInitialSource?.initialSnapshot\n ? \"initial-snapshot\"\n : stableInitialSource?.initialDocx\n ? \"initial-docx\"\n : \"datastore\";\n\n useEffect(() => {\n datastoreRef.current = datastore;\n onEventRef.current = onEvent;\n onWarningRef.current = onWarning;\n onErrorRef.current = onError;\n }, [datastore, onError, onEvent, onWarning]);\n\n useEffect(() => {\n let cancelled = false;\n\n async function loadRuntime(): Promise<void> {\n setLoadError(null);\n\n try {\n const source = await __resolveWordReviewEditorSource({\n documentId,\n datastore: datastoreRef.current,\n externalDocSource,\n initialDocx: stableInitialSource?.initialDocx,\n initialSnapshot: stableInitialSource?.initialSnapshot,\n initialSourceLabel: stableInitialSource?.initialSourceLabel,\n });\n\n if (cancelled) {\n return;\n }\n\n runtimeRef.current?.dispose?.();\n const nextRuntime = createRuntime(\n {\n documentId,\n readOnly,\n source,\n datastore: datastoreRef.current,\n currentUserId: currentUser.userId,\n },\n {\n onWarning: onWarningRef.current,\n onError: onErrorRef.current,\n },\n );\n emitEditorEvent({\n datastore: datastoreRef.current,\n onEvent: onEventRef.current,\n event: createReadyEvent(nextRuntime, source.source),\n });\n runtimeRef.current = nextRuntime;\n setRuntime(nextRuntime);\n } catch (error) {\n if (cancelled) {\n return;\n }\n\n const normalized = normalizeEditorError(error);\n setLoadError(normalized);\n onErrorRef.current?.(normalized);\n emitEditorEvent({\n datastore: datastoreRef.current,\n onEvent: onEventRef.current,\n event: {\n type: \"error\",\n documentId,\n error: normalized,\n },\n });\n }\n }\n\n void loadRuntime();\n\n return () => {\n cancelled = true;\n };\n }, [\n documentId,\n readOnly,\n sourceReloadKey,\n ]);\n\n useEffect(() => {\n if (!runtime?.subscribeToEvents) {\n return;\n }\n\n return runtime.subscribeToEvents((event) => {\n emitEditorEvent({\n datastore: datastoreRef.current,\n onEvent: onEventRef.current,\n event,\n });\n });\n }, [runtime]);\n\n useEffect(() => {\n return () => {\n if (autosaveTimerRef.current) {\n clearTimeout(autosaveTimerRef.current);\n autosaveTimerRef.current = null;\n }\n runtimeRef.current?.dispose?.();\n runtimeRef.current = null;\n };\n }, []);\n\n const optimisticRuntime = useMemo(\n () =>\n __createFallbackRuntime({\n documentId,\n readOnly,\n currentUserId: currentUser.userId,\n source: {\n source: \"snapshot\",\n initialSnapshot:\n initialSnapshot ?? createFallbackPersistedSnapshot(documentId, initialSourceLabel),\n sourceLabel: guessSourceLabel(initialSourceLabel, initialSnapshot, externalDocSource),\n },\n datastore: datastoreRef.current,\n }),\n [\n currentUser.userId,\n documentId,\n initialSnapshot,\n initialSourceLabel,\n readOnly,\n externalDocSource?.kind,\n externalDocSource?.sourceLabel,\n ],\n );\n\n const fallbackSnapshot = useMemo(\n () =>\n loadError\n ? createErrorSnapshot(documentId, loadError)\n : createLoadingSnapshot(\n documentId,\n readOnly,\n guessSourceLabel(initialSourceLabel, initialSnapshot, externalDocSource),\n ),\n [\n documentId,\n externalDocSource,\n initialSnapshot,\n initialSourceLabel,\n loadError,\n readOnly,\n ],\n );\n\n const snapshot = useSyncExternalStore(\n (listener) => runtime?.subscribe(listener) ?? (() => undefined),\n () => runtime?.getRenderSnapshot() ?? fallbackSnapshot,\n () => runtime?.getRenderSnapshot() ?? fallbackSnapshot,\n );\n\n const activeRuntime = runtime ?? optimisticRuntime;\n\n useImperativeHandle(\n ref,\n () => ({\n focus: () => activeRuntime.focus(),\n blur: () => activeRuntime.blur(),\n undo: () => activeRuntime.undo(),\n redo: () => activeRuntime.redo(),\n addComment: (params) =>\n activeRuntime.addComment({\n ...params,\n authorId: params.authorId ?? currentUser.userId,\n }),\n openComment: (commentId) => activeRuntime.openComment(commentId),\n resolveComment: (commentId) => activeRuntime.resolveComment(commentId),\n reopenComment: (commentId) => activeRuntime.reopenComment(commentId),\n addCommentReply: (commentId, body) =>\n activeRuntime.addCommentReply(commentId, body, currentUser.userId),\n editCommentBody: (commentId, body) =>\n activeRuntime.editCommentBody(commentId, body),\n acceptChange: (changeId) => activeRuntime.acceptChange(changeId),\n rejectChange: (changeId) => activeRuntime.rejectChange(changeId),\n acceptAllChanges: () => activeRuntime.acceptAllChanges(),\n rejectAllChanges: () => activeRuntime.rejectAllChanges(),\n exportDocx: (options) =>\n runtime\n ? persistAndExport({\n datastore: datastoreRef.current,\n documentId,\n runtime,\n onError: onErrorRef.current,\n onEvent: onEventRef.current,\n options,\n lastSavedRevisionTokenRef,\n autosaveTimerRef,\n })\n : rejectExportWhileLoading({\n documentId,\n datastore: datastoreRef.current,\n onError: onErrorRef.current,\n onEvent: onEventRef.current,\n }),\n getSnapshot: () => activeRuntime.getPersistedSnapshot(),\n getCompatibilityReport: () => activeRuntime.getCompatibilityReport(),\n getWarnings: () => activeRuntime.getWarnings(),\n }),\n [activeRuntime, currentUser.userId, documentId, runtime],\n );\n\n useEffect(() => {\n if (!datastoreRef.current || props.autosave?.enabled === false || !runtime || readOnly) {\n if (autosaveTimerRef.current) {\n clearTimeout(autosaveTimerRef.current);\n autosaveTimerRef.current = null;\n }\n return;\n }\n\n if (!snapshot.isReady || !snapshot.isDirty) {\n return;\n }\n\n if (lastSavedRevisionTokenRef.current === snapshot.revisionToken) {\n return;\n }\n\n if (autosaveTimerRef.current) {\n clearTimeout(autosaveTimerRef.current);\n }\n\n const debounceMs = props.autosave?.debounceMs ?? 800;\n if (debounceMs <= 0) {\n void persistSnapshot({\n datastore: datastoreRef.current,\n documentId,\n runtime,\n isAutosave: true,\n onError: onErrorRef.current,\n onEvent: onEventRef.current,\n lastSavedRevisionTokenRef,\n });\n return;\n }\n\n autosaveTimerRef.current = setTimeout(() => {\n void persistSnapshot({\n datastore: datastoreRef.current,\n documentId,\n runtime,\n isAutosave: true,\n onError: onErrorRef.current,\n onEvent: onEventRef.current,\n lastSavedRevisionTokenRef,\n });\n }, debounceMs);\n\n return () => {\n if (autosaveTimerRef.current) {\n clearTimeout(autosaveTimerRef.current);\n autosaveTimerRef.current = null;\n }\n };\n }, [\n documentId,\n props.autosave?.debounceMs,\n props.autosave?.enabled,\n readOnly,\n runtime,\n snapshot.isDirty,\n snapshot.isReady,\n snapshot.revisionToken,\n ]);\n\n // Auto-select the most relevant rail tab based on content.\n // Health tab was moved to toolbar popover — rail has only comments/changes.\n useEffect(() => {\n if (\n activeRailTab === \"comments\" &&\n snapshot.comments.totalCount === 0 &&\n snapshot.trackedChanges.totalCount > 0\n ) {\n setActiveRailTab(\"changes\");\n return;\n }\n }, [\n activeRailTab,\n loadError,\n snapshot.comments.totalCount,\n snapshot.compatibility.blockExport,\n snapshot.fatalError,\n snapshot.trackedChanges.totalCount,\n ]);\n\n function focusAnchor(anchor: PublicSelectionSnapshot[\"activeRange\"]): void {\n if (anchor.kind === \"detached\") {\n return;\n }\n\n activeRuntime.dispatch({\n type: \"selection.set\",\n selection: toRuntimeSelectionSnapshot(createSelectionFromAnchor(anchor)),\n });\n }\n\n function addReviewComment(): void {\n activeRuntime.addComment({\n anchor: snapshot.selection.activeRange,\n body: \"New review comment\",\n authorId: currentUser.userId,\n });\n setActiveRailTab(\"comments\");\n }\n\n function exportCurrentDocument(): void {\n void (runtime\n ? persistAndExport({\n datastore: datastoreRef.current,\n documentId,\n runtime,\n onError: onErrorRef.current,\n onEvent: onEventRef.current,\n lastSavedRevisionTokenRef,\n autosaveTimerRef,\n })\n : rejectExportWhileLoading({\n documentId,\n datastore: datastoreRef.current,\n onError: onErrorRef.current,\n onEvent: onEventRef.current,\n }));\n }\n\n const selectionPreview = summarizeSelectionPreview(snapshot);\n const capabilities = deriveCapabilities(snapshot, reviewMode);\n\n const dispatchSelection = (selection: PublicSelectionSnapshot) =>\n activeRuntime.dispatch({\n type: \"selection.set\",\n selection: toRuntimeSelectionSnapshot(selection),\n });\n\n const editorCallbacks = {\n onFocus: () => activeRuntime.focus(),\n onBlur: () => activeRuntime.blur(),\n onSelectionChange: dispatchSelection,\n onInsertText: (text: string) => activeRuntime.dispatch({ type: \"text.insert\", text }),\n onDeleteBackward: () => activeRuntime.dispatch({ type: \"text.delete-backward\" }),\n onDeleteForward: () => activeRuntime.dispatch({ type: \"text.delete-forward\" }),\n onInsertTab: () => activeRuntime.dispatch({ type: \"text.insert-tab\" }),\n onInsertHardBreak: () => activeRuntime.dispatch({ type: \"text.insert-hard-break\" }),\n onSplitParagraph: () => activeRuntime.dispatch({ type: \"paragraph.split\" }),\n };\n\n const reviewCallbacks = {\n onUndo: () => activeRuntime.undo(),\n onRedo: () => activeRuntime.redo(),\n onAddComment: addReviewComment,\n onExport: exportCurrentDocument,\n onOpenComment: (thread: typeof snapshot.comments.threads[number]) => {\n activeRuntime.openComment(thread.commentId);\n focusAnchor(thread.anchor);\n setActiveRailTab(\"comments\");\n },\n onResolveComment: (commentId: string) => {\n activeRuntime.resolveComment(commentId);\n setActiveRailTab(\"comments\");\n },\n onReopenComment: (commentId: string) => {\n activeRuntime.reopenComment(commentId);\n setActiveRailTab(\"comments\");\n },\n onAddReply: (commentId: string, body: string) => {\n activeRuntime.addCommentReply(commentId, body, currentUser.userId);\n },\n onEditBody: (commentId: string, body: string) => {\n activeRuntime.editCommentBody(commentId, body);\n },\n onOpenRevision: (revision: typeof snapshot.trackedChanges.revisions[number]) => {\n setActiveRevisionId(revision.revisionId);\n focusAnchor(revision.anchor);\n setActiveRailTab(\"changes\");\n },\n onAcceptRevision: (revisionId: string) => {\n activeRuntime.acceptChange(revisionId);\n setActiveRailTab(\"changes\");\n },\n onRejectRevision: (revisionId: string) => {\n activeRuntime.rejectChange(revisionId);\n setActiveRailTab(\"changes\");\n },\n onAcceptAllChanges: () => {\n activeRuntime.acceptAllChanges();\n setActiveRailTab(\"changes\");\n },\n onRejectAllChanges: () => {\n activeRuntime.rejectAllChanges();\n setActiveRailTab(\"changes\");\n },\n };\n\n return (\n <TwReviewWorkspace\n snapshot={snapshot}\n currentUserId={currentUser.userId}\n capabilities={capabilities}\n reviewMode={reviewMode}\n viewMode={viewMode}\n activeRailTab={activeRailTab}\n activeCommentId={snapshot.comments.activeCommentId}\n activeRevisionId={activeRevisionId}\n showTrackedChanges={showTrackedChanges}\n selectionPreview={selectionPreview}\n onViewModeChange={setViewMode}\n onActiveRailTabChange={setActiveRailTab}\n onShowTrackedChangesChange={setShowTrackedChanges}\n {...reviewCallbacks}\n document={\n <TwProseMirrorSurface\n currentUser={currentUser}\n snapshot={snapshot}\n reviewMode={reviewMode}\n markupDisplay={liveMarkupDisplay}\n activeRevisionId={activeRevisionId}\n showTrackedChanges={showTrackedChanges}\n {...editorCallbacks}\n onCommentActivated={(commentId) => {\n activeRuntime.openComment(commentId);\n setActiveRailTab(\"comments\");\n }}\n onRevisionActivated={(revisionId) => {\n setActiveRevisionId(revisionId);\n setActiveRailTab(\"changes\");\n }}\n />\n }\n />\n );\n },\n);\n\nfunction normalizeEditorError(error: unknown): EditorError {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"errorId\" in error &&\n \"code\" in error &&\n \"message\" in error\n ) {\n return error as EditorError;\n }\n\n return {\n errorId: \"word-review-editor-load\",\n code: \"internal_invariant\",\n message: error instanceof Error ? error.message : \"Unknown editor load failure.\",\n isFatal: true,\n source: \"runtime\",\n };\n}\n\nfunction guessSourceLabel(\n initialSourceLabel?: string,\n initialSnapshot?: PersistedEditorSnapshot,\n externalDocSource?: WordReviewEditorProps[\"externalDocSource\"],\n): string | undefined {\n return (\n externalDocSource?.sourceLabel ??\n initialSourceLabel ??\n initialSnapshot?.editorBuild ??\n undefined\n );\n}\n\nfunction createLoadingSnapshot(\n documentId: string,\n readOnly: boolean,\n sourceLabel?: string,\n): RuntimeRenderSnapshot {\n return {\n documentId,\n sessionId: `${documentId}-loading`,\n sourceLabel,\n revisionToken: `${documentId}:loading`,\n isReady: false,\n isDirty: false,\n readOnly,\n selection: collapsedSelection(),\n documentStats: {\n storyLength: 0,\n commentCount: 0,\n revisionCount: 0,\n opaqueFragmentCount: 0,\n },\n comments: {\n openCommentIds: [],\n resolvedCommentIds: [],\n detachedCommentIds: [],\n totalCount: 0,\n threads: [],\n },\n trackedChanges: {\n pendingChangeIds: [],\n acceptedChangeIds: [],\n rejectedChangeIds: [],\n detachedChangeIds: [],\n actionableChangeIds: [],\n preserveOnlyChangeIds: [],\n totalCount: 0,\n revisions: [],\n },\n compatibility: {\n blockExport: false,\n blockExportReasons: [],\n warningCount: 0,\n errorCount: 0,\n featureEntries: [],\n },\n warnings: [],\n commandState: {\n canUndo: false,\n canRedo: false,\n readOnly,\n },\n };\n}\n\nfunction createErrorSnapshot(documentId: string, error: EditorError): RuntimeRenderSnapshot {\n return {\n ...createLoadingSnapshot(documentId, true),\n isReady: true,\n sessionId: `${documentId}-error`,\n revisionToken: `${documentId}:error`,\n compatibility: {\n blockExport: true,\n blockExportReasons: [error.message],\n warningCount: 0,\n errorCount: 1,\n featureEntries: [],\n },\n fatalError: error,\n };\n}\n\nasync function persistAndExport(input: {\n datastore?: EditorDatastoreAdapter;\n documentId: string;\n runtime: WordReviewEditorRuntime;\n onError?: (error: EditorError) => void;\n onEvent?: (event: WordReviewEditorEvent) => void;\n options?: ExportDocxOptions;\n lastSavedRevisionTokenRef: React.MutableRefObject<string | null>;\n autosaveTimerRef: React.MutableRefObject<ReturnType<typeof setTimeout> | null>;\n}): Promise<ExportResult> {\n if (input.autosaveTimerRef.current) {\n clearTimeout(input.autosaveTimerRef.current);\n input.autosaveTimerRef.current = null;\n }\n\n await persistSnapshot({\n datastore: input.datastore,\n documentId: input.documentId,\n runtime: input.runtime,\n isAutosave: false,\n onError: input.onError,\n onEvent: input.onEvent,\n lastSavedRevisionTokenRef: input.lastSavedRevisionTokenRef,\n });\n\n const result = await input.runtime.exportDocx(input.options);\n\n if (!input.datastore) {\n return result;\n }\n\n try {\n await input.datastore.saveExport({\n documentId: input.documentId,\n result,\n });\n } catch (error) {\n const normalized = normalizeDatastoreError(error, {\n message: \"Export persisted bytes could not be stored.\",\n details: {\n operation: \"saveExport\",\n },\n });\n input.onError?.(normalized);\n emitEditorEvent({\n datastore: input.datastore,\n onEvent: input.onEvent,\n event: {\n type: \"error\",\n documentId: input.documentId,\n error: normalized,\n },\n });\n }\n\n return result;\n}\n\nfunction rejectExportWhileLoading(input: {\n documentId: string;\n datastore?: EditorDatastoreAdapter;\n onError?: (error: EditorError) => void;\n onEvent?: (event: WordReviewEditorEvent) => void;\n}): Promise<never> {\n const error: EditorError = {\n errorId: \"word-review-editor-loading-export\",\n code: \"internal_invariant\",\n message: \"WordReviewEditor is still loading and cannot export yet.\",\n isFatal: false,\n source: \"runtime\",\n };\n input.onError?.(error);\n emitEditorEvent({\n datastore: input.datastore,\n onEvent: input.onEvent,\n event: {\n type: \"error\",\n documentId: input.documentId,\n error,\n },\n });\n return Promise.reject(error);\n}\n\nasync function persistSnapshot(input: {\n datastore?: EditorDatastoreAdapter;\n documentId: string;\n runtime: WordReviewEditorRuntime;\n isAutosave: boolean;\n onError?: (error: EditorError) => void;\n onEvent?: (event: WordReviewEditorEvent) => void;\n lastSavedRevisionTokenRef: React.MutableRefObject<string | null>;\n}): Promise<void> {\n if (!input.datastore) {\n return;\n }\n\n const snapshot = input.runtime.getPersistedSnapshot();\n const revisionToken = input.runtime.getRenderSnapshot().revisionToken;\n\n if (input.isAutosave) {\n emitEditorEvent({\n datastore: input.datastore,\n onEvent: input.onEvent,\n event: {\n type: \"autosave_state\",\n documentId: input.documentId,\n state: {\n status: \"saving\",\n } satisfies AutosaveState,\n },\n });\n }\n\n try {\n const result = await input.datastore.saveSnapshot({\n documentId: input.documentId,\n snapshot,\n isAutosave: input.isAutosave,\n });\n const savedSnapshot: PersistedEditorSnapshot = {\n ...snapshot,\n savedAt: result.savedAt,\n };\n input.lastSavedRevisionTokenRef.current = revisionToken;\n emitEditorEvent({\n datastore: input.datastore,\n onEvent: input.onEvent,\n event: {\n type: \"snapshot_saved\",\n documentId: input.documentId,\n snapshot: savedSnapshot,\n isAutosave: input.isAutosave,\n },\n });\n if (input.isAutosave) {\n emitEditorEvent({\n datastore: input.datastore,\n onEvent: input.onEvent,\n event: {\n type: \"autosave_state\",\n documentId: input.documentId,\n state: {\n status: \"saved\",\n savedAt: result.savedAt,\n } satisfies AutosaveState,\n },\n });\n }\n } catch (error) {\n const normalized = normalizeDatastoreError(error, {\n message: input.isAutosave\n ? \"Autosave failed while storing the editor snapshot.\"\n : \"Snapshot save failed while preparing the export checkpoint.\",\n details: {\n operation: \"saveSnapshot\",\n isAutosave: input.isAutosave,\n },\n });\n input.onError?.(normalized);\n emitEditorEvent({\n datastore: input.datastore,\n onEvent: input.onEvent,\n event: {\n type: \"error\",\n documentId: input.documentId,\n error: normalized,\n },\n });\n if (input.isAutosave) {\n emitEditorEvent({\n datastore: input.datastore,\n onEvent: input.onEvent,\n event: {\n type: \"autosave_state\",\n documentId: input.documentId,\n state: {\n status: \"error\",\n error: normalized,\n } satisfies AutosaveState,\n },\n });\n }\n if (!input.isAutosave) {\n throw normalized;\n }\n }\n}\n\nfunction emitEditorEvent(input: {\n datastore?: EditorDatastoreAdapter;\n onEvent?: (event: WordReviewEditorEvent) => void;\n event: WordReviewEditorEvent;\n}): void {\n input.onEvent?.(input.event);\n input.datastore?.logEvent?.({\n type: input.event.type,\n documentId: input.event.documentId,\n detail: summarizeEventDetail(input.event),\n });\n}\n\nfunction summarizeEventDetail(\n event: WordReviewEditorEvent,\n): Record<string, unknown> | undefined {\n switch (event.type) {\n case \"dirty_changed\":\n return { isDirty: event.isDirty };\n case \"comment_added\":\n return { commentId: event.commentId };\n case \"comment_resolved\":\n return { commentId: event.commentId };\n case \"change_accepted\":\n case \"change_rejected\":\n return { changeId: event.changeId };\n case \"warning_added\":\n return { warningId: event.warning.warningId, code: event.warning.code };\n case \"warning_cleared\":\n return { warningId: event.warningId, code: event.code };\n case \"error\":\n return { errorId: event.error.errorId, code: event.error.code };\n case \"autosave_state\":\n return { status: event.state.status };\n case \"snapshot_saved\":\n return { isAutosave: event.isAutosave, savedAt: event.snapshot.savedAt };\n case \"export_completed\":\n return { fileName: event.result.fileName };\n case \"selection_changed\":\n return {\n anchor: event.selection.anchor,\n head: event.selection.head,\n };\n case \"ready\":\n return {\n source: event.source,\n blockExport: event.compatibility.blockExport,\n };\n }\n}\n\nfunction createReadyEvent(\n runtime: Pick<WordReviewEditorRuntime, \"getCompatibilityReport\" | \"getRenderSnapshot\">,\n source: \"docx\" | \"snapshot\" | \"datastore\" | \"canonical\",\n): Extract<WordReviewEditorEvent, { type: \"ready\" }> {\n const snapshot = runtime.getRenderSnapshot();\n return {\n type: \"ready\",\n documentId: snapshot.documentId,\n sessionId: snapshot.sessionId,\n source,\n stats: snapshot.documentStats,\n compatibility: runtime.getCompatibilityReport(),\n };\n}\n\nfunction normalizeDatastoreError(\n error: unknown,\n fallback: {\n message: string;\n details?: Record<string, unknown>;\n },\n): EditorError {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"errorId\" in error &&\n \"code\" in error &&\n \"message\" in error\n ) {\n return error as EditorError;\n }\n\n return {\n errorId: \"word-review-editor-datastore\",\n code: \"datastore_failed\",\n message: error instanceof Error ? error.message : fallback.message,\n isFatal: false,\n source: \"datastore\",\n details: fallback.details,\n };\n}\n\nfunction createFallbackSnapshot(args: CreateRuntimeArgs): RuntimeRenderSnapshot {\n const warnings = args.source.initialSnapshot?.warningLog ?? [];\n const compatibility = args.source.initialSnapshot?.compatibility ?? emptyCompatibilityReport();\n\n return {\n ...createLoadingSnapshot(args.documentId, args.readOnly, args.source.sourceLabel),\n sessionId: `${args.documentId}-session`,\n revisionToken: `${args.documentId}:0`,\n isReady: true,\n documentStats: {\n storyLength: estimateStoryLength(args.source.initialSnapshot),\n commentCount: 0,\n revisionCount: 0,\n opaqueFragmentCount: 0,\n },\n compatibility: {\n blockExport: compatibility.blockExport,\n blockExportReasons: [],\n warningCount: compatibility.warnings.length,\n errorCount: compatibility.errors.length,\n featureEntries: compatibility.featureEntries,\n },\n warnings,\n };\n}\n\nfunction createFallbackPersistedSnapshot(\n documentId: string,\n label = \"Generated shell snapshot\",\n): PersistedEditorSnapshot {\n const docId = createCanonicalDocumentId(documentId);\n return {\n snapshotVersion: \"persisted-editor-snapshot/1\",\n schemaVersion: \"cds/1.0.0\",\n documentId,\n docId,\n createdAt: \"1970-01-01T00:00:00.000Z\",\n updatedAt: \"1970-01-01T00:00:00.000Z\",\n savedAt: \"1970-01-01T00:00:00.000Z\",\n editorBuild: label,\n canonicalDocument: {\n schemaVersion: \"cds/1.0.0\",\n docId,\n createdAt: \"1970-01-01T00:00:00.000Z\",\n updatedAt: \"1970-01-01T00:00:00.000Z\",\n metadata: {\n customProperties: {},\n },\n styles: {\n paragraphs: {},\n characters: {},\n tables: {},\n },\n numbering: {\n abstractDefinitions: {},\n instances: {},\n },\n media: {\n items: {},\n },\n content: {\n type: \"doc\",\n children: [{ type: \"paragraph\", children: [] }],\n },\n review: {\n comments: {},\n revisions: {},\n },\n preservation: {\n opaqueFragments: {},\n packageParts: {},\n },\n diagnostics: {\n warnings: [],\n errors: [],\n },\n },\n compatibility: emptyCompatibilityReport(),\n warningLog: [],\n };\n}\n\nfunction emptyCompatibilityReport(): CompatibilityReport {\n return {\n reportVersion: \"compatibility-report/1\",\n generatedAt: \"1970-01-01T00:00:00.000Z\",\n blockExport: false,\n featureEntries: [],\n warnings: [],\n errors: [],\n };\n}\n\nfunction toRuntimeSelectionSnapshot(selection: PublicSelectionSnapshot) {\n return {\n anchor: selection.anchor,\n head: selection.head,\n isCollapsed: selection.isCollapsed,\n activeRange:\n selection.activeRange.kind === \"range\"\n ? createRangeAnchor(\n selection.activeRange.from,\n selection.activeRange.to,\n selection.activeRange.assoc,\n )\n : selection.activeRange.kind === \"node\"\n ? createNodeAnchor(selection.activeRange.at, selection.activeRange.assoc)\n : createDetachedAnchor(\n selection.activeRange.lastKnownRange,\n selection.activeRange.reason,\n ),\n };\n}\n\nfunction createSelectionFromAnchor(\n anchor: PublicSelectionSnapshot[\"activeRange\"],\n): PublicSelectionSnapshot {\n switch (anchor.kind) {\n case \"range\":\n return {\n anchor: anchor.from,\n head: anchor.to,\n isCollapsed: anchor.from === anchor.to,\n activeRange: anchor,\n };\n case \"node\":\n return {\n anchor: anchor.at,\n head: anchor.at,\n isCollapsed: true,\n activeRange: anchor,\n };\n case \"detached\":\n return {\n anchor: anchor.lastKnownRange.from,\n head: anchor.lastKnownRange.to,\n isCollapsed: anchor.lastKnownRange.from === anchor.lastKnownRange.to,\n activeRange: anchor,\n };\n }\n}\n\nfunction estimateStoryLength(snapshot?: PersistedEditorSnapshot): number {\n const content = snapshot?.canonicalDocument.content;\n return Array.isArray(content) ? content.length : 0;\n}\n\nfunction collapsedSelection(): RuntimeRenderSnapshot[\"selection\"] {\n return {\n anchor: 0,\n head: 0,\n isCollapsed: true,\n activeRange: {\n kind: \"range\",\n from: 0,\n to: 0,\n assoc: {\n start: -1,\n end: 1,\n },\n },\n };\n}\n\nfunction toUint8Array(bytes: Uint8Array | ArrayBuffer): Uint8Array {\n return bytes instanceof Uint8Array ? new Uint8Array(bytes) : new Uint8Array(bytes);\n}\n\nfunction summarizeSelectionPreview(snapshot: RuntimeRenderSnapshot): string | null {\n if (!snapshot.surface || snapshot.selection.isCollapsed) {\n return null;\n }\n\n const range = snapshot.selection.activeRange;\n if (range.kind !== \"range\") {\n return \"Selected range\";\n }\n\n const preview = snapshot.surface.plainText\n .slice(range.from, range.to)\n .replace(/\\s+/g, \" \")\n .trim();\n\n if (!preview) {\n return \"Selected range\";\n }\n\n return preview.length > 48 ? `${preview.slice(0, 45)}...` : preview;\n}\n","export type Position = number;\nexport type Assoc = -1 | 1;\n\nexport interface DocRange {\n from: Position;\n to: Position;\n}\n\nexport interface BoundaryAssoc {\n start: Assoc;\n end: Assoc;\n}\n\nexport interface RangeAnchor {\n kind: \"range\";\n range: DocRange;\n assoc: BoundaryAssoc;\n}\n\nexport interface NodeAnchor {\n kind: \"node\";\n at: Position;\n assoc: Assoc;\n}\n\nexport interface DetachedAnchor {\n kind: \"detached\";\n lastKnownRange: DocRange;\n reason: \"deleted\" | \"invalidatedByStructureChange\" | \"importAmbiguity\";\n}\n\nexport type EditorAnchorProjection = RangeAnchor | NodeAnchor | DetachedAnchor;\n\nexport interface MappingStep {\n from: Position;\n to: Position;\n insertSize: number;\n}\n\nexport interface MappingResult {\n position: Position;\n deleted: boolean;\n}\n\nexport interface TransactionMapping {\n steps: MappingStep[];\n metadata?: {\n invalidatesStructures?: boolean;\n affectsComments?: boolean;\n affectsRevisions?: boolean;\n affectsOpaqueFragments?: boolean;\n [key: string]: unknown;\n };\n}\n\nexport const DEFAULT_BOUNDARY_ASSOC: BoundaryAssoc = {\n start: 1,\n end: -1,\n};\n\nexport function createRangeAnchor(\n from: Position,\n to = from,\n assoc: BoundaryAssoc = DEFAULT_BOUNDARY_ASSOC,\n): RangeAnchor {\n return {\n kind: \"range\",\n range: normalizeRange({ from, to }),\n assoc,\n };\n}\n\nexport function createNodeAnchor(at: Position, assoc: Assoc = 1): NodeAnchor {\n return {\n kind: \"node\",\n at,\n assoc,\n };\n}\n\nexport function createDetachedAnchor(\n lastKnownRange: DocRange,\n reason: DetachedAnchor[\"reason\"],\n): DetachedAnchor {\n return {\n kind: \"detached\",\n lastKnownRange: normalizeRange(lastKnownRange),\n reason,\n };\n}\n\nexport function createEmptyMapping(): TransactionMapping {\n return {\n steps: [],\n };\n}\n\nexport function normalizeRange(range: DocRange): DocRange {\n return range.from <= range.to\n ? { from: range.from, to: range.to }\n : { from: range.to, to: range.from };\n}\n\nexport function mapPosition(\n position: Position,\n assoc: Assoc,\n mapping: TransactionMapping,\n): MappingResult {\n let mappedPosition = position;\n let deleted = false;\n\n for (const step of mapping.steps) {\n const next = mapPositionThroughStep(mappedPosition, assoc, step);\n mappedPosition = next.position;\n deleted = deleted || next.deleted;\n }\n\n return {\n position: mappedPosition,\n deleted,\n };\n}\n\nexport function mapAnchor(\n anchor: EditorAnchorProjection,\n mapping: TransactionMapping,\n): EditorAnchorProjection {\n if (anchor.kind === \"detached\") {\n return anchor;\n }\n\n if (anchor.kind === \"node\") {\n const mapped = mapPosition(anchor.at, anchor.assoc, mapping);\n\n if (mapped.deleted) {\n return createDetachedAnchor(\n { from: anchor.at, to: anchor.at + 1 },\n mapping.metadata?.invalidatesStructures\n ? \"invalidatedByStructureChange\"\n : \"deleted\",\n );\n }\n\n return createNodeAnchor(mapped.position, anchor.assoc);\n }\n\n const from = mapPosition(anchor.range.from, anchor.assoc.start, mapping);\n const to = mapPosition(anchor.range.to, anchor.assoc.end, mapping);\n const mappedRange = normalizeRange({ from: from.position, to: to.position });\n\n if (from.deleted && to.deleted && mappedRange.from === mappedRange.to) {\n return createDetachedAnchor(\n anchor.range,\n mapping.metadata?.invalidatesStructures\n ? \"invalidatedByStructureChange\"\n : \"deleted\",\n );\n }\n\n return createRangeAnchor(mappedRange.from, mappedRange.to, anchor.assoc);\n}\n\nexport function mapRange(\n range: DocRange,\n assoc: BoundaryAssoc,\n mapping: TransactionMapping,\n): RangeAnchor | DetachedAnchor {\n const mapped = mapAnchor(createRangeAnchor(range.from, range.to, assoc), mapping);\n return mapped.kind === \"node\" ? createRangeAnchor(mapped.at, mapped.at, assoc) : mapped;\n}\n\nexport function areAnchorsEqual(\n left: EditorAnchorProjection,\n right: EditorAnchorProjection,\n): boolean {\n if (left.kind !== right.kind) {\n return false;\n }\n\n if (left.kind === \"detached\" && right.kind === \"detached\") {\n return (\n left.reason === right.reason &&\n left.lastKnownRange.from === right.lastKnownRange.from &&\n left.lastKnownRange.to === right.lastKnownRange.to\n );\n }\n\n if (left.kind === \"node\" && right.kind === \"node\") {\n return left.at === right.at && left.assoc === right.assoc;\n }\n\n if (left.kind === \"range\" && right.kind === \"range\") {\n return (\n left.range.from === right.range.from &&\n left.range.to === right.range.to &&\n left.assoc.start === right.assoc.start &&\n left.assoc.end === right.assoc.end\n );\n }\n\n return false;\n}\n\nfunction mapPositionThroughStep(\n position: Position,\n assoc: Assoc,\n step: MappingStep,\n): MappingResult {\n if (position < step.from) {\n return { position, deleted: false };\n }\n\n if (position > step.to) {\n return {\n position: position + step.insertSize - (step.to - step.from),\n deleted: false,\n };\n }\n\n if (position === step.from) {\n return {\n position: assoc < 0 ? step.from : step.from + step.insertSize,\n deleted: false,\n };\n }\n\n if (position === step.to) {\n return {\n position: assoc < 0 ? step.from : step.from + step.insertSize,\n deleted: false,\n };\n }\n\n return {\n position: assoc < 0 ? step.from : step.from + step.insertSize,\n deleted: true,\n };\n}\n","export const CDS_SCHEMA_VERSION = \"cds/1.0.0\" as const;\nexport const PERSISTED_EDITOR_SNAPSHOT_VERSION =\n \"persisted-editor-snapshot/1\" as const;\nexport const COMPATIBILITY_REPORT_VERSION = \"compatibility-report/1\" as const;\n\nexport type CDS_SchemaVersion = typeof CDS_SCHEMA_VERSION;\nexport type PersistedEditorSnapshotVersion =\n typeof PERSISTED_EDITOR_SNAPSHOT_VERSION;\nexport type CompatibilityReportVersion = typeof COMPATIBILITY_REPORT_VERSION;\n\nexport type Id = string;\nexport type UUID = string;\nexport type ISO8601DateTime = string;\nexport type Base64 = string;\nexport type PartName = string;\nexport type RelationshipId = string;\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\n\nexport interface JsonObject {\n [key: string]: JsonValue | undefined;\n}\n\nexport interface ModelValidationIssue {\n path: string;\n message: string;\n}\n\nexport class ModelValidationError extends Error {\n readonly issues: readonly ModelValidationIssue[];\n\n constructor(message: string, issues: readonly ModelValidationIssue[]) {\n super(message);\n this.name = \"ModelValidationError\";\n this.issues = issues;\n }\n}\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst ISO_8601_UTC_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{3})?Z$/;\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nexport function isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nexport function isUuid(value: unknown): value is UUID {\n return typeof value === \"string\" && UUID_PATTERN.test(value);\n}\n\nexport function isIso8601UtcTimestamp(\n value: unknown,\n): value is ISO8601DateTime {\n return (\n typeof value === \"string\" &&\n ISO_8601_UTC_PATTERN.test(value) &&\n !Number.isNaN(Date.parse(value))\n );\n}\n\nexport function asPlainObject(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): Record<string, unknown> | null {\n if (!isPlainObject(value)) {\n issues.push({ path, message: \"Expected a plain object.\" });\n return null;\n }\n\n return value;\n}\n\nexport function expectString(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): string | null {\n if (!isNonEmptyString(value)) {\n issues.push({ path, message: \"Expected a non-empty string.\" });\n return null;\n }\n\n return value;\n}\n\nexport function expectExactString<T extends string>(\n value: unknown,\n expected: T,\n path: string,\n issues: ModelValidationIssue[],\n): T | null {\n if (value !== expected) {\n issues.push({\n path,\n message: `Expected ${JSON.stringify(expected)}.`,\n });\n return null;\n }\n\n return expected;\n}\n\nexport function expectIso8601UtcTimestamp(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): ISO8601DateTime | null {\n if (!isIso8601UtcTimestamp(value)) {\n issues.push({\n path,\n message: \"Expected an ISO 8601 UTC timestamp string.\",\n });\n return null;\n }\n\n return value;\n}\n\nexport function expectUuid(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): UUID | null {\n if (!isUuid(value)) {\n issues.push({\n path,\n message: \"Expected an RFC 4122 UUID string.\",\n });\n return null;\n }\n\n return value;\n}\n\nexport function sortRecordKeys<T>(\n record: Record<string, T>,\n): Array<[string, T]> {\n return Object.entries(record).sort(([left], [right]) =>\n left.localeCompare(right),\n );\n}\n\nexport function assertValid(\n issues: readonly ModelValidationIssue[],\n message: string,\n): void {\n if (issues.length > 0) {\n throw new ModelValidationError(message, issues);\n }\n}\n\nfunction toStableJsonValue(value: unknown): JsonValue {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => toStableJsonValue(item));\n }\n\n if (!isPlainObject(value)) {\n throw new TypeError(\"Cannot serialize non-JSON value.\");\n }\n\n const sortedEntries = sortRecordKeys(value).filter(\n ([, entryValue]) => entryValue !== undefined,\n );\n const result: JsonObject = {};\n\n for (const [key, entryValue] of sortedEntries) {\n result[key] = toStableJsonValue(entryValue);\n }\n\n return result;\n}\n\nexport function stableStringify(value: unknown): string {\n return JSON.stringify(toStableJsonValue(value));\n}\n","import {\n CDS_SCHEMA_VERSION,\n type ISO8601DateTime,\n type ModelValidationIssue,\n type UUID,\n asPlainObject,\n assertValid,\n expectExactString,\n expectIso8601UtcTimestamp,\n expectString,\n expectUuid,\n stableStringify,\n} from \"./cds-1.0.0.ts\";\n\nconst CANONICAL_DOCUMENT_TOP_LEVEL_KEYS = [\n \"schemaVersion\",\n \"docId\",\n \"createdAt\",\n \"updatedAt\",\n \"metadata\",\n \"styles\",\n \"numbering\",\n \"media\",\n \"content\",\n \"review\",\n \"preservation\",\n \"diagnostics\",\n] as const;\n\nconst CANONICAL_DOCUMENT_OPTIONAL_KEYS = [\"subParts\"] as const;\n\nconst ID_PATTERNS = {\n styleId: /^[A-Za-z_][A-Za-z0-9._-]{0,127}$/,\n abstractNumberingId: /^abstract-num:[A-Za-z0-9._-]{1,120}$/,\n numberingInstanceId: /^num:[A-Za-z0-9._-]{1,120}$/,\n mediaId: /^media:[A-Za-z0-9._/-]{1,120}$/,\n commentId:\n /^(?:comment:[A-Za-z0-9._-]{1,120}|comment-[A-Za-z0-9._-]{1,120}|[0-9]{1,18})$/,\n revisionId:\n /^(?:revision:[A-Za-z0-9._-]{1,120}|change-[A-Za-z0-9._-]{1,120})$/,\n fragmentId: /^fragment:[A-Za-z0-9._-]{1,120}$/,\n warningId: /^warning:[A-Za-z0-9._:-]{1,120}$/,\n diagnosticId: /^diagnostic:[A-Za-z0-9._-]{1,120}$/,\n packagePartName: /^\\/[A-Za-z0-9_.\\-\\/]+\\.[A-Za-z0-9]+$/,\n relationshipId: /^rId[A-Za-z0-9._-]{1,120}$/,\n} as const;\n\ntype StableIdDomain = keyof typeof ID_PATTERNS;\n\nexport interface CanonicalDocument {\n schemaVersion: typeof CDS_SCHEMA_VERSION;\n docId: UUID;\n createdAt: ISO8601DateTime;\n updatedAt: ISO8601DateTime;\n metadata: DocumentMetadata;\n styles: StylesCatalog;\n numbering: NumberingCatalog;\n media: MediaCatalog;\n content: DocumentNode;\n review: ReviewStore;\n preservation: PreservationStore;\n diagnostics: DiagnosticStore;\n subParts?: SubPartsCatalog;\n}\n\nexport interface DocumentMetadata {\n title?: string;\n subject?: string;\n description?: string;\n language?: string;\n keywords?: string[];\n category?: string;\n customProperties: Record<string, string>;\n}\n\nexport interface StylesCatalog {\n paragraphs: Record<string, ParagraphStyleDefinition>;\n characters: Record<string, CharacterStyleDefinition>;\n tables: Record<string, TableStyleDefinition>;\n latentStyles?: Record<string, LatentStyleDefinition>;\n}\n\nexport interface ParagraphStyleDefinition {\n styleId: string;\n basedOn?: string;\n nextStyle?: string;\n displayName: string;\n kind: \"paragraph\";\n isDefault: boolean;\n}\n\nexport interface CharacterStyleDefinition {\n styleId: string;\n basedOn?: string;\n displayName: string;\n kind: \"character\";\n isDefault: boolean;\n}\n\nexport interface TableStyleDefinition {\n styleId: string;\n basedOn?: string;\n displayName: string;\n kind: \"table\";\n isDefault: boolean;\n}\n\nexport interface LatentStyleDefinition {\n name: string;\n locked?: boolean;\n semiHidden?: boolean;\n unhideWhenUsed?: boolean;\n qFormat?: boolean;\n uiPriority?: number;\n}\n\nexport interface NumberingCatalog {\n abstractDefinitions: Record<string, AbstractNumberingDefinition>;\n instances: Record<string, NumberingInstance>;\n}\n\nexport interface AbstractNumberingDefinition {\n abstractNumberingId: string;\n levels: NumberingLevelDefinition[];\n}\n\nexport interface NumberingLevelDefinition {\n level: number;\n format: string;\n text: string;\n startAt?: number;\n paragraphStyleId?: string;\n}\n\nexport interface NumberingInstance {\n numberingInstanceId: string;\n abstractNumberingId: string;\n overrides: NumberingLevelOverride[];\n}\n\nexport interface NumberingLevelOverride {\n level: number;\n startAt?: number;\n}\n\nexport interface MediaCatalog {\n items: Record<string, MediaItem>;\n}\n\nexport interface MediaItem {\n mediaId: string;\n contentType: string;\n filename: string;\n relationshipId?: string;\n packagePartName: string;\n altText?: string;\n}\n\n// ---- Sub-part canonical types ----\n\nexport type HeaderFooterVariant = \"default\" | \"first\" | \"even\";\n\nexport interface HeaderDocument {\n variant: HeaderFooterVariant;\n partPath: string;\n relationshipId: string;\n blocks: BlockNode[];\n}\n\nexport interface FooterDocument {\n variant: HeaderFooterVariant;\n partPath: string;\n relationshipId: string;\n blocks: BlockNode[];\n}\n\nexport interface FootnoteDefinition {\n noteId: string;\n kind: \"footnote\" | \"endnote\";\n blocks: BlockNode[];\n}\n\nexport interface FootnoteCollection {\n footnotes: Record<string, FootnoteDefinition>;\n endnotes: Record<string, FootnoteDefinition>;\n}\n\nexport interface ThemeColorScheme {\n name: string;\n colors: Record<string, string>;\n}\n\nexport interface ThemeFontScheme {\n name: string;\n majorFont?: string;\n minorFont?: string;\n}\n\nexport interface ThemeDefinition {\n name?: string;\n colorScheme?: ThemeColorScheme;\n fontScheme?: ThemeFontScheme;\n}\n\nexport interface SubPartsCatalog {\n headers: HeaderDocument[];\n footers: FooterDocument[];\n footnoteCollection?: FootnoteCollection;\n theme?: ThemeDefinition;\n}\n\n// ---- Inline footnote reference node ----\n\nexport interface FootnoteRefNode {\n type: \"footnote_ref\";\n noteId: string;\n noteKind: \"footnote\" | \"endnote\";\n}\n\nexport type DocumentNode =\n | DocumentRootNode\n | ParagraphNode\n | TableNode\n | TableRowNode\n | TableCellNode\n | SdtNode\n | CustomXmlNode\n | AltChunkNode\n | TextNode\n | HardBreakNode\n | TabNode\n | ColumnBreakNode\n | SymbolNode\n | HyperlinkNode\n | ImageNode\n | FieldNode\n | BookmarkStartNode\n | BookmarkEndNode\n | SectionBreakNode\n | OpaqueInlineNode\n | OpaqueBlockNode\n | FootnoteRefNode\n | ChartPreviewNode\n | SmartArtPreviewNode\n | ShapeNode\n | WordArtNode\n | VmlShapeNode;\n\nexport interface DocumentRootNode {\n type: \"doc\";\n children: BlockNode[];\n}\n\nexport type BlockNode =\n | ParagraphNode\n | TableNode\n | SdtNode\n | CustomXmlNode\n | AltChunkNode\n | SectionBreakNode\n | OpaqueBlockNode;\n\nexport interface ParagraphSpacing {\n before?: number;\n after?: number;\n line?: number;\n lineRule?: \"auto\" | \"exact\" | \"atLeast\";\n}\n\nexport interface ParagraphIndentation {\n left?: number;\n right?: number;\n firstLine?: number;\n hanging?: number;\n}\n\nexport interface TabStop {\n position: number;\n align: \"left\" | \"center\" | \"right\" | \"decimal\" | \"bar\" | \"clear\";\n leader?: \"none\" | \"dot\" | \"hyphen\" | \"underscore\" | \"heavy\" | \"middleDot\";\n}\n\nexport interface ParagraphBorders {\n top?: BorderSpec;\n left?: BorderSpec;\n bottom?: BorderSpec;\n right?: BorderSpec;\n bar?: BorderSpec;\n between?: BorderSpec;\n}\n\nexport interface ParagraphShading {\n fill?: string;\n color?: string;\n val?: string;\n}\n\nexport interface ParagraphNode {\n type: \"paragraph\";\n styleId?: string;\n numbering?: {\n numberingInstanceId: string;\n level: number;\n };\n alignment?: \"left\" | \"center\" | \"right\" | \"both\" | \"distribute\";\n spacing?: ParagraphSpacing;\n indentation?: ParagraphIndentation;\n tabStops?: TabStop[];\n keepNext?: boolean;\n keepLines?: boolean;\n outlineLevel?: number;\n pageBreakBefore?: boolean;\n widowControl?: boolean;\n borders?: ParagraphBorders;\n shading?: ParagraphShading;\n bidi?: boolean;\n suppressLineNumbers?: boolean;\n cnfStyle?: string;\n children: InlineNode[];\n}\n\nexport interface BorderSpec {\n value?: string;\n size?: number;\n space?: number;\n color?: string;\n}\n\nexport interface TableBorders {\n top?: BorderSpec;\n left?: BorderSpec;\n bottom?: BorderSpec;\n right?: BorderSpec;\n insideH?: BorderSpec;\n insideV?: BorderSpec;\n}\n\nexport interface TableCellBorders {\n top?: BorderSpec;\n left?: BorderSpec;\n bottom?: BorderSpec;\n right?: BorderSpec;\n insideH?: BorderSpec;\n insideV?: BorderSpec;\n}\n\nexport interface TableWidth {\n value: number;\n type: \"dxa\" | \"auto\" | \"pct\" | \"nil\";\n}\n\nexport interface CellShading {\n fill?: string;\n color?: string;\n val?: string;\n}\n\nexport interface TableCellMargins {\n top?: number;\n left?: number;\n bottom?: number;\n right?: number;\n}\n\nexport interface TableLook {\n val?: string;\n firstRow?: boolean;\n lastRow?: boolean;\n firstColumn?: boolean;\n lastColumn?: boolean;\n noHBand?: boolean;\n noVBand?: boolean;\n}\n\nexport interface TableNode {\n type: \"table\";\n styleId?: string;\n propertiesXml?: string;\n gridColumns: number[];\n rows: TableRowNode[];\n width?: TableWidth;\n alignment?: \"left\" | \"center\" | \"right\";\n borders?: TableBorders;\n cellMargins?: TableCellMargins;\n tblLook?: TableLook;\n}\n\nexport interface TableRowNode {\n type: \"table_row\";\n propertiesXml?: string;\n cells: TableCellNode[];\n height?: number;\n heightRule?: \"auto\" | \"atLeast\" | \"exact\";\n isHeader?: boolean;\n}\n\nexport interface TableCellNode {\n type: \"table_cell\";\n propertiesXml?: string;\n gridSpan?: number;\n verticalMerge?: \"restart\" | \"continue\";\n children: BlockNode[];\n width?: TableWidth;\n borders?: TableCellBorders;\n shading?: CellShading;\n verticalAlign?: \"top\" | \"center\" | \"bottom\";\n}\n\nexport interface SdtNode {\n type: \"sdt\";\n properties: {\n sdtType?: string;\n alias?: string;\n tag?: string;\n lock?: string;\n propertiesXml?: string;\n };\n children: BlockNode[];\n}\n\nexport interface CustomXmlNode {\n type: \"custom_xml\";\n uri?: string;\n element?: string;\n children: BlockNode[];\n}\n\nexport interface AltChunkNode {\n type: \"alt_chunk\";\n relationshipId: string;\n}\n\nexport interface FieldNode {\n type: \"field\";\n fieldType: \"simple\" | \"complex\";\n instruction: string;\n children: InlineNode[];\n}\n\nexport interface BookmarkStartNode {\n type: \"bookmark_start\";\n bookmarkId: string;\n name: string;\n}\n\nexport interface BookmarkEndNode {\n type: \"bookmark_end\";\n bookmarkId: string;\n}\n\nexport interface SectionBreakNode {\n type: \"section_break\";\n propertiesXml?: string;\n}\n\nexport type InlineNode =\n | TextNode\n | HardBreakNode\n | TabNode\n | HyperlinkNode\n | ImageNode\n | FieldNode\n | BookmarkStartNode\n | BookmarkEndNode\n | OpaqueInlineNode\n | FootnoteRefNode\n | ChartPreviewNode\n | SmartArtPreviewNode\n | ShapeNode\n | WordArtNode\n | VmlShapeNode;\n\nexport interface TextNode {\n type: \"text\";\n text: string;\n marks?: TextMark[];\n}\n\nexport type TextMark =\n | { type: \"bold\" }\n | { type: \"italic\" }\n | { type: \"underline\" }\n | { type: \"strikethrough\" }\n | { type: \"doubleStrikethrough\" }\n | { type: \"vanish\" }\n | { type: \"lang\"; val: string }\n | { type: \"backgroundColor\"; color: string }\n | { type: \"charSpacing\"; val: number }\n | { type: \"kerning\"; val: number }\n | { type: \"emboss\" }\n | { type: \"imprint\" }\n | { type: \"shadow\" }\n | { type: \"position\"; val: number }\n | { type: \"textFill\"; xml: string };\n\nexport interface HardBreakNode {\n type: \"hard_break\";\n}\n\nexport interface ColumnBreakNode {\n type: \"column_break\";\n}\n\nexport interface TabNode {\n type: \"tab\";\n}\n\nexport interface SymbolNode {\n type: \"symbol\";\n char: string;\n font?: string;\n marks?: TextMark[];\n}\n\nexport interface HyperlinkNode {\n type: \"hyperlink\";\n href: string;\n children: Array<TextNode | HardBreakNode | ColumnBreakNode | TabNode | SymbolNode>;\n}\n\nexport interface ImageNode {\n type: \"image\";\n mediaId: string;\n altText?: string;\n placementXml?: string;\n display?: \"inline\" | \"floating\";\n floating?: FloatingImageProperties;\n}\n\nexport interface FloatingImageProperties {\n horizontalPosition?: FloatingAxisPosition;\n verticalPosition?: FloatingAxisPosition;\n wrap?: \"none\" | \"square\" | \"tight\" | \"through\" | \"topAndBottom\";\n behindDoc?: boolean;\n layoutInCell?: boolean;\n allowOverlap?: boolean;\n}\n\nexport interface FloatingAxisPosition {\n relativeFrom?: string;\n align?: string;\n offset?: number;\n}\n\nexport interface OpaqueInlineNode {\n type: \"opaque_inline\";\n fragmentId: string;\n warningId: string;\n}\n\n// ---- Complex rendering inline nodes (read-only previews) ----\n\n/**\n * Read-only preview of a chart (c:chart). The original drawing XML is stored in\n * rawXml for lossless round-trip export. If a fallback image was present in\n * mc:AlternateContent it is referenced by previewMediaId.\n */\nexport interface ChartPreviewNode {\n type: \"chart_preview\";\n previewMediaId?: string;\n rawXml: string;\n}\n\n/**\n * Read-only preview of a SmartArt diagram (dgm:*). The original drawing XML is\n * stored in rawXml for lossless round-trip export.\n */\nexport interface SmartArtPreviewNode {\n type: \"smartart_preview\";\n previewMediaId?: string;\n rawXml: string;\n}\n\n/**\n * Read-only rendering of a wps:wsp WordprocessingShape. Text content is\n * extracted for display. The original drawing XML is preserved in rawXml.\n */\nexport interface ShapeNode {\n type: \"shape\";\n text?: string;\n geometry?: string;\n rawXml: string;\n}\n\n/**\n * Read-only rendering of WordArt — a wps:wsp shape with a text-geometry preset.\n * Text is extracted for display. The original drawing XML is preserved in rawXml.\n */\nexport interface WordArtNode {\n type: \"wordart\";\n text: string;\n geometry?: string;\n rawXml: string;\n}\n\n/**\n * Read-only rendering of a VML shape (v:shape, v:rect, v:textbox) from a w:pict\n * element. Text is extracted for display. The original w:pict XML is preserved\n * in rawXml for lossless round-trip export.\n */\nexport interface VmlShapeNode {\n type: \"vml_shape\";\n text?: string;\n shapeType?: string;\n rawXml: string;\n}\n\nexport interface OpaqueBlockNode {\n type: \"opaque_block\";\n fragmentId: string;\n warningId: string;\n}\n\nexport interface DocRange {\n from: number;\n to: number;\n}\n\nexport interface BoundaryAssoc {\n start: -1 | 1;\n end: -1 | 1;\n}\n\nexport type CanonicalAnchor =\n | {\n kind: \"range\";\n range: DocRange;\n assoc: BoundaryAssoc;\n }\n | {\n kind: \"node\";\n at: number;\n assoc: -1 | 1;\n }\n | {\n kind: \"detached\";\n lastKnownRange: DocRange;\n reason: \"deleted\" | \"invalidatedByStructureChange\" | \"importAmbiguity\";\n };\n\nexport interface ReviewStore {\n comments: Record<string, CommentThread>;\n revisions: Record<string, RevisionRecord>;\n}\n\nexport interface CommentThread {\n commentId: string;\n status: \"open\" | \"resolved\" | \"detached\";\n anchor: CanonicalAnchor;\n createdAt: ISO8601DateTime;\n createdBy?: string;\n authorId?: string;\n body?: string;\n entries?: CommentEntry[];\n resolution?: CommentResolution;\n resolvedAt?: ISO8601DateTime;\n warningIds: string[];\n isResolved?: boolean;\n metadata?: CommentThreadMetadata;\n}\n\nexport interface CommentEntry {\n entryId: string;\n authorId: string;\n createdAt: ISO8601DateTime;\n body: string;\n metadata?: CommentEntryMetadata;\n}\n\nexport interface CommentEntryMetadata {\n ooxmlCommentId?: string;\n paraId?: string;\n parentParaId?: string;\n durableId?: string;\n initials?: string;\n}\n\nexport interface CommentResolution {\n resolvedAt: ISO8601DateTime;\n resolvedBy: string;\n}\n\nexport interface CommentThreadMetadata {\n source?: \"runtime\" | \"import\";\n rootOoxmlCommentId?: string;\n rootParaId?: string;\n}\n\nexport interface RevisionPropertyChangeData {\n xmlTag: \"pPrChange\" | \"sectPrChange\" | \"tblPrChange\" | \"rPrChange\";\n beforeXml: string;\n}\n\nexport interface RevisionMoveData {\n moveId: string;\n direction: \"from\" | \"to\";\n}\n\nexport interface RevisionRecord {\n changeId: string;\n kind: \"insertion\" | \"deletion\" | \"formatting\" | \"move\" | \"property-change\";\n anchor: CanonicalAnchor;\n authorId?: string;\n createdAt: ISO8601DateTime;\n warningIds?: string[];\n metadata?: RevisionMetadataRecord;\n status: \"open\" | \"accepted\" | \"rejected\" | \"detached\";\n}\n\nexport interface RevisionMetadataRecord {\n source?: \"runtime\" | \"import\";\n preserveOnlyReason?: string;\n importedRevisionForm?:\n | \"run-insertion\"\n | \"run-deletion\"\n | \"paragraph-insertion\"\n | \"paragraph-deletion\";\n originalRevisionType?: string;\n ooxmlRevisionId?: string;\n propertyChangeData?: RevisionPropertyChangeData;\n moveData?: RevisionMoveData;\n}\n\nexport interface PreservationStore {\n opaqueFragments: Record<string, OpaqueFragmentRecord>;\n packageParts: Record<string, PreservedPackagePart>;\n}\n\nexport interface OpaqueFragmentRecord {\n fragmentId: string;\n payloadKind: \"xml-subtree\" | \"package-part\";\n payloadReference: string;\n featureClass: \"preserve-only\";\n lastKnownRange: DocRange;\n warningId: string;\n packagePartName?: string;\n relationshipId?: string;\n}\n\nexport interface PreservedPackagePart {\n packagePartName: string;\n contentType: string;\n relationshipIds: string[];\n}\n\nexport interface DiagnosticStore {\n warnings: DiagnosticWarningEntry[];\n errors: DiagnosticErrorEntry[];\n}\n\nexport interface DiagnosticWarningEntry {\n diagnosticId: string;\n warningId: string;\n source:\n | \"import\"\n | \"runtime\"\n | \"review\"\n | \"preservation\"\n | \"validation\"\n | \"export\";\n message: string;\n}\n\nexport interface DiagnosticErrorEntry {\n diagnosticId: string;\n code:\n | \"load_failed\"\n | \"export_failed\"\n | \"package_corrupt\"\n | \"validation_failed\"\n | \"datastore_failed\"\n | \"internal_invariant\";\n message: string;\n isFatal: boolean;\n source: \"import\" | \"runtime\" | \"validation\" | \"datastore\" | \"export\";\n}\n\nexport function createCanonicalDocument(\n input: Omit<CanonicalDocument, \"schemaVersion\">,\n): CanonicalDocument {\n const document: CanonicalDocument = {\n schemaVersion: CDS_SCHEMA_VERSION,\n ...input,\n };\n\n assertCanonicalDocument(document);\n return document;\n}\n\nexport function serializeCanonicalDocument(document: CanonicalDocument): string {\n assertCanonicalDocument(document);\n return stableStringify(document);\n}\n\nexport function createCanonicalDocumentSignature(document: unknown): string {\n return stableStringify(document);\n}\n\nexport function parseCanonicalDocument(json: string): CanonicalDocument {\n const parsed = JSON.parse(json) as unknown;\n assertCanonicalDocument(parsed);\n return parsed;\n}\n\nexport function projectCanonicalDocument(\n document: CanonicalDocument,\n): CanonicalDocument {\n assertCanonicalDocument(document);\n return JSON.parse(stableStringify(document)) as CanonicalDocument;\n}\n\nexport function assertCanonicalDocument(\n value: unknown,\n): asserts value is CanonicalDocument {\n const issues = validateCanonicalDocument(value);\n assertValid(issues, \"Invalid canonical document.\");\n}\n\nexport function validateCanonicalDocument(\n value: unknown,\n): ModelValidationIssue[] {\n const issues: ModelValidationIssue[] = [];\n const record = asPlainObject(value, \"$\", issues);\n if (!record) {\n return issues;\n }\n\n validateExactObjectKeys(record, CANONICAL_DOCUMENT_TOP_LEVEL_KEYS, \"$\", issues, CANONICAL_DOCUMENT_OPTIONAL_KEYS);\n expectExactString(record.schemaVersion, CDS_SCHEMA_VERSION, \"$.schemaVersion\", issues);\n expectUuid(record.docId, \"$.docId\", issues);\n expectIso8601UtcTimestamp(record.createdAt, \"$.createdAt\", issues);\n expectIso8601UtcTimestamp(record.updatedAt, \"$.updatedAt\", issues);\n\n validateMetadata(record.metadata, \"$.metadata\", issues);\n validateStylesCatalog(record.styles, \"$.styles\", issues);\n validateNumberingCatalog(record.numbering, \"$.numbering\", issues);\n validateMediaCatalog(record.media, \"$.media\", issues);\n validateDocumentNode(record.content, \"$.content\", issues);\n validateReviewStore(record.review, \"$.review\", issues);\n validatePreservationStore(record.preservation, \"$.preservation\", issues);\n validateDiagnosticStore(record.diagnostics, \"$.diagnostics\", issues);\n if (record.subParts !== undefined) {\n validateSubPartsCatalog(record.subParts, \"$.subParts\", issues);\n }\n\n return issues;\n}\n\nfunction validateMetadata(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n const customProperties = asPlainObject(record.customProperties, `${path}.customProperties`, issues);\n if (!customProperties) {\n return;\n }\n\n for (const [propertyKey, propertyValue] of Object.entries(customProperties)) {\n if (typeof propertyValue !== \"string\") {\n issues.push({\n path: `${path}.customProperties.${propertyKey}`,\n message: \"customProperties values must be strings.\",\n });\n }\n }\n}\n\nfunction validateStylesCatalog(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n validateStyleMap(record.paragraphs, `${path}.paragraphs`, issues);\n validateStyleMap(record.characters, `${path}.characters`, issues);\n validateStyleMap(record.tables, `${path}.tables`, issues);\n if (record.latentStyles !== undefined) {\n validateLatentStyleMap(record.latentStyles, `${path}.latentStyles`, issues);\n }\n}\n\nfunction validateStyleMap(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n for (const [styleId, definition] of Object.entries(record)) {\n expectDomainString(styleId, \"styleId\", `${path}.${styleId}`, issues);\n const definitionRecord = asPlainObject(definition, `${path}.${styleId}`, issues);\n if (!definitionRecord) {\n continue;\n }\n if (definitionRecord.styleId !== styleId) {\n issues.push({\n path: `${path}.${styleId}.styleId`,\n message: \"styleId must match the map key.\",\n });\n }\n }\n}\n\nfunction validateLatentStyleMap(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n for (const [styleName, definition] of Object.entries(record)) {\n const definitionRecord = asPlainObject(definition, `${path}.${styleName}`, issues);\n if (!definitionRecord) {\n continue;\n }\n if (definitionRecord.name !== styleName) {\n issues.push({\n path: `${path}.${styleName}.name`,\n message: \"name must match the map key.\",\n });\n }\n if (definitionRecord.uiPriority !== undefined && typeof definitionRecord.uiPriority !== \"number\") {\n issues.push({\n path: `${path}.${styleName}.uiPriority`,\n message: \"uiPriority must be a number.\",\n });\n }\n }\n}\n\nfunction validateNumberingCatalog(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n const abstractDefinitions = asPlainObject(\n record.abstractDefinitions,\n `${path}.abstractDefinitions`,\n issues,\n );\n if (abstractDefinitions) {\n for (const [abstractId, definition] of Object.entries(abstractDefinitions)) {\n expectDomainString(\n abstractId,\n \"abstractNumberingId\",\n `${path}.abstractDefinitions.${abstractId}`,\n issues,\n );\n const definitionRecord = asPlainObject(\n definition,\n `${path}.abstractDefinitions.${abstractId}`,\n issues,\n );\n if (definitionRecord && definitionRecord.abstractNumberingId !== abstractId) {\n issues.push({\n path: `${path}.abstractDefinitions.${abstractId}.abstractNumberingId`,\n message: \"abstractNumberingId must match the map key.\",\n });\n }\n }\n }\n\n const instances = asPlainObject(record.instances, `${path}.instances`, issues);\n if (instances) {\n for (const [instanceId, instance] of Object.entries(instances)) {\n expectDomainString(\n instanceId,\n \"numberingInstanceId\",\n `${path}.instances.${instanceId}`,\n issues,\n );\n const instanceRecord = asPlainObject(\n instance,\n `${path}.instances.${instanceId}`,\n issues,\n );\n if (!instanceRecord) {\n continue;\n }\n if (instanceRecord.numberingInstanceId !== instanceId) {\n issues.push({\n path: `${path}.instances.${instanceId}.numberingInstanceId`,\n message: \"numberingInstanceId must match the map key.\",\n });\n }\n expectDomainString(\n instanceRecord.abstractNumberingId,\n \"abstractNumberingId\",\n `${path}.instances.${instanceId}.abstractNumberingId`,\n issues,\n );\n }\n }\n}\n\nfunction validateMediaCatalog(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n const items = asPlainObject(record.items, `${path}.items`, issues);\n if (!items) {\n return;\n }\n\n for (const [mediaId, item] of Object.entries(items)) {\n expectDomainString(mediaId, \"mediaId\", `${path}.items.${mediaId}`, issues);\n const itemRecord = asPlainObject(item, `${path}.items.${mediaId}`, issues);\n if (!itemRecord) {\n continue;\n }\n if (itemRecord.mediaId !== mediaId) {\n issues.push({\n path: `${path}.items.${mediaId}.mediaId`,\n message: \"mediaId must match the map key.\",\n });\n }\n expectDomainString(\n itemRecord.packagePartName,\n \"packagePartName\",\n `${path}.items.${mediaId}.packagePartName`,\n issues,\n );\n if (itemRecord.relationshipId !== undefined) {\n expectDomainString(\n itemRecord.relationshipId,\n \"relationshipId\",\n `${path}.items.${mediaId}.relationshipId`,\n issues,\n );\n }\n }\n}\n\nfunction validateDocumentNode(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n const type = expectString(record.type, `${path}.type`, issues);\n if (!type) {\n return;\n }\n\n switch (type) {\n case \"doc\":\n case \"paragraph\":\n case \"sdt\":\n case \"custom_xml\":\n case \"hyperlink\":\n if (!Array.isArray(record.children)) {\n issues.push({ path: `${path}.children`, message: \"children must be an array.\" });\n } else {\n record.children.forEach((child, index) =>\n validateDocumentNode(child, `${path}.children[${index}]`, issues),\n );\n }\n if (type === \"paragraph\" && record.numbering !== undefined) {\n const numbering = asPlainObject(record.numbering, `${path}.numbering`, issues);\n if (numbering) {\n expectDomainString(\n numbering.numberingInstanceId,\n \"numberingInstanceId\",\n `${path}.numbering.numberingInstanceId`,\n issues,\n );\n }\n }\n return;\n case \"alt_chunk\":\n expectDomainString(record.relationshipId, \"relationshipId\", `${path}.relationshipId`, issues);\n return;\n case \"image\":\n expectDomainString(record.mediaId, \"mediaId\", `${path}.mediaId`, issues);\n if (record.placementXml !== undefined) {\n expectString(record.placementXml, `${path}.placementXml`, issues);\n }\n if (record.display !== undefined) {\n const display = expectString(record.display, `${path}.display`, issues);\n if (display && display !== \"inline\" && display !== \"floating\") {\n issues.push({\n path: `${path}.display`,\n message: \"display must be 'inline' or 'floating'.\",\n });\n }\n }\n if (record.floating !== undefined) {\n validateFloatingImageProperties(record.floating, `${path}.floating`, issues);\n }\n return;\n case \"opaque_inline\":\n case \"opaque_block\":\n expectDomainString(record.fragmentId, \"fragmentId\", `${path}.fragmentId`, issues);\n expectDomainString(record.warningId, \"warningId\", `${path}.warningId`, issues);\n return;\n case \"table\":\n if (!Array.isArray(record.gridColumns)) {\n issues.push({ path: `${path}.gridColumns`, message: \"gridColumns must be an array.\" });\n }\n if (!Array.isArray(record.rows)) {\n issues.push({ path: `${path}.rows`, message: \"rows must be an array.\" });\n } else {\n record.rows.forEach((row, rowIndex) =>\n validateDocumentNode(row, `${path}.rows[${rowIndex}]`, issues),\n );\n }\n return;\n case \"table_row\":\n if (!Array.isArray(record.cells)) {\n issues.push({ path: `${path}.cells`, message: \"cells must be an array.\" });\n } else {\n record.cells.forEach((cell, cellIndex) =>\n validateDocumentNode(cell, `${path}.cells[${cellIndex}]`, issues),\n );\n }\n return;\n case \"table_cell\":\n if (!Array.isArray(record.children)) {\n issues.push({ path: `${path}.children`, message: \"children must be an array.\" });\n } else {\n record.children.forEach((child, childIndex) =>\n validateDocumentNode(child, `${path}.children[${childIndex}]`, issues),\n );\n }\n return;\n case \"field\":\n if (!Array.isArray(record.children)) {\n issues.push({ path: `${path}.children`, message: \"children must be an array.\" });\n } else {\n record.children.forEach((child, index) =>\n validateDocumentNode(child, `${path}.children[${index}]`, issues),\n );\n }\n return;\n case \"bookmark_start\":\n expectString(record.bookmarkId, `${path}.bookmarkId`, issues);\n expectString(record.name, `${path}.name`, issues);\n return;\n case \"bookmark_end\":\n expectString(record.bookmarkId, `${path}.bookmarkId`, issues);\n return;\n case \"section_break\":\n return;\n case \"text\":\n case \"hard_break\":\n case \"column_break\":\n case \"tab\":\n return;\n case \"symbol\":\n expectString(record.char, `${path}.char`, issues);\n if (record.font !== undefined) {\n expectString(record.font, `${path}.font`, issues);\n }\n return;\n case \"footnote_ref\":\n expectString(record.noteId, `${path}.noteId`, issues);\n expectString(record.noteKind, `${path}.noteKind`, issues);\n return;\n case \"chart_preview\":\n case \"smartart_preview\":\n case \"shape\":\n case \"wordart\":\n case \"vml_shape\":\n expectString(record.rawXml, `${path}.rawXml`, issues);\n return;\n default:\n issues.push({\n path: `${path}.type`,\n message: `Unsupported node type ${JSON.stringify(type)}.`,\n });\n }\n}\n\nfunction validateFloatingImageProperties(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n if (record.horizontalPosition !== undefined) {\n validateFloatingAxisPosition(record.horizontalPosition, `${path}.horizontalPosition`, issues);\n }\n if (record.verticalPosition !== undefined) {\n validateFloatingAxisPosition(record.verticalPosition, `${path}.verticalPosition`, issues);\n }\n if (record.wrap !== undefined) {\n const wrap = expectString(record.wrap, `${path}.wrap`, issues);\n if (\n wrap &&\n wrap !== \"none\" &&\n wrap !== \"square\" &&\n wrap !== \"tight\" &&\n wrap !== \"through\" &&\n wrap !== \"topAndBottom\"\n ) {\n issues.push({\n path: `${path}.wrap`,\n message: \"wrap must be one of none, square, tight, through, or topAndBottom.\",\n });\n }\n }\n}\n\nfunction validateFloatingAxisPosition(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n if (record.relativeFrom !== undefined) {\n expectString(record.relativeFrom, `${path}.relativeFrom`, issues);\n }\n if (record.align !== undefined) {\n expectString(record.align, `${path}.align`, issues);\n }\n if (record.offset !== undefined && typeof record.offset !== \"number\") {\n issues.push({\n path: `${path}.offset`,\n message: \"offset must be a number.\",\n });\n }\n}\n\nfunction validateReviewStore(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n const comments = asPlainObject(record.comments, `${path}.comments`, issues);\n if (comments) {\n for (const [commentId, thread] of Object.entries(comments)) {\n expectDomainString(commentId, \"commentId\", `${path}.comments.${commentId}`, issues);\n const threadRecord = asPlainObject(thread, `${path}.comments.${commentId}`, issues);\n if (!threadRecord) {\n continue;\n }\n if (threadRecord.commentId !== commentId) {\n issues.push({\n path: `${path}.comments.${commentId}.commentId`,\n message: \"commentId must match the map key.\",\n });\n }\n validateAnchor(threadRecord.anchor, `${path}.comments.${commentId}.anchor`, issues);\n expectIso8601UtcTimestamp(\n threadRecord.createdAt,\n `${path}.comments.${commentId}.createdAt`,\n issues,\n );\n validateCommentStatus(threadRecord.status, `${path}.comments.${commentId}.status`, issues);\n if (threadRecord.createdBy !== undefined) {\n expectString(\n threadRecord.createdBy,\n `${path}.comments.${commentId}.createdBy`,\n issues,\n );\n }\n if (threadRecord.authorId !== undefined) {\n expectString(\n threadRecord.authorId,\n `${path}.comments.${commentId}.authorId`,\n issues,\n );\n }\n if (threadRecord.body !== undefined) {\n expectString(threadRecord.body, `${path}.comments.${commentId}.body`, issues);\n }\n if (!Array.isArray(threadRecord.warningIds)) {\n issues.push({\n path: `${path}.comments.${commentId}.warningIds`,\n message: \"warningIds must be an array.\",\n });\n } else {\n threadRecord.warningIds.forEach((warningId, index) =>\n expectDomainString(\n warningId,\n \"warningId\",\n `${path}.comments.${commentId}.warningIds[${index}]`,\n issues,\n ),\n );\n }\n if (threadRecord.entries !== undefined) {\n validateCommentEntries(\n threadRecord.entries,\n `${path}.comments.${commentId}.entries`,\n issues,\n );\n }\n if (threadRecord.resolution !== undefined) {\n validateCommentResolution(\n threadRecord.resolution,\n `${path}.comments.${commentId}.resolution`,\n issues,\n );\n }\n if (threadRecord.resolvedAt !== undefined) {\n expectIso8601UtcTimestamp(\n threadRecord.resolvedAt,\n `${path}.comments.${commentId}.resolvedAt`,\n issues,\n );\n }\n if (\n threadRecord.isResolved !== undefined &&\n typeof threadRecord.isResolved !== \"boolean\"\n ) {\n issues.push({\n path: `${path}.comments.${commentId}.isResolved`,\n message: \"isResolved must be a boolean.\",\n });\n }\n if (threadRecord.metadata !== undefined) {\n validateCommentThreadMetadata(\n threadRecord.metadata,\n `${path}.comments.${commentId}.metadata`,\n issues,\n );\n }\n }\n }\n\n const revisions = asPlainObject(record.revisions, `${path}.revisions`, issues);\n if (revisions) {\n for (const [revisionId, revision] of Object.entries(revisions)) {\n expectDomainString(revisionId, \"revisionId\", `${path}.revisions.${revisionId}`, issues);\n const revisionRecord = asPlainObject(\n revision,\n `${path}.revisions.${revisionId}`,\n issues,\n );\n if (!revisionRecord) {\n continue;\n }\n if (revisionRecord.changeId !== revisionId) {\n issues.push({\n path: `${path}.revisions.${revisionId}.changeId`,\n message: \"changeId must match the map key.\",\n });\n }\n validateAnchor(revisionRecord.anchor, `${path}.revisions.${revisionId}.anchor`, issues);\n validateRevisionKind(revisionRecord.kind, `${path}.revisions.${revisionId}.kind`, issues);\n validateRevisionStatus(\n revisionRecord.status,\n `${path}.revisions.${revisionId}.status`,\n issues,\n );\n expectIso8601UtcTimestamp(\n revisionRecord.createdAt,\n `${path}.revisions.${revisionId}.createdAt`,\n issues,\n );\n if (revisionRecord.authorId !== undefined) {\n expectString(\n revisionRecord.authorId,\n `${path}.revisions.${revisionId}.authorId`,\n issues,\n );\n }\n if (revisionRecord.warningIds !== undefined) {\n validateWarningIds(\n revisionRecord.warningIds,\n `${path}.revisions.${revisionId}.warningIds`,\n issues,\n );\n }\n if (revisionRecord.metadata !== undefined) {\n validateRevisionMetadata(\n revisionRecord.metadata,\n `${path}.revisions.${revisionId}.metadata`,\n issues,\n );\n }\n }\n }\n}\n\nfunction validateCommentStatus(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n if (value === \"open\" || value === \"resolved\" || value === \"detached\") {\n return;\n }\n issues.push({\n path,\n message: \"status must be one of open, resolved, or detached.\",\n });\n}\n\nfunction validateCommentEntries(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n if (!Array.isArray(value)) {\n issues.push({\n path,\n message: \"entries must be an array.\",\n });\n return;\n }\n\n value.forEach((entry, index) => {\n const record = asPlainObject(entry, `${path}[${index}]`, issues);\n if (!record) {\n return;\n }\n expectString(record.entryId, `${path}[${index}].entryId`, issues);\n expectString(record.authorId, `${path}[${index}].authorId`, issues);\n expectString(record.body, `${path}[${index}].body`, issues);\n expectIso8601UtcTimestamp(record.createdAt, `${path}[${index}].createdAt`, issues);\n if (record.metadata !== undefined) {\n validateCommentEntryMetadata(record.metadata, `${path}[${index}].metadata`, issues);\n }\n });\n}\n\nfunction validateCommentEntryMetadata(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n for (const field of [\n \"ooxmlCommentId\",\n \"paraId\",\n \"parentParaId\",\n \"durableId\",\n \"initials\",\n ] as const) {\n if (record[field] !== undefined) {\n expectString(record[field], `${path}.${field}`, issues);\n }\n }\n}\n\nfunction validateCommentResolution(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n expectIso8601UtcTimestamp(record.resolvedAt, `${path}.resolvedAt`, issues);\n expectString(record.resolvedBy, `${path}.resolvedBy`, issues);\n}\n\nfunction validateCommentThreadMetadata(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n if (\n record.source !== undefined &&\n record.source !== \"runtime\" &&\n record.source !== \"import\"\n ) {\n issues.push({\n path: `${path}.source`,\n message: \"source must be either runtime or import.\",\n });\n }\n if (record.rootOoxmlCommentId !== undefined) {\n expectString(record.rootOoxmlCommentId, `${path}.rootOoxmlCommentId`, issues);\n }\n if (record.rootParaId !== undefined) {\n expectString(record.rootParaId, `${path}.rootParaId`, issues);\n }\n}\n\nfunction validateRevisionKind(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n if (\n value === \"insertion\" ||\n value === \"deletion\" ||\n value === \"formatting\" ||\n value === \"move\" ||\n value === \"property-change\"\n ) {\n return;\n }\n issues.push({\n path,\n message: \"kind must be insertion, deletion, formatting, move, or property-change.\",\n });\n}\n\nfunction validateRevisionStatus(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n if (\n value === \"open\" ||\n value === \"accepted\" ||\n value === \"rejected\" ||\n value === \"detached\"\n ) {\n return;\n }\n issues.push({\n path,\n message: \"status must be one of open, accepted, rejected, or detached.\",\n });\n}\n\nfunction validateWarningIds(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n if (!Array.isArray(value)) {\n issues.push({\n path,\n message: \"warningIds must be an array.\",\n });\n return;\n }\n\n value.forEach((warningId, index) =>\n expectDomainString(warningId, \"warningId\", `${path}[${index}]`, issues),\n );\n}\n\nfunction validateRevisionMetadata(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n if (\n record.source !== undefined &&\n record.source !== \"runtime\" &&\n record.source !== \"import\"\n ) {\n issues.push({\n path: `${path}.source`,\n message: \"source must be either runtime or import.\",\n });\n }\n for (const field of [\n \"preserveOnlyReason\",\n \"importedRevisionForm\",\n \"originalRevisionType\",\n \"ooxmlRevisionId\",\n ] as const) {\n if (record[field] !== undefined) {\n expectString(record[field], `${path}.${field}`, issues);\n }\n }\n\n if (record.propertyChangeData !== undefined) {\n const pcd = asPlainObject(record.propertyChangeData, `${path}.propertyChangeData`, issues);\n if (pcd) {\n expectString(pcd.xmlTag, `${path}.propertyChangeData.xmlTag`, issues);\n expectString(pcd.beforeXml, `${path}.propertyChangeData.beforeXml`, issues);\n }\n }\n\n if (record.moveData !== undefined) {\n const md = asPlainObject(record.moveData, `${path}.moveData`, issues);\n if (md) {\n expectString(md.moveId, `${path}.moveData.moveId`, issues);\n expectString(md.direction, `${path}.moveData.direction`, issues);\n }\n }\n}\n\nfunction validatePreservationStore(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n const opaqueFragments = asPlainObject(\n record.opaqueFragments,\n `${path}.opaqueFragments`,\n issues,\n );\n if (opaqueFragments) {\n for (const [fragmentId, fragment] of Object.entries(opaqueFragments)) {\n expectDomainString(fragmentId, \"fragmentId\", `${path}.opaqueFragments.${fragmentId}`, issues);\n const fragmentRecord = asPlainObject(\n fragment,\n `${path}.opaqueFragments.${fragmentId}`,\n issues,\n );\n if (!fragmentRecord) {\n continue;\n }\n if (fragmentRecord.fragmentId !== fragmentId) {\n issues.push({\n path: `${path}.opaqueFragments.${fragmentId}.fragmentId`,\n message: \"fragmentId must match the map key.\",\n });\n }\n validateRange(\n fragmentRecord.lastKnownRange,\n `${path}.opaqueFragments.${fragmentId}.lastKnownRange`,\n issues,\n );\n expectDomainString(\n fragmentRecord.warningId,\n \"warningId\",\n `${path}.opaqueFragments.${fragmentId}.warningId`,\n issues,\n );\n if (fragmentRecord.packagePartName !== undefined) {\n expectDomainString(\n fragmentRecord.packagePartName,\n \"packagePartName\",\n `${path}.opaqueFragments.${fragmentId}.packagePartName`,\n issues,\n );\n }\n if (fragmentRecord.relationshipId !== undefined) {\n expectDomainString(\n fragmentRecord.relationshipId,\n \"relationshipId\",\n `${path}.opaqueFragments.${fragmentId}.relationshipId`,\n issues,\n );\n }\n }\n }\n\n const packageParts = asPlainObject(record.packageParts, `${path}.packageParts`, issues);\n if (packageParts) {\n for (const [packagePartName, packagePart] of Object.entries(packageParts)) {\n expectDomainString(\n packagePartName,\n \"packagePartName\",\n `${path}.packageParts.${packagePartName}`,\n issues,\n );\n const packagePartRecord = asPlainObject(\n packagePart,\n `${path}.packageParts.${packagePartName}`,\n issues,\n );\n if (!packagePartRecord) {\n continue;\n }\n if (packagePartRecord.packagePartName !== packagePartName) {\n issues.push({\n path: `${path}.packageParts.${packagePartName}.packagePartName`,\n message: \"packagePartName must match the map key.\",\n });\n }\n if (Array.isArray(packagePartRecord.relationshipIds)) {\n packagePartRecord.relationshipIds.forEach((relationshipId, index) =>\n expectDomainString(\n relationshipId,\n \"relationshipId\",\n `${path}.packageParts.${packagePartName}.relationshipIds[${index}]`,\n issues,\n ),\n );\n }\n }\n }\n}\n\nfunction validateDiagnosticStore(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n if (Array.isArray(record.warnings)) {\n record.warnings.forEach((warning, index) => {\n const warningRecord = asPlainObject(warning, `${path}.warnings[${index}]`, issues);\n if (!warningRecord) {\n return;\n }\n expectDomainString(\n warningRecord.diagnosticId,\n \"diagnosticId\",\n `${path}.warnings[${index}].diagnosticId`,\n issues,\n );\n expectDomainString(\n warningRecord.warningId,\n \"warningId\",\n `${path}.warnings[${index}].warningId`,\n issues,\n );\n });\n }\n\n if (Array.isArray(record.errors)) {\n record.errors.forEach((error, index) => {\n const errorRecord = asPlainObject(error, `${path}.errors[${index}]`, issues);\n if (!errorRecord) {\n return;\n }\n expectDomainString(\n errorRecord.diagnosticId,\n \"diagnosticId\",\n `${path}.errors[${index}].diagnosticId`,\n issues,\n );\n });\n }\n}\n\nfunction validateAnchor(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n const kind = expectString(record.kind, `${path}.kind`, issues);\n if (!kind) {\n return;\n }\n\n if (kind === \"range\") {\n validateRange(record.range, `${path}.range`, issues);\n } else if (kind === \"detached\") {\n validateRange(record.lastKnownRange, `${path}.lastKnownRange`, issues);\n }\n}\n\nfunction validateRange(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n if (typeof record.from !== \"number\" || typeof record.to !== \"number\") {\n issues.push({\n path,\n message: \"Range must contain numeric from and to values.\",\n });\n }\n}\n\nfunction validateExactObjectKeys(\n record: Record<string, unknown>,\n expectedKeys: readonly string[],\n path: string,\n issues: ModelValidationIssue[],\n allowedOptionalKeys?: readonly string[],\n): void {\n const actualKeys = new Set(Object.keys(record));\n const expected = new Set(expectedKeys);\n const optional = new Set(allowedOptionalKeys ?? []);\n\n for (const expectedKey of expectedKeys) {\n if (!actualKeys.has(expectedKey)) {\n issues.push({\n path,\n message: `Missing required key ${JSON.stringify(expectedKey)}.`,\n });\n }\n }\n\n for (const actualKey of actualKeys) {\n if (!expected.has(actualKey) && !optional.has(actualKey)) {\n issues.push({\n path: `${path}.${actualKey}`,\n message:\n \"Unexpected canonical document key. Render/UI state is not part of the canonical envelope.\",\n });\n }\n }\n}\n\nfunction validateSubPartsCatalog(\n value: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(value, path, issues);\n if (!record) {\n return;\n }\n\n if (record.headers !== undefined) {\n if (!Array.isArray(record.headers)) {\n issues.push({ path: `${path}.headers`, message: \"headers must be an array.\" });\n } else {\n record.headers.forEach((header, index) => {\n const headerRecord = asPlainObject(header, `${path}.headers[${index}]`, issues);\n if (headerRecord) {\n expectString(headerRecord.variant, `${path}.headers[${index}].variant`, issues);\n expectString(headerRecord.partPath, `${path}.headers[${index}].partPath`, issues);\n expectString(headerRecord.relationshipId, `${path}.headers[${index}].relationshipId`, issues);\n }\n });\n }\n }\n\n if (record.footers !== undefined) {\n if (!Array.isArray(record.footers)) {\n issues.push({ path: `${path}.footers`, message: \"footers must be an array.\" });\n } else {\n record.footers.forEach((footer, index) => {\n const footerRecord = asPlainObject(footer, `${path}.footers[${index}]`, issues);\n if (footerRecord) {\n expectString(footerRecord.variant, `${path}.footers[${index}].variant`, issues);\n expectString(footerRecord.partPath, `${path}.footers[${index}].partPath`, issues);\n expectString(footerRecord.relationshipId, `${path}.footers[${index}].relationshipId`, issues);\n }\n });\n }\n }\n}\n\nfunction expectDomainString(\n value: unknown,\n domain: StableIdDomain,\n path: string,\n issues: ModelValidationIssue[],\n): string | null {\n const stableId = expectString(value, path, issues);\n if (!stableId) {\n return null;\n }\n\n if (!ID_PATTERNS[domain].test(stableId)) {\n issues.push({\n path,\n message: `Expected a valid ${domain}.`,\n });\n return null;\n }\n\n return stableId;\n}\n","import {\n CDS_SCHEMA_VERSION,\n COMPATIBILITY_REPORT_VERSION,\n PERSISTED_EDITOR_SNAPSHOT_VERSION,\n type CompatibilityReportVersion,\n type ISO8601DateTime,\n type ModelValidationIssue,\n type PersistedEditorSnapshotVersion,\n asPlainObject,\n assertValid,\n expectExactString,\n expectIso8601UtcTimestamp,\n expectString,\n stableStringify,\n} from \"./cds-1.0.0.ts\";\nimport {\n type CanonicalDocument,\n assertCanonicalDocument,\n validateCanonicalDocument,\n} from \"./canonical-document.ts\";\n\nexport type EditorWarningCode =\n | \"unsupported_ooxml_preserved\"\n | \"unsupported_ooxml_locked\"\n | \"import_normalized\"\n | \"export_roundtrip_risk\"\n | \"comment_anchor_detached\"\n | \"revision_anchor_detached\"\n | \"large_document_degraded\"\n | \"font_substitution\"\n | \"image_missing\";\n\nexport interface EditorWarning {\n warningId: string;\n code: EditorWarningCode;\n severity: \"info\" | \"warning\";\n message: string;\n source:\n | \"import\"\n | \"runtime\"\n | \"review\"\n | \"preservation\"\n | \"validation\"\n | \"export\";\n affectedAnchor?: Record<string, unknown>;\n featureEntryId?: string;\n details?: Record<string, unknown>;\n}\n\nexport type EditorErrorCode =\n | \"import_failed\"\n | \"export_failed\"\n | \"package_corrupt\"\n | \"validation_failed\"\n | \"datastore_failed\"\n | \"internal_invariant\";\n\nexport interface EditorError {\n errorId: string;\n code: EditorErrorCode;\n message: string;\n isFatal: boolean;\n source: \"import\" | \"runtime\" | \"validation\" | \"datastore\" | \"export\";\n details?: Record<string, unknown>;\n}\n\nexport type CompatibilityFeatureClass =\n | \"supported-roundtrip\"\n | \"preserve-only\"\n | \"unsupported-fatal\";\n\nexport interface CompatibilityFeatureEntry {\n featureEntryId: string;\n featureKey: string;\n featureClass: CompatibilityFeatureClass;\n message: string;\n affectedAnchor?: Record<string, unknown>;\n details?: Record<string, unknown>;\n}\n\nexport interface CompatibilityReport {\n reportVersion: CompatibilityReportVersion;\n generatedAt: ISO8601DateTime;\n blockExport: boolean;\n featureEntries: CompatibilityFeatureEntry[];\n warnings: EditorWarning[];\n errors: EditorError[];\n}\n\nexport interface PersistedEditorSnapshot {\n snapshotVersion: PersistedEditorSnapshotVersion;\n schemaVersion: typeof CDS_SCHEMA_VERSION;\n documentId: string;\n docId: string;\n createdAt: ISO8601DateTime;\n updatedAt: ISO8601DateTime;\n savedAt: ISO8601DateTime;\n editorBuild: string;\n canonicalDocument: CanonicalDocument;\n compatibility: CompatibilityReport;\n warningLog: EditorWarning[];\n}\n\nconst SNAPSHOT_TOP_LEVEL_KEYS = [\n \"snapshotVersion\",\n \"schemaVersion\",\n \"documentId\",\n \"docId\",\n \"createdAt\",\n \"updatedAt\",\n \"savedAt\",\n \"editorBuild\",\n \"canonicalDocument\",\n \"compatibility\",\n \"warningLog\",\n] as const;\n\nexport function serializePersistedEditorSnapshot(\n snapshot: PersistedEditorSnapshot,\n): string {\n assertPersistedEditorSnapshot(snapshot);\n return stableStringify(snapshot);\n}\n\nexport function parsePersistedEditorSnapshot(\n json: string,\n): PersistedEditorSnapshot {\n const parsed = JSON.parse(json) as unknown;\n assertPersistedEditorSnapshot(parsed);\n return parsed;\n}\n\nexport function assertPersistedEditorSnapshot(\n snapshot: unknown,\n): asserts snapshot is PersistedEditorSnapshot {\n const issues = validatePersistedEditorSnapshot(snapshot);\n assertValid(issues, \"Invalid persisted editor snapshot.\");\n}\n\nexport function validatePersistedEditorSnapshot(\n snapshot: unknown,\n): ModelValidationIssue[] {\n const issues: ModelValidationIssue[] = [];\n const record = asPlainObject(snapshot, \"$\", issues);\n if (!record) {\n return issues;\n }\n\n validateExactObjectKeys(record, SNAPSHOT_TOP_LEVEL_KEYS, \"$\", issues);\n\n expectExactString(\n record.snapshotVersion,\n PERSISTED_EDITOR_SNAPSHOT_VERSION,\n \"$.snapshotVersion\",\n issues,\n );\n expectExactString(\n record.schemaVersion,\n CDS_SCHEMA_VERSION,\n \"$.schemaVersion\",\n issues,\n );\n expectString(record.documentId, \"$.documentId\", issues);\n expectString(record.docId, \"$.docId\", issues);\n expectIso8601UtcTimestamp(record.createdAt, \"$.createdAt\", issues);\n expectIso8601UtcTimestamp(record.updatedAt, \"$.updatedAt\", issues);\n expectIso8601UtcTimestamp(record.savedAt, \"$.savedAt\", issues);\n expectString(record.editorBuild, \"$.editorBuild\", issues);\n\n const canonicalDocumentIssues = validateCanonicalDocument(record.canonicalDocument);\n issues.push(...canonicalDocumentIssues.map(prefixIssue(\"$.canonicalDocument\")));\n\n if (\n asPlainObject(record.canonicalDocument, \"$.canonicalDocument\", [])?.docId !==\n record.docId\n ) {\n issues.push({\n path: \"$.docId\",\n message: \"Snapshot docId must match canonicalDocument.docId.\",\n });\n }\n\n validateCompatibilityReport(record.compatibility, \"$.compatibility\", issues);\n\n if (!Array.isArray(record.warningLog)) {\n issues.push({\n path: \"$.warningLog\",\n message: \"warningLog must be an array.\",\n });\n } else {\n record.warningLog.forEach((warning, index) => {\n validateEditorWarning(warning, `$.warningLog[${index}]`, issues);\n });\n }\n\n return issues;\n}\n\nexport function assertCompatibilityReport(\n report: unknown,\n): asserts report is CompatibilityReport {\n const issues = validateCompatibilityReport(report);\n assertValid(issues, \"Invalid compatibility report.\");\n}\n\nexport function validateCompatibilityReport(\n report: unknown,\n path = \"$\",\n issues: ModelValidationIssue[] = [],\n): ModelValidationIssue[] {\n const record = asPlainObject(report, path, issues);\n if (!record) {\n return issues;\n }\n\n expectExactString(\n record.reportVersion,\n COMPATIBILITY_REPORT_VERSION,\n `${path}.reportVersion`,\n issues,\n );\n expectIso8601UtcTimestamp(record.generatedAt, `${path}.generatedAt`, issues);\n\n if (typeof record.blockExport !== \"boolean\") {\n issues.push({\n path: `${path}.blockExport`,\n message: \"blockExport must be a boolean.\",\n });\n }\n\n if (!Array.isArray(record.featureEntries)) {\n issues.push({\n path: `${path}.featureEntries`,\n message: \"featureEntries must be an array.\",\n });\n } else {\n record.featureEntries.forEach((featureEntry, index) => {\n validateCompatibilityFeatureEntry(\n featureEntry,\n `${path}.featureEntries[${index}]`,\n issues,\n );\n });\n }\n\n if (!Array.isArray(record.warnings)) {\n issues.push({\n path: `${path}.warnings`,\n message: \"warnings must be an array.\",\n });\n } else {\n record.warnings.forEach((warning, index) => {\n validateEditorWarning(warning, `${path}.warnings[${index}]`, issues);\n });\n }\n\n if (!Array.isArray(record.errors)) {\n issues.push({\n path: `${path}.errors`,\n message: \"errors must be an array.\",\n });\n } else {\n record.errors.forEach((error, index) => {\n validateEditorError(error, `${path}.errors[${index}]`, issues);\n });\n }\n\n return issues;\n}\n\nfunction validateCompatibilityFeatureEntry(\n featureEntry: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(featureEntry, path, issues);\n if (!record) {\n return;\n }\n\n expectString(record.featureEntryId, `${path}.featureEntryId`, issues);\n expectString(record.featureKey, `${path}.featureKey`, issues);\n expectString(record.featureClass, `${path}.featureClass`, issues);\n expectString(record.message, `${path}.message`, issues);\n}\n\nfunction validateEditorWarning(\n warning: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(warning, path, issues);\n if (!record) {\n return;\n }\n\n expectString(record.warningId, `${path}.warningId`, issues);\n expectString(record.code, `${path}.code`, issues);\n expectString(record.severity, `${path}.severity`, issues);\n expectString(record.message, `${path}.message`, issues);\n expectString(record.source, `${path}.source`, issues);\n}\n\nfunction validateEditorError(\n error: unknown,\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const record = asPlainObject(error, path, issues);\n if (!record) {\n return;\n }\n\n expectString(record.errorId, `${path}.errorId`, issues);\n expectString(record.code, `${path}.code`, issues);\n expectString(record.message, `${path}.message`, issues);\n expectString(record.source, `${path}.source`, issues);\n\n if (typeof record.isFatal !== \"boolean\") {\n issues.push({\n path: `${path}.isFatal`,\n message: \"isFatal must be a boolean.\",\n });\n }\n}\n\nfunction validateExactObjectKeys(\n record: Record<string, unknown>,\n expectedKeys: readonly string[],\n path: string,\n issues: ModelValidationIssue[],\n): void {\n const actualKeys = new Set(Object.keys(record));\n const expected = new Set(expectedKeys);\n\n for (const expectedKey of expectedKeys) {\n if (!actualKeys.has(expectedKey)) {\n issues.push({\n path,\n message: `Missing required key ${JSON.stringify(expectedKey)}.`,\n });\n }\n }\n\n for (const actualKey of actualKeys) {\n if (!expected.has(actualKey)) {\n issues.push({\n path: `${path}.${actualKey}`,\n message:\n \"Unexpected persisted snapshot key. Render/UI state is not part of the persistence contract.\",\n });\n }\n }\n}\n\nfunction prefixIssue(basePath: string) {\n return (issue: ModelValidationIssue): ModelValidationIssue => ({\n path: `${basePath}${issue.path === \"$\" ? \"\" : issue.path.slice(1)}`,\n message: issue.message,\n });\n}\n\nexport function createPersistedEditorSnapshot(params: {\n documentId: string;\n savedAt: ISO8601DateTime;\n editorBuild: string;\n canonicalDocument: CanonicalDocument;\n compatibility: CompatibilityReport;\n warningLog?: EditorWarning[];\n}): PersistedEditorSnapshot {\n assertCanonicalDocument(params.canonicalDocument);\n assertCompatibilityReport(params.compatibility);\n\n return {\n snapshotVersion: PERSISTED_EDITOR_SNAPSHOT_VERSION,\n schemaVersion: CDS_SCHEMA_VERSION,\n documentId: params.documentId,\n docId: params.canonicalDocument.docId,\n createdAt: params.canonicalDocument.createdAt,\n updatedAt: params.canonicalDocument.updatedAt,\n savedAt: params.savedAt,\n editorBuild: params.editorBuild,\n canonicalDocument: params.canonicalDocument,\n compatibility: params.compatibility,\n warningLog: params.warningLog ?? params.compatibility.warnings,\n };\n}\n\nexport function projectAnchorToSnapshot(\n anchor: Record<string, unknown>,\n): Record<string, unknown> {\n return JSON.parse(JSON.stringify(anchor)) as Record<string, unknown>;\n}\n","import {\n DEFAULT_BOUNDARY_ASSOC,\n createDetachedAnchor,\n createRangeAnchor,\n type EditorAnchorProjection,\n} from \"../selection/mapping.ts\";\nimport {\n assertPersistedEditorSnapshot as assertModelPersistedEditorSnapshot,\n createPersistedEditorSnapshot as createModelPersistedEditorSnapshot,\n type PersistedEditorSnapshot as ModelPersistedEditorSnapshot,\n} from \"../../model/snapshot.ts\";\nimport {\n assertCanonicalDocument,\n type CanonicalDocument,\n type CommentEntry as ModelCommentEntry,\n type CommentResolution as ModelCommentResolution,\n type CommentThread as ModelCommentThread,\n type RevisionMetadataRecord as ModelRevisionMetadataRecord,\n type RevisionRecord as ModelRevisionRecord,\n} from \"../../model/canonical-document.ts\";\n\nexport type RuntimePhase = \"loading\" | \"ready\" | \"error\";\nexport type EditorWarningCode =\n | \"unsupported_ooxml_preserved\"\n | \"unsupported_ooxml_locked\"\n | \"import_normalized\"\n | \"export_roundtrip_risk\"\n | \"comment_anchor_detached\"\n | \"revision_anchor_detached\"\n | \"large_document_degraded\"\n | \"font_substitution\"\n | \"image_missing\";\n\nexport interface EditorWarning {\n warningId: string;\n code: EditorWarningCode;\n severity: \"info\" | \"warning\";\n message: string;\n source:\n | \"import\"\n | \"runtime\"\n | \"review\"\n | \"preservation\"\n | \"validation\"\n | \"export\";\n affectedAnchor?: EditorAnchorProjection;\n featureEntryId?: string;\n details?: Record<string, unknown>;\n}\n\nexport interface EditorError {\n errorId: string;\n code:\n | \"import_failed\"\n | \"export_failed\"\n | \"package_corrupt\"\n | \"validation_failed\"\n | \"datastore_failed\"\n | \"internal_invariant\";\n message: string;\n isFatal: boolean;\n source: \"import\" | \"runtime\" | \"validation\" | \"datastore\" | \"export\";\n details?: Record<string, unknown>;\n}\n\nexport type CompatibilityFeatureClass =\n | \"supported-roundtrip\"\n | \"preserve-only\"\n | \"unsupported-fatal\";\n\nexport interface CompatibilityFeatureEntry {\n featureEntryId: string;\n featureKey: string;\n featureClass: CompatibilityFeatureClass;\n message: string;\n affectedAnchor?: EditorAnchorProjection;\n details?: Record<string, unknown>;\n}\n\nexport interface CompatibilityReport {\n reportVersion: \"compatibility-report/1\";\n generatedAt: string;\n blockExport: boolean;\n featureEntries: CompatibilityFeatureEntry[];\n warnings: EditorWarning[];\n errors: EditorError[];\n}\n\nexport type CommentEntryRecord = ModelCommentEntry;\nexport type CommentResolutionRecord = ModelCommentResolution;\nexport type CommentThreadRecord = ModelCommentThread;\nexport type RevisionMetadataRecord = ModelRevisionMetadataRecord;\nexport type RevisionRecord = ModelRevisionRecord;\nexport type ReviewStore = CanonicalDocument[\"review\"];\nexport type CanonicalDocumentEnvelope = CanonicalDocument;\n\nexport interface SelectionSnapshot {\n anchor: number;\n head: number;\n isCollapsed: boolean;\n activeRange: EditorAnchorProjection;\n}\n\nexport interface DocumentStats {\n paragraphCount: number;\n wordCount: number;\n characterCount: number;\n commentCount: number;\n revisionCount: number;\n}\n\nexport interface CommentSidebarSnapshot {\n activeCommentId?: string;\n openThreadCount: number;\n resolvedThreadCount: number;\n threads: CommentThreadRecord[];\n}\n\nexport interface TrackedChangesSnapshot {\n totalCount: number;\n pendingCount: number;\n acceptedCount: number;\n rejectedCount: number;\n}\n\nexport interface CompatibilityPanelSnapshot {\n report: CompatibilityReport;\n blockExport: boolean;\n totalEntries: number;\n}\n\nexport interface CommandStateSnapshot {\n canUndo: boolean;\n canRedo: boolean;\n canAddComment: boolean;\n canAcceptAllChanges: boolean;\n canRejectAllChanges: boolean;\n}\n\nexport interface RuntimeRenderSnapshot {\n documentId: string;\n sessionId: string;\n sourceLabel?: string;\n revisionToken: string;\n isReady: boolean;\n isDirty: boolean;\n readOnly: boolean;\n selection: SelectionSnapshot;\n documentStats: DocumentStats;\n comments: CommentSidebarSnapshot;\n trackedChanges: TrackedChangesSnapshot;\n compatibility: CompatibilityPanelSnapshot;\n warnings: EditorWarning[];\n fatalError?: EditorError;\n commandState: CommandStateSnapshot;\n}\n\nexport interface PersistedEditorSnapshot\n extends Omit<\n ModelPersistedEditorSnapshot,\n \"canonicalDocument\" | \"compatibility\" | \"warningLog\"\n > {\n canonicalDocument: CanonicalDocumentEnvelope;\n compatibility: CompatibilityReport;\n warningLog: EditorWarning[];\n}\n\nexport interface EditorRuntimeState {\n hasFocus: boolean;\n activeCommentId?: string;\n}\n\nexport interface EditorState {\n phase: RuntimePhase;\n documentId: string;\n sessionId: string;\n sourceLabel?: string;\n revision: number;\n revisionToken: string;\n isDirty: boolean;\n readOnly: boolean;\n document: CanonicalDocumentEnvelope;\n selection: SelectionSnapshot;\n warnings: EditorWarning[];\n compatibility: CompatibilityReport;\n fatalError?: EditorError;\n runtime: EditorRuntimeState;\n}\n\nexport interface CreateEditorStateOptions {\n documentId: string;\n sessionId: string;\n sourceLabel?: string;\n readOnly?: boolean;\n canonicalDocument?: CanonicalDocumentEnvelope;\n persistedSnapshot?: PersistedEditorSnapshot;\n compatibility?: CompatibilityReport;\n warnings?: EditorWarning[];\n fatalError?: EditorError;\n}\n\nexport function createEmptyReviewStore(): ReviewStore {\n return {\n comments: {},\n revisions: {},\n };\n}\n\nexport function createDefaultCanonicalDocument(\n documentId: string,\n timestamp: string,\n): CanonicalDocumentEnvelope {\n return {\n schemaVersion: \"cds/1.0.0\",\n docId: createCanonicalDocumentId(documentId),\n createdAt: timestamp,\n updatedAt: timestamp,\n metadata: {\n customProperties: {},\n },\n styles: {\n paragraphs: {},\n characters: {},\n tables: {},\n },\n numbering: {\n abstractDefinitions: {},\n instances: {},\n },\n media: {\n items: {},\n },\n content: {\n type: \"doc\",\n children: [{ type: \"paragraph\", children: [] }],\n },\n review: createEmptyReviewStore(),\n preservation: {\n opaqueFragments: {},\n packageParts: {},\n },\n diagnostics: {\n warnings: [],\n errors: [],\n },\n };\n}\n\nexport function createSelectionSnapshot(anchor = 0, head = anchor): SelectionSnapshot {\n return {\n anchor,\n head,\n isCollapsed: anchor === head,\n activeRange: createRangeAnchor(anchor, head, DEFAULT_BOUNDARY_ASSOC),\n };\n}\n\nexport function createEmptyCompatibilityReport(generatedAt: string): CompatibilityReport {\n return {\n reportVersion: \"compatibility-report/1\",\n generatedAt,\n blockExport: false,\n featureEntries: [],\n warnings: [],\n errors: [],\n };\n}\n\nexport function createEditorState(options: CreateEditorStateOptions): EditorState {\n const timestamp = new Date(0).toISOString();\n if (options.persistedSnapshot) {\n assertModelPersistedEditorSnapshot(options.persistedSnapshot as unknown);\n }\n if (options.canonicalDocument) {\n assertCanonicalDocument(options.canonicalDocument as unknown);\n }\n\n const normalizedDocument = options.persistedSnapshot\n ? structuredClone(options.persistedSnapshot.canonicalDocument)\n : options.canonicalDocument\n ? structuredClone(options.canonicalDocument)\n : createDefaultCanonicalDocument(options.documentId, timestamp);\n const warnings = options.persistedSnapshot?.warningLog ?? options.warnings ?? [];\n const compatibility =\n options.persistedSnapshot?.compatibility ??\n options.compatibility ??\n createEmptyCompatibilityReport(normalizedDocument.updatedAt);\n\n return {\n phase: options.fatalError ? \"error\" : \"ready\",\n documentId: options.documentId,\n sessionId: options.sessionId,\n sourceLabel: options.sourceLabel,\n revision: 0,\n revisionToken: `${options.sessionId}:0`,\n isDirty: false,\n readOnly: options.readOnly ?? false,\n document: normalizedDocument,\n selection: createSelectionSnapshot(),\n warnings,\n compatibility,\n fatalError: options.fatalError,\n runtime: {\n hasFocus: false,\n },\n };\n}\n\nexport function deriveDocumentStats(state: Pick<EditorState, \"document\">): DocumentStats {\n const serializedContent = extractText(state.document.content);\n\n return {\n paragraphCount: estimateParagraphCount(state.document.content),\n wordCount: serializedContent.trim().length === 0 ? 0 : serializedContent.trim().split(/\\s+/u).length,\n characterCount: Array.from(serializedContent).length,\n commentCount: Object.keys(state.document.review.comments).length,\n revisionCount: Object.keys(state.document.review.revisions).length,\n };\n}\n\nexport function deriveRenderSnapshot(\n state: EditorState,\n history: { canUndo: boolean; canRedo: boolean },\n): RuntimeRenderSnapshot {\n const comments = Object.values(state.document.review.comments).sort((left, right) =>\n left.createdAt.localeCompare(right.createdAt),\n );\n const revisions = Object.values(state.document.review.revisions);\n\n return {\n documentId: state.documentId,\n sessionId: state.sessionId,\n sourceLabel: state.sourceLabel,\n revisionToken: state.revisionToken,\n isReady: state.phase === \"ready\",\n isDirty: state.isDirty,\n readOnly: state.readOnly,\n selection: state.selection,\n documentStats: deriveDocumentStats(state),\n comments: {\n activeCommentId: state.runtime.activeCommentId,\n openThreadCount: comments.filter((comment) => comment.status === \"open\").length,\n resolvedThreadCount: comments.filter((comment) => comment.status === \"resolved\").length,\n threads: comments,\n },\n trackedChanges: {\n totalCount: revisions.length,\n pendingCount: revisions.filter((revision) => revision.status === \"open\").length,\n acceptedCount: revisions.filter((revision) => revision.status === \"accepted\").length,\n rejectedCount: revisions.filter((revision) => revision.status === \"rejected\").length,\n },\n compatibility: {\n report: state.compatibility,\n blockExport: state.compatibility.blockExport,\n totalEntries: state.compatibility.featureEntries.length,\n },\n warnings: state.warnings,\n fatalError: state.fatalError,\n commandState: {\n canUndo: history.canUndo,\n canRedo: history.canRedo,\n canAddComment: !state.readOnly,\n canAcceptAllChanges: revisions.some((revision) => revision.status === \"open\"),\n canRejectAllChanges: revisions.some((revision) => revision.status === \"open\"),\n },\n };\n}\n\nexport function createPersistedEditorSnapshot(\n state: EditorState,\n options: {\n editorBuild: string;\n savedAt: string;\n compatibility?: CompatibilityReport;\n },\n): PersistedEditorSnapshot {\n const snapshot = createModelPersistedEditorSnapshot({\n documentId: state.documentId,\n savedAt: options.savedAt,\n editorBuild: options.editorBuild,\n canonicalDocument: state.document,\n compatibility: (options.compatibility ?? state.compatibility) as never,\n warningLog: state.warnings as never,\n });\n return snapshot as PersistedEditorSnapshot;\n}\n\nfunction estimateParagraphCount(content: unknown): number {\n if (Array.isArray(content)) {\n return content.length;\n }\n\n if (content && typeof content === \"object\" && Array.isArray((content as { blocks?: unknown[] }).blocks)) {\n return ((content as { blocks: unknown[] }).blocks).length;\n }\n\n return extractText(content).length > 0 ? 1 : 0;\n}\n\nfunction extractText(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => extractText(item)).join(\" \");\n }\n\n if (!value || typeof value !== \"object\") {\n return \"\";\n }\n\n return Object.values(value as Record<string, unknown>)\n .map((item) => extractText(item))\n .filter(Boolean)\n .join(\" \");\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function createCanonicalDocumentId(documentId: string): string {\n const hashWord = (seed: string): string => {\n let hash = 0x811c9dc5;\n for (const char of seed) {\n hash ^= char.charCodeAt(0);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n };\n\n const raw =\n hashWord(`${documentId}:0`) +\n hashWord(`${documentId}:1`) +\n hashWord(`${documentId}:2`) +\n hashWord(`${documentId}:3`);\n\n return [\n raw.slice(0, 8),\n raw.slice(8, 12),\n `4${raw.slice(13, 16)}`,\n `8${raw.slice(17, 20)}`,\n raw.slice(20, 32),\n ].join(\"-\");\n}\n\nexport function normalizeCommentThreadRecord(value: unknown): CommentThreadRecord {\n const record = isRecord(value) ? value : {};\n const authorId =\n typeof record.createdBy === \"string\" && record.createdBy.length > 0\n ? record.createdBy\n : typeof record.authorId === \"string\" && record.authorId.length > 0\n ? record.authorId\n : \"unknown\";\n const createdAt =\n typeof record.createdAt === \"string\" && record.createdAt.length > 0\n ? record.createdAt\n : new Date(0).toISOString();\n const entries = Array.isArray(record.entries)\n ? record.entries\n .filter((entry): entry is Record<string, unknown> => isRecord(entry))\n .map((entry, index) => ({\n entryId:\n typeof entry.entryId === \"string\" && entry.entryId.length > 0\n ? entry.entryId\n : `${String(record.commentId ?? \"comment\")}-entry-${index + 1}`,\n authorId:\n typeof entry.authorId === \"string\" && entry.authorId.length > 0\n ? entry.authorId\n : authorId,\n body: typeof entry.body === \"string\" ? entry.body : \"\",\n createdAt:\n typeof entry.createdAt === \"string\" && entry.createdAt.length > 0\n ? entry.createdAt\n : createdAt,\n metadata: isRecord(entry.metadata)\n ? {\n ooxmlCommentId:\n typeof entry.metadata.ooxmlCommentId === \"string\"\n ? entry.metadata.ooxmlCommentId\n : undefined,\n paraId:\n typeof entry.metadata.paraId === \"string\"\n ? entry.metadata.paraId\n : undefined,\n parentParaId:\n typeof entry.metadata.parentParaId === \"string\"\n ? entry.metadata.parentParaId\n : undefined,\n durableId:\n typeof entry.metadata.durableId === \"string\"\n ? entry.metadata.durableId\n : undefined,\n initials:\n typeof entry.metadata.initials === \"string\"\n ? entry.metadata.initials\n : undefined,\n }\n : undefined,\n }))\n : [\n {\n entryId: `${String(record.commentId ?? \"comment\")}-entry-1`,\n authorId,\n body: typeof record.body === \"string\" ? record.body : \"\",\n createdAt,\n },\n ];\n const resolution = isRecord(record.resolution)\n ? {\n resolvedAt:\n typeof record.resolution.resolvedAt === \"string\"\n ? record.resolution.resolvedAt\n : typeof record.resolvedAt === \"string\"\n ? record.resolvedAt\n : createdAt,\n resolvedBy:\n typeof record.resolution.resolvedBy === \"string\" &&\n record.resolution.resolvedBy.length > 0\n ? record.resolution.resolvedBy\n : authorId,\n }\n : typeof record.resolvedAt === \"string\"\n ? {\n resolvedAt: record.resolvedAt,\n resolvedBy: authorId,\n }\n : undefined;\n const normalizedStatus =\n typeof record.status === \"string\"\n ? record.status\n : record.anchor && isRecord(record.anchor) && record.anchor.kind === \"detached\"\n ? \"detached\"\n : resolution || record.isResolved\n ? \"resolved\"\n : \"open\";\n\n return {\n commentId:\n typeof record.commentId === \"string\" && record.commentId.length > 0\n ? record.commentId\n : \"comment-generated\",\n anchor:\n isRecord(record.anchor) && typeof record.anchor.kind === \"string\"\n ? (record.anchor as unknown as EditorAnchorProjection)\n : createDetachedAnchor({ from: 0, to: 0 }, \"importAmbiguity\"),\n createdAt,\n createdBy: authorId,\n authorId,\n body: entries.map((entry) => entry.body).join(\"\\n\"),\n entries,\n status:\n normalizedStatus === \"resolved\" || normalizedStatus === \"detached\"\n ? normalizedStatus\n : \"open\",\n resolution,\n resolvedAt: resolution?.resolvedAt,\n warningIds: Array.isArray(record.warningIds)\n ? record.warningIds.filter((warningId): warningId is string => typeof warningId === \"string\")\n : [],\n isResolved: normalizedStatus === \"resolved\",\n metadata: isRecord(record.metadata)\n ? {\n source:\n record.metadata.source === \"import\" || record.metadata.source === \"runtime\"\n ? record.metadata.source\n : undefined,\n rootOoxmlCommentId:\n typeof record.metadata.rootOoxmlCommentId === \"string\"\n ? record.metadata.rootOoxmlCommentId\n : undefined,\n rootParaId:\n typeof record.metadata.rootParaId === \"string\"\n ? record.metadata.rootParaId\n : undefined,\n }\n : undefined,\n };\n}\n","export interface ReviewCommandOrigin {\n source:\n | \"keyboard\"\n | \"toolbar\"\n | \"context_menu\"\n | \"comment_panel\"\n | \"review_panel\"\n | \"api\"\n | \"runtime\";\n timestamp: string;\n}\n\nexport type ReviewCommand =\n | {\n type: \"review.accept-revision\";\n revisionId: string;\n origin?: ReviewCommandOrigin;\n }\n | {\n type: \"review.reject-revision\";\n revisionId: string;\n origin?: ReviewCommandOrigin;\n }\n | {\n type: \"review.accept-all-revisions\";\n origin?: ReviewCommandOrigin;\n }\n | {\n type: \"review.reject-all-revisions\";\n origin?: ReviewCommandOrigin;\n };\n\nexport type SingleRevisionReviewCommand = Extract<\n ReviewCommand,\n { revisionId: string }\n>;\n\nexport type BatchRevisionReviewCommand = Exclude<\n ReviewCommand,\n SingleRevisionReviewCommand\n>;\n\nexport type ReviewCommandIntent = \"accept\" | \"reject\";\n\nexport function isSingleRevisionReviewCommand(\n command: ReviewCommand,\n): command is SingleRevisionReviewCommand {\n return \"revisionId\" in command;\n}\n\nexport function isBatchRevisionReviewCommand(\n command: ReviewCommand,\n): command is BatchRevisionReviewCommand {\n return !isSingleRevisionReviewCommand(command);\n}\n\nexport function getReviewCommandIntent(\n command: ReviewCommand,\n): ReviewCommandIntent {\n switch (command.type) {\n case \"review.accept-revision\":\n case \"review.accept-all-revisions\":\n return \"accept\";\n case \"review.reject-revision\":\n case \"review.reject-all-revisions\":\n return \"reject\";\n }\n}\n\nexport function createAcceptRevisionCommand(\n revisionId: string,\n origin?: ReviewCommandOrigin,\n): SingleRevisionReviewCommand {\n return {\n type: \"review.accept-revision\",\n revisionId,\n ...(origin ? { origin } : {}),\n };\n}\n\nexport function createRejectRevisionCommand(\n revisionId: string,\n origin?: ReviewCommandOrigin,\n): SingleRevisionReviewCommand {\n return {\n type: \"review.reject-revision\",\n revisionId,\n ...(origin ? { origin } : {}),\n };\n}\n\nexport function createAcceptAllRevisionsCommand(\n origin?: ReviewCommandOrigin,\n): BatchRevisionReviewCommand {\n return {\n type: \"review.accept-all-revisions\",\n ...(origin ? { origin } : {}),\n };\n}\n\nexport function createRejectAllRevisionsCommand(\n origin?: ReviewCommandOrigin,\n): BatchRevisionReviewCommand {\n return {\n type: \"review.reject-all-revisions\",\n ...(origin ? { origin } : {}),\n };\n}\n","import type {\n DocumentRootNode,\n HyperlinkNode,\n InlineNode,\n OpaqueBlockNode,\n OpaqueInlineNode,\n ParagraphNode,\n TextMark,\n} from \"../../model/canonical-document.ts\";\n\nexport interface ParagraphProperties {\n styleId?: string;\n numbering?: ParagraphNode[\"numbering\"];\n}\n\nexport interface TextStory {\n firstParagraph: ParagraphProperties;\n units: StoryUnit[];\n size: number;\n}\n\nexport type StoryUnit =\n | TextCharacterUnit\n | TabUnit\n | HardBreakUnit\n | ImageUnit\n | OpaqueInlineUnit\n | OpaqueBlockUnit\n | ParagraphBreakUnit;\n\nexport interface TextCharacterUnit {\n kind: \"text\";\n value: string;\n marks?: TextMark[];\n hyperlinkHref?: string;\n}\n\nexport interface TabUnit {\n kind: \"tab\";\n hyperlinkHref?: string;\n}\n\nexport interface HardBreakUnit {\n kind: \"hard_break\";\n hyperlinkHref?: string;\n}\n\nexport interface ImageUnit {\n kind: \"image\";\n mediaId: string;\n altText?: string;\n}\n\nexport interface OpaqueInlineUnit {\n kind: \"opaque_inline\";\n fragmentId: string;\n warningId: string;\n}\n\nexport interface OpaqueBlockUnit {\n kind: \"opaque_block\";\n fragmentId: string;\n warningId: string;\n nextParagraph?: ParagraphProperties;\n}\n\nexport interface ParagraphBreakUnit {\n kind: \"paragraph_break\";\n nextParagraph: ParagraphProperties;\n}\n\nexport function parseTextStory(content: unknown): TextStory {\n const root = normalizeDocumentRoot(content);\n const firstParagraphNode = root.children.find(isParagraphNode);\n const firstParagraph = firstParagraphNode\n ? extractParagraphProperties(firstParagraphNode)\n : cloneParagraphProperties(EMPTY_PARAGRAPH_PROPERTIES);\n const units: StoryUnit[] = [];\n\n for (let index = 0; index < root.children.length; index += 1) {\n const block = root.children[index];\n const nextBlock = root.children[index + 1];\n\n if (isParagraphNode(block)) {\n units.push(...flattenInlineNodes(block.children));\n\n if (isParagraphNode(nextBlock)) {\n units.push({\n kind: \"paragraph_break\",\n nextParagraph: extractParagraphProperties(nextBlock),\n });\n }\n\n continue;\n }\n\n units.push({\n kind: \"opaque_block\",\n fragmentId: block.fragmentId,\n warningId: block.warningId,\n ...(isParagraphNode(nextBlock)\n ? { nextParagraph: extractParagraphProperties(nextBlock) }\n : {}),\n });\n }\n\n return {\n firstParagraph,\n units,\n size: units.length,\n };\n}\n\nexport function serializeTextStory(story: TextStory): DocumentRootNode {\n const blocks: Array<ParagraphNode | OpaqueBlockNode> = [];\n let currentParagraph: ParagraphNode | undefined = createParagraph(story.firstParagraph);\n let currentHyperlink: HyperlinkNode | undefined;\n let activeTextBuffer:\n | {\n text: string;\n marks?: TextMark[];\n hyperlinkHref?: string;\n }\n | undefined;\n\n const ensureCurrentParagraph = () => {\n if (!currentParagraph) {\n currentParagraph = createParagraph(EMPTY_PARAGRAPH_PROPERTIES);\n }\n };\n\n const flushTextBuffer = () => {\n if (!activeTextBuffer || activeTextBuffer.text.length === 0) {\n activeTextBuffer = undefined;\n return;\n }\n\n const textNode = {\n type: \"text\" as const,\n text: activeTextBuffer.text,\n ...(activeTextBuffer.marks ? { marks: cloneMarks(activeTextBuffer.marks) } : {}),\n };\n\n ensureCurrentParagraph();\n\n if (activeTextBuffer.hyperlinkHref) {\n if (!currentHyperlink || currentHyperlink.href !== activeTextBuffer.hyperlinkHref) {\n flushHyperlink();\n currentHyperlink = {\n type: \"hyperlink\",\n href: activeTextBuffer.hyperlinkHref,\n children: [],\n };\n }\n\n currentHyperlink.children.push(textNode);\n } else {\n flushHyperlink();\n currentParagraph!.children.push(textNode);\n }\n\n activeTextBuffer = undefined;\n };\n\n const flushHyperlink = () => {\n if (currentHyperlink) {\n ensureCurrentParagraph();\n currentParagraph!.children.push(currentHyperlink);\n currentHyperlink = undefined;\n }\n };\n\n const flushParagraph = () => {\n flushTextBuffer();\n flushHyperlink();\n\n if (!currentParagraph) {\n return;\n }\n\n blocks.push(currentParagraph);\n currentParagraph = undefined;\n };\n\n const pushInlineNode = (\n node: Exclude<InlineNode, { type: \"text\" }>,\n hyperlinkHref?: string,\n ) => {\n flushTextBuffer();\n ensureCurrentParagraph();\n\n if (hyperlinkHref) {\n if (!currentHyperlink || currentHyperlink.href !== hyperlinkHref) {\n flushHyperlink();\n currentHyperlink = {\n type: \"hyperlink\",\n href: hyperlinkHref,\n children: [],\n };\n }\n\n currentHyperlink.children.push(node as HyperlinkNode[\"children\"][number]);\n return;\n }\n\n flushHyperlink();\n currentParagraph!.children.push(node);\n };\n\n for (const unit of story.units) {\n if (unit.kind === \"paragraph_break\") {\n flushParagraph();\n currentParagraph = createParagraph(unit.nextParagraph);\n continue;\n }\n\n if (unit.kind === \"opaque_block\") {\n flushParagraph();\n blocks.push({\n type: \"opaque_block\",\n fragmentId: unit.fragmentId,\n warningId: unit.warningId,\n });\n currentParagraph = unit.nextParagraph\n ? createParagraph(unit.nextParagraph)\n : undefined;\n continue;\n }\n\n if (unit.kind === \"text\") {\n const shouldExtendBuffer =\n activeTextBuffer &&\n activeTextBuffer.hyperlinkHref === unit.hyperlinkHref &&\n haveEqualMarks(activeTextBuffer.marks, unit.marks);\n\n if (shouldExtendBuffer && activeTextBuffer) {\n activeTextBuffer.text += unit.value;\n } else {\n flushTextBuffer();\n activeTextBuffer = {\n text: unit.value,\n ...(unit.marks ? { marks: cloneMarks(unit.marks) } : {}),\n ...(unit.hyperlinkHref ? { hyperlinkHref: unit.hyperlinkHref } : {}),\n };\n }\n\n continue;\n }\n\n switch (unit.kind) {\n case \"tab\":\n pushInlineNode({ type: \"tab\" }, unit.hyperlinkHref);\n break;\n case \"hard_break\":\n pushInlineNode({ type: \"hard_break\" }, unit.hyperlinkHref);\n break;\n case \"image\":\n pushInlineNode({\n type: \"image\",\n mediaId: unit.mediaId,\n ...(unit.altText ? { altText: unit.altText } : {}),\n });\n break;\n case \"opaque_inline\":\n pushInlineNode({\n type: \"opaque_inline\",\n fragmentId: unit.fragmentId,\n warningId: unit.warningId,\n });\n break;\n }\n }\n\n flushParagraph();\n\n if (blocks.length === 0) {\n blocks.push(createParagraph(story.firstParagraph));\n }\n\n return {\n type: \"doc\",\n children: blocks,\n };\n}\n\nexport function createPlainText(story: TextStory): string {\n return story.units\n .map((unit) => {\n switch (unit.kind) {\n case \"text\":\n return unit.value;\n case \"tab\":\n return \"\\t\";\n case \"hard_break\":\n return \"\\n\";\n case \"paragraph_break\":\n return \"\\n\";\n case \"image\":\n return \"\\uFFFC\";\n case \"opaque_inline\":\n return \"\\uFFF9\";\n case \"opaque_block\":\n return \"\\uFFFA\";\n }\n })\n .join(\"\");\n}\n\nexport function cloneStoryUnit(unit: StoryUnit): StoryUnit {\n switch (unit.kind) {\n case \"text\":\n return {\n kind: \"text\",\n value: unit.value,\n ...(unit.marks ? { marks: cloneMarks(unit.marks) } : {}),\n ...(unit.hyperlinkHref ? { hyperlinkHref: unit.hyperlinkHref } : {}),\n };\n case \"tab\":\n return {\n kind: \"tab\",\n ...(unit.hyperlinkHref ? { hyperlinkHref: unit.hyperlinkHref } : {}),\n };\n case \"hard_break\":\n return {\n kind: \"hard_break\",\n ...(unit.hyperlinkHref ? { hyperlinkHref: unit.hyperlinkHref } : {}),\n };\n case \"image\":\n return {\n kind: \"image\",\n mediaId: unit.mediaId,\n ...(unit.altText ? { altText: unit.altText } : {}),\n };\n case \"opaque_inline\":\n return {\n kind: \"opaque_inline\",\n fragmentId: unit.fragmentId,\n warningId: unit.warningId,\n };\n case \"opaque_block\":\n return {\n kind: \"opaque_block\",\n fragmentId: unit.fragmentId,\n warningId: unit.warningId,\n ...(unit.nextParagraph\n ? { nextParagraph: cloneParagraphProperties(unit.nextParagraph) }\n : {}),\n };\n case \"paragraph_break\":\n return {\n kind: \"paragraph_break\",\n nextParagraph: cloneParagraphProperties(unit.nextParagraph),\n };\n }\n}\n\nexport function cloneParagraphProperties(\n properties: ParagraphProperties,\n): ParagraphProperties {\n return {\n ...(properties.styleId ? { styleId: properties.styleId } : {}),\n ...(properties.numbering\n ? {\n numbering: {\n numberingInstanceId: properties.numbering.numberingInstanceId,\n level: properties.numbering.level,\n },\n }\n : {}),\n };\n}\n\nfunction normalizeDocumentRoot(content: unknown): DocumentRootNode {\n if (isDocumentRootNode(content)) {\n return content;\n }\n\n if (Array.isArray(content)) {\n return {\n type: \"doc\",\n children: content.filter(\n (block): block is DocumentRootNode[\"children\"][number] =>\n isParagraphNode(block) || isOpaqueBlockNode(block),\n ),\n };\n }\n\n return {\n type: \"doc\",\n children: [createEmptyParagraph()],\n };\n}\n\nfunction flattenInlineNodes(\n nodes: ParagraphNode[\"children\"],\n hyperlinkHref?: string,\n): StoryUnit[] {\n const units: StoryUnit[] = [];\n\n for (const node of nodes) {\n switch (node.type) {\n case \"text\":\n for (const character of Array.from(node.text)) {\n units.push({\n kind: \"text\",\n value: character,\n ...(node.marks ? { marks: cloneMarks(node.marks) } : {}),\n ...(hyperlinkHref ? { hyperlinkHref } : {}),\n });\n }\n break;\n case \"tab\":\n units.push({\n kind: \"tab\",\n ...(hyperlinkHref ? { hyperlinkHref } : {}),\n });\n break;\n case \"hard_break\":\n units.push({\n kind: \"hard_break\",\n ...(hyperlinkHref ? { hyperlinkHref } : {}),\n });\n break;\n case \"hyperlink\":\n units.push(...flattenInlineNodes(node.children, node.href));\n break;\n case \"image\":\n units.push({\n kind: \"image\",\n mediaId: node.mediaId,\n ...(node.altText ? { altText: node.altText } : {}),\n });\n break;\n case \"opaque_inline\":\n units.push({\n kind: \"opaque_inline\",\n fragmentId: node.fragmentId,\n warningId: node.warningId,\n });\n break;\n }\n }\n\n return units;\n}\n\nfunction extractParagraphProperties(paragraph: ParagraphNode): ParagraphProperties {\n return {\n ...(paragraph.styleId ? { styleId: paragraph.styleId } : {}),\n ...(paragraph.numbering\n ? {\n numbering: {\n numberingInstanceId: paragraph.numbering.numberingInstanceId,\n level: paragraph.numbering.level,\n },\n }\n : {}),\n };\n}\n\nfunction createParagraph(properties: ParagraphProperties): ParagraphNode {\n return {\n type: \"paragraph\",\n ...(properties.styleId ? { styleId: properties.styleId } : {}),\n ...(properties.numbering\n ? {\n numbering: {\n numberingInstanceId: properties.numbering.numberingInstanceId,\n level: properties.numbering.level,\n },\n }\n : {}),\n children: [],\n };\n}\n\nfunction createEmptyParagraph(): ParagraphNode {\n return {\n type: \"paragraph\",\n children: [],\n };\n}\n\nconst EMPTY_PARAGRAPH_PROPERTIES: ParagraphProperties = {};\n\nfunction cloneMarks(marks: TextMark[]): TextMark[] {\n return marks.map((mark) => ({ type: mark.type }));\n}\n\nfunction haveEqualMarks(left?: TextMark[], right?: TextMark[]): boolean {\n if (!left && !right) {\n return true;\n }\n\n if (!left || !right || left.length !== right.length) {\n return false;\n }\n\n return left.every((mark, index) => mark.type === right[index]?.type);\n}\n\nfunction isDocumentRootNode(value: unknown): value is DocumentRootNode {\n return Boolean(value) && typeof value === \"object\" && (value as { type?: string }).type === \"doc\";\n}\n\nfunction isParagraphNode(value: unknown): value is ParagraphNode {\n return Boolean(value) && typeof value === \"object\" && (value as { type?: string }).type === \"paragraph\";\n}\n\nfunction isOpaqueBlockNode(value: unknown): value is OpaqueBlockNode {\n return Boolean(value) && typeof value === \"object\" && (value as { type?: string }).type === \"opaque_block\";\n}\n","import { createSelectionSnapshot, type CanonicalDocumentEnvelope, type SelectionSnapshot } from \"./editor-state.ts\";\nimport type { TransactionMapping } from \"../selection/mapping.ts\";\nimport {\n cloneParagraphProperties,\n cloneStoryUnit,\n createPlainText,\n parseTextStory,\n serializeTextStory,\n type ParagraphProperties,\n type StoryUnit,\n type TextStory,\n} from \"../schema/text-schema.ts\";\n\nexport type TextInsertion =\n | {\n type: \"text\";\n text: string;\n }\n | {\n type: \"tab\";\n }\n | {\n type: \"hard_break\";\n }\n | {\n type: \"paragraph_break\";\n };\n\nexport type TextTransactionIntent =\n | {\n type: \"replace\";\n range?: {\n from: number;\n to: number;\n };\n insertion: TextInsertion[];\n }\n | {\n type: \"delete_backward\";\n }\n | {\n type: \"delete_forward\";\n };\n\nexport interface TextTransactionResult {\n document: CanonicalDocumentEnvelope;\n selection: SelectionSnapshot;\n mapping: TransactionMapping;\n storyText: string;\n}\n\nexport class TextTransactionError extends Error {\n readonly code: \"invalid_selection\" | \"unsupported_content\";\n\n constructor(\n code: TextTransactionError[\"code\"],\n message: string,\n ) {\n super(message);\n this.name = \"TextTransactionError\";\n this.code = code;\n }\n}\n\nexport function applyTextTransaction(\n document: CanonicalDocumentEnvelope,\n selection: SelectionSnapshot,\n intent: TextTransactionIntent,\n options: {\n timestamp: string;\n },\n): TextTransactionResult {\n const story = parseTextStory(document.content);\n const normalizedRange = resolveRange(selection, story.size, intent);\n const insertionUnits = createInsertionUnits(intent, story, normalizedRange.from);\n\n ensureEditableRange(story.units.slice(normalizedRange.from, normalizedRange.to));\n\n const nextUnits = [\n ...story.units.slice(0, normalizedRange.from).map(cloneStoryUnit),\n ...insertionUnits.map(cloneStoryUnit),\n ...story.units.slice(normalizedRange.to).map(cloneStoryUnit),\n ];\n\n const nextStory: TextStory = {\n firstParagraph: cloneParagraphProperties(story.firstParagraph),\n units: normalizeStoryUnits(nextUnits),\n size: 0,\n };\n nextStory.size = nextStory.units.length;\n\n const caret = normalizedRange.from + insertionUnits.length;\n\n return {\n document: {\n ...document,\n updatedAt: options.timestamp,\n content: serializeTextStory(nextStory),\n },\n selection: createSelectionSnapshot(caret, caret),\n mapping: {\n steps: [\n {\n from: normalizedRange.from,\n to: normalizedRange.to,\n insertSize: insertionUnits.length,\n },\n ],\n metadata: {\n affectsComments: true,\n affectsRevisions: true,\n ...(containsParagraphBoundaryChange(story, normalizedRange, insertionUnits)\n ? { invalidatesStructures: true }\n : {}),\n },\n },\n storyText: createPlainText(nextStory),\n };\n}\n\nfunction resolveRange(\n selection: SelectionSnapshot,\n storySize: number,\n intent: TextTransactionIntent,\n): { from: number; to: number } {\n const from = Math.max(0, Math.min(selection.anchor, selection.head));\n const to = Math.max(0, Math.max(selection.anchor, selection.head));\n\n if (from > storySize || to > storySize) {\n throw new TextTransactionError(\n \"invalid_selection\",\n `Selection ${from}-${to} exceeds story size ${storySize}.`,\n );\n }\n\n if (intent.type === \"replace\") {\n if (intent.range) {\n const explicitFrom = Math.max(0, Math.min(intent.range.from, intent.range.to));\n const explicitTo = Math.max(0, Math.max(intent.range.from, intent.range.to));\n if (explicitFrom > storySize || explicitTo > storySize) {\n throw new TextTransactionError(\n \"invalid_selection\",\n `Explicit range ${explicitFrom}-${explicitTo} exceeds story size ${storySize}.`,\n );\n }\n\n return {\n from: explicitFrom,\n to: explicitTo,\n };\n }\n\n return { from, to };\n }\n\n if (from !== to) {\n return { from, to };\n }\n\n if (intent.type === \"delete_backward\") {\n return {\n from: Math.max(0, from - 1),\n to: from,\n };\n }\n\n return {\n from,\n to: Math.min(storySize, from + 1),\n };\n}\n\nfunction createInsertionUnits(\n intent: TextTransactionIntent,\n story: TextStory,\n position: number,\n): StoryUnit[] {\n if (intent.type !== \"replace\") {\n return [];\n }\n\n const inheritedProps = resolveParagraphPropertiesAtPosition(story, position);\n\n return intent.insertion.flatMap((entry) => {\n switch (entry.type) {\n case \"text\":\n return Array.from(entry.text).map<StoryUnit>((character) => ({\n kind: \"text\",\n value: character,\n }));\n case \"tab\":\n return [{ kind: \"tab\" }];\n case \"hard_break\":\n return [{ kind: \"hard_break\" }];\n case \"paragraph_break\":\n return [\n {\n kind: \"paragraph_break\",\n nextParagraph: cloneParagraphProperties(inheritedProps),\n },\n ];\n }\n });\n}\n\nfunction resolveParagraphPropertiesAtPosition(\n story: TextStory,\n position: number,\n): ParagraphProperties {\n let current = cloneParagraphProperties(story.firstParagraph);\n\n for (let index = 0; index < Math.min(position, story.units.length); index += 1) {\n const unit = story.units[index];\n if (unit.kind === \"paragraph_break\") {\n current = cloneParagraphProperties(unit.nextParagraph);\n } else if (unit.kind === \"opaque_block\" && unit.nextParagraph) {\n current = cloneParagraphProperties(unit.nextParagraph);\n }\n }\n\n return current;\n}\n\nfunction normalizeStoryUnits(units: StoryUnit[]): StoryUnit[] {\n if (units.length === 0) {\n return [];\n }\n\n const normalized: StoryUnit[] = [];\n\n for (const unit of units) {\n if (\n unit.kind === \"paragraph_break\" &&\n normalized[normalized.length - 1]?.kind === \"paragraph_break\"\n ) {\n normalized.push({\n kind: \"paragraph_break\",\n nextParagraph: cloneParagraphProperties(unit.nextParagraph),\n });\n continue;\n }\n\n normalized.push(cloneStoryUnit(unit));\n }\n\n return normalized;\n}\n\nfunction ensureEditableRange(units: StoryUnit[]): void {\n const protectedUnit = units.find(\n (unit) => unit.kind === \"opaque_inline\" || unit.kind === \"opaque_block\" || unit.kind === \"image\",\n );\n\n if (!protectedUnit) {\n return;\n }\n\n throw new TextTransactionError(\n \"unsupported_content\",\n `Text transaction crosses protected ${protectedUnit.kind} content.`,\n );\n}\n\nfunction containsParagraphBoundaryChange(\n story: TextStory,\n range: { from: number; to: number },\n insertionUnits: StoryUnit[],\n): boolean {\n if (insertionUnits.some((unit) => unit.kind === \"paragraph_break\")) {\n return true;\n }\n\n return story.units\n .slice(range.from, range.to)\n .some((unit) => unit.kind === \"paragraph_break\");\n}\n","import type { CanonicalDocumentEnvelope, SelectionSnapshot } from \"../state/editor-state.ts\";\nimport {\n applyTextTransaction,\n type TextTransactionResult,\n} from \"../state/text-transaction.ts\";\n\nexport interface TextCommandContext {\n timestamp: string;\n}\n\nexport function insertText(\n document: CanonicalDocumentEnvelope,\n selection: SelectionSnapshot,\n text: string,\n context: TextCommandContext,\n): TextTransactionResult {\n return applyTextTransaction(\n document,\n selection,\n {\n type: \"replace\",\n insertion: [\n {\n type: \"text\",\n text,\n },\n ],\n },\n context,\n );\n}\n\nexport function deleteSelectionOrBackward(\n document: CanonicalDocumentEnvelope,\n selection: SelectionSnapshot,\n context: TextCommandContext,\n): TextTransactionResult {\n return applyTextTransaction(\n document,\n selection,\n selection.isCollapsed\n ? {\n type: \"delete_backward\",\n }\n : {\n type: \"replace\",\n insertion: [],\n },\n context,\n );\n}\n\nexport function deleteSelectionOrForward(\n document: CanonicalDocumentEnvelope,\n selection: SelectionSnapshot,\n context: TextCommandContext,\n): TextTransactionResult {\n return applyTextTransaction(\n document,\n selection,\n selection.isCollapsed\n ? {\n type: \"delete_forward\",\n }\n : {\n type: \"replace\",\n insertion: [],\n },\n context,\n );\n}\n\nexport function insertTab(\n document: CanonicalDocumentEnvelope,\n selection: SelectionSnapshot,\n context: TextCommandContext,\n): TextTransactionResult {\n return applyTextTransaction(\n document,\n selection,\n {\n type: \"replace\",\n insertion: [{ type: \"tab\" }],\n },\n context,\n );\n}\n\nexport function insertHardBreak(\n document: CanonicalDocumentEnvelope,\n selection: SelectionSnapshot,\n context: TextCommandContext,\n): TextTransactionResult {\n return applyTextTransaction(\n document,\n selection,\n {\n type: \"replace\",\n insertion: [{ type: \"hard_break\" }],\n },\n context,\n );\n}\n\nexport function splitParagraph(\n document: CanonicalDocumentEnvelope,\n selection: SelectionSnapshot,\n context: TextCommandContext,\n): TextTransactionResult {\n return applyTextTransaction(\n document,\n selection,\n {\n type: \"replace\",\n insertion: [{ type: \"paragraph_break\" }],\n },\n context,\n );\n}\n","import { parseTextStory } from \"../schema/text-schema.ts\";\nimport {\n DEFAULT_BOUNDARY_ASSOC,\n createDetachedAnchor,\n createRangeAnchor,\n mapAnchor,\n normalizeRange,\n type BoundaryAssoc,\n type DetachedAnchor,\n type DocRange,\n type EditorAnchorProjection,\n type TransactionMapping,\n} from \"./mapping.ts\";\n\nexport type ReviewAnchor = EditorAnchorProjection;\n\nexport const COMMENT_RANGE_ASSOC: BoundaryAssoc = DEFAULT_BOUNDARY_ASSOC;\n\nexport function createCommentReviewAnchor(\n from: number,\n to = from,\n assoc: BoundaryAssoc = COMMENT_RANGE_ASSOC,\n): ReviewAnchor {\n return createRangeAnchor(from, to, assoc);\n}\n\nexport function detachReviewAnchor(\n lastKnownRange: DocRange,\n reason: DetachedAnchor[\"reason\"],\n): DetachedAnchor {\n return createDetachedAnchor(lastKnownRange, reason);\n}\n\nexport function mapReviewAnchor(\n anchor: ReviewAnchor,\n mapping: TransactionMapping,\n): ReviewAnchor {\n return mapAnchor(anchor, mapping);\n}\n\nexport function getAnchorRange(anchor: ReviewAnchor): DocRange {\n if (anchor.kind === \"range\") {\n return normalizeRange(anchor.range);\n }\n\n if (anchor.kind === \"node\") {\n return { from: anchor.at, to: anchor.at };\n }\n\n return normalizeRange(anchor.lastKnownRange);\n}\n\nexport function mappingTouchesAnchorContent(\n anchor: ReviewAnchor,\n mapping: TransactionMapping,\n): boolean {\n const range = getAnchorRange(anchor);\n\n if (range.from === range.to) {\n return mapping.steps.some(\n (step) => step.from <= range.from && step.to >= range.to,\n );\n }\n\n return mapping.steps.some(\n (step) => step.from < range.to && step.to > range.from,\n );\n}\n\nexport function rangeStaysWithinSingleParagraph(\n content: unknown,\n range: DocRange,\n): boolean {\n const normalized = normalizeRange(range);\n if (normalized.from === normalized.to) {\n return true;\n }\n\n const story = parseTextStory(content);\n const upperBound = Math.min(normalized.to, story.units.length);\n\n for (let index = Math.max(0, normalized.from); index < upperBound; index += 1) {\n const unit = story.units[index];\n if (!unit) {\n continue;\n }\n\n if (unit.kind === \"paragraph_break\" || unit.kind === \"opaque_block\") {\n return false;\n }\n }\n\n return true;\n}\n","import type { CommentThreadRecord, EditorWarning } from \"../../core/state/editor-state.ts\";\nimport {\n detachReviewAnchor,\n getAnchorRange,\n mapReviewAnchor,\n mappingTouchesAnchorContent,\n rangeStaysWithinSingleParagraph,\n type ReviewAnchor,\n} from \"../../core/selection/review-anchors.ts\";\nimport type { TransactionMapping } from \"../../core/selection/mapping.ts\";\n\nexport interface RemapCommentThreadsOptions {\n comments: Record<string, CommentThreadRecord>;\n mapping: TransactionMapping;\n nextContent: unknown;\n existingWarnings?: EditorWarning[];\n}\n\nexport interface RemapCommentThreadsResult {\n comments: Record<string, CommentThreadRecord>;\n warnings: EditorWarning[];\n detachedCommentIds: string[];\n}\n\nexport function remapCommentThreads(\n options: RemapCommentThreadsOptions,\n): RemapCommentThreadsResult {\n const comments = Object.fromEntries(\n Object.entries(options.comments).map(([commentId, comment]) => [\n commentId,\n remapCommentThread(comment, options.mapping, options.nextContent),\n ]),\n );\n const detachedCommentIds = Object.values(comments)\n .filter((comment) => comment.anchor.kind === \"detached\")\n .map((comment) => comment.commentId);\n\n return {\n comments,\n warnings: mergeDetachedAnchorWarnings(comments, options.existingWarnings ?? []),\n detachedCommentIds,\n };\n}\n\nexport function remapCommentThread(\n comment: CommentThreadRecord,\n mapping: TransactionMapping,\n nextContent: unknown,\n): CommentThreadRecord {\n if (comment.anchor.kind === \"detached\") {\n return comment;\n }\n\n const mappedAnchor = mapReviewAnchor(comment.anchor, mapping);\n const anchor = normalizeCommentAnchor(comment.anchor, mappedAnchor, mapping, nextContent);\n\n return {\n ...comment,\n anchor,\n };\n}\n\nfunction normalizeCommentAnchor(\n previousAnchor: ReviewAnchor,\n mappedAnchor: ReviewAnchor,\n mapping: TransactionMapping,\n nextContent: unknown,\n): ReviewAnchor {\n if (mappedAnchor.kind === \"detached\") {\n return mappedAnchor;\n }\n\n const previousRange = getAnchorRange(previousAnchor);\n const mappedRange = getAnchorRange(mappedAnchor);\n\n if (\n previousAnchor.kind === \"range\" &&\n previousRange.from < previousRange.to &&\n mappedAnchor.kind === \"range\" &&\n mappedRange.from === mappedRange.to &&\n mappingTouchesAnchorContent(previousAnchor, mapping)\n ) {\n return detachReviewAnchor(previousRange, detachReason(mapping));\n }\n\n if (\n mappedAnchor.kind === \"range\" &&\n !rangeStaysWithinSingleParagraph(nextContent, mappedAnchor.range)\n ) {\n return detachReviewAnchor(previousRange, \"invalidatedByStructureChange\");\n }\n\n return mappedAnchor;\n}\n\nfunction detachReason(\n mapping: TransactionMapping,\n): \"deleted\" | \"invalidatedByStructureChange\" {\n return mapping.metadata?.invalidatesStructures\n ? \"invalidatedByStructureChange\"\n : \"deleted\";\n}\n\nfunction mergeDetachedAnchorWarnings(\n comments: Record<string, CommentThreadRecord>,\n existingWarnings: EditorWarning[],\n): EditorWarning[] {\n const retainedWarnings = existingWarnings.filter(\n (warning) =>\n warning.code !== \"comment_anchor_detached\" ||\n !warning.details ||\n typeof warning.details.commentId !== \"string\" ||\n comments[warning.details.commentId]?.anchor.kind === \"detached\",\n );\n\n const knownDetachedIds = new Set(\n retainedWarnings\n .filter((warning) => warning.code === \"comment_anchor_detached\")\n .map((warning) =>\n typeof warning.details?.commentId === \"string\"\n ? warning.details.commentId\n : undefined,\n )\n .filter((value): value is string => Boolean(value)),\n );\n\n const detachedWarnings = Object.values(comments)\n .filter(\n (comment) =>\n comment.anchor.kind === \"detached\" && !knownDetachedIds.has(comment.commentId),\n )\n .map((comment) => createDetachedCommentWarning(comment));\n\n return [...retainedWarnings, ...detachedWarnings];\n}\n\nfunction createDetachedCommentWarning(\n comment: CommentThreadRecord,\n): EditorWarning {\n const anchor = comment.anchor.kind === \"detached\" ? comment.anchor : undefined;\n\n return {\n warningId: `warning:comment-anchor-detached:${comment.commentId}`,\n code: \"comment_anchor_detached\",\n severity: \"warning\",\n message: `Comment ${comment.commentId} detached after edit remapping.`,\n source: \"review\",\n affectedAnchor: anchor,\n details: {\n commentId: comment.commentId,\n reason: anchor?.reason,\n },\n };\n}\n","import {\n createNodeAnchor,\n createRangeAnchor,\n mapAnchor,\n normalizeRange,\n type Assoc,\n type BoundaryAssoc,\n type DocRange,\n type EditorAnchorProjection,\n type TransactionMapping,\n} from \"../../core/selection/mapping.ts\";\n\nexport type RevisionAnchor = EditorAnchorProjection;\n\nexport type SupportedRevisionKind = \"insertion\" | \"deletion\" | \"property-change\";\nexport type PreserveOnlyRevisionKind = \"formatting\" | \"move\";\nexport type RevisionKind = SupportedRevisionKind | PreserveOnlyRevisionKind;\n\nexport type RevisionStatus = \"active\" | \"accepted\" | \"rejected\" | \"detached\";\nexport type RevisionActionability = \"actionable\" | \"preserve-only\";\nexport type RevisionAnchorState = \"active\" | \"detached\";\n\nexport interface PropertyChangeData {\n xmlTag: \"pPrChange\" | \"sectPrChange\" | \"tblPrChange\" | \"rPrChange\";\n beforeXml: string;\n}\n\nexport interface MoveData {\n moveId: string;\n direction: \"from\" | \"to\";\n}\n\nexport interface RevisionMetadataEnvelope {\n source: \"runtime\" | \"import\";\n preserveOnlyReason?: string;\n importedRevisionForm?:\n | \"run-insertion\"\n | \"run-deletion\"\n | \"paragraph-insertion\"\n | \"paragraph-deletion\";\n originalRevisionType?: string;\n ooxmlRevisionId?: string;\n propertyChangeData?: PropertyChangeData;\n moveData?: MoveData;\n}\n\nexport type PropertyChangeRevision = RevisionRecord & {\n kind: \"property-change\";\n metadata: RevisionMetadataEnvelope & { propertyChangeData: PropertyChangeData };\n};\n\nexport type MoveRevision = RevisionRecord & {\n kind: \"move\";\n metadata: RevisionMetadataEnvelope & { moveData: MoveData };\n};\n\nexport interface RevisionRecord {\n revisionId: string;\n kind: RevisionKind;\n anchor: RevisionAnchor;\n authorId: string;\n createdAt: string;\n status: RevisionStatus;\n warningIds: string[];\n metadata: RevisionMetadataEnvelope;\n}\n\nexport interface RevisionAnchorSummary {\n anchor: RevisionAnchor;\n state: RevisionAnchorState;\n range: DocRange;\n}\n\nexport function createRevisionRangeAnchor(\n from: number,\n to = from,\n assoc?: BoundaryAssoc,\n): RevisionAnchor {\n return createRangeAnchor(from, to, assoc);\n}\n\nexport function createRevisionNodeAnchor(at: number, assoc?: Assoc): RevisionAnchor {\n return createNodeAnchor(at, assoc);\n}\n\nexport function remapRevisionAnchor(\n anchor: RevisionAnchor,\n mapping: TransactionMapping,\n): RevisionAnchor {\n return mapAnchor(anchor, mapping);\n}\n\nexport function isDetachedRevisionAnchor(anchor: RevisionAnchor): boolean {\n return anchor.kind === \"detached\";\n}\n\nexport function summarizeRevisionAnchor(anchor: RevisionAnchor): RevisionAnchorSummary {\n if (anchor.kind === \"range\") {\n return {\n anchor,\n state: \"active\",\n range: normalizeRange(anchor.range),\n };\n }\n\n if (anchor.kind === \"node\") {\n return {\n anchor,\n state: \"active\",\n range: {\n from: anchor.at,\n to: anchor.at,\n },\n };\n }\n\n return {\n anchor,\n state: \"detached\",\n range: normalizeRange(anchor.lastKnownRange),\n };\n}\n\nexport function getRevisionActionability(\n revision:\n | RevisionKind\n | Pick<RevisionRecord, \"kind\" | \"metadata\">,\n): RevisionActionability {\n if (\n typeof revision !== \"string\" &&\n typeof revision.metadata.preserveOnlyReason === \"string\" &&\n revision.metadata.preserveOnlyReason.length > 0\n ) {\n return \"preserve-only\";\n }\n\n const kind = typeof revision === \"string\" ? revision : revision.kind;\n switch (kind) {\n case \"insertion\":\n case \"deletion\":\n case \"property-change\":\n return \"actionable\";\n case \"formatting\":\n case \"move\":\n return \"preserve-only\";\n }\n}\n\nexport function isRevisionActionable(\n record: Pick<RevisionRecord, \"kind\" | \"metadata\" | \"status\">,\n): boolean {\n return getRevisionActionability(record) === \"actionable\" && record.status === \"active\";\n}\n\nexport function describeRevisionKind(kind: RevisionKind): string {\n switch (kind) {\n case \"insertion\":\n return \"Insertion\";\n case \"deletion\":\n return \"Deletion\";\n case \"formatting\":\n return \"Formatting change\";\n case \"move\":\n return \"Move\";\n case \"property-change\":\n return \"Property change\";\n }\n}\n","import type { TransactionMapping } from \"../../core/selection/mapping.ts\";\nimport {\n describeRevisionKind,\n getRevisionActionability,\n isDetachedRevisionAnchor,\n isRevisionActionable,\n remapRevisionAnchor,\n summarizeRevisionAnchor,\n type RevisionActionability,\n type RevisionKind,\n type RevisionMetadataEnvelope,\n type RevisionRecord,\n type RevisionStatus,\n} from \"./revision-types.ts\";\n\nexport interface RevisionStore {\n version: \"revision-store/1\";\n revisions: Record<string, RevisionRecord>;\n}\n\nexport interface CreateRevisionRecordParams {\n revisionId: string;\n kind: RevisionKind;\n anchor: RevisionRecord[\"anchor\"];\n authorId: string;\n createdAt: string;\n status?: Exclude<RevisionStatus, \"detached\">;\n warningIds?: string[];\n metadata?: Partial<RevisionMetadataEnvelope>;\n}\n\nexport interface RevisionSidebarEntry {\n revisionId: string;\n kind: RevisionKind;\n label: string;\n status: RevisionStatus;\n actionability: RevisionActionability;\n anchorLabel: string;\n createdAt: string;\n authorId: string;\n warningCount: number;\n canAccept: boolean;\n canReject: boolean;\n preserveOnlyReason?: string;\n}\n\nexport interface RevisionSidebarProjection {\n totalCount: number;\n activeRevisionIds: string[];\n acceptedRevisionIds: string[];\n rejectedRevisionIds: string[];\n detachedRevisionIds: string[];\n actionableRevisionIds: string[];\n preserveOnlyRevisionIds: string[];\n revisions: RevisionSidebarEntry[];\n}\n\nexport function createRevisionStore(\n revisions: Record<string, RevisionRecord> = {},\n): RevisionStore {\n return {\n version: \"revision-store/1\",\n revisions,\n };\n}\n\nexport function createRevisionRecord(\n params: CreateRevisionRecordParams,\n): RevisionRecord {\n return normalizeRevisionRecord({\n revisionId: params.revisionId,\n kind: params.kind,\n anchor: params.anchor,\n authorId: params.authorId,\n createdAt: params.createdAt,\n status: params.status ?? \"active\",\n warningIds: [...(params.warningIds ?? [])],\n metadata: {\n source: params.metadata?.source ?? \"runtime\",\n preserveOnlyReason:\n params.metadata?.preserveOnlyReason ??\n (getRevisionActionability(params.kind) === \"preserve-only\"\n ? \"Imported preserve-only revision.\"\n : undefined),\n importedRevisionForm: params.metadata?.importedRevisionForm,\n originalRevisionType: params.metadata?.originalRevisionType,\n ooxmlRevisionId: params.metadata?.ooxmlRevisionId,\n propertyChangeData: params.metadata?.propertyChangeData,\n moveData: params.metadata?.moveData,\n },\n });\n}\n\nexport function upsertRevisionRecord(\n store: RevisionStore,\n revision: RevisionRecord,\n): RevisionStore {\n return {\n ...store,\n revisions: {\n ...store.revisions,\n [revision.revisionId]: normalizeRevisionRecord(revision),\n },\n };\n}\n\nexport function setRevisionStatus(\n store: RevisionStore,\n revisionId: string,\n status: Exclude<RevisionStatus, \"detached\">,\n): RevisionStore {\n const existing = store.revisions[revisionId];\n if (!existing) {\n return store;\n }\n\n if (existing.status === \"detached\") {\n return store;\n }\n\n if (\n (status === \"accepted\" || status === \"rejected\") &&\n getRevisionActionability(existing) !== \"actionable\"\n ) {\n return store;\n }\n\n return upsertRevisionRecord(store, {\n ...existing,\n status,\n });\n}\n\nexport function setRevisionWarnings(\n store: RevisionStore,\n revisionId: string,\n warningIds: string[],\n): RevisionStore {\n const existing = store.revisions[revisionId];\n if (!existing) {\n return store;\n }\n\n return upsertRevisionRecord(store, {\n ...existing,\n warningIds: [...warningIds],\n });\n}\n\nexport function remapRevisionStore(\n store: RevisionStore,\n mapping: TransactionMapping,\n): RevisionStore {\n return createRevisionStore(\n Object.fromEntries(\n Object.entries(store.revisions).map(([revisionId, revision]) => {\n const anchor = remapRevisionAnchor(revision.anchor, mapping);\n const status =\n anchor.kind === \"detached\"\n ? \"detached\"\n : revision.status === \"accepted\" || revision.status === \"rejected\"\n ? revision.status\n : \"active\";\n\n return [\n revisionId,\n normalizeRevisionRecord({\n ...revision,\n anchor,\n status,\n }),\n ];\n }),\n ),\n );\n}\n\nexport function createRevisionSidebarProjection(\n store: RevisionStore,\n): RevisionSidebarProjection {\n const revisions = Object.values(store.revisions)\n .map(toSidebarEntry)\n .sort(compareRevisionEntries);\n\n return {\n totalCount: revisions.length,\n activeRevisionIds: revisions\n .filter((revision) => revision.status === \"active\")\n .map((revision) => revision.revisionId),\n acceptedRevisionIds: revisions\n .filter((revision) => revision.status === \"accepted\")\n .map((revision) => revision.revisionId),\n rejectedRevisionIds: revisions\n .filter((revision) => revision.status === \"rejected\")\n .map((revision) => revision.revisionId),\n detachedRevisionIds: revisions\n .filter((revision) => revision.status === \"detached\")\n .map((revision) => revision.revisionId),\n actionableRevisionIds: revisions\n .filter((revision) => revision.actionability === \"actionable\")\n .map((revision) => revision.revisionId),\n preserveOnlyRevisionIds: revisions\n .filter((revision) => revision.actionability === \"preserve-only\")\n .map((revision) => revision.revisionId),\n revisions,\n };\n}\n\nfunction toSidebarEntry(revision: RevisionRecord): RevisionSidebarEntry {\n const anchorSummary = summarizeRevisionAnchor(revision.anchor);\n const actionability = getRevisionActionability(revision);\n\n return {\n revisionId: revision.revisionId,\n kind: revision.kind,\n label: describeRevisionKind(revision.kind),\n status: revision.status,\n actionability,\n anchorLabel:\n anchorSummary.state === \"detached\"\n ? `Detached ${anchorSummary.range.from}-${anchorSummary.range.to}`\n : `Range ${anchorSummary.range.from}-${anchorSummary.range.to}`,\n createdAt: revision.createdAt,\n authorId: revision.authorId,\n warningCount: revision.warningIds.length,\n canAccept: isRevisionActionable(revision),\n canReject: isRevisionActionable(revision),\n preserveOnlyReason: revision.metadata.preserveOnlyReason,\n };\n}\n\nfunction normalizeRevisionRecord(revision: RevisionRecord): RevisionRecord {\n const actionability = getRevisionActionability(revision);\n\n if (isDetachedRevisionAnchor(revision.anchor)) {\n return {\n ...revision,\n status: \"detached\",\n metadata: {\n ...revision.metadata,\n preserveOnlyReason:\n revision.metadata.preserveOnlyReason ??\n (actionability === \"preserve-only\"\n ? \"Imported preserve-only revision.\"\n : undefined),\n },\n };\n }\n\n if (actionability === \"preserve-only\" && revision.status !== \"detached\") {\n return {\n ...revision,\n status: revision.status === \"accepted\" || revision.status === \"rejected\" ? \"active\" : revision.status,\n metadata: {\n ...revision.metadata,\n preserveOnlyReason:\n revision.metadata.preserveOnlyReason ?? \"Imported preserve-only revision.\",\n },\n };\n }\n\n return revision;\n}\n\nfunction compareRevisionEntries(\n left: RevisionSidebarEntry,\n right: RevisionSidebarEntry,\n): number {\n const statusDelta = priorityForStatus(left.status) - priorityForStatus(right.status);\n if (statusDelta !== 0) {\n return statusDelta;\n }\n\n const actionabilityDelta =\n priorityForActionability(left.actionability) - priorityForActionability(right.actionability);\n if (actionabilityDelta !== 0) {\n return actionabilityDelta;\n }\n\n return left.createdAt.localeCompare(right.createdAt);\n}\n\nfunction priorityForStatus(status: RevisionStatus): number {\n switch (status) {\n case \"active\":\n return 0;\n case \"detached\":\n return 1;\n case \"accepted\":\n return 2;\n case \"rejected\":\n return 3;\n }\n}\n\nfunction priorityForActionability(actionability: RevisionActionability): number {\n switch (actionability) {\n case \"actionable\":\n return 0;\n case \"preserve-only\":\n return 1;\n }\n}\n","import { createEmptyMapping, type TransactionMapping } from \"../../core/selection/mapping.ts\";\nimport { parseTextStory } from \"../../core/schema/text-schema.ts\";\nimport { createSelectionSnapshot, type CanonicalDocumentEnvelope } from \"../../core/state/editor-state.ts\";\nimport { applyTextTransaction } from \"../../core/state/text-transaction.ts\";\nimport {\n remapRevisionStore,\n setRevisionStatus,\n type RevisionStore,\n} from \"./revision-store.ts\";\nimport { getRevisionActionability, type RevisionRecord } from \"./revision-types.ts\";\n\nexport type RevisionActionIntent = \"accept\" | \"reject\";\n\nexport type RevisionActionSkipReason =\n | \"missing\"\n | \"already-resolved\"\n | \"detached-anchor\"\n | \"preserve-only\"\n | \"structural-range\"\n | \"protected-range\"\n | \"invalid-range\";\n\nexport interface ApplyRevisionActionOptions {\n document: CanonicalDocumentEnvelope;\n store: RevisionStore;\n revisionId: string;\n intent: RevisionActionIntent;\n timestamp: string;\n}\n\nexport interface AppliedRevisionAction {\n kind: \"applied\";\n revisionId: string;\n intent: RevisionActionIntent;\n resultingStatus: \"accepted\" | \"rejected\";\n contentChanged: boolean;\n}\n\nexport interface SkippedRevisionAction {\n kind: \"skipped\";\n revisionId: string;\n intent: RevisionActionIntent;\n reason: RevisionActionSkipReason;\n detail: string;\n}\n\nexport type RevisionActionOutcome =\n | AppliedRevisionAction\n | SkippedRevisionAction;\n\nexport interface ApplyRevisionActionResult {\n document: CanonicalDocumentEnvelope;\n store: RevisionStore;\n mapping: TransactionMapping;\n outcome: RevisionActionOutcome;\n detachedRevisionIds: string[];\n}\n\nexport function applyRevisionAction(\n options: ApplyRevisionActionOptions,\n): ApplyRevisionActionResult {\n const revision = options.store.revisions[options.revisionId];\n\n if (!revision) {\n return skippedResult(options, \"missing\", \"Revision record was not found.\");\n }\n\n if (revision.status !== \"active\") {\n return skippedResult(\n options,\n \"already-resolved\",\n `Revision is already ${revision.status}.`,\n );\n }\n\n if (revision.anchor.kind === \"detached\") {\n return skippedResult(\n options,\n \"detached-anchor\",\n \"Detached revisions remain visible but cannot be accepted or rejected.\",\n );\n }\n\n if (getRevisionActionability(revision) !== \"actionable\") {\n return skippedResult(\n options,\n \"preserve-only\",\n revision.metadata.preserveOnlyReason ??\n \"This revision kind remains preserve-only in the current runtime.\",\n );\n }\n\n if (revision.anchor.kind !== \"range\") {\n return skippedResult(\n options,\n \"structural-range\",\n \"Non-range revisions remain preserve-only in the current runtime.\",\n );\n }\n\n const story = parseTextStory(options.document.content);\n const range = normalizeRange(\n revision.anchor.range.from,\n revision.anchor.range.to,\n );\n\n if (range.to > story.size) {\n return skippedResult(\n options,\n \"invalid-range\",\n `Revision range ${range.from}-${range.to} exceeds story size ${story.size}.`,\n );\n }\n\n const paragraphMarkRange = resolveParagraphMarkDeletionRange(story, revision, options.intent);\n if (paragraphMarkRange) {\n const resultingStatus = toResultingStatus(options.intent);\n const textResult = applyTextTransaction(\n options.document,\n createSelectionSnapshot(paragraphMarkRange.from, paragraphMarkRange.to),\n {\n type: \"replace\",\n range: paragraphMarkRange,\n insertion: [],\n },\n {\n timestamp: options.timestamp,\n },\n );\n\n const nextStore = remapRevisionStore(\n setRevisionStatus(options.store, revision.revisionId, resultingStatus),\n textResult.mapping,\n );\n\n return {\n document: textResult.document,\n store: nextStore,\n mapping: textResult.mapping,\n outcome: {\n kind: \"applied\",\n revisionId: revision.revisionId,\n intent: options.intent,\n resultingStatus,\n contentChanged: true,\n },\n detachedRevisionIds: findNewDetachedRevisionIds(options.store, nextStore),\n };\n }\n if (requiresParagraphBoundaryDeletion(revision, options.intent)) {\n return skippedResult(\n options,\n \"structural-range\",\n \"Paragraph-boundary revisions need a stable paragraph break and remain blocked for this shape.\",\n );\n }\n\n const slice = story.units.slice(range.from, range.to);\n if (\n slice.some(\n (unit) =>\n unit.kind === \"paragraph_break\" || unit.kind === \"opaque_block\",\n )\n ) {\n return skippedResult(\n options,\n \"structural-range\",\n \"Paragraph-boundary and structural revisions remain preserve-only.\",\n );\n }\n\n if (\n slice.some(\n (unit) =>\n unit.kind === \"image\" || unit.kind === \"opaque_inline\",\n )\n ) {\n return skippedResult(\n options,\n \"protected-range\",\n \"Revisions touching protected inline content remain preserve-only.\",\n );\n }\n\n const resultingStatus = toResultingStatus(options.intent);\n const contentChanged = requiresContentDeletion(revision, options.intent);\n\n if (!contentChanged) {\n return {\n document: options.document,\n store: setRevisionStatus(options.store, revision.revisionId, resultingStatus),\n mapping: createEmptyMapping(),\n outcome: {\n kind: \"applied\",\n revisionId: revision.revisionId,\n intent: options.intent,\n resultingStatus,\n contentChanged: false,\n },\n detachedRevisionIds: [],\n };\n }\n\n const textResult = applyTextTransaction(\n options.document,\n createSelectionSnapshot(range.from, range.to),\n {\n type: \"replace\",\n range,\n insertion: [],\n },\n {\n timestamp: options.timestamp,\n },\n );\n\n const nextStore = remapRevisionStore(\n setRevisionStatus(options.store, revision.revisionId, resultingStatus),\n textResult.mapping,\n );\n\n return {\n document: textResult.document,\n store: nextStore,\n mapping: textResult.mapping,\n outcome: {\n kind: \"applied\",\n revisionId: revision.revisionId,\n intent: options.intent,\n resultingStatus,\n contentChanged: true,\n },\n detachedRevisionIds: findNewDetachedRevisionIds(options.store, nextStore),\n };\n}\n\nfunction skippedResult(\n options: ApplyRevisionActionOptions,\n reason: RevisionActionSkipReason,\n detail: string,\n): ApplyRevisionActionResult {\n return {\n document: options.document,\n store: options.store,\n mapping: createEmptyMapping(),\n outcome: {\n kind: \"skipped\",\n revisionId: options.revisionId,\n intent: options.intent,\n reason,\n detail,\n },\n detachedRevisionIds: [],\n };\n}\n\nfunction toResultingStatus(\n intent: RevisionActionIntent,\n): \"accepted\" | \"rejected\" {\n return intent === \"accept\" ? \"accepted\" : \"rejected\";\n}\n\nfunction requiresContentDeletion(\n revision: Pick<RevisionRecord, \"kind\">,\n intent: RevisionActionIntent,\n): boolean {\n return (\n (revision.kind === \"insertion\" && intent === \"reject\") ||\n (revision.kind === \"deletion\" && intent === \"accept\")\n );\n}\n\nfunction requiresParagraphBoundaryDeletion(\n revision: RevisionRecord,\n intent: RevisionActionIntent,\n): boolean {\n return (\n (revision.metadata.originalRevisionType === \"paragraph-del\" && intent === \"accept\") ||\n (revision.metadata.originalRevisionType === \"paragraph-ins\" && intent === \"reject\")\n );\n}\n\nfunction resolveParagraphMarkDeletionRange(\n story: ReturnType<typeof parseTextStory>,\n revision: RevisionRecord,\n intent: RevisionActionIntent,\n): { from: number; to: number } | undefined {\n const originalRevisionType = revision.metadata.originalRevisionType;\n if (\n revision.anchor.kind !== \"range\" ||\n (originalRevisionType !== \"paragraph-del\" && originalRevisionType !== \"paragraph-ins\")\n ) {\n return undefined;\n }\n\n const shouldDeleteBoundary =\n (originalRevisionType === \"paragraph-del\" && intent === \"accept\") ||\n (originalRevisionType === \"paragraph-ins\" && intent === \"reject\");\n if (!shouldDeleteBoundary) {\n return undefined;\n }\n\n const paragraphs = mapParagraphRanges(story);\n const anchorPosition = normalizeRange(\n revision.anchor.range.from,\n revision.anchor.range.to,\n ).from;\n const paragraph = paragraphs.find(\n (candidate) =>\n candidate.end === anchorPosition ||\n (anchorPosition >= candidate.start && anchorPosition <= candidate.end),\n );\n if (!paragraph) {\n return undefined;\n }\n\n if (originalRevisionType === \"paragraph-del\") {\n const boundaryIndex = paragraph.end;\n if (story.units[boundaryIndex]?.kind !== \"paragraph_break\") {\n return undefined;\n }\n\n return {\n from: boundaryIndex,\n to: boundaryIndex + 1,\n };\n }\n\n const boundaryIndex = paragraph.start - 1;\n if (boundaryIndex < 0 || story.units[boundaryIndex]?.kind !== \"paragraph_break\") {\n return undefined;\n }\n\n return {\n from: boundaryIndex,\n to: boundaryIndex + 1,\n };\n}\n\nfunction mapParagraphRanges(\n story: ReturnType<typeof parseTextStory>,\n): Array<{ start: number; end: number }> {\n const paragraphs: Array<{ start: number; end: number }> = [];\n let start = 0;\n let hasPendingParagraph = true;\n\n for (let index = 0; index < story.units.length; index += 1) {\n const unit = story.units[index];\n if (unit.kind === \"paragraph_break\") {\n paragraphs.push({ start, end: index });\n start = index + 1;\n hasPendingParagraph = true;\n continue;\n }\n\n if (unit.kind === \"opaque_block\") {\n if (hasPendingParagraph) {\n paragraphs.push({ start, end: index });\n }\n start = index + 1;\n hasPendingParagraph = Boolean(unit.nextParagraph);\n }\n }\n\n if (hasPendingParagraph) {\n paragraphs.push({ start, end: story.units.length });\n }\n return paragraphs;\n}\n\nfunction normalizeRange(from: number, to: number): { from: number; to: number } {\n return {\n from: Math.min(from, to),\n to: Math.max(from, to),\n };\n}\n\nfunction findNewDetachedRevisionIds(\n previousStore: RevisionStore,\n nextStore: RevisionStore,\n): string[] {\n const detachedRevisionIds: string[] = [];\n\n for (const [revisionId, revision] of Object.entries(nextStore.revisions)) {\n if (\n revision.status === \"detached\" &&\n previousStore.revisions[revisionId]?.status !== \"detached\"\n ) {\n detachedRevisionIds.push(revisionId);\n }\n }\n\n return detachedRevisionIds;\n}\n","import type { CanonicalDocumentEnvelope } from \"../core/state/editor-state.ts\";\nimport {\n getReviewCommandIntent,\n isSingleRevisionReviewCommand,\n type ReviewCommand,\n} from \"../core/commands/review-commands.ts\";\nimport type { TransactionMapping } from \"../core/selection/mapping.ts\";\nimport {\n applyRevisionAction,\n type RevisionActionOutcome,\n} from \"../review/store/revision-actions.ts\";\nimport { type RevisionStore } from \"../review/store/revision-store.ts\";\n\nexport interface RevisionRuntimeState {\n document: CanonicalDocumentEnvelope;\n store: RevisionStore;\n}\n\nexport interface ApplyRevisionRuntimeCommandOptions {\n state: RevisionRuntimeState;\n command: ReviewCommand;\n timestamp: string;\n}\n\nexport interface RevisionRuntimeCommandEffects {\n appliedRevisionIds: string[];\n skippedRevisions: RevisionActionOutcome[];\n detachedRevisionIds: string[];\n}\n\nexport interface RevisionRuntimeCommandResult extends RevisionRuntimeState {\n outcomes: RevisionActionOutcome[];\n mappings: Array<{ revisionId: string; mapping: TransactionMapping; steps: number }>;\n effects: RevisionRuntimeCommandEffects;\n}\n\nexport function applyRevisionRuntimeCommand(\n options: ApplyRevisionRuntimeCommandOptions,\n): RevisionRuntimeCommandResult {\n const revisionIds = isSingleRevisionReviewCommand(options.command)\n ? [options.command.revisionId]\n : listBatchRevisionIds(options.state.store);\n\n const outcomes: RevisionActionOutcome[] = [];\n const mappings: Array<{ revisionId: string; steps: number }> = [];\n const appliedRevisionIds: string[] = [];\n const detachedRevisionIds = new Set<string>();\n\n let state = options.state;\n\n for (const revisionId of revisionIds) {\n const result = applyRevisionAction({\n document: state.document,\n store: state.store,\n revisionId,\n intent: getReviewCommandIntent(options.command),\n timestamp: options.timestamp,\n });\n\n state = {\n document: result.document,\n store: result.store,\n };\n outcomes.push(result.outcome);\n mappings.push({\n revisionId,\n mapping: result.mapping,\n steps: result.mapping.steps.length,\n });\n\n if (result.outcome.kind === \"applied\") {\n appliedRevisionIds.push(revisionId);\n }\n\n for (const detachedRevisionId of result.detachedRevisionIds) {\n detachedRevisionIds.add(detachedRevisionId);\n }\n }\n\n return {\n ...state,\n outcomes,\n mappings,\n effects: {\n appliedRevisionIds,\n skippedRevisions: outcomes.filter(\n (outcome): outcome is Extract<RevisionActionOutcome, { kind: \"skipped\" }> =>\n outcome.kind === \"skipped\",\n ),\n detachedRevisionIds: [...detachedRevisionIds],\n },\n };\n}\n\nfunction listBatchRevisionIds(store: RevisionStore): string[] {\n return Object.values(store.revisions)\n .filter((revision) => revision.status === \"active\")\n .sort((left, right) => {\n const createdAtDelta = left.createdAt.localeCompare(right.createdAt);\n if (createdAtDelta !== 0) {\n return createdAtDelta;\n }\n\n return left.revisionId.localeCompare(right.revisionId);\n })\n .map((revision) => revision.revisionId);\n}\n","import {\n createSelectionSnapshot,\n type CanonicalDocumentEnvelope,\n type CommentThreadRecord,\n type EditorState,\n type EditorWarning,\n normalizeCommentThreadRecord,\n type SelectionSnapshot,\n} from \"../state/editor-state.ts\";\nimport {\n areAnchorsEqual,\n createEmptyMapping,\n mapAnchor,\n type EditorAnchorProjection,\n type MappingStep,\n type TransactionMapping,\n} from \"../selection/mapping.ts\";\nimport {\n createAcceptRevisionCommand,\n createRejectRevisionCommand,\n type ReviewCommand,\n} from \"./review-commands.ts\";\nimport {\n deleteSelectionOrBackward,\n deleteSelectionOrForward,\n insertHardBreak,\n insertTab,\n insertText,\n splitParagraph,\n} from \"./text-commands.ts\";\nimport { remapCommentThreads } from \"../../review/store/comment-remapping.ts\";\nimport { applyRevisionRuntimeCommand } from \"../../runtime/revision-runtime.ts\";\nimport type { RevisionStore } from \"../../review/store/revision-store.ts\";\n\nexport interface CommandOrigin {\n source:\n | \"keyboard\"\n | \"toolbar\"\n | \"context_menu\"\n | \"comment_panel\"\n | \"review_panel\"\n | \"api\"\n | \"runtime\";\n timestamp: string;\n}\n\nexport type EditorCommand =\n | {\n type: \"selection.set\";\n selection: SelectionSnapshot;\n origin?: CommandOrigin;\n }\n | {\n type: \"document.replace\";\n document: CanonicalDocumentEnvelope;\n mapping?: TransactionMapping;\n selection?: SelectionSnapshot;\n origin?: CommandOrigin;\n }\n | {\n type: \"text.insert\";\n text: string;\n origin?: CommandOrigin;\n }\n | {\n type: \"text.delete-backward\";\n origin?: CommandOrigin;\n }\n | {\n type: \"text.delete-forward\";\n origin?: CommandOrigin;\n }\n | {\n type: \"text.insert-tab\";\n origin?: CommandOrigin;\n }\n | {\n type: \"text.insert-hard-break\";\n origin?: CommandOrigin;\n }\n | {\n type: \"paragraph.split\";\n origin?: CommandOrigin;\n }\n | {\n type: \"runtime.set-read-only\";\n readOnly: boolean;\n origin?: CommandOrigin;\n }\n | {\n type: \"runtime.focus\";\n focused: boolean;\n origin?: CommandOrigin;\n }\n | {\n type: \"warning.add\";\n warning: EditorWarning;\n origin?: CommandOrigin;\n }\n | {\n type: \"warning.clear\";\n warningId: string;\n origin?: CommandOrigin;\n }\n | {\n type: \"comment.add\";\n comment: CommentThreadRecord;\n origin?: CommandOrigin;\n }\n | {\n type: \"comment.open\";\n commentId: string;\n origin?: CommandOrigin;\n }\n | {\n type: \"comment.resolve\";\n commentId: string;\n resolvedBy?: string;\n origin?: CommandOrigin;\n }\n | {\n type: \"comment.reopen\";\n commentId: string;\n origin?: CommandOrigin;\n }\n | {\n type: \"comment.add-reply\";\n commentId: string;\n body: string;\n authorId?: string;\n origin?: CommandOrigin;\n }\n | {\n type: \"comment.edit-body\";\n commentId: string;\n body: string;\n origin?: CommandOrigin;\n }\n | {\n type: \"change.accept\";\n changeId: string;\n origin?: CommandOrigin;\n }\n | {\n type: \"change.reject\";\n changeId: string;\n origin?: CommandOrigin;\n }\n | {\n type: \"change.accept-all\";\n origin?: CommandOrigin;\n }\n | {\n type: \"change.reject-all\";\n origin?: CommandOrigin;\n }\n | {\n type: \"history.undo\";\n origin?: CommandOrigin;\n }\n | {\n type: \"history.redo\";\n origin?: CommandOrigin;\n };\n\nexport interface TransactionEffects {\n warningsAdded: EditorWarning[];\n warningsCleared: Array<{ warningId: string; code: EditorWarning[\"code\"] }>;\n commentAdded?: { commentId: string; anchor: EditorAnchorProjection };\n commentResolved?: { commentId: string };\n commentReopened?: { commentId: string };\n commentReplyAdded?: { commentId: string };\n commentBodyEdited?: { commentId: string };\n changeAccepted?: { changeId: string };\n changeRejected?: { changeId: string };\n}\n\nexport interface EditorTransaction {\n nextState: EditorState;\n mapping: TransactionMapping;\n effects: TransactionEffects;\n historyBoundary: \"push\" | \"skip\";\n markDirty: boolean;\n}\n\nexport interface CommandExecutionContext {\n timestamp: string;\n}\n\nexport function executeEditorCommand(\n state: EditorState,\n command: Exclude<EditorCommand, { type: \"history.undo\" } | { type: \"history.redo\" }>,\n context: CommandExecutionContext,\n): EditorTransaction {\n switch (command.type) {\n case \"selection.set\":\n return createTransaction(\n {\n ...state,\n selection: normalizeSelection(command.selection),\n },\n {\n historyBoundary: \"skip\",\n markDirty: false,\n },\n );\n case \"document.replace\": {\n const mapping = command.mapping ?? createEmptyMapping();\n const selection =\n command.selection ?? remapSelection(state.selection, mapping);\n const reviewState = remapReviewStateAfterContentChange(\n state,\n command.document,\n mapping,\n );\n\n return createTransaction(\n {\n ...state,\n document: reviewState.document,\n selection,\n warnings: reviewState.warnings,\n runtime: {\n ...state.runtime,\n activeCommentId: reviewState.activeCommentId,\n },\n compatibility: {\n ...state.compatibility,\n generatedAt: context.timestamp,\n warnings: reviewState.warnings,\n featureEntries: state.compatibility.featureEntries.map((entry) =>\n entry.affectedAnchor\n ? {\n ...entry,\n affectedAnchor: mapAnchor(entry.affectedAnchor, mapping),\n }\n : entry,\n ),\n },\n },\n {\n historyBoundary: \"push\",\n markDirty: true,\n mapping,\n effects: reviewState.effects,\n },\n );\n }\n case \"text.insert\":\n return applyTextCommand(state, context.timestamp, (document, selection) =>\n insertText(document, selection, command.text, context),\n );\n case \"text.delete-backward\":\n return applyTextCommand(state, context.timestamp, (document, selection) =>\n deleteSelectionOrBackward(document, selection, context),\n );\n case \"text.delete-forward\":\n return applyTextCommand(state, context.timestamp, (document, selection) =>\n deleteSelectionOrForward(document, selection, context),\n );\n case \"text.insert-tab\":\n return applyTextCommand(state, context.timestamp, (document, selection) =>\n insertTab(document, selection, context),\n );\n case \"text.insert-hard-break\":\n return applyTextCommand(state, context.timestamp, (document, selection) =>\n insertHardBreak(document, selection, context),\n );\n case \"paragraph.split\":\n return applyTextCommand(state, context.timestamp, (document, selection) =>\n splitParagraph(document, selection, context),\n );\n case \"runtime.set-read-only\":\n return createTransaction(\n {\n ...state,\n readOnly: command.readOnly,\n },\n {\n historyBoundary: \"skip\",\n markDirty: false,\n },\n );\n case \"runtime.focus\":\n return createTransaction(\n {\n ...state,\n runtime: {\n ...state.runtime,\n hasFocus: command.focused,\n },\n },\n {\n historyBoundary: \"skip\",\n markDirty: false,\n },\n );\n case \"warning.add\": {\n if (state.warnings.some((warning) => warning.warningId === command.warning.warningId)) {\n return createTransaction(state, {\n historyBoundary: \"skip\",\n markDirty: false,\n });\n }\n\n const warnings = [...state.warnings, command.warning];\n return createTransaction(\n {\n ...state,\n warnings,\n compatibility: {\n ...state.compatibility,\n generatedAt: context.timestamp,\n warnings,\n },\n },\n {\n historyBoundary: \"skip\",\n markDirty: false,\n effects: {\n warningsAdded: [command.warning],\n },\n },\n );\n }\n case \"warning.clear\": {\n const existing = state.warnings.find((warning) => warning.warningId === command.warningId);\n\n if (!existing) {\n return createTransaction(state, {\n historyBoundary: \"skip\",\n markDirty: false,\n });\n }\n\n const warnings = state.warnings.filter((warning) => warning.warningId !== command.warningId);\n return createTransaction(\n {\n ...state,\n warnings,\n compatibility: {\n ...state.compatibility,\n generatedAt: context.timestamp,\n warnings,\n },\n },\n {\n historyBoundary: \"skip\",\n markDirty: false,\n effects: {\n warningsCleared: [\n {\n warningId: existing.warningId,\n code: existing.code,\n },\n ],\n },\n },\n );\n }\n case \"comment.add\": {\n const comments = {\n ...state.document.review.comments,\n [command.comment.commentId]: normalizeCommentThreadRecord(command.comment),\n };\n\n return createTransaction(\n {\n ...state,\n document: {\n ...state.document,\n updatedAt: context.timestamp,\n review: {\n ...state.document.review,\n comments,\n },\n },\n runtime: {\n ...state.runtime,\n activeCommentId: command.comment.commentId,\n },\n },\n {\n historyBoundary: \"push\",\n markDirty: true,\n effects: {\n commentAdded: {\n commentId: command.comment.commentId,\n anchor: command.comment.anchor,\n },\n },\n },\n );\n }\n case \"comment.open\":\n return createTransaction(\n {\n ...state,\n runtime: {\n ...state.runtime,\n activeCommentId: command.commentId,\n },\n },\n {\n historyBoundary: \"skip\",\n markDirty: false,\n },\n );\n case \"comment.resolve\": {\n const existing = state.document.review.comments[command.commentId];\n if (!existing) {\n return createTransaction(state, {\n historyBoundary: \"skip\",\n markDirty: false,\n });\n }\n\n const comments = {\n ...state.document.review.comments,\n [command.commentId]: {\n ...existing,\n status: (existing.anchor.kind === \"detached\" ? \"detached\" : \"resolved\") as \"detached\" | \"resolved\",\n resolution: {\n resolvedAt: context.timestamp,\n resolvedBy:\n command.resolvedBy ??\n existing.createdBy ??\n existing.authorId ??\n existing.entries?.[0]?.authorId ??\n \"unknown\",\n },\n isResolved: true,\n resolvedAt: context.timestamp,\n },\n };\n\n return createTransaction(\n {\n ...state,\n document: {\n ...state.document,\n updatedAt: context.timestamp,\n review: {\n ...state.document.review,\n comments,\n },\n },\n },\n {\n historyBoundary: \"push\",\n markDirty: true,\n effects: {\n commentResolved: {\n commentId: command.commentId,\n },\n },\n },\n );\n }\n case \"comment.reopen\": {\n const existingThread = state.document.review.comments[command.commentId];\n if (!existingThread || existingThread.status === \"detached\") {\n return createTransaction(state, { historyBoundary: \"skip\", markDirty: false });\n }\n const reopenedComments = {\n ...state.document.review.comments,\n [command.commentId]: {\n ...existingThread,\n status: \"open\" as const,\n isResolved: false,\n resolvedAt: undefined,\n resolution: undefined,\n },\n };\n return createTransaction(\n {\n ...state,\n document: {\n ...state.document,\n updatedAt: context.timestamp,\n review: { ...state.document.review, comments: reopenedComments },\n },\n runtime: { ...state.runtime, activeCommentId: command.commentId },\n },\n {\n historyBoundary: \"push\",\n markDirty: true,\n effects: { commentReopened: { commentId: command.commentId } },\n },\n );\n }\n case \"comment.add-reply\": {\n const threadForReply = state.document.review.comments[command.commentId];\n if (!threadForReply) {\n return createTransaction(state, { historyBoundary: \"skip\", markDirty: false });\n }\n // Block reply on resolved or detached threads (must reopen first)\n if (threadForReply.status === \"resolved\" || threadForReply.status === \"detached\") {\n return createTransaction(state, { historyBoundary: \"skip\", markDirty: false });\n }\n const entryId = `${command.commentId}-entry-${(threadForReply.entries?.length ?? 0) + 1}`;\n const newEntry = {\n entryId,\n authorId: command.authorId ?? threadForReply.createdBy ?? \"unknown\",\n body: command.body,\n createdAt: context.timestamp,\n };\n const updatedThread = {\n ...threadForReply,\n entries: [...(threadForReply.entries ?? []), newEntry],\n };\n const replyComments = {\n ...state.document.review.comments,\n [command.commentId]: updatedThread,\n };\n return createTransaction(\n {\n ...state,\n document: {\n ...state.document,\n updatedAt: context.timestamp,\n review: { ...state.document.review, comments: replyComments },\n },\n },\n {\n historyBoundary: \"push\",\n markDirty: true,\n effects: { commentReplyAdded: { commentId: command.commentId } },\n },\n );\n }\n case \"comment.edit-body\": {\n const threadToEdit = state.document.review.comments[command.commentId];\n if (!threadToEdit || !threadToEdit.entries?.length) {\n return createTransaction(state, { historyBoundary: \"skip\", markDirty: false });\n }\n const editedEntries = [...threadToEdit.entries];\n editedEntries[0] = { ...editedEntries[0], body: command.body };\n const editedThread = { ...threadToEdit, entries: editedEntries };\n const editedComments = {\n ...state.document.review.comments,\n [command.commentId]: editedThread,\n };\n return createTransaction(\n {\n ...state,\n document: {\n ...state.document,\n updatedAt: context.timestamp,\n review: { ...state.document.review, comments: editedComments },\n },\n },\n {\n historyBoundary: \"push\",\n markDirty: true,\n effects: { commentBodyEdited: { commentId: command.commentId } },\n },\n );\n }\n case \"change.accept\":\n return applyReviewCommand(\n state,\n createAcceptRevisionCommand(command.changeId, command.origin),\n context.timestamp,\n );\n case \"change.reject\":\n return applyReviewCommand(\n state,\n createRejectRevisionCommand(command.changeId, command.origin),\n context.timestamp,\n );\n case \"change.accept-all\":\n return applyReviewCommand(\n state,\n {\n type: \"review.accept-all-revisions\",\n ...(command.origin ? { origin: command.origin } : {}),\n },\n context.timestamp,\n );\n case \"change.reject-all\":\n return applyReviewCommand(\n state,\n {\n type: \"review.reject-all-revisions\",\n ...(command.origin ? { origin: command.origin } : {}),\n },\n context.timestamp,\n );\n }\n}\n\nexport function remapSelection(\n selection: SelectionSnapshot,\n mapping: TransactionMapping,\n): SelectionSnapshot {\n const activeRange = mapAnchor(selection.activeRange, mapping);\n\n if (activeRange.kind === \"range\") {\n return {\n anchor: activeRange.range.from,\n head: activeRange.range.to,\n isCollapsed: activeRange.range.from === activeRange.range.to,\n activeRange,\n };\n }\n\n if (activeRange.kind === \"node\") {\n return createSelectionSnapshot(activeRange.at, activeRange.at);\n }\n\n return {\n anchor: selection.anchor,\n head: selection.head,\n isCollapsed: selection.anchor === selection.head,\n activeRange,\n };\n}\n\nexport function selectionChanged(\n left: SelectionSnapshot,\n right: SelectionSnapshot,\n): boolean {\n return (\n left.anchor !== right.anchor ||\n left.head !== right.head ||\n left.isCollapsed !== right.isCollapsed ||\n !areAnchorsEqual(left.activeRange, right.activeRange)\n );\n}\n\nfunction createTransaction(\n nextState: EditorState,\n options: {\n mapping?: TransactionMapping;\n historyBoundary: \"push\" | \"skip\";\n markDirty: boolean;\n effects?: Partial<TransactionEffects>;\n },\n): EditorTransaction {\n return {\n nextState,\n mapping: options.mapping ?? createEmptyMapping(),\n historyBoundary: options.historyBoundary,\n markDirty: options.markDirty,\n effects: {\n warningsAdded: options.effects?.warningsAdded ?? [],\n warningsCleared: options.effects?.warningsCleared ?? [],\n commentAdded: options.effects?.commentAdded,\n commentResolved: options.effects?.commentResolved,\n changeAccepted: options.effects?.changeAccepted,\n changeRejected: options.effects?.changeRejected,\n },\n };\n}\n\nfunction normalizeSelection(selection: SelectionSnapshot): SelectionSnapshot {\n if (selection.activeRange.kind === \"range\") {\n return {\n ...selection,\n anchor: selection.activeRange.range.from,\n head: selection.activeRange.range.to,\n isCollapsed: selection.activeRange.range.from === selection.activeRange.range.to,\n };\n }\n\n if (selection.activeRange.kind === \"node\") {\n return createSelectionSnapshot(selection.activeRange.at, selection.activeRange.at);\n }\n\n return selection;\n}\n\nfunction applyTextCommand(\n state: EditorState,\n timestamp: string,\n apply: (\n document: CanonicalDocumentEnvelope,\n selection: SelectionSnapshot,\n ) => {\n document: CanonicalDocumentEnvelope;\n selection: SelectionSnapshot;\n mapping: TransactionMapping;\n },\n): EditorTransaction {\n if (state.readOnly) {\n return createTransaction(state, {\n historyBoundary: \"skip\",\n markDirty: false,\n });\n }\n\n const result = apply(state.document, state.selection);\n const reviewState = remapReviewStateAfterContentChange(\n state,\n result.document,\n result.mapping,\n );\n\n return createTransaction(\n {\n ...state,\n document: reviewState.document,\n selection: result.selection,\n warnings: reviewState.warnings,\n runtime: {\n ...state.runtime,\n activeCommentId: reviewState.activeCommentId,\n },\n },\n {\n historyBoundary: \"push\",\n markDirty: true,\n mapping: result.mapping,\n effects: reviewState.effects,\n },\n );\n}\n\nfunction applyReviewCommand(\n state: EditorState,\n command: ReviewCommand,\n timestamp: string,\n): EditorTransaction {\n if (state.readOnly) {\n return createTransaction(state, {\n historyBoundary: \"skip\",\n markDirty: false,\n });\n }\n\n const result = applyRevisionRuntimeCommand({\n state: {\n document: state.document,\n store: createRevisionStoreFromState(state),\n },\n command,\n timestamp,\n });\n const hasAppliedOutcome = result.outcomes.some((outcome) => outcome.kind === \"applied\");\n\n if (!hasAppliedOutcome) {\n return createTransaction(state, {\n historyBoundary: \"skip\",\n markDirty: false,\n });\n }\n\n let selection = state.selection;\n let comments = result.document.review.comments;\n let warnings = state.warnings;\n let activeCommentId = state.runtime.activeCommentId;\n const mappingSteps: MappingStep[] = [];\n\n for (const entry of result.mappings) {\n if (entry.steps === 0) {\n continue;\n }\n\n selection = remapSelection(selection, entry.mapping);\n mappingSteps.push(...entry.mapping.steps);\n\n const remappedComments = remapCommentThreads({\n comments,\n mapping: entry.mapping,\n nextContent: result.document.content,\n existingWarnings: mapWarningsThroughMapping(warnings, entry.mapping),\n });\n comments = remappedComments.comments;\n warnings = remappedComments.warnings;\n activeCommentId =\n activeCommentId && comments[activeCommentId]\n ? activeCommentId\n : undefined;\n }\n\n warnings = mergeDetachedRevisionWarnings(result.store, warnings);\n\n const nextDocument = {\n ...result.document,\n review: {\n ...result.document.review,\n comments,\n revisions: toEditorRevisionRecords(result.store),\n },\n };\n const appliedRevisionIds = result.effects.appliedRevisionIds;\n\n return createTransaction(\n {\n ...state,\n document: nextDocument,\n selection,\n warnings,\n runtime: {\n ...state.runtime,\n activeCommentId,\n },\n },\n {\n historyBoundary: \"push\",\n markDirty: true,\n mapping: combineMappingSteps(mappingSteps),\n effects: {\n ...buildWarningEffects(state.warnings, warnings),\n changeAccepted:\n command.type === \"review.accept-revision\" && appliedRevisionIds[0]\n ? {\n changeId: appliedRevisionIds[0],\n }\n : undefined,\n changeRejected:\n command.type === \"review.reject-revision\" && appliedRevisionIds[0]\n ? {\n changeId: appliedRevisionIds[0],\n }\n : undefined,\n },\n },\n );\n}\n\nfunction remapReviewStateAfterContentChange(\n state: EditorState,\n nextDocument: CanonicalDocumentEnvelope,\n mapping: TransactionMapping,\n): {\n document: CanonicalDocumentEnvelope;\n warnings: EditorWarning[];\n activeCommentId?: string;\n effects: Pick<TransactionEffects, \"warningsAdded\" | \"warningsCleared\">;\n} {\n const mappedWarnings = mapWarningsThroughMapping(state.warnings, mapping);\n const remappedComments = remapCommentThreads({\n comments: nextDocument.review.comments,\n mapping,\n nextContent: nextDocument.content,\n existingWarnings: mappedWarnings,\n });\n const revisions = Object.fromEntries(\n Object.entries(nextDocument.review.revisions).map(([changeId, revision]) => [\n changeId,\n {\n ...revision,\n anchor: mapAnchor(revision.anchor, mapping),\n },\n ]),\n );\n const activeCommentId =\n state.runtime.activeCommentId &&\n remappedComments.comments[state.runtime.activeCommentId]\n ? state.runtime.activeCommentId\n : undefined;\n const warnings = remappedComments.warnings;\n\n return {\n document: {\n ...nextDocument,\n review: {\n ...nextDocument.review,\n comments: remappedComments.comments,\n revisions,\n },\n },\n warnings,\n activeCommentId,\n effects: buildWarningEffects(state.warnings, warnings),\n };\n}\n\nfunction createRevisionStoreFromState(\n state: Pick<EditorState, \"document\">,\n): RevisionStore {\n return {\n version: \"revision-store/1\",\n revisions: Object.fromEntries(\n Object.values(state.document.review.revisions).map((revision) => [\n revision.changeId,\n {\n revisionId: revision.changeId,\n kind: revision.kind,\n anchor: revision.anchor,\n authorId: revision.authorId ?? \"unknown\",\n createdAt: revision.createdAt,\n status: revision.status === \"open\" ? \"active\" : revision.status,\n warningIds: [...(revision.warningIds ?? [])],\n metadata: {\n source: revision.metadata?.source ?? \"runtime\",\n preserveOnlyReason: revision.metadata?.preserveOnlyReason,\n importedRevisionForm: revision.metadata?.importedRevisionForm,\n originalRevisionType: revision.metadata?.originalRevisionType,\n ooxmlRevisionId: revision.metadata?.ooxmlRevisionId,\n },\n },\n ]),\n ),\n };\n}\n\nfunction toEditorRevisionRecords(\n store: RevisionStore,\n): EditorState[\"document\"][\"review\"][\"revisions\"] {\n return Object.fromEntries(\n Object.values(store.revisions).map((revision) => [\n revision.revisionId,\n {\n changeId: revision.revisionId,\n kind: revision.kind,\n anchor: revision.anchor,\n authorId: revision.authorId,\n createdAt: revision.createdAt,\n warningIds: [...revision.warningIds],\n metadata: {\n source: revision.metadata.source,\n preserveOnlyReason: revision.metadata.preserveOnlyReason,\n importedRevisionForm: revision.metadata.importedRevisionForm,\n originalRevisionType: revision.metadata.originalRevisionType,\n ooxmlRevisionId: revision.metadata.ooxmlRevisionId,\n },\n status: revision.status === \"active\" ? \"open\" : revision.status,\n },\n ]),\n );\n}\n\nfunction mapWarningsThroughMapping(\n warnings: EditorWarning[],\n mapping: TransactionMapping,\n): EditorWarning[] {\n return warnings.map((warning) =>\n warning.affectedAnchor\n ? {\n ...warning,\n affectedAnchor: mapAnchor(warning.affectedAnchor, mapping),\n }\n : warning,\n );\n}\n\nfunction buildWarningEffects(\n previousWarnings: EditorWarning[],\n nextWarnings: EditorWarning[],\n): Pick<TransactionEffects, \"warningsAdded\" | \"warningsCleared\"> {\n const previousById = new Set(previousWarnings.map((warning) => warning.warningId));\n const nextById = new Set(nextWarnings.map((warning) => warning.warningId));\n\n return {\n warningsAdded: nextWarnings.filter((warning) => !previousById.has(warning.warningId)),\n warningsCleared: previousWarnings\n .filter((warning) => !nextById.has(warning.warningId))\n .map((warning) => ({\n warningId: warning.warningId,\n code: warning.code,\n })),\n };\n}\n\nfunction mergeDetachedRevisionWarnings(\n store: RevisionStore,\n existingWarnings: EditorWarning[],\n): EditorWarning[] {\n const retainedWarnings = existingWarnings.filter(\n (warning) =>\n warning.code !== \"revision_anchor_detached\" ||\n !warning.details ||\n typeof warning.details.changeId !== \"string\" ||\n store.revisions[warning.details.changeId]?.status === \"detached\",\n );\n\n const knownDetachedIds = new Set(\n retainedWarnings\n .filter((warning) => warning.code === \"revision_anchor_detached\")\n .map((warning) =>\n typeof warning.details?.changeId === \"string\"\n ? warning.details.changeId\n : undefined,\n )\n .filter((value): value is string => Boolean(value)),\n );\n\n const detachedWarnings = Object.values(store.revisions)\n .filter(\n (revision) =>\n revision.status === \"detached\" && !knownDetachedIds.has(revision.revisionId),\n )\n .map((revision) => ({\n warningId: `warning:revision-anchor-detached:${revision.revisionId}`,\n code: \"revision_anchor_detached\" as const,\n severity: \"warning\" as const,\n message: `Revision ${revision.revisionId} detached after review remapping.`,\n source: \"review\" as const,\n affectedAnchor: revision.anchor.kind === \"detached\" ? revision.anchor : undefined,\n details: {\n changeId: revision.revisionId,\n reason:\n revision.anchor.kind === \"detached\"\n ? revision.anchor.reason\n : undefined,\n },\n }));\n\n return [...retainedWarnings, ...detachedWarnings];\n}\n\nfunction combineMappingSteps(\n steps: MappingStep[],\n): TransactionMapping {\n return steps.length > 0\n ? {\n steps,\n }\n : createEmptyMapping();\n}\n","import {\n createNodeAnchor,\n createRangeAnchor,\n mapAnchor,\n normalizeRange,\n type Assoc,\n type BoundaryAssoc,\n type DocRange,\n type EditorAnchorProjection,\n type TransactionMapping,\n} from \"../../core/selection/mapping.ts\";\n\nexport type CommentAnchor = EditorAnchorProjection;\nexport type CommentAnchorState = \"active\" | \"detached\";\n\nexport interface CommentAnchorSummary {\n anchor: CommentAnchor;\n state: CommentAnchorState;\n range: DocRange;\n}\n\nexport function createCommentRangeAnchor(\n from: number,\n to = from,\n assoc?: BoundaryAssoc,\n): CommentAnchor {\n return createRangeAnchor(from, to, assoc);\n}\n\nexport function createCommentNodeAnchor(at: number, assoc?: Assoc): CommentAnchor {\n return createNodeAnchor(at, assoc);\n}\n\nexport function remapCommentAnchor(\n anchor: CommentAnchor,\n mapping: TransactionMapping,\n): CommentAnchor {\n return mapAnchor(anchor, mapping);\n}\n\nexport function isDetachedCommentAnchor(anchor: CommentAnchor): boolean {\n return anchor.kind === \"detached\";\n}\n\nexport function summarizeCommentAnchor(anchor: CommentAnchor): CommentAnchorSummary {\n if (anchor.kind === \"range\") {\n return {\n anchor,\n state: \"active\",\n range: normalizeRange(anchor.range),\n };\n }\n\n if (anchor.kind === \"node\") {\n return {\n anchor,\n state: \"active\",\n range: {\n from: anchor.at,\n to: anchor.at,\n },\n };\n }\n\n return {\n anchor,\n state: \"detached\",\n range: normalizeRange(anchor.lastKnownRange),\n };\n}\n","import type { TransactionMapping } from \"../../core/selection/mapping.ts\";\nimport {\n isDetachedCommentAnchor,\n remapCommentAnchor,\n summarizeCommentAnchor,\n type CommentAnchor,\n} from \"./comment-anchors.ts\";\n\nexport interface CommentEntry {\n entryId: string;\n authorId: string;\n body: string;\n createdAt: string;\n metadata?: CommentEntryMetadata;\n}\n\nexport interface CommentEntryMetadata {\n ooxmlCommentId?: string;\n paraId?: string;\n parentParaId?: string;\n durableId?: string;\n initials?: string;\n}\n\nexport interface CommentResolution {\n resolvedAt: string;\n resolvedBy: string;\n}\n\nexport type CommentThreadStatus = \"open\" | \"resolved\" | \"detached\";\n\nexport interface CommentThread {\n commentId: string;\n anchor: CommentAnchor;\n status: CommentThreadStatus;\n entries: CommentEntry[];\n createdBy: string;\n createdAt: string;\n resolution?: CommentResolution;\n warningIds: string[];\n metadata?: CommentThreadMetadata;\n}\n\nexport interface CommentThreadMetadata {\n source?: \"runtime\" | \"import\";\n rootOoxmlCommentId?: string;\n rootParaId?: string;\n}\n\nexport interface CommentStore {\n version: \"comment-store/1\";\n threads: Record<string, CommentThread>;\n}\n\nexport interface CreateCommentThreadParams {\n commentId: string;\n anchor: CommentAnchor;\n createdBy: string;\n createdAt: string;\n body: string;\n entryId?: string;\n warningIds?: string[];\n}\n\nexport interface AppendCommentEntryParams {\n commentId: string;\n entry: CommentEntry;\n}\n\nexport interface ResolveCommentThreadParams {\n commentId: string;\n resolvedAt: string;\n resolvedBy: string;\n}\n\nexport interface CommentSidebarThread {\n commentId: string;\n status: CommentThreadStatus;\n excerpt: string;\n entryCount: number;\n createdAt: string;\n createdBy: string;\n warningCount: number;\n anchorLabel: string;\n isActive: boolean;\n resolvedAt?: string;\n resolvedBy?: string;\n}\n\nexport interface CommentSidebarProjection {\n totalCount: number;\n openCommentIds: string[];\n resolvedCommentIds: string[];\n detachedCommentIds: string[];\n threads: CommentSidebarThread[];\n}\n\nexport function createCommentStore(\n threads: Record<string, CommentThread> = {},\n): CommentStore {\n return {\n version: \"comment-store/1\",\n threads,\n };\n}\n\nexport function createCommentThread(\n params: CreateCommentThreadParams,\n): CommentThread {\n return {\n commentId: params.commentId,\n anchor: params.anchor,\n status: isDetachedCommentAnchor(params.anchor) ? \"detached\" : \"open\",\n entries: [\n {\n entryId: params.entryId ?? `${params.commentId}-entry-1`,\n authorId: params.createdBy,\n body: params.body,\n createdAt: params.createdAt,\n },\n ],\n createdBy: params.createdBy,\n createdAt: params.createdAt,\n warningIds: [...(params.warningIds ?? [])],\n };\n}\n\nexport function upsertCommentThread(\n store: CommentStore,\n thread: CommentThread,\n): CommentStore {\n return {\n ...store,\n threads: {\n ...store.threads,\n [thread.commentId]: normalizeThread(thread),\n },\n };\n}\n\nexport function appendCommentEntry(\n store: CommentStore,\n params: AppendCommentEntryParams,\n): CommentStore {\n const existing = store.threads[params.commentId];\n if (!existing) {\n return store;\n }\n\n return upsertCommentThread(store, {\n ...existing,\n entries: [...existing.entries, params.entry],\n });\n}\n\nexport function resolveCommentThread(\n store: CommentStore,\n params: ResolveCommentThreadParams,\n): CommentStore {\n const existing = store.threads[params.commentId];\n if (!existing) {\n return store;\n }\n\n return upsertCommentThread(store, {\n ...existing,\n status: existing.status === \"detached\" ? \"detached\" : \"resolved\",\n resolution: {\n resolvedAt: params.resolvedAt,\n resolvedBy: params.resolvedBy,\n },\n });\n}\n\nexport function reopenCommentThread(\n store: CommentStore,\n commentId: string,\n): CommentStore {\n const existing = store.threads[commentId];\n if (!existing) {\n return store;\n }\n\n return upsertCommentThread(store, {\n ...existing,\n status: isDetachedCommentAnchor(existing.anchor) ? \"detached\" : \"open\",\n resolution: undefined,\n });\n}\n\nexport function setCommentThreadWarnings(\n store: CommentStore,\n commentId: string,\n warningIds: string[],\n): CommentStore {\n const existing = store.threads[commentId];\n if (!existing) {\n return store;\n }\n\n return upsertCommentThread(store, {\n ...existing,\n warningIds: [...warningIds],\n });\n}\n\nexport function remapCommentStore(\n store: CommentStore,\n mapping: TransactionMapping,\n): CommentStore {\n return createCommentStore(\n Object.fromEntries(\n Object.entries(store.threads).map(([commentId, thread]) => {\n const anchor = remapCommentAnchor(thread.anchor, mapping);\n const nextStatus =\n anchor.kind === \"detached\"\n ? \"detached\"\n : thread.status === \"resolved\"\n ? \"resolved\"\n : \"open\";\n\n return [\n commentId,\n normalizeThread({\n ...thread,\n anchor,\n status: nextStatus,\n }),\n ];\n }),\n ),\n );\n}\n\nexport function createCommentSidebarProjection(\n store: CommentStore,\n activeCommentId?: string,\n): CommentSidebarProjection {\n const threads = Object.values(store.threads)\n .map((thread) => toSidebarThread(thread, activeCommentId))\n .sort(compareSidebarThreads);\n\n return {\n totalCount: threads.length,\n openCommentIds: threads\n .filter((thread) => thread.status === \"open\")\n .map((thread) => thread.commentId),\n resolvedCommentIds: threads\n .filter((thread) => thread.status === \"resolved\")\n .map((thread) => thread.commentId),\n detachedCommentIds: threads\n .filter((thread) => thread.status === \"detached\")\n .map((thread) => thread.commentId),\n threads,\n };\n}\n\nfunction toSidebarThread(\n thread: CommentThread,\n activeCommentId?: string,\n): CommentSidebarThread {\n const firstEntry = thread.entries[0];\n const anchorSummary = summarizeCommentAnchor(thread.anchor);\n\n return {\n commentId: thread.commentId,\n status: thread.status,\n excerpt: firstEntry ? summarizeBody(firstEntry.body) : \"Empty thread\",\n entryCount: thread.entries.length,\n createdAt: thread.createdAt,\n createdBy: thread.createdBy,\n warningCount: thread.warningIds.length,\n anchorLabel:\n anchorSummary.state === \"detached\"\n ? `Detached ${anchorSummary.range.from}-${anchorSummary.range.to}`\n : `Range ${anchorSummary.range.from}-${anchorSummary.range.to}`,\n isActive: activeCommentId === thread.commentId,\n resolvedAt: thread.resolution?.resolvedAt,\n resolvedBy: thread.resolution?.resolvedBy,\n };\n}\n\nfunction normalizeThread(thread: CommentThread): CommentThread {\n if (isDetachedCommentAnchor(thread.anchor)) {\n return {\n ...thread,\n status: \"detached\",\n };\n }\n\n if (thread.status === \"detached\") {\n return {\n ...thread,\n status: thread.resolution ? \"resolved\" : \"open\",\n };\n }\n\n return thread;\n}\n\nfunction compareSidebarThreads(\n left: CommentSidebarThread,\n right: CommentSidebarThread,\n): number {\n const statusDelta = priorityForStatus(left.status) - priorityForStatus(right.status);\n if (statusDelta !== 0) {\n return statusDelta;\n }\n\n return left.createdAt.localeCompare(right.createdAt);\n}\n\nfunction priorityForStatus(status: CommentThreadStatus): number {\n switch (status) {\n case \"open\":\n return 0;\n case \"detached\":\n return 1;\n case \"resolved\":\n return 2;\n }\n}\n\nfunction summarizeBody(body: string): string {\n const collapsed = body.replace(/\\s+/g, \" \").trim();\n if (!collapsed) {\n return \"Empty thread\";\n }\n\n return collapsed.length > 80 ? `${collapsed.slice(0, 77)}...` : collapsed;\n}\n","import {\n normalizeCommentThreadRecord,\n type CommentThreadRecord,\n} from \"../../core/state/editor-state.ts\";\nimport {\n createCommentStore,\n type CommentStore,\n type CommentThread,\n} from \"./comment-store.ts\";\n\nexport function createCommentStoreFromRuntimeComments(\n comments: Record<string, CommentThreadRecord>,\n): CommentStore {\n const threads = Object.fromEntries(\n Object.values(comments).map((comment) => [\n comment.commentId,\n toCommentThread(comment),\n ]),\n );\n\n return createCommentStore(threads);\n}\n\nfunction toCommentThread(comment: CommentThreadRecord): CommentThread {\n const normalized = normalizeCommentThreadRecord(comment);\n\n return {\n commentId: normalized.commentId,\n anchor: normalized.anchor,\n status:\n normalized.anchor.kind === \"detached\"\n ? \"detached\"\n : normalized.status === \"resolved\"\n ? \"resolved\"\n : \"open\",\n entries: normalized.entries ?? [],\n createdBy: normalized.createdBy ?? normalized.authorId ?? \"unknown\",\n createdAt: normalized.createdAt,\n resolution: normalized.resolution,\n warningIds: [...(normalized.warningIds ?? [])],\n metadata: normalized.metadata,\n };\n}\n","import type {\n DocRange,\n OpaqueFragmentRecord,\n PreservationStore,\n PreservedPackagePart,\n} from \"../model/canonical-document.ts\";\n\nexport interface OpaqueFragmentDescriptor {\n featureKey:\n | \"sections\"\n | \"tables\"\n | \"headers-footers\"\n | \"fields\"\n | \"content-controls\"\n | \"custom-xml\"\n | \"alt-chunk\"\n | \"embedded-objects\"\n | \"alternate-content\"\n | \"unknown-ooxml\";\n label: string;\n detail: string;\n}\n\nexport function createPreservationStore(\n seed?: Partial<PreservationStore>,\n): PreservationStore {\n return {\n opaqueFragments: { ...(seed?.opaqueFragments ?? {}) },\n packageParts: { ...(seed?.packageParts ?? {}) },\n };\n}\n\nexport function getOpaqueFragment(\n store: PreservationStore,\n fragmentId: string,\n): OpaqueFragmentRecord | undefined {\n return normalizeOpaqueFragmentMap(store)[fragmentId];\n}\n\nexport function listOpaqueFragments(\n store: PreservationStore,\n): OpaqueFragmentRecord[] {\n return Object.values(normalizeOpaqueFragmentMap(store)).sort((left, right) => {\n return (\n left.lastKnownRange.from - right.lastKnownRange.from ||\n left.fragmentId.localeCompare(right.fragmentId)\n );\n });\n}\n\nexport function listPreservedPackageParts(\n store: PreservationStore,\n): PreservedPackagePart[] {\n return Object.values(normalizePackagePartMap(store)).sort((left, right) =>\n left.packagePartName.localeCompare(right.packagePartName),\n );\n}\n\nexport function findOpaqueFragmentsIntersectingRange(\n store: PreservationStore,\n range: DocRange,\n): OpaqueFragmentRecord[] {\n return listOpaqueFragments(store).filter((fragment) =>\n rangesIntersect(fragment.lastKnownRange, range),\n );\n}\n\nexport function describeOpaqueFragment(\n fragment: OpaqueFragmentRecord,\n): OpaqueFragmentDescriptor {\n const xml = fragment.payloadReference;\n const detail = createDetail(fragment);\n\n if (/\\b(?:w:)?sectPr\\b/u.test(xml)) {\n return {\n featureKey: \"sections\",\n label: \"Section properties\",\n detail,\n };\n }\n\n if (/\\b(?:w:)?tbl\\b/u.test(xml)) {\n return {\n featureKey: \"tables\",\n label: \"Preserved table structure\",\n detail,\n };\n }\n\n if (/\\b(?:w:)?hdr\\b|\\b(?:w:)?ftr\\b/u.test(xml)) {\n return {\n featureKey: \"headers-footers\",\n label: \"Header or footer content\",\n detail,\n };\n }\n\n if (/\\b(?:w:)?fldSimple\\b|\\b(?:w:)?fldChar\\b|\\b(?:w:)?instrText\\b/u.test(xml)) {\n return {\n featureKey: \"fields\",\n label: \"Word field content\",\n detail,\n };\n }\n\n if (/\\b(?:w:)?sdt\\b/u.test(xml)) {\n return {\n featureKey: \"content-controls\",\n label: \"Content control\",\n detail,\n };\n }\n\n if (/\\b(?:w:)?customXml\\b/u.test(xml)) {\n return {\n featureKey: \"custom-xml\",\n label: \"Custom XML wrapper\",\n detail,\n };\n }\n\n if (/\\b(?:w:)?altChunk\\b/u.test(xml)) {\n return {\n featureKey: \"alt-chunk\",\n label: \"Alternate content import\",\n detail,\n };\n }\n\n if (/\\b(?:w:)?object\\b|\\b(?:o:)?OLEObject\\b/u.test(xml)) {\n return {\n featureKey: \"embedded-objects\",\n label: \"Embedded object\",\n detail,\n };\n }\n\n if (/\\b(?:mc:)?AlternateContent\\b/u.test(xml)) {\n return {\n featureKey: \"alternate-content\",\n label: \"Markup compatibility block\",\n detail,\n };\n }\n\n return {\n featureKey: \"unknown-ooxml\",\n label: \"Unsupported OOXML fragment\",\n detail,\n };\n}\n\nfunction createDetail(fragment: OpaqueFragmentRecord): string {\n const detail = [\n `Preserved whole-unit from ${fragment.lastKnownRange.from}-${fragment.lastKnownRange.to}.`,\n fragment.packagePartName ? `Part ${fragment.packagePartName}.` : null,\n fragment.relationshipId ? `Relationship ${fragment.relationshipId}.` : null,\n ]\n .filter(Boolean)\n .join(\" \");\n\n return detail.length > 0\n ? detail\n : \"Preserved whole-unit to keep unsupported OOXML intact.\";\n}\n\nfunction rangesIntersect(left: DocRange, right: DocRange): boolean {\n return left.from < right.to && right.from < left.to;\n}\n\nfunction normalizeOpaqueFragmentMap(\n store: PreservationStore,\n): Record<string, OpaqueFragmentRecord> {\n return store && typeof store === \"object\" && store.opaqueFragments && typeof store.opaqueFragments === \"object\"\n ? (store.opaqueFragments as Record<string, OpaqueFragmentRecord>)\n : {};\n}\n\nfunction normalizePackagePartMap(\n store: PreservationStore,\n): Record<string, PreservedPackagePart> {\n return store && typeof store === \"object\" && store.packageParts && typeof store.packageParts === \"object\"\n ? (store.packageParts as Record<string, PreservedPackagePart>)\n : {};\n}\n","import { createRangeAnchor } from \"../core/selection/mapping.ts\";\nimport type {\n CanonicalDocumentEnvelope,\n CompatibilityFeatureEntry,\n CompatibilityReport,\n EditorError,\n EditorWarning,\n} from \"../core/state/editor-state.ts\";\nimport type {\n DocumentRootNode,\n InlineNode,\n ParagraphNode,\n} from \"../model/canonical-document.ts\";\nimport {\n describeOpaqueFragment,\n listOpaqueFragments,\n listPreservedPackageParts,\n} from \"../preservation/store.ts\";\n\nexport interface BuildCompatibilityReportInput {\n document: CanonicalDocumentEnvelope;\n warnings?: readonly EditorWarning[];\n fatalError?: EditorError;\n generatedAt: string;\n}\n\nexport function buildCompatibilityReport(\n input: BuildCompatibilityReportInput,\n): CompatibilityReport {\n const content = normalizeDocumentRoot(input.document.content);\n const contentFeatures = collectContentFeatures(content);\n if (hasSupportedRuntimeComments(input.document.review.comments)) {\n contentFeatures.push(\n supportedEntry(\n \"comments-single-paragraph\",\n \"Single-paragraph review comments stay mappable through runtime selections.\",\n ),\n );\n }\n const featureEntries: CompatibilityFeatureEntry[] = [\n ...contentFeatures,\n ...collectPreservationFeatures(input.document),\n ];\n const warnings = dedupeWarnings([\n ...(input.warnings ?? []),\n ...collectDiagnosticWarnings(input.document),\n ]);\n const errors = dedupeErrors([\n ...collectDiagnosticErrors(input.document),\n ...(input.fatalError ? [input.fatalError] : []),\n ]);\n\n return {\n reportVersion: \"compatibility-report/1\",\n generatedAt: input.generatedAt,\n blockExport:\n featureEntries.some((entry) => entry.featureClass === \"unsupported-fatal\") ||\n errors.some((error) => error.isFatal),\n featureEntries,\n warnings,\n errors,\n };\n}\n\nfunction hasSupportedRuntimeComments(\n comments: CanonicalDocumentEnvelope[\"review\"][\"comments\"],\n): boolean {\n return Object.values(comments).some((comment) => comment.anchor.kind !== \"detached\");\n}\n\nfunction normalizeDocumentRoot(content: unknown): DocumentRootNode {\n if (content && typeof content === \"object\" && (content as { type?: string }).type === \"doc\") {\n return content as DocumentRootNode;\n }\n\n if (Array.isArray(content)) {\n return {\n type: \"doc\",\n children: content.filter(\n (value): value is DocumentRootNode[\"children\"][number] =>\n Boolean(value) &&\n typeof value === \"object\" &&\n ((value as { type?: string }).type === \"paragraph\" ||\n (value as { type?: string }).type === \"opaque_block\"),\n ),\n };\n }\n\n return {\n type: \"doc\",\n children: [{ type: \"paragraph\", children: [] }],\n };\n}\n\nfunction collectContentFeatures(\n content: DocumentRootNode,\n): CompatibilityFeatureEntry[] {\n const flags = {\n paragraphs: false,\n runs: false,\n whitespace: false,\n headings: false,\n lists: false,\n hyperlinks: false,\n images: false,\n };\n\n for (let index = 0; index < content.children.length; index += 1) {\n const block = content.children[index];\n if (block.type !== \"paragraph\") {\n continue;\n }\n\n flags.paragraphs = true;\n if (block.styleId?.toLowerCase().startsWith(\"heading\")) {\n flags.headings = true;\n }\n if (block.numbering) {\n flags.lists = true;\n }\n\n measureParagraph(block, flags);\n }\n\n const entries: CompatibilityFeatureEntry[] = [];\n if (flags.paragraphs) {\n entries.push(supportedEntry(\"paragraphs\", \"Paragraph structure is editable and round-trippable.\"));\n }\n if (flags.runs) {\n entries.push(supportedEntry(\"runs\", \"Runs and inline text are editable through runtime commands.\"));\n }\n if (flags.whitespace) {\n entries.push(supportedEntry(\"whitespace\", \"Whitespace-sensitive text units stay explicit in the runtime model.\"));\n }\n if (flags.headings) {\n entries.push(supportedEntry(\"headings\", \"Heading styles remain attached to paragraph structure.\"));\n }\n if (flags.lists) {\n entries.push(supportedEntry(\"lists\", \"Numbering metadata stays attached to paragraph blocks.\"));\n }\n if (flags.hyperlinks) {\n entries.push(supportedEntry(\"hyperlinks\", \"Hyperlink relationships are preserved and re-serialized.\"));\n }\n if (flags.images) {\n entries.push(supportedEntry(\"inline-images\", \"Inline image placements stay attached to preserved media parts.\"));\n }\n return entries;\n}\n\nfunction measureParagraph(\n paragraph: ParagraphNode,\n flags: {\n runs: boolean;\n whitespace: boolean;\n hyperlinks: boolean;\n images: boolean;\n },\n): number {\n let size = 0;\n const children = Array.isArray(paragraph.children) ? paragraph.children : [];\n\n for (const child of children) {\n size += measureInlineNode(child, flags);\n }\n\n return size;\n}\n\nfunction measureInlineNode(\n node: InlineNode,\n flags: {\n runs: boolean;\n whitespace: boolean;\n hyperlinks: boolean;\n images: boolean;\n },\n): number {\n switch (node.type) {\n case \"text\":\n flags.runs = flags.runs || node.text.length > 0;\n flags.whitespace =\n flags.whitespace ||\n /^\\s/u.test(node.text) ||\n /\\s$/u.test(node.text) ||\n node.text.includes(\" \");\n return Array.from(node.text).length;\n case \"tab\":\n case \"hard_break\":\n flags.runs = true;\n flags.whitespace = true;\n return 1;\n case \"hyperlink\":\n flags.runs = true;\n flags.hyperlinks = true;\n return node.children.reduce((size, child) => size + measureInlineNode(child, flags), 0);\n case \"image\":\n flags.images = true;\n flags.runs = true;\n return 1;\n case \"opaque_inline\":\n flags.runs = true;\n return 1;\n }\n}\n\nfunction collectPreservationFeatures(\n document: CanonicalDocumentEnvelope,\n): CompatibilityFeatureEntry[] {\n const entries: CompatibilityFeatureEntry[] = [];\n\n for (const fragment of listOpaqueFragments(document.preservation as never)) {\n const descriptor = describeOpaqueFragment(fragment);\n entries.push({\n featureEntryId: `feature:${fragment.fragmentId}`,\n featureKey: descriptor.featureKey,\n featureClass: \"preserve-only\",\n message: descriptor.label,\n affectedAnchor: createRangeAnchor(\n fragment.lastKnownRange.from,\n fragment.lastKnownRange.to,\n ),\n details: {\n fragmentId: fragment.fragmentId,\n warningId: fragment.warningId,\n detail: descriptor.detail,\n },\n });\n }\n\n for (const packagePart of listPreservedPackageParts(document.preservation as never)) {\n entries.push({\n featureEntryId: `feature:package:${packagePart.packagePartName}`,\n featureKey: \"unknown-package-parts\",\n featureClass: \"preserve-only\",\n message: `Preserved package part ${packagePart.packagePartName}.`,\n details: {\n packagePartName: packagePart.packagePartName,\n contentType: packagePart.contentType,\n relationshipIds: packagePart.relationshipIds,\n },\n });\n }\n\n return entries;\n}\n\nfunction collectDiagnosticWarnings(\n document: CanonicalDocumentEnvelope,\n): EditorWarning[] {\n const diagnostics = Array.isArray(document.diagnostics?.warnings)\n ? document.diagnostics.warnings\n : [];\n\n return diagnostics.map((warning) => ({\n warningId: warning.warningId,\n code:\n warning.source === \"validation\" || warning.source === \"export\"\n ? \"export_roundtrip_risk\"\n : warning.source === \"preservation\"\n ? \"unsupported_ooxml_preserved\"\n : \"import_normalized\",\n severity: \"warning\",\n message: warning.message,\n source: warning.source,\n }));\n}\n\nfunction collectDiagnosticErrors(\n document: CanonicalDocumentEnvelope,\n): EditorError[] {\n const diagnostics = Array.isArray(document.diagnostics?.errors)\n ? document.diagnostics.errors\n : [];\n\n return diagnostics.map((error) => ({\n errorId: error.diagnosticId,\n code:\n error.code === \"load_failed\"\n ? \"import_failed\"\n : error.code,\n message: error.message,\n isFatal: error.isFatal,\n source: error.source,\n }));\n}\n\nfunction supportedEntry(\n featureKey: CompatibilityFeatureEntry[\"featureKey\"],\n message: string,\n): CompatibilityFeatureEntry {\n return {\n featureEntryId: `feature:${featureKey}`,\n featureKey,\n featureClass: \"supported-roundtrip\",\n message,\n };\n}\n\nfunction dedupeWarnings(warnings: EditorWarning[]): EditorWarning[] {\n const byId = new Map<string, EditorWarning>();\n\n for (const warning of warnings) {\n byId.set(warning.warningId, warning);\n }\n\n return [...byId.values()];\n}\n\nfunction dedupeErrors(errors: EditorError[]): EditorError[] {\n const byId = new Map<string, EditorError>();\n\n for (const error of errors) {\n byId.set(error.errorId, error);\n }\n\n return [...byId.values()];\n}\n","import type {\n EditorSurfaceSnapshot,\n SurfaceBlockSnapshot,\n SurfaceInlineSegment,\n SurfaceTableCellSnapshot,\n SurfaceTableRowSnapshot,\n} from \"../api/public-types\";\nimport type {\n CanonicalDocumentEnvelope,\n SelectionSnapshot,\n} from \"../core/state/editor-state.ts\";\nimport type {\n BlockNode,\n ChartPreviewNode,\n DocumentRootNode,\n InlineNode,\n ParagraphNode,\n SdtNode,\n ShapeNode,\n SmartArtPreviewNode,\n TableNode,\n TextMark,\n VmlShapeNode,\n WordArtNode,\n} from \"../model/canonical-document.ts\";\nimport {\n describeOpaqueFragment,\n getOpaqueFragment,\n} from \"../preservation/store.ts\";\n\ninterface ParagraphAccumulator {\n blockId: string;\n kind: \"paragraph\";\n from: number;\n to: number;\n styleId?: string;\n numbering?: ParagraphNode[\"numbering\"];\n segments: SurfaceInlineSegment[];\n}\n\nexport function createEditorSurfaceSnapshot(\n document: CanonicalDocumentEnvelope,\n _selection: SelectionSnapshot,\n): EditorSurfaceSnapshot {\n const root = normalizeDocumentRoot(document.content);\n const blocks: SurfaceBlockSnapshot[] = [];\n const lockedFragmentIds: string[] = [];\n let cursor = 0;\n const counters = {\n paragraph: 0,\n table: 0,\n opaque: 0,\n sdt: 0,\n customXml: 0,\n altChunk: 0,\n };\n\n for (let index = 0; index < root.children.length; index += 1) {\n const surfaceBlock = createSurfaceBlock(root.children[index], document, cursor, counters);\n blocks.push(surfaceBlock.block);\n lockedFragmentIds.push(...surfaceBlock.lockedFragmentIds);\n cursor = surfaceBlock.nextCursor;\n if (index < root.children.length - 1 && root.children[index + 1]?.type === \"paragraph\") {\n cursor += 1;\n }\n }\n\n return {\n storySize: cursor,\n plainText: createPlainText(blocks),\n blocks,\n lockedFragmentIds,\n };\n}\n\nfunction createSurfaceBlock(\n block: BlockNode,\n document: CanonicalDocumentEnvelope,\n cursor: number,\n counters: {\n paragraph: number;\n table: number;\n opaque: number;\n sdt: number;\n customXml: number;\n altChunk: number;\n },\n): { block: SurfaceBlockSnapshot; lockedFragmentIds: string[]; nextCursor: number } {\n if (block.type === \"opaque_block\") {\n const fragment = getOpaqueFragment(document.preservation as never, block.fragmentId);\n const descriptor = fragment ? describeOpaqueFragment(fragment) : null;\n const blockId = `opaque-${counters.opaque}`;\n counters.opaque += 1;\n return {\n block: {\n blockId,\n kind: \"opaque_block\",\n from: cursor,\n to: cursor + 1,\n fragmentId: block.fragmentId,\n warningId: block.warningId,\n label: descriptor?.label ?? \"Unsupported OOXML fragment\",\n detail:\n descriptor?.detail ??\n \"Locked whole-unit to keep unsupported OOXML intact through export.\",\n state: \"locked-preserve-only\",\n },\n lockedFragmentIds: [block.fragmentId],\n nextCursor: cursor + 1,\n };\n }\n\n if (block.type === \"table\") {\n const tableIndex = counters.table;\n counters.table += 1;\n return createTableBlock(tableIndex, block, document, cursor, counters);\n }\n\n if (block.type === \"sdt\") {\n const sdtIndex = counters.sdt;\n counters.sdt += 1;\n return createSdtBlock(sdtIndex, block, document, cursor, counters);\n }\n\n if (block.type === \"custom_xml\") {\n const blockId = `custom-xml-${counters.customXml}`;\n counters.customXml += 1;\n return {\n block: {\n blockId,\n kind: \"opaque_block\",\n from: cursor,\n to: cursor + 1,\n fragmentId: blockId,\n warningId: blockId,\n label: \"Custom XML block\",\n detail:\n block.uri || block.element\n ? `Custom XML wrapper ${[block.element, block.uri].filter(Boolean).join(\" \")} preserved as a read-only block.`\n : \"Custom XML wrapper preserved as a read-only block.\",\n state: \"locked-preserve-only\",\n },\n lockedFragmentIds: [],\n nextCursor: cursor + 1,\n };\n }\n\n if (block.type === \"alt_chunk\") {\n const blockId = `alt-chunk-${counters.altChunk}`;\n counters.altChunk += 1;\n return {\n block: {\n blockId,\n kind: \"opaque_block\",\n from: cursor,\n to: cursor + 1,\n fragmentId: blockId,\n warningId: blockId,\n label: \"AltChunk import\",\n detail: `Alternate content import remains read-only through relationship ${block.relationshipId}.`,\n state: \"locked-preserve-only\",\n },\n lockedFragmentIds: [],\n nextCursor: cursor + 1,\n };\n }\n\n const paragraphIndex = counters.paragraph;\n counters.paragraph += 1;\n return createParagraphBlock(paragraphIndex, block, document, cursor);\n}\n\nfunction createTableBlock(\n tableIndex: number,\n table: TableNode,\n document: CanonicalDocumentEnvelope,\n cursor: number,\n counters: {\n paragraph: number;\n table: number;\n opaque: number;\n sdt: number;\n customXml: number;\n altChunk: number;\n },\n): { block: SurfaceBlockSnapshot; lockedFragmentIds: string[]; nextCursor: number } {\n const lockedFragmentIds: string[] = [];\n let innerCursor = cursor;\n const rows: SurfaceTableRowSnapshot[] = [];\n\n for (const row of table.rows) {\n const cells: SurfaceTableCellSnapshot[] = [];\n for (const cell of row.cells) {\n const cellContent: SurfaceBlockSnapshot[] = [];\n for (const child of cell.children) {\n const result = createSurfaceBlock(child, document, innerCursor, counters);\n cellContent.push(result.block);\n lockedFragmentIds.push(...result.lockedFragmentIds);\n innerCursor = result.nextCursor;\n }\n cells.push({\n gridSpan: cell.gridSpan ?? 1,\n verticalMerge: cell.verticalMerge ?? null,\n colspan: cell.gridSpan ?? 1,\n rowspan: cell.verticalMerge === \"restart\" ? 1 : 1,\n content: cellContent,\n });\n }\n rows.push({ cells });\n }\n\n return {\n block: {\n blockId: `table-${tableIndex}`,\n kind: \"table\",\n from: cursor,\n to: innerCursor,\n styleId: table.styleId,\n gridColumns: table.gridColumns,\n rows,\n },\n lockedFragmentIds,\n nextCursor: innerCursor,\n };\n}\n\nfunction createSdtBlock(\n sdtIndex: number,\n block: SdtNode,\n document: CanonicalDocumentEnvelope,\n cursor: number,\n counters: {\n paragraph: number;\n table: number;\n opaque: number;\n sdt: number;\n customXml: number;\n altChunk: number;\n },\n): { block: SurfaceBlockSnapshot; lockedFragmentIds: string[]; nextCursor: number } {\n const children: SurfaceBlockSnapshot[] = [];\n const lockedFragmentIds: string[] = [];\n let innerCursor = cursor;\n\n for (const child of block.children) {\n const result = createSurfaceBlock(child, document, innerCursor, counters);\n children.push(result.block);\n lockedFragmentIds.push(...result.lockedFragmentIds);\n innerCursor = result.nextCursor;\n }\n\n return {\n block: {\n blockId: `sdt-${sdtIndex}`,\n kind: \"sdt_block\",\n from: cursor,\n to: innerCursor,\n ...(block.properties.sdtType ? { sdtType: block.properties.sdtType } : {}),\n ...(block.properties.alias ? { alias: block.properties.alias } : {}),\n ...(block.properties.tag ? { tag: block.properties.tag } : {}),\n ...(block.properties.lock ? { lock: block.properties.lock } : {}),\n children,\n },\n lockedFragmentIds,\n nextCursor: innerCursor,\n };\n}\n\nfunction createParagraphBlock(\n paragraphIndex: number,\n paragraph: ParagraphNode,\n document: CanonicalDocumentEnvelope,\n start: number,\n): {\n block: SurfaceBlockSnapshot;\n nextCursor: number;\n lockedFragmentIds: string[];\n} {\n const accumulator: ParagraphAccumulator = {\n blockId: `paragraph-${paragraphIndex}`,\n kind: \"paragraph\",\n from: start,\n to: start,\n ...(paragraph.styleId ? { styleId: paragraph.styleId } : {}),\n ...(paragraph.numbering ? { numbering: paragraph.numbering } : {}),\n segments: [],\n };\n const lockedFragmentIds: string[] = [];\n let cursor = start;\n const children = Array.isArray(paragraph.children) ? paragraph.children : [];\n\n for (const child of children) {\n const result = appendInlineSegments(accumulator, child, document, cursor);\n cursor = result.nextCursor;\n lockedFragmentIds.push(...result.lockedFragmentIds);\n }\n\n accumulator.to = cursor;\n return {\n block: accumulator,\n nextCursor: cursor,\n lockedFragmentIds,\n };\n}\n\nfunction appendInlineSegments(\n paragraph: ParagraphAccumulator,\n node: InlineNode,\n document: CanonicalDocumentEnvelope,\n start: number,\n hyperlinkHref?: string,\n): { nextCursor: number; lockedFragmentIds: string[] } {\n switch (node.type) {\n case \"text\":\n paragraph.segments.push({\n segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,\n kind: \"text\",\n from: start,\n to: start + Array.from(node.text).length,\n text: node.text,\n ...(node.marks ? { marks: cloneMarks(node.marks) } : {}),\n ...(hyperlinkHref ? { hyperlinkHref } : {}),\n });\n return { nextCursor: start + Array.from(node.text).length, lockedFragmentIds: [] };\n case \"tab\":\n paragraph.segments.push({\n segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,\n kind: \"tab\",\n from: start,\n to: start + 1,\n ...(hyperlinkHref ? { hyperlinkHref } : {}),\n });\n return { nextCursor: start + 1, lockedFragmentIds: [] };\n case \"hard_break\":\n paragraph.segments.push({\n segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,\n kind: \"hard_break\",\n from: start,\n to: start + 1,\n ...(hyperlinkHref ? { hyperlinkHref } : {}),\n });\n return { nextCursor: start + 1, lockedFragmentIds: [] };\n case \"hyperlink\": {\n let cursor = start;\n for (const child of node.children) {\n const result = appendInlineSegments(paragraph, child, document, cursor, node.href);\n cursor = result.nextCursor;\n }\n return { nextCursor: cursor, lockedFragmentIds: [] };\n }\n case \"image\":\n paragraph.segments.push({\n segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,\n kind: \"image\",\n from: start,\n to: start + 1,\n mediaId: node.mediaId,\n altText: node.altText,\n state: hasMediaItem(document.media, node.mediaId) ? \"editable\" : \"missing\",\n ...(node.display ? { display: node.display } : {}),\n detail:\n node.display === \"floating\"\n ? createFloatingImageDetail(node.altText, node.floating)\n : node.altText\n ? `Alt text ${node.altText}.`\n : \"Inline image remains a whole-unit render surface.\",\n });\n return { nextCursor: start + 1, lockedFragmentIds: [] };\n case \"opaque_inline\": {\n const fragment = getOpaqueFragment(document.preservation as never, node.fragmentId);\n const descriptor = fragment ? describeOpaqueFragment(fragment) : null;\n paragraph.segments.push({\n segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,\n kind: \"opaque_inline\",\n from: start,\n to: start + 1,\n fragmentId: node.fragmentId,\n warningId: node.warningId,\n label: descriptor?.label ?? \"Unsupported inline OOXML\",\n detail:\n descriptor?.detail ??\n \"Locked whole-unit to keep unsupported inline OOXML intact through export.\",\n state: \"locked-preserve-only\",\n });\n return { nextCursor: start + 1, lockedFragmentIds: [node.fragmentId] };\n }\n case \"chart_preview\":\n return appendComplexPreviewSegment(paragraph, node, start, \"Chart\", createChartDetail(node));\n case \"smartart_preview\":\n return appendComplexPreviewSegment(paragraph, node, start, \"SmartArt\", createSmartArtDetail(node));\n case \"shape\":\n return appendComplexPreviewSegment(paragraph, node, start, \"Shape\", createShapeDetail(node));\n case \"wordart\":\n return appendComplexPreviewSegment(paragraph, node, start, \"WordArt\", createWordArtDetail(node));\n case \"vml_shape\":\n return appendComplexPreviewSegment(paragraph, node, start, \"VML shape\", createVmlDetail(node));\n }\n}\n\nfunction appendComplexPreviewSegment(\n paragraph: ParagraphAccumulator,\n node: { rawXml: string },\n start: number,\n label: string,\n detail: string,\n): { nextCursor: number; lockedFragmentIds: string[] } {\n paragraph.segments.push({\n segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,\n kind: \"opaque_inline\",\n from: start,\n to: start + 1,\n fragmentId: `complex:${label.replace(/\\s/g, \"-\").toLowerCase()}:${start}`,\n warningId: `warning:complex-preview:${start}`,\n label,\n detail,\n state: \"locked-preserve-only\",\n });\n return { nextCursor: start + 1, lockedFragmentIds: [] };\n}\n\nfunction createChartDetail(node: ChartPreviewNode): string {\n return node.previewMediaId\n ? `Chart read-only preview. Fallback image ${node.previewMediaId}. Original XML preserved for export.`\n : \"Chart read-only preview. Original XML preserved for export.\";\n}\n\nfunction createSmartArtDetail(node: SmartArtPreviewNode): string {\n return node.previewMediaId\n ? `SmartArt diagram read-only preview. Fallback image ${node.previewMediaId}. Original XML preserved for export.`\n : \"SmartArt diagram read-only preview. Original XML preserved for export.\";\n}\n\nfunction createShapeDetail(node: ShapeNode): string {\n const parts = [\"Shape read-only preview.\"];\n if (node.geometry) parts.push(`Geometry: ${node.geometry}.`);\n if (node.text) parts.push(`Text: \"${node.text}\".`);\n parts.push(\"Original XML preserved for export.\");\n return parts.join(\" \");\n}\n\nfunction createWordArtDetail(node: WordArtNode): string {\n const parts = [\"WordArt read-only preview.\"];\n if (node.text) parts.push(`Text: \"${node.text}\".`);\n if (node.geometry) parts.push(`Effect: ${node.geometry}.`);\n parts.push(\"Original XML preserved for export.\");\n return parts.join(\" \");\n}\n\nfunction createVmlDetail(node: VmlShapeNode): string {\n const parts = [\"VML shape read-only preview.\"];\n if (node.shapeType) parts.push(`Type: ${node.shapeType}.`);\n if (node.text) parts.push(`Text: \"${node.text}\".`);\n parts.push(\"Legacy VML; original XML preserved for export.\");\n return parts.join(\" \");\n}\n\nfunction createPlainText(\n blocks: SurfaceBlockSnapshot[],\n): string {\n const text: string[] = [];\n for (const block of blocks) {\n if (block.kind === \"opaque_block\") {\n text.push(\"\\uFFFA\");\n continue;\n }\n\n if (block.kind === \"table\") {\n text.push(\"\\uFFFA\"); // placeholder for table in plain text\n continue;\n }\n\n if (block.kind === \"sdt_block\") {\n text.push(createPlainText(block.children));\n continue;\n }\n\n for (const segment of block.segments) {\n switch (segment.kind) {\n case \"text\":\n text.push(segment.text);\n break;\n case \"tab\":\n text.push(\"\\t\");\n break;\n case \"hard_break\":\n text.push(\"\\n\");\n break;\n case \"image\":\n text.push(\"\\uFFFC\");\n break;\n case \"opaque_inline\":\n text.push(\"\\uFFF9\");\n break;\n }\n }\n }\n\n return text.join(\"\");\n}\n\nfunction cloneMarks(marks: TextMark[]): Array<\"bold\" | \"italic\" | \"underline\" | \"strikethrough\"> {\n return marks.map((mark) => mark.type);\n}\n\nfunction normalizeDocumentRoot(content: unknown): DocumentRootNode {\n if (content && typeof content === \"object\" &&\n ((content as { type?: string }).type === \"doc\" || (content as { type?: string }).type === \"document_root\")) {\n return content as DocumentRootNode;\n }\n\n if (Array.isArray(content)) {\n return {\n type: \"doc\",\n children: content.filter(\n (value): value is DocumentRootNode[\"children\"][number] =>\n Boolean(value) &&\n typeof value === \"object\" &&\n ((value as { type?: string }).type === \"paragraph\" ||\n (value as { type?: string }).type === \"table\" ||\n (value as { type?: string }).type === \"sdt\" ||\n (value as { type?: string }).type === \"custom_xml\" ||\n (value as { type?: string }).type === \"alt_chunk\" ||\n (value as { type?: string }).type === \"opaque_block\"),\n ),\n };\n }\n\n return {\n type: \"doc\",\n children: [{ type: \"paragraph\", children: [] }],\n };\n}\n\nfunction createFloatingImageDetail(\n altText: string | undefined,\n floating: {\n horizontalPosition?: { relativeFrom?: string; align?: string; offset?: number };\n verticalPosition?: { relativeFrom?: string; align?: string; offset?: number };\n wrap?: string;\n } | undefined,\n): string {\n const parts = [altText ? `Alt text ${altText}.` : \"Floating image rendered inline in the editor.\"];\n if (floating?.wrap) {\n parts.push(`Wrap ${floating.wrap}.`);\n }\n if (floating?.horizontalPosition?.align || floating?.horizontalPosition?.offset !== undefined) {\n parts.push(\n `Horizontal ${floating.horizontalPosition.align ?? floating.horizontalPosition.offset}.`,\n );\n }\n if (floating?.verticalPosition?.align || floating?.verticalPosition?.offset !== undefined) {\n parts.push(\n `Vertical ${floating.verticalPosition.align ?? floating.verticalPosition.offset}.`,\n );\n }\n return parts.join(\" \");\n}\n\nfunction hasMediaItem(media: Record<string, unknown>, mediaId: string): boolean {\n if (mediaId in media) {\n return true;\n }\n\n const items = media.items;\n if (!items || typeof items !== \"object\" || Array.isArray(items)) {\n return false;\n }\n\n return mediaId in items;\n}\n","import {\n createEditorState,\n createPersistedEditorSnapshot,\n deriveDocumentStats,\n type CanonicalDocumentEnvelope,\n type CommentEntryRecord,\n type CommentThreadRecord,\n type CompatibilityFeatureEntry as InternalCompatibilityFeatureEntry,\n type CompatibilityReport as InternalCompatibilityReport,\n type EditorError as InternalEditorError,\n type EditorState,\n type EditorWarning as InternalEditorWarning,\n} from \"../core/state/editor-state.ts\";\nimport type {\n AddCommentParams,\n CommentSidebarSnapshot,\n CommentSidebarThreadSnapshot,\n CompatibilityReport,\n EditorAnchorProjection,\n EditorError,\n EditorWarning,\n ExportDocxOptions,\n ExportResult,\n PersistedEditorSnapshot,\n RuntimeRenderSnapshot,\n SelectionSnapshot,\n TrackedChangeEntrySnapshot,\n TrackedChangesSnapshot,\n WordReviewEditorEvent,\n} from \"../api/public-types\";\nimport {\n executeEditorCommand,\n selectionChanged,\n type CommandOrigin,\n type EditorCommand,\n type EditorTransaction,\n} from \"../core/commands/index.ts\";\nimport {\n createDetachedAnchor,\n createNodeAnchor,\n createRangeAnchor,\n type EditorAnchorProjection as InternalEditorAnchorProjection,\n} from \"../core/selection/mapping.ts\";\nimport { createCommentSidebarProjection } from \"../review/store/comment-store.ts\";\nimport { createCommentStoreFromRuntimeComments } from \"../review/store/runtime-comment-store.ts\";\nimport {\n createRevisionSidebarProjection,\n type RevisionStore,\n} from \"../review/store/revision-store.ts\";\nimport { buildCompatibilityReport } from \"../validation/compatibility-engine.ts\";\nimport { createEditorSurfaceSnapshot } from \"./surface-projection.ts\";\n\nexport type Unsubscribe = () => void;\n\nexport interface DocumentRuntime {\n subscribe(listener: () => void): Unsubscribe;\n subscribeToEvents(listener: (event: WordReviewEditorEvent) => void): Unsubscribe;\n getRenderSnapshot(): RuntimeRenderSnapshot;\n dispatch(command: EditorCommand): void;\n undo(): void;\n redo(): void;\n focus(): void;\n blur(): void;\n addComment(params: AddCommentParams): string;\n openComment(commentId: string): void;\n resolveComment(commentId: string): void;\n reopenComment(commentId: string): void;\n addCommentReply(commentId: string, body: string, authorId?: string): void;\n editCommentBody(commentId: string, body: string): void;\n acceptChange(changeId: string): void;\n rejectChange(changeId: string): void;\n acceptAllChanges(): void;\n rejectAllChanges(): void;\n getPersistedSnapshot(): PersistedEditorSnapshot;\n getCompatibilityReport(): CompatibilityReport;\n getWarnings(): EditorWarning[];\n exportDocx(options?: ExportDocxOptions): Promise<ExportResult>;\n}\n\nexport interface CreateDocumentRuntimeOptions {\n documentId: string;\n initialSnapshot?: PersistedEditorSnapshot;\n initialCanonicalDocument?: CanonicalDocumentEnvelope;\n sourceLabel?: string;\n sourceKind?: \"docx\" | \"snapshot\" | \"datastore\" | \"canonical\";\n readOnly?: boolean;\n editorBuild?: string;\n defaultAuthorId?: string;\n fatalError?: EditorError;\n clock?: () => string;\n exportDocx?: (\n snapshot: PersistedEditorSnapshot,\n options?: ExportDocxOptions,\n ) => Promise<ExportResult>;\n onEvent?: (event: WordReviewEditorEvent) => void;\n onWarning?: (warning: EditorWarning) => void;\n onError?: (error: EditorError) => void;\n}\n\ninterface HistoryState {\n past: EditorState[];\n future: EditorState[];\n}\n\nexport function createDocumentRuntime(\n options: CreateDocumentRuntimeOptions,\n): DocumentRuntime {\n const clock = options.clock ?? (() => new Date().toISOString());\n const editorBuild = options.editorBuild ?? \"dev\";\n const sessionId = createSessionId(options.documentId, clock());\n const listeners = new Set<() => void>();\n const eventListeners = new Set<(event: WordReviewEditorEvent) => void>();\n const history: HistoryState = {\n past: [],\n future: [],\n };\n\n let state = createEditorState({\n documentId: options.documentId,\n sessionId,\n sourceLabel: options.sourceLabel,\n readOnly: options.readOnly,\n persistedSnapshot: options.initialSnapshot as never,\n canonicalDocument: options.initialCanonicalDocument,\n fatalError: options.fatalError as never,\n });\n let cachedRenderSnapshot = createPublicRenderSnapshot(state, history);\n\n emit({\n type: \"ready\",\n documentId: state.documentId,\n sessionId: state.sessionId,\n source: options.sourceKind ?? (options.initialSnapshot ? \"snapshot\" : \"canonical\"),\n stats: toPublicDocumentStats(state),\n compatibility: toPublicCompatibilityReport(createDerivedCompatibility(state)),\n });\n if (options.fatalError) {\n emit({\n type: \"error\",\n documentId: state.documentId,\n error: options.fatalError,\n });\n }\n\n return {\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n subscribeToEvents(listener) {\n eventListeners.add(listener);\n return () => {\n eventListeners.delete(listener);\n };\n },\n getRenderSnapshot() {\n return cachedRenderSnapshot;\n },\n dispatch(command) {\n if (command.type === \"history.undo\") {\n applyHistory(\"undo\");\n return;\n }\n\n if (command.type === \"history.redo\") {\n applyHistory(\"redo\");\n return;\n }\n\n try {\n const transaction = executeEditorCommand(state, command, {\n timestamp: command.origin?.timestamp ?? clock(),\n });\n commit(transaction);\n } catch (error) {\n emitError(toRuntimeError(error));\n }\n },\n undo() {\n this.dispatch({\n type: \"history.undo\",\n origin: createOrigin(\"runtime\", clock()),\n });\n },\n redo() {\n this.dispatch({\n type: \"history.redo\",\n origin: createOrigin(\"runtime\", clock()),\n });\n },\n focus() {\n this.dispatch({\n type: \"runtime.focus\",\n focused: true,\n origin: createOrigin(\"api\", clock()),\n });\n },\n blur() {\n this.dispatch({\n type: \"runtime.focus\",\n focused: false,\n origin: createOrigin(\"api\", clock()),\n });\n },\n addComment(params) {\n const commentId = createEntityId(\"comment\", state.document.review.comments, clock());\n const anchor = params.anchor\n ? toInternalAnchorProjection(params.anchor)\n : state.selection.activeRange;\n const authorId = params.authorId ?? options.defaultAuthorId ?? \"unknown\";\n const createdAt = clock();\n const entries: CommentEntryRecord[] = [\n {\n entryId: `${commentId}-entry-1`,\n authorId,\n body: params.body ?? \"\",\n createdAt,\n },\n ];\n const comment: CommentThreadRecord = {\n commentId,\n anchor,\n createdAt,\n createdBy: authorId,\n authorId,\n body: params.body ?? \"\",\n entries,\n status: anchor.kind === \"detached\" ? \"detached\" : \"open\",\n warningIds: [],\n isResolved: false,\n metadata: {\n source: \"runtime\",\n },\n };\n\n this.dispatch({\n type: \"comment.add\",\n comment,\n origin: createOrigin(\"api\", clock()),\n });\n\n return commentId;\n },\n openComment(commentId) {\n this.dispatch({\n type: \"comment.open\",\n commentId,\n origin: createOrigin(\"api\", clock()),\n });\n },\n resolveComment(commentId) {\n this.dispatch({\n type: \"comment.resolve\",\n commentId,\n resolvedBy: options.defaultAuthorId ?? \"unknown\",\n origin: createOrigin(\"api\", clock()),\n });\n },\n reopenComment(commentId) {\n this.dispatch({\n type: \"comment.reopen\",\n commentId,\n origin: createOrigin(\"api\", clock()),\n });\n },\n addCommentReply(commentId, body, authorId) {\n this.dispatch({\n type: \"comment.add-reply\",\n commentId,\n body,\n authorId: authorId ?? options.defaultAuthorId,\n origin: createOrigin(\"api\", clock()),\n });\n },\n editCommentBody(commentId, body) {\n this.dispatch({\n type: \"comment.edit-body\",\n commentId,\n body,\n origin: createOrigin(\"api\", clock()),\n });\n },\n acceptChange(changeId) {\n this.dispatch({\n type: \"change.accept\",\n changeId,\n origin: createOrigin(\"api\", clock()),\n });\n },\n rejectChange(changeId) {\n this.dispatch({\n type: \"change.reject\",\n changeId,\n origin: createOrigin(\"api\", clock()),\n });\n },\n acceptAllChanges() {\n this.dispatch({\n type: \"change.accept-all\",\n origin: createOrigin(\"api\", clock()),\n });\n },\n rejectAllChanges() {\n this.dispatch({\n type: \"change.reject-all\",\n origin: createOrigin(\"api\", clock()),\n });\n },\n getPersistedSnapshot() {\n const compatibility = createDerivedCompatibility(state);\n return createPersistedEditorSnapshot(state, {\n editorBuild,\n savedAt: clock(),\n compatibility,\n }) as unknown as PersistedEditorSnapshot;\n },\n getCompatibilityReport() {\n return toPublicCompatibilityReport(createDerivedCompatibility(state));\n },\n getWarnings() {\n return state.warnings.map((warning) => toPublicWarning(warning));\n },\n async exportDocx(exportOptions) {\n if (!options.exportDocx) {\n const error: InternalEditorError = {\n errorId: createEntityId(\"error\", {}, clock()),\n code: \"export_failed\",\n isFatal: false,\n message: \"DOCX export requires an injected exporter until the IO substrate lands.\",\n source: \"export\",\n details: {\n requestedOptions: exportOptions ?? {},\n },\n };\n emitError(error);\n throw new Error(error.message);\n }\n\n const result = await options.exportDocx(\n createPersistedEditorSnapshot(state, {\n editorBuild,\n savedAt: clock(),\n compatibility: createDerivedCompatibility(state),\n }) as unknown as PersistedEditorSnapshot,\n exportOptions,\n );\n\n emit({\n type: \"export_completed\",\n documentId: state.documentId,\n result,\n });\n\n return result;\n },\n };\n\n function applyHistory(direction: \"undo\" | \"redo\"): void {\n const source = direction === \"undo\" ? history.past : history.future;\n const target = source.pop();\n\n if (!target) {\n return;\n }\n\n const counterpart = direction === \"undo\" ? history.future : history.past;\n counterpart.push(state);\n\n const previous = state;\n // Undo/redo changes the document — must mint a new revisionToken so\n // autosave/export checkpoint dedup treats it as fresh content.\n state = finalizeState(target, true, clock());\n cachedRenderSnapshot = createPublicRenderSnapshot(state, history);\n notify(previous, state, {\n nextState: state,\n mapping: { steps: [] },\n effects: {\n warningsAdded: [],\n warningsCleared: [],\n },\n historyBoundary: \"skip\",\n markDirty: true,\n });\n }\n\n function commit(transaction: EditorTransaction): void {\n const previous = state;\n\n if (transaction.historyBoundary === \"push\") {\n history.past.push(state);\n history.future = [];\n }\n\n state = finalizeState(transaction.nextState, transaction.markDirty, clock());\n cachedRenderSnapshot = createPublicRenderSnapshot(state, history);\n notify(previous, state, transaction);\n }\n\n function notify(\n previous: EditorState,\n next: EditorState,\n transaction: EditorTransaction,\n ): void {\n if (previous.isDirty !== next.isDirty) {\n emit({\n type: \"dirty_changed\",\n documentId: next.documentId,\n isDirty: next.isDirty,\n });\n }\n\n if (selectionChanged(previous.selection, next.selection)) {\n emit({\n type: \"selection_changed\",\n documentId: next.documentId,\n selection: toPublicSelectionSnapshot(next.selection),\n });\n }\n\n if (transaction.effects.commentAdded) {\n emit({\n type: \"comment_added\",\n documentId: next.documentId,\n commentId: transaction.effects.commentAdded.commentId,\n anchor: toPublicAnchorProjection(transaction.effects.commentAdded.anchor),\n });\n }\n\n if (transaction.effects.commentResolved) {\n emit({\n type: \"comment_resolved\",\n documentId: next.documentId,\n commentId: transaction.effects.commentResolved.commentId,\n });\n }\n\n if (transaction.effects.changeAccepted) {\n emit({\n type: \"change_accepted\",\n documentId: next.documentId,\n changeId: transaction.effects.changeAccepted.changeId,\n });\n }\n\n if (transaction.effects.changeRejected) {\n emit({\n type: \"change_rejected\",\n documentId: next.documentId,\n changeId: transaction.effects.changeRejected.changeId,\n });\n }\n\n for (const warning of transaction.effects.warningsAdded) {\n const publicWarning = toPublicWarning(warning);\n emit({\n type: \"warning_added\",\n documentId: next.documentId,\n warning: publicWarning,\n });\n options.onWarning?.(publicWarning);\n }\n\n for (const cleared of transaction.effects.warningsCleared) {\n emit({\n type: \"warning_cleared\",\n documentId: next.documentId,\n warningId: cleared.warningId,\n code: cleared.code,\n });\n }\n\n for (const listener of listeners) {\n listener();\n }\n }\n\n function emit(event: WordReviewEditorEvent): void {\n options.onEvent?.(event);\n for (const listener of eventListeners) {\n listener(event);\n }\n }\n\n function emitError(error: InternalEditorError): void {\n const nextState: EditorState = {\n ...state,\n phase: error.isFatal ? \"error\" : state.phase,\n fatalError: error.isFatal ? error : state.fatalError,\n };\n state = nextState;\n cachedRenderSnapshot = createPublicRenderSnapshot(state, history);\n const publicError = toPublicError(error);\n options.onError?.(publicError);\n emit({\n type: \"error\",\n documentId: state.documentId,\n error: publicError,\n });\n for (const listener of listeners) {\n listener();\n }\n }\n}\n\nfunction createSessionId(documentId: string, timestamp: string): string {\n return `session-${documentId}-${timestamp.replace(/[^0-9]/gu, \"\")}`;\n}\n\nfunction createOrigin(\n source: CommandOrigin[\"source\"],\n timestamp: string,\n): CommandOrigin {\n return {\n source,\n timestamp,\n };\n}\n\nfunction createEntityId(\n prefix: string,\n existing: Record<string, unknown>,\n timestamp: string,\n): string {\n let counter = Object.keys(existing).length;\n let nextId = `${prefix}-${timestamp.replace(/[^0-9]/gu, \"\")}-${counter}`;\n\n while (existing[nextId]) {\n counter += 1;\n nextId = `${prefix}-${timestamp.replace(/[^0-9]/gu, \"\")}-${counter}`;\n }\n\n return nextId;\n}\n\nfunction finalizeState(\n state: EditorState,\n markDirty: boolean,\n timestamp: string,\n): EditorState {\n // Only increment revision on actual document mutations (markDirty=true).\n // Selection-only changes must not churn the revisionToken, which would\n // cause autosave/checkpoint dedup to treat cursor movement as new content.\n const revision = markDirty ? state.revision + 1 : state.revision;\n\n return {\n ...state,\n document: {\n ...state.document,\n updatedAt: markDirty ? timestamp : state.document.updatedAt,\n },\n selection: state.selection,\n revision,\n revisionToken: `${state.sessionId}:${revision}`,\n isDirty: state.isDirty || markDirty,\n };\n}\n\nfunction toRuntimeError(error: unknown): InternalEditorError {\n if (typeof error === \"object\" && error && \"message\" in error) {\n return {\n errorId: createSessionId(\"runtime-error\", new Date().toISOString()),\n code: \"internal_invariant\",\n isFatal: false,\n message: String((error as { message?: unknown }).message ?? \"Runtime error\"),\n source: \"runtime\",\n };\n }\n\n return {\n errorId: createSessionId(\"runtime-error\", new Date().toISOString()),\n code: \"internal_invariant\",\n isFatal: false,\n message: \"Runtime error\",\n source: \"runtime\",\n };\n}\n\nfunction createPublicRenderSnapshot(\n state: EditorState,\n history: HistoryState,\n): RuntimeRenderSnapshot {\n const compatibility = createDerivedCompatibility(state);\n const surface = createEditorSurfaceSnapshot(state.document, state.selection);\n const comments = toPublicCommentSidebarSnapshot(state);\n const trackedChanges = toPublicTrackedChangesSnapshot(state, surface.plainText);\n\n return {\n documentId: state.documentId,\n sessionId: state.sessionId,\n sourceLabel: state.sourceLabel,\n revisionToken: state.revisionToken,\n isReady: state.phase === \"ready\",\n isDirty: state.isDirty,\n readOnly: state.readOnly,\n selection: toPublicSelectionSnapshot(state.selection),\n documentStats: toPublicDocumentStats(state),\n comments,\n trackedChanges,\n compatibility: {\n blockExport: compatibility.blockExport,\n blockExportReasons: listBlockExportReasons(compatibility),\n warningCount: compatibility.warnings.length,\n errorCount: compatibility.errors.length,\n featureEntries: compatibility.featureEntries.map((entry) =>\n toPublicCompatibilityFeatureEntry(entry),\n ),\n },\n warnings: state.warnings.map((warning) => toPublicWarning(warning)),\n fatalError: state.fatalError ? toPublicError(state.fatalError) : undefined,\n commandState: {\n canUndo: history.past.length > 0,\n canRedo: history.future.length > 0,\n readOnly: state.readOnly,\n },\n surface,\n };\n}\n\nfunction toPublicDocumentStats(state: Pick<EditorState, \"document\">) {\n const stats = deriveDocumentStats(state);\n return {\n storyLength: stats.characterCount,\n commentCount: stats.commentCount,\n revisionCount: stats.revisionCount,\n opaqueFragmentCount: countOpaqueFragments(state.document.preservation.opaqueFragments),\n };\n}\n\nfunction toPublicSelectionSnapshot(\n selection: EditorState[\"selection\"],\n): SelectionSnapshot {\n return {\n anchor: selection.anchor,\n head: selection.head,\n isCollapsed: selection.isCollapsed,\n activeRange: toPublicAnchorProjection(selection.activeRange),\n };\n}\n\nfunction toPublicAnchorProjection(\n anchor: InternalEditorAnchorProjection,\n): EditorAnchorProjection {\n switch (anchor.kind) {\n case \"range\":\n return {\n kind: \"range\",\n from: anchor.range.from,\n to: anchor.range.to,\n assoc: anchor.assoc,\n };\n case \"node\":\n return {\n kind: \"node\",\n at: anchor.at,\n assoc: anchor.assoc,\n };\n case \"detached\":\n return {\n kind: \"detached\",\n lastKnownRange: anchor.lastKnownRange,\n reason: anchor.reason,\n };\n }\n}\n\nfunction toInternalAnchorProjection(\n anchor: EditorAnchorProjection,\n): InternalEditorAnchorProjection {\n switch (anchor.kind) {\n case \"range\":\n return createRangeAnchor(anchor.from, anchor.to, anchor.assoc);\n case \"node\":\n return createNodeAnchor(anchor.at, anchor.assoc);\n case \"detached\":\n return createDetachedAnchor(anchor.lastKnownRange, anchor.reason);\n }\n}\n\nfunction toPublicCompatibilityReport(\n report: InternalCompatibilityReport,\n): CompatibilityReport {\n return {\n reportVersion: report.reportVersion,\n generatedAt: report.generatedAt,\n blockExport: report.blockExport,\n featureEntries: report.featureEntries.map((entry) =>\n toPublicCompatibilityFeatureEntry(entry),\n ),\n warnings: report.warnings.map((warning) => toPublicWarning(warning)),\n errors: report.errors.map((error) => toPublicError(error)),\n };\n}\n\nfunction toPublicCompatibilityFeatureEntry(\n entry: InternalCompatibilityFeatureEntry,\n) {\n return {\n ...entry,\n affectedAnchor: entry.affectedAnchor\n ? toPublicAnchorProjection(entry.affectedAnchor)\n : undefined,\n };\n}\n\nfunction toPublicWarning(warning: InternalEditorWarning): EditorWarning {\n return {\n ...warning,\n affectedAnchor: warning.affectedAnchor\n ? toPublicAnchorProjection(warning.affectedAnchor)\n : undefined,\n };\n}\n\nfunction toPublicError(error: InternalEditorError): EditorError {\n return { ...error };\n}\n\nfunction countOpaqueFragments(opaqueFragments: Record<string, unknown>): number {\n return Object.keys(opaqueFragments).length;\n}\n\nfunction createDerivedCompatibility(state: EditorState): InternalCompatibilityReport {\n return buildCompatibilityReport({\n document: state.document,\n warnings: state.warnings,\n fatalError: state.fatalError,\n generatedAt: state.document.updatedAt,\n });\n}\n\nfunction toPublicCommentSidebarSnapshot(\n state: EditorState,\n): CommentSidebarSnapshot {\n const projection = createCommentSidebarProjection(\n createCommentStoreFromRuntimeComments(state.document.review.comments),\n state.runtime.activeCommentId,\n );\n\n return {\n activeCommentId: state.runtime.activeCommentId,\n openCommentIds: projection.openCommentIds,\n resolvedCommentIds: projection.resolvedCommentIds,\n detachedCommentIds: projection.detachedCommentIds,\n totalCount: projection.totalCount,\n threads: projection.threads.map((thread): CommentSidebarThreadSnapshot => {\n const sourceThread = state.document.review.comments[thread.commentId];\n const projectedEntries =\n sourceThread?.entries?.map((entry) => ({\n entryId: entry.entryId,\n authorId: entry.authorId,\n body: entry.body,\n createdAt: entry.createdAt,\n })) ??\n (sourceThread?.body\n ? [\n {\n entryId: `${thread.commentId}-entry-1`,\n authorId:\n sourceThread.authorId ?? sourceThread.createdBy ?? \"unknown\",\n body: sourceThread.body,\n createdAt: sourceThread.createdAt,\n },\n ]\n : []);\n\n return {\n commentId: thread.commentId,\n status: thread.status,\n anchor: toPublicAnchorProjection(\n sourceThread?.anchor ??\n createDetachedAnchor({ from: 0, to: 0 }, \"importAmbiguity\"),\n ),\n excerpt: thread.excerpt,\n entryCount: thread.entryCount,\n createdAt: thread.createdAt,\n createdBy: thread.createdBy,\n warningCount: thread.warningCount,\n anchorLabel: thread.anchorLabel,\n isActive: thread.isActive,\n resolvedAt: thread.resolvedAt,\n resolvedBy: thread.resolvedBy,\n entries: projectedEntries,\n };\n }),\n };\n}\n\nfunction toPublicTrackedChangesSnapshot(\n state: EditorState,\n surfaceText = \"\",\n): TrackedChangesSnapshot {\n const projection = createRevisionSidebarProjection(\n createRevisionStoreFromDocument(state),\n );\n\n return {\n pendingChangeIds: projection.activeRevisionIds,\n acceptedChangeIds: projection.acceptedRevisionIds,\n rejectedChangeIds: projection.rejectedRevisionIds,\n detachedChangeIds: projection.detachedRevisionIds,\n actionableChangeIds: projection.actionableRevisionIds,\n preserveOnlyChangeIds: projection.preserveOnlyRevisionIds,\n totalCount: projection.totalCount,\n revisions: projection.revisions.map((revision): TrackedChangeEntrySnapshot => {\n const sourceRevision = state.document.review.revisions[revision.revisionId];\n const preview = describeRevisionPreview(\n revision,\n sourceRevision?.anchor ??\n createDetachedAnchor({ from: 0, to: 0 }, \"importAmbiguity\"),\n surfaceText,\n );\n\n return {\n revisionId: revision.revisionId,\n kind: revision.kind,\n label: revision.label,\n status: revision.status,\n actionability: revision.actionability,\n anchor: toPublicAnchorProjection(\n sourceRevision?.anchor ??\n createDetachedAnchor({ from: 0, to: 0 }, \"importAmbiguity\"),\n ),\n anchorLabel: revision.anchorLabel,\n createdAt: revision.createdAt,\n authorId: revision.authorId,\n warningCount: revision.warningCount,\n canAccept: revision.canAccept,\n canReject: revision.canReject,\n importedRevisionForm: sourceRevision?.metadata?.importedRevisionForm,\n preserveOnlyReason: revision.preserveOnlyReason,\n excerpt: preview.excerpt,\n detail: preview.detail,\n };\n }),\n };\n}\n\nfunction createRevisionStoreFromDocument(\n state: Pick<EditorState, \"document\">,\n): RevisionStore {\n return {\n version: \"revision-store/1\",\n revisions: Object.fromEntries(\n Object.values(state.document.review.revisions).map((revision) => [\n revision.changeId,\n {\n revisionId: revision.changeId,\n kind: revision.kind,\n anchor: revision.anchor,\n authorId: revision.authorId ?? \"unknown\",\n createdAt: revision.createdAt,\n status:\n revision.status === \"open\"\n ? \"active\"\n : revision.status,\n warningIds: [...(revision.warningIds ?? [])],\n metadata: {\n source: revision.metadata?.source ?? \"runtime\",\n preserveOnlyReason: revision.metadata?.preserveOnlyReason,\n importedRevisionForm: revision.metadata?.importedRevisionForm,\n originalRevisionType: revision.metadata?.originalRevisionType,\n ooxmlRevisionId: revision.metadata?.ooxmlRevisionId,\n },\n },\n ]),\n ),\n };\n}\n\nfunction listBlockExportReasons(\n report: InternalCompatibilityReport,\n): string[] {\n return [\n ...report.featureEntries\n .filter((entry) => entry.featureClass === \"unsupported-fatal\")\n .map((entry) => entry.message),\n ...report.errors\n .filter((error) => error.isFatal)\n .map((error) => error.message),\n ];\n}\n\nfunction describeRevisionPreview(\n revision: ReturnType<typeof createRevisionSidebarProjection>[\"revisions\"][number],\n anchor: InternalEditorAnchorProjection,\n plainText: string,\n): { excerpt: string; detail: string } {\n const { from, to } = toAnchorBounds(anchor);\n const excerpt = summarizeRevisionExcerpt(plainText, from, to, revision.label);\n\n if (revision.actionability === \"preserve-only\") {\n return {\n excerpt,\n detail:\n revision.preserveOnlyReason ??\n \"Visible for review, but this change remains preserve-only in the current runtime.\",\n };\n }\n\n if (revision.status === \"accepted\") {\n return {\n excerpt,\n detail: \"Accepted in the live review runtime and retained here for audit visibility.\",\n };\n }\n\n if (revision.status === \"rejected\") {\n return {\n excerpt,\n detail: \"Rejected in the live review runtime and retained here for audit visibility.\",\n };\n }\n\n return {\n excerpt,\n detail:\n revision.kind === \"deletion\"\n ? \"Deleted content stays reviewable here until it is accepted or rejected.\"\n : \"Runtime-backed change. Review it here or reopen the anchor in the canvas.\",\n };\n}\n\nfunction toAnchorBounds(anchor: InternalEditorAnchorProjection): { from: number; to: number } {\n switch (anchor.kind) {\n case \"range\":\n return {\n from: Math.min(anchor.range.from, anchor.range.to),\n to: Math.max(anchor.range.from, anchor.range.to),\n };\n case \"node\":\n return {\n from: anchor.at,\n to: anchor.at + 1,\n };\n case \"detached\":\n return {\n from: Math.min(anchor.lastKnownRange.from, anchor.lastKnownRange.to),\n to: Math.max(anchor.lastKnownRange.from, anchor.lastKnownRange.to),\n };\n }\n}\n\nfunction summarizeRevisionExcerpt(\n plainText: string,\n from: number,\n to: number,\n fallback: string,\n): string {\n const normalizedFrom = Math.max(0, Math.min(from, plainText.length));\n const normalizedTo = Math.max(normalizedFrom, Math.min(to, plainText.length));\n const collapsed = plainText\n .slice(normalizedFrom, normalizedTo)\n .replace(/\\s+/g, \" \")\n .trim();\n\n if (!collapsed) {\n return fallback;\n }\n\n return collapsed.length > 96 ? `${collapsed.slice(0, 93)}...` : collapsed;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","export const CONTENT_TYPES_PATH = \"/[Content_Types].xml\";\nexport const PACKAGE_RELATIONSHIPS_PATH = \"/_rels/.rels\";\n\nexport type OpcCompressionMethod = \"store\" | \"deflate\";\nexport type OpcSurfaceKind = \"content\" | \"relationships\" | \"content-types\";\nexport type OpcRelationshipTargetMode = \"internal\" | \"external\";\n\nexport interface OpcRelationship {\n id: string;\n type: string;\n target: string;\n targetMode: OpcRelationshipTargetMode;\n}\n\nexport interface OpcPartManifestEntry {\n path: string;\n surfaceKind: OpcSurfaceKind;\n contentType: string | null;\n relationshipsPartPath: string | null;\n relationships: OpcRelationship[];\n compression: OpcCompressionMethod;\n byteLength: number;\n}\n\nexport interface OpcContentTypesManifest {\n defaults: Record<string, string>;\n overrides: Record<string, string>;\n}\n\nexport interface OpcPackageManifest {\n contentTypes: OpcContentTypesManifest;\n packageRelationships: OpcRelationship[];\n parts: OpcPartManifestEntry[];\n}\n\nexport interface OpcPackagePart {\n path: string;\n surfaceKind: OpcSurfaceKind;\n contentType: string | null;\n relationshipsPartPath: string | null;\n relationships: OpcRelationship[];\n compression: OpcCompressionMethod;\n bytes: Uint8Array;\n crc32: number;\n}\n\nexport function normalizePartPath(path: string): string {\n const normalized = path.replace(/\\\\/g, \"/\").trim();\n if (normalized.length === 0) {\n throw new Error(\"OPC part path must not be empty.\");\n }\n\n const withLeadingSlash = normalized.startsWith(\"/\") ? normalized : `/${normalized}`;\n const segments = withLeadingSlash.split(\"/\");\n const resolved: string[] = [];\n\n for (const segment of segments) {\n if (segment === \"\" || segment === \".\") {\n continue;\n }\n\n if (segment === \"..\") {\n if (resolved.length === 0) {\n throw new Error(`OPC part path escapes package root: ${path}`);\n }\n\n resolved.pop();\n continue;\n }\n\n resolved.push(segment);\n }\n\n return `/${resolved.join(\"/\")}`;\n}\n\nexport function getExtension(partPath: string): string {\n const normalized = normalizePartPath(partPath);\n const lastSlash = normalized.lastIndexOf(\"/\");\n const lastDot = normalized.lastIndexOf(\".\");\n if (lastDot <= lastSlash) {\n return \"\";\n }\n\n return normalized.slice(lastDot + 1).toLowerCase();\n}\n\nexport function getRelationshipsPartPath(partPath?: string | null): string {\n if (!partPath) {\n return PACKAGE_RELATIONSHIPS_PATH;\n }\n\n const normalized = normalizePartPath(partPath);\n const lastSlash = normalized.lastIndexOf(\"/\");\n const directory = lastSlash <= 0 ? \"\" : normalized.slice(0, lastSlash);\n const filename = normalized.slice(lastSlash + 1);\n return `${directory}/_rels/${filename}.rels`;\n}\n\nexport function getSourcePartPathFromRelationshipsPart(path: string): string | null {\n const normalized = normalizePartPath(path);\n if (normalized === PACKAGE_RELATIONSHIPS_PATH) {\n return null;\n }\n\n const marker = \"/_rels/\";\n const markerIndex = normalized.lastIndexOf(marker);\n if (markerIndex === -1 || !normalized.endsWith(\".rels\")) {\n throw new Error(`Invalid OPC relationships part path: ${path}`);\n }\n\n return normalizePartPath(\n `${normalized.slice(0, markerIndex)}${normalized.slice(markerIndex + marker.length, -\".rels\".length)}`,\n );\n}\n\nexport function resolveRelationshipTarget(\n sourcePartPath: string | null,\n relationship: Pick<OpcRelationship, \"target\" | \"targetMode\">,\n): string {\n if (relationship.targetMode === \"external\") {\n return relationship.target;\n }\n\n if (relationship.target.startsWith(\"/\")) {\n return normalizePartPath(relationship.target);\n }\n\n const basePath = sourcePartPath ? normalizePartPath(sourcePartPath) : \"/\";\n const baseDir = basePath === \"/\" ? \"/\" : basePath.slice(0, basePath.lastIndexOf(\"/\") + 1);\n return normalizePartPath(`${baseDir}${relationship.target}`);\n}\n\nexport function comparePartPaths(a: string, b: string): number {\n return normalizePartPath(a).localeCompare(normalizePartPath(b));\n}\n","import {\n CONTENT_TYPES_PATH,\n OpcCompressionMethod,\n OpcPackageManifest,\n OpcPackagePart,\n OpcRelationship,\n PACKAGE_RELATIONSHIPS_PATH,\n comparePartPaths,\n getExtension,\n getRelationshipsPartPath,\n normalizePartPath,\n} from \"../ooxml/part-manifest.ts\";\nimport type { OpcPackage } from \"./package-reader.ts\";\n\ninterface ZipEntryPayload {\n path: string;\n compression: OpcCompressionMethod;\n uncompressedBytes: Uint8Array;\n compressedBytes: Uint8Array;\n crc32: number;\n}\n\nexport function writeOpcPackage(input: OpcPackage | { manifest: OpcPackageManifest; parts: Map<string, OpcPackagePart> }): Uint8Array {\n const entries = collectZipEntries(input.manifest, input.parts);\n return buildZipArchive(entries);\n}\n\nfunction collectZipEntries(\n manifest: OpcPackageManifest,\n parts: Map<string, OpcPackagePart>,\n): ZipEntryPayload[] {\n const entries: ZipEntryPayload[] = [];\n const contentParts = [...parts.values()]\n .filter((part) => part.surfaceKind === \"content\")\n .sort((left, right) => comparePartPaths(left.path, right.path));\n\n entries.push(createZipPayload(CONTENT_TYPES_PATH, \"deflate\", encodeXml(buildContentTypesXml(manifest, contentParts))));\n entries.push(\n createZipPayload(\n PACKAGE_RELATIONSHIPS_PATH,\n \"deflate\",\n encodeXml(buildRelationshipsXml(manifest.packageRelationships)),\n ),\n );\n\n for (const part of contentParts) {\n entries.push(createZipPayload(part.path, part.compression, part.bytes));\n\n if (part.relationships.length > 0) {\n entries.push(\n createZipPayload(\n getRelationshipsPartPath(part.path),\n \"deflate\",\n encodeXml(buildRelationshipsXml(part.relationships)),\n ),\n );\n }\n }\n\n return entries.sort((left, right) => comparePartPaths(left.path, right.path));\n}\n\nfunction buildContentTypesXml(\n manifest: OpcPackageManifest,\n parts: OpcPackagePart[],\n): string {\n const defaults: Record<string, string> = {\n ...manifest.contentTypes.defaults,\n rels: manifest.contentTypes.defaults.rels ?? \"application/vnd.openxmlformats-package.relationships+xml\",\n xml: manifest.contentTypes.defaults.xml ?? \"application/xml\",\n };\n\n const overrides = { ...manifest.contentTypes.overrides };\n\n for (const part of parts) {\n if (!part.contentType) {\n throw new Error(`Cannot write OPC package: missing content type for ${part.path}.`);\n }\n\n const extension = getExtension(part.path);\n if (!extension) {\n overrides[part.path] = part.contentType;\n continue;\n }\n\n const defaultContentType = defaults[extension];\n if (!defaultContentType) {\n defaults[extension] = part.contentType;\n delete overrides[part.path];\n continue;\n }\n\n if (defaultContentType === part.contentType) {\n delete overrides[part.path];\n continue;\n }\n\n overrides[part.path] = part.contentType;\n }\n\n const defaultEntries = Object.entries(defaults).sort(([left], [right]) => left.localeCompare(right));\n const overrideEntries = Object.entries(overrides).sort(([left], [right]) => comparePartPaths(left, right));\n\n const defaultXml = defaultEntries\n .map(([extension, contentType]) => ` <Default Extension=\"${escapeXml(extension)}\" ContentType=\"${escapeXml(contentType)}\"/>`)\n .join(\"\\n\");\n const overrideXml = overrideEntries\n .map(([partName, contentType]) => ` <Override PartName=\"${escapeXml(partName)}\" ContentType=\"${escapeXml(contentType)}\"/>`)\n .join(\"\\n\");\n const body = [defaultXml, overrideXml].filter((value) => value.length > 0).join(\"\\n\");\n\n return [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n `<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">`,\n body,\n `</Types>`,\n ].join(\"\\n\");\n}\n\nfunction buildRelationshipsXml(relationships: OpcRelationship[]): string {\n const relationshipXml = [...relationships]\n .sort((left, right) => left.id.localeCompare(right.id))\n .map((relationship) => {\n const targetMode =\n relationship.targetMode === \"external\"\n ? ` TargetMode=\"External\"`\n : \"\";\n return ` <Relationship Id=\"${escapeXml(relationship.id)}\" Type=\"${escapeXml(relationship.type)}\" Target=\"${escapeXml(relationship.target)}\"${targetMode}/>`;\n })\n .join(\"\\n\");\n\n return [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n `<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">`,\n relationshipXml,\n `</Relationships>`,\n ].join(\"\\n\");\n}\n\nfunction createZipPayload(\n path: string,\n compression: OpcCompressionMethod,\n bytes: Uint8Array,\n): ZipEntryPayload {\n const normalizedPath = normalizePartPath(path).slice(1);\n const uncompressedBytes = new Uint8Array(bytes);\n // Keep export browser-safe by storing entries without Node-only compression primitives.\n const compressedBytes = uncompressedBytes;\n const effectiveCompression: OpcCompressionMethod = \"store\";\n\n return {\n path: normalizedPath,\n compression: effectiveCompression,\n uncompressedBytes,\n compressedBytes,\n crc32: calculateCrc32(uncompressedBytes),\n };\n}\n\nfunction buildZipArchive(entries: ZipEntryPayload[]): Uint8Array {\n const localChunks: Uint8Array[] = [];\n const centralChunks: Uint8Array[] = [];\n let localOffset = 0;\n\n for (const entry of entries) {\n const fileName = encodeUtf8(entry.path);\n const localHeader = createByteBuffer(30 + fileName.length);\n const localHeaderView = new DataView(localHeader.buffer);\n localHeaderView.setUint32(0, 0x04034b50, true);\n localHeaderView.setUint16(4, 20, true);\n localHeaderView.setUint16(6, 0, true);\n localHeaderView.setUint16(8, entry.compression === \"store\" ? 0 : 8, true);\n localHeaderView.setUint16(10, 0, true);\n localHeaderView.setUint16(12, 0, true);\n localHeaderView.setUint32(14, entry.crc32 >>> 0, true);\n localHeaderView.setUint32(18, entry.compressedBytes.byteLength, true);\n localHeaderView.setUint32(22, entry.uncompressedBytes.byteLength, true);\n localHeaderView.setUint16(26, fileName.length, true);\n localHeaderView.setUint16(28, 0, true);\n localHeader.set(fileName, 30);\n\n localChunks.push(localHeader, entry.compressedBytes);\n\n const centralHeader = createByteBuffer(46 + fileName.length);\n const centralHeaderView = new DataView(centralHeader.buffer);\n centralHeaderView.setUint32(0, 0x02014b50, true);\n centralHeaderView.setUint16(4, 20, true);\n centralHeaderView.setUint16(6, 20, true);\n centralHeaderView.setUint16(8, 0, true);\n centralHeaderView.setUint16(10, entry.compression === \"store\" ? 0 : 8, true);\n centralHeaderView.setUint16(12, 0, true);\n centralHeaderView.setUint16(14, 0, true);\n centralHeaderView.setUint32(16, entry.crc32 >>> 0, true);\n centralHeaderView.setUint32(20, entry.compressedBytes.byteLength, true);\n centralHeaderView.setUint32(24, entry.uncompressedBytes.byteLength, true);\n centralHeaderView.setUint16(28, fileName.length, true);\n centralHeaderView.setUint16(30, 0, true);\n centralHeaderView.setUint16(32, 0, true);\n centralHeaderView.setUint16(34, 0, true);\n centralHeaderView.setUint16(36, 0, true);\n centralHeaderView.setUint32(38, 0, true);\n centralHeaderView.setUint32(42, localOffset, true);\n centralHeader.set(fileName, 46);\n centralChunks.push(centralHeader);\n\n localOffset += localHeader.byteLength + entry.compressedBytes.byteLength;\n }\n\n const centralDirectoryOffset = localOffset;\n const centralDirectory = concatByteArrays(centralChunks);\n const endOfCentralDirectory = createByteBuffer(22);\n const endOfCentralDirectoryView = new DataView(endOfCentralDirectory.buffer);\n endOfCentralDirectoryView.setUint32(0, 0x06054b50, true);\n endOfCentralDirectoryView.setUint16(4, 0, true);\n endOfCentralDirectoryView.setUint16(6, 0, true);\n endOfCentralDirectoryView.setUint16(8, entries.length, true);\n endOfCentralDirectoryView.setUint16(10, entries.length, true);\n endOfCentralDirectoryView.setUint32(12, centralDirectory.byteLength, true);\n endOfCentralDirectoryView.setUint32(16, centralDirectoryOffset, true);\n endOfCentralDirectoryView.setUint16(20, 0, true);\n\n return concatByteArrays([...localChunks, centralDirectory, endOfCentralDirectory]);\n}\n\nfunction encodeXml(xml: string): Uint8Array {\n return encodeUtf8(xml);\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/\"/g, \""\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/'/g, \"'\");\n}\n\nfunction calculateCrc32(bytes: Uint8Array): number {\n let crc = 0xffffffff;\n\n for (const byte of bytes) {\n crc ^= byte;\n for (let bit = 0; bit < 8; bit += 1) {\n const mask = -(crc & 1);\n crc = (crc >>> 1) ^ (0xedb88320 & mask);\n }\n }\n\n return (crc ^ 0xffffffff) >>> 0;\n}\n\nfunction createByteBuffer(size: number): Uint8Array {\n return new Uint8Array(size);\n}\n\nfunction concatByteArrays(chunks: readonly Uint8Array[]): Uint8Array {\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return combined;\n}\n\nfunction encodeUtf8(value: string): Uint8Array {\n return new TextEncoder().encode(value);\n}\n\nexport { buildContentTypesXml, buildRelationshipsXml, calculateCrc32 };\n","import {\n getRelationshipsPartPath,\n type OpcPackageManifest,\n type OpcPackagePart,\n} from \"../ooxml/part-manifest.ts\";\nimport { writeOpcPackage } from \"./package-writer.ts\";\n\nexport const DOCX_MIME_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\";\nexport const DOCX_DOCUMENT_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\";\nexport const DOCX_DOCUMENT_RELATIONSHIP_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\";\n\ninterface WriteDocxPackageInput {\n documentXml: string;\n documentContentType?: string;\n packageRelationshipType?: string;\n}\n\nexport function writeDocxPackage(input: WriteDocxPackageInput): Uint8Array {\n const documentPath = \"/word/document.xml\";\n const contentType = input.documentContentType ?? DOCX_DOCUMENT_CONTENT_TYPE;\n const relationshipType =\n input.packageRelationshipType ?? DOCX_DOCUMENT_RELATIONSHIP_TYPE;\n const documentBytes = new TextEncoder().encode(input.documentXml);\n\n const documentPart: OpcPackagePart = {\n path: documentPath,\n surfaceKind: \"content\",\n contentType,\n relationshipsPartPath: getRelationshipsPartPath(documentPath),\n relationships: [],\n compression: \"deflate\",\n bytes: documentBytes,\n crc32: 0,\n };\n\n const manifest: OpcPackageManifest = {\n contentTypes: {\n defaults: {\n rels: \"application/vnd.openxmlformats-package.relationships+xml\",\n xml: \"application/xml\",\n },\n overrides: {\n [documentPath]: contentType,\n },\n },\n packageRelationships: [\n {\n id: \"rId1\",\n type: relationshipType,\n target: \"word/document.xml\",\n targetMode: \"internal\",\n },\n ],\n parts: [\n {\n path: documentPart.path,\n surfaceKind: documentPart.surfaceKind,\n contentType: documentPart.contentType,\n relationshipsPartPath: documentPart.relationshipsPartPath,\n relationships: documentPart.relationships,\n compression: documentPart.compression,\n byteLength: documentPart.bytes.byteLength,\n },\n ],\n };\n\n return writeOpcPackage({\n manifest,\n parts: new Map([[documentPart.path, documentPart]]),\n });\n}\n","import { inflateRawSync } from \"node:zlib\";\n\nimport {\n CONTENT_TYPES_PATH,\n OpcCompressionMethod,\n OpcPackageManifest,\n OpcPackagePart,\n OpcPartManifestEntry,\n OpcRelationship,\n PACKAGE_RELATIONSHIPS_PATH,\n getRelationshipsPartPath,\n getSourcePartPathFromRelationshipsPart,\n normalizePartPath,\n} from \"../ooxml/part-manifest.ts\";\n\ninterface ZipCentralDirectoryEntry {\n path: string;\n compression: OpcCompressionMethod;\n crc32: number;\n compressedSize: number;\n uncompressedSize: number;\n localHeaderOffset: number;\n generalPurposeBitFlag: number;\n}\n\nexport interface OpcPackage {\n manifest: OpcPackageManifest;\n parts: Map<string, OpcPackagePart>;\n sourceByteLength: number;\n}\n\nconst EOCD_SIGNATURE = 0x06054b50;\nconst CENTRAL_DIRECTORY_SIGNATURE = 0x02014b50;\nconst LOCAL_FILE_HEADER_SIGNATURE = 0x04034b50;\n\nexport function readOpcPackage(source: Uint8Array | ArrayBuffer): OpcPackage {\n const bytes = source instanceof Uint8Array ? source : new Uint8Array(source);\n const archive = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const centralDirectory = readCentralDirectory(archive);\n const parts = new Map<string, OpcPackagePart>();\n\n for (const entry of centralDirectory) {\n if (entry.path.endsWith(\"/\")) {\n continue;\n }\n\n const storedBytes = readZipEntry(archive, entry);\n const normalizedPath = normalizePartPath(entry.path);\n const surfaceKind = getSurfaceKind(normalizedPath);\n\n parts.set(normalizedPath, {\n path: normalizedPath,\n surfaceKind,\n contentType: null,\n relationshipsPartPath:\n surfaceKind === \"content\" ? getRelationshipsPartPath(normalizedPath) : null,\n relationships: [],\n compression: entry.compression,\n bytes: storedBytes,\n crc32: entry.crc32 >>> 0,\n });\n }\n\n const contentTypesPart = parts.get(CONTENT_TYPES_PATH);\n if (!contentTypesPart) {\n throw new Error(\"Invalid OPC package: missing /[Content_Types].xml.\");\n }\n\n const contentTypes = parseContentTypesXml(decodeXml(contentTypesPart.bytes));\n const packageRelationshipsPart = parts.get(PACKAGE_RELATIONSHIPS_PATH);\n const packageRelationships = packageRelationshipsPart\n ? parseRelationshipsXml(decodeXml(packageRelationshipsPart.bytes))\n : [];\n\n const manifestParts: OpcPartManifestEntry[] = [];\n\n for (const [path, part] of [...parts.entries()].sort(([left], [right]) => left.localeCompare(right))) {\n const contentType = resolveContentType(path, contentTypes);\n const relationshipsPartPath = part.surfaceKind === \"content\" ? getRelationshipsPartPath(path) : null;\n const relationshipsPart = relationshipsPartPath ? parts.get(relationshipsPartPath) : undefined;\n const relationships = relationshipsPart\n ? parseRelationshipsXml(decodeXml(relationshipsPart.bytes))\n : [];\n\n const nextPart: OpcPackagePart = {\n ...part,\n contentType,\n relationshipsPartPath,\n relationships,\n };\n\n parts.set(path, nextPart);\n manifestParts.push({\n path,\n surfaceKind: nextPart.surfaceKind,\n contentType,\n relationshipsPartPath,\n relationships,\n compression: nextPart.compression,\n byteLength: nextPart.bytes.byteLength,\n });\n }\n\n return {\n manifest: {\n contentTypes,\n packageRelationships,\n parts: manifestParts,\n },\n parts,\n sourceByteLength: bytes.byteLength,\n };\n}\n\nfunction readCentralDirectory(archive: Buffer): ZipCentralDirectoryEntry[] {\n const eocdOffset = findEndOfCentralDirectory(archive);\n const entryCount = archive.readUInt16LE(eocdOffset + 10);\n const centralDirectoryOffset = archive.readUInt32LE(eocdOffset + 16);\n const entries: ZipCentralDirectoryEntry[] = [];\n let offset = centralDirectoryOffset;\n\n for (let index = 0; index < entryCount; index += 1) {\n const signature = archive.readUInt32LE(offset);\n if (signature !== CENTRAL_DIRECTORY_SIGNATURE) {\n throw new Error(`Invalid ZIP central directory signature at offset ${offset}.`);\n }\n\n const generalPurposeBitFlag = archive.readUInt16LE(offset + 8);\n const compressionMethod = archive.readUInt16LE(offset + 10);\n const crc32 = archive.readUInt32LE(offset + 16);\n const compressedSize = archive.readUInt32LE(offset + 20);\n const uncompressedSize = archive.readUInt32LE(offset + 24);\n const fileNameLength = archive.readUInt16LE(offset + 28);\n const extraFieldLength = archive.readUInt16LE(offset + 30);\n const fileCommentLength = archive.readUInt16LE(offset + 32);\n const localHeaderOffset = archive.readUInt32LE(offset + 42);\n const fileNameOffset = offset + 46;\n const fileName = archive.subarray(fileNameOffset, fileNameOffset + fileNameLength).toString(\"utf8\");\n\n entries.push({\n path: fileName,\n compression: mapCompressionMethod(compressionMethod),\n crc32,\n compressedSize,\n uncompressedSize,\n localHeaderOffset,\n generalPurposeBitFlag,\n });\n\n offset += 46 + fileNameLength + extraFieldLength + fileCommentLength;\n }\n\n return entries;\n}\n\nfunction findEndOfCentralDirectory(archive: Buffer): number {\n const minimumEocdSize = 22;\n const maximumCommentSize = 0xffff;\n const searchStart = Math.max(0, archive.length - minimumEocdSize - maximumCommentSize);\n\n for (let offset = archive.length - minimumEocdSize; offset >= searchStart; offset -= 1) {\n if (archive.readUInt32LE(offset) === EOCD_SIGNATURE) {\n return offset;\n }\n }\n\n throw new Error(\"Invalid ZIP archive: end of central directory not found.\");\n}\n\nfunction readZipEntry(archive: Buffer, entry: ZipCentralDirectoryEntry): Uint8Array {\n const headerOffset = entry.localHeaderOffset;\n const signature = archive.readUInt32LE(headerOffset);\n if (signature !== LOCAL_FILE_HEADER_SIGNATURE) {\n throw new Error(`Invalid ZIP local file header signature at offset ${headerOffset}.`);\n }\n\n const fileNameLength = archive.readUInt16LE(headerOffset + 26);\n const extraFieldLength = archive.readUInt16LE(headerOffset + 28);\n const dataOffset = headerOffset + 30 + fileNameLength + extraFieldLength;\n const compressed = archive.subarray(dataOffset, dataOffset + entry.compressedSize);\n\n switch (entry.compression) {\n case \"store\":\n return new Uint8Array(compressed);\n case \"deflate\":\n return new Uint8Array(inflateRawSync(compressed));\n default:\n throw new Error(`Unsupported ZIP compression for ${entry.path}.`);\n }\n}\n\nfunction mapCompressionMethod(method: number): OpcCompressionMethod {\n switch (method) {\n case 0:\n return \"store\";\n case 8:\n return \"deflate\";\n default:\n throw new Error(`Unsupported ZIP compression method ${method}.`);\n }\n}\n\nfunction getSurfaceKind(path: string): OpcPartManifestEntry[\"surfaceKind\"] {\n if (path === CONTENT_TYPES_PATH) {\n return \"content-types\";\n }\n\n if (path === PACKAGE_RELATIONSHIPS_PATH || path.includes(\"/_rels/\")) {\n return \"relationships\";\n }\n\n return \"content\";\n}\n\nfunction decodeXml(bytes: Uint8Array): string {\n return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString(\"utf8\");\n}\n\nfunction parseContentTypesXml(xml: string): OpcPackageManifest[\"contentTypes\"] {\n const defaults: Record<string, string> = {};\n const overrides: Record<string, string> = {};\n\n for (const attributes of findTagAttributes(xml, \"Default\")) {\n const extension = attributes.Extension?.toLowerCase();\n const contentType = attributes.ContentType;\n if (!extension || !contentType) {\n continue;\n }\n\n defaults[extension] = contentType;\n }\n\n for (const attributes of findTagAttributes(xml, \"Override\")) {\n const partName = attributes.PartName;\n const contentType = attributes.ContentType;\n if (!partName || !contentType) {\n continue;\n }\n\n overrides[normalizePartPath(partName)] = contentType;\n }\n\n return { defaults, overrides };\n}\n\nfunction parseRelationshipsXml(xml: string): OpcRelationship[] {\n const relationships: OpcRelationship[] = [];\n\n for (const attributes of findTagAttributes(xml, \"Relationship\")) {\n const id = attributes.Id;\n const type = attributes.Type;\n const target = attributes.Target;\n if (!id || !type || !target) {\n continue;\n }\n\n relationships.push({\n id,\n type,\n target,\n targetMode: attributes.TargetMode === \"External\" ? \"external\" : \"internal\",\n });\n }\n\n return relationships;\n}\n\nfunction findTagAttributes(xml: string, tagName: string): Record<string, string>[] {\n const tagPattern = new RegExp(`<${tagName}\\\\b([^>]*)\\\\/?>`, \"g\");\n const results: Record<string, string>[] = [];\n let tagMatch: RegExpExecArray | null = tagPattern.exec(xml);\n\n while (tagMatch) {\n results.push(parseAttributes(tagMatch[1] ?? \"\"));\n tagMatch = tagPattern.exec(xml);\n }\n\n return results;\n}\n\nfunction parseAttributes(rawAttributes: string): Record<string, string> {\n const attributes: Record<string, string> = {};\n const attributePattern = /([A-Za-z_][\\w:.-]*)=\"([^\"]*)\"/g;\n let match: RegExpExecArray | null = attributePattern.exec(rawAttributes);\n\n while (match) {\n attributes[match[1]] = decodeXmlEntities(match[2]);\n match = attributePattern.exec(rawAttributes);\n }\n\n return attributes;\n}\n\nfunction decodeXmlEntities(value: string): string {\n return value\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/&/g, \"&\");\n}\n\nfunction resolveContentType(\n path: string,\n contentTypes: OpcPackageManifest[\"contentTypes\"],\n): string | null {\n if (path === CONTENT_TYPES_PATH) {\n return \"application/xml\";\n }\n\n const override = contentTypes.overrides[path];\n if (override) {\n return override;\n }\n\n const extension = path.includes(\".\") ? path.slice(path.lastIndexOf(\".\") + 1).toLowerCase() : \"\";\n return extension ? contentTypes.defaults[extension] ?? null : null;\n}\n\nexport { parseContentTypesXml, parseRelationshipsXml };\n","import type { OpcRelationship } from \"./part-manifest.ts\";\nimport { normalizePartPath, resolveRelationshipTarget } from \"./part-manifest.ts\";\n\nexport interface InlineMediaPart {\n path: string;\n contentType: string;\n}\n\nexport interface ParsedInlineMedia {\n type: \"image\";\n mediaId: string;\n relationshipId: string;\n packagePartName: string;\n contentType?: string;\n filename: string;\n altText?: string;\n display?: \"inline\" | \"floating\";\n floating?: {\n horizontalPosition?: {\n relativeFrom?: string;\n align?: string;\n offset?: number;\n };\n verticalPosition?: {\n relativeFrom?: string;\n align?: string;\n offset?: number;\n };\n wrap?: \"none\" | \"square\" | \"tight\" | \"through\" | \"topAndBottom\";\n behindDoc?: boolean;\n layoutInCell?: boolean;\n allowOverlap?: boolean;\n };\n}\n\ninterface XmlElementNode {\n type: \"element\";\n name: string;\n attributes: Record<string, string>;\n children: XmlNode[];\n}\n\ninterface XmlTextNode {\n type: \"text\";\n text: string;\n}\n\ntype XmlNode = XmlElementNode | XmlTextNode;\n\nexport function parseInlineMediaXml(\n xml: string,\n relationships: readonly OpcRelationship[],\n mediaParts: ReadonlyMap<string, InlineMediaPart> = new Map(),\n sourcePartPath = \"/word/document.xml\",\n): ParsedInlineMedia[] {\n const root = parseXml(xml);\n const relationshipMap = new Map(relationships.map((relationship) => [relationship.id, relationship]));\n const drawings = findDescendants(root, \"drawing\");\n const media: ParsedInlineMedia[] = [];\n\n for (const drawing of drawings) {\n const inline = findFirstDescendant(drawing, \"inline\");\n const anchor = findFirstDescendant(drawing, \"anchor\");\n const container = anchor ?? inline;\n const blip = findFirstDescendant(drawing, \"blip\");\n if (!container || !blip) {\n continue;\n }\n\n const relationshipId = blip.attributes[\"r:embed\"] ?? blip.attributes.embed;\n if (!relationshipId) {\n continue;\n }\n\n const relationship = relationshipMap.get(relationshipId);\n if (!relationship || !relationship.type.endsWith(\"/image\")) {\n continue;\n }\n\n const packagePartName = normalizePartPath(\n resolveRelationshipTarget(sourcePartPath, relationship),\n );\n const mediaPart = mediaParts.get(packagePartName);\n const docProperties = findFirstDescendant(container, \"docPr\");\n const altText = readAltText(docProperties);\n const floating = anchor ? readFloatingProperties(anchor) : undefined;\n\n media.push({\n type: \"image\",\n mediaId: `media:${packagePartName.slice(1)}`,\n relationshipId,\n packagePartName,\n ...(mediaPart ? { contentType: mediaPart.contentType } : {}),\n filename: packagePartName.slice(packagePartName.lastIndexOf(\"/\") + 1),\n ...(altText ? { altText } : {}),\n ...(anchor ? { display: \"floating\" as const } : {}),\n ...(floating ? { floating } : {}),\n });\n }\n\n return media;\n}\n\nfunction readFloatingProperties(\n node: XmlElementNode,\n): NonNullable<ParsedInlineMedia[\"floating\"]> | undefined {\n const horizontalPosition = findFirstDescendant(node, \"positionH\");\n const verticalPosition = findFirstDescendant(node, \"positionV\");\n const wrap =\n findFirstDescendant(node, \"wrapNone\") ??\n findFirstDescendant(node, \"wrapSquare\") ??\n findFirstDescendant(node, \"wrapTight\") ??\n findFirstDescendant(node, \"wrapThrough\") ??\n findFirstDescendant(node, \"wrapTopAndBottom\");\n\n const properties: NonNullable<ParsedInlineMedia[\"floating\"]> = {};\n const horizontalAxis = readAxisPosition(horizontalPosition);\n const verticalAxis = readAxisPosition(verticalPosition);\n if (horizontalAxis) {\n properties.horizontalPosition = horizontalAxis;\n }\n if (verticalAxis) {\n properties.verticalPosition = verticalAxis;\n }\n if (wrap) {\n const wrapName = localName(wrap.name);\n properties.wrap =\n wrapName === \"wrapSquare\"\n ? \"square\"\n : wrapName === \"wrapTight\"\n ? \"tight\"\n : wrapName === \"wrapThrough\"\n ? \"through\"\n : wrapName === \"wrapTopAndBottom\"\n ? \"topAndBottom\"\n : \"none\";\n }\n\n properties.behindDoc = readBooleanAttribute(node, \"behindDoc\");\n properties.layoutInCell = readBooleanAttribute(node, \"layoutInCell\");\n properties.allowOverlap = readBooleanAttribute(node, \"allowOverlap\");\n\n return Object.values(properties).some((value) => value !== undefined) ? properties : undefined;\n}\n\nfunction readAxisPosition(\n node: XmlElementNode | undefined,\n): NonNullable<NonNullable<ParsedInlineMedia[\"floating\"]>[\"horizontalPosition\"]> | undefined {\n if (!node) {\n return undefined;\n }\n\n const align = findFirstDescendant(node, \"align\");\n const posOffset = findFirstDescendant(node, \"posOffset\");\n const position: NonNullable<NonNullable<ParsedInlineMedia[\"floating\"]>[\"horizontalPosition\"]> = {\n ...(readOptionalAttribute(node, \"relativeFrom\") ? { relativeFrom: readOptionalAttribute(node, \"relativeFrom\") } : {}),\n ...(align && extractText(align).trim() ? { align: extractText(align).trim() } : {}),\n };\n\n if (posOffset) {\n const offset = Number.parseInt(extractText(posOffset).trim(), 10);\n if (Number.isFinite(offset)) {\n position.offset = offset;\n }\n }\n\n return Object.keys(position).length > 0 ? position : undefined;\n}\n\nfunction readAltText(node: XmlElementNode | undefined): string | undefined {\n if (!node) {\n return undefined;\n }\n\n const description = node.attributes.descr?.trim();\n if (description) {\n return description;\n }\n\n const title = node.attributes.title?.trim();\n if (title) {\n return title;\n }\n\n const name = node.attributes.name?.trim();\n return name || undefined;\n}\n\nfunction findFirstDescendant(node: XmlElementNode, local: string): XmlElementNode | undefined {\n for (const child of node.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n if (localName(child.name) === local) {\n return child;\n }\n\n const nested = findFirstDescendant(child, local);\n if (nested) {\n return nested;\n }\n }\n\n return undefined;\n}\n\nfunction findDescendants(node: XmlElementNode, local: string): XmlElementNode[] {\n const results: XmlElementNode[] = [];\n\n for (const child of node.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n if (localName(child.name) === local) {\n results.push(child);\n }\n\n results.push(...findDescendants(child, local));\n }\n\n return results;\n}\n\nfunction localName(name: string): string {\n const separatorIndex = name.indexOf(\":\");\n return separatorIndex >= 0 ? name.slice(separatorIndex + 1) : name;\n}\n\nfunction extractText(node: XmlElementNode): string {\n return node.children.map((child) => child.type === \"text\" ? child.text : extractText(child)).join(\"\");\n}\n\nfunction readOptionalAttribute(node: XmlElementNode, name: string): string | undefined {\n return node.attributes[`wp:${name}`]\n ?? node.attributes[`w:${name}`]\n ?? node.attributes[name];\n}\n\nfunction readBooleanAttribute(node: XmlElementNode, name: string): boolean | undefined {\n const value = readOptionalAttribute(node, name);\n if (value === undefined) {\n return undefined;\n }\n return value !== \"0\" && value !== \"false\" && value !== \"off\";\n}\n\nfunction parseXml(xml: string): XmlElementNode {\n const root: XmlElementNode = {\n type: \"element\",\n name: \"__root__\",\n attributes: {},\n children: [],\n };\n const stack: XmlElementNode[] = [root];\n let cursor = 0;\n\n while (cursor < xml.length) {\n if (xml.startsWith(\"<!--\", cursor)) {\n const end = xml.indexOf(\"-->\", cursor);\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<?\", cursor)) {\n const end = xml.indexOf(\"?>\", cursor);\n cursor = end >= 0 ? end + 2 : xml.length;\n continue;\n }\n\n if (xml[cursor] !== \"<\") {\n const nextTag = xml.indexOf(\"<\", cursor);\n const end = nextTag >= 0 ? nextTag : xml.length;\n const text = decodeXmlEntities(xml.slice(cursor, end));\n if (text.length > 0) {\n stack[stack.length - 1]?.children.push({ type: \"text\", text });\n }\n cursor = end;\n continue;\n }\n\n if (xml[cursor + 1] === \"/\") {\n const end = xml.indexOf(\">\", cursor);\n const current = stack.pop();\n const name = xml.slice(cursor + 2, end).trim();\n if (!current || localName(current.name) !== localName(name)) {\n throw new Error(`Malformed XML: unexpected closing tag </${name}>.`);\n }\n cursor = end + 1;\n continue;\n }\n\n const tagEnd = findTagEnd(xml, cursor);\n const tagBody = xml.slice(cursor + 1, tagEnd);\n const selfClosing = /\\/\\s*$/.test(tagBody);\n const { name, attributes } = parseTag(tagBody.replace(/\\/\\s*$/, \"\").trim());\n const element: XmlElementNode = {\n type: \"element\",\n name,\n attributes,\n children: [],\n };\n stack[stack.length - 1]?.children.push(element);\n\n if (!selfClosing) {\n stack.push(element);\n }\n\n cursor = tagEnd + 1;\n }\n\n if (stack.length !== 1) {\n throw new Error(\"Malformed XML: unclosed element.\");\n }\n\n return root;\n}\n\nfunction parseTag(tagBody: string): { name: string; attributes: Record<string, string> } {\n let cursor = 0;\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n\n const nameStart = cursor;\n while (cursor < tagBody.length && !/\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n const name = tagBody.slice(nameStart, cursor);\n const attributes: Record<string, string> = {};\n\n while (cursor < tagBody.length) {\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n if (cursor >= tagBody.length) {\n break;\n }\n\n const keyStart = cursor;\n while (cursor < tagBody.length && !/[\\s=]/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n const key = tagBody.slice(keyStart, cursor);\n\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n\n if (tagBody[cursor] !== \"=\") {\n attributes[key] = \"\";\n continue;\n }\n cursor += 1;\n\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n\n const quote = tagBody[cursor];\n if (quote !== `\"` && quote !== `'`) {\n throw new Error(`Malformed XML attribute ${key}.`);\n }\n cursor += 1;\n\n const valueStart = cursor;\n while (cursor < tagBody.length && tagBody[cursor] !== quote) {\n cursor += 1;\n }\n attributes[key] = decodeXmlEntities(tagBody.slice(valueStart, cursor));\n cursor += 1;\n }\n\n return { name, attributes };\n}\n\nfunction findTagEnd(xml: string, start: number): number {\n let cursor = start + 1;\n let quote: string | null = null;\n\n while (cursor < xml.length) {\n const current = xml[cursor];\n if (quote) {\n if (current === quote) {\n quote = null;\n }\n cursor += 1;\n continue;\n }\n\n if (current === `\"` || current === `'`) {\n quote = current;\n cursor += 1;\n continue;\n }\n\n if (current === \">\") {\n return cursor;\n }\n\n cursor += 1;\n }\n\n throw new Error(\"Malformed XML: missing >.\");\n}\n\nfunction decodeXmlEntities(value: string): string {\n return value.replace(/&(#x[0-9a-fA-F]+|#\\d+|amp|lt|gt|quot|apos);/g, (match, entity) => {\n switch (entity) {\n case \"amp\":\n return \"&\";\n case \"lt\":\n return \"<\";\n case \"gt\":\n return \">\";\n case \"quot\":\n return `\"`;\n case \"apos\":\n return \"'\";\n default:\n if (entity.startsWith(\"#x\")) {\n return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));\n }\n if (entity.startsWith(\"#\")) {\n return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));\n }\n return match;\n }\n });\n}\n","import type { NumberingCatalog, NumberingLevelDefinition, NumberingLevelOverride } from \"../../model/canonical-document.ts\";\n\nexport interface ParsedParagraphNumberingReference {\n paragraphIndex: number;\n numberingInstanceId: string;\n level: number;\n}\n\ninterface XmlElementNode {\n type: \"element\";\n name: string;\n attributes: Record<string, string>;\n children: XmlNode[];\n}\n\ninterface XmlTextNode {\n type: \"text\";\n text: string;\n}\n\ntype XmlNode = XmlElementNode | XmlTextNode;\n\nexport function parseNumberingXml(xml: string): NumberingCatalog {\n const root = parseXml(xml);\n const numberingElement = findChildElement(root, \"numbering\");\n const abstractDefinitions: NumberingCatalog[\"abstractDefinitions\"] = {};\n const instances: NumberingCatalog[\"instances\"] = {};\n\n for (const child of numberingElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n switch (localName(child.name)) {\n case \"abstractNum\": {\n const rawId = child.attributes[\"w:abstractNumId\"] ?? child.attributes.abstractNumId;\n if (!rawId) {\n continue;\n }\n\n const abstractNumberingId = toCanonicalAbstractNumberingId(rawId);\n abstractDefinitions[abstractNumberingId] = {\n abstractNumberingId,\n levels: readLevels(child),\n };\n break;\n }\n case \"num\": {\n const rawId = child.attributes[\"w:numId\"] ?? child.attributes.numId;\n const abstractReference = findChildElementOptional(child, \"abstractNumId\");\n const rawAbstractId =\n abstractReference?.attributes[\"w:val\"] ?? abstractReference?.attributes.val;\n\n if (!rawId || !rawAbstractId) {\n continue;\n }\n\n const numberingInstanceId = toCanonicalNumberingInstanceId(rawId);\n instances[numberingInstanceId] = {\n numberingInstanceId,\n abstractNumberingId: toCanonicalAbstractNumberingId(rawAbstractId),\n overrides: readOverrides(child),\n };\n break;\n }\n }\n }\n\n return {\n abstractDefinitions,\n instances,\n };\n}\n\nexport function parseParagraphNumberingReferences(\n documentXml: string,\n): ParsedParagraphNumberingReference[] {\n const root = parseXml(documentXml);\n const documentElement = findChildElement(root, \"document\");\n const bodyElement = findChildElement(documentElement, \"body\");\n const references: ParsedParagraphNumberingReference[] = [];\n let paragraphIndex = 0;\n\n for (const child of bodyElement.children) {\n if (child.type !== \"element\" || localName(child.name) !== \"p\") {\n continue;\n }\n\n const paragraphProperties = findChildElementOptional(child, \"pPr\");\n const numberingProperties = paragraphProperties\n ? findChildElementOptional(paragraphProperties, \"numPr\")\n : undefined;\n\n if (numberingProperties) {\n const levelNode = findChildElementOptional(numberingProperties, \"ilvl\");\n const instanceNode = findChildElementOptional(numberingProperties, \"numId\");\n const rawLevel = levelNode?.attributes[\"w:val\"] ?? levelNode?.attributes.val;\n const rawInstanceId = instanceNode?.attributes[\"w:val\"] ?? instanceNode?.attributes.val;\n\n if (rawLevel !== undefined && rawInstanceId) {\n const level = parseInteger(rawLevel);\n if (level !== undefined) {\n references.push({\n paragraphIndex,\n numberingInstanceId: toCanonicalNumberingInstanceId(rawInstanceId),\n level,\n });\n }\n }\n }\n\n paragraphIndex += 1;\n }\n\n return references;\n}\n\nexport function toCanonicalAbstractNumberingId(value: string): string {\n return value.startsWith(\"abstract-num:\") ? value : `abstract-num:${value}`;\n}\n\nexport function toCanonicalNumberingInstanceId(value: string): string {\n return value.startsWith(\"num:\") ? value : `num:${value}`;\n}\n\nfunction readLevels(abstractNode: XmlElementNode): NumberingLevelDefinition[] {\n const levels: NumberingLevelDefinition[] = [];\n\n for (const child of abstractNode.children) {\n if (child.type !== \"element\" || localName(child.name) !== \"lvl\") {\n continue;\n }\n\n const rawLevel = child.attributes[\"w:ilvl\"] ?? child.attributes.ilvl;\n const level = rawLevel === undefined ? undefined : parseInteger(rawLevel);\n if (level === undefined) {\n continue;\n }\n\n const startNode = findChildElementOptional(child, \"start\");\n const formatNode = findChildElementOptional(child, \"numFmt\");\n const textNode = findChildElementOptional(child, \"lvlText\");\n const paragraphStyleNode = findChildElementOptional(child, \"pStyle\");\n const rawStart = startNode?.attributes[\"w:val\"] ?? startNode?.attributes.val;\n const startAt = rawStart === undefined ? undefined : parseInteger(rawStart);\n const format = formatNode?.attributes[\"w:val\"] ?? formatNode?.attributes.val ?? \"decimal\";\n const text = textNode?.attributes[\"w:val\"] ?? textNode?.attributes.val ?? `%${level + 1}.`;\n const paragraphStyleId =\n paragraphStyleNode?.attributes[\"w:val\"] ?? paragraphStyleNode?.attributes.val;\n\n levels.push({\n level,\n format,\n text,\n ...(startAt !== undefined ? { startAt } : {}),\n ...(paragraphStyleId ? { paragraphStyleId } : {}),\n });\n }\n\n return levels.sort((left, right) => left.level - right.level);\n}\n\nfunction readOverrides(numNode: XmlElementNode): NumberingLevelOverride[] {\n const overrides: NumberingLevelOverride[] = [];\n\n for (const child of numNode.children) {\n if (child.type !== \"element\" || localName(child.name) !== \"lvlOverride\") {\n continue;\n }\n\n const rawLevel = child.attributes[\"w:ilvl\"] ?? child.attributes.ilvl;\n const level = rawLevel === undefined ? undefined : parseInteger(rawLevel);\n if (level === undefined) {\n continue;\n }\n\n const startOverrideNode = findChildElementOptional(child, \"startOverride\");\n const rawStart = startOverrideNode?.attributes[\"w:val\"] ?? startOverrideNode?.attributes.val;\n const startAt = rawStart === undefined ? undefined : parseInteger(rawStart);\n\n overrides.push({\n level,\n ...(startAt !== undefined ? { startAt } : {}),\n });\n }\n\n return overrides.sort((left, right) => left.level - right.level);\n}\n\nfunction findChildElement(node: XmlElementNode, childLocalName: string): XmlElementNode {\n const child = findChildElementOptional(node, childLocalName);\n if (!child) {\n throw new Error(`Expected <${childLocalName}> element in numbering XML.`);\n }\n\n return child;\n}\n\nfunction findChildElementOptional(\n node: XmlElementNode,\n childLocalName: string,\n): XmlElementNode | undefined {\n return node.children.find(\n (entry): entry is XmlElementNode =>\n entry.type === \"element\" && localName(entry.name) === childLocalName,\n );\n}\n\nfunction localName(name: string): string {\n const separatorIndex = name.indexOf(\":\");\n return separatorIndex >= 0 ? name.slice(separatorIndex + 1) : name;\n}\n\nfunction parseInteger(value: string): number | undefined {\n if (!/^-?\\d+$/.test(value)) {\n return undefined;\n }\n\n return Number.parseInt(value, 10);\n}\n\nfunction parseXml(xml: string): XmlElementNode {\n const root: XmlElementNode = {\n type: \"element\",\n name: \"__root__\",\n attributes: {},\n children: [],\n };\n const stack: XmlElementNode[] = [root];\n let cursor = 0;\n\n while (cursor < xml.length) {\n if (xml.startsWith(\"<!--\", cursor)) {\n const end = xml.indexOf(\"-->\", cursor);\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<?\", cursor)) {\n const end = xml.indexOf(\"?>\", cursor);\n cursor = end >= 0 ? end + 2 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<![CDATA[\", cursor)) {\n const end = xml.indexOf(\"]]>\", cursor);\n const textEnd = end >= 0 ? end : xml.length;\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text: xml.slice(cursor + 9, textEnd),\n });\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml[cursor] !== \"<\") {\n const nextTag = xml.indexOf(\"<\", cursor);\n const end = nextTag >= 0 ? nextTag : xml.length;\n const text = decodeXmlEntities(xml.slice(cursor, end));\n if (text.length > 0) {\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text,\n });\n }\n cursor = end;\n continue;\n }\n\n if (xml[cursor + 1] === \"/\") {\n const end = xml.indexOf(\">\", cursor);\n if (end < 0) {\n throw new Error(\"Malformed XML: missing closing >.\");\n }\n\n const name = xml.slice(cursor + 2, end).trim();\n const current = stack.pop();\n if (!current || localName(current.name) !== localName(name)) {\n throw new Error(`Malformed XML: unexpected closing tag </${name}>.`);\n }\n\n cursor = end + 1;\n continue;\n }\n\n const tagEnd = findTagEnd(xml, cursor);\n const tagBody = xml.slice(cursor + 1, tagEnd);\n const selfClosing = /\\/\\s*$/.test(tagBody);\n const { name, attributes } = parseTag(tagBody.replace(/\\/\\s*$/, \"\").trim());\n const element: XmlElementNode = {\n type: \"element\",\n name,\n attributes,\n children: [],\n };\n stack[stack.length - 1]?.children.push(element);\n\n if (!selfClosing) {\n stack.push(element);\n }\n\n cursor = tagEnd + 1;\n }\n\n if (stack.length !== 1) {\n throw new Error(\"Malformed XML: unclosed element.\");\n }\n\n return root;\n}\n\nfunction parseTag(tagBody: string): { name: string; attributes: Record<string, string> } {\n let cursor = 0;\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n\n const nameStart = cursor;\n while (cursor < tagBody.length && !/\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n\n const name = tagBody.slice(nameStart, cursor);\n const attributes: Record<string, string> = {};\n\n while (cursor < tagBody.length) {\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n if (cursor >= tagBody.length) {\n break;\n }\n\n const keyStart = cursor;\n while (cursor < tagBody.length && !/[\\s=]/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n const key = tagBody.slice(keyStart, cursor);\n\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n\n if (tagBody[cursor] !== \"=\") {\n attributes[key] = \"\";\n continue;\n }\n cursor += 1;\n\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n\n const quote = tagBody[cursor];\n if (quote !== `\"` && quote !== `'`) {\n throw new Error(`Malformed XML attribute ${key}.`);\n }\n cursor += 1;\n\n const valueStart = cursor;\n while (cursor < tagBody.length && tagBody[cursor] !== quote) {\n cursor += 1;\n }\n const rawValue = tagBody.slice(valueStart, cursor);\n attributes[key] = decodeXmlEntities(rawValue);\n cursor += 1;\n }\n\n return { name, attributes };\n}\n\nfunction findTagEnd(xml: string, start: number): number {\n let cursor = start + 1;\n let quote: string | null = null;\n\n while (cursor < xml.length) {\n const current = xml[cursor];\n if (quote) {\n if (current === quote) {\n quote = null;\n }\n cursor += 1;\n continue;\n }\n\n if (current === `\"` || current === `'`) {\n quote = current;\n cursor += 1;\n continue;\n }\n\n if (current === \">\") {\n return cursor;\n }\n\n cursor += 1;\n }\n\n throw new Error(\"Malformed XML: missing >.\");\n}\n\nfunction decodeXmlEntities(value: string): string {\n return value.replace(/&(#x[0-9a-fA-F]+|#\\d+|amp|lt|gt|quot|apos);/g, (match, entity) => {\n switch (entity) {\n case \"amp\":\n return \"&\";\n case \"lt\":\n return \"<\";\n case \"gt\":\n return \">\";\n case \"quot\":\n return `\"`;\n case \"apos\":\n return \"'\";\n default:\n if (entity.startsWith(\"#x\")) {\n return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));\n }\n if (entity.startsWith(\"#\")) {\n return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));\n }\n return match;\n }\n });\n}\n","import type {\n TextMark,\n ParagraphBorders,\n ParagraphShading,\n ParagraphSpacing,\n ParagraphIndentation,\n TabStop,\n TableLook,\n} from \"../../model/canonical-document.ts\";\nimport type { OpcRelationship } from \"./part-manifest.ts\";\nimport {\n parseInlineMediaXml,\n type InlineMediaPart,\n} from \"./parse-inline-media.ts\";\nimport { toCanonicalNumberingInstanceId } from \"./parse-numbering.ts\";\n\nexport interface ParsedMainDocument {\n blocks: ParsedBlockNode[];\n}\n\nexport type ParsedBlockNode =\n | ParsedParagraphNode\n | ParsedTableBlockNode\n | ParsedSdtNode\n | ParsedCustomXmlNode\n | ParsedAltChunkNode\n | ParsedOpaqueBlockNode;\n\nexport interface ParsedParagraphNode {\n type: \"paragraph\";\n styleId?: string;\n numbering?: {\n numberingInstanceId: string;\n level: number;\n };\n alignment?: \"left\" | \"center\" | \"right\" | \"both\" | \"distribute\";\n spacing?: ParagraphSpacing;\n indentation?: ParagraphIndentation;\n tabStops?: TabStop[];\n keepNext?: boolean;\n keepLines?: boolean;\n outlineLevel?: number;\n pageBreakBefore?: boolean;\n widowControl?: boolean;\n borders?: ParagraphBorders;\n shading?: ParagraphShading;\n bidi?: boolean;\n suppressLineNumbers?: boolean;\n cnfStyle?: string;\n children: ParsedInlineNode[];\n rawXml: string;\n}\n\nexport type ParsedInlineNode =\n | ParsedTextNode\n | ParsedBreakNode\n | ParsedColumnBreakNode\n | ParsedTabNode\n | ParsedSymbolNode\n | ParsedImageNode\n | ParsedHyperlinkNode\n | ParsedOpaqueInlineNode;\n\nexport interface ParsedTextNode {\n type: \"text\";\n text: string;\n marks?: TextMark[];\n}\n\nexport interface ParsedBreakNode {\n type: \"hard_break\";\n}\n\nexport interface ParsedColumnBreakNode {\n type: \"column_break\";\n}\n\nexport interface ParsedTabNode {\n type: \"tab\";\n}\n\nexport interface ParsedSymbolNode {\n type: \"symbol\";\n char: string;\n font?: string;\n marks?: TextMark[];\n}\n\nexport interface ParsedImageNode {\n type: \"image\";\n mediaId: string;\n relationshipId?: string;\n packagePartName?: string;\n contentType?: string;\n filename?: string;\n altText?: string;\n placementXml?: string;\n display?: \"inline\" | \"floating\";\n floating?: {\n horizontalPosition?: {\n relativeFrom?: string;\n align?: string;\n offset?: number;\n };\n verticalPosition?: {\n relativeFrom?: string;\n align?: string;\n offset?: number;\n };\n wrap?: \"none\" | \"square\" | \"tight\" | \"through\" | \"topAndBottom\";\n behindDoc?: boolean;\n layoutInCell?: boolean;\n allowOverlap?: boolean;\n };\n}\n\nexport interface ParsedHyperlinkNode {\n type: \"hyperlink\";\n href: string;\n children: Array<ParsedTextNode | ParsedBreakNode | ParsedColumnBreakNode | ParsedTabNode | ParsedSymbolNode>;\n rawXml: string;\n}\n\nexport interface ParsedOpaqueInlineNode {\n type: \"opaque_inline\";\n rawXml: string;\n}\n\nexport interface ParsedOpaqueBlockNode {\n type: \"opaque_block\";\n rawXml: string;\n}\n\nexport interface ParsedSdtNode {\n type: \"sdt\";\n properties: {\n sdtType?: string;\n alias?: string;\n tag?: string;\n lock?: string;\n propertiesXml?: string;\n };\n children: ParsedBlockNode[];\n rawXml: string;\n}\n\nexport interface ParsedCustomXmlNode {\n type: \"custom_xml\";\n uri?: string;\n element?: string;\n children: ParsedBlockNode[];\n rawXml: string;\n}\n\nexport interface ParsedAltChunkNode {\n type: \"alt_chunk\";\n relationshipId: string;\n rawXml: string;\n}\n\nexport interface ParsedTableBlockNode {\n type: \"table\";\n styleId?: string;\n tblLook?: TableLook;\n propertiesXml?: string;\n gridColumns: number[];\n rows: ParsedTableRowNode[];\n rawXml: string;\n}\n\nexport interface ParsedTableRowNode {\n type: \"table_row\";\n propertiesXml?: string;\n cells: ParsedTableCellNode[];\n rawXml: string;\n}\n\nexport interface ParsedTableCellNode {\n type: \"table_cell\";\n propertiesXml?: string;\n gridSpan?: number;\n verticalMerge?: \"restart\" | \"continue\";\n children: ParsedBlockNode[];\n rawXml: string;\n}\n\ninterface XmlElementNode {\n type: \"element\";\n name: string;\n attributes: Record<string, string>;\n children: XmlNode[];\n start: number;\n end: number;\n}\n\ninterface XmlTextNode {\n type: \"text\";\n text: string;\n start: number;\n end: number;\n}\n\ntype XmlNode = XmlElementNode | XmlTextNode;\n\ninterface RunParseResult {\n nodes: Array<ParsedTextNode | ParsedBreakNode | ParsedColumnBreakNode | ParsedTabNode | ParsedSymbolNode>;\n supported: boolean;\n}\n\ninterface MarksParseResult {\n marks: TextMark[];\n supported: boolean;\n}\n\nconst HYPERLINK_RELATIONSHIP_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\";\n\nexport function parseMainDocumentXml(\n xml: string,\n relationships: readonly OpcRelationship[] = [],\n mediaParts: ReadonlyMap<string, InlineMediaPart> = new Map(),\n sourcePartPath = \"/word/document.xml\",\n): ParsedMainDocument {\n const root = parseXml(xml);\n const documentElement = findChildElement(root, \"document\");\n const bodyElement = findChildElement(documentElement, \"body\");\n const relationshipMap = new Map(relationships.map((relationship) => [relationship.id, relationship]));\n\n return {\n blocks: bodyElement.children\n .filter((node): node is XmlElementNode => node.type === \"element\")\n .map((node) => parseBodyChild(node, xml, relationshipMap, relationships, mediaParts, sourcePartPath)),\n };\n}\n\nfunction parseBodyChild(\n node: XmlElementNode,\n sourceXml: string,\n relationshipMap: Map<string, OpcRelationship>,\n relationships: readonly OpcRelationship[],\n mediaParts: ReadonlyMap<string, InlineMediaPart>,\n sourcePartPath: string,\n): ParsedBlockNode {\n const nodeType = localName(node.name);\n\n if (nodeType === \"tbl\") {\n // Tables with revision markup (tracked changes inside cells) stay opaque\n // to preserve fidelity until revision-aware table editing is implemented\n const rawTableXml = sourceXml.slice(node.start, node.end);\n if (tableRequiresOpaquePreservation(rawTableXml)) {\n return {\n type: \"opaque_block\",\n rawXml: rawTableXml,\n };\n }\n try {\n return parseTableElement(node, sourceXml, relationshipMap, relationships, mediaParts, sourcePartPath);\n } catch {\n // If table parsing fails for any reason, fall back to opaque preservation\n return {\n type: \"opaque_block\",\n rawXml: rawTableXml,\n };\n }\n }\n\n if (nodeType === \"sdt\") {\n return parseSdtElement(node, sourceXml, relationshipMap, relationships, mediaParts, sourcePartPath);\n }\n\n if (nodeType === \"customXml\") {\n return parseCustomXmlElement(node, sourceXml, relationshipMap, relationships, mediaParts, sourcePartPath);\n }\n\n if (nodeType === \"altChunk\") {\n return parseAltChunkElement(node, sourceXml);\n }\n\n if (nodeType !== \"p\") {\n return {\n type: \"opaque_block\",\n rawXml: sourceXml.slice(node.start, node.end),\n };\n }\n\n let styleId: string | undefined;\n let numbering: ParsedParagraphNode[\"numbering\"];\n let alignment: ParsedParagraphNode[\"alignment\"];\n let spacing: ParsedParagraphNode[\"spacing\"];\n let indentation: ParsedParagraphNode[\"indentation\"];\n let tabStops: ParsedParagraphNode[\"tabStops\"];\n let keepNext: ParsedParagraphNode[\"keepNext\"];\n let keepLines: ParsedParagraphNode[\"keepLines\"];\n let outlineLevel: ParsedParagraphNode[\"outlineLevel\"];\n let pageBreakBefore: ParsedParagraphNode[\"pageBreakBefore\"];\n let widowControl: ParsedParagraphNode[\"widowControl\"];\n let borders: ParsedParagraphNode[\"borders\"];\n let shading: ParsedParagraphNode[\"shading\"];\n let bidi: ParsedParagraphNode[\"bidi\"];\n let suppressLineNumbers: ParsedParagraphNode[\"suppressLineNumbers\"];\n let cnfStyle: ParsedParagraphNode[\"cnfStyle\"];\n let paragraphSupported = true;\n const children: ParsedInlineNode[] = [];\n\n for (const child of node.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n switch (localName(child.name)) {\n case \"pPr\":\n styleId = readParagraphStyleId(child);\n numbering = readParagraphNumbering(child);\n alignment = readParagraphAlignment(child);\n spacing = readParagraphSpacing(child);\n indentation = readParagraphIndentation(child);\n tabStops = readParagraphTabStops(child);\n keepNext = readOnOffParagraphProperty(child, \"keepNext\");\n keepLines = readOnOffParagraphProperty(child, \"keepLines\");\n outlineLevel = readParagraphOutlineLevel(child);\n pageBreakBefore = readOnOffParagraphProperty(child, \"pageBreakBefore\");\n widowControl = readOnOffParagraphProperty(child, \"widowControl\");\n borders = readParagraphBorders(child);\n shading = readParagraphShading(child);\n bidi = readOnOffParagraphProperty(child, \"bidi\");\n suppressLineNumbers = readOnOffParagraphProperty(child, \"suppressLineNumbers\");\n cnfStyle = readParagraphCnfStyle(child);\n paragraphSupported = paragraphSupported && supportsParagraphProperties(child);\n break;\n case \"r\":\n children.push(...parseRun(child, sourceXml, relationships, mediaParts, sourcePartPath));\n break;\n case \"hyperlink\": {\n const hyperlink = parseHyperlink(child, sourceXml, relationshipMap);\n children.push(hyperlink);\n break;\n }\n case \"ins\":\n case \"del\": {\n children.push(...parseRevisionContainer(child, sourceXml, relationshipMap));\n break;\n }\n case \"commentRangeStart\":\n case \"commentRangeEnd\":\n break;\n case \"bookmarkStart\":\n case \"bookmarkEnd\":\n case \"permStart\":\n case \"permEnd\":\n case \"proofErr\":\n children.push({\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(child.start, child.end),\n });\n break;\n default:\n children.push({\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(child.start, child.end),\n });\n break;\n }\n }\n\n if (!paragraphSupported) {\n return {\n type: \"opaque_block\",\n rawXml: sourceXml.slice(node.start, node.end),\n };\n }\n\n return {\n type: \"paragraph\",\n styleId,\n ...(numbering ? { numbering } : {}),\n ...(alignment ? { alignment } : {}),\n ...(spacing ? { spacing } : {}),\n ...(indentation ? { indentation } : {}),\n ...(tabStops && tabStops.length > 0 ? { tabStops } : {}),\n ...(keepNext ? { keepNext } : {}),\n ...(keepLines ? { keepLines } : {}),\n ...(outlineLevel !== undefined ? { outlineLevel } : {}),\n ...(pageBreakBefore ? { pageBreakBefore } : {}),\n ...(widowControl ? { widowControl } : {}),\n ...(borders ? { borders } : {}),\n ...(shading ? { shading } : {}),\n ...(bidi ? { bidi } : {}),\n ...(suppressLineNumbers ? { suppressLineNumbers } : {}),\n ...(cnfStyle ? { cnfStyle } : {}),\n children,\n rawXml: sourceXml.slice(node.start, node.end),\n };\n}\n\nfunction parseTableElement(\n node: XmlElementNode,\n sourceXml: string,\n relationshipMap: Map<string, OpcRelationship>,\n relationships: readonly OpcRelationship[],\n mediaParts: ReadonlyMap<string, InlineMediaPart>,\n sourcePartPath: string,\n): ParsedTableBlockNode {\n let styleId: string | undefined;\n let tblLook: TableLook | undefined;\n let propertiesXml: string | undefined;\n let gridColumns: number[] = [];\n const rows: ParsedTableRowNode[] = [];\n\n for (const child of node.children) {\n if (child.type !== \"element\") continue;\n\n switch (localName(child.name)) {\n case \"tblPr\": {\n propertiesXml = sourceXml.slice(child.start, child.end);\n styleId = readTableStyleId(child);\n tblLook = readTableLook(child);\n break;\n }\n case \"tblGrid\": {\n gridColumns = readTableGridColumns(child);\n break;\n }\n case \"tr\": {\n rows.push(parseTableRowElement(child, sourceXml, relationshipMap, relationships, mediaParts, sourcePartPath));\n break;\n }\n }\n }\n\n return {\n type: \"table\",\n ...(styleId ? { styleId } : {}),\n ...(tblLook ? { tblLook } : {}),\n ...(propertiesXml ? { propertiesXml } : {}),\n gridColumns,\n rows,\n rawXml: sourceXml.slice(node.start, node.end),\n };\n}\n\nfunction parseTableRowElement(\n node: XmlElementNode,\n sourceXml: string,\n relationshipMap: Map<string, OpcRelationship>,\n relationships: readonly OpcRelationship[],\n mediaParts: ReadonlyMap<string, InlineMediaPart>,\n sourcePartPath: string,\n): ParsedTableRowNode {\n let propertiesXml: string | undefined;\n const cells: ParsedTableCellNode[] = [];\n\n for (const child of node.children) {\n if (child.type !== \"element\") continue;\n\n switch (localName(child.name)) {\n case \"trPr\":\n propertiesXml = sourceXml.slice(child.start, child.end);\n break;\n case \"tc\":\n cells.push(parseTableCellElement(child, sourceXml, relationshipMap, relationships, mediaParts, sourcePartPath));\n break;\n }\n }\n\n return {\n type: \"table_row\",\n ...(propertiesXml ? { propertiesXml } : {}),\n cells,\n rawXml: sourceXml.slice(node.start, node.end),\n };\n}\n\nfunction parseTableCellElement(\n node: XmlElementNode,\n sourceXml: string,\n relationshipMap: Map<string, OpcRelationship>,\n relationships: readonly OpcRelationship[],\n mediaParts: ReadonlyMap<string, InlineMediaPart>,\n sourcePartPath: string,\n): ParsedTableCellNode {\n let propertiesXml: string | undefined;\n let gridSpan: number | undefined;\n let verticalMerge: \"restart\" | \"continue\" | undefined;\n const children: ParsedBlockNode[] = [];\n\n for (const child of node.children) {\n if (child.type !== \"element\") continue;\n\n switch (localName(child.name)) {\n case \"tcPr\": {\n propertiesXml = sourceXml.slice(child.start, child.end);\n gridSpan = readCellGridSpan(child);\n verticalMerge = readCellVerticalMerge(child);\n break;\n }\n default: {\n // Everything else in a cell is a block child (paragraphs, nested tables, etc.)\n children.push(parseBodyChild(child, sourceXml, relationshipMap, relationships, mediaParts, sourcePartPath));\n break;\n }\n }\n }\n\n return {\n type: \"table_cell\",\n ...(propertiesXml ? { propertiesXml } : {}),\n ...(gridSpan ? { gridSpan } : {}),\n ...(verticalMerge ? { verticalMerge } : {}),\n children,\n rawXml: sourceXml.slice(node.start, node.end),\n };\n}\n\nfunction parseSdtElement(\n node: XmlElementNode,\n sourceXml: string,\n relationshipMap: Map<string, OpcRelationship>,\n relationships: readonly OpcRelationship[],\n mediaParts: ReadonlyMap<string, InlineMediaPart>,\n sourcePartPath: string,\n): ParsedBlockNode {\n const propertiesNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"sdtPr\",\n );\n const contentNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"sdtContent\",\n );\n\n if (!contentNode) {\n return {\n type: \"opaque_block\",\n rawXml: sourceXml.slice(node.start, node.end),\n };\n }\n\n const children = contentNode.children\n .filter((child): child is XmlElementNode => child.type === \"element\")\n .map((child) => parseBodyChild(child, sourceXml, relationshipMap, relationships, mediaParts, sourcePartPath));\n\n return {\n type: \"sdt\",\n properties: readSdtProperties(propertiesNode, sourceXml),\n children,\n rawXml: sourceXml.slice(node.start, node.end),\n };\n}\n\nfunction parseCustomXmlElement(\n node: XmlElementNode,\n sourceXml: string,\n relationshipMap: Map<string, OpcRelationship>,\n relationships: readonly OpcRelationship[],\n mediaParts: ReadonlyMap<string, InlineMediaPart>,\n sourcePartPath: string,\n): ParsedBlockNode {\n const uri = readOptionalAttribute(node, \"uri\");\n const element = readOptionalAttribute(node, \"element\");\n if (!uri && !element) {\n return {\n type: \"opaque_block\",\n rawXml: sourceXml.slice(node.start, node.end),\n };\n }\n\n const children = node.children\n .filter(\n (child): child is XmlElementNode =>\n child.type === \"element\" && localName(child.name) !== \"customXmlPr\",\n )\n .map((child) => parseBodyChild(child, sourceXml, relationshipMap, relationships, mediaParts, sourcePartPath));\n\n return {\n type: \"custom_xml\",\n ...(uri ? { uri } : {}),\n ...(element ? { element } : {}),\n children,\n rawXml: sourceXml.slice(node.start, node.end),\n };\n}\n\nfunction parseAltChunkElement(\n node: XmlElementNode,\n sourceXml: string,\n): ParsedBlockNode {\n const relationshipId = readOptionalAttribute(node, \"id\");\n if (!relationshipId) {\n return {\n type: \"opaque_block\",\n rawXml: sourceXml.slice(node.start, node.end),\n };\n }\n\n return {\n type: \"alt_chunk\",\n relationshipId,\n rawXml: sourceXml.slice(node.start, node.end),\n };\n}\n\nfunction readSdtProperties(\n node: XmlElementNode | undefined,\n sourceXml: string,\n): ParsedSdtNode[\"properties\"] {\n if (!node) {\n return {};\n }\n\n const properties: ParsedSdtNode[\"properties\"] = {\n propertiesXml: sourceXml.slice(node.start, node.end),\n };\n\n for (const child of node.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n if (name === \"alias\") {\n properties.alias = readOptionalAttribute(child, \"val\");\n continue;\n }\n if (name === \"tag\") {\n properties.tag = readOptionalAttribute(child, \"val\");\n continue;\n }\n if (name === \"lock\") {\n properties.lock = readOptionalAttribute(child, \"val\");\n continue;\n }\n if (!properties.sdtType && name !== \"id\" && name !== \"placeholder\" && name !== \"showingPlcHdr\") {\n properties.sdtType = name;\n }\n }\n\n return properties;\n}\n\nfunction readTableStyleId(node: XmlElementNode): string | undefined {\n for (const child of node.children) {\n if (child.type !== \"element\" || localName(child.name) !== \"tblStyle\") continue;\n const styleId = child.attributes[\"w:val\"] ?? child.attributes.val;\n if (styleId) return styleId;\n }\n return undefined;\n}\n\nfunction readTableLook(node: XmlElementNode): TableLook | undefined {\n const tblLookNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"tblLook\",\n );\n if (!tblLookNode) {\n return undefined;\n }\n\n const tableLook: TableLook = {};\n const val = tblLookNode.attributes[\"w:val\"] ?? tblLookNode.attributes.val;\n if (val) {\n tableLook.val = val;\n }\n for (const [attribute, key] of [\n [\"w:firstRow\", \"firstRow\"],\n [\"w:lastRow\", \"lastRow\"],\n [\"w:firstColumn\", \"firstColumn\"],\n [\"w:lastColumn\", \"lastColumn\"],\n [\"w:noHBand\", \"noHBand\"],\n [\"w:noVBand\", \"noVBand\"],\n ] as const) {\n const fallback = attribute.replace(\"w:\", \"\");\n const raw = tblLookNode.attributes[attribute] ?? tblLookNode.attributes[fallback];\n if (raw !== undefined) {\n tableLook[key] = raw !== \"0\" && raw !== \"false\" && raw !== \"off\";\n }\n }\n\n return Object.keys(tableLook).length > 0 ? tableLook : undefined;\n}\n\nfunction readTableGridColumns(node: XmlElementNode): number[] {\n return node.children\n .filter((child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"gridCol\")\n .map((child) => {\n const raw = child.attributes[\"w:w\"] ?? child.attributes.w ?? \"0\";\n const value = Number.parseInt(raw, 10);\n return Number.isFinite(value) && value > 0 ? value : 0;\n });\n}\n\n/**\n * Check if a table's raw XML contains content that cannot safely round-trip\n * through the parsed table path yet. This includes:\n * - Revision markup (tracked changes inside cells)\n * - Hyperlink relationships (original relationship IDs would be lost)\n * - Comment ranges, bookmarks, and other annotation markup\n *\n * Tables matching this check stay opaque until the respective features\n * are implemented in the table editing path.\n */\nfunction tableRequiresOpaquePreservation(rawXml: string): boolean {\n // For now, only parse tables that contain exclusively simple content\n // (plain text, basic formatting). Any complex OOXML stays opaque.\n // This list will shrink as the table editing path gains feature coverage.\n return /<w:(ins|del|rPrChange|pPrChange|tblPrChange|trPrChange|tcPrChange|sectPrChange|cellIns|cellDel|cellMerge|hyperlink|commentRangeStart|commentRangeEnd|commentReference|bookmarkStart|bookmarkEnd|rStyle|pict|fldChar|fldSimple|smartTag|gridAfter|gridBefore|hideMark|tblHeader|tblCellSpacing|bCs)\\b/.test(rawXml);\n}\n\nfunction readCellGridSpan(node: XmlElementNode): number | undefined {\n const gridSpanNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"gridSpan\",\n );\n if (!gridSpanNode) return undefined;\n const raw = gridSpanNode.attributes[\"w:val\"] ?? gridSpanNode.attributes.val;\n const value = Number.parseInt(raw ?? \"0\", 10);\n return Number.isFinite(value) && value > 1 ? value : undefined;\n}\n\nfunction readCellVerticalMerge(node: XmlElementNode): \"restart\" | \"continue\" | undefined {\n const vMergeNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"vMerge\",\n );\n if (!vMergeNode) return undefined;\n const raw = (vMergeNode.attributes[\"w:val\"] ?? vMergeNode.attributes.val ?? \"continue\").toLowerCase();\n return raw === \"restart\" ? \"restart\" : \"continue\";\n}\n\nfunction readParagraphAlignment(node: XmlElementNode): ParsedParagraphNode[\"alignment\"] {\n const jcNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"jc\",\n );\n if (!jcNode) return undefined;\n const val = (jcNode.attributes[\"w:val\"] ?? jcNode.attributes.val ?? \"\").toLowerCase();\n if (val === \"left\" || val === \"center\" || val === \"right\" || val === \"both\" || val === \"distribute\") {\n return val;\n }\n return undefined;\n}\n\nfunction readParagraphSpacing(node: XmlElementNode): ParagraphSpacing | undefined {\n const spacingNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"spacing\",\n );\n if (!spacingNode) return undefined;\n\n const spacing: ParagraphSpacing = {};\n const before = spacingNode.attributes[\"w:before\"] ?? spacingNode.attributes.before;\n const after = spacingNode.attributes[\"w:after\"] ?? spacingNode.attributes.after;\n const line = spacingNode.attributes[\"w:line\"] ?? spacingNode.attributes.line;\n const lineRule = spacingNode.attributes[\"w:lineRule\"] ?? spacingNode.attributes.lineRule;\n\n if (before !== undefined) {\n const v = Number.parseInt(before, 10);\n if (Number.isFinite(v)) spacing.before = v;\n }\n if (after !== undefined) {\n const v = Number.parseInt(after, 10);\n if (Number.isFinite(v)) spacing.after = v;\n }\n if (line !== undefined) {\n const v = Number.parseInt(line, 10);\n if (Number.isFinite(v)) spacing.line = v;\n }\n if (lineRule !== undefined) {\n const lr = lineRule.toLowerCase();\n if (lr === \"auto\" || lr === \"exact\") {\n spacing.lineRule = lr;\n } else if (lr === \"atleast\") {\n spacing.lineRule = \"atLeast\";\n }\n }\n\n if (\n spacing.before === undefined &&\n spacing.after === undefined &&\n spacing.line === undefined &&\n spacing.lineRule === undefined\n ) {\n return undefined;\n }\n return spacing;\n}\n\nfunction readParagraphIndentation(node: XmlElementNode): ParagraphIndentation | undefined {\n const indNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"ind\",\n );\n if (!indNode) return undefined;\n\n const indentation: ParagraphIndentation = {};\n const left = indNode.attributes[\"w:left\"] ?? indNode.attributes.left;\n const right = indNode.attributes[\"w:right\"] ?? indNode.attributes.right;\n const firstLine = indNode.attributes[\"w:firstLine\"] ?? indNode.attributes.firstLine;\n const hanging = indNode.attributes[\"w:hanging\"] ?? indNode.attributes.hanging;\n\n if (left !== undefined) {\n const v = Number.parseInt(left, 10);\n if (Number.isFinite(v)) indentation.left = v;\n }\n if (right !== undefined) {\n const v = Number.parseInt(right, 10);\n if (Number.isFinite(v)) indentation.right = v;\n }\n if (firstLine !== undefined) {\n const v = Number.parseInt(firstLine, 10);\n if (Number.isFinite(v)) indentation.firstLine = v;\n }\n if (hanging !== undefined) {\n const v = Number.parseInt(hanging, 10);\n if (Number.isFinite(v)) indentation.hanging = v;\n }\n\n if (\n indentation.left === undefined &&\n indentation.right === undefined &&\n indentation.firstLine === undefined &&\n indentation.hanging === undefined\n ) {\n return undefined;\n }\n return indentation;\n}\n\nfunction readParagraphTabStops(node: XmlElementNode): TabStop[] | undefined {\n const tabsNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"tabs\",\n );\n if (!tabsNode) return undefined;\n\n const tabStops: TabStop[] = [];\n for (const child of tabsNode.children) {\n if (child.type !== \"element\" || localName(child.name) !== \"tab\") continue;\n const pos = child.attributes[\"w:pos\"] ?? child.attributes.pos;\n const val = (child.attributes[\"w:val\"] ?? child.attributes.val ?? \"left\").toLowerCase();\n const leader = (child.attributes[\"w:leader\"] ?? child.attributes.leader ?? \"none\").toLowerCase();\n\n if (pos === undefined) continue;\n const position = Number.parseInt(pos, 10);\n if (!Number.isFinite(position)) continue;\n\n const align = ([\"left\", \"center\", \"right\", \"decimal\", \"bar\", \"clear\"] as const).includes(\n val as \"left\" | \"center\" | \"right\" | \"decimal\" | \"bar\" | \"clear\",\n )\n ? (val as TabStop[\"align\"])\n : \"left\";\n\n const leaderValue =\n leader === \"none\" ||\n leader === \"dot\" ||\n leader === \"hyphen\" ||\n leader === \"underscore\" ||\n leader === \"heavy\"\n ? (leader as Exclude<TabStop[\"leader\"], \"middleDot\">)\n : leader === \"middledot\"\n ? \"middleDot\"\n : undefined;\n\n tabStops.push({\n position,\n align,\n ...(leaderValue && leaderValue !== \"none\" ? { leader: leaderValue } : {}),\n });\n }\n\n return tabStops.length > 0 ? tabStops : undefined;\n}\n\nfunction readOnOffParagraphProperty(node: XmlElementNode, name: string): boolean | undefined {\n const propNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === name,\n );\n if (!propNode) return undefined;\n const val = (propNode.attributes[\"w:val\"] ?? propNode.attributes.val ?? \"true\").toLowerCase();\n return val !== \"false\" && val !== \"0\" && val !== \"off\" ? true : undefined;\n}\n\nfunction readParagraphOutlineLevel(node: XmlElementNode): number | undefined {\n const propNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"outlineLvl\",\n );\n if (!propNode) return undefined;\n const val = propNode.attributes[\"w:val\"] ?? propNode.attributes.val;\n if (val === undefined) return undefined;\n const level = Number.parseInt(val, 10);\n return Number.isFinite(level) ? level : undefined;\n}\n\nfunction readParagraphBorders(node: XmlElementNode): ParagraphBorders | undefined {\n const borderContainer = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"pBdr\",\n );\n if (!borderContainer) {\n return undefined;\n }\n\n const borders: ParagraphBorders = {};\n for (const [name, key] of [\n [\"top\", \"top\"],\n [\"left\", \"left\"],\n [\"bottom\", \"bottom\"],\n [\"right\", \"right\"],\n [\"bar\", \"bar\"],\n [\"between\", \"between\"],\n ] as const) {\n const borderNode = borderContainer.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === name,\n );\n if (borderNode) {\n const border = readBorder(borderNode);\n if (border) {\n borders[key] = border;\n }\n }\n }\n\n return Object.keys(borders).length > 0 ? borders : undefined;\n}\n\nfunction readParagraphShading(node: XmlElementNode): ParagraphShading | undefined {\n const shadingNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"shd\",\n );\n if (!shadingNode) {\n return undefined;\n }\n\n const shading: ParagraphShading = {};\n const fill = shadingNode.attributes[\"w:fill\"] ?? shadingNode.attributes.fill;\n const color = shadingNode.attributes[\"w:color\"] ?? shadingNode.attributes.color;\n const val = shadingNode.attributes[\"w:val\"] ?? shadingNode.attributes.val;\n if (fill) shading.fill = fill;\n if (color) shading.color = color;\n if (val) shading.val = val;\n return Object.keys(shading).length > 0 ? shading : undefined;\n}\n\nfunction readParagraphCnfStyle(node: XmlElementNode): string | undefined {\n const cnfStyleNode = node.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"cnfStyle\",\n );\n return cnfStyleNode?.attributes[\"w:val\"] ?? cnfStyleNode?.attributes.val;\n}\n\nfunction readBorder(node: XmlElementNode): ParagraphBorders[keyof ParagraphBorders] {\n const border: NonNullable<ParagraphBorders[keyof ParagraphBorders]> = {};\n const value = node.attributes[\"w:val\"] ?? node.attributes.val;\n const size = node.attributes[\"w:sz\"] ?? node.attributes.sz;\n const space = node.attributes[\"w:space\"] ?? node.attributes.space;\n const color = node.attributes[\"w:color\"] ?? node.attributes.color;\n if (value) border.value = value;\n if (size !== undefined) {\n const parsedSize = Number.parseInt(size, 10);\n if (Number.isFinite(parsedSize)) border.size = parsedSize;\n }\n if (space !== undefined) {\n const parsedSpace = Number.parseInt(space, 10);\n if (Number.isFinite(parsedSpace)) border.space = parsedSpace;\n }\n if (color) border.color = color;\n return Object.keys(border).length > 0 ? border : undefined;\n}\n\nfunction readParagraphStyleId(node: XmlElementNode): string | undefined {\n for (const child of node.children) {\n if (child.type !== \"element\" || localName(child.name) !== \"pStyle\") {\n continue;\n }\n\n const styleId = child.attributes[\"w:val\"] ?? child.attributes.val;\n if (styleId) {\n return styleId;\n }\n }\n\n return undefined;\n}\n\nfunction readParagraphNumbering(\n node: XmlElementNode,\n): ParsedParagraphNode[\"numbering\"] | undefined {\n const numberingProperties = node.children.find(\n (child): child is XmlElementNode =>\n child.type === \"element\" && localName(child.name) === \"numPr\",\n );\n if (!numberingProperties) {\n return undefined;\n }\n\n const levelNode = numberingProperties.children.find(\n (child): child is XmlElementNode =>\n child.type === \"element\" && localName(child.name) === \"ilvl\",\n );\n const instanceNode = numberingProperties.children.find(\n (child): child is XmlElementNode =>\n child.type === \"element\" && localName(child.name) === \"numId\",\n );\n const rawLevel = levelNode?.attributes[\"w:val\"] ?? levelNode?.attributes.val;\n const rawInstanceId = instanceNode?.attributes[\"w:val\"] ?? instanceNode?.attributes.val;\n if (!rawInstanceId || rawLevel === undefined || !/^-?\\d+$/.test(rawLevel)) {\n return undefined;\n }\n\n return {\n numberingInstanceId: toCanonicalNumberingInstanceId(rawInstanceId),\n level: Number.parseInt(rawLevel, 10),\n };\n}\n\nfunction parseRun(\n node: XmlElementNode,\n sourceXml: string,\n relationships: readonly OpcRelationship[],\n mediaParts: ReadonlyMap<string, InlineMediaPart>,\n sourcePartPath: string,\n): ParsedInlineNode[] {\n const marksResult = readRunMarks(node, sourceXml);\n if (!marksResult.supported) {\n return [\n {\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(node.start, node.end),\n },\n ];\n }\n\n const marks = marksResult.marks;\n const result: ParsedInlineNode[] = [];\n let encounteredUnsupportedChild = false;\n\n for (const child of node.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n switch (localName(child.name)) {\n case \"rPr\":\n break;\n case \"t\": {\n const text = child.children\n .filter((entry): entry is XmlTextNode => entry.type === \"text\")\n .map((entry) => entry.text)\n .join(\"\");\n result.push({\n type: \"text\",\n text,\n ...(marks.length > 0 ? { marks } : {}),\n });\n break;\n }\n case \"tab\":\n result.push({ type: \"tab\" });\n break;\n case \"sym\": {\n const symbol = parseSymbolNode(child, marks);\n if (!symbol) {\n encounteredUnsupportedChild = true;\n result.push({\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(child.start, child.end),\n });\n break;\n }\n result.push(symbol);\n break;\n }\n case \"br\":\n if (isColumnBreak(child)) {\n result.push({ type: \"column_break\" });\n } else if (isSimpleLineBreak(child)) {\n result.push({ type: \"hard_break\" });\n } else {\n result.push({\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(child.start, child.end),\n });\n }\n break;\n case \"drawing\": {\n const parsedMedia = parseInlineMediaXml(\n sourceXml.slice(child.start, child.end),\n relationships,\n mediaParts,\n sourcePartPath,\n );\n if (parsedMedia.length === 0) {\n encounteredUnsupportedChild = true;\n result.push({\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(node.start, node.end),\n });\n break;\n }\n\n const semanticChildren = node.children.filter(\n (entry): entry is XmlElementNode =>\n entry.type === \"element\" && localName(entry.name) !== \"rPr\",\n );\n const placementXml =\n semanticChildren.length === 1\n ? sourceXml.slice(node.start, node.end)\n : sourceXml.slice(child.start, child.end);\n\n result.push(\n ...parsedMedia.map((media) => ({\n type: \"image\" as const,\n mediaId: media.mediaId,\n relationshipId: media.relationshipId,\n packagePartName: media.packagePartName,\n contentType: media.contentType,\n filename: media.filename,\n ...(media.altText ? { altText: media.altText } : {}),\n placementXml,\n ...(media.display ? { display: media.display } : {}),\n ...(media.floating ? { floating: media.floating } : {}),\n })),\n );\n break;\n }\n case \"commentReference\":\n break;\n case \"lastRenderedPageBreak\":\n case \"proofErr\":\n result.push({\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(child.start, child.end),\n });\n break;\n default:\n encounteredUnsupportedChild = true;\n result.push({\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(child.start, child.end),\n });\n break;\n }\n }\n\n if (encounteredUnsupportedChild && result.every((child) => child.type === \"opaque_inline\")) {\n return [\n {\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(node.start, node.end),\n },\n ];\n }\n\n return result;\n}\n\nfunction parseRevisionContainer(\n node: XmlElementNode,\n sourceXml: string,\n relationshipMap: Map<string, OpcRelationship>,\n): ParsedInlineNode[] {\n const result: ParsedInlineNode[] = [];\n const allowsDeletedText = localName(node.name) === \"del\";\n\n for (const child of node.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n switch (localName(child.name)) {\n case \"r\": {\n const run = parseRunContentOnly(child, sourceXml, {\n allowDeletedText: allowsDeletedText,\n preserveUnsupportedReviewMarkup: true,\n });\n if (!run.supported) {\n return [\n {\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(node.start, node.end),\n },\n ];\n }\n result.push(...run.nodes);\n break;\n }\n case \"hyperlink\": {\n const hyperlink = parseHyperlink(child, sourceXml, relationshipMap, {\n allowDeletedText: allowsDeletedText,\n preserveUnsupportedReviewMarkup: true,\n });\n if (hyperlink.type === \"opaque_inline\") {\n return [\n {\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(node.start, node.end),\n },\n ];\n }\n result.push(hyperlink);\n break;\n }\n case \"commentRangeStart\":\n case \"commentRangeEnd\":\n case \"bookmarkStart\":\n case \"bookmarkEnd\":\n case \"permStart\":\n case \"permEnd\":\n case \"proofErr\":\n case \"lastRenderedPageBreak\":\n return [\n {\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(node.start, node.end),\n },\n ];\n default:\n return [\n {\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(node.start, node.end),\n },\n ];\n }\n }\n\n return result;\n}\n\nfunction parseHyperlink(\n node: XmlElementNode,\n sourceXml: string,\n relationshipMap: Map<string, OpcRelationship>,\n options: {\n allowDeletedText?: boolean;\n preserveUnsupportedReviewMarkup?: boolean;\n } = {},\n): ParsedHyperlinkNode | ParsedOpaqueInlineNode {\n const relationshipId = node.attributes[\"r:id\"] ?? node.attributes.id;\n const anchor = node.attributes[\"w:anchor\"] ?? node.attributes.anchor;\n let href: string | undefined;\n\n if (relationshipId) {\n const relationship = relationshipMap.get(relationshipId);\n if (\n relationship &&\n relationship.type === HYPERLINK_RELATIONSHIP_TYPE &&\n relationship.targetMode === \"external\"\n ) {\n href = relationship.target;\n }\n } else if (anchor) {\n href = `#${anchor}`;\n }\n\n if (!href) {\n return {\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(node.start, node.end),\n };\n }\n\n const children: Array<ParsedTextNode | ParsedBreakNode | ParsedTabNode> = [];\n\n for (const child of node.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n if (localName(child.name) !== \"r\") {\n return {\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(node.start, node.end),\n };\n }\n\n const run = parseRunContentOnly(child, sourceXml, {\n allowDeletedText: options.allowDeletedText,\n preserveUnsupportedReviewMarkup: options.preserveUnsupportedReviewMarkup,\n });\n if (!run.supported) {\n return {\n type: \"opaque_inline\",\n rawXml: sourceXml.slice(node.start, node.end),\n };\n }\n\n children.push(...run.nodes);\n }\n\n return {\n type: \"hyperlink\",\n href,\n children,\n rawXml: sourceXml.slice(node.start, node.end),\n };\n}\n\nfunction parseRunContentOnly(\n node: XmlElementNode,\n _sourceXml: string,\n options: {\n allowDeletedText?: boolean;\n preserveUnsupportedReviewMarkup?: boolean;\n } = {},\n): RunParseResult {\n const marksResult = readRunMarks(node, _sourceXml);\n if (!marksResult.supported) {\n return { nodes: [], supported: false };\n }\n\n const marks = marksResult.marks;\n const nodes: Array<ParsedTextNode | ParsedBreakNode | ParsedColumnBreakNode | ParsedTabNode | ParsedSymbolNode> = [];\n\n for (const child of node.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n switch (localName(child.name)) {\n case \"rPr\":\n break;\n case \"t\": {\n const text = child.children\n .filter((entry): entry is XmlTextNode => entry.type === \"text\")\n .map((entry) => entry.text)\n .join(\"\");\n nodes.push({\n type: \"text\",\n text,\n ...(marks.length > 0 ? { marks } : {}),\n });\n break;\n }\n case \"delText\":\n case \"delInstrText\":\n if (!options.allowDeletedText) {\n return { nodes: [], supported: false };\n }\n nodes.push({\n type: \"text\",\n text: child.children\n .filter((entry): entry is XmlTextNode => entry.type === \"text\")\n .map((entry) => entry.text)\n .join(\"\"),\n ...(marks.length > 0 ? { marks } : {}),\n });\n break;\n case \"tab\":\n nodes.push({ type: \"tab\" });\n break;\n case \"sym\": {\n const symbol = parseSymbolNode(child, marks);\n if (!symbol) {\n return { nodes: [], supported: false };\n }\n nodes.push(symbol);\n break;\n }\n case \"br\":\n if (isColumnBreak(child)) {\n nodes.push({ type: \"column_break\" });\n break;\n }\n if (!isSimpleLineBreak(child)) {\n return { nodes: [], supported: false };\n }\n nodes.push({ type: \"hard_break\" });\n break;\n case \"commentReference\":\n case \"lastRenderedPageBreak\":\n case \"proofErr\":\n if (options.preserveUnsupportedReviewMarkup) {\n return { nodes: [], supported: false };\n }\n break;\n default:\n return { nodes: [], supported: false };\n }\n }\n\n return { nodes, supported: true };\n}\n\nfunction readRunMarks(node: XmlElementNode, sourceXml: string): MarksParseResult {\n const properties = node.children.find(\n (child): child is XmlElementNode =>\n child.type === \"element\" && localName(child.name) === \"rPr\",\n );\n\n if (!properties) {\n return { marks: [], supported: true };\n }\n\n if (\n properties.children.some(\n (child) =>\n child.type === \"element\" &&\n DISALLOWED_RUN_PROPERTY_NAMES.has(localName(child.name)),\n )\n ) {\n return {\n marks: [],\n supported: false,\n };\n }\n\n const marks: TextMark[] = [];\n if (hasOnOffProperty(properties, \"b\")) {\n marks.push({ type: \"bold\" });\n }\n if (hasOnOffProperty(properties, \"i\")) {\n marks.push({ type: \"italic\" });\n }\n if (hasUnderlineProperty(properties)) {\n marks.push({ type: \"underline\" });\n }\n if (hasOnOffProperty(properties, \"strike\")) {\n marks.push({ type: \"strikethrough\" });\n }\n if (hasOnOffProperty(properties, \"dstrike\")) {\n marks.push({ type: \"doubleStrikethrough\" });\n }\n if (hasOnOffProperty(properties, \"vanish\")) {\n marks.push({ type: \"vanish\" });\n }\n\n const langMark = readRunLang(properties);\n if (langMark) {\n marks.push(langMark);\n }\n\n const backgroundColorMark = readRunBackgroundColor(properties);\n if (backgroundColorMark) {\n marks.push(backgroundColorMark);\n }\n\n const charSpacingMark = readNumericRunMark(properties, \"spacing\", \"charSpacing\");\n if (charSpacingMark) {\n marks.push(charSpacingMark);\n }\n\n const kerningMark = readNumericRunMark(properties, \"kern\", \"kerning\");\n if (kerningMark) {\n marks.push(kerningMark);\n }\n\n const positionMark = readNumericRunMark(properties, \"position\", \"position\");\n if (positionMark) {\n marks.push(positionMark);\n }\n\n if (hasOnOffProperty(properties, \"emboss\")) {\n marks.push({ type: \"emboss\" });\n }\n if (hasOnOffProperty(properties, \"imprint\")) {\n marks.push({ type: \"imprint\" });\n }\n if (hasOnOffProperty(properties, \"shadow\")) {\n marks.push({ type: \"shadow\" });\n }\n\n const textFillMark = readRunTextFill(properties, sourceXml);\n if (textFillMark) {\n marks.push(textFillMark);\n }\n\n return {\n marks,\n supported: true,\n };\n}\n\nfunction readRunLang(properties: XmlElementNode): TextMark | undefined {\n const langNode = properties.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"lang\",\n );\n if (!langNode) return undefined;\n const val =\n langNode.attributes[\"w:val\"] ??\n langNode.attributes.val ??\n langNode.attributes[\"w:bidi\"] ??\n langNode.attributes.bidi;\n if (!val) return undefined;\n return { type: \"lang\", val };\n}\n\nfunction readRunBackgroundColor(properties: XmlElementNode): TextMark | undefined {\n const shadingNode = properties.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"shd\",\n );\n if (!shadingNode) {\n return undefined;\n }\n\n const fill = shadingNode.attributes[\"w:fill\"] ?? shadingNode.attributes.fill;\n if (!fill || fill === \"auto\") {\n return undefined;\n }\n\n return { type: \"backgroundColor\", color: fill };\n}\n\nfunction readNumericRunMark(\n properties: XmlElementNode,\n elementName: \"spacing\" | \"kern\" | \"position\",\n markType: \"charSpacing\" | \"kerning\" | \"position\",\n): TextMark | undefined {\n const propertyNode = properties.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === elementName,\n );\n if (!propertyNode) {\n return undefined;\n }\n const rawValue = propertyNode.attributes[\"w:val\"] ?? propertyNode.attributes.val;\n if (rawValue === undefined) {\n return undefined;\n }\n const value = Number.parseInt(rawValue, 10);\n if (!Number.isFinite(value)) {\n return undefined;\n }\n return { type: markType, val: value };\n}\n\nfunction readRunTextFill(properties: XmlElementNode, sourceXml: string): TextMark | undefined {\n const textFillNode = properties.children.find(\n (child): child is XmlElementNode => child.type === \"element\" && localName(child.name) === \"textFill\",\n );\n if (!textFillNode) {\n return undefined;\n }\n return {\n type: \"textFill\",\n xml: sourceXml.slice(textFillNode.start, textFillNode.end),\n };\n}\n\nfunction parseSymbolNode(\n node: XmlElementNode,\n marks: TextMark[],\n): ParsedSymbolNode | undefined {\n const char = node.attributes[\"w:char\"] ?? node.attributes.char;\n if (!char) {\n return undefined;\n }\n const font = node.attributes[\"w:font\"] ?? node.attributes.font;\n return {\n type: \"symbol\",\n char,\n ...(font ? { font } : {}),\n ...(marks.length > 0 ? { marks } : {}),\n };\n}\n\nfunction supportsParagraphProperties(node: XmlElementNode): boolean {\n for (const child of node.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n if (name === \"pPrChange\") {\n return false;\n }\n\n if (name === \"rPr\") {\n if (\n child.children.some(\n (entry) =>\n entry.type === \"element\" &&\n DISALLOWED_PARAGRAPH_PROPERTY_NAMES.has(localName(entry.name)),\n )\n ) {\n return false;\n }\n }\n }\n\n return true;\n}\n\nconst DISALLOWED_RUN_PROPERTY_NAMES = new Set([\"rPrChange\"]);\nconst DISALLOWED_PARAGRAPH_PROPERTY_NAMES = new Set([\"pPrChange\", \"rPrChange\"]);\n\nfunction hasOnOffProperty(properties: XmlElementNode, propertyName: string): boolean {\n const property = properties.children.find(\n (child): child is XmlElementNode =>\n child.type === \"element\" && localName(child.name) === propertyName,\n );\n if (!property) {\n return false;\n }\n\n const value = (property.attributes[\"w:val\"] ?? property.attributes.val ?? \"true\").toLowerCase();\n return value !== \"false\" && value !== \"0\" && value !== \"off\";\n}\n\nfunction hasUnderlineProperty(properties: XmlElementNode): boolean {\n const property = properties.children.find(\n (child): child is XmlElementNode =>\n child.type === \"element\" && localName(child.name) === \"u\",\n );\n if (!property) {\n return false;\n }\n\n const value = (property.attributes[\"w:val\"] ?? property.attributes.val ?? \"single\").toLowerCase();\n return value !== \"none\";\n}\n\nfunction isSimpleLineBreak(node: XmlElementNode): boolean {\n const value = (node.attributes[\"w:type\"] ?? node.attributes.type ?? \"textWrapping\").toLowerCase();\n return value === \"textwrapping\" || value === \"line\";\n}\n\nfunction isColumnBreak(node: XmlElementNode): boolean {\n const value = (node.attributes[\"w:type\"] ?? node.attributes.type ?? \"\").toLowerCase();\n return value === \"column\";\n}\n\nfunction findChildElement(node: XmlElementNode, childLocalName: string): XmlElementNode {\n const child = node.children.find(\n (entry): entry is XmlElementNode =>\n entry.type === \"element\" && localName(entry.name) === childLocalName,\n );\n\n if (!child) {\n throw new Error(`Expected <${childLocalName}> element in main document XML.`);\n }\n\n return child;\n}\n\nfunction localName(name: string): string {\n const separatorIndex = name.indexOf(\":\");\n return separatorIndex >= 0 ? name.slice(separatorIndex + 1) : name;\n}\n\nfunction readOptionalAttribute(node: XmlElementNode, name: string): string | undefined {\n return node.attributes[`w:${name}`]\n ?? node.attributes[`r:${name}`]\n ?? node.attributes[name];\n}\n\nfunction parseXml(xml: string): XmlElementNode {\n const root: XmlElementNode = {\n type: \"element\",\n name: \"__root__\",\n attributes: {},\n children: [],\n start: 0,\n end: xml.length,\n };\n const stack: XmlElementNode[] = [root];\n let cursor = 0;\n\n while (cursor < xml.length) {\n if (xml.startsWith(\"<!--\", cursor)) {\n const end = xml.indexOf(\"-->\", cursor);\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<?\", cursor)) {\n const end = xml.indexOf(\"?>\", cursor);\n cursor = end >= 0 ? end + 2 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<![CDATA[\", cursor)) {\n const end = xml.indexOf(\"]]>\", cursor);\n const textEnd = end >= 0 ? end : xml.length;\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text: xml.slice(cursor + 9, textEnd),\n start: cursor,\n end: end >= 0 ? end + 3 : xml.length,\n });\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n const currentChar = xml[cursor];\n if (currentChar !== \"<\") {\n const nextTag = xml.indexOf(\"<\", cursor);\n const end = nextTag >= 0 ? nextTag : xml.length;\n const text = decodeXmlEntities(xml.slice(cursor, end));\n if (text.length > 0) {\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text,\n start: cursor,\n end,\n });\n }\n cursor = end;\n continue;\n }\n\n if (xml[cursor + 1] === \"/\") {\n const end = xml.indexOf(\">\", cursor);\n if (end < 0) {\n throw new Error(\"Malformed XML: missing closing >.\");\n }\n\n const name = xml.slice(cursor + 2, end).trim();\n const current = stack.pop();\n if (!current || localName(current.name) !== localName(name)) {\n throw new Error(`Malformed XML: unexpected closing tag </${name}>.`);\n }\n current.end = end + 1;\n cursor = end + 1;\n continue;\n }\n\n const tagEnd = findTagEnd(xml, cursor);\n const tagBody = xml.slice(cursor + 1, tagEnd);\n const selfClosing = /\\/\\s*$/.test(tagBody);\n const { name, attributes } = parseTag(tagBody.replace(/\\/\\s*$/, \"\").trim());\n const element: XmlElementNode = {\n type: \"element\",\n name,\n attributes,\n children: [],\n start: cursor,\n end: tagEnd + 1,\n };\n stack[stack.length - 1]?.children.push(element);\n\n if (!selfClosing) {\n stack.push(element);\n }\n\n cursor = tagEnd + 1;\n }\n\n if (stack.length !== 1) {\n throw new Error(\"Malformed XML: unclosed element in main document XML.\");\n }\n\n return root;\n}\n\nfunction parseTag(tagBody: string): { name: string; attributes: Record<string, string> } {\n let cursor = 0;\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n\n const nameStart = cursor;\n while (cursor < tagBody.length && !/\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n const name = tagBody.slice(nameStart, cursor);\n const attributes: Record<string, string> = {};\n\n while (cursor < tagBody.length) {\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n if (cursor >= tagBody.length) {\n break;\n }\n\n const keyStart = cursor;\n while (cursor < tagBody.length && !/[\\s=]/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n const key = tagBody.slice(keyStart, cursor);\n\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n\n if (tagBody[cursor] !== \"=\") {\n attributes[key] = \"\";\n continue;\n }\n cursor += 1;\n\n while (cursor < tagBody.length && /\\s/.test(tagBody[cursor] ?? \"\")) {\n cursor += 1;\n }\n\n const quote = tagBody[cursor];\n if (quote !== `\"` && quote !== `'`) {\n throw new Error(`Malformed XML attribute ${key}.`);\n }\n cursor += 1;\n\n const valueStart = cursor;\n while (cursor < tagBody.length && tagBody[cursor] !== quote) {\n cursor += 1;\n }\n const rawValue = tagBody.slice(valueStart, cursor);\n attributes[key] = decodeXmlEntities(rawValue);\n cursor += 1;\n }\n\n return { name, attributes };\n}\n\nfunction findTagEnd(xml: string, start: number): number {\n let cursor = start + 1;\n let quote: string | null = null;\n\n while (cursor < xml.length) {\n const current = xml[cursor];\n if (quote) {\n if (current === quote) {\n quote = null;\n }\n cursor += 1;\n continue;\n }\n\n if (current === `\"` || current === `'`) {\n quote = current;\n cursor += 1;\n continue;\n }\n\n if (current === \">\") {\n return cursor;\n }\n\n cursor += 1;\n }\n\n throw new Error(\"Malformed XML: missing >.\");\n}\n\nfunction decodeXmlEntities(value: string): string {\n return value.replace(/&(#x[0-9a-fA-F]+|#\\d+|amp|lt|gt|quot|apos);/g, (match, entity) => {\n switch (entity) {\n case \"amp\":\n return \"&\";\n case \"lt\":\n return \"<\";\n case \"gt\":\n return \">\";\n case \"quot\":\n return `\"`;\n case \"apos\":\n return \"'\";\n default:\n if (entity.startsWith(\"#x\")) {\n return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));\n }\n if (entity.startsWith(\"#\")) {\n return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));\n }\n return match;\n }\n });\n}\n","import type {\n AltChunkNode,\n BlockNode,\n CustomXmlNode,\n DiagnosticStore,\n DocumentRootNode,\n InlineNode,\n MediaCatalog,\n OpaqueBlockNode,\n OpaqueFragmentRecord,\n OpaqueInlineNode,\n ParagraphNode,\n PreservationStore,\n TableCellNode,\n TableNode,\n TableRowNode,\n TextMark,\n TextNode,\n SdtNode,\n} from \"../../model/canonical-document.ts\";\nimport type {\n ParsedAltChunkNode,\n ParsedBlockNode,\n ParsedCustomXmlNode,\n ParsedHyperlinkNode,\n ParsedInlineNode,\n ParsedImageNode,\n ParsedMainDocument,\n ParsedParagraphNode,\n ParsedSdtNode,\n ParsedTableBlockNode,\n ParsedTableCellNode,\n ParsedTableRowNode,\n} from \"../ooxml/parse-main-document.ts\";\n\nexport interface NormalizedTextDocument {\n content: DocumentRootNode;\n media: MediaCatalog;\n preservation: PreservationStore;\n diagnostics: DiagnosticStore;\n}\n\ninterface NormalizationState {\n nextFragmentIndex: number;\n nextWarningIndex: number;\n nextDiagnosticIndex: number;\n cursor: number;\n media: MediaCatalog;\n preservation: PreservationStore;\n diagnostics: DiagnosticStore;\n}\n\nexport function normalizeParsedTextDocument(\n document: ParsedMainDocument,\n packagePartName = \"/word/document.xml\",\n): NormalizedTextDocument {\n const state: NormalizationState = {\n nextFragmentIndex: 1,\n nextWarningIndex: 1,\n nextDiagnosticIndex: 1,\n cursor: 0,\n media: {\n items: {},\n },\n preservation: {\n opaqueFragments: {},\n packageParts: {},\n },\n diagnostics: {\n warnings: [],\n errors: [],\n },\n };\n\n const children = document.blocks.map((block, index) => {\n if (\n index > 0 &&\n document.blocks[index - 1]?.type === \"paragraph\" &&\n block.type === \"paragraph\"\n ) {\n state.cursor += 1;\n }\n\n return normalizeBlock(block, state, packagePartName);\n });\n\n return {\n content: {\n type: \"doc\",\n children,\n },\n media: state.media,\n preservation: state.preservation,\n diagnostics: state.diagnostics,\n };\n}\n\nfunction normalizeBlock(\n block: ParsedBlockNode,\n state: NormalizationState,\n packagePartName: string,\n): BlockNode {\n if (block.type === \"opaque_block\") {\n const opaque = recordOpaqueFragment(\"opaque_block\", block.rawXml, state, packagePartName);\n state.cursor += 1;\n return {\n type: \"opaque_block\",\n fragmentId: opaque.fragmentId,\n warningId: opaque.warningId,\n };\n }\n\n if (block.type === \"table\") {\n return normalizeTable(block, state, packagePartName);\n }\n\n if (block.type === \"sdt\") {\n return normalizeSdt(block, state, packagePartName);\n }\n\n if (block.type === \"custom_xml\") {\n return normalizeCustomXml(block, state, packagePartName);\n }\n\n if (block.type === \"alt_chunk\") {\n return normalizeAltChunk(block, state);\n }\n\n return normalizeParagraph(block, state, packagePartName);\n}\n\nfunction normalizeParagraph(\n paragraph: ParsedParagraphNode,\n state: NormalizationState,\n packagePartName: string,\n): ParagraphNode {\n const children = normalizeInlineChildren(paragraph.children, state, packagePartName);\n return {\n type: \"paragraph\",\n ...(paragraph.styleId ? { styleId: paragraph.styleId } : {}),\n ...(paragraph.numbering ? { numbering: paragraph.numbering } : {}),\n ...(paragraph.alignment ? { alignment: paragraph.alignment } : {}),\n ...(paragraph.spacing ? { spacing: paragraph.spacing } : {}),\n ...(paragraph.indentation ? { indentation: paragraph.indentation } : {}),\n ...(paragraph.tabStops && paragraph.tabStops.length > 0 ? { tabStops: paragraph.tabStops } : {}),\n ...(paragraph.keepNext ? { keepNext: paragraph.keepNext } : {}),\n ...(paragraph.keepLines ? { keepLines: paragraph.keepLines } : {}),\n ...(paragraph.outlineLevel !== undefined ? { outlineLevel: paragraph.outlineLevel } : {}),\n ...(paragraph.pageBreakBefore ? { pageBreakBefore: paragraph.pageBreakBefore } : {}),\n children,\n };\n}\n\nfunction normalizeTable(\n table: ParsedTableBlockNode,\n state: NormalizationState,\n packagePartName: string,\n): TableNode {\n const rows = table.rows.map((row) => normalizeTableRow(row, state, packagePartName));\n state.cursor += 1;\n return {\n type: \"table\",\n ...(table.styleId ? { styleId: table.styleId } : {}),\n ...(table.propertiesXml ? { propertiesXml: table.propertiesXml } : {}),\n gridColumns: table.gridColumns,\n rows,\n };\n}\n\nfunction normalizeTableRow(\n row: ParsedTableRowNode,\n state: NormalizationState,\n packagePartName: string,\n): TableRowNode {\n const cells = row.cells.map((cell) => normalizeTableCell(cell, state, packagePartName));\n return {\n type: \"table_row\",\n ...(row.propertiesXml ? { propertiesXml: row.propertiesXml } : {}),\n cells,\n };\n}\n\nfunction normalizeTableCell(\n cell: ParsedTableCellNode,\n state: NormalizationState,\n packagePartName: string,\n): TableCellNode {\n const children: BlockNode[] = [];\n for (const block of cell.children) {\n children.push(normalizeBlock(block, state, packagePartName));\n }\n // Ensure at least one child (OOXML requires at least one <w:p> per cell)\n if (children.length === 0) {\n children.push({ type: \"paragraph\", children: [] });\n }\n return {\n type: \"table_cell\",\n ...(cell.propertiesXml ? { propertiesXml: cell.propertiesXml } : {}),\n ...(cell.gridSpan ? { gridSpan: cell.gridSpan } : {}),\n ...(cell.verticalMerge ? { verticalMerge: cell.verticalMerge } : {}),\n children,\n };\n}\n\nfunction normalizeSdt(\n block: ParsedSdtNode,\n state: NormalizationState,\n packagePartName: string,\n): SdtNode {\n return {\n type: \"sdt\",\n properties: { ...block.properties },\n children: block.children.map((child) => normalizeBlock(child, state, packagePartName)),\n };\n}\n\nfunction normalizeCustomXml(\n block: ParsedCustomXmlNode,\n state: NormalizationState,\n packagePartName: string,\n): CustomXmlNode {\n return {\n type: \"custom_xml\",\n ...(block.uri ? { uri: block.uri } : {}),\n ...(block.element ? { element: block.element } : {}),\n children: block.children.map((child) => normalizeBlock(child, state, packagePartName)),\n };\n}\n\nfunction normalizeAltChunk(\n block: ParsedAltChunkNode,\n state: NormalizationState,\n): AltChunkNode {\n state.cursor += 1;\n return {\n type: \"alt_chunk\",\n relationshipId: block.relationshipId,\n };\n}\n\nfunction normalizeInlineChildren(\n nodes: ParsedInlineNode[],\n state: NormalizationState,\n packagePartName: string,\n): InlineNode[] {\n const normalized: InlineNode[] = [];\n\n for (const node of nodes) {\n switch (node.type) {\n case \"text\": {\n if (node.text.length === 0) {\n continue;\n }\n\n const previous = normalized[normalized.length - 1];\n if (previous?.type === \"text\" && sameMarks(previous.marks, node.marks)) {\n previous.text += node.text;\n } else {\n normalized.push({\n type: \"text\",\n text: node.text,\n ...(node.marks && node.marks.length > 0 ? { marks: node.marks } : {}),\n });\n }\n state.cursor += node.text.length;\n break;\n }\n case \"tab\":\n normalized.push({ type: \"tab\" });\n state.cursor += 1;\n break;\n case \"hard_break\":\n normalized.push({ type: \"hard_break\" });\n state.cursor += 1;\n break;\n case \"image\":\n normalized.push(normalizeImageNode(node, state));\n state.cursor += 1;\n break;\n case \"hyperlink\":\n normalized.push(normalizeHyperlink(node));\n state.cursor += measureHyperlink(node);\n break;\n case \"opaque_inline\": {\n const opaque = recordOpaqueFragment(\"opaque_inline\", node.rawXml, state, packagePartName);\n normalized.push(opaque as OpaqueInlineNode);\n state.cursor += 1;\n break;\n }\n }\n }\n\n return normalized;\n}\n\nfunction normalizeImageNode(\n node: ParsedImageNode,\n state: NormalizationState,\n): InlineNode {\n if (!state.media.items[node.mediaId]) {\n const packagePartName =\n typeof node.packagePartName === \"string\" && node.packagePartName.length > 0\n ? node.packagePartName\n : `/${node.mediaId.slice(\"media:\".length)}`;\n const filename =\n typeof node.filename === \"string\" && node.filename.length > 0\n ? node.filename\n : packagePartName.slice(packagePartName.lastIndexOf(\"/\") + 1) || \"image.bin\";\n state.media.items[node.mediaId] = {\n mediaId: node.mediaId,\n contentType: node.contentType ?? \"application/octet-stream\",\n filename,\n packagePartName,\n ...(node.relationshipId ? { relationshipId: node.relationshipId } : {}),\n ...(node.altText ? { altText: node.altText } : {}),\n };\n }\n\n return {\n type: \"image\",\n mediaId: node.mediaId,\n ...(node.altText ? { altText: node.altText } : {}),\n ...(node.placementXml ? { placementXml: node.placementXml } : {}),\n ...(node.display ? { display: node.display } : {}),\n ...(node.floating ? { floating: node.floating } : {}),\n };\n}\n\nfunction normalizeHyperlink(node: ParsedHyperlinkNode): {\n type: \"hyperlink\";\n href: string;\n children: Array<TextNode | { type: \"hard_break\" } | { type: \"tab\" }>;\n} {\n const children: Array<TextNode | { type: \"hard_break\" } | { type: \"tab\" }> = [];\n\n for (const child of node.children) {\n switch (child.type) {\n case \"text\": {\n if (child.text.length === 0) {\n continue;\n }\n const previous = children[children.length - 1];\n if (previous?.type === \"text\" && sameMarks(previous.marks, child.marks)) {\n previous.text += child.text;\n } else {\n children.push({\n type: \"text\",\n text: child.text,\n ...(child.marks && child.marks.length > 0 ? { marks: child.marks } : {}),\n });\n }\n break;\n }\n case \"tab\":\n children.push({ type: \"tab\" });\n break;\n case \"hard_break\":\n children.push({ type: \"hard_break\" });\n break;\n }\n }\n\n return {\n type: \"hyperlink\",\n href: node.href,\n children,\n };\n}\n\nfunction measureHyperlink(node: ParsedHyperlinkNode): number {\n return node.children.reduce((size, child) => {\n switch (child.type) {\n case \"text\":\n return size + child.text.length;\n case \"tab\":\n case \"hard_break\":\n return size + 1;\n }\n }, 0);\n}\n\nfunction sameMarks(left: TextMark[] | undefined, right: TextMark[] | undefined): boolean {\n const leftMarks = normalizeMarks(left);\n const rightMarks = normalizeMarks(right);\n return leftMarks.length === rightMarks.length && leftMarks.every((mark, index) => mark === rightMarks[index]);\n}\n\nfunction normalizeMarks(marks: TextMark[] | undefined): string[] {\n return [...(marks ?? []).map((mark) => mark.type)].sort();\n}\n\nfunction recordOpaqueFragment(\n nodeType: \"opaque_inline\" | \"opaque_block\",\n rawXml: string,\n state: NormalizationState,\n packagePartName: string,\n): { type: \"opaque_inline\" | \"opaque_block\"; fragmentId: string; warningId: string } {\n const fragmentId = `fragment:import-${state.nextFragmentIndex}`;\n state.nextFragmentIndex += 1;\n const warningId = `warning:import-${state.nextWarningIndex}`;\n state.nextWarningIndex += 1;\n const diagnosticId = `diagnostic:import-${state.nextDiagnosticIndex}`;\n state.nextDiagnosticIndex += 1;\n\n const rangeStart = state.cursor;\n const rangeEnd = state.cursor + 1;\n\n const record: OpaqueFragmentRecord = {\n fragmentId,\n payloadKind: \"xml-subtree\",\n payloadReference: rawXml,\n featureClass: \"preserve-only\",\n lastKnownRange: {\n from: rangeStart,\n to: rangeEnd,\n },\n warningId,\n packagePartName,\n };\n\n state.preservation.opaqueFragments[fragmentId] = record;\n state.diagnostics.warnings.push({\n diagnosticId,\n warningId,\n source: \"import\",\n message:\n nodeType === \"opaque_inline\"\n ? \"Unsupported inline OOXML was preserved as an opaque placeholder.\"\n : \"Unsupported block OOXML was preserved as an opaque placeholder.\",\n });\n\n return {\n type: nodeType,\n fragmentId,\n warningId,\n };\n}\n","import type { EditorError } from \"../../api/public-types.ts\";\n\nexport const CORRUPT_PACKAGE_REASONS = [\n \"zip-structure\",\n \"content-types-missing\",\n \"main-document-missing\",\n \"broken-relationship-graph\",\n \"malformed-xml\",\n \"unsupported-compression\",\n \"unreadable-package\",\n] as const;\n\nexport type CorruptPackageReason = (typeof CORRUPT_PACKAGE_REASONS)[number];\n\nexport interface CorruptPackageIssue {\n reason: CorruptPackageReason;\n message: string;\n partPath?: string;\n relationshipSourcePath?: string;\n relationshipId?: string;\n targetPartPath?: string;\n details?: Record<string, unknown>;\n}\n\nexport interface CorruptPackageErrorDetails extends Record<string, unknown> {\n stage: \"package\";\n reason: CorruptPackageReason;\n diagnosticsToken: string;\n partPath?: string;\n relationshipSourcePath?: string;\n relationshipId?: string;\n targetPartPath?: string;\n}\n\nexport function createCorruptPackageError(\n issue: CorruptPackageIssue,\n): EditorError {\n return {\n errorId: `error:package_corrupt:${createCorruptPackageDiagnosticsToken(issue)}`,\n code: \"package_corrupt\",\n message: issue.message,\n isFatal: true,\n source: \"import\",\n details: {\n stage: \"package\",\n reason: issue.reason,\n diagnosticsToken: createCorruptPackageDiagnosticsToken(issue),\n ...(issue.partPath ? { partPath: issue.partPath } : {}),\n ...(issue.relationshipSourcePath\n ? { relationshipSourcePath: issue.relationshipSourcePath }\n : {}),\n ...(issue.relationshipId ? { relationshipId: issue.relationshipId } : {}),\n ...(issue.targetPartPath ? { targetPartPath: issue.targetPartPath } : {}),\n ...(issue.details ?? {}),\n } satisfies CorruptPackageErrorDetails,\n };\n}\n\nexport function createMissingPartIssue(partPath: string): CorruptPackageIssue {\n return {\n reason:\n partPath === \"/[Content_Types].xml\"\n ? \"content-types-missing\"\n : partPath === \"/word/document.xml\"\n ? \"main-document-missing\"\n : \"unreadable-package\",\n message: `DOCX package is missing required part ${partPath}.`,\n partPath,\n };\n}\n\nexport function createBrokenRelationshipIssue(input: {\n relationshipSourcePath: string | null;\n relationshipId: string;\n targetPartPath: string;\n}): CorruptPackageIssue {\n return {\n reason: \"broken-relationship-graph\",\n message:\n input.relationshipSourcePath === null\n ? `DOCX package relationship ${input.relationshipId} points to missing part ${input.targetPartPath}.`\n : `DOCX part ${input.relationshipSourcePath} has unresolved relationship ${input.relationshipId} targeting ${input.targetPartPath}.`,\n relationshipSourcePath: input.relationshipSourcePath ?? undefined,\n relationshipId: input.relationshipId,\n targetPartPath: input.targetPartPath,\n };\n}\n\nexport function classifyCorruptPackageError(error: unknown): CorruptPackageIssue {\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"DOCX package could not be read safely.\";\n const normalized = message.toLowerCase();\n\n if (\n normalized.includes(\"end of central directory\") ||\n normalized.includes(\"zip archive\") ||\n normalized.includes(\"central directory signature\") ||\n normalized.includes(\"local file header signature\")\n ) {\n return {\n reason: \"zip-structure\",\n message,\n };\n }\n\n if (normalized.includes(\"compression\")) {\n return {\n reason: \"unsupported-compression\",\n message,\n };\n }\n\n if (normalized.includes(\"relationship\")) {\n return {\n reason: \"broken-relationship-graph\",\n message,\n };\n }\n\n if (normalized.includes(\"/[content_types].xml\")) {\n return createMissingPartIssue(\"/[Content_Types].xml\");\n }\n\n if (normalized.includes(\"/word/document.xml\")) {\n return createMissingPartIssue(\"/word/document.xml\");\n }\n\n if (normalized.includes(\"xml\")) {\n return {\n reason: \"malformed-xml\",\n message,\n };\n }\n\n return {\n reason: \"unreadable-package\",\n message,\n };\n}\n\nexport function createCorruptPackageDiagnosticsToken(\n issue: CorruptPackageIssue,\n): string {\n const fields = [\n issue.reason,\n issue.message,\n issue.partPath ?? \"\",\n issue.relationshipSourcePath ?? \"\",\n issue.relationshipId ?? \"\",\n issue.targetPartPath ?? \"\",\n ];\n\n let hash = 2166136261;\n for (const field of fields) {\n for (let index = 0; index < field.length; index += 1) {\n hash ^= field.charCodeAt(index);\n hash = Math.imul(hash, 16777619) >>> 0;\n }\n }\n\n return `pkg-${hash.toString(16).padStart(8, \"0\")}`;\n}\n","import type { OpcPackage } from \"../opc/package-reader.ts\";\nimport type { OpcPackagePart, OpcRelationship } from \"../ooxml/part-manifest.ts\";\n\nexport function reattachPreservedParts(\n sourcePackage: OpcPackage,\n workingParts: Map<string, OpcPackagePart>,\n packageRelationships: OpcRelationship[],\n ownedPaths: ReadonlySet<string>,\n): void {\n for (const [path, sourcePart] of sourcePackage.parts.entries()) {\n if (ownedPaths.has(path) || sourcePart.surfaceKind !== \"content\") {\n continue;\n }\n\n if (!workingParts.has(path)) {\n workingParts.set(path, clonePart(sourcePart));\n continue;\n }\n\n const currentPart = workingParts.get(path);\n if (!currentPart) {\n continue;\n }\n\n currentPart.contentType = sourcePart.contentType;\n currentPart.relationships = sourcePart.relationships.map(cloneRelationship);\n currentPart.relationshipsPartPath = sourcePart.relationshipsPartPath;\n currentPart.compression = sourcePart.compression;\n currentPart.bytes = new Uint8Array(sourcePart.bytes);\n currentPart.crc32 = sourcePart.crc32;\n }\n\n const knownPackageRelationshipIds = new Set(packageRelationships.map((relationship) => relationship.id));\n for (const relationship of sourcePackage.manifest.packageRelationships) {\n if (knownPackageRelationshipIds.has(relationship.id)) {\n continue;\n }\n\n packageRelationships.push(cloneRelationship(relationship));\n knownPackageRelationshipIds.add(relationship.id);\n }\n}\n\nfunction clonePart(part: OpcPackagePart): OpcPackagePart {\n return {\n ...part,\n relationships: part.relationships.map(cloneRelationship),\n bytes: new Uint8Array(part.bytes),\n };\n}\n\nfunction cloneRelationship(relationship: OpcRelationship): OpcRelationship {\n return { ...relationship };\n}\n","import {\n CONTENT_TYPES_PATH,\n PACKAGE_RELATIONSHIPS_PATH,\n OpcCompressionMethod,\n OpcPackagePart,\n OpcRelationship,\n comparePartPaths,\n getRelationshipsPartPath,\n normalizePartPath,\n} from \"../ooxml/part-manifest.ts\";\nimport type { OpcPackage } from \"../opc/package-reader.ts\";\nimport { writeOpcPackage } from \"../opc/package-writer.ts\";\nimport { reattachPreservedParts } from \"./reattach-preserved-parts.ts\";\n\nexport interface ExportPartReplacement {\n path: string;\n bytes: Uint8Array;\n contentType: string;\n relationships?: OpcRelationship[];\n compression?: OpcCompressionMethod;\n}\n\nexport interface ExportSessionSnapshot {\n manifest: OpcPackage[\"manifest\"];\n parts: Map<string, OpcPackagePart>;\n}\n\nexport class ExportSession {\n private readonly ownedPaths: Set<string>;\n private readonly workingParts: Map<string, OpcPackagePart>;\n private readonly packageRelationships: OpcRelationship[];\n\n public constructor(private readonly sourcePackage: OpcPackage, ownedOutputPaths: Iterable<string>) {\n this.ownedPaths = new Set(\n [...ownedOutputPaths].map((path) => {\n const normalized = normalizePartPath(path);\n if (normalized === CONTENT_TYPES_PATH || normalized.endsWith(\".rels\") || normalized === PACKAGE_RELATIONSHIPS_PATH) {\n throw new Error(`ExportSession cannot directly own reserved OPC manifest path ${normalized}.`);\n }\n\n return normalized;\n }),\n );\n this.workingParts = cloneParts(sourcePackage.parts);\n this.packageRelationships = sourcePackage.manifest.packageRelationships.map(cloneRelationship);\n }\n\n public replaceOwnedPart(replacement: ExportPartReplacement): void {\n const normalizedPath = normalizePartPath(replacement.path);\n if (!this.ownedPaths.has(normalizedPath)) {\n throw new Error(`Attempted to rewrite non-owned OPC path ${normalizedPath}.`);\n }\n\n const existing = this.workingParts.get(normalizedPath);\n const nextPart: OpcPackagePart = {\n path: normalizedPath,\n surfaceKind: \"content\",\n contentType: replacement.contentType,\n relationshipsPartPath: getRelationshipsPartPath(normalizedPath),\n relationships: (replacement.relationships ?? existing?.relationships ?? []).map(cloneRelationship),\n compression: replacement.compression ?? existing?.compression ?? \"deflate\",\n bytes: new Uint8Array(replacement.bytes),\n crc32: 0,\n };\n\n this.workingParts.set(normalizedPath, nextPart);\n }\n\n public withOwnedPart(replacement: ExportPartReplacement): ExportSession {\n this.replaceOwnedPart(replacement);\n return this;\n }\n\n public toPackage(): OpcPackage {\n reattachPreservedParts(\n this.sourcePackage,\n this.workingParts,\n this.packageRelationships,\n this.ownedPaths,\n );\n const parts = pruneReservedManifestParts(this.workingParts);\n const manifest = buildManifest(parts, this.packageRelationships, this.sourcePackage.manifest.contentTypes);\n return {\n manifest,\n parts,\n sourceByteLength: this.sourcePackage.sourceByteLength,\n };\n }\n\n public serialize(): Uint8Array {\n return writeOpcPackage(this.toPackage());\n }\n}\n\nexport function createExportSession(\n sourcePackage: OpcPackage,\n ownedOutputPaths: Iterable<string>,\n): ExportSession {\n return new ExportSession(sourcePackage, ownedOutputPaths);\n}\n\nfunction cloneParts(parts: Map<string, OpcPackagePart>): Map<string, OpcPackagePart> {\n return new Map(\n [...parts.entries()].map(([path, part]) => [\n path,\n {\n ...part,\n relationships: part.relationships.map(cloneRelationship),\n bytes: new Uint8Array(part.bytes),\n },\n ]),\n );\n}\n\nfunction pruneReservedManifestParts(parts: Map<string, OpcPackagePart>): Map<string, OpcPackagePart> {\n return new Map(\n [...parts.entries()].filter(([path]) => path !== CONTENT_TYPES_PATH && path !== PACKAGE_RELATIONSHIPS_PATH && !path.includes(\"/_rels/\")),\n );\n}\n\nfunction buildManifest(\n parts: Map<string, OpcPackagePart>,\n packageRelationships: OpcRelationship[],\n contentTypesSeed: OpcPackage[\"manifest\"][\"contentTypes\"],\n): OpcPackage[\"manifest\"] {\n const partsList = [...parts.values()].sort((left, right) => comparePartPaths(left.path, right.path));\n\n const overrides = { ...contentTypesSeed.overrides };\n for (const key of Object.keys(overrides)) {\n if (!parts.has(normalizePartPath(key))) {\n delete overrides[key];\n }\n }\n\n for (const part of partsList) {\n if (!part.contentType) {\n throw new Error(`Cannot export part without content type: ${part.path}`);\n }\n\n overrides[part.path] = part.contentType;\n }\n\n return {\n contentTypes: {\n defaults: { ...contentTypesSeed.defaults },\n overrides,\n },\n packageRelationships: packageRelationships.map(cloneRelationship),\n parts: partsList.map((part) => ({\n path: part.path,\n surfaceKind: part.surfaceKind,\n contentType: part.contentType,\n relationshipsPartPath: part.relationshipsPartPath,\n relationships: part.relationships.map(cloneRelationship),\n compression: part.compression,\n byteLength: part.bytes.byteLength,\n })),\n };\n}\n\nfunction cloneRelationship(relationship: OpcRelationship): OpcRelationship {\n return { ...relationship };\n}\n\nexport { buildManifest };\n","import type { OpaqueFragmentRecord, PreservationStore } from \"../model/canonical-document.ts\";\nimport type { OpcRelationship } from \"../io/ooxml/part-manifest.ts\";\n\nexport function retainRelationshipsForFragment(\n fragment: OpaqueFragmentRecord | undefined,\n relationships: OpcRelationship[],\n existingRelationshipMap: Map<string, OpcRelationship>,\n retainedRelationshipIds: Set<string>,\n): void {\n if (!fragment || fragment.payloadKind !== \"xml-subtree\") {\n return;\n }\n\n for (const relationshipId of extractReferencedRelationshipIds(fragment.payloadReference)) {\n if (retainedRelationshipIds.has(relationshipId)) {\n continue;\n }\n\n const relationship = existingRelationshipMap.get(relationshipId);\n if (!relationship) {\n continue;\n }\n\n relationships.push({ ...relationship });\n retainedRelationshipIds.add(relationshipId);\n }\n}\n\nexport function retainRelationshipsForStore(\n store: PreservationStore,\n relationships: OpcRelationship[],\n existingRelationshipMap: Map<string, OpcRelationship>,\n retainedRelationshipIds: Set<string>,\n): void {\n for (const fragment of Object.values(store.opaqueFragments)) {\n retainRelationshipsForFragment(\n fragment,\n relationships,\n existingRelationshipMap,\n retainedRelationshipIds,\n );\n }\n}\n\nexport function extractReferencedRelationshipIds(xml: string): Set<string> {\n const relationshipIds = new Set<string>();\n const relationshipPattern = /\\br:id=([\"'])([^\"']+)\\1/gu;\n\n for (const match of xml.matchAll(relationshipPattern)) {\n const relationshipId = match[2];\n if (relationshipId) {\n relationshipIds.add(relationshipId);\n }\n }\n\n return relationshipIds;\n}\n","import type { NumberingCatalog, ParagraphNode } from \"../../model/canonical-document.ts\";\n\nexport const WORD_NUMBERING_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml\";\n\nexport function serializeNumberingXml(catalog: NumberingCatalog): string {\n const abstractDefinitions = Object.values(catalog.abstractDefinitions).sort((left, right) =>\n compareSerializedIds(left.abstractNumberingId, right.abstractNumberingId),\n );\n const instances = Object.values(catalog.instances).sort((left, right) =>\n compareSerializedIds(left.numberingInstanceId, right.numberingInstanceId),\n );\n\n const body = [\n ...abstractDefinitions.map((definition) => serializeAbstractDefinition(definition)),\n ...instances.map((instance) => serializeInstance(instance)),\n ].join(\"\");\n\n return [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n `<w:numbering xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">${body}</w:numbering>`,\n ].join(\"\\n\");\n}\n\nexport function serializeParagraphNumberingProperties(\n numbering: ParagraphNode[\"numbering\"],\n): string {\n if (!numbering) {\n return \"\";\n }\n\n return `<w:numPr><w:ilvl w:val=\"${numbering.level}\"/><w:numId w:val=\"${escapeAttribute(\n stripCanonicalPrefix(numbering.numberingInstanceId, \"num:\"),\n )}\"/></w:numPr>`;\n}\n\nfunction serializeAbstractDefinition(definition: NumberingCatalog[\"abstractDefinitions\"][string]): string {\n const abstractNumId = escapeAttribute(\n stripCanonicalPrefix(definition.abstractNumberingId, \"abstract-num:\"),\n );\n const levels = [...definition.levels]\n .sort((left, right) => left.level - right.level)\n .map((level) => serializeLevel(level))\n .join(\"\");\n\n return `<w:abstractNum w:abstractNumId=\"${abstractNumId}\">${levels}</w:abstractNum>`;\n}\n\nfunction serializeLevel(level: NumberingCatalog[\"abstractDefinitions\"][string][\"levels\"][number]): string {\n const start = level.startAt !== undefined ? `<w:start w:val=\"${level.startAt}\"/>` : \"\";\n const paragraphStyle = level.paragraphStyleId\n ? `<w:pStyle w:val=\"${escapeAttribute(level.paragraphStyleId)}\"/>`\n : \"\";\n\n return `<w:lvl w:ilvl=\"${level.level}\">${start}<w:numFmt w:val=\"${escapeAttribute(\n level.format,\n )}\"/><w:lvlText w:val=\"${escapeAttribute(level.text)}\"/>${paragraphStyle}</w:lvl>`;\n}\n\nfunction serializeInstance(instance: NumberingCatalog[\"instances\"][string]): string {\n const numId = escapeAttribute(stripCanonicalPrefix(instance.numberingInstanceId, \"num:\"));\n const abstractNumId = escapeAttribute(\n stripCanonicalPrefix(instance.abstractNumberingId, \"abstract-num:\"),\n );\n const overrides = [...instance.overrides]\n .sort((left, right) => left.level - right.level)\n .map((override) => serializeOverride(override))\n .join(\"\");\n\n return `<w:num w:numId=\"${numId}\"><w:abstractNumId w:val=\"${abstractNumId}\"/>${overrides}</w:num>`;\n}\n\nfunction serializeOverride(override: NumberingCatalog[\"instances\"][string][\"overrides\"][number]): string {\n const startOverride =\n override.startAt !== undefined ? `<w:startOverride w:val=\"${override.startAt}\"/>` : \"\";\n return `<w:lvlOverride w:ilvl=\"${override.level}\">${startOverride}</w:lvlOverride>`;\n}\n\nfunction compareSerializedIds(left: string, right: string): number {\n return stripKnownPrefix(left).localeCompare(stripKnownPrefix(right), \"en\", { numeric: true });\n}\n\nfunction stripKnownPrefix(value: string): string {\n return value.replace(/^abstract-num:|^num:/, \"\");\n}\n\nfunction stripCanonicalPrefix(value: string, prefix: \"abstract-num:\" | \"num:\"): string {\n return value.startsWith(prefix) ? value.slice(prefix.length) : value;\n}\n\nfunction escapeAttribute(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/\"/g, \""\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n","import type {\n AltChunkNode,\n BorderSpec,\n CustomXmlNode,\n DocumentRootNode,\n InlineNode,\n MediaCatalog,\n ParagraphNode,\n PreservationStore,\n SdtNode,\n TableNode,\n TableCellNode,\n TextMark,\n} from \"../../model/canonical-document.ts\";\nimport type { OpcRelationship } from \"../ooxml/part-manifest.ts\";\nimport type { RevisionParagraphBoundary } from \"../ooxml/revision-boundaries.ts\";\nimport { getOpaqueFragment } from \"../../preservation/store.ts\";\nimport { retainRelationshipsForFragment } from \"../../preservation/relationship-retention.ts\";\nimport { serializeParagraphNumberingProperties } from \"./serialize-numbering.ts\";\n\nconst HYPERLINK_RELATIONSHIP_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\";\n\nexport interface SerializedMainDocument {\n documentXml: string;\n relationships: OpcRelationship[];\n paragraphBoundaries: RevisionParagraphBoundary[];\n}\n\nexport interface SerializeMainDocumentOptions {\n documentAttributes?: Record<string, string>;\n media?: MediaCatalog;\n}\n\ninterface SerializationState {\n nextHyperlinkRelationshipIndex: number;\n relationships: OpcRelationship[];\n existingRelationshipMap: Map<string, OpcRelationship>;\n retainedRelationshipIds: Set<string>;\n media: MediaCatalog;\n preservation: PreservationStore;\n}\n\ninterface InlineSerializationResult {\n xml: string;\n cursor: number;\n boundaries: Map<number, number>;\n}\n\ninterface ParagraphSerializationResult {\n xml: string;\n nextCursor: number;\n boundary: RevisionParagraphBoundary;\n}\n\nexport function serializeMainDocument(\n content: DocumentRootNode,\n preservation: PreservationStore = { opaqueFragments: {}, packageParts: {} },\n existingRelationships: readonly OpcRelationship[] = [],\n options: SerializeMainDocumentOptions = {},\n): SerializedMainDocument {\n const nextRelationshipIndex =\n existingRelationships.reduce((maxIndex, relationship) => {\n const match = /^rIdHyperlink(\\d+)$/.exec(relationship.id);\n return match ? Math.max(maxIndex, Number.parseInt(match[1] ?? \"0\", 10)) : maxIndex;\n }, 0) + 1;\n const state: SerializationState = {\n nextHyperlinkRelationshipIndex: nextRelationshipIndex,\n relationships: existingRelationships.filter(\n (relationship) => relationship.type !== HYPERLINK_RELATIONSHIP_TYPE,\n ).map(cloneRelationship),\n existingRelationshipMap: new Map(\n existingRelationships.map((relationship) => [relationship.id, cloneRelationship(relationship)]),\n ),\n retainedRelationshipIds: new Set(\n existingRelationships\n .filter((relationship) => relationship.type !== HYPERLINK_RELATIONSHIP_TYPE)\n .map((relationship) => relationship.id),\n ),\n media: options.media ?? { items: {} },\n preservation,\n };\n const documentOpen = `<w:document${serializeDocumentAttributes(options.documentAttributes, content)}>`;\n const prefix = [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n documentOpen,\n ` <w:body>`,\n ].join(\"\\n\");\n const suffix = `</w:body>\\n</w:document>`;\n const bodyPieces: string[] = [];\n const paragraphBoundaries: RevisionParagraphBoundary[] = [];\n let bodyLength = 0;\n let sectionPropertiesXml = \"<w:sectPr/>\";\n let cursor = 0;\n let paragraphIndex = -1;\n let previousWasParagraph = false;\n\n for (const block of content.children) {\n if (block.type === \"paragraph\") {\n if (previousWasParagraph) {\n cursor += 1;\n }\n\n paragraphIndex += 1;\n const serializedParagraph = serializeParagraph(\n block,\n state,\n cursor,\n paragraphIndex,\n );\n const paragraphOffset = prefix.length + bodyLength;\n bodyPieces.push(serializedParagraph.xml);\n bodyLength += serializedParagraph.xml.length;\n paragraphBoundaries.push(\n offsetParagraphBoundary(serializedParagraph.boundary, paragraphOffset),\n );\n cursor = serializedParagraph.nextCursor;\n previousWasParagraph = true;\n continue;\n }\n\n if (block.type === \"table\") {\n const tableXml = serializeTableNode(block, state);\n bodyPieces.push(tableXml);\n bodyLength += tableXml.length;\n cursor += 1;\n previousWasParagraph = false;\n continue;\n }\n\n if (block.type === \"sdt\") {\n const sdtXml = serializeSdtNode(block, state);\n bodyPieces.push(sdtXml);\n bodyLength += sdtXml.length;\n previousWasParagraph = false;\n continue;\n }\n\n if (block.type === \"custom_xml\") {\n const customXml = serializeCustomXmlNode(block, state);\n bodyPieces.push(customXml);\n bodyLength += customXml.length;\n previousWasParagraph = false;\n continue;\n }\n\n if (block.type === \"alt_chunk\") {\n const altChunkXml = serializeAltChunkNode(block);\n bodyPieces.push(altChunkXml);\n bodyLength += altChunkXml.length;\n cursor += 1;\n previousWasParagraph = false;\n continue;\n }\n\n const blockXml = serializeOpaqueBlock(block, state);\n if (looksLikeSectionPropertiesXml(blockXml)) {\n sectionPropertiesXml = blockXml;\n } else {\n bodyPieces.push(blockXml);\n bodyLength += blockXml.length;\n }\n cursor += 1;\n previousWasParagraph = false;\n }\n\n const bodyXml = bodyPieces.join(\"\");\n const documentXml = `${prefix}${bodyXml || \"<w:p><w:r><w:t></w:t></w:r></w:p>\"}${sectionPropertiesXml}${suffix}`;\n\n return {\n documentXml,\n relationships: state.relationships,\n paragraphBoundaries,\n };\n}\n\nfunction serializeOpaqueBlock(\n block: Extract<DocumentRootNode[\"children\"][number], { type: \"opaque_block\" }>,\n state: SerializationState,\n): string {\n return lookupOpaqueXml(block.fragmentId, state);\n}\n\nfunction serializeTableNode(\n table: TableNode,\n state: SerializationState,\n): string {\n const propertiesXml = table.propertiesXml ?? buildTablePropertiesXml(table);\n const gridXml =\n table.gridColumns.length > 0\n ? `<w:tblGrid>${table.gridColumns\n .map((width) => `<w:gridCol w:w=\"${width}\"/>`)\n .join(\"\")}</w:tblGrid>`\n : \"\";\n const rowsXml = table.rows\n .map((row) => {\n const rowPropertiesXml = row.propertiesXml ?? \"\";\n const cellsXml = row.cells\n .map((cell) => serializeTableCellNode(cell, state))\n .join(\"\");\n return `<w:tr>${rowPropertiesXml}${cellsXml}</w:tr>`;\n })\n .join(\"\");\n return `<w:tbl>${propertiesXml}${gridXml}${rowsXml}</w:tbl>`;\n}\n\nfunction serializeTableCellNode(\n cell: TableCellNode,\n state: SerializationState,\n): string {\n const propertiesXml = cell.propertiesXml ?? buildCellPropertiesXml(cell);\n const blocksXml = cell.children\n .map((child) => serializeBlockNode(child, state))\n .join(\"\");\n return `<w:tc>${propertiesXml}${blocksXml || \"<w:p/>\"}</w:tc>`;\n}\n\nfunction serializeBlockNode(\n block: DocumentRootNode[\"children\"][number],\n state: SerializationState,\n): string {\n switch (block.type) {\n case \"paragraph\":\n return serializeTableCellParagraph(block, state);\n case \"table\":\n return serializeTableNode(block, state);\n case \"sdt\":\n return serializeSdtNode(block, state);\n case \"custom_xml\":\n return serializeCustomXmlNode(block, state);\n case \"alt_chunk\":\n return serializeAltChunkNode(block);\n case \"opaque_block\":\n return lookupOpaqueXml(block.fragmentId, state);\n case \"section_break\":\n return block.propertiesXml ?? \"<w:sectPr/>\";\n }\n}\n\nfunction buildCellPropertiesXml(cell: TableCellNode): string {\n const children: string[] = [];\n if (cell.gridSpan && cell.gridSpan > 1) {\n children.push(`<w:gridSpan w:val=\"${cell.gridSpan}\"/>`);\n }\n if (cell.verticalMerge) {\n children.push(\n cell.verticalMerge === \"restart\"\n ? `<w:vMerge w:val=\"restart\"/>`\n : `<w:vMerge/>`,\n );\n }\n return children.length > 0 ? `<w:tcPr>${children.join(\"\")}</w:tcPr>` : \"\";\n}\n\nfunction serializeSdtNode(\n block: SdtNode,\n state: SerializationState,\n): string {\n const propertiesXml = block.properties.propertiesXml ?? buildSdtPropertiesXml(block);\n const childrenXml = block.children.map((child) => serializeBlockNode(child, state)).join(\"\") || \"<w:p/>\";\n return `<w:sdt>${propertiesXml}<w:sdtContent>${childrenXml}</w:sdtContent></w:sdt>`;\n}\n\nfunction serializeCustomXmlNode(\n block: CustomXmlNode,\n state: SerializationState,\n): string {\n const attrs: string[] = [];\n if (block.uri) {\n attrs.push(`w:uri=\"${escapeAttribute(block.uri)}\"`);\n }\n if (block.element) {\n attrs.push(`w:element=\"${escapeAttribute(block.element)}\"`);\n }\n const attrXml = attrs.length > 0 ? ` ${attrs.join(\" \")}` : \"\";\n const childrenXml = block.children.map((child) => serializeBlockNode(child, state)).join(\"\");\n return `<w:customXml${attrXml}>${childrenXml || \"<w:p/>\"}</w:customXml>`;\n}\n\nfunction serializeAltChunkNode(\n block: AltChunkNode,\n): string {\n return `<w:altChunk r:id=\"${escapeAttribute(block.relationshipId)}\"/>`;\n}\n\nfunction buildSdtPropertiesXml(block: SdtNode): string {\n const children: string[] = [];\n if (block.properties.alias) {\n children.push(`<w:alias w:val=\"${escapeAttribute(block.properties.alias)}\"/>`);\n }\n if (block.properties.tag) {\n children.push(`<w:tag w:val=\"${escapeAttribute(block.properties.tag)}\"/>`);\n }\n if (block.properties.lock) {\n children.push(`<w:lock w:val=\"${escapeAttribute(block.properties.lock)}\"/>`);\n }\n if (block.properties.sdtType) {\n children.push(`<w:${block.properties.sdtType}/>`);\n }\n return children.length > 0 ? `<w:sdtPr>${children.join(\"\")}</w:sdtPr>` : \"<w:sdtPr/>\";\n}\n\nfunction serializeTableCellParagraph(\n paragraph: ParagraphNode,\n state: SerializationState,\n): string {\n let xml = \"<w:p>\";\n const paragraphPropertiesXml = buildParagraphPropertiesXml(paragraph);\n if (paragraphPropertiesXml.length > 0) {\n xml += paragraphPropertiesXml;\n }\n const childrenXml = paragraph.children.map((child) => serializeTableInlineNode(child, state)).join(\"\");\n xml += childrenXml || \"<w:r><w:t></w:t></w:r>\";\n xml += \"</w:p>\";\n return xml;\n}\n\nfunction serializeTableInlineNode(\n node: InlineNode,\n state: SerializationState,\n): string {\n switch (node.type) {\n case \"text\": {\n const marks = node.marks;\n const properties = serializeRunPropertiesFromMarks(marks);\n const preserve = requiresPreservedSpace(node.text) ? ` xml:space=\"preserve\"` : \"\";\n return `<w:r>${properties}<w:t${preserve}>${escapeXml(node.text)}</w:t></w:r>`;\n }\n case \"tab\":\n return \"<w:r><w:tab/></w:r>\";\n case \"column_break\":\n return \"<w:r><w:br w:type=\\\"column\\\"/></w:r>\";\n case \"hard_break\":\n return \"<w:r><w:br/></w:r>\";\n case \"symbol\": {\n const properties = serializeRunPropertiesFromMarks(node.marks);\n const fontAttribute = node.font ? ` w:font=\"${escapeAttribute(node.font)}\"` : \"\";\n return `<w:r>${properties}<w:sym${fontAttribute} w:char=\"${escapeAttribute(node.char)}\"/></w:r>`;\n }\n case \"image\":\n return serializeImageNode(node, state);\n case \"opaque_inline\":\n return lookupOpaqueXml(node.fragmentId, state);\n case \"chart_preview\":\n case \"smartart_preview\":\n case \"shape\":\n case \"wordart\":\n case \"vml_shape\":\n return node.rawXml;\n case \"hyperlink\": {\n const hyperlinkOpen = node.href.startsWith(\"#\")\n ? `<w:hyperlink w:anchor=\"${escapeAttribute(node.href.slice(1))}\">`\n : (() => {\n const relationshipId = `rIdHyperlink${state.nextHyperlinkRelationshipIndex}`;\n state.nextHyperlinkRelationshipIndex += 1;\n state.relationships.push({\n id: relationshipId,\n type: \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\",\n target: node.href,\n targetMode: \"external\",\n });\n state.retainedRelationshipIds.add(relationshipId);\n return `<w:hyperlink r:id=\"${relationshipId}\">`;\n })();\n const childrenXml = node.children.map((child) => serializeTableInlineNode(child, state)).join(\"\");\n return `${hyperlinkOpen}${childrenXml}</w:hyperlink>`;\n }\n }\n}\n\nfunction buildParagraphPropertiesXml(paragraph: ParagraphNode): string {\n const children: string[] = [];\n\n if (paragraph.styleId) {\n children.push(`<w:pStyle w:val=\"${escapeAttribute(paragraph.styleId)}\"/>`);\n }\n if (paragraph.keepNext) {\n children.push(\"<w:keepNext/>\");\n }\n if (paragraph.keepLines) {\n children.push(\"<w:keepLines/>\");\n }\n if (paragraph.pageBreakBefore) {\n children.push(\"<w:pageBreakBefore/>\");\n }\n if (paragraph.widowControl) {\n children.push(\"<w:widowControl/>\");\n }\n if (paragraph.outlineLevel !== undefined) {\n children.push(`<w:outlineLvl w:val=\"${paragraph.outlineLevel}\"/>`);\n }\n if (paragraph.numbering) {\n children.push(serializeParagraphNumberingProperties(paragraph.numbering));\n }\n if (paragraph.spacing) {\n const s = paragraph.spacing;\n const attrs: string[] = [];\n if (s.before !== undefined) attrs.push(`w:before=\"${s.before}\"`);\n if (s.after !== undefined) attrs.push(`w:after=\"${s.after}\"`);\n if (s.line !== undefined) attrs.push(`w:line=\"${s.line}\"`);\n if (s.lineRule !== undefined) attrs.push(`w:lineRule=\"${s.lineRule}\"`);\n if (attrs.length > 0) children.push(`<w:spacing ${attrs.join(\" \")}/>`);\n }\n if (paragraph.indentation) {\n const ind = paragraph.indentation;\n const attrs: string[] = [];\n if (ind.left !== undefined) attrs.push(`w:left=\"${ind.left}\"`);\n if (ind.right !== undefined) attrs.push(`w:right=\"${ind.right}\"`);\n if (ind.firstLine !== undefined) attrs.push(`w:firstLine=\"${ind.firstLine}\"`);\n if (ind.hanging !== undefined) attrs.push(`w:hanging=\"${ind.hanging}\"`);\n if (attrs.length > 0) children.push(`<w:ind ${attrs.join(\" \")}/>`);\n }\n if (paragraph.alignment) {\n children.push(`<w:jc w:val=\"${paragraph.alignment}\"/>`);\n }\n if (paragraph.borders) {\n const bordersXml = serializeParagraphBorders(paragraph.borders);\n if (bordersXml) {\n children.push(bordersXml);\n }\n }\n if (paragraph.shading) {\n const shadingXml = serializeParagraphShading(paragraph.shading);\n if (shadingXml) {\n children.push(shadingXml);\n }\n }\n if (paragraph.bidi) {\n children.push(\"<w:bidi/>\");\n }\n if (paragraph.suppressLineNumbers) {\n children.push(\"<w:suppressLineNumbers/>\");\n }\n if (paragraph.cnfStyle) {\n children.push(`<w:cnfStyle w:val=\"${escapeAttribute(paragraph.cnfStyle)}\"/>`);\n }\n if (paragraph.tabStops && paragraph.tabStops.length > 0) {\n const tabsXml = paragraph.tabStops.map((tab) => {\n const leaderAttr = tab.leader ? ` w:leader=\"${tab.leader}\"` : \"\";\n return `<w:tab w:val=\"${tab.align}\" w:pos=\"${tab.position}\"${leaderAttr}/>`;\n }).join(\"\");\n children.push(`<w:tabs>${tabsXml}</w:tabs>`);\n }\n\n if (children.length === 0) return \"\";\n return `<w:pPr>${children.join(\"\")}</w:pPr>`;\n}\n\nfunction buildTablePropertiesXml(table: TableNode): string {\n const children: string[] = [];\n if (table.styleId) {\n children.push(`<w:tblStyle w:val=\"${escapeAttribute(table.styleId)}\"/>`);\n }\n if (table.tblLook) {\n const attrs: string[] = [];\n if (table.tblLook.val) {\n attrs.push(`w:val=\"${escapeAttribute(table.tblLook.val)}\"`);\n }\n for (const [key, attr] of [\n [\"firstRow\", \"w:firstRow\"],\n [\"lastRow\", \"w:lastRow\"],\n [\"firstColumn\", \"w:firstColumn\"],\n [\"lastColumn\", \"w:lastColumn\"],\n [\"noHBand\", \"w:noHBand\"],\n [\"noVBand\", \"w:noVBand\"],\n ] as const) {\n const value = table.tblLook[key];\n if (value !== undefined) {\n attrs.push(`${attr}=\"${value ? \"1\" : \"0\"}\"`);\n }\n }\n if (attrs.length > 0) {\n children.push(`<w:tblLook ${attrs.join(\" \")}/>`);\n }\n }\n return children.length > 0 ? `<w:tblPr>${children.join(\"\")}</w:tblPr>` : \"\";\n}\n\nfunction serializeParagraphBorders(borders: ParagraphNode[\"borders\"]): string {\n if (!borders) {\n return \"\";\n }\n const parts: string[] = [];\n for (const [name, border] of [\n [\"top\", borders.top],\n [\"left\", borders.left],\n [\"bottom\", borders.bottom],\n [\"right\", borders.right],\n [\"bar\", borders.bar],\n [\"between\", borders.between],\n ] as const) {\n const xml = serializeBorder(name, border);\n if (xml) {\n parts.push(xml);\n }\n }\n return parts.length > 0 ? `<w:pBdr>${parts.join(\"\")}</w:pBdr>` : \"\";\n}\n\nfunction serializeBorder(name: string, border: BorderSpec | undefined): string {\n if (!border) {\n return \"\";\n }\n const attrs: string[] = [];\n if (border.value) attrs.push(`w:val=\"${escapeAttribute(border.value)}\"`);\n if (border.size !== undefined) attrs.push(`w:sz=\"${border.size}\"`);\n if (border.space !== undefined) attrs.push(`w:space=\"${border.space}\"`);\n if (border.color) attrs.push(`w:color=\"${escapeAttribute(border.color)}\"`);\n return attrs.length > 0 ? `<w:${name} ${attrs.join(\" \")}/>` : \"\";\n}\n\nfunction serializeParagraphShading(shading: ParagraphNode[\"shading\"]): string {\n if (!shading) {\n return \"\";\n }\n const attrs: string[] = [];\n if (shading.val) attrs.push(`w:val=\"${escapeAttribute(shading.val)}\"`);\n if (shading.color) attrs.push(`w:color=\"${escapeAttribute(shading.color)}\"`);\n if (shading.fill) attrs.push(`w:fill=\"${escapeAttribute(shading.fill)}\"`);\n return attrs.length > 0 ? `<w:shd ${attrs.join(\" \")}/>` : \"\";\n}\n\nfunction serializeRunPropertiesFromMarks(marks: TextMark[] | undefined): string {\n return serializeRunProperties(marks);\n}\n\nfunction serializeParagraph(\n paragraph: ParagraphNode,\n state: SerializationState,\n cursor: number,\n paragraphIndex: number,\n): ParagraphSerializationResult {\n let xml = \"<w:p>\";\n const boundaries = new Map<number, number>();\n const paragraphStart = 0;\n const paragraphStartTagEnd = xml.length;\n boundaries.set(cursor, paragraphStartTagEnd);\n\n let paragraphPropertiesStart: number | undefined;\n let paragraphPropertiesEnd: number | undefined;\n\n const paragraphPropertiesXml = buildParagraphPropertiesXml(paragraph);\n if (paragraphPropertiesXml.length > 0) {\n paragraphPropertiesStart = xml.length;\n xml += paragraphPropertiesXml;\n paragraphPropertiesEnd = xml.length;\n }\n\n const children = serializeParagraphChildren(paragraph.children, state, cursor, xml.length);\n xml += children.xml;\n const contentEmpty = children.xml.length === 0;\n if (contentEmpty) {\n xml += \"<w:r><w:t></w:t></w:r>\";\n }\n const paragraphEndTagStart = xml.length;\n xml += \"</w:p>\";\n\n if (!children.boundaries.has(children.cursor)) {\n children.boundaries.set(children.cursor, paragraphEndTagStart);\n }\n\n return {\n xml,\n nextCursor: children.cursor,\n boundary: {\n paragraphIndex,\n start: cursor,\n end: children.cursor,\n boundaries: children.boundaries,\n paragraphStart,\n paragraphStartTagEnd,\n paragraphEndTagStart,\n paragraphEnd: xml.length,\n ...(paragraphPropertiesStart !== undefined\n ? { paragraphPropertiesStart }\n : {}),\n ...(paragraphPropertiesEnd !== undefined ? { paragraphPropertiesEnd } : {}),\n },\n };\n}\n\nfunction serializeParagraphChildren(\n children: InlineNode[],\n state: SerializationState,\n cursor: number,\n xmlOffset: number,\n): InlineSerializationResult {\n const pieces: string[] = [];\n const boundaries = new Map<number, number>();\n let nextCursor = cursor;\n let nextOffset = xmlOffset;\n boundaries.set(nextCursor, nextOffset);\n\n for (const child of children) {\n const result = serializeInlineNode(child, state, nextCursor, nextOffset);\n pieces.push(result.xml);\n for (const [position, index] of result.boundaries) {\n boundaries.set(position, index);\n }\n nextCursor = result.cursor;\n nextOffset += result.xml.length;\n }\n\n return {\n xml: pieces.join(\"\"),\n cursor: nextCursor,\n boundaries,\n };\n}\n\ntype RunPiece =\n | { kind: \"text\"; text: string; marks?: TextMark[] }\n | { kind: \"tab\" }\n | { kind: \"hard_break\" };\n\nfunction serializeRunPiece(piece: RunPiece): string {\n switch (piece.kind) {\n case \"text\":\n return serializeText(piece.text);\n case \"tab\":\n return \"<w:tab/>\";\n case \"hard_break\":\n return \"<w:br/>\";\n }\n}\n\nfunction serializeText(text: string): string {\n const preserve = requiresPreservedSpace(text) ? ` xml:space=\"preserve\"` : \"\";\n return `<w:t${preserve}>${escapeXml(text)}</w:t>`;\n}\n\nfunction serializeInlineNode(\n node: InlineNode,\n state: SerializationState,\n cursor: number,\n xmlOffset: number,\n): InlineSerializationResult {\n switch (node.type) {\n case \"text\": {\n const xml = serializeRun({\n kind: \"text\",\n text: node.text,\n ...(node.marks && node.marks.length > 0 ? { marks: node.marks } : {}),\n });\n const boundaries = new Map<number, number>();\n boundaries.set(cursor, xmlOffset);\n boundaries.set(cursor + Array.from(node.text).length, xmlOffset + xml.length);\n return {\n xml,\n cursor: cursor + Array.from(node.text).length,\n boundaries,\n };\n }\n case \"tab\": {\n const xml = serializeRun({ kind: \"tab\" });\n const boundaries = new Map<number, number>();\n boundaries.set(cursor, xmlOffset);\n boundaries.set(cursor + 1, xmlOffset + xml.length);\n return {\n xml,\n cursor: cursor + 1,\n boundaries,\n };\n }\n case \"column_break\": {\n const xml = `<w:r><w:br w:type=\"column\"/></w:r>`;\n const boundaries = new Map<number, number>();\n boundaries.set(cursor, xmlOffset);\n boundaries.set(cursor + 1, xmlOffset + xml.length);\n return {\n xml,\n cursor: cursor + 1,\n boundaries,\n };\n }\n case \"hard_break\": {\n const xml = serializeRun({ kind: \"hard_break\" });\n const boundaries = new Map<number, number>();\n boundaries.set(cursor, xmlOffset);\n boundaries.set(cursor + 1, xmlOffset + xml.length);\n return {\n xml,\n cursor: cursor + 1,\n boundaries,\n };\n }\n case \"symbol\": {\n const xml = serializeTableInlineNode(node, state);\n const boundaries = new Map<number, number>();\n boundaries.set(cursor, xmlOffset);\n boundaries.set(cursor + 1, xmlOffset + xml.length);\n return {\n xml,\n cursor: cursor + 1,\n boundaries,\n };\n }\n case \"image\": {\n const xml = serializeImageNode(node, state);\n const boundaries = new Map<number, number>();\n boundaries.set(cursor, xmlOffset);\n boundaries.set(cursor + 1, xmlOffset + xml.length);\n return {\n xml,\n cursor: cursor + 1,\n boundaries,\n };\n }\n case \"opaque_inline\": {\n const xml = lookupOpaqueXml(node.fragmentId, state);\n const boundaries = new Map<number, number>();\n boundaries.set(cursor, xmlOffset);\n boundaries.set(cursor + 1, xmlOffset + xml.length);\n return {\n xml,\n cursor: cursor + 1,\n boundaries,\n };\n }\n case \"chart_preview\":\n case \"smartart_preview\":\n case \"shape\":\n case \"wordart\":\n case \"vml_shape\": {\n // Reattach original XML unchanged for lossless round-trip.\n const xml = node.rawXml;\n const boundaries = new Map<number, number>();\n boundaries.set(cursor, xmlOffset);\n boundaries.set(cursor + 1, xmlOffset + xml.length);\n return {\n xml,\n cursor: cursor + 1,\n boundaries,\n };\n }\n case \"hyperlink\": {\n const hyperlinkOpen = node.href.startsWith(\"#\")\n ? `<w:hyperlink w:anchor=\"${escapeAttribute(node.href.slice(1))}\">`\n : (() => {\n const relationshipId = `rIdHyperlink${state.nextHyperlinkRelationshipIndex}`;\n state.nextHyperlinkRelationshipIndex += 1;\n state.relationships.push({\n id: relationshipId,\n type: HYPERLINK_RELATIONSHIP_TYPE,\n target: node.href,\n targetMode: \"external\",\n });\n state.retainedRelationshipIds.add(relationshipId);\n return `<w:hyperlink r:id=\"${relationshipId}\">`;\n })();\n const hyperlinkClose = \"</w:hyperlink>\";\n const boundaries = new Map<number, number>();\n let nextCursor = cursor;\n let nextOffset = xmlOffset + hyperlinkOpen.length;\n boundaries.set(cursor, nextOffset);\n const children: string[] = [];\n\n for (const child of node.children) {\n const result = serializeInlineNode(child, state, nextCursor, nextOffset);\n children.push(result.xml);\n for (const [position, index] of result.boundaries) {\n boundaries.set(position, index);\n }\n nextCursor = result.cursor;\n nextOffset += result.xml.length;\n }\n\n boundaries.set(nextCursor, nextOffset);\n return {\n xml: `${hyperlinkOpen}${children.join(\"\")}${hyperlinkClose}`,\n cursor: nextCursor,\n boundaries,\n };\n }\n }\n}\n\nfunction serializeImageNode(\n node: Extract<InlineNode, { type: \"image\" }>,\n state: SerializationState,\n): string {\n const placementXml = typeof node.placementXml === \"string\" ? node.placementXml.trim() : \"\";\n if (placementXml.length > 0) {\n return placementXml.startsWith(\"<w:r\") ? placementXml : `<w:r>${placementXml}</w:r>`;\n }\n\n const mediaItem = state.media.items[node.mediaId];\n if (mediaItem?.relationshipId && state.existingRelationshipMap.has(mediaItem.relationshipId)) {\n const altText = node.altText ?? mediaItem.altText ?? mediaItem.filename;\n return `<w:r><w:drawing><wp:inline xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\"><wp:extent cx=\"9525\" cy=\"9525\"/><wp:docPr id=\"1\" name=\"${escapeAttribute(mediaItem.filename)}\" descr=\"${escapeAttribute(altText ?? \"\")}\"/><wp:cNvGraphicFramePr/><a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"><pic:pic><pic:nvPicPr><pic:cNvPr id=\"0\" name=\"${escapeAttribute(mediaItem.filename)}\"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed=\"${escapeAttribute(mediaItem.relationshipId)}\"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"9525\" cy=\"9525\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>`;\n }\n\n return serializeRun({\n kind: \"text\",\n text: node.altText ?? \"[Image]\",\n });\n}\n\nfunction serializeRun(piece: RunPiece): string {\n const marks = piece.kind === \"text\" ? piece.marks : undefined;\n const properties = serializeRunProperties(marks);\n const content = serializeRunPiece(piece);\n return `<w:r>${properties}${content}</w:r>`;\n}\n\nfunction serializeRunProperties(marks: TextMark[] | undefined): string {\n if (!marks || marks.length === 0) {\n return \"\";\n }\n\n const markParts: string[] = [];\n for (const mark of marks) {\n switch (mark.type) {\n case \"bold\":\n markParts.push(\"<w:b/>\");\n break;\n case \"italic\":\n markParts.push(\"<w:i/>\");\n break;\n case \"underline\":\n markParts.push(`<w:u w:val=\"single\"/>`);\n break;\n case \"strikethrough\":\n markParts.push(\"<w:strike/>\");\n break;\n case \"doubleStrikethrough\":\n markParts.push(\"<w:dstrike/>\");\n break;\n case \"vanish\":\n markParts.push(\"<w:vanish/>\");\n break;\n case \"lang\":\n markParts.push(`<w:lang w:val=\"${escapeAttribute(mark.val)}\"/>`);\n break;\n case \"backgroundColor\":\n markParts.push(\n `<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"${escapeAttribute(mark.color)}\"/>`,\n );\n break;\n case \"charSpacing\":\n markParts.push(`<w:spacing w:val=\"${mark.val}\"/>`);\n break;\n case \"kerning\":\n markParts.push(`<w:kern w:val=\"${mark.val}\"/>`);\n break;\n case \"emboss\":\n markParts.push(\"<w:emboss/>\");\n break;\n case \"imprint\":\n markParts.push(\"<w:imprint/>\");\n break;\n case \"shadow\":\n markParts.push(\"<w:shadow/>\");\n break;\n case \"position\":\n markParts.push(`<w:position w:val=\"${mark.val}\"/>`);\n break;\n case \"textFill\":\n markParts.push(mark.xml);\n break;\n }\n }\n\n const children = markParts.join(\"\");\n return children.length > 0 ? `<w:rPr>${children}</w:rPr>` : \"\";\n}\n\nfunction requiresPreservedSpace(text: string): boolean {\n return /^\\s/.test(text) || /\\s$/.test(text) || text.includes(\" \");\n}\n\nfunction lookupOpaqueXml(fragmentId: string, state: SerializationState): string {\n const fragment = getOpaqueFragment(state.preservation, fragmentId);\n if (!fragment || fragment.payloadKind !== \"xml-subtree\") {\n throw new Error(`Missing preserved OOXML fragment ${fragmentId} during serialization.`);\n }\n\n retainRelationshipsForFragment(\n fragment,\n state.relationships,\n state.existingRelationshipMap,\n state.retainedRelationshipIds,\n );\n return fragment.payloadReference;\n}\n\nfunction cloneRelationship(relationship: OpcRelationship): OpcRelationship {\n return { ...relationship };\n}\n\nfunction looksLikeSectionPropertiesXml(xml: string): boolean {\n return /^<[^>]*:?sectPr(?:\\s|>|\\/)/.test(xml.trim());\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction escapeAttribute(value: string): string {\n return escapeXml(value).replace(/\"/g, \""\");\n}\n\nfunction offsetParagraphBoundary(\n boundary: RevisionParagraphBoundary,\n offset: number,\n): RevisionParagraphBoundary {\n return {\n ...boundary,\n boundaries: new Map(\n [...boundary.boundaries.entries()].map(([position, index]) => [\n position,\n index + offset,\n ]),\n ),\n paragraphStart: boundary.paragraphStart + offset,\n paragraphStartTagEnd: boundary.paragraphStartTagEnd + offset,\n paragraphEndTagStart: boundary.paragraphEndTagStart + offset,\n paragraphEnd: boundary.paragraphEnd + offset,\n ...(boundary.paragraphPropertiesStart !== undefined\n ? { paragraphPropertiesStart: boundary.paragraphPropertiesStart + offset }\n : {}),\n ...(boundary.paragraphPropertiesEnd !== undefined\n ? { paragraphPropertiesEnd: boundary.paragraphPropertiesEnd + offset }\n : {}),\n ...(boundary.paragraphRunPropertiesStart !== undefined\n ? { paragraphRunPropertiesStart: boundary.paragraphRunPropertiesStart + offset }\n : {}),\n ...(boundary.paragraphRunPropertiesEnd !== undefined\n ? { paragraphRunPropertiesEnd: boundary.paragraphRunPropertiesEnd + offset }\n : {}),\n };\n}\n\nfunction serializeDocumentAttributes(\n attributes: Record<string, string> | undefined,\n content?: DocumentRootNode,\n): string {\n const merged = {\n \"xmlns:r\": \"http://schemas.openxmlformats.org/officeDocument/2006/relationships\",\n \"xmlns:w\": \"http://schemas.openxmlformats.org/wordprocessingml/2006/main\",\n ...(content && documentNeedsW14Namespace(content)\n ? { \"xmlns:w14\": \"http://schemas.microsoft.com/office/word/2010/wordml\" }\n : {}),\n ...(attributes ?? {}),\n };\n\n return Object.entries(merged)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join(\"\");\n}\n\nfunction documentNeedsW14Namespace(content: DocumentRootNode): boolean {\n const blockQueue = [...content.children];\n while (blockQueue.length > 0) {\n const block = blockQueue.shift();\n if (!block) {\n continue;\n }\n if (block.type === \"paragraph\") {\n for (const child of block.children) {\n if (\n (child.type === \"text\" || child.type === \"symbol\") &&\n child.marks?.some((mark) => mark.type === \"textFill\")\n ) {\n return true;\n }\n }\n continue;\n }\n if (block.type === \"table\") {\n for (const row of block.rows) {\n for (const cell of row.cells) {\n blockQueue.push(...cell.children);\n }\n }\n }\n }\n return false;\n}\n","export interface XmlElementNode {\n type: \"element\";\n name: string;\n attributes: Record<string, string>;\n children: XmlNode[];\n start: number;\n end: number;\n openingTagEnd: number;\n closingTagStart: number;\n}\n\nexport interface XmlTextNode {\n type: \"text\";\n text: string;\n start: number;\n end: number;\n}\n\nexport type XmlNode = XmlElementNode | XmlTextNode;\n\nexport interface RevisionParagraphBoundary {\n paragraphIndex: number;\n start: number;\n end: number;\n boundaries: Map<number, number>;\n paragraphStart: number;\n paragraphStartTagEnd: number;\n paragraphEndTagStart: number;\n paragraphEnd: number;\n paragraphPropertiesStart?: number;\n paragraphPropertiesEnd?: number;\n paragraphRunPropertiesStart?: number;\n paragraphRunPropertiesEnd?: number;\n}\n\nexport function mapRevisionBoundaries(\n documentXml: string,\n): RevisionParagraphBoundary[] {\n const root = parseXmlWithPositions(documentXml);\n const documentElement = findRequiredChildElement(root, \"document\");\n const bodyElement = findRequiredChildElement(documentElement, \"body\");\n const paragraphs: RevisionParagraphBoundary[] = [];\n let cursor = 0;\n let paragraphIndex = -1;\n let previousWasParagraph = false;\n\n for (const child of bodyElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n if (localName(child.name) !== \"p\") {\n cursor += 1;\n previousWasParagraph = false;\n continue;\n }\n\n if (previousWasParagraph) {\n cursor += 1;\n }\n paragraphIndex += 1;\n const boundaries = new Map<number, number>();\n boundaries.set(cursor, child.openingTagEnd);\n\n const paragraphProperties = findChildElement(child, \"pPr\");\n const paragraphRunProperties = paragraphProperties\n ? findChildElement(paragraphProperties, \"rPr\")\n : undefined;\n\n walkStoryNodesForBoundaries(\n child.children,\n boundaries,\n () => cursor,\n (next) => {\n cursor = next;\n },\n );\n\n boundaries.set(cursor, child.closingTagStart);\n paragraphs.push({\n paragraphIndex,\n start: Math.min(...boundaries.keys()),\n end: Math.max(...boundaries.keys()),\n boundaries,\n paragraphStart: child.start,\n paragraphStartTagEnd: child.openingTagEnd,\n paragraphEndTagStart: child.closingTagStart,\n paragraphEnd: child.end,\n ...(paragraphProperties\n ? {\n paragraphPropertiesStart: paragraphProperties.start,\n paragraphPropertiesEnd: paragraphProperties.end,\n }\n : {}),\n ...(paragraphRunProperties\n ? {\n paragraphRunPropertiesStart: paragraphRunProperties.start,\n paragraphRunPropertiesEnd: paragraphRunProperties.end,\n }\n : {}),\n });\n previousWasParagraph = true;\n }\n\n return paragraphs;\n}\n\nfunction walkStoryNodesForBoundaries(\n nodes: XmlNode[],\n boundaries: Map<number, number>,\n getCursor: () => number,\n setCursor: (next: number) => void,\n): void {\n for (const node of nodes) {\n walkStoryNodeForBoundaries(node, boundaries, getCursor, setCursor);\n }\n}\n\nfunction walkStoryNodeForBoundaries(\n node: XmlNode,\n boundaries: Map<number, number>,\n getCursor: () => number,\n setCursor: (next: number) => void,\n): void {\n if (node.type !== \"element\") {\n return;\n }\n\n switch (localName(node.name)) {\n case \"pPr\":\n return;\n case \"r\":\n boundaries.set(getCursor(), node.start);\n for (const child of node.children) {\n walkStoryNodeForBoundaries(child, boundaries, getCursor, setCursor);\n }\n boundaries.set(getCursor(), node.end);\n return;\n case \"ins\":\n case \"del\":\n case \"moveFrom\":\n case \"moveTo\":\n case \"hyperlink\":\n case \"smartTag\":\n case \"sdtContent\":\n case \"customXml\":\n for (const child of node.children) {\n walkStoryNodeForBoundaries(child, boundaries, getCursor, setCursor);\n }\n return;\n case \"t\":\n case \"delText\":\n case \"instrText\":\n case \"delInstrText\": {\n const text = node.children\n .filter((child): child is XmlTextNode => child.type === \"text\")\n .map((child) => child.text)\n .join(\"\");\n if (text.length === 0) {\n return;\n }\n\n if (!boundaries.has(getCursor())) {\n boundaries.set(getCursor(), node.start);\n }\n setCursor(getCursor() + text.length);\n boundaries.set(getCursor(), node.end);\n return;\n }\n case \"tab\":\n case \"br\":\n case \"cr\":\n if (!boundaries.has(getCursor())) {\n boundaries.set(getCursor(), node.start);\n }\n setCursor(getCursor() + 1);\n boundaries.set(getCursor(), node.end);\n return;\n default:\n for (const child of node.children) {\n walkStoryNodeForBoundaries(child, boundaries, getCursor, setCursor);\n }\n }\n}\n\nexport function parseXmlWithPositions(xml: string): XmlElementNode {\n const root: XmlElementNode = {\n type: \"element\",\n name: \"__root__\",\n attributes: {},\n children: [],\n start: 0,\n end: xml.length,\n openingTagEnd: 0,\n closingTagStart: xml.length,\n };\n const stack: XmlElementNode[] = [root];\n let cursor = 0;\n\n while (cursor < xml.length) {\n if (xml.startsWith(\"<!--\", cursor)) {\n const end = xml.indexOf(\"-->\", cursor);\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<?\", cursor)) {\n const end = xml.indexOf(\"?>\", cursor);\n cursor = end >= 0 ? end + 2 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<![CDATA[\", cursor)) {\n const end = xml.indexOf(\"]]>\", cursor);\n const textEnd = end >= 0 ? end : xml.length;\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text: xml.slice(cursor + 9, textEnd),\n start: cursor,\n end: textEnd,\n });\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml[cursor] !== \"<\") {\n const nextTag = xml.indexOf(\"<\", cursor);\n const end = nextTag >= 0 ? nextTag : xml.length;\n const text = decodeXmlEntities(xml.slice(cursor, end));\n if (text.length > 0) {\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text,\n start: cursor,\n end,\n });\n }\n cursor = end;\n continue;\n }\n\n if (xml[cursor + 1] === \"/\") {\n const tagEnd = xml.indexOf(\">\", cursor);\n if (tagEnd < 0) {\n throw new Error(\"Malformed XML: unterminated closing tag.\");\n }\n\n const node = stack.pop();\n if (!node || stack.length === 0) {\n throw new Error(\"Malformed XML: unexpected closing tag.\");\n }\n\n node.closingTagStart = cursor;\n node.end = tagEnd + 1;\n cursor = tagEnd + 1;\n continue;\n }\n\n const tagEnd = xml.indexOf(\">\", cursor);\n if (tagEnd < 0) {\n throw new Error(\"Malformed XML: unterminated opening tag.\");\n }\n\n const rawTag = xml.slice(cursor + 1, tagEnd);\n const selfClosing = /\\/\\s*$/.test(rawTag);\n const normalizedTag = selfClosing ? rawTag.replace(/\\/\\s*$/, \"\") : rawTag;\n const parts = normalizedTag.trim().split(/\\s+/, 1);\n const name = parts[0];\n if (!name) {\n throw new Error(\"Malformed XML: empty tag name.\");\n }\n\n const attributes = parseAttributes(normalizedTag.slice(name.length));\n const node: XmlElementNode = {\n type: \"element\",\n name,\n attributes,\n children: [],\n start: cursor,\n end: selfClosing ? tagEnd + 1 : xml.length,\n openingTagEnd: tagEnd + 1,\n closingTagStart: tagEnd + 1,\n };\n\n stack[stack.length - 1]?.children.push(node);\n cursor = tagEnd + 1;\n\n if (!selfClosing) {\n stack.push(node);\n }\n }\n\n if (stack.length !== 1) {\n throw new Error(\"Malformed XML: unclosed element.\");\n }\n\n return root;\n}\n\nexport function findRequiredChildElement(\n node: XmlElementNode,\n childLocalName: string,\n): XmlElementNode {\n const child = findChildElement(node, childLocalName);\n if (!child) {\n throw new Error(`Expected <${childLocalName}> element.`);\n }\n\n return child;\n}\n\nexport function findChildElement(\n node: XmlElementNode,\n childLocalName: string,\n): XmlElementNode | undefined {\n return node.children.find(\n (entry): entry is XmlElementNode =>\n entry.type === \"element\" && localName(entry.name) === childLocalName,\n );\n}\n\nexport function localName(name: string): string {\n const separatorIndex = name.indexOf(\":\");\n return separatorIndex >= 0 ? name.slice(separatorIndex + 1) : name;\n}\n\nfunction parseAttributes(source: string): Record<string, string> {\n const attributes: Record<string, string> = {};\n const attributePattern = /([A-Za-z_][A-Za-z0-9:._-]*)\\s*=\\s*(\"([^\"]*)\"|'([^']*)')/g;\n\n for (const match of source.matchAll(attributePattern)) {\n const key = match[1];\n if (!key) {\n continue;\n }\n\n const rawValue = match[3] ?? match[4] ?? \"\";\n attributes[key] = decodeXmlEntities(rawValue);\n }\n\n return attributes;\n}\n\nfunction decodeXmlEntities(value: string): string {\n return value\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/"/g, \"\\\"\")\n .replace(/'/g, \"'\")\n .replace(/&/g, \"&\");\n}\n","import { createDetachedAnchor } from \"../../core/selection/mapping.ts\";\nimport {\n createRevisionRecord,\n type RevisionRecord,\n} from \"../../review/store/revision-store.ts\";\nimport {\n createRevisionRangeAnchor,\n type MoveData,\n type PropertyChangeData,\n type RevisionKind,\n} from \"../../review/store/revision-types.ts\";\nimport {\n findChildElement,\n findRequiredChildElement,\n localName,\n mapRevisionBoundaries,\n parseXmlWithPositions,\n type RevisionParagraphBoundary,\n type XmlElementNode,\n type XmlNode,\n} from \"./revision-boundaries.ts\";\n\nexport interface PreservedRevisionMarkup {\n revisionId: string;\n rawXml: string;\n xmlStart: number;\n xmlEnd: number;\n originalRevisionType: string;\n paragraphIndex?: number;\n containerXmlStart?: number;\n containerXmlEnd?: number;\n beforeContainerXml?: string;\n}\n\nexport interface RevisionImportDiagnostic {\n revisionId: string;\n code:\n | \"preserve_only_move_revision\"\n | \"preserve_only_formatting_revision\"\n | \"nested_revision_preserve_only\"\n | \"ambiguous_revision_anchor\";\n message: string;\n featureClass: \"preserve-only\";\n}\n\nexport interface ParsedRevisionsResult {\n revisions: RevisionRecord[];\n preservedMarkup: PreservedRevisionMarkup[];\n diagnostics: RevisionImportDiagnostic[];\n boundaries: RevisionParagraphBoundary[];\n}\n\ninterface ParseState {\n documentXml: string;\n boundaries: RevisionParagraphBoundary[];\n revisions: RevisionRecord[];\n preservedMarkup: PreservedRevisionMarkup[];\n diagnostics: RevisionImportDiagnostic[];\n nextGeneratedIndex: number;\n}\n\ninterface RevisionMetadata {\n revisionId: string;\n ooxmlRevisionId?: string;\n authorId: string;\n createdAt: string;\n}\n\nconst SUPPORTED_CONTAINER_TYPES = new Set([\"ins\", \"del\"]);\nconst PRESERVE_ONLY_CONTAINER_TYPES = new Set([\"moveFrom\", \"moveTo\"]);\nconst FORMATTING_REVISION_TYPES = new Set([\"rPrChange\", \"pPrChange\"]);\n\nexport function parseRevisionsFromDocumentXml(\n documentXml: string,\n): ParsedRevisionsResult {\n const root = parseXmlWithPositions(documentXml);\n const documentElement = findRequiredChildElement(root, \"document\");\n const bodyElement = findRequiredChildElement(documentElement, \"body\");\n const boundaries = mapRevisionBoundaries(documentXml);\n const state: ParseState = {\n documentXml,\n boundaries,\n revisions: [],\n preservedMarkup: [],\n diagnostics: [],\n nextGeneratedIndex: 1,\n };\n\n let paragraphIndex = -1;\n let cursor = 0;\n let previousWasParagraph = false;\n\n for (const child of bodyElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const childType = localName(child.name);\n\n if (childType !== \"p\") {\n if (childType === \"tbl\") {\n parseTblPropertyRevisions(child, cursor, state);\n } else if (childType === \"sectPr\") {\n parseSectPrRevisions(child, cursor, state);\n }\n cursor += 1;\n previousWasParagraph = false;\n continue;\n }\n\n if (previousWasParagraph) {\n cursor += 1;\n }\n paragraphIndex += 1;\n const paragraphBoundary = boundaries[paragraphIndex];\n if (!paragraphBoundary) {\n continue;\n }\n\n parseParagraphMarkRevisions(child, paragraphBoundary, state);\n walkParagraphContent(child.children, paragraphIndex, state, () => cursor, (next) => {\n cursor = next;\n });\n previousWasParagraph = true;\n }\n\n return {\n revisions: state.revisions,\n preservedMarkup: state.preservedMarkup.sort((left, right) => left.xmlStart - right.xmlStart),\n diagnostics: state.diagnostics,\n boundaries,\n };\n}\n\nfunction parseParagraphMarkRevisions(\n paragraph: XmlElementNode,\n boundary: RevisionParagraphBoundary,\n state: ParseState,\n): void {\n const paragraphProperties = findChildElement(paragraph, \"pPr\");\n const paragraphRunProperties = paragraphProperties\n ? findChildElement(paragraphProperties, \"rPr\")\n : undefined;\n\n if (!paragraphProperties) {\n return;\n }\n\n const paragraphRange =\n boundary.start === boundary.end\n ? createRevisionRangeAnchor(boundary.end, boundary.end)\n : createRevisionRangeAnchor(boundary.start, boundary.end);\n\n for (const child of paragraphProperties.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const type = localName(child.name);\n if (type === \"pPrChange\") {\n const metadata = readRevisionMetadata(child, state, \"formatting\");\n const innerPPr = findChildElement(child, \"pPr\");\n const propertyChangeData: PropertyChangeData = {\n xmlTag: \"pPrChange\",\n beforeXml: innerPPr ? state.documentXml.slice(innerPPr.start, innerPPr.end) : \"\",\n };\n state.revisions.push(\n createRevisionRecord({\n revisionId: metadata.revisionId,\n kind: \"formatting\",\n anchor: paragraphRange,\n authorId: metadata.authorId,\n createdAt: metadata.createdAt,\n metadata: {\n source: \"import\",\n originalRevisionType: \"pPrChange\",\n ooxmlRevisionId: metadata.ooxmlRevisionId,\n preserveOnlyReason: \"Imported preserve-only revision.\",\n propertyChangeData,\n },\n }),\n );\n state.preservedMarkup.push({\n revisionId: metadata.revisionId,\n rawXml: state.documentXml.slice(child.start, child.end),\n xmlStart: child.start,\n xmlEnd: child.end,\n originalRevisionType: \"pPrChange\",\n });\n state.diagnostics.push({\n revisionId: metadata.revisionId,\n code: \"preserve_only_formatting_revision\",\n message: \"Paragraph property revisions remain preserve-only for Wave 6.\",\n featureClass: \"preserve-only\",\n });\n }\n }\n\n if (!paragraphRunProperties) {\n return;\n }\n\n for (const child of paragraphRunProperties.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const type = localName(child.name);\n if (!SUPPORTED_CONTAINER_TYPES.has(type)) {\n continue;\n }\n\n const metadata = readRevisionMetadata(child, state, type);\n state.revisions.push(\n createRevisionRecord({\n revisionId: metadata.revisionId,\n kind: type === \"ins\" ? \"insertion\" : \"deletion\",\n anchor: createRevisionRangeAnchor(boundary.end, boundary.end),\n authorId: metadata.authorId,\n createdAt: metadata.createdAt,\n metadata: {\n source: \"import\",\n importedRevisionForm:\n type === \"ins\" ? \"paragraph-insertion\" : \"paragraph-deletion\",\n originalRevisionType: `paragraph-${type}`,\n ooxmlRevisionId: metadata.ooxmlRevisionId,\n },\n }),\n );\n state.preservedMarkup.push({\n revisionId: metadata.revisionId,\n rawXml: state.documentXml.slice(child.start, child.end),\n xmlStart: child.start,\n xmlEnd: child.end,\n originalRevisionType: `paragraph-${type}`,\n paragraphIndex: boundary.paragraphIndex,\n });\n }\n}\n\nfunction walkParagraphContent(\n nodes: XmlNode[],\n paragraphIndex: number,\n state: ParseState,\n getCursor: () => number,\n setCursor: (next: number) => void,\n): void {\n for (const node of nodes) {\n walkContentNode(node, paragraphIndex, state, getCursor, setCursor);\n }\n}\n\nfunction walkContentNode(\n node: XmlNode,\n paragraphIndex: number,\n state: ParseState,\n getCursor: () => number,\n setCursor: (next: number) => void,\n): void {\n if (node.type !== \"element\") {\n return;\n }\n\n const type = localName(node.name);\n if (type === \"pPr\") {\n return;\n }\n\n if (type === \"r\") {\n parseRunFormattingRevisions(node, paragraphIndex, state, getCursor());\n for (const child of node.children) {\n walkContentNode(child, paragraphIndex, state, getCursor, setCursor);\n }\n return;\n }\n\n if (SUPPORTED_CONTAINER_TYPES.has(type) || PRESERVE_ONLY_CONTAINER_TYPES.has(type)) {\n const start = getCursor();\n const length = measureStoryLength(node);\n const end = start + length;\n const hasNestedRevision = containsNestedRevision(node);\n const metadata = readRevisionMetadata(\n node,\n state,\n type === \"moveFrom\" || type === \"moveTo\" ? \"move\" : type,\n );\n\n if (hasNestedRevision) {\n const nestedKind = type === \"ins\" ? \"insertion\" : type === \"del\" ? \"deletion\" : \"move\";\n state.revisions.push(\n createRevisionRecord({\n revisionId: metadata.revisionId,\n kind: nestedKind,\n anchor:\n length > 0\n ? createRevisionRangeAnchor(start, end)\n : createDetachedAnchor({ from: start, to: end }, \"importAmbiguity\"),\n authorId: metadata.authorId,\n createdAt: metadata.createdAt,\n metadata: {\n source: \"import\",\n originalRevisionType: type,\n ooxmlRevisionId: metadata.ooxmlRevisionId,\n preserveOnlyReason: \"Nested revision markup remains preserve-only.\",\n },\n }),\n );\n state.preservedMarkup.push({\n revisionId: metadata.revisionId,\n rawXml: state.documentXml.slice(node.start, node.end),\n xmlStart: node.start,\n xmlEnd: node.end,\n originalRevisionType: type,\n });\n state.diagnostics.push({\n revisionId: metadata.revisionId,\n code: \"nested_revision_preserve_only\",\n message: \"Nested revision markup remains preserve-only and is exported unchanged.\",\n featureClass: \"preserve-only\",\n });\n advanceCursor(node, setCursor, getCursor);\n return;\n }\n\n if (type === \"moveFrom\" || type === \"moveTo\") {\n const moveData: MoveData = {\n moveId: metadata.ooxmlRevisionId ?? `generated-${metadata.revisionId}`,\n direction: type === \"moveFrom\" ? \"from\" : \"to\",\n };\n state.revisions.push(\n createRevisionRecord({\n revisionId: metadata.revisionId,\n kind: \"move\",\n anchor:\n length > 0\n ? createRevisionRangeAnchor(start, end)\n : createDetachedAnchor({ from: start, to: end }, \"importAmbiguity\"),\n authorId: metadata.authorId,\n createdAt: metadata.createdAt,\n metadata: {\n source: \"import\",\n originalRevisionType: type,\n ooxmlRevisionId: metadata.ooxmlRevisionId,\n preserveOnlyReason: \"Imported preserve-only revision.\",\n moveData,\n },\n }),\n );\n state.preservedMarkup.push({\n revisionId: metadata.revisionId,\n rawXml: state.documentXml.slice(node.start, node.end),\n xmlStart: node.start,\n xmlEnd: node.end,\n originalRevisionType: type,\n });\n state.diagnostics.push({\n revisionId: metadata.revisionId,\n code: \"preserve_only_move_revision\",\n message: \"Tracked move revisions remain preserve-only for Wave 6.\",\n featureClass: \"preserve-only\",\n });\n advanceCursor(node, setCursor, getCursor);\n return;\n }\n\n state.revisions.push(\n createRevisionRecord({\n revisionId: metadata.revisionId,\n kind: type === \"ins\" ? \"insertion\" : \"deletion\",\n anchor: createRevisionRangeAnchor(start, end),\n authorId: metadata.authorId,\n createdAt: metadata.createdAt,\n metadata: {\n source: \"import\",\n importedRevisionForm:\n type === \"ins\" ? \"run-insertion\" : \"run-deletion\",\n originalRevisionType: type,\n ooxmlRevisionId: metadata.ooxmlRevisionId,\n },\n }),\n );\n state.preservedMarkup.push({\n revisionId: metadata.revisionId,\n rawXml: state.documentXml.slice(node.start, node.end),\n xmlStart: node.start,\n xmlEnd: node.end,\n originalRevisionType: type,\n });\n advanceCursor(node, setCursor, getCursor);\n return;\n }\n\n switch (type) {\n case \"t\":\n case \"delText\":\n case \"instrText\":\n case \"delInstrText\": {\n const text = node.children\n .filter((child): child is XmlElementNode[\"children\"][number] & { type: \"text\" } => child.type === \"text\")\n .map((child) => child.text)\n .join(\"\");\n setCursor(getCursor() + text.length);\n return;\n }\n case \"tab\":\n case \"br\":\n case \"cr\":\n setCursor(getCursor() + 1);\n return;\n default:\n for (const child of node.children) {\n walkContentNode(child, paragraphIndex, state, getCursor, setCursor);\n }\n }\n}\n\nfunction parseRunFormattingRevisions(\n run: XmlElementNode,\n _paragraphIndex: number,\n state: ParseState,\n runStart: number,\n): void {\n const runProperties = findChildElement(run, \"rPr\");\n if (!runProperties) {\n return;\n }\n\n const runLength = measureStoryLength(run);\n const anchor =\n runLength > 0\n ? createRevisionRangeAnchor(runStart, runStart + runLength)\n : createDetachedAnchor({ from: runStart, to: runStart }, \"importAmbiguity\");\n\n for (const child of runProperties.children) {\n if (child.type !== \"element\" || !FORMATTING_REVISION_TYPES.has(localName(child.name))) {\n continue;\n }\n\n const childLocalName = localName(child.name) as \"rPrChange\" | \"pPrChange\";\n const metadata = readRevisionMetadata(child, state, \"formatting\");\n const innerRPr = findChildElement(child, \"rPr\");\n const propertyChangeData: PropertyChangeData = {\n xmlTag: childLocalName === \"rPrChange\" ? \"rPrChange\" : \"pPrChange\",\n beforeXml: innerRPr ? state.documentXml.slice(innerRPr.start, innerRPr.end) : \"\",\n };\n state.revisions.push(\n createRevisionRecord({\n revisionId: metadata.revisionId,\n kind: \"formatting\",\n anchor,\n authorId: metadata.authorId,\n createdAt: metadata.createdAt,\n metadata: {\n source: \"import\",\n originalRevisionType: childLocalName,\n ooxmlRevisionId: metadata.ooxmlRevisionId,\n preserveOnlyReason: \"Imported preserve-only revision.\",\n propertyChangeData,\n },\n }),\n );\n state.preservedMarkup.push({\n revisionId: metadata.revisionId,\n rawXml: state.documentXml.slice(child.start, child.end),\n xmlStart: child.start,\n xmlEnd: child.end,\n originalRevisionType: childLocalName,\n });\n state.diagnostics.push({\n revisionId: metadata.revisionId,\n code: \"preserve_only_formatting_revision\",\n message: \"Formatting revisions remain preserve-only for Wave 6.\",\n featureClass: \"preserve-only\",\n });\n }\n}\n\nfunction parseTblPropertyRevisions(\n table: XmlElementNode,\n position: number,\n state: ParseState,\n): void {\n const tblPr = findChildElement(table, \"tblPr\");\n if (!tblPr) {\n return;\n }\n\n const tblPrChange = findChildElement(tblPr, \"tblPrChange\");\n if (!tblPrChange) {\n return;\n }\n\n const metadata = readRevisionMetadata(tblPrChange, state, \"property-change\");\n const innerTblPr = findChildElement(tblPrChange, \"tblPr\");\n const beforeXml = innerTblPr ? state.documentXml.slice(innerTblPr.start, innerTblPr.end) : \"\";\n const propertyChangeData: PropertyChangeData = { xmlTag: \"tblPrChange\", beforeXml };\n\n state.revisions.push(\n createRevisionRecord({\n revisionId: metadata.revisionId,\n kind: \"property-change\",\n anchor: createRevisionRangeAnchor(position, position),\n authorId: metadata.authorId,\n createdAt: metadata.createdAt,\n metadata: {\n source: \"import\",\n originalRevisionType: \"tblPrChange\",\n ooxmlRevisionId: metadata.ooxmlRevisionId,\n propertyChangeData,\n },\n }),\n );\n state.preservedMarkup.push({\n revisionId: metadata.revisionId,\n rawXml: state.documentXml.slice(tblPrChange.start, tblPrChange.end),\n xmlStart: tblPrChange.start,\n xmlEnd: tblPrChange.end,\n originalRevisionType: \"tblPrChange\",\n containerXmlStart: tblPr.start,\n containerXmlEnd: tblPr.end,\n beforeContainerXml: beforeXml,\n });\n}\n\nfunction parseSectPrRevisions(\n sectPr: XmlElementNode,\n position: number,\n state: ParseState,\n): void {\n const sectPrChange = findChildElement(sectPr, \"sectPrChange\");\n if (!sectPrChange) {\n return;\n }\n\n const metadata = readRevisionMetadata(sectPrChange, state, \"property-change\");\n const innerSectPr = findChildElement(sectPrChange, \"sectPr\");\n const beforeXml = innerSectPr ? state.documentXml.slice(innerSectPr.start, innerSectPr.end) : \"\";\n const propertyChangeData: PropertyChangeData = { xmlTag: \"sectPrChange\", beforeXml };\n\n state.revisions.push(\n createRevisionRecord({\n revisionId: metadata.revisionId,\n kind: \"property-change\",\n anchor: createRevisionRangeAnchor(position, position),\n authorId: metadata.authorId,\n createdAt: metadata.createdAt,\n metadata: {\n source: \"import\",\n originalRevisionType: \"sectPrChange\",\n ooxmlRevisionId: metadata.ooxmlRevisionId,\n propertyChangeData,\n },\n }),\n );\n state.preservedMarkup.push({\n revisionId: metadata.revisionId,\n rawXml: state.documentXml.slice(sectPrChange.start, sectPrChange.end),\n xmlStart: sectPrChange.start,\n xmlEnd: sectPrChange.end,\n originalRevisionType: \"sectPrChange\",\n containerXmlStart: sectPr.start,\n containerXmlEnd: sectPr.end,\n beforeContainerXml: beforeXml,\n });\n}\n\nfunction readRevisionMetadata(\n node: XmlElementNode,\n state: ParseState,\n prefix: string,\n): RevisionMetadata {\n const rawId = node.attributes[\"w:id\"] ?? node.attributes.id;\n const ooxmlRevisionId = rawId ? rawId : undefined;\n const revisionId = rawId\n ? `revision:${sanitizeRevisionToken(prefix)}-${sanitizeRevisionToken(rawId)}`\n : `revision:${sanitizeRevisionToken(prefix)}-generated-${state.nextGeneratedIndex++}`;\n const authorId =\n node.attributes[\"w:author\"] ??\n node.attributes.author ??\n \"word:unknown-author\";\n const createdAt =\n normalizeImportedTimestamp(\n node.attributes[\"w:date\"] ?? node.attributes.date,\n ) ??\n \"1970-01-01T00:00:00.000Z\";\n\n return {\n revisionId,\n ooxmlRevisionId,\n authorId,\n createdAt,\n };\n}\n\nfunction normalizeImportedTimestamp(value: string | undefined): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const parsed = new Date(value);\n if (Number.isNaN(parsed.valueOf())) {\n return undefined;\n }\n\n return parsed.toISOString();\n}\n\nfunction sanitizeRevisionToken(value: string): string {\n const sanitized = value.replace(/[^A-Za-z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n return sanitized.length > 0 ? sanitized : \"unknown\";\n}\n\nfunction containsNestedRevision(node: XmlElementNode): boolean {\n return node.children.some(\n (child) =>\n child.type === \"element\" &&\n (SUPPORTED_CONTAINER_TYPES.has(localName(child.name)) ||\n PRESERVE_ONLY_CONTAINER_TYPES.has(localName(child.name)) ||\n FORMATTING_REVISION_TYPES.has(localName(child.name)) ||\n containsNestedRevision(child)),\n );\n}\n\nfunction advanceCursor(\n node: XmlElementNode,\n setCursor: (next: number) => void,\n getCursor: () => number,\n): void {\n setCursor(getCursor() + measureStoryLength(node));\n}\n\nfunction measureStoryLength(node: XmlNode): number {\n if (node.type !== \"element\") {\n return 0;\n }\n\n switch (localName(node.name)) {\n case \"t\":\n case \"delText\":\n case \"instrText\":\n case \"delInstrText\":\n return node.children\n .filter((child): child is XmlElementNode[\"children\"][number] & { type: \"text\" } => child.type === \"text\")\n .map((child) => child.text.length)\n .reduce((total, length) => total + length, 0);\n case \"tab\":\n case \"br\":\n case \"cr\":\n return 1;\n case \"pPr\":\n case \"rPr\":\n case \"rPrChange\":\n case \"pPrChange\":\n return 0;\n default:\n return node.children.reduce((total, child) => total + measureStoryLength(child), 0);\n }\n}\n","import { createDetachedAnchor } from \"../../core/selection/mapping.ts\";\nimport type {\n CommentEntry,\n CommentEntryMetadata,\n CommentThread,\n CommentThreadMetadata,\n} from \"./comment-store.ts\";\nimport { createCommentRangeAnchor } from \"./comment-anchors.ts\";\n\nexport interface ImportedCommentEntryInput {\n entryId?: string;\n authorId?: string;\n body: string;\n createdAt?: string;\n metadata?: CommentEntryMetadata;\n}\n\nexport interface ImportedCommentThreadInput {\n commentId: string;\n body: string;\n createdBy?: string;\n createdAt?: string;\n range?:\n | {\n from: number;\n to: number;\n }\n | undefined;\n warningIds?: string[];\n entries?: CommentEntry[];\n status?: CommentThread[\"status\"];\n resolution?: CommentThread[\"resolution\"];\n metadata?: CommentThreadMetadata;\n}\n\nexport function createImportedCommentThread(\n input: ImportedCommentThreadInput,\n): CommentThread {\n const createdAt = input.createdAt ?? \"1970-01-01T00:00:00.000Z\";\n const createdBy = input.createdBy ?? \"unknown\";\n const entries =\n input.entries && input.entries.length > 0\n ? input.entries\n : [\n {\n entryId: `${input.commentId}-entry-1`,\n authorId: createdBy,\n body: input.body,\n createdAt,\n },\n ];\n const status =\n input.status ??\n (input.range ? \"open\" : \"detached\");\n\n return {\n commentId: input.commentId,\n anchor:\n status === \"detached\"\n ? createDetachedAnchor(input.range ?? { from: 0, to: 0 }, \"importAmbiguity\")\n : input.range\n ? createCommentRangeAnchor(input.range.from, input.range.to)\n : createDetachedAnchor({ from: 0, to: 0 }, \"importAmbiguity\"),\n status,\n entries,\n createdBy,\n createdAt,\n resolution: input.resolution,\n warningIds: [...(input.warningIds ?? [])],\n metadata: input.metadata,\n };\n}\n\nexport function createImportedCommentReply(\n commentId: string,\n input: ImportedCommentEntryInput,\n) {\n return {\n entryId: input.entryId ?? `${commentId}-entry-reply`,\n authorId: input.authorId ?? \"unknown\",\n body: input.body,\n createdAt: input.createdAt ?? \"1970-01-01T00:00:00.000Z\",\n };\n}\n\nexport function updateCommentThreadBody(\n thread: CommentThread,\n body: string,\n): CommentThread {\n const firstEntry = thread.entries[0];\n if (!firstEntry) {\n return thread;\n }\n\n return {\n ...thread,\n entries: [\n {\n ...firstEntry,\n body,\n },\n ...thread.entries.slice(1),\n ],\n };\n}\n\nexport function getCommentThreadBody(thread: CommentThread): string {\n return thread.entries.map((entry) => entry.body).join(\"\\n\");\n}\n","import type { CommentThread } from \"../../review/store/comment-store.ts\";\nimport { createImportedCommentThread } from \"../../review/store/comment-thread.ts\";\n\ninterface XmlElementNode {\n type: \"element\";\n name: string;\n attributes: Record<string, string>;\n children: XmlNode[];\n start: number;\n end: number;\n}\n\ninterface XmlTextNode {\n type: \"text\";\n text: string;\n start: number;\n end: number;\n}\n\ntype XmlNode = XmlElementNode | XmlTextNode;\n\nexport interface ParsedCommentsInput {\n commentsXml: string;\n commentsExtendedXml?: string;\n commentsIdsXml?: string;\n peopleXml?: string;\n}\n\nexport interface ImportedCommentDefinition {\n commentId: string;\n authorId?: string;\n createdAt?: string;\n body: string;\n rawXml: string;\n order: number;\n initials?: string;\n paraId?: string;\n parentParaId?: string;\n durableId?: string;\n isDone?: boolean;\n}\n\ninterface CommentAnchorBounds {\n start?: number;\n end?: number;\n startParagraphIndex?: number;\n endParagraphIndex?: number;\n referenceAt?: number;\n referenceParagraphIndex?: number;\n}\n\ninterface CommentExtensionRecord {\n paraId: string;\n parentParaId?: string;\n isDone?: boolean;\n}\n\nexport interface CommentImportDiagnostic {\n commentId: string;\n code:\n | \"missing_comment_definition\"\n | \"missing_anchor_reference\"\n | \"multi_paragraph_anchor_preserve_only\"\n | \"opaque_anchor_preserve_only\"\n | \"preserve_only_revision_overlap\";\n message: string;\n featureClass: \"preserve-only\";\n}\n\nexport interface ParsedCommentsResult {\n threads: CommentThread[];\n diagnostics: CommentImportDiagnostic[];\n definitions: ImportedCommentDefinition[];\n sourceRootTag?: string;\n sourceExtendedRootTag?: string;\n sourceIdsRootTag?: string;\n sourcePeopleRootTag?: string;\n peopleAuthors: string[];\n}\n\nexport function parseCommentsFromOoxml(\n documentXml: string,\n input: string | ParsedCommentsInput,\n): ParsedCommentsResult {\n const parts = normalizeInput(input);\n const commentExtensions = parseCommentExtensions(parts.commentsExtendedXml);\n const durableIds = parseCommentDurableIds(parts.commentsIdsXml);\n const peopleAuthors = parsePeopleAuthors(parts.peopleXml);\n const definitions = parseCommentDefinitions(parts.commentsXml, commentExtensions, durableIds);\n const definitionsById = new Map(definitions.map((definition) => [definition.commentId, definition]));\n const definitionsByParaId = new Map(\n definitions\n .filter((definition) => typeof definition.paraId === \"string\")\n .map((definition) => [definition.paraId!, definition]),\n );\n const anchors = parseCommentAnchors(documentXml);\n const diagnostics: CommentImportDiagnostic[] = [];\n const threadDefinitions = groupThreadDefinitions(definitions, definitionsByParaId);\n const threads: CommentThread[] = [];\n\n for (const [rootCommentId, groupedDefinitions] of threadDefinitions) {\n const rootDefinition = groupedDefinitions[0];\n if (!rootDefinition) {\n continue;\n }\n\n const anchor = anchors.get(rootCommentId);\n const start = anchor?.start ?? anchor?.referenceAt;\n const end = anchor?.end ?? anchor?.referenceAt;\n const startParagraphIndex = anchor?.startParagraphIndex ?? anchor?.referenceParagraphIndex;\n const endParagraphIndex = anchor?.endParagraphIndex ?? anchor?.referenceParagraphIndex;\n const entries = groupedDefinitions.map((definition, index) => ({\n entryId: `${rootCommentId}-entry-${index + 1}`,\n authorId: definition.authorId ?? \"unknown\",\n body: definition.body,\n createdAt: definition.createdAt ?? \"1970-01-01T00:00:00.000Z\",\n metadata: {\n ooxmlCommentId: definition.commentId,\n paraId: definition.paraId,\n parentParaId: definition.parentParaId,\n durableId: definition.durableId,\n initials: definition.initials,\n },\n }));\n const createdBy = rootDefinition.authorId ?? entries[0]?.authorId ?? \"unknown\";\n const createdAt = rootDefinition.createdAt ?? entries[0]?.createdAt ?? \"1970-01-01T00:00:00.000Z\";\n const resolution =\n rootDefinition.isDone\n ? {\n resolvedAt: entries.at(-1)?.createdAt ?? createdAt,\n resolvedBy: entries.at(-1)?.authorId ?? createdBy,\n }\n : undefined;\n const detachedRange = toDetachedRange(anchor);\n\n if (\n start === undefined ||\n end === undefined ||\n startParagraphIndex === undefined ||\n endParagraphIndex === undefined\n ) {\n diagnostics.push({\n commentId: rootCommentId,\n code: \"missing_anchor_reference\",\n message: \"Comment anchor markers are incomplete and remain preserve-only.\",\n featureClass: \"preserve-only\",\n });\n threads.push(\n createImportedCommentThread({\n commentId: rootCommentId,\n body: rootDefinition.body,\n createdBy,\n createdAt,\n range: detachedRange,\n entries,\n status: \"detached\",\n resolution,\n metadata: {\n source: \"import\",\n rootOoxmlCommentId: rootDefinition.commentId,\n rootParaId: rootDefinition.paraId,\n },\n }),\n );\n continue;\n }\n\n if (startParagraphIndex !== endParagraphIndex) {\n diagnostics.push({\n commentId: rootCommentId,\n code: \"multi_paragraph_anchor_preserve_only\",\n message:\n \"Comment anchor spans multiple paragraphs and remains preserve-only for Wave 5.\",\n featureClass: \"preserve-only\",\n });\n threads.push(\n createImportedCommentThread({\n commentId: rootCommentId,\n body: rootDefinition.body,\n createdBy,\n createdAt,\n range: detachedRange,\n entries,\n status: \"detached\",\n resolution,\n metadata: {\n source: \"import\",\n rootOoxmlCommentId: rootDefinition.commentId,\n rootParaId: rootDefinition.paraId,\n },\n }),\n );\n continue;\n }\n\n threads.push(\n createImportedCommentThread({\n commentId: rootCommentId,\n body: rootDefinition.body,\n createdBy,\n createdAt,\n range: {\n from: Math.min(start, end),\n to: Math.max(start, end),\n },\n entries,\n status: resolution ? \"resolved\" : \"open\",\n resolution,\n metadata: {\n source: \"import\",\n rootOoxmlCommentId: rootDefinition.commentId,\n rootParaId: rootDefinition.paraId,\n },\n }),\n );\n }\n\n for (const commentId of anchors.keys()) {\n if (definitionsById.has(commentId)) {\n continue;\n }\n\n diagnostics.push({\n commentId,\n code: \"missing_comment_definition\",\n message: \"Document anchor markers reference a comment id missing from comments.xml.\",\n featureClass: \"preserve-only\",\n });\n }\n\n threads.sort(compareThreadsByAnchor);\n\n return {\n threads,\n diagnostics,\n definitions,\n sourceRootTag: extractRootTag(parts.commentsXml, \"comments\"),\n sourceExtendedRootTag: extractRootTag(parts.commentsExtendedXml, \"commentsEx\"),\n sourceIdsRootTag: extractRootTag(parts.commentsIdsXml, \"commentsIds\"),\n sourcePeopleRootTag: extractRootTag(parts.peopleXml, \"people\"),\n peopleAuthors,\n };\n}\n\nfunction normalizeInput(input: string | ParsedCommentsInput): ParsedCommentsInput {\n return typeof input === \"string\"\n ? {\n commentsXml: input,\n }\n : input;\n}\n\nfunction groupThreadDefinitions(\n definitions: ImportedCommentDefinition[],\n definitionsByParaId: Map<string, ImportedCommentDefinition>,\n): Map<string, ImportedCommentDefinition[]> {\n const grouped = new Map<string, ImportedCommentDefinition[]>();\n\n for (const definition of definitions) {\n const rootCommentId = resolveRootCommentId(definition, definitionsByParaId);\n const group = grouped.get(rootCommentId);\n if (group) {\n group.push(definition);\n } else {\n grouped.set(rootCommentId, [definition]);\n }\n }\n\n for (const group of grouped.values()) {\n group.sort((left, right) => left.order - right.order);\n const rootIndex = group.findIndex((definition) => !definition.parentParaId);\n if (rootIndex > 0) {\n const [rootDefinition] = group.splice(rootIndex, 1);\n if (rootDefinition) {\n group.unshift(rootDefinition);\n }\n }\n }\n\n return new Map(\n [...grouped.entries()].sort(([leftId], [rightId]) => leftId.localeCompare(rightId)),\n );\n}\n\nfunction resolveRootCommentId(\n definition: ImportedCommentDefinition,\n definitionsByParaId: Map<string, ImportedCommentDefinition>,\n): string {\n const visited = new Set<string>();\n let current: ImportedCommentDefinition | undefined = definition;\n\n while (current?.parentParaId) {\n if (visited.has(current.parentParaId)) {\n break;\n }\n visited.add(current.parentParaId);\n const parent = definitionsByParaId.get(current.parentParaId);\n if (!parent) {\n break;\n }\n current = parent;\n }\n\n return current?.commentId ?? definition.commentId;\n}\n\nfunction parseCommentDefinitions(\n commentsXml: string,\n extensions: Map<string, CommentExtensionRecord>,\n durableIds: Map<string, string>,\n): ImportedCommentDefinition[] {\n if (commentsXml.trim().length === 0) {\n return [];\n }\n\n const root = parseXml(commentsXml);\n const commentsElement = findChildElement(root, \"comments\");\n const definitions: ImportedCommentDefinition[] = [];\n let order = 0;\n\n for (const child of commentsElement.children) {\n if (child.type !== \"element\" || localName(child.name) !== \"comment\") {\n continue;\n }\n\n const commentId = child.attributes[\"w:id\"] ?? child.attributes.id;\n if (!commentId) {\n continue;\n }\n\n const authorId = child.attributes[\"w:author\"] ?? child.attributes.author;\n const createdAt = normalizeImportedTimestamp(\n child.attributes[\"w:date\"] ?? child.attributes.date,\n );\n const initials = child.attributes[\"w:initials\"] ?? child.attributes.initials;\n const paragraphNodes = child.children.filter(\n (node): node is XmlElementNode => node.type === \"element\" && localName(node.name) === \"p\",\n );\n const body = paragraphNodes\n .map(extractParagraphText)\n .join(\"\\n\");\n const paraId = paragraphNodes[0]?.attributes[\"w14:paraId\"] ?? paragraphNodes[0]?.attributes.paraId;\n const extension = paraId ? extensions.get(paraId) : undefined;\n\n definitions.push({\n commentId,\n authorId,\n createdAt,\n body,\n rawXml: commentsXml.slice(child.start, child.end),\n order,\n initials,\n paraId,\n parentParaId: extension?.parentParaId,\n durableId: paraId ? durableIds.get(paraId) : undefined,\n isDone: extension?.isDone,\n });\n order += 1;\n }\n\n return definitions;\n}\n\nfunction normalizeImportedTimestamp(value: string | undefined): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const parsed = new Date(value);\n if (Number.isNaN(parsed.valueOf())) {\n return undefined;\n }\n\n return parsed.toISOString();\n}\n\nfunction parseCommentExtensions(xml: string | undefined): Map<string, CommentExtensionRecord> {\n if (!xml || xml.trim().length === 0) {\n return new Map();\n }\n\n const root = parseXml(xml);\n const commentsElement = findChildElement(root, \"commentsEx\");\n const extensions = new Map<string, CommentExtensionRecord>();\n\n for (const child of commentsElement.children) {\n if (child.type !== \"element\" || localName(child.name) !== \"commentEx\") {\n continue;\n }\n\n const paraId = child.attributes[\"w15:paraId\"] ?? child.attributes.paraId;\n if (!paraId) {\n continue;\n }\n\n const parentParaId = child.attributes[\"w15:paraIdParent\"] ?? child.attributes.paraIdParent;\n const doneValue = child.attributes[\"w15:done\"] ?? child.attributes.done;\n extensions.set(paraId, {\n paraId,\n parentParaId,\n isDone:\n typeof doneValue === \"string\"\n ? doneValue.toLowerCase() === \"true\" || doneValue === \"1\"\n : undefined,\n });\n }\n\n return extensions;\n}\n\nfunction parseCommentDurableIds(xml: string | undefined): Map<string, string> {\n if (!xml || xml.trim().length === 0) {\n return new Map();\n }\n\n const root = parseXml(xml);\n const commentsIdsElement = findChildElement(root, \"commentsIds\");\n const durableIds = new Map<string, string>();\n\n for (const child of commentsIdsElement.children) {\n if (child.type !== \"element\" || localName(child.name) !== \"commentId\") {\n continue;\n }\n\n const paraId = child.attributes[\"w16cid:paraId\"] ?? child.attributes.paraId;\n const durableId = child.attributes[\"w16cid:durableId\"] ?? child.attributes.durableId;\n if (paraId && durableId) {\n durableIds.set(paraId, durableId);\n }\n }\n\n return durableIds;\n}\n\nfunction parsePeopleAuthors(xml: string | undefined): string[] {\n if (!xml || xml.trim().length === 0) {\n return [];\n }\n\n const root = parseXml(xml);\n const peopleElement = findChildElement(root, \"people\");\n const authors = new Set<string>();\n\n for (const child of peopleElement.children) {\n if (child.type !== \"element\" || localName(child.name) !== \"person\") {\n continue;\n }\n\n const author = child.attributes[\"w15:author\"] ?? child.attributes.author;\n if (author) {\n authors.add(author);\n }\n }\n\n return [...authors].sort((left, right) => left.localeCompare(right));\n}\n\nfunction extractRootTag(xml: string | undefined, localTagName: string): string | undefined {\n if (!xml) {\n return undefined;\n }\n\n const pattern = new RegExp(`<[^>]*:?${localTagName}\\\\b[^>]*>`, \"u\");\n return pattern.exec(xml)?.[0];\n}\n\nfunction parseCommentAnchors(documentXml: string): Map<string, CommentAnchorBounds> {\n const root = parseXml(documentXml);\n const documentElement = findChildElement(root, \"document\");\n const bodyElement = findChildElement(documentElement, \"body\");\n const anchors = new Map<string, CommentAnchorBounds>();\n let cursor = 0;\n let paragraphIndex = -1;\n let previousWasParagraph = false;\n\n for (const child of bodyElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n if (localName(child.name) !== \"p\") {\n cursor += 1;\n previousWasParagraph = false;\n continue;\n }\n\n if (previousWasParagraph) {\n cursor += 1;\n }\n paragraphIndex += 1;\n walkParagraph(child, paragraphIndex, anchors, () => cursor, (next) => {\n cursor = next;\n });\n previousWasParagraph = true;\n }\n\n return anchors;\n}\n\nfunction walkParagraph(\n paragraph: XmlElementNode,\n paragraphIndex: number,\n anchors: Map<string, CommentAnchorBounds>,\n getCursor: () => number,\n setCursor: (next: number) => void,\n): void {\n for (const child of paragraph.children) {\n walkInlineNode(child, paragraphIndex, anchors, getCursor, setCursor);\n }\n}\n\nfunction walkInlineNode(\n node: XmlNode,\n paragraphIndex: number,\n anchors: Map<string, CommentAnchorBounds>,\n getCursor: () => number,\n setCursor: (next: number) => void,\n): void {\n if (node.type !== \"element\") {\n return;\n }\n\n switch (localName(node.name)) {\n case \"commentRangeStart\": {\n const commentId = node.attributes[\"w:id\"] ?? node.attributes.id;\n if (commentId) {\n const bounds = ensureCommentAnchor(anchors, commentId);\n bounds.start = getCursor();\n bounds.startParagraphIndex = paragraphIndex;\n }\n return;\n }\n case \"commentRangeEnd\": {\n const commentId = node.attributes[\"w:id\"] ?? node.attributes.id;\n if (commentId) {\n const bounds = ensureCommentAnchor(anchors, commentId);\n bounds.end = getCursor();\n bounds.endParagraphIndex = paragraphIndex;\n }\n return;\n }\n case \"commentReference\": {\n const commentId = node.attributes[\"w:id\"] ?? node.attributes.id;\n if (commentId) {\n const bounds = ensureCommentAnchor(anchors, commentId);\n bounds.referenceAt = getCursor();\n bounds.referenceParagraphIndex = paragraphIndex;\n }\n return;\n }\n case \"t\": {\n const text = node.children\n .filter((child): child is XmlTextNode => child.type === \"text\")\n .map((child) => child.text)\n .join(\"\");\n setCursor(getCursor() + text.length);\n return;\n }\n case \"tab\":\n case \"br\":\n setCursor(getCursor() + 1);\n return;\n default:\n for (const child of node.children) {\n walkInlineNode(child, paragraphIndex, anchors, getCursor, setCursor);\n }\n }\n}\n\nfunction ensureCommentAnchor(\n anchors: Map<string, CommentAnchorBounds>,\n commentId: string,\n): CommentAnchorBounds {\n const existing = anchors.get(commentId);\n if (existing) {\n return existing;\n }\n\n const next: CommentAnchorBounds = {};\n anchors.set(commentId, next);\n return next;\n}\n\nfunction extractParagraphText(paragraph: XmlElementNode): string {\n let text = \"\";\n\n for (const child of paragraph.children) {\n text += extractNodeText(child);\n }\n\n return text;\n}\n\nfunction extractNodeText(node: XmlNode): string {\n if (node.type === \"text\") {\n return node.text;\n }\n\n switch (localName(node.name)) {\n case \"t\":\n return node.children.map(extractNodeText).join(\"\");\n case \"tab\":\n return \"\\t\";\n case \"br\":\n return \"\\n\";\n default:\n return node.children.map(extractNodeText).join(\"\");\n }\n}\n\nfunction compareThreadsByAnchor(left: CommentThread, right: CommentThread): number {\n const leftStart =\n left.anchor.kind === \"range\" ? left.anchor.range.from : Number.MAX_SAFE_INTEGER;\n const rightStart =\n right.anchor.kind === \"range\" ? right.anchor.range.from : Number.MAX_SAFE_INTEGER;\n\n if (leftStart !== rightStart) {\n return leftStart - rightStart;\n }\n\n return left.commentId.localeCompare(right.commentId);\n}\n\nfunction toDetachedRange(anchor: CommentAnchorBounds): { from: number; to: number } | undefined {\n const positions = [anchor.start, anchor.end, anchor.referenceAt].filter(\n (value): value is number => typeof value === \"number\",\n );\n if (positions.length === 0) {\n return undefined;\n }\n return {\n from: Math.min(...positions),\n to: Math.max(...positions),\n };\n}\n\nfunction parseXml(xml: string): XmlElementNode {\n const root: XmlElementNode = {\n type: \"element\",\n name: \"#document\",\n attributes: {},\n children: [],\n start: 0,\n end: xml.length,\n };\n const stack: XmlElementNode[] = [root];\n const tokenPattern =\n /<!--[\\s\\S]*?-->|<\\?[\\s\\S]*?\\?>|<!DOCTYPE[\\s\\S]*?>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>|<[^>]+>|[^<]+/gu;\n\n for (const match of xml.matchAll(tokenPattern)) {\n const token = match[0] ?? \"\";\n const start = match.index ?? 0;\n const end = start + token.length;\n\n if (token.startsWith(\"<?\") || token.startsWith(\"<!DOCTYPE\") || token.startsWith(\"<!--\")) {\n continue;\n }\n\n if (token.startsWith(\"<![CDATA[\")) {\n const text = token.slice(9, -3);\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text,\n start,\n end,\n });\n continue;\n }\n\n if (token.startsWith(\"</\")) {\n const node = stack.pop();\n if (!node) {\n throw new Error(\"Malformed XML: unexpected closing tag.\");\n }\n node.end = end;\n continue;\n }\n\n if (token.startsWith(\"<\")) {\n const selfClosing = /\\/>$/.test(token);\n const tagBody = token.slice(1, token.length - (selfClosing ? 2 : 1)).trim();\n const { name, attributes } = parseTag(tagBody);\n const node: XmlElementNode = {\n type: \"element\",\n name,\n attributes,\n children: [],\n start,\n end,\n };\n stack[stack.length - 1]?.children.push(node);\n if (!selfClosing) {\n stack.push(node);\n }\n continue;\n }\n\n const text = decodeXmlText(token);\n if (text.length > 0) {\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text,\n start,\n end,\n });\n }\n }\n\n if (stack.length !== 1) {\n throw new Error(\"Malformed XML: unclosed tag.\");\n }\n\n return root;\n}\n\nfunction parseTag(tagBody: string): { name: string; attributes: Record<string, string> } {\n const whitespaceIndex = tagBody.search(/\\s/u);\n const name = whitespaceIndex === -1 ? tagBody : tagBody.slice(0, whitespaceIndex);\n const rawAttributes = whitespaceIndex === -1 ? \"\" : tagBody.slice(whitespaceIndex + 1);\n const attributes: Record<string, string> = {};\n const pattern = /([A-Za-z_][A-Za-z0-9:._-]*)\\s*=\\s*(\"([^\"]*)\"|'([^']*)')/gu;\n\n for (const match of rawAttributes.matchAll(pattern)) {\n const key = match[1];\n const value = match[3] ?? match[4] ?? \"\";\n if (key) {\n attributes[key] = decodeXmlText(value);\n }\n }\n\n return { name, attributes };\n}\n\nfunction findChildElement(node: XmlElementNode, name: string): XmlElementNode {\n const match = node.children.find(\n (child): child is XmlElementNode =>\n child.type === \"element\" && localName(child.name) === name,\n );\n\n if (!match) {\n throw new Error(`Expected XML element ${name}.`);\n }\n\n return match;\n}\n\nfunction localName(name: string): string {\n const index = name.indexOf(\":\");\n return index === -1 ? name : name.slice(index + 1);\n}\n\nfunction decodeXmlText(text: string): string {\n return text.replace(\n /&(?:#x([0-9A-Fa-f]+)|#([0-9]+)|([A-Za-z]+));/gu,\n (_, hex, dec, named) => {\n if (hex) {\n return String.fromCodePoint(Number.parseInt(hex, 16));\n }\n if (dec) {\n return String.fromCodePoint(Number.parseInt(dec, 10));\n }\n\n switch (named) {\n case \"amp\":\n return \"&\";\n case \"lt\":\n return \"<\";\n case \"gt\":\n return \">\";\n case \"quot\":\n return \"\\\"\";\n case \"apos\":\n return \"'\";\n default:\n return `&${named};`;\n }\n },\n );\n}\n","import type { CommentEntry, CommentThread } from \"../../review/store/comment-store.ts\";\nimport type { RevisionParagraphBoundary } from \"../ooxml/revision-boundaries.ts\";\nimport type { ImportedCommentDefinition } from \"../ooxml/parse-comments.ts\";\n\ninterface XmlElementNode {\n type: \"element\";\n name: string;\n attributes: Record<string, string>;\n children: XmlNode[];\n start: number;\n end: number;\n}\n\ninterface XmlTextNode {\n type: \"text\";\n text: string;\n start: number;\n end: number;\n}\n\ntype XmlNode = XmlElementNode | XmlTextNode;\n\ninterface ParagraphBoundaryMap {\n paragraphIndex: number;\n start: number;\n end: number;\n boundaries: Map<number, number>;\n}\n\ninterface SerializableCommentEntry {\n thread: CommentThread;\n entry: CommentEntry;\n exportCommentId: string;\n paraId: string;\n durableId?: string;\n isRoot: boolean;\n}\n\nexport interface SerializedCommentsResult {\n commentsXml: string;\n serializedCommentIds: string[];\n commentsExtendedXml?: string;\n commentsIdsXml?: string;\n peopleXml?: string;\n}\n\nexport interface SerializeMergedCommentsXmlOptions {\n preservedDefinitions?: readonly ImportedCommentDefinition[];\n sourceRootTag?: string;\n sourceExtendedRootTag?: string;\n sourceIdsRootTag?: string;\n sourcePeopleRootTag?: string;\n peopleAuthors?: readonly string[];\n exportCommentIds?: ReadonlyMap<string, string>;\n}\n\nexport interface SerializeCommentAnchorsOptions {\n exportCommentIds?: ReadonlyMap<string, string>;\n}\n\nexport interface SerializedCommentDocumentResult {\n documentXml: string;\n serializedCommentIds: string[];\n skippedCommentIds: string[];\n}\n\nconst DEFAULT_COMMENTS_ROOT_TAG =\n `<w:comments xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" mc:Ignorable=\"w14\">`;\nconst DEFAULT_COMMENTS_EXTENDED_ROOT_TAG =\n `<w15:commentsEx xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\">`;\nconst DEFAULT_COMMENTS_IDS_ROOT_TAG =\n `<w16cid:commentsIds xmlns:w16cid=\"http://schemas.microsoft.com/office/word/2016/wordml/cid\">`;\nconst DEFAULT_PEOPLE_ROOT_TAG =\n `<w15:people xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\">`;\n\nexport function serializeCommentsXml(\n threads: readonly CommentThread[],\n options: {\n exportCommentIds?: ReadonlyMap<string, string>;\n } = {},\n): SerializedCommentsResult {\n return serializeMergedCommentsXml(threads, {\n exportCommentIds: options.exportCommentIds,\n });\n}\n\nexport function serializeMergedCommentsXml(\n threads: readonly CommentThread[],\n options: SerializeMergedCommentsXmlOptions = {},\n): SerializedCommentsResult {\n const serializableThreads = threads.filter((thread) => thread.entries.length > 0);\n const preservedDefinitions = (options.preservedDefinitions ?? [])\n .slice()\n .sort((left, right) => left.order - right.order);\n const runtimeThreadById = new Map(\n serializableThreads.map((thread) => [thread.commentId, thread]),\n );\n const exportCommentIds =\n options.exportCommentIds ??\n createCommentExportIdMap(serializableThreads, preservedDefinitions);\n const serializableEntries = createSerializableEntries(\n serializableThreads,\n preservedDefinitions,\n exportCommentIds,\n );\n const serializedEntryByOoxmlId = new Map(\n serializableEntries.map((entry) => [entry.exportCommentId, entry]),\n );\n const emittedThreadIds = new Set<string>();\n const mergedComments: string[] = [];\n\n for (const definition of preservedDefinitions) {\n const ownedThread = runtimeThreadById.get(definition.commentId);\n if (ownedThread) {\n if (emittedThreadIds.has(ownedThread.commentId)) {\n continue;\n }\n mergedComments.push(\n ...serializeThreadEntries(\n serializableEntries.filter((entry) => entry.thread.commentId === ownedThread.commentId),\n ),\n );\n emittedThreadIds.add(ownedThread.commentId);\n continue;\n }\n\n if (serializedEntryByOoxmlId.has(definition.commentId)) {\n continue;\n }\n\n mergedComments.push(definition.rawXml);\n }\n\n for (const thread of serializableThreads) {\n if (emittedThreadIds.has(thread.commentId)) {\n continue;\n }\n\n mergedComments.push(\n ...serializeThreadEntries(\n serializableEntries.filter((entry) => entry.thread.commentId === thread.commentId),\n ),\n );\n emittedThreadIds.add(thread.commentId);\n }\n\n const mergedExtendedEntries = [\n ...serializePreservedCommentExtensions(\n preservedDefinitions.filter((definition) => !serializedEntryByOoxmlId.has(definition.commentId)),\n ),\n ...serializableEntries\n .map((entry) => serializeCommentExtension(entry))\n .filter((xml): xml is string => Boolean(xml)),\n ];\n const mergedDurableIds = [\n ...serializePreservedCommentIds(\n preservedDefinitions.filter((definition) => !serializedEntryByOoxmlId.has(definition.commentId)),\n ),\n ...serializableEntries\n .map((entry) => serializeCommentDurableId(entry))\n .filter((xml): xml is string => Boolean(xml)),\n ];\n const peopleAuthors = new Set([\n ...(options.peopleAuthors ?? []),\n ...preservedDefinitions\n .map((definition) => definition.authorId)\n .filter((authorId): authorId is string => typeof authorId === \"string\" && authorId.length > 0),\n ...serializableEntries\n .map((entry) => entry.entry.authorId)\n .filter((authorId): authorId is string => typeof authorId === \"string\" && authorId.length > 0),\n ]);\n\n return {\n commentsXml: [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n normalizeCommentsRootTag(options.sourceRootTag ?? DEFAULT_COMMENTS_ROOT_TAG),\n ...mergedComments,\n `</w:comments>`,\n ].join(\"\\n\"),\n serializedCommentIds: serializableThreads.map((thread) => thread.commentId),\n commentsExtendedXml:\n mergedExtendedEntries.length > 0\n ? [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n options.sourceExtendedRootTag ?? DEFAULT_COMMENTS_EXTENDED_ROOT_TAG,\n ...mergedExtendedEntries,\n `</w15:commentsEx>`,\n ].join(\"\\n\")\n : undefined,\n commentsIdsXml:\n mergedDurableIds.length > 0\n ? [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n options.sourceIdsRootTag ?? DEFAULT_COMMENTS_IDS_ROOT_TAG,\n ...mergedDurableIds,\n `</w16cid:commentsIds>`,\n ].join(\"\\n\")\n : undefined,\n peopleXml:\n peopleAuthors.size > 0\n ? [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n options.sourcePeopleRootTag ?? DEFAULT_PEOPLE_ROOT_TAG,\n ...[...peopleAuthors]\n .sort((left, right) => left.localeCompare(right))\n .map(\n (authorId) =>\n `<w15:person w15:author=\"${escapeAttribute(authorId)}\" />`,\n ),\n `</w15:people>`,\n ].join(\"\\n\")\n : undefined,\n };\n}\n\nfunction normalizeCommentsRootTag(rootTag: string): string {\n let normalized = rootTag;\n if (!/\\bxmlns:w14=/u.test(normalized)) {\n normalized = normalized.replace(\n />$/u,\n ` xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\">`,\n );\n }\n if (!/\\bxmlns:mc=/u.test(normalized)) {\n normalized = normalized.replace(\n />$/u,\n ` xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\">`,\n );\n }\n if (!/\\bmc:Ignorable=/u.test(normalized)) {\n normalized = normalized.replace(/>$/u, ` mc:Ignorable=\"w14\">`);\n } else if (!/\\bmc:Ignorable=\"[^\"]*\\bw14\\b/u.test(normalized)) {\n normalized = normalized.replace(\n /\\bmc:Ignorable=\"([^\"]*)\"/u,\n (_match, value: string) =>\n `mc:Ignorable=\"${`${value} w14`.trim().replace(/\\s+/gu, \" \")}\"`,\n );\n }\n return normalized;\n}\n\nexport function serializeCommentAnchorsIntoDocumentXml(\n documentXml: string,\n threads: readonly CommentThread[],\n paragraphs: readonly Pick<\n RevisionParagraphBoundary,\n \"paragraphIndex\" | \"start\" | \"end\" | \"boundaries\"\n >[] = mapParagraphBoundaries(documentXml),\n options: SerializeCommentAnchorsOptions = {},\n): SerializedCommentDocumentResult {\n const insertions = new Map<number, string[]>();\n const serializedCommentIds: string[] = [];\n const skippedCommentIds: string[] = [];\n const exportCommentIds =\n options.exportCommentIds ?? createCommentExportIdMap(threads);\n\n for (const thread of threads) {\n if (thread.anchor.kind !== \"range\") {\n skippedCommentIds.push(thread.commentId);\n continue;\n }\n\n const paragraph = paragraphs.find(\n (candidate) =>\n thread.anchor.range.from >= candidate.start &&\n thread.anchor.range.to <= candidate.end,\n );\n\n if (!paragraph) {\n skippedCommentIds.push(thread.commentId);\n continue;\n }\n\n const startIndex = paragraph.boundaries.get(thread.anchor.range.from);\n const endIndex = paragraph.boundaries.get(thread.anchor.range.to);\n\n if (startIndex === undefined || endIndex === undefined) {\n skippedCommentIds.push(thread.commentId);\n continue;\n }\n\n const exportCommentId = exportCommentIds.get(thread.commentId) ?? thread.commentId;\n pushInsertion(\n insertions,\n startIndex,\n `<w:commentRangeStart w:id=\"${escapeAttribute(exportCommentId)}\"/>`,\n );\n pushInsertion(\n insertions,\n endIndex,\n `<w:commentRangeEnd w:id=\"${escapeAttribute(exportCommentId)}\"/>`,\n );\n pushInsertion(\n insertions,\n endIndex,\n `<w:r><w:commentReference w:id=\"${escapeAttribute(exportCommentId)}\"/></w:r>`,\n );\n serializedCommentIds.push(thread.commentId);\n }\n\n const sortedInsertions = [...insertions.entries()].sort((left, right) => left[0] - right[0]);\n let cursor = 0;\n let output = \"\";\n\n for (const [index, snippets] of sortedInsertions) {\n output += documentXml.slice(cursor, index);\n output += snippets.join(\"\");\n cursor = index;\n }\n\n output += documentXml.slice(cursor);\n\n return {\n documentXml: output,\n serializedCommentIds,\n skippedCommentIds,\n };\n}\n\nexport function createCommentExportIdMap(\n threads: readonly CommentThread[],\n preservedDefinitions: readonly ImportedCommentDefinition[] = [],\n): ReadonlyMap<string, string> {\n const exportIds = new Map<string, string>();\n const reservedNumericIds = new Set<number>();\n\n for (const definition of preservedDefinitions) {\n const numericId = parseOoxmlNumericId(definition.commentId);\n if (numericId !== undefined) {\n reservedNumericIds.add(numericId);\n }\n }\n\n for (const thread of threads) {\n const rootEntry = getRootEntry(thread);\n const preferredValue =\n thread.metadata?.rootOoxmlCommentId ??\n rootEntry?.metadata?.ooxmlCommentId ??\n thread.commentId;\n const numericId = parseOoxmlNumericId(preferredValue);\n if (numericId !== undefined && !reservedNumericIds.has(numericId)) {\n exportIds.set(thread.commentId, String(numericId));\n reservedNumericIds.add(numericId);\n }\n }\n\n let nextGeneratedId =\n reservedNumericIds.size > 0 ? Math.max(...reservedNumericIds) + 1 : 1;\n\n for (const thread of threads) {\n if (exportIds.has(thread.commentId)) {\n continue;\n }\n\n while (reservedNumericIds.has(nextGeneratedId)) {\n nextGeneratedId += 1;\n }\n\n exportIds.set(thread.commentId, String(nextGeneratedId));\n reservedNumericIds.add(nextGeneratedId);\n nextGeneratedId += 1;\n }\n\n return exportIds;\n}\n\nfunction createSerializableEntries(\n threads: readonly CommentThread[],\n preservedDefinitions: readonly ImportedCommentDefinition[],\n exportCommentIds: ReadonlyMap<string, string>,\n): SerializableCommentEntry[] {\n const entries: SerializableCommentEntry[] = [];\n const reservedNumericIds = new Set<number>();\n\n for (const definition of preservedDefinitions) {\n const numericId = parseOoxmlNumericId(definition.commentId);\n if (numericId !== undefined) {\n reservedNumericIds.add(numericId);\n }\n }\n\n for (const thread of threads) {\n const rootEntry = getRootEntry(thread);\n if (!rootEntry) {\n continue;\n }\n\n const rootExportCommentId = exportCommentIds.get(thread.commentId) ?? thread.commentId;\n const rootNumericId = parseOoxmlNumericId(rootExportCommentId);\n if (rootNumericId !== undefined) {\n reservedNumericIds.add(rootNumericId);\n }\n\n const rootParaId =\n rootEntry.metadata?.paraId ??\n thread.metadata?.rootParaId ??\n generateParaId(thread.commentId, 0);\n const rootDurableId =\n rootEntry.metadata?.durableId ??\n createDurableId(rootEntry, rootExportCommentId, 0);\n\n entries.push({\n thread,\n entry: rootEntry,\n exportCommentId: rootExportCommentId,\n paraId: rootParaId,\n durableId: rootDurableId,\n isRoot: true,\n });\n\n for (let index = 1; index < thread.entries.length; index += 1) {\n const entry = thread.entries[index];\n if (!entry) {\n continue;\n }\n\n const preferredCommentId = entry.metadata?.ooxmlCommentId;\n let exportCommentId: string | undefined;\n const preferredNumericId = preferredCommentId\n ? parseOoxmlNumericId(preferredCommentId)\n : undefined;\n if (\n preferredNumericId !== undefined &&\n !reservedNumericIds.has(preferredNumericId)\n ) {\n exportCommentId = String(preferredNumericId);\n reservedNumericIds.add(preferredNumericId);\n } else {\n let nextGeneratedId =\n reservedNumericIds.size > 0 ? Math.max(...reservedNumericIds) + 1 : 1;\n while (reservedNumericIds.has(nextGeneratedId)) {\n nextGeneratedId += 1;\n }\n exportCommentId = String(nextGeneratedId);\n reservedNumericIds.add(nextGeneratedId);\n }\n\n entries.push({\n thread,\n entry,\n exportCommentId,\n paraId: entry.metadata?.paraId ?? generateParaId(thread.commentId, index),\n durableId:\n entry.metadata?.durableId ??\n createDurableId(entry, exportCommentId, index),\n isRoot: false,\n });\n }\n }\n\n return entries;\n}\n\nfunction serializeThreadEntries(entries: readonly SerializableCommentEntry[]): string[] {\n return entries.map((entry) => serializeCommentEntry(entry));\n}\n\nfunction serializeCommentEntry(entry: SerializableCommentEntry): string {\n const author = escapeAttribute(entry.entry.authorId);\n const createdAt = escapeAttribute(entry.entry.createdAt);\n const initials = entry.entry.metadata?.initials;\n const paragraphXml = serializeCommentParagraphs(entry.entry.body, entry.paraId);\n\n return `<w:comment w:id=\"${escapeAttribute(entry.exportCommentId)}\"${initials ? ` w:initials=\"${escapeAttribute(initials)}\"` : \"\"} w:author=\"${author}\" w:date=\"${createdAt}\">${paragraphXml}</w:comment>`;\n}\n\nfunction serializeCommentParagraphs(body: string, paraId: string): string {\n const paragraphs = body.length > 0 ? body.split(\"\\n\") : [\"\"];\n const textId = deriveTextIdFromParaId(paraId);\n return paragraphs\n .map((paragraph, index) => {\n const attributes =\n index === 0\n ? ` w14:paraId=\"${escapeAttribute(paraId)}\" w14:textId=\"${escapeAttribute(textId)}\"`\n : \"\";\n return `<w:p${attributes}><w:r>${serializeText(paragraph)}</w:r></w:p>`;\n })\n .join(\"\");\n}\n\nfunction serializePreservedCommentExtensions(\n definitions: readonly ImportedCommentDefinition[],\n): string[] {\n return definitions\n .map((definition) =>\n definition.paraId\n ? serializePreservedCommentExtension(definition)\n : undefined,\n )\n .filter((xml): xml is string => Boolean(xml));\n}\n\nfunction serializePreservedCommentExtension(\n definition: ImportedCommentDefinition,\n): string {\n const doneValue = definition.isDone ? \"true\" : \"false\";\n return `<w15:commentEx w15:paraId=\"${escapeAttribute(definition.paraId!)}\"${definition.parentParaId ? ` w15:paraIdParent=\"${escapeAttribute(definition.parentParaId)}\"` : \"\"} w15:done=\"${doneValue}\" />`;\n}\n\nfunction serializeCommentExtension(\n entry: SerializableCommentEntry,\n): string | undefined {\n return `<w15:commentEx w15:paraId=\"${escapeAttribute(entry.paraId)}\"${entry.isRoot ? \"\" : ` w15:paraIdParent=\"${escapeAttribute(findRootParaId(entry.thread, entry.paraId))}\"`} w15:done=\"${entry.isRoot && entry.thread.status === \"resolved\" ? \"true\" : \"false\"}\" />`;\n}\n\nfunction serializePreservedCommentIds(\n definitions: readonly ImportedCommentDefinition[],\n): string[] {\n return definitions\n .map((definition) =>\n definition.paraId && definition.durableId\n ? `<w16cid:commentId w16cid:paraId=\"${escapeAttribute(definition.paraId)}\" w16cid:durableId=\"${escapeAttribute(definition.durableId)}\" />`\n : undefined,\n )\n .filter((xml): xml is string => Boolean(xml));\n}\n\nfunction serializeCommentDurableId(\n entry: SerializableCommentEntry,\n): string | undefined {\n if (!entry.durableId) {\n return undefined;\n }\n\n return `<w16cid:commentId w16cid:paraId=\"${escapeAttribute(entry.paraId)}\" w16cid:durableId=\"${escapeAttribute(entry.durableId)}\" />`;\n}\n\nfunction getRootEntry(thread: CommentThread): CommentEntry | undefined {\n return thread.entries[0];\n}\n\nfunction findRootParaId(thread: CommentThread, fallback: string): string {\n return (\n thread.entries[0]?.metadata?.paraId ??\n thread.metadata?.rootParaId ??\n fallback\n );\n}\n\nfunction generateParaId(seed: string, index: number): string {\n const normalized = `${seed}:${index}`;\n let hash = 0;\n\n for (let cursor = 0; cursor < normalized.length; cursor += 1) {\n hash = (hash * 31 + normalized.charCodeAt(cursor)) >>> 0;\n }\n\n return hash.toString(16).toUpperCase().padStart(8, \"0\").slice(-8);\n}\n\nfunction createDurableId(\n entry: CommentEntry,\n exportCommentId: string,\n index: number,\n): string {\n const seed = `${entry.entryId}:${exportCommentId}:${index}`;\n let hash = 0n;\n\n for (let cursor = 0; cursor < seed.length; cursor += 1) {\n hash = (hash * 131n + BigInt(seed.charCodeAt(cursor))) & 0xffffffffffffffffn;\n }\n\n return hash.toString(16).toUpperCase().padStart(16, \"0\").slice(-16);\n}\n\nfunction deriveTextIdFromParaId(paraId: string): string {\n return paraId.slice(-8).padStart(8, \"0\");\n}\n\nfunction parseOoxmlNumericId(value: string): number | undefined {\n if (!/^-?\\d+$/u.test(value)) {\n return undefined;\n }\n\n const numericId = Number.parseInt(value, 10);\n return Number.isFinite(numericId) ? numericId : undefined;\n}\n\nfunction mapParagraphBoundaries(documentXml: string): ParagraphBoundaryMap[] {\n const root = parseXml(documentXml);\n const documentElement = findChildElement(root, \"document\");\n const bodyElement = findChildElement(documentElement, \"body\");\n const paragraphs: ParagraphBoundaryMap[] = [];\n let globalCursor = 0;\n let paragraphIndex = -1;\n let previousWasParagraph = false;\n\n for (const child of bodyElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n if (localName(child.name) !== \"p\") {\n globalCursor += 1;\n previousWasParagraph = false;\n continue;\n }\n\n if (previousWasParagraph) {\n globalCursor += 1;\n }\n paragraphIndex += 1;\n const boundaries = new Map<number, number>();\n boundaries.set(globalCursor, child.start + openingTagLength(documentXml, child.start));\n\n walkParagraphForBoundaries(\n child,\n documentXml,\n boundaries,\n () => globalCursor,\n (next) => {\n globalCursor = next;\n },\n );\n\n if (!boundaries.has(globalCursor)) {\n boundaries.set(globalCursor, child.end - 4);\n }\n paragraphs.push({\n paragraphIndex,\n start: Math.min(...boundaries.keys()),\n end: Math.max(...boundaries.keys()),\n boundaries,\n });\n previousWasParagraph = true;\n }\n\n return paragraphs;\n}\n\nfunction walkParagraphForBoundaries(\n paragraph: XmlElementNode,\n sourceXml: string,\n boundaries: Map<number, number>,\n getCursor: () => number,\n setCursor: (next: number) => void,\n): void {\n for (const child of paragraph.children) {\n walkInlineNodeForBoundaries(child, sourceXml, boundaries, getCursor, setCursor);\n }\n}\n\nfunction walkInlineNodeForBoundaries(\n node: XmlNode,\n sourceXml: string,\n boundaries: Map<number, number>,\n getCursor: () => number,\n setCursor: (next: number) => void,\n): void {\n if (node.type !== \"element\") {\n return;\n }\n\n switch (localName(node.name)) {\n case \"r\": {\n if (!boundaries.has(getCursor())) {\n boundaries.set(getCursor(), node.start);\n }\n\n for (const child of node.children) {\n walkInlineNodeForBoundaries(child, sourceXml, boundaries, getCursor, setCursor);\n }\n\n boundaries.set(getCursor(), node.end);\n return;\n }\n case \"t\": {\n const text = node.children\n .filter((child): child is XmlTextNode => child.type === \"text\")\n .map((child) => child.text)\n .join(\"\");\n setCursor(getCursor() + Array.from(text).length);\n return;\n }\n case \"tab\":\n case \"br\": {\n const startCursor = getCursor();\n boundaries.set(startCursor, node.start);\n const nextCursor = startCursor + 1;\n boundaries.set(nextCursor, node.end);\n setCursor(nextCursor);\n return;\n }\n default:\n for (const child of node.children) {\n walkInlineNodeForBoundaries(child, sourceXml, boundaries, getCursor, setCursor);\n }\n }\n}\n\nfunction pushInsertion(\n insertions: Map<number, string[]>,\n index: number,\n xml: string,\n): void {\n const bucket = insertions.get(index);\n if (bucket) {\n bucket.push(xml);\n return;\n }\n\n insertions.set(index, [xml]);\n}\n\nfunction serializeText(text: string): string {\n const preserve = requiresPreservedSpace(text) ? ` xml:space=\"preserve\"` : \"\";\n return `<w:t${preserve}>${escapeXml(text)}</w:t>`;\n}\n\nfunction requiresPreservedSpace(text: string): boolean {\n return /^\\s/u.test(text) || /\\s$/u.test(text) || /\\s{2,}/u.test(text);\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction escapeAttribute(value: string): string {\n return escapeXml(value).replace(/\"/g, \""\");\n}\n\nfunction openingTagLength(xml: string, start: number): number {\n const end = xml.indexOf(\">\", start);\n if (end < 0) {\n throw new Error(\"Malformed XML: missing tag close.\");\n }\n\n return end - start + 1;\n}\n\nfunction parseXml(xml: string): XmlElementNode {\n const root: XmlElementNode = {\n type: \"element\",\n name: \"#document\",\n attributes: {},\n children: [],\n start: 0,\n end: xml.length,\n };\n const stack: XmlElementNode[] = [root];\n const tokenPattern =\n /<!--[\\s\\S]*?-->|<\\?[\\s\\S]*?\\?>|<!DOCTYPE[\\s\\S]*?>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>|<[^>]+>|[^<]+/gu;\n\n for (const match of xml.matchAll(tokenPattern)) {\n const token = match[0] ?? \"\";\n const start = match.index ?? 0;\n const end = start + token.length;\n\n if (token.startsWith(\"<?\") || token.startsWith(\"<!DOCTYPE\") || token.startsWith(\"<!--\")) {\n continue;\n }\n\n if (token.startsWith(\"<![CDATA[\")) {\n const text = token.slice(9, -3);\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text,\n start,\n end,\n });\n continue;\n }\n\n if (token.startsWith(\"</\")) {\n const node = stack.pop();\n if (!node) {\n throw new Error(\"Malformed XML: unexpected closing tag.\");\n }\n node.end = end;\n continue;\n }\n\n if (token.startsWith(\"<\")) {\n const selfClosing = /\\/>$/.test(token);\n const tagBody = token.slice(1, token.length - (selfClosing ? 2 : 1)).trim();\n const { name, attributes } = parseTag(tagBody);\n const node: XmlElementNode = {\n type: \"element\",\n name,\n attributes,\n children: [],\n start,\n end,\n };\n stack[stack.length - 1]?.children.push(node);\n if (!selfClosing) {\n stack.push(node);\n }\n continue;\n }\n\n const text = decodeXmlText(token);\n if (text.length > 0) {\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text,\n start,\n end,\n });\n }\n }\n\n if (stack.length !== 1) {\n throw new Error(\"Malformed XML: unclosed tag.\");\n }\n\n return root;\n}\n\nfunction parseTag(tagBody: string): { name: string; attributes: Record<string, string> } {\n const whitespaceIndex = tagBody.search(/\\s/u);\n const name = whitespaceIndex === -1 ? tagBody : tagBody.slice(0, whitespaceIndex);\n const rawAttributes = whitespaceIndex === -1 ? \"\" : tagBody.slice(whitespaceIndex + 1);\n const attributes: Record<string, string> = {};\n const pattern = /([A-Za-z_][A-Za-z0-9:._-]*)\\s*=\\s*(\"([^\"]*)\"|'([^']*)')/gu;\n\n for (const match of rawAttributes.matchAll(pattern)) {\n const key = match[1];\n const value = match[3] ?? match[4] ?? \"\";\n if (key) {\n attributes[key] = decodeXmlText(value);\n }\n }\n\n return { name, attributes };\n}\n\nfunction findChildElement(node: XmlElementNode, name: string): XmlElementNode {\n const match = node.children.find(\n (child): child is XmlElementNode =>\n child.type === \"element\" && localName(child.name) === name,\n );\n\n if (!match) {\n throw new Error(`Expected XML element ${name}.`);\n }\n\n return match;\n}\n\nfunction localName(name: string): string {\n const index = name.indexOf(\":\");\n return index === -1 ? name : name.slice(index + 1);\n}\n\nfunction decodeXmlText(text: string): string {\n return text.replace(\n /&(?:#x([0-9A-Fa-f]+)|#([0-9]+)|([A-Za-z]+));/gu,\n (_, hex, dec, named) => {\n if (hex) {\n return String.fromCodePoint(Number.parseInt(hex, 16));\n }\n if (dec) {\n return String.fromCodePoint(Number.parseInt(dec, 10));\n }\n\n switch (named) {\n case \"amp\":\n return \"&\";\n case \"lt\":\n return \"<\";\n case \"gt\":\n return \">\";\n case \"quot\":\n return \"\\\"\";\n case \"apos\":\n return \"'\";\n default:\n return `&${named};`;\n }\n },\n );\n}\n","import type {\n DocumentRootNode,\n HyperlinkNode,\n InlineNode,\n ParagraphNode,\n TextNode,\n} from \"../../model/canonical-document.ts\";\nimport type { CommentThread } from \"../../review/store/comment-store.ts\";\nimport type { RevisionRecord } from \"../../review/store/revision-types.ts\";\n\nexport function splitDocumentAtReviewBoundaries(\n content: DocumentRootNode,\n comments: readonly CommentThread[],\n revisions: readonly RevisionRecord[],\n): DocumentRootNode {\n const splitPositions = collectSplitPositions(comments, revisions);\n if (splitPositions.size === 0) {\n return content;\n }\n\n let cursor = 0;\n const children = content.children.map((block, index) => {\n if (index > 0 && content.children[index - 1]?.type === \"paragraph\" && block.type === \"paragraph\") {\n cursor += 1;\n }\n\n if (block.type !== \"paragraph\") {\n cursor += 1;\n return block;\n }\n\n const next = splitParagraph(block, splitPositions, cursor);\n cursor = next.cursor;\n return next.paragraph;\n });\n\n return {\n type: \"doc\",\n children,\n };\n}\n\nfunction collectSplitPositions(\n comments: readonly CommentThread[],\n revisions: readonly RevisionRecord[],\n): Set<number> {\n const positions = new Set<number>();\n\n for (const thread of comments) {\n if (thread.anchor.kind !== \"range\") {\n continue;\n }\n\n positions.add(thread.anchor.range.from);\n positions.add(thread.anchor.range.to);\n }\n\n for (const revision of revisions) {\n if (revision.status !== \"active\" || revision.anchor.kind !== \"range\") {\n continue;\n }\n\n if (\n revision.metadata.importedRevisionForm === \"paragraph-insertion\" ||\n revision.metadata.importedRevisionForm === \"paragraph-deletion\"\n ) {\n continue;\n }\n\n positions.add(revision.anchor.range.from);\n positions.add(revision.anchor.range.to);\n }\n\n return positions;\n}\n\nfunction splitParagraph(\n paragraph: ParagraphNode,\n splitPositions: ReadonlySet<number>,\n cursor: number,\n): { paragraph: ParagraphNode; cursor: number } {\n const children: InlineNode[] = [];\n let nextCursor = cursor;\n\n for (const child of paragraph.children) {\n if (child.type === \"text\") {\n const split = splitTextNode(child, splitPositions, nextCursor);\n children.push(...split.children);\n nextCursor = split.cursor;\n continue;\n }\n\n if (child.type === \"hyperlink\") {\n const split = splitHyperlinkNode(child, splitPositions, nextCursor);\n children.push(...split.children);\n nextCursor = split.cursor;\n continue;\n }\n\n children.push(child);\n nextCursor += 1;\n }\n\n return {\n paragraph: {\n ...paragraph,\n children,\n },\n cursor: nextCursor,\n };\n}\n\nfunction splitHyperlinkNode(\n node: HyperlinkNode,\n splitPositions: ReadonlySet<number>,\n cursor: number,\n): { children: HyperlinkNode[]; cursor: number } {\n let nextCursor = cursor;\n const groups: Array<HyperlinkNode[\"children\"]> = [[]];\n\n for (const child of node.children) {\n if (child.type === \"text\") {\n const split = splitTextNode(child, splitPositions, nextCursor);\n for (const piece of split.children) {\n groups[groups.length - 1]?.push(piece);\n nextCursor += Array.from(piece.text).length;\n if (splitPositions.has(nextCursor)) {\n groups.push([]);\n }\n }\n continue;\n }\n\n groups[groups.length - 1]?.push(child);\n nextCursor += 1;\n if (splitPositions.has(nextCursor)) {\n groups.push([]);\n }\n }\n\n const hyperlinks = groups\n .filter((children) => children.length > 0)\n .map((children) => ({\n type: \"hyperlink\" as const,\n href: node.href,\n children,\n }));\n\n return {\n children: hyperlinks.length > 0 ? hyperlinks : [node],\n cursor: nextCursor,\n };\n}\n\nfunction splitTextNode(\n node: TextNode,\n splitPositions: ReadonlySet<number>,\n cursor: number,\n): { children: TextNode[]; cursor: number } {\n const codepoints = Array.from(node.text);\n if (codepoints.length === 0) {\n return { children: [], cursor };\n }\n\n const boundaries = new Set<number>([0, codepoints.length]);\n for (let index = 1; index < codepoints.length; index += 1) {\n if (splitPositions.has(cursor + index)) {\n boundaries.add(index);\n }\n }\n\n const ordered = [...boundaries].sort((left, right) => left - right);\n const children: TextNode[] = [];\n\n for (let index = 0; index < ordered.length - 1; index += 1) {\n const start = ordered[index] ?? 0;\n const end = ordered[index + 1] ?? codepoints.length;\n const text = codepoints.slice(start, end).join(\"\");\n if (text.length === 0) {\n continue;\n }\n\n children.push({\n type: \"text\",\n text,\n ...(node.marks && node.marks.length > 0 ? { marks: node.marks } : {}),\n });\n }\n\n return {\n children: children.length > 0 ? children : [node],\n cursor: cursor + codepoints.length,\n };\n}\n","import type { RevisionRecord } from \"../../review/store/revision-types.ts\";\nimport {\n mapRevisionBoundaries,\n type RevisionParagraphBoundary,\n} from \"../ooxml/revision-boundaries.ts\";\n\ninterface XmlReplacement {\n start: number;\n end: number;\n replacement: string;\n}\n\nexport interface SerializedRuntimeRevisionsResult {\n documentXml: string;\n serializedRevisionIds: string[];\n skippedRevisionIds: string[];\n}\n\nexport function serializeRuntimeRevisionsIntoDocumentXml(\n documentXml: string,\n revisions: readonly RevisionRecord[],\n boundaries: readonly RevisionParagraphBoundary[] = mapRevisionBoundaries(documentXml),\n): SerializedRuntimeRevisionsResult {\n const replacements: XmlReplacement[] = [];\n const serializedRevisionIds: string[] = [];\n const skippedRevisionIds: string[] = [];\n const paragraphMarkers = new Map<\n number,\n { boundary: RevisionParagraphBoundary; markers: string[]; revisionIds: string[] }\n >();\n\n for (const revision of revisions) {\n if (revision.status !== \"active\" || revision.anchor.kind !== \"range\") {\n continue;\n }\n\n if (revision.kind !== \"insertion\" && revision.kind !== \"deletion\") {\n continue;\n }\n\n const form = revision.metadata.importedRevisionForm;\n if (form === \"paragraph-insertion\" || form === \"paragraph-deletion\") {\n const paragraphBoundary = findParagraphBoundaryForAnchor(boundaries, revision);\n if (!paragraphBoundary) {\n skippedRevisionIds.push(revision.revisionId);\n continue;\n }\n\n const entry = paragraphMarkers.get(paragraphBoundary.paragraphIndex) ?? {\n boundary: paragraphBoundary,\n markers: [],\n revisionIds: [],\n };\n entry.markers.push(createParagraphRevisionMarker(revision));\n entry.revisionIds.push(revision.revisionId);\n paragraphMarkers.set(paragraphBoundary.paragraphIndex, entry);\n serializedRevisionIds.push(revision.revisionId);\n continue;\n }\n\n const rangeReplacement = createRangeRevisionReplacement(documentXml, boundaries, revision);\n if (!rangeReplacement) {\n skippedRevisionIds.push(revision.revisionId);\n continue;\n }\n\n replacements.push(rangeReplacement);\n serializedRevisionIds.push(revision.revisionId);\n }\n\n for (const { boundary, markers, revisionIds } of paragraphMarkers.values()) {\n const paragraphInsertion = createParagraphRevisionInsertion(\n documentXml,\n boundary,\n markers,\n );\n if (!paragraphInsertion) {\n skippedRevisionIds.push(...revisionIds);\n continue;\n }\n\n replacements.push(paragraphInsertion);\n }\n\n return {\n documentXml: applyReplacements(documentXml, replacements),\n serializedRevisionIds,\n skippedRevisionIds,\n };\n}\n\nfunction createRangeRevisionReplacement(\n documentXml: string,\n boundaries: readonly RevisionParagraphBoundary[],\n revision: RevisionRecord,\n): XmlReplacement | undefined {\n const paragraphBoundary = findParagraphBoundaryForRange(boundaries, revision.anchor.range.from, revision.anchor.range.to);\n if (!paragraphBoundary) {\n return undefined;\n }\n\n const startIndex = paragraphBoundary.boundaries.get(revision.anchor.range.from);\n const endIndex = paragraphBoundary.boundaries.get(revision.anchor.range.to);\n if (startIndex === undefined || endIndex === undefined || endIndex < startIndex) {\n return undefined;\n }\n\n const xml = documentXml.slice(startIndex, endIndex);\n const attributes = serializeRevisionAttributes(revision);\n return {\n start: startIndex,\n end: endIndex,\n replacement:\n revision.kind === \"insertion\"\n ? `<w:ins${attributes}>${xml}</w:ins>`\n : `<w:del${attributes}>${convertRunsToDeletedContent(xml)}</w:del>`,\n };\n}\n\nfunction createParagraphRevisionMarker(revision: RevisionRecord): string {\n const markerName = revision.kind === \"insertion\" ? \"w:ins\" : \"w:del\";\n return `<${markerName}${serializeRevisionAttributes(revision)}/>`;\n}\n\nfunction createParagraphRevisionInsertion(\n documentXml: string,\n paragraphBoundary: RevisionParagraphBoundary,\n markers: readonly string[],\n): XmlReplacement | undefined {\n const paragraphXml = documentXml.slice(\n paragraphBoundary.paragraphStart,\n paragraphBoundary.paragraphEnd,\n );\n const markerXml = markers.join(\"\");\n const paragraphRunPropertiesInsertionIndex = findClosingTagInsertionIndex(\n documentXml,\n paragraphBoundary.paragraphRunPropertiesStart,\n paragraphBoundary.paragraphRunPropertiesEnd,\n \"w:rPr\",\n );\n if (paragraphRunPropertiesInsertionIndex !== undefined) {\n return {\n start: paragraphRunPropertiesInsertionIndex,\n end: paragraphRunPropertiesInsertionIndex,\n replacement: markerXml,\n };\n }\n\n const paragraphPropertiesInsertionIndex = findClosingTagInsertionIndex(\n documentXml,\n paragraphBoundary.paragraphPropertiesStart,\n paragraphBoundary.paragraphPropertiesEnd,\n \"w:pPr\",\n );\n if (paragraphPropertiesInsertionIndex !== undefined) {\n return {\n start: paragraphPropertiesInsertionIndex,\n end: paragraphPropertiesInsertionIndex,\n replacement: `<w:rPr>${markerXml}</w:rPr>`,\n };\n }\n\n if (!/<w:p[\\s>]/u.test(paragraphXml)) {\n return undefined;\n }\n\n return {\n start: paragraphBoundary.paragraphStartTagEnd,\n end: paragraphBoundary.paragraphStartTagEnd,\n replacement: `<w:pPr><w:rPr>${markerXml}</w:rPr></w:pPr>`,\n };\n}\n\nfunction findParagraphBoundaryForRange(\n boundaries: readonly RevisionParagraphBoundary[],\n from: number,\n to: number,\n): RevisionParagraphBoundary | undefined {\n return boundaries.find(\n (boundary) => from >= boundary.start && to <= boundary.end,\n );\n}\n\nfunction findParagraphBoundaryForAnchor(\n boundaries: readonly RevisionParagraphBoundary[],\n revision: RevisionRecord,\n): RevisionParagraphBoundary | undefined {\n const anchor = revision.anchor.kind === \"range\" ? revision.anchor.range.from : undefined;\n if (anchor === undefined) {\n return undefined;\n }\n\n return boundaries.find(\n (boundary) =>\n boundary.end === anchor ||\n (anchor >= boundary.start && anchor <= boundary.end),\n );\n}\n\nfunction serializeRevisionAttributes(revision: RevisionRecord): string {\n const attributes = {\n \"w:id\": revision.metadata.ooxmlRevisionId ?? sanitizeRevisionId(revision.revisionId),\n \"w:author\": revision.authorId,\n \"w:date\": revision.createdAt,\n };\n\n return Object.entries(attributes)\n .filter(([, value]) => value && value.length > 0)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join(\"\");\n}\n\nfunction findClosingTagInsertionIndex(\n documentXml: string,\n start: number | undefined,\n end: number | undefined,\n tagName: string,\n): number | undefined {\n if (start === undefined || end === undefined) {\n return undefined;\n }\n\n const closingTag = `</${tagName}>`;\n const closingIndex = documentXml.lastIndexOf(closingTag, end);\n if (closingIndex < start) {\n return undefined;\n }\n\n return closingIndex;\n}\n\nfunction sanitizeRevisionId(revisionId: string): string {\n const numericTail = /(\\d+)$/.exec(revisionId)?.[1];\n return numericTail ?? revisionId.replace(/[^A-Za-z0-9._-]/g, \"-\");\n}\n\nfunction convertRunsToDeletedContent(xml: string): string {\n return xml\n .replace(/<(\\/?)w:t\\b/g, \"<$1w:delText\")\n .replace(/<(\\/?)w:instrText\\b/g, \"<$1w:delInstrText\");\n}\n\nfunction applyReplacements(documentXml: string, replacements: readonly XmlReplacement[]): string {\n const sorted = replacements\n .slice()\n .sort((left, right) => right.start - left.start || right.end - left.end);\n let output = documentXml;\n\n for (const replacement of sorted) {\n output =\n output.slice(0, replacement.start) +\n replacement.replacement +\n output.slice(replacement.end);\n }\n\n return output;\n}\n\nfunction escapeAttribute(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","export const COMPATIBILITY_FEATURE_CLASSES = [\n \"supported-roundtrip\",\n \"preserve-only\",\n \"unsupported-fatal\",\n] as const;\n\nexport type CompatibilityFeatureClass =\n (typeof COMPATIBILITY_FEATURE_CLASSES)[number];\n\nexport const EDITOR_WARNING_CODES = [\n \"unsupported_ooxml_preserved\",\n \"unsupported_ooxml_locked\",\n \"import_normalized\",\n \"export_roundtrip_risk\",\n \"comment_anchor_detached\",\n \"revision_anchor_detached\",\n \"large_document_degraded\",\n \"font_substitution\",\n \"image_missing\",\n] as const;\n\nexport type EditorWarningCode = (typeof EDITOR_WARNING_CODES)[number];\n\nexport const EDITOR_WARNING_SOURCES = [\n \"import\",\n \"runtime\",\n \"review\",\n \"preservation\",\n \"validation\",\n \"export\",\n] as const;\n\nexport type EditorWarningSource = (typeof EDITOR_WARNING_SOURCES)[number];\n\nexport const EDITOR_ERROR_CODES = [\n \"import_failed\",\n \"export_failed\",\n \"package_corrupt\",\n \"validation_failed\",\n \"datastore_failed\",\n \"internal_invariant\",\n] as const;\n\nexport type EditorErrorCode = (typeof EDITOR_ERROR_CODES)[number];\n\nexport const EDITOR_ERROR_SOURCES = [\n \"import\",\n \"runtime\",\n \"validation\",\n \"datastore\",\n \"export\",\n] as const;\n\nexport type EditorErrorSource = (typeof EDITOR_ERROR_SOURCES)[number];\n\nexport type EditorAnchorProjection =\n | {\n kind: \"range\";\n from: number;\n to: number;\n assoc: {\n start: -1 | 1;\n end: -1 | 1;\n };\n }\n | {\n kind: \"node\";\n at: number;\n assoc: -1 | 1;\n }\n | {\n kind: \"detached\";\n lastKnownRange: {\n from: number;\n to: number;\n };\n reason: \"deleted\" | \"invalidatedByStructureChange\" | \"importAmbiguity\";\n };\n\nexport interface EditorWarning {\n warningId: string;\n code: EditorWarningCode;\n severity: \"info\" | \"warning\";\n message: string;\n source: EditorWarningSource;\n affectedAnchor?: EditorAnchorProjection;\n featureEntryId?: string;\n details?: Record<string, unknown>;\n}\n\nexport interface EditorError {\n errorId: string;\n code: EditorErrorCode;\n message: string;\n isFatal: boolean;\n source: EditorErrorSource;\n details?: Record<string, unknown>;\n}\n\nexport interface CompatibilityFeatureEntry<\n FeatureKey extends string = string,\n FeatureClass extends CompatibilityFeatureClass = CompatibilityFeatureClass,\n> {\n featureEntryId: string;\n featureKey: FeatureKey;\n featureClass: FeatureClass;\n message: string;\n affectedAnchor?: EditorAnchorProjection;\n details?: Record<string, unknown>;\n}\n\nexport interface CompatibilityDiagnostics<\n FeatureKey extends string = string,\n FeatureClass extends CompatibilityFeatureClass = CompatibilityFeatureClass,\n> {\n featureEntries: readonly CompatibilityFeatureEntry<FeatureKey, FeatureClass>[];\n warnings: readonly EditorWarning[];\n errors: readonly EditorError[];\n}\n\nconst EXPORT_BLOCKING_ERROR_CODES = new Set<EditorErrorCode>([\n \"import_failed\",\n \"export_failed\",\n \"package_corrupt\",\n \"validation_failed\",\n]);\n\nexport function isCompatibilityFeatureClass(\n value: string,\n): value is CompatibilityFeatureClass {\n return COMPATIBILITY_FEATURE_CLASSES.includes(\n value as CompatibilityFeatureClass,\n );\n}\n\nexport function isEditorWarningCode(value: string): value is EditorWarningCode {\n return EDITOR_WARNING_CODES.includes(value as EditorWarningCode);\n}\n\nexport function isEditorErrorCode(value: string): value is EditorErrorCode {\n return EDITOR_ERROR_CODES.includes(value as EditorErrorCode);\n}\n\nexport function createDiagnostics<\n FeatureKey extends string = string,\n FeatureClass extends CompatibilityFeatureClass = CompatibilityFeatureClass,\n>(\n input: Partial<CompatibilityDiagnostics<FeatureKey, FeatureClass>> = {},\n): CompatibilityDiagnostics<FeatureKey, FeatureClass> {\n return {\n featureEntries: freezeArray(input.featureEntries ?? []),\n warnings: freezeArray(input.warnings ?? []),\n errors: freezeArray(input.errors ?? []),\n };\n}\n\nexport function collectWarningIds(warnings: readonly EditorWarning[]): string[] {\n return warnings.map((warning) => warning.warningId);\n}\n\nexport function summarizeFeatureClasses<\n FeatureKey extends string,\n FeatureClass extends CompatibilityFeatureClass,\n>(\n featureEntries: readonly CompatibilityFeatureEntry<FeatureKey, FeatureClass>[],\n): Record<CompatibilityFeatureClass, number> {\n return featureEntries.reduce<Record<CompatibilityFeatureClass, number>>(\n (counts, entry) => {\n counts[entry.featureClass] += 1;\n return counts;\n },\n {\n \"supported-roundtrip\": 0,\n \"preserve-only\": 0,\n \"unsupported-fatal\": 0,\n },\n );\n}\n\nexport function diagnosticsBlockExport<\n FeatureKey extends string,\n FeatureClass extends CompatibilityFeatureClass,\n>(\n diagnostics: CompatibilityDiagnostics<FeatureKey, FeatureClass>,\n explicitBlockExport = false,\n): boolean {\n if (explicitBlockExport) {\n return true;\n }\n\n return (\n diagnostics.featureEntries.some(\n (entry) => entry.featureClass === \"unsupported-fatal\",\n ) ||\n diagnostics.errors.some(\n (error) => error.isFatal || EXPORT_BLOCKING_ERROR_CODES.has(error.code),\n )\n );\n}\n\nfunction freezeArray<Value>(items: readonly Value[]): readonly Value[] {\n return Object.freeze([...items]);\n}\n","import type {\n CompatibilityFeatureEntry,\n EditorError,\n} from \"../api/public-types.ts\";\nimport {\n createCorruptPackageError,\n createCorruptPackageDiagnosticsToken,\n type CorruptPackageIssue,\n} from \"../io/opc/corrupt-package.ts\";\nimport {\n createDiagnostics,\n diagnosticsBlockExport,\n type CompatibilityDiagnostics,\n} from \"./diagnostics.ts\";\n\nexport const IMPORT_FAILURE_STAGES = [\"package\", \"validation\"] as const;\n\nexport type ImportFailureStage = (typeof IMPORT_FAILURE_STAGES)[number];\n\nexport interface ImportDiagnosticsResult {\n mode: \"read-only-diagnostics\";\n readOnly: true;\n blockExport: true;\n fatalError: EditorError;\n diagnostics: CompatibilityDiagnostics;\n featureEntry: CompatibilityFeatureEntry;\n}\n\nexport function createPackageImportDiagnostics(input: {\n issue: CorruptPackageIssue;\n}): ImportDiagnosticsResult {\n const fatalError = createCorruptPackageError(input.issue);\n const featureEntry = {\n featureEntryId: `feature:${fatalError.errorId}`,\n featureKey: \"malformed-package\",\n featureClass: \"unsupported-fatal\",\n message: input.issue.message,\n details: {\n stage: \"package\",\n reason: input.issue.reason,\n diagnosticsToken: createCorruptPackageDiagnosticsToken(input.issue),\n },\n } satisfies CompatibilityFeatureEntry;\n\n const diagnostics = createDiagnostics({\n featureEntries: [featureEntry],\n warnings: [],\n errors: [fatalError],\n });\n\n return createReadOnlyDiagnosticsResult(featureEntry, diagnostics, fatalError);\n}\n\nexport function createValidationImportDiagnostics(input: {\n message: string;\n source?: EditorError[\"source\"];\n details?: Record<string, unknown>;\n}): ImportDiagnosticsResult {\n const diagnosticsToken = createImportDiagnosticsToken(\"validation\", input.message);\n const fatalError: EditorError = {\n errorId: `error:validation_failed:${diagnosticsToken}`,\n code: \"validation_failed\",\n message: input.message,\n isFatal: true,\n source: input.source ?? \"validation\",\n details: {\n stage: \"validation\",\n diagnosticsToken,\n ...(input.details ?? {}),\n },\n };\n const featureEntry = {\n featureEntryId: `feature:${fatalError.errorId}`,\n featureKey: \"openxml-validation\",\n featureClass: \"unsupported-fatal\",\n message: input.message,\n details: {\n stage: \"validation\",\n diagnosticsToken,\n },\n } satisfies CompatibilityFeatureEntry;\n const diagnostics = createDiagnostics({\n featureEntries: [featureEntry],\n warnings: [],\n errors: [fatalError],\n });\n\n return createReadOnlyDiagnosticsResult(featureEntry, diagnostics, fatalError);\n}\n\nexport function getImportFailureStage(error: Pick<EditorError, \"code\" | \"details\">): ImportFailureStage {\n if (error.code === \"package_corrupt\") {\n return \"package\";\n }\n\n const stage = error.details?.stage;\n return stage === \"package\" ? \"package\" : \"validation\";\n}\n\nfunction createReadOnlyDiagnosticsResult(\n featureEntry: CompatibilityFeatureEntry,\n diagnostics: CompatibilityDiagnostics,\n fatalError: EditorError,\n): ImportDiagnosticsResult {\n if (!diagnosticsBlockExport(diagnostics, true)) {\n throw new Error(\"Import diagnostics must conservatively block export.\");\n }\n\n return {\n mode: \"read-only-diagnostics\",\n readOnly: true,\n blockExport: true,\n fatalError,\n diagnostics,\n featureEntry,\n };\n}\n\nfunction createImportDiagnosticsToken(stage: ImportFailureStage, message: string): string {\n let hash = 2166136261;\n const text = `${stage}:${message}`;\n for (let index = 0; index < text.length; index += 1) {\n hash ^= text.charCodeAt(index);\n hash = Math.imul(hash, 16777619) >>> 0;\n }\n\n return `${stage}-${hash.toString(16).padStart(8, \"0\")}`;\n}\n","import type {\n CompatibilityReport,\n EditorWarning,\n ExportDocxOptions,\n ExportResult,\n PersistedEditorSnapshot,\n RuntimeRenderSnapshot,\n} from \"../api/public-types.ts\";\nimport { createCanonicalDocumentId } from \"../core/state/editor-state.ts\";\nimport type { ImportDiagnosticsResult } from \"../validation/import-diagnostics.ts\";\n\nexport interface ReadOnlyDiagnosticsRuntime {\n getRenderSnapshot(): RuntimeRenderSnapshot;\n getPersistedSnapshot(): PersistedEditorSnapshot;\n getCompatibilityReport(): CompatibilityReport;\n getWarnings(): EditorWarning[];\n dispatch(command: { type: string }): never;\n undo(): never;\n redo(): never;\n exportDocx(options?: ExportDocxOptions): Promise<ExportResult>;\n}\n\nexport function createReadOnlyDiagnosticsRuntime(input: {\n documentId: string;\n sourceLabel?: string;\n editorBuild: string;\n generatedAt: string;\n diagnostics: ImportDiagnosticsResult;\n}): ReadOnlyDiagnosticsRuntime {\n const persistedSnapshot = createDiagnosticsSnapshot(input);\n const renderSnapshot = createDiagnosticsRenderSnapshot(input, persistedSnapshot);\n\n return {\n getRenderSnapshot() {\n return renderSnapshot;\n },\n getPersistedSnapshot() {\n return persistedSnapshot;\n },\n getCompatibilityReport() {\n return persistedSnapshot.compatibility;\n },\n getWarnings() {\n return persistedSnapshot.warningLog;\n },\n dispatch(command) {\n throw createReadOnlyDiagnosticsModeError(command.type);\n },\n undo() {\n throw createReadOnlyDiagnosticsModeError(\"history.undo\");\n },\n redo() {\n throw createReadOnlyDiagnosticsModeError(\"history.redo\");\n },\n async exportDocx(options) {\n void options;\n throw new Error(\n \"DOCX export is blocked in read-only diagnostics mode because the imported package is not safe to rewrite.\",\n );\n },\n };\n}\n\nfunction createDiagnosticsSnapshot(input: {\n documentId: string;\n editorBuild: string;\n generatedAt: string;\n diagnostics: ImportDiagnosticsResult;\n}): PersistedEditorSnapshot {\n const docId = createCanonicalDocumentId(input.documentId);\n const diagnosticId = `diagnostic:${sanitizeDiagnosticsToken(input.documentId)}`;\n\n return {\n snapshotVersion: \"persisted-editor-snapshot/1\",\n schemaVersion: \"cds/1.0.0\",\n documentId: input.documentId,\n docId,\n createdAt: input.generatedAt,\n updatedAt: input.generatedAt,\n savedAt: input.generatedAt,\n editorBuild: input.editorBuild,\n canonicalDocument: {\n schemaVersion: \"cds/1.0.0\",\n docId,\n createdAt: input.generatedAt,\n updatedAt: input.generatedAt,\n metadata: {\n customProperties: {},\n importMode: input.diagnostics.mode,\n },\n styles: {\n paragraphs: {},\n characters: {},\n tables: {},\n },\n numbering: {\n abstractDefinitions: {},\n instances: {},\n },\n media: {\n items: {},\n },\n content: {\n type: \"doc\",\n children: [{ type: \"paragraph\", children: [] }],\n },\n review: {\n comments: {},\n revisions: {},\n },\n preservation: {\n opaqueFragments: {},\n packageParts: {},\n },\n diagnostics: {\n warnings: [],\n errors: [\n {\n diagnosticId,\n code: input.diagnostics.fatalError.code,\n message: input.diagnostics.fatalError.message,\n isFatal: input.diagnostics.fatalError.isFatal,\n source: input.diagnostics.fatalError.source,\n details: input.diagnostics.fatalError.details,\n },\n ],\n },\n },\n compatibility: {\n reportVersion: \"compatibility-report/1\",\n generatedAt: input.generatedAt,\n blockExport: true,\n featureEntries: [...input.diagnostics.diagnostics.featureEntries],\n warnings: [...input.diagnostics.diagnostics.warnings],\n errors: [...input.diagnostics.diagnostics.errors],\n },\n warningLog: [],\n };\n}\n\nfunction createDiagnosticsRenderSnapshot(\n input: {\n documentId: string;\n sourceLabel?: string;\n diagnostics: ImportDiagnosticsResult;\n },\n persistedSnapshot: PersistedEditorSnapshot,\n): RuntimeRenderSnapshot {\n return {\n documentId: input.documentId,\n sessionId: `${input.documentId}-diagnostics`,\n sourceLabel: input.sourceLabel,\n revisionToken: `${input.documentId}:diagnostics`,\n isReady: true,\n isDirty: false,\n readOnly: true,\n selection: collapsedSelection(),\n documentStats: {\n storyLength: 0,\n commentCount: 0,\n revisionCount: 0,\n opaqueFragmentCount: 0,\n },\n comments: {\n openCommentIds: [],\n resolvedCommentIds: [],\n detachedCommentIds: [],\n totalCount: 0,\n threads: [],\n },\n trackedChanges: {\n pendingChangeIds: [],\n acceptedChangeIds: [],\n rejectedChangeIds: [],\n detachedChangeIds: [],\n actionableChangeIds: [],\n preserveOnlyChangeIds: [],\n totalCount: 0,\n revisions: [],\n },\n compatibility: {\n blockExport: true,\n blockExportReasons: [persistedSnapshot.compatibility.errors[0]?.message ?? input.diagnostics.featureEntry.message],\n warningCount: persistedSnapshot.compatibility.warnings.length,\n errorCount: persistedSnapshot.compatibility.errors.length,\n featureEntries: [...persistedSnapshot.compatibility.featureEntries],\n },\n warnings: [],\n fatalError: input.diagnostics.fatalError,\n commandState: {\n canUndo: false,\n canRedo: false,\n readOnly: true,\n },\n };\n}\n\nfunction collapsedSelection(): RuntimeRenderSnapshot[\"selection\"] {\n return {\n anchor: 0,\n head: 0,\n isCollapsed: true,\n activeRange: {\n kind: \"range\",\n from: 0,\n to: 0,\n assoc: {\n start: -1,\n end: 1,\n },\n },\n };\n}\n\nfunction createReadOnlyDiagnosticsModeError(commandType: string): Error {\n const error = new Error(\n `Command ${commandType} is blocked in read-only diagnostics mode.`,\n );\n Object.assign(error, {\n code: \"import_failed\",\n details: {\n mode: \"read-only-diagnostics\",\n commandType,\n },\n });\n return error;\n}\n\nfunction sanitizeDiagnosticsToken(documentId: string): string {\n const collapsed = documentId.replace(/[^A-Za-z0-9._-]/g, \"-\");\n return collapsed.length > 0 ? `read-only-${collapsed}` : \"read-only-diagnostics\";\n}\n","import type {\n BlockNode,\n FootnoteRefNode,\n HeaderFooterVariant,\n InlineNode,\n ParagraphNode,\n TextMark,\n} from \"../../model/canonical-document.ts\";\n\n// ---- Public types ----\n\nexport interface ParsedHeaderFooterReference {\n variant: HeaderFooterVariant;\n relationshipId: string;\n kind: \"header\" | \"footer\";\n}\n\nexport interface ParsedHeaderFooterDocument {\n blocks: BlockNode[];\n}\n\n// ---- XML node types (inline, no external dep) ----\n\ninterface XmlElementNode {\n type: \"element\";\n name: string;\n attributes: Record<string, string>;\n children: XmlNode[];\n}\n\ninterface XmlTextNode {\n type: \"text\";\n text: string;\n}\n\ntype XmlNode = XmlElementNode | XmlTextNode;\n\n// ---- Public API ----\n\n/**\n * Scan a document body XML for w:headerReference / w:footerReference elements\n * inside w:sectPr and return the relationship references.\n */\nexport function parseHeaderFooterReferences(\n documentXml: string,\n): ParsedHeaderFooterReference[] {\n const root = parseXml(documentXml);\n const documentElement = findChildElementOptional(root, \"document\");\n if (!documentElement) {\n return [];\n }\n\n const bodyElement = findChildElementOptional(documentElement, \"body\");\n if (!bodyElement) {\n return [];\n }\n\n const refs: ParsedHeaderFooterReference[] = [];\n\n // Collect all sectPr elements (can appear in paragraph pPr and at body level)\n collectSectPrReferences(bodyElement, refs);\n\n return refs;\n}\n\n/**\n * Parse a headerN.xml part (<w:hdr> root) into block nodes.\n */\nexport function parseHeaderXml(xml: string): ParsedHeaderFooterDocument {\n return parseHdrFtrXml(xml, \"hdr\");\n}\n\n/**\n * Parse a footerN.xml part (<w:ftr> root) into block nodes.\n */\nexport function parseFooterXml(xml: string): ParsedHeaderFooterDocument {\n return parseHdrFtrXml(xml, \"ftr\");\n}\n\n// ---- Internal helpers ----\n\nfunction collectSectPrReferences(\n element: XmlElementNode,\n refs: ParsedHeaderFooterReference[],\n): void {\n for (const child of element.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n\n if (name === \"sectPr\") {\n extractSectPrRefs(child, refs);\n } else if (name === \"p\") {\n // Check paragraph properties for sectPr\n const pPr = findChildElementOptional(child, \"pPr\");\n if (pPr) {\n const sectPr = findChildElementOptional(pPr, \"sectPr\");\n if (sectPr) {\n extractSectPrRefs(sectPr, refs);\n }\n }\n }\n }\n}\n\nfunction extractSectPrRefs(\n sectPr: XmlElementNode,\n refs: ParsedHeaderFooterReference[],\n): void {\n for (const child of sectPr.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n if (name === \"headerReference\" || name === \"footerReference\") {\n const kind: \"header\" | \"footer\" = name === \"headerReference\" ? \"header\" : \"footer\";\n const rawType =\n child.attributes[\"w:type\"] ?? child.attributes.type ?? \"default\";\n const variant = toHeaderFooterVariant(rawType);\n const relationshipId =\n child.attributes[\"r:id\"] ??\n child.attributes[\"r:Id\"] ??\n child.attributes.id ??\n child.attributes.Id ??\n \"\";\n\n if (relationshipId) {\n // Avoid duplicates (multiple sectPr may reference same header)\n const alreadyAdded = refs.some(\n (ref) => ref.relationshipId === relationshipId && ref.kind === kind,\n );\n if (!alreadyAdded) {\n refs.push({ variant, relationshipId, kind });\n }\n }\n }\n }\n}\n\nfunction toHeaderFooterVariant(raw: string): HeaderFooterVariant {\n if (raw === \"first\") {\n return \"first\";\n }\n if (raw === \"even\") {\n return \"even\";\n }\n return \"default\";\n}\n\nfunction parseHdrFtrXml(\n xml: string,\n rootLocalName: \"hdr\" | \"ftr\",\n): ParsedHeaderFooterDocument {\n const root = parseXml(xml);\n const hdrFtrElement = findChildElementOptional(root, rootLocalName);\n if (!hdrFtrElement) {\n return { blocks: [] };\n }\n\n const blocks: BlockNode[] = [];\n\n for (const child of hdrFtrElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n\n if (name === \"p\") {\n blocks.push(parseParagraphElement(child));\n } else if (name === \"tbl\") {\n // Table in header/footer: store as opaque to preserve fidelity\n blocks.push({\n type: \"opaque_block\",\n fragmentId: \"fragment:hdrftr-tbl\",\n warningId: \"warning:hdrftr-opaque-table\",\n });\n } else {\n // Other block-level elements: treat as opaque\n blocks.push({\n type: \"opaque_block\",\n fragmentId: \"fragment:hdrftr-opaque\",\n warningId: \"warning:hdrftr-opaque-block\",\n });\n }\n }\n\n return { blocks };\n}\n\nfunction parseParagraphElement(pElement: XmlElementNode): ParagraphNode {\n let styleId: string | undefined;\n let alignment: ParagraphNode[\"alignment\"];\n const children: InlineNode[] = [];\n\n for (const child of pElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n\n if (name === \"pPr\") {\n const pStyle = findChildElementOptional(child, \"pStyle\");\n styleId = pStyle?.attributes[\"w:val\"] ?? pStyle?.attributes.val;\n const jc = findChildElementOptional(child, \"jc\");\n const jcVal = jc?.attributes[\"w:val\"] ?? jc?.attributes.val;\n if (jcVal === \"left\" || jcVal === \"center\" || jcVal === \"right\" || jcVal === \"both\" || jcVal === \"distribute\") {\n alignment = jcVal;\n }\n } else if (name === \"r\") {\n children.push(...parseRunElement(child));\n } else if (name === \"hyperlink\") {\n // Simplified: collect text children from hyperlink runs\n for (const hChild of child.children) {\n if (hChild.type === \"element\" && localName(hChild.name) === \"r\") {\n children.push(...parseRunElement(hChild));\n }\n }\n } else if (name === \"bookmarkStart\" || name === \"bookmarkEnd\") {\n // Skip bookmark nodes in headers/footers\n } else if (name === \"fldChar\" || name === \"instrText\") {\n // Skip field chars, handled via run parsing\n }\n }\n\n return {\n type: \"paragraph\",\n ...(styleId ? { styleId } : {}),\n ...(alignment ? { alignment } : {}),\n children,\n };\n}\n\nfunction parseRunElement(rElement: XmlElementNode): InlineNode[] {\n const nodes: InlineNode[] = [];\n const marks: TextMark[] = parseRunProperties(rElement);\n\n for (const child of rElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n\n if (name === \"t\") {\n const text = extractTextContent(child);\n if (text.length > 0) {\n nodes.push({\n type: \"text\",\n text,\n ...(marks.length > 0 ? { marks } : {}),\n });\n }\n } else if (name === \"br\") {\n nodes.push({ type: \"hard_break\" });\n } else if (name === \"tab\") {\n nodes.push({ type: \"tab\" });\n } else if (name === \"footnoteReference\") {\n const noteId =\n child.attributes[\"w:id\"] ?? child.attributes.id ?? \"\";\n if (noteId) {\n const ref: FootnoteRefNode = {\n type: \"footnote_ref\",\n noteId,\n noteKind: \"footnote\",\n };\n nodes.push(ref);\n }\n } else if (name === \"endnoteReference\") {\n const noteId =\n child.attributes[\"w:id\"] ?? child.attributes.id ?? \"\";\n if (noteId) {\n const ref: FootnoteRefNode = {\n type: \"footnote_ref\",\n noteId,\n noteKind: \"endnote\",\n };\n nodes.push(ref);\n }\n }\n }\n\n return nodes;\n}\n\nfunction parseRunProperties(rElement: XmlElementNode): TextMark[] {\n const rPr = findChildElementOptional(rElement, \"rPr\");\n if (!rPr) {\n return [];\n }\n\n const marks: TextMark[] = [];\n\n for (const child of rPr.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n const val = child.attributes[\"w:val\"] ?? child.attributes.val ?? \"true\";\n\n switch (name) {\n case \"b\":\n if (val !== \"0\" && val !== \"false\") {\n marks.push({ type: \"bold\" });\n }\n break;\n case \"i\":\n if (val !== \"0\" && val !== \"false\") {\n marks.push({ type: \"italic\" });\n }\n break;\n case \"u\":\n if (val !== \"none\" && val !== \"0\") {\n marks.push({ type: \"underline\" });\n }\n break;\n case \"strike\":\n if (val !== \"0\" && val !== \"false\") {\n marks.push({ type: \"strikethrough\" });\n }\n break;\n case \"dstrike\":\n if (val !== \"0\" && val !== \"false\") {\n marks.push({ type: \"doubleStrikethrough\" });\n }\n break;\n }\n }\n\n return marks;\n}\n\nfunction extractTextContent(tElement: XmlElementNode): string {\n let text = \"\";\n for (const child of tElement.children) {\n if (child.type === \"text\") {\n text += child.text;\n }\n }\n return text;\n}\n\nfunction findChildElementOptional(\n node: XmlElementNode,\n childLocalName: string,\n): XmlElementNode | undefined {\n return node.children.find(\n (entry): entry is XmlElementNode =>\n entry.type === \"element\" && localName(entry.name) === childLocalName,\n );\n}\n\nfunction localName(name: string): string {\n const separatorIndex = name.indexOf(\":\");\n return separatorIndex >= 0 ? name.slice(separatorIndex + 1) : name;\n}\n\n// ---- Minimal XML parser (same pattern as parse-numbering.ts) ----\n\nfunction parseXml(xml: string): XmlElementNode {\n const root: XmlElementNode = {\n type: \"element\",\n name: \"__root__\",\n attributes: {},\n children: [],\n };\n const stack: XmlElementNode[] = [root];\n let cursor = 0;\n\n while (cursor < xml.length) {\n if (xml.startsWith(\"<!--\", cursor)) {\n const end = xml.indexOf(\"-->\", cursor);\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<?\", cursor)) {\n const end = xml.indexOf(\"?>\", cursor);\n cursor = end >= 0 ? end + 2 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<![CDATA[\", cursor)) {\n const end = xml.indexOf(\"]]>\", cursor);\n const textEnd = end >= 0 ? end : xml.length;\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text: xml.slice(cursor + 9, textEnd),\n });\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml[cursor] !== \"<\") {\n const nextTag = xml.indexOf(\"<\", cursor);\n const end = nextTag >= 0 ? nextTag : xml.length;\n const text = decodeXmlEntities(xml.slice(cursor, end));\n if (text.trim().length > 0 || (text.length > 0 && stack.length > 1)) {\n stack[stack.length - 1]?.children.push({ type: \"text\", text });\n }\n cursor = end;\n continue;\n }\n\n // Closing tag\n if (xml[cursor + 1] === \"/\") {\n const end = xml.indexOf(\">\", cursor);\n if (end < 0) {\n break;\n }\n stack.pop();\n cursor = end + 1;\n continue;\n }\n\n // Open or self-closing tag\n const tagEnd = xml.indexOf(\">\", cursor);\n if (tagEnd < 0) {\n break;\n }\n\n const tagContent = xml.slice(cursor + 1, tagEnd);\n const selfClosing = tagContent.endsWith(\"/\");\n const normalized = selfClosing ? tagContent.slice(0, -1).trimEnd() : tagContent;\n\n const spaceIndex = normalized.search(/\\s/);\n const tagName =\n spaceIndex >= 0 ? normalized.slice(0, spaceIndex) : normalized;\n const attrString =\n spaceIndex >= 0 ? normalized.slice(spaceIndex + 1) : \"\";\n const attributes = parseAttributes(attrString);\n\n const element: XmlElementNode = {\n type: \"element\",\n name: tagName,\n attributes,\n children: [],\n };\n\n stack[stack.length - 1]?.children.push(element);\n\n if (!selfClosing) {\n stack.push(element);\n }\n\n cursor = tagEnd + 1;\n }\n\n return root;\n}\n\nfunction parseAttributes(attrString: string): Record<string, string> {\n const attrs: Record<string, string> = {};\n const pattern = /([A-Za-z_:][A-Za-z0-9:._-]*)\\s*=\\s*(\"([^\"]*)\"|'([^']*)')/gu;\n\n for (const match of attrString.matchAll(pattern)) {\n const name = match[1];\n const value = match[3] ?? match[4] ?? \"\";\n if (name) {\n attrs[name] = decodeXmlEntities(value);\n }\n }\n\n return attrs;\n}\n\nfunction decodeXmlEntities(text: string): string {\n return text\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/&#(\\d+);/g, (_, dec) => String.fromCodePoint(Number.parseInt(dec, 10)))\n .replace(/&#x([0-9a-fA-F]+);/g, (_, hex) =>\n String.fromCodePoint(Number.parseInt(hex, 16)),\n );\n}\n","import type {\n BlockNode,\n FootnoteCollection,\n FootnoteDefinition,\n InlineNode,\n ParagraphNode,\n TextMark,\n} from \"../../model/canonical-document.ts\";\n\n// ---- XML node types (inline, no external dep) ----\n\ninterface XmlElementNode {\n type: \"element\";\n name: string;\n attributes: Record<string, string>;\n children: XmlNode[];\n}\n\ninterface XmlTextNode {\n type: \"text\";\n text: string;\n}\n\ntype XmlNode = XmlElementNode | XmlTextNode;\n\n// ---- Special footnote/endnote IDs to skip ----\n\nconst SPECIAL_NOTE_IDS = new Set([\"-1\", \"0\"]);\nconst SPECIAL_NOTE_TYPES = new Set([\"separator\", \"continuationSeparator\"]);\n\n// ---- Public API ----\n\n/**\n * Parse footnotes.xml (<w:footnotes> root) into a FootnoteCollection.\n * Also accepts endnotes.xml (<w:endnotes> root).\n */\nexport function parseFootnotesXml(xml: string): FootnoteCollection {\n const root = parseXml(xml);\n\n const footnotesElement = findChildElementOptional(root, \"footnotes\");\n const endnotesElement = findChildElementOptional(root, \"endnotes\");\n\n const footnotes: Record<string, FootnoteDefinition> = {};\n const endnotes: Record<string, FootnoteDefinition> = {};\n\n if (footnotesElement) {\n for (const child of footnotesElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n if (localName(child.name) !== \"footnote\") {\n continue;\n }\n const definition = parseNoteElement(child, \"footnote\");\n if (definition) {\n footnotes[definition.noteId] = definition;\n }\n }\n }\n\n if (endnotesElement) {\n for (const child of endnotesElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n if (localName(child.name) !== \"endnote\") {\n continue;\n }\n const definition = parseNoteElement(child, \"endnote\");\n if (definition) {\n endnotes[definition.noteId] = definition;\n }\n }\n }\n\n return { footnotes, endnotes };\n}\n\n/**\n * Parse a standalone endnotes.xml (<w:endnotes> root).\n * Merges into the provided collection or creates a new one.\n */\nexport function parseEndnotesXml(\n xml: string,\n existing?: FootnoteCollection,\n): FootnoteCollection {\n const root = parseXml(xml);\n const endnotesElement = findChildElementOptional(root, \"endnotes\");\n const endnotes: Record<string, FootnoteDefinition> = {\n ...(existing?.endnotes ?? {}),\n };\n\n if (endnotesElement) {\n for (const child of endnotesElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n if (localName(child.name) !== \"endnote\") {\n continue;\n }\n const definition = parseNoteElement(child, \"endnote\");\n if (definition) {\n endnotes[definition.noteId] = definition;\n }\n }\n }\n\n return {\n footnotes: existing?.footnotes ?? {},\n endnotes,\n };\n}\n\n// ---- Internal helpers ----\n\nfunction parseNoteElement(\n element: XmlElementNode,\n kind: \"footnote\" | \"endnote\",\n): FootnoteDefinition | undefined {\n const rawId =\n element.attributes[\"w:id\"] ?? element.attributes.id ?? \"\";\n const rawType =\n element.attributes[\"w:type\"] ?? element.attributes.type ?? \"\";\n\n if (!rawId || SPECIAL_NOTE_IDS.has(rawId) || SPECIAL_NOTE_TYPES.has(rawType)) {\n return undefined;\n }\n\n const noteId = rawId;\n const blocks: BlockNode[] = [];\n\n for (const child of element.children) {\n if (child.type !== \"element\") {\n continue;\n }\n const name = localName(child.name);\n if (name === \"p\") {\n blocks.push(parseParagraphElement(child));\n } else if (name === \"tbl\") {\n blocks.push({\n type: \"opaque_block\",\n fragmentId: `fragment:note-tbl-${noteId}`,\n warningId: `warning:note-opaque-table`,\n });\n } else {\n blocks.push({\n type: \"opaque_block\",\n fragmentId: `fragment:note-opaque-${noteId}`,\n warningId: `warning:note-opaque-block`,\n });\n }\n }\n\n return { noteId, kind, blocks };\n}\n\nfunction parseParagraphElement(pElement: XmlElementNode): ParagraphNode {\n let styleId: string | undefined;\n const children: InlineNode[] = [];\n\n for (const child of pElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n\n if (name === \"pPr\") {\n const pStyle = findChildElementOptional(child, \"pStyle\");\n styleId = pStyle?.attributes[\"w:val\"] ?? pStyle?.attributes.val;\n } else if (name === \"r\") {\n children.push(...parseRunElement(child));\n } else if (name === \"hyperlink\") {\n for (const hChild of child.children) {\n if (hChild.type === \"element\" && localName(hChild.name) === \"r\") {\n children.push(...parseRunElement(hChild));\n }\n }\n }\n }\n\n return {\n type: \"paragraph\",\n ...(styleId ? { styleId } : {}),\n children,\n };\n}\n\nfunction parseRunElement(rElement: XmlElementNode): InlineNode[] {\n const nodes: InlineNode[] = [];\n const marks: TextMark[] = parseRunProperties(rElement);\n\n for (const child of rElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n\n if (name === \"t\") {\n const text = extractTextContent(child);\n if (text.length > 0) {\n nodes.push({\n type: \"text\",\n text,\n ...(marks.length > 0 ? { marks } : {}),\n });\n }\n } else if (name === \"br\") {\n nodes.push({ type: \"hard_break\" });\n } else if (name === \"tab\") {\n nodes.push({ type: \"tab\" });\n } else if (name === \"footnoteRef\" || name === \"endnoteRef\") {\n // The in-note reference marker (superscript) - skip, rendered by the host\n } else if (name === \"footnoteReference\") {\n const noteId =\n child.attributes[\"w:id\"] ?? child.attributes.id ?? \"\";\n if (noteId) {\n nodes.push({ type: \"footnote_ref\", noteId, noteKind: \"footnote\" });\n }\n } else if (name === \"endnoteReference\") {\n const noteId =\n child.attributes[\"w:id\"] ?? child.attributes.id ?? \"\";\n if (noteId) {\n nodes.push({ type: \"footnote_ref\", noteId, noteKind: \"endnote\" });\n }\n }\n }\n\n return nodes;\n}\n\nfunction parseRunProperties(rElement: XmlElementNode): TextMark[] {\n const rPr = findChildElementOptional(rElement, \"rPr\");\n if (!rPr) {\n return [];\n }\n\n const marks: TextMark[] = [];\n\n for (const child of rPr.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n const val = child.attributes[\"w:val\"] ?? child.attributes.val ?? \"true\";\n\n switch (name) {\n case \"b\":\n if (val !== \"0\" && val !== \"false\") marks.push({ type: \"bold\" });\n break;\n case \"i\":\n if (val !== \"0\" && val !== \"false\") marks.push({ type: \"italic\" });\n break;\n case \"u\":\n if (val !== \"none\" && val !== \"0\") marks.push({ type: \"underline\" });\n break;\n case \"strike\":\n if (val !== \"0\" && val !== \"false\") marks.push({ type: \"strikethrough\" });\n break;\n }\n }\n\n return marks;\n}\n\nfunction extractTextContent(tElement: XmlElementNode): string {\n let text = \"\";\n for (const child of tElement.children) {\n if (child.type === \"text\") {\n text += child.text;\n }\n }\n return text;\n}\n\nfunction findChildElementOptional(\n node: XmlElementNode,\n childLocalName: string,\n): XmlElementNode | undefined {\n return node.children.find(\n (entry): entry is XmlElementNode =>\n entry.type === \"element\" && localName(entry.name) === childLocalName,\n );\n}\n\nfunction localName(name: string): string {\n const idx = name.indexOf(\":\");\n return idx >= 0 ? name.slice(idx + 1) : name;\n}\n\n// ---- Minimal XML parser (same pattern as parse-numbering.ts) ----\n\nfunction parseXml(xml: string): XmlElementNode {\n const root: XmlElementNode = {\n type: \"element\",\n name: \"__root__\",\n attributes: {},\n children: [],\n };\n const stack: XmlElementNode[] = [root];\n let cursor = 0;\n\n while (cursor < xml.length) {\n if (xml.startsWith(\"<!--\", cursor)) {\n const end = xml.indexOf(\"-->\", cursor);\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<?\", cursor)) {\n const end = xml.indexOf(\"?>\", cursor);\n cursor = end >= 0 ? end + 2 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<![CDATA[\", cursor)) {\n const end = xml.indexOf(\"]]>\", cursor);\n const textEnd = end >= 0 ? end : xml.length;\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text: xml.slice(cursor + 9, textEnd),\n });\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml[cursor] !== \"<\") {\n const nextTag = xml.indexOf(\"<\", cursor);\n const end = nextTag >= 0 ? nextTag : xml.length;\n const text = decodeXmlEntities(xml.slice(cursor, end));\n if (text.trim().length > 0 || (text.length > 0 && stack.length > 1)) {\n stack[stack.length - 1]?.children.push({ type: \"text\", text });\n }\n cursor = end;\n continue;\n }\n\n if (xml[cursor + 1] === \"/\") {\n const end = xml.indexOf(\">\", cursor);\n if (end < 0) break;\n stack.pop();\n cursor = end + 1;\n continue;\n }\n\n const tagEnd = xml.indexOf(\">\", cursor);\n if (tagEnd < 0) break;\n\n const tagContent = xml.slice(cursor + 1, tagEnd);\n const selfClosing = tagContent.endsWith(\"/\");\n const normalized = selfClosing ? tagContent.slice(0, -1).trimEnd() : tagContent;\n\n const spaceIndex = normalized.search(/\\s/);\n const tagName = spaceIndex >= 0 ? normalized.slice(0, spaceIndex) : normalized;\n const attrString = spaceIndex >= 0 ? normalized.slice(spaceIndex + 1) : \"\";\n const attributes = parseAttributes(attrString);\n\n const element: XmlElementNode = {\n type: \"element\",\n name: tagName,\n attributes,\n children: [],\n };\n\n stack[stack.length - 1]?.children.push(element);\n\n if (!selfClosing) {\n stack.push(element);\n }\n\n cursor = tagEnd + 1;\n }\n\n return root;\n}\n\nfunction parseAttributes(attrString: string): Record<string, string> {\n const attrs: Record<string, string> = {};\n const pattern = /([A-Za-z_:][A-Za-z0-9:._-]*)\\s*=\\s*(\"([^\"]*)\"|'([^']*)')/gu;\n for (const match of attrString.matchAll(pattern)) {\n const name = match[1];\n const value = match[3] ?? match[4] ?? \"\";\n if (name) {\n attrs[name] = decodeXmlEntities(value);\n }\n }\n return attrs;\n}\n\nfunction decodeXmlEntities(text: string): string {\n return text\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/&#(\\d+);/g, (_, dec) => String.fromCodePoint(Number.parseInt(dec, 10)))\n .replace(/&#x([0-9a-fA-F]+);/g, (_, hex) =>\n String.fromCodePoint(Number.parseInt(hex, 16)),\n );\n}\n","import type {\n ThemeColorScheme,\n ThemeDefinition,\n ThemeFontScheme,\n} from \"../../model/canonical-document.ts\";\n\n// ---- XML node types (inline, no external dep) ----\n\ninterface XmlElementNode {\n type: \"element\";\n name: string;\n attributes: Record<string, string>;\n children: XmlNode[];\n}\n\ninterface XmlTextNode {\n type: \"text\";\n text: string;\n}\n\ntype XmlNode = XmlElementNode | XmlTextNode;\n\n// ---- Well-known DrawingML color slot names ----\n\nconst COLOR_SLOTS = [\n \"dk1\",\n \"lt1\",\n \"dk2\",\n \"lt2\",\n \"accent1\",\n \"accent2\",\n \"accent3\",\n \"accent4\",\n \"accent5\",\n \"accent6\",\n \"hlink\",\n \"folHlink\",\n] as const;\n\n// ---- Public API ----\n\n/**\n * Parse a DrawingML theme1.xml part into a ThemeDefinition.\n * Returns an empty ThemeDefinition if the XML is empty or malformed.\n */\nexport function parseThemeXml(xml: string): ThemeDefinition {\n if (!xml.trim()) {\n return {};\n }\n\n const root = parseXml(xml);\n const themeElement = findChildElementOptional(root, \"theme\");\n if (!themeElement) {\n return {};\n }\n\n const themeName =\n themeElement.attributes[\"name\"] ??\n themeElement.attributes[\"a:name\"] ??\n undefined;\n\n const themeElements = findChildElementOptional(themeElement, \"themeElements\");\n if (!themeElements) {\n return { ...(themeName ? { name: themeName } : {}) };\n }\n\n const colorScheme = parseColorScheme(\n findChildElementOptional(themeElements, \"clrScheme\"),\n );\n const fontScheme = parseFontScheme(\n findChildElementOptional(themeElements, \"fontScheme\"),\n );\n\n const result: ThemeDefinition = {};\n if (themeName) {\n result.name = themeName;\n }\n if (colorScheme) {\n result.colorScheme = colorScheme;\n }\n if (fontScheme) {\n result.fontScheme = fontScheme;\n }\n\n return result;\n}\n\n// ---- Internal helpers ----\n\nfunction parseColorScheme(\n element: XmlElementNode | undefined,\n): ThemeColorScheme | undefined {\n if (!element) {\n return undefined;\n }\n\n const schemeName =\n element.attributes[\"name\"] ?? element.attributes[\"a:name\"] ?? \"\";\n const colors: Record<string, string> = {};\n\n for (const slot of COLOR_SLOTS) {\n const slotElement = findChildElementOptional(element, slot);\n if (!slotElement) {\n continue;\n }\n\n const color = extractColorValue(slotElement);\n if (color) {\n colors[slot] = color;\n }\n }\n\n return { name: schemeName, colors };\n}\n\nfunction extractColorValue(slotElement: XmlElementNode): string | undefined {\n for (const child of slotElement.children) {\n if (child.type !== \"element\") {\n continue;\n }\n\n const name = localName(child.name);\n\n if (name === \"srgbClr\") {\n const val = child.attributes[\"val\"] ?? child.attributes[\"a:val\"] ?? \"\";\n if (val) {\n return `#${val.toUpperCase()}`;\n }\n } else if (name === \"sysClr\") {\n // Use lastClr as the resolved color value\n const lastClr =\n child.attributes[\"lastClr\"] ??\n child.attributes[\"a:lastClr\"] ??\n \"\";\n if (lastClr) {\n return `#${lastClr.toUpperCase()}`;\n }\n }\n }\n\n return undefined;\n}\n\nfunction parseFontScheme(\n element: XmlElementNode | undefined,\n): ThemeFontScheme | undefined {\n if (!element) {\n return undefined;\n }\n\n const schemeName =\n element.attributes[\"name\"] ?? element.attributes[\"a:name\"] ?? \"\";\n\n const majorFontElement = findChildElementOptional(element, \"majorFont\");\n const minorFontElement = findChildElementOptional(element, \"minorFont\");\n\n const majorFont = majorFontElement\n ? extractFontTypeface(majorFontElement)\n : undefined;\n const minorFont = minorFontElement\n ? extractFontTypeface(minorFontElement)\n : undefined;\n\n const result: ThemeFontScheme = { name: schemeName };\n if (majorFont) {\n result.majorFont = majorFont;\n }\n if (minorFont) {\n result.minorFont = minorFont;\n }\n\n return result;\n}\n\nfunction extractFontTypeface(\n fontGroupElement: XmlElementNode,\n): string | undefined {\n const latinElement = findChildElementOptional(fontGroupElement, \"latin\");\n if (latinElement) {\n return (\n latinElement.attributes[\"typeface\"] ??\n latinElement.attributes[\"a:typeface\"] ??\n undefined\n );\n }\n return undefined;\n}\n\nfunction findChildElementOptional(\n node: XmlElementNode,\n childLocalName: string,\n): XmlElementNode | undefined {\n return node.children.find(\n (entry): entry is XmlElementNode =>\n entry.type === \"element\" && localName(entry.name) === childLocalName,\n );\n}\n\nfunction localName(name: string): string {\n const idx = name.indexOf(\":\");\n return idx >= 0 ? name.slice(idx + 1) : name;\n}\n\n// ---- Minimal XML parser ----\n\nfunction parseXml(xml: string): XmlElementNode {\n const root: XmlElementNode = {\n type: \"element\",\n name: \"__root__\",\n attributes: {},\n children: [],\n };\n const stack: XmlElementNode[] = [root];\n let cursor = 0;\n\n while (cursor < xml.length) {\n if (xml.startsWith(\"<!--\", cursor)) {\n const end = xml.indexOf(\"-->\", cursor);\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<?\", cursor)) {\n const end = xml.indexOf(\"?>\", cursor);\n cursor = end >= 0 ? end + 2 : xml.length;\n continue;\n }\n\n if (xml.startsWith(\"<![CDATA[\", cursor)) {\n const end = xml.indexOf(\"]]>\", cursor);\n const textEnd = end >= 0 ? end : xml.length;\n stack[stack.length - 1]?.children.push({\n type: \"text\",\n text: xml.slice(cursor + 9, textEnd),\n });\n cursor = end >= 0 ? end + 3 : xml.length;\n continue;\n }\n\n if (xml[cursor] !== \"<\") {\n const nextTag = xml.indexOf(\"<\", cursor);\n const end = nextTag >= 0 ? nextTag : xml.length;\n const text = decodeXmlEntities(xml.slice(cursor, end));\n if (text.trim().length > 0 || (text.length > 0 && stack.length > 1)) {\n stack[stack.length - 1]?.children.push({ type: \"text\", text });\n }\n cursor = end;\n continue;\n }\n\n if (xml[cursor + 1] === \"/\") {\n const end = xml.indexOf(\">\", cursor);\n if (end < 0) break;\n stack.pop();\n cursor = end + 1;\n continue;\n }\n\n const tagEnd = xml.indexOf(\">\", cursor);\n if (tagEnd < 0) break;\n\n const tagContent = xml.slice(cursor + 1, tagEnd);\n const selfClosing = tagContent.endsWith(\"/\");\n const normalized = selfClosing ? tagContent.slice(0, -1).trimEnd() : tagContent;\n\n const spaceIndex = normalized.search(/\\s/);\n const tagName = spaceIndex >= 0 ? normalized.slice(0, spaceIndex) : normalized;\n const attrString = spaceIndex >= 0 ? normalized.slice(spaceIndex + 1) : \"\";\n const attributes = parseAttributes(attrString);\n\n const element: XmlElementNode = {\n type: \"element\",\n name: tagName,\n attributes,\n children: [],\n };\n\n stack[stack.length - 1]?.children.push(element);\n\n if (!selfClosing) {\n stack.push(element);\n }\n\n cursor = tagEnd + 1;\n }\n\n return root;\n}\n\nfunction parseAttributes(attrString: string): Record<string, string> {\n const attrs: Record<string, string> = {};\n const pattern = /([A-Za-z_:][A-Za-z0-9:._-]*)\\s*=\\s*(\"([^\"]*)\"|'([^']*)')/gu;\n for (const match of attrString.matchAll(pattern)) {\n const name = match[1];\n const value = match[3] ?? match[4] ?? \"\";\n if (name) {\n attrs[name] = decodeXmlEntities(value);\n }\n }\n return attrs;\n}\n\nfunction decodeXmlEntities(text: string): string {\n return text\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/&#(\\d+);/g, (_, dec) => String.fromCodePoint(Number.parseInt(dec, 10)))\n .replace(/&#x([0-9a-fA-F]+);/g, (_, hex) =>\n String.fromCodePoint(Number.parseInt(hex, 16)),\n );\n}\n","import type {\n FooterDocument,\n HeaderDocument,\n InlineNode,\n ParagraphNode,\n TextMark,\n} from \"../../model/canonical-document.ts\";\n\nexport const WORD_HEADER_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml\";\nexport const WORD_FOOTER_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml\";\n\nconst W_NS = `xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"`;\nconst R_NS = `xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"`;\n\n/**\n * Serialize a HeaderDocument into a headerN.xml string.\n */\nexport function serializeHeaderXml(header: HeaderDocument): string {\n const body = serializeBlocks(header.blocks);\n return [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n `<w:hdr ${W_NS} ${R_NS}>${body}</w:hdr>`,\n ].join(\"\\n\");\n}\n\n/**\n * Serialize a FooterDocument into a footerN.xml string.\n */\nexport function serializeFooterXml(footer: FooterDocument): string {\n const body = serializeBlocks(footer.blocks);\n return [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n `<w:ftr ${W_NS} ${R_NS}>${body}</w:ftr>`,\n ].join(\"\\n\");\n}\n\n// ---- Internal serialization ----\n\nfunction serializeBlocks(\n blocks: HeaderDocument[\"blocks\"] | FooterDocument[\"blocks\"],\n): string {\n if (blocks.length === 0) {\n // A valid header/footer must have at least one paragraph\n return `<w:p><w:r><w:t></w:t></w:r></w:p>`;\n }\n\n return blocks\n .map((block) => {\n if (block.type === \"paragraph\") {\n return serializeParagraph(block);\n }\n // opaque_block: emit empty paragraph to preserve structure\n return `<w:p/>`;\n })\n .join(\"\");\n}\n\nfunction serializeParagraph(paragraph: ParagraphNode): string {\n let xml = \"<w:p>\";\n\n const propertiesXml = buildParagraphPropertiesXml(paragraph);\n if (propertiesXml) {\n xml += propertiesXml;\n }\n\n const childrenXml = paragraph.children\n .map((child) => serializeInlineNode(child))\n .join(\"\");\n xml += childrenXml || \"<w:r><w:t></w:t></w:r>\";\n xml += \"</w:p>\";\n\n return xml;\n}\n\nfunction buildParagraphPropertiesXml(paragraph: ParagraphNode): string {\n const parts: string[] = [];\n\n if (paragraph.styleId) {\n parts.push(`<w:pStyle w:val=\"${escapeAttribute(paragraph.styleId)}\"/>`);\n }\n if (paragraph.alignment) {\n parts.push(`<w:jc w:val=\"${escapeAttribute(paragraph.alignment)}\"/>`);\n }\n\n return parts.length > 0 ? `<w:pPr>${parts.join(\"\")}</w:pPr>` : \"\";\n}\n\nfunction serializeInlineNode(node: InlineNode): string {\n switch (node.type) {\n case \"text\": {\n const properties = buildRunPropertiesXml(node.marks);\n const preserve = requiresPreservedSpace(node.text)\n ? ` xml:space=\"preserve\"`\n : \"\";\n return `<w:r>${properties}<w:t${preserve}>${escapeXml(node.text)}</w:t></w:r>`;\n }\n case \"tab\":\n return \"<w:r><w:tab/></w:r>\";\n case \"hard_break\":\n return \"<w:r><w:br/></w:r>\";\n case \"footnote_ref\": {\n const refElement =\n node.noteKind === \"footnote\"\n ? `<w:footnoteReference w:id=\"${escapeAttribute(node.noteId)}\"/>`\n : `<w:endnoteReference w:id=\"${escapeAttribute(node.noteId)}\"/>`;\n return `<w:r><w:rPr><w:rStyle w:val=\"${node.noteKind === \"footnote\" ? \"FootnoteReference\" : \"EndnoteReference\"}\"/></w:rPr>${refElement}</w:r>`;\n }\n case \"opaque_inline\":\n // Cannot reproduce opaque inline content without original XML; emit empty\n return \"\";\n case \"hyperlink\": {\n const childrenXml = node.children\n .map((child) => {\n switch (child.type) {\n case \"text\": {\n const properties = buildRunPropertiesXml(undefined);\n const preserve = requiresPreservedSpace(child.text)\n ? ` xml:space=\"preserve\"`\n : \"\";\n return `<w:r>${properties}<w:t${preserve}>${escapeXml(child.text)}</w:t></w:r>`;\n }\n case \"tab\":\n return \"<w:r><w:tab/></w:r>\";\n case \"hard_break\":\n return \"<w:r><w:br/></w:r>\";\n default:\n return \"\";\n }\n })\n .join(\"\");\n // Hyperlinks in headers/footers typically use bookmark anchors or external URLs.\n // Emit as a plain run since we don't retain the relationship ID here.\n return childrenXml;\n }\n case \"image\":\n case \"field\":\n case \"bookmark_start\":\n case \"bookmark_end\":\n case \"column_break\":\n case \"symbol\":\n // These node types are not parsed from headers/footers by parse-headers-footers.ts\n return \"\";\n }\n}\n\nfunction buildRunPropertiesXml(marks: TextMark[] | undefined): string {\n if (!marks || marks.length === 0) {\n return \"\";\n }\n\n const parts: string[] = [];\n for (const mark of marks) {\n switch (mark.type) {\n case \"bold\":\n parts.push(\"<w:b/>\");\n break;\n case \"italic\":\n parts.push(\"<w:i/>\");\n break;\n case \"underline\":\n parts.push(\"<w:u w:val=\\\"single\\\"/>\");\n break;\n case \"strikethrough\":\n parts.push(\"<w:strike/>\");\n break;\n case \"doubleStrikethrough\":\n parts.push(\"<w:dstrike/>\");\n break;\n default:\n // Other mark types not parsed from headers/footers\n break;\n }\n }\n\n return parts.length > 0 ? `<w:rPr>${parts.join(\"\")}</w:rPr>` : \"\";\n}\n\nfunction requiresPreservedSpace(text: string): boolean {\n return (\n text.length > 0 &&\n (text[0] === \" \" || text[text.length - 1] === \" \" || text.includes(\" \"))\n );\n}\n\nfunction escapeXml(text: string): string {\n return text\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction escapeAttribute(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type {\n FootnoteCollection,\n FootnoteDefinition,\n InlineNode,\n ParagraphNode,\n TextMark,\n} from \"../../model/canonical-document.ts\";\n\nexport const WORD_FOOTNOTES_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml\";\nexport const WORD_ENDNOTES_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml\";\n\nconst W_NS = `xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"`;\nconst R_NS = `xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"`;\n\n/**\n * Serialize the footnotes portion of a FootnoteCollection to footnotes.xml.\n * Includes the required separator and continuation-separator stubs.\n */\nexport function serializeFootnotesXml(collection: FootnoteCollection): string {\n const entries = Object.values(collection.footnotes).sort(compareNoteIds);\n const body = [\n serializeSeparatorStub(\"footnote\", \"-1\", \"separator\"),\n serializeSeparatorStub(\"footnote\", \"0\", \"continuationSeparator\"),\n ...entries.map((entry) => serializeNoteDefinition(\"footnote\", entry)),\n ].join(\"\");\n\n return [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n `<w:footnotes ${W_NS} ${R_NS}>${body}</w:footnotes>`,\n ].join(\"\\n\");\n}\n\n/**\n * Serialize the endnotes portion of a FootnoteCollection to endnotes.xml.\n * Includes the required separator and continuation-separator stubs.\n */\nexport function serializeEndnotesXml(collection: FootnoteCollection): string {\n const entries = Object.values(collection.endnotes).sort(compareNoteIds);\n const body = [\n serializeSeparatorStub(\"endnote\", \"-1\", \"separator\"),\n serializeSeparatorStub(\"endnote\", \"0\", \"continuationSeparator\"),\n ...entries.map((entry) => serializeNoteDefinition(\"endnote\", entry)),\n ].join(\"\");\n\n return [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n `<w:endnotes ${W_NS} ${R_NS}>${body}</w:endnotes>`,\n ].join(\"\\n\");\n}\n\n// ---- Internal serialization ----\n\nfunction serializeSeparatorStub(\n kind: \"footnote\" | \"endnote\",\n id: string,\n type: \"separator\" | \"continuationSeparator\",\n): string {\n const tag = kind === \"footnote\" ? \"w:footnote\" : \"w:endnote\";\n return `<${tag} w:type=\"${type}\" w:id=\"${id}\"><w:p/></${tag}>`;\n}\n\nfunction serializeNoteDefinition(\n kind: \"footnote\" | \"endnote\",\n definition: FootnoteDefinition,\n): string {\n const tag = kind === \"footnote\" ? \"w:footnote\" : \"w:endnote\";\n const blocks = definition.blocks\n .map((block) => {\n if (block.type === \"paragraph\") {\n return serializeParagraph(block);\n }\n // opaque_block: emit empty paragraph\n return `<w:p/>`;\n })\n .join(\"\");\n\n const body = blocks || `<w:p><w:r><w:t></w:t></w:r></w:p>`;\n return `<${tag} w:id=\"${escapeAttribute(definition.noteId)}\">${body}</${tag}>`;\n}\n\nfunction serializeParagraph(paragraph: ParagraphNode): string {\n let xml = \"<w:p>\";\n\n const propertiesXml = buildParagraphPropertiesXml(paragraph);\n if (propertiesXml) {\n xml += propertiesXml;\n }\n\n const childrenXml = paragraph.children\n .map((child) => serializeInlineNode(child))\n .join(\"\");\n xml += childrenXml || \"<w:r><w:t></w:t></w:r>\";\n xml += \"</w:p>\";\n\n return xml;\n}\n\nfunction buildParagraphPropertiesXml(paragraph: ParagraphNode): string {\n const parts: string[] = [];\n\n if (paragraph.styleId) {\n parts.push(`<w:pStyle w:val=\"${escapeAttribute(paragraph.styleId)}\"/>`);\n }\n if (paragraph.alignment) {\n parts.push(`<w:jc w:val=\"${escapeAttribute(paragraph.alignment)}\"/>`);\n }\n\n return parts.length > 0 ? `<w:pPr>${parts.join(\"\")}</w:pPr>` : \"\";\n}\n\nfunction serializeInlineNode(node: InlineNode): string {\n switch (node.type) {\n case \"text\": {\n const properties = buildRunPropertiesXml(node.marks);\n const preserve = requiresPreservedSpace(node.text)\n ? ` xml:space=\"preserve\"`\n : \"\";\n return `<w:r>${properties}<w:t${preserve}>${escapeXml(node.text)}</w:t></w:r>`;\n }\n case \"tab\":\n return \"<w:r><w:tab/></w:r>\";\n case \"hard_break\":\n return \"<w:r><w:br/></w:r>\";\n case \"footnote_ref\": {\n const refElement =\n node.noteKind === \"footnote\"\n ? `<w:footnoteReference w:id=\"${escapeAttribute(node.noteId)}\"/>`\n : `<w:endnoteReference w:id=\"${escapeAttribute(node.noteId)}\"/>`;\n const styleVal =\n node.noteKind === \"footnote\"\n ? \"FootnoteReference\"\n : \"EndnoteReference\";\n return `<w:r><w:rPr><w:rStyle w:val=\"${styleVal}\"/></w:rPr>${refElement}</w:r>`;\n }\n case \"opaque_inline\":\n return \"\";\n case \"hyperlink\": {\n return node.children\n .map((child) => {\n if (child.type === \"text\") {\n const preserve = requiresPreservedSpace(child.text)\n ? ` xml:space=\"preserve\"`\n : \"\";\n return `<w:r><w:t${preserve}>${escapeXml(child.text)}</w:t></w:r>`;\n }\n if (child.type === \"tab\") return \"<w:r><w:tab/></w:r>\";\n if (child.type === \"hard_break\") return \"<w:r><w:br/></w:r>\";\n return \"\";\n })\n .join(\"\");\n }\n default:\n return \"\";\n }\n}\n\nfunction buildRunPropertiesXml(marks: TextMark[] | undefined): string {\n if (!marks || marks.length === 0) {\n return \"\";\n }\n\n const parts: string[] = [];\n for (const mark of marks) {\n switch (mark.type) {\n case \"bold\":\n parts.push(\"<w:b/>\");\n break;\n case \"italic\":\n parts.push(\"<w:i/>\");\n break;\n case \"underline\":\n parts.push(\"<w:u w:val=\\\"single\\\"/>\");\n break;\n case \"strikethrough\":\n parts.push(\"<w:strike/>\");\n break;\n case \"doubleStrikethrough\":\n parts.push(\"<w:dstrike/>\");\n break;\n default:\n break;\n }\n }\n\n return parts.length > 0 ? `<w:rPr>${parts.join(\"\")}</w:rPr>` : \"\";\n}\n\nfunction compareNoteIds(\n left: FootnoteDefinition,\n right: FootnoteDefinition,\n): number {\n return Number.parseInt(left.noteId, 10) - Number.parseInt(right.noteId, 10);\n}\n\nfunction requiresPreservedSpace(text: string): boolean {\n return (\n text.length > 0 &&\n (text[0] === \" \" || text[text.length - 1] === \" \" || text.includes(\" \"))\n );\n}\n\nfunction escapeXml(text: string): string {\n return text\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction escapeAttribute(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type {\n CompatibilityReport as PublicCompatibilityReport,\n EditorError,\n EditorWarning as PublicEditorWarning,\n EditorAnchorProjection as PublicEditorAnchorProjection,\n ExportDocxOptions,\n ExportResult,\n PersistedEditorSnapshot,\n} from \"../api/public-types.ts\";\nimport type {\n CanonicalDocumentEnvelope,\n CompatibilityFeatureEntry as InternalCompatibilityFeatureEntry,\n CompatibilityReport as InternalCompatibilityReport,\n CommentThreadRecord,\n EditorError as InternalEditorError,\n RevisionRecord as RuntimeRevisionRecord,\n EditorWarning as InternalEditorWarning,\n} from \"../core/state/editor-state.ts\";\nimport { createCanonicalDocumentId } from \"../core/state/editor-state.ts\";\nimport {\n createDetachedAnchor,\n type EditorAnchorProjection as InternalEditorAnchorProjection,\n} from \"../core/selection/mapping.ts\";\nimport { DOCX_MIME_TYPE } from \"./opc/docx-package.ts\";\nimport { readOpcPackage, type OpcPackage } from \"./opc/package-reader.ts\";\nimport { parseMainDocumentXml } from \"./ooxml/parse-main-document.ts\";\nimport { normalizeParsedTextDocument } from \"./normalize/normalize-text.ts\";\nimport {\n normalizePartPath,\n resolveRelationshipTarget,\n type OpcRelationship,\n} from \"./ooxml/part-manifest.ts\";\nimport {\n classifyCorruptPackageError,\n createBrokenRelationshipIssue,\n createMissingPartIssue,\n} from \"./opc/corrupt-package.ts\";\nimport { createExportSession } from \"./export/export-session.ts\";\nimport { serializeMainDocument } from \"./export/serialize-main-document.ts\";\nimport { parseRevisionsFromDocumentXml, type ParsedRevisionsResult } from \"./ooxml/parse-revisions.ts\";\nimport { parseCommentsFromOoxml } from \"./ooxml/parse-comments.ts\";\nimport { parseNumberingXml } from \"./ooxml/parse-numbering.ts\";\nimport {\n createCommentExportIdMap,\n serializeCommentAnchorsIntoDocumentXml,\n serializeMergedCommentsXml,\n} from \"./export/serialize-comments.ts\";\nimport { splitDocumentAtReviewBoundaries } from \"./export/split-review-boundaries.ts\";\nimport { serializeRuntimeRevisionsIntoDocumentXml } from \"./export/serialize-runtime-revisions.ts\";\nimport { createCommentStoreFromRuntimeComments } from \"../review/store/runtime-comment-store.ts\";\nimport type { CommentThread } from \"../review/store/comment-store.ts\";\nimport type { RevisionRecord as ReviewRevisionRecord } from \"../review/store/revision-types.ts\";\nimport { getRevisionActionability } from \"../review/store/revision-types.ts\";\nimport { buildCompatibilityReport } from \"../validation/compatibility-engine.ts\";\nimport {\n createPackageImportDiagnostics,\n createValidationImportDiagnostics,\n type ImportDiagnosticsResult,\n} from \"../validation/import-diagnostics.ts\";\nimport type {\n FootnoteCollection,\n HeaderDocument,\n FooterDocument,\n MediaCatalog,\n NumberingCatalog,\n OpaqueFragmentRecord,\n PreservedPackagePart,\n SubPartsCatalog,\n} from \"../model/canonical-document.ts\";\nimport { createCanonicalDocumentSignature } from \"../model/canonical-document.ts\";\nimport type {\n CommentImportDiagnostic,\n ImportedCommentDefinition,\n ParsedCommentsResult,\n} from \"./ooxml/parse-comments.ts\";\nimport { createReadOnlyDiagnosticsRuntime } from \"../runtime/read-only-diagnostics-runtime.ts\";\nimport {\n WORD_NUMBERING_CONTENT_TYPE,\n serializeNumberingXml,\n} from \"./export/serialize-numbering.ts\";\nimport {\n parseHeaderFooterReferences,\n parseHeaderXml,\n parseFooterXml,\n} from \"./ooxml/parse-headers-footers.ts\";\nimport { parseFootnotesXml, parseEndnotesXml } from \"./ooxml/parse-footnotes.ts\";\nimport { parseThemeXml } from \"./ooxml/parse-theme.ts\";\nimport {\n serializeHeaderXml,\n serializeFooterXml,\n WORD_HEADER_CONTENT_TYPE,\n WORD_FOOTER_CONTENT_TYPE,\n} from \"./export/serialize-headers-footers.ts\";\nimport {\n serializeFootnotesXml,\n serializeEndnotesXml,\n WORD_FOOTNOTES_CONTENT_TYPE,\n WORD_ENDNOTES_CONTENT_TYPE,\n} from \"./export/serialize-footnotes.ts\";\n\nconst MAIN_DOCUMENT_PATH = \"/word/document.xml\";\nconst NUMBERING_PART_PATH = \"/word/numbering.xml\";\nconst COMMENTS_PART_PATH = \"/word/comments.xml\";\nconst COMMENTS_EXTENDED_PART_PATH = \"/word/commentsExtended.xml\";\nconst COMMENTS_IDS_PART_PATH = \"/word/commentsIds.xml\";\nconst PEOPLE_PART_PATH = \"/word/people.xml\";\nconst MAIN_DOCUMENT_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\";\nconst NUMBERING_RELATIONSHIP_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering\";\nconst COMMENTS_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml\";\nconst COMMENTS_EXTENDED_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml\";\nconst COMMENTS_IDS_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.commentsIds+xml\";\nconst PEOPLE_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.people+xml\";\nconst COMMENTS_RELATIONSHIP_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments\";\nconst COMMENTS_EXTENDED_RELATIONSHIP_TYPE =\n \"http://schemas.microsoft.com/office/2011/relationships/commentsExtended\";\nconst COMMENTS_IDS_RELATIONSHIP_TYPE =\n \"http://schemas.microsoft.com/office/2016/09/relationships/commentsIds\";\nconst PEOPLE_RELATIONSHIP_TYPE =\n \"http://schemas.microsoft.com/office/2011/relationships/people\";\nconst HEADER_RELATIONSHIP_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/header\";\nconst FOOTER_RELATIONSHIP_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer\";\nconst FOOTNOTES_RELATIONSHIP_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes\";\nconst ENDNOTES_RELATIONSHIP_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes\";\nconst FOOTNOTES_PART_PATH = \"/word/footnotes.xml\";\nconst ENDNOTES_PART_PATH = \"/word/endnotes.xml\";\n\ninterface LoadDocxEditorSessionOptions {\n documentId: string;\n sourceLabel?: string;\n bytes: Uint8Array | ArrayBuffer;\n editorBuild: string;\n}\n\nexport interface LoadedDocxEditorSession {\n initialSnapshot: PersistedEditorSnapshot;\n fatalError?: EditorError;\n readOnly: boolean;\n exportDocx: (\n snapshot: PersistedEditorSnapshot,\n options?: ExportDocxOptions,\n ) => Promise<ExportResult>;\n}\n\ninterface ImportedDocxState {\n sourceBytes: Uint8Array;\n sourcePackage: OpcPackage;\n sourceDocumentRelationships: readonly OpcRelationship[];\n sourceDocumentAttributes: Record<string, string>;\n sourceNumberingPartPath?: string;\n sourceNumberingRelationshipId?: string;\n sourceCommentsPartPath?: string;\n sourceCommentsRelationshipId?: string;\n sourceCommentsRootTag?: string;\n sourceCommentsExtendedPartPath?: string;\n sourceCommentsExtendedRelationshipId?: string;\n sourceCommentsExtendedRootTag?: string;\n sourceCommentsIdsPartPath?: string;\n sourceCommentsIdsRelationshipId?: string;\n sourceCommentsIdsRootTag?: string;\n sourcePeoplePartPath?: string;\n sourcePeopleRelationshipId?: string;\n sourcePeopleRootTag?: string;\n sourcePeopleAuthors: readonly string[];\n preservedCommentDefinitions: readonly ImportedCommentDefinition[];\n blockingCommentDiagnostics: readonly CommentImportDiagnostic[];\n initialCanonicalSignature: string;\n sourceSubPartPaths: {\n headers: Array<{ partPath: string; relationshipId: string }>;\n footers: Array<{ partPath: string; relationshipId: string }>;\n footnotesPartPath?: string;\n footnotesRelationshipId?: string;\n endnotesPartPath?: string;\n endnotesRelationshipId?: string;\n themePartPath?: string;\n themeRelationshipId?: string;\n };\n}\n\ninterface NormalizedImportedCommentsResult extends ParsedCommentsResult {\n preservedDefinitions: readonly ImportedCommentDefinition[];\n}\n\nconst BLOCKING_COMMENT_DIAGNOSTIC_CODES = new Set<CommentImportDiagnostic[\"code\"]>([\n \"missing_comment_definition\",\n \"missing_anchor_reference\",\n \"multi_paragraph_anchor_preserve_only\",\n \"opaque_anchor_preserve_only\",\n \"preserve_only_revision_overlap\",\n]);\n\nexport function loadDocxEditorSession(\n options: LoadDocxEditorSessionOptions,\n): LoadedDocxEditorSession {\n const sourceBytes = toUint8Array(options.bytes);\n let sourcePackage: OpcPackage;\n\n try {\n sourcePackage = readOpcPackage(sourceBytes);\n } catch (error) {\n return createDiagnosticsSession(\n options,\n createPackageImportDiagnostics({\n issue: classifyCorruptPackageError(error),\n }),\n );\n }\n\n const brokenRelationshipIssues = collectBrokenInternalRelationshipIssues(sourcePackage);\n if (brokenRelationshipIssues.length > 0) {\n return createDiagnosticsSession(\n options,\n createPackageImportDiagnostics({\n issue: {\n ...brokenRelationshipIssues[0],\n message: summarizeBrokenRelationshipIssues(brokenRelationshipIssues),\n details: {\n issueCount: brokenRelationshipIssues.length,\n targets: brokenRelationshipIssues.map((issue) => issue.targetPartPath).filter(Boolean),\n },\n },\n }),\n );\n }\n\n const documentPart = sourcePackage.parts.get(MAIN_DOCUMENT_PATH);\n if (!documentPart) {\n return createDiagnosticsSession(\n options,\n createPackageImportDiagnostics({\n issue: createMissingPartIssue(MAIN_DOCUMENT_PATH),\n }),\n );\n }\n\n try {\n const sourceDocumentXml = decodeUtf8(documentPart.bytes);\n const importedRevisions = parseRevisionsFromDocumentXml(sourceDocumentXml);\n const numberingPartPath = resolveDocumentRelatedPartPath(\n sourcePackage,\n documentPart.relationships,\n NUMBERING_RELATIONSHIP_TYPE,\n NUMBERING_PART_PATH,\n );\n const parsedNumbering = numberingPartPath\n ? parseNumberingXml(\n decodeUtf8(sourcePackage.parts.get(numberingPartPath)?.bytes ?? new Uint8Array()),\n )\n : createEmptyNumberingCatalog();\n const mediaParts = collectInlineMediaParts(sourcePackage);\n const parsedDocument = parseMainDocumentXml(\n sourceDocumentXml,\n documentPart.relationships,\n mediaParts,\n MAIN_DOCUMENT_PATH,\n );\n const normalizedDocument = normalizeParsedTextDocument(\n parsedDocument,\n MAIN_DOCUMENT_PATH,\n );\n const commentsPartPath = resolveCommentsPartPath(sourcePackage, documentPart.relationships);\n const commentsExtendedPartPath = resolveDocumentRelatedPartPath(\n sourcePackage,\n documentPart.relationships,\n COMMENTS_EXTENDED_RELATIONSHIP_TYPE,\n COMMENTS_EXTENDED_PART_PATH,\n );\n const commentsIdsPartPath = resolveDocumentRelatedPartPath(\n sourcePackage,\n documentPart.relationships,\n COMMENTS_IDS_RELATIONSHIP_TYPE,\n COMMENTS_IDS_PART_PATH,\n );\n const peoplePartPath = resolveDocumentRelatedPartPath(\n sourcePackage,\n documentPart.relationships,\n PEOPLE_RELATIONSHIP_TYPE,\n PEOPLE_PART_PATH,\n );\n const parsedComments = commentsPartPath\n ? parseCommentsFromOoxml(\n sourceDocumentXml,\n {\n commentsXml: decodeUtf8(sourcePackage.parts.get(commentsPartPath)?.bytes ?? new Uint8Array()),\n commentsExtendedXml: decodeUtf8(\n sourcePackage.parts.get(commentsExtendedPartPath ?? \"\")?.bytes ?? new Uint8Array(),\n ),\n commentsIdsXml: decodeUtf8(\n sourcePackage.parts.get(commentsIdsPartPath ?? \"\")?.bytes ?? new Uint8Array(),\n ),\n peopleXml: decodeUtf8(\n sourcePackage.parts.get(peoplePartPath ?? \"\")?.bytes ?? new Uint8Array(),\n ),\n },\n )\n : {\n threads: [] as CommentThread[],\n diagnostics: [] as CommentImportDiagnostic[],\n definitions: [] as ImportedCommentDefinition[],\n sourceRootTag: undefined,\n sourceExtendedRootTag: undefined,\n sourceIdsRootTag: undefined,\n sourcePeopleRootTag: undefined,\n peopleAuthors: [] as string[],\n };\n const normalizedRevisions = normalizeImportedRevisionRecords(\n importedRevisions,\n normalizedDocument.content,\n normalizedDocument.preservation.opaqueFragments,\n );\n const normalizedComments = normalizeImportedCommentThreads(\n parsedComments,\n normalizedDocument.preservation.opaqueFragments,\n normalizedRevisions.revisions,\n );\n // ---- Parse sub-parts: headers, footers, footnotes, endnotes, theme ----\n const headerFooterRefs = parseHeaderFooterReferences(sourceDocumentXml);\n const parsedHeaders: HeaderDocument[] = [];\n const parsedFooters: FooterDocument[] = [];\n const sourceHeaderPaths: Array<{ partPath: string; relationshipId: string }> = [];\n const sourceFooterPaths: Array<{ partPath: string; relationshipId: string }> = [];\n const seenSubPartRelIds = new Set<string>();\n\n for (const ref of headerFooterRefs) {\n if (seenSubPartRelIds.has(ref.relationshipId)) {\n continue;\n }\n seenSubPartRelIds.add(ref.relationshipId);\n\n const relationship = documentPart.relationships.find(\n (r) => r.id === ref.relationshipId && r.targetMode === \"internal\",\n );\n if (!relationship) {\n continue;\n }\n\n const partPath = resolveRelationshipTarget(MAIN_DOCUMENT_PATH, relationship);\n const partBytes = sourcePackage.parts.get(partPath)?.bytes;\n if (!partBytes) {\n continue;\n }\n\n const xml = decodeUtf8(partBytes);\n if (ref.kind === \"header\") {\n const parsed = parseHeaderXml(xml);\n parsedHeaders.push({\n variant: ref.variant,\n partPath,\n relationshipId: ref.relationshipId,\n blocks: parsed.blocks,\n });\n sourceHeaderPaths.push({ partPath, relationshipId: ref.relationshipId });\n } else {\n const parsed = parseFooterXml(xml);\n parsedFooters.push({\n variant: ref.variant,\n partPath,\n relationshipId: ref.relationshipId,\n blocks: parsed.blocks,\n });\n sourceFooterPaths.push({ partPath, relationshipId: ref.relationshipId });\n }\n }\n\n const footnotesPartPath = resolveDocumentRelatedPartPath(\n sourcePackage,\n documentPart.relationships,\n FOOTNOTES_RELATIONSHIP_TYPE,\n FOOTNOTES_PART_PATH,\n );\n const footnotesRelationshipId = documentPart.relationships.find(\n (r) => r.type === FOOTNOTES_RELATIONSHIP_TYPE && r.targetMode === \"internal\",\n )?.id;\n const endnotesPartPath = resolveDocumentRelatedPartPath(\n sourcePackage,\n documentPart.relationships,\n ENDNOTES_RELATIONSHIP_TYPE,\n ENDNOTES_PART_PATH,\n );\n const endnotesRelationshipId = documentPart.relationships.find(\n (r) => r.type === ENDNOTES_RELATIONSHIP_TYPE && r.targetMode === \"internal\",\n )?.id;\n\n let footnoteCollection: FootnoteCollection | undefined;\n if (footnotesPartPath) {\n footnoteCollection = parseFootnotesXml(\n decodeUtf8(sourcePackage.parts.get(footnotesPartPath)?.bytes ?? new Uint8Array()),\n );\n }\n if (endnotesPartPath) {\n footnoteCollection = parseEndnotesXml(\n decodeUtf8(sourcePackage.parts.get(endnotesPartPath)?.bytes ?? new Uint8Array()),\n footnoteCollection,\n );\n }\n\n const themeRelationship = documentPart.relationships.find(\n (r) => r.type === \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme\" &&\n r.targetMode === \"internal\",\n );\n const themePartPath = themeRelationship\n ? resolveRelationshipTarget(MAIN_DOCUMENT_PATH, themeRelationship)\n : undefined;\n const parsedTheme =\n themePartPath && sourcePackage.parts.has(themePartPath)\n ? parseThemeXml(\n decodeUtf8(sourcePackage.parts.get(themePartPath)?.bytes ?? new Uint8Array()),\n )\n : undefined;\n\n const subParts: SubPartsCatalog | undefined =\n parsedHeaders.length > 0 ||\n parsedFooters.length > 0 ||\n footnoteCollection !== undefined ||\n parsedTheme !== undefined\n ? {\n headers: parsedHeaders,\n footers: parsedFooters,\n ...(footnoteCollection !== undefined ? { footnoteCollection } : {}),\n ...(parsedTheme !== undefined ? { theme: parsedTheme } : {}),\n }\n : undefined;\n\n const timestamp = new Date().toISOString();\n const document = createImportedCanonicalDocument({\n documentId: options.documentId,\n timestamp,\n numbering: parsedNumbering,\n media: normalizedDocument.media,\n content: normalizedDocument.content,\n subParts,\n preservation: {\n ...normalizedDocument.preservation,\n packageParts: {\n ...normalizedDocument.preservation.packageParts,\n ...collectPreservedPackageParts(sourcePackage, [\n numberingPartPath,\n commentsPartPath,\n commentsExtendedPartPath,\n commentsIdsPartPath,\n peoplePartPath,\n ]),\n },\n },\n diagnostics: {\n warnings: [\n ...normalizedDocument.diagnostics.warnings,\n ...normalizedRevisions.diagnostics.map((diagnostic, index) => ({\n diagnosticId: `diagnostic:revision-import-${index + 1}`,\n warningId: `warning:revision-import-${diagnostic.revisionId}`,\n source: \"review\" as const,\n message: diagnostic.message,\n })),\n ...normalizedComments.diagnostics.map((diagnostic, index) => ({\n diagnosticId: `diagnostic:comment-import-${index + 1}`,\n warningId: `warning:comment-import-${diagnostic.commentId}`,\n source: \"review\" as const,\n message: diagnostic.message,\n })),\n ],\n errors: [],\n },\n review: {\n comments: toRuntimeCommentRecords(normalizedComments.threads),\n revisions: toRuntimeRevisionRecords(normalizedRevisions.revisions),\n },\n });\n const compatibility = buildCompatibilityReport({\n document,\n generatedAt: timestamp,\n });\n const snapshot = createImportedSnapshot({\n documentId: options.documentId,\n editorBuild: options.editorBuild,\n timestamp,\n document,\n compatibility: toPublicCompatibilityReport(compatibility),\n });\n const importedState: ImportedDocxState = {\n sourceBytes: new Uint8Array(sourceBytes),\n sourcePackage,\n sourceDocumentRelationships: documentPart.relationships,\n sourceDocumentAttributes: extractDocumentRootAttributes(sourceDocumentXml),\n sourceNumberingPartPath: numberingPartPath,\n sourceNumberingRelationshipId: documentPart.relationships.find(\n (relationship) =>\n relationship.type === NUMBERING_RELATIONSHIP_TYPE &&\n relationship.targetMode === \"internal\",\n )?.id,\n sourceCommentsPartPath: commentsPartPath,\n sourceCommentsRelationshipId: documentPart.relationships.find(\n (relationship) =>\n relationship.type === COMMENTS_RELATIONSHIP_TYPE &&\n relationship.targetMode === \"internal\",\n )?.id,\n sourceCommentsRootTag: normalizedComments.sourceRootTag,\n sourceCommentsExtendedPartPath: commentsExtendedPartPath,\n sourceCommentsExtendedRelationshipId: documentPart.relationships.find(\n (relationship) =>\n relationship.type === COMMENTS_EXTENDED_RELATIONSHIP_TYPE &&\n relationship.targetMode === \"internal\",\n )?.id,\n sourceCommentsExtendedRootTag: normalizedComments.sourceExtendedRootTag,\n sourceCommentsIdsPartPath: commentsIdsPartPath,\n sourceCommentsIdsRelationshipId: documentPart.relationships.find(\n (relationship) =>\n relationship.type === COMMENTS_IDS_RELATIONSHIP_TYPE &&\n relationship.targetMode === \"internal\",\n )?.id,\n sourceCommentsIdsRootTag: normalizedComments.sourceIdsRootTag,\n sourcePeoplePartPath: peoplePartPath,\n sourcePeopleRelationshipId: documentPart.relationships.find(\n (relationship) =>\n relationship.type === PEOPLE_RELATIONSHIP_TYPE &&\n relationship.targetMode === \"internal\",\n )?.id,\n sourcePeopleRootTag: normalizedComments.sourcePeopleRootTag,\n sourcePeopleAuthors: normalizedComments.peopleAuthors,\n preservedCommentDefinitions: normalizedComments.preservedDefinitions,\n blockingCommentDiagnostics: normalizedComments.diagnostics.filter((diagnostic) =>\n BLOCKING_COMMENT_DIAGNOSTIC_CODES.has(diagnostic.code),\n ),\n initialCanonicalSignature: serializeCanonicalDocumentForExport(document),\n sourceSubPartPaths: {\n headers: sourceHeaderPaths,\n footers: sourceFooterPaths,\n footnotesPartPath,\n footnotesRelationshipId,\n endnotesPartPath,\n endnotesRelationshipId,\n themePartPath,\n themeRelationshipId: themeRelationship?.id,\n },\n };\n\n return {\n initialSnapshot: snapshot,\n readOnly: false,\n exportDocx: async (nextSnapshot, exportOptions) =>\n exportDocxEditorSession(importedState, nextSnapshot, exportOptions),\n };\n } catch (error) {\n return createDiagnosticsSession(\n options,\n createImportDiagnosticsFromError(error),\n );\n }\n}\n\nfunction exportDocxEditorSession(\n state: ImportedDocxState,\n snapshot: PersistedEditorSnapshot,\n options?: ExportDocxOptions,\n): ExportResult {\n if (snapshot.compatibility.blockExport) {\n throw new Error(\"DOCX export is blocked by the current compatibility report.\");\n }\n\n const currentDocument = snapshot.canonicalDocument as CanonicalDocumentEnvelope;\n if (\n serializeCanonicalDocumentForExport(currentDocument) ===\n state.initialCanonicalSignature &&\n canReuseSourceBytesForCurrentDocument(state, currentDocument)\n ) {\n return {\n bytes: new Uint8Array(state.sourceBytes),\n mimeType: DOCX_MIME_TYPE,\n fileName: options?.fileName ?? `${snapshot.documentId}.docx`,\n };\n }\n if (state.blockingCommentDiagnostics.length > 0) {\n throw new Error(\n `DOCX export is blocked because ${state.blockingCommentDiagnostics.length} preserve-only comment anchors cannot be safely remapped after runtime edits.`,\n );\n }\n const currentRevisions = toReviewRevisionRecords(currentDocument.review.revisions);\n const actionableRevisions = currentRevisions.filter(\n (revision) => getRevisionActionability(revision) === \"actionable\",\n );\n const commentThreads = Object.values(\n createCommentStoreFromRuntimeComments(currentDocument.review.comments).threads,\n );\n const preservedCommentIds = new Set(\n state.preservedCommentDefinitions.map((definition) => definition.commentId),\n );\n const ownedCommentThreads = commentThreads.filter(\n (thread) => !preservedCommentIds.has(thread.commentId),\n );\n const serialized = serializeMainDocument(\n splitDocumentAtReviewBoundaries(\n currentDocument.content as never,\n ownedCommentThreads,\n actionableRevisions,\n ) as never,\n currentDocument.preservation as never,\n state.sourceDocumentRelationships,\n {\n documentAttributes: state.sourceDocumentAttributes,\n media: currentDocument.media as MediaCatalog,\n },\n );\n const revisionDocument = serializeRuntimeRevisionsIntoDocumentXml(\n serialized.documentXml,\n actionableRevisions,\n serialized.paragraphBoundaries,\n );\n if (revisionDocument.skippedRevisionIds.length > 0) {\n throw new Error(\n `DOCX export is blocked because ${revisionDocument.skippedRevisionIds.length} active revisions overlap unsupported serialization boundaries.`,\n );\n }\n\n const strippedDocumentXml = stripCommentMarkup(\n revisionDocument.documentXml,\n ownedCommentThreads.map((thread) => thread.commentId),\n );\n const exportCommentIds = createCommentExportIdMap(\n ownedCommentThreads,\n state.preservedCommentDefinitions,\n );\n const serializedComments = serializeMergedCommentsXml(ownedCommentThreads, {\n exportCommentIds,\n preservedDefinitions: state.preservedCommentDefinitions,\n sourceRootTag: state.sourceCommentsRootTag,\n sourceExtendedRootTag: state.sourceCommentsExtendedRootTag,\n sourceIdsRootTag: state.sourceCommentsIdsRootTag,\n sourcePeopleRootTag: state.sourcePeopleRootTag,\n peopleAuthors: state.sourcePeopleAuthors,\n });\n const annotatedDocument = serializeCommentAnchorsIntoDocumentXml(\n strippedDocumentXml,\n ownedCommentThreads,\n undefined,\n {\n exportCommentIds,\n },\n );\n const blockingSkippedCommentIds = annotatedDocument.skippedCommentIds.filter((commentId) => {\n const thread = ownedCommentThreads.find((candidate) => candidate.commentId === commentId);\n return !thread || thread.anchor.kind !== \"detached\";\n });\n if (blockingSkippedCommentIds.length > 0) {\n throw new Error(\n `DOCX export is blocked because ${blockingSkippedCommentIds.length} comments no longer map to serializable ranges.`,\n );\n }\n const commentsPartPath =\n state.sourceCommentsPartPath ?? COMMENTS_PART_PATH;\n const commentsExtendedPartPath =\n state.sourceCommentsExtendedPartPath ?? COMMENTS_EXTENDED_PART_PATH;\n const commentsIdsPartPath =\n state.sourceCommentsIdsPartPath ?? COMMENTS_IDS_PART_PATH;\n const peoplePartPath =\n state.sourcePeoplePartPath ?? PEOPLE_PART_PATH;\n const numberingPartPath =\n state.sourceNumberingPartPath ?? NUMBERING_PART_PATH;\n const serializedNumberingXml = hasNumberingEntries(currentDocument.numbering as NumberingCatalog)\n ? serializeNumberingXml(currentDocument.numbering as NumberingCatalog)\n : undefined;\n const nextRelationships = withDocumentRelatedParts(\n serialized.relationships,\n [\n {\n relationshipType: NUMBERING_RELATIONSHIP_TYPE,\n partPath: numberingPartPath,\n existingRelationshipId: state.sourceNumberingRelationshipId,\n include:\n Boolean(serializedNumberingXml) ||\n Boolean(state.sourceNumberingPartPath),\n },\n {\n relationshipType: COMMENTS_RELATIONSHIP_TYPE,\n partPath: commentsPartPath,\n existingRelationshipId: state.sourceCommentsRelationshipId,\n include:\n serializedComments.serializedCommentIds.length > 0 ||\n Boolean(state.sourceCommentsPartPath),\n },\n {\n relationshipType: COMMENTS_EXTENDED_RELATIONSHIP_TYPE,\n partPath: commentsExtendedPartPath,\n existingRelationshipId: state.sourceCommentsExtendedRelationshipId,\n include:\n Boolean(serializedComments.commentsExtendedXml) ||\n Boolean(state.sourceCommentsExtendedPartPath),\n },\n {\n relationshipType: COMMENTS_IDS_RELATIONSHIP_TYPE,\n partPath: commentsIdsPartPath,\n existingRelationshipId: state.sourceCommentsIdsRelationshipId,\n include:\n Boolean(serializedComments.commentsIdsXml) ||\n Boolean(state.sourceCommentsIdsPartPath),\n },\n {\n relationshipType: PEOPLE_RELATIONSHIP_TYPE,\n partPath: peoplePartPath,\n existingRelationshipId: state.sourcePeopleRelationshipId,\n include:\n Boolean(serializedComments.peopleXml) ||\n Boolean(state.sourcePeoplePartPath),\n },\n ],\n );\n\n const exportedSubParts = currentDocument.subParts as SubPartsCatalog | undefined;\n const subPartOwnedPaths: string[] = [];\n if (exportedSubParts) {\n for (const header of exportedSubParts.headers) {\n subPartOwnedPaths.push(header.partPath);\n }\n for (const footer of exportedSubParts.footers) {\n subPartOwnedPaths.push(footer.partPath);\n }\n if (exportedSubParts.footnoteCollection) {\n if (state.sourceSubPartPaths.footnotesPartPath) {\n subPartOwnedPaths.push(state.sourceSubPartPaths.footnotesPartPath);\n }\n if (state.sourceSubPartPaths.endnotesPartPath) {\n subPartOwnedPaths.push(state.sourceSubPartPaths.endnotesPartPath);\n }\n }\n if (exportedSubParts.theme && state.sourceSubPartPaths.themePartPath) {\n subPartOwnedPaths.push(state.sourceSubPartPaths.themePartPath);\n }\n }\n\n const exportSession = createExportSession(state.sourcePackage, [\n MAIN_DOCUMENT_PATH,\n numberingPartPath,\n commentsPartPath,\n commentsExtendedPartPath,\n commentsIdsPartPath,\n peoplePartPath,\n ...subPartOwnedPaths,\n ]);\n\n exportSession.replaceOwnedPart({\n path: MAIN_DOCUMENT_PATH,\n bytes: new TextEncoder().encode(annotatedDocument.documentXml),\n contentType: MAIN_DOCUMENT_CONTENT_TYPE,\n relationships: nextRelationships,\n });\n\n if (serializedNumberingXml || state.sourceNumberingPartPath) {\n exportSession.replaceOwnedPart({\n path: numberingPartPath,\n bytes: new TextEncoder().encode(\n serializedNumberingXml ??\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\\n<w:numbering xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"></w:numbering>`,\n ),\n contentType:\n state.sourcePackage.parts.get(numberingPartPath)?.contentType ??\n WORD_NUMBERING_CONTENT_TYPE,\n });\n }\n\n if (serializedComments.serializedCommentIds.length > 0 || state.sourceCommentsPartPath) {\n exportSession.replaceOwnedPart({\n path: commentsPartPath,\n bytes: new TextEncoder().encode(serializedComments.commentsXml),\n contentType:\n state.sourcePackage.parts.get(commentsPartPath)?.contentType ?? COMMENTS_CONTENT_TYPE,\n });\n }\n\n if (serializedComments.commentsExtendedXml || state.sourceCommentsExtendedPartPath) {\n exportSession.replaceOwnedPart({\n path: commentsExtendedPartPath,\n bytes: new TextEncoder().encode(\n serializedComments.commentsExtendedXml ?? `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\\n<w15:commentsEx xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\"></w15:commentsEx>`,\n ),\n contentType:\n state.sourcePackage.parts.get(commentsExtendedPartPath)?.contentType ??\n COMMENTS_EXTENDED_CONTENT_TYPE,\n });\n }\n\n if (serializedComments.commentsIdsXml || state.sourceCommentsIdsPartPath) {\n exportSession.replaceOwnedPart({\n path: commentsIdsPartPath,\n bytes: new TextEncoder().encode(\n serializedComments.commentsIdsXml ?? `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\\n<w16cid:commentsIds xmlns:w16cid=\"http://schemas.microsoft.com/office/word/2016/wordml/cid\"></w16cid:commentsIds>`,\n ),\n contentType:\n state.sourcePackage.parts.get(commentsIdsPartPath)?.contentType ??\n COMMENTS_IDS_CONTENT_TYPE,\n });\n }\n\n if (serializedComments.peopleXml || state.sourcePeoplePartPath) {\n exportSession.replaceOwnedPart({\n path: peoplePartPath,\n bytes: new TextEncoder().encode(\n serializedComments.peopleXml ?? `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\\n<w15:people xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\"></w15:people>`,\n ),\n contentType:\n state.sourcePackage.parts.get(peoplePartPath)?.contentType ??\n PEOPLE_CONTENT_TYPE,\n });\n }\n\n if (exportedSubParts) {\n for (const header of exportedSubParts.headers) {\n exportSession.replaceOwnedPart({\n path: header.partPath,\n bytes: new TextEncoder().encode(serializeHeaderXml(header)),\n contentType:\n state.sourcePackage.parts.get(header.partPath)?.contentType ?? WORD_HEADER_CONTENT_TYPE,\n });\n }\n for (const footer of exportedSubParts.footers) {\n exportSession.replaceOwnedPart({\n path: footer.partPath,\n bytes: new TextEncoder().encode(serializeFooterXml(footer)),\n contentType:\n state.sourcePackage.parts.get(footer.partPath)?.contentType ?? WORD_FOOTER_CONTENT_TYPE,\n });\n }\n if (exportedSubParts.footnoteCollection) {\n if (state.sourceSubPartPaths.footnotesPartPath) {\n exportSession.replaceOwnedPart({\n path: state.sourceSubPartPaths.footnotesPartPath,\n bytes: new TextEncoder().encode(serializeFootnotesXml(exportedSubParts.footnoteCollection)),\n contentType:\n state.sourcePackage.parts.get(state.sourceSubPartPaths.footnotesPartPath)?.contentType ??\n WORD_FOOTNOTES_CONTENT_TYPE,\n });\n }\n if (state.sourceSubPartPaths.endnotesPartPath) {\n exportSession.replaceOwnedPart({\n path: state.sourceSubPartPaths.endnotesPartPath,\n bytes: new TextEncoder().encode(serializeEndnotesXml(exportedSubParts.footnoteCollection)),\n contentType:\n state.sourcePackage.parts.get(state.sourceSubPartPaths.endnotesPartPath)?.contentType ??\n WORD_ENDNOTES_CONTENT_TYPE,\n });\n }\n }\n if (exportedSubParts.theme && state.sourceSubPartPaths.themePartPath) {\n const sourceThemePart = state.sourcePackage.parts.get(state.sourceSubPartPaths.themePartPath);\n if (sourceThemePart) {\n exportSession.replaceOwnedPart({\n path: state.sourceSubPartPaths.themePartPath,\n bytes: sourceThemePart.bytes,\n contentType: sourceThemePart.contentType,\n relationships: sourceThemePart.relationships,\n compression: sourceThemePart.compression,\n });\n }\n }\n }\n\n return {\n bytes: exportSession.serialize(),\n mimeType: DOCX_MIME_TYPE,\n fileName: options?.fileName ?? `${snapshot.documentId}.docx`,\n };\n}\n\nfunction createImportedCanonicalDocument(input: {\n documentId: string;\n timestamp: string;\n numbering: CanonicalDocumentEnvelope[\"numbering\"];\n media: CanonicalDocumentEnvelope[\"media\"];\n content: CanonicalDocumentEnvelope[\"content\"];\n subParts?: SubPartsCatalog;\n preservation: CanonicalDocumentEnvelope[\"preservation\"];\n diagnostics: CanonicalDocumentEnvelope[\"diagnostics\"];\n review: CanonicalDocumentEnvelope[\"review\"];\n}): CanonicalDocumentEnvelope {\n return {\n schemaVersion: \"cds/1.0.0\",\n docId: createCanonicalDocumentId(input.documentId),\n createdAt: input.timestamp,\n updatedAt: input.timestamp,\n metadata: {\n customProperties: {},\n },\n styles: {\n paragraphs: {},\n characters: {},\n tables: {},\n },\n numbering: input.numbering,\n media: input.media,\n content: input.content,\n review: input.review,\n preservation: input.preservation,\n diagnostics: input.diagnostics,\n ...(input.subParts !== undefined ? { subParts: input.subParts } : {}),\n };\n}\n\nfunction createImportedSnapshot(input: {\n documentId: string;\n editorBuild: string;\n timestamp: string;\n document: CanonicalDocumentEnvelope;\n compatibility: PersistedEditorSnapshot[\"compatibility\"];\n}): PersistedEditorSnapshot {\n return {\n snapshotVersion: \"persisted-editor-snapshot/1\",\n schemaVersion: input.document.schemaVersion,\n documentId: input.documentId,\n docId: input.document.docId,\n createdAt: input.document.createdAt,\n updatedAt: input.document.updatedAt,\n savedAt: input.timestamp,\n editorBuild: input.editorBuild,\n canonicalDocument: input.document,\n compatibility: input.compatibility,\n warningLog: input.compatibility.warnings,\n };\n}\n\nfunction toPublicAnchorProjection(\n anchor: InternalEditorAnchorProjection,\n): PublicEditorAnchorProjection {\n switch (anchor.kind) {\n case \"range\":\n return {\n kind: \"range\",\n from: anchor.range.from,\n to: anchor.range.to,\n assoc: anchor.assoc,\n };\n case \"node\":\n return {\n kind: \"node\",\n at: anchor.at,\n assoc: anchor.assoc,\n };\n case \"detached\":\n return {\n kind: \"detached\",\n lastKnownRange: anchor.lastKnownRange,\n reason: anchor.reason,\n };\n }\n}\n\nfunction toPublicCompatibilityFeatureEntry(entry: InternalCompatibilityFeatureEntry) {\n return {\n ...entry,\n affectedAnchor: entry.affectedAnchor\n ? toPublicAnchorProjection(entry.affectedAnchor)\n : undefined,\n };\n}\n\nfunction toPublicWarning(warning: InternalEditorWarning): PublicEditorWarning {\n return {\n ...warning,\n affectedAnchor: warning.affectedAnchor\n ? toPublicAnchorProjection(warning.affectedAnchor)\n : undefined,\n };\n}\n\nfunction toPublicError(error: InternalEditorError): EditorError {\n return { ...error };\n}\n\nfunction toPublicCompatibilityReport(\n report: InternalCompatibilityReport,\n): PublicCompatibilityReport {\n return {\n reportVersion: report.reportVersion,\n generatedAt: report.generatedAt,\n blockExport: report.blockExport,\n featureEntries: report.featureEntries.map((entry) =>\n toPublicCompatibilityFeatureEntry(entry),\n ),\n warnings: report.warnings.map((warning) => toPublicWarning(warning)),\n errors: report.errors.map((error) => toPublicError(error)),\n };\n}\n\nfunction createDiagnosticsSession(\n options: LoadDocxEditorSessionOptions,\n diagnostics: ImportDiagnosticsResult,\n): LoadedDocxEditorSession {\n const timestamp = new Date().toISOString();\n const runtime = createReadOnlyDiagnosticsRuntime({\n documentId: options.documentId,\n sourceLabel: options.sourceLabel,\n editorBuild: options.editorBuild,\n generatedAt: timestamp,\n diagnostics,\n });\n const initialSnapshot = runtime.getPersistedSnapshot();\n\n return {\n initialSnapshot,\n fatalError: diagnostics.fatalError,\n readOnly: true,\n exportDocx: async (_snapshot, exportOptions) => runtime.exportDocx(exportOptions),\n };\n}\n\nfunction createImportDiagnosticsFromError(error: unknown): ImportDiagnosticsResult {\n if (isPackageImportError(error)) {\n return createPackageImportDiagnostics({\n issue: classifyCorruptPackageError(error),\n });\n }\n\n return createValidationImportDiagnostics({\n message:\n error instanceof Error\n ? error.message\n : \"DOCX import failed during validation.\",\n });\n}\n\nfunction normalizeImportedRevisionRecords(\n parsed: ParsedRevisionsResult,\n content: CanonicalDocumentEnvelope[\"content\"],\n opaqueFragments: Record<string, OpaqueFragmentRecord>,\n): ParsedRevisionsResult {\n const opaqueRanges = Object.values(opaqueFragments).map((fragment) => fragment.lastKnownRange);\n const paragraphRanges = collectCanonicalParagraphRanges(content);\n if (opaqueRanges.length === 0) {\n return {\n ...parsed,\n revisions: parsed.revisions.map((revision) => {\n if (revision.anchor.kind !== \"range\" || revision.metadata.preserveOnlyReason) {\n return revision;\n }\n\n const preserveOnlyReason = getStructuralPreserveOnlyReason(\n revision,\n paragraphRanges,\n );\n if (!preserveOnlyReason) {\n return revision;\n }\n\n return {\n ...revision,\n metadata: {\n ...revision.metadata,\n preserveOnlyReason,\n },\n };\n }),\n };\n }\n\n return {\n ...parsed,\n revisions: parsed.revisions.map((revision) => {\n if (revision.anchor.kind !== \"range\" || revision.metadata.preserveOnlyReason) {\n return revision;\n }\n\n const preserveOnlyReason =\n getStructuralPreserveOnlyReason(revision, paragraphRanges) ??\n (opaqueRanges.some((range) => rangesIntersect(range, revision.anchor.range))\n ? \"Imported revision overlaps preserve-only OOXML and remains preserve-only.\"\n : undefined);\n\n if (!preserveOnlyReason) {\n return revision;\n }\n\n return {\n ...revision,\n metadata: {\n ...revision.metadata,\n preserveOnlyReason,\n },\n };\n }),\n };\n}\n\nfunction normalizeImportedCommentThreads(\n parsed: ParsedCommentsResult,\n opaqueFragments: Record<string, OpaqueFragmentRecord>,\n revisions: readonly ReviewRevisionRecord[],\n): NormalizedImportedCommentsResult {\n const opaqueRanges = Object.values(opaqueFragments).map((fragment) => fragment.lastKnownRange);\n const preserveOnlyRevisionRanges = revisions\n .filter(\n (revision) =>\n revision.anchor.kind === \"range\" &&\n typeof revision.metadata.preserveOnlyReason === \"string\" &&\n revision.metadata.preserveOnlyReason.length > 0,\n )\n .map((revision) => revision.anchor.range);\n const preserveOnlyCommentIds = new Set(parsed.diagnostics.map((diagnostic) => diagnostic.commentId));\n const additionalDiagnostics: CommentImportDiagnostic[] = [];\n const normalizedThreads = parsed.threads.map((thread) => {\n if (thread.anchor.kind !== \"range\") {\n preserveOnlyCommentIds.add(thread.commentId);\n return thread;\n }\n\n const opaqueOverlap = opaqueRanges.some((range) => rangesIntersect(range, thread.anchor.range));\n if (opaqueOverlap) {\n preserveOnlyCommentIds.add(thread.commentId);\n additionalDiagnostics.push({\n commentId: thread.commentId,\n code: \"opaque_anchor_preserve_only\",\n message:\n \"Comment anchor intersects preserve-only OOXML and remains preserve-only on export.\",\n featureClass: \"preserve-only\",\n });\n return {\n ...thread,\n anchor: createDetachedAnchor(thread.anchor.range, \"importAmbiguity\"),\n status: \"detached\",\n };\n }\n\n const preserveOnlyRevisionOverlap = preserveOnlyRevisionRanges.some((range) =>\n rangesIntersect(range, thread.anchor.range),\n );\n if (preserveOnlyRevisionOverlap) {\n preserveOnlyCommentIds.add(thread.commentId);\n additionalDiagnostics.push({\n commentId: thread.commentId,\n code: \"preserve_only_revision_overlap\",\n message:\n \"Comment anchor overlaps preserve-only review markup and remains preserve-only on export.\",\n featureClass: \"preserve-only\",\n });\n return {\n ...thread,\n anchor: createDetachedAnchor(thread.anchor.range, \"importAmbiguity\"),\n status: \"detached\",\n };\n }\n\n return thread;\n });\n\n return {\n ...parsed,\n threads: normalizedThreads,\n diagnostics: [...parsed.diagnostics, ...additionalDiagnostics],\n definitions: parsed.definitions,\n preservedDefinitions: parsed.definitions.filter((definition) =>\n preserveOnlyCommentIds.has(\n resolveDefinitionRootCommentId(definition, parsed.definitions),\n ),\n ),\n };\n}\n\nfunction resolveDefinitionRootCommentId(\n definition: ImportedCommentDefinition,\n definitions: readonly ImportedCommentDefinition[],\n): string {\n if (!definition.parentParaId) {\n return definition.commentId;\n }\n\n const definitionsByParaId = new Map(\n definitions\n .filter((candidate) => typeof candidate.paraId === \"string\")\n .map((candidate) => [candidate.paraId!, candidate]),\n );\n const visited = new Set<string>();\n let current: ImportedCommentDefinition | undefined = definition;\n\n while (current?.parentParaId) {\n if (visited.has(current.parentParaId)) {\n break;\n }\n visited.add(current.parentParaId);\n const parent = definitionsByParaId.get(current.parentParaId);\n if (!parent) {\n break;\n }\n current = parent;\n }\n\n return current?.commentId ?? definition.commentId;\n}\n\nfunction getStructuralPreserveOnlyReason(\n revision: ReviewRevisionRecord,\n paragraphRanges: ReadonlyArray<{ start: number; end: number }>,\n): string | undefined {\n const form = revision.metadata.importedRevisionForm;\n if (!form || revision.anchor.kind !== \"range\") {\n return undefined;\n }\n\n if (\n (form === \"run-insertion\" || form === \"run-deletion\") &&\n revision.anchor.range.from === revision.anchor.range.to\n ) {\n return \"Imported zero-width run revision remains preserve-only.\";\n }\n\n if (form === \"paragraph-insertion\" || form === \"paragraph-deletion\") {\n const paragraphBoundary = paragraphRanges.find(\n (boundary) =>\n boundary.end === revision.anchor.range.from ||\n (revision.anchor.range.from >= boundary.start &&\n revision.anchor.range.from <= boundary.end),\n );\n return paragraphBoundary\n ? undefined\n : \"Imported revision spans paragraph-level structure and remains preserve-only.\";\n }\n\n const paragraphBoundary = paragraphRanges.find(\n (boundary) =>\n revision.anchor.range.from >= boundary.start &&\n revision.anchor.range.to <= boundary.end,\n );\n return paragraphBoundary\n ? undefined\n : \"Imported revision spans structural boundaries and remains preserve-only.\";\n}\n\nfunction collectCanonicalParagraphRanges(\n content: CanonicalDocumentEnvelope[\"content\"],\n): Array<{ start: number; end: number }> {\n const ranges: Array<{ start: number; end: number }> = [];\n let cursor = 0;\n let previousWasParagraph = false;\n\n for (const block of content.children) {\n if (block.type === \"paragraph\") {\n if (previousWasParagraph) {\n cursor += 1;\n }\n const start = cursor;\n cursor += measureCanonicalParagraph(block);\n ranges.push({ start, end: cursor });\n previousWasParagraph = true;\n continue;\n }\n\n cursor += 1;\n previousWasParagraph = false;\n }\n\n return ranges;\n}\n\nfunction measureCanonicalParagraph(paragraph: CanonicalDocumentEnvelope[\"content\"][\"children\"][number] & { type: \"paragraph\" }): number {\n return paragraph.children.reduce((size, child) => {\n switch (child.type) {\n case \"text\":\n return size + child.text.length;\n case \"tab\":\n case \"hard_break\":\n case \"image\":\n case \"opaque_inline\":\n return size + 1;\n case \"hyperlink\":\n return (\n size +\n child.children.reduce((childSize, entry) => {\n switch (entry.type) {\n case \"text\":\n return childSize + entry.text.length;\n case \"tab\":\n case \"hard_break\":\n return childSize + 1;\n }\n }, 0)\n );\n }\n }, 0);\n}\n\nfunction rangesIntersect(\n left: { from: number; to: number },\n right: { from: number; to: number },\n): boolean {\n return left.from < right.to && right.from < left.to;\n}\n\nfunction resolveCommentsPartPath(\n sourcePackage: OpcPackage,\n relationships: readonly OpcRelationship[],\n): string | undefined {\n return resolveDocumentRelatedPartPath(\n sourcePackage,\n relationships,\n COMMENTS_RELATIONSHIP_TYPE,\n COMMENTS_PART_PATH,\n );\n}\n\nfunction resolveDocumentRelatedPartPath(\n sourcePackage: OpcPackage,\n relationships: readonly OpcRelationship[],\n relationshipType: string,\n fallbackPartPath: string,\n): string | undefined {\n const relationship = relationships.find(\n (candidate) =>\n candidate.type === relationshipType &&\n candidate.targetMode === \"internal\",\n );\n if (!relationship) {\n return sourcePackage.parts.has(fallbackPartPath) ? fallbackPartPath : undefined;\n }\n\n const targetPath = resolveRelationshipTarget(MAIN_DOCUMENT_PATH, relationship);\n return sourcePackage.parts.has(targetPath) ? targetPath : undefined;\n}\n\nfunction toRuntimeCommentRecords(\n threads: readonly CommentThread[],\n): Record<string, CommentThreadRecord> {\n return Object.fromEntries(\n threads.map((thread) => {\n return [\n thread.commentId,\n {\n commentId: thread.commentId,\n body: thread.entries.map((entry) => entry.body).join(\"\\n\"),\n anchor: thread.anchor,\n createdBy: thread.createdBy,\n authorId: thread.createdBy,\n createdAt: thread.createdAt,\n entries: thread.entries.map((entry) => ({\n entryId: entry.entryId,\n authorId: entry.authorId,\n body: entry.body,\n createdAt: entry.createdAt,\n metadata: entry.metadata\n ? {\n ooxmlCommentId: entry.metadata.ooxmlCommentId,\n paraId: entry.metadata.paraId,\n parentParaId: entry.metadata.parentParaId,\n durableId: entry.metadata.durableId,\n initials: entry.metadata.initials,\n }\n : undefined,\n })),\n status: thread.status,\n resolution: thread.resolution\n ? {\n resolvedAt: thread.resolution.resolvedAt,\n resolvedBy: thread.resolution.resolvedBy,\n }\n : undefined,\n resolvedAt: thread.resolution?.resolvedAt,\n warningIds: [...thread.warningIds],\n isResolved: thread.status === \"resolved\",\n metadata: thread.metadata\n ? {\n source: thread.metadata.source,\n rootOoxmlCommentId: thread.metadata.rootOoxmlCommentId,\n rootParaId: thread.metadata.rootParaId,\n }\n : undefined,\n } satisfies CommentThreadRecord,\n ];\n }),\n );\n}\n\nfunction toRuntimeRevisionRecords(\n revisions: readonly ReviewRevisionRecord[],\n): Record<string, RuntimeRevisionRecord> {\n return Object.fromEntries(\n revisions.map((revision) => [\n revision.revisionId,\n {\n changeId: revision.revisionId,\n kind: revision.kind,\n anchor: revision.anchor,\n authorId: revision.authorId,\n createdAt: revision.createdAt,\n warningIds: [...revision.warningIds],\n metadata: {\n source: revision.metadata.source,\n preserveOnlyReason: revision.metadata.preserveOnlyReason,\n importedRevisionForm: revision.metadata.importedRevisionForm,\n originalRevisionType: revision.metadata.originalRevisionType,\n ooxmlRevisionId: revision.metadata.ooxmlRevisionId,\n },\n status: revision.status === \"active\" ? \"open\" : revision.status,\n } satisfies RuntimeRevisionRecord,\n ]),\n );\n}\n\nfunction toReviewRevisionRecords(\n revisions: CanonicalDocumentEnvelope[\"review\"][\"revisions\"],\n): ReviewRevisionRecord[] {\n return Object.values(revisions).map((revision) => ({\n revisionId: revision.changeId,\n kind: revision.kind,\n anchor: revision.anchor,\n authorId: revision.authorId ?? \"unknown\",\n createdAt: revision.createdAt,\n warningIds: [...(revision.warningIds ?? [])],\n metadata: {\n source: revision.metadata?.source ?? \"runtime\",\n preserveOnlyReason: revision.metadata?.preserveOnlyReason,\n importedRevisionForm: revision.metadata?.importedRevisionForm,\n originalRevisionType: revision.metadata?.originalRevisionType,\n ooxmlRevisionId: revision.metadata?.ooxmlRevisionId,\n },\n status: revision.status === \"open\" ? \"active\" : revision.status,\n }));\n}\n\nexport function stripCommentMarkup(\n documentXml: string,\n ownedCommentIds: readonly string[],\n): string {\n if (ownedCommentIds.length === 0) {\n return documentXml;\n }\n\n let output = documentXml;\n for (const commentId of ownedCommentIds) {\n const escapedCommentId = escapeRegExp(commentId);\n const attributePattern = `(?:w:id|id)=[\"']${escapedCommentId}[\"']`;\n output = output\n .replace(\n new RegExp(`<w:commentRangeStart\\\\b[^>]*${attributePattern}[^>]*/>`, \"gu\"),\n \"\",\n )\n .replace(\n new RegExp(`<w:commentRangeEnd\\\\b[^>]*${attributePattern}[^>]*/>`, \"gu\"),\n \"\",\n )\n .replace(\n new RegExp(\n `<w:r\\\\b[^>]*>(?:(?!<w:t\\\\b|</w:r>)[\\\\s\\\\S])*?<w:commentReference\\\\b[^>]*${attributePattern}[^>]*/>(?:(?!<w:t\\\\b|</w:r>)[\\\\s\\\\S])*?</w:r>`,\n \"gu\",\n ),\n \"\",\n );\n }\n\n return output;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction withDocumentRelatedParts(\n relationships: readonly OpcRelationship[],\n relatedParts: ReadonlyArray<{\n relationshipType: string;\n partPath: string;\n existingRelationshipId?: string;\n include: boolean;\n }>,\n): OpcRelationship[] {\n const filteredTypes = new Set(relatedParts.map((part) => part.relationshipType));\n const nextRelationships = relationships\n .filter((relationship) => !filteredTypes.has(relationship.type))\n .map(cloneRelationship);\n\n for (const part of relatedParts) {\n if (!part.include) {\n continue;\n }\n\n nextRelationships.push({\n id: part.existingRelationshipId ?? createCommentsRelationshipId(nextRelationships),\n type: part.relationshipType,\n target: toDocumentRelativeTarget(part.partPath),\n targetMode: \"internal\",\n });\n }\n\n return nextRelationships;\n}\n\nfunction collectPreservedPackageParts(\n sourcePackage: OpcPackage,\n ownedPartPaths: ReadonlyArray<string | undefined>,\n): Record<string, PreservedPackagePart> {\n const normalizedOwnedPaths = new Set(\n ownedPartPaths\n .filter((value): value is string => typeof value === \"string\")\n .map((path) => normalizePartPath(path)),\n );\n return Object.fromEntries(\n [...sourcePackage.parts.values()]\n .filter((part) =>\n shouldPreservePackagePart(part.path, part.surfaceKind, normalizedOwnedPaths),\n )\n .map((part) => [\n part.path,\n {\n packagePartName: part.path,\n contentType: part.contentType ?? \"application/octet-stream\",\n relationshipIds: findRelationshipIdsTargetingPart(sourcePackage, part.path),\n } satisfies PreservedPackagePart,\n ]),\n );\n}\n\nfunction collectInlineMediaParts(\n sourcePackage: OpcPackage,\n): ReadonlyMap<string, { path: string; contentType: string }> {\n return new Map(\n [...sourcePackage.parts.values()]\n .filter(\n (part) =>\n part.path.startsWith(\"/word/media/\") && typeof part.contentType === \"string\",\n )\n .map((part) => [\n part.path,\n {\n path: part.path,\n contentType: part.contentType ?? \"application/octet-stream\",\n },\n ]),\n );\n}\n\nfunction createEmptyNumberingCatalog(): NumberingCatalog {\n return {\n abstractDefinitions: {},\n instances: {},\n };\n}\n\nfunction hasNumberingEntries(catalog: NumberingCatalog): boolean {\n return (\n Object.keys(catalog.abstractDefinitions ?? {}).length > 0 ||\n Object.keys(catalog.instances ?? {}).length > 0\n );\n}\n\nfunction collectBrokenInternalRelationshipIssues(\n sourcePackage: OpcPackage,\n): ReturnType<typeof createBrokenRelationshipIssue>[] {\n const brokenTargets = new Map<string, ReturnType<typeof createBrokenRelationshipIssue>>();\n\n for (const relationship of sourcePackage.manifest.packageRelationships) {\n if (relationship.targetMode !== \"internal\") {\n continue;\n }\n\n const target = resolveRelationshipTarget(null, relationship);\n if (!sourcePackage.parts.has(target)) {\n brokenTargets.set(\n `package:${relationship.id}:${target}`,\n createBrokenRelationshipIssue({\n relationshipSourcePath: null,\n relationshipId: relationship.id,\n targetPartPath: target,\n }),\n );\n }\n }\n\n for (const part of sourcePackage.parts.values()) {\n for (const relationship of part.relationships) {\n if (relationship.targetMode !== \"internal\") {\n continue;\n }\n\n const target = resolveRelationshipTarget(part.path, relationship);\n if (!sourcePackage.parts.has(target)) {\n brokenTargets.set(\n `${part.path}:${relationship.id}:${target}`,\n createBrokenRelationshipIssue({\n relationshipSourcePath: part.path,\n relationshipId: relationship.id,\n targetPartPath: target,\n }),\n );\n }\n }\n }\n\n return [...brokenTargets.values()].sort((left, right) =>\n `${left.relationshipSourcePath ?? \"\"}:${left.relationshipId}:${left.targetPartPath}`.localeCompare(\n `${right.relationshipSourcePath ?? \"\"}:${right.relationshipId}:${right.targetPartPath}`,\n ),\n );\n}\n\nfunction summarizeBrokenRelationshipIssues(\n issues: readonly ReturnType<typeof createBrokenRelationshipIssue>[],\n): string {\n return `DOCX package has unresolved internal relationships: ${issues\n .map((issue) => issue.targetPartPath ?? issue.message)\n .slice(0, 3)\n .join(\", \")}${issues.length > 3 ? \", ...\" : \"\"}.`;\n}\n\nfunction shouldPreservePackagePart(\n partPath: string,\n surfaceKind: OpcPackage[\"parts\"] extends Map<string, infer T>\n ? T extends { surfaceKind: infer U }\n ? U\n : never\n : never,\n ownedPartPaths: ReadonlySet<string>,\n): boolean {\n if (surfaceKind !== \"content\") {\n return false;\n }\n\n if (\n partPath === MAIN_DOCUMENT_PATH ||\n ownedPartPaths.has(partPath) ||\n partPath.startsWith(\"/word/media/\") ||\n CORE_NON_PRESERVED_PART_PATHS.has(partPath)\n ) {\n return false;\n }\n\n return true;\n}\n\nfunction findRelationshipIdsTargetingPart(\n sourcePackage: OpcPackage,\n targetPartPath: string,\n): string[] {\n const ids = new Set<string>();\n\n for (const relationship of sourcePackage.manifest.packageRelationships) {\n if (\n relationship.targetMode === \"internal\" &&\n resolveRelationshipTarget(null, relationship) === targetPartPath\n ) {\n ids.add(relationship.id);\n }\n }\n\n for (const part of sourcePackage.parts.values()) {\n for (const relationship of part.relationships) {\n if (\n relationship.targetMode === \"internal\" &&\n resolveRelationshipTarget(part.path, relationship) === targetPartPath\n ) {\n ids.add(relationship.id);\n }\n }\n }\n\n return [...ids].sort();\n}\n\nfunction extractDocumentRootAttributes(documentXml: string): Record<string, string> {\n const match = documentXml.match(\n /<(?:[A-Za-z_][A-Za-z0-9:._-]*:)?document\\b([^>]*)>/u,\n );\n if (!match) {\n return {};\n }\n\n const attributes: Record<string, string> = {};\n const pattern = /([A-Za-z_][A-Za-z0-9:._-]*)\\s*=\\s*(\"([^\"]*)\"|'([^']*)')/gu;\n for (const attributeMatch of (match[1] ?? \"\").matchAll(pattern)) {\n const name = attributeMatch[1];\n const value = attributeMatch[3] ?? attributeMatch[4] ?? \"\";\n if (!name) {\n continue;\n }\n attributes[name] = value;\n }\n\n return attributes;\n}\n\nfunction isPackageImportError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n\n const normalized = error.message.toLowerCase();\n return (\n normalized.includes(\"zip\") ||\n normalized.includes(\"opc package\") ||\n normalized.includes(\"compression\") ||\n normalized.includes(\"relationship\") ||\n normalized.includes(\"/[content_types].xml\") ||\n normalized.includes(\"/word/document.xml\") ||\n normalized.includes(\"xml\")\n );\n}\n\nconst CORE_NON_PRESERVED_PART_PATHS = new Set([\n \"/docProps/app.xml\",\n \"/docProps/core.xml\",\n \"/docProps/custom.xml\",\n \"/word/fontTable.xml\",\n \"/word/numbering.xml\",\n \"/word/settings.xml\",\n \"/word/styles.xml\",\n \"/word/stylesWithEffects.xml\",\n \"/word/webSettings.xml\",\n]);\n\nfunction createCommentsRelationshipId(\n relationships: readonly OpcRelationship[],\n): string {\n let nextIndex = 1;\n while (relationships.some((relationship) => relationship.id === `rIdComments${nextIndex}`)) {\n nextIndex += 1;\n }\n\n return `rIdComments${nextIndex}`;\n}\n\nfunction toDocumentRelativeTarget(partPath: string): string {\n const normalized = normalizePartPath(partPath);\n return normalized.startsWith(\"/word/\") ? normalized.slice(\"/word/\".length) : normalized.slice(1);\n}\n\nfunction cloneRelationship(relationship: OpcRelationship): OpcRelationship {\n return { ...relationship };\n}\n\nfunction decodeUtf8(bytes: Uint8Array | undefined): string {\n if (!bytes) {\n return \"\";\n }\n\n return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString(\"utf8\");\n}\n\nfunction toUint8Array(bytes: Uint8Array | ArrayBuffer): Uint8Array {\n return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);\n}\n\nfunction serializeCanonicalDocumentForExport(document: CanonicalDocumentEnvelope): string {\n return createCanonicalDocumentSignature(document);\n}\n\nfunction canReuseSourceBytesForCurrentDocument(\n state: ImportedDocxState,\n document: CanonicalDocumentEnvelope,\n): boolean {\n const commentThreads = Object.values(document.review.comments);\n const hasLiveComments = commentThreads.some((thread) => thread.anchor.kind !== \"detached\");\n if (!hasLiveComments) {\n return true;\n }\n\n return Boolean(\n state.sourceCommentsPartPath &&\n state.sourceCommentsExtendedPartPath &&\n state.sourceCommentsIdsPartPath &&\n state.sourcePeoplePartPath,\n );\n}\n","import type { PersistedEditorSnapshot } from \"../../api/public-types\";\nimport {\n DOCX_DOCUMENT_CONTENT_TYPE,\n DOCX_DOCUMENT_RELATIONSHIP_TYPE,\n writeDocxPackage,\n} from \"../opc/docx-package.ts\";\n\nexport function exportSnapshotToMinimalDocx(\n snapshot: PersistedEditorSnapshot,\n): Uint8Array {\n const paragraphs = collectParagraphTexts(snapshot.canonicalDocument.content);\n const documentXml = buildDocumentXml(paragraphs);\n\n return writeDocxPackage({\n documentXml,\n documentContentType: DOCX_DOCUMENT_CONTENT_TYPE,\n packageRelationshipType: DOCX_DOCUMENT_RELATIONSHIP_TYPE,\n });\n}\n\nfunction collectParagraphTexts(content: unknown): string[] {\n const paragraphs = collectParagraphs(content).map((paragraph) =>\n paragraph.length > 0 ? paragraph : \"\",\n );\n return paragraphs.length > 0 ? paragraphs : [\"\"];\n}\n\nfunction collectParagraphs(value: unknown): string[] {\n if (Array.isArray(value)) {\n return value.flatMap((entry) => collectParagraphs(entry));\n }\n\n if (typeof value === \"string\") {\n return [value];\n }\n\n if (!isRecord(value)) {\n return [];\n }\n\n if (value.type === \"doc\" && Array.isArray(value.children)) {\n return value.children.flatMap((entry) => collectParagraphs(entry));\n }\n\n if (value.type === \"paragraph\") {\n return [collectInlineText(value.children)];\n }\n\n return [];\n}\n\nfunction collectInlineText(value: unknown): string {\n if (Array.isArray(value)) {\n return value.map((entry) => collectInlineText(entry)).join(\"\");\n }\n\n if (typeof value === \"string\") {\n return value;\n }\n\n if (!isRecord(value)) {\n return \"\";\n }\n\n switch (value.type) {\n case \"text\":\n return typeof value.text === \"string\" ? value.text : \"\";\n case \"tab\":\n return \"\\t\";\n case \"hard_break\":\n return \"\\n\";\n case \"hyperlink\":\n return collectInlineText(value.children);\n case \"image\":\n return typeof value.altText === \"string\" ? value.altText : \"[Image]\";\n case \"opaque_inline\":\n return \"[Preserved content]\";\n default:\n return Array.isArray(value.children) ? collectInlineText(value.children) : \"\";\n }\n}\n\nfunction buildDocumentXml(paragraphs: string[]): string {\n const body = paragraphs\n .map(\n (paragraph) =>\n ` <w:p><w:r><w:t xml:space=\"preserve\">${escapeXml(\n paragraph,\n )}</w:t></w:r></w:p>`,\n )\n .join(\"\\n\");\n\n return [\n `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>`,\n `<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">`,\n ` <w:body>`,\n body,\n ` <w:sectPr/>`,\n ` </w:body>`,\n `</w:document>`,\n ].join(\"\\n\");\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","import type { RuntimeRenderSnapshot } from \"../api/public-types\";\n\n/**\n * Session capabilities derived from the runtime snapshot.\n *\n * All fields are computed from `RuntimeRenderSnapshot` — no local component\n * state. The UI reads these to decide what controls to enable/disable, what\n * chrome to show, and what mode the editor is in.\n */\nexport interface SessionCapabilities {\n // ── Session phase ──\n /** Current lifecycle phase of the editor session. */\n phase: \"loading\" | \"ready\" | \"diagnostics\" | \"error\";\n\n /** Effective editor mode after accounting for runtime state. */\n mode: \"editing\" | \"review\" | \"read-only-diagnostics\";\n\n // ── Command capabilities ──\n canUndo: boolean;\n canRedo: boolean;\n canEdit: boolean;\n canAddComment: boolean;\n canExport: boolean;\n canAcceptChange: boolean;\n canRejectChange: boolean;\n canAcceptAll: boolean;\n canRejectAll: boolean;\n\n // ── Review visibility ──\n /** Whether the review rail should be visible by default. */\n reviewRailVisible: boolean;\n\n /** Whether tracked changes exist in the document (display toggle is meaningful). */\n trackChangesSupported: boolean;\n\n // ── Trust posture ──\n exportBlocked: boolean;\n preserveOnlyCount: number;\n unsupportedFatalCount: number;\n\n // ── Health ──\n /** Total count of health issues (preserve-only + unsupported-fatal + warnings). */\n healthIssueCount: number;\n\n // ── Status ──\n isDirty: boolean;\n isReady: boolean;\n hasFatalError: boolean;\n}\n\n/**\n * Derive UI capabilities from the runtime snapshot and requested review mode.\n *\n * This is a pure function with no side effects. Call it on every render to\n * get the current capability state.\n */\nexport function deriveCapabilities(\n snapshot: RuntimeRenderSnapshot,\n reviewMode: \"editing\" | \"review\",\n): SessionCapabilities {\n const hasFatalError = Boolean(snapshot.fatalError);\n const isReady = snapshot.isReady;\n const isReadOnly = snapshot.readOnly;\n const exportBlocked = snapshot.compatibility.blockExport;\n\n // Phase derivation\n const phase: SessionCapabilities[\"phase\"] = !isReady\n ? \"loading\"\n : hasFatalError\n ? \"diagnostics\"\n : \"ready\";\n\n // Mode derivation: if diagnostics or read-only, override the requested mode\n const mode: SessionCapabilities[\"mode\"] =\n phase === \"diagnostics\"\n ? \"read-only-diagnostics\"\n : reviewMode;\n\n // Command capabilities\n const canEdit = isReady && !isReadOnly && !hasFatalError;\n const canUndo = snapshot.commandState.canUndo && canEdit;\n const canRedo = snapshot.commandState.canRedo && canEdit;\n const canAddComment = canEdit && !snapshot.selection.isCollapsed;\n const canExport = isReady && !exportBlocked && !hasFatalError;\n\n // Revision capabilities\n const actionableRevisions = snapshot.trackedChanges.revisions.filter(\n (r) => r.status === \"active\" && r.actionability === \"actionable\",\n );\n const canAcceptChange = canEdit && actionableRevisions.some((r) => r.canAccept);\n const canRejectChange = canEdit && actionableRevisions.some((r) => r.canReject);\n const canAcceptAll = canEdit && actionableRevisions.length > 0;\n const canRejectAll = canEdit && actionableRevisions.length > 0;\n\n // Trust posture (computed before review visibility since it depends on these)\n const preserveOnlyCount = snapshot.compatibility.featureEntries.filter(\n (e) => e.featureClass === \"preserve-only\",\n ).length;\n const unsupportedFatalCount = snapshot.compatibility.featureEntries.filter(\n (e) => e.featureClass === \"unsupported-fatal\",\n ).length;\n\n // Review visibility\n const trackChangesSupported = snapshot.trackedChanges.totalCount > 0;\n // Rail visible in review/diagnostics mode always.\n // In editing mode, rail stays visible when there are trust/health concerns\n // that the user must be able to reach (per DESIGN.md: health/trust info\n // stays reachable in both modes).\n const hasTrustConcerns = exportBlocked || preserveOnlyCount > 0 || unsupportedFatalCount > 0\n || snapshot.warnings.length > 0 || hasFatalError;\n const reviewRailVisible = mode === \"review\" || mode === \"read-only-diagnostics\"\n || (mode === \"editing\" && hasTrustConcerns);\n\n const healthIssueCount = preserveOnlyCount + unsupportedFatalCount + snapshot.warnings.length;\n\n return {\n phase,\n mode,\n canUndo,\n canRedo,\n canEdit,\n canAddComment,\n canExport,\n canAcceptChange,\n canRejectChange,\n canAcceptAll,\n canRejectAll,\n reviewRailVisible,\n trackChangesSupported,\n exportBlocked,\n preserveOnlyCount,\n unsupportedFatalCount,\n healthIssueCount,\n isDirty: snapshot.isDirty,\n isReady,\n hasFatalError,\n };\n}\n","import React, { type FocusEventHandler, useEffect, useMemo, useRef } from \"react\";\nimport { EditorView } from \"prosemirror-view\";\n\nimport type {\n EditorUser,\n RuntimeRenderSnapshot,\n SelectionSnapshot,\n} from \"../../api/public-types\";\nimport {\n createCommentDecorationModel,\n type MarkupDisplay,\n} from \"../../ui/headless/comment-decoration-model\";\nimport { createRevisionDecorationModel } from \"../../ui/headless/revision-decoration-model\";\nimport { createPMStateFromSnapshot } from \"./pm-state-from-snapshot\";\nimport {\n createCommandBridgePlugins,\n type CommandBridgeCallbacks,\n} from \"./pm-command-bridge\";\nimport { buildDecorations } from \"./pm-decorations\";\nimport type { PositionMap } from \"./pm-position-map\";\nimport { tableNodeViews } from \"./tw-table-node-view\";\n\n/**\n * Same props interface as the legacy TwEditorSurface — drop-in replacement.\n */\nexport interface TwProseMirrorSurfaceProps {\n currentUser: EditorUser;\n snapshot: RuntimeRenderSnapshot;\n reviewMode: \"editing\" | \"review\";\n markupDisplay: MarkupDisplay;\n activeRevisionId?: string;\n showTrackedChanges?: boolean;\n onFocus: FocusEventHandler<HTMLDivElement>;\n onBlur: FocusEventHandler<HTMLDivElement>;\n onSelectionChange?: (selection: SelectionSnapshot) => void;\n onInsertText?: (text: string) => void;\n onDeleteBackward?: () => void;\n onDeleteForward?: () => void;\n onInsertTab?: () => void;\n onInsertHardBreak?: () => void;\n onSplitParagraph?: () => void;\n onCommentActivated?: (commentId: string) => void;\n onRevisionActivated?: (revisionId: string) => void;\n}\n\nexport function TwProseMirrorSurface(props: TwProseMirrorSurfaceProps) {\n const {\n currentUser,\n snapshot,\n markupDisplay,\n onFocus,\n onBlur,\n } = props;\n const surface = snapshot.surface;\n\n const canEdit = Boolean(\n surface && snapshot.isReady && !snapshot.readOnly && !snapshot.fatalError,\n );\n\n const mountRef = useRef<HTMLDivElement>(null);\n const viewRef = useRef<EditorView | null>(null);\n const positionMapRef = useRef<PositionMap | null>(null);\n const callbacksRef = useRef<CommandBridgeCallbacks | null>(null);\n\n // Keep callbacks ref up to date (avoids stale closures in PM plugins)\n callbacksRef.current = {\n onInsertText: (text) => props.onInsertText?.(text),\n onDeleteBackward: () => props.onDeleteBackward?.(),\n onDeleteForward: () => props.onDeleteForward?.(),\n onSplitParagraph: () => props.onSplitParagraph?.(),\n onInsertHardBreak: () => props.onInsertHardBreak?.(),\n onInsertTab: () => props.onInsertTab?.(),\n onUndo: () => {}, // Handled by toolbar, not PM\n onRedo: () => {}, // Handled by toolbar, not PM\n onSelectionChange: (sel) => props.onSelectionChange?.(sel),\n getPositionMap: () => positionMapRef.current,\n };\n\n // Comment/revision decoration models\n const commentModel = useMemo(\n () => createCommentDecorationModel(snapshot.comments),\n [snapshot.comments],\n );\n const showTrackedChanges = props.showTrackedChanges !== false;\n // Always create the revision model — needed for deletion hiding in clean mode\n // even when the tracked changes display toggle is off.\n const revisionModel = useMemo(\n () => createRevisionDecorationModel(snapshot.trackedChanges, props.activeRevisionId),\n [snapshot.trackedChanges, props.activeRevisionId],\n );\n\n // Create PM plugins (stable across renders — callbacks accessed via ref)\n const plugins = useMemo(() => {\n return createCommandBridgePlugins({\n onInsertText: (text) => callbacksRef.current?.onInsertText(text),\n onDeleteBackward: () => callbacksRef.current?.onDeleteBackward(),\n onDeleteForward: () => callbacksRef.current?.onDeleteForward(),\n onSplitParagraph: () => callbacksRef.current?.onSplitParagraph(),\n onInsertHardBreak: () => callbacksRef.current?.onInsertHardBreak(),\n onInsertTab: () => callbacksRef.current?.onInsertTab(),\n onUndo: () => callbacksRef.current?.onUndo(),\n onRedo: () => callbacksRef.current?.onRedo(),\n onSelectionChange: (sel) => callbacksRef.current?.onSelectionChange(sel),\n getPositionMap: () => callbacksRef.current?.getPositionMap() ?? null,\n });\n }, []);\n\n // Create or update PM view whenever surface becomes available or changes.\n // The view is created lazily — if surface is null on first render (loading),\n // it will be created when the runtime provides a real snapshot.\n useEffect(() => {\n if (!mountRef.current || !surface) return;\n\n const { state, positionMap } = createPMStateFromSnapshot(\n surface,\n snapshot.selection,\n plugins,\n );\n positionMapRef.current = positionMap;\n\n const decorations = buildDecorations(\n state.doc,\n positionMap,\n commentModel,\n revisionModel,\n markupDisplay,\n showTrackedChanges,\n );\n\n if (!viewRef.current) {\n // First time surface is available — create the EditorView\n const view = new EditorView(mountRef.current, {\n state,\n nodeViews: tableNodeViews,\n editable: () => canEdit,\n decorations: () => decorations,\n dispatchTransaction(tr) {\n const newState = view.state.apply(tr);\n view.updateState(newState);\n },\n });\n viewRef.current = view;\n } else {\n // View exists — update state and decorations\n viewRef.current.setProps({\n editable: () => canEdit,\n decorations: () => decorations,\n });\n viewRef.current.updateState(state);\n }\n }, [snapshot.revisionToken, surface, commentModel, revisionModel, markupDisplay, canEdit]);\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n viewRef.current?.destroy();\n viewRef.current = null;\n };\n }, []);\n\n const fontClass =\n markupDisplay === \"clean\"\n ? \"font-[family-name:var(--font-legal-sans)]\"\n : \"font-[family-name:var(--font-legal-serif)]\";\n\n return (\n <section aria-label=\"Document canvas\" className=\"min-w-0\">\n {/* ProseMirror mount point — document content including headings is editable */}\n {surface ? (\n <div\n ref={mountRef}\n role=\"textbox\"\n aria-multiline=\"true\"\n className={`px-12 py-10 ${fontClass} text-[15px] text-primary leading-relaxed prosemirror-surface outline-none`}\n onFocus={onFocus as unknown as React.FocusEventHandler<HTMLDivElement>}\n onBlur={onBlur as unknown as React.FocusEventHandler<HTMLDivElement>}\n onClick={(e) => {\n // Activate comment or revision when clicking on decorated text\n const target = e.target as HTMLElement;\n const commentEl = target.closest?.(\"[data-comment-id]\");\n if (commentEl) {\n const commentId = commentEl.getAttribute(\"data-comment-id\");\n if (commentId) {\n props.onCommentActivated?.(commentId);\n return;\n }\n }\n const revisionEl = target.closest?.(\"[data-revision-id]\");\n if (revisionEl) {\n const revisionId = revisionEl.getAttribute(\"data-revision-id\");\n if (revisionId) {\n props.onRevisionActivated?.(revisionId);\n }\n }\n }}\n aria-label=\"Document surface\"\n />\n ) : (\n <div className=\"px-12 pb-10\">\n <p className=\"text-sm text-secondary leading-relaxed\">\n Loading the review surface...\n </p>\n </div>\n )}\n\n {snapshot.fatalError ? (\n <div className=\"px-12 pb-10\">\n <p className=\"text-sm text-danger\">\n Fatal runtime error: {snapshot.fatalError.message}\n </p>\n </div>\n ) : null}\n </section>\n );\n}\n","import type { CommentSidebarSnapshot } from \"../../api/public-types\";\n\nexport interface CommentDecorationModel {\n threads: CommentDecorationThread[];\n activeCommentId?: string;\n}\n\nexport interface CommentDecorationThread {\n commentId: string;\n from: number;\n to: number;\n status: CommentSidebarSnapshot[\"threads\"][number][\"status\"];\n isActive: boolean;\n}\n\nexport interface CommentRangeState {\n hasComments: boolean;\n hasOpen: boolean;\n hasResolved: boolean;\n hasActive: boolean;\n count: number;\n overlapping: CommentDecorationThread[];\n}\n\nexport function createCommentDecorationModel(\n snapshot?: CommentSidebarSnapshot,\n): CommentDecorationModel | undefined {\n if (!snapshot) {\n return undefined;\n }\n\n return {\n activeCommentId: snapshot.activeCommentId,\n threads: snapshot.threads\n .filter((thread) => thread.anchor.kind !== \"detached\")\n .map((thread) => {\n const anchor = thread.anchor;\n const from = anchor.kind === \"range\" ? anchor.from : anchor.kind === \"node\" ? anchor.at : 0;\n const to = anchor.kind === \"range\" ? anchor.to : anchor.kind === \"node\" ? anchor.at : 0;\n return {\n commentId: thread.commentId,\n from,\n to,\n status: thread.status,\n isActive: thread.isActive,\n };\n }),\n };\n}\n\nexport function getCommentRangeState(\n model: CommentDecorationModel | undefined,\n from: number,\n to: number,\n): CommentRangeState {\n if (!model) {\n return {\n hasComments: false,\n hasOpen: false,\n hasResolved: false,\n hasActive: false,\n count: 0,\n overlapping: [],\n };\n }\n\n const overlapping = model.threads.filter((thread) =>\n rangesOverlap(thread.from, thread.to, from, to),\n );\n return {\n hasComments: overlapping.length > 0,\n hasOpen: overlapping.some((thread) => thread.status === \"open\"),\n hasResolved: overlapping.some((thread) => thread.status === \"resolved\"),\n hasActive: overlapping.some((thread) => thread.isActive),\n count: overlapping.length,\n overlapping,\n };\n}\n\nexport type MarkupDisplay = \"clean\" | \"simple\" | \"all\";\n\nexport function getCommentHighlightClass(\n model: CommentDecorationModel | undefined,\n from: number,\n to: number,\n markupDisplay: MarkupDisplay = \"all\",\n): string {\n const state = getCommentRangeState(model, from, to);\n if (!state.hasComments) {\n return \"\";\n }\n\n switch (markupDisplay) {\n case \"clean\":\n return state.hasActive ? \"bg-comment-soft\" : \"\";\n case \"simple\":\n if (state.hasActive) {\n return \"underline decoration-comment decoration-2 underline-offset-4\";\n }\n if (state.hasOpen) {\n return \"underline decoration-comment/60 decoration-1 underline-offset-4\";\n }\n return \"underline decoration-comment/40 decoration-1 underline-offset-4\";\n case \"all\":\n if (state.hasActive) {\n return \"bg-comment-strong\";\n }\n if (state.hasOpen) {\n return \"bg-comment-soft\";\n }\n return \"bg-comment-soft opacity-60\";\n }\n}\n\nexport function rangesOverlap(\n leftFrom: number,\n leftTo: number,\n rightFrom: number,\n rightTo: number,\n): boolean {\n const leftEnd = Math.max(leftFrom, leftTo);\n const rightEnd = Math.max(rightFrom, rightTo);\n return leftFrom < rightEnd && rightFrom < leftEnd;\n}\n","import type { TrackedChangesSnapshot, TrackedChangeEntrySnapshot } from \"../../api/public-types\";\nimport { rangesOverlap, type MarkupDisplay } from \"./comment-decoration-model\";\n\nexport interface RevisionDecorationModel {\n revisions: RevisionDecorationEntry[];\n}\n\nexport interface RevisionDecorationEntry {\n revisionId: string;\n from: number;\n to: number;\n kind: TrackedChangeEntrySnapshot[\"kind\"];\n status: TrackedChangeEntrySnapshot[\"status\"];\n actionability: TrackedChangeEntrySnapshot[\"actionability\"];\n isActive: boolean;\n}\n\nexport interface RevisionRangeState {\n hasChanges: boolean;\n hasInsertions: boolean;\n hasDeletions: boolean;\n hasActive: boolean;\n count: number;\n overlapping: RevisionDecorationEntry[];\n}\n\nexport function createRevisionDecorationModel(\n snapshot?: TrackedChangesSnapshot,\n activeRevisionId?: string,\n): RevisionDecorationModel | undefined {\n if (!snapshot) {\n return undefined;\n }\n\n return {\n revisions: snapshot.revisions\n .filter((rev) => rev.anchor.kind !== \"detached\" && rev.status === \"active\")\n .map((rev) => {\n const anchor = rev.anchor;\n const from = anchor.kind === \"range\" ? anchor.from : anchor.kind === \"node\" ? anchor.at : 0;\n const to = anchor.kind === \"range\" ? anchor.to : anchor.kind === \"node\" ? anchor.at : 0;\n return {\n revisionId: rev.revisionId,\n from,\n to,\n kind: rev.kind,\n status: rev.status,\n actionability: rev.actionability,\n isActive: rev.revisionId === activeRevisionId,\n };\n }),\n };\n}\n\nexport function getRevisionRangeState(\n model: RevisionDecorationModel | undefined,\n from: number,\n to: number,\n): RevisionRangeState {\n if (!model) {\n return {\n hasChanges: false,\n hasInsertions: false,\n hasDeletions: false,\n hasActive: false,\n count: 0,\n overlapping: [],\n };\n }\n\n const overlapping = model.revisions.filter((rev) =>\n rangesOverlap(rev.from, rev.to, from, to),\n );\n return {\n hasChanges: overlapping.length > 0,\n hasInsertions: overlapping.some((rev) => rev.kind === \"insertion\"),\n hasDeletions: overlapping.some((rev) => rev.kind === \"deletion\"),\n hasActive: overlapping.some((rev) => rev.isActive),\n count: overlapping.length,\n overlapping,\n };\n}\n\nexport function getRevisionHighlightClass(\n model: RevisionDecorationModel | undefined,\n from: number,\n to: number,\n markupDisplay: MarkupDisplay = \"all\",\n): string {\n const state = getRevisionRangeState(model, from, to);\n if (!state.hasChanges) {\n return \"\";\n }\n\n const activeRing = state.hasActive ? \" ring-1 ring-accent/30\" : \"\";\n\n switch (markupDisplay) {\n case \"clean\":\n // In clean mode, deletions are hidden entirely (caller should not render).\n // Insertions render as normal text with no decoration.\n return \"\";\n case \"simple\":\n if (state.hasInsertions) {\n return `underline decoration-insert/40 decoration-1 underline-offset-2${activeRing}`;\n }\n if (state.hasDeletions) {\n return `text-secondary line-through decoration-1${activeRing}`;\n }\n return activeRing;\n case \"all\":\n if (state.hasInsertions) {\n return `text-insert bg-insert-soft${activeRing}`;\n }\n if (state.hasDeletions) {\n return `text-danger line-through decoration-1 bg-delete-soft${activeRing}`;\n }\n return activeRing;\n }\n}\n\nexport function shouldHideInCleanMode(\n model: RevisionDecorationModel | undefined,\n from: number,\n to: number,\n): boolean {\n const state = getRevisionRangeState(model, from, to);\n return state.hasDeletions;\n}\n","import { Fragment, type Node as PMNode } from \"prosemirror-model\";\nimport { EditorState, type Plugin, TextSelection } from \"prosemirror-state\";\n\nimport type {\n EditorSurfaceSnapshot,\n SelectionSnapshot,\n SurfaceBlockSnapshot,\n SurfaceInlineSegment,\n SurfaceTableRowSnapshot,\n SurfaceTableCellSnapshot,\n} from \"../../api/public-types\";\nimport { editorSchema } from \"./pm-schema\";\nimport { buildPositionMap, type PositionMap } from \"./pm-position-map\";\n\nexport interface PMStateResult {\n state: EditorState;\n positionMap: PositionMap;\n}\n\n/**\n * Create a ProseMirror EditorState from a runtime surface snapshot.\n *\n * The PM document mirrors the snapshot for rendering and input.\n * It is NOT the canonical source — the runtime owns that.\n */\nexport function createPMStateFromSnapshot(\n surface: EditorSurfaceSnapshot,\n selection: SelectionSnapshot,\n plugins: Plugin[],\n): PMStateResult {\n const doc = buildPMDoc(surface);\n const positionMap = buildPositionMap(surface);\n\n // Convert runtime selection to PM selection\n const pmAnchor = clamp(\n positionMap.runtimeToPm(selection.anchor),\n 1,\n positionMap.pmDocSize - 1,\n );\n const pmHead = clamp(\n positionMap.runtimeToPm(selection.head),\n 1,\n positionMap.pmDocSize - 1,\n );\n\n let pmSelection: TextSelection;\n try {\n pmSelection = TextSelection.create(doc, pmAnchor, pmHead);\n } catch {\n // If the position is invalid (e.g., inside an atom), fall back to start\n pmSelection = TextSelection.create(doc, 1);\n }\n\n const state = EditorState.create({\n doc,\n selection: pmSelection,\n plugins,\n });\n\n return { state, positionMap };\n}\n\nfunction buildPMDoc(surface: EditorSurfaceSnapshot): PMNode {\n const blocks: PMNode[] = [];\n\n for (const block of surface.blocks) {\n if (block.kind === \"paragraph\") {\n blocks.push(buildParagraph(block));\n } else if (block.kind === \"table\") {\n blocks.push(buildTable(block));\n } else if (block.kind === \"sdt_block\") {\n blocks.push(buildSdtBlock(block));\n } else {\n blocks.push(buildOpaqueBlock(block));\n }\n }\n\n // Ensure at least one block (PM requires non-empty doc)\n if (blocks.length === 0) {\n blocks.push(editorSchema.nodes.paragraph.create());\n }\n\n return editorSchema.nodes.doc.create(null, Fragment.from(blocks));\n}\n\nfunction buildParagraph(\n block: Extract<SurfaceBlockSnapshot, { kind: \"paragraph\" }>,\n): PMNode {\n const content: PMNode[] = [];\n\n for (const segment of block.segments) {\n const nodes = buildInlineContent(segment);\n content.push(...nodes);\n }\n\n return editorSchema.nodes.paragraph.create(\n {\n styleId: block.styleId ?? null,\n numberingInstanceId: block.numbering?.numberingInstanceId ?? null,\n numberingLevel: block.numbering?.level ?? null,\n },\n content.length > 0 ? Fragment.from(content) : undefined,\n );\n}\n\nfunction buildInlineContent(segment: SurfaceInlineSegment): PMNode[] {\n switch (segment.kind) {\n case \"text\": {\n if (!segment.text) return [];\n\n // Build PM marks from segment marks\n let marks = editorSchema.marks.bold.isInSet([])\n ? [] // shouldn't happen, just type safety\n : [];\n\n const pmMarks = [];\n if (segment.marks) {\n for (const mark of segment.marks) {\n const pmMark = editorSchema.marks[mark];\n if (pmMark) {\n pmMarks.push(pmMark.create());\n }\n }\n }\n if (segment.hyperlinkHref) {\n pmMarks.push(editorSchema.marks.link.create({ href: segment.hyperlinkHref }));\n }\n\n return [editorSchema.text(segment.text, pmMarks.length > 0 ? pmMarks : undefined)];\n }\n\n case \"hard_break\":\n return [editorSchema.nodes.hard_break.create()];\n\n case \"tab\":\n return [editorSchema.nodes.tab_char.create()];\n\n case \"image\":\n return [\n editorSchema.nodes.image_atom.create({\n mediaId: segment.mediaId,\n altText: segment.altText ?? null,\n state: segment.state,\n display: segment.display ?? \"inline\",\n detail: segment.detail ?? null,\n }),\n ];\n\n case \"opaque_inline\":\n return [buildOpaqueInlineOrComplexAtom(segment)];\n\n default:\n return [];\n }\n}\n\nfunction buildTable(\n block: Extract<SurfaceBlockSnapshot, { kind: \"table\" }>,\n): PMNode {\n const rows: PMNode[] = [];\n for (const row of block.rows) {\n const cells: PMNode[] = [];\n for (const cell of row.cells) {\n const cellContent: PMNode[] = [];\n for (const child of cell.content) {\n if (child.kind === \"paragraph\") {\n cellContent.push(buildParagraph(child as Extract<SurfaceBlockSnapshot, { kind: \"paragraph\" }>));\n } else if (child.kind === \"table\") {\n cellContent.push(buildNestedTablePlaceholder(child as Extract<SurfaceBlockSnapshot, { kind: \"table\" }>));\n } else if (child.kind === \"sdt_block\") {\n cellContent.push(buildOpaqueBlock({\n blockId: child.blockId,\n kind: \"opaque_block\",\n from: child.from,\n to: child.to,\n fragmentId: child.blockId,\n warningId: child.blockId,\n label: child.alias ?? child.tag ?? \"Content control\",\n detail: \"Structured content control remains read-only inside table cells.\",\n state: \"locked-preserve-only\",\n }));\n } else if (child.kind === \"opaque_block\") {\n cellContent.push(buildOpaqueBlock(child as Extract<SurfaceBlockSnapshot, { kind: \"opaque_block\" }>));\n }\n }\n // Ensure at least one paragraph in cell (PM requires non-empty)\n if (cellContent.length === 0) {\n cellContent.push(editorSchema.nodes.paragraph.create());\n }\n cells.push(\n editorSchema.nodes.table_cell.create(\n {\n colspan: cell.colspan,\n rowspan: cell.rowspan,\n gridSpan: cell.gridSpan,\n verticalMerge: cell.verticalMerge,\n },\n Fragment.from(cellContent),\n ),\n );\n }\n rows.push(editorSchema.nodes.table_row.create(null, Fragment.from(cells)));\n }\n return editorSchema.nodes.table.create(\n {\n styleId: block.styleId ?? null,\n gridColumns: block.gridColumns,\n },\n Fragment.from(rows),\n );\n}\n\nfunction buildNestedTablePlaceholder(\n block: Extract<SurfaceBlockSnapshot, { kind: \"table\" }>,\n): PMNode {\n return buildOpaqueBlock({\n blockId: block.blockId,\n kind: \"opaque_block\",\n from: block.from,\n to: block.to,\n fragmentId: block.blockId,\n warningId: block.blockId,\n label: \"Nested table\",\n detail: \"Nested table remains read-only in the live ProseMirror cell surface.\",\n state: \"locked-preserve-only\",\n });\n}\n\nfunction buildSdtBlock(\n block: Extract<SurfaceBlockSnapshot, { kind: \"sdt_block\" }>,\n): PMNode {\n const children = block.children.map((child) => {\n if (child.kind === \"paragraph\") {\n return buildParagraph(child);\n }\n if (child.kind === \"table\") {\n return buildTable(child);\n }\n if (child.kind === \"sdt_block\") {\n return buildSdtBlock(child);\n }\n return buildOpaqueBlock(child);\n });\n\n if (children.length === 0) {\n children.push(editorSchema.nodes.paragraph.create());\n }\n\n return editorSchema.nodes.sdt_block.create(\n {\n sdtType: block.sdtType ?? null,\n alias: block.alias ?? null,\n tag: block.tag ?? null,\n lock: block.lock ?? null,\n },\n Fragment.from(children),\n );\n}\n\n/**\n * Map an opaque_inline surface segment to a dedicated complex-rendering PM atom\n * node when the label identifies a known complex content type, or fall back to\n * the generic opaque_inline node.\n */\nfunction buildOpaqueInlineOrComplexAtom(\n segment: Extract<import(\"../../api/public-types\").SurfaceInlineSegment, { kind: \"opaque_inline\" }>,\n): PMNode {\n const label = segment.label;\n const detail = segment.detail;\n\n if (label === \"Chart\") {\n return editorSchema.nodes.chart_atom.create({ detail });\n }\n if (label === \"SmartArt\") {\n return editorSchema.nodes.smartart_atom.create({ detail });\n }\n if (label === \"Shape\") {\n // Extract text hint from detail if present\n const textMatch = /Text: \"([^\"]+)\"/.exec(detail);\n const geometryMatch = /Geometry: ([^.]+)\\./.exec(detail);\n return editorSchema.nodes.shape_atom.create({\n text: textMatch ? textMatch[1] : null,\n geometry: geometryMatch ? geometryMatch[1] : null,\n detail,\n });\n }\n if (label === \"WordArt\") {\n const textMatch = /Text: \"([^\"]+)\"/.exec(detail);\n const effectMatch = /Effect: ([^.]+)\\./.exec(detail);\n return editorSchema.nodes.wordart_atom.create({\n text: textMatch ? textMatch[1] : \"\",\n geometry: effectMatch ? effectMatch[1] : null,\n detail,\n });\n }\n if (label === \"VML shape\") {\n const textMatch = /Text: \"([^\"]+)\"/.exec(detail);\n const typeMatch = /Type: ([^.]+)\\./.exec(detail);\n return editorSchema.nodes.vml_atom.create({\n text: textMatch ? textMatch[1] : null,\n shapeType: typeMatch ? typeMatch[1] : null,\n detail,\n });\n }\n\n return editorSchema.nodes.opaque_inline.create({\n fragmentId: segment.fragmentId,\n warningId: segment.warningId,\n label,\n detail,\n });\n}\n\nfunction buildOpaqueBlock(\n block: Extract<SurfaceBlockSnapshot, { kind: \"opaque_block\" }>,\n): PMNode {\n return editorSchema.nodes.opaque_block.create({\n fragmentId: block.fragmentId,\n warningId: block.warningId,\n label: block.label,\n detail: block.detail,\n });\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n","import { Schema } from \"prosemirror-model\";\nimport {\n tableNodeSpec,\n tableRowNodeSpec,\n tableCellNodeSpec,\n tableHeaderCellNodeSpec,\n} from \"../../runtime/table-schema.ts\";\n\n/**\n * ProseMirror schema for the supported live surface slice.\n *\n * Maps canonical document node types to PM nodes and marks.\n * This schema is used for rendering and input capture only —\n * ProseMirror does not own the canonical document state.\n */\nexport const editorSchema = new Schema({\n nodes: {\n doc: {\n content: \"block+\",\n },\n\n paragraph: {\n content: \"inline*\",\n group: \"block\",\n attrs: {\n styleId: { default: null },\n numberingInstanceId: { default: null },\n numberingLevel: { default: null },\n alignment: { default: null },\n },\n parseDOM: [{ tag: \"p\" }],\n toDOM(node) {\n const classes: string[] = [\"leading-relaxed\"];\n const styleId = node.attrs.styleId as string | null;\n if (styleId) {\n const lower = styleId.toLowerCase();\n if (lower === \"heading1\") classes.push(\"text-2xl font-medium\");\n else if (lower === \"heading2\") classes.push(\"text-xl font-medium\");\n else if (lower === \"heading3\") classes.push(\"text-lg font-medium\");\n }\n const attrs: Record<string, string> = { class: classes.join(\" \") };\n const alignment = node.attrs.alignment as string | null;\n if (alignment) attrs.style = `text-align: ${alignment}`;\n return [\"p\", attrs, 0];\n },\n },\n\n text: {\n group: \"inline\",\n },\n\n hard_break: {\n inline: true,\n group: \"inline\",\n selectable: false,\n parseDOM: [{ tag: \"br\" }],\n toDOM() {\n return [\"br\"];\n },\n },\n\n tab_char: {\n inline: true,\n group: \"inline\",\n atom: true,\n selectable: false,\n toDOM() {\n return [\"span\", { class: \"inline-block w-8\", \"data-node-type\": \"tab\" }, \"\\u00A0\"];\n },\n },\n\n image_atom: {\n inline: true,\n group: \"inline\",\n atom: true,\n attrs: {\n mediaId: { default: \"\" },\n altText: { default: null },\n state: { default: \"editable\" },\n display: { default: \"inline\" },\n detail: { default: null },\n },\n toDOM(node) {\n const isMissing = node.attrs.state === \"missing\";\n const isFloating = node.attrs.display === \"floating\";\n return [\n \"span\",\n {\n class: `inline-flex items-center gap-1 mx-0.5 px-1.5 py-0.5 rounded text-xs border-none ${\n isMissing ? \"text-danger bg-delete-soft\" : \"text-secondary bg-surface\"\n }`,\n \"data-node-type\": \"image\",\n title: (node.attrs.detail as string) ?? (node.attrs.altText as string) ?? \"Image\",\n },\n \"\\uD83D\\uDCF7 \" + ((node.attrs.altText as string) ?? (isMissing ? \"Missing\" : isFloating ? \"Floating image\" : \"Image\")),\n ];\n },\n },\n\n sdt_block: {\n group: \"block\",\n content: \"block+\",\n isolating: true,\n attrs: {\n sdtType: { default: null },\n alias: { default: null },\n tag: { default: null },\n lock: { default: null },\n },\n toDOM(node) {\n const meta = [node.attrs.alias, node.attrs.tag, node.attrs.sdtType].filter(Boolean).join(\" · \");\n return [\n \"section\",\n {\n class: \"my-2 rounded-xl border border-primary/15 bg-surface-raised/60 px-3 py-2\",\n \"data-node-type\": \"sdt_block\",\n },\n [\n \"div\",\n {\n class: \"mb-2 text-[11px] uppercase tracking-[0.18em] text-tertiary\",\n contenteditable: \"false\",\n },\n meta || \"Content control\",\n ],\n [\"div\", 0],\n ];\n },\n },\n\n opaque_inline: {\n inline: true,\n group: \"inline\",\n atom: true,\n selectable: false,\n attrs: {\n fragmentId: { default: \"\" },\n warningId: { default: \"\" },\n label: { default: \"Locked\" },\n detail: { default: \"\" },\n },\n toDOM(node) {\n return [\n \"span\",\n {\n class: \"inline-flex items-center gap-1 mx-0.5 px-1.5 py-0.5 rounded text-xs text-comment bg-warning-soft\",\n \"data-node-type\": \"opaque_inline\",\n title: node.attrs.detail as string,\n },\n \"\\uD83D\\uDD12 \" + (node.attrs.label as string),\n ];\n },\n },\n\n table: tableNodeSpec,\n table_row: tableRowNodeSpec,\n table_cell: tableCellNodeSpec,\n table_header_cell: tableHeaderCellNodeSpec,\n\n // ---- Complex rendering atoms (read-only previews) ----\n\n chart_atom: {\n inline: true,\n group: \"inline\",\n atom: true,\n selectable: false,\n attrs: {\n previewMediaId: { default: null },\n detail: { default: null },\n },\n toDOM(node) {\n return [\n \"span\",\n {\n class: \"inline-flex items-center gap-1 mx-0.5 px-1.5 py-0.5 rounded text-xs text-blue-700 bg-blue-50 border border-blue-200\",\n \"data-node-type\": \"chart_atom\",\n contenteditable: \"false\",\n title: (node.attrs.detail as string) ?? \"Chart\",\n },\n \"\\uD83D\\uDCC8 Chart\",\n ];\n },\n },\n\n smartart_atom: {\n inline: true,\n group: \"inline\",\n atom: true,\n selectable: false,\n attrs: {\n previewMediaId: { default: null },\n detail: { default: null },\n },\n toDOM(node) {\n return [\n \"span\",\n {\n class: \"inline-flex items-center gap-1 mx-0.5 px-1.5 py-0.5 rounded text-xs text-purple-700 bg-purple-50 border border-purple-200\",\n \"data-node-type\": \"smartart_atom\",\n contenteditable: \"false\",\n title: (node.attrs.detail as string) ?? \"SmartArt\",\n },\n \"\\uD83D\\uDDFA SmartArt\",\n ];\n },\n },\n\n shape_atom: {\n inline: true,\n group: \"inline\",\n atom: true,\n selectable: false,\n attrs: {\n text: { default: null },\n geometry: { default: null },\n detail: { default: null },\n },\n toDOM(node) {\n const text = node.attrs.text as string | null;\n const label = text ? `Shape: ${text}` : \"Shape\";\n return [\n \"span\",\n {\n class: \"inline-flex items-center gap-1 mx-0.5 px-1.5 py-0.5 rounded text-xs text-green-700 bg-green-50 border border-green-200\",\n \"data-node-type\": \"shape_atom\",\n contenteditable: \"false\",\n title: (node.attrs.detail as string) ?? label,\n },\n \"\\u25A1 \" + label,\n ];\n },\n },\n\n wordart_atom: {\n inline: true,\n group: \"inline\",\n atom: true,\n selectable: false,\n attrs: {\n text: { default: \"\" },\n geometry: { default: null },\n detail: { default: null },\n },\n toDOM(node) {\n const text = node.attrs.text as string;\n return [\n \"span\",\n {\n class: \"inline-flex items-center gap-1 mx-0.5 px-1.5 py-0.5 rounded text-xs text-orange-700 bg-orange-50 border border-orange-200 font-medium italic\",\n \"data-node-type\": \"wordart_atom\",\n contenteditable: \"false\",\n title: (node.attrs.detail as string) ?? `WordArt: ${text}`,\n },\n \"\\u2728 \" + (text || \"WordArt\"),\n ];\n },\n },\n\n vml_atom: {\n inline: true,\n group: \"inline\",\n atom: true,\n selectable: false,\n attrs: {\n text: { default: null },\n shapeType: { default: null },\n detail: { default: null },\n },\n toDOM(node) {\n const text = node.attrs.text as string | null;\n const label = text ? `VML: ${text}` : \"VML shape\";\n return [\n \"span\",\n {\n class: \"inline-flex items-center gap-1 mx-0.5 px-1.5 py-0.5 rounded text-xs text-gray-600 bg-gray-100 border border-gray-300\",\n \"data-node-type\": \"vml_atom\",\n contenteditable: \"false\",\n title: (node.attrs.detail as string) ?? label,\n },\n \"\\u25A6 \" + label,\n ];\n },\n },\n\n opaque_block: {\n group: \"block\",\n atom: true,\n selectable: false,\n attrs: {\n fragmentId: { default: \"\" },\n warningId: { default: \"\" },\n label: { default: \"Locked\" },\n detail: { default: \"\" },\n },\n toDOM(node) {\n return [\n \"div\",\n {\n class: \"border-l-2 border-dashed border-warning/30 pl-4 py-2 rounded-r bg-warning-soft/20 my-2\",\n contenteditable: \"false\",\n \"data-node-type\": \"opaque_block\",\n },\n [\n \"div\",\n { class: \"flex items-center gap-1.5 text-xs text-tertiary mb-1\" },\n \"\\uD83D\\uDD12 \" + (node.attrs.label as string),\n ],\n [\"p\", { class: \"text-sm text-secondary\" }, node.attrs.detail as string],\n ];\n },\n },\n },\n\n marks: {\n bold: {\n parseDOM: [{ tag: \"strong\" }, { tag: \"b\" }],\n toDOM() {\n return [\"strong\", 0];\n },\n },\n italic: {\n parseDOM: [{ tag: \"em\" }, { tag: \"i\" }],\n toDOM() {\n return [\"em\", 0];\n },\n },\n underline: {\n parseDOM: [{ tag: \"u\" }],\n toDOM() {\n return [\"u\", 0];\n },\n },\n strikethrough: {\n parseDOM: [{ tag: \"s\" }, { tag: \"del\" }],\n toDOM() {\n return [\"s\", 0];\n },\n },\n superscript: {\n excludes: \"subscript\",\n parseDOM: [{ tag: \"sup\" }],\n toDOM() {\n return [\"sup\", 0];\n },\n },\n subscript: {\n excludes: \"superscript\",\n parseDOM: [{ tag: \"sub\" }],\n toDOM() {\n return [\"sub\", 0];\n },\n },\n small_caps: {\n parseDOM: [\n {\n style: \"font-variant\",\n getAttrs: (value) => (value === \"small-caps\" ? null : false),\n },\n ],\n toDOM() {\n return [\"span\", { style: \"font-variant: small-caps\" }, 0];\n },\n },\n all_caps: {\n parseDOM: [\n {\n style: \"text-transform\",\n getAttrs: (value) => (value === \"uppercase\" ? null : false),\n },\n ],\n toDOM() {\n return [\"span\", { style: \"text-transform: uppercase\" }, 0];\n },\n },\n font_family: {\n attrs: { family: { default: null } },\n parseDOM: [\n {\n style: \"font-family\",\n getAttrs: (value) => ({ family: (value as string).replace(/['\"]/g, \"\") }),\n },\n ],\n toDOM(mark) {\n return [\"span\", { style: `font-family: ${mark.attrs.family as string}` }, 0];\n },\n },\n font_size: {\n attrs: { size: { default: null } },\n parseDOM: [\n {\n style: \"font-size\",\n getAttrs: (value) => {\n const match = (value as string).match(/^(\\d+(?:\\.\\d+)?)/);\n return match ? { size: Number.parseFloat(match[1]) } : false;\n },\n },\n ],\n toDOM(mark) {\n return [\"span\", { style: `font-size: ${mark.attrs.size as number}pt` }, 0];\n },\n },\n text_color: {\n attrs: { color: { default: null } },\n parseDOM: [\n {\n style: \"color\",\n getAttrs: (value) => ({ color: value }),\n },\n ],\n toDOM(mark) {\n const color = mark.attrs.color as string;\n return [\"span\", { style: `color: ${color}` }, 0];\n },\n },\n highlight: {\n attrs: { color: { default: \"yellow\" } },\n parseDOM: [\n {\n tag: \"mark\",\n getAttrs: (dom) => ({ color: (dom as HTMLElement).style.backgroundColor || \"yellow\" }),\n },\n ],\n toDOM(mark) {\n return [\"mark\", { style: `background-color: ${mark.attrs.color as string}` }, 0];\n },\n },\n link: {\n attrs: { href: { default: \"\" } },\n inclusive: false,\n parseDOM: [\n {\n tag: \"a[href]\",\n getAttrs(dom) {\n return { href: (dom as HTMLElement).getAttribute(\"href\") };\n },\n },\n ],\n toDOM(mark) {\n return [\n \"a\",\n {\n href: mark.attrs.href as string,\n class: \"text-accent underline decoration-1 underline-offset-2\",\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n 0,\n ];\n },\n },\n },\n});\n","/**\n * ProseMirror table node specifications for first-class table editing.\n *\n * These specs define the structure required for tables in the ProseMirror schema,\n * compatible with prosemirror-tables when used as a dependency, or standalone for\n * basic cell-content editing.\n *\n * All four specs must be included together when merging into a schema because\n * table_row references both table_cell and table_header_cell in its content model.\n */\n\nimport type { NodeSpec } from \"prosemirror-model\";\n\nexport const tableNodeSpec: NodeSpec = {\n content: \"table_row+\",\n tableRole: \"table\",\n group: \"block\",\n isolating: true,\n attrs: {\n styleId: { default: null },\n propertiesXml: { default: null },\n gridColumns: { default: [] },\n },\n parseDOM: [{ tag: \"table\" }],\n toDOM() {\n return [\"table\", { class: \"border-collapse w-full my-2 text-sm\" }, [\"tbody\", 0]];\n },\n};\n\nexport const tableRowNodeSpec: NodeSpec = {\n content: \"(table_cell | table_header_cell)+\",\n tableRole: \"row\",\n attrs: {\n propertiesXml: { default: null },\n },\n parseDOM: [{ tag: \"tr\" }],\n toDOM() {\n return [\"tr\", 0];\n },\n};\n\nexport const tableCellNodeSpec: NodeSpec = {\n content: \"paragraph+\",\n tableRole: \"cell\",\n isolating: true,\n attrs: {\n propertiesXml: { default: null },\n gridSpan: { default: 1 },\n verticalMerge: { default: null },\n colspan: { default: 1 },\n rowspan: { default: 1 },\n colwidth: { default: null },\n },\n parseDOM: [\n {\n tag: \"td\",\n getAttrs(dom: HTMLElement) {\n const colspan = dom.getAttribute(\"colspan\");\n const rowspan = dom.getAttribute(\"rowspan\");\n return {\n colspan: colspan ? Number.parseInt(colspan, 10) : 1,\n rowspan: rowspan ? Number.parseInt(rowspan, 10) : 1,\n };\n },\n },\n ],\n toDOM(node) {\n const attrs: Record<string, string> = {\n class: \"border border-primary/20 p-2 align-top\",\n };\n if (node.attrs.colspan > 1) attrs.colspan = String(node.attrs.colspan);\n if (node.attrs.rowspan > 1) attrs.rowspan = String(node.attrs.rowspan);\n return [\"td\", attrs, 0];\n },\n};\n\nexport const tableHeaderCellNodeSpec: NodeSpec = {\n content: \"paragraph+\",\n tableRole: \"header_cell\",\n isolating: true,\n attrs: {\n propertiesXml: { default: null },\n gridSpan: { default: 1 },\n verticalMerge: { default: null },\n colspan: { default: 1 },\n rowspan: { default: 1 },\n colwidth: { default: null },\n },\n parseDOM: [\n {\n tag: \"th\",\n getAttrs(dom: HTMLElement) {\n const colspan = dom.getAttribute(\"colspan\");\n const rowspan = dom.getAttribute(\"rowspan\");\n return {\n colspan: colspan ? Number.parseInt(colspan, 10) : 1,\n rowspan: rowspan ? Number.parseInt(rowspan, 10) : 1,\n };\n },\n },\n ],\n toDOM(node) {\n const attrs: Record<string, string> = {\n class: \"border border-primary/20 p-2 align-top font-semibold bg-surface-raised\",\n };\n if (node.attrs.colspan > 1) attrs.colspan = String(node.attrs.colspan);\n if (node.attrs.rowspan > 1) attrs.rowspan = String(node.attrs.rowspan);\n return [\"th\", attrs, 0];\n },\n};\n\n/**\n * Returns a record of all four table node specs to merge into an existing ProseMirror Schema.\n *\n * All four must be included together because table_row references both table_cell and\n * table_header_cell in its content model.\n */\nexport function getTableNodeSpecs(): Record<string, NodeSpec> {\n return {\n table: tableNodeSpec,\n table_row: tableRowNodeSpec,\n table_cell: tableCellNodeSpec,\n table_header_cell: tableHeaderCellNodeSpec,\n };\n}\n","import type { EditorSurfaceSnapshot, SurfaceBlockSnapshot } from \"../../api/public-types\";\n\nexport interface PositionMap {\n runtimeToPm(runtimePos: number): number;\n pmToRuntime(pmPos: number): number;\n pmDocSize: number;\n runtimeStorySize: number;\n}\n\ninterface MapEntry {\n runtimeStart: number;\n pmStart: number;\n runtimeEnd: number;\n pmEnd: number;\n}\n\nexport function buildPositionMap(surface: EditorSurfaceSnapshot): PositionMap {\n const entries: MapEntry[] = [];\n const pmDocSize = walkBlocks(surface.blocks, 1, entries);\n const runtimeStorySize = surface.storySize;\n\n return {\n runtimeToPm(runtimePos: number): number {\n if (runtimePos <= 0) {\n return entries[0]?.pmStart ?? 1;\n }\n if (runtimePos >= runtimeStorySize) {\n return pmDocSize - 1;\n }\n\n for (const entry of entries) {\n if (runtimePos >= entry.runtimeStart && runtimePos <= entry.runtimeEnd) {\n return entry.pmStart + (runtimePos - entry.runtimeStart);\n }\n if (runtimePos < entry.runtimeStart) {\n return entry.pmStart;\n }\n }\n\n return entries[entries.length - 1]?.pmEnd ?? 1;\n },\n\n pmToRuntime(pmPos: number): number {\n if (pmPos <= 1) {\n return 0;\n }\n if (pmPos >= pmDocSize - 1) {\n return runtimeStorySize;\n }\n\n for (const entry of entries) {\n if (pmPos >= entry.pmStart && pmPos <= entry.pmEnd) {\n return entry.runtimeStart + (pmPos - entry.pmStart);\n }\n if (pmPos < entry.pmStart) {\n return entry.runtimeStart;\n }\n }\n\n return runtimeStorySize;\n },\n\n pmDocSize,\n runtimeStorySize,\n };\n}\n\nfunction walkBlocks(\n blocks: SurfaceBlockSnapshot[],\n pmCursor: number,\n entries: MapEntry[],\n): number {\n let nextPmCursor = pmCursor;\n\n for (const block of blocks) {\n switch (block.kind) {\n case \"paragraph\": {\n const pmContentStart = nextPmCursor + 1;\n const runtimeLength = block.to - block.from;\n entries.push({\n runtimeStart: block.from,\n pmStart: pmContentStart,\n runtimeEnd: block.to,\n pmEnd: pmContentStart + runtimeLength,\n });\n nextPmCursor += runtimeLength + 2;\n break;\n }\n case \"opaque_block\": {\n entries.push({\n runtimeStart: block.from,\n pmStart: nextPmCursor,\n runtimeEnd: block.to,\n pmEnd: nextPmCursor + 1,\n });\n nextPmCursor += 1;\n break;\n }\n case \"sdt_block\": {\n nextPmCursor += 1;\n nextPmCursor = walkBlocks(block.children, nextPmCursor, entries);\n nextPmCursor += 1;\n break;\n }\n case \"table\": {\n nextPmCursor += 1;\n for (const row of block.rows) {\n nextPmCursor += 1;\n for (const cell of row.cells) {\n nextPmCursor += 1;\n nextPmCursor = walkBlocks(cell.content, nextPmCursor, entries);\n nextPmCursor += 1;\n }\n nextPmCursor += 1;\n }\n nextPmCursor += 1;\n break;\n }\n }\n }\n\n return nextPmCursor;\n}\n","import { Plugin, PluginKey } from \"prosemirror-state\";\nimport { keymap } from \"prosemirror-keymap\";\nimport { columnResizing, goToNextCell, isInTable, tableEditing } from \"prosemirror-tables\";\n\nimport type { SelectionSnapshot } from \"../../api/public-types\";\nimport { createSelectionSnapshot } from \"../../ui/headless/selection-helpers\";\nimport type { PositionMap } from \"./pm-position-map\";\n\nexport interface CommandBridgeCallbacks {\n onInsertText: (text: string) => void;\n onDeleteBackward: () => void;\n onDeleteForward: () => void;\n onSplitParagraph: () => void;\n onInsertHardBreak: () => void;\n onInsertTab: () => void;\n onUndo: () => void;\n onRedo: () => void;\n onSelectionChange: (selection: SelectionSnapshot) => void;\n getPositionMap: () => PositionMap | null;\n}\n\nconst bridgeKey = new PluginKey(\"command-bridge\");\n\n/**\n * Creates ProseMirror plugins that intercept user input and dispatch\n * runtime commands instead of letting PM mutate its own state.\n *\n * All doc-changing transactions are blocked. Only the explicit input\n * hooks below are allowed to trigger runtime commands.\n */\nexport function createCommandBridgePlugins(\n callbacks: CommandBridgeCallbacks,\n): Plugin[] {\n // Transaction filter: block ALL doc-changing transactions.\n // The runtime is the sole authority for document mutations.\n const filterPlugin = new Plugin({\n key: bridgeKey,\n filterTransaction(tr) {\n // Allow selection-only and metadata-only transactions\n if (!tr.docChanged) return true;\n // Block doc changes — runtime handles mutations via callbacks\n return false;\n },\n });\n\n // Selection sync: when PM selection changes, notify the runtime.\n const selectionPlugin = new Plugin({\n view() {\n return {\n update(view, prevState) {\n if (!view.state.selection.eq(prevState.selection)) {\n const posMap = callbacks.getPositionMap();\n if (!posMap) return;\n\n const { from, to } = view.state.selection;\n const runtimeAnchor = posMap.pmToRuntime(from);\n const runtimeHead = posMap.pmToRuntime(to);\n callbacks.onSelectionChange(\n createSelectionSnapshot(runtimeAnchor, runtimeHead),\n );\n }\n },\n };\n },\n });\n\n // Text input hook: intercept typed characters.\n const inputPlugin = new Plugin({\n props: {\n handleTextInput(_view, _from, _to, text) {\n callbacks.onInsertText(text);\n return true; // Block PM from processing\n },\n\n // Block paste (rich paste is not safe, plain paste via text.insert is TODO)\n handlePaste() {\n return true; // Block\n },\n\n // Block drop\n handleDrop() {\n return true; // Block\n },\n },\n });\n\n // Keymap: intercept editing keys and dispatch runtime commands.\n const keymapPlugin = keymap({\n Backspace: () => {\n callbacks.onDeleteBackward();\n return true;\n },\n Delete: () => {\n callbacks.onDeleteForward();\n return true;\n },\n Enter: () => {\n callbacks.onSplitParagraph();\n return true;\n },\n \"Shift-Enter\": () => {\n callbacks.onInsertHardBreak();\n return true;\n },\n Tab: (state, dispatch, view) => {\n if (isInTable(state)) {\n return goToNextCell(1)(state, dispatch, view);\n }\n callbacks.onInsertTab();\n return true;\n },\n \"Shift-Tab\": (state, dispatch, view) => {\n if (isInTable(state)) {\n return goToNextCell(-1)(state, dispatch, view);\n }\n return false;\n },\n \"Mod-z\": () => {\n callbacks.onUndo();\n return true;\n },\n \"Mod-y\": () => {\n callbacks.onRedo();\n return true;\n },\n \"Shift-Mod-z\": () => {\n callbacks.onRedo();\n return true;\n },\n });\n\n // Table editing: provides Tab/Shift-Tab navigation between cells and\n // selection handles. Doc-changing table transactions (new rows, etc.) are\n // filtered by the runtime filter above; navigation-only steps pass through.\n const tablePlugin = tableEditing();\n const columnResizingPlugin = columnResizing();\n\n return [filterPlugin, selectionPlugin, inputPlugin, keymapPlugin, tablePlugin, columnResizingPlugin];\n}\n","import type { SelectionSnapshot } from \"../../api/public-types\";\n\nexport function createSelectionSnapshot(anchor: number, head = anchor): SelectionSnapshot {\n const from = Math.min(anchor, head);\n const to = Math.max(anchor, head);\n return {\n anchor,\n head,\n isCollapsed: anchor === head,\n activeRange: {\n kind: \"range\",\n from,\n to,\n assoc: {\n start: -1,\n end: 1,\n },\n },\n };\n}\n\nexport function selectionTouchesRange(\n selection: SelectionSnapshot,\n from: number,\n to: number,\n): boolean {\n if (selection.isCollapsed) {\n return false;\n }\n\n const selectionFrom = Math.min(selection.anchor, selection.head);\n const selectionTo = Math.max(selection.anchor, selection.head);\n return selectionFrom < to && from < selectionTo;\n}\n","import { Decoration, DecorationSet } from \"prosemirror-view\";\n\nimport type { CommentDecorationModel } from \"../../ui/headless/comment-decoration-model\";\nimport { getCommentHighlightClass, type MarkupDisplay } from \"../../ui/headless/comment-decoration-model\";\nimport type { RevisionDecorationModel } from \"../../ui/headless/revision-decoration-model\";\nimport { getRevisionHighlightClass } from \"../../ui/headless/revision-decoration-model\";\nimport type { PositionMap } from \"./pm-position-map\";\nimport type { Node as PMNode } from \"prosemirror-model\";\n\n/**\n * Build ProseMirror DecorationSet from runtime comment and revision models.\n *\n * Uses the existing headless decoration models to compute Tailwind class\n * strings, then converts them to PM inline decorations at the correct\n * PM positions via the PositionMap.\n */\nexport function buildDecorations(\n doc: PMNode,\n positionMap: PositionMap,\n commentModel: CommentDecorationModel | undefined,\n revisionModel: RevisionDecorationModel | undefined,\n markupDisplay: MarkupDisplay,\n showTrackedChanges = true,\n): DecorationSet {\n const decorations: Decoration[] = [];\n\n // Walk comment threads and create inline decorations\n if (commentModel) {\n for (const thread of commentModel.threads) {\n const cls = getCommentHighlightClass(\n commentModel,\n thread.from,\n thread.to,\n markupDisplay,\n );\n if (!cls) continue;\n\n const pmFrom = positionMap.runtimeToPm(thread.from);\n const pmTo = positionMap.runtimeToPm(thread.to);\n if (pmFrom < pmTo) {\n decorations.push(\n Decoration.inline(pmFrom, pmTo, {\n class: cls,\n \"data-comment-id\": thread.commentId,\n }),\n );\n }\n }\n }\n\n // Walk revision entries and create inline decorations.\n // Deletion hiding in clean mode ALWAYS applies, even when showTrackedChanges is off.\n // Visual styling (underlines, colors) only applies when showTrackedChanges is on.\n if (revisionModel) {\n for (const rev of revisionModel.revisions) {\n // Always hide deletions in clean mode (final-text semantics).\n // This is the critical behavior: \"hide tracked changes\" must show\n // the document as if accepted, not show deleted text as kept text.\n if (markupDisplay === \"clean\" && rev.kind === \"deletion\") {\n const pmFrom = positionMap.runtimeToPm(rev.from);\n const pmTo = positionMap.runtimeToPm(rev.to);\n if (pmFrom < pmTo) {\n decorations.push(\n Decoration.inline(pmFrom, pmTo, {\n class: \"hidden\",\n \"data-revision-id\": rev.revisionId,\n }),\n );\n }\n continue;\n }\n\n // Skip visual styling when tracked changes display is off\n if (!showTrackedChanges) continue;\n\n const cls = getRevisionHighlightClass(\n revisionModel,\n rev.from,\n rev.to,\n markupDisplay,\n );\n if (!cls) continue;\n\n const pmFrom = positionMap.runtimeToPm(rev.from);\n const pmTo = positionMap.runtimeToPm(rev.to);\n if (pmFrom < pmTo) {\n decorations.push(\n Decoration.inline(pmFrom, pmTo, {\n class: cls,\n \"data-revision-id\": rev.revisionId,\n }),\n );\n }\n }\n }\n\n return DecorationSet.create(doc, decorations);\n}\n","/**\n * ProseMirror NodeView implementations for table nodes.\n *\n * These NodeViews render table structure as proper HTML tables with\n * colspan/rowspan support for merged cells (from gridSpan/verticalMerge attrs).\n *\n * Usage with EditorView:\n * new EditorView(mount, {\n * nodeViews: tableNodeViews,\n * ...\n * })\n */\n\nimport type { Node as PMNode } from \"prosemirror-model\";\n\n/**\n * NodeView for the table node.\n * Renders as <table><tbody>...</tbody></table>.\n * ProseMirror places row content into the tbody via contentDOM.\n */\nexport class TableNodeView {\n dom: HTMLElement;\n contentDOM: HTMLElement;\n\n constructor(_node: PMNode) {\n const table = document.createElement(\"table\");\n table.className = \"border-collapse w-full my-2 text-sm\";\n\n const tbody = document.createElement(\"tbody\");\n table.appendChild(tbody);\n\n this.dom = table;\n this.contentDOM = tbody;\n }\n}\n\n/**\n * NodeView for table_row nodes.\n * Renders as <tr>...</tr>.\n */\nexport class TableRowNodeView {\n dom: HTMLElement;\n contentDOM: HTMLElement;\n\n constructor(_node: PMNode) {\n const tr = document.createElement(\"tr\");\n this.dom = tr;\n this.contentDOM = tr;\n }\n}\n\n/**\n * NodeView for table_cell and table_header_cell nodes.\n *\n * Applies colspan/rowspan from node attrs (mapped from gridSpan/verticalMerge\n * in the OOXML model). Distinguishes header cells by tableRole spec attribute.\n */\nexport class TableCellNodeView {\n dom: HTMLElement;\n contentDOM: HTMLElement;\n\n constructor(node: PMNode) {\n const isHeader = (node.type.spec as { tableRole?: string }).tableRole === \"header_cell\";\n const cell = document.createElement(isHeader ? \"th\" : \"td\");\n\n cell.className = isHeader\n ? \"border border-primary/20 p-2 align-top font-semibold bg-surface-raised\"\n : \"border border-primary/20 p-2 align-top\";\n\n const colspan = node.attrs.colspan as number;\n const rowspan = node.attrs.rowspan as number;\n if (colspan > 1) (cell as HTMLTableCellElement).colSpan = colspan;\n if (rowspan > 1) (cell as HTMLTableCellElement).rowSpan = rowspan;\n\n this.dom = cell;\n this.contentDOM = cell;\n }\n\n /**\n * Update the DOM when the node's attrs change (e.g., after a merge/split operation).\n * Return false to let ProseMirror rebuild the node view from scratch.\n */\n update(node: PMNode): boolean {\n const isHeader = (node.type.spec as { tableRole?: string }).tableRole === \"header_cell\";\n const expectedTag = isHeader ? \"TH\" : \"TD\";\n if (this.dom.tagName !== expectedTag) return false;\n\n const colspan = node.attrs.colspan as number;\n const rowspan = node.attrs.rowspan as number;\n const cell = this.dom as HTMLTableCellElement;\n cell.colSpan = colspan > 1 ? colspan : 1;\n cell.rowSpan = rowspan > 1 ? rowspan : 1;\n return true;\n }\n}\n\n/**\n * NodeView factory map for use with EditorView.nodeViews.\n *\n * Pass this object directly to the EditorView constructor options:\n * new EditorView(mount, { nodeViews: tableNodeViews, ... })\n */\nexport const tableNodeViews = {\n table: (node: PMNode) => new TableNodeView(node),\n table_row: (node: PMNode) => new TableRowNodeView(node),\n table_cell: (node: PMNode) => new TableCellNodeView(node),\n table_header_cell: (node: PMNode) => new TableCellNodeView(node),\n};\n","import * as React from 'react';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { DismissableLayer } from '@radix-ui/react-dismissable-layer';\nimport { useId } from '@radix-ui/react-id';\nimport * as PopperPrimitive from '@radix-ui/react-popper';\nimport { createPopperScope } from '@radix-ui/react-popper';\nimport { Portal as PortalPrimitive } from '@radix-ui/react-portal';\nimport { Presence } from '@radix-ui/react-presence';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { createSlottable } from '@radix-ui/react-slot';\nimport { useControllableState } from '@radix-ui/react-use-controllable-state';\nimport * as VisuallyHiddenPrimitive from '@radix-ui/react-visually-hidden';\n\nimport type { Scope } from '@radix-ui/react-context';\n\ntype ScopedProps<P = {}> = P & { __scopeTooltip?: Scope };\nconst [createTooltipContext, createTooltipScope] = createContextScope('Tooltip', [\n createPopperScope,\n]);\nconst usePopperScope = createPopperScope();\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipProvider\n * -----------------------------------------------------------------------------------------------*/\n\nconst PROVIDER_NAME = 'TooltipProvider';\nconst DEFAULT_DELAY_DURATION = 700;\nconst TOOLTIP_OPEN = 'tooltip.open';\n\ntype TooltipProviderContextValue = {\n isOpenDelayedRef: React.MutableRefObject<boolean>;\n delayDuration: number;\n onOpen(): void;\n onClose(): void;\n onPointerInTransitChange(inTransit: boolean): void;\n isPointerInTransitRef: React.MutableRefObject<boolean>;\n disableHoverableContent: boolean;\n};\n\nconst [TooltipProviderContextProvider, useTooltipProviderContext] =\n createTooltipContext<TooltipProviderContextValue>(PROVIDER_NAME);\n\ninterface TooltipProviderProps {\n children: React.ReactNode;\n /**\n * The duration from when the pointer enters the trigger until the tooltip gets opened.\n * @defaultValue 700\n */\n delayDuration?: number;\n /**\n * How much time a user has to enter another trigger without incurring a delay again.\n * @defaultValue 300\n */\n skipDelayDuration?: number;\n /**\n * When `true`, trying to hover the content will result in the tooltip closing as the pointer leaves the trigger.\n * @defaultValue false\n */\n disableHoverableContent?: boolean;\n}\n\nconst TooltipProvider: React.FC<TooltipProviderProps> = (\n props: ScopedProps<TooltipProviderProps>\n) => {\n const {\n __scopeTooltip,\n delayDuration = DEFAULT_DELAY_DURATION,\n skipDelayDuration = 300,\n disableHoverableContent = false,\n children,\n } = props;\n const isOpenDelayedRef = React.useRef(true);\n const isPointerInTransitRef = React.useRef(false);\n const skipDelayTimerRef = React.useRef(0);\n\n React.useEffect(() => {\n const skipDelayTimer = skipDelayTimerRef.current;\n return () => window.clearTimeout(skipDelayTimer);\n }, []);\n\n return (\n <TooltipProviderContextProvider\n scope={__scopeTooltip}\n isOpenDelayedRef={isOpenDelayedRef}\n delayDuration={delayDuration}\n onOpen={React.useCallback(() => {\n window.clearTimeout(skipDelayTimerRef.current);\n isOpenDelayedRef.current = false;\n }, [])}\n onClose={React.useCallback(() => {\n window.clearTimeout(skipDelayTimerRef.current);\n skipDelayTimerRef.current = window.setTimeout(\n () => (isOpenDelayedRef.current = true),\n skipDelayDuration\n );\n }, [skipDelayDuration])}\n isPointerInTransitRef={isPointerInTransitRef}\n onPointerInTransitChange={React.useCallback((inTransit: boolean) => {\n isPointerInTransitRef.current = inTransit;\n }, [])}\n disableHoverableContent={disableHoverableContent}\n >\n {children}\n </TooltipProviderContextProvider>\n );\n};\n\nTooltipProvider.displayName = PROVIDER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * Tooltip\n * -----------------------------------------------------------------------------------------------*/\n\nconst TOOLTIP_NAME = 'Tooltip';\n\ntype TooltipContextValue = {\n contentId: string;\n open: boolean;\n stateAttribute: 'closed' | 'delayed-open' | 'instant-open';\n trigger: TooltipTriggerElement | null;\n onTriggerChange(trigger: TooltipTriggerElement | null): void;\n onTriggerEnter(): void;\n onTriggerLeave(): void;\n onOpen(): void;\n onClose(): void;\n disableHoverableContent: boolean;\n};\n\nconst [TooltipContextProvider, useTooltipContext] =\n createTooltipContext<TooltipContextValue>(TOOLTIP_NAME);\n\ninterface TooltipProps {\n children?: React.ReactNode;\n open?: boolean;\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n /**\n * The duration from when the pointer enters the trigger until the tooltip gets opened. This will\n * override the prop with the same name passed to Provider.\n * @defaultValue 700\n */\n delayDuration?: number;\n /**\n * When `true`, trying to hover the content will result in the tooltip closing as the pointer leaves the trigger.\n * @defaultValue false\n */\n disableHoverableContent?: boolean;\n}\n\nconst Tooltip: React.FC<TooltipProps> = (props: ScopedProps<TooltipProps>) => {\n const {\n __scopeTooltip,\n children,\n open: openProp,\n defaultOpen,\n onOpenChange,\n disableHoverableContent: disableHoverableContentProp,\n delayDuration: delayDurationProp,\n } = props;\n const providerContext = useTooltipProviderContext(TOOLTIP_NAME, props.__scopeTooltip);\n const popperScope = usePopperScope(__scopeTooltip);\n const [trigger, setTrigger] = React.useState<HTMLButtonElement | null>(null);\n const contentId = useId();\n const openTimerRef = React.useRef(0);\n const disableHoverableContent =\n disableHoverableContentProp ?? providerContext.disableHoverableContent;\n const delayDuration = delayDurationProp ?? providerContext.delayDuration;\n const wasOpenDelayedRef = React.useRef(false);\n const [open, setOpen] = useControllableState({\n prop: openProp,\n defaultProp: defaultOpen ?? false,\n onChange: (open) => {\n if (open) {\n providerContext.onOpen();\n\n // as `onChange` is called within a lifecycle method we\n // avoid dispatching via `dispatchDiscreteCustomEvent`.\n document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN));\n } else {\n providerContext.onClose();\n }\n onOpenChange?.(open);\n },\n caller: TOOLTIP_NAME,\n });\n const stateAttribute = React.useMemo(() => {\n return open ? (wasOpenDelayedRef.current ? 'delayed-open' : 'instant-open') : 'closed';\n }, [open]);\n\n const handleOpen = React.useCallback(() => {\n window.clearTimeout(openTimerRef.current);\n openTimerRef.current = 0;\n wasOpenDelayedRef.current = false;\n setOpen(true);\n }, [setOpen]);\n\n const handleClose = React.useCallback(() => {\n window.clearTimeout(openTimerRef.current);\n openTimerRef.current = 0;\n setOpen(false);\n }, [setOpen]);\n\n const handleDelayedOpen = React.useCallback(() => {\n window.clearTimeout(openTimerRef.current);\n openTimerRef.current = window.setTimeout(() => {\n wasOpenDelayedRef.current = true;\n setOpen(true);\n openTimerRef.current = 0;\n }, delayDuration);\n }, [delayDuration, setOpen]);\n\n React.useEffect(() => {\n return () => {\n if (openTimerRef.current) {\n window.clearTimeout(openTimerRef.current);\n openTimerRef.current = 0;\n }\n };\n }, []);\n\n return (\n <PopperPrimitive.Root {...popperScope}>\n <TooltipContextProvider\n scope={__scopeTooltip}\n contentId={contentId}\n open={open}\n stateAttribute={stateAttribute}\n trigger={trigger}\n onTriggerChange={setTrigger}\n onTriggerEnter={React.useCallback(() => {\n if (providerContext.isOpenDelayedRef.current) handleDelayedOpen();\n else handleOpen();\n }, [providerContext.isOpenDelayedRef, handleDelayedOpen, handleOpen])}\n onTriggerLeave={React.useCallback(() => {\n if (disableHoverableContent) {\n handleClose();\n } else {\n // Clear the timer in case the pointer leaves the trigger before the tooltip is opened.\n window.clearTimeout(openTimerRef.current);\n openTimerRef.current = 0;\n }\n }, [handleClose, disableHoverableContent])}\n onOpen={handleOpen}\n onClose={handleClose}\n disableHoverableContent={disableHoverableContent}\n >\n {children}\n </TooltipContextProvider>\n </PopperPrimitive.Root>\n );\n};\n\nTooltip.displayName = TOOLTIP_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipTrigger\n * -----------------------------------------------------------------------------------------------*/\n\nconst TRIGGER_NAME = 'TooltipTrigger';\n\ntype TooltipTriggerElement = React.ComponentRef<typeof Primitive.button>;\ntype PrimitiveButtonProps = React.ComponentPropsWithoutRef<typeof Primitive.button>;\ninterface TooltipTriggerProps extends PrimitiveButtonProps {}\n\nconst TooltipTrigger = React.forwardRef<TooltipTriggerElement, TooltipTriggerProps>(\n (props: ScopedProps<TooltipTriggerProps>, forwardedRef) => {\n const { __scopeTooltip, ...triggerProps } = props;\n const context = useTooltipContext(TRIGGER_NAME, __scopeTooltip);\n const providerContext = useTooltipProviderContext(TRIGGER_NAME, __scopeTooltip);\n const popperScope = usePopperScope(__scopeTooltip);\n const ref = React.useRef<TooltipTriggerElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref, context.onTriggerChange);\n const isPointerDownRef = React.useRef(false);\n const hasPointerMoveOpenedRef = React.useRef(false);\n const handlePointerUp = React.useCallback(() => (isPointerDownRef.current = false), []);\n\n React.useEffect(() => {\n return () => document.removeEventListener('pointerup', handlePointerUp);\n }, [handlePointerUp]);\n\n return (\n <PopperPrimitive.Anchor asChild {...popperScope}>\n <Primitive.button\n // We purposefully avoid adding `type=button` here because tooltip triggers are also\n // commonly anchors and the anchor `type` attribute signifies MIME type.\n aria-describedby={context.open ? context.contentId : undefined}\n data-state={context.stateAttribute}\n {...triggerProps}\n ref={composedRefs}\n onPointerMove={composeEventHandlers(props.onPointerMove, (event) => {\n if (event.pointerType === 'touch') return;\n if (\n !hasPointerMoveOpenedRef.current &&\n !providerContext.isPointerInTransitRef.current\n ) {\n context.onTriggerEnter();\n hasPointerMoveOpenedRef.current = true;\n }\n })}\n onPointerLeave={composeEventHandlers(props.onPointerLeave, () => {\n context.onTriggerLeave();\n hasPointerMoveOpenedRef.current = false;\n })}\n onPointerDown={composeEventHandlers(props.onPointerDown, () => {\n if (context.open) {\n context.onClose();\n }\n isPointerDownRef.current = true;\n document.addEventListener('pointerup', handlePointerUp, { once: true });\n })}\n onFocus={composeEventHandlers(props.onFocus, () => {\n if (!isPointerDownRef.current) context.onOpen();\n })}\n onBlur={composeEventHandlers(props.onBlur, context.onClose)}\n onClick={composeEventHandlers(props.onClick, context.onClose)}\n />\n </PopperPrimitive.Anchor>\n );\n }\n);\n\nTooltipTrigger.displayName = TRIGGER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipPortal\n * -----------------------------------------------------------------------------------------------*/\n\nconst PORTAL_NAME = 'TooltipPortal';\n\ntype PortalContextValue = { forceMount?: true };\nconst [PortalProvider, usePortalContext] = createTooltipContext<PortalContextValue>(PORTAL_NAME, {\n forceMount: undefined,\n});\n\ntype PortalProps = React.ComponentPropsWithoutRef<typeof PortalPrimitive>;\ninterface TooltipPortalProps {\n children?: React.ReactNode;\n /**\n * Specify a container element to portal the content into.\n */\n container?: PortalProps['container'];\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst TooltipPortal: React.FC<TooltipPortalProps> = (props: ScopedProps<TooltipPortalProps>) => {\n const { __scopeTooltip, forceMount, children, container } = props;\n const context = useTooltipContext(PORTAL_NAME, __scopeTooltip);\n return (\n <PortalProvider scope={__scopeTooltip} forceMount={forceMount}>\n <Presence present={forceMount || context.open}>\n <PortalPrimitive asChild container={container}>\n {children}\n </PortalPrimitive>\n </Presence>\n </PortalProvider>\n );\n};\n\nTooltipPortal.displayName = PORTAL_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipContent\n * -----------------------------------------------------------------------------------------------*/\n\nconst CONTENT_NAME = 'TooltipContent';\n\ntype TooltipContentElement = TooltipContentImplElement;\ninterface TooltipContentProps extends TooltipContentImplProps {\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst TooltipContent = React.forwardRef<TooltipContentElement, TooltipContentProps>(\n (props: ScopedProps<TooltipContentProps>, forwardedRef) => {\n const portalContext = usePortalContext(CONTENT_NAME, props.__scopeTooltip);\n const { forceMount = portalContext.forceMount, side = 'top', ...contentProps } = props;\n const context = useTooltipContext(CONTENT_NAME, props.__scopeTooltip);\n\n return (\n <Presence present={forceMount || context.open}>\n {context.disableHoverableContent ? (\n <TooltipContentImpl side={side} {...contentProps} ref={forwardedRef} />\n ) : (\n <TooltipContentHoverable side={side} {...contentProps} ref={forwardedRef} />\n )}\n </Presence>\n );\n }\n);\n\ntype Point = { x: number; y: number };\ntype Polygon = Point[];\n\ntype TooltipContentHoverableElement = TooltipContentImplElement;\ninterface TooltipContentHoverableProps extends TooltipContentImplProps {}\n\nconst TooltipContentHoverable = React.forwardRef<\n TooltipContentHoverableElement,\n TooltipContentHoverableProps\n>((props: ScopedProps<TooltipContentHoverableProps>, forwardedRef) => {\n const context = useTooltipContext(CONTENT_NAME, props.__scopeTooltip);\n const providerContext = useTooltipProviderContext(CONTENT_NAME, props.__scopeTooltip);\n const ref = React.useRef<TooltipContentHoverableElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n const [pointerGraceArea, setPointerGraceArea] = React.useState<Polygon | null>(null);\n\n const { trigger, onClose } = context;\n const content = ref.current;\n\n const { onPointerInTransitChange } = providerContext;\n\n const handleRemoveGraceArea = React.useCallback(() => {\n setPointerGraceArea(null);\n onPointerInTransitChange(false);\n }, [onPointerInTransitChange]);\n\n const handleCreateGraceArea = React.useCallback(\n (event: PointerEvent, hoverTarget: HTMLElement) => {\n const currentTarget = event.currentTarget as HTMLElement;\n const exitPoint = { x: event.clientX, y: event.clientY };\n const exitSide = getExitSideFromRect(exitPoint, currentTarget.getBoundingClientRect());\n const paddedExitPoints = getPaddedExitPoints(exitPoint, exitSide);\n const hoverTargetPoints = getPointsFromRect(hoverTarget.getBoundingClientRect());\n const graceArea = getHull([...paddedExitPoints, ...hoverTargetPoints]);\n setPointerGraceArea(graceArea);\n onPointerInTransitChange(true);\n },\n [onPointerInTransitChange]\n );\n\n React.useEffect(() => {\n return () => handleRemoveGraceArea();\n }, [handleRemoveGraceArea]);\n\n React.useEffect(() => {\n if (trigger && content) {\n const handleTriggerLeave = (event: PointerEvent) => handleCreateGraceArea(event, content);\n const handleContentLeave = (event: PointerEvent) => handleCreateGraceArea(event, trigger);\n\n trigger.addEventListener('pointerleave', handleTriggerLeave);\n content.addEventListener('pointerleave', handleContentLeave);\n return () => {\n trigger.removeEventListener('pointerleave', handleTriggerLeave);\n content.removeEventListener('pointerleave', handleContentLeave);\n };\n }\n }, [trigger, content, handleCreateGraceArea, handleRemoveGraceArea]);\n\n React.useEffect(() => {\n if (pointerGraceArea) {\n const handleTrackPointerGrace = (event: PointerEvent) => {\n const target = event.target as HTMLElement;\n const pointerPosition = { x: event.clientX, y: event.clientY };\n const hasEnteredTarget = trigger?.contains(target) || content?.contains(target);\n const isPointerOutsideGraceArea = !isPointInPolygon(pointerPosition, pointerGraceArea);\n\n if (hasEnteredTarget) {\n handleRemoveGraceArea();\n } else if (isPointerOutsideGraceArea) {\n handleRemoveGraceArea();\n onClose();\n }\n };\n document.addEventListener('pointermove', handleTrackPointerGrace);\n return () => document.removeEventListener('pointermove', handleTrackPointerGrace);\n }\n }, [trigger, content, pointerGraceArea, onClose, handleRemoveGraceArea]);\n\n return <TooltipContentImpl {...props} ref={composedRefs} />;\n});\n\nconst [VisuallyHiddenContentContextProvider, useVisuallyHiddenContentContext] =\n createTooltipContext(TOOLTIP_NAME, { isInside: false });\n\ntype TooltipContentImplElement = React.ComponentRef<typeof PopperPrimitive.Content>;\ntype DismissableLayerProps = React.ComponentPropsWithoutRef<typeof DismissableLayer>;\ntype PopperContentProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Content>;\ninterface TooltipContentImplProps extends Omit<PopperContentProps, 'onPlaced'> {\n /**\n * A more descriptive label for accessibility purpose\n */\n 'aria-label'?: string;\n\n /**\n * Event handler called when the escape key is down.\n * Can be prevented.\n */\n onEscapeKeyDown?: DismissableLayerProps['onEscapeKeyDown'];\n /**\n * Event handler called when the a `pointerdown` event happens outside of the `Tooltip`.\n * Can be prevented.\n */\n onPointerDownOutside?: DismissableLayerProps['onPointerDownOutside'];\n}\n\nconst Slottable = createSlottable('TooltipContent');\n\nconst TooltipContentImpl = React.forwardRef<TooltipContentImplElement, TooltipContentImplProps>(\n (props: ScopedProps<TooltipContentImplProps>, forwardedRef) => {\n const {\n __scopeTooltip,\n children,\n 'aria-label': ariaLabel,\n onEscapeKeyDown,\n onPointerDownOutside,\n ...contentProps\n } = props;\n const context = useTooltipContext(CONTENT_NAME, __scopeTooltip);\n const popperScope = usePopperScope(__scopeTooltip);\n const { onClose } = context;\n\n // Close this tooltip if another one opens\n React.useEffect(() => {\n document.addEventListener(TOOLTIP_OPEN, onClose);\n return () => document.removeEventListener(TOOLTIP_OPEN, onClose);\n }, [onClose]);\n\n // Close the tooltip if the trigger is scrolled\n React.useEffect(() => {\n if (context.trigger) {\n const handleScroll = (event: Event) => {\n const target = event.target as HTMLElement;\n if (target?.contains(context.trigger)) onClose();\n };\n window.addEventListener('scroll', handleScroll, { capture: true });\n return () => window.removeEventListener('scroll', handleScroll, { capture: true });\n }\n }, [context.trigger, onClose]);\n\n return (\n <DismissableLayer\n asChild\n disableOutsidePointerEvents={false}\n onEscapeKeyDown={onEscapeKeyDown}\n onPointerDownOutside={onPointerDownOutside}\n onFocusOutside={(event) => event.preventDefault()}\n onDismiss={onClose}\n >\n <PopperPrimitive.Content\n data-state={context.stateAttribute}\n {...popperScope}\n {...contentProps}\n ref={forwardedRef}\n style={{\n ...contentProps.style,\n // re-namespace exposed content custom properties\n ...{\n '--radix-tooltip-content-transform-origin': 'var(--radix-popper-transform-origin)',\n '--radix-tooltip-content-available-width': 'var(--radix-popper-available-width)',\n '--radix-tooltip-content-available-height': 'var(--radix-popper-available-height)',\n '--radix-tooltip-trigger-width': 'var(--radix-popper-anchor-width)',\n '--radix-tooltip-trigger-height': 'var(--radix-popper-anchor-height)',\n },\n }}\n >\n <Slottable>{children}</Slottable>\n <VisuallyHiddenContentContextProvider scope={__scopeTooltip} isInside={true}>\n <VisuallyHiddenPrimitive.Root id={context.contentId} role=\"tooltip\">\n {ariaLabel || children}\n </VisuallyHiddenPrimitive.Root>\n </VisuallyHiddenContentContextProvider>\n </PopperPrimitive.Content>\n </DismissableLayer>\n );\n }\n);\n\nTooltipContent.displayName = CONTENT_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipArrow\n * -----------------------------------------------------------------------------------------------*/\n\nconst ARROW_NAME = 'TooltipArrow';\n\ntype TooltipArrowElement = React.ComponentRef<typeof PopperPrimitive.Arrow>;\ntype PopperArrowProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Arrow>;\ninterface TooltipArrowProps extends PopperArrowProps {}\n\nconst TooltipArrow = React.forwardRef<TooltipArrowElement, TooltipArrowProps>(\n (props: ScopedProps<TooltipArrowProps>, forwardedRef) => {\n const { __scopeTooltip, ...arrowProps } = props;\n const popperScope = usePopperScope(__scopeTooltip);\n const visuallyHiddenContentContext = useVisuallyHiddenContentContext(\n ARROW_NAME,\n __scopeTooltip\n );\n // if the arrow is inside the `VisuallyHidden`, we don't want to render it all to\n // prevent issues in positioning the arrow due to the duplicate\n return visuallyHiddenContentContext.isInside ? null : (\n <PopperPrimitive.Arrow {...popperScope} {...arrowProps} ref={forwardedRef} />\n );\n }\n);\n\nTooltipArrow.displayName = ARROW_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype Side = NonNullable<TooltipContentProps['side']>;\n\nfunction getExitSideFromRect(point: Point, rect: DOMRect): Side {\n const top = Math.abs(rect.top - point.y);\n const bottom = Math.abs(rect.bottom - point.y);\n const right = Math.abs(rect.right - point.x);\n const left = Math.abs(rect.left - point.x);\n\n switch (Math.min(top, bottom, right, left)) {\n case left:\n return 'left';\n case right:\n return 'right';\n case top:\n return 'top';\n case bottom:\n return 'bottom';\n default:\n throw new Error('unreachable');\n }\n}\n\nfunction getPaddedExitPoints(exitPoint: Point, exitSide: Side, padding = 5) {\n const paddedExitPoints: Point[] = [];\n switch (exitSide) {\n case 'top':\n paddedExitPoints.push(\n { x: exitPoint.x - padding, y: exitPoint.y + padding },\n { x: exitPoint.x + padding, y: exitPoint.y + padding }\n );\n break;\n case 'bottom':\n paddedExitPoints.push(\n { x: exitPoint.x - padding, y: exitPoint.y - padding },\n { x: exitPoint.x + padding, y: exitPoint.y - padding }\n );\n break;\n case 'left':\n paddedExitPoints.push(\n { x: exitPoint.x + padding, y: exitPoint.y - padding },\n { x: exitPoint.x + padding, y: exitPoint.y + padding }\n );\n break;\n case 'right':\n paddedExitPoints.push(\n { x: exitPoint.x - padding, y: exitPoint.y - padding },\n { x: exitPoint.x - padding, y: exitPoint.y + padding }\n );\n break;\n }\n return paddedExitPoints;\n}\n\nfunction getPointsFromRect(rect: DOMRect) {\n const { top, right, bottom, left } = rect;\n return [\n { x: left, y: top },\n { x: right, y: top },\n { x: right, y: bottom },\n { x: left, y: bottom },\n ];\n}\n\n// Determine if a point is inside of a polygon.\n// Based on https://github.com/substack/point-in-polygon\nfunction isPointInPolygon(point: Point, polygon: Polygon) {\n const { x, y } = point;\n let inside = false;\n for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n const ii = polygon[i]!;\n const jj = polygon[j]!;\n const xi = ii.x;\n const yi = ii.y;\n const xj = jj.x;\n const yj = jj.y;\n\n // prettier-ignore\n const intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);\n if (intersect) inside = !inside;\n }\n\n return inside;\n}\n\n// Returns a new array of points representing the convex hull of the given set of points.\n// https://www.nayuki.io/page/convex-hull-algorithm\nfunction getHull<P extends Point>(points: Readonly<Array<P>>): Array<P> {\n const newPoints: Array<P> = points.slice();\n newPoints.sort((a: Point, b: Point) => {\n if (a.x < b.x) return -1;\n else if (a.x > b.x) return +1;\n else if (a.y < b.y) return -1;\n else if (a.y > b.y) return +1;\n else return 0;\n });\n return getHullPresorted(newPoints);\n}\n\n// Returns the convex hull, assuming that each points[i] <= points[i + 1]. Runs in O(n) time.\nfunction getHullPresorted<P extends Point>(points: Readonly<Array<P>>): Array<P> {\n if (points.length <= 1) return points.slice();\n\n const upperHull: Array<P> = [];\n for (let i = 0; i < points.length; i++) {\n const p = points[i]!;\n while (upperHull.length >= 2) {\n const q = upperHull[upperHull.length - 1]!;\n const r = upperHull[upperHull.length - 2]!;\n if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) upperHull.pop();\n else break;\n }\n upperHull.push(p);\n }\n upperHull.pop();\n\n const lowerHull: Array<P> = [];\n for (let i = points.length - 1; i >= 0; i--) {\n const p = points[i]!;\n while (lowerHull.length >= 2) {\n const q = lowerHull[lowerHull.length - 1]!;\n const r = lowerHull[lowerHull.length - 2]!;\n if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) lowerHull.pop();\n else break;\n }\n lowerHull.push(p);\n }\n lowerHull.pop();\n\n if (\n upperHull.length === 1 &&\n lowerHull.length === 1 &&\n upperHull[0]!.x === lowerHull[0]!.x &&\n upperHull[0]!.y === lowerHull[0]!.y\n ) {\n return upperHull;\n } else {\n return upperHull.concat(lowerHull);\n }\n}\n\nconst Provider = TooltipProvider;\nconst Root = Tooltip;\nconst Trigger = TooltipTrigger;\nconst Portal = TooltipPortal;\nconst Content = TooltipContent;\nconst Arrow = TooltipArrow;\n\nexport {\n createTooltipScope,\n //\n TooltipProvider,\n Tooltip,\n TooltipTrigger,\n TooltipPortal,\n TooltipContent,\n TooltipArrow,\n //\n Provider,\n Root,\n Trigger,\n Portal,\n Content,\n Arrow,\n};\nexport type {\n TooltipProviderProps,\n TooltipProps,\n TooltipTriggerProps,\n TooltipPortalProps,\n TooltipContentProps,\n TooltipArrowProps,\n};\n","/* eslint-disable no-restricted-properties */\n\n/* eslint-disable no-restricted-globals */\nexport const canUseDOM = !!(\n typeof window !== 'undefined' &&\n window.document &&\n window.document.createElement\n);\n/* eslint-enable no-restricted-globals */\n\nexport function composeEventHandlers<E extends { defaultPrevented: boolean }>(\n originalEventHandler?: (event: E) => void,\n ourEventHandler?: (event: E) => void,\n { checkForDefaultPrevented = true } = {}\n) {\n return function handleEvent(event: E) {\n originalEventHandler?.(event);\n\n if (checkForDefaultPrevented === false || !event.defaultPrevented) {\n return ourEventHandler?.(event);\n }\n };\n}\n\nexport function getOwnerWindow(element: Node | null | undefined) {\n if (!canUseDOM) {\n throw new Error('Cannot access window outside of the DOM');\n }\n // eslint-disable-next-line no-restricted-globals\n return element?.ownerDocument?.defaultView ?? window;\n}\n\nexport function getOwnerDocument(element: Node | null | undefined) {\n if (!canUseDOM) {\n throw new Error('Cannot access document outside of the DOM');\n }\n // eslint-disable-next-line no-restricted-globals\n return element?.ownerDocument ?? document;\n}\n\n/**\n * Lifted from https://github.com/ariakit/ariakit/blob/main/packages/ariakit-core/src/utils/dom.ts#L37\n * MIT License, Copyright (c) AriaKit.\n */\nexport function getActiveElement(\n node: Node | null | undefined,\n activeDescendant = false\n): HTMLElement | null {\n const { activeElement } = getOwnerDocument(node);\n if (!activeElement?.nodeName) {\n // `activeElement` might be an empty object if we're interacting with elements\n // inside of an iframe.\n return null;\n }\n\n if (isFrame(activeElement) && activeElement.contentDocument) {\n return getActiveElement(activeElement.contentDocument.body, activeDescendant);\n }\n\n if (activeDescendant) {\n const id = activeElement.getAttribute('aria-activedescendant');\n if (id) {\n const element = getOwnerDocument(activeElement).getElementById(id);\n if (element) {\n return element;\n }\n }\n }\n\n return activeElement as HTMLElement | null;\n}\n\nexport function isFrame(element: Element): element is HTMLIFrameElement {\n return element.tagName === 'IFRAME';\n}\n","import * as React from 'react';\n\ntype PossibleRef<T> = React.Ref<T> | undefined;\n\n/**\n * Set a given ref to a given value\n * This utility takes care of different types of refs: callback refs and RefObject(s)\n */\nfunction setRef<T>(ref: PossibleRef<T>, value: T) {\n if (typeof ref === 'function') {\n return ref(value);\n } else if (ref !== null && ref !== undefined) {\n ref.current = value;\n }\n}\n\n/**\n * A utility to compose multiple refs together\n * Accepts callback refs and RefObject(s)\n */\nfunction composeRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {\n return (node) => {\n let hasCleanup = false;\n const cleanups = refs.map((ref) => {\n const cleanup = setRef(ref, node);\n if (!hasCleanup && typeof cleanup == 'function') {\n hasCleanup = true;\n }\n return cleanup;\n });\n\n // React <19 will log an error to the console if a callback ref returns a\n // value. We don't use ref cleanups internally so this will only happen if a\n // user's ref callback returns a value, which we only expect if they are\n // using the cleanup functionality added in React 19.\n if (hasCleanup) {\n return () => {\n for (let i = 0; i < cleanups.length; i++) {\n const cleanup = cleanups[i];\n if (typeof cleanup == 'function') {\n cleanup();\n } else {\n setRef(refs[i], null);\n }\n }\n };\n }\n };\n}\n\n/**\n * A custom hook that composes multiple refs\n * Accepts callback refs and RefObject(s)\n */\nfunction useComposedRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return React.useCallback(composeRefs(...refs), refs);\n}\n\nexport { composeRefs, useComposedRefs };\n","import * as React from 'react';\n\nfunction createContext<ContextValueType extends object | null>(\n rootComponentName: string,\n defaultContext?: ContextValueType\n) {\n const Context = React.createContext<ContextValueType | undefined>(defaultContext);\n\n const Provider: React.FC<ContextValueType & { children: React.ReactNode }> = (props) => {\n const { children, ...context } = props;\n // Only re-memoize when prop values change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const value = React.useMemo(() => context, Object.values(context)) as ContextValueType;\n return <Context.Provider value={value}>{children}</Context.Provider>;\n };\n\n Provider.displayName = rootComponentName + 'Provider';\n\n function useContext(consumerName: string) {\n const context = React.useContext(Context);\n if (context) return context;\n if (defaultContext !== undefined) return defaultContext;\n // if a defaultContext wasn't specified, it's a required context.\n throw new Error(`\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``);\n }\n\n return [Provider, useContext] as const;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * createContextScope\n * -----------------------------------------------------------------------------------------------*/\n\ntype Scope<C = any> = { [scopeName: string]: React.Context<C>[] } | undefined;\ntype ScopeHook = (scope: Scope) => { [__scopeProp: string]: Scope };\ninterface CreateScope {\n scopeName: string;\n (): ScopeHook;\n}\n\nfunction createContextScope(scopeName: string, createContextScopeDeps: CreateScope[] = []) {\n let defaultContexts: any[] = [];\n\n /* -----------------------------------------------------------------------------------------------\n * createContext\n * ---------------------------------------------------------------------------------------------*/\n\n function createContext<ContextValueType extends object | null>(\n rootComponentName: string,\n defaultContext?: ContextValueType\n ) {\n const BaseContext = React.createContext<ContextValueType | undefined>(defaultContext);\n const index = defaultContexts.length;\n defaultContexts = [...defaultContexts, defaultContext];\n\n const Provider: React.FC<\n ContextValueType & { scope: Scope<ContextValueType>; children: React.ReactNode }\n > = (props) => {\n const { scope, children, ...context } = props;\n const Context = scope?.[scopeName]?.[index] || BaseContext;\n // Only re-memoize when prop values change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const value = React.useMemo(() => context, Object.values(context)) as ContextValueType;\n return <Context.Provider value={value}>{children}</Context.Provider>;\n };\n\n Provider.displayName = rootComponentName + 'Provider';\n\n function useContext(consumerName: string, scope: Scope<ContextValueType | undefined>) {\n const Context = scope?.[scopeName]?.[index] || BaseContext;\n const context = React.useContext(Context);\n if (context) return context;\n if (defaultContext !== undefined) return defaultContext;\n // if a defaultContext wasn't specified, it's a required context.\n throw new Error(`\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``);\n }\n\n return [Provider, useContext] as const;\n }\n\n /* -----------------------------------------------------------------------------------------------\n * createScope\n * ---------------------------------------------------------------------------------------------*/\n\n const createScope: CreateScope = () => {\n const scopeContexts = defaultContexts.map((defaultContext) => {\n return React.createContext(defaultContext);\n });\n return function useScope(scope: Scope) {\n const contexts = scope?.[scopeName] || scopeContexts;\n return React.useMemo(\n () => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }),\n [scope, contexts]\n );\n };\n };\n\n createScope.scopeName = scopeName;\n return [createContext, composeContextScopes(createScope, ...createContextScopeDeps)] as const;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * composeContextScopes\n * -----------------------------------------------------------------------------------------------*/\n\nfunction composeContextScopes(...scopes: CreateScope[]) {\n const baseScope = scopes[0];\n if (scopes.length === 1) return baseScope;\n\n const createScope: CreateScope = () => {\n const scopeHooks = scopes.map((createScope) => ({\n useScope: createScope(),\n scopeName: createScope.scopeName,\n }));\n\n return function useComposedScopes(overrideScopes) {\n const nextScopes = scopeHooks.reduce((nextScopes, { useScope, scopeName }) => {\n // We are calling a hook inside a callback which React warns against to avoid inconsistent\n // renders, however, scoping doesn't have render side effects so we ignore the rule.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const scopeProps = useScope(overrideScopes);\n const currentScope = scopeProps[`__scope${scopeName}`];\n return { ...nextScopes, ...currentScope };\n }, {});\n\n return React.useMemo(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }), [nextScopes]);\n };\n };\n\n createScope.scopeName = baseScope.scopeName;\n return createScope;\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n\nexport { createContext, createContextScope };\nexport type { CreateScope, Scope };\n","import * as React from 'react';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { Primitive, dispatchDiscreteCustomEvent } from '@radix-ui/react-primitive';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\nimport { useEscapeKeydown } from '@radix-ui/react-use-escape-keydown';\n\n/* -------------------------------------------------------------------------------------------------\n * DismissableLayer\n * -----------------------------------------------------------------------------------------------*/\n\nconst DISMISSABLE_LAYER_NAME = 'DismissableLayer';\nconst CONTEXT_UPDATE = 'dismissableLayer.update';\nconst POINTER_DOWN_OUTSIDE = 'dismissableLayer.pointerDownOutside';\nconst FOCUS_OUTSIDE = 'dismissableLayer.focusOutside';\n\nlet originalBodyPointerEvents: string;\n\nconst DismissableLayerContext = React.createContext({\n layers: new Set<DismissableLayerElement>(),\n layersWithOutsidePointerEventsDisabled: new Set<DismissableLayerElement>(),\n branches: new Set<DismissableLayerBranchElement>(),\n});\n\ntype DismissableLayerElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface DismissableLayerProps extends PrimitiveDivProps {\n /**\n * When `true`, hover/focus/click interactions will be disabled on elements outside\n * the `DismissableLayer`. Users will need to click twice on outside elements to\n * interact with them: once to close the `DismissableLayer`, and again to trigger the element.\n */\n disableOutsidePointerEvents?: boolean;\n /**\n * Event handler called when the escape key is down.\n * Can be prevented.\n */\n onEscapeKeyDown?: (event: KeyboardEvent) => void;\n /**\n * Event handler called when the a `pointerdown` event happens outside of the `DismissableLayer`.\n * Can be prevented.\n */\n onPointerDownOutside?: (event: PointerDownOutsideEvent) => void;\n /**\n * Event handler called when the focus moves outside of the `DismissableLayer`.\n * Can be prevented.\n */\n onFocusOutside?: (event: FocusOutsideEvent) => void;\n /**\n * Event handler called when an interaction happens outside the `DismissableLayer`.\n * Specifically, when a `pointerdown` event happens outside or focus moves outside of it.\n * Can be prevented.\n */\n onInteractOutside?: (event: PointerDownOutsideEvent | FocusOutsideEvent) => void;\n /**\n * Handler called when the `DismissableLayer` should be dismissed\n */\n onDismiss?: () => void;\n}\n\nconst DismissableLayer = React.forwardRef<DismissableLayerElement, DismissableLayerProps>(\n (props, forwardedRef) => {\n const {\n disableOutsidePointerEvents = false,\n onEscapeKeyDown,\n onPointerDownOutside,\n onFocusOutside,\n onInteractOutside,\n onDismiss,\n ...layerProps\n } = props;\n const context = React.useContext(DismissableLayerContext);\n const [node, setNode] = React.useState<DismissableLayerElement | null>(null);\n const ownerDocument = node?.ownerDocument ?? globalThis?.document;\n const [, force] = React.useState({});\n const composedRefs = useComposedRefs(forwardedRef, (node) => setNode(node));\n const layers = Array.from(context.layers);\n const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1); // prettier-ignore\n const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled!); // prettier-ignore\n const index = node ? layers.indexOf(node) : -1;\n const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;\n const isPointerEventsEnabled = index >= highestLayerWithOutsidePointerEventsDisabledIndex;\n\n const pointerDownOutside = usePointerDownOutside((event) => {\n const target = event.target as HTMLElement;\n const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target));\n if (!isPointerEventsEnabled || isPointerDownOnBranch) return;\n onPointerDownOutside?.(event);\n onInteractOutside?.(event);\n if (!event.defaultPrevented) onDismiss?.();\n }, ownerDocument);\n\n const focusOutside = useFocusOutside((event) => {\n const target = event.target as HTMLElement;\n const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target));\n if (isFocusInBranch) return;\n onFocusOutside?.(event);\n onInteractOutside?.(event);\n if (!event.defaultPrevented) onDismiss?.();\n }, ownerDocument);\n\n useEscapeKeydown((event) => {\n const isHighestLayer = index === context.layers.size - 1;\n if (!isHighestLayer) return;\n onEscapeKeyDown?.(event);\n if (!event.defaultPrevented && onDismiss) {\n event.preventDefault();\n onDismiss();\n }\n }, ownerDocument);\n\n React.useEffect(() => {\n if (!node) return;\n if (disableOutsidePointerEvents) {\n if (context.layersWithOutsidePointerEventsDisabled.size === 0) {\n originalBodyPointerEvents = ownerDocument.body.style.pointerEvents;\n ownerDocument.body.style.pointerEvents = 'none';\n }\n context.layersWithOutsidePointerEventsDisabled.add(node);\n }\n context.layers.add(node);\n dispatchUpdate();\n return () => {\n if (\n disableOutsidePointerEvents &&\n context.layersWithOutsidePointerEventsDisabled.size === 1\n ) {\n ownerDocument.body.style.pointerEvents = originalBodyPointerEvents;\n }\n };\n }, [node, ownerDocument, disableOutsidePointerEvents, context]);\n\n /**\n * We purposefully prevent combining this effect with the `disableOutsidePointerEvents` effect\n * because a change to `disableOutsidePointerEvents` would remove this layer from the stack\n * and add it to the end again so the layering order wouldn't be _creation order_.\n * We only want them to be removed from context stacks when unmounted.\n */\n React.useEffect(() => {\n return () => {\n if (!node) return;\n context.layers.delete(node);\n context.layersWithOutsidePointerEventsDisabled.delete(node);\n dispatchUpdate();\n };\n }, [node, context]);\n\n React.useEffect(() => {\n const handleUpdate = () => force({});\n document.addEventListener(CONTEXT_UPDATE, handleUpdate);\n return () => document.removeEventListener(CONTEXT_UPDATE, handleUpdate);\n }, []);\n\n return (\n <Primitive.div\n {...layerProps}\n ref={composedRefs}\n style={{\n pointerEvents: isBodyPointerEventsDisabled\n ? isPointerEventsEnabled\n ? 'auto'\n : 'none'\n : undefined,\n ...props.style,\n }}\n onFocusCapture={composeEventHandlers(props.onFocusCapture, focusOutside.onFocusCapture)}\n onBlurCapture={composeEventHandlers(props.onBlurCapture, focusOutside.onBlurCapture)}\n onPointerDownCapture={composeEventHandlers(\n props.onPointerDownCapture,\n pointerDownOutside.onPointerDownCapture\n )}\n />\n );\n }\n);\n\nDismissableLayer.displayName = DISMISSABLE_LAYER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * DismissableLayerBranch\n * -----------------------------------------------------------------------------------------------*/\n\nconst BRANCH_NAME = 'DismissableLayerBranch';\n\ntype DismissableLayerBranchElement = React.ComponentRef<typeof Primitive.div>;\ninterface DismissableLayerBranchProps extends PrimitiveDivProps {}\n\nconst DismissableLayerBranch = React.forwardRef<\n DismissableLayerBranchElement,\n DismissableLayerBranchProps\n>((props, forwardedRef) => {\n const context = React.useContext(DismissableLayerContext);\n const ref = React.useRef<DismissableLayerBranchElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n\n React.useEffect(() => {\n const node = ref.current;\n if (node) {\n context.branches.add(node);\n return () => {\n context.branches.delete(node);\n };\n }\n }, [context.branches]);\n\n return <Primitive.div {...props} ref={composedRefs} />;\n});\n\nDismissableLayerBranch.displayName = BRANCH_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype PointerDownOutsideEvent = CustomEvent<{ originalEvent: PointerEvent }>;\ntype FocusOutsideEvent = CustomEvent<{ originalEvent: FocusEvent }>;\n\n/**\n * Listens for `pointerdown` outside a react subtree. We use `pointerdown` rather than `pointerup`\n * to mimic layer dismissing behaviour present in OS.\n * Returns props to pass to the node we want to check for outside events.\n */\nfunction usePointerDownOutside(\n onPointerDownOutside?: (event: PointerDownOutsideEvent) => void,\n ownerDocument: Document = globalThis?.document\n) {\n const handlePointerDownOutside = useCallbackRef(onPointerDownOutside) as EventListener;\n const isPointerInsideReactTreeRef = React.useRef(false);\n const handleClickRef = React.useRef(() => {});\n\n React.useEffect(() => {\n const handlePointerDown = (event: PointerEvent) => {\n if (event.target && !isPointerInsideReactTreeRef.current) {\n const eventDetail = { originalEvent: event };\n\n function handleAndDispatchPointerDownOutsideEvent() {\n handleAndDispatchCustomEvent(\n POINTER_DOWN_OUTSIDE,\n handlePointerDownOutside,\n eventDetail,\n { discrete: true }\n );\n }\n\n /**\n * On touch devices, we need to wait for a click event because browsers implement\n * a ~350ms delay between the time the user stops touching the display and when the\n * browser executres events. We need to ensure we don't reactivate pointer-events within\n * this timeframe otherwise the browser may execute events that should have been prevented.\n *\n * Additionally, this also lets us deal automatically with cancellations when a click event\n * isn't raised because the page was considered scrolled/drag-scrolled, long-pressed, etc.\n *\n * This is why we also continuously remove the previous listener, because we cannot be\n * certain that it was raised, and therefore cleaned-up.\n */\n if (event.pointerType === 'touch') {\n ownerDocument.removeEventListener('click', handleClickRef.current);\n handleClickRef.current = handleAndDispatchPointerDownOutsideEvent;\n ownerDocument.addEventListener('click', handleClickRef.current, { once: true });\n } else {\n handleAndDispatchPointerDownOutsideEvent();\n }\n } else {\n // We need to remove the event listener in case the outside click has been canceled.\n // See: https://github.com/radix-ui/primitives/issues/2171\n ownerDocument.removeEventListener('click', handleClickRef.current);\n }\n isPointerInsideReactTreeRef.current = false;\n };\n /**\n * if this hook executes in a component that mounts via a `pointerdown` event, the event\n * would bubble up to the document and trigger a `pointerDownOutside` event. We avoid\n * this by delaying the event listener registration on the document.\n * This is not React specific, but rather how the DOM works, ie:\n * ```\n * button.addEventListener('pointerdown', () => {\n * console.log('I will log');\n * document.addEventListener('pointerdown', () => {\n * console.log('I will also log');\n * })\n * });\n */\n const timerId = window.setTimeout(() => {\n ownerDocument.addEventListener('pointerdown', handlePointerDown);\n }, 0);\n return () => {\n window.clearTimeout(timerId);\n ownerDocument.removeEventListener('pointerdown', handlePointerDown);\n ownerDocument.removeEventListener('click', handleClickRef.current);\n };\n }, [ownerDocument, handlePointerDownOutside]);\n\n return {\n // ensures we check React component tree (not just DOM tree)\n onPointerDownCapture: () => (isPointerInsideReactTreeRef.current = true),\n };\n}\n\n/**\n * Listens for when focus happens outside a react subtree.\n * Returns props to pass to the root (node) of the subtree we want to check.\n */\nfunction useFocusOutside(\n onFocusOutside?: (event: FocusOutsideEvent) => void,\n ownerDocument: Document = globalThis?.document\n) {\n const handleFocusOutside = useCallbackRef(onFocusOutside) as EventListener;\n const isFocusInsideReactTreeRef = React.useRef(false);\n\n React.useEffect(() => {\n const handleFocus = (event: FocusEvent) => {\n if (event.target && !isFocusInsideReactTreeRef.current) {\n const eventDetail = { originalEvent: event };\n handleAndDispatchCustomEvent(FOCUS_OUTSIDE, handleFocusOutside, eventDetail, {\n discrete: false,\n });\n }\n };\n ownerDocument.addEventListener('focusin', handleFocus);\n return () => ownerDocument.removeEventListener('focusin', handleFocus);\n }, [ownerDocument, handleFocusOutside]);\n\n return {\n onFocusCapture: () => (isFocusInsideReactTreeRef.current = true),\n onBlurCapture: () => (isFocusInsideReactTreeRef.current = false),\n };\n}\n\nfunction dispatchUpdate() {\n const event = new CustomEvent(CONTEXT_UPDATE);\n document.dispatchEvent(event);\n}\n\nfunction handleAndDispatchCustomEvent<E extends CustomEvent, OriginalEvent extends Event>(\n name: string,\n handler: ((event: E) => void) | undefined,\n detail: { originalEvent: OriginalEvent } & (E extends CustomEvent<infer D> ? D : never),\n { discrete }: { discrete: boolean }\n) {\n const target = detail.originalEvent.target;\n const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail });\n if (handler) target.addEventListener(name, handler as EventListener, { once: true });\n\n if (discrete) {\n dispatchDiscreteCustomEvent(target, event);\n } else {\n target.dispatchEvent(event);\n }\n}\n\nconst Root = DismissableLayer;\nconst Branch = DismissableLayerBranch;\n\nexport {\n DismissableLayer,\n DismissableLayerBranch,\n //\n Root,\n Branch,\n};\nexport type { DismissableLayerProps };\n","import * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport { createSlot } from '@radix-ui/react-slot';\n\nconst NODES = [\n 'a',\n 'button',\n 'div',\n 'form',\n 'h2',\n 'h3',\n 'img',\n 'input',\n 'label',\n 'li',\n 'nav',\n 'ol',\n 'p',\n 'select',\n 'span',\n 'svg',\n 'ul',\n] as const;\n\ntype Primitives = { [E in (typeof NODES)[number]]: PrimitiveForwardRefComponent<E> };\ntype PrimitivePropsWithRef<E extends React.ElementType> = React.ComponentPropsWithRef<E> & {\n asChild?: boolean;\n};\n\ninterface PrimitiveForwardRefComponent<E extends React.ElementType>\n extends React.ForwardRefExoticComponent<PrimitivePropsWithRef<E>> {}\n\n/* -------------------------------------------------------------------------------------------------\n * Primitive\n * -----------------------------------------------------------------------------------------------*/\n\nconst Primitive = NODES.reduce((primitive, node) => {\n const Slot = createSlot(`Primitive.${node}`);\n const Node = React.forwardRef((props: PrimitivePropsWithRef<typeof node>, forwardedRef: any) => {\n const { asChild, ...primitiveProps } = props;\n const Comp: any = asChild ? Slot : node;\n\n if (typeof window !== 'undefined') {\n (window as any)[Symbol.for('radix-ui')] = true;\n }\n\n return <Comp {...primitiveProps} ref={forwardedRef} />;\n });\n\n Node.displayName = `Primitive.${node}`;\n\n return { ...primitive, [node]: Node };\n}, {} as Primitives);\n\n/* -------------------------------------------------------------------------------------------------\n * Utils\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * Flush custom event dispatch\n * https://github.com/radix-ui/primitives/pull/1378\n *\n * React batches *all* event handlers since version 18, this introduces certain considerations when using custom event types.\n *\n * Internally, React prioritises events in the following order:\n * - discrete\n * - continuous\n * - default\n *\n * https://github.com/facebook/react/blob/a8a4742f1c54493df00da648a3f9d26e3db9c8b5/packages/react-dom/src/events/ReactDOMEventListener.js#L294-L350\n *\n * `discrete` is an important distinction as updates within these events are applied immediately.\n * React however, is not able to infer the priority of custom event types due to how they are detected internally.\n * Because of this, it's possible for updates from custom events to be unexpectedly batched when\n * dispatched by another `discrete` event.\n *\n * In order to ensure that updates from custom events are applied predictably, we need to manually flush the batch.\n * This utility should be used when dispatching a custom event from within another `discrete` event, this utility\n * is not necessary when dispatching known event types, or if dispatching a custom type inside a non-discrete event.\n * For example:\n *\n * dispatching a known click 👎\n * target.dispatchEvent(new Event(‘click’))\n *\n * dispatching a custom type within a non-discrete event 👎\n * onScroll={(event) => event.target.dispatchEvent(new CustomEvent(‘customType’))}\n *\n * dispatching a custom type within a `discrete` event 👍\n * onPointerDown={(event) => dispatchDiscreteCustomEvent(event.target, new CustomEvent(‘customType’))}\n *\n * Note: though React classifies `focus`, `focusin` and `focusout` events as `discrete`, it's not recommended to use\n * this utility with them. This is because it's possible for those handlers to be called implicitly during render\n * e.g. when focus is within a component as it is unmounted, or when managing focus on mount.\n */\n\nfunction dispatchDiscreteCustomEvent<E extends CustomEvent>(target: E['target'], event: E) {\n if (target) ReactDOM.flushSync(() => target.dispatchEvent(event));\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = Primitive;\n\nexport {\n Primitive,\n //\n Root,\n //\n dispatchDiscreteCustomEvent,\n};\nexport type { PrimitivePropsWithRef };\n","import * as React from 'react';\nimport { composeRefs } from '@radix-ui/react-compose-refs';\n\n/* -------------------------------------------------------------------------------------------------\n * Slot\n * -----------------------------------------------------------------------------------------------*/\n\ninterface SlotProps extends React.HTMLAttributes<HTMLElement> {\n children?: React.ReactNode;\n}\n\n/* @__NO_SIDE_EFFECTS__ */ export function createSlot(ownerName: string) {\n const SlotClone = createSlotClone(ownerName);\n const Slot = React.forwardRef<HTMLElement, SlotProps>((props, forwardedRef) => {\n const { children, ...slotProps } = props;\n const childrenArray = React.Children.toArray(children);\n const slottable = childrenArray.find(isSlottable);\n\n if (slottable) {\n // the new element to render is the one passed as a child of `Slottable`\n const newElement = slottable.props.children;\n\n const newChildren = childrenArray.map((child) => {\n if (child === slottable) {\n // because the new element will be the one rendered, we are only interested\n // in grabbing its children (`newElement.props.children`)\n if (React.Children.count(newElement) > 1) return React.Children.only(null);\n return React.isValidElement(newElement)\n ? (newElement.props as { children: React.ReactNode }).children\n : null;\n } else {\n return child;\n }\n });\n\n return (\n <SlotClone {...slotProps} ref={forwardedRef}>\n {React.isValidElement(newElement)\n ? React.cloneElement(newElement, undefined, newChildren)\n : null}\n </SlotClone>\n );\n }\n\n return (\n <SlotClone {...slotProps} ref={forwardedRef}>\n {children}\n </SlotClone>\n );\n });\n\n Slot.displayName = `${ownerName}.Slot`;\n return Slot;\n}\n\nconst Slot = createSlot('Slot');\n\n/* -------------------------------------------------------------------------------------------------\n * SlotClone\n * -----------------------------------------------------------------------------------------------*/\n\ninterface SlotCloneProps {\n children: React.ReactNode;\n}\n\n/* @__NO_SIDE_EFFECTS__ */ function createSlotClone(ownerName: string) {\n const SlotClone = React.forwardRef<any, SlotCloneProps>((props, forwardedRef) => {\n const { children, ...slotProps } = props;\n\n if (React.isValidElement(children)) {\n const childrenRef = getElementRef(children);\n const props = mergeProps(slotProps, children.props as AnyProps);\n // do not pass ref to React.Fragment for React 19 compatibility\n if (children.type !== React.Fragment) {\n props.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;\n }\n return React.cloneElement(children, props);\n }\n\n return React.Children.count(children) > 1 ? React.Children.only(null) : null;\n });\n\n SlotClone.displayName = `${ownerName}.SlotClone`;\n return SlotClone;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Slottable\n * -----------------------------------------------------------------------------------------------*/\n\nconst SLOTTABLE_IDENTIFIER = Symbol('radix.slottable');\n\ninterface SlottableProps {\n children: React.ReactNode;\n}\n\ninterface SlottableComponent extends React.FC<SlottableProps> {\n __radixId: symbol;\n}\n\n/* @__NO_SIDE_EFFECTS__ */ export function createSlottable(ownerName: string) {\n const Slottable: SlottableComponent = ({ children }) => {\n return <>{children}</>;\n };\n Slottable.displayName = `${ownerName}.Slottable`;\n Slottable.__radixId = SLOTTABLE_IDENTIFIER;\n return Slottable;\n}\n\nconst Slottable = createSlottable('Slottable');\n\n/* ---------------------------------------------------------------------------------------------- */\n\ntype AnyProps = Record<string, any>;\n\nfunction isSlottable(\n child: React.ReactNode\n): child is React.ReactElement<SlottableProps, typeof Slottable> {\n return (\n React.isValidElement(child) &&\n typeof child.type === 'function' &&\n '__radixId' in child.type &&\n child.type.__radixId === SLOTTABLE_IDENTIFIER\n );\n}\n\nfunction mergeProps(slotProps: AnyProps, childProps: AnyProps) {\n // all child props should override\n const overrideProps = { ...childProps };\n\n for (const propName in childProps) {\n const slotPropValue = slotProps[propName];\n const childPropValue = childProps[propName];\n\n const isHandler = /^on[A-Z]/.test(propName);\n if (isHandler) {\n // if the handler exists on both, we compose them\n if (slotPropValue && childPropValue) {\n overrideProps[propName] = (...args: unknown[]) => {\n const result = childPropValue(...args);\n slotPropValue(...args);\n return result;\n };\n }\n // but if it exists only on the slot, we use only this one\n else if (slotPropValue) {\n overrideProps[propName] = slotPropValue;\n }\n }\n // if it's `style`, we merge them\n else if (propName === 'style') {\n overrideProps[propName] = { ...slotPropValue, ...childPropValue };\n } else if (propName === 'className') {\n overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(' ');\n }\n }\n\n return { ...slotProps, ...overrideProps };\n}\n\n// Before React 19 accessing `element.props.ref` will throw a warning and suggest using `element.ref`\n// After React 19 accessing `element.ref` does the opposite.\n// https://github.com/facebook/react/pull/28348\n//\n// Access the ref using the method that doesn't yield a warning.\nfunction getElementRef(element: React.ReactElement) {\n // React <=18 in DEV\n let getter = Object.getOwnPropertyDescriptor(element.props, 'ref')?.get;\n let mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return (element as any).ref;\n }\n\n // React 19 in DEV\n getter = Object.getOwnPropertyDescriptor(element, 'ref')?.get;\n mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return (element.props as { ref?: React.Ref<unknown> }).ref;\n }\n\n // Not DEV\n return (element.props as { ref?: React.Ref<unknown> }).ref || (element as any).ref;\n}\n\nexport {\n Slot,\n Slottable,\n //\n Slot as Root,\n};\nexport type { SlotProps };\n","import * as React from 'react';\n\n/**\n * A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a\n * prop or avoid re-executing effects when passed as a dependency\n */\nfunction useCallbackRef<T extends (...args: any[]) => any>(callback: T | undefined): T {\n const callbackRef = React.useRef(callback);\n\n React.useEffect(() => {\n callbackRef.current = callback;\n });\n\n // https://github.com/facebook/react/issues/19240\n return React.useMemo(() => ((...args) => callbackRef.current?.(...args)) as T, []);\n}\n\nexport { useCallbackRef };\n","import * as React from 'react';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\n\n/**\n * Listens for when the escape key is down\n */\nfunction useEscapeKeydown(\n onEscapeKeyDownProp?: (event: KeyboardEvent) => void,\n ownerDocument: Document = globalThis?.document\n) {\n const onEscapeKeyDown = useCallbackRef(onEscapeKeyDownProp);\n\n React.useEffect(() => {\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n onEscapeKeyDown(event);\n }\n };\n ownerDocument.addEventListener('keydown', handleKeyDown, { capture: true });\n return () => ownerDocument.removeEventListener('keydown', handleKeyDown, { capture: true });\n }, [onEscapeKeyDown, ownerDocument]);\n}\n\nexport { useEscapeKeydown };\n","import * as React from 'react';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\n\n// We spaces with `.trim().toString()` to prevent bundlers from trying to `import { useId } from 'react';`\nconst useReactId = (React as any)[' useId '.trim().toString()] || (() => undefined);\nlet count = 0;\n\nfunction useId(deterministicId?: string): string {\n const [id, setId] = React.useState<string | undefined>(useReactId());\n // React versions older than 18 will have client-side ids only.\n useLayoutEffect(() => {\n if (!deterministicId) setId((reactId) => reactId ?? String(count++));\n }, [deterministicId]);\n return deterministicId || (id ? `radix-${id}` : '');\n}\n\nexport { useId };\n","import * as React from 'react';\n\n/**\n * On the server, React emits a warning when calling `useLayoutEffect`.\n * This is because neither `useLayoutEffect` nor `useEffect` run on the server.\n * We use this safe version which suppresses the warning by replacing it with a noop on the server.\n *\n * See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect\n */\nconst useLayoutEffect = globalThis?.document ? React.useLayoutEffect : () => {};\n\nexport { useLayoutEffect };\n","import * as React from 'react';\nimport {\n useFloating,\n autoUpdate,\n offset,\n shift,\n limitShift,\n hide,\n arrow as floatingUIarrow,\n flip,\n size,\n} from '@floating-ui/react-dom';\nimport * as ArrowPrimitive from '@radix-ui/react-arrow';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\nimport { useSize } from '@radix-ui/react-use-size';\n\nimport type { Placement, Middleware } from '@floating-ui/react-dom';\nimport type { Scope } from '@radix-ui/react-context';\nimport type { Measurable } from '@radix-ui/rect';\n\nconst SIDE_OPTIONS = ['top', 'right', 'bottom', 'left'] as const;\nconst ALIGN_OPTIONS = ['start', 'center', 'end'] as const;\n\ntype Side = (typeof SIDE_OPTIONS)[number];\ntype Align = (typeof ALIGN_OPTIONS)[number];\n\n/* -------------------------------------------------------------------------------------------------\n * Popper\n * -----------------------------------------------------------------------------------------------*/\n\nconst POPPER_NAME = 'Popper';\n\ntype ScopedProps<P> = P & { __scopePopper?: Scope };\nconst [createPopperContext, createPopperScope] = createContextScope(POPPER_NAME);\n\ntype PopperContextValue = {\n anchor: Measurable | null;\n onAnchorChange(anchor: Measurable | null): void;\n};\nconst [PopperProvider, usePopperContext] = createPopperContext<PopperContextValue>(POPPER_NAME);\n\ninterface PopperProps {\n children?: React.ReactNode;\n}\nconst Popper: React.FC<PopperProps> = (props: ScopedProps<PopperProps>) => {\n const { __scopePopper, children } = props;\n const [anchor, setAnchor] = React.useState<Measurable | null>(null);\n return (\n <PopperProvider scope={__scopePopper} anchor={anchor} onAnchorChange={setAnchor}>\n {children}\n </PopperProvider>\n );\n};\n\nPopper.displayName = POPPER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopperAnchor\n * -----------------------------------------------------------------------------------------------*/\n\nconst ANCHOR_NAME = 'PopperAnchor';\n\ntype PopperAnchorElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface PopperAnchorProps extends PrimitiveDivProps {\n virtualRef?: React.RefObject<Measurable>;\n}\n\nconst PopperAnchor = React.forwardRef<PopperAnchorElement, PopperAnchorProps>(\n (props: ScopedProps<PopperAnchorProps>, forwardedRef) => {\n const { __scopePopper, virtualRef, ...anchorProps } = props;\n const context = usePopperContext(ANCHOR_NAME, __scopePopper);\n const ref = React.useRef<PopperAnchorElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n\n const anchorRef = React.useRef<Measurable | null>(null);\n React.useEffect(() => {\n const previousAnchor = anchorRef.current;\n anchorRef.current = virtualRef?.current || ref.current;\n if (previousAnchor !== anchorRef.current) {\n // Consumer can anchor the popper to something that isn't\n // a DOM node e.g. pointer position, so we override the\n // `anchorRef` with their virtual ref in this case.\n context.onAnchorChange(anchorRef.current);\n }\n });\n\n return virtualRef ? null : <Primitive.div {...anchorProps} ref={composedRefs} />;\n }\n);\n\nPopperAnchor.displayName = ANCHOR_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopperContent\n * -----------------------------------------------------------------------------------------------*/\n\nconst CONTENT_NAME = 'PopperContent';\n\ntype PopperContentContextValue = {\n placedSide: Side;\n onArrowChange(arrow: HTMLSpanElement | null): void;\n arrowX?: number;\n arrowY?: number;\n shouldHideArrow: boolean;\n};\n\nconst [PopperContentProvider, useContentContext] =\n createPopperContext<PopperContentContextValue>(CONTENT_NAME);\n\ntype Boundary = Element | null;\n\ntype PopperContentElement = React.ComponentRef<typeof Primitive.div>;\ninterface PopperContentProps extends PrimitiveDivProps {\n side?: Side;\n sideOffset?: number;\n align?: Align;\n alignOffset?: number;\n arrowPadding?: number;\n avoidCollisions?: boolean;\n collisionBoundary?: Boundary | Boundary[];\n collisionPadding?: number | Partial<Record<Side, number>>;\n sticky?: 'partial' | 'always';\n hideWhenDetached?: boolean;\n updatePositionStrategy?: 'optimized' | 'always';\n onPlaced?: () => void;\n}\n\nconst PopperContent = React.forwardRef<PopperContentElement, PopperContentProps>(\n (props: ScopedProps<PopperContentProps>, forwardedRef) => {\n const {\n __scopePopper,\n side = 'bottom',\n sideOffset = 0,\n align = 'center',\n alignOffset = 0,\n arrowPadding = 0,\n avoidCollisions = true,\n collisionBoundary = [],\n collisionPadding: collisionPaddingProp = 0,\n sticky = 'partial',\n hideWhenDetached = false,\n updatePositionStrategy = 'optimized',\n onPlaced,\n ...contentProps\n } = props;\n\n const context = usePopperContext(CONTENT_NAME, __scopePopper);\n\n const [content, setContent] = React.useState<HTMLDivElement | null>(null);\n const composedRefs = useComposedRefs(forwardedRef, (node) => setContent(node));\n\n const [arrow, setArrow] = React.useState<HTMLSpanElement | null>(null);\n const arrowSize = useSize(arrow);\n const arrowWidth = arrowSize?.width ?? 0;\n const arrowHeight = arrowSize?.height ?? 0;\n\n const desiredPlacement = (side + (align !== 'center' ? '-' + align : '')) as Placement;\n\n const collisionPadding =\n typeof collisionPaddingProp === 'number'\n ? collisionPaddingProp\n : { top: 0, right: 0, bottom: 0, left: 0, ...collisionPaddingProp };\n\n const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary];\n const hasExplicitBoundaries = boundary.length > 0;\n\n const detectOverflowOptions = {\n padding: collisionPadding,\n boundary: boundary.filter(isNotNull),\n // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries\n altBoundary: hasExplicitBoundaries,\n };\n\n const { refs, floatingStyles, placement, isPositioned, middlewareData } = useFloating({\n // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues\n strategy: 'fixed',\n placement: desiredPlacement,\n whileElementsMounted: (...args) => {\n const cleanup = autoUpdate(...args, {\n animationFrame: updatePositionStrategy === 'always',\n });\n return cleanup;\n },\n elements: {\n reference: context.anchor,\n },\n middleware: [\n offset({ mainAxis: sideOffset + arrowHeight, alignmentAxis: alignOffset }),\n avoidCollisions &&\n shift({\n mainAxis: true,\n crossAxis: false,\n limiter: sticky === 'partial' ? limitShift() : undefined,\n ...detectOverflowOptions,\n }),\n avoidCollisions && flip({ ...detectOverflowOptions }),\n size({\n ...detectOverflowOptions,\n apply: ({ elements, rects, availableWidth, availableHeight }) => {\n const { width: anchorWidth, height: anchorHeight } = rects.reference;\n const contentStyle = elements.floating.style;\n contentStyle.setProperty('--radix-popper-available-width', `${availableWidth}px`);\n contentStyle.setProperty('--radix-popper-available-height', `${availableHeight}px`);\n contentStyle.setProperty('--radix-popper-anchor-width', `${anchorWidth}px`);\n contentStyle.setProperty('--radix-popper-anchor-height', `${anchorHeight}px`);\n },\n }),\n arrow && floatingUIarrow({ element: arrow, padding: arrowPadding }),\n transformOrigin({ arrowWidth, arrowHeight }),\n hideWhenDetached && hide({ strategy: 'referenceHidden', ...detectOverflowOptions }),\n ],\n });\n\n const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement);\n\n const handlePlaced = useCallbackRef(onPlaced);\n useLayoutEffect(() => {\n if (isPositioned) {\n handlePlaced?.();\n }\n }, [isPositioned, handlePlaced]);\n\n const arrowX = middlewareData.arrow?.x;\n const arrowY = middlewareData.arrow?.y;\n const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;\n\n const [contentZIndex, setContentZIndex] = React.useState<string>();\n useLayoutEffect(() => {\n if (content) setContentZIndex(window.getComputedStyle(content).zIndex);\n }, [content]);\n\n return (\n <div\n ref={refs.setFloating}\n data-radix-popper-content-wrapper=\"\"\n style={{\n ...floatingStyles,\n transform: isPositioned ? floatingStyles.transform : 'translate(0, -200%)', // keep off the page when measuring\n minWidth: 'max-content',\n zIndex: contentZIndex,\n ['--radix-popper-transform-origin' as any]: [\n middlewareData.transformOrigin?.x,\n middlewareData.transformOrigin?.y,\n ].join(' '),\n\n // hide the content if using the hide middleware and should be hidden\n // set visibility to hidden and disable pointer events so the UI behaves\n // as if the PopperContent isn't there at all\n ...(middlewareData.hide?.referenceHidden && {\n visibility: 'hidden',\n pointerEvents: 'none',\n }),\n }}\n // Floating UI interally calculates logical alignment based the `dir` attribute on\n // the reference/floating node, we must add this attribute here to ensure\n // this is calculated when portalled as well as inline.\n dir={props.dir}\n >\n <PopperContentProvider\n scope={__scopePopper}\n placedSide={placedSide}\n onArrowChange={setArrow}\n arrowX={arrowX}\n arrowY={arrowY}\n shouldHideArrow={cannotCenterArrow}\n >\n <Primitive.div\n data-side={placedSide}\n data-align={placedAlign}\n {...contentProps}\n ref={composedRefs}\n style={{\n ...contentProps.style,\n // if the PopperContent hasn't been placed yet (not all measurements done)\n // we prevent animations so that users's animation don't kick in too early referring wrong sides\n animation: !isPositioned ? 'none' : undefined,\n }}\n />\n </PopperContentProvider>\n </div>\n );\n }\n);\n\nPopperContent.displayName = CONTENT_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopperArrow\n * -----------------------------------------------------------------------------------------------*/\n\nconst ARROW_NAME = 'PopperArrow';\n\nconst OPPOSITE_SIDE: Record<Side, Side> = {\n top: 'bottom',\n right: 'left',\n bottom: 'top',\n left: 'right',\n};\n\ntype PopperArrowElement = React.ComponentRef<typeof ArrowPrimitive.Root>;\ntype ArrowProps = React.ComponentPropsWithoutRef<typeof ArrowPrimitive.Root>;\ninterface PopperArrowProps extends ArrowProps {}\n\nconst PopperArrow = React.forwardRef<PopperArrowElement, PopperArrowProps>(function PopperArrow(\n props: ScopedProps<PopperArrowProps>,\n forwardedRef\n) {\n const { __scopePopper, ...arrowProps } = props;\n const contentContext = useContentContext(ARROW_NAME, __scopePopper);\n const baseSide = OPPOSITE_SIDE[contentContext.placedSide];\n\n return (\n // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`)\n // doesn't report size as we'd expect on SVG elements.\n // it reports their bounding box which is effectively the largest path inside the SVG.\n <span\n ref={contentContext.onArrowChange}\n style={{\n position: 'absolute',\n left: contentContext.arrowX,\n top: contentContext.arrowY,\n [baseSide]: 0,\n transformOrigin: {\n top: '',\n right: '0 0',\n bottom: 'center 0',\n left: '100% 0',\n }[contentContext.placedSide],\n transform: {\n top: 'translateY(100%)',\n right: 'translateY(50%) rotate(90deg) translateX(-50%)',\n bottom: `rotate(180deg)`,\n left: 'translateY(50%) rotate(-90deg) translateX(50%)',\n }[contentContext.placedSide],\n visibility: contentContext.shouldHideArrow ? 'hidden' : undefined,\n }}\n >\n <ArrowPrimitive.Root\n {...arrowProps}\n ref={forwardedRef}\n style={{\n ...arrowProps.style,\n // ensures the element can be measured correctly (mostly for if SVG)\n display: 'block',\n }}\n />\n </span>\n );\n});\n\nPopperArrow.displayName = ARROW_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nfunction isNotNull<T>(value: T | null): value is T {\n return value !== null;\n}\n\nconst transformOrigin = (options: { arrowWidth: number; arrowHeight: number }): Middleware => ({\n name: 'transformOrigin',\n options,\n fn(data) {\n const { placement, rects, middlewareData } = data;\n\n const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;\n const isArrowHidden = cannotCenterArrow;\n const arrowWidth = isArrowHidden ? 0 : options.arrowWidth;\n const arrowHeight = isArrowHidden ? 0 : options.arrowHeight;\n\n const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement);\n const noArrowAlign = { start: '0%', center: '50%', end: '100%' }[placedAlign];\n\n const arrowXCenter = (middlewareData.arrow?.x ?? 0) + arrowWidth / 2;\n const arrowYCenter = (middlewareData.arrow?.y ?? 0) + arrowHeight / 2;\n\n let x = '';\n let y = '';\n\n if (placedSide === 'bottom') {\n x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;\n y = `${-arrowHeight}px`;\n } else if (placedSide === 'top') {\n x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;\n y = `${rects.floating.height + arrowHeight}px`;\n } else if (placedSide === 'right') {\n x = `${-arrowHeight}px`;\n y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;\n } else if (placedSide === 'left') {\n x = `${rects.floating.width + arrowHeight}px`;\n y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;\n }\n return { data: { x, y } };\n },\n});\n\nfunction getSideAndAlignFromPlacement(placement: Placement) {\n const [side, align = 'center'] = placement.split('-');\n return [side as Side, align as Align] as const;\n}\n\nconst Root = Popper;\nconst Anchor = PopperAnchor;\nconst Content = PopperContent;\nconst Arrow = PopperArrow;\n\nexport {\n createPopperScope,\n //\n Popper,\n PopperAnchor,\n PopperContent,\n PopperArrow,\n //\n Root,\n Anchor,\n Content,\n Arrow,\n //\n SIDE_OPTIONS,\n ALIGN_OPTIONS,\n};\nexport type { PopperProps, PopperAnchorProps, PopperContentProps, PopperArrowProps };\n","/**\n * Custom positioning reference element.\n * @see https://floating-ui.com/docs/virtual-elements\n */\n\nconst sides = ['top', 'right', 'bottom', 'left'];\nconst alignments = ['start', 'end'];\nconst placements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + \"-\" + alignments[0], side + \"-\" + alignments[1]), []);\nconst min = Math.min;\nconst max = Math.max;\nconst round = Math.round;\nconst floor = Math.floor;\nconst createCoords = v => ({\n x: v,\n y: v\n});\nconst oppositeSideMap = {\n left: 'right',\n right: 'left',\n bottom: 'top',\n top: 'bottom'\n};\nfunction clamp(start, value, end) {\n return max(start, min(value, end));\n}\nfunction evaluate(value, param) {\n return typeof value === 'function' ? value(param) : value;\n}\nfunction getSide(placement) {\n return placement.split('-')[0];\n}\nfunction getAlignment(placement) {\n return placement.split('-')[1];\n}\nfunction getOppositeAxis(axis) {\n return axis === 'x' ? 'y' : 'x';\n}\nfunction getAxisLength(axis) {\n return axis === 'y' ? 'height' : 'width';\n}\nfunction getSideAxis(placement) {\n const firstChar = placement[0];\n return firstChar === 't' || firstChar === 'b' ? 'y' : 'x';\n}\nfunction getAlignmentAxis(placement) {\n return getOppositeAxis(getSideAxis(placement));\n}\nfunction getAlignmentSides(placement, rects, rtl) {\n if (rtl === void 0) {\n rtl = false;\n }\n const alignment = getAlignment(placement);\n const alignmentAxis = getAlignmentAxis(placement);\n const length = getAxisLength(alignmentAxis);\n let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';\n if (rects.reference[length] > rects.floating[length]) {\n mainAlignmentSide = getOppositePlacement(mainAlignmentSide);\n }\n return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];\n}\nfunction getExpandedPlacements(placement) {\n const oppositePlacement = getOppositePlacement(placement);\n return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];\n}\nfunction getOppositeAlignmentPlacement(placement) {\n return placement.includes('start') ? placement.replace('start', 'end') : placement.replace('end', 'start');\n}\nconst lrPlacement = ['left', 'right'];\nconst rlPlacement = ['right', 'left'];\nconst tbPlacement = ['top', 'bottom'];\nconst btPlacement = ['bottom', 'top'];\nfunction getSideList(side, isStart, rtl) {\n switch (side) {\n case 'top':\n case 'bottom':\n if (rtl) return isStart ? rlPlacement : lrPlacement;\n return isStart ? lrPlacement : rlPlacement;\n case 'left':\n case 'right':\n return isStart ? tbPlacement : btPlacement;\n default:\n return [];\n }\n}\nfunction getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {\n const alignment = getAlignment(placement);\n let list = getSideList(getSide(placement), direction === 'start', rtl);\n if (alignment) {\n list = list.map(side => side + \"-\" + alignment);\n if (flipAlignment) {\n list = list.concat(list.map(getOppositeAlignmentPlacement));\n }\n }\n return list;\n}\nfunction getOppositePlacement(placement) {\n const side = getSide(placement);\n return oppositeSideMap[side] + placement.slice(side.length);\n}\nfunction expandPaddingObject(padding) {\n return {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n ...padding\n };\n}\nfunction getPaddingObject(padding) {\n return typeof padding !== 'number' ? expandPaddingObject(padding) : {\n top: padding,\n right: padding,\n bottom: padding,\n left: padding\n };\n}\nfunction rectToClientRect(rect) {\n const {\n x,\n y,\n width,\n height\n } = rect;\n return {\n width,\n height,\n top: y,\n left: x,\n right: x + width,\n bottom: y + height,\n x,\n y\n };\n}\n\nexport { alignments, clamp, createCoords, evaluate, expandPaddingObject, floor, getAlignment, getAlignmentAxis, getAlignmentSides, getAxisLength, getExpandedPlacements, getOppositeAlignmentPlacement, getOppositeAxis, getOppositeAxisPlacements, getOppositePlacement, getPaddingObject, getSide, getSideAxis, max, min, placements, rectToClientRect, round, sides };\n","import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils';\nexport { rectToClientRect } from '@floating-ui/utils';\n\nfunction computeCoordsFromPlacement(_ref, placement, rtl) {\n let {\n reference,\n floating\n } = _ref;\n const sideAxis = getSideAxis(placement);\n const alignmentAxis = getAlignmentAxis(placement);\n const alignLength = getAxisLength(alignmentAxis);\n const side = getSide(placement);\n const isVertical = sideAxis === 'y';\n const commonX = reference.x + reference.width / 2 - floating.width / 2;\n const commonY = reference.y + reference.height / 2 - floating.height / 2;\n const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;\n let coords;\n switch (side) {\n case 'top':\n coords = {\n x: commonX,\n y: reference.y - floating.height\n };\n break;\n case 'bottom':\n coords = {\n x: commonX,\n y: reference.y + reference.height\n };\n break;\n case 'right':\n coords = {\n x: reference.x + reference.width,\n y: commonY\n };\n break;\n case 'left':\n coords = {\n x: reference.x - floating.width,\n y: commonY\n };\n break;\n default:\n coords = {\n x: reference.x,\n y: reference.y\n };\n }\n switch (getAlignment(placement)) {\n case 'start':\n coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);\n break;\n case 'end':\n coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);\n break;\n }\n return coords;\n}\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nasync function detectOverflow(state, options) {\n var _await$platform$isEle;\n if (options === void 0) {\n options = {};\n }\n const {\n x,\n y,\n platform,\n rects,\n elements,\n strategy\n } = state;\n const {\n boundary = 'clippingAncestors',\n rootBoundary = 'viewport',\n elementContext = 'floating',\n altBoundary = false,\n padding = 0\n } = evaluate(options, state);\n const paddingObject = getPaddingObject(padding);\n const altContext = elementContext === 'floating' ? 'reference' : 'floating';\n const element = elements[altBoundary ? altContext : elementContext];\n const clippingClientRect = rectToClientRect(await platform.getClippingRect({\n element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))),\n boundary,\n rootBoundary,\n strategy\n }));\n const rect = elementContext === 'floating' ? {\n x,\n y,\n width: rects.floating.width,\n height: rects.floating.height\n } : rects.reference;\n const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));\n const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {\n x: 1,\n y: 1\n } : {\n x: 1,\n y: 1\n };\n const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({\n elements,\n rect,\n offsetParent,\n strategy\n }) : rect);\n return {\n top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,\n bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,\n left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,\n right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x\n };\n}\n\n// Maximum number of resets that can occur before bailing to avoid infinite reset loops.\nconst MAX_RESET_COUNT = 50;\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n *\n * This export does not have any `platform` interface logic. You will need to\n * write one for the platform you are using Floating UI with.\n */\nconst computePosition = async (reference, floating, config) => {\n const {\n placement = 'bottom',\n strategy = 'absolute',\n middleware = [],\n platform\n } = config;\n const platformWithDetectOverflow = platform.detectOverflow ? platform : {\n ...platform,\n detectOverflow\n };\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));\n let rects = await platform.getElementRects({\n reference,\n floating,\n strategy\n });\n let {\n x,\n y\n } = computeCoordsFromPlacement(rects, placement, rtl);\n let statefulPlacement = placement;\n let resetCount = 0;\n const middlewareData = {};\n for (let i = 0; i < middleware.length; i++) {\n const currentMiddleware = middleware[i];\n if (!currentMiddleware) {\n continue;\n }\n const {\n name,\n fn\n } = currentMiddleware;\n const {\n x: nextX,\n y: nextY,\n data,\n reset\n } = await fn({\n x,\n y,\n initialPlacement: placement,\n placement: statefulPlacement,\n strategy,\n middlewareData,\n rects,\n platform: platformWithDetectOverflow,\n elements: {\n reference,\n floating\n }\n });\n x = nextX != null ? nextX : x;\n y = nextY != null ? nextY : y;\n middlewareData[name] = {\n ...middlewareData[name],\n ...data\n };\n if (reset && resetCount < MAX_RESET_COUNT) {\n resetCount++;\n if (typeof reset === 'object') {\n if (reset.placement) {\n statefulPlacement = reset.placement;\n }\n if (reset.rects) {\n rects = reset.rects === true ? await platform.getElementRects({\n reference,\n floating,\n strategy\n }) : reset.rects;\n }\n ({\n x,\n y\n } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));\n }\n i = -1;\n }\n }\n return {\n x,\n y,\n placement: statefulPlacement,\n strategy,\n middlewareData\n };\n};\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = options => ({\n name: 'arrow',\n options,\n async fn(state) {\n const {\n x,\n y,\n placement,\n rects,\n platform,\n elements,\n middlewareData\n } = state;\n // Since `element` is required, we don't Partial<> the type.\n const {\n element,\n padding = 0\n } = evaluate(options, state) || {};\n if (element == null) {\n return {};\n }\n const paddingObject = getPaddingObject(padding);\n const coords = {\n x,\n y\n };\n const axis = getAlignmentAxis(placement);\n const length = getAxisLength(axis);\n const arrowDimensions = await platform.getDimensions(element);\n const isYAxis = axis === 'y';\n const minProp = isYAxis ? 'top' : 'left';\n const maxProp = isYAxis ? 'bottom' : 'right';\n const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';\n const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];\n const startDiff = coords[axis] - rects.reference[axis];\n const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));\n let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;\n\n // DOM platform can return `window` as the `offsetParent`.\n if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) {\n clientSize = elements.floating[clientProp] || rects.floating[length];\n }\n const centerToReference = endDiff / 2 - startDiff / 2;\n\n // If the padding is large enough that it causes the arrow to no longer be\n // centered, modify the padding so that it is centered.\n const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;\n const minPadding = min(paddingObject[minProp], largestPossiblePadding);\n const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);\n\n // Make sure the arrow doesn't overflow the floating element if the center\n // point is outside the floating element's bounds.\n const min$1 = minPadding;\n const max = clientSize - arrowDimensions[length] - maxPadding;\n const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;\n const offset = clamp(min$1, center, max);\n\n // If the reference is small enough that the arrow's padding causes it to\n // to point to nothing for an aligned placement, adjust the offset of the\n // floating element itself. To ensure `shift()` continues to take action,\n // a single reset is performed when this is true.\n const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;\n const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0;\n return {\n [axis]: coords[axis] + alignmentOffset,\n data: {\n [axis]: offset,\n centerOffset: center - offset - alignmentOffset,\n ...(shouldAddOffset && {\n alignmentOffset\n })\n },\n reset: shouldAddOffset\n };\n }\n});\n\nfunction getPlacementList(alignment, autoAlignment, allowedPlacements) {\n const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement);\n return allowedPlacementsSortedByAlignment.filter(placement => {\n if (alignment) {\n return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false);\n }\n return true;\n });\n}\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'autoPlacement',\n options,\n async fn(state) {\n var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE;\n const {\n rects,\n middlewareData,\n placement,\n platform,\n elements\n } = state;\n const {\n crossAxis = false,\n alignment,\n allowedPlacements = placements,\n autoAlignment = true,\n ...detectOverflowOptions\n } = evaluate(options, state);\n const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements;\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0;\n const currentPlacement = placements$1[currentIndex];\n if (currentPlacement == null) {\n return {};\n }\n const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)));\n\n // Make `computeCoords` start from the right place.\n if (placement !== currentPlacement) {\n return {\n reset: {\n placement: placements$1[0]\n }\n };\n }\n const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]];\n const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), {\n placement: currentPlacement,\n overflows: currentOverflows\n }];\n const nextPlacement = placements$1[currentIndex + 1];\n\n // There are more placements to check.\n if (nextPlacement) {\n return {\n data: {\n index: currentIndex + 1,\n overflows: allOverflows\n },\n reset: {\n placement: nextPlacement\n }\n };\n }\n const placementsSortedByMostSpace = allOverflows.map(d => {\n const alignment = getAlignment(d.placement);\n return [d.placement, alignment && crossAxis ?\n // Check along the mainAxis and main crossAxis side.\n d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) :\n // Check only the mainAxis.\n d.overflows[0], d.overflows];\n }).sort((a, b) => a[1] - b[1]);\n const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0,\n // Aligned placements should not check their opposite crossAxis\n // side.\n getAlignment(d[0]) ? 2 : 3).every(v => v <= 0));\n const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0];\n if (resetPlacement !== placement) {\n return {\n data: {\n index: currentIndex + 1,\n overflows: allOverflows\n },\n reset: {\n placement: resetPlacement\n }\n };\n }\n return {};\n }\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'flip',\n options,\n async fn(state) {\n var _middlewareData$arrow, _middlewareData$flip;\n const {\n placement,\n middlewareData,\n rects,\n initialPlacement,\n platform,\n elements\n } = state;\n const {\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = true,\n fallbackPlacements: specifiedFallbackPlacements,\n fallbackStrategy = 'bestFit',\n fallbackAxisSideDirection = 'none',\n flipAlignment = true,\n ...detectOverflowOptions\n } = evaluate(options, state);\n\n // If a reset by the arrow was caused due to an alignment offset being\n // added, we should skip any logic now since `flip()` has already done its\n // work.\n // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643\n if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n return {};\n }\n const side = getSide(placement);\n const initialSideAxis = getSideAxis(initialPlacement);\n const isBasePlacement = getSide(initialPlacement) === initialPlacement;\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));\n const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none';\n if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {\n fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));\n }\n const placements = [initialPlacement, ...fallbackPlacements];\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const overflows = [];\n let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];\n if (checkMainAxis) {\n overflows.push(overflow[side]);\n }\n if (checkCrossAxis) {\n const sides = getAlignmentSides(placement, rects, rtl);\n overflows.push(overflow[sides[0]], overflow[sides[1]]);\n }\n overflowsData = [...overflowsData, {\n placement,\n overflows\n }];\n\n // One or more sides is overflowing.\n if (!overflows.every(side => side <= 0)) {\n var _middlewareData$flip2, _overflowsData$filter;\n const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;\n const nextPlacement = placements[nextIndex];\n if (nextPlacement) {\n const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false;\n if (!ignoreCrossAxisOverflow ||\n // We leave the current main axis only if every placement on that axis\n // overflows the main axis.\n overflowsData.every(d => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) {\n // Try next placement and re-run the lifecycle.\n return {\n data: {\n index: nextIndex,\n overflows: overflowsData\n },\n reset: {\n placement: nextPlacement\n }\n };\n }\n }\n\n // First, find the candidates that fit on the mainAxis side of overflow,\n // then find the placement that fits the best on the main crossAxis side.\n let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;\n\n // Otherwise fallback.\n if (!resetPlacement) {\n switch (fallbackStrategy) {\n case 'bestFit':\n {\n var _overflowsData$filter2;\n const placement = (_overflowsData$filter2 = overflowsData.filter(d => {\n if (hasFallbackAxisSideDirection) {\n const currentSideAxis = getSideAxis(d.placement);\n return currentSideAxis === initialSideAxis ||\n // Create a bias to the `y` side axis due to horizontal\n // reading directions favoring greater width.\n currentSideAxis === 'y';\n }\n return true;\n }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0];\n if (placement) {\n resetPlacement = placement;\n }\n break;\n }\n case 'initialPlacement':\n resetPlacement = initialPlacement;\n break;\n }\n }\n if (placement !== resetPlacement) {\n return {\n reset: {\n placement: resetPlacement\n }\n };\n }\n }\n return {};\n }\n };\n};\n\nfunction getSideOffsets(overflow, rect) {\n return {\n top: overflow.top - rect.height,\n right: overflow.right - rect.width,\n bottom: overflow.bottom - rect.height,\n left: overflow.left - rect.width\n };\n}\nfunction isAnySideFullyClipped(overflow) {\n return sides.some(side => overflow[side] >= 0);\n}\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'hide',\n options,\n async fn(state) {\n const {\n rects,\n platform\n } = state;\n const {\n strategy = 'referenceHidden',\n ...detectOverflowOptions\n } = evaluate(options, state);\n switch (strategy) {\n case 'referenceHidden':\n {\n const overflow = await platform.detectOverflow(state, {\n ...detectOverflowOptions,\n elementContext: 'reference'\n });\n const offsets = getSideOffsets(overflow, rects.reference);\n return {\n data: {\n referenceHiddenOffsets: offsets,\n referenceHidden: isAnySideFullyClipped(offsets)\n }\n };\n }\n case 'escaped':\n {\n const overflow = await platform.detectOverflow(state, {\n ...detectOverflowOptions,\n altBoundary: true\n });\n const offsets = getSideOffsets(overflow, rects.floating);\n return {\n data: {\n escapedOffsets: offsets,\n escaped: isAnySideFullyClipped(offsets)\n }\n };\n }\n default:\n {\n return {};\n }\n }\n }\n };\n};\n\nfunction getBoundingRect(rects) {\n const minX = min(...rects.map(rect => rect.left));\n const minY = min(...rects.map(rect => rect.top));\n const maxX = max(...rects.map(rect => rect.right));\n const maxY = max(...rects.map(rect => rect.bottom));\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY\n };\n}\nfunction getRectsByLine(rects) {\n const sortedRects = rects.slice().sort((a, b) => a.y - b.y);\n const groups = [];\n let prevRect = null;\n for (let i = 0; i < sortedRects.length; i++) {\n const rect = sortedRects[i];\n if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) {\n groups.push([rect]);\n } else {\n groups[groups.length - 1].push(rect);\n }\n prevRect = rect;\n }\n return groups.map(rect => rectToClientRect(getBoundingRect(rect)));\n}\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'inline',\n options,\n async fn(state) {\n const {\n placement,\n elements,\n rects,\n platform,\n strategy\n } = state;\n // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a\n // ClientRect's bounds, despite the event listener being triggered. A\n // padding of 2 seems to handle this issue.\n const {\n padding = 2,\n x,\n y\n } = evaluate(options, state);\n const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []);\n const clientRects = getRectsByLine(nativeClientRects);\n const fallback = rectToClientRect(getBoundingRect(nativeClientRects));\n const paddingObject = getPaddingObject(padding);\n function getBoundingClientRect() {\n // There are two rects and they are disjoined.\n if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) {\n // Find the first rect in which the point is fully inside.\n return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback;\n }\n\n // There are 2 or more connected rects.\n if (clientRects.length >= 2) {\n if (getSideAxis(placement) === 'y') {\n const firstRect = clientRects[0];\n const lastRect = clientRects[clientRects.length - 1];\n const isTop = getSide(placement) === 'top';\n const top = firstRect.top;\n const bottom = lastRect.bottom;\n const left = isTop ? firstRect.left : lastRect.left;\n const right = isTop ? firstRect.right : lastRect.right;\n const width = right - left;\n const height = bottom - top;\n return {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x: left,\n y: top\n };\n }\n const isLeftSide = getSide(placement) === 'left';\n const maxRight = max(...clientRects.map(rect => rect.right));\n const minLeft = min(...clientRects.map(rect => rect.left));\n const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight);\n const top = measureRects[0].top;\n const bottom = measureRects[measureRects.length - 1].bottom;\n const left = minLeft;\n const right = maxRight;\n const width = right - left;\n const height = bottom - top;\n return {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x: left,\n y: top\n };\n }\n return fallback;\n }\n const resetRects = await platform.getElementRects({\n reference: {\n getBoundingClientRect\n },\n floating: elements.floating,\n strategy\n });\n if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) {\n return {\n reset: {\n rects: resetRects\n }\n };\n }\n return {};\n }\n };\n};\n\nconst originSides = /*#__PURE__*/new Set(['left', 'top']);\n\n// For type backwards-compatibility, the `OffsetOptions` type was also\n// Derivable.\n\nasync function convertValueToCoords(state, options) {\n const {\n placement,\n platform,\n elements\n } = state;\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n const side = getSide(placement);\n const alignment = getAlignment(placement);\n const isVertical = getSideAxis(placement) === 'y';\n const mainAxisMulti = originSides.has(side) ? -1 : 1;\n const crossAxisMulti = rtl && isVertical ? -1 : 1;\n const rawValue = evaluate(options, state);\n\n // eslint-disable-next-line prefer-const\n let {\n mainAxis,\n crossAxis,\n alignmentAxis\n } = typeof rawValue === 'number' ? {\n mainAxis: rawValue,\n crossAxis: 0,\n alignmentAxis: null\n } : {\n mainAxis: rawValue.mainAxis || 0,\n crossAxis: rawValue.crossAxis || 0,\n alignmentAxis: rawValue.alignmentAxis\n };\n if (alignment && typeof alignmentAxis === 'number') {\n crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;\n }\n return isVertical ? {\n x: crossAxis * crossAxisMulti,\n y: mainAxis * mainAxisMulti\n } : {\n x: mainAxis * mainAxisMulti,\n y: crossAxis * crossAxisMulti\n };\n}\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = function (options) {\n if (options === void 0) {\n options = 0;\n }\n return {\n name: 'offset',\n options,\n async fn(state) {\n var _middlewareData$offse, _middlewareData$arrow;\n const {\n x,\n y,\n placement,\n middlewareData\n } = state;\n const diffCoords = await convertValueToCoords(state, options);\n\n // If the placement is the same and the arrow caused an alignment offset\n // then we don't need to change the positioning coordinates.\n if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n return {};\n }\n return {\n x: x + diffCoords.x,\n y: y + diffCoords.y,\n data: {\n ...diffCoords,\n placement\n }\n };\n }\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'shift',\n options,\n async fn(state) {\n const {\n x,\n y,\n placement,\n platform\n } = state;\n const {\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = false,\n limiter = {\n fn: _ref => {\n let {\n x,\n y\n } = _ref;\n return {\n x,\n y\n };\n }\n },\n ...detectOverflowOptions\n } = evaluate(options, state);\n const coords = {\n x,\n y\n };\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const crossAxis = getSideAxis(getSide(placement));\n const mainAxis = getOppositeAxis(crossAxis);\n let mainAxisCoord = coords[mainAxis];\n let crossAxisCoord = coords[crossAxis];\n if (checkMainAxis) {\n const minSide = mainAxis === 'y' ? 'top' : 'left';\n const maxSide = mainAxis === 'y' ? 'bottom' : 'right';\n const min = mainAxisCoord + overflow[minSide];\n const max = mainAxisCoord - overflow[maxSide];\n mainAxisCoord = clamp(min, mainAxisCoord, max);\n }\n if (checkCrossAxis) {\n const minSide = crossAxis === 'y' ? 'top' : 'left';\n const maxSide = crossAxis === 'y' ? 'bottom' : 'right';\n const min = crossAxisCoord + overflow[minSide];\n const max = crossAxisCoord - overflow[maxSide];\n crossAxisCoord = clamp(min, crossAxisCoord, max);\n }\n const limitedCoords = limiter.fn({\n ...state,\n [mainAxis]: mainAxisCoord,\n [crossAxis]: crossAxisCoord\n });\n return {\n ...limitedCoords,\n data: {\n x: limitedCoords.x - x,\n y: limitedCoords.y - y,\n enabled: {\n [mainAxis]: checkMainAxis,\n [crossAxis]: checkCrossAxis\n }\n }\n };\n }\n };\n};\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n options,\n fn(state) {\n const {\n x,\n y,\n placement,\n rects,\n middlewareData\n } = state;\n const {\n offset = 0,\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = true\n } = evaluate(options, state);\n const coords = {\n x,\n y\n };\n const crossAxis = getSideAxis(placement);\n const mainAxis = getOppositeAxis(crossAxis);\n let mainAxisCoord = coords[mainAxis];\n let crossAxisCoord = coords[crossAxis];\n const rawOffset = evaluate(offset, state);\n const computedOffset = typeof rawOffset === 'number' ? {\n mainAxis: rawOffset,\n crossAxis: 0\n } : {\n mainAxis: 0,\n crossAxis: 0,\n ...rawOffset\n };\n if (checkMainAxis) {\n const len = mainAxis === 'y' ? 'height' : 'width';\n const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;\n const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;\n if (mainAxisCoord < limitMin) {\n mainAxisCoord = limitMin;\n } else if (mainAxisCoord > limitMax) {\n mainAxisCoord = limitMax;\n }\n }\n if (checkCrossAxis) {\n var _middlewareData$offse, _middlewareData$offse2;\n const len = mainAxis === 'y' ? 'width' : 'height';\n const isOriginSide = originSides.has(getSide(placement));\n const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);\n const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);\n if (crossAxisCoord < limitMin) {\n crossAxisCoord = limitMin;\n } else if (crossAxisCoord > limitMax) {\n crossAxisCoord = limitMax;\n }\n }\n return {\n [mainAxis]: mainAxisCoord,\n [crossAxis]: crossAxisCoord\n };\n }\n };\n};\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'size',\n options,\n async fn(state) {\n var _state$middlewareData, _state$middlewareData2;\n const {\n placement,\n rects,\n platform,\n elements\n } = state;\n const {\n apply = () => {},\n ...detectOverflowOptions\n } = evaluate(options, state);\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const side = getSide(placement);\n const alignment = getAlignment(placement);\n const isYAxis = getSideAxis(placement) === 'y';\n const {\n width,\n height\n } = rects.floating;\n let heightSide;\n let widthSide;\n if (side === 'top' || side === 'bottom') {\n heightSide = side;\n widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right';\n } else {\n widthSide = side;\n heightSide = alignment === 'end' ? 'top' : 'bottom';\n }\n const maximumClippingHeight = height - overflow.top - overflow.bottom;\n const maximumClippingWidth = width - overflow.left - overflow.right;\n const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight);\n const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth);\n const noShift = !state.middlewareData.shift;\n let availableHeight = overflowAvailableHeight;\n let availableWidth = overflowAvailableWidth;\n if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {\n availableWidth = maximumClippingWidth;\n }\n if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {\n availableHeight = maximumClippingHeight;\n }\n if (noShift && !alignment) {\n const xMin = max(overflow.left, 0);\n const xMax = max(overflow.right, 0);\n const yMin = max(overflow.top, 0);\n const yMax = max(overflow.bottom, 0);\n if (isYAxis) {\n availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));\n } else {\n availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));\n }\n }\n await apply({\n ...state,\n availableWidth,\n availableHeight\n });\n const nextDimensions = await platform.getDimensions(elements.floating);\n if (width !== nextDimensions.width || height !== nextDimensions.height) {\n return {\n reset: {\n rects: true\n }\n };\n }\n return {};\n }\n };\n};\n\nexport { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size };\n","function hasWindow() {\n return typeof window !== 'undefined';\n}\nfunction getNodeName(node) {\n if (isNode(node)) {\n return (node.nodeName || '').toLowerCase();\n }\n // Mocked nodes in testing environments may not be instances of Node. By\n // returning `#document` an infinite loop won't occur.\n // https://github.com/floating-ui/floating-ui/issues/2317\n return '#document';\n}\nfunction getWindow(node) {\n var _node$ownerDocument;\n return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;\n}\nfunction getDocumentElement(node) {\n var _ref;\n return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;\n}\nfunction isNode(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof Node || value instanceof getWindow(value).Node;\n}\nfunction isElement(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof Element || value instanceof getWindow(value).Element;\n}\nfunction isHTMLElement(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;\n}\nfunction isShadowRoot(value) {\n if (!hasWindow() || typeof ShadowRoot === 'undefined') {\n return false;\n }\n return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;\n}\nfunction isOverflowElement(element) {\n const {\n overflow,\n overflowX,\n overflowY,\n display\n } = getComputedStyle(element);\n return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && display !== 'inline' && display !== 'contents';\n}\nfunction isTableElement(element) {\n return /^(table|td|th)$/.test(getNodeName(element));\n}\nfunction isTopLayer(element) {\n try {\n if (element.matches(':popover-open')) {\n return true;\n }\n } catch (_e) {\n // no-op\n }\n try {\n return element.matches(':modal');\n } catch (_e) {\n return false;\n }\n}\nconst willChangeRe = /transform|translate|scale|rotate|perspective|filter/;\nconst containRe = /paint|layout|strict|content/;\nconst isNotNone = value => !!value && value !== 'none';\nlet isWebKitValue;\nfunction isContainingBlock(elementOrCss) {\n const css = isElement(elementOrCss) ? getComputedStyle(elementOrCss) : elementOrCss;\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n // https://drafts.csswg.org/css-transforms-2/#individual-transforms\n return isNotNone(css.transform) || isNotNone(css.translate) || isNotNone(css.scale) || isNotNone(css.rotate) || isNotNone(css.perspective) || !isWebKit() && (isNotNone(css.backdropFilter) || isNotNone(css.filter)) || willChangeRe.test(css.willChange || '') || containRe.test(css.contain || '');\n}\nfunction getContainingBlock(element) {\n let currentNode = getParentNode(element);\n while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {\n if (isContainingBlock(currentNode)) {\n return currentNode;\n } else if (isTopLayer(currentNode)) {\n return null;\n }\n currentNode = getParentNode(currentNode);\n }\n return null;\n}\nfunction isWebKit() {\n if (isWebKitValue == null) {\n isWebKitValue = typeof CSS !== 'undefined' && CSS.supports && CSS.supports('-webkit-backdrop-filter', 'none');\n }\n return isWebKitValue;\n}\nfunction isLastTraversableNode(node) {\n return /^(html|body|#document)$/.test(getNodeName(node));\n}\nfunction getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}\nfunction getNodeScroll(element) {\n if (isElement(element)) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n }\n return {\n scrollLeft: element.scrollX,\n scrollTop: element.scrollY\n };\n}\nfunction getParentNode(node) {\n if (getNodeName(node) === 'html') {\n return node;\n }\n const result =\n // Step into the shadow DOM of the parent of a slotted node.\n node.assignedSlot ||\n // DOM Element detected.\n node.parentNode ||\n // ShadowRoot detected.\n isShadowRoot(node) && node.host ||\n // Fallback.\n getDocumentElement(node);\n return isShadowRoot(result) ? result.host : result;\n}\nfunction getNearestOverflowAncestor(node) {\n const parentNode = getParentNode(node);\n if (isLastTraversableNode(parentNode)) {\n return node.ownerDocument ? node.ownerDocument.body : node.body;\n }\n if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {\n return parentNode;\n }\n return getNearestOverflowAncestor(parentNode);\n}\nfunction getOverflowAncestors(node, list, traverseIframes) {\n var _node$ownerDocument2;\n if (list === void 0) {\n list = [];\n }\n if (traverseIframes === void 0) {\n traverseIframes = true;\n }\n const scrollableAncestor = getNearestOverflowAncestor(node);\n const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);\n const win = getWindow(scrollableAncestor);\n if (isBody) {\n const frameElement = getFrameElement(win);\n return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);\n } else {\n return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));\n }\n}\nfunction getFrameElement(win) {\n return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;\n}\n\nexport { getComputedStyle, getContainingBlock, getDocumentElement, getFrameElement, getNearestOverflowAncestor, getNodeName, getNodeScroll, getOverflowAncestors, getParentNode, getWindow, isContainingBlock, isElement, isHTMLElement, isLastTraversableNode, isNode, isOverflowElement, isShadowRoot, isTableElement, isTopLayer, isWebKit };\n","import { rectToClientRect, arrow as arrow$1, autoPlacement as autoPlacement$1, detectOverflow as detectOverflow$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1, computePosition as computePosition$1 } from '@floating-ui/core';\nimport { round, createCoords, max, min, floor } from '@floating-ui/utils';\nimport { getComputedStyle as getComputedStyle$1, isHTMLElement, isElement, getWindow, isWebKit, getFrameElement, getNodeScroll, getDocumentElement, isTopLayer, getNodeName, isOverflowElement, getOverflowAncestors, getParentNode, isLastTraversableNode, isContainingBlock, isTableElement, getContainingBlock } from '@floating-ui/utils/dom';\nexport { getOverflowAncestors } from '@floating-ui/utils/dom';\n\nfunction getCssDimensions(element) {\n const css = getComputedStyle$1(element);\n // In testing environments, the `width` and `height` properties are empty\n // strings for SVG elements, returning NaN. Fallback to `0` in this case.\n let width = parseFloat(css.width) || 0;\n let height = parseFloat(css.height) || 0;\n const hasOffset = isHTMLElement(element);\n const offsetWidth = hasOffset ? element.offsetWidth : width;\n const offsetHeight = hasOffset ? element.offsetHeight : height;\n const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;\n if (shouldFallback) {\n width = offsetWidth;\n height = offsetHeight;\n }\n return {\n width,\n height,\n $: shouldFallback\n };\n}\n\nfunction unwrapElement(element) {\n return !isElement(element) ? element.contextElement : element;\n}\n\nfunction getScale(element) {\n const domElement = unwrapElement(element);\n if (!isHTMLElement(domElement)) {\n return createCoords(1);\n }\n const rect = domElement.getBoundingClientRect();\n const {\n width,\n height,\n $\n } = getCssDimensions(domElement);\n let x = ($ ? round(rect.width) : rect.width) / width;\n let y = ($ ? round(rect.height) : rect.height) / height;\n\n // 0, NaN, or Infinity should always fallback to 1.\n\n if (!x || !Number.isFinite(x)) {\n x = 1;\n }\n if (!y || !Number.isFinite(y)) {\n y = 1;\n }\n return {\n x,\n y\n };\n}\n\nconst noOffsets = /*#__PURE__*/createCoords(0);\nfunction getVisualOffsets(element) {\n const win = getWindow(element);\n if (!isWebKit() || !win.visualViewport) {\n return noOffsets;\n }\n return {\n x: win.visualViewport.offsetLeft,\n y: win.visualViewport.offsetTop\n };\n}\nfunction shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {\n if (isFixed === void 0) {\n isFixed = false;\n }\n if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {\n return false;\n }\n return isFixed;\n}\n\nfunction getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {\n if (includeScale === void 0) {\n includeScale = false;\n }\n if (isFixedStrategy === void 0) {\n isFixedStrategy = false;\n }\n const clientRect = element.getBoundingClientRect();\n const domElement = unwrapElement(element);\n let scale = createCoords(1);\n if (includeScale) {\n if (offsetParent) {\n if (isElement(offsetParent)) {\n scale = getScale(offsetParent);\n }\n } else {\n scale = getScale(element);\n }\n }\n const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);\n let x = (clientRect.left + visualOffsets.x) / scale.x;\n let y = (clientRect.top + visualOffsets.y) / scale.y;\n let width = clientRect.width / scale.x;\n let height = clientRect.height / scale.y;\n if (domElement) {\n const win = getWindow(domElement);\n const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;\n let currentWin = win;\n let currentIFrame = getFrameElement(currentWin);\n while (currentIFrame && offsetParent && offsetWin !== currentWin) {\n const iframeScale = getScale(currentIFrame);\n const iframeRect = currentIFrame.getBoundingClientRect();\n const css = getComputedStyle$1(currentIFrame);\n const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;\n const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;\n x *= iframeScale.x;\n y *= iframeScale.y;\n width *= iframeScale.x;\n height *= iframeScale.y;\n x += left;\n y += top;\n currentWin = getWindow(currentIFrame);\n currentIFrame = getFrameElement(currentWin);\n }\n }\n return rectToClientRect({\n width,\n height,\n x,\n y\n });\n}\n\n// If <html> has a CSS width greater than the viewport, then this will be\n// incorrect for RTL.\nfunction getWindowScrollBarX(element, rect) {\n const leftScroll = getNodeScroll(element).scrollLeft;\n if (!rect) {\n return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;\n }\n return rect.left + leftScroll;\n}\n\nfunction getHTMLOffset(documentElement, scroll) {\n const htmlRect = documentElement.getBoundingClientRect();\n const x = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);\n const y = htmlRect.top + scroll.scrollTop;\n return {\n x,\n y\n };\n}\n\nfunction convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {\n let {\n elements,\n rect,\n offsetParent,\n strategy\n } = _ref;\n const isFixed = strategy === 'fixed';\n const documentElement = getDocumentElement(offsetParent);\n const topLayer = elements ? isTopLayer(elements.floating) : false;\n if (offsetParent === documentElement || topLayer && isFixed) {\n return rect;\n }\n let scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n let scale = createCoords(1);\n const offsets = createCoords(0);\n const isOffsetParentAnElement = isHTMLElement(offsetParent);\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n if (isOffsetParentAnElement) {\n const offsetRect = getBoundingClientRect(offsetParent);\n scale = getScale(offsetParent);\n offsets.x = offsetRect.x + offsetParent.clientLeft;\n offsets.y = offsetRect.y + offsetParent.clientTop;\n }\n }\n const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);\n return {\n width: rect.width * scale.x,\n height: rect.height * scale.y,\n x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,\n y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y\n };\n}\n\nfunction getClientRects(element) {\n return Array.from(element.getClientRects());\n}\n\n// Gets the entire size of the scrollable document area, even extending outside\n// of the `<html>` and `<body>` rect bounds if horizontally scrollable.\nfunction getDocumentRect(element) {\n const html = getDocumentElement(element);\n const scroll = getNodeScroll(element);\n const body = element.ownerDocument.body;\n const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);\n const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);\n let x = -scroll.scrollLeft + getWindowScrollBarX(element);\n const y = -scroll.scrollTop;\n if (getComputedStyle$1(body).direction === 'rtl') {\n x += max(html.clientWidth, body.clientWidth) - width;\n }\n return {\n width,\n height,\n x,\n y\n };\n}\n\n// Safety check: ensure the scrollbar space is reasonable in case this\n// calculation is affected by unusual styles.\n// Most scrollbars leave 15-18px of space.\nconst SCROLLBAR_MAX = 25;\nfunction getViewportRect(element, strategy) {\n const win = getWindow(element);\n const html = getDocumentElement(element);\n const visualViewport = win.visualViewport;\n let width = html.clientWidth;\n let height = html.clientHeight;\n let x = 0;\n let y = 0;\n if (visualViewport) {\n width = visualViewport.width;\n height = visualViewport.height;\n const visualViewportBased = isWebKit();\n if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {\n x = visualViewport.offsetLeft;\n y = visualViewport.offsetTop;\n }\n }\n const windowScrollbarX = getWindowScrollBarX(html);\n // <html> `overflow: hidden` + `scrollbar-gutter: stable` reduces the\n // visual width of the <html> but this is not considered in the size\n // of `html.clientWidth`.\n if (windowScrollbarX <= 0) {\n const doc = html.ownerDocument;\n const body = doc.body;\n const bodyStyles = getComputedStyle(body);\n const bodyMarginInline = doc.compatMode === 'CSS1Compat' ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;\n const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);\n if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {\n width -= clippingStableScrollbarWidth;\n }\n } else if (windowScrollbarX <= SCROLLBAR_MAX) {\n // If the <body> scrollbar is on the left, the width needs to be extended\n // by the scrollbar amount so there isn't extra space on the right.\n width += windowScrollbarX;\n }\n return {\n width,\n height,\n x,\n y\n };\n}\n\n// Returns the inner client rect, subtracting scrollbars if present.\nfunction getInnerBoundingClientRect(element, strategy) {\n const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');\n const top = clientRect.top + element.clientTop;\n const left = clientRect.left + element.clientLeft;\n const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);\n const width = element.clientWidth * scale.x;\n const height = element.clientHeight * scale.y;\n const x = left * scale.x;\n const y = top * scale.y;\n return {\n width,\n height,\n x,\n y\n };\n}\nfunction getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {\n let rect;\n if (clippingAncestor === 'viewport') {\n rect = getViewportRect(element, strategy);\n } else if (clippingAncestor === 'document') {\n rect = getDocumentRect(getDocumentElement(element));\n } else if (isElement(clippingAncestor)) {\n rect = getInnerBoundingClientRect(clippingAncestor, strategy);\n } else {\n const visualOffsets = getVisualOffsets(element);\n rect = {\n x: clippingAncestor.x - visualOffsets.x,\n y: clippingAncestor.y - visualOffsets.y,\n width: clippingAncestor.width,\n height: clippingAncestor.height\n };\n }\n return rectToClientRect(rect);\n}\nfunction hasFixedPositionAncestor(element, stopNode) {\n const parentNode = getParentNode(element);\n if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {\n return false;\n }\n return getComputedStyle$1(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);\n}\n\n// A \"clipping ancestor\" is an `overflow` element with the characteristic of\n// clipping (or hiding) child elements. This returns all clipping ancestors\n// of the given element up the tree.\nfunction getClippingElementAncestors(element, cache) {\n const cachedResult = cache.get(element);\n if (cachedResult) {\n return cachedResult;\n }\n let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');\n let currentContainingBlockComputedStyle = null;\n const elementIsFixed = getComputedStyle$1(element).position === 'fixed';\n let currentNode = elementIsFixed ? getParentNode(element) : element;\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {\n const computedStyle = getComputedStyle$1(currentNode);\n const currentNodeIsContaining = isContainingBlock(currentNode);\n if (!currentNodeIsContaining && computedStyle.position === 'fixed') {\n currentContainingBlockComputedStyle = null;\n }\n const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && (currentContainingBlockComputedStyle.position === 'absolute' || currentContainingBlockComputedStyle.position === 'fixed') || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);\n if (shouldDropCurrentNode) {\n // Drop non-containing blocks.\n result = result.filter(ancestor => ancestor !== currentNode);\n } else {\n // Record last containing block for next iteration.\n currentContainingBlockComputedStyle = computedStyle;\n }\n currentNode = getParentNode(currentNode);\n }\n cache.set(element, result);\n return result;\n}\n\n// Gets the maximum area that the element is visible in due to any number of\n// clipping ancestors.\nfunction getClippingRect(_ref) {\n let {\n element,\n boundary,\n rootBoundary,\n strategy\n } = _ref;\n const elementClippingAncestors = boundary === 'clippingAncestors' ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);\n const clippingAncestors = [...elementClippingAncestors, rootBoundary];\n const firstRect = getClientRectFromClippingAncestor(element, clippingAncestors[0], strategy);\n let top = firstRect.top;\n let right = firstRect.right;\n let bottom = firstRect.bottom;\n let left = firstRect.left;\n for (let i = 1; i < clippingAncestors.length; i++) {\n const rect = getClientRectFromClippingAncestor(element, clippingAncestors[i], strategy);\n top = max(rect.top, top);\n right = min(rect.right, right);\n bottom = min(rect.bottom, bottom);\n left = max(rect.left, left);\n }\n return {\n width: right - left,\n height: bottom - top,\n x: left,\n y: top\n };\n}\n\nfunction getDimensions(element) {\n const {\n width,\n height\n } = getCssDimensions(element);\n return {\n width,\n height\n };\n}\n\nfunction getRectRelativeToOffsetParent(element, offsetParent, strategy) {\n const isOffsetParentAnElement = isHTMLElement(offsetParent);\n const documentElement = getDocumentElement(offsetParent);\n const isFixed = strategy === 'fixed';\n const rect = getBoundingClientRect(element, true, isFixed, offsetParent);\n let scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n const offsets = createCoords(0);\n\n // If the <body> scrollbar appears on the left (e.g. RTL systems). Use\n // Firefox with layout.scrollbar.side = 3 in about:config to test this.\n function setLeftRTLScrollbarOffset() {\n offsets.x = getWindowScrollBarX(documentElement);\n }\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n if (isOffsetParentAnElement) {\n const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);\n offsets.x = offsetRect.x + offsetParent.clientLeft;\n offsets.y = offsetRect.y + offsetParent.clientTop;\n } else if (documentElement) {\n setLeftRTLScrollbarOffset();\n }\n }\n if (isFixed && !isOffsetParentAnElement && documentElement) {\n setLeftRTLScrollbarOffset();\n }\n const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);\n const x = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;\n const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;\n return {\n x,\n y,\n width: rect.width,\n height: rect.height\n };\n}\n\nfunction isStaticPositioned(element) {\n return getComputedStyle$1(element).position === 'static';\n}\n\nfunction getTrueOffsetParent(element, polyfill) {\n if (!isHTMLElement(element) || getComputedStyle$1(element).position === 'fixed') {\n return null;\n }\n if (polyfill) {\n return polyfill(element);\n }\n let rawOffsetParent = element.offsetParent;\n\n // Firefox returns the <html> element as the offsetParent if it's non-static,\n // while Chrome and Safari return the <body> element. The <body> element must\n // be used to perform the correct calculations even if the <html> element is\n // non-static.\n if (getDocumentElement(element) === rawOffsetParent) {\n rawOffsetParent = rawOffsetParent.ownerDocument.body;\n }\n return rawOffsetParent;\n}\n\n// Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\nfunction getOffsetParent(element, polyfill) {\n const win = getWindow(element);\n if (isTopLayer(element)) {\n return win;\n }\n if (!isHTMLElement(element)) {\n let svgOffsetParent = getParentNode(element);\n while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {\n if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {\n return svgOffsetParent;\n }\n svgOffsetParent = getParentNode(svgOffsetParent);\n }\n return win;\n }\n let offsetParent = getTrueOffsetParent(element, polyfill);\n while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {\n offsetParent = getTrueOffsetParent(offsetParent, polyfill);\n }\n if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {\n return win;\n }\n return offsetParent || getContainingBlock(element) || win;\n}\n\nconst getElementRects = async function (data) {\n const getOffsetParentFn = this.getOffsetParent || getOffsetParent;\n const getDimensionsFn = this.getDimensions;\n const floatingDimensions = await getDimensionsFn(data.floating);\n return {\n reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),\n floating: {\n x: 0,\n y: 0,\n width: floatingDimensions.width,\n height: floatingDimensions.height\n }\n };\n};\n\nfunction isRTL(element) {\n return getComputedStyle$1(element).direction === 'rtl';\n}\n\nconst platform = {\n convertOffsetParentRelativeRectToViewportRelativeRect,\n getDocumentElement,\n getClippingRect,\n getOffsetParent,\n getElementRects,\n getClientRects,\n getDimensions,\n getScale,\n isElement,\n isRTL\n};\n\nfunction rectsAreEqual(a, b) {\n return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;\n}\n\n// https://samthor.au/2021/observing-dom/\nfunction observeMove(element, onMove) {\n let io = null;\n let timeoutId;\n const root = getDocumentElement(element);\n function cleanup() {\n var _io;\n clearTimeout(timeoutId);\n (_io = io) == null || _io.disconnect();\n io = null;\n }\n function refresh(skip, threshold) {\n if (skip === void 0) {\n skip = false;\n }\n if (threshold === void 0) {\n threshold = 1;\n }\n cleanup();\n const elementRectForRootMargin = element.getBoundingClientRect();\n const {\n left,\n top,\n width,\n height\n } = elementRectForRootMargin;\n if (!skip) {\n onMove();\n }\n if (!width || !height) {\n return;\n }\n const insetTop = floor(top);\n const insetRight = floor(root.clientWidth - (left + width));\n const insetBottom = floor(root.clientHeight - (top + height));\n const insetLeft = floor(left);\n const rootMargin = -insetTop + \"px \" + -insetRight + \"px \" + -insetBottom + \"px \" + -insetLeft + \"px\";\n const options = {\n rootMargin,\n threshold: max(0, min(1, threshold)) || 1\n };\n let isFirstUpdate = true;\n function handleObserve(entries) {\n const ratio = entries[0].intersectionRatio;\n if (ratio !== threshold) {\n if (!isFirstUpdate) {\n return refresh();\n }\n if (!ratio) {\n // If the reference is clipped, the ratio is 0. Throttle the refresh\n // to prevent an infinite loop of updates.\n timeoutId = setTimeout(() => {\n refresh(false, 1e-7);\n }, 1000);\n } else {\n refresh(false, ratio);\n }\n }\n if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) {\n // It's possible that even though the ratio is reported as 1, the\n // element is not actually fully within the IntersectionObserver's root\n // area anymore. This can happen under performance constraints. This may\n // be a bug in the browser's IntersectionObserver implementation. To\n // work around this, we compare the element's bounding rect now with\n // what it was at the time we created the IntersectionObserver. If they\n // are not equal then the element moved, so we refresh.\n refresh();\n }\n isFirstUpdate = false;\n }\n\n // Older browsers don't support a `document` as the root and will throw an\n // error.\n try {\n io = new IntersectionObserver(handleObserve, {\n ...options,\n // Handle <iframe>s\n root: root.ownerDocument\n });\n } catch (_e) {\n io = new IntersectionObserver(handleObserve, options);\n }\n io.observe(element);\n }\n refresh(true);\n return cleanup;\n}\n\n/**\n * Automatically updates the position of the floating element when necessary.\n * Should only be called when the floating element is mounted on the DOM or\n * visible on the screen.\n * @returns cleanup function that should be invoked when the floating element is\n * removed from the DOM or hidden from the screen.\n * @see https://floating-ui.com/docs/autoUpdate\n */\nfunction autoUpdate(reference, floating, update, options) {\n if (options === void 0) {\n options = {};\n }\n const {\n ancestorScroll = true,\n ancestorResize = true,\n elementResize = typeof ResizeObserver === 'function',\n layoutShift = typeof IntersectionObserver === 'function',\n animationFrame = false\n } = options;\n const referenceEl = unwrapElement(reference);\n const ancestors = ancestorScroll || ancestorResize ? [...(referenceEl ? getOverflowAncestors(referenceEl) : []), ...(floating ? getOverflowAncestors(floating) : [])] : [];\n ancestors.forEach(ancestor => {\n ancestorScroll && ancestor.addEventListener('scroll', update, {\n passive: true\n });\n ancestorResize && ancestor.addEventListener('resize', update);\n });\n const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;\n let reobserveFrame = -1;\n let resizeObserver = null;\n if (elementResize) {\n resizeObserver = new ResizeObserver(_ref => {\n let [firstEntry] = _ref;\n if (firstEntry && firstEntry.target === referenceEl && resizeObserver && floating) {\n // Prevent update loops when using the `size` middleware.\n // https://github.com/floating-ui/floating-ui/issues/1740\n resizeObserver.unobserve(floating);\n cancelAnimationFrame(reobserveFrame);\n reobserveFrame = requestAnimationFrame(() => {\n var _resizeObserver;\n (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);\n });\n }\n update();\n });\n if (referenceEl && !animationFrame) {\n resizeObserver.observe(referenceEl);\n }\n if (floating) {\n resizeObserver.observe(floating);\n }\n }\n let frameId;\n let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;\n if (animationFrame) {\n frameLoop();\n }\n function frameLoop() {\n const nextRefRect = getBoundingClientRect(reference);\n if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) {\n update();\n }\n prevRefRect = nextRefRect;\n frameId = requestAnimationFrame(frameLoop);\n }\n update();\n return () => {\n var _resizeObserver2;\n ancestors.forEach(ancestor => {\n ancestorScroll && ancestor.removeEventListener('scroll', update);\n ancestorResize && ancestor.removeEventListener('resize', update);\n });\n cleanupIo == null || cleanupIo();\n (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();\n resizeObserver = null;\n if (animationFrame) {\n cancelAnimationFrame(frameId);\n }\n };\n}\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nconst detectOverflow = detectOverflow$1;\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = offset$1;\n\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = autoPlacement$1;\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = shift$1;\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = flip$1;\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = size$1;\n\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = hide$1;\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = arrow$1;\n\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = inline$1;\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = limitShift$1;\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n */\nconst computePosition = (reference, floating, options) => {\n // This caches the expensive `getClippingElementAncestors` function so that\n // multiple lifecycle resets re-use the same result. It only lives for a\n // single call. If other functions become expensive, we can add them as well.\n const cache = new Map();\n const mergedOptions = {\n platform,\n ...options\n };\n const platformWithCache = {\n ...mergedOptions.platform,\n _c: cache\n };\n return computePosition$1(reference, floating, {\n ...mergedOptions,\n platform: platformWithCache\n });\n};\n\nexport { arrow, autoPlacement, autoUpdate, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, platform, shift, size };\n","import { computePosition, arrow as arrow$2, autoPlacement as autoPlacement$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1 } from '@floating-ui/dom';\nexport { autoUpdate, computePosition, detectOverflow, getOverflowAncestors, platform } from '@floating-ui/dom';\nimport * as React from 'react';\nimport { useLayoutEffect } from 'react';\nimport * as ReactDOM from 'react-dom';\n\nvar isClient = typeof document !== 'undefined';\n\nvar noop = function noop() {};\nvar index = isClient ? useLayoutEffect : noop;\n\n// Fork of `fast-deep-equal` that only does the comparisons we need and compares\n// functions\nfunction deepEqual(a, b) {\n if (a === b) {\n return true;\n }\n if (typeof a !== typeof b) {\n return false;\n }\n if (typeof a === 'function' && a.toString() === b.toString()) {\n return true;\n }\n let length;\n let i;\n let keys;\n if (a && b && typeof a === 'object') {\n if (Array.isArray(a)) {\n length = a.length;\n if (length !== b.length) return false;\n for (i = length; i-- !== 0;) {\n if (!deepEqual(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) {\n return false;\n }\n for (i = length; i-- !== 0;) {\n if (!{}.hasOwnProperty.call(b, keys[i])) {\n return false;\n }\n }\n for (i = length; i-- !== 0;) {\n const key = keys[i];\n if (key === '_owner' && a.$$typeof) {\n continue;\n }\n if (!deepEqual(a[key], b[key])) {\n return false;\n }\n }\n return true;\n }\n return a !== a && b !== b;\n}\n\nfunction getDPR(element) {\n if (typeof window === 'undefined') {\n return 1;\n }\n const win = element.ownerDocument.defaultView || window;\n return win.devicePixelRatio || 1;\n}\n\nfunction roundByDPR(element, value) {\n const dpr = getDPR(element);\n return Math.round(value * dpr) / dpr;\n}\n\nfunction useLatestRef(value) {\n const ref = React.useRef(value);\n index(() => {\n ref.current = value;\n });\n return ref;\n}\n\n/**\n * Provides data to position a floating element.\n * @see https://floating-ui.com/docs/useFloating\n */\nfunction useFloating(options) {\n if (options === void 0) {\n options = {};\n }\n const {\n placement = 'bottom',\n strategy = 'absolute',\n middleware = [],\n platform,\n elements: {\n reference: externalReference,\n floating: externalFloating\n } = {},\n transform = true,\n whileElementsMounted,\n open\n } = options;\n const [data, setData] = React.useState({\n x: 0,\n y: 0,\n strategy,\n placement,\n middlewareData: {},\n isPositioned: false\n });\n const [latestMiddleware, setLatestMiddleware] = React.useState(middleware);\n if (!deepEqual(latestMiddleware, middleware)) {\n setLatestMiddleware(middleware);\n }\n const [_reference, _setReference] = React.useState(null);\n const [_floating, _setFloating] = React.useState(null);\n const setReference = React.useCallback(node => {\n if (node !== referenceRef.current) {\n referenceRef.current = node;\n _setReference(node);\n }\n }, []);\n const setFloating = React.useCallback(node => {\n if (node !== floatingRef.current) {\n floatingRef.current = node;\n _setFloating(node);\n }\n }, []);\n const referenceEl = externalReference || _reference;\n const floatingEl = externalFloating || _floating;\n const referenceRef = React.useRef(null);\n const floatingRef = React.useRef(null);\n const dataRef = React.useRef(data);\n const hasWhileElementsMounted = whileElementsMounted != null;\n const whileElementsMountedRef = useLatestRef(whileElementsMounted);\n const platformRef = useLatestRef(platform);\n const openRef = useLatestRef(open);\n const update = React.useCallback(() => {\n if (!referenceRef.current || !floatingRef.current) {\n return;\n }\n const config = {\n placement,\n strategy,\n middleware: latestMiddleware\n };\n if (platformRef.current) {\n config.platform = platformRef.current;\n }\n computePosition(referenceRef.current, floatingRef.current, config).then(data => {\n const fullData = {\n ...data,\n // The floating element's position may be recomputed while it's closed\n // but still mounted (such as when transitioning out). To ensure\n // `isPositioned` will be `false` initially on the next open, avoid\n // setting it to `true` when `open === false` (must be specified).\n isPositioned: openRef.current !== false\n };\n if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {\n dataRef.current = fullData;\n ReactDOM.flushSync(() => {\n setData(fullData);\n });\n }\n });\n }, [latestMiddleware, placement, strategy, platformRef, openRef]);\n index(() => {\n if (open === false && dataRef.current.isPositioned) {\n dataRef.current.isPositioned = false;\n setData(data => ({\n ...data,\n isPositioned: false\n }));\n }\n }, [open]);\n const isMountedRef = React.useRef(false);\n index(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n index(() => {\n if (referenceEl) referenceRef.current = referenceEl;\n if (floatingEl) floatingRef.current = floatingEl;\n if (referenceEl && floatingEl) {\n if (whileElementsMountedRef.current) {\n return whileElementsMountedRef.current(referenceEl, floatingEl, update);\n }\n update();\n }\n }, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);\n const refs = React.useMemo(() => ({\n reference: referenceRef,\n floating: floatingRef,\n setReference,\n setFloating\n }), [setReference, setFloating]);\n const elements = React.useMemo(() => ({\n reference: referenceEl,\n floating: floatingEl\n }), [referenceEl, floatingEl]);\n const floatingStyles = React.useMemo(() => {\n const initialStyles = {\n position: strategy,\n left: 0,\n top: 0\n };\n if (!elements.floating) {\n return initialStyles;\n }\n const x = roundByDPR(elements.floating, data.x);\n const y = roundByDPR(elements.floating, data.y);\n if (transform) {\n return {\n ...initialStyles,\n transform: \"translate(\" + x + \"px, \" + y + \"px)\",\n ...(getDPR(elements.floating) >= 1.5 && {\n willChange: 'transform'\n })\n };\n }\n return {\n position: strategy,\n left: x,\n top: y\n };\n }, [strategy, transform, elements.floating, data.x, data.y]);\n return React.useMemo(() => ({\n ...data,\n update,\n refs,\n elements,\n floatingStyles\n }), [data, update, refs, elements, floatingStyles]);\n}\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow$1 = options => {\n function isRef(value) {\n return {}.hasOwnProperty.call(value, 'current');\n }\n return {\n name: 'arrow',\n options,\n fn(state) {\n const {\n element,\n padding\n } = typeof options === 'function' ? options(state) : options;\n if (element && isRef(element)) {\n if (element.current != null) {\n return arrow$2({\n element: element.current,\n padding\n }).fn(state);\n }\n return {};\n }\n if (element) {\n return arrow$2({\n element,\n padding\n }).fn(state);\n }\n return {};\n }\n };\n};\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = (options, deps) => {\n const result = offset$1(options);\n return {\n name: result.name,\n fn: result.fn,\n options: [options, deps]\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = (options, deps) => {\n const result = shift$1(options);\n return {\n name: result.name,\n fn: result.fn,\n options: [options, deps]\n };\n};\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = (options, deps) => {\n const result = limitShift$1(options);\n return {\n fn: result.fn,\n options: [options, deps]\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = (options, deps) => {\n const result = flip$1(options);\n return {\n name: result.name,\n fn: result.fn,\n options: [options, deps]\n };\n};\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = (options, deps) => {\n const result = size$1(options);\n return {\n name: result.name,\n fn: result.fn,\n options: [options, deps]\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = (options, deps) => {\n const result = autoPlacement$1(options);\n return {\n name: result.name,\n fn: result.fn,\n options: [options, deps]\n };\n};\n\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = (options, deps) => {\n const result = hide$1(options);\n return {\n name: result.name,\n fn: result.fn,\n options: [options, deps]\n };\n};\n\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = (options, deps) => {\n const result = inline$1(options);\n return {\n name: result.name,\n fn: result.fn,\n options: [options, deps]\n };\n};\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = (options, deps) => {\n const result = arrow$1(options);\n return {\n name: result.name,\n fn: result.fn,\n options: [options, deps]\n };\n};\n\nexport { arrow, autoPlacement, flip, hide, inline, limitShift, offset, shift, size, useFloating };\n","import * as React from 'react';\nimport { Primitive } from '@radix-ui/react-primitive';\n\n/* -------------------------------------------------------------------------------------------------\n * Arrow\n * -----------------------------------------------------------------------------------------------*/\n\nconst NAME = 'Arrow';\n\ntype ArrowElement = React.ComponentRef<typeof Primitive.svg>;\ntype PrimitiveSvgProps = React.ComponentPropsWithoutRef<typeof Primitive.svg>;\ninterface ArrowProps extends PrimitiveSvgProps {}\n\nconst Arrow = React.forwardRef<ArrowElement, ArrowProps>((props, forwardedRef) => {\n const { children, width = 10, height = 5, ...arrowProps } = props;\n return (\n <Primitive.svg\n {...arrowProps}\n ref={forwardedRef}\n width={width}\n height={height}\n viewBox=\"0 0 30 10\"\n preserveAspectRatio=\"none\"\n >\n {/* We use their children if they're slotting to replace the whole svg */}\n {props.asChild ? children : <polygon points=\"0,0 30,0 15,10\" />}\n </Primitive.svg>\n );\n});\n\nArrow.displayName = NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = Arrow;\n\nexport {\n Arrow,\n //\n Root,\n};\nexport type { ArrowProps };\n","/// <reference types=\"resize-observer-browser\" />\n\nimport * as React from 'react';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\n\nfunction useSize(element: HTMLElement | null) {\n const [size, setSize] = React.useState<{ width: number; height: number } | undefined>(undefined);\n\n useLayoutEffect(() => {\n if (element) {\n // provide size as early as possible\n setSize({ width: element.offsetWidth, height: element.offsetHeight });\n\n const resizeObserver = new ResizeObserver((entries) => {\n if (!Array.isArray(entries)) {\n return;\n }\n\n // Since we only observe the one element, we don't need to loop over the\n // array\n if (!entries.length) {\n return;\n }\n\n const entry = entries[0];\n let width: number;\n let height: number;\n\n if ('borderBoxSize' in entry) {\n const borderSizeEntry = entry['borderBoxSize'];\n // iron out differences between browsers\n const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry;\n width = borderSize['inlineSize'];\n height = borderSize['blockSize'];\n } else {\n // for browsers that don't support `borderBoxSize`\n // we calculate it ourselves to get the correct border box.\n width = element.offsetWidth;\n height = element.offsetHeight;\n }\n\n setSize({ width, height });\n });\n\n resizeObserver.observe(element, { box: 'border-box' });\n\n return () => resizeObserver.unobserve(element);\n } else {\n // We only want to reset to `undefined` when the element becomes `null`,\n // not if it changes to another element.\n setSize(undefined);\n }\n }, [element]);\n\n return size;\n}\n\nexport { useSize };\n","import * as React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\n\n/* -------------------------------------------------------------------------------------------------\n * Portal\n * -----------------------------------------------------------------------------------------------*/\n\nconst PORTAL_NAME = 'Portal';\n\ntype PortalElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface PortalProps extends PrimitiveDivProps {\n /**\n * An optional container where the portaled content should be appended.\n */\n container?: Element | DocumentFragment | null;\n}\n\nconst Portal = React.forwardRef<PortalElement, PortalProps>((props, forwardedRef) => {\n const { container: containerProp, ...portalProps } = props;\n const [mounted, setMounted] = React.useState(false);\n useLayoutEffect(() => setMounted(true), []);\n const container = containerProp || (mounted && globalThis?.document?.body);\n return container\n ? ReactDOM.createPortal(<Primitive.div {...portalProps} ref={forwardedRef} />, container)\n : null;\n});\n\nPortal.displayName = PORTAL_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = Portal;\n\nexport {\n Portal,\n //\n Root,\n};\nexport type { PortalProps };\n","import * as React from 'react';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\nimport { useStateMachine } from './use-state-machine';\n\ninterface PresenceProps {\n children: React.ReactElement | ((props: { present: boolean }) => React.ReactElement);\n present: boolean;\n}\n\nconst Presence: React.FC<PresenceProps> = (props) => {\n const { present, children } = props;\n const presence = usePresence(present);\n\n const child = (\n typeof children === 'function'\n ? children({ present: presence.isPresent })\n : React.Children.only(children)\n ) as React.ReactElement<{ ref?: React.Ref<HTMLElement> }>;\n\n const ref = useComposedRefs(presence.ref, getElementRef(child));\n const forceMount = typeof children === 'function';\n return forceMount || presence.isPresent ? React.cloneElement(child, { ref }) : null;\n};\n\nPresence.displayName = 'Presence';\n\n/* -------------------------------------------------------------------------------------------------\n * usePresence\n * -----------------------------------------------------------------------------------------------*/\n\nfunction usePresence(present: boolean) {\n const [node, setNode] = React.useState<HTMLElement>();\n const stylesRef = React.useRef<CSSStyleDeclaration | null>(null);\n const prevPresentRef = React.useRef(present);\n const prevAnimationNameRef = React.useRef<string>('none');\n const initialState = present ? 'mounted' : 'unmounted';\n const [state, send] = useStateMachine(initialState, {\n mounted: {\n UNMOUNT: 'unmounted',\n ANIMATION_OUT: 'unmountSuspended',\n },\n unmountSuspended: {\n MOUNT: 'mounted',\n ANIMATION_END: 'unmounted',\n },\n unmounted: {\n MOUNT: 'mounted',\n },\n });\n\n React.useEffect(() => {\n const currentAnimationName = getAnimationName(stylesRef.current);\n prevAnimationNameRef.current = state === 'mounted' ? currentAnimationName : 'none';\n }, [state]);\n\n useLayoutEffect(() => {\n const styles = stylesRef.current;\n const wasPresent = prevPresentRef.current;\n const hasPresentChanged = wasPresent !== present;\n\n if (hasPresentChanged) {\n const prevAnimationName = prevAnimationNameRef.current;\n const currentAnimationName = getAnimationName(styles);\n\n if (present) {\n send('MOUNT');\n } else if (currentAnimationName === 'none' || styles?.display === 'none') {\n // If there is no exit animation or the element is hidden, animations won't run\n // so we unmount instantly\n send('UNMOUNT');\n } else {\n /**\n * When `present` changes to `false`, we check changes to animation-name to\n * determine whether an animation has started. We chose this approach (reading\n * computed styles) because there is no `animationrun` event and `animationstart`\n * fires after `animation-delay` has expired which would be too late.\n */\n const isAnimating = prevAnimationName !== currentAnimationName;\n\n if (wasPresent && isAnimating) {\n send('ANIMATION_OUT');\n } else {\n send('UNMOUNT');\n }\n }\n\n prevPresentRef.current = present;\n }\n }, [present, send]);\n\n useLayoutEffect(() => {\n if (node) {\n let timeoutId: number;\n const ownerWindow = node.ownerDocument.defaultView ?? window;\n /**\n * Triggering an ANIMATION_OUT during an ANIMATION_IN will fire an `animationcancel`\n * event for ANIMATION_IN after we have entered `unmountSuspended` state. So, we\n * make sure we only trigger ANIMATION_END for the currently active animation.\n */\n const handleAnimationEnd = (event: AnimationEvent) => {\n const currentAnimationName = getAnimationName(stylesRef.current);\n // The event.animationName is unescaped for CSS syntax,\n // so we need to escape it to compare with the animationName computed from the style.\n const isCurrentAnimation = currentAnimationName.includes(CSS.escape(event.animationName));\n if (event.target === node && isCurrentAnimation) {\n // With React 18 concurrency this update is applied a frame after the\n // animation ends, creating a flash of visible content. By setting the\n // animation fill mode to \"forwards\", we force the node to keep the\n // styles of the last keyframe, removing the flash.\n //\n // Previously we flushed the update via ReactDom.flushSync, but with\n // exit animations this resulted in the node being removed from the\n // DOM before the synthetic animationEnd event was dispatched, meaning\n // user-provided event handlers would not be called.\n // https://github.com/radix-ui/primitives/pull/1849\n send('ANIMATION_END');\n if (!prevPresentRef.current) {\n const currentFillMode = node.style.animationFillMode;\n node.style.animationFillMode = 'forwards';\n // Reset the style after the node had time to unmount (for cases\n // where the component chooses not to unmount). Doing this any\n // sooner than `setTimeout` (e.g. with `requestAnimationFrame`)\n // still causes a flash.\n timeoutId = ownerWindow.setTimeout(() => {\n if (node.style.animationFillMode === 'forwards') {\n node.style.animationFillMode = currentFillMode;\n }\n });\n }\n }\n };\n const handleAnimationStart = (event: AnimationEvent) => {\n if (event.target === node) {\n // if animation occurred, store its name as the previous animation.\n prevAnimationNameRef.current = getAnimationName(stylesRef.current);\n }\n };\n node.addEventListener('animationstart', handleAnimationStart);\n node.addEventListener('animationcancel', handleAnimationEnd);\n node.addEventListener('animationend', handleAnimationEnd);\n return () => {\n ownerWindow.clearTimeout(timeoutId);\n node.removeEventListener('animationstart', handleAnimationStart);\n node.removeEventListener('animationcancel', handleAnimationEnd);\n node.removeEventListener('animationend', handleAnimationEnd);\n };\n } else {\n // Transition to the unmounted state if the node is removed prematurely.\n // We avoid doing so during cleanup as the node may change but still exist.\n send('ANIMATION_END');\n }\n }, [node, send]);\n\n return {\n isPresent: ['mounted', 'unmountSuspended'].includes(state),\n ref: React.useCallback((node: HTMLElement) => {\n stylesRef.current = node ? getComputedStyle(node) : null;\n setNode(node);\n }, []),\n };\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n\nfunction getAnimationName(styles: CSSStyleDeclaration | null) {\n return styles?.animationName || 'none';\n}\n\n// Before React 19 accessing `element.props.ref` will throw a warning and suggest using `element.ref`\n// After React 19 accessing `element.ref` does the opposite.\n// https://github.com/facebook/react/pull/28348\n//\n// Access the ref using the method that doesn't yield a warning.\nfunction getElementRef(element: React.ReactElement<{ ref?: React.Ref<unknown> }>) {\n // React <=18 in DEV\n let getter = Object.getOwnPropertyDescriptor(element.props, 'ref')?.get;\n let mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return (element as any).ref;\n }\n\n // React 19 in DEV\n getter = Object.getOwnPropertyDescriptor(element, 'ref')?.get;\n mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return element.props.ref;\n }\n\n // Not DEV\n return element.props.ref || (element as any).ref;\n}\n\nconst Root = Presence;\n\nexport {\n Presence,\n //\n Root,\n};\nexport type { PresenceProps };\n","import * as React from 'react';\n\ntype Machine<S> = { [k: string]: { [k: string]: S } };\ntype MachineState<T> = keyof T;\ntype MachineEvent<T> = keyof UnionToIntersection<T[keyof T]>;\n\n// 🤯 https://fettblog.eu/typescript-union-to-intersection/\ntype UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (x: infer R) => any\n ? R\n : never;\n\nexport function useStateMachine<M>(\n initialState: MachineState<M>,\n machine: M & Machine<MachineState<M>>\n) {\n return React.useReducer((state: MachineState<M>, event: MachineEvent<M>): MachineState<M> => {\n const nextState = (machine[state] as any)[event];\n return nextState ?? state;\n }, initialState);\n}\n","import * as React from 'react';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\n\n// Prevent bundlers from trying to optimize the import\nconst useInsertionEffect: typeof useLayoutEffect =\n (React as any)[' useInsertionEffect '.trim().toString()] || useLayoutEffect;\n\ntype ChangeHandler<T> = (state: T) => void;\ntype SetStateFn<T> = React.Dispatch<React.SetStateAction<T>>;\n\ninterface UseControllableStateParams<T> {\n prop?: T | undefined;\n defaultProp: T;\n onChange?: ChangeHandler<T>;\n caller?: string;\n}\n\nexport function useControllableState<T>({\n prop,\n defaultProp,\n onChange = () => {},\n caller,\n}: UseControllableStateParams<T>): [T, SetStateFn<T>] {\n const [uncontrolledProp, setUncontrolledProp, onChangeRef] = useUncontrolledState({\n defaultProp,\n onChange,\n });\n const isControlled = prop !== undefined;\n const value = isControlled ? prop : uncontrolledProp;\n\n // OK to disable conditionally calling hooks here because they will always run\n // consistently in the same environment. Bundlers should be able to remove the\n // code block entirely in production.\n /* eslint-disable react-hooks/rules-of-hooks */\n if (process.env.NODE_ENV !== 'production') {\n const isControlledRef = React.useRef(prop !== undefined);\n React.useEffect(() => {\n const wasControlled = isControlledRef.current;\n if (wasControlled !== isControlled) {\n const from = wasControlled ? 'controlled' : 'uncontrolled';\n const to = isControlled ? 'controlled' : 'uncontrolled';\n console.warn(\n `${caller} is changing from ${from} to ${to}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`\n );\n }\n isControlledRef.current = isControlled;\n }, [isControlled, caller]);\n }\n /* eslint-enable react-hooks/rules-of-hooks */\n\n const setValue = React.useCallback<SetStateFn<T>>(\n (nextValue) => {\n if (isControlled) {\n const value = isFunction(nextValue) ? nextValue(prop) : nextValue;\n if (value !== prop) {\n onChangeRef.current?.(value);\n }\n } else {\n setUncontrolledProp(nextValue);\n }\n },\n [isControlled, prop, setUncontrolledProp, onChangeRef]\n );\n\n return [value, setValue];\n}\n\nfunction useUncontrolledState<T>({\n defaultProp,\n onChange,\n}: Omit<UseControllableStateParams<T>, 'prop'>): [\n Value: T,\n setValue: React.Dispatch<React.SetStateAction<T>>,\n OnChangeRef: React.RefObject<ChangeHandler<T> | undefined>,\n] {\n const [value, setValue] = React.useState(defaultProp);\n const prevValueRef = React.useRef(value);\n\n const onChangeRef = React.useRef(onChange);\n useInsertionEffect(() => {\n onChangeRef.current = onChange;\n }, [onChange]);\n\n React.useEffect(() => {\n if (prevValueRef.current !== value) {\n onChangeRef.current?.(value);\n prevValueRef.current = value;\n }\n }, [value, prevValueRef]);\n\n return [value, setValue, onChangeRef];\n}\n\nfunction isFunction(value: unknown): value is (...args: any[]) => any {\n return typeof value === 'function';\n}\n","import * as React from 'react';\nimport { useEffectEvent } from '@radix-ui/react-use-effect-event';\n\ntype ChangeHandler<T> = (state: T) => void;\n\ninterface UseControllableStateParams<T> {\n prop: T | undefined;\n defaultProp: T;\n onChange: ChangeHandler<T> | undefined;\n caller: string;\n}\n\ninterface AnyAction {\n type: string;\n}\n\nconst SYNC_STATE = Symbol('RADIX:SYNC_STATE');\n\ninterface SyncStateAction<T> {\n type: typeof SYNC_STATE;\n state: T;\n}\n\nexport function useControllableStateReducer<T, S extends {}, A extends AnyAction>(\n reducer: (prevState: S & { state: T }, action: A) => S & { state: T },\n userArgs: UseControllableStateParams<T>,\n initialState: S\n): [S & { state: T }, React.Dispatch<A>];\n\nexport function useControllableStateReducer<T, S extends {}, I, A extends AnyAction>(\n reducer: (prevState: S & { state: T }, action: A) => S & { state: T },\n userArgs: UseControllableStateParams<T>,\n initialArg: I,\n init: (i: I & { state: T }) => S\n): [S & { state: T }, React.Dispatch<A>];\n\nexport function useControllableStateReducer<T, S extends {}, A extends AnyAction>(\n reducer: (prevState: S & { state: T }, action: A) => S & { state: T },\n userArgs: UseControllableStateParams<T>,\n initialArg: any,\n init?: (i: any) => Omit<S, 'state'>\n): [S & { state: T }, React.Dispatch<A>] {\n const { prop: controlledState, defaultProp, onChange: onChangeProp, caller } = userArgs;\n const isControlled = controlledState !== undefined;\n\n const onChange = useEffectEvent(onChangeProp);\n\n // OK to disable conditionally calling hooks here because they will always run\n // consistently in the same environment. Bundlers should be able to remove the\n // code block entirely in production.\n /* eslint-disable react-hooks/rules-of-hooks */\n if (process.env.NODE_ENV !== 'production') {\n const isControlledRef = React.useRef(controlledState !== undefined);\n React.useEffect(() => {\n const wasControlled = isControlledRef.current;\n if (wasControlled !== isControlled) {\n const from = wasControlled ? 'controlled' : 'uncontrolled';\n const to = isControlled ? 'controlled' : 'uncontrolled';\n console.warn(\n `${caller} is changing from ${from} to ${to}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`\n );\n }\n isControlledRef.current = isControlled;\n }, [isControlled, caller]);\n }\n /* eslint-enable react-hooks/rules-of-hooks */\n\n type InternalState = S & { state: T };\n const args: [InternalState] = [{ ...initialArg, state: defaultProp }];\n if (init) {\n // @ts-expect-error\n args.push(init);\n }\n\n const [internalState, dispatch] = React.useReducer(\n (state: InternalState, action: A | SyncStateAction<T>): InternalState => {\n if (action.type === SYNC_STATE) {\n return { ...state, state: action.state };\n }\n\n const next = reducer(state, action);\n if (isControlled && !Object.is(next.state, state.state)) {\n onChange(next.state);\n }\n return next;\n },\n ...args\n );\n\n const uncontrolledState = internalState.state;\n const prevValueRef = React.useRef(uncontrolledState);\n React.useEffect(() => {\n if (prevValueRef.current !== uncontrolledState) {\n prevValueRef.current = uncontrolledState;\n if (!isControlled) {\n onChange(uncontrolledState);\n }\n }\n }, [onChange, uncontrolledState, prevValueRef, isControlled]);\n\n const state = React.useMemo(() => {\n const isControlled = controlledState !== undefined;\n if (isControlled) {\n return { ...internalState, state: controlledState };\n }\n\n return internalState;\n }, [internalState, controlledState]);\n\n React.useEffect(() => {\n // Sync internal state for controlled components so that reducer is called\n // with the correct state values\n if (isControlled && !Object.is(controlledState, internalState.state)) {\n dispatch({ type: SYNC_STATE, state: controlledState });\n }\n }, [controlledState, internalState.state, isControlled]);\n\n return [state, dispatch as React.Dispatch<A>];\n}\n","import * as React from 'react';\nimport { Primitive } from '@radix-ui/react-primitive';\n\n/* -------------------------------------------------------------------------------------------------\n * VisuallyHidden\n * -----------------------------------------------------------------------------------------------*/\n\nconst VISUALLY_HIDDEN_STYLES = Object.freeze({\n // See: https://github.com/twbs/bootstrap/blob/main/scss/mixins/_visually-hidden.scss\n position: 'absolute',\n border: 0,\n width: 1,\n height: 1,\n padding: 0,\n margin: -1,\n overflow: 'hidden',\n clip: 'rect(0, 0, 0, 0)',\n whiteSpace: 'nowrap',\n wordWrap: 'normal',\n}) satisfies React.CSSProperties;\n\nconst NAME = 'VisuallyHidden';\n\ntype VisuallyHiddenElement = React.ComponentRef<typeof Primitive.span>;\ntype PrimitiveSpanProps = React.ComponentPropsWithoutRef<typeof Primitive.span>;\ninterface VisuallyHiddenProps extends PrimitiveSpanProps {}\n\nconst VisuallyHidden = React.forwardRef<VisuallyHiddenElement, VisuallyHiddenProps>(\n (props, forwardedRef) => {\n return (\n <Primitive.span\n {...props}\n ref={forwardedRef}\n style={{ ...VISUALLY_HIDDEN_STYLES, ...props.style }}\n />\n );\n }\n);\n\nVisuallyHidden.displayName = NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = VisuallyHidden;\n\nexport {\n VisuallyHidden,\n //\n Root,\n //\n VISUALLY_HIDDEN_STYLES,\n};\nexport type { VisuallyHiddenProps };\n","/**\n * Merges classes into a single string\n *\n * @param {array} classes\n * @returns {string} A string of classes\n */\nexport const mergeClasses = <ClassType = string | undefined | null>(...classes: ClassType[]) =>\n classes\n .filter((className, index, array) => {\n return (\n Boolean(className) &&\n (className as string).trim() !== '' &&\n array.indexOf(className) === index\n );\n })\n .join(' ')\n .trim();\n","/**\n * Converts string to kebab case\n *\n * @param {string} string\n * @returns {string} A kebabized string\n */\nexport const toKebabCase = (string: string) =>\n string.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n","/**\n * Converts string to camel case\n *\n * @param {string} string\n * @returns {string} A camelized string\n */\nexport const toCamelCase = <T extends string>(string: T) =>\n string.replace(/^([A-Z])|[\\s-_]+(\\w)/g, (match, p1, p2) =>\n p2 ? p2.toUpperCase() : p1.toLowerCase(),\n );\n","import { CamelToPascal } from '../utility-types';\nimport { toCamelCase } from './toCamelCase';\n\n/**\n * Converts string to pascal case\n *\n * @param {string} string\n * @returns {string} A pascalized string\n */\nexport const toPascalCase = <T extends string>(string: T): CamelToPascal<T> => {\n const camelCase = toCamelCase(string);\n\n return (camelCase.charAt(0).toUpperCase() + camelCase.slice(1)) as CamelToPascal<T>;\n};\n","export default {\n xmlns: 'http://www.w3.org/2000/svg',\n width: 24,\n height: 24,\n viewBox: '0 0 24 24',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 2,\n strokeLinecap: 'round',\n strokeLinejoin: 'round',\n};\n","/**\n * Check if a component has an accessibility prop\n *\n * @param {object} props\n * @returns {boolean} Whether the component has an accessibility prop\n */\nexport const hasA11yProp = (props: Record<string, any>) => {\n for (const prop in props) {\n if (prop.startsWith('aria-') || prop === 'role' || prop === 'title') {\n return true;\n }\n }\n\n return false;\n};\n","'use client';\n\nimport { createContext, createElement, type ReactNode, useContext, useMemo } from 'react';\nimport { LucideProps } from './types';\n\ntype LucideConfig = {\n size: number;\n color: string;\n strokeWidth: number;\n absoluteStrokeWidth: boolean;\n className: string;\n};\n\nconst LucideContext = createContext<LucideProps>({});\n\ntype LucideProviderProps = {\n children: ReactNode;\n} & Partial<LucideConfig>;\n\nexport function LucideProvider({\n children,\n size,\n color,\n strokeWidth,\n absoluteStrokeWidth,\n className,\n}: LucideProviderProps) {\n const value = useMemo(\n () => ({\n size,\n color,\n strokeWidth,\n absoluteStrokeWidth,\n className,\n }),\n [size, color, strokeWidth, absoluteStrokeWidth, className],\n );\n\n return createElement(LucideContext.Provider, { value }, children);\n}\n\nexport const useLucideContext = () => useContext(LucideContext);\n","'use client';\n\nimport { createElement, forwardRef } from 'react';\nimport defaultAttributes from './defaultAttributes';\nimport { IconNode, LucideProps } from './types';\nimport { mergeClasses, hasA11yProp } from '@lucide/shared';\nimport { useLucideContext } from './context';\n\ninterface IconComponentProps extends LucideProps {\n iconNode: IconNode;\n}\n\n/**\n * Lucide icon component\n *\n * @component Icon\n * @param {object} props\n * @param {string} props.color - The color of the icon\n * @param {number} props.size - The size of the icon\n * @param {number} props.strokeWidth - The stroke width of the icon\n * @param {boolean} props.absoluteStrokeWidth - Whether to use absolute stroke width\n * @param {string} props.className - The class name of the icon\n * @param {IconNode} props.children - The children of the icon\n * @param {IconNode} props.iconNode - The icon node of the icon\n *\n * @returns {ForwardRefExoticComponent} LucideIcon\n */\nconst Icon = forwardRef<SVGSVGElement, IconComponentProps>(\n (\n { color, size, strokeWidth, absoluteStrokeWidth, className = '', children, iconNode, ...rest },\n ref,\n ) => {\n const {\n size: contextSize = 24,\n strokeWidth: contextStrokeWidth = 2,\n absoluteStrokeWidth: contextAbsoluteStrokeWidth = false,\n color: contextColor = 'currentColor',\n className: contextClass = '',\n } = useLucideContext() ?? {};\n\n const calculatedStrokeWidth =\n absoluteStrokeWidth ?? contextAbsoluteStrokeWidth\n ? (Number(strokeWidth ?? contextStrokeWidth) * 24) / Number(size ?? contextSize)\n : strokeWidth ?? contextStrokeWidth;\n\n return createElement(\n 'svg',\n {\n ref,\n ...defaultAttributes,\n width: size ?? contextSize ?? defaultAttributes.width,\n height: size ?? contextSize ?? defaultAttributes.height,\n stroke: color ?? contextColor,\n strokeWidth: calculatedStrokeWidth,\n className: mergeClasses('lucide', contextClass, className),\n ...(!children && !hasA11yProp(rest) && { 'aria-hidden': 'true' }),\n ...rest,\n },\n [\n ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n ...(Array.isArray(children) ? children : [children]),\n ],\n );\n },\n);\n\nexport default Icon;\n","import { createElement, forwardRef } from 'react';\nimport { mergeClasses, toKebabCase, toPascalCase } from '@lucide/shared';\nimport { IconNode, LucideProps } from './types';\nimport Icon from './Icon';\n\n/**\n * Create a Lucide icon component\n * @param {string} iconName\n * @param {array} iconNode\n * @returns {ForwardRefExoticComponent} LucideIcon\n */\nconst createLucideIcon = (iconName: string, iconNode: IconNode) => {\n const Component = forwardRef<SVGSVGElement, LucideProps>(({ className, ...props }, ref) =>\n createElement(Icon, {\n ref,\n iconNode,\n className: mergeClasses(\n `lucide-${toKebabCase(toPascalCase(iconName))}`,\n `lucide-${iconName}`,\n className,\n ),\n ...props,\n }),\n );\n\n Component.displayName = toPascalCase(iconName);\n\n return Component;\n};\n\nexport default createLucideIcon;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [['path', { d: 'M20 6 9 17l-5-5', key: '1gmf2c' }]];\n\n/**\n * @component @name Check\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/check\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Check = createLucideIcon('check', __iconNode);\n\nexport default Check;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n ['circle', { cx: '12', cy: '12', r: '10', key: '1mglay' }],\n ['path', { d: 'm15 9-6 6', key: '1uzhvr' }],\n ['path', { d: 'm9 9 6 6', key: 'z0biqf' }],\n];\n\n/**\n * @component @name CircleX\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/circle-x\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst CircleX = createLucideIcon('circle-x', __iconNode);\n\nexport default CircleX;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n ['path', { d: 'M12 15V3', key: 'm9g1x1' }],\n ['path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4', key: 'ih7n3h' }],\n ['path', { d: 'm7 10 5 5 5-5', key: 'brsn70' }],\n];\n\n/**\n * @component @name Download\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/download\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Download = createLucideIcon('download', __iconNode);\n\nexport default Download;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n [\n 'path',\n {\n d: 'M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49',\n key: 'ct8e1f',\n },\n ],\n ['path', { d: 'M14.084 14.158a3 3 0 0 1-4.242-4.242', key: '151rxh' }],\n [\n 'path',\n {\n d: 'M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143',\n key: '13bj9a',\n },\n ],\n ['path', { d: 'm2 2 20 20', key: '1ooewy' }],\n];\n\n/**\n * @component @name EyeOff\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/eye-off\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst EyeOff = createLucideIcon('eye-off', __iconNode);\n\nexport default EyeOff;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n [\n 'path',\n {\n d: 'M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0',\n key: '1nclc0',\n },\n ],\n ['circle', { cx: '12', cy: '12', r: '3', key: '1v7zrd' }],\n];\n\n/**\n * @component @name Eye\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/eye\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Eye = createLucideIcon('eye', __iconNode);\n\nexport default Eye;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n [\n 'path',\n {\n d: 'M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z',\n key: '1oefj6',\n },\n ],\n ['path', { d: 'M14 2v5a1 1 0 0 0 1 1h5', key: 'wfsgrz' }],\n ['path', { d: 'M10 9H8', key: 'b1mrlr' }],\n ['path', { d: 'M16 13H8', key: 't4e002' }],\n ['path', { d: 'M16 17H8', key: 'z1uh3a' }],\n];\n\n/**\n * @component @name FileText\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/file-text\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst FileText = createLucideIcon('file-text', __iconNode);\n\nexport default FileText;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n ['circle', { cx: '12', cy: '12', r: '10', key: '1mglay' }],\n ['path', { d: 'M12 16v-4', key: '1dtifu' }],\n ['path', { d: 'M12 8h.01', key: 'e9boi3' }],\n];\n\n/**\n * @component @name Info\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/info\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Info = createLucideIcon('info', __iconNode);\n\nexport default Info;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n [\n 'path',\n {\n d: 'M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z',\n key: '18887p',\n },\n ],\n ['path', { d: 'M12 8v6', key: '1ib9pf' }],\n ['path', { d: 'M9 11h6', key: '1fldmi' }],\n];\n\n/**\n * @component @name MessageSquarePlus\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/message-square-plus\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst MessageSquarePlus = createLucideIcon('message-square-plus', __iconNode);\n\nexport default MessageSquarePlus;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n [\n 'path',\n {\n d: 'M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z',\n key: '18887p',\n },\n ],\n];\n\n/**\n * @component @name MessageSquare\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/message-square\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst MessageSquare = createLucideIcon('message-square', __iconNode);\n\nexport default MessageSquare;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n ['rect', { width: '20', height: '14', x: '2', y: '3', rx: '2', key: '48i651' }],\n ['line', { x1: '8', x2: '16', y1: '21', y2: '21', key: '1svkeh' }],\n ['line', { x1: '12', x2: '12', y1: '17', y2: '21', key: 'vw1qmm' }],\n];\n\n/**\n * @component @name Monitor\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/monitor\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Monitor = createLucideIcon('monitor', __iconNode);\n\nexport default Monitor;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n ['path', { d: 'm15 14 5-5-5-5', key: '12vg1m' }],\n ['path', { d: 'M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13', key: '6uklza' }],\n];\n\n/**\n * @component @name Redo2\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/redo-2\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Redo2 = createLucideIcon('redo-2', __iconNode);\n\nexport default Redo2;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n [\n 'path',\n {\n d: 'M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z',\n key: 'oel41y',\n },\n ],\n ['path', { d: 'M12 8v4', key: '1got3b' }],\n ['path', { d: 'M12 16h.01', key: '1drbdi' }],\n];\n\n/**\n * @component @name ShieldAlert\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/shield-alert\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst ShieldAlert = createLucideIcon('shield-alert', __iconNode);\n\nexport default ShieldAlert;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n [\n 'path',\n {\n d: 'M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z',\n key: 'oel41y',\n },\n ],\n ['path', { d: 'm9 12 2 2 4-4', key: 'dzmm74' }],\n];\n\n/**\n * @component @name ShieldCheck\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/shield-check\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst ShieldCheck = createLucideIcon('shield-check', __iconNode);\n\nexport default ShieldCheck;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n [\n 'path',\n {\n d: 'M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z',\n key: 'oel41y',\n },\n ],\n];\n\n/**\n * @component @name Shield\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/shield\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Shield = createLucideIcon('shield', __iconNode);\n\nexport default Shield;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n [\n 'path',\n {\n d: 'm21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3',\n key: 'wmoenq',\n },\n ],\n ['path', { d: 'M12 9v4', key: 'juzpu7' }],\n ['path', { d: 'M12 17h.01', key: 'p32p05' }],\n];\n\n/**\n * @component @name TriangleAlert\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/triangle-alert\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst TriangleAlert = createLucideIcon('triangle-alert', __iconNode);\n\nexport default TriangleAlert;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n ['path', { d: 'M9 14 4 9l5-5', key: '102s5s' }],\n ['path', { d: 'M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11', key: 'f3b9sd' }],\n];\n\n/**\n * @component @name Undo2\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/undo-2\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Undo2 = createLucideIcon('undo-2', __iconNode);\n\nexport default Undo2;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n ['path', { d: 'M18 6 6 18', key: '1bl5f8' }],\n ['path', { d: 'm6 6 12 12', key: 'd8bk6v' }],\n];\n\n/**\n * @component @name X\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview  - https://lucide.dev/icons/x\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst X = createLucideIcon('x', __iconNode);\n\nexport default X;\n","import React from \"react\";\nimport { AlertTriangle, XCircle } from \"lucide-react\";\n\nimport type { RuntimeRenderSnapshot } from \"../../api/public-types\";\n\nexport interface TwAlertBannerProps {\n snapshot: RuntimeRenderSnapshot;\n preserveOnlyCount: number;\n}\n\nexport function TwAlertBanner(props: TwAlertBannerProps) {\n const { snapshot, preserveOnlyCount } = props;\n\n if (snapshot.fatalError) {\n return (\n <div className=\"flex items-center gap-2 px-3 py-1.5 bg-danger-soft text-danger text-xs\">\n <XCircle className=\"h-3.5 w-3.5 shrink-0\" />\n <span>{snapshot.fatalError.message}</span>\n </div>\n );\n }\n\n if (snapshot.compatibility.blockExport) {\n return (\n <div className=\"flex items-center gap-2 px-3 py-1.5 bg-danger-soft text-danger text-xs\">\n <XCircle className=\"h-3.5 w-3.5 shrink-0\" />\n <span>\n Export blocked —{\" \"}\n {snapshot.compatibility.blockExportReasons[0] ?? \"unsupported content\"}\n </span>\n </div>\n );\n }\n\n if (preserveOnlyCount > 0) {\n return (\n <div className=\"flex items-center gap-2 px-3 py-1.5 bg-warning-soft text-comment text-xs\">\n <AlertTriangle className=\"h-3.5 w-3.5 shrink-0\" />\n <span>\n {preserveOnlyCount} preserve-only feature\n {preserveOnlyCount !== 1 ? \"s\" : \"\"} detected\n </span>\n </div>\n );\n }\n\n return null;\n}\n","import React from \"react\";\nimport * as Tooltip from \"@radix-ui/react-tooltip\";\nimport { MessageSquare } from \"lucide-react\";\n\nexport interface TwSelectionToolbarProps {\n selectionPreview: string;\n readOnly: boolean;\n onAddComment?: () => void;\n}\n\nconst focusRingClass =\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-canvas\";\n\nexport function TwSelectionToolbar(props: TwSelectionToolbarProps) {\n return (\n <div className=\"mb-6 inline-flex items-center gap-1 rounded-lg bg-canvas shadow-lg ring-1 ring-border p-1\">\n <Tooltip.Root>\n <Tooltip.Trigger asChild>\n <button\n type=\"button\"\n aria-label=\"Comment\"\n disabled={props.readOnly}\n onClick={props.onAddComment}\n className={`inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors text-accent hover:bg-accent-soft disabled:opacity-30 disabled:cursor-not-allowed ${focusRingClass}`}\n >\n <MessageSquare className=\"h-3.5 w-3.5\" />\n </button>\n </Tooltip.Trigger>\n <Tooltip.Portal>\n <Tooltip.Content\n className=\"rounded-md bg-primary px-2 py-1 text-xs text-white shadow-md z-50\"\n sideOffset={6}\n >\n Add comment\n </Tooltip.Content>\n </Tooltip.Portal>\n </Tooltip.Root>\n <div className=\"h-4 w-px bg-border mx-0.5\" />\n <span className=\"text-xs text-tertiary px-2 max-w-[200px] truncate\">\n {props.selectionPreview}\n </span>\n </div>\n );\n}\n","import * as React from 'react';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { createRovingFocusGroupScope } from '@radix-ui/react-roving-focus';\nimport { Presence } from '@radix-ui/react-presence';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport * as RovingFocusGroup from '@radix-ui/react-roving-focus';\nimport { useDirection } from '@radix-ui/react-direction';\nimport { useControllableState } from '@radix-ui/react-use-controllable-state';\nimport { useId } from '@radix-ui/react-id';\n\nimport type { Scope } from '@radix-ui/react-context';\n\n/* -------------------------------------------------------------------------------------------------\n * Tabs\n * -----------------------------------------------------------------------------------------------*/\n\nconst TABS_NAME = 'Tabs';\n\ntype ScopedProps<P> = P & { __scopeTabs?: Scope };\nconst [createTabsContext, createTabsScope] = createContextScope(TABS_NAME, [\n createRovingFocusGroupScope,\n]);\nconst useRovingFocusGroupScope = createRovingFocusGroupScope();\n\ntype TabsContextValue = {\n baseId: string;\n value: string;\n onValueChange: (value: string) => void;\n orientation?: TabsProps['orientation'];\n dir?: TabsProps['dir'];\n activationMode?: TabsProps['activationMode'];\n};\n\nconst [TabsProvider, useTabsContext] = createTabsContext<TabsContextValue>(TABS_NAME);\n\ntype TabsElement = React.ComponentRef<typeof Primitive.div>;\ntype RovingFocusGroupProps = React.ComponentPropsWithoutRef<typeof RovingFocusGroup.Root>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface TabsProps extends PrimitiveDivProps {\n /** The value for the selected tab, if controlled */\n value?: string;\n /** The value of the tab to select by default, if uncontrolled */\n defaultValue?: string;\n /** A function called when a new tab is selected */\n onValueChange?: (value: string) => void;\n /**\n * The orientation the tabs are layed out.\n * Mainly so arrow navigation is done accordingly (left & right vs. up & down)\n * @defaultValue horizontal\n */\n orientation?: RovingFocusGroupProps['orientation'];\n /**\n * The direction of navigation between toolbar items.\n */\n dir?: RovingFocusGroupProps['dir'];\n /**\n * Whether a tab is activated automatically or manually.\n * @defaultValue automatic\n * */\n activationMode?: 'automatic' | 'manual';\n}\n\nconst Tabs = React.forwardRef<TabsElement, TabsProps>(\n (props: ScopedProps<TabsProps>, forwardedRef) => {\n const {\n __scopeTabs,\n value: valueProp,\n onValueChange,\n defaultValue,\n orientation = 'horizontal',\n dir,\n activationMode = 'automatic',\n ...tabsProps\n } = props;\n const direction = useDirection(dir);\n const [value, setValue] = useControllableState({\n prop: valueProp,\n onChange: onValueChange,\n defaultProp: defaultValue ?? '',\n caller: TABS_NAME,\n });\n\n return (\n <TabsProvider\n scope={__scopeTabs}\n baseId={useId()}\n value={value}\n onValueChange={setValue}\n orientation={orientation}\n dir={direction}\n activationMode={activationMode}\n >\n <Primitive.div\n dir={direction}\n data-orientation={orientation}\n {...tabsProps}\n ref={forwardedRef}\n />\n </TabsProvider>\n );\n }\n);\n\nTabs.displayName = TABS_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TabsList\n * -----------------------------------------------------------------------------------------------*/\n\nconst TAB_LIST_NAME = 'TabsList';\n\ntype TabsListElement = React.ComponentRef<typeof Primitive.div>;\ninterface TabsListProps extends PrimitiveDivProps {\n loop?: RovingFocusGroupProps['loop'];\n}\n\nconst TabsList = React.forwardRef<TabsListElement, TabsListProps>(\n (props: ScopedProps<TabsListProps>, forwardedRef) => {\n const { __scopeTabs, loop = true, ...listProps } = props;\n const context = useTabsContext(TAB_LIST_NAME, __scopeTabs);\n const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeTabs);\n return (\n <RovingFocusGroup.Root\n asChild\n {...rovingFocusGroupScope}\n orientation={context.orientation}\n dir={context.dir}\n loop={loop}\n >\n <Primitive.div\n role=\"tablist\"\n aria-orientation={context.orientation}\n {...listProps}\n ref={forwardedRef}\n />\n </RovingFocusGroup.Root>\n );\n }\n);\n\nTabsList.displayName = TAB_LIST_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TabsTrigger\n * -----------------------------------------------------------------------------------------------*/\n\nconst TRIGGER_NAME = 'TabsTrigger';\n\ntype TabsTriggerElement = React.ComponentRef<typeof Primitive.button>;\ntype PrimitiveButtonProps = React.ComponentPropsWithoutRef<typeof Primitive.button>;\ninterface TabsTriggerProps extends PrimitiveButtonProps {\n value: string;\n}\n\nconst TabsTrigger = React.forwardRef<TabsTriggerElement, TabsTriggerProps>(\n (props: ScopedProps<TabsTriggerProps>, forwardedRef) => {\n const { __scopeTabs, value, disabled = false, ...triggerProps } = props;\n const context = useTabsContext(TRIGGER_NAME, __scopeTabs);\n const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeTabs);\n const triggerId = makeTriggerId(context.baseId, value);\n const contentId = makeContentId(context.baseId, value);\n const isSelected = value === context.value;\n return (\n <RovingFocusGroup.Item\n asChild\n {...rovingFocusGroupScope}\n focusable={!disabled}\n active={isSelected}\n >\n <Primitive.button\n type=\"button\"\n role=\"tab\"\n aria-selected={isSelected}\n aria-controls={contentId}\n data-state={isSelected ? 'active' : 'inactive'}\n data-disabled={disabled ? '' : undefined}\n disabled={disabled}\n id={triggerId}\n {...triggerProps}\n ref={forwardedRef}\n onMouseDown={composeEventHandlers(props.onMouseDown, (event) => {\n // only call handler if it's the left button (mousedown gets triggered by all mouse buttons)\n // but not when the control key is pressed (avoiding MacOS right click)\n if (!disabled && event.button === 0 && event.ctrlKey === false) {\n context.onValueChange(value);\n } else {\n // prevent focus to avoid accidental activation\n event.preventDefault();\n }\n })}\n onKeyDown={composeEventHandlers(props.onKeyDown, (event) => {\n if ([' ', 'Enter'].includes(event.key)) context.onValueChange(value);\n })}\n onFocus={composeEventHandlers(props.onFocus, () => {\n // handle \"automatic\" activation if necessary\n // ie. activate tab following focus\n const isAutomaticActivation = context.activationMode !== 'manual';\n if (!isSelected && !disabled && isAutomaticActivation) {\n context.onValueChange(value);\n }\n })}\n />\n </RovingFocusGroup.Item>\n );\n }\n);\n\nTabsTrigger.displayName = TRIGGER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TabsContent\n * -----------------------------------------------------------------------------------------------*/\n\nconst CONTENT_NAME = 'TabsContent';\n\ntype TabsContentElement = React.ComponentRef<typeof Primitive.div>;\ninterface TabsContentProps extends PrimitiveDivProps {\n value: string;\n\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst TabsContent = React.forwardRef<TabsContentElement, TabsContentProps>(\n (props: ScopedProps<TabsContentProps>, forwardedRef) => {\n const { __scopeTabs, value, forceMount, children, ...contentProps } = props;\n const context = useTabsContext(CONTENT_NAME, __scopeTabs);\n const triggerId = makeTriggerId(context.baseId, value);\n const contentId = makeContentId(context.baseId, value);\n const isSelected = value === context.value;\n const isMountAnimationPreventedRef = React.useRef(isSelected);\n\n React.useEffect(() => {\n const rAF = requestAnimationFrame(() => (isMountAnimationPreventedRef.current = false));\n return () => cancelAnimationFrame(rAF);\n }, []);\n\n return (\n <Presence present={forceMount || isSelected}>\n {({ present }) => (\n <Primitive.div\n data-state={isSelected ? 'active' : 'inactive'}\n data-orientation={context.orientation}\n role=\"tabpanel\"\n aria-labelledby={triggerId}\n hidden={!present}\n id={contentId}\n tabIndex={0}\n {...contentProps}\n ref={forwardedRef}\n style={{\n ...props.style,\n animationDuration: isMountAnimationPreventedRef.current ? '0s' : undefined,\n }}\n >\n {present && children}\n </Primitive.div>\n )}\n </Presence>\n );\n }\n);\n\nTabsContent.displayName = CONTENT_NAME;\n\n/* ---------------------------------------------------------------------------------------------- */\n\nfunction makeTriggerId(baseId: string, value: string) {\n return `${baseId}-trigger-${value}`;\n}\n\nfunction makeContentId(baseId: string, value: string) {\n return `${baseId}-content-${value}`;\n}\n\nconst Root = Tabs;\nconst List = TabsList;\nconst Trigger = TabsTrigger;\nconst Content = TabsContent;\n\nexport {\n createTabsScope,\n //\n Tabs,\n TabsList,\n TabsTrigger,\n TabsContent,\n //\n Root,\n List,\n Trigger,\n Content,\n};\nexport type { TabsProps, TabsListProps, TabsTriggerProps, TabsContentProps };\n","import * as React from 'react';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { createCollection } from '@radix-ui/react-collection';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { useId } from '@radix-ui/react-id';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\nimport { useControllableState } from '@radix-ui/react-use-controllable-state';\nimport { useDirection } from '@radix-ui/react-direction';\n\nimport type { Scope } from '@radix-ui/react-context';\n\nconst ENTRY_FOCUS = 'rovingFocusGroup.onEntryFocus';\nconst EVENT_OPTIONS = { bubbles: false, cancelable: true };\n\n/* -------------------------------------------------------------------------------------------------\n * RovingFocusGroup\n * -----------------------------------------------------------------------------------------------*/\n\nconst GROUP_NAME = 'RovingFocusGroup';\n\ntype ItemData = { id: string; focusable: boolean; active: boolean };\nconst [Collection, useCollection, createCollectionScope] = createCollection<\n HTMLSpanElement,\n ItemData\n>(GROUP_NAME);\n\ntype ScopedProps<P> = P & { __scopeRovingFocusGroup?: Scope };\nconst [createRovingFocusGroupContext, createRovingFocusGroupScope] = createContextScope(\n GROUP_NAME,\n [createCollectionScope]\n);\n\ntype Orientation = React.AriaAttributes['aria-orientation'];\ntype Direction = 'ltr' | 'rtl';\n\ninterface RovingFocusGroupOptions {\n /**\n * The orientation of the group.\n * Mainly so arrow navigation is done accordingly (left & right vs. up & down)\n */\n orientation?: Orientation;\n /**\n * The direction of navigation between items.\n */\n dir?: Direction;\n /**\n * Whether keyboard navigation should loop around\n * @defaultValue false\n */\n loop?: boolean;\n}\n\ntype RovingContextValue = RovingFocusGroupOptions & {\n currentTabStopId: string | null;\n onItemFocus(tabStopId: string): void;\n onItemShiftTab(): void;\n onFocusableItemAdd(): void;\n onFocusableItemRemove(): void;\n};\n\nconst [RovingFocusProvider, useRovingFocusContext] =\n createRovingFocusGroupContext<RovingContextValue>(GROUP_NAME);\n\ntype RovingFocusGroupElement = RovingFocusGroupImplElement;\ninterface RovingFocusGroupProps extends RovingFocusGroupImplProps {}\n\nconst RovingFocusGroup = React.forwardRef<RovingFocusGroupElement, RovingFocusGroupProps>(\n (props: ScopedProps<RovingFocusGroupProps>, forwardedRef) => {\n return (\n <Collection.Provider scope={props.__scopeRovingFocusGroup}>\n <Collection.Slot scope={props.__scopeRovingFocusGroup}>\n <RovingFocusGroupImpl {...props} ref={forwardedRef} />\n </Collection.Slot>\n </Collection.Provider>\n );\n }\n);\n\nRovingFocusGroup.displayName = GROUP_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype RovingFocusGroupImplElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface RovingFocusGroupImplProps\n extends Omit<PrimitiveDivProps, 'dir'>,\n RovingFocusGroupOptions {\n currentTabStopId?: string | null;\n defaultCurrentTabStopId?: string;\n onCurrentTabStopIdChange?: (tabStopId: string | null) => void;\n onEntryFocus?: (event: Event) => void;\n preventScrollOnEntryFocus?: boolean;\n}\n\nconst RovingFocusGroupImpl = React.forwardRef<\n RovingFocusGroupImplElement,\n RovingFocusGroupImplProps\n>((props: ScopedProps<RovingFocusGroupImplProps>, forwardedRef) => {\n const {\n __scopeRovingFocusGroup,\n orientation,\n loop = false,\n dir,\n currentTabStopId: currentTabStopIdProp,\n defaultCurrentTabStopId,\n onCurrentTabStopIdChange,\n onEntryFocus,\n preventScrollOnEntryFocus = false,\n ...groupProps\n } = props;\n const ref = React.useRef<RovingFocusGroupImplElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n const direction = useDirection(dir);\n const [currentTabStopId, setCurrentTabStopId] = useControllableState({\n prop: currentTabStopIdProp,\n defaultProp: defaultCurrentTabStopId ?? null,\n onChange: onCurrentTabStopIdChange,\n caller: GROUP_NAME,\n });\n const [isTabbingBackOut, setIsTabbingBackOut] = React.useState(false);\n const handleEntryFocus = useCallbackRef(onEntryFocus);\n const getItems = useCollection(__scopeRovingFocusGroup);\n const isClickFocusRef = React.useRef(false);\n const [focusableItemsCount, setFocusableItemsCount] = React.useState(0);\n\n React.useEffect(() => {\n const node = ref.current;\n if (node) {\n node.addEventListener(ENTRY_FOCUS, handleEntryFocus);\n return () => node.removeEventListener(ENTRY_FOCUS, handleEntryFocus);\n }\n }, [handleEntryFocus]);\n\n return (\n <RovingFocusProvider\n scope={__scopeRovingFocusGroup}\n orientation={orientation}\n dir={direction}\n loop={loop}\n currentTabStopId={currentTabStopId}\n onItemFocus={React.useCallback(\n (tabStopId) => setCurrentTabStopId(tabStopId),\n [setCurrentTabStopId]\n )}\n onItemShiftTab={React.useCallback(() => setIsTabbingBackOut(true), [])}\n onFocusableItemAdd={React.useCallback(\n () => setFocusableItemsCount((prevCount) => prevCount + 1),\n []\n )}\n onFocusableItemRemove={React.useCallback(\n () => setFocusableItemsCount((prevCount) => prevCount - 1),\n []\n )}\n >\n <Primitive.div\n tabIndex={isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0}\n data-orientation={orientation}\n {...groupProps}\n ref={composedRefs}\n style={{ outline: 'none', ...props.style }}\n onMouseDown={composeEventHandlers(props.onMouseDown, () => {\n isClickFocusRef.current = true;\n })}\n onFocus={composeEventHandlers(props.onFocus, (event) => {\n // We normally wouldn't need this check, because we already check\n // that the focus is on the current target and not bubbling to it.\n // We do this because Safari doesn't focus buttons when clicked, and\n // instead, the wrapper will get focused and not through a bubbling event.\n const isKeyboardFocus = !isClickFocusRef.current;\n\n if (event.target === event.currentTarget && isKeyboardFocus && !isTabbingBackOut) {\n const entryFocusEvent = new CustomEvent(ENTRY_FOCUS, EVENT_OPTIONS);\n event.currentTarget.dispatchEvent(entryFocusEvent);\n\n if (!entryFocusEvent.defaultPrevented) {\n const items = getItems().filter((item) => item.focusable);\n const activeItem = items.find((item) => item.active);\n const currentItem = items.find((item) => item.id === currentTabStopId);\n const candidateItems = [activeItem, currentItem, ...items].filter(\n Boolean\n ) as typeof items;\n const candidateNodes = candidateItems.map((item) => item.ref.current!);\n focusFirst(candidateNodes, preventScrollOnEntryFocus);\n }\n }\n\n isClickFocusRef.current = false;\n })}\n onBlur={composeEventHandlers(props.onBlur, () => setIsTabbingBackOut(false))}\n />\n </RovingFocusProvider>\n );\n});\n\n/* -------------------------------------------------------------------------------------------------\n * RovingFocusGroupItem\n * -----------------------------------------------------------------------------------------------*/\n\nconst ITEM_NAME = 'RovingFocusGroupItem';\n\ntype RovingFocusItemElement = React.ComponentRef<typeof Primitive.span>;\ntype PrimitiveSpanProps = React.ComponentPropsWithoutRef<typeof Primitive.span>;\ninterface RovingFocusItemProps extends Omit<PrimitiveSpanProps, 'children'> {\n tabStopId?: string;\n focusable?: boolean;\n active?: boolean;\n children?:\n | React.ReactNode\n | ((props: { hasTabStop: boolean; isCurrentTabStop: boolean }) => React.ReactNode);\n}\n\nconst RovingFocusGroupItem = React.forwardRef<RovingFocusItemElement, RovingFocusItemProps>(\n (props: ScopedProps<RovingFocusItemProps>, forwardedRef) => {\n const {\n __scopeRovingFocusGroup,\n focusable = true,\n active = false,\n tabStopId,\n children,\n ...itemProps\n } = props;\n const autoId = useId();\n const id = tabStopId || autoId;\n const context = useRovingFocusContext(ITEM_NAME, __scopeRovingFocusGroup);\n const isCurrentTabStop = context.currentTabStopId === id;\n const getItems = useCollection(__scopeRovingFocusGroup);\n\n const { onFocusableItemAdd, onFocusableItemRemove, currentTabStopId } = context;\n\n React.useEffect(() => {\n if (focusable) {\n onFocusableItemAdd();\n return () => onFocusableItemRemove();\n }\n }, [focusable, onFocusableItemAdd, onFocusableItemRemove]);\n\n return (\n <Collection.ItemSlot\n scope={__scopeRovingFocusGroup}\n id={id}\n focusable={focusable}\n active={active}\n >\n <Primitive.span\n tabIndex={isCurrentTabStop ? 0 : -1}\n data-orientation={context.orientation}\n {...itemProps}\n ref={forwardedRef}\n onMouseDown={composeEventHandlers(props.onMouseDown, (event) => {\n // We prevent focusing non-focusable items on `mousedown`.\n // Even though the item has tabIndex={-1}, that only means take it out of the tab order.\n if (!focusable) event.preventDefault();\n // Safari doesn't focus a button when clicked so we run our logic on mousedown also\n else context.onItemFocus(id);\n })}\n onFocus={composeEventHandlers(props.onFocus, () => context.onItemFocus(id))}\n onKeyDown={composeEventHandlers(props.onKeyDown, (event) => {\n if (event.key === 'Tab' && event.shiftKey) {\n context.onItemShiftTab();\n return;\n }\n\n if (event.target !== event.currentTarget) return;\n\n const focusIntent = getFocusIntent(event, context.orientation, context.dir);\n\n if (focusIntent !== undefined) {\n if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;\n event.preventDefault();\n const items = getItems().filter((item) => item.focusable);\n let candidateNodes = items.map((item) => item.ref.current!);\n\n if (focusIntent === 'last') candidateNodes.reverse();\n else if (focusIntent === 'prev' || focusIntent === 'next') {\n if (focusIntent === 'prev') candidateNodes.reverse();\n const currentIndex = candidateNodes.indexOf(event.currentTarget);\n candidateNodes = context.loop\n ? wrapArray(candidateNodes, currentIndex + 1)\n : candidateNodes.slice(currentIndex + 1);\n }\n\n /**\n * Imperative focus during keydown is risky so we prevent React's batching updates\n * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332\n */\n setTimeout(() => focusFirst(candidateNodes));\n }\n })}\n >\n {typeof children === 'function'\n ? children({ isCurrentTabStop, hasTabStop: currentTabStopId != null })\n : children}\n </Primitive.span>\n </Collection.ItemSlot>\n );\n }\n);\n\nRovingFocusGroupItem.displayName = ITEM_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\n// prettier-ignore\nconst MAP_KEY_TO_FOCUS_INTENT: Record<string, FocusIntent> = {\n ArrowLeft: 'prev', ArrowUp: 'prev',\n ArrowRight: 'next', ArrowDown: 'next',\n PageUp: 'first', Home: 'first',\n PageDown: 'last', End: 'last',\n};\n\nfunction getDirectionAwareKey(key: string, dir?: Direction) {\n if (dir !== 'rtl') return key;\n return key === 'ArrowLeft' ? 'ArrowRight' : key === 'ArrowRight' ? 'ArrowLeft' : key;\n}\n\ntype FocusIntent = 'first' | 'last' | 'prev' | 'next';\n\nfunction getFocusIntent(event: React.KeyboardEvent, orientation?: Orientation, dir?: Direction) {\n const key = getDirectionAwareKey(event.key, dir);\n if (orientation === 'vertical' && ['ArrowLeft', 'ArrowRight'].includes(key)) return undefined;\n if (orientation === 'horizontal' && ['ArrowUp', 'ArrowDown'].includes(key)) return undefined;\n return MAP_KEY_TO_FOCUS_INTENT[key];\n}\n\nfunction focusFirst(candidates: HTMLElement[], preventScroll = false) {\n const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;\n for (const candidate of candidates) {\n // if focus is already where we want to go, we don't want to keep going through the candidates\n if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return;\n candidate.focus({ preventScroll });\n if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return;\n }\n}\n\n/**\n * Wraps an array around itself at a given start index\n * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']`\n */\nfunction wrapArray<T>(array: T[], startIndex: number) {\n return array.map<T>((_, index) => array[(startIndex + index) % array.length]!);\n}\n\nconst Root = RovingFocusGroup;\nconst Item = RovingFocusGroupItem;\n\nexport {\n createRovingFocusGroupScope,\n //\n RovingFocusGroup,\n RovingFocusGroupItem,\n //\n Root,\n Item,\n};\nexport type { RovingFocusGroupProps, RovingFocusItemProps };\n","import React from 'react';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { createSlot, type Slot } from '@radix-ui/react-slot';\n\ntype SlotProps = React.ComponentPropsWithoutRef<typeof Slot>;\ntype CollectionElement = HTMLElement;\ninterface CollectionProps extends SlotProps {\n scope: any;\n}\n\n// We have resorted to returning slots directly rather than exposing primitives that can then\n// be slotted like `<CollectionItem as={Slot}>…</CollectionItem>`.\n// This is because we encountered issues with generic types that cannot be statically analysed\n// due to creating them dynamically via createCollection.\n\nfunction createCollection<ItemElement extends HTMLElement, ItemData = {}>(name: string) {\n /* -----------------------------------------------------------------------------------------------\n * CollectionProvider\n * ---------------------------------------------------------------------------------------------*/\n\n const PROVIDER_NAME = name + 'CollectionProvider';\n const [createCollectionContext, createCollectionScope] = createContextScope(PROVIDER_NAME);\n\n type ContextValue = {\n collectionRef: React.RefObject<CollectionElement | null>;\n itemMap: Map<\n React.RefObject<ItemElement | null>,\n { ref: React.RefObject<ItemElement | null> } & ItemData\n >;\n };\n\n const [CollectionProviderImpl, useCollectionContext] = createCollectionContext<ContextValue>(\n PROVIDER_NAME,\n { collectionRef: { current: null }, itemMap: new Map() }\n );\n\n const CollectionProvider: React.FC<{ children?: React.ReactNode; scope: any }> = (props) => {\n const { scope, children } = props;\n const ref = React.useRef<CollectionElement>(null);\n const itemMap = React.useRef<ContextValue['itemMap']>(new Map()).current;\n return (\n <CollectionProviderImpl scope={scope} itemMap={itemMap} collectionRef={ref}>\n {children}\n </CollectionProviderImpl>\n );\n };\n\n CollectionProvider.displayName = PROVIDER_NAME;\n\n /* -----------------------------------------------------------------------------------------------\n * CollectionSlot\n * ---------------------------------------------------------------------------------------------*/\n\n const COLLECTION_SLOT_NAME = name + 'CollectionSlot';\n\n const CollectionSlotImpl = createSlot(COLLECTION_SLOT_NAME);\n const CollectionSlot = React.forwardRef<CollectionElement, CollectionProps>(\n (props, forwardedRef) => {\n const { scope, children } = props;\n const context = useCollectionContext(COLLECTION_SLOT_NAME, scope);\n const composedRefs = useComposedRefs(forwardedRef, context.collectionRef);\n return <CollectionSlotImpl ref={composedRefs}>{children}</CollectionSlotImpl>;\n }\n );\n\n CollectionSlot.displayName = COLLECTION_SLOT_NAME;\n\n /* -----------------------------------------------------------------------------------------------\n * CollectionItem\n * ---------------------------------------------------------------------------------------------*/\n\n const ITEM_SLOT_NAME = name + 'CollectionItemSlot';\n const ITEM_DATA_ATTR = 'data-radix-collection-item';\n\n type CollectionItemSlotProps = ItemData & {\n children: React.ReactNode;\n scope: any;\n };\n\n const CollectionItemSlotImpl = createSlot(ITEM_SLOT_NAME);\n const CollectionItemSlot = React.forwardRef<ItemElement, CollectionItemSlotProps>(\n (props, forwardedRef) => {\n const { scope, children, ...itemData } = props;\n const ref = React.useRef<ItemElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n const context = useCollectionContext(ITEM_SLOT_NAME, scope);\n\n React.useEffect(() => {\n context.itemMap.set(ref, { ref, ...(itemData as unknown as ItemData) });\n return () => void context.itemMap.delete(ref);\n });\n\n return (\n <CollectionItemSlotImpl {...{ [ITEM_DATA_ATTR]: '' }} ref={composedRefs}>\n {children}\n </CollectionItemSlotImpl>\n );\n }\n );\n\n CollectionItemSlot.displayName = ITEM_SLOT_NAME;\n\n /* -----------------------------------------------------------------------------------------------\n * useCollection\n * ---------------------------------------------------------------------------------------------*/\n\n function useCollection(scope: any) {\n const context = useCollectionContext(name + 'CollectionConsumer', scope);\n\n const getItems = React.useCallback(() => {\n const collectionNode = context.collectionRef.current;\n if (!collectionNode) return [];\n const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`));\n const items = Array.from(context.itemMap.values());\n const orderedItems = items.sort(\n (a, b) => orderedNodes.indexOf(a.ref.current!) - orderedNodes.indexOf(b.ref.current!)\n );\n return orderedItems;\n }, [context.collectionRef, context.itemMap]);\n\n return getItems;\n }\n\n return [\n { Provider: CollectionProvider, Slot: CollectionSlot, ItemSlot: CollectionItemSlot },\n useCollection,\n createCollectionScope,\n ] as const;\n}\n\nexport { createCollection };\nexport type { CollectionProps };\n","import React from 'react';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { createSlot, type Slot } from '@radix-ui/react-slot';\nimport type { EntryOf } from './ordered-dictionary';\nimport { OrderedDict } from './ordered-dictionary';\n\ntype SlotProps = React.ComponentPropsWithoutRef<typeof Slot>;\ntype CollectionElement = HTMLElement;\ninterface CollectionProps extends SlotProps {\n scope: any;\n}\n\ninterface BaseItemData {\n id?: string;\n}\n\ntype ItemDataWithElement<\n ItemData extends BaseItemData,\n ItemElement extends HTMLElement,\n> = ItemData & {\n element: ItemElement;\n};\n\ntype ItemMap<ItemElement extends HTMLElement, ItemData extends BaseItemData> = OrderedDict<\n ItemElement,\n ItemDataWithElement<ItemData, ItemElement>\n>;\n\nfunction createCollection<\n ItemElement extends HTMLElement,\n ItemData extends BaseItemData = BaseItemData,\n>(name: string) {\n /* -----------------------------------------------------------------------------------------------\n * CollectionProvider\n * ---------------------------------------------------------------------------------------------*/\n\n const PROVIDER_NAME = name + 'CollectionProvider';\n const [createCollectionContext, createCollectionScope] = createContextScope(PROVIDER_NAME);\n\n type ContextValue = {\n collectionElement: CollectionElement | null;\n collectionRef: React.Ref<CollectionElement | null>;\n collectionRefObject: React.RefObject<CollectionElement | null>;\n itemMap: ItemMap<ItemElement, ItemData>;\n setItemMap: React.Dispatch<React.SetStateAction<ItemMap<ItemElement, ItemData>>>;\n };\n\n const [CollectionContextProvider, useCollectionContext] = createCollectionContext<ContextValue>(\n PROVIDER_NAME,\n {\n collectionElement: null,\n collectionRef: { current: null },\n collectionRefObject: { current: null },\n itemMap: new OrderedDict(),\n setItemMap: () => void 0,\n }\n );\n\n type CollectionState = [\n ItemMap: ItemMap<ItemElement, ItemData>,\n SetItemMap: React.Dispatch<React.SetStateAction<ItemMap<ItemElement, ItemData>>>,\n ];\n\n const CollectionProvider: React.FC<{\n children?: React.ReactNode;\n scope: any;\n state?: CollectionState;\n }> = ({ state, ...props }) => {\n return state ? (\n <CollectionProviderImpl {...props} state={state} />\n ) : (\n <CollectionInit {...props} />\n );\n };\n CollectionProvider.displayName = PROVIDER_NAME;\n\n const CollectionInit: React.FC<{\n children?: React.ReactNode;\n scope: any;\n }> = (props) => {\n const state = useInitCollection();\n return <CollectionProviderImpl {...props} state={state} />;\n };\n CollectionInit.displayName = PROVIDER_NAME + 'Init';\n\n const CollectionProviderImpl: React.FC<{\n children?: React.ReactNode;\n scope: any;\n state: CollectionState;\n }> = (props) => {\n const { scope, children, state } = props;\n const ref = React.useRef<CollectionElement>(null);\n const [collectionElement, setCollectionElement] = React.useState<CollectionElement | null>(\n null\n );\n const composeRefs = useComposedRefs(ref, setCollectionElement);\n const [itemMap, setItemMap] = state;\n\n React.useEffect(() => {\n if (!collectionElement) return;\n\n const observer = getChildListObserver(() => {\n // setItemMap((map) => {\n // const copy = new OrderedDict(map).toSorted(([, a], [, b]) =>\n // !a.element || !b.element ? 0 : isElementPreceding(a.element, b.element) ? -1 : 1\n // );\n // // check if the order has changed\n // let index = -1;\n // for (const entry of copy) {\n // index++;\n // const key = map.keyAt(index)!;\n // const [copyKey] = entry;\n // if (key !== copyKey) {\n // // order has changed!\n // return copy;\n // }\n // }\n // return map;\n // });\n });\n observer.observe(collectionElement, {\n childList: true,\n subtree: true,\n });\n return () => {\n observer.disconnect();\n };\n }, [collectionElement]);\n\n return (\n <CollectionContextProvider\n scope={scope}\n itemMap={itemMap}\n setItemMap={setItemMap}\n collectionRef={composeRefs}\n collectionRefObject={ref}\n collectionElement={collectionElement}\n >\n {children}\n </CollectionContextProvider>\n );\n };\n\n CollectionProviderImpl.displayName = PROVIDER_NAME + 'Impl';\n\n /* -----------------------------------------------------------------------------------------------\n * CollectionSlot\n * ---------------------------------------------------------------------------------------------*/\n\n const COLLECTION_SLOT_NAME = name + 'CollectionSlot';\n\n const CollectionSlotImpl = createSlot(COLLECTION_SLOT_NAME);\n const CollectionSlot = React.forwardRef<CollectionElement, CollectionProps>(\n (props, forwardedRef) => {\n const { scope, children } = props;\n const context = useCollectionContext(COLLECTION_SLOT_NAME, scope);\n const composedRefs = useComposedRefs(forwardedRef, context.collectionRef);\n return <CollectionSlotImpl ref={composedRefs}>{children}</CollectionSlotImpl>;\n }\n );\n\n CollectionSlot.displayName = COLLECTION_SLOT_NAME;\n\n /* -----------------------------------------------------------------------------------------------\n * CollectionItem\n * ---------------------------------------------------------------------------------------------*/\n\n const ITEM_SLOT_NAME = name + 'CollectionItemSlot';\n const ITEM_DATA_ATTR = 'data-radix-collection-item';\n\n type CollectionItemSlotProps = ItemData & {\n children: React.ReactNode;\n scope: any;\n };\n\n const CollectionItemSlotImpl = createSlot(ITEM_SLOT_NAME);\n const CollectionItemSlot = React.forwardRef<ItemElement, CollectionItemSlotProps>(\n (props, forwardedRef) => {\n const { scope, children, ...itemData } = props;\n const ref = React.useRef<ItemElement>(null);\n const [element, setElement] = React.useState<ItemElement | null>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref, setElement);\n const context = useCollectionContext(ITEM_SLOT_NAME, scope);\n\n const { setItemMap } = context;\n\n const itemDataRef = React.useRef(itemData);\n if (!shallowEqual(itemDataRef.current, itemData)) {\n itemDataRef.current = itemData;\n }\n const memoizedItemData = itemDataRef.current;\n\n React.useEffect(() => {\n const itemData = memoizedItemData;\n setItemMap((map) => {\n if (!element) {\n return map;\n }\n\n if (!map.has(element)) {\n map.set(element, { ...(itemData as unknown as ItemData), element });\n return map.toSorted(sortByDocumentPosition);\n }\n\n return map\n .set(element, { ...(itemData as unknown as ItemData), element })\n .toSorted(sortByDocumentPosition);\n });\n\n return () => {\n setItemMap((map) => {\n if (!element || !map.has(element)) {\n return map;\n }\n map.delete(element);\n return new OrderedDict(map);\n });\n };\n }, [element, memoizedItemData, setItemMap]);\n\n return (\n <CollectionItemSlotImpl {...{ [ITEM_DATA_ATTR]: '' }} ref={composedRefs as any}>\n {children}\n </CollectionItemSlotImpl>\n );\n }\n );\n\n CollectionItemSlot.displayName = ITEM_SLOT_NAME;\n\n /* -----------------------------------------------------------------------------------------------\n * useInitCollection\n * ---------------------------------------------------------------------------------------------*/\n\n function useInitCollection() {\n return React.useState<ItemMap<ItemElement, ItemData>>(new OrderedDict());\n }\n\n /* -----------------------------------------------------------------------------------------------\n * useCollection\n * ---------------------------------------------------------------------------------------------*/\n\n function useCollection(scope: any) {\n const { itemMap } = useCollectionContext(name + 'CollectionConsumer', scope);\n\n return itemMap;\n }\n\n const functions = {\n createCollectionScope,\n useCollection,\n useInitCollection,\n };\n\n return [\n { Provider: CollectionProvider, Slot: CollectionSlot, ItemSlot: CollectionItemSlot },\n functions,\n ] as const;\n}\n\nexport { createCollection };\nexport type { CollectionProps };\n\nfunction shallowEqual(a: any, b: any) {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object') return false;\n if (a == null || b == null) return false;\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n for (const key of keysA) {\n if (!Object.prototype.hasOwnProperty.call(b, key)) return false;\n if (a[key] !== b[key]) return false;\n }\n return true;\n}\n\nfunction isElementPreceding(a: Element, b: Element) {\n return !!(b.compareDocumentPosition(a) & Node.DOCUMENT_POSITION_PRECEDING);\n}\n\nfunction sortByDocumentPosition<E extends HTMLElement, T extends BaseItemData>(\n a: EntryOf<ItemMap<E, T>>,\n b: EntryOf<ItemMap<E, T>>\n) {\n return !a[1].element || !b[1].element\n ? 0\n : isElementPreceding(a[1].element, b[1].element)\n ? -1\n : 1;\n}\n\nfunction getChildListObserver(callback: () => void) {\n const observer = new MutationObserver((mutationsList) => {\n for (const mutation of mutationsList) {\n if (mutation.type === 'childList') {\n callback();\n return;\n }\n }\n });\n\n return observer;\n}\n","// Not a real member because it shouldn't be accessible, but the super class\n// calls `set` which needs to read the instanciation state, so it can't be a\n// private member.\nconst __instanciated = new WeakMap<OrderedDict<any, any>, boolean>();\nexport class OrderedDict<K, V> extends Map<K, V> {\n #keys: K[];\n\n constructor(iterable?: Iterable<readonly [K, V]> | null | undefined);\n constructor(entries?: readonly (readonly [K, V])[] | null) {\n super(entries);\n this.#keys = [...super.keys()];\n __instanciated.set(this, true);\n }\n\n set(key: K, value: V) {\n if (__instanciated.get(this)) {\n if (this.has(key)) {\n this.#keys[this.#keys.indexOf(key)] = key;\n } else {\n this.#keys.push(key);\n }\n }\n super.set(key, value);\n return this;\n }\n\n insert(index: number, key: K, value: V) {\n const has = this.has(key);\n const length = this.#keys.length;\n const relativeIndex = toSafeInteger(index);\n let actualIndex = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;\n const safeIndex = actualIndex < 0 || actualIndex >= length ? -1 : actualIndex;\n\n if (safeIndex === this.size || (has && safeIndex === this.size - 1) || safeIndex === -1) {\n this.set(key, value);\n return this;\n }\n\n const size = this.size + (has ? 0 : 1);\n\n // If you insert at, say, -2, without this bit you'd replace the\n // second-to-last item and push the rest up one, which means the new item is\n // 3rd to last. This isn't very intuitive; inserting at -2 is more like\n // saying \"make this item the second to last\".\n if (relativeIndex < 0) {\n actualIndex++;\n }\n\n const keys = [...this.#keys];\n let nextValue: V | undefined;\n let shouldSkip = false;\n for (let i = actualIndex; i < size; i++) {\n if (actualIndex === i) {\n let nextKey = keys[i]!;\n if (keys[i] === key) {\n nextKey = keys[i + 1]!;\n }\n if (has) {\n // delete first to ensure that the item is moved to the end\n this.delete(key);\n }\n nextValue = this.get(nextKey);\n this.set(key, value);\n } else {\n if (!shouldSkip && keys[i - 1] === key) {\n shouldSkip = true;\n }\n const currentKey = keys[shouldSkip ? i : i - 1]!;\n const currentValue = nextValue!;\n nextValue = this.get(currentKey);\n this.delete(currentKey);\n this.set(currentKey, currentValue);\n }\n }\n return this;\n }\n\n with(index: number, key: K, value: V) {\n const copy = new OrderedDict(this);\n copy.insert(index, key, value);\n return copy;\n }\n\n before(key: K) {\n const index = this.#keys.indexOf(key) - 1;\n if (index < 0) {\n return undefined;\n }\n return this.entryAt(index);\n }\n\n /**\n * Sets a new key-value pair at the position before the given key.\n */\n setBefore(key: K, newKey: K, value: V) {\n const index = this.#keys.indexOf(key);\n if (index === -1) {\n return this;\n }\n return this.insert(index, newKey, value);\n }\n\n after(key: K) {\n let index = this.#keys.indexOf(key);\n index = index === -1 || index === this.size - 1 ? -1 : index + 1;\n if (index === -1) {\n return undefined;\n }\n return this.entryAt(index);\n }\n\n /**\n * Sets a new key-value pair at the position after the given key.\n */\n setAfter(key: K, newKey: K, value: V) {\n const index = this.#keys.indexOf(key);\n if (index === -1) {\n return this;\n }\n return this.insert(index + 1, newKey, value);\n }\n\n first() {\n return this.entryAt(0);\n }\n\n last() {\n return this.entryAt(-1);\n }\n\n clear() {\n this.#keys = [];\n return super.clear();\n }\n\n delete(key: K) {\n const deleted = super.delete(key);\n if (deleted) {\n this.#keys.splice(this.#keys.indexOf(key), 1);\n }\n return deleted;\n }\n\n deleteAt(index: number) {\n const key = this.keyAt(index);\n if (key !== undefined) {\n return this.delete(key);\n }\n return false;\n }\n\n at(index: number) {\n const key = at(this.#keys, index);\n if (key !== undefined) {\n return this.get(key);\n }\n }\n\n entryAt(index: number): [K, V] | undefined {\n const key = at(this.#keys, index);\n if (key !== undefined) {\n return [key, this.get(key)!];\n }\n }\n\n indexOf(key: K) {\n return this.#keys.indexOf(key);\n }\n\n keyAt(index: number) {\n return at(this.#keys, index);\n }\n\n from(key: K, offset: number) {\n const index = this.indexOf(key);\n if (index === -1) {\n return undefined;\n }\n let dest = index + offset;\n if (dest < 0) dest = 0;\n if (dest >= this.size) dest = this.size - 1;\n return this.at(dest);\n }\n\n keyFrom(key: K, offset: number) {\n const index = this.indexOf(key);\n if (index === -1) {\n return undefined;\n }\n let dest = index + offset;\n if (dest < 0) dest = 0;\n if (dest >= this.size) dest = this.size - 1;\n return this.keyAt(dest);\n }\n\n find(\n predicate: (entry: [K, V], index: number, dictionary: OrderedDict<K, V>) => boolean,\n thisArg?: any\n ) {\n let index = 0;\n for (const entry of this) {\n if (Reflect.apply(predicate, thisArg, [entry, index, this])) {\n return entry;\n }\n index++;\n }\n return undefined;\n }\n\n findIndex(\n predicate: (entry: [K, V], index: number, dictionary: OrderedDict<K, V>) => boolean,\n thisArg?: any\n ) {\n let index = 0;\n for (const entry of this) {\n if (Reflect.apply(predicate, thisArg, [entry, index, this])) {\n return index;\n }\n index++;\n }\n return -1;\n }\n\n filter<KK extends K, VV extends V>(\n predicate: (entry: [K, V], index: number, dict: OrderedDict<K, V>) => entry is [KK, VV],\n thisArg?: any\n ): OrderedDict<KK, VV>;\n\n filter(\n predicate: (entry: [K, V], index: number, dictionary: OrderedDict<K, V>) => unknown,\n thisArg?: any\n ): OrderedDict<K, V>;\n\n filter(\n predicate: (entry: [K, V], index: number, dictionary: OrderedDict<K, V>) => unknown,\n thisArg?: any\n ) {\n const entries: Array<[K, V]> = [];\n let index = 0;\n for (const entry of this) {\n if (Reflect.apply(predicate, thisArg, [entry, index, this])) {\n entries.push(entry);\n }\n index++;\n }\n return new OrderedDict(entries);\n }\n\n map<U>(\n callbackfn: (entry: [K, V], index: number, dictionary: OrderedDict<K, V>) => U,\n thisArg?: any\n ): OrderedDict<K, U> {\n const entries: [K, U][] = [];\n let index = 0;\n for (const entry of this) {\n entries.push([entry[0], Reflect.apply(callbackfn, thisArg, [entry, index, this])]);\n index++;\n }\n return new OrderedDict(entries);\n }\n\n reduce(\n callbackfn: (\n previousValue: [K, V],\n currentEntry: [K, V],\n currentIndex: number,\n dictionary: OrderedDict<K, V>\n ) => [K, V]\n ): [K, V];\n reduce(\n callbackfn: (\n previousValue: [K, V],\n currentEntry: [K, V],\n currentIndex: number,\n dictionary: OrderedDict<K, V>\n ) => [K, V],\n initialValue: [K, V]\n ): [K, V];\n reduce<U>(\n callbackfn: (\n previousValue: U,\n currentEntry: [K, V],\n currentIndex: number,\n dictionary: OrderedDict<K, V>\n ) => U,\n initialValue: U\n ): U;\n\n reduce<U>(\n ...args: [\n (\n previousValue: U,\n currentEntry: [K, V],\n currentIndex: number,\n dictionary: OrderedDict<K, V>\n ) => U,\n U?,\n ]\n ) {\n const [callbackfn, initialValue] = args;\n let index = 0;\n let accumulator = initialValue ?? this.at(0)!;\n for (const entry of this) {\n if (index === 0 && args.length === 1) {\n accumulator = entry as any;\n } else {\n accumulator = Reflect.apply(callbackfn, this, [accumulator, entry, index, this]);\n }\n index++;\n }\n return accumulator;\n }\n\n reduceRight(\n callbackfn: (\n previousValue: [K, V],\n currentEntry: [K, V],\n currentIndex: number,\n dictionary: OrderedDict<K, V>\n ) => [K, V]\n ): [K, V];\n reduceRight(\n callbackfn: (\n previousValue: [K, V],\n currentEntry: [K, V],\n currentIndex: number,\n dictionary: OrderedDict<K, V>\n ) => [K, V],\n initialValue: [K, V]\n ): [K, V];\n reduceRight<U>(\n callbackfn: (\n previousValue: [K, V],\n currentValue: U,\n currentIndex: number,\n dictionary: OrderedDict<K, V>\n ) => U,\n initialValue: U\n ): U;\n\n reduceRight<U>(\n ...args: [\n (\n previousValue: U,\n currentEntry: [K, V],\n currentIndex: number,\n dictionary: OrderedDict<K, V>\n ) => U,\n U?,\n ]\n ) {\n const [callbackfn, initialValue] = args;\n let accumulator = initialValue ?? this.at(-1)!;\n for (let index = this.size - 1; index >= 0; index--) {\n const entry = this.at(index)!;\n if (index === this.size - 1 && args.length === 1) {\n accumulator = entry as any;\n } else {\n accumulator = Reflect.apply(callbackfn, this, [accumulator, entry, index, this]);\n }\n }\n return accumulator;\n }\n\n toSorted(compareFn?: (a: [K, V], b: [K, V]) => number): OrderedDict<K, V> {\n const entries = [...this.entries()].sort(compareFn);\n return new OrderedDict(entries);\n }\n\n toReversed(): OrderedDict<K, V> {\n const reversed = new OrderedDict<K, V>();\n for (let index = this.size - 1; index >= 0; index--) {\n const key = this.keyAt(index)!;\n const element = this.get(key)!;\n reversed.set(key, element);\n }\n return reversed;\n }\n\n toSpliced(start: number, deleteCount?: number): OrderedDict<K, V>;\n toSpliced(start: number, deleteCount: number, ...items: [K, V][]): OrderedDict<K, V>;\n\n toSpliced(...args: [start: number, deleteCount: number, ...items: [K, V][]]) {\n const entries = [...this.entries()];\n entries.splice(...args);\n return new OrderedDict(entries);\n }\n\n slice(start?: number, end?: number) {\n const result = new OrderedDict<K, V>();\n let stop = this.size - 1;\n\n if (start === undefined) {\n return result;\n }\n\n if (start < 0) {\n start = start + this.size;\n }\n\n if (end !== undefined && end > 0) {\n stop = end - 1;\n }\n\n for (let index = start; index <= stop; index++) {\n const key = this.keyAt(index)!;\n const element = this.get(key)!;\n result.set(key, element);\n }\n return result;\n }\n\n every(\n predicate: (entry: [K, V], index: number, dictionary: OrderedDict<K, V>) => unknown,\n thisArg?: any\n ) {\n let index = 0;\n for (const entry of this) {\n if (!Reflect.apply(predicate, thisArg, [entry, index, this])) {\n return false;\n }\n index++;\n }\n return true;\n }\n\n some(\n predicate: (entry: [K, V], index: number, dictionary: OrderedDict<K, V>) => unknown,\n thisArg?: any\n ) {\n let index = 0;\n for (const entry of this) {\n if (Reflect.apply(predicate, thisArg, [entry, index, this])) {\n return true;\n }\n index++;\n }\n return false;\n }\n}\n\nexport type KeyOf<D extends OrderedDict<any, any>> =\n D extends OrderedDict<infer K, any> ? K : never;\nexport type ValueOf<D extends OrderedDict<any, any>> =\n D extends OrderedDict<any, infer V> ? V : never;\nexport type EntryOf<D extends OrderedDict<any, any>> = [KeyOf<D>, ValueOf<D>];\nexport type KeyFrom<E extends EntryOf<any>> = E[0];\nexport type ValueFrom<E extends EntryOf<any>> = E[1];\n\nfunction at<T>(array: ArrayLike<T>, index: number): T | undefined {\n if ('at' in Array.prototype) {\n return Array.prototype.at.call(array, index);\n }\n const actualIndex = toSafeIndex(array, index);\n return actualIndex === -1 ? undefined : array[actualIndex];\n}\n\nfunction toSafeIndex(array: ArrayLike<any>, index: number) {\n const length = array.length;\n const relativeIndex = toSafeInteger(index);\n const actualIndex = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;\n return actualIndex < 0 || actualIndex >= length ? -1 : actualIndex;\n}\n\nfunction toSafeInteger(number: number) {\n // eslint-disable-next-line no-self-compare\n return number !== number || number === 0 ? 0 : Math.trunc(number);\n}\n","import * as React from 'react';\n\ntype Direction = 'ltr' | 'rtl';\nconst DirectionContext = React.createContext<Direction | undefined>(undefined);\n\n/* -------------------------------------------------------------------------------------------------\n * Direction\n * -----------------------------------------------------------------------------------------------*/\n\ninterface DirectionProviderProps {\n children?: React.ReactNode;\n dir: Direction;\n}\nconst DirectionProvider: React.FC<DirectionProviderProps> = (props) => {\n const { dir, children } = props;\n return <DirectionContext.Provider value={dir}>{children}</DirectionContext.Provider>;\n};\n\n/* -----------------------------------------------------------------------------------------------*/\n\nfunction useDirection(localDir?: Direction) {\n const globalDir = React.useContext(DirectionContext);\n return localDir || globalDir || 'ltr';\n}\n\nconst Provider = DirectionProvider;\n\nexport {\n useDirection,\n //\n Provider,\n //\n DirectionProvider,\n};\n","import * as React from 'react';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { Presence } from '@radix-ui/react-presence';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\nimport { useDirection } from '@radix-ui/react-direction';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\nimport { clamp } from '@radix-ui/number';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { useStateMachine } from './use-state-machine';\n\nimport type { Scope } from '@radix-ui/react-context';\n\ntype Direction = 'ltr' | 'rtl';\ntype Sizes = {\n content: number;\n viewport: number;\n scrollbar: {\n size: number;\n paddingStart: number;\n paddingEnd: number;\n };\n};\n\n/* -------------------------------------------------------------------------------------------------\n * ScrollArea\n * -----------------------------------------------------------------------------------------------*/\n\nconst SCROLL_AREA_NAME = 'ScrollArea';\n\ntype ScopedProps<P> = P & { __scopeScrollArea?: Scope };\nconst [createScrollAreaContext, createScrollAreaScope] = createContextScope(SCROLL_AREA_NAME);\n\ntype ScrollAreaContextValue = {\n type: 'auto' | 'always' | 'scroll' | 'hover';\n dir: Direction;\n scrollHideDelay: number;\n scrollArea: ScrollAreaElement | null;\n viewport: ScrollAreaViewportElement | null;\n onViewportChange(viewport: ScrollAreaViewportElement | null): void;\n content: HTMLDivElement | null;\n onContentChange(content: HTMLDivElement): void;\n scrollbarX: ScrollAreaScrollbarElement | null;\n onScrollbarXChange(scrollbar: ScrollAreaScrollbarElement | null): void;\n scrollbarXEnabled: boolean;\n onScrollbarXEnabledChange(rendered: boolean): void;\n scrollbarY: ScrollAreaScrollbarElement | null;\n onScrollbarYChange(scrollbar: ScrollAreaScrollbarElement | null): void;\n scrollbarYEnabled: boolean;\n onScrollbarYEnabledChange(rendered: boolean): void;\n onCornerWidthChange(width: number): void;\n onCornerHeightChange(height: number): void;\n};\n\nconst [ScrollAreaProvider, useScrollAreaContext] =\n createScrollAreaContext<ScrollAreaContextValue>(SCROLL_AREA_NAME);\n\ntype ScrollAreaElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface ScrollAreaProps extends PrimitiveDivProps {\n type?: ScrollAreaContextValue['type'];\n dir?: ScrollAreaContextValue['dir'];\n scrollHideDelay?: number;\n}\n\nconst ScrollArea = React.forwardRef<ScrollAreaElement, ScrollAreaProps>(\n (props: ScopedProps<ScrollAreaProps>, forwardedRef) => {\n const {\n __scopeScrollArea,\n type = 'hover',\n dir,\n scrollHideDelay = 600,\n ...scrollAreaProps\n } = props;\n const [scrollArea, setScrollArea] = React.useState<ScrollAreaElement | null>(null);\n const [viewport, setViewport] = React.useState<ScrollAreaViewportElement | null>(null);\n const [content, setContent] = React.useState<HTMLDivElement | null>(null);\n const [scrollbarX, setScrollbarX] = React.useState<ScrollAreaScrollbarElement | null>(null);\n const [scrollbarY, setScrollbarY] = React.useState<ScrollAreaScrollbarElement | null>(null);\n const [cornerWidth, setCornerWidth] = React.useState(0);\n const [cornerHeight, setCornerHeight] = React.useState(0);\n const [scrollbarXEnabled, setScrollbarXEnabled] = React.useState(false);\n const [scrollbarYEnabled, setScrollbarYEnabled] = React.useState(false);\n const composedRefs = useComposedRefs(forwardedRef, (node) => setScrollArea(node));\n const direction = useDirection(dir);\n\n return (\n <ScrollAreaProvider\n scope={__scopeScrollArea}\n type={type}\n dir={direction}\n scrollHideDelay={scrollHideDelay}\n scrollArea={scrollArea}\n viewport={viewport}\n onViewportChange={setViewport}\n content={content}\n onContentChange={setContent}\n scrollbarX={scrollbarX}\n onScrollbarXChange={setScrollbarX}\n scrollbarXEnabled={scrollbarXEnabled}\n onScrollbarXEnabledChange={setScrollbarXEnabled}\n scrollbarY={scrollbarY}\n onScrollbarYChange={setScrollbarY}\n scrollbarYEnabled={scrollbarYEnabled}\n onScrollbarYEnabledChange={setScrollbarYEnabled}\n onCornerWidthChange={setCornerWidth}\n onCornerHeightChange={setCornerHeight}\n >\n <Primitive.div\n dir={direction}\n {...scrollAreaProps}\n ref={composedRefs}\n style={{\n position: 'relative',\n // Pass corner sizes as CSS vars to reduce re-renders of context consumers\n ['--radix-scroll-area-corner-width' as any]: cornerWidth + 'px',\n ['--radix-scroll-area-corner-height' as any]: cornerHeight + 'px',\n ...props.style,\n }}\n />\n </ScrollAreaProvider>\n );\n }\n);\n\nScrollArea.displayName = SCROLL_AREA_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * ScrollAreaViewport\n * -----------------------------------------------------------------------------------------------*/\n\nconst VIEWPORT_NAME = 'ScrollAreaViewport';\n\ntype ScrollAreaViewportElement = React.ComponentRef<typeof Primitive.div>;\ninterface ScrollAreaViewportProps extends PrimitiveDivProps {\n nonce?: string;\n}\n\nconst ScrollAreaViewport = React.forwardRef<ScrollAreaViewportElement, ScrollAreaViewportProps>(\n (props: ScopedProps<ScrollAreaViewportProps>, forwardedRef) => {\n const { __scopeScrollArea, children, nonce, ...viewportProps } = props;\n const context = useScrollAreaContext(VIEWPORT_NAME, __scopeScrollArea);\n const ref = React.useRef<ScrollAreaViewportElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref, context.onViewportChange);\n return (\n <>\n {/* Hide scrollbars cross-browser and enable momentum scroll for touch devices */}\n <style\n dangerouslySetInnerHTML={{\n __html: `[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}`,\n }}\n nonce={nonce}\n />\n <Primitive.div\n data-radix-scroll-area-viewport=\"\"\n {...viewportProps}\n ref={composedRefs}\n style={{\n /**\n * We don't support `visible` because the intention is to have at least one scrollbar\n * if this component is used and `visible` will behave like `auto` in that case\n * https://developer.mozilla.org/en-US/docs/Web/CSS/overflow#description\n *\n * We don't handle `auto` because the intention is for the native implementation\n * to be hidden if using this component. We just want to ensure the node is scrollable\n * so could have used either `scroll` or `auto` here. We picked `scroll` to prevent\n * the browser from having to work out whether to render native scrollbars or not,\n * we tell it to with the intention of hiding them in CSS.\n */\n overflowX: context.scrollbarXEnabled ? 'scroll' : 'hidden',\n overflowY: context.scrollbarYEnabled ? 'scroll' : 'hidden',\n ...props.style,\n }}\n >\n {/**\n * `display: table` ensures our content div will match the size of its children in both\n * horizontal and vertical axis so we can determine if scroll width/height changed and\n * recalculate thumb sizes. This doesn't account for children with *percentage*\n * widths that change. We'll wait to see what use-cases consumers come up with there\n * before trying to resolve it.\n */}\n <div ref={context.onContentChange} style={{ minWidth: '100%', display: 'table' }}>\n {children}\n </div>\n </Primitive.div>\n </>\n );\n }\n);\n\nScrollAreaViewport.displayName = VIEWPORT_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * ScrollAreaScrollbar\n * -----------------------------------------------------------------------------------------------*/\n\nconst SCROLLBAR_NAME = 'ScrollAreaScrollbar';\n\ntype ScrollAreaScrollbarElement = ScrollAreaScrollbarVisibleElement;\ninterface ScrollAreaScrollbarProps extends ScrollAreaScrollbarVisibleProps {\n forceMount?: true;\n}\n\nconst ScrollAreaScrollbar = React.forwardRef<ScrollAreaScrollbarElement, ScrollAreaScrollbarProps>(\n (props: ScopedProps<ScrollAreaScrollbarProps>, forwardedRef) => {\n const { forceMount, ...scrollbarProps } = props;\n const context = useScrollAreaContext(SCROLLBAR_NAME, props.__scopeScrollArea);\n const { onScrollbarXEnabledChange, onScrollbarYEnabledChange } = context;\n const isHorizontal = props.orientation === 'horizontal';\n\n React.useEffect(() => {\n isHorizontal ? onScrollbarXEnabledChange(true) : onScrollbarYEnabledChange(true);\n return () => {\n isHorizontal ? onScrollbarXEnabledChange(false) : onScrollbarYEnabledChange(false);\n };\n }, [isHorizontal, onScrollbarXEnabledChange, onScrollbarYEnabledChange]);\n\n return context.type === 'hover' ? (\n <ScrollAreaScrollbarHover {...scrollbarProps} ref={forwardedRef} forceMount={forceMount} />\n ) : context.type === 'scroll' ? (\n <ScrollAreaScrollbarScroll {...scrollbarProps} ref={forwardedRef} forceMount={forceMount} />\n ) : context.type === 'auto' ? (\n <ScrollAreaScrollbarAuto {...scrollbarProps} ref={forwardedRef} forceMount={forceMount} />\n ) : context.type === 'always' ? (\n <ScrollAreaScrollbarVisible {...scrollbarProps} ref={forwardedRef} />\n ) : null;\n }\n);\n\nScrollAreaScrollbar.displayName = SCROLLBAR_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype ScrollAreaScrollbarHoverElement = ScrollAreaScrollbarAutoElement;\ninterface ScrollAreaScrollbarHoverProps extends ScrollAreaScrollbarAutoProps {\n forceMount?: true;\n}\n\nconst ScrollAreaScrollbarHover = React.forwardRef<\n ScrollAreaScrollbarHoverElement,\n ScrollAreaScrollbarHoverProps\n>((props: ScopedProps<ScrollAreaScrollbarHoverProps>, forwardedRef) => {\n const { forceMount, ...scrollbarProps } = props;\n const context = useScrollAreaContext(SCROLLBAR_NAME, props.__scopeScrollArea);\n const [visible, setVisible] = React.useState(false);\n\n React.useEffect(() => {\n const scrollArea = context.scrollArea;\n let hideTimer = 0;\n if (scrollArea) {\n const handlePointerEnter = () => {\n window.clearTimeout(hideTimer);\n setVisible(true);\n };\n const handlePointerLeave = () => {\n hideTimer = window.setTimeout(() => setVisible(false), context.scrollHideDelay);\n };\n scrollArea.addEventListener('pointerenter', handlePointerEnter);\n scrollArea.addEventListener('pointerleave', handlePointerLeave);\n return () => {\n window.clearTimeout(hideTimer);\n scrollArea.removeEventListener('pointerenter', handlePointerEnter);\n scrollArea.removeEventListener('pointerleave', handlePointerLeave);\n };\n }\n }, [context.scrollArea, context.scrollHideDelay]);\n\n return (\n <Presence present={forceMount || visible}>\n <ScrollAreaScrollbarAuto\n data-state={visible ? 'visible' : 'hidden'}\n {...scrollbarProps}\n ref={forwardedRef}\n />\n </Presence>\n );\n});\n\ntype ScrollAreaScrollbarScrollElement = ScrollAreaScrollbarVisibleElement;\ninterface ScrollAreaScrollbarScrollProps extends ScrollAreaScrollbarVisibleProps {\n forceMount?: true;\n}\n\nconst ScrollAreaScrollbarScroll = React.forwardRef<\n ScrollAreaScrollbarScrollElement,\n ScrollAreaScrollbarScrollProps\n>((props: ScopedProps<ScrollAreaScrollbarScrollProps>, forwardedRef) => {\n const { forceMount, ...scrollbarProps } = props;\n const context = useScrollAreaContext(SCROLLBAR_NAME, props.__scopeScrollArea);\n const isHorizontal = props.orientation === 'horizontal';\n const debounceScrollEnd = useDebounceCallback(() => send('SCROLL_END'), 100);\n const [state, send] = useStateMachine('hidden', {\n hidden: {\n SCROLL: 'scrolling',\n },\n scrolling: {\n SCROLL_END: 'idle',\n POINTER_ENTER: 'interacting',\n },\n interacting: {\n SCROLL: 'interacting',\n POINTER_LEAVE: 'idle',\n },\n idle: {\n HIDE: 'hidden',\n SCROLL: 'scrolling',\n POINTER_ENTER: 'interacting',\n },\n });\n\n React.useEffect(() => {\n if (state === 'idle') {\n const hideTimer = window.setTimeout(() => send('HIDE'), context.scrollHideDelay);\n return () => window.clearTimeout(hideTimer);\n }\n }, [state, context.scrollHideDelay, send]);\n\n React.useEffect(() => {\n const viewport = context.viewport;\n const scrollDirection = isHorizontal ? 'scrollLeft' : 'scrollTop';\n\n if (viewport) {\n let prevScrollPos = viewport[scrollDirection];\n const handleScroll = () => {\n const scrollPos = viewport[scrollDirection];\n const hasScrollInDirectionChanged = prevScrollPos !== scrollPos;\n if (hasScrollInDirectionChanged) {\n send('SCROLL');\n debounceScrollEnd();\n }\n prevScrollPos = scrollPos;\n };\n viewport.addEventListener('scroll', handleScroll);\n return () => viewport.removeEventListener('scroll', handleScroll);\n }\n }, [context.viewport, isHorizontal, send, debounceScrollEnd]);\n\n return (\n <Presence present={forceMount || state !== 'hidden'}>\n <ScrollAreaScrollbarVisible\n data-state={state === 'hidden' ? 'hidden' : 'visible'}\n {...scrollbarProps}\n ref={forwardedRef}\n onPointerEnter={composeEventHandlers(props.onPointerEnter, () => send('POINTER_ENTER'))}\n onPointerLeave={composeEventHandlers(props.onPointerLeave, () => send('POINTER_LEAVE'))}\n />\n </Presence>\n );\n});\n\ntype ScrollAreaScrollbarAutoElement = ScrollAreaScrollbarVisibleElement;\ninterface ScrollAreaScrollbarAutoProps extends ScrollAreaScrollbarVisibleProps {\n forceMount?: true;\n}\n\nconst ScrollAreaScrollbarAuto = React.forwardRef<\n ScrollAreaScrollbarAutoElement,\n ScrollAreaScrollbarAutoProps\n>((props: ScopedProps<ScrollAreaScrollbarAutoProps>, forwardedRef) => {\n const context = useScrollAreaContext(SCROLLBAR_NAME, props.__scopeScrollArea);\n const { forceMount, ...scrollbarProps } = props;\n const [visible, setVisible] = React.useState(false);\n const isHorizontal = props.orientation === 'horizontal';\n const handleResize = useDebounceCallback(() => {\n if (context.viewport) {\n const isOverflowX = context.viewport.offsetWidth < context.viewport.scrollWidth;\n const isOverflowY = context.viewport.offsetHeight < context.viewport.scrollHeight;\n setVisible(isHorizontal ? isOverflowX : isOverflowY);\n }\n }, 10);\n\n useResizeObserver(context.viewport, handleResize);\n useResizeObserver(context.content, handleResize);\n\n return (\n <Presence present={forceMount || visible}>\n <ScrollAreaScrollbarVisible\n data-state={visible ? 'visible' : 'hidden'}\n {...scrollbarProps}\n ref={forwardedRef}\n />\n </Presence>\n );\n});\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype ScrollAreaScrollbarVisibleElement = ScrollAreaScrollbarAxisElement;\ninterface ScrollAreaScrollbarVisibleProps\n extends Omit<ScrollAreaScrollbarAxisProps, keyof ScrollAreaScrollbarAxisPrivateProps> {\n orientation?: 'horizontal' | 'vertical';\n}\n\nconst ScrollAreaScrollbarVisible = React.forwardRef<\n ScrollAreaScrollbarVisibleElement,\n ScrollAreaScrollbarVisibleProps\n>((props: ScopedProps<ScrollAreaScrollbarVisibleProps>, forwardedRef) => {\n const { orientation = 'vertical', ...scrollbarProps } = props;\n const context = useScrollAreaContext(SCROLLBAR_NAME, props.__scopeScrollArea);\n const thumbRef = React.useRef<ScrollAreaThumbElement | null>(null);\n const pointerOffsetRef = React.useRef(0);\n const [sizes, setSizes] = React.useState<Sizes>({\n content: 0,\n viewport: 0,\n scrollbar: { size: 0, paddingStart: 0, paddingEnd: 0 },\n });\n const thumbRatio = getThumbRatio(sizes.viewport, sizes.content);\n\n type UncommonProps = 'onThumbPositionChange' | 'onDragScroll' | 'onWheelScroll';\n const commonProps: Omit<ScrollAreaScrollbarAxisPrivateProps, UncommonProps> = {\n ...scrollbarProps,\n sizes,\n onSizesChange: setSizes,\n hasThumb: Boolean(thumbRatio > 0 && thumbRatio < 1),\n onThumbChange: (thumb) => (thumbRef.current = thumb),\n onThumbPointerUp: () => (pointerOffsetRef.current = 0),\n onThumbPointerDown: (pointerPos) => (pointerOffsetRef.current = pointerPos),\n };\n\n function getScrollPosition(pointerPos: number, dir?: Direction) {\n return getScrollPositionFromPointer(pointerPos, pointerOffsetRef.current, sizes, dir);\n }\n\n if (orientation === 'horizontal') {\n return (\n <ScrollAreaScrollbarX\n {...commonProps}\n ref={forwardedRef}\n onThumbPositionChange={() => {\n if (context.viewport && thumbRef.current) {\n const scrollPos = context.viewport.scrollLeft;\n const offset = getThumbOffsetFromScroll(scrollPos, sizes, context.dir);\n thumbRef.current.style.transform = `translate3d(${offset}px, 0, 0)`;\n }\n }}\n onWheelScroll={(scrollPos) => {\n if (context.viewport) context.viewport.scrollLeft = scrollPos;\n }}\n onDragScroll={(pointerPos) => {\n if (context.viewport) {\n context.viewport.scrollLeft = getScrollPosition(pointerPos, context.dir);\n }\n }}\n />\n );\n }\n\n if (orientation === 'vertical') {\n return (\n <ScrollAreaScrollbarY\n {...commonProps}\n ref={forwardedRef}\n onThumbPositionChange={() => {\n if (context.viewport && thumbRef.current) {\n const scrollPos = context.viewport.scrollTop;\n const offset = getThumbOffsetFromScroll(scrollPos, sizes);\n thumbRef.current.style.transform = `translate3d(0, ${offset}px, 0)`;\n }\n }}\n onWheelScroll={(scrollPos) => {\n if (context.viewport) context.viewport.scrollTop = scrollPos;\n }}\n onDragScroll={(pointerPos) => {\n if (context.viewport) context.viewport.scrollTop = getScrollPosition(pointerPos);\n }}\n />\n );\n }\n\n return null;\n});\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype ScrollAreaScrollbarAxisPrivateProps = {\n hasThumb: boolean;\n sizes: Sizes;\n onSizesChange(sizes: Sizes): void;\n onThumbChange(thumb: ScrollAreaThumbElement | null): void;\n onThumbPointerDown(pointerPos: number): void;\n onThumbPointerUp(): void;\n onThumbPositionChange(): void;\n onWheelScroll(scrollPos: number): void;\n onDragScroll(pointerPos: number): void;\n};\n\ntype ScrollAreaScrollbarAxisElement = ScrollAreaScrollbarImplElement;\ninterface ScrollAreaScrollbarAxisProps\n extends Omit<ScrollAreaScrollbarImplProps, keyof ScrollAreaScrollbarImplPrivateProps>,\n ScrollAreaScrollbarAxisPrivateProps {}\n\nconst ScrollAreaScrollbarX = React.forwardRef<\n ScrollAreaScrollbarAxisElement,\n ScrollAreaScrollbarAxisProps\n>((props: ScopedProps<ScrollAreaScrollbarAxisProps>, forwardedRef) => {\n const { sizes, onSizesChange, ...scrollbarProps } = props;\n const context = useScrollAreaContext(SCROLLBAR_NAME, props.__scopeScrollArea);\n const [computedStyle, setComputedStyle] = React.useState<CSSStyleDeclaration>();\n const ref = React.useRef<ScrollAreaScrollbarAxisElement>(null);\n const composeRefs = useComposedRefs(forwardedRef, ref, context.onScrollbarXChange);\n\n React.useEffect(() => {\n if (ref.current) setComputedStyle(getComputedStyle(ref.current));\n }, [ref]);\n\n return (\n <ScrollAreaScrollbarImpl\n data-orientation=\"horizontal\"\n {...scrollbarProps}\n ref={composeRefs}\n sizes={sizes}\n style={{\n bottom: 0,\n left: context.dir === 'rtl' ? 'var(--radix-scroll-area-corner-width)' : 0,\n right: context.dir === 'ltr' ? 'var(--radix-scroll-area-corner-width)' : 0,\n ['--radix-scroll-area-thumb-width' as any]: getThumbSize(sizes) + 'px',\n ...props.style,\n }}\n onThumbPointerDown={(pointerPos) => props.onThumbPointerDown(pointerPos.x)}\n onDragScroll={(pointerPos) => props.onDragScroll(pointerPos.x)}\n onWheelScroll={(event, maxScrollPos) => {\n if (context.viewport) {\n const scrollPos = context.viewport.scrollLeft + event.deltaX;\n props.onWheelScroll(scrollPos);\n // prevent window scroll when wheeling on scrollbar\n if (isScrollingWithinScrollbarBounds(scrollPos, maxScrollPos)) {\n event.preventDefault();\n }\n }\n }}\n onResize={() => {\n if (ref.current && context.viewport && computedStyle) {\n onSizesChange({\n content: context.viewport.scrollWidth,\n viewport: context.viewport.offsetWidth,\n scrollbar: {\n size: ref.current.clientWidth,\n paddingStart: toInt(computedStyle.paddingLeft),\n paddingEnd: toInt(computedStyle.paddingRight),\n },\n });\n }\n }}\n />\n );\n});\n\nconst ScrollAreaScrollbarY = React.forwardRef<\n ScrollAreaScrollbarAxisElement,\n ScrollAreaScrollbarAxisProps\n>((props: ScopedProps<ScrollAreaScrollbarAxisProps>, forwardedRef) => {\n const { sizes, onSizesChange, ...scrollbarProps } = props;\n const context = useScrollAreaContext(SCROLLBAR_NAME, props.__scopeScrollArea);\n const [computedStyle, setComputedStyle] = React.useState<CSSStyleDeclaration>();\n const ref = React.useRef<ScrollAreaScrollbarAxisElement>(null);\n const composeRefs = useComposedRefs(forwardedRef, ref, context.onScrollbarYChange);\n\n React.useEffect(() => {\n if (ref.current) setComputedStyle(getComputedStyle(ref.current));\n }, [ref]);\n\n return (\n <ScrollAreaScrollbarImpl\n data-orientation=\"vertical\"\n {...scrollbarProps}\n ref={composeRefs}\n sizes={sizes}\n style={{\n top: 0,\n right: context.dir === 'ltr' ? 0 : undefined,\n left: context.dir === 'rtl' ? 0 : undefined,\n bottom: 'var(--radix-scroll-area-corner-height)',\n ['--radix-scroll-area-thumb-height' as any]: getThumbSize(sizes) + 'px',\n ...props.style,\n }}\n onThumbPointerDown={(pointerPos) => props.onThumbPointerDown(pointerPos.y)}\n onDragScroll={(pointerPos) => props.onDragScroll(pointerPos.y)}\n onWheelScroll={(event, maxScrollPos) => {\n if (context.viewport) {\n const scrollPos = context.viewport.scrollTop + event.deltaY;\n props.onWheelScroll(scrollPos);\n // prevent window scroll when wheeling on scrollbar\n if (isScrollingWithinScrollbarBounds(scrollPos, maxScrollPos)) {\n event.preventDefault();\n }\n }\n }}\n onResize={() => {\n if (ref.current && context.viewport && computedStyle) {\n onSizesChange({\n content: context.viewport.scrollHeight,\n viewport: context.viewport.offsetHeight,\n scrollbar: {\n size: ref.current.clientHeight,\n paddingStart: toInt(computedStyle.paddingTop),\n paddingEnd: toInt(computedStyle.paddingBottom),\n },\n });\n }\n }}\n />\n );\n});\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype ScrollbarContext = {\n hasThumb: boolean;\n scrollbar: ScrollAreaScrollbarElement | null;\n onThumbChange(thumb: ScrollAreaThumbElement | null): void;\n onThumbPointerUp(): void;\n onThumbPointerDown(pointerPos: { x: number; y: number }): void;\n onThumbPositionChange(): void;\n};\n\nconst [ScrollbarProvider, useScrollbarContext] =\n createScrollAreaContext<ScrollbarContext>(SCROLLBAR_NAME);\n\ntype ScrollAreaScrollbarImplElement = React.ComponentRef<typeof Primitive.div>;\ntype ScrollAreaScrollbarImplPrivateProps = {\n sizes: Sizes;\n hasThumb: boolean;\n onThumbChange: ScrollbarContext['onThumbChange'];\n onThumbPointerUp: ScrollbarContext['onThumbPointerUp'];\n onThumbPointerDown: ScrollbarContext['onThumbPointerDown'];\n onThumbPositionChange: ScrollbarContext['onThumbPositionChange'];\n onWheelScroll(event: WheelEvent, maxScrollPos: number): void;\n onDragScroll(pointerPos: { x: number; y: number }): void;\n onResize(): void;\n};\ninterface ScrollAreaScrollbarImplProps\n extends Omit<PrimitiveDivProps, keyof ScrollAreaScrollbarImplPrivateProps>,\n ScrollAreaScrollbarImplPrivateProps {}\n\nconst ScrollAreaScrollbarImpl = React.forwardRef<\n ScrollAreaScrollbarImplElement,\n ScrollAreaScrollbarImplProps\n>((props: ScopedProps<ScrollAreaScrollbarImplProps>, forwardedRef) => {\n const {\n __scopeScrollArea,\n sizes,\n hasThumb,\n onThumbChange,\n onThumbPointerUp,\n onThumbPointerDown,\n onThumbPositionChange,\n onDragScroll,\n onWheelScroll,\n onResize,\n ...scrollbarProps\n } = props;\n const context = useScrollAreaContext(SCROLLBAR_NAME, __scopeScrollArea);\n const [scrollbar, setScrollbar] = React.useState<ScrollAreaScrollbarElement | null>(null);\n const composeRefs = useComposedRefs(forwardedRef, (node) => setScrollbar(node));\n const rectRef = React.useRef<DOMRect | null>(null);\n const prevWebkitUserSelectRef = React.useRef<string>('');\n const viewport = context.viewport;\n const maxScrollPos = sizes.content - sizes.viewport;\n const handleWheelScroll = useCallbackRef(onWheelScroll);\n const handleThumbPositionChange = useCallbackRef(onThumbPositionChange);\n const handleResize = useDebounceCallback(onResize, 10);\n\n function handleDragScroll(event: React.PointerEvent<HTMLElement>) {\n if (rectRef.current) {\n const x = event.clientX - rectRef.current.left;\n const y = event.clientY - rectRef.current.top;\n onDragScroll({ x, y });\n }\n }\n\n /**\n * We bind wheel event imperatively so we can switch off passive\n * mode for document wheel event to allow it to be prevented\n */\n React.useEffect(() => {\n const handleWheel = (event: WheelEvent) => {\n const element = event.target as HTMLElement;\n const isScrollbarWheel = scrollbar?.contains(element);\n if (isScrollbarWheel) handleWheelScroll(event, maxScrollPos);\n };\n document.addEventListener('wheel', handleWheel, { passive: false });\n return () => document.removeEventListener('wheel', handleWheel, { passive: false } as any);\n }, [viewport, scrollbar, maxScrollPos, handleWheelScroll]);\n\n /**\n * Update thumb position on sizes change\n */\n React.useEffect(handleThumbPositionChange, [sizes, handleThumbPositionChange]);\n\n useResizeObserver(scrollbar, handleResize);\n useResizeObserver(context.content, handleResize);\n\n return (\n <ScrollbarProvider\n scope={__scopeScrollArea}\n scrollbar={scrollbar}\n hasThumb={hasThumb}\n onThumbChange={useCallbackRef(onThumbChange)}\n onThumbPointerUp={useCallbackRef(onThumbPointerUp)}\n onThumbPositionChange={handleThumbPositionChange}\n onThumbPointerDown={useCallbackRef(onThumbPointerDown)}\n >\n <Primitive.div\n {...scrollbarProps}\n ref={composeRefs}\n style={{ position: 'absolute', ...scrollbarProps.style }}\n onPointerDown={composeEventHandlers(props.onPointerDown, (event) => {\n const mainPointer = 0;\n if (event.button === mainPointer) {\n const element = event.target as HTMLElement;\n element.setPointerCapture(event.pointerId);\n rectRef.current = scrollbar!.getBoundingClientRect();\n // pointer capture doesn't prevent text selection in Safari\n // so we remove text selection manually when scrolling\n prevWebkitUserSelectRef.current = document.body.style.webkitUserSelect;\n document.body.style.webkitUserSelect = 'none';\n if (context.viewport) context.viewport.style.scrollBehavior = 'auto';\n handleDragScroll(event);\n }\n })}\n onPointerMove={composeEventHandlers(props.onPointerMove, handleDragScroll)}\n onPointerUp={composeEventHandlers(props.onPointerUp, (event) => {\n const element = event.target as HTMLElement;\n if (element.hasPointerCapture(event.pointerId)) {\n element.releasePointerCapture(event.pointerId);\n }\n document.body.style.webkitUserSelect = prevWebkitUserSelectRef.current;\n if (context.viewport) context.viewport.style.scrollBehavior = '';\n rectRef.current = null;\n })}\n />\n </ScrollbarProvider>\n );\n});\n\n/* -------------------------------------------------------------------------------------------------\n * ScrollAreaThumb\n * -----------------------------------------------------------------------------------------------*/\n\nconst THUMB_NAME = 'ScrollAreaThumb';\n\ntype ScrollAreaThumbElement = ScrollAreaThumbImplElement;\ninterface ScrollAreaThumbProps extends ScrollAreaThumbImplProps {\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst ScrollAreaThumb = React.forwardRef<ScrollAreaThumbElement, ScrollAreaThumbProps>(\n (props: ScopedProps<ScrollAreaThumbProps>, forwardedRef) => {\n const { forceMount, ...thumbProps } = props;\n const scrollbarContext = useScrollbarContext(THUMB_NAME, props.__scopeScrollArea);\n return (\n <Presence present={forceMount || scrollbarContext.hasThumb}>\n <ScrollAreaThumbImpl ref={forwardedRef} {...thumbProps} />\n </Presence>\n );\n }\n);\n\ntype ScrollAreaThumbImplElement = React.ComponentRef<typeof Primitive.div>;\ninterface ScrollAreaThumbImplProps extends PrimitiveDivProps {}\n\nconst ScrollAreaThumbImpl = React.forwardRef<ScrollAreaThumbImplElement, ScrollAreaThumbImplProps>(\n (props: ScopedProps<ScrollAreaThumbImplProps>, forwardedRef) => {\n const { __scopeScrollArea, style, ...thumbProps } = props;\n const scrollAreaContext = useScrollAreaContext(THUMB_NAME, __scopeScrollArea);\n const scrollbarContext = useScrollbarContext(THUMB_NAME, __scopeScrollArea);\n const { onThumbPositionChange } = scrollbarContext;\n const composedRef = useComposedRefs(forwardedRef, (node) =>\n scrollbarContext.onThumbChange(node)\n );\n const removeUnlinkedScrollListenerRef = React.useRef<() => void>(undefined);\n const debounceScrollEnd = useDebounceCallback(() => {\n if (removeUnlinkedScrollListenerRef.current) {\n removeUnlinkedScrollListenerRef.current();\n removeUnlinkedScrollListenerRef.current = undefined;\n }\n }, 100);\n\n React.useEffect(() => {\n const viewport = scrollAreaContext.viewport;\n if (viewport) {\n /**\n * We only bind to native scroll event so we know when scroll starts and ends.\n * When scroll starts we start a requestAnimationFrame loop that checks for\n * changes to scroll position. That rAF loop triggers our thumb position change\n * when relevant to avoid scroll-linked effects. We cancel the loop when scroll ends.\n * https://developer.mozilla.org/en-US/docs/Mozilla/Performance/Scroll-linked_effects\n */\n const handleScroll = () => {\n debounceScrollEnd();\n if (!removeUnlinkedScrollListenerRef.current) {\n const listener = addUnlinkedScrollListener(viewport, onThumbPositionChange);\n removeUnlinkedScrollListenerRef.current = listener;\n onThumbPositionChange();\n }\n };\n onThumbPositionChange();\n viewport.addEventListener('scroll', handleScroll);\n return () => viewport.removeEventListener('scroll', handleScroll);\n }\n }, [scrollAreaContext.viewport, debounceScrollEnd, onThumbPositionChange]);\n\n return (\n <Primitive.div\n data-state={scrollbarContext.hasThumb ? 'visible' : 'hidden'}\n {...thumbProps}\n ref={composedRef}\n style={{\n width: 'var(--radix-scroll-area-thumb-width)',\n height: 'var(--radix-scroll-area-thumb-height)',\n ...style,\n }}\n onPointerDownCapture={composeEventHandlers(props.onPointerDownCapture, (event) => {\n const thumb = event.target as HTMLElement;\n const thumbRect = thumb.getBoundingClientRect();\n const x = event.clientX - thumbRect.left;\n const y = event.clientY - thumbRect.top;\n scrollbarContext.onThumbPointerDown({ x, y });\n })}\n onPointerUp={composeEventHandlers(props.onPointerUp, scrollbarContext.onThumbPointerUp)}\n />\n );\n }\n);\n\nScrollAreaThumb.displayName = THUMB_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * ScrollAreaCorner\n * -----------------------------------------------------------------------------------------------*/\n\nconst CORNER_NAME = 'ScrollAreaCorner';\n\ntype ScrollAreaCornerElement = ScrollAreaCornerImplElement;\ninterface ScrollAreaCornerProps extends ScrollAreaCornerImplProps {}\n\nconst ScrollAreaCorner = React.forwardRef<ScrollAreaCornerElement, ScrollAreaCornerProps>(\n (props: ScopedProps<ScrollAreaCornerProps>, forwardedRef) => {\n const context = useScrollAreaContext(CORNER_NAME, props.__scopeScrollArea);\n const hasBothScrollbarsVisible = Boolean(context.scrollbarX && context.scrollbarY);\n const hasCorner = context.type !== 'scroll' && hasBothScrollbarsVisible;\n return hasCorner ? <ScrollAreaCornerImpl {...props} ref={forwardedRef} /> : null;\n }\n);\n\nScrollAreaCorner.displayName = CORNER_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype ScrollAreaCornerImplElement = React.ComponentRef<typeof Primitive.div>;\ninterface ScrollAreaCornerImplProps extends PrimitiveDivProps {}\n\nconst ScrollAreaCornerImpl = React.forwardRef<\n ScrollAreaCornerImplElement,\n ScrollAreaCornerImplProps\n>((props: ScopedProps<ScrollAreaCornerImplProps>, forwardedRef) => {\n const { __scopeScrollArea, ...cornerProps } = props;\n const context = useScrollAreaContext(CORNER_NAME, __scopeScrollArea);\n const [width, setWidth] = React.useState(0);\n const [height, setHeight] = React.useState(0);\n const hasSize = Boolean(width && height);\n\n useResizeObserver(context.scrollbarX, () => {\n const height = context.scrollbarX?.offsetHeight || 0;\n context.onCornerHeightChange(height);\n setHeight(height);\n });\n\n useResizeObserver(context.scrollbarY, () => {\n const width = context.scrollbarY?.offsetWidth || 0;\n context.onCornerWidthChange(width);\n setWidth(width);\n });\n\n return hasSize ? (\n <Primitive.div\n {...cornerProps}\n ref={forwardedRef}\n style={{\n width,\n height,\n position: 'absolute',\n right: context.dir === 'ltr' ? 0 : undefined,\n left: context.dir === 'rtl' ? 0 : undefined,\n bottom: 0,\n ...props.style,\n }}\n />\n ) : null;\n});\n\n/* -----------------------------------------------------------------------------------------------*/\n\nfunction toInt(value?: string) {\n return value ? parseInt(value, 10) : 0;\n}\n\nfunction getThumbRatio(viewportSize: number, contentSize: number) {\n const ratio = viewportSize / contentSize;\n return isNaN(ratio) ? 0 : ratio;\n}\n\nfunction getThumbSize(sizes: Sizes) {\n const ratio = getThumbRatio(sizes.viewport, sizes.content);\n const scrollbarPadding = sizes.scrollbar.paddingStart + sizes.scrollbar.paddingEnd;\n const thumbSize = (sizes.scrollbar.size - scrollbarPadding) * ratio;\n // minimum of 18 matches macOS minimum\n return Math.max(thumbSize, 18);\n}\n\nfunction getScrollPositionFromPointer(\n pointerPos: number,\n pointerOffset: number,\n sizes: Sizes,\n dir: Direction = 'ltr'\n) {\n const thumbSizePx = getThumbSize(sizes);\n const thumbCenter = thumbSizePx / 2;\n const offset = pointerOffset || thumbCenter;\n const thumbOffsetFromEnd = thumbSizePx - offset;\n const minPointerPos = sizes.scrollbar.paddingStart + offset;\n const maxPointerPos = sizes.scrollbar.size - sizes.scrollbar.paddingEnd - thumbOffsetFromEnd;\n const maxScrollPos = sizes.content - sizes.viewport;\n const scrollRange = dir === 'ltr' ? [0, maxScrollPos] : [maxScrollPos * -1, 0];\n const interpolate = linearScale([minPointerPos, maxPointerPos], scrollRange as [number, number]);\n return interpolate(pointerPos);\n}\n\nfunction getThumbOffsetFromScroll(scrollPos: number, sizes: Sizes, dir: Direction = 'ltr') {\n const thumbSizePx = getThumbSize(sizes);\n const scrollbarPadding = sizes.scrollbar.paddingStart + sizes.scrollbar.paddingEnd;\n const scrollbar = sizes.scrollbar.size - scrollbarPadding;\n const maxScrollPos = sizes.content - sizes.viewport;\n const maxThumbPos = scrollbar - thumbSizePx;\n const scrollClampRange = dir === 'ltr' ? [0, maxScrollPos] : [maxScrollPos * -1, 0];\n const scrollWithoutMomentum = clamp(scrollPos, scrollClampRange as [number, number]);\n const interpolate = linearScale([0, maxScrollPos], [0, maxThumbPos]);\n return interpolate(scrollWithoutMomentum);\n}\n\n// https://github.com/tmcw-up-for-adoption/simple-linear-scale/blob/master/index.js\nfunction linearScale(input: readonly [number, number], output: readonly [number, number]) {\n return (value: number) => {\n if (input[0] === input[1] || output[0] === output[1]) return output[0];\n const ratio = (output[1] - output[0]) / (input[1] - input[0]);\n return output[0] + ratio * (value - input[0]);\n };\n}\n\nfunction isScrollingWithinScrollbarBounds(scrollPos: number, maxScrollPos: number) {\n return scrollPos > 0 && scrollPos < maxScrollPos;\n}\n\n// Custom scroll handler to avoid scroll-linked effects\n// https://developer.mozilla.org/en-US/docs/Mozilla/Performance/Scroll-linked_effects\nconst addUnlinkedScrollListener = (node: HTMLElement, handler = () => {}) => {\n let prevPosition = { left: node.scrollLeft, top: node.scrollTop };\n let rAF = 0;\n (function loop() {\n const position = { left: node.scrollLeft, top: node.scrollTop };\n const isHorizontalScroll = prevPosition.left !== position.left;\n const isVerticalScroll = prevPosition.top !== position.top;\n if (isHorizontalScroll || isVerticalScroll) handler();\n prevPosition = position;\n rAF = window.requestAnimationFrame(loop);\n })();\n return () => window.cancelAnimationFrame(rAF);\n};\n\nfunction useDebounceCallback(callback: () => void, delay: number) {\n const handleCallback = useCallbackRef(callback);\n const debounceTimerRef = React.useRef(0);\n React.useEffect(() => () => window.clearTimeout(debounceTimerRef.current), []);\n return React.useCallback(() => {\n window.clearTimeout(debounceTimerRef.current);\n debounceTimerRef.current = window.setTimeout(handleCallback, delay);\n }, [handleCallback, delay]);\n}\n\nfunction useResizeObserver(element: HTMLElement | null, onResize: () => void) {\n const handleResize = useCallbackRef(onResize);\n useLayoutEffect(() => {\n let rAF = 0;\n if (element) {\n /**\n * Resize Observer will throw an often benign error that says `ResizeObserver loop\n * completed with undelivered notifications`. This means that ResizeObserver was not\n * able to deliver all observations within a single animation frame, so we use\n * `requestAnimationFrame` to ensure we don't deliver unnecessary observations.\n * Further reading: https://github.com/WICG/resize-observer/issues/38\n */\n const resizeObserver = new ResizeObserver(() => {\n cancelAnimationFrame(rAF);\n rAF = window.requestAnimationFrame(handleResize);\n });\n resizeObserver.observe(element);\n return () => {\n window.cancelAnimationFrame(rAF);\n resizeObserver.unobserve(element);\n };\n }\n }, [element, handleResize]);\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = ScrollArea;\nconst Viewport = ScrollAreaViewport;\nconst Scrollbar = ScrollAreaScrollbar;\nconst Thumb = ScrollAreaThumb;\nconst Corner = ScrollAreaCorner;\n\nexport {\n createScrollAreaScope,\n //\n ScrollArea,\n ScrollAreaViewport,\n ScrollAreaScrollbar,\n ScrollAreaThumb,\n ScrollAreaCorner,\n //\n Root,\n Viewport,\n Scrollbar,\n Thumb,\n Corner,\n};\nexport type {\n ScrollAreaProps,\n ScrollAreaViewportProps,\n ScrollAreaScrollbarProps,\n ScrollAreaThumbProps,\n ScrollAreaCornerProps,\n};\n","import * as React from 'react';\n\ntype Machine<S> = { [k: string]: { [k: string]: S } };\ntype MachineState<T> = keyof T;\ntype MachineEvent<T> = keyof UnionToIntersection<T[keyof T]>;\n\n// 🤯 https://fettblog.eu/typescript-union-to-intersection/\ntype UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (x: infer R) => any\n ? R\n : never;\n\nexport function useStateMachine<M>(\n initialState: MachineState<M>,\n machine: M & Machine<MachineState<M>>\n) {\n return React.useReducer((state: MachineState<M>, event: MachineEvent<M>): MachineState<M> => {\n const nextState = (machine[state] as any)[event];\n return nextState ?? state;\n }, initialState);\n}\n","function clamp(value: number, [min, max]: [number, number]): number {\n return Math.min(max, Math.max(min, value));\n}\n\nexport { clamp };\n","import React, { useRef, useState } from \"react\";\nimport { Check, MessageSquarePlus } from \"lucide-react\";\n\nimport type { CommentSidebarSnapshot, CommentSidebarThreadSnapshot } from \"../../api/public-types\";\n\nexport interface TwCommentSidebarProps {\n comments: CommentSidebarSnapshot;\n activeCommentId?: string;\n currentUserId?: string;\n onOpenComment?: (thread: CommentSidebarThreadSnapshot) => void;\n onResolveComment?: (commentId: string) => void;\n onReopenComment?: (commentId: string) => void;\n onAddReply?: (commentId: string, body: string) => void;\n onEditBody?: (commentId: string, body: string) => void;\n}\n\nconst focusRingClass =\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-canvas\";\n\nexport function TwCommentSidebar(props: TwCommentSidebarProps) {\n const { comments, activeCommentId, currentUserId } = props;\n\n return (\n <div className=\"outline-none\">\n <p className=\"text-xs text-tertiary mb-3\">\n {comments.openCommentIds.length} open · {comments.resolvedCommentIds.length} resolved · {comments.detachedCommentIds.length} detached\n </p>\n {comments.threads.length > 0 ? (\n <div className=\"space-y-1\">\n {comments.threads.map((thread) => {\n const isActive = activeCommentId === thread.commentId;\n const leadEntry = thread.entries[0];\n const isOwnComment = currentUserId != null && leadEntry?.authorId === currentUserId;\n const canEdit = isOwnComment && thread.status === \"open\" && props.onEditBody != null;\n\n return (\n <div\n key={thread.commentId}\n role=\"button\"\n tabIndex={0}\n className={`rounded-lg p-2.5 transition-colors cursor-pointer ${focusRingClass} ${isActive ? \"bg-accent-soft\" : \"hover:bg-surface\"}`}\n onClick={() => props.onOpenComment?.(thread)}\n onKeyDown={(event) => {\n if (event.key === \"Enter\" || event.key === \" \") {\n event.preventDefault();\n props.onOpenComment?.(thread);\n }\n }}\n >\n <div className=\"flex items-start justify-between gap-2 mb-1\">\n <span className=\"text-sm font-medium text-primary\">{thread.createdBy}</span>\n <StatusBadge status={thread.status} />\n </div>\n <p className=\"text-xs text-tertiary mb-1\">{thread.createdAt}</p>\n <p className=\"text-xs font-medium text-comment bg-comment-soft rounded px-1 py-0.5 inline-block mb-1.5\">\n {thread.excerpt}\n </p>\n\n {/* Comment body — inline editable for own comments on open threads */}\n {leadEntry?.body ? (\n canEdit ? (\n <InlineEditableBody\n commentId={thread.commentId}\n body={leadEntry.body}\n onSave={(newBody) => props.onEditBody?.(thread.commentId, newBody)}\n />\n ) : (\n <p className=\"text-sm text-secondary leading-relaxed\">{leadEntry.body}</p>\n )\n ) : null}\n\n {/* Show reply entries */}\n {thread.entries.slice(1).map((entry) => (\n <div key={entry.entryId} className=\"mt-2 pl-2 border-l border-border\">\n <p className=\"text-xs text-tertiary\">{entry.authorId} · {entry.createdAt}</p>\n <p className=\"text-sm text-secondary leading-relaxed\">{entry.body}</p>\n </div>\n ))}\n\n {thread.entryCount > thread.entries.length ? (\n <p className=\"text-xs text-tertiary mt-1.5\">\n +{thread.entryCount - thread.entries.length} more repl{thread.entryCount - thread.entries.length === 1 ? \"y\" : \"ies\"}\n </p>\n ) : null}\n\n {thread.resolvedAt && thread.resolvedBy ? (\n <p className=\"text-xs text-tertiary mt-1\">\n Resolved by {thread.resolvedBy} at {thread.resolvedAt}\n </p>\n ) : null}\n\n <div className=\"flex gap-1.5 mt-2\">\n {thread.status === \"open\" ? (\n <button\n type=\"button\"\n className=\"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs text-insert hover:bg-insert-soft transition-colors\"\n onClick={(e) => {\n e.stopPropagation();\n props.onResolveComment?.(thread.commentId);\n }}\n >\n <Check className=\"h-3 w-3\" /> Resolve\n </button>\n ) : thread.status === \"resolved\" ? (\n <button\n type=\"button\"\n className=\"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs text-secondary hover:bg-surface transition-colors\"\n onClick={(e) => {\n e.stopPropagation();\n props.onReopenComment?.(thread.commentId);\n }}\n >\n Reopen\n </button>\n ) : (\n <span className=\"text-xs text-tertiary px-2 py-1\">Detached</span>\n )}\n </div>\n\n {/* Reply input — only for open threads */}\n {thread.status === \"open\" && props.onAddReply ? (\n <ReplyInput commentId={thread.commentId} onAddReply={props.onAddReply} />\n ) : null}\n </div>\n );\n })}\n </div>\n ) : (\n <p className=\"text-xs text-tertiary py-4\">\n Comment threads will appear here when the runtime loads them.\n </p>\n )}\n </div>\n );\n}\n\nfunction InlineEditableBody(props: {\n commentId: string;\n body: string;\n onSave: (newBody: string) => void;\n}) {\n const [isEditing, setIsEditing] = useState(false);\n const [draft, setDraft] = useState(props.body);\n\n if (!isEditing) {\n return (\n <p\n className=\"text-sm text-secondary leading-relaxed cursor-text rounded px-1 -mx-1 hover:bg-surface transition-colors\"\n onClick={(e) => {\n e.stopPropagation();\n setDraft(props.body);\n setIsEditing(true);\n }}\n title=\"Click to edit\"\n >\n {props.body}\n </p>\n );\n }\n\n return (\n <textarea\n className=\"w-full text-sm text-primary leading-relaxed bg-surface rounded-md border border-border px-2 py-1.5 resize-none focus:outline-none focus:ring-1 focus:ring-accent\"\n rows={Math.max(2, props.body.split(\"\\n\").length)}\n value={draft}\n autoFocus\n onClick={(e) => e.stopPropagation()}\n onChange={(e) => setDraft(e.target.value)}\n onBlur={() => {\n if (draft.trim() && draft.trim() !== props.body) {\n props.onSave(draft.trim());\n }\n setIsEditing(false);\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && !e.shiftKey) {\n e.preventDefault();\n if (draft.trim() && draft.trim() !== props.body) {\n props.onSave(draft.trim());\n }\n setIsEditing(false);\n }\n if (e.key === \"Escape\") {\n setDraft(props.body);\n setIsEditing(false);\n }\n e.stopPropagation();\n }}\n />\n );\n}\n\nfunction ReplyInput(props: { commentId: string; onAddReply: (commentId: string, body: string) => void }) {\n const [body, setBody] = useState(\"\");\n const [isOpen, setIsOpen] = useState(false);\n\n if (!isOpen) {\n return (\n <button\n type=\"button\"\n className=\"inline-flex items-center gap-1 text-xs text-tertiary hover:text-secondary transition-colors mt-1\"\n onClick={(e) => {\n e.stopPropagation();\n setIsOpen(true);\n }}\n >\n <MessageSquarePlus className=\"h-3 w-3\" /> Reply\n </button>\n );\n }\n\n return (\n <div className=\"mt-2\" onClick={(e) => e.stopPropagation()}>\n <textarea\n className=\"w-full rounded-md border border-border bg-surface px-2 py-1.5 text-xs text-primary placeholder:text-tertiary resize-none focus:outline-none focus:ring-1 focus:ring-accent\"\n rows={2}\n placeholder=\"Write a reply...\"\n value={body}\n onChange={(e) => setBody(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && !e.shiftKey && body.trim()) {\n e.preventDefault();\n props.onAddReply(props.commentId, body.trim());\n setBody(\"\");\n setIsOpen(false);\n }\n if (e.key === \"Escape\") {\n setBody(\"\");\n setIsOpen(false);\n }\n e.stopPropagation();\n }}\n autoFocus\n />\n <div className=\"flex gap-1.5 mt-1\">\n <button\n type=\"button\"\n disabled={!body.trim()}\n className=\"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs text-accent hover:bg-accent-soft transition-colors disabled:opacity-40\"\n onClick={() => {\n if (body.trim()) {\n props.onAddReply(props.commentId, body.trim());\n setBody(\"\");\n setIsOpen(false);\n }\n }}\n >\n Reply\n </button>\n <button\n type=\"button\"\n className=\"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs text-tertiary hover:bg-surface transition-colors\"\n onClick={() => {\n setBody(\"\");\n setIsOpen(false);\n }}\n >\n Cancel\n </button>\n </div>\n </div>\n );\n}\n\nfunction StatusBadge(props: { status: string }) {\n const styles: Record<string, string> = {\n open: \"text-accent bg-accent-soft\",\n resolved: \"text-insert bg-insert-soft\",\n detached: \"text-comment bg-warning-soft\",\n };\n return (\n <span className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ${styles[props.status] ?? \"text-secondary bg-subtle\"}`}>\n {props.status}\n </span>\n );\n}\n","import type { RuntimeRenderSnapshot } from \"../../api/public-types\";\n\ntype Revision = RuntimeRenderSnapshot[\"trackedChanges\"][\"revisions\"][number];\ntype MarkupDisplay = \"clean\" | \"simple\" | \"all\";\n\nexport function selectVisibleRevisions(\n revisions: readonly Revision[],\n markupDisplay: MarkupDisplay,\n): Revision[] {\n switch (markupDisplay) {\n case \"clean\":\n case \"simple\":\n return revisions.filter(\n (revision) =>\n revision.status === \"active\" && revision.actionability === \"actionable\",\n );\n case \"all\":\n return [...revisions];\n }\n}\n\nexport function describeEmptyRevisionState(\n markupDisplay: MarkupDisplay,\n totalCount: number,\n): string {\n if ((markupDisplay === \"clean\" || markupDisplay === \"simple\") && totalCount > 0) {\n return \"Simple markup keeps the rail focused on actionable live changes. Switch to All to inspect preserve-only or historical revision records.\";\n }\n\n return \"Runtime-backed change cards will appear here when tracked changes are present.\";\n}\n","import React from \"react\";\nimport { Check, X } from \"lucide-react\";\n\nimport type { TrackedChangesSnapshot, TrackedChangeEntrySnapshot } from \"../../api/public-types\";\nimport { selectVisibleRevisions } from \"../../ui/shared/revision-filters\";\nimport type { MarkupDisplay } from \"../../ui/headless/comment-decoration-model\";\n\nexport interface TwRevisionSidebarProps {\n trackedChanges: TrackedChangesSnapshot;\n markupDisplay: MarkupDisplay;\n activeRevisionId?: string;\n onOpenRevision?: (revision: TrackedChangeEntrySnapshot) => void;\n onAcceptRevision?: (revisionId: string) => void;\n onRejectRevision?: (revisionId: string) => void;\n onAcceptAllChanges?: () => void;\n onRejectAllChanges?: () => void;\n}\n\nconst focusRingClass =\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-canvas\";\n\nexport function TwRevisionSidebar(props: TwRevisionSidebarProps) {\n const { trackedChanges, markupDisplay, activeRevisionId } = props;\n const visibleRevisions = selectVisibleRevisions(trackedChanges.revisions, markupDisplay);\n const actionablePendingCount = trackedChanges.revisions.filter(\n (r) => r.status === \"active\" && r.actionability === \"actionable\",\n ).length;\n\n return (\n <div className=\"outline-none\">\n <p className=\"text-xs text-tertiary mb-3\">\n {trackedChanges.pendingChangeIds.length} active · {trackedChanges.acceptedChangeIds.length} accepted · {trackedChanges.preserveOnlyChangeIds.length} preserve-only\n </p>\n\n {/* Bulk actions */}\n <div className=\"flex gap-1.5 mb-3\">\n <button\n type=\"button\"\n disabled={actionablePendingCount === 0}\n className=\"inline-flex items-center gap-1 rounded-md px-2.5 py-1.5 text-xs font-semibold text-accent hover:bg-accent-soft transition-colors disabled:opacity-30 disabled:cursor-not-allowed\"\n onClick={props.onAcceptAllChanges}\n >\n Accept all ({actionablePendingCount})\n </button>\n <button\n type=\"button\"\n disabled={actionablePendingCount === 0}\n className=\"inline-flex items-center gap-1 rounded-md px-2.5 py-1.5 text-xs text-secondary hover:bg-surface transition-colors disabled:opacity-30 disabled:cursor-not-allowed\"\n onClick={props.onRejectAllChanges}\n >\n Reject all\n </button>\n </div>\n\n {visibleRevisions.length > 0 ? (\n <div className=\"space-y-1\">\n {visibleRevisions.map((rev) => {\n const isActive = activeRevisionId === rev.revisionId;\n\n return (\n <div\n key={rev.revisionId}\n role=\"button\"\n tabIndex={0}\n className={`flex rounded-lg transition-colors cursor-pointer ${focusRingClass} ${isActive ? \"bg-accent-soft\" : \"hover:bg-surface\"}`}\n onClick={() => props.onOpenRevision?.(rev)}\n onKeyDown={(event) => {\n if (event.key === \"Enter\" || event.key === \" \") {\n event.preventDefault();\n props.onOpenRevision?.(rev);\n }\n }}\n >\n <div className={`w-0.5 shrink-0 rounded-l-lg ${\n rev.kind === \"insertion\" ? \"bg-insert\"\n : rev.kind === \"deletion\" ? \"bg-danger\"\n : \"bg-tertiary\"\n }`} />\n <div className=\"p-2.5 flex-1 min-w-0\">\n <div className=\"flex items-start justify-between gap-2 mb-1\">\n <span className=\"text-sm font-medium text-primary\">{rev.anchorLabel}</span>\n <RevisionBadge status={rev.status} actionability={rev.actionability} />\n </div>\n <p className=\"text-xs text-tertiary mb-1\">{rev.authorId} · {rev.createdAt}</p>\n {rev.excerpt ? (\n <p className={`text-sm ${\n rev.kind === \"insertion\" ? \"text-insert\"\n : rev.kind === \"deletion\" ? \"text-danger line-through\"\n : \"text-secondary\"\n }`}>\n {rev.excerpt}\n </p>\n ) : (\n <p className=\"text-sm text-secondary\">{rev.label}</p>\n )}\n {rev.detail ? (\n <p className=\"text-xs text-secondary mt-1\">{rev.detail}</p>\n ) : null}\n <div className=\"flex gap-1.5 mt-2\">\n {rev.actionability === \"actionable\" ? (\n <>\n <button\n type=\"button\"\n disabled={!rev.canAccept || rev.status === \"accepted\"}\n className=\"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs text-insert hover:bg-insert-soft transition-colors disabled:opacity-30 disabled:cursor-not-allowed\"\n onClick={(e) => {\n e.stopPropagation();\n props.onAcceptRevision?.(rev.revisionId);\n }}\n >\n <Check className=\"h-3 w-3\" /> Accept\n </button>\n <button\n type=\"button\"\n disabled={!rev.canReject || rev.status === \"rejected\"}\n className=\"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs text-danger hover:bg-delete-soft transition-colors disabled:opacity-30 disabled:cursor-not-allowed\"\n onClick={(e) => {\n e.stopPropagation();\n props.onRejectRevision?.(rev.revisionId);\n }}\n >\n <X className=\"h-3 w-3\" /> Reject\n </button>\n </>\n ) : (\n <span className=\"text-xs text-tertiary px-2 py-1\">Preserve-only</span>\n )}\n </div>\n </div>\n </div>\n );\n })}\n </div>\n ) : (\n <p className=\"text-xs text-tertiary py-4\">\n {trackedChanges.totalCount > 0\n ? \"Switch to Full markup to see all tracked changes.\"\n : \"Tracked change cards will appear here when present.\"}\n </p>\n )}\n </div>\n );\n}\n\nfunction RevisionBadge(props: { status: string; actionability: string }) {\n if (props.actionability === \"preserve-only\") {\n return (\n <span className=\"inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium text-comment bg-warning-soft\">\n preserve-only\n </span>\n );\n }\n const styles: Record<string, string> = {\n active: \"text-secondary bg-subtle\",\n accepted: \"text-insert bg-insert-soft\",\n rejected: \"text-danger bg-delete-soft\",\n detached: \"text-comment bg-warning-soft\",\n };\n return (\n <span className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ${styles[props.status] ?? \"text-secondary bg-subtle\"}`}>\n {props.status}\n </span>\n );\n}\n","import React from \"react\";\n\nimport * as Tabs from \"@radix-ui/react-tabs\";\nimport * as ScrollArea from \"@radix-ui/react-scroll-area\";\n\nimport type {\n CommentSidebarSnapshot,\n CommentSidebarThreadSnapshot,\n CompatibilityPanelSnapshot,\n EditorWarning,\n TrackedChangesSnapshot,\n TrackedChangeEntrySnapshot,\n} from \"../../api/public-types\";\nimport type { MarkupDisplay } from \"../../ui/headless/comment-decoration-model\";\nimport { TwCommentSidebar } from \"./tw-comment-sidebar\";\nimport { TwRevisionSidebar } from \"./tw-revision-sidebar\";\nimport { TwHealthPanel } from \"./tw-health-panel\";\n\nexport type ReviewRailTab = \"comments\" | \"changes\";\n\nexport interface TwReviewRailProps {\n activeTab: ReviewRailTab;\n currentUserId?: string;\n comments: CommentSidebarSnapshot;\n trackedChanges: TrackedChangesSnapshot;\n compatibility: CompatibilityPanelSnapshot;\n warnings: EditorWarning[];\n markupDisplay: MarkupDisplay;\n activeCommentId?: string;\n activeRevisionId?: string;\n onActiveTabChange: (tab: ReviewRailTab) => void;\n onOpenComment?: (thread: CommentSidebarThreadSnapshot) => void;\n onResolveComment?: (commentId: string) => void;\n onReopenComment?: (commentId: string) => void;\n onAddReply?: (commentId: string, body: string) => void;\n onEditBody?: (commentId: string, body: string) => void;\n onOpenRevision?: (revision: TrackedChangeEntrySnapshot) => void;\n onAcceptRevision?: (revisionId: string) => void;\n onRejectRevision?: (revisionId: string) => void;\n onAcceptAllChanges?: () => void;\n onRejectAllChanges?: () => void;\n}\n\nconst focusRingClass =\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-canvas\";\n\nexport function TwReviewRail(props: TwReviewRailProps) {\n const warningCount = props.compatibility.featureEntries.filter(\n (e) => e.featureClass !== \"supported-roundtrip\",\n ).length + props.warnings.length;\n\n return (\n <aside\n aria-label=\"Review rail\"\n className=\"flex w-[340px] shrink-0 flex-col border-l border-border bg-canvas\"\n >\n <Tabs.Root\n value={props.activeTab}\n onValueChange={(v: string) => props.onActiveTabChange(v as ReviewRailTab)}\n className=\"flex flex-1 flex-col min-h-0\"\n >\n <Tabs.List className=\"flex shrink-0 border-b border-border\">\n <Tabs.Trigger\n value=\"comments\"\n className={`flex-1 py-2 text-xs text-tertiary transition-colors data-[state=active]:text-primary data-[state=active]:shadow-[inset_0_-2px_0_var(--color-accent)] outline-none ${focusRingClass}`}\n >\n Comments{\" \"}\n <span className=\"text-tertiary\">{props.comments.totalCount}</span>\n </Tabs.Trigger>\n <Tabs.Trigger\n value=\"changes\"\n className={`flex-1 py-2 text-xs text-tertiary transition-colors data-[state=active]:text-primary data-[state=active]:shadow-[inset_0_-2px_0_var(--color-accent)] outline-none ${focusRingClass}`}\n >\n Changes{\" \"}\n <span className=\"text-tertiary\">{props.trackedChanges.totalCount}</span>\n </Tabs.Trigger>\n {/* Health moved to toolbar popover */}\n </Tabs.List>\n\n <ScrollArea.Root className=\"flex-1 min-h-0\">\n <ScrollArea.Viewport className=\"h-full w-full\">\n <Tabs.Content value=\"comments\" className=\"p-3 outline-none\">\n <TwCommentSidebar\n currentUserId={props.currentUserId}\n comments={props.comments}\n activeCommentId={props.activeCommentId}\n onOpenComment={props.onOpenComment}\n onResolveComment={props.onResolveComment}\n onReopenComment={props.onReopenComment}\n onAddReply={props.onAddReply}\n onEditBody={props.onEditBody}\n />\n </Tabs.Content>\n\n <Tabs.Content value=\"changes\" className=\"p-3 outline-none\">\n <TwRevisionSidebar\n trackedChanges={props.trackedChanges}\n markupDisplay={props.markupDisplay}\n activeRevisionId={props.activeRevisionId}\n onOpenRevision={props.onOpenRevision}\n onAcceptRevision={props.onAcceptRevision}\n onRejectRevision={props.onRejectRevision}\n onAcceptAllChanges={props.onAcceptAllChanges}\n onRejectAllChanges={props.onRejectAllChanges}\n />\n </Tabs.Content>\n\n {/* Health panel moved to toolbar popover */}\n </ScrollArea.Viewport>\n <ScrollArea.Scrollbar\n orientation=\"vertical\"\n className=\"flex w-1.5 touch-none select-none p-0.5\"\n >\n <ScrollArea.Thumb className=\"relative flex-1 rounded-full bg-black/[0.12]\" />\n </ScrollArea.Scrollbar>\n </ScrollArea.Root>\n </Tabs.Root>\n </aside>\n );\n}\n","import React from \"react\";\n\nexport interface TwStatusBarProps {\n isDirty: boolean;\n isExportBlocked: boolean;\n preserveOnlyCount: number;\n commentCount: number;\n changeCount: number;\n sessionId: string;\n}\n\nexport function TwStatusBar(props: TwStatusBarProps) {\n const saveState = props.isExportBlocked\n ? \"Read-only\"\n : props.isDirty\n ? \"Unsaved\"\n : \"Ready\";\n const exportState = props.isExportBlocked\n ? \"Blocked\"\n : props.preserveOnlyCount > 0\n ? \"Warnings\"\n : \"Ready\";\n\n return (\n <footer className=\"flex h-7 shrink-0 items-center gap-4 border-t border-border px-3 text-xs text-tertiary\">\n <span className=\"flex items-center gap-1.5\">\n <span\n className={`inline-block h-1.5 w-1.5 rounded-full ${\n props.isExportBlocked\n ? \"bg-danger\"\n : props.isDirty\n ? \"bg-comment\"\n : \"bg-insert\"\n }`}\n />\n {saveState}\n </span>\n <span className=\"flex items-center gap-1.5\">\n <span\n className={`inline-block h-1.5 w-1.5 rounded-full ${\n props.isExportBlocked\n ? \"bg-danger\"\n : props.preserveOnlyCount > 0\n ? \"bg-comment\"\n : \"bg-insert\"\n }`}\n />\n Export {exportState.toLowerCase()}\n </span>\n <span>\n {props.commentCount} comment{props.commentCount !== 1 ? \"s\" : \"\"} ·{\" \"}\n {props.changeCount} change{props.changeCount !== 1 ? \"s\" : \"\"}\n </span>\n <span className=\"flex-1\" />\n <span>{props.sessionId}</span>\n </footer>\n );\n}\n","import * as React from 'react';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { DismissableLayer } from '@radix-ui/react-dismissable-layer';\nimport { useFocusGuards } from '@radix-ui/react-focus-guards';\nimport { FocusScope } from '@radix-ui/react-focus-scope';\nimport { useId } from '@radix-ui/react-id';\nimport * as PopperPrimitive from '@radix-ui/react-popper';\nimport { createPopperScope } from '@radix-ui/react-popper';\nimport { Portal as PortalPrimitive } from '@radix-ui/react-portal';\nimport { Presence } from '@radix-ui/react-presence';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { createSlot } from '@radix-ui/react-slot';\nimport { useControllableState } from '@radix-ui/react-use-controllable-state';\nimport { hideOthers } from 'aria-hidden';\nimport { RemoveScroll } from 'react-remove-scroll';\n\nimport type { Scope } from '@radix-ui/react-context';\n\n/* -------------------------------------------------------------------------------------------------\n * Popover\n * -----------------------------------------------------------------------------------------------*/\n\nconst POPOVER_NAME = 'Popover';\n\ntype ScopedProps<P> = P & { __scopePopover?: Scope };\nconst [createPopoverContext, createPopoverScope] = createContextScope(POPOVER_NAME, [\n createPopperScope,\n]);\nconst usePopperScope = createPopperScope();\n\ntype PopoverContextValue = {\n triggerRef: React.RefObject<HTMLButtonElement | null>;\n contentId: string;\n open: boolean;\n onOpenChange(open: boolean): void;\n onOpenToggle(): void;\n hasCustomAnchor: boolean;\n onCustomAnchorAdd(): void;\n onCustomAnchorRemove(): void;\n modal: boolean;\n};\n\nconst [PopoverProvider, usePopoverContext] =\n createPopoverContext<PopoverContextValue>(POPOVER_NAME);\n\ninterface PopoverProps {\n children?: React.ReactNode;\n open?: boolean;\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n modal?: boolean;\n}\n\nconst Popover: React.FC<PopoverProps> = (props: ScopedProps<PopoverProps>) => {\n const {\n __scopePopover,\n children,\n open: openProp,\n defaultOpen,\n onOpenChange,\n modal = false,\n } = props;\n const popperScope = usePopperScope(__scopePopover);\n const triggerRef = React.useRef<HTMLButtonElement>(null);\n const [hasCustomAnchor, setHasCustomAnchor] = React.useState(false);\n const [open, setOpen] = useControllableState({\n prop: openProp,\n defaultProp: defaultOpen ?? false,\n onChange: onOpenChange,\n caller: POPOVER_NAME,\n });\n\n return (\n <PopperPrimitive.Root {...popperScope}>\n <PopoverProvider\n scope={__scopePopover}\n contentId={useId()}\n triggerRef={triggerRef}\n open={open}\n onOpenChange={setOpen}\n onOpenToggle={React.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen])}\n hasCustomAnchor={hasCustomAnchor}\n onCustomAnchorAdd={React.useCallback(() => setHasCustomAnchor(true), [])}\n onCustomAnchorRemove={React.useCallback(() => setHasCustomAnchor(false), [])}\n modal={modal}\n >\n {children}\n </PopoverProvider>\n </PopperPrimitive.Root>\n );\n};\n\nPopover.displayName = POPOVER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopoverAnchor\n * -----------------------------------------------------------------------------------------------*/\n\nconst ANCHOR_NAME = 'PopoverAnchor';\n\ntype PopoverAnchorElement = React.ComponentRef<typeof PopperPrimitive.Anchor>;\ntype PopperAnchorProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Anchor>;\ninterface PopoverAnchorProps extends PopperAnchorProps {}\n\nconst PopoverAnchor = React.forwardRef<PopoverAnchorElement, PopoverAnchorProps>(\n (props: ScopedProps<PopoverAnchorProps>, forwardedRef) => {\n const { __scopePopover, ...anchorProps } = props;\n const context = usePopoverContext(ANCHOR_NAME, __scopePopover);\n const popperScope = usePopperScope(__scopePopover);\n const { onCustomAnchorAdd, onCustomAnchorRemove } = context;\n\n React.useEffect(() => {\n onCustomAnchorAdd();\n return () => onCustomAnchorRemove();\n }, [onCustomAnchorAdd, onCustomAnchorRemove]);\n\n return <PopperPrimitive.Anchor {...popperScope} {...anchorProps} ref={forwardedRef} />;\n }\n);\n\nPopoverAnchor.displayName = ANCHOR_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopoverTrigger\n * -----------------------------------------------------------------------------------------------*/\n\nconst TRIGGER_NAME = 'PopoverTrigger';\n\ntype PopoverTriggerElement = React.ComponentRef<typeof Primitive.button>;\ntype PrimitiveButtonProps = React.ComponentPropsWithoutRef<typeof Primitive.button>;\ninterface PopoverTriggerProps extends PrimitiveButtonProps {}\n\nconst PopoverTrigger = React.forwardRef<PopoverTriggerElement, PopoverTriggerProps>(\n (props: ScopedProps<PopoverTriggerProps>, forwardedRef) => {\n const { __scopePopover, ...triggerProps } = props;\n const context = usePopoverContext(TRIGGER_NAME, __scopePopover);\n const popperScope = usePopperScope(__scopePopover);\n const composedTriggerRef = useComposedRefs(forwardedRef, context.triggerRef);\n\n const trigger = (\n <Primitive.button\n type=\"button\"\n aria-haspopup=\"dialog\"\n aria-expanded={context.open}\n aria-controls={context.contentId}\n data-state={getState(context.open)}\n {...triggerProps}\n ref={composedTriggerRef}\n onClick={composeEventHandlers(props.onClick, context.onOpenToggle)}\n />\n );\n\n return context.hasCustomAnchor ? (\n trigger\n ) : (\n <PopperPrimitive.Anchor asChild {...popperScope}>\n {trigger}\n </PopperPrimitive.Anchor>\n );\n }\n);\n\nPopoverTrigger.displayName = TRIGGER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopoverPortal\n * -----------------------------------------------------------------------------------------------*/\n\nconst PORTAL_NAME = 'PopoverPortal';\n\ntype PortalContextValue = { forceMount?: true };\nconst [PortalProvider, usePortalContext] = createPopoverContext<PortalContextValue>(PORTAL_NAME, {\n forceMount: undefined,\n});\n\ntype PortalProps = React.ComponentPropsWithoutRef<typeof PortalPrimitive>;\ninterface PopoverPortalProps {\n children?: React.ReactNode;\n /**\n * Specify a container element to portal the content into.\n */\n container?: PortalProps['container'];\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst PopoverPortal: React.FC<PopoverPortalProps> = (props: ScopedProps<PopoverPortalProps>) => {\n const { __scopePopover, forceMount, children, container } = props;\n const context = usePopoverContext(PORTAL_NAME, __scopePopover);\n return (\n <PortalProvider scope={__scopePopover} forceMount={forceMount}>\n <Presence present={forceMount || context.open}>\n <PortalPrimitive asChild container={container}>\n {children}\n </PortalPrimitive>\n </Presence>\n </PortalProvider>\n );\n};\n\nPopoverPortal.displayName = PORTAL_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopoverContent\n * -----------------------------------------------------------------------------------------------*/\n\nconst CONTENT_NAME = 'PopoverContent';\n\ninterface PopoverContentProps extends PopoverContentTypeProps {\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst PopoverContent = React.forwardRef<PopoverContentTypeElement, PopoverContentProps>(\n (props: ScopedProps<PopoverContentProps>, forwardedRef) => {\n const portalContext = usePortalContext(CONTENT_NAME, props.__scopePopover);\n const { forceMount = portalContext.forceMount, ...contentProps } = props;\n const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);\n return (\n <Presence present={forceMount || context.open}>\n {context.modal ? (\n <PopoverContentModal {...contentProps} ref={forwardedRef} />\n ) : (\n <PopoverContentNonModal {...contentProps} ref={forwardedRef} />\n )}\n </Presence>\n );\n }\n);\n\nPopoverContent.displayName = CONTENT_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Slot = createSlot('PopoverContent.RemoveScroll');\n\ntype PopoverContentTypeElement = PopoverContentImplElement;\ninterface PopoverContentTypeProps\n extends Omit<PopoverContentImplProps, 'trapFocus' | 'disableOutsidePointerEvents'> {}\n\nconst PopoverContentModal = React.forwardRef<PopoverContentTypeElement, PopoverContentTypeProps>(\n (props: ScopedProps<PopoverContentTypeProps>, forwardedRef) => {\n const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);\n const contentRef = React.useRef<HTMLDivElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, contentRef);\n const isRightClickOutsideRef = React.useRef(false);\n\n // aria-hide everything except the content (better supported equivalent to setting aria-modal)\n React.useEffect(() => {\n const content = contentRef.current;\n if (content) return hideOthers(content);\n }, []);\n\n return (\n <RemoveScroll as={Slot} allowPinchZoom>\n <PopoverContentImpl\n {...props}\n ref={composedRefs}\n // we make sure we're not trapping once it's been closed\n // (closed !== unmounted when animating out)\n trapFocus={context.open}\n disableOutsidePointerEvents\n onCloseAutoFocus={composeEventHandlers(props.onCloseAutoFocus, (event) => {\n event.preventDefault();\n if (!isRightClickOutsideRef.current) context.triggerRef.current?.focus();\n })}\n onPointerDownOutside={composeEventHandlers(\n props.onPointerDownOutside,\n (event) => {\n const originalEvent = event.detail.originalEvent;\n const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;\n const isRightClick = originalEvent.button === 2 || ctrlLeftClick;\n\n isRightClickOutsideRef.current = isRightClick;\n },\n { checkForDefaultPrevented: false }\n )}\n // When focus is trapped, a `focusout` event may still happen.\n // We make sure we don't trigger our `onDismiss` in such case.\n onFocusOutside={composeEventHandlers(\n props.onFocusOutside,\n (event) => event.preventDefault(),\n { checkForDefaultPrevented: false }\n )}\n />\n </RemoveScroll>\n );\n }\n);\n\nconst PopoverContentNonModal = React.forwardRef<PopoverContentTypeElement, PopoverContentTypeProps>(\n (props: ScopedProps<PopoverContentTypeProps>, forwardedRef) => {\n const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);\n const hasInteractedOutsideRef = React.useRef(false);\n const hasPointerDownOutsideRef = React.useRef(false);\n\n return (\n <PopoverContentImpl\n {...props}\n ref={forwardedRef}\n trapFocus={false}\n disableOutsidePointerEvents={false}\n onCloseAutoFocus={(event) => {\n props.onCloseAutoFocus?.(event);\n\n if (!event.defaultPrevented) {\n if (!hasInteractedOutsideRef.current) context.triggerRef.current?.focus();\n // Always prevent auto focus because we either focus manually or want user agent focus\n event.preventDefault();\n }\n\n hasInteractedOutsideRef.current = false;\n hasPointerDownOutsideRef.current = false;\n }}\n onInteractOutside={(event) => {\n props.onInteractOutside?.(event);\n\n if (!event.defaultPrevented) {\n hasInteractedOutsideRef.current = true;\n if (event.detail.originalEvent.type === 'pointerdown') {\n hasPointerDownOutsideRef.current = true;\n }\n }\n\n // Prevent dismissing when clicking the trigger.\n // As the trigger is already setup to close, without doing so would\n // cause it to close and immediately open.\n const target = event.target as HTMLElement;\n const targetIsTrigger = context.triggerRef.current?.contains(target);\n if (targetIsTrigger) event.preventDefault();\n\n // On Safari if the trigger is inside a container with tabIndex={0}, when clicked\n // we will get the pointer down outside event on the trigger, but then a subsequent\n // focus outside event on the container, we ignore any focus outside event when we've\n // already had a pointer down outside event.\n if (event.detail.originalEvent.type === 'focusin' && hasPointerDownOutsideRef.current) {\n event.preventDefault();\n }\n }}\n />\n );\n }\n);\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype PopoverContentImplElement = React.ComponentRef<typeof PopperPrimitive.Content>;\ntype FocusScopeProps = React.ComponentPropsWithoutRef<typeof FocusScope>;\ntype DismissableLayerProps = React.ComponentPropsWithoutRef<typeof DismissableLayer>;\ntype PopperContentProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Content>;\ninterface PopoverContentImplProps\n extends Omit<PopperContentProps, 'onPlaced'>,\n Omit<DismissableLayerProps, 'onDismiss'> {\n /**\n * Whether focus should be trapped within the `Popover`\n * (default: false)\n */\n trapFocus?: FocusScopeProps['trapped'];\n\n /**\n * Event handler called when auto-focusing on open.\n * Can be prevented.\n */\n onOpenAutoFocus?: FocusScopeProps['onMountAutoFocus'];\n\n /**\n * Event handler called when auto-focusing on close.\n * Can be prevented.\n */\n onCloseAutoFocus?: FocusScopeProps['onUnmountAutoFocus'];\n}\n\nconst PopoverContentImpl = React.forwardRef<PopoverContentImplElement, PopoverContentImplProps>(\n (props: ScopedProps<PopoverContentImplProps>, forwardedRef) => {\n const {\n __scopePopover,\n trapFocus,\n onOpenAutoFocus,\n onCloseAutoFocus,\n disableOutsidePointerEvents,\n onEscapeKeyDown,\n onPointerDownOutside,\n onFocusOutside,\n onInteractOutside,\n ...contentProps\n } = props;\n const context = usePopoverContext(CONTENT_NAME, __scopePopover);\n const popperScope = usePopperScope(__scopePopover);\n\n // Make sure the whole tree has focus guards as our `Popover` may be\n // the last element in the DOM (because of the `Portal`)\n useFocusGuards();\n\n return (\n <FocusScope\n asChild\n loop\n trapped={trapFocus}\n onMountAutoFocus={onOpenAutoFocus}\n onUnmountAutoFocus={onCloseAutoFocus}\n >\n <DismissableLayer\n asChild\n disableOutsidePointerEvents={disableOutsidePointerEvents}\n onInteractOutside={onInteractOutside}\n onEscapeKeyDown={onEscapeKeyDown}\n onPointerDownOutside={onPointerDownOutside}\n onFocusOutside={onFocusOutside}\n onDismiss={() => context.onOpenChange(false)}\n >\n <PopperPrimitive.Content\n data-state={getState(context.open)}\n role=\"dialog\"\n id={context.contentId}\n {...popperScope}\n {...contentProps}\n ref={forwardedRef}\n style={{\n ...contentProps.style,\n // re-namespace exposed content custom properties\n ...{\n '--radix-popover-content-transform-origin': 'var(--radix-popper-transform-origin)',\n '--radix-popover-content-available-width': 'var(--radix-popper-available-width)',\n '--radix-popover-content-available-height': 'var(--radix-popper-available-height)',\n '--radix-popover-trigger-width': 'var(--radix-popper-anchor-width)',\n '--radix-popover-trigger-height': 'var(--radix-popper-anchor-height)',\n },\n }}\n />\n </DismissableLayer>\n </FocusScope>\n );\n }\n);\n\n/* -------------------------------------------------------------------------------------------------\n * PopoverClose\n * -----------------------------------------------------------------------------------------------*/\n\nconst CLOSE_NAME = 'PopoverClose';\n\ntype PopoverCloseElement = React.ComponentRef<typeof Primitive.button>;\ninterface PopoverCloseProps extends PrimitiveButtonProps {}\n\nconst PopoverClose = React.forwardRef<PopoverCloseElement, PopoverCloseProps>(\n (props: ScopedProps<PopoverCloseProps>, forwardedRef) => {\n const { __scopePopover, ...closeProps } = props;\n const context = usePopoverContext(CLOSE_NAME, __scopePopover);\n return (\n <Primitive.button\n type=\"button\"\n {...closeProps}\n ref={forwardedRef}\n onClick={composeEventHandlers(props.onClick, () => context.onOpenChange(false))}\n />\n );\n }\n);\n\nPopoverClose.displayName = CLOSE_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopoverArrow\n * -----------------------------------------------------------------------------------------------*/\n\nconst ARROW_NAME = 'PopoverArrow';\n\ntype PopoverArrowElement = React.ComponentRef<typeof PopperPrimitive.Arrow>;\ntype PopperArrowProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Arrow>;\ninterface PopoverArrowProps extends PopperArrowProps {}\n\nconst PopoverArrow = React.forwardRef<PopoverArrowElement, PopoverArrowProps>(\n (props: ScopedProps<PopoverArrowProps>, forwardedRef) => {\n const { __scopePopover, ...arrowProps } = props;\n const popperScope = usePopperScope(__scopePopover);\n return <PopperPrimitive.Arrow {...popperScope} {...arrowProps} ref={forwardedRef} />;\n }\n);\n\nPopoverArrow.displayName = ARROW_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nfunction getState(open: boolean) {\n return open ? 'open' : 'closed';\n}\n\nconst Root = Popover;\nconst Anchor = PopoverAnchor;\nconst Trigger = PopoverTrigger;\nconst Portal = PopoverPortal;\nconst Content = PopoverContent;\nconst Close = PopoverClose;\nconst Arrow = PopoverArrow;\n\nexport {\n createPopoverScope,\n //\n Popover,\n PopoverAnchor,\n PopoverTrigger,\n PopoverPortal,\n PopoverContent,\n PopoverClose,\n PopoverArrow,\n //\n Root,\n Anchor,\n Trigger,\n Portal,\n Content,\n Close,\n Arrow,\n};\nexport type {\n PopoverProps,\n PopoverAnchorProps,\n PopoverTriggerProps,\n PopoverPortalProps,\n PopoverContentProps,\n PopoverCloseProps,\n PopoverArrowProps,\n};\n","import * as React from 'react';\n\n/** Number of components which have requested interest to have focus guards */\nlet count = 0;\n\ninterface FocusGuardsProps {\n children?: React.ReactNode;\n}\n\nfunction FocusGuards(props: FocusGuardsProps) {\n useFocusGuards();\n return props.children;\n}\n\n/**\n * Injects a pair of focus guards at the edges of the whole DOM tree\n * to ensure `focusin` & `focusout` events can be caught consistently.\n */\nfunction useFocusGuards() {\n /* eslint-disable no-restricted-globals */\n React.useEffect(() => {\n const edgeGuards = document.querySelectorAll('[data-radix-focus-guard]');\n document.body.insertAdjacentElement('afterbegin', edgeGuards[0] ?? createFocusGuard());\n document.body.insertAdjacentElement('beforeend', edgeGuards[1] ?? createFocusGuard());\n count++;\n\n return () => {\n if (count === 1) {\n document.querySelectorAll('[data-radix-focus-guard]').forEach((node) => node.remove());\n }\n count--;\n };\n }, []);\n /* eslint-enable no-restricted-globals */\n}\n\nfunction createFocusGuard() {\n // eslint-disable-next-line no-restricted-globals\n const element = document.createElement('span');\n element.setAttribute('data-radix-focus-guard', '');\n element.tabIndex = 0;\n element.style.outline = 'none';\n element.style.opacity = '0';\n element.style.position = 'fixed';\n element.style.pointerEvents = 'none';\n return element;\n}\n\nexport {\n FocusGuards,\n //\n FocusGuards as Root,\n //\n useFocusGuards,\n};\n","import * as React from 'react';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\n\nconst AUTOFOCUS_ON_MOUNT = 'focusScope.autoFocusOnMount';\nconst AUTOFOCUS_ON_UNMOUNT = 'focusScope.autoFocusOnUnmount';\nconst EVENT_OPTIONS = { bubbles: false, cancelable: true };\n\ntype FocusableTarget = HTMLElement | { focus(): void };\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope\n * -----------------------------------------------------------------------------------------------*/\n\nconst FOCUS_SCOPE_NAME = 'FocusScope';\n\ntype FocusScopeElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface FocusScopeProps extends PrimitiveDivProps {\n /**\n * When `true`, tabbing from last item will focus first tabbable\n * and shift+tab from first item will focus last tababble.\n * @defaultValue false\n */\n loop?: boolean;\n\n /**\n * When `true`, focus cannot escape the focus scope via keyboard,\n * pointer, or a programmatic focus.\n * @defaultValue false\n */\n trapped?: boolean;\n\n /**\n * Event handler called when auto-focusing on mount.\n * Can be prevented.\n */\n onMountAutoFocus?: (event: Event) => void;\n\n /**\n * Event handler called when auto-focusing on unmount.\n * Can be prevented.\n */\n onUnmountAutoFocus?: (event: Event) => void;\n}\n\nconst FocusScope = React.forwardRef<FocusScopeElement, FocusScopeProps>((props, forwardedRef) => {\n const {\n loop = false,\n trapped = false,\n onMountAutoFocus: onMountAutoFocusProp,\n onUnmountAutoFocus: onUnmountAutoFocusProp,\n ...scopeProps\n } = props;\n const [container, setContainer] = React.useState<HTMLElement | null>(null);\n const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);\n const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);\n const lastFocusedElementRef = React.useRef<HTMLElement | null>(null);\n const composedRefs = useComposedRefs(forwardedRef, (node) => setContainer(node));\n\n const focusScope = React.useRef({\n paused: false,\n pause() {\n this.paused = true;\n },\n resume() {\n this.paused = false;\n },\n }).current;\n\n // Takes care of trapping focus if focus is moved outside programmatically for example\n React.useEffect(() => {\n if (trapped) {\n function handleFocusIn(event: FocusEvent) {\n if (focusScope.paused || !container) return;\n const target = event.target as HTMLElement | null;\n if (container.contains(target)) {\n lastFocusedElementRef.current = target;\n } else {\n focus(lastFocusedElementRef.current, { select: true });\n }\n }\n\n function handleFocusOut(event: FocusEvent) {\n if (focusScope.paused || !container) return;\n const relatedTarget = event.relatedTarget as HTMLElement | null;\n\n // A `focusout` event with a `null` `relatedTarget` will happen in at least two cases:\n //\n // 1. When the user switches app/tabs/windows/the browser itself loses focus.\n // 2. In Google Chrome, when the focused element is removed from the DOM.\n //\n // We let the browser do its thing here because:\n //\n // 1. The browser already keeps a memory of what's focused for when the page gets refocused.\n // 2. In Google Chrome, if we try to focus the deleted focused element (as per below), it\n // throws the CPU to 100%, so we avoid doing anything for this reason here too.\n if (relatedTarget === null) return;\n\n // If the focus has moved to an actual legitimate element (`relatedTarget !== null`)\n // that is outside the container, we move focus to the last valid focused element inside.\n if (!container.contains(relatedTarget)) {\n focus(lastFocusedElementRef.current, { select: true });\n }\n }\n\n // When the focused element gets removed from the DOM, browsers move focus\n // back to the document.body. In this case, we move focus to the container\n // to keep focus trapped correctly.\n function handleMutations(mutations: MutationRecord[]) {\n const focusedElement = document.activeElement as HTMLElement | null;\n if (focusedElement !== document.body) return;\n for (const mutation of mutations) {\n if (mutation.removedNodes.length > 0) focus(container);\n }\n }\n\n document.addEventListener('focusin', handleFocusIn);\n document.addEventListener('focusout', handleFocusOut);\n const mutationObserver = new MutationObserver(handleMutations);\n if (container) mutationObserver.observe(container, { childList: true, subtree: true });\n\n return () => {\n document.removeEventListener('focusin', handleFocusIn);\n document.removeEventListener('focusout', handleFocusOut);\n mutationObserver.disconnect();\n };\n }\n }, [trapped, container, focusScope.paused]);\n\n React.useEffect(() => {\n if (container) {\n focusScopesStack.add(focusScope);\n const previouslyFocusedElement = document.activeElement as HTMLElement | null;\n const hasFocusedCandidate = container.contains(previouslyFocusedElement);\n\n if (!hasFocusedCandidate) {\n const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);\n container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n container.dispatchEvent(mountEvent);\n if (!mountEvent.defaultPrevented) {\n focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });\n if (document.activeElement === previouslyFocusedElement) {\n focus(container);\n }\n }\n }\n\n return () => {\n container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n\n // We hit a react bug (fixed in v17) with focusing in unmount.\n // We need to delay the focus a little to get around it for now.\n // See: https://github.com/facebook/react/issues/17894\n setTimeout(() => {\n const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);\n container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n container.dispatchEvent(unmountEvent);\n if (!unmountEvent.defaultPrevented) {\n focus(previouslyFocusedElement ?? document.body, { select: true });\n }\n // we need to remove the listener after we `dispatchEvent`\n container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n\n focusScopesStack.remove(focusScope);\n }, 0);\n };\n }\n }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);\n\n // Takes care of looping focus (when tabbing whilst at the edges)\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (!loop && !trapped) return;\n if (focusScope.paused) return;\n\n const isTabKey = event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey;\n const focusedElement = document.activeElement as HTMLElement | null;\n\n if (isTabKey && focusedElement) {\n const container = event.currentTarget as HTMLElement;\n const [first, last] = getTabbableEdges(container);\n const hasTabbableElementsInside = first && last;\n\n // we can only wrap focus if we have tabbable edges\n if (!hasTabbableElementsInside) {\n if (focusedElement === container) event.preventDefault();\n } else {\n if (!event.shiftKey && focusedElement === last) {\n event.preventDefault();\n if (loop) focus(first, { select: true });\n } else if (event.shiftKey && focusedElement === first) {\n event.preventDefault();\n if (loop) focus(last, { select: true });\n }\n }\n }\n },\n [loop, trapped, focusScope.paused]\n );\n\n return (\n <Primitive.div tabIndex={-1} {...scopeProps} ref={composedRefs} onKeyDown={handleKeyDown} />\n );\n});\n\nFocusScope.displayName = FOCUS_SCOPE_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * Utils\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * Attempts focusing the first element in a list of candidates.\n * Stops when focus has actually moved.\n */\nfunction focusFirst(candidates: HTMLElement[], { select = false } = {}) {\n const previouslyFocusedElement = document.activeElement;\n for (const candidate of candidates) {\n focus(candidate, { select });\n if (document.activeElement !== previouslyFocusedElement) return;\n }\n}\n\n/**\n * Returns the first and last tabbable elements inside a container.\n */\nfunction getTabbableEdges(container: HTMLElement) {\n const candidates = getTabbableCandidates(container);\n const first = findVisible(candidates, container);\n const last = findVisible(candidates.reverse(), container);\n return [first, last] as const;\n}\n\n/**\n * Returns a list of potential tabbable candidates.\n *\n * NOTE: This is only a close approximation. For example it doesn't take into account cases like when\n * elements are not visible. This cannot be worked out easily by just reading a property, but rather\n * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately.\n *\n * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker\n * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1\n */\nfunction getTabbableCandidates(container: HTMLElement) {\n const nodes: HTMLElement[] = [];\n const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {\n acceptNode: (node: any) => {\n const isHiddenInput = node.tagName === 'INPUT' && node.type === 'hidden';\n if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;\n // `.tabIndex` is not the same as the `tabindex` attribute. It works on the\n // runtime's understanding of tabbability, so this automatically accounts\n // for any kind of element that could be tabbed to.\n return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;\n },\n });\n while (walker.nextNode()) nodes.push(walker.currentNode as HTMLElement);\n // we do not take into account the order of nodes with positive `tabIndex` as it\n // hinders accessibility to have tab order different from visual order.\n return nodes;\n}\n\n/**\n * Returns the first visible element in a list.\n * NOTE: Only checks visibility up to the `container`.\n */\nfunction findVisible(elements: HTMLElement[], container: HTMLElement) {\n for (const element of elements) {\n // we stop checking if it's hidden at the `container` level (excluding)\n if (!isHidden(element, { upTo: container })) return element;\n }\n}\n\nfunction isHidden(node: HTMLElement, { upTo }: { upTo?: HTMLElement }) {\n if (getComputedStyle(node).visibility === 'hidden') return true;\n while (node) {\n // we stop at `upTo` (excluding it)\n if (upTo !== undefined && node === upTo) return false;\n if (getComputedStyle(node).display === 'none') return true;\n node = node.parentElement as HTMLElement;\n }\n return false;\n}\n\nfunction isSelectableInput(element: any): element is FocusableTarget & { select: () => void } {\n return element instanceof HTMLInputElement && 'select' in element;\n}\n\nfunction focus(element?: FocusableTarget | null, { select = false } = {}) {\n // only focus if that element is focusable\n if (element && element.focus) {\n const previouslyFocusedElement = document.activeElement;\n // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users\n element.focus({ preventScroll: true });\n // only select if its not the same element, it supports selection and we need to select\n if (element !== previouslyFocusedElement && isSelectableInput(element) && select)\n element.select();\n }\n}\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope stack\n * -----------------------------------------------------------------------------------------------*/\n\ntype FocusScopeAPI = { paused: boolean; pause(): void; resume(): void };\nconst focusScopesStack = createFocusScopesStack();\n\nfunction createFocusScopesStack() {\n /** A stack of focus scopes, with the active one at the top */\n let stack: FocusScopeAPI[] = [];\n\n return {\n add(focusScope: FocusScopeAPI) {\n // pause the currently active focus scope (at the top of the stack)\n const activeFocusScope = stack[0];\n if (focusScope !== activeFocusScope) {\n activeFocusScope?.pause();\n }\n // remove in case it already exists (because we'll re-add it at the top of the stack)\n stack = arrayRemove(stack, focusScope);\n stack.unshift(focusScope);\n },\n\n remove(focusScope: FocusScopeAPI) {\n stack = arrayRemove(stack, focusScope);\n stack[0]?.resume();\n },\n };\n}\n\nfunction arrayRemove<T>(array: T[], item: T) {\n const updatedArray = [...array];\n const index = updatedArray.indexOf(item);\n if (index !== -1) {\n updatedArray.splice(index, 1);\n }\n return updatedArray;\n}\n\nfunction removeLinks(items: HTMLElement[]) {\n return items.filter((item) => item.tagName !== 'A');\n}\n\nconst Root = FocusScope;\n\nexport {\n FocusScope,\n //\n Root,\n};\nexport type { FocusScopeProps };\n","var getDefaultParent = function (originalTarget) {\n if (typeof document === 'undefined') {\n return null;\n }\n var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget;\n return sampleTarget.ownerDocument.body;\n};\nvar counterMap = new WeakMap();\nvar uncontrolledNodes = new WeakMap();\nvar markerMap = {};\nvar lockCount = 0;\nvar unwrapHost = function (node) {\n return node && (node.host || unwrapHost(node.parentNode));\n};\nvar correctTargets = function (parent, targets) {\n return targets\n .map(function (target) {\n if (parent.contains(target)) {\n return target;\n }\n var correctedTarget = unwrapHost(target);\n if (correctedTarget && parent.contains(correctedTarget)) {\n return correctedTarget;\n }\n console.error('aria-hidden', target, 'in not contained inside', parent, '. Doing nothing');\n return null;\n })\n .filter(function (x) { return Boolean(x); });\n};\n/**\n * Marks everything except given node(or nodes) as aria-hidden\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @param {String} [controlAttribute] - html Attribute to control\n * @return {Undo} undo command\n */\nvar applyAttributeToOthers = function (originalTarget, parentNode, markerName, controlAttribute) {\n var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]);\n if (!markerMap[markerName]) {\n markerMap[markerName] = new WeakMap();\n }\n var markerCounter = markerMap[markerName];\n var hiddenNodes = [];\n var elementsToKeep = new Set();\n var elementsToStop = new Set(targets);\n var keep = function (el) {\n if (!el || elementsToKeep.has(el)) {\n return;\n }\n elementsToKeep.add(el);\n keep(el.parentNode);\n };\n targets.forEach(keep);\n var deep = function (parent) {\n if (!parent || elementsToStop.has(parent)) {\n return;\n }\n Array.prototype.forEach.call(parent.children, function (node) {\n if (elementsToKeep.has(node)) {\n deep(node);\n }\n else {\n try {\n var attr = node.getAttribute(controlAttribute);\n var alreadyHidden = attr !== null && attr !== 'false';\n var counterValue = (counterMap.get(node) || 0) + 1;\n var markerValue = (markerCounter.get(node) || 0) + 1;\n counterMap.set(node, counterValue);\n markerCounter.set(node, markerValue);\n hiddenNodes.push(node);\n if (counterValue === 1 && alreadyHidden) {\n uncontrolledNodes.set(node, true);\n }\n if (markerValue === 1) {\n node.setAttribute(markerName, 'true');\n }\n if (!alreadyHidden) {\n node.setAttribute(controlAttribute, 'true');\n }\n }\n catch (e) {\n console.error('aria-hidden: cannot operate on ', node, e);\n }\n }\n });\n };\n deep(parentNode);\n elementsToKeep.clear();\n lockCount++;\n return function () {\n hiddenNodes.forEach(function (node) {\n var counterValue = counterMap.get(node) - 1;\n var markerValue = markerCounter.get(node) - 1;\n counterMap.set(node, counterValue);\n markerCounter.set(node, markerValue);\n if (!counterValue) {\n if (!uncontrolledNodes.has(node)) {\n node.removeAttribute(controlAttribute);\n }\n uncontrolledNodes.delete(node);\n }\n if (!markerValue) {\n node.removeAttribute(markerName);\n }\n });\n lockCount--;\n if (!lockCount) {\n // clear\n counterMap = new WeakMap();\n counterMap = new WeakMap();\n uncontrolledNodes = new WeakMap();\n markerMap = {};\n }\n };\n};\n/**\n * Marks everything except given node(or nodes) as aria-hidden\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Undo} undo command\n */\nexport var hideOthers = function (originalTarget, parentNode, markerName) {\n if (markerName === void 0) { markerName = 'data-aria-hidden'; }\n var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]);\n var activeParentNode = parentNode || getDefaultParent(originalTarget);\n if (!activeParentNode) {\n return function () { return null; };\n }\n // we should not hide aria-live elements - https://github.com/theKashey/aria-hidden/issues/10\n // and script elements, as they have no impact on accessibility.\n targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll('[aria-live], script')));\n return applyAttributeToOthers(targets, activeParentNode, markerName, 'aria-hidden');\n};\n/**\n * Marks everything except given node(or nodes) as inert\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Undo} undo command\n */\nexport var inertOthers = function (originalTarget, parentNode, markerName) {\n if (markerName === void 0) { markerName = 'data-inert-ed'; }\n var activeParentNode = parentNode || getDefaultParent(originalTarget);\n if (!activeParentNode) {\n return function () { return null; };\n }\n return applyAttributeToOthers(originalTarget, activeParentNode, markerName, 'inert');\n};\n/**\n * @returns if current browser supports inert\n */\nexport var supportsInert = function () {\n return typeof HTMLElement !== 'undefined' && HTMLElement.prototype.hasOwnProperty('inert');\n};\n/**\n * Automatic function to \"suppress\" DOM elements - _hide_ or _inert_ in the best possible way\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Undo} undo command\n */\nexport var suppressOthers = function (originalTarget, parentNode, markerName) {\n if (markerName === void 0) { markerName = 'data-suppressed'; }\n return (supportsInert() ? inertOthers : hideOthers)(originalTarget, parentNode, markerName);\n};\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n","import { __assign } from \"tslib\";\nimport * as React from 'react';\nimport { RemoveScroll } from './UI';\nimport SideCar from './sidecar';\nvar ReactRemoveScroll = React.forwardRef(function (props, ref) { return (React.createElement(RemoveScroll, __assign({}, props, { ref: ref, sideCar: SideCar }))); });\nReactRemoveScroll.classNames = RemoveScroll.classNames;\nexport default ReactRemoveScroll;\n","import { __assign, __rest } from \"tslib\";\nimport * as React from 'react';\nimport { fullWidthClassName, zeroRightClassName } from 'react-remove-scroll-bar/constants';\nimport { useMergeRefs } from 'use-callback-ref';\nimport { effectCar } from './medium';\nvar nothing = function () {\n return;\n};\n/**\n * Removes scrollbar from the page and contain the scroll within the Lock\n */\nvar RemoveScroll = React.forwardRef(function (props, parentRef) {\n var ref = React.useRef(null);\n var _a = React.useState({\n onScrollCapture: nothing,\n onWheelCapture: nothing,\n onTouchMoveCapture: nothing,\n }), callbacks = _a[0], setCallbacks = _a[1];\n var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noRelative = props.noRelative, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container = _b === void 0 ? 'div' : _b, gapMode = props.gapMode, rest = __rest(props, [\"forwardProps\", \"children\", \"className\", \"removeScrollBar\", \"enabled\", \"shards\", \"sideCar\", \"noRelative\", \"noIsolation\", \"inert\", \"allowPinchZoom\", \"as\", \"gapMode\"]);\n var SideCar = sideCar;\n var containerRef = useMergeRefs([ref, parentRef]);\n var containerProps = __assign(__assign({}, rest), callbacks);\n return (React.createElement(React.Fragment, null,\n enabled && (React.createElement(SideCar, { sideCar: effectCar, removeScrollBar: removeScrollBar, shards: shards, noRelative: noRelative, noIsolation: noIsolation, inert: inert, setCallbacks: setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref, gapMode: gapMode })),\n forwardProps ? (React.cloneElement(React.Children.only(children), __assign(__assign({}, containerProps), { ref: containerRef }))) : (React.createElement(Container, __assign({}, containerProps, { className: className, ref: containerRef }), children))));\n});\nRemoveScroll.defaultProps = {\n enabled: true,\n removeScrollBar: true,\n inert: false,\n};\nRemoveScroll.classNames = {\n fullWidth: fullWidthClassName,\n zeroRight: zeroRightClassName,\n};\nexport { RemoveScroll };\n","export var zeroRightClassName = 'right-scroll-bar-position';\nexport var fullWidthClassName = 'width-before-scroll-bar';\nexport var noScrollbarsClassName = 'with-scroll-bars-hidden';\n/**\n * Name of a CSS variable containing the amount of \"hidden\" scrollbar\n * ! might be undefined ! use will fallback!\n */\nexport var removedBarSizeVariable = '--removed-body-scroll-bar-size';\n","/**\n * Assigns a value for a given ref, no matter of the ref format\n * @param {RefObject} ref - a callback function or ref object\n * @param value - a new value\n *\n * @see https://github.com/theKashey/use-callback-ref#assignref\n * @example\n * const refObject = useRef();\n * const refFn = (ref) => {....}\n *\n * assignRef(refObject, \"refValue\");\n * assignRef(refFn, \"refValue\");\n */\nexport function assignRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n }\n else if (ref) {\n ref.current = value;\n }\n return ref;\n}\n","import { useState } from 'react';\n/**\n * creates a MutableRef with ref change callback\n * @param initialValue - initial ref value\n * @param {Function} callback - a callback to run when value changes\n *\n * @example\n * const ref = useCallbackRef(0, (newValue, oldValue) => console.log(oldValue, '->', newValue);\n * ref.current = 1;\n * // prints 0 -> 1\n *\n * @see https://reactjs.org/docs/hooks-reference.html#useref\n * @see https://github.com/theKashey/use-callback-ref#usecallbackref---to-replace-reactuseref\n * @returns {MutableRefObject}\n */\nexport function useCallbackRef(initialValue, callback) {\n var ref = useState(function () { return ({\n // value\n value: initialValue,\n // last callback\n callback: callback,\n // \"memoized\" public interface\n facade: {\n get current() {\n return ref.value;\n },\n set current(value) {\n var last = ref.value;\n if (last !== value) {\n ref.value = value;\n ref.callback(value, last);\n }\n },\n },\n }); })[0];\n // update callback\n ref.callback = callback;\n return ref.facade;\n}\n","import * as React from 'react';\nimport { assignRef } from './assignRef';\nimport { useCallbackRef } from './useRef';\nvar useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\nvar currentValues = new WeakMap();\n/**\n * Merges two or more refs together providing a single interface to set their value\n * @param {RefObject|Ref} refs\n * @returns {MutableRefObject} - a new ref, which translates all changes to {refs}\n *\n * @see {@link mergeRefs} a version without buit-in memoization\n * @see https://github.com/theKashey/use-callback-ref#usemergerefs\n * @example\n * const Component = React.forwardRef((props, ref) => {\n * const ownRef = useRef();\n * const domRef = useMergeRefs([ref, ownRef]); // 👈 merge together\n * return <div ref={domRef}>...</div>\n * }\n */\nexport function useMergeRefs(refs, defaultValue) {\n var callbackRef = useCallbackRef(defaultValue || null, function (newValue) {\n return refs.forEach(function (ref) { return assignRef(ref, newValue); });\n });\n // handle refs changes - added or removed\n useIsomorphicLayoutEffect(function () {\n var oldValue = currentValues.get(callbackRef);\n if (oldValue) {\n var prevRefs_1 = new Set(oldValue);\n var nextRefs_1 = new Set(refs);\n var current_1 = callbackRef.current;\n prevRefs_1.forEach(function (ref) {\n if (!nextRefs_1.has(ref)) {\n assignRef(ref, null);\n }\n });\n nextRefs_1.forEach(function (ref) {\n if (!prevRefs_1.has(ref)) {\n assignRef(ref, current_1);\n }\n });\n }\n currentValues.set(callbackRef, refs);\n }, [refs]);\n return callbackRef;\n}\n","import { __assign } from \"tslib\";\nfunction ItoI(a) {\n return a;\n}\nfunction innerCreateMedium(defaults, middleware) {\n if (middleware === void 0) { middleware = ItoI; }\n var buffer = [];\n var assigned = false;\n var medium = {\n read: function () {\n if (assigned) {\n throw new Error('Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.');\n }\n if (buffer.length) {\n return buffer[buffer.length - 1];\n }\n return defaults;\n },\n useMedium: function (data) {\n var item = middleware(data, assigned);\n buffer.push(item);\n return function () {\n buffer = buffer.filter(function (x) { return x !== item; });\n };\n },\n assignSyncMedium: function (cb) {\n assigned = true;\n while (buffer.length) {\n var cbs = buffer;\n buffer = [];\n cbs.forEach(cb);\n }\n buffer = {\n push: function (x) { return cb(x); },\n filter: function () { return buffer; },\n };\n },\n assignMedium: function (cb) {\n assigned = true;\n var pendingQueue = [];\n if (buffer.length) {\n var cbs = buffer;\n buffer = [];\n cbs.forEach(cb);\n pendingQueue = buffer;\n }\n var executeQueue = function () {\n var cbs = pendingQueue;\n pendingQueue = [];\n cbs.forEach(cb);\n };\n var cycle = function () { return Promise.resolve().then(executeQueue); };\n cycle();\n buffer = {\n push: function (x) {\n pendingQueue.push(x);\n cycle();\n },\n filter: function (filter) {\n pendingQueue = pendingQueue.filter(filter);\n return buffer;\n },\n };\n },\n };\n return medium;\n}\nexport function createMedium(defaults, middleware) {\n if (middleware === void 0) { middleware = ItoI; }\n return innerCreateMedium(defaults, middleware);\n}\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function createSidecarMedium(options) {\n if (options === void 0) { options = {}; }\n var medium = innerCreateMedium(null);\n medium.options = __assign({ async: true, ssr: false }, options);\n return medium;\n}\n","import { __assign, __rest } from \"tslib\";\nimport * as React from 'react';\nvar SideCar = function (_a) {\n var sideCar = _a.sideCar, rest = __rest(_a, [\"sideCar\"]);\n if (!sideCar) {\n throw new Error('Sidecar: please provide `sideCar` property to import the right car');\n }\n var Target = sideCar.read();\n if (!Target) {\n throw new Error('Sidecar medium not found');\n }\n return React.createElement(Target, __assign({}, rest));\n};\nSideCar.isSideCarExport = true;\nexport function exportSidecar(medium, exported) {\n medium.useMedium(exported);\n return SideCar;\n}\n","import { createSidecarMedium } from 'use-sidecar';\nexport var effectCar = createSidecarMedium();\n","import { __spreadArray } from \"tslib\";\nimport * as React from 'react';\nimport { RemoveScrollBar } from 'react-remove-scroll-bar';\nimport { styleSingleton } from 'react-style-singleton';\nimport { nonPassive } from './aggresiveCapture';\nimport { handleScroll, locationCouldBeScrolled } from './handleScroll';\nexport var getTouchXY = function (event) {\n return 'changedTouches' in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0];\n};\nexport var getDeltaXY = function (event) { return [event.deltaX, event.deltaY]; };\nvar extractRef = function (ref) {\n return ref && 'current' in ref ? ref.current : ref;\n};\nvar deltaCompare = function (x, y) { return x[0] === y[0] && x[1] === y[1]; };\nvar generateStyle = function (id) { return \"\\n .block-interactivity-\".concat(id, \" {pointer-events: none;}\\n .allow-interactivity-\").concat(id, \" {pointer-events: all;}\\n\"); };\nvar idCounter = 0;\nvar lockStack = [];\nexport function RemoveScrollSideCar(props) {\n var shouldPreventQueue = React.useRef([]);\n var touchStartRef = React.useRef([0, 0]);\n var activeAxis = React.useRef();\n var id = React.useState(idCounter++)[0];\n var Style = React.useState(styleSingleton)[0];\n var lastProps = React.useRef(props);\n React.useEffect(function () {\n lastProps.current = props;\n }, [props]);\n React.useEffect(function () {\n if (props.inert) {\n document.body.classList.add(\"block-interactivity-\".concat(id));\n var allow_1 = __spreadArray([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean);\n allow_1.forEach(function (el) { return el.classList.add(\"allow-interactivity-\".concat(id)); });\n return function () {\n document.body.classList.remove(\"block-interactivity-\".concat(id));\n allow_1.forEach(function (el) { return el.classList.remove(\"allow-interactivity-\".concat(id)); });\n };\n }\n return;\n }, [props.inert, props.lockRef.current, props.shards]);\n var shouldCancelEvent = React.useCallback(function (event, parent) {\n if (('touches' in event && event.touches.length === 2) || (event.type === 'wheel' && event.ctrlKey)) {\n return !lastProps.current.allowPinchZoom;\n }\n var touch = getTouchXY(event);\n var touchStart = touchStartRef.current;\n var deltaX = 'deltaX' in event ? event.deltaX : touchStart[0] - touch[0];\n var deltaY = 'deltaY' in event ? event.deltaY : touchStart[1] - touch[1];\n var currentAxis;\n var target = event.target;\n var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? 'h' : 'v';\n // allow horizontal touch move on Range inputs. They will not cause any scroll\n if ('touches' in event && moveDirection === 'h' && target.type === 'range') {\n return false;\n }\n // allow drag selection (iOS); check if selection's anchorNode is the same as target or contains target\n var selection = window.getSelection();\n var anchorNode = selection && selection.anchorNode;\n var isTouchingSelection = anchorNode ? anchorNode === target || anchorNode.contains(target) : false;\n if (isTouchingSelection) {\n return false;\n }\n var canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);\n if (!canBeScrolledInMainDirection) {\n return true;\n }\n if (canBeScrolledInMainDirection) {\n currentAxis = moveDirection;\n }\n else {\n currentAxis = moveDirection === 'v' ? 'h' : 'v';\n canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);\n // other axis might be not scrollable\n }\n if (!canBeScrolledInMainDirection) {\n return false;\n }\n if (!activeAxis.current && 'changedTouches' in event && (deltaX || deltaY)) {\n activeAxis.current = currentAxis;\n }\n if (!currentAxis) {\n return true;\n }\n var cancelingAxis = activeAxis.current || currentAxis;\n return handleScroll(cancelingAxis, parent, event, cancelingAxis === 'h' ? deltaX : deltaY, true);\n }, []);\n var shouldPrevent = React.useCallback(function (_event) {\n var event = _event;\n if (!lockStack.length || lockStack[lockStack.length - 1] !== Style) {\n // not the last active\n return;\n }\n var delta = 'deltaY' in event ? getDeltaXY(event) : getTouchXY(event);\n var sourceEvent = shouldPreventQueue.current.filter(function (e) { return e.name === event.type && (e.target === event.target || event.target === e.shadowParent) && deltaCompare(e.delta, delta); })[0];\n // self event, and should be canceled\n if (sourceEvent && sourceEvent.should) {\n if (event.cancelable) {\n event.preventDefault();\n }\n return;\n }\n // outside or shard event\n if (!sourceEvent) {\n var shardNodes = (lastProps.current.shards || [])\n .map(extractRef)\n .filter(Boolean)\n .filter(function (node) { return node.contains(event.target); });\n var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation;\n if (shouldStop) {\n if (event.cancelable) {\n event.preventDefault();\n }\n }\n }\n }, []);\n var shouldCancel = React.useCallback(function (name, delta, target, should) {\n var event = { name: name, delta: delta, target: target, should: should, shadowParent: getOutermostShadowParent(target) };\n shouldPreventQueue.current.push(event);\n setTimeout(function () {\n shouldPreventQueue.current = shouldPreventQueue.current.filter(function (e) { return e !== event; });\n }, 1);\n }, []);\n var scrollTouchStart = React.useCallback(function (event) {\n touchStartRef.current = getTouchXY(event);\n activeAxis.current = undefined;\n }, []);\n var scrollWheel = React.useCallback(function (event) {\n shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));\n }, []);\n var scrollTouchMove = React.useCallback(function (event) {\n shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));\n }, []);\n React.useEffect(function () {\n lockStack.push(Style);\n props.setCallbacks({\n onScrollCapture: scrollWheel,\n onWheelCapture: scrollWheel,\n onTouchMoveCapture: scrollTouchMove,\n });\n document.addEventListener('wheel', shouldPrevent, nonPassive);\n document.addEventListener('touchmove', shouldPrevent, nonPassive);\n document.addEventListener('touchstart', scrollTouchStart, nonPassive);\n return function () {\n lockStack = lockStack.filter(function (inst) { return inst !== Style; });\n document.removeEventListener('wheel', shouldPrevent, nonPassive);\n document.removeEventListener('touchmove', shouldPrevent, nonPassive);\n document.removeEventListener('touchstart', scrollTouchStart, nonPassive);\n };\n }, []);\n var removeScrollBar = props.removeScrollBar, inert = props.inert;\n return (React.createElement(React.Fragment, null,\n inert ? React.createElement(Style, { styles: generateStyle(id) }) : null,\n removeScrollBar ? React.createElement(RemoveScrollBar, { noRelative: props.noRelative, gapMode: props.gapMode }) : null));\n}\nfunction getOutermostShadowParent(node) {\n var shadowParent = null;\n while (node !== null) {\n if (node instanceof ShadowRoot) {\n shadowParent = node.host;\n node = node.host;\n }\n node = node.parentNode;\n }\n return shadowParent;\n}\n","import * as React from 'react';\nimport { styleSingleton } from 'react-style-singleton';\nimport { fullWidthClassName, zeroRightClassName, noScrollbarsClassName, removedBarSizeVariable } from './constants';\nimport { getGapWidth } from './utils';\nvar Style = styleSingleton();\nexport var lockAttribute = 'data-scroll-locked';\n// important tip - once we measure scrollBar width and remove them\n// we could not repeat this operation\n// thus we are using style-singleton - only the first \"yet correct\" style will be applied.\nvar getStyles = function (_a, allowRelative, gapMode, important) {\n var left = _a.left, top = _a.top, right = _a.right, gap = _a.gap;\n if (gapMode === void 0) { gapMode = 'margin'; }\n return \"\\n .\".concat(noScrollbarsClassName, \" {\\n overflow: hidden \").concat(important, \";\\n padding-right: \").concat(gap, \"px \").concat(important, \";\\n }\\n body[\").concat(lockAttribute, \"] {\\n overflow: hidden \").concat(important, \";\\n overscroll-behavior: contain;\\n \").concat([\n allowRelative && \"position: relative \".concat(important, \";\"),\n gapMode === 'margin' &&\n \"\\n padding-left: \".concat(left, \"px;\\n padding-top: \").concat(top, \"px;\\n padding-right: \").concat(right, \"px;\\n margin-left:0;\\n margin-top:0;\\n margin-right: \").concat(gap, \"px \").concat(important, \";\\n \"),\n gapMode === 'padding' && \"padding-right: \".concat(gap, \"px \").concat(important, \";\"),\n ]\n .filter(Boolean)\n .join(''), \"\\n }\\n \\n .\").concat(zeroRightClassName, \" {\\n right: \").concat(gap, \"px \").concat(important, \";\\n }\\n \\n .\").concat(fullWidthClassName, \" {\\n margin-right: \").concat(gap, \"px \").concat(important, \";\\n }\\n \\n .\").concat(zeroRightClassName, \" .\").concat(zeroRightClassName, \" {\\n right: 0 \").concat(important, \";\\n }\\n \\n .\").concat(fullWidthClassName, \" .\").concat(fullWidthClassName, \" {\\n margin-right: 0 \").concat(important, \";\\n }\\n \\n body[\").concat(lockAttribute, \"] {\\n \").concat(removedBarSizeVariable, \": \").concat(gap, \"px;\\n }\\n\");\n};\nvar getCurrentUseCounter = function () {\n var counter = parseInt(document.body.getAttribute(lockAttribute) || '0', 10);\n return isFinite(counter) ? counter : 0;\n};\nexport var useLockAttribute = function () {\n React.useEffect(function () {\n document.body.setAttribute(lockAttribute, (getCurrentUseCounter() + 1).toString());\n return function () {\n var newCounter = getCurrentUseCounter() - 1;\n if (newCounter <= 0) {\n document.body.removeAttribute(lockAttribute);\n }\n else {\n document.body.setAttribute(lockAttribute, newCounter.toString());\n }\n };\n }, []);\n};\n/**\n * Removes page scrollbar and blocks page scroll when mounted\n */\nexport var RemoveScrollBar = function (_a) {\n var noRelative = _a.noRelative, noImportant = _a.noImportant, _b = _a.gapMode, gapMode = _b === void 0 ? 'margin' : _b;\n useLockAttribute();\n /*\n gap will be measured on every component mount\n however it will be used only by the \"first\" invocation\n due to singleton nature of <Style\n */\n var gap = React.useMemo(function () { return getGapWidth(gapMode); }, [gapMode]);\n return React.createElement(Style, { styles: getStyles(gap, !noRelative, gapMode, !noImportant ? '!important' : '') });\n};\n","import * as React from 'react';\nimport { stylesheetSingleton } from './singleton';\n/**\n * creates a hook to control style singleton\n * @see {@link styleSingleton} for a safer component version\n * @example\n * ```tsx\n * const useStyle = styleHookSingleton();\n * ///\n * useStyle('body { overflow: hidden}');\n */\nexport var styleHookSingleton = function () {\n var sheet = stylesheetSingleton();\n return function (styles, isDynamic) {\n React.useEffect(function () {\n sheet.add(styles);\n return function () {\n sheet.remove();\n };\n }, [styles && isDynamic]);\n };\n};\n","var currentNonce;\nexport var setNonce = function (nonce) {\n currentNonce = nonce;\n};\nexport var getNonce = function () {\n if (currentNonce) {\n return currentNonce;\n }\n if (typeof __webpack_nonce__ !== 'undefined') {\n return __webpack_nonce__;\n }\n return undefined;\n};\n","import { getNonce } from 'get-nonce';\nfunction makeStyleTag() {\n if (!document)\n return null;\n var tag = document.createElement('style');\n tag.type = 'text/css';\n var nonce = getNonce();\n if (nonce) {\n tag.setAttribute('nonce', nonce);\n }\n return tag;\n}\nfunction injectStyles(tag, css) {\n // @ts-ignore\n if (tag.styleSheet) {\n // @ts-ignore\n tag.styleSheet.cssText = css;\n }\n else {\n tag.appendChild(document.createTextNode(css));\n }\n}\nfunction insertStyleTag(tag) {\n var head = document.head || document.getElementsByTagName('head')[0];\n head.appendChild(tag);\n}\nexport var stylesheetSingleton = function () {\n var counter = 0;\n var stylesheet = null;\n return {\n add: function (style) {\n if (counter == 0) {\n if ((stylesheet = makeStyleTag())) {\n injectStyles(stylesheet, style);\n insertStyleTag(stylesheet);\n }\n }\n counter++;\n },\n remove: function () {\n counter--;\n if (!counter && stylesheet) {\n stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet);\n stylesheet = null;\n }\n },\n };\n};\n","import { styleHookSingleton } from './hook';\n/**\n * create a Component to add styles on demand\n * - styles are added when first instance is mounted\n * - styles are removed when the last instance is unmounted\n * - changing styles in runtime does nothing unless dynamic is set. But with multiple components that can lead to the undefined behavior\n */\nexport var styleSingleton = function () {\n var useStyle = styleHookSingleton();\n var Sheet = function (_a) {\n var styles = _a.styles, dynamic = _a.dynamic;\n useStyle(styles, dynamic);\n return null;\n };\n return Sheet;\n};\n","export var zeroGap = {\n left: 0,\n top: 0,\n right: 0,\n gap: 0,\n};\nvar parse = function (x) { return parseInt(x || '', 10) || 0; };\nvar getOffset = function (gapMode) {\n var cs = window.getComputedStyle(document.body);\n var left = cs[gapMode === 'padding' ? 'paddingLeft' : 'marginLeft'];\n var top = cs[gapMode === 'padding' ? 'paddingTop' : 'marginTop'];\n var right = cs[gapMode === 'padding' ? 'paddingRight' : 'marginRight'];\n return [parse(left), parse(top), parse(right)];\n};\nexport var getGapWidth = function (gapMode) {\n if (gapMode === void 0) { gapMode = 'margin'; }\n if (typeof window === 'undefined') {\n return zeroGap;\n }\n var offsets = getOffset(gapMode);\n var documentWidth = document.documentElement.clientWidth;\n var windowWidth = window.innerWidth;\n return {\n left: offsets[0],\n top: offsets[1],\n right: offsets[2],\n gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0]),\n };\n};\n","var passiveSupported = false;\nif (typeof window !== 'undefined') {\n try {\n var options = Object.defineProperty({}, 'passive', {\n get: function () {\n passiveSupported = true;\n return true;\n },\n });\n // @ts-ignore\n window.addEventListener('test', options, options);\n // @ts-ignore\n window.removeEventListener('test', options, options);\n }\n catch (err) {\n passiveSupported = false;\n }\n}\nexport var nonPassive = passiveSupported ? { passive: false } : false;\n","var alwaysContainsScroll = function (node) {\n // textarea will always _contain_ scroll inside self. It only can be hidden\n return node.tagName === 'TEXTAREA';\n};\nvar elementCanBeScrolled = function (node, overflow) {\n if (!(node instanceof Element)) {\n return false;\n }\n var styles = window.getComputedStyle(node);\n return (\n // not-not-scrollable\n styles[overflow] !== 'hidden' &&\n // contains scroll inside self\n !(styles.overflowY === styles.overflowX && !alwaysContainsScroll(node) && styles[overflow] === 'visible'));\n};\nvar elementCouldBeVScrolled = function (node) { return elementCanBeScrolled(node, 'overflowY'); };\nvar elementCouldBeHScrolled = function (node) { return elementCanBeScrolled(node, 'overflowX'); };\nexport var locationCouldBeScrolled = function (axis, node) {\n var ownerDocument = node.ownerDocument;\n var current = node;\n do {\n // Skip over shadow root\n if (typeof ShadowRoot !== 'undefined' && current instanceof ShadowRoot) {\n current = current.host;\n }\n var isScrollable = elementCouldBeScrolled(axis, current);\n if (isScrollable) {\n var _a = getScrollVariables(axis, current), scrollHeight = _a[1], clientHeight = _a[2];\n if (scrollHeight > clientHeight) {\n return true;\n }\n }\n current = current.parentNode;\n } while (current && current !== ownerDocument.body);\n return false;\n};\nvar getVScrollVariables = function (_a) {\n var scrollTop = _a.scrollTop, scrollHeight = _a.scrollHeight, clientHeight = _a.clientHeight;\n return [\n scrollTop,\n scrollHeight,\n clientHeight,\n ];\n};\nvar getHScrollVariables = function (_a) {\n var scrollLeft = _a.scrollLeft, scrollWidth = _a.scrollWidth, clientWidth = _a.clientWidth;\n return [\n scrollLeft,\n scrollWidth,\n clientWidth,\n ];\n};\nvar elementCouldBeScrolled = function (axis, node) {\n return axis === 'v' ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node);\n};\nvar getScrollVariables = function (axis, node) {\n return axis === 'v' ? getVScrollVariables(node) : getHScrollVariables(node);\n};\nvar getDirectionFactor = function (axis, direction) {\n /**\n * If the element's direction is rtl (right-to-left), then scrollLeft is 0 when the scrollbar is at its rightmost position,\n * and then increasingly negative as you scroll towards the end of the content.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft\n */\n return axis === 'h' && direction === 'rtl' ? -1 : 1;\n};\nexport var handleScroll = function (axis, endTarget, event, sourceDelta, noOverscroll) {\n var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction);\n var delta = directionFactor * sourceDelta;\n // find scrollable target\n var target = event.target;\n var targetInLock = endTarget.contains(target);\n var shouldCancelScroll = false;\n var isDeltaPositive = delta > 0;\n var availableScroll = 0;\n var availableScrollTop = 0;\n do {\n if (!target) {\n break;\n }\n var _a = getScrollVariables(axis, target), position = _a[0], scroll_1 = _a[1], capacity = _a[2];\n var elementScroll = scroll_1 - capacity - directionFactor * position;\n if (position || elementScroll) {\n if (elementCouldBeScrolled(axis, target)) {\n availableScroll += elementScroll;\n availableScrollTop += position;\n }\n }\n var parent_1 = target.parentNode;\n // we will \"bubble\" from ShadowDom in case we are, or just to the parent in normal case\n // this is the same logic used in focus-lock\n target = (parent_1 && parent_1.nodeType === Node.DOCUMENT_FRAGMENT_NODE ? parent_1.host : parent_1);\n } while (\n // portaled content\n (!targetInLock && target !== document.body) ||\n // self content\n (targetInLock && (endTarget.contains(target) || endTarget === target)));\n // handle epsilon around 0 (non standard zoom levels)\n if (isDeltaPositive &&\n ((noOverscroll && Math.abs(availableScroll) < 1) || (!noOverscroll && delta > availableScroll))) {\n shouldCancelScroll = true;\n }\n else if (!isDeltaPositive &&\n ((noOverscroll && Math.abs(availableScrollTop) < 1) || (!noOverscroll && -delta > availableScrollTop))) {\n shouldCancelScroll = true;\n }\n return shouldCancelScroll;\n};\n","import { exportSidecar } from 'use-sidecar';\nimport { RemoveScrollSideCar } from './SideEffect';\nimport { effectCar } from './medium';\nexport default exportSidecar(effectCar, RemoveScrollSideCar);\n","import * as React from 'react';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { useControllableState } from '@radix-ui/react-use-controllable-state';\nimport { Primitive } from '@radix-ui/react-primitive';\n\n/* -------------------------------------------------------------------------------------------------\n * Toggle\n * -----------------------------------------------------------------------------------------------*/\n\nconst NAME = 'Toggle';\n\ntype ToggleElement = React.ComponentRef<typeof Primitive.button>;\ntype PrimitiveButtonProps = React.ComponentPropsWithoutRef<typeof Primitive.button>;\ninterface ToggleProps extends PrimitiveButtonProps {\n /**\n * The controlled state of the toggle.\n */\n pressed?: boolean;\n /**\n * The state of the toggle when initially rendered. Use `defaultPressed`\n * if you do not need to control the state of the toggle.\n * @defaultValue false\n */\n defaultPressed?: boolean;\n /**\n * The callback that fires when the state of the toggle changes.\n */\n onPressedChange?(pressed: boolean): void;\n}\n\nconst Toggle = React.forwardRef<ToggleElement, ToggleProps>((props, forwardedRef) => {\n const { pressed: pressedProp, defaultPressed, onPressedChange, ...buttonProps } = props;\n\n const [pressed, setPressed] = useControllableState({\n prop: pressedProp,\n onChange: onPressedChange,\n defaultProp: defaultPressed ?? false,\n caller: NAME,\n });\n\n return (\n <Primitive.button\n type=\"button\"\n aria-pressed={pressed}\n data-state={pressed ? 'on' : 'off'}\n data-disabled={props.disabled ? '' : undefined}\n {...buttonProps}\n ref={forwardedRef}\n onClick={composeEventHandlers(props.onClick, () => {\n if (!props.disabled) {\n setPressed(!pressed);\n }\n })}\n />\n );\n});\n\nToggle.displayName = NAME;\n\n/* ---------------------------------------------------------------------------------------------- */\n\nconst Root = Toggle;\n\nexport {\n Toggle,\n //\n Root,\n};\nexport type { ToggleProps };\n","import React from 'react';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport * as RovingFocusGroup from '@radix-ui/react-roving-focus';\nimport { createRovingFocusGroupScope } from '@radix-ui/react-roving-focus';\nimport { Toggle } from '@radix-ui/react-toggle';\nimport { useControllableState } from '@radix-ui/react-use-controllable-state';\nimport { useDirection } from '@radix-ui/react-direction';\n\nimport type { Scope } from '@radix-ui/react-context';\n\n/* -------------------------------------------------------------------------------------------------\n * ToggleGroup\n * -----------------------------------------------------------------------------------------------*/\n\nconst TOGGLE_GROUP_NAME = 'ToggleGroup';\n\ntype ScopedProps<P> = P & { __scopeToggleGroup?: Scope };\nconst [createToggleGroupContext, createToggleGroupScope] = createContextScope(TOGGLE_GROUP_NAME, [\n createRovingFocusGroupScope,\n]);\nconst useRovingFocusGroupScope = createRovingFocusGroupScope();\n\ntype ToggleGroupElement = ToggleGroupImplSingleElement | ToggleGroupImplMultipleElement;\ninterface ToggleGroupSingleProps extends ToggleGroupImplSingleProps {\n type: 'single';\n}\ninterface ToggleGroupMultipleProps extends ToggleGroupImplMultipleProps {\n type: 'multiple';\n}\n\nconst ToggleGroup = React.forwardRef<\n ToggleGroupElement,\n ToggleGroupSingleProps | ToggleGroupMultipleProps\n>((props, forwardedRef) => {\n const { type, ...toggleGroupProps } = props;\n\n if (type === 'single') {\n const singleProps = toggleGroupProps as ToggleGroupImplSingleProps;\n return <ToggleGroupImplSingle {...singleProps} ref={forwardedRef} />;\n }\n\n if (type === 'multiple') {\n const multipleProps = toggleGroupProps as ToggleGroupImplMultipleProps;\n return <ToggleGroupImplMultiple {...multipleProps} ref={forwardedRef} />;\n }\n\n throw new Error(`Missing prop \\`type\\` expected on \\`${TOGGLE_GROUP_NAME}\\``);\n});\n\nToggleGroup.displayName = TOGGLE_GROUP_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype ToggleGroupValueContextValue = {\n type: 'single' | 'multiple';\n value: string[];\n onItemActivate(value: string): void;\n onItemDeactivate(value: string): void;\n};\n\nconst [ToggleGroupValueProvider, useToggleGroupValueContext] =\n createToggleGroupContext<ToggleGroupValueContextValue>(TOGGLE_GROUP_NAME);\n\ntype ToggleGroupImplSingleElement = ToggleGroupImplElement;\ninterface ToggleGroupImplSingleProps extends ToggleGroupImplProps {\n /**\n * The controlled stateful value of the item that is pressed.\n */\n value?: string;\n /**\n * The value of the item that is pressed when initially rendered. Use\n * `defaultValue` if you do not need to control the state of a toggle group.\n */\n defaultValue?: string;\n /**\n * The callback that fires when the value of the toggle group changes.\n */\n onValueChange?(value: string): void;\n}\n\nconst ToggleGroupImplSingle = React.forwardRef<\n ToggleGroupImplSingleElement,\n ToggleGroupImplSingleProps\n>((props: ScopedProps<ToggleGroupImplSingleProps>, forwardedRef) => {\n const {\n value: valueProp,\n defaultValue,\n onValueChange = () => {},\n ...toggleGroupSingleProps\n } = props;\n\n const [value, setValue] = useControllableState({\n prop: valueProp,\n defaultProp: defaultValue ?? '',\n onChange: onValueChange,\n caller: TOGGLE_GROUP_NAME,\n });\n\n return (\n <ToggleGroupValueProvider\n scope={props.__scopeToggleGroup}\n type=\"single\"\n value={React.useMemo(() => (value ? [value] : []), [value])}\n onItemActivate={setValue}\n onItemDeactivate={React.useCallback(() => setValue(''), [setValue])}\n >\n <ToggleGroupImpl {...toggleGroupSingleProps} ref={forwardedRef} />\n </ToggleGroupValueProvider>\n );\n});\n\ntype ToggleGroupImplMultipleElement = ToggleGroupImplElement;\ninterface ToggleGroupImplMultipleProps extends ToggleGroupImplProps {\n /**\n * The controlled stateful value of the items that are pressed.\n */\n value?: string[];\n /**\n * The value of the items that are pressed when initially rendered. Use\n * `defaultValue` if you do not need to control the state of a toggle group.\n */\n defaultValue?: string[];\n /**\n * The callback that fires when the state of the toggle group changes.\n */\n onValueChange?(value: string[]): void;\n}\n\nconst ToggleGroupImplMultiple = React.forwardRef<\n ToggleGroupImplMultipleElement,\n ToggleGroupImplMultipleProps\n>((props: ScopedProps<ToggleGroupImplMultipleProps>, forwardedRef) => {\n const {\n value: valueProp,\n defaultValue,\n onValueChange = () => {},\n ...toggleGroupMultipleProps\n } = props;\n\n const [value, setValue] = useControllableState({\n prop: valueProp,\n defaultProp: defaultValue ?? [],\n onChange: onValueChange,\n caller: TOGGLE_GROUP_NAME,\n });\n\n const handleButtonActivate = React.useCallback(\n (itemValue: string) => setValue((prevValue = []) => [...prevValue, itemValue]),\n [setValue]\n );\n\n const handleButtonDeactivate = React.useCallback(\n (itemValue: string) =>\n setValue((prevValue = []) => prevValue.filter((value) => value !== itemValue)),\n [setValue]\n );\n\n return (\n <ToggleGroupValueProvider\n scope={props.__scopeToggleGroup}\n type=\"multiple\"\n value={value}\n onItemActivate={handleButtonActivate}\n onItemDeactivate={handleButtonDeactivate}\n >\n <ToggleGroupImpl {...toggleGroupMultipleProps} ref={forwardedRef} />\n </ToggleGroupValueProvider>\n );\n});\n\nToggleGroup.displayName = TOGGLE_GROUP_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype ToggleGroupContextValue = { rovingFocus: boolean; disabled: boolean };\n\nconst [ToggleGroupContext, useToggleGroupContext] =\n createToggleGroupContext<ToggleGroupContextValue>(TOGGLE_GROUP_NAME);\n\ntype RovingFocusGroupProps = React.ComponentPropsWithoutRef<typeof RovingFocusGroup.Root>;\ntype ToggleGroupImplElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface ToggleGroupImplProps extends PrimitiveDivProps {\n /**\n * Whether the group is disabled from user interaction.\n * @defaultValue false\n */\n disabled?: boolean;\n /**\n * Whether the group should maintain roving focus of its buttons.\n * @defaultValue true\n */\n rovingFocus?: boolean;\n loop?: RovingFocusGroupProps['loop'];\n orientation?: RovingFocusGroupProps['orientation'];\n dir?: RovingFocusGroupProps['dir'];\n}\n\nconst ToggleGroupImpl = React.forwardRef<ToggleGroupImplElement, ToggleGroupImplProps>(\n (props: ScopedProps<ToggleGroupImplProps>, forwardedRef) => {\n const {\n __scopeToggleGroup,\n disabled = false,\n rovingFocus = true,\n orientation,\n dir,\n loop = true,\n ...toggleGroupProps\n } = props;\n const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeToggleGroup);\n const direction = useDirection(dir);\n const commonProps = { role: 'group', dir: direction, ...toggleGroupProps };\n return (\n <ToggleGroupContext scope={__scopeToggleGroup} rovingFocus={rovingFocus} disabled={disabled}>\n {rovingFocus ? (\n <RovingFocusGroup.Root\n asChild\n {...rovingFocusGroupScope}\n orientation={orientation}\n dir={direction}\n loop={loop}\n >\n <Primitive.div {...commonProps} ref={forwardedRef} />\n </RovingFocusGroup.Root>\n ) : (\n <Primitive.div {...commonProps} ref={forwardedRef} />\n )}\n </ToggleGroupContext>\n );\n }\n);\n\n/* -------------------------------------------------------------------------------------------------\n * ToggleGroupItem\n * -----------------------------------------------------------------------------------------------*/\n\nconst ITEM_NAME = 'ToggleGroupItem';\n\ntype ToggleGroupItemElement = ToggleGroupItemImplElement;\ninterface ToggleGroupItemProps extends Omit<ToggleGroupItemImplProps, 'pressed'> {}\n\nconst ToggleGroupItem = React.forwardRef<ToggleGroupItemElement, ToggleGroupItemProps>(\n (props: ScopedProps<ToggleGroupItemProps>, forwardedRef) => {\n const valueContext = useToggleGroupValueContext(ITEM_NAME, props.__scopeToggleGroup);\n const context = useToggleGroupContext(ITEM_NAME, props.__scopeToggleGroup);\n const rovingFocusGroupScope = useRovingFocusGroupScope(props.__scopeToggleGroup);\n const pressed = valueContext.value.includes(props.value);\n const disabled = context.disabled || props.disabled;\n const commonProps = { ...props, pressed, disabled };\n const ref = React.useRef<HTMLDivElement>(null);\n return context.rovingFocus ? (\n <RovingFocusGroup.Item\n asChild\n {...rovingFocusGroupScope}\n focusable={!disabled}\n active={pressed}\n ref={ref}\n >\n <ToggleGroupItemImpl {...commonProps} ref={forwardedRef} />\n </RovingFocusGroup.Item>\n ) : (\n <ToggleGroupItemImpl {...commonProps} ref={forwardedRef} />\n );\n }\n);\n\nToggleGroupItem.displayName = ITEM_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype ToggleGroupItemImplElement = React.ComponentRef<typeof Toggle>;\ntype ToggleProps = React.ComponentPropsWithoutRef<typeof Toggle>;\ninterface ToggleGroupItemImplProps extends Omit<ToggleProps, 'defaultPressed' | 'onPressedChange'> {\n /**\n * A string value for the toggle group item. All items within a toggle group should use a unique value.\n */\n value: string;\n}\n\nconst ToggleGroupItemImpl = React.forwardRef<ToggleGroupItemImplElement, ToggleGroupItemImplProps>(\n (props: ScopedProps<ToggleGroupItemImplProps>, forwardedRef) => {\n const { __scopeToggleGroup, value, ...itemProps } = props;\n const valueContext = useToggleGroupValueContext(ITEM_NAME, __scopeToggleGroup);\n const singleProps = { role: 'radio', 'aria-checked': props.pressed, 'aria-pressed': undefined };\n const typeProps = valueContext.type === 'single' ? singleProps : undefined;\n return (\n <Toggle\n {...typeProps}\n {...itemProps}\n ref={forwardedRef}\n onPressedChange={(pressed) => {\n if (pressed) {\n valueContext.onItemActivate(value);\n } else {\n valueContext.onItemDeactivate(value);\n }\n }}\n />\n );\n }\n);\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = ToggleGroup;\nconst Item = ToggleGroupItem;\n\nexport {\n createToggleGroupScope,\n //\n ToggleGroup,\n ToggleGroupItem,\n //\n Root,\n Item,\n};\nexport type { ToggleGroupSingleProps, ToggleGroupMultipleProps, ToggleGroupItemProps };\n","import React from \"react\";\nimport { AlertTriangle, Info, Shield, ShieldAlert, ShieldCheck } from \"lucide-react\";\n\nimport type {\n CompatibilityFeatureEntry,\n CompatibilityPanelSnapshot,\n EditorWarning,\n} from \"../../api/public-types\";\n\nexport interface TwHealthPanelProps {\n compatibility: CompatibilityPanelSnapshot;\n warnings: EditorWarning[];\n}\n\nexport function TwHealthPanel(props: TwHealthPanelProps) {\n const { compatibility, warnings } = props;\n const supportedCount = compatibility.featureEntries.filter(\n (e) => e.featureClass === \"supported-roundtrip\",\n ).length;\n const preserveOnlyCount = compatibility.featureEntries.filter(\n (e) => e.featureClass === \"preserve-only\",\n ).length;\n const blockedCount = compatibility.featureEntries.filter(\n (e) => e.featureClass === \"unsupported-fatal\",\n ).length;\n\n return (\n <div className=\"outline-none\">\n <p className=\"text-xs text-tertiary mb-3\">\n {supportedCount} supported · {preserveOnlyCount} preserve-only · {blockedCount} blocked\n {warnings.length > 0 ? ` · ${warnings.length} warning${warnings.length !== 1 ? \"s\" : \"\"}` : \"\"}\n </p>\n\n <div className=\"space-y-1\">\n {compatibility.featureEntries.map((entry) => (\n <div key={entry.featureEntryId} className=\"flex rounded-lg transition-colors hover:bg-surface\">\n {entry.featureClass !== \"supported-roundtrip\" ? (\n <div className={`w-0.5 shrink-0 rounded-l-lg ${\n entry.featureClass === \"unsupported-fatal\" ? \"bg-danger\" : \"bg-comment\"\n }`} />\n ) : null}\n <div className=\"flex items-start gap-2 p-2.5 flex-1\">\n <HealthIcon featureClass={entry.featureClass} />\n <div className=\"flex-1 min-w-0\">\n <div className=\"flex items-start justify-between gap-2\">\n <span className=\"text-sm font-medium text-primary\">{entry.message}</span>\n <FeatureClassBadge featureClass={entry.featureClass} />\n </div>\n <p className=\"text-xs text-tertiary mt-0.5\">{entry.featureKey}</p>\n </div>\n </div>\n </div>\n ))}\n\n {warnings.map((warning) => (\n <div key={warning.warningId} className=\"flex rounded-lg transition-colors hover:bg-surface\">\n <div className={`w-0.5 shrink-0 rounded-l-lg ${\n warning.severity === \"warning\" ? \"bg-comment\" : \"bg-accent\"\n }`} />\n <div className=\"flex items-start gap-2 p-2.5 flex-1\">\n {warning.severity === \"warning\" ? (\n <AlertTriangle className=\"h-4 w-4 text-comment shrink-0 mt-0.5\" />\n ) : (\n <Info className=\"h-4 w-4 text-accent shrink-0 mt-0.5\" />\n )}\n <div className=\"flex-1 min-w-0\">\n <div className=\"flex items-start justify-between gap-2\">\n <span className=\"text-sm font-medium text-primary\">{warning.message}</span>\n <span className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ${\n warning.severity === \"warning\"\n ? \"text-comment bg-warning-soft\"\n : \"text-accent bg-accent-soft\"\n }`}>\n {warning.code.replace(/_/g, \" \")}\n </span>\n </div>\n <p className=\"text-xs text-tertiary mt-0.5\">{warning.source}</p>\n </div>\n </div>\n </div>\n ))}\n\n {compatibility.featureEntries.length === 0 && warnings.length === 0 ? (\n <p className=\"text-xs text-tertiary py-4\">\n No compatibility entries or warnings to display.\n </p>\n ) : null}\n </div>\n </div>\n );\n}\n\nfunction HealthIcon(props: { featureClass: CompatibilityFeatureEntry[\"featureClass\"] }) {\n switch (props.featureClass) {\n case \"supported-roundtrip\":\n return <ShieldCheck className=\"h-4 w-4 text-insert shrink-0 mt-0.5\" />;\n case \"preserve-only\":\n return <Shield className=\"h-4 w-4 text-comment shrink-0 mt-0.5\" />;\n case \"unsupported-fatal\":\n return <ShieldAlert className=\"h-4 w-4 text-danger shrink-0 mt-0.5\" />;\n }\n}\n\nfunction FeatureClassBadge(props: { featureClass: CompatibilityFeatureEntry[\"featureClass\"] }) {\n const styles: Record<string, string> = {\n \"supported-roundtrip\": \"text-insert bg-insert-soft\",\n \"preserve-only\": \"text-comment bg-warning-soft\",\n \"unsupported-fatal\": \"text-danger bg-delete-soft\",\n };\n const labels: Record<string, string> = {\n \"supported-roundtrip\": \"supported\",\n \"preserve-only\": \"preserve-only\",\n \"unsupported-fatal\": \"blocked\",\n };\n return (\n <span className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ${styles[props.featureClass]}`}>\n {labels[props.featureClass]}\n </span>\n );\n}\n","import React from \"react\";\nimport * as Tooltip from \"@radix-ui/react-tooltip\";\n\nexport interface TwToolbarIconButtonProps {\n icon: React.ComponentType<{ className?: string }>;\n label: string;\n disabled?: boolean;\n active?: boolean;\n emphasis?: boolean;\n onClick?: () => void;\n}\n\nconst focusRingClass =\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-canvas\";\n\nexport function TwToolbarIconButton(props: TwToolbarIconButtonProps) {\n return (\n <Tooltip.Root>\n <Tooltip.Trigger asChild>\n <button\n type=\"button\"\n disabled={props.disabled}\n onClick={props.onClick}\n className={[\n \"inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors outline-none\",\n \"disabled:opacity-30 disabled:cursor-not-allowed\",\n props.emphasis\n ? \"text-accent hover:bg-accent-soft\"\n : props.active\n ? \"bg-accent-soft text-accent\"\n : \"text-secondary hover:bg-surface hover:text-primary\",\n focusRingClass,\n ].join(\" \")}\n >\n <props.icon className=\"h-4 w-4\" />\n </button>\n </Tooltip.Trigger>\n <Tooltip.Portal>\n <Tooltip.Content\n className=\"rounded-md bg-primary px-2 py-1 text-xs text-white shadow-md z-50\"\n sideOffset={6}\n >\n {props.label}\n </Tooltip.Content>\n </Tooltip.Portal>\n </Tooltip.Root>\n );\n}\n","import React from \"react\";\n\nimport * as Popover from \"@radix-ui/react-popover\";\nimport * as Toggle from \"@radix-ui/react-toggle\";\nimport * as ToggleGroup from \"@radix-ui/react-toggle-group\";\nimport * as Tooltip from \"@radix-ui/react-tooltip\";\nimport {\n Download,\n Eye,\n EyeOff,\n FileText,\n MessageSquare,\n Monitor,\n Redo2,\n ShieldAlert,\n ShieldCheck,\n Undo2,\n} from \"lucide-react\";\n\nimport type { CompatibilityPanelSnapshot, EditorWarning } from \"../../api/public-types\";\nimport type { SessionCapabilities } from \"../../runtime/session-capabilities\";\nimport { TwHealthPanel } from \"../review/tw-health-panel\";\nimport { TwToolbarIconButton } from \"./tw-toolbar-icon-button\";\n\nexport type ViewMode = \"canvas\" | \"document\";\n\nexport interface TwToolbarProps {\n sourceLabel?: string;\n capabilities?: SessionCapabilities;\n compatibility?: CompatibilityPanelSnapshot;\n warnings?: EditorWarning[];\n viewMode: ViewMode;\n /** Display toggle for tracked change decorations (not a runtime mutation toggle). */\n showTrackedChanges: boolean;\n onUndo: () => void;\n onRedo: () => void;\n onAddComment: () => void;\n onExport: () => void;\n onViewModeChange: (value: ViewMode) => void;\n onShowTrackedChangesChange: (show: boolean) => void;\n}\n\nconst focusRingClass =\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-canvas\";\n\nexport function TwToolbar(props: TwToolbarProps) {\n const caps = props.capabilities;\n\n return (\n <header className=\"flex h-10 shrink-0 items-center gap-1 border-b border-border px-2\">\n {/* Left cluster: undo/redo + formatting */}\n <div className=\"flex items-center gap-0.5\">\n <TwToolbarIconButton\n icon={Undo2}\n label=\"Undo\"\n disabled={caps ? !caps.canUndo : true}\n onClick={props.onUndo}\n />\n <TwToolbarIconButton\n icon={Redo2}\n label=\"Redo\"\n disabled={caps ? !caps.canRedo : true}\n onClick={props.onRedo}\n />\n <div className=\"mx-1 h-4 w-px bg-border\" />\n\n {/* Paragraph style selector and B/I/U removed — not yet supported */}\n </div>\n\n {/* Center: document title */}\n <div className=\"flex-1 text-center min-w-0\">\n <span className=\"text-sm font-medium truncate block\">\n {props.sourceLabel ?? \"Untitled\"}\n </span>\n </div>\n\n {/* Right cluster: comment, track changes, markup, view, export */}\n <div className=\"flex items-center gap-0.5\">\n <TwToolbarIconButton\n icon={MessageSquare}\n label=\"Add comment\"\n disabled={caps ? !caps.canAddComment : true}\n emphasis\n onClick={props.onAddComment}\n />\n\n <Tooltip.Root>\n <Tooltip.Trigger asChild>\n <Toggle.Root\n pressed={props.showTrackedChanges}\n onPressedChange={props.onShowTrackedChangesChange}\n disabled={caps ? !caps.trackChangesSupported : false}\n className={`inline-flex h-7 w-7 items-center justify-center rounded-md text-secondary transition-colors hover:bg-surface data-[state=on]:bg-accent-soft data-[state=on]:text-accent outline-none disabled:opacity-40 ${focusRingClass}`}\n >\n {props.showTrackedChanges ? <Eye className=\"h-4 w-4\" /> : <EyeOff className=\"h-4 w-4\" />}\n </Toggle.Root>\n </Tooltip.Trigger>\n <Tooltip.Portal>\n <Tooltip.Content\n className=\"rounded-md bg-primary px-2 py-1 text-xs text-white shadow-md z-50\"\n sideOffset={6}\n >\n {props.showTrackedChanges ? \"Hide tracked changes\" : \"Show tracked changes\"}\n </Tooltip.Content>\n </Tooltip.Portal>\n </Tooltip.Root>\n\n <div className=\"mx-1 h-4 w-px bg-border\" />\n\n {/* View mode toggle group: Canvas (clean, flowing) / Document (paged, markup) */}\n <ToggleGroup.Root\n type=\"single\"\n value={props.viewMode}\n onValueChange={(v: string) => {\n if (v) props.onViewModeChange(v as ViewMode);\n }}\n className=\"flex items-center gap-0.5\"\n >\n <Tooltip.Root>\n <Tooltip.Trigger asChild>\n <ToggleGroup.Item\n value=\"canvas\"\n className={`inline-flex h-7 w-7 items-center justify-center rounded-md text-secondary transition-colors hover:bg-surface data-[state=on]:bg-accent-soft data-[state=on]:text-accent outline-none ${focusRingClass}`}\n >\n <Monitor className=\"h-3.5 w-3.5\" />\n </ToggleGroup.Item>\n </Tooltip.Trigger>\n <Tooltip.Portal>\n <Tooltip.Content className=\"rounded-md bg-primary px-2 py-1 text-xs text-white shadow-md z-50\" sideOffset={6}>\n Canvas — clean flowing text\n </Tooltip.Content>\n </Tooltip.Portal>\n </Tooltip.Root>\n <Tooltip.Root>\n <Tooltip.Trigger asChild>\n <ToggleGroup.Item\n value=\"document\"\n className={`inline-flex h-7 w-7 items-center justify-center rounded-md text-secondary transition-colors hover:bg-surface data-[state=on]:bg-accent-soft data-[state=on]:text-accent outline-none ${focusRingClass}`}\n >\n <FileText className=\"h-3.5 w-3.5\" />\n </ToggleGroup.Item>\n </Tooltip.Trigger>\n <Tooltip.Portal>\n <Tooltip.Content className=\"rounded-md bg-primary px-2 py-1 text-xs text-white shadow-md z-50\" sideOffset={6}>\n Document — paged with markup\n </Tooltip.Content>\n </Tooltip.Portal>\n </Tooltip.Root>\n </ToggleGroup.Root>\n\n {/* Health indicator */}\n {props.compatibility && props.warnings ? (\n <Popover.Root>\n <Tooltip.Root>\n <Tooltip.Trigger asChild>\n <Popover.Trigger asChild>\n <button\n type=\"button\"\n className={`relative inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors hover:bg-surface hover:text-primary outline-none ${focusRingClass} ${\n (caps?.healthIssueCount ?? 0) > 0 ? \"text-secondary\" : \"text-secondary\"\n }`}\n >\n {(caps?.healthIssueCount ?? 0) > 0\n ? <ShieldAlert className=\"h-4 w-4\" />\n : <ShieldCheck className=\"h-4 w-4\" />\n }\n {(caps?.healthIssueCount ?? 0) > 0 ? (\n <span className=\"absolute -top-0.5 -right-0.5 flex h-3 min-w-[12px] items-center justify-center rounded-full bg-tertiary text-[8px] font-medium text-white\">\n {caps?.healthIssueCount}\n </span>\n ) : null}\n </button>\n </Popover.Trigger>\n </Tooltip.Trigger>\n <Tooltip.Portal>\n <Tooltip.Content className=\"rounded-md bg-primary px-2 py-1 text-xs text-white shadow-md z-50\" sideOffset={6}>\n {(caps?.healthIssueCount ?? 0) > 0\n ? `Document health — ${caps?.healthIssueCount} issue${(caps?.healthIssueCount ?? 0) !== 1 ? \"s\" : \"\"}`\n : \"Document health — no issues\"\n }\n </Tooltip.Content>\n </Tooltip.Portal>\n </Tooltip.Root>\n <Popover.Portal>\n <Popover.Content\n className=\"w-[360px] max-h-[480px] overflow-y-auto rounded-lg bg-canvas shadow-lg ring-1 ring-border p-3 z-50\"\n sideOffset={8}\n align=\"end\"\n >\n <TwHealthPanel\n compatibility={props.compatibility}\n warnings={props.warnings}\n />\n </Popover.Content>\n </Popover.Portal>\n </Popover.Root>\n ) : null}\n\n <div className=\"mx-1 h-4 w-px bg-border\" />\n\n {/* Export button */}\n <Tooltip.Root>\n <Tooltip.Trigger asChild>\n <button\n type=\"button\"\n disabled={caps ? !caps.canExport : true}\n className={[\n \"inline-flex h-7 items-center gap-1.5 rounded-md px-2.5 text-xs font-semibold transition-colors outline-none\",\n focusRingClass,\n caps?.exportBlocked\n ? \"cursor-not-allowed text-danger opacity-50\"\n : \"text-accent hover:bg-accent-soft\",\n ].join(\" \")}\n onClick={props.onExport}\n >\n <Download className=\"h-3.5 w-3.5\" />\n Export\n </button>\n </Tooltip.Trigger>\n <Tooltip.Portal>\n <Tooltip.Content className=\"rounded-md bg-primary px-2 py-1 text-xs text-white shadow-md z-50\" sideOffset={6}>\n {caps?.exportBlocked\n ? \"Export blocked by unsupported content\"\n : \"Export document\"}\n </Tooltip.Content>\n </Tooltip.Portal>\n </Tooltip.Root>\n </div>\n </header>\n );\n}\n","import React, { type ReactNode, useState } from \"react\";\n\nimport * as Tooltip from \"@radix-ui/react-tooltip\";\n\nimport type {\n CommentSidebarThreadSnapshot,\n RuntimeRenderSnapshot,\n TrackedChangeEntrySnapshot,\n} from \"../api/public-types\";\nimport type { SessionCapabilities } from \"../runtime/session-capabilities\";\nimport type { MarkupDisplay } from \"../ui/headless/comment-decoration-model\";\nimport { TwAlertBanner } from \"./chrome/tw-alert-banner\";\nimport { TwSelectionToolbar } from \"./chrome/tw-selection-toolbar\";\nimport { TwReviewRail, type ReviewRailTab } from \"./review/tw-review-rail\";\nimport { TwStatusBar } from \"./status/tw-status-bar\";\nimport { TwToolbar, type ViewMode } from \"./toolbar/tw-toolbar\";\n\nexport interface TwReviewWorkspaceProps {\n snapshot: RuntimeRenderSnapshot;\n currentUserId?: string;\n capabilities?: SessionCapabilities;\n reviewMode?: \"editing\" | \"review\";\n document: ReactNode;\n viewMode: ViewMode;\n activeRailTab: ReviewRailTab;\n activeCommentId?: string;\n activeRevisionId?: string;\n showTrackedChanges: boolean;\n selectionPreview?: string | null;\n onViewModeChange: (value: ViewMode) => void;\n onActiveRailTabChange: (value: ReviewRailTab) => void;\n onShowTrackedChangesChange: (show: boolean) => void;\n onUndo: () => void;\n onRedo: () => void;\n onAddComment: () => void;\n onExport: () => void;\n onOpenComment: (thread: CommentSidebarThreadSnapshot) => void;\n onResolveComment: (commentId: string) => void;\n onReopenComment?: (commentId: string) => void;\n onAddReply?: (commentId: string, body: string) => void;\n onEditBody?: (commentId: string, body: string) => void;\n onOpenRevision: (revision: TrackedChangeEntrySnapshot) => void;\n onAcceptRevision: (revisionId: string) => void;\n onRejectRevision: (revisionId: string) => void;\n onAcceptAllChanges: () => void;\n onRejectAllChanges: () => void;\n}\n\nexport function TwReviewWorkspace(props: TwReviewWorkspaceProps) {\n const { snapshot } = props;\n const caps = props.capabilities;\n const markupDisplay: MarkupDisplay = props.viewMode === \"document\" ? \"all\" : \"clean\";\n const preserveOnlyCount = caps?.preserveOnlyCount ??\n snapshot.compatibility.featureEntries.filter(\n (entry) => entry.featureClass === \"preserve-only\",\n ).length;\n const showReviewRail = caps?.reviewRailVisible ?? true;\n\n return (\n <Tooltip.Provider delayDuration={400}>\n <div className=\"flex h-full flex-col bg-canvas text-primary\">\n <TwToolbar\n sourceLabel={snapshot.sourceLabel}\n capabilities={caps}\n compatibility={snapshot.compatibility}\n warnings={snapshot.warnings}\n viewMode={props.viewMode}\n showTrackedChanges={props.showTrackedChanges}\n onUndo={props.onUndo}\n onRedo={props.onRedo}\n onAddComment={props.onAddComment}\n onExport={props.onExport}\n onViewModeChange={props.onViewModeChange}\n onShowTrackedChangesChange={props.onShowTrackedChangesChange}\n />\n\n <TwAlertBanner snapshot={snapshot} preserveOnlyCount={preserveOnlyCount} />\n\n <div className=\"flex flex-1 min-h-0\">\n {/* Document column */}\n <div className=\"flex flex-1 flex-col min-w-0\">\n <div className={`flex-1 overflow-y-auto ${props.viewMode === \"document\" ? \"bg-surface\" : \"bg-canvas\"}`}>\n <div\n className={`mx-auto min-h-full ${\n props.viewMode === \"document\"\n ? \"max-w-[780px] my-8 rounded-xl ring-1 ring-border shadow-sm bg-canvas\"\n : \"bg-canvas\"\n }`}\n >\n {props.selectionPreview ? (\n <div className=\"flex justify-center pt-4 px-4\">\n <TwSelectionToolbar\n selectionPreview={props.selectionPreview}\n readOnly={snapshot.readOnly}\n onAddComment={props.onAddComment}\n />\n </div>\n ) : null}\n {props.document}\n </div>\n </div>\n\n <TwStatusBar\n isDirty={snapshot.isDirty}\n isExportBlocked={snapshot.compatibility.blockExport}\n preserveOnlyCount={preserveOnlyCount}\n commentCount={snapshot.comments.totalCount}\n changeCount={snapshot.trackedChanges.totalCount}\n sessionId={snapshot.sessionId}\n />\n </div>\n\n {/* Review rail — hidden in editing mode unless toggled */}\n {showReviewRail ? <TwReviewRail\n activeTab={props.activeRailTab}\n currentUserId={props.currentUserId}\n comments={snapshot.comments}\n trackedChanges={snapshot.trackedChanges}\n compatibility={snapshot.compatibility}\n warnings={snapshot.warnings}\n markupDisplay={markupDisplay}\n activeCommentId={props.activeCommentId}\n activeRevisionId={props.activeRevisionId}\n onActiveTabChange={props.onActiveRailTabChange}\n onOpenComment={props.onOpenComment}\n onResolveComment={props.onResolveComment}\n onReopenComment={props.onReopenComment}\n onAddReply={props.onAddReply}\n onEditBody={props.onEditBody}\n onOpenRevision={props.onOpenRevision}\n onAcceptRevision={props.onAcceptRevision}\n onRejectRevision={props.onRejectRevision}\n onAcceptAllChanges={props.onAcceptAllChanges}\n onRejectAllChanges={props.onRejectAllChanges}\n /> : null}\n </div>\n </div>\n </Tooltip.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAQO;;;AC+CA,IAAM,yBAAwC;AAAA,EACnD,OAAO;AAAA,EACP,KAAK;AACP;AAEO,SAAS,kBACd,MACA,KAAK,MACL,QAAuB,wBACV;AACb,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO,eAAe,EAAE,MAAM,GAAG,CAAC;AAAA,IAClC;AAAA,EACF;AACF;AAEO,SAAS,iBAAiB,IAAc,QAAe,GAAe;AAC3E,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,qBACd,gBACA,QACgB;AAChB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,gBAAgB,eAAe,cAAc;AAAA,IAC7C;AAAA,EACF;AACF;AAEO,SAAS,qBAAyC;AACvD,SAAO;AAAA,IACL,OAAO,CAAC;AAAA,EACV;AACF;AAEO,SAAS,eAAe,OAA2B;AACxD,SAAO,MAAM,QAAQ,MAAM,KACvB,EAAE,MAAM,MAAM,MAAM,IAAI,MAAM,GAAG,IACjC,EAAE,MAAM,MAAM,IAAI,IAAI,MAAM,KAAK;AACvC;AAEO,SAAS,YACd,UACA,OACA,SACe;AACf,MAAI,iBAAiB;AACrB,MAAI,UAAU;AAEd,aAAW,QAAQ,QAAQ,OAAO;AAChC,UAAM,OAAO,uBAAuB,gBAAgB,OAAO,IAAI;AAC/D,qBAAiB,KAAK;AACtB,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,KAAK;AACH,aAAO;AAAA,QACL,QAAQ,OAAO;AAAA,QACf,MAAM,OAAO;AAAA,QACb,aAAa,OAAO,SAAS,OAAO;AAAA,QACpC,aAAa;AAAA,MACf;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,QAAQ,OAAO;AAAA,QACf,MAAM,OAAO;AAAA,QACb,aAAa;AAAA,QACb,aAAa;AAAA,MACf;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,QAAQ,OAAO,eAAe;AAAA,QAC9B,MAAM,OAAO,eAAe;AAAA,QAC5B,aAAa,OAAO,eAAe,SAAS,OAAO,eAAe;AAAA,QAClE,aAAa;AAAA,MACf;AAAA,EACJ;AACF;AAOA,SAASC,sBAAyD;AAChE,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,aAAa;AAAA,IACb,aAAa;AAAA,MACX,MAAM;AAAA,MACN,MAAM;AAAA,MACN,IAAI;AAAA,MACJ,OAAO;AAAA,QACL,OAAO;AAAA,QACP,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACF;AAMA,SAAS,0BAA0B,UAAgD;AACjF,MAAI,CAAC,SAAS,WAAW,SAAS,UAAU,aAAa;AACvD,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,SAAS,UAAU;AACjC,MAAI,MAAM,SAAS,SAAS;AAC1B,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,SAAS,QAAQ,UAC9B,MAAM,MAAM,MAAM,MAAM,EAAE,EAC1B,QAAQ,QAAQ,GAAG,EACnB,KAAK;AAER,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,QAAQ,SAAS,KAAK,GAAG,QAAQ,MAAM,GAAG,EAAE,CAAC,QAAQ;AAC9D;","names":["import_react","document","index","validateExactObjectKeys","index","createPersistedEditorSnapshot","index","index","document","index","document","index","normalizeRange","resultingStatus","textResult","nextStore","boundaryIndex","index","document","priorityForStatus","normalizeDocumentRoot","index","size","document","document","normalizeDocumentRoot","index","createPlainText","cloneMarks","createPersistedEditorSnapshot","size","offset","offset","index","inline","extractText","offset","decodeXmlEntities","name","parseXml","localName","localName","parseXml","decodeXmlEntities","name","findTagEnd","parseTag","parseXml","findChildElement","localName","readOptionalAttribute","size","decodeXmlEntities","name","findTagEnd","parseTag","document","index","size","index","cloneRelationship","HYPERLINK_RELATIONSHIP_TYPE","cloneRelationship","escapeAttribute","escapeXml","index","offset","localName","findChildElement","decodeXmlEntities","tagEnd","node","parseAttributes","localName","findChildElement","index","parseXml","findChildElement","localName","normalizeImportedTimestamp","text","parseTag","escapeAttribute","index","serializeText","parseXml","findChildElement","localName","requiresPreservedSpace","escapeXml","text","parseTag","decodeXmlText","index","splitParagraph","escapeAttribute","index","parseXml","findChildElementOptional","localName","decodeXmlEntities","parseAttributes","parseXml","findChildElementOptional","localName","parseParagraphElement","parseRunElement","parseRunProperties","extractTextContent","decodeXmlEntities","parseAttributes","parseXml","findChildElementOptional","localName","decodeXmlEntities","parseAttributes","serializeParagraph","buildParagraphPropertiesXml","serializeInlineNode","escapeAttribute","requiresPreservedSpace","escapeXml","W_NS","R_NS","serializeParagraph","escapeAttribute","buildParagraphPropertiesXml","serializeInlineNode","buildRunPropertiesXml","requiresPreservedSpace","escapeXml","document","index","toPublicCompatibilityReport","toPublicAnchorProjection","toPublicCompatibilityFeatureEntry","toPublicWarning","toPublicError","paragraphBoundary","size","cloneRelationship","isRecord","escapeXml","import_prosemirror_view","import_prosemirror_model","min","max","import_prosemirror_state","createSelectionSnapshot","createSelectionSnapshot","pmFrom","pmTo","React","React","React","import_jsx_runtime","createContext","index","Provider","useContext","createScope","nextScopes","React","React","React","import_jsx_runtime","Slot","props","Slottable","Fragment","import_jsx_runtime","Slot","Node","React","React","import_jsx_runtime","node","index","handleAndDispatchPointerDownOutsideEvent","React","React","useLayoutEffect","React","React","clamp","platform","max","offset","clamp","platform","placements","sides","side","placement","overflow","platform","x","y","min","max","clamp","offset","getComputedStyle","getComputedStyle","offset","shift","flip","size","hide","arrow","limitShift","computePosition","React","import_react","ReactDOM","noop","platform","computePosition","data","arrow","offset","shift","limitShift","flip","size","hide","arrow","React","import_jsx_runtime","React","size","import_jsx_runtime","arrow","offset","shift","limitShift","flip","size","hide","PopperArrow","Root","Arrow","React","import_react_dom","import_jsx_runtime","ReactDOM","React2","React","getElementRef","node","React","React2","React","value","React","import_jsx_runtime","NAME","Root","import_jsx_runtime","open","PORTAL_NAME","CONTENT_NAME","handleScroll","Root","ARROW_NAME","Arrow","Portal","Content","index","size","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","__iconNode","import_jsx_runtime","import_jsx_runtime","Root3","Portal","React","React","import_react","import_jsx_runtime","import_react","import_jsx_runtime","PROVIDER_NAME","createCollectionScope","React","useCollection","React","import_jsx_runtime","import_jsx_runtime","index","Root","import_jsx_runtime","Root","TRIGGER_NAME","CONTENT_NAME","Trigger","Content","React2","clamp","min","max","React","import_jsx_runtime","useStateMachine","handleScroll","offset","composeRefs","height","width","clamp","Root","import_react","import_jsx_runtime","focusRingClass","import_jsx_runtime","focusRingClass","import_jsx_runtime","focusRingClass","Root2","Trigger","Root","Content","import_jsx_runtime","React","React","count","count","React","import_jsx_runtime","EVENT_OPTIONS","handleFocusIn","handleFocusOut","handleMutations","focusFirst","container","index","__assign","React","React","import_react","useCallbackRef","React","useCallbackRef","cbs","React","SideCar","React","React","React","Style","import_jsx_runtime","usePopperScope","ANCHOR_NAME","TRIGGER_NAME","PORTAL_NAME","PortalProvider","usePortalContext","CONTENT_NAME","ARROW_NAME","Arrow","Root","Trigger","Portal","Content","React","import_jsx_runtime","NAME","Root","import_react","import_jsx_runtime","useRovingFocusGroupScope","React","value","Root","ITEM_NAME","Item","import_jsx_runtime","import_jsx_runtime","focusRingClass","Root3","Portal","import_jsx_runtime","focusRingClass","Root3","Root","Portal","Root2","Trigger","Content2","import_jsx_runtime","import_jsx_runtime","WordReviewEditor","collapsedSelection","collapsedSelection"]}
|