@beyondwork/docx-react-component 1.0.19 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/package.json +44 -25
  2. package/src/api/public-types.ts +336 -0
  3. package/src/api/session-state.ts +2 -0
  4. package/src/core/commands/formatting-commands.ts +1 -1
  5. package/src/core/commands/index.ts +14 -2
  6. package/src/core/search/search-text.ts +28 -0
  7. package/src/core/state/editor-state.ts +3 -0
  8. package/src/index.ts +21 -0
  9. package/src/io/docx-session.ts +363 -17
  10. package/src/io/export/serialize-comments.ts +104 -34
  11. package/src/io/export/serialize-footnotes.ts +198 -1
  12. package/src/io/export/serialize-headers-footers.ts +203 -10
  13. package/src/io/export/serialize-main-document.ts +83 -3
  14. package/src/io/export/split-review-boundaries.ts +181 -19
  15. package/src/io/normalize/normalize-text.ts +82 -8
  16. package/src/io/ooxml/highlight-colors.ts +39 -0
  17. package/src/io/ooxml/parse-comments.ts +85 -19
  18. package/src/io/ooxml/parse-fields.ts +396 -0
  19. package/src/io/ooxml/parse-footnotes.ts +240 -2
  20. package/src/io/ooxml/parse-headers-footers.ts +431 -7
  21. package/src/io/ooxml/parse-inline-media.ts +15 -1
  22. package/src/io/ooxml/parse-main-document.ts +396 -14
  23. package/src/io/ooxml/parse-revisions.ts +317 -38
  24. package/src/legal/bookmarks.ts +44 -0
  25. package/src/legal/cross-references.ts +59 -1
  26. package/src/model/canonical-document.ts +117 -1
  27. package/src/model/snapshot.ts +85 -1
  28. package/src/review/store/revision-store.ts +6 -0
  29. package/src/review/store/revision-types.ts +1 -0
  30. package/src/runtime/document-navigation.ts +52 -13
  31. package/src/runtime/document-runtime.ts +1521 -75
  32. package/src/runtime/read-only-diagnostics-runtime.ts +8 -0
  33. package/src/runtime/session-capabilities.ts +33 -3
  34. package/src/runtime/surface-projection.ts +86 -25
  35. package/src/runtime/table-schema.ts +2 -2
  36. package/src/runtime/view-state.ts +24 -6
  37. package/src/runtime/workflow-markup.ts +349 -0
  38. package/src/ui/WordReviewEditor.tsx +915 -1314
  39. package/src/ui/editor-command-bag.ts +120 -0
  40. package/src/ui/editor-runtime-boundary.ts +1448 -0
  41. package/src/ui/editor-shell-view.tsx +134 -0
  42. package/src/ui/editor-surface-controller.tsx +55 -0
  43. package/src/ui/headless/revision-decoration-model.ts +4 -4
  44. package/src/ui/runtime-snapshot-selectors.ts +197 -0
  45. package/src/ui/workflow-surface-blocked-rails.ts +94 -0
  46. package/src/ui-tailwind/chrome/tw-alert-banner.tsx +18 -2
  47. package/src/ui-tailwind/chrome/tw-image-context-toolbar.tsx +129 -0
  48. package/src/ui-tailwind/chrome/tw-layout-panel.tsx +114 -0
  49. package/src/ui-tailwind/chrome/tw-object-context-toolbar.tsx +34 -0
  50. package/src/ui-tailwind/chrome/tw-selection-toolbar.tsx +27 -2
  51. package/src/ui-tailwind/chrome/tw-table-context-toolbar.tsx +128 -0
  52. package/src/ui-tailwind/editor-surface/perf-probe.ts +86 -14
  53. package/src/ui-tailwind/editor-surface/pm-command-bridge.ts +2 -2
  54. package/src/ui-tailwind/editor-surface/pm-decorations.ts +237 -0
  55. package/src/ui-tailwind/editor-surface/pm-position-map.ts +1 -1
  56. package/src/ui-tailwind/editor-surface/pm-schema.ts +139 -8
  57. package/src/ui-tailwind/editor-surface/pm-state-from-snapshot.ts +98 -48
  58. package/src/ui-tailwind/editor-surface/surface-build-keys.ts +55 -0
  59. package/src/ui-tailwind/editor-surface/tw-opaque-block.tsx +7 -1
  60. package/src/ui-tailwind/editor-surface/tw-prosemirror-surface.tsx +190 -48
  61. package/src/ui-tailwind/page-chrome-model.ts +27 -0
  62. package/src/ui-tailwind/review/tw-comment-sidebar.tsx +7 -7
  63. package/src/ui-tailwind/review/tw-health-panel.tsx +31 -2
  64. package/src/ui-tailwind/review/tw-review-rail.tsx +3 -3
  65. package/src/ui-tailwind/review/tw-revision-sidebar.tsx +15 -15
  66. package/src/ui-tailwind/theme/editor-theme.css +130 -0
  67. package/src/ui-tailwind/toolbar/tw-toolbar.tsx +543 -5
  68. package/src/ui-tailwind/tw-review-workspace.tsx +316 -19
  69. package/src/validation/compatibility-engine.ts +27 -4
  70. package/src/validation/compatibility-report.ts +1 -0
  71. package/src/validation/docx-comment-proof.ts +220 -0
@@ -0,0 +1,1448 @@
1
+ import React, { useEffect, useMemo, useRef, useState } from "react";
2
+
3
+ import type {
4
+ AutosaveState,
5
+ CompatibilityReport,
6
+ DocumentNavigationSnapshot,
7
+ EditorDatastoreAdapter,
8
+ EditorError,
9
+ EditorHostAdapter,
10
+ EditorSessionState,
11
+ EditorViewStateSnapshot,
12
+ EditorWarning,
13
+ ExportDocxOptions,
14
+ ExportResult,
15
+ FieldSnapshot,
16
+ PersistedEditorSnapshot,
17
+ RuntimeRenderSnapshot,
18
+ TocRefreshResult,
19
+ UpdateFieldsResult,
20
+ ViewMode as EditorViewMode,
21
+ WordReviewEditorEvent,
22
+ WordReviewEditorProps,
23
+ WorkspaceMode,
24
+ ZoomLevel,
25
+ } from "../api/public-types";
26
+ import {
27
+ editorSessionStateFromPersistedSnapshot,
28
+ persistedSnapshotFromEditorSessionState,
29
+ } from "../api/session-state.ts";
30
+ import { createCanonicalDocumentId } from "../core/state/editor-state.ts";
31
+ import {
32
+ createDocumentRuntime,
33
+ type DocumentRuntime,
34
+ } from "../runtime/document-runtime.ts";
35
+ import { loadDocxEditorSession } from "../io/docx-session.ts";
36
+ import {
37
+ decodePersistedSourcePackageBytes,
38
+ hasValidPersistedSourcePackageDigest,
39
+ } from "../io/source-package-provenance.ts";
40
+ import {
41
+ createEditorViewStateSnapshot,
42
+ createViewState,
43
+ } from "../runtime/view-state.ts";
44
+ import {
45
+ recordPerfSample,
46
+ } from "../ui-tailwind/editor-surface/perf-probe.ts";
47
+ import {
48
+ downloadExportResult,
49
+ withExportDelivery,
50
+ } from "./browser-export";
51
+
52
+ export interface ResolvedSource {
53
+ source: "docx" | "session" | "snapshot";
54
+ sourceLabel?: string;
55
+ initialDocx?: Uint8Array | ArrayBuffer;
56
+ initialSessionState?: EditorSessionState;
57
+ initialSnapshot?: PersistedEditorSnapshot;
58
+ }
59
+
60
+ export interface CreateRuntimeArgs {
61
+ documentId: string;
62
+ readOnly: boolean;
63
+ source: ResolvedSource;
64
+ initialViewState?: {
65
+ workspaceMode?: WorkspaceMode;
66
+ zoomLevel?: ZoomLevel;
67
+ };
68
+ hostAdapter?: EditorHostAdapter;
69
+ datastore?: EditorDatastoreAdapter;
70
+ currentUserId?: string;
71
+ }
72
+
73
+ interface RuntimeLifecycleHandlers {
74
+ onWarning?: (warning: EditorWarning) => void;
75
+ onError?: (error: EditorError) => void;
76
+ onEvent?: (event: WordReviewEditorEvent) => void;
77
+ }
78
+
79
+ export interface WordReviewEditorRuntime extends DocumentRuntime {
80
+ getFatalError?(): EditorError | undefined;
81
+ dispose?(): void;
82
+ setDefaultAuthorId?(authorId?: string): void;
83
+ emitBlockedCommand(
84
+ command: string,
85
+ reasons: Extract<WordReviewEditorEvent, { type: "command_blocked" }>["reasons"],
86
+ ): void;
87
+ }
88
+
89
+ type PackageBackedDocxSession = ReturnType<typeof loadDocxEditorSession>;
90
+
91
+ interface SnapshotExportBarrier {
92
+ reason:
93
+ | "missing_source_package_provenance"
94
+ | "invalid_source_package_provenance";
95
+ message: string;
96
+ }
97
+
98
+ export interface EditorRuntimeBoundaryState {
99
+ runtime: WordReviewEditorRuntime | null;
100
+ loadError: EditorError | null;
101
+ activeRuntime: WordReviewEditorRuntime;
102
+ fallbackSnapshot: RuntimeRenderSnapshot;
103
+ loadingSessionState: EditorSessionState;
104
+ loadingViewState: EditorViewStateSnapshot;
105
+ loadingNavigation: DocumentNavigationSnapshot;
106
+ hostAdapterRef: React.MutableRefObject<EditorHostAdapter | undefined>;
107
+ datastoreRef: React.MutableRefObject<EditorDatastoreAdapter | undefined>;
108
+ onEventRef: React.MutableRefObject<((event: WordReviewEditorEvent) => void) | undefined>;
109
+ onWarningRef: React.MutableRefObject<((warning: EditorWarning) => void) | undefined>;
110
+ onErrorRef: React.MutableRefObject<((error: EditorError) => void) | undefined>;
111
+ autosaveTimerRef: React.MutableRefObject<ReturnType<typeof setTimeout> | null>;
112
+ lastSavedRevisionTokenRef: React.MutableRefObject<string | null>;
113
+ runtimeViewStateSeedRef: React.MutableRefObject<{
114
+ workspaceMode: WorkspaceMode;
115
+ zoomLevel: ZoomLevel;
116
+ }>;
117
+ }
118
+
119
+ export async function __resolveWordReviewEditorSource(
120
+ props: Pick<
121
+ WordReviewEditorProps,
122
+ | "documentId"
123
+ | "hostAdapter"
124
+ | "datastore"
125
+ | "externalDocSource"
126
+ | "initialDocx"
127
+ | "initialSessionState"
128
+ | "initialSnapshot"
129
+ | "initialSourceLabel"
130
+ | "loadRevision"
131
+ | "loadSourcePolicy"
132
+ >,
133
+ ): Promise<ResolvedSource> {
134
+ const explicitInitialCount =
135
+ Number(Boolean(props.initialDocx)) +
136
+ Number(Boolean(props.initialSessionState)) +
137
+ Number(Boolean(props.initialSnapshot));
138
+ if (explicitInitialCount > 1) {
139
+ throw new Error(
140
+ "Provide exactly one of initialDocx, initialSessionState, or initialSnapshot.",
141
+ );
142
+ }
143
+
144
+ if (props.externalDocSource) {
145
+ if (props.externalDocSource.kind === "docx") {
146
+ return {
147
+ source: "docx",
148
+ initialDocx: props.externalDocSource.bytes,
149
+ sourceLabel: props.externalDocSource.sourceLabel,
150
+ };
151
+ }
152
+
153
+ if (props.externalDocSource.kind === "session") {
154
+ return {
155
+ source: "session",
156
+ initialSessionState: props.externalDocSource.sessionState,
157
+ sourceLabel:
158
+ props.externalDocSource.sourceLabel ??
159
+ props.externalDocSource.sessionState.sourcePackage?.sourceLabel,
160
+ };
161
+ }
162
+
163
+ return {
164
+ source: "snapshot",
165
+ initialSnapshot: props.externalDocSource.snapshot,
166
+ sourceLabel: props.externalDocSource.sourceLabel,
167
+ };
168
+ }
169
+
170
+ if (props.initialSessionState) {
171
+ return {
172
+ source: "session",
173
+ initialSessionState: props.initialSessionState,
174
+ sourceLabel:
175
+ props.initialSourceLabel ??
176
+ props.initialSessionState.sourcePackage?.sourceLabel,
177
+ };
178
+ }
179
+
180
+ if (props.initialSnapshot) {
181
+ return {
182
+ source: "snapshot",
183
+ initialSnapshot: props.initialSnapshot,
184
+ sourceLabel: props.initialSourceLabel,
185
+ };
186
+ }
187
+
188
+ if (props.initialDocx) {
189
+ return {
190
+ source: "docx",
191
+ initialDocx: props.initialDocx,
192
+ sourceLabel: props.initialSourceLabel,
193
+ };
194
+ }
195
+
196
+ const loader = props.hostAdapter?.load ?? props.datastore?.load;
197
+ if (!loader) {
198
+ throw new Error(
199
+ `WordReviewEditor ${props.documentId} needs initialDocx, initialSessionState, initialSnapshot, or a host/datastore load source.`,
200
+ );
201
+ }
202
+
203
+ const loadResult = await loader({
204
+ documentId: props.documentId,
205
+ loadRevision: props.loadRevision,
206
+ loadSourcePolicy: props.loadSourcePolicy,
207
+ });
208
+
209
+ if (!loadResult.source) {
210
+ throw new Error(
211
+ `Host or datastore loader did not return a loadable source for ${props.documentId}.`,
212
+ );
213
+ }
214
+
215
+ if (loadResult.source.kind === "docx") {
216
+ return {
217
+ source: "docx",
218
+ initialDocx: loadResult.source.bytes,
219
+ sourceLabel: loadResult.source.sourceLabel,
220
+ };
221
+ }
222
+
223
+ if (loadResult.source.kind === "session") {
224
+ return {
225
+ source: "session",
226
+ initialSessionState: loadResult.source.sessionState,
227
+ sourceLabel:
228
+ loadResult.source.sourceLabel ??
229
+ loadResult.source.sessionState.sourcePackage?.sourceLabel,
230
+ };
231
+ }
232
+
233
+ return {
234
+ source: "snapshot",
235
+ initialSnapshot: loadResult.source.snapshot,
236
+ sourceLabel: loadResult.source.sourceLabel,
237
+ };
238
+ }
239
+
240
+ export function __createFallbackRuntime(args: CreateRuntimeArgs): WordReviewEditorRuntime {
241
+ return createRuntime(args);
242
+ }
243
+
244
+ export function useEditorRuntimeBoundary(
245
+ props: WordReviewEditorProps,
246
+ ): EditorRuntimeBoundaryState {
247
+ const {
248
+ currentUser,
249
+ datastore,
250
+ documentId,
251
+ externalDocSource,
252
+ externalDocumentRevision,
253
+ hostAdapter,
254
+ initialDocx,
255
+ initialSessionState,
256
+ initialSnapshot,
257
+ initialSourceLabel,
258
+ loadRevision,
259
+ loadSourcePolicy = "prefer-saved-state",
260
+ onError,
261
+ onEvent,
262
+ onWarning,
263
+ readOnly = false,
264
+ reviewMode = "review",
265
+ } = props;
266
+
267
+ const [runtime, setRuntime] = useState<WordReviewEditorRuntime | null>(null);
268
+ const [loadError, setLoadError] = useState<EditorError | null>(null);
269
+ const runtimeRef = useRef<WordReviewEditorRuntime | null>(null);
270
+ const autosaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
271
+ const lastSavedRevisionTokenRef = useRef<string | null>(null);
272
+ const hostAdapterRef = useRef(hostAdapter);
273
+ const datastoreRef = useRef(datastore);
274
+ const onEventRef = useRef(onEvent);
275
+ const onWarningRef = useRef(onWarning);
276
+ const onErrorRef = useRef(onError);
277
+ const runtimeViewStateSeedRef = useRef<{
278
+ workspaceMode: WorkspaceMode;
279
+ zoomLevel: ZoomLevel;
280
+ }>({
281
+ workspaceMode: "canvas",
282
+ zoomLevel: 100,
283
+ });
284
+ const initialSourceRef = useRef<{
285
+ documentId: string;
286
+ initialDocx?: Uint8Array | ArrayBuffer;
287
+ initialSessionState?: EditorSessionState;
288
+ initialSnapshot?: PersistedEditorSnapshot;
289
+ initialSourceLabel?: string;
290
+ } | null>(null);
291
+
292
+ if (!initialSourceRef.current || initialSourceRef.current.documentId !== documentId) {
293
+ initialSourceRef.current = {
294
+ documentId,
295
+ initialDocx,
296
+ initialSessionState,
297
+ initialSnapshot,
298
+ initialSourceLabel,
299
+ };
300
+ }
301
+
302
+ const stableInitialSource = initialSourceRef.current;
303
+ const sourceReloadKey = externalDocSource
304
+ ? `external:${externalDocSource.kind}:${externalDocumentRevision ?? "static"}`
305
+ : stableInitialSource?.initialSessionState
306
+ ? "initial-session"
307
+ : stableInitialSource?.initialSnapshot
308
+ ? "initial-snapshot"
309
+ : stableInitialSource?.initialDocx
310
+ ? "initial-docx"
311
+ : hostAdapter
312
+ ? `host-adapter:${loadRevision ?? "static"}`
313
+ : `datastore:${loadRevision ?? "static"}`;
314
+
315
+ useEffect(() => {
316
+ hostAdapterRef.current = hostAdapter;
317
+ datastoreRef.current = datastore;
318
+ onEventRef.current = onEvent;
319
+ onWarningRef.current = onWarning;
320
+ onErrorRef.current = onError;
321
+ }, [datastore, hostAdapter, onError, onEvent, onWarning]);
322
+
323
+ useEffect(() => {
324
+ runtimeRef.current?.setDefaultAuthorId?.(currentUser.userId);
325
+ }, [currentUser.userId]);
326
+
327
+ useEffect(() => {
328
+ let cancelled = false;
329
+
330
+ async function loadRuntime(): Promise<void> {
331
+ setLoadError(null);
332
+
333
+ try {
334
+ const source = await __resolveWordReviewEditorSource({
335
+ documentId,
336
+ hostAdapter: hostAdapterRef.current,
337
+ datastore: datastoreRef.current,
338
+ externalDocSource,
339
+ initialDocx: stableInitialSource?.initialDocx,
340
+ initialSessionState: stableInitialSource?.initialSessionState,
341
+ initialSnapshot: stableInitialSource?.initialSnapshot,
342
+ initialSourceLabel: stableInitialSource?.initialSourceLabel,
343
+ loadRevision,
344
+ loadSourcePolicy,
345
+ });
346
+
347
+ if (cancelled) {
348
+ return;
349
+ }
350
+
351
+ runtimeRef.current?.dispose?.();
352
+ const nextRuntime = createRuntime(
353
+ {
354
+ documentId,
355
+ readOnly,
356
+ source,
357
+ initialViewState: runtimeViewStateSeedRef.current,
358
+ hostAdapter: hostAdapterRef.current,
359
+ datastore: datastoreRef.current,
360
+ currentUserId: currentUser.userId,
361
+ },
362
+ {
363
+ onWarning: onWarningRef.current,
364
+ onError: onErrorRef.current,
365
+ onEvent: onEventRef.current,
366
+ },
367
+ );
368
+ recordPerfSample("runtime.create");
369
+ emitEditorEvent({
370
+ hostAdapter: hostAdapterRef.current,
371
+ datastore: datastoreRef.current,
372
+ onEvent: onEventRef.current,
373
+ event: createReadyEvent(nextRuntime, source.source),
374
+ });
375
+ runtimeRef.current = nextRuntime;
376
+ setRuntime(nextRuntime);
377
+ } catch (error) {
378
+ if (cancelled) {
379
+ return;
380
+ }
381
+
382
+ const normalized = normalizeEditorError(error);
383
+ setLoadError(normalized);
384
+ onErrorRef.current?.(normalized);
385
+ emitEditorEvent({
386
+ hostAdapter: hostAdapterRef.current,
387
+ datastore: datastoreRef.current,
388
+ onEvent: onEventRef.current,
389
+ event: {
390
+ type: "error",
391
+ documentId,
392
+ error: normalized,
393
+ },
394
+ });
395
+ }
396
+ }
397
+
398
+ void loadRuntime();
399
+
400
+ return () => {
401
+ cancelled = true;
402
+ };
403
+ }, [
404
+ documentId,
405
+ readOnly,
406
+ sourceReloadKey,
407
+ ]);
408
+
409
+ useEffect(() => {
410
+ if (!runtime?.subscribeToEvents) {
411
+ return;
412
+ }
413
+
414
+ return runtime.subscribeToEvents((event) => {
415
+ if (event.type === "export_completed" || event.type === "ready") {
416
+ return;
417
+ }
418
+ emitEditorEvent({
419
+ hostAdapter: hostAdapterRef.current,
420
+ datastore: datastoreRef.current,
421
+ onEvent: onEventRef.current,
422
+ event,
423
+ });
424
+ });
425
+ }, [runtime]);
426
+
427
+ useEffect(() => {
428
+ return () => {
429
+ if (autosaveTimerRef.current) {
430
+ clearTimeout(autosaveTimerRef.current);
431
+ autosaveTimerRef.current = null;
432
+ }
433
+ runtimeRef.current?.dispose?.();
434
+ runtimeRef.current = null;
435
+ };
436
+ }, []);
437
+
438
+ const fallbackSnapshot = useMemo(
439
+ () =>
440
+ loadError
441
+ ? createErrorSnapshot(documentId, loadError)
442
+ : createLoadingSnapshot(
443
+ documentId,
444
+ readOnly,
445
+ guessSourceLabel(
446
+ initialSourceLabel,
447
+ initialSessionState,
448
+ initialSnapshot,
449
+ externalDocSource,
450
+ ),
451
+ ),
452
+ [
453
+ documentId,
454
+ externalDocSource,
455
+ initialSessionState,
456
+ initialSnapshot,
457
+ initialSourceLabel,
458
+ loadError,
459
+ readOnly,
460
+ ],
461
+ );
462
+ const loadingPersistedSnapshot = useMemo(
463
+ () => createFallbackPersistedSnapshot(documentId, initialSourceLabel),
464
+ [documentId, initialSourceLabel],
465
+ );
466
+ const loadingSessionState = useMemo(
467
+ () =>
468
+ initialSessionState ??
469
+ (initialSnapshot
470
+ ? editorSessionStateFromPersistedSnapshot(initialSnapshot)
471
+ : editorSessionStateFromPersistedSnapshot(loadingPersistedSnapshot)),
472
+ [initialSessionState, initialSnapshot, loadingPersistedSnapshot],
473
+ );
474
+ const loadingViewState = useMemo(
475
+ () =>
476
+ createLoadingViewStateSnapshot(
477
+ fallbackSnapshot,
478
+ runtimeViewStateSeedRef.current,
479
+ deriveEditorViewMode(fallbackSnapshot.readOnly, reviewMode),
480
+ ),
481
+ [fallbackSnapshot, reviewMode],
482
+ );
483
+ const loadingNavigation = useMemo(
484
+ () => createLoadingNavigationSnapshot(),
485
+ [],
486
+ );
487
+ const loadingRuntimeBridge = useMemo(
488
+ () =>
489
+ createLoadingRuntimeBridge({
490
+ snapshot: fallbackSnapshot,
491
+ sessionState: loadingSessionState,
492
+ viewState: loadingViewState,
493
+ navigation: loadingNavigation,
494
+ }),
495
+ [fallbackSnapshot, loadingNavigation, loadingSessionState, loadingViewState],
496
+ );
497
+
498
+ return {
499
+ runtime,
500
+ loadError,
501
+ activeRuntime: runtime ?? loadingRuntimeBridge,
502
+ fallbackSnapshot,
503
+ loadingSessionState,
504
+ loadingViewState,
505
+ loadingNavigation,
506
+ hostAdapterRef,
507
+ datastoreRef,
508
+ onEventRef,
509
+ onWarningRef,
510
+ onErrorRef,
511
+ autosaveTimerRef,
512
+ lastSavedRevisionTokenRef,
513
+ runtimeViewStateSeedRef,
514
+ };
515
+ }
516
+
517
+ function createRuntime(
518
+ args: CreateRuntimeArgs,
519
+ handlers: RuntimeLifecycleHandlers = {},
520
+ ): WordReviewEditorRuntime {
521
+ const docxSession = args.source.initialDocx
522
+ ? loadDocxEditorSession({
523
+ documentId: args.documentId,
524
+ sourceLabel: args.source.sourceLabel,
525
+ bytes: args.source.initialDocx,
526
+ editorBuild: "dev",
527
+ })
528
+ : undefined;
529
+ const snapshotExportResolution = !args.source.initialDocx
530
+ ? resolvePackageBackedExportSession(args)
531
+ : undefined;
532
+ const initialSessionState =
533
+ args.source.initialSessionState ??
534
+ docxSession?.initialSessionState ??
535
+ (args.source.initialSnapshot
536
+ ? editorSessionStateFromPersistedSnapshot(args.source.initialSnapshot)
537
+ : editorSessionStateFromPersistedSnapshot(
538
+ createFallbackPersistedSnapshot(
539
+ args.documentId,
540
+ args.source.sourceLabel ?? "Generated shell snapshot",
541
+ ),
542
+ ));
543
+ const runtimeSessionState = snapshotExportResolution?.barrier
544
+ ? applySessionExportBarrier(initialSessionState, snapshotExportResolution.barrier)
545
+ : initialSessionState;
546
+
547
+ const runtime: WordReviewEditorRuntime = Object.assign(createDocumentRuntime({
548
+ documentId: args.documentId,
549
+ initialSessionState: runtimeSessionState,
550
+ sourceKind: args.source.source,
551
+ sourceLabel: args.source.sourceLabel,
552
+ initialViewState: args.initialViewState,
553
+ readOnly: args.readOnly || docxSession?.readOnly,
554
+ editorBuild: runtimeSessionState.editorBuild,
555
+ fatalError: docxSession?.fatalError,
556
+ protectionSnapshot: docxSession?.protectionSnapshot,
557
+ exportDocx: async (sessionState, options) => {
558
+ if (docxSession) {
559
+ return docxSession.exportDocx(sessionState, options);
560
+ }
561
+
562
+ if (snapshotExportResolution?.session) {
563
+ return snapshotExportResolution.session.exportDocx(sessionState, options);
564
+ }
565
+
566
+ throw createSnapshotExportBlockedError(
567
+ args.documentId,
568
+ snapshotExportResolution?.barrier ?? {
569
+ reason: "missing_source_package_provenance",
570
+ message:
571
+ "DOCX export is blocked because this session does not carry embedded source package provenance.",
572
+ },
573
+ );
574
+ },
575
+ onWarning: handlers.onWarning,
576
+ onError: handlers.onError,
577
+ defaultAuthorId: args.currentUserId,
578
+ }), {
579
+ emitBlockedCommand: (
580
+ command: string,
581
+ reasons: Extract<WordReviewEditorEvent, { type: "command_blocked" }>["reasons"],
582
+ ) => {
583
+ emitEditorEvent({
584
+ hostAdapter: args.hostAdapter,
585
+ datastore: args.datastore,
586
+ onEvent: handlers.onEvent,
587
+ event: {
588
+ type: "command_blocked",
589
+ documentId: args.documentId,
590
+ command,
591
+ reasons,
592
+ },
593
+ });
594
+ },
595
+ });
596
+
597
+ return runtime;
598
+ }
599
+
600
+ function createLoadingSnapshot(
601
+ documentId: string,
602
+ readOnly: boolean,
603
+ sourceLabel?: string,
604
+ ): RuntimeRenderSnapshot {
605
+ return {
606
+ documentId,
607
+ sessionId: `${documentId}-loading`,
608
+ sourceLabel,
609
+ revisionToken: `${documentId}:loading`,
610
+ isReady: false,
611
+ isDirty: false,
612
+ readOnly,
613
+ documentMode: "editing",
614
+ selection: collapsedSelection(),
615
+ activeStory: { kind: "main" },
616
+ documentStats: {
617
+ storyLength: 0,
618
+ commentCount: 0,
619
+ revisionCount: 0,
620
+ opaqueFragmentCount: 0,
621
+ },
622
+ comments: {
623
+ openCommentIds: [],
624
+ resolvedCommentIds: [],
625
+ detachedCommentIds: [],
626
+ totalCount: 0,
627
+ threads: [],
628
+ },
629
+ trackedChanges: {
630
+ pendingChangeIds: [],
631
+ acceptedChangeIds: [],
632
+ rejectedChangeIds: [],
633
+ detachedChangeIds: [],
634
+ actionableChangeIds: [],
635
+ preserveOnlyChangeIds: [],
636
+ totalCount: 0,
637
+ revisions: [],
638
+ },
639
+ compatibility: {
640
+ blockExport: false,
641
+ blockExportReasons: [],
642
+ warningCount: 0,
643
+ errorCount: 0,
644
+ featureEntries: [],
645
+ },
646
+ warnings: [],
647
+ commandState: {
648
+ canUndo: false,
649
+ canRedo: false,
650
+ readOnly,
651
+ },
652
+ protectionSnapshot: {
653
+ hasDocumentProtection: false,
654
+ enforcementActive: false,
655
+ ranges: [],
656
+ enforcedRangeCount: 0,
657
+ preservedRangeCount: 0,
658
+ },
659
+ };
660
+ }
661
+
662
+ function createLoadingNavigationSnapshot(): DocumentNavigationSnapshot {
663
+ return {
664
+ pageCount: 0,
665
+ pages: [],
666
+ headings: [],
667
+ activePageIndex: 0,
668
+ activeSectionIndex: 0,
669
+ };
670
+ }
671
+
672
+ function createLoadingViewStateSnapshot(
673
+ snapshot: RuntimeRenderSnapshot,
674
+ seed: {
675
+ workspaceMode?: WorkspaceMode;
676
+ zoomLevel?: ZoomLevel;
677
+ },
678
+ viewMode: EditorViewMode,
679
+ ): EditorViewStateSnapshot {
680
+ return createEditorViewStateSnapshot(
681
+ createViewState({
682
+ viewMode,
683
+ workspaceMode: seed.workspaceMode,
684
+ zoomLevel: seed.zoomLevel,
685
+ }),
686
+ snapshot.activeStory,
687
+ snapshot.selection,
688
+ snapshot.surface,
689
+ snapshot.surface,
690
+ snapshot.pageLayout,
691
+ );
692
+ }
693
+
694
+ function createLoadingRuntimeBridge(input: {
695
+ snapshot: RuntimeRenderSnapshot;
696
+ sessionState: EditorSessionState;
697
+ viewState: EditorViewStateSnapshot;
698
+ navigation: DocumentNavigationSnapshot;
699
+ }): WordReviewEditorRuntime {
700
+ const emptyFieldSnapshot: FieldSnapshot = {
701
+ totalCount: 0,
702
+ supportedCount: 0,
703
+ preserveOnlyCount: 0,
704
+ fields: [],
705
+ };
706
+ const emptyFieldResult: UpdateFieldsResult = {
707
+ totalCount: 0,
708
+ updatedCount: 0,
709
+ preserveOnlyCount: 0,
710
+ };
711
+ const emptyTocResult: TocRefreshResult = {
712
+ entryCount: 0,
713
+ entries: [],
714
+ };
715
+
716
+ return {
717
+ subscribe: () => () => undefined,
718
+ subscribeToEvents: () => () => undefined,
719
+ emitBlockedCommand: () => undefined,
720
+ getRenderSnapshot: () => input.snapshot,
721
+ replaceText: () => undefined,
722
+ dispatch: () => undefined,
723
+ undo: () => undefined,
724
+ redo: () => undefined,
725
+ focus: () => undefined,
726
+ blur: () => undefined,
727
+ addComment: () => {
728
+ throw createLoadingBoundaryError(input.snapshot.documentId, "comment");
729
+ },
730
+ openComment: () => undefined,
731
+ resolveComment: () => undefined,
732
+ reopenComment: () => undefined,
733
+ addCommentReply: () => undefined,
734
+ editCommentBody: () => undefined,
735
+ acceptChange: () => undefined,
736
+ rejectChange: () => undefined,
737
+ acceptAllChanges: () => undefined,
738
+ rejectAllChanges: () => undefined,
739
+ openStory: () => false,
740
+ closeStory: () => undefined,
741
+ getActiveStory: () => input.snapshot.activeStory,
742
+ getViewState: () => input.viewState,
743
+ setViewMode: () => undefined,
744
+ setDocumentMode: () => undefined,
745
+ getProtectionSnapshot: () => input.snapshot.protectionSnapshot,
746
+ setWorkspaceMode: () => undefined,
747
+ setZoom: () => undefined,
748
+ getPageLayoutSnapshot: () => null,
749
+ getDocumentNavigationSnapshot: () => input.navigation,
750
+ getFieldSnapshot: () => emptyFieldSnapshot,
751
+ updateFields: () => emptyFieldResult,
752
+ updateTableOfContents: () => emptyTocResult,
753
+ getSessionState: () => {
754
+ throw createLoadingBoundaryError(input.snapshot.documentId, "session");
755
+ },
756
+ getPersistedSnapshot: () => {
757
+ throw createLoadingBoundaryError(input.snapshot.documentId, "snapshot");
758
+ },
759
+ getCompatibilityReport: () => ({
760
+ reportVersion: "compatibility-report/1",
761
+ generatedAt: input.sessionState.updatedAt,
762
+ blockExport: input.snapshot.compatibility.blockExport,
763
+ featureEntries: input.snapshot.compatibility.featureEntries,
764
+ warnings: input.snapshot.warnings,
765
+ errors: input.snapshot.fatalError ? [input.snapshot.fatalError] : [],
766
+ }),
767
+ getWarnings: () => input.snapshot.warnings,
768
+ exportDocx: () =>
769
+ Promise.reject(createLoadingBoundaryError(input.snapshot.documentId, "export")),
770
+ setWorkflowOverlay: () => undefined,
771
+ clearWorkflowOverlay: () => undefined,
772
+ getWorkflowScopeSnapshot: () => null,
773
+ getInteractionGuardSnapshot: () => ({ blockedReasons: [] }),
774
+ getWorkflowMarkupSnapshot: () => ({
775
+ totalCount: 0,
776
+ items: [],
777
+ highlights: [],
778
+ comments: [],
779
+ revisions: [],
780
+ fields: [],
781
+ protectedRanges: [],
782
+ opaqueFragments: [],
783
+ }),
784
+ getWorkflowCandidateRanges: () => [],
785
+ replaceWorkflowMarkupText: () => undefined,
786
+ };
787
+ }
788
+
789
+ function createLoadingBoundaryError(
790
+ documentId: string,
791
+ target: "comment" | "session" | "snapshot" | "export",
792
+ ): EditorError {
793
+ return {
794
+ errorId: `${documentId}-loading-${target}`,
795
+ code: "internal_invariant",
796
+ message: "Editor is still loading.",
797
+ isFatal: false,
798
+ source: "runtime",
799
+ };
800
+ }
801
+
802
+ function deriveEditorViewMode(
803
+ readOnly: boolean,
804
+ reviewMode: WordReviewEditorProps["reviewMode"] = "review",
805
+ ): EditorViewMode {
806
+ if (readOnly) {
807
+ return "view";
808
+ }
809
+ return reviewMode === "editing" ? "editing" : "review";
810
+ }
811
+
812
+ function createErrorSnapshot(documentId: string, error: EditorError): RuntimeRenderSnapshot {
813
+ return {
814
+ ...createLoadingSnapshot(documentId, true),
815
+ isReady: true,
816
+ sessionId: `${documentId}-error`,
817
+ revisionToken: `${documentId}:error`,
818
+ compatibility: {
819
+ blockExport: true,
820
+ blockExportReasons: [error.message],
821
+ warningCount: 0,
822
+ errorCount: 1,
823
+ featureEntries: [],
824
+ },
825
+ fatalError: error,
826
+ };
827
+ }
828
+
829
+ export async function persistAndExport(input: {
830
+ hostAdapter?: EditorHostAdapter;
831
+ datastore?: EditorDatastoreAdapter;
832
+ documentId: string;
833
+ runtime: WordReviewEditorRuntime;
834
+ onError?: (error: EditorError) => void;
835
+ onEvent?: (event: WordReviewEditorEvent) => void;
836
+ options?: ExportDocxOptions;
837
+ lastSavedRevisionTokenRef: React.MutableRefObject<string | null>;
838
+ autosaveTimerRef: React.MutableRefObject<ReturnType<typeof setTimeout> | null>;
839
+ }): Promise<ExportResult> {
840
+ if (input.autosaveTimerRef.current) {
841
+ clearTimeout(input.autosaveTimerRef.current);
842
+ input.autosaveTimerRef.current = null;
843
+ }
844
+
845
+ await persistSession({
846
+ hostAdapter: input.hostAdapter,
847
+ datastore: input.datastore,
848
+ documentId: input.documentId,
849
+ runtime: input.runtime,
850
+ isAutosave: false,
851
+ onError: input.onError,
852
+ onEvent: input.onEvent,
853
+ lastSavedRevisionTokenRef: input.lastSavedRevisionTokenRef,
854
+ });
855
+
856
+ let result: ExportResult;
857
+ try {
858
+ result = await input.runtime.exportDocx(input.options);
859
+ } catch (error) {
860
+ const normalized = normalizeExportError(error, input.documentId, input.options);
861
+ input.onError?.(normalized);
862
+ emitEditorEvent({
863
+ hostAdapter: input.hostAdapter,
864
+ datastore: input.datastore,
865
+ onEvent: input.onEvent,
866
+ event: {
867
+ type: "error",
868
+ documentId: input.documentId,
869
+ error: normalized,
870
+ },
871
+ });
872
+ throw normalized;
873
+ }
874
+
875
+ const saveExport = input.hostAdapter?.saveExport ?? input.datastore?.saveExport;
876
+ const saveExportSource = input.hostAdapter?.saveExport ? "host" : "datastore";
877
+ if (!saveExport) {
878
+ result = downloadExportResult(result);
879
+ emitEditorEvent({
880
+ hostAdapter: input.hostAdapter,
881
+ datastore: input.datastore,
882
+ onEvent: input.onEvent,
883
+ event: {
884
+ type: "export_completed",
885
+ documentId: input.documentId,
886
+ result,
887
+ },
888
+ });
889
+ return result;
890
+ }
891
+
892
+ try {
893
+ const saveResult = await saveExport({
894
+ documentId: input.documentId,
895
+ result,
896
+ });
897
+ result = withExportDelivery(result, {
898
+ mode: "persisted-by-host",
899
+ savedAt: saveResult.savedAt,
900
+ });
901
+ } catch (error) {
902
+ const normalized = normalizeStorageError(error, {
903
+ message: "Export persisted bytes could not be stored.",
904
+ source: saveExportSource,
905
+ details: {
906
+ operation: "saveExport",
907
+ },
908
+ });
909
+ input.onError?.(normalized);
910
+ emitEditorEvent({
911
+ hostAdapter: input.hostAdapter,
912
+ datastore: input.datastore,
913
+ onEvent: input.onEvent,
914
+ event: {
915
+ type: "error",
916
+ documentId: input.documentId,
917
+ error: normalized,
918
+ },
919
+ });
920
+ result = withExportDelivery(result, {
921
+ mode: "exported-bytes-only",
922
+ });
923
+ }
924
+
925
+ emitEditorEvent({
926
+ hostAdapter: input.hostAdapter,
927
+ datastore: input.datastore,
928
+ onEvent: input.onEvent,
929
+ event: {
930
+ type: "export_completed",
931
+ documentId: input.documentId,
932
+ result,
933
+ },
934
+ });
935
+
936
+ return result;
937
+ }
938
+
939
+ export function rejectExportWhileLoading(input: {
940
+ documentId: string;
941
+ hostAdapter?: EditorHostAdapter;
942
+ datastore?: EditorDatastoreAdapter;
943
+ onError?: (error: EditorError) => void;
944
+ onEvent?: (event: WordReviewEditorEvent) => void;
945
+ }): Promise<never> {
946
+ const error: EditorError = {
947
+ errorId: "word-review-editor-loading-export",
948
+ code: "internal_invariant",
949
+ message: "WordReviewEditor is still loading and cannot export yet.",
950
+ isFatal: false,
951
+ source: "runtime",
952
+ };
953
+ input.onError?.(error);
954
+ emitEditorEvent({
955
+ hostAdapter: input.hostAdapter,
956
+ datastore: input.datastore,
957
+ onEvent: input.onEvent,
958
+ event: {
959
+ type: "error",
960
+ documentId: input.documentId,
961
+ error,
962
+ },
963
+ });
964
+ return Promise.reject(error);
965
+ }
966
+
967
+ export async function persistSession(input: {
968
+ hostAdapter?: EditorHostAdapter;
969
+ datastore?: EditorDatastoreAdapter;
970
+ documentId: string;
971
+ runtime: WordReviewEditorRuntime;
972
+ isAutosave: boolean;
973
+ onError?: (error: EditorError) => void;
974
+ onEvent?: (event: WordReviewEditorEvent) => void;
975
+ lastSavedRevisionTokenRef: React.MutableRefObject<string | null>;
976
+ }): Promise<void> {
977
+ const saveSession = input.hostAdapter?.saveSession;
978
+ const saveSnapshot = input.datastore?.saveSnapshot;
979
+ if (!saveSession && !saveSnapshot) {
980
+ return;
981
+ }
982
+
983
+ const sessionState = input.runtime.getSessionState();
984
+ const snapshot = input.runtime.getPersistedSnapshot();
985
+ const revisionToken = input.runtime.getRenderSnapshot().revisionToken;
986
+
987
+ if (input.isAutosave) {
988
+ emitEditorEvent({
989
+ hostAdapter: input.hostAdapter,
990
+ datastore: input.datastore,
991
+ onEvent: input.onEvent,
992
+ event: {
993
+ type: "autosave_state",
994
+ documentId: input.documentId,
995
+ state: {
996
+ status: "saving",
997
+ } satisfies AutosaveState,
998
+ },
999
+ });
1000
+ }
1001
+
1002
+ try {
1003
+ const result = saveSession
1004
+ ? await saveSession({
1005
+ documentId: input.documentId,
1006
+ sessionState,
1007
+ isAutosave: input.isAutosave,
1008
+ })
1009
+ : await saveSnapshot!({
1010
+ documentId: input.documentId,
1011
+ snapshot,
1012
+ isAutosave: input.isAutosave,
1013
+ });
1014
+ input.lastSavedRevisionTokenRef.current = revisionToken;
1015
+ emitEditorEvent({
1016
+ hostAdapter: input.hostAdapter,
1017
+ datastore: input.datastore,
1018
+ onEvent: input.onEvent,
1019
+ event: saveSession
1020
+ ? {
1021
+ type: "session_saved",
1022
+ documentId: input.documentId,
1023
+ sessionState: input.runtime.getSessionState(),
1024
+ savedAt: result.savedAt,
1025
+ isAutosave: input.isAutosave,
1026
+ }
1027
+ : {
1028
+ type: "snapshot_saved",
1029
+ documentId: input.documentId,
1030
+ snapshot: {
1031
+ ...snapshot,
1032
+ savedAt: result.savedAt,
1033
+ },
1034
+ isAutosave: input.isAutosave,
1035
+ },
1036
+ });
1037
+ if (input.isAutosave) {
1038
+ emitEditorEvent({
1039
+ hostAdapter: input.hostAdapter,
1040
+ datastore: input.datastore,
1041
+ onEvent: input.onEvent,
1042
+ event: {
1043
+ type: "autosave_state",
1044
+ documentId: input.documentId,
1045
+ state: {
1046
+ status: "saved",
1047
+ savedAt: result.savedAt,
1048
+ } satisfies AutosaveState,
1049
+ },
1050
+ });
1051
+ }
1052
+ } catch (error) {
1053
+ const normalized = normalizeStorageError(error, {
1054
+ message: input.isAutosave
1055
+ ? saveSession
1056
+ ? "Autosave failed while storing the editor session."
1057
+ : "Autosave failed while storing the editor snapshot."
1058
+ : saveSession
1059
+ ? "Session save failed while preparing the export checkpoint."
1060
+ : "Snapshot save failed while preparing the export checkpoint.",
1061
+ source: saveSession ? "host" : "datastore",
1062
+ details: {
1063
+ operation: saveSession ? "saveSession" : "saveSnapshot",
1064
+ isAutosave: input.isAutosave,
1065
+ },
1066
+ });
1067
+ input.onError?.(normalized);
1068
+ emitEditorEvent({
1069
+ hostAdapter: input.hostAdapter,
1070
+ datastore: input.datastore,
1071
+ onEvent: input.onEvent,
1072
+ event: {
1073
+ type: "error",
1074
+ documentId: input.documentId,
1075
+ error: normalized,
1076
+ },
1077
+ });
1078
+ if (input.isAutosave) {
1079
+ emitEditorEvent({
1080
+ hostAdapter: input.hostAdapter,
1081
+ datastore: input.datastore,
1082
+ onEvent: input.onEvent,
1083
+ event: {
1084
+ type: "autosave_state",
1085
+ documentId: input.documentId,
1086
+ state: {
1087
+ status: "error",
1088
+ error: normalized,
1089
+ } satisfies AutosaveState,
1090
+ },
1091
+ });
1092
+ }
1093
+ if (!input.isAutosave) {
1094
+ throw normalized;
1095
+ }
1096
+ }
1097
+ }
1098
+
1099
+ function emitEditorEvent(input: {
1100
+ hostAdapter?: EditorHostAdapter;
1101
+ datastore?: EditorDatastoreAdapter;
1102
+ onEvent?: (event: WordReviewEditorEvent) => void;
1103
+ event: WordReviewEditorEvent;
1104
+ }): void {
1105
+ input.onEvent?.(input.event);
1106
+ const logEvent = input.hostAdapter?.logEvent ?? input.datastore?.logEvent;
1107
+ logEvent?.({
1108
+ type: input.event.type,
1109
+ documentId: input.event.documentId,
1110
+ detail: summarizeEventDetail(input.event),
1111
+ });
1112
+ }
1113
+
1114
+ function summarizeEventDetail(
1115
+ event: WordReviewEditorEvent,
1116
+ ): Record<string, unknown> | undefined {
1117
+ switch (event.type) {
1118
+ case "dirty_changed":
1119
+ return { isDirty: event.isDirty };
1120
+ case "comment_added":
1121
+ case "comment_resolved":
1122
+ return { commentId: event.commentId };
1123
+ case "change_accepted":
1124
+ case "change_rejected":
1125
+ return { changeId: event.changeId };
1126
+ case "warning_added":
1127
+ return { warningId: event.warning.warningId, code: event.warning.code };
1128
+ case "warning_cleared":
1129
+ return { warningId: event.warningId, code: event.code };
1130
+ case "error":
1131
+ return { errorId: event.error.errorId, code: event.error.code };
1132
+ case "autosave_state":
1133
+ return { status: event.state.status };
1134
+ case "snapshot_saved":
1135
+ return { isAutosave: event.isAutosave, savedAt: event.snapshot.savedAt };
1136
+ case "session_saved":
1137
+ return { isAutosave: event.isAutosave, savedAt: event.savedAt };
1138
+ case "export_completed":
1139
+ return {
1140
+ fileName: event.result.fileName,
1141
+ deliveryMode: event.result.delivery?.mode,
1142
+ savedAt: event.result.delivery?.savedAt,
1143
+ };
1144
+ case "story_changed":
1145
+ return { activeStory: event.activeStory };
1146
+ case "selection_changed":
1147
+ return {
1148
+ anchor: event.selection.anchor,
1149
+ head: event.selection.head,
1150
+ };
1151
+ case "ready":
1152
+ return {
1153
+ source: event.source,
1154
+ blockExport: event.compatibility.blockExport,
1155
+ };
1156
+ }
1157
+ }
1158
+
1159
+ function createReadyEvent(
1160
+ runtime: Pick<WordReviewEditorRuntime, "getCompatibilityReport" | "getRenderSnapshot">,
1161
+ source: "docx" | "session" | "snapshot",
1162
+ ): Extract<WordReviewEditorEvent, { type: "ready" }> {
1163
+ const snapshot = runtime.getRenderSnapshot();
1164
+ return {
1165
+ type: "ready",
1166
+ documentId: snapshot.documentId,
1167
+ sessionId: snapshot.sessionId,
1168
+ source,
1169
+ stats: snapshot.documentStats,
1170
+ compatibility: runtime.getCompatibilityReport(),
1171
+ comments: snapshot.comments,
1172
+ trackedChanges: snapshot.trackedChanges,
1173
+ };
1174
+ }
1175
+
1176
+ function normalizeEditorError(error: unknown): EditorError {
1177
+ if (
1178
+ typeof error === "object" &&
1179
+ error !== null &&
1180
+ "errorId" in error &&
1181
+ "code" in error &&
1182
+ "message" in error
1183
+ ) {
1184
+ return error as EditorError;
1185
+ }
1186
+
1187
+ return {
1188
+ errorId: "word-review-editor-load",
1189
+ code: "internal_invariant",
1190
+ message: error instanceof Error ? error.message : "Unknown editor load failure.",
1191
+ isFatal: true,
1192
+ source: "runtime",
1193
+ };
1194
+ }
1195
+
1196
+ function guessSourceLabel(
1197
+ initialSourceLabel?: string,
1198
+ initialSessionState?: EditorSessionState,
1199
+ initialSnapshot?: PersistedEditorSnapshot,
1200
+ externalDocSource?: WordReviewEditorProps["externalDocSource"],
1201
+ ): string | undefined {
1202
+ return (
1203
+ externalDocSource?.sourceLabel ??
1204
+ (externalDocSource?.kind === "session"
1205
+ ? externalDocSource.sessionState.sourcePackage?.sourceLabel
1206
+ : undefined) ??
1207
+ (externalDocSource?.kind === "snapshot"
1208
+ ? externalDocSource.snapshot.sourcePackage?.sourceLabel
1209
+ : undefined) ??
1210
+ initialSourceLabel ??
1211
+ initialSessionState?.sourcePackage?.sourceLabel ??
1212
+ initialSessionState?.editorBuild ??
1213
+ initialSnapshot?.sourcePackage?.sourceLabel ??
1214
+ initialSnapshot?.editorBuild ??
1215
+ undefined
1216
+ );
1217
+ }
1218
+
1219
+ function createFallbackPersistedSnapshot(
1220
+ documentId: string,
1221
+ label = "Generated shell snapshot",
1222
+ ): PersistedEditorSnapshot {
1223
+ const docId = createCanonicalDocumentId(documentId);
1224
+ return {
1225
+ snapshotVersion: "persisted-editor-snapshot/2",
1226
+ schemaVersion: "cds/1.0.0",
1227
+ documentId,
1228
+ docId,
1229
+ createdAt: "1970-01-01T00:00:00.000Z",
1230
+ updatedAt: "1970-01-01T00:00:00.000Z",
1231
+ savedAt: "1970-01-01T00:00:00.000Z",
1232
+ editorBuild: label,
1233
+ canonicalDocument: {
1234
+ schemaVersion: "cds/1.0.0",
1235
+ docId,
1236
+ createdAt: "1970-01-01T00:00:00.000Z",
1237
+ updatedAt: "1970-01-01T00:00:00.000Z",
1238
+ metadata: { customProperties: {} },
1239
+ styles: { paragraphs: {}, characters: {}, tables: {} },
1240
+ numbering: { abstractDefinitions: {}, instances: {} },
1241
+ media: { items: {} },
1242
+ content: {
1243
+ type: "doc",
1244
+ children: [{ type: "paragraph", children: [] }],
1245
+ },
1246
+ review: { comments: {}, revisions: {} },
1247
+ preservation: { opaqueFragments: {}, packageParts: {} },
1248
+ diagnostics: { warnings: [], errors: [] },
1249
+ },
1250
+ compatibility: emptyCompatibilityReport(),
1251
+ warningLog: [],
1252
+ };
1253
+ }
1254
+
1255
+ function emptyCompatibilityReport(): CompatibilityReport {
1256
+ return {
1257
+ reportVersion: "compatibility-report/1",
1258
+ generatedAt: "1970-01-01T00:00:00.000Z",
1259
+ blockExport: false,
1260
+ featureEntries: [],
1261
+ warnings: [],
1262
+ errors: [],
1263
+ };
1264
+ }
1265
+
1266
+ function resolvePackageBackedExportSession(args: CreateRuntimeArgs): {
1267
+ session?: PackageBackedDocxSession;
1268
+ barrier?: SnapshotExportBarrier;
1269
+ } {
1270
+ const sourcePackage =
1271
+ args.source.initialSessionState?.sourcePackage ??
1272
+ args.source.initialSnapshot?.sourcePackage;
1273
+ if (!sourcePackage) {
1274
+ return {
1275
+ barrier: {
1276
+ reason: "missing_source_package_provenance",
1277
+ message:
1278
+ "DOCX export is blocked because this session was loaded without embedded source package provenance.",
1279
+ },
1280
+ };
1281
+ }
1282
+
1283
+ try {
1284
+ const bytes = decodePersistedSourcePackageBytes(sourcePackage);
1285
+ if (!hasValidPersistedSourcePackageDigest(sourcePackage, bytes)) {
1286
+ return {
1287
+ barrier: {
1288
+ reason: "invalid_source_package_provenance",
1289
+ message:
1290
+ "DOCX export is blocked because the embedded source package provenance failed its integrity check.",
1291
+ },
1292
+ };
1293
+ }
1294
+
1295
+ const session = loadDocxEditorSession({
1296
+ documentId: args.documentId,
1297
+ sourceLabel: sourcePackage.sourceLabel ?? args.source.sourceLabel,
1298
+ bytes,
1299
+ editorBuild:
1300
+ args.source.initialSessionState?.editorBuild ??
1301
+ args.source.initialSnapshot?.editorBuild ??
1302
+ "dev",
1303
+ });
1304
+ if (session.readOnly || session.fatalError) {
1305
+ return {
1306
+ barrier: {
1307
+ reason: "invalid_source_package_provenance",
1308
+ message:
1309
+ "DOCX export is blocked because the embedded source package provenance is no longer loadable as a valid package-backed session.",
1310
+ },
1311
+ };
1312
+ }
1313
+
1314
+ return { session };
1315
+ } catch {
1316
+ return {
1317
+ barrier: {
1318
+ reason: "invalid_source_package_provenance",
1319
+ message:
1320
+ "DOCX export is blocked because the embedded source package provenance could not be decoded into a package-backed session.",
1321
+ },
1322
+ };
1323
+ }
1324
+ }
1325
+
1326
+ function applySessionExportBarrier(
1327
+ sessionState: EditorSessionState,
1328
+ barrier: SnapshotExportBarrier,
1329
+ ): EditorSessionState {
1330
+ const featureEntryId = `feature:source-package-provenance:${barrier.reason}`;
1331
+ const featureEntries = sessionState.compatibility.featureEntries.some(
1332
+ (entry) => entry.featureEntryId === featureEntryId,
1333
+ )
1334
+ ? sessionState.compatibility.featureEntries
1335
+ : [
1336
+ ...sessionState.compatibility.featureEntries,
1337
+ {
1338
+ featureEntryId,
1339
+ featureKey: "source-package-provenance",
1340
+ featureClass: "unsupported-fatal" as const,
1341
+ message: barrier.message,
1342
+ details: {
1343
+ reason: barrier.reason,
1344
+ },
1345
+ },
1346
+ ];
1347
+
1348
+ return {
1349
+ ...sessionState,
1350
+ compatibility: {
1351
+ ...sessionState.compatibility,
1352
+ blockExport: true,
1353
+ featureEntries,
1354
+ },
1355
+ };
1356
+ }
1357
+
1358
+ function createSnapshotExportBlockedError(
1359
+ documentId: string,
1360
+ barrier: SnapshotExportBarrier,
1361
+ ): EditorError {
1362
+ return {
1363
+ errorId: `${documentId}:export:${barrier.reason}`,
1364
+ code: "export_failed",
1365
+ message: barrier.message,
1366
+ isFatal: false,
1367
+ source: "export",
1368
+ details: {
1369
+ reason: barrier.reason,
1370
+ },
1371
+ };
1372
+ }
1373
+
1374
+ function normalizeStorageError(
1375
+ error: unknown,
1376
+ fallback: {
1377
+ message: string;
1378
+ source: "host" | "datastore";
1379
+ details?: Record<string, unknown>;
1380
+ },
1381
+ ): EditorError {
1382
+ if (
1383
+ typeof error === "object" &&
1384
+ error !== null &&
1385
+ "errorId" in error &&
1386
+ "code" in error &&
1387
+ "message" in error
1388
+ ) {
1389
+ return error as EditorError;
1390
+ }
1391
+
1392
+ return {
1393
+ errorId:
1394
+ fallback.source === "host"
1395
+ ? "word-review-editor-host"
1396
+ : "word-review-editor-datastore",
1397
+ code: "datastore_failed",
1398
+ message: error instanceof Error ? error.message : fallback.message,
1399
+ isFatal: false,
1400
+ source: fallback.source === "host" ? "host" : "datastore",
1401
+ details: fallback.details,
1402
+ };
1403
+ }
1404
+
1405
+ function normalizeExportError(
1406
+ error: unknown,
1407
+ documentId: string,
1408
+ options?: ExportDocxOptions,
1409
+ ): EditorError {
1410
+ if (
1411
+ typeof error === "object" &&
1412
+ error !== null &&
1413
+ "errorId" in error &&
1414
+ "code" in error &&
1415
+ "message" in error
1416
+ ) {
1417
+ return error as EditorError;
1418
+ }
1419
+
1420
+ return {
1421
+ errorId: `${documentId}:export:failed`,
1422
+ code: "export_failed",
1423
+ message:
1424
+ error instanceof Error ? error.message : "DOCX export failed for an unknown reason.",
1425
+ isFatal: false,
1426
+ source: "export",
1427
+ details: {
1428
+ requestedOptions: options ?? {},
1429
+ },
1430
+ };
1431
+ }
1432
+
1433
+ function collapsedSelection(): RuntimeRenderSnapshot["selection"] {
1434
+ return {
1435
+ anchor: 0,
1436
+ head: 0,
1437
+ isCollapsed: true,
1438
+ activeRange: {
1439
+ kind: "range",
1440
+ from: 0,
1441
+ to: 0,
1442
+ assoc: {
1443
+ start: -1,
1444
+ end: 1,
1445
+ },
1446
+ },
1447
+ };
1448
+ }