@asyra/factory 0.2.5 → 0.5.1

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 (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -1
  3. package/dist/data-transact.d.ts +182 -6
  4. package/dist/data-transact.d.ts.map +1 -1
  5. package/dist/data-transact.js +3128 -57
  6. package/dist/data-transact.js.map +1 -1
  7. package/dist/factory.d.ts +58 -8
  8. package/dist/factory.d.ts.map +1 -1
  9. package/dist/factory.js +273 -13
  10. package/dist/factory.js.map +1 -1
  11. package/dist/index.d.ts +22 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +21 -2
  14. package/dist/index.js.map +1 -1
  15. package/dist/mutation-batch.d.ts +28 -0
  16. package/dist/mutation-batch.d.ts.map +1 -0
  17. package/dist/mutation-batch.js +11 -0
  18. package/dist/mutation-batch.js.map +1 -0
  19. package/dist/shared-data-channel.d.ts +29 -0
  20. package/dist/shared-data-channel.d.ts.map +1 -0
  21. package/dist/shared-data-channel.js +147 -0
  22. package/dist/shared-data-channel.js.map +1 -0
  23. package/dist/shared-delivery.d.ts +76 -0
  24. package/dist/shared-delivery.d.ts.map +1 -0
  25. package/dist/shared-delivery.js +4 -0
  26. package/dist/shared-delivery.js.map +1 -0
  27. package/dist/subscribes.d.ts +1 -1
  28. package/dist/subscribes.d.ts.map +1 -1
  29. package/dist/subscribes.js +3 -19
  30. package/dist/subscribes.js.map +1 -1
  31. package/dist/transaction.d.ts +31 -0
  32. package/dist/transaction.d.ts.map +1 -0
  33. package/dist/transaction.js +17 -0
  34. package/dist/transaction.js.map +1 -0
  35. package/dist/value-clone.d.ts +7 -0
  36. package/dist/value-clone.d.ts.map +1 -0
  37. package/dist/value-clone.js +76 -0
  38. package/dist/value-clone.js.map +1 -0
  39. package/package.json +22 -5
  40. package/.turbo/turbo-test$colon$ci.log +0 -66
  41. package/.turbo/turbo-test$colon$local.log +0 -25
  42. package/.turbo/turbo-test.log +0 -357
  43. package/CHANGELOG.md +0 -46
  44. package/coverage/base.css +0 -224
  45. package/coverage/block-navigation.js +0 -87
  46. package/coverage/clover.xml +0 -228
  47. package/coverage/coverage-final.json +0 -3214
  48. package/coverage/favicon.png +0 -0
  49. package/coverage/index.html +0 -131
  50. package/coverage/prettify.css +0 -1
  51. package/coverage/prettify.js +0 -2
  52. package/coverage/sort-arrow-sprite.png +0 -0
  53. package/coverage/sorter.js +0 -196
  54. package/coverage/src/data-transact.ts.html +0 -589
  55. package/coverage/src/data.ts.html +0 -94
  56. package/coverage/src/factory.ts.html +0 -205
  57. package/coverage/src/index.html +0 -176
  58. package/coverage/src/index.ts.html +0 -106
  59. package/coverage/src/registry/constants.ts.html +0 -88
  60. package/coverage/src/registry/index.html +0 -176
  61. package/coverage/src/registry/index.ts.html +0 -94
  62. package/coverage/src/registry/props.ts.html +0 -112
  63. package/coverage/src/registry/scene-tree.ts.html +0 -115
  64. package/coverage/src/registry/selection.ts.html +0 -124
  65. package/coverage/src/subscribes.ts.html +0 -178
  66. package/dist/__tests__/factory.test.d.ts +0 -2
  67. package/dist/__tests__/factory.test.d.ts.map +0 -1
  68. package/dist/__tests__/factory.test.js +0 -44
  69. package/dist/__tests__/factory.test.js.map +0 -1
  70. package/dist/data.d.ts +0 -4
  71. package/dist/data.d.ts.map +0 -1
  72. package/dist/data.js +0 -4
  73. package/dist/data.js.map +0 -1
  74. package/dist/registry/constants.d.ts +0 -2
  75. package/dist/registry/constants.d.ts.map +0 -1
  76. package/dist/registry/constants.js +0 -2
  77. package/dist/registry/constants.js.map +0 -1
  78. package/dist/registry/index.d.ts +0 -4
  79. package/dist/registry/index.d.ts.map +0 -1
  80. package/dist/registry/index.js +0 -4
  81. package/dist/registry/index.js.map +0 -1
  82. package/dist/registry/props.d.ts +0 -5
  83. package/dist/registry/props.d.ts.map +0 -1
  84. package/dist/registry/props.js +0 -8
  85. package/dist/registry/props.js.map +0 -1
  86. package/dist/registry/scene-tree.d.ts +0 -5
  87. package/dist/registry/scene-tree.d.ts.map +0 -1
  88. package/dist/registry/scene-tree.js +0 -8
  89. package/dist/registry/scene-tree.js.map +0 -1
  90. package/dist/registry/selection.d.ts +0 -5
  91. package/dist/registry/selection.d.ts.map +0 -1
  92. package/dist/registry/selection.js +0 -8
  93. package/dist/registry/selection.js.map +0 -1
  94. package/src/__tests__/factory.test.ts +0 -54
  95. package/src/data-transact.ts +0 -168
  96. package/src/data.ts +0 -3
  97. package/src/factory.ts +0 -40
  98. package/src/index.ts +0 -7
  99. package/src/registry/constants.ts +0 -1
  100. package/src/registry/index.ts +0 -3
  101. package/src/registry/props.ts +0 -9
  102. package/src/registry/scene-tree.ts +0 -10
  103. package/src/registry/selection.ts +0 -13
  104. package/src/subscribes.ts +0 -31
  105. package/tsconfig.json +0 -17
@@ -1,116 +1,3187 @@
1
- import * as Y from 'yjs';
2
- import { OWNER, UNDO } from '@asyra/utils';
3
- import { endTransaction, publishEvent, startTransaction, updateUndoRedoStatus } from '@asyra/reactive-events';
4
- import { sceneTreeChanges, elementSelectionChanges, propsChanges } from './registry';
5
- const ChangesMaps = {
6
- [OWNER.SCENE_TREE]: sceneTreeChanges,
7
- [OWNER.ELEMENT_SELECTION]: elementSelectionChanges,
8
- [OWNER.PROPS]: propsChanges
1
+ import { UNDO, measureBrowserDragPhase } from '@asyra/utils';
2
+ import { acknowledgeTransactionReplayApplied, applyEventBatchToSynchronousOwners, EventTypes, endTransaction, hasSynchronousEventBatchHandler, isDetachedTransactionValue, isTransactionReplayApplied, publishEvent, publishEventsToObservers, publishEventToObservers, resolveCooperativeRenderMaxItemsPerSlice, runInTransactionReplayMode, startTransaction, userActionCompleted, wasTransactionReplayApplied, updateUndoRedoStatus } from '@asyra/reactive-events';
3
+ import { pushFactoryOwnedBatchToSharedChannel, SharedDataChannelRegistry } from './shared-data-channel.js';
4
+ import { TransactionRollbackError, TransactionValidationError } from './transaction.js';
5
+ import { FactoryMutationBatchAcceptanceError } from './mutation-batch.js';
6
+ import { adoptDeeplyFrozenValue, cloneAndDeepFreezeValue, cloneValue, deepFreezeValue, freezeTrustedValue, isDeeplyFrozenValue } from './value-clone.js';
7
+ const BUILT_IN_INVERTIBLE_EVENT_TYPES = new Set([
8
+ EventTypes.ADD_ELEMENT,
9
+ EventTypes.ADD_ELEMENTS,
10
+ EventTypes.REMOVE_ELEMENT,
11
+ EventTypes.REMOVE_ELEMENTS,
12
+ EventTypes.MOVE_ELEMENTS,
13
+ EventTypes.CHANGE_SUBTREE,
14
+ EventTypes.UPDATE_ELEMENT_DATA,
15
+ EventTypes.ADD_PROPERTY,
16
+ EventTypes.REMOVE_PROPERTY,
17
+ EventTypes.UPDATE_PROPERTY,
18
+ EventTypes.SELECT_ELEMENTS,
19
+ EventTypes.SELECT_VECTOR_POINTS,
20
+ EventTypes.SELECT_VECTOR_SEGMENTS
21
+ ]);
22
+ const LOCAL_ONLY_COMPUTED_EVENT_TYPES = new Set([
23
+ EventTypes.UPDATE_COMPUTED_DATA,
24
+ EventTypes.UPDATE_COMPUTED_DATA_PATCH
25
+ ]);
26
+ const MAX_CANONICAL_REPLAY_OWNER_BATCH_ITEMS = 32;
27
+ const DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS = 512;
28
+ const toDefinedMutationOptions = (options) => {
29
+ if (!options)
30
+ return;
31
+ const definedOptions = {};
32
+ if (options.undoable !== undefined) {
33
+ definedOptions.undoable = options.undoable;
34
+ }
35
+ if (options.rollbackable !== undefined) {
36
+ definedOptions.rollbackable = options.rollbackable;
37
+ }
38
+ if (options.shared !== undefined) {
39
+ definedOptions.shared = options.shared;
40
+ }
41
+ if (options.sharedDelivery !== undefined) {
42
+ definedOptions.sharedDelivery = options.sharedDelivery;
43
+ }
44
+ if (Object.keys(definedOptions).length === 0)
45
+ return;
46
+ return definedOptions;
47
+ };
48
+ const toSharedChannelPayload = (payload, options) => {
49
+ const { options: originalPayloadOptions, ...payloadWithoutUnsetOptions } = payload;
50
+ const existingPayloadOptions = toDefinedMutationOptions(originalPayloadOptions);
51
+ const normalizedPayload = existingPayloadOptions
52
+ ? { ...payloadWithoutUnsetOptions, options: existingPayloadOptions }
53
+ : payloadWithoutUnsetOptions;
54
+ if (!options) {
55
+ return normalizedPayload;
56
+ }
57
+ const payloadOptions = {};
58
+ if (options.undoable !== undefined) {
59
+ payloadOptions.undoable = options.undoable;
60
+ }
61
+ if (options.rollbackable !== undefined) {
62
+ payloadOptions.rollbackable = options.rollbackable;
63
+ }
64
+ if (options.sharedDelivery !== undefined) {
65
+ payloadOptions.sharedDelivery = options.sharedDelivery;
66
+ }
67
+ const hasPayloadOptions = Object.keys(payloadOptions).length > 0;
68
+ if (!hasPayloadOptions) {
69
+ return normalizedPayload;
70
+ }
71
+ return {
72
+ ...normalizedPayload,
73
+ options: {
74
+ ...(existingPayloadOptions ?? {}),
75
+ ...payloadOptions
76
+ }
77
+ };
78
+ };
79
+ const freezeTrustedTransactionPayload = (payload) => {
80
+ if (payload.options) {
81
+ freezeTrustedValue(payload.options);
82
+ }
83
+ return freezeTrustedValue(payload);
9
84
  };
85
+ const freezeSharedChannelPayload = (payload, options, trustedOwnerValues) => {
86
+ const sharedPayload = toSharedChannelPayload(payload, options);
87
+ return trustedOwnerValues
88
+ ? freezeTrustedTransactionPayload(sharedPayload)
89
+ : deepFreezeValue(sharedPayload);
90
+ };
91
+ const freezeReplayEvents = (events, trustedOwnerValues) => {
92
+ if (!trustedOwnerValues) {
93
+ return deepFreezeValue(events);
94
+ }
95
+ events.forEach((event) => {
96
+ const payload = event.payload;
97
+ if (payload && typeof payload === 'object') {
98
+ ;
99
+ ['changes', 'moves'].forEach((key) => {
100
+ if (!(key in payload))
101
+ return;
102
+ const values = payload[key];
103
+ if (!Array.isArray(values))
104
+ return;
105
+ values.forEach((value) => {
106
+ if (value && typeof value === 'object') {
107
+ freezeTrustedValue(value);
108
+ }
109
+ });
110
+ freezeTrustedValue(values);
111
+ });
112
+ const options = payload.options;
113
+ if (options && typeof options === 'object') {
114
+ freezeTrustedValue(options);
115
+ }
116
+ freezeTrustedValue(payload);
117
+ }
118
+ freezeTrustedValue(event);
119
+ });
120
+ return freezeTrustedValue(events);
121
+ };
122
+ const cloneEvent = (event) => cloneValue(event);
123
+ const isReplayEvent = (value) => typeof value === 'object' &&
124
+ value !== null &&
125
+ typeof value.type === 'string';
126
+ const isPlainRecord = (value) => {
127
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
128
+ return false;
129
+ }
130
+ const prototype = Object.getPrototypeOf(value);
131
+ return prototype === Object.prototype || prototype === null;
132
+ };
133
+ const areHistoryValuesEqual = (left, right) => {
134
+ if (Object.is(left, right))
135
+ return true;
136
+ if (Array.isArray(left) || Array.isArray(right)) {
137
+ return (Array.isArray(left) &&
138
+ Array.isArray(right) &&
139
+ left.length === right.length &&
140
+ left.every((value, index) => areHistoryValuesEqual(value, right[index])));
141
+ }
142
+ if (!isPlainRecord(left) || !isPlainRecord(right))
143
+ return false;
144
+ const leftRecord = left;
145
+ const rightRecord = right;
146
+ const leftKeys = Reflect.ownKeys(leftRecord);
147
+ const rightKeys = Reflect.ownKeys(rightRecord);
148
+ return (leftKeys.length === rightKeys.length &&
149
+ leftKeys.every((key) => Object.prototype.hasOwnProperty.call(rightRecord, key) &&
150
+ areHistoryValuesEqual(Reflect.get(leftRecord, key), Reflect.get(rightRecord, key))));
151
+ };
152
+ const toReplayFailure = (cause) => ({
153
+ kind: 'explicit',
154
+ message: cause instanceof Error ? cause.message : undefined,
155
+ cause
156
+ });
10
157
  class DataTransact {
11
- constructor() {
12
- this.changes = [];
158
+ constructor(sharedDataChannelRegistry, callbacks) {
159
+ this.journal = [];
160
+ this.replaceLatestHistoryStages = new Map();
161
+ this.preparedActionHistoryEntries = null;
13
162
  this.undoStack = [];
14
163
  this.redoStack = [];
15
164
  this.isTransacting = 0;
16
165
  this.inUndo = false;
17
166
  this.inRedo = false;
167
+ this.applyingReplayEvent = false;
168
+ this.restoringNestedReplay = false;
169
+ this.nestedReplaySourceEvents = null;
170
+ this.nestedReplaySourceHistory = null;
171
+ this.nestedReplayRestorationBatches = [];
172
+ this.actionId = 0;
173
+ this.transactionId = 0;
174
+ this.currentTransactionId = 0;
175
+ this.currentArtifactId = '';
176
+ this.activeOrigin = 'action';
177
+ this.rollbackOnly = false;
178
+ this.transactionSettlementDepth = 0;
179
+ this.pendingSharedPublications = [];
180
+ this.publicationAcknowledgements = new Map();
181
+ this.unacknowledgedSharedPublications = [];
182
+ this.emittingSharedPublications = false;
183
+ this.pendingImmediatePublicationEntries = [];
184
+ this.pendingImmediatePublicationRecords = [];
185
+ this.pendingImmediatePublicationWorkItemKeys = new Set();
186
+ this.immediatePublicationToken = 0;
187
+ this.scheduledImmediatePublicationToken = null;
188
+ this.publicationSequence = 0;
189
+ this.deliveryBatchSequence = 0;
190
+ this.currentSharedDeliveryBatches = [];
191
+ this.preparedSharedBatchRecords = new Map();
192
+ this.transactionEndDeliveryBatches = null;
193
+ this.transactionEndBatchesBySlice = new Map();
194
+ this.transactionEndRecordsBySlice = new Map();
195
+ this.pendingProgressivePublicationRecords = [];
196
+ this.pendingProgressivePublicationWorkItemKeys = new Set();
197
+ this.pendingHistoryReplayPublicationBatches = [];
198
+ this.pendingHistoryReplayPublicationWorkItemKeys = new Set();
199
+ this.retainingHistoryReplaySharedEvidence = false;
200
+ this.activeDeliverySliceByOrderedId = new Map();
201
+ this.activeDeliverySliceOrder = new Map();
202
+ this.activeDeliveryBoundaryBySliceId = new Map();
203
+ this.activeDeliveryOrderedIdOrder = new Map();
204
+ this.activeDeliverySequenceValidated = false;
205
+ this.nextDeliverySliceIndex = 0;
206
+ this.pendingTransactionStatuses = [];
207
+ this.emittingTransactionStatuses = false;
208
+ this.sharedEvidenceNotificationDepth = 0;
209
+ this.inverters = new Map();
210
+ this.validators = new Map();
211
+ this.sharedDataChannelRegistry =
212
+ sharedDataChannelRegistry ?? new SharedDataChannelRegistry();
213
+ this.onCommitCapture = callbacks?.onCommitCapture;
214
+ this.onStatus = callbacks?.onStatus;
215
+ this.onUserActionCompleted = callbacks
216
+ ? callbacks.onUserActionCompleted
217
+ : userActionCompleted;
218
+ this.onReplayEvent = callbacks?.onReplayEvent;
219
+ this.canReplayEventBatch = callbacks?.canReplayEventBatch;
220
+ this.onSharedDeliveryBatch = callbacks?.onSharedDeliveryBatch;
221
+ this.onSharedPublication = callbacks?.onSharedPublication;
18
222
  }
19
- start() {
223
+ start(origin) {
224
+ if (this.sharedEvidenceNotificationDepth > 0) {
225
+ throw new Error('Factory shared evidence observers cannot start a canonical transaction');
226
+ }
227
+ if (this.isTransacting > 0 &&
228
+ origin !== undefined &&
229
+ origin !== this.activeOrigin) {
230
+ throw new Error(`Nested transaction origin ${origin} cannot join ${this.activeOrigin}`);
231
+ }
20
232
  this.isTransacting++;
21
233
  if (this.isTransacting > 1) {
22
234
  return;
23
235
  }
24
- this.changes = [];
236
+ this.activeOrigin = origin ?? 'action';
237
+ this.journal = [];
238
+ this.replaceLatestHistoryStages.clear();
239
+ this.preparedActionHistoryEntries = null;
240
+ this.pendingImmediatePublicationEntries.length = 0;
241
+ this.pendingImmediatePublicationRecords.length = 0;
242
+ this.pendingImmediatePublicationWorkItemKeys.clear();
243
+ this.immediatePublicationToken += 1;
244
+ this.scheduledImmediatePublicationToken = null;
245
+ this.publicationSequence = 0;
246
+ this.deliveryBatchSequence = 0;
247
+ this.currentSharedDeliveryBatches = [];
248
+ this.preparedSharedBatchRecords.clear();
249
+ this.transactionEndDeliveryBatches = null;
250
+ this.transactionEndBatchesBySlice.clear();
251
+ this.transactionEndRecordsBySlice.clear();
252
+ this.pendingProgressivePublicationRecords.length = 0;
253
+ this.pendingProgressivePublicationWorkItemKeys.clear();
254
+ this.pendingHistoryReplayPublicationBatches.length = 0;
255
+ this.pendingHistoryReplayPublicationWorkItemKeys.clear();
256
+ this.historyReplaySharedState = undefined;
257
+ this.retainingHistoryReplaySharedEvidence = false;
258
+ this.activeDeliverySequence = undefined;
259
+ this.activeDeliverySliceByOrderedId.clear();
260
+ this.activeDeliverySliceOrder.clear();
261
+ this.activeDeliveryBoundaryBySliceId.clear();
262
+ this.activeDeliveryOrderedIdOrder.clear();
263
+ this.activeDeliverySequenceValidated = false;
264
+ this.nextDeliverySliceIndex = 0;
265
+ this.nestedReplayRestorationBatches = [];
266
+ this.rollbackOnly = false;
267
+ this.rollbackFailure = undefined;
268
+ this.transactionId += 1;
269
+ this.currentTransactionId = this.transactionId;
270
+ this.currentArtifactId = `${this.currentTransactionId}:artifact`;
271
+ const transactionId = this.currentTransactionId;
272
+ const artifactId = this.currentArtifactId;
273
+ const handleToken = Symbol(artifactId);
274
+ this.activeDeliveryHandleToken = handleToken;
275
+ const assertControllerActive = () => {
276
+ if (this.isTransacting <= 0 ||
277
+ this.activeDeliveryHandleToken !== handleToken ||
278
+ this.currentTransactionId !== transactionId ||
279
+ this.currentArtifactId !== artifactId) {
280
+ throw new Error('Factory staged delivery controller is no longer active');
281
+ }
282
+ this.assertSharedEvidenceCanonicalControlAllowed();
283
+ };
284
+ const setDeliverySequence = (sequence) => {
285
+ assertControllerActive();
286
+ if (this.activeDeliverySequence) {
287
+ throw new Error('Factory mutation batch delivery sequence is already configured');
288
+ }
289
+ try {
290
+ this.configureActiveDeliverySequence(sequence);
291
+ }
292
+ catch (error) {
293
+ this.rollbackOnly = true;
294
+ this.rollbackFailure ?? (this.rollbackFailure = toReplayFailure(error));
295
+ throw error;
296
+ }
297
+ };
298
+ const stageSlice = (sliceId) => {
299
+ assertControllerActive();
300
+ this.deliverActiveSlice(sliceId);
301
+ };
302
+ this.activeStagedDeliveryController = Object.freeze({
303
+ artifactId,
304
+ transactionId,
305
+ setDeliverySequence,
306
+ stageSlice
307
+ });
308
+ this.activeDeliveryHandle = Object.freeze({
309
+ artifactId,
310
+ transactionId,
311
+ setDeliverySequence,
312
+ deliverSlice: stageSlice
313
+ });
314
+ }
315
+ getActiveStagedDeliveryController() {
316
+ return this.activeStagedDeliveryController ?? null;
317
+ }
318
+ assertSharedEvidenceCanonicalControlAllowed() {
319
+ if (this.sharedEvidenceNotificationDepth > 0) {
320
+ throw new Error('Factory shared evidence observers cannot mutate canonical transaction controls');
321
+ }
322
+ }
323
+ registerInverter(eventName, inverter) {
324
+ if (this.inverters.has(eventName)) {
325
+ throw new Error(`Transaction inverter is already registered for ${eventName}`);
326
+ }
327
+ this.inverters.set(eventName, inverter);
328
+ }
329
+ registerValidator(name, validator) {
330
+ if (this.validators.has(name)) {
331
+ throw new Error(`Transaction validator is already registered: ${name}`);
332
+ }
333
+ this.validators.set(name, validator);
334
+ }
335
+ hasInverseContract(eventName, payload) {
336
+ if (this.inverters.has(eventName)) {
337
+ return true;
338
+ }
339
+ if (!BUILT_IN_INVERTIBLE_EVENT_TYPES.has(eventName)) {
340
+ return false;
341
+ }
342
+ if (!payload || typeof payload !== 'object') {
343
+ return false;
344
+ }
345
+ return ('undoType' in payload ||
346
+ 'undoAction' in payload ||
347
+ 'after' in payload ||
348
+ 'patch' in payload ||
349
+ ('moves' in payload && Array.isArray(payload.moves)) ||
350
+ ('changes' in payload && Array.isArray(payload.changes)));
25
351
  }
26
352
  update(event) {
27
- if (this.isTransacting <= 0) {
353
+ return this.updateBatch([event]);
354
+ }
355
+ updateBatch(events) {
356
+ this.assertSharedEvidenceCanonicalControlAllowed();
357
+ if (this.isTransacting <= 0 || this.restoringNestedReplay) {
358
+ return null;
359
+ }
360
+ const deliveryHandle = this.activeDeliveryHandle ?? null;
361
+ const journalStart = this.journal.length;
362
+ const trustedOwnerValues = isDetachedTransactionValue(events);
363
+ let batchAccepted = false;
364
+ try {
365
+ const ownerHandoff = measureBrowserDragPhase('factory:owner-batch-clone', () => isDeeplyFrozenValue(events)
366
+ ? events
367
+ : cloneAndDeepFreezeValue([...events]));
368
+ const detachedEvents = ownerHandoff;
369
+ const localComputedEvent = detachedEvents.find((event) => LOCAL_ONLY_COMPUTED_EVENT_TYPES.has(event.eventName));
370
+ if (localComputedEvent) {
371
+ throw new Error(`Factory canonical mutation batch cannot contain local-only computed event: ${localComputedEvent.eventName}`);
372
+ }
373
+ if (this.transactionEndDeliveryBatches !== null &&
374
+ detachedEvents.some((event) => event.options?.shared !== undefined &&
375
+ (event.options.sharedDelivery ?? 'transaction-end') ===
376
+ 'transaction-end')) {
377
+ throw new Error('Factory mutation batch cannot change after progressive delivery preparation');
378
+ }
379
+ if (!(this.applyingReplayEvent && this.retainingHistoryReplaySharedEvidence) &&
380
+ this.activeDeliverySequence?.mode === 'progressive' &&
381
+ this.nextDeliverySliceIndex <
382
+ this.activeDeliverySequence.slices.length &&
383
+ detachedEvents.some((event) => event.options?.shared !== undefined &&
384
+ event.options.sharedDelivery === 'immediate')) {
385
+ throw new Error('Factory mutation immediate delivery requires every progressive slice to be delivered first');
386
+ }
387
+ const recordedEntries = detachedEvents.map((event) => this.recordJournalEntry(event, trustedOwnerValues));
388
+ this.stageReplaceLatestHistory(detachedEvents, recordedEntries.map(({ index }) => index));
389
+ batchAccepted = true;
390
+ if (this.nestedReplaySourceEvents &&
391
+ recordedEntries.some((entry) => entry.source === 'action')) {
392
+ throw new Error('Nested undo or redo cannot accept a new action mutation');
393
+ }
394
+ const immediateEntries = this.applyingReplayEvent && this.retainingHistoryReplaySharedEvidence
395
+ ? []
396
+ : recordedEntries.filter((entry) => entry.shared && entry.options.sharedDelivery === 'immediate');
397
+ this.deliverSharedEntries(immediateEntries, immediateEntries.length > 0
398
+ ? `${this.currentArtifactId}:owner-batch:${journalStart}`
399
+ : undefined);
400
+ this.queueImmediatePublicationEntries(immediateEntries.filter((entry) => entry.shared?.records.some((record) => record.delivered)));
401
+ return recordedEntries.length > 0 ? deliveryHandle : null;
402
+ }
403
+ catch (error) {
404
+ if (!batchAccepted) {
405
+ this.journal.splice(journalStart);
406
+ }
407
+ this.rollbackOnly = true;
408
+ this.rollbackFailure ?? (this.rollbackFailure = toReplayFailure(error));
409
+ throw new FactoryMutationBatchAcceptanceError(batchAccepted, error);
410
+ }
411
+ }
412
+ stageReplaceLatestHistory(events, journalIndexes) {
413
+ const firstEvent = events[0];
414
+ if (!firstEvent)
415
+ return;
416
+ const history = firstEvent.options?.history;
417
+ const candidate = firstEvent.historyCandidate;
418
+ if (!history && !candidate)
28
419
  return;
420
+ if (history?.mode !== 'replace-latest' || !candidate)
421
+ return;
422
+ let stage = this.replaceLatestHistoryStages.get(history.key);
423
+ if (!stage) {
424
+ stage = {
425
+ eventOrder: [],
426
+ firstEventsByKey: new Map(),
427
+ latestEventsByKey: new Map(),
428
+ journalIndexes: new Set()
429
+ };
430
+ this.replaceLatestHistoryStages.set(history.key, stage);
431
+ }
432
+ journalIndexes.forEach((index) => stage.journalIndexes.add(index));
433
+ const eventKeys = candidate.eventKeys ?? candidate.events.map((_event, index) => `${index}`);
434
+ candidate.events.forEach((event, index) => {
435
+ const eventKey = eventKeys[index];
436
+ if (!stage.firstEventsByKey.has(eventKey)) {
437
+ stage.eventOrder.push(eventKey);
438
+ stage.firstEventsByKey.set(eventKey, event);
439
+ }
440
+ stage.latestEventsByKey.set(eventKey, event);
441
+ });
442
+ }
443
+ validateEventDeliveryEvidence(evidence, eventIndex, trustedOwnerValues) {
444
+ if (trustedOwnerValues) {
445
+ adoptDeeplyFrozenValue(evidence);
446
+ adoptDeeplyFrozenValue(evidence.orderedIds);
447
+ if (evidence.sharedRecords) {
448
+ adoptDeeplyFrozenValue(evidence.sharedRecords);
449
+ }
450
+ }
451
+ if (evidence.orderedIds.length === 0) {
452
+ throw new Error(`Factory mutation delivery evidence ${eventIndex} requires at least one canonical ordered id`);
453
+ }
454
+ const canonicalIds = new Set();
455
+ evidence.orderedIds.forEach((orderedId) => {
456
+ if (!orderedId) {
457
+ throw new Error(`Factory mutation delivery evidence ${eventIndex} has an empty canonical ordered id`);
458
+ }
459
+ if (canonicalIds.has(orderedId)) {
460
+ throw new Error(`Factory mutation delivery evidence ${eventIndex} has a duplicate canonical ordered id: ${orderedId}`);
461
+ }
462
+ canonicalIds.add(orderedId);
463
+ });
464
+ if (evidence.sharedRecords !== undefined &&
465
+ evidence.sharedRecords.length === 0) {
466
+ throw new Error(`Factory mutation delivery evidence ${eventIndex} requires at least one shared record`);
29
467
  }
468
+ if (!evidence.sharedRecords)
469
+ return;
470
+ const firstOccurrences = [];
471
+ const seenOccurrences = new Set();
472
+ evidence.sharedRecords.forEach((record, recordIndex) => {
473
+ if (trustedOwnerValues) {
474
+ adoptDeeplyFrozenValue(record);
475
+ adoptDeeplyFrozenValue(record.orderedIds);
476
+ adoptDeeplyFrozenValue(record.payload);
477
+ }
478
+ if (record.orderedIds.length === 0) {
479
+ throw new Error(`Factory mutation shared record ${eventIndex}:${recordIndex} requires at least one ordered id`);
480
+ }
481
+ const recordIds = new Set();
482
+ record.orderedIds.forEach((orderedId) => {
483
+ if (!orderedId || !canonicalIds.has(orderedId)) {
484
+ throw new Error(`Factory mutation shared record ${eventIndex}:${recordIndex} contains an unknown canonical ordered id: ${orderedId}`);
485
+ }
486
+ if (recordIds.has(orderedId)) {
487
+ throw new Error(`Factory mutation shared record ${eventIndex}:${recordIndex} has a duplicate ordered id: ${orderedId}`);
488
+ }
489
+ recordIds.add(orderedId);
490
+ if (!seenOccurrences.has(orderedId)) {
491
+ seenOccurrences.add(orderedId);
492
+ firstOccurrences.push(orderedId);
493
+ }
494
+ });
495
+ if (!isPlainRecord(record.payload)) {
496
+ throw new Error(`Factory mutation shared record ${eventIndex}:${recordIndex} requires a plain record payload`);
497
+ }
498
+ });
499
+ if (seenOccurrences.size !== canonicalIds.size) {
500
+ throw new Error(`Factory mutation shared records ${eventIndex} must cover every canonical ordered id`);
501
+ }
502
+ if (firstOccurrences.some((orderedId, index) => evidence.orderedIds[index] !== orderedId)) {
503
+ throw new Error(`Factory mutation shared records ${eventIndex} must preserve canonical ordered id order`);
504
+ }
505
+ }
506
+ recordJournalEntry(event, trustedOwnerValues) {
507
+ const journalEntry = this.createJournalEntry(event, trustedOwnerValues, this.journal.length, this.applyingReplayEvent ? 'replay' : 'action');
508
+ this.journal.push(journalEntry);
509
+ return journalEntry;
510
+ }
511
+ createJournalEntry(event, trustedOwnerValues, entryIndex, source) {
512
+ const deliveryEvidence = event.canonicalEvidence;
513
+ const newPayload = event.payload;
30
514
  const newType = event.eventName;
31
- const newPayload = JSON.parse(JSON.stringify(event.payload));
32
- const newEvent = {
515
+ if (trustedOwnerValues) {
516
+ adoptDeeplyFrozenValue(newPayload);
517
+ }
518
+ if (deliveryEvidence) {
519
+ this.validateEventDeliveryEvidence(deliveryEvidence, entryIndex, trustedOwnerValues);
520
+ if (deliveryEvidence.sharedRecords && !event.options?.shared) {
521
+ throw new Error(`Factory mutation shared record evidence ${entryIndex} requires a shared canonical event`);
522
+ }
523
+ }
524
+ const newEvent = deepFreezeValue({
33
525
  type: newType,
34
526
  payload: newPayload
527
+ });
528
+ const origin = this.transactionOrigin();
529
+ const isReplayOrigin = origin === 'undo' || origin === 'redo';
530
+ const options = {
531
+ undoable: origin === 'remote' || isReplayOrigin
532
+ ? false
533
+ : event.options?.undoable !== false,
534
+ rollbackable: origin === 'remote' ? true : event.options?.rollbackable !== false,
535
+ shared: event.options?.shared,
536
+ sharedDelivery: event.options?.sharedDelivery ?? 'transaction-end',
537
+ history: event.options?.history
538
+ };
539
+ if ((options.rollbackable || options.undoable) &&
540
+ !this.hasInverseContract(event.eventName, newPayload)) {
541
+ throw new Error(`Reversible transaction event ${event.eventName} requires an inverter`);
542
+ }
543
+ const journalEntry = {
544
+ index: entryIndex,
545
+ event: newEvent,
546
+ orderedIds: deliveryEvidence?.orderedIds ?? deepFreezeValue([]),
547
+ options,
548
+ source,
549
+ trustedOwnerValues
35
550
  };
36
- if (!(event.options && !event.options.undoable)) {
37
- this.changes.push(newEvent);
551
+ const sharedChannelName = event.options?.shared;
552
+ if (sharedChannelName) {
553
+ const sharedOptions = origin === 'remote'
554
+ ? { ...event.options, undoable: false, rollbackable: true }
555
+ : event.options;
556
+ const sharedChange = measureBrowserDragPhase('factory:shared-payload-normalize', () => freezeSharedChannelPayload(newPayload, sharedOptions, trustedOwnerValues));
557
+ const recordInputs = deliveryEvidence?.sharedRecords ?? [
558
+ {
559
+ orderedIds: deliveryEvidence?.orderedIds ?? [],
560
+ payload: newPayload
561
+ }
562
+ ];
563
+ journalEntry.shared = {
564
+ name: sharedChannelName,
565
+ change: sharedChange,
566
+ orderedIds: deliveryEvidence?.orderedIds ?? [],
567
+ recordInversesPrepared: false,
568
+ records: recordInputs.map((record, occurrence) => ({
569
+ occurrence,
570
+ orderedIds: record.orderedIds,
571
+ change: record.payload === newPayload
572
+ ? sharedChange
573
+ : freezeSharedChannelPayload(record.payload, sharedOptions, trustedOwnerValues),
574
+ delivered: false
575
+ }))
576
+ };
577
+ }
578
+ this.prepareEntryInverses(journalEntry);
579
+ return journalEntry;
580
+ }
581
+ mergeReplaceLatestHistoryPayload(firstPayload, latestPayload) {
582
+ const firstRecord = firstPayload;
583
+ const latestRecord = latestPayload;
584
+ const before = firstRecord.before;
585
+ const after = latestRecord.after;
586
+ if (areHistoryValuesEqual(before, after)) {
587
+ return null;
588
+ }
589
+ return {
590
+ ...latestRecord,
591
+ before,
592
+ after
593
+ };
594
+ }
595
+ materializeReplaceLatestHistoryStage(stage, firstSyntheticIndex) {
596
+ const entries = [];
597
+ stage.eventOrder.forEach((eventKey) => {
598
+ const firstEvent = stage.firstEventsByKey.get(eventKey);
599
+ const latestEvent = stage.latestEventsByKey.get(eventKey);
600
+ const payload = this.mergeReplaceLatestHistoryPayload(firstEvent.payload, latestEvent.payload);
601
+ if (!payload)
602
+ return;
603
+ const { history: _history, ...options } = latestEvent.options ?? {};
604
+ entries.push(this.createJournalEntry({
605
+ type: latestEvent.type,
606
+ eventName: latestEvent.eventName,
607
+ payload,
608
+ options,
609
+ canonicalEvidence: latestEvent.canonicalEvidence
610
+ }, false, firstSyntheticIndex + entries.length, 'action'));
611
+ });
612
+ return entries;
613
+ }
614
+ prepareReplaceLatestHistorySourceBatches(entries) {
615
+ const sharedEntries = entries.filter((entry) => entry.shared);
616
+ if (sharedEntries.length === 0)
617
+ return;
618
+ const unsupportedEntry = sharedEntries.find((entry) => entry.options.sharedDelivery !== 'immediate');
619
+ if (unsupportedEntry) {
620
+ throw new Error('Factory replace-latest shared History requires immediate delivery');
621
+ }
622
+ const currentBatchCount = this.currentSharedDeliveryBatches.length;
623
+ const batches = this.prepareSharedDeliveryBatches(sharedEntries);
624
+ this.currentSharedDeliveryBatches.splice(currentBatchCount);
625
+ batches.forEach((batch) => this.preparedSharedBatchRecords.delete(batch.batchId));
626
+ this.sharedRecordRefs(sharedEntries).forEach(({ record }) => {
627
+ record.delivered = true;
628
+ });
629
+ }
630
+ prepareCommittedActionHistoryEntries() {
631
+ if (this.replaceLatestHistoryStages.size === 0) {
632
+ return this.journal;
633
+ }
634
+ const entries = [];
635
+ const emittedKeys = new Set();
636
+ const syntheticEntries = [];
637
+ let nextSyntheticIndex = this.journal.length;
638
+ this.journal.forEach((entry) => {
639
+ const history = entry.options.history;
640
+ if (history?.mode !== 'replace-latest') {
641
+ entries.push(entry);
642
+ return;
643
+ }
644
+ const stage = this.replaceLatestHistoryStages.get(history.key);
645
+ if (!stage || !stage.journalIndexes.has(entry.index)) {
646
+ entries.push(entry);
647
+ return;
648
+ }
649
+ if (emittedKeys.has(history.key))
650
+ return;
651
+ emittedKeys.add(history.key);
652
+ const materialized = this.materializeReplaceLatestHistoryStage(stage, nextSyntheticIndex);
653
+ nextSyntheticIndex += materialized.length;
654
+ entries.push(...materialized);
655
+ syntheticEntries.push(...materialized);
656
+ });
657
+ this.prepareReplaceLatestHistorySourceBatches(syntheticEntries);
658
+ return entries;
659
+ }
660
+ prepareEntryInverses(entry) {
661
+ const trustedBuiltInReplayValues = entry.trustedOwnerValues && !this.inverters.has(entry.event.type);
662
+ if (!entry.inverseEvents) {
663
+ entry.inverseEvents = freezeReplayEvents(entry.options.rollbackable || entry.options.undoable
664
+ ? this.createReplayEvents(entry.event, 'inverse', 'factory-owned-journal')
665
+ : [], trustedBuiltInReplayValues);
666
+ }
667
+ if (entry.shared && !entry.shared.inverseEvents) {
668
+ const sharedPayloadOptions = toDefinedMutationOptions(entry.shared.change.options);
669
+ const sharedInverseEvents = entry.options.rollbackable || entry.options.undoable
670
+ ? (entry.inverseEvents ?? []).map((inverseEvent) => {
671
+ const inversePayload = inverseEvent.payload;
672
+ const { options: _canonicalOptions, ...payloadWithoutOptions } = inversePayload;
673
+ const payload = {
674
+ ...payloadWithoutOptions,
675
+ ...(sharedPayloadOptions
676
+ ? { options: sharedPayloadOptions }
677
+ : {})
678
+ };
679
+ return {
680
+ type: inverseEvent.type,
681
+ payload: entry.trustedOwnerValues
682
+ ? freezeTrustedTransactionPayload(payload)
683
+ : deepFreezeValue(payload)
684
+ };
685
+ })
686
+ : [];
687
+ entry.shared.inverseEvents = freezeReplayEvents(sharedInverseEvents, entry.trustedOwnerValues);
688
+ }
689
+ if (entry.shared && !entry.shared.recordInversesPrepared) {
690
+ let inverseCountMismatch;
691
+ measureBrowserDragPhase('factory:prepare-shared-record-inverses', () => {
692
+ entry.shared?.records.forEach((record) => {
693
+ if (!record.inverseEvents) {
694
+ const recordInverseEvents = record.change === entry.shared?.change
695
+ ? entry.shared.inverseEvents
696
+ : this.projectFrameworkRecordInverseEvents(entry, record);
697
+ if (recordInverseEvents) {
698
+ record.inverseEvents = recordInverseEvents;
699
+ }
700
+ else {
701
+ const recordEvent = (trustedBuiltInReplayValues
702
+ ? freezeTrustedValue
703
+ : deepFreezeValue)({
704
+ type: entry.event.type,
705
+ payload: record.change
706
+ });
707
+ record.inverseEvents = freezeReplayEvents(entry.options.rollbackable || entry.options.undoable
708
+ ? this.createReplayEvents(recordEvent, 'inverse', 'factory-owned-journal')
709
+ : [], trustedBuiltInReplayValues);
710
+ }
711
+ }
712
+ if (!inverseCountMismatch &&
713
+ record.inverseEvents.length !== (entry.inverseEvents ?? []).length) {
714
+ inverseCountMismatch = {
715
+ recordId: this.sharedRecordId(entry, record),
716
+ canonicalCount: (entry.inverseEvents ?? []).length,
717
+ recordCount: record.inverseEvents.length
718
+ };
719
+ }
720
+ if (!record.evidence) {
721
+ record.evidence = deepFreezeValue({
722
+ recordId: this.sharedRecordId(entry, record),
723
+ deliveryId: this.forwardDeliveryId(entry, record),
724
+ occurrence: record.occurrence,
725
+ orderedIds: record.orderedIds,
726
+ payload: record.change,
727
+ inverseEvents: record.inverseEvents
728
+ });
729
+ }
730
+ });
731
+ });
732
+ entry.shared.recordInversesPrepared = true;
733
+ if (inverseCountMismatch) {
734
+ throw new Error(`Factory mutation shared record inverse output count must match canonical inverse output count: ${inverseCountMismatch.recordId} (${inverseCountMismatch.recordCount} !== ${inverseCountMismatch.canonicalCount})`);
735
+ }
736
+ }
737
+ }
738
+ projectFrameworkRecordInverseEvents(entry, record) {
739
+ if (this.inverters.has(entry.event.type) ||
740
+ (!entry.options.rollbackable && !entry.options.undoable)) {
741
+ return;
742
+ }
743
+ const sharedInverseEvents = entry.shared?.inverseEvents;
744
+ if (sharedInverseEvents?.length !== 1)
745
+ return;
746
+ const inverseEvent = sharedInverseEvents[0];
747
+ if (!inverseEvent)
748
+ return;
749
+ const inversePayload = inverseEvent.payload;
750
+ const recordPayload = record.change;
751
+ let projectedCollection;
752
+ if (Array.isArray(inversePayload.entries) &&
753
+ Array.isArray(recordPayload.entries)) {
754
+ projectedCollection = { key: 'entries', value: recordPayload.entries };
755
+ }
756
+ else if (Array.isArray(inversePayload.data) &&
757
+ Array.isArray(recordPayload.data)) {
758
+ projectedCollection = { key: 'data', value: recordPayload.data };
759
+ }
760
+ else if (Array.isArray(inversePayload.changes) &&
761
+ Array.isArray(recordPayload.changes)) {
762
+ projectedCollection = {
763
+ key: 'changes',
764
+ value: [...recordPayload.changes].reverse().map((change) => {
765
+ if (!isPlainRecord(change) ||
766
+ !('before' in change) ||
767
+ !('after' in change)) {
768
+ throw new Error(`Transaction event ${entry.event.type} has an invalid record change`);
769
+ }
770
+ return {
771
+ ...change,
772
+ before: change.after,
773
+ after: change.before
774
+ };
775
+ })
776
+ };
38
777
  }
39
- const map = ChangesMaps[event.payload.owner];
40
- if (map instanceof Y.Array) {
41
- map.push([event.payload]);
778
+ else if (Array.isArray(inversePayload.moves) &&
779
+ Array.isArray(recordPayload.moves)) {
780
+ projectedCollection = {
781
+ key: 'moves',
782
+ value: recordPayload.moves.map((move) => {
783
+ if (!isPlainRecord(move) ||
784
+ !('before' in move) ||
785
+ !('after' in move)) {
786
+ throw new Error(`Transaction event ${entry.event.type} has an invalid record move`);
787
+ }
788
+ return {
789
+ ...move,
790
+ before: move.after,
791
+ after: move.before
792
+ };
793
+ })
794
+ };
42
795
  }
796
+ if (!projectedCollection)
797
+ return;
798
+ return freezeReplayEvents([
799
+ {
800
+ ...inverseEvent,
801
+ payload: {
802
+ ...inversePayload,
803
+ [projectedCollection.key]: projectedCollection.value
804
+ }
805
+ }
806
+ ], entry.trustedOwnerValues);
807
+ }
808
+ sharedRecordId(entry, record) {
809
+ return `${this.currentTransactionId}:${entry.index}:record:${record.occurrence}`;
810
+ }
811
+ forwardDeliveryId(entry, record) {
812
+ return record.occurrence === 0
813
+ ? `${this.currentTransactionId}:${entry.index}:forward`
814
+ : `${this.currentTransactionId}:${entry.index}:record:${record.occurrence}:forward`;
815
+ }
816
+ compensationDeliveryId(entry, record, compensationIndex) {
817
+ const deliveryPrefix = record.occurrence === 0
818
+ ? `${this.currentTransactionId}:${entry.index}`
819
+ : `${this.currentTransactionId}:${entry.index}:record:${record.occurrence}`;
820
+ return `${deliveryPrefix}:compensation:${compensationIndex}`;
821
+ }
822
+ nextDeliveryBatchId() {
823
+ this.deliveryBatchSequence += 1;
824
+ return `${this.currentArtifactId}:batch:${this.deliveryBatchSequence}`;
825
+ }
826
+ createForwardSharedDelivery({ entry, record }, batchId) {
827
+ const shared = entry.shared;
828
+ if (!shared)
829
+ return;
830
+ const evidence = record.evidence;
831
+ if (!evidence)
832
+ return;
833
+ return deepFreezeValue({
834
+ deliveryId: evidence.deliveryId,
835
+ artifactId: this.currentArtifactId,
836
+ batchId,
837
+ transactionId: this.currentTransactionId,
838
+ origin: this.transactionOrigin(),
839
+ kind: 'forward',
840
+ channel: shared.name,
841
+ eventName: entry.event.type,
842
+ payload: record.change,
843
+ recordId: evidence.recordId,
844
+ record: evidence,
845
+ sharedDelivery: entry.options.sharedDelivery,
846
+ compensationDeliveryIds: deepFreezeValue(evidence.inverseEvents.map((_event, compensationIndex) => this.compensationDeliveryId(entry, record, compensationIndex)))
847
+ });
848
+ }
849
+ configureActiveDeliverySequence(sequence) {
850
+ if (this.currentSharedDeliveryBatches.some((batch) => batch.sharedDelivery !== 'immediate')) {
851
+ throw new Error('Factory mutation delivery sequence must be configured before shared delivery');
852
+ }
853
+ const detachedSequence = cloneAndDeepFreezeValue(sequence);
854
+ const sliceIds = new Set();
855
+ const orderedIds = new Set();
856
+ const sliceByOrderedId = new Map();
857
+ const sliceOrder = new Map();
858
+ const boundaryBySliceId = new Map();
859
+ const orderedIdOrder = new Map();
860
+ let orderedIdIndex = 0;
861
+ detachedSequence.slices.forEach((slice, sliceIndex) => {
862
+ if (!slice.sliceId || sliceIds.has(slice.sliceId)) {
863
+ throw new Error(`Factory mutation delivery sequence has an invalid slice at index ${sliceIndex}`);
864
+ }
865
+ sliceIds.add(slice.sliceId);
866
+ sliceOrder.set(slice.sliceId, sliceIndex);
867
+ boundaryBySliceId.set(slice.sliceId, slice);
868
+ slice.orderedIds.forEach((orderedId) => {
869
+ if (!orderedId || orderedIds.has(orderedId)) {
870
+ throw new Error(`Factory mutation delivery sequence has a duplicate ordered id: ${orderedId}`);
871
+ }
872
+ orderedIds.add(orderedId);
873
+ sliceByOrderedId.set(orderedId, slice.sliceId);
874
+ orderedIdOrder.set(orderedId, orderedIdIndex);
875
+ orderedIdIndex += 1;
876
+ });
877
+ });
878
+ if (detachedSequence.mode === 'progressive' &&
879
+ detachedSequence.slices.length === 0) {
880
+ throw new Error('Progressive Factory mutation delivery sequence requires at least one slice');
881
+ }
882
+ if (detachedSequence.mode === 'atomic' &&
883
+ detachedSequence.slices.length > 1) {
884
+ throw new Error('Atomic Factory mutation delivery sequence accepts at most one slice');
885
+ }
886
+ if (detachedSequence.batchPublications !== undefined &&
887
+ typeof detachedSequence.batchPublications !== 'boolean') {
888
+ throw new Error('Factory mutation delivery sequence batchPublications must be boolean');
889
+ }
890
+ const alreadyDeliveredImmediateOrderedId = this.currentSharedDeliveryBatches
891
+ .filter((batch) => batch.sharedDelivery === 'immediate')
892
+ .flatMap((batch) => batch.records)
893
+ .flatMap((record) => record.orderedIds)
894
+ .find((orderedId) => orderedIds.has(orderedId));
895
+ if (alreadyDeliveredImmediateOrderedId) {
896
+ throw new Error(`Factory mutation delivery sequence cannot include an already delivered immediate ordered id: ${alreadyDeliveredImmediateOrderedId}`);
897
+ }
898
+ this.activeDeliverySliceByOrderedId.clear();
899
+ sliceByOrderedId.forEach((sliceId, orderedId) => this.activeDeliverySliceByOrderedId.set(orderedId, sliceId));
900
+ this.activeDeliverySliceOrder.clear();
901
+ sliceOrder.forEach((sliceIndex, sliceId) => this.activeDeliverySliceOrder.set(sliceId, sliceIndex));
902
+ this.activeDeliveryBoundaryBySliceId.clear();
903
+ boundaryBySliceId.forEach((boundary, sliceId) => this.activeDeliveryBoundaryBySliceId.set(sliceId, boundary));
904
+ this.activeDeliveryOrderedIdOrder.clear();
905
+ orderedIdOrder.forEach((index, orderedId) => this.activeDeliveryOrderedIdOrder.set(orderedId, index));
906
+ this.activeDeliverySequence = detachedSequence;
907
+ this.activeDeliverySequenceValidated = false;
908
+ }
909
+ sharedRecordRefs(entries) {
910
+ return entries.flatMap((entry) => (entry.shared?.records ?? []).map((record) => ({ entry, record })));
911
+ }
912
+ validateActiveDeliverySequenceCoverage(entries) {
913
+ if (this.activeDeliverySequenceValidated ||
914
+ this.activeDeliverySequence?.mode !== 'progressive') {
915
+ return;
916
+ }
917
+ const seenAssignedOrderedIds = new Set();
918
+ entries.forEach((entry) => {
919
+ let previousOrderedIdIndex = -1;
920
+ entry.orderedIds.forEach((orderedId) => {
921
+ const orderedIdIndex = this.activeDeliveryOrderedIdOrder.get(orderedId);
922
+ if (orderedIdIndex === undefined) {
923
+ throw new Error(`Factory mutation ordered id is not assigned to a progressive delivery slice: ${orderedId}`);
924
+ }
925
+ if (orderedIdIndex <= previousOrderedIdIndex) {
926
+ throw new Error('Factory mutation delivery slices must preserve canonical order');
927
+ }
928
+ previousOrderedIdIndex = orderedIdIndex;
929
+ seenAssignedOrderedIds.add(orderedId);
930
+ });
931
+ });
932
+ if (seenAssignedOrderedIds.size !== this.activeDeliveryOrderedIdOrder.size) {
933
+ throw new Error('Factory mutation delivery sequence must cover every canonical id exactly once');
934
+ }
935
+ this.activeDeliverySequenceValidated = true;
936
+ }
937
+ orderSharedRecordsByActiveSlice(records) {
938
+ if (this.activeDeliverySequence?.mode !== 'progressive') {
939
+ return [...records];
940
+ }
941
+ const recordsBySlice = new Map();
942
+ this.activeDeliverySequence.slices.forEach(({ sliceId }) => recordsBySlice.set(sliceId, []));
943
+ records.forEach((recordRef) => {
944
+ const sliceId = this.deliverySliceIdForRecord(recordRef);
945
+ const sliceRecords = sliceId ? recordsBySlice.get(sliceId) : undefined;
946
+ if (!sliceId || !sliceRecords) {
947
+ throw new Error(`Factory mutation shared record ${this.sharedRecordId(recordRef.entry, recordRef.record)} is not assigned to a progressive delivery slice`);
948
+ }
949
+ sliceRecords.push(recordRef);
950
+ });
951
+ return this.activeDeliverySequence.slices.flatMap(({ sliceId }) => recordsBySlice.get(sliceId) ?? []);
952
+ }
953
+ deliverySliceIdForRecord({ entry, record }) {
954
+ if (entry.options.sharedDelivery === 'immediate')
955
+ return;
956
+ if (this.activeDeliverySequence?.mode === 'atomic') {
957
+ return this.activeDeliverySequence.slices[0]?.sliceId;
958
+ }
959
+ if (this.activeDeliverySequence?.mode !== 'progressive')
960
+ return;
961
+ if (record.orderedIds.length === 0) {
962
+ throw new Error(`Factory mutation shared record ${this.sharedRecordId(entry, record)} is not assigned to a progressive delivery slice`);
963
+ }
964
+ const sliceIds = new Set();
965
+ record.orderedIds.forEach((orderedId) => {
966
+ const sliceId = this.activeDeliverySliceByOrderedId.get(orderedId);
967
+ if (!sliceId) {
968
+ throw new Error(`Factory mutation ordered id is not assigned to a progressive delivery slice: ${orderedId}`);
969
+ }
970
+ sliceIds.add(sliceId);
971
+ });
972
+ if (sliceIds.size > 1) {
973
+ throw new Error(`Factory mutation shared record ${this.sharedRecordId(entry, record)} cannot span delivery slices`);
974
+ }
975
+ return [...sliceIds][0];
976
+ }
977
+ prepareSharedDeliveryBatches(entries, orderedRecords, deliverySliceIdOverride) {
978
+ const records = orderedRecords ?? this.sharedRecordRefs(entries);
979
+ const preparedBatches = [];
980
+ const seenBatchIds = new Set();
981
+ const deliverySliceIds = new Map();
982
+ records.forEach((recordRef) => {
983
+ const sliceId = recordRef.record.batch?.sliceId ??
984
+ deliverySliceIdOverride ??
985
+ this.deliverySliceIdForRecord(recordRef);
986
+ if (!sliceId)
987
+ return;
988
+ if (this.activeDeliverySequence &&
989
+ recordRef.entry.options.sharedDelivery !== 'immediate' &&
990
+ !this.activeDeliverySliceOrder.has(sliceId)) {
991
+ throw new Error(`Factory mutation delivery slice is unknown: ${sliceId}`);
992
+ }
993
+ deliverySliceIds.set(recordRef.record, sliceId);
994
+ });
995
+ let cursor = 0;
996
+ while (cursor < records.length) {
997
+ const first = records[cursor];
998
+ const shared = first?.entry.shared;
999
+ if (!first || !shared) {
1000
+ cursor += 1;
1001
+ continue;
1002
+ }
1003
+ if (first.record.batch) {
1004
+ if (!seenBatchIds.has(first.record.batch.batchId)) {
1005
+ seenBatchIds.add(first.record.batch.batchId);
1006
+ preparedBatches.push(first.record.batch);
1007
+ }
1008
+ cursor += 1;
1009
+ continue;
1010
+ }
1011
+ const group = [first];
1012
+ const deliverySliceId = deliverySliceIds.get(first.record);
1013
+ cursor += 1;
1014
+ while (cursor < records.length) {
1015
+ const candidate = records[cursor];
1016
+ const candidateShared = candidate?.entry.shared;
1017
+ if (!candidate ||
1018
+ !candidateShared ||
1019
+ candidate.record.batch ||
1020
+ candidateShared.name !== shared.name ||
1021
+ candidate.entry.options.sharedDelivery !==
1022
+ first.entry.options.sharedDelivery ||
1023
+ deliverySliceIds.get(candidate.record) !== deliverySliceId) {
1024
+ break;
1025
+ }
1026
+ group.push(candidate);
1027
+ cursor += 1;
1028
+ }
1029
+ new Set(group.map(({ entry }) => entry)).forEach((entry) => this.prepareEntryInverses(entry));
1030
+ const batchId = this.nextDeliveryBatchId();
1031
+ const deliveries = deepFreezeValue(group.flatMap((recordRef) => {
1032
+ const delivery = this.createForwardSharedDelivery(recordRef, batchId);
1033
+ return delivery ? [delivery] : [];
1034
+ }));
1035
+ const batch = deepFreezeValue({
1036
+ batchId,
1037
+ sliceId: deliverySliceId ?? batchId,
1038
+ artifactId: this.currentArtifactId,
1039
+ transactionId: this.currentTransactionId,
1040
+ origin: this.transactionOrigin(),
1041
+ kind: 'forward',
1042
+ channel: shared.name,
1043
+ sharedDelivery: first.entry.options.sharedDelivery,
1044
+ deliveries,
1045
+ records: deepFreezeValue(deliveries.map((delivery) => delivery.record)),
1046
+ changes: deepFreezeValue(deliveries.map((delivery) => delivery.payload)),
1047
+ compensationBatchId: `${batchId}:compensation`
1048
+ });
1049
+ group.forEach(({ record }, index) => {
1050
+ record.batch = batch;
1051
+ record.delivery = deliveries[index];
1052
+ });
1053
+ this.preparedSharedBatchRecords.set(batch.batchId, group);
1054
+ this.currentSharedDeliveryBatches.push(batch);
1055
+ preparedBatches.push(batch);
1056
+ seenBatchIds.add(batch.batchId);
1057
+ }
1058
+ return preparedBatches;
1059
+ }
1060
+ deliverPreparedSharedBatch(batch) {
1061
+ const historyReplayState = this.historyReplaySharedState?.batchStateById.get(batch.batchId);
1062
+ if (historyReplayState) {
1063
+ if (historyReplayState.delivered)
1064
+ return true;
1065
+ if (historyReplayState.readyReadinessKeys.size !==
1066
+ historyReplayState.requiredReadinessKeys.size) {
1067
+ return false;
1068
+ }
1069
+ this.sharedEvidenceNotificationDepth += 1;
1070
+ try {
1071
+ const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, batch.channel, batch.changes);
1072
+ if (!delivered)
1073
+ return false;
1074
+ historyReplayState.delivered = true;
1075
+ if (this.transactionOrigin() !== 'remote') {
1076
+ this.onSharedDeliveryBatch?.(batch);
1077
+ }
1078
+ return true;
1079
+ }
1080
+ finally {
1081
+ this.sharedEvidenceNotificationDepth -= 1;
1082
+ }
1083
+ }
1084
+ const records = (this.preparedSharedBatchRecords.get(batch.batchId) ?? []).filter(({ record }) => !record.delivered);
1085
+ if (records.length === 0)
1086
+ return true;
1087
+ this.sharedEvidenceNotificationDepth += 1;
1088
+ try {
1089
+ const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, batch.channel, batch.changes);
1090
+ if (!delivered)
1091
+ return false;
1092
+ records.forEach(({ record }) => {
1093
+ record.delivered = true;
1094
+ });
1095
+ if (this.transactionOrigin() !== 'remote') {
1096
+ this.onSharedDeliveryBatch?.(batch);
1097
+ }
1098
+ return true;
1099
+ }
1100
+ finally {
1101
+ this.sharedEvidenceNotificationDepth -= 1;
1102
+ }
1103
+ }
1104
+ deliverSharedEntries(entries, deliverySliceIdOverride) {
1105
+ this.prepareSharedDeliveryBatches(entries, undefined, deliverySliceIdOverride).forEach((batch) => this.deliverPreparedSharedBatch(batch));
1106
+ }
1107
+ prepareTransactionEndDeliveryIndex() {
1108
+ if (this.transactionEndDeliveryBatches) {
1109
+ return this.transactionEndDeliveryBatches;
1110
+ }
1111
+ return measureBrowserDragPhase('factory:index-shared-delivery-records', () => {
1112
+ if (this.historyReplaySharedState?.batchStates.length) {
1113
+ const batches = this.historyReplaySharedState.batchStates
1114
+ .filter(({ batch }) => batch.sharedDelivery === 'transaction-end')
1115
+ .map(({ batch }) => batch);
1116
+ const unreadyBatch = batches.find((batch) => {
1117
+ const state = this.historyReplaySharedState?.batchStateById.get(batch.batchId);
1118
+ return (!state ||
1119
+ state.readyReadinessKeys.size !== state.requiredReadinessKeys.size);
1120
+ });
1121
+ if (unreadyBatch) {
1122
+ throw new Error(`Factory history replay batch is not ready: ${unreadyBatch.batchId}`);
1123
+ }
1124
+ const batchesBySlice = new Map();
1125
+ batches.forEach((batch) => {
1126
+ const sliceBatches = batchesBySlice.get(batch.sliceId) ?? [];
1127
+ sliceBatches.push(batch);
1128
+ batchesBySlice.set(batch.sliceId, sliceBatches);
1129
+ });
1130
+ const immediateSliceIds = new Set(this.historyReplaySharedState.batchStates.flatMap(({ batch }) => batch.sharedDelivery === 'immediate' ? [batch.sliceId] : []));
1131
+ if (this.activeDeliverySequence?.mode === 'progressive' &&
1132
+ this.activeDeliverySequence.slices.some(({ sliceId }) => !batchesBySlice.has(sliceId) && !immediateSliceIds.has(sliceId))) {
1133
+ throw new Error('Factory mutation delivery sequence contains an empty progressive slice');
1134
+ }
1135
+ batchesBySlice.forEach((sliceBatches, sliceId) => this.transactionEndBatchesBySlice.set(sliceId, deepFreezeValue(sliceBatches)));
1136
+ this.transactionEndDeliveryBatches = deepFreezeValue(batches);
1137
+ return this.transactionEndDeliveryBatches;
1138
+ }
1139
+ const canonicalTransactionEndEntries = this.journal.filter((entry) => entry.options.sharedDelivery === 'transaction-end');
1140
+ const transactionEndEntries = canonicalTransactionEndEntries.filter((entry) => entry.shared !== undefined);
1141
+ const records = this.sharedRecordRefs(transactionEndEntries);
1142
+ this.validateActiveDeliverySequenceCoverage(canonicalTransactionEndEntries);
1143
+ const orderedRecords = this.orderSharedRecordsByActiveSlice(records);
1144
+ const batches = this.prepareSharedDeliveryBatches(transactionEndEntries, orderedRecords);
1145
+ const batchesBySlice = new Map();
1146
+ const recordsBySlice = new Map();
1147
+ batches.forEach((batch) => {
1148
+ const sliceBatches = batchesBySlice.get(batch.sliceId) ?? [];
1149
+ sliceBatches.push(batch);
1150
+ batchesBySlice.set(batch.sliceId, sliceBatches);
1151
+ const sliceRecords = recordsBySlice.get(batch.sliceId) ?? [];
1152
+ sliceRecords.push(...(this.preparedSharedBatchRecords.get(batch.batchId) ?? []));
1153
+ recordsBySlice.set(batch.sliceId, sliceRecords);
1154
+ });
1155
+ if (records.length > 0 &&
1156
+ this.activeDeliverySequence?.mode === 'progressive' &&
1157
+ this.activeDeliverySequence.slices.some(({ sliceId }) => !batchesBySlice.has(sliceId))) {
1158
+ throw new Error('Factory mutation delivery sequence contains an empty progressive slice');
1159
+ }
1160
+ batchesBySlice.forEach((sliceBatches, sliceId) => this.transactionEndBatchesBySlice.set(sliceId, deepFreezeValue(sliceBatches)));
1161
+ recordsBySlice.forEach((sliceRecords, sliceId) => this.transactionEndRecordsBySlice.set(sliceId, sliceRecords));
1162
+ this.transactionEndDeliveryBatches = deepFreezeValue(batches);
1163
+ return this.transactionEndDeliveryBatches;
1164
+ });
1165
+ }
1166
+ sharedRecordPublicationWorkItemKeys(records) {
1167
+ return records.flatMap(({ entry, record }) => record.orderedIds.length > 0
1168
+ ? record.orderedIds.map((orderedId) => `ordered:${orderedId}`)
1169
+ : [
1170
+ `delivery:${record.delivery?.deliveryId ??
1171
+ record.evidence?.deliveryId ??
1172
+ `${entry.index}:${record.occurrence}`}`
1173
+ ]);
1174
+ }
1175
+ sharedBatchPublicationWorkItemKeys(batches) {
1176
+ return batches.flatMap(({ deliveries }) => deliveries.flatMap(({ deliveryId, record }) => record.orderedIds.length > 0
1177
+ ? record.orderedIds.map((orderedId) => `ordered:${orderedId}`)
1178
+ : [`delivery:${deliveryId}`]));
1179
+ }
1180
+ publicationWindowWouldExceedTarget(pendingWorkItemKeys, currentWorkItemKeys, maxItemsPerPublication = DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS) {
1181
+ if (pendingWorkItemKeys.size === 0)
1182
+ return false;
1183
+ let distinctCount = pendingWorkItemKeys.size;
1184
+ for (const workItemKey of currentWorkItemKeys) {
1185
+ if (!pendingWorkItemKeys.has(workItemKey))
1186
+ distinctCount += 1;
1187
+ }
1188
+ return distinctCount > maxItemsPerPublication;
1189
+ }
1190
+ shouldFlushPublicationWindow(pendingWorkItemKeys, finalSlice, maxItemsPerPublication = DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS) {
1191
+ return (this.activeDeliverySequence?.batchPublications === false ||
1192
+ pendingWorkItemKeys.size >= maxItemsPerPublication ||
1193
+ finalSlice);
1194
+ }
1195
+ flushPendingProgressivePublication() {
1196
+ const records = this.pendingProgressivePublicationRecords.splice(0);
1197
+ this.pendingProgressivePublicationWorkItemKeys.clear();
1198
+ if (records.length === 0)
1199
+ return;
1200
+ this.queueSharedPublication(this.createSharedPublicationFromRecords(records));
1201
+ this.flushSharedPublications();
1202
+ }
1203
+ queueProgressiveSlicePublication(records, sliceOrderedIds, finalSlice) {
1204
+ const publishableRecords = records.filter(({ record }) => record.delivered && record.publicationId === undefined);
1205
+ const workItemKeys = sliceOrderedIds.length > 0
1206
+ ? sliceOrderedIds.map((orderedId) => `ordered:${orderedId}`)
1207
+ : this.sharedRecordPublicationWorkItemKeys(publishableRecords);
1208
+ if (publishableRecords.length > 0 &&
1209
+ this.activeDeliverySequence?.batchPublications !== false &&
1210
+ this.publicationWindowWouldExceedTarget(this.pendingProgressivePublicationWorkItemKeys, workItemKeys)) {
1211
+ this.flushPendingProgressivePublication();
1212
+ }
1213
+ this.pendingProgressivePublicationRecords.push(...publishableRecords);
1214
+ workItemKeys.forEach((workItemKey) => this.pendingProgressivePublicationWorkItemKeys.add(workItemKey));
1215
+ if (this.shouldFlushPublicationWindow(this.pendingProgressivePublicationWorkItemKeys, finalSlice)) {
1216
+ this.flushPendingProgressivePublication();
1217
+ }
1218
+ }
1219
+ deliverActiveSlice(sliceId) {
1220
+ try {
1221
+ const sequence = this.activeDeliverySequence;
1222
+ if (sequence?.mode !== 'progressive') {
1223
+ throw new Error('Factory mutation delivery slice requires a progressive delivery sequence');
1224
+ }
1225
+ const expectedSlice = sequence.slices[this.nextDeliverySliceIndex];
1226
+ if (!expectedSlice || expectedSlice.sliceId !== sliceId) {
1227
+ throw new Error(`Factory mutation delivery slice must follow sequence order: ${expectedSlice?.sliceId ?? 'complete'}`);
1228
+ }
1229
+ this.prepareTransactionEndDeliveryIndex();
1230
+ const batches = this.transactionEndBatchesBySlice.get(sliceId) ?? [];
1231
+ if (!batches.every((batch) => this.deliverPreparedSharedBatch(batch))) {
1232
+ throw new Error(`Factory mutation delivery slice could not be delivered: ${sliceId}`);
1233
+ }
1234
+ const records = this.transactionEndRecordsBySlice.get(sliceId) ?? [];
1235
+ this.queueProgressiveSlicePublication(records, expectedSlice.orderedIds, this.nextDeliverySliceIndex === sequence.slices.length - 1);
1236
+ this.nextDeliverySliceIndex += 1;
1237
+ }
1238
+ catch (error) {
1239
+ this.rollbackOnly = true;
1240
+ this.rollbackFailure ?? (this.rollbackFailure = toReplayFailure(error));
1241
+ throw error;
1242
+ }
1243
+ }
1244
+ nextPublicationId() {
1245
+ this.publicationSequence += 1;
1246
+ return `${this.currentTransactionId}:publication:${this.publicationSequence}`;
1247
+ }
1248
+ createSharedPublication(entries, origin = this.transactionOrigin()) {
1249
+ return this.createSharedPublicationFromRecords(this.sharedRecordRefs(entries), origin);
1250
+ }
1251
+ createSharedPublicationFromRecords(records, origin = this.transactionOrigin()) {
1252
+ return measureBrowserDragPhase('factory:create-shared-publication', () => {
1253
+ if (this.transactionOrigin() === 'remote' || origin === 'remote')
1254
+ return;
1255
+ const publishableRecords = records.filter(({ record }) => {
1256
+ if (!record.delivered || record.publicationId !== undefined) {
1257
+ return false;
1258
+ }
1259
+ return true;
1260
+ });
1261
+ const batches = [];
1262
+ const seenBatchIds = new Set();
1263
+ publishableRecords.forEach(({ record }) => {
1264
+ const batch = record.batch;
1265
+ if (!batch || seenBatchIds.has(batch.batchId))
1266
+ return;
1267
+ seenBatchIds.add(batch.batchId);
1268
+ batches.push(batch);
1269
+ });
1270
+ if (batches.length === 0)
1271
+ return;
1272
+ const publication = this.createSharedPublicationFromBatches(batches, origin);
1273
+ if (!publication)
1274
+ return;
1275
+ publishableRecords.forEach(({ record }) => {
1276
+ record.publicationId = publication.publicationId;
1277
+ record.compensationPublicationId = `${publication.publicationId}:compensation`;
1278
+ });
1279
+ this.publicationAcknowledgements.set(publication, () => {
1280
+ publishableRecords.forEach(({ record }) => {
1281
+ record.acknowledgedPublicationId = publication.publicationId;
1282
+ });
1283
+ });
1284
+ return publication;
1285
+ });
1286
+ }
1287
+ createSharedPublicationFromBatches(batches, origin, identity = {}) {
1288
+ if (batches.length === 0 ||
1289
+ origin === 'remote' ||
1290
+ this.transactionOrigin() === 'remote') {
1291
+ return;
1292
+ }
1293
+ const deliverySequence = this.resolveDeliverySequence(batches, {
1294
+ includeActiveSequence: origin !== 'rollback-compensation',
1295
+ modeOverride: origin === 'rollback-compensation' &&
1296
+ this.activeDeliverySequence?.mode === 'progressive'
1297
+ ? 'progressive'
1298
+ : undefined,
1299
+ orderedIdsFromRecords: origin === 'rollback-compensation' &&
1300
+ this.activeDeliverySequence?.mode === 'progressive'
1301
+ });
1302
+ const publicationBatchesBySliceId = new Map();
1303
+ batches.forEach((batch) => {
1304
+ const deliveries = Object.freeze(batch.deliveries.map((delivery) => Object.freeze({
1305
+ deliveryId: delivery.deliveryId,
1306
+ eventName: delivery.eventName,
1307
+ orderedIds: delivery.record.orderedIds,
1308
+ payload: delivery.payload,
1309
+ ...(delivery.compensatesDeliveryId
1310
+ ? { compensatesDeliveryId: delivery.compensatesDeliveryId }
1311
+ : {})
1312
+ })));
1313
+ const publicationBatch = Object.freeze({
1314
+ batchId: batch.batchId,
1315
+ channel: batch.channel,
1316
+ deliveries
1317
+ });
1318
+ const sliceBatches = publicationBatchesBySliceId.get(batch.sliceId) ?? [];
1319
+ sliceBatches.push(publicationBatch);
1320
+ publicationBatchesBySliceId.set(batch.sliceId, sliceBatches);
1321
+ });
1322
+ const slices = Object.freeze(deliverySequence.slices.map((slice) => Object.freeze({
1323
+ sliceId: slice.sliceId,
1324
+ orderedIds: slice.orderedIds,
1325
+ batches: Object.freeze([
1326
+ ...(publicationBatchesBySliceId.get(slice.sliceId) ?? [])
1327
+ ])
1328
+ })));
1329
+ const publicationId = identity.publicationId ?? this.nextPublicationId();
1330
+ return Object.freeze({
1331
+ publicationId,
1332
+ artifactId: this.currentArtifactId,
1333
+ transactionId: this.currentTransactionId,
1334
+ origin,
1335
+ mode: deliverySequence.mode,
1336
+ slices,
1337
+ ...(identity.compensatesPublicationId
1338
+ ? { compensatesPublicationId: identity.compensatesPublicationId }
1339
+ : {})
1340
+ });
1341
+ }
1342
+ createHistoryReplaySharedPublication(batches) {
1343
+ const state = this.historyReplaySharedState;
1344
+ if (!state)
1345
+ return;
1346
+ const publishableBatches = batches.filter((batch) => {
1347
+ const batchState = state.batchStateById.get(batch.batchId);
1348
+ return (batchState?.delivered === true && batchState.publicationId === undefined);
1349
+ });
1350
+ const publication = this.createSharedPublicationFromBatches(publishableBatches, this.transactionOrigin());
1351
+ if (!publication)
1352
+ return;
1353
+ publishableBatches.forEach((batch) => {
1354
+ const batchState = state.batchStateById.get(batch.batchId);
1355
+ if (!batchState)
1356
+ return;
1357
+ batchState.publicationId = publication.publicationId;
1358
+ batchState.compensationPublicationId = `${publication.publicationId}:compensation`;
1359
+ });
1360
+ this.publicationAcknowledgements.set(publication, () => {
1361
+ publishableBatches.forEach((batch) => {
1362
+ const batchState = state.batchStateById.get(batch.batchId);
1363
+ if (batchState) {
1364
+ batchState.acknowledgedPublicationId = publication.publicationId;
1365
+ }
1366
+ });
1367
+ });
1368
+ return publication;
1369
+ }
1370
+ queueAcknowledgedCompensationPublications(items) {
1371
+ const groups = new Map();
1372
+ items.forEach(({ batch, publicationId, compensatesPublicationId }) => {
1373
+ const group = groups.get(publicationId);
1374
+ if (group) {
1375
+ group.batches.push(batch);
1376
+ return;
1377
+ }
1378
+ groups.set(publicationId, {
1379
+ compensatesPublicationId,
1380
+ batches: [batch]
1381
+ });
1382
+ });
1383
+ groups.forEach(({ batches, compensatesPublicationId }, publicationId) => {
1384
+ this.queueSharedPublication(this.createSharedPublicationFromBatches(batches, 'rollback-compensation', {
1385
+ publicationId,
1386
+ compensatesPublicationId
1387
+ }));
1388
+ });
1389
+ }
1390
+ resolveDeliverySequence(batches = this.currentSharedDeliveryBatches, options = {}) {
1391
+ const activeSequenceBatches = batches.filter((batch) => batch.sharedDelivery === 'transaction-end');
1392
+ if (this.activeDeliverySequence &&
1393
+ this.activeDeliverySequence.slices.length > 0 &&
1394
+ options.includeActiveSequence !== false &&
1395
+ (batches.length === 0 || activeSequenceBatches.length > 0)) {
1396
+ if (batches.length === 0)
1397
+ return this.activeDeliverySequence;
1398
+ return measureBrowserDragPhase('factory:select-delivery-sequence-boundaries', () => {
1399
+ const seenSliceIds = new Set();
1400
+ const slices = [];
1401
+ activeSequenceBatches.forEach((batch) => {
1402
+ if (seenSliceIds.has(batch.sliceId))
1403
+ return;
1404
+ const boundary = this.activeDeliveryBoundaryBySliceId.get(batch.sliceId);
1405
+ if (!boundary) {
1406
+ throw new Error(`Factory mutation delivery slice is unknown: ${batch.sliceId}`);
1407
+ }
1408
+ seenSliceIds.add(batch.sliceId);
1409
+ slices.push(boundary);
1410
+ });
1411
+ return deepFreezeValue({
1412
+ mode: this.activeDeliverySequence?.mode ?? 'atomic',
1413
+ slices
1414
+ });
1415
+ });
1416
+ }
1417
+ const slices = new Map();
1418
+ const seenSliceOrderedIds = new Map();
1419
+ batches.forEach((batch) => {
1420
+ const orderedIds = slices.get(batch.sliceId) ?? [];
1421
+ if (options.orderedIdsFromRecords) {
1422
+ const seenOrderedIds = seenSliceOrderedIds.get(batch.sliceId) ?? new Set();
1423
+ batch.records.forEach((record) => [...record.orderedIds].reverse().forEach((orderedId) => {
1424
+ if (seenOrderedIds.has(orderedId))
1425
+ return;
1426
+ seenOrderedIds.add(orderedId);
1427
+ orderedIds.push(orderedId);
1428
+ }));
1429
+ seenSliceOrderedIds.set(batch.sliceId, seenOrderedIds);
1430
+ }
1431
+ else {
1432
+ orderedIds.push(...batch.deliveries.map((delivery) => delivery.deliveryId));
1433
+ }
1434
+ slices.set(batch.sliceId, orderedIds);
1435
+ });
1436
+ return deepFreezeValue({
1437
+ mode: options.modeOverride ??
1438
+ (batches.some((batch) => batch.sharedDelivery === 'immediate')
1439
+ ? 'progressive'
1440
+ : 'atomic'),
1441
+ slices: [...slices].map(([sliceId, orderedIds]) => ({
1442
+ sliceId,
1443
+ orderedIds
1444
+ }))
1445
+ });
1446
+ }
1447
+ resolveCommittedHistoryDeliverySequence() {
1448
+ if (this.activeDeliverySequence?.mode === 'progressive') {
1449
+ return this.activeDeliverySequence;
1450
+ }
1451
+ if (this.activeDeliverySequence?.batchPublications !== false)
1452
+ return;
1453
+ const deliveryIdsBySlice = new Map();
1454
+ this.currentSharedDeliveryBatches.forEach((batch) => {
1455
+ const deliveryIds = deliveryIdsBySlice.get(batch.sliceId) ?? [];
1456
+ deliveryIds.push(...batch.deliveries.map((delivery) => delivery.deliveryId));
1457
+ deliveryIdsBySlice.set(batch.sliceId, deliveryIds);
1458
+ });
1459
+ if (deliveryIdsBySlice.size === 0)
1460
+ return;
1461
+ return deepFreezeValue({
1462
+ mode: 'progressive',
1463
+ batchPublications: false,
1464
+ slices: [...deliveryIdsBySlice].map(([sliceId, orderedIds]) => ({
1465
+ sliceId,
1466
+ orderedIds
1467
+ }))
1468
+ });
1469
+ }
1470
+ queueImmediatePublicationEntries(entries) {
1471
+ if (entries.length === 0)
1472
+ return;
1473
+ this.pendingImmediatePublicationEntries.push(...entries);
1474
+ const token = this.immediatePublicationToken;
1475
+ if (this.scheduledImmediatePublicationToken === token)
1476
+ return;
1477
+ this.scheduledImmediatePublicationToken = token;
1478
+ queueMicrotask(() => {
1479
+ if (this.scheduledImmediatePublicationToken === token) {
1480
+ this.scheduledImmediatePublicationToken = null;
1481
+ }
1482
+ if (token !== this.immediatePublicationToken)
1483
+ return;
1484
+ this.queuePendingImmediatePublication();
1485
+ this.flushSharedPublications();
1486
+ });
1487
+ }
1488
+ queuePendingImmediatePublication() {
1489
+ this.scheduledImmediatePublicationToken = null;
1490
+ this.immediatePublicationToken += 1;
1491
+ const entries = this.pendingImmediatePublicationEntries.splice(0);
1492
+ if (entries.length === 0)
1493
+ return;
1494
+ const records = this.sharedRecordRefs(entries).filter(({ record }) => record.delivered && record.publicationId === undefined);
1495
+ const workItemKeys = this.sharedRecordPublicationWorkItemKeys(records);
1496
+ if (records.length > 0 &&
1497
+ this.activeDeliverySequence?.mode !== 'atomic' &&
1498
+ this.publicationWindowWouldExceedTarget(this.pendingImmediatePublicationWorkItemKeys, workItemKeys)) {
1499
+ this.flushPendingImmediatePublication();
1500
+ }
1501
+ this.pendingImmediatePublicationRecords.push(...records);
1502
+ workItemKeys.forEach((workItemKey) => this.pendingImmediatePublicationWorkItemKeys.add(workItemKey));
1503
+ if (this.activeDeliverySequence?.batchPublications === false ||
1504
+ (this.activeDeliverySequence?.mode !== 'atomic' &&
1505
+ this.pendingImmediatePublicationWorkItemKeys.size >=
1506
+ DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS)) {
1507
+ this.flushPendingImmediatePublication();
1508
+ }
1509
+ }
1510
+ flushPendingImmediatePublication() {
1511
+ const records = this.pendingImmediatePublicationRecords.splice(0);
1512
+ this.pendingImmediatePublicationWorkItemKeys.clear();
1513
+ if (records.length === 0)
1514
+ return;
1515
+ this.queueSharedPublication(this.createSharedPublicationFromRecords(records));
1516
+ this.flushSharedPublications();
1517
+ }
1518
+ discardPendingImmediatePublication() {
1519
+ this.scheduledImmediatePublicationToken = null;
1520
+ this.immediatePublicationToken += 1;
1521
+ this.pendingImmediatePublicationEntries.length = 0;
1522
+ this.pendingImmediatePublicationRecords.length = 0;
1523
+ this.pendingImmediatePublicationWorkItemKeys.clear();
1524
+ }
1525
+ queueSharedPublication(publication) {
1526
+ if (!publication)
1527
+ return;
1528
+ this.pendingSharedPublications.push(publication);
1529
+ }
1530
+ queueUnacknowledgedSharedPublications() {
1531
+ this.unacknowledgedSharedPublications.forEach((publication) => {
1532
+ if (!this.pendingSharedPublications.includes(publication)) {
1533
+ this.pendingSharedPublications.push(publication);
1534
+ }
1535
+ });
43
1536
  }
44
- end() {
1537
+ removeUnacknowledgedSharedPublication(publication) {
1538
+ const index = this.unacknowledgedSharedPublications.indexOf(publication);
1539
+ if (index >= 0) {
1540
+ this.unacknowledgedSharedPublications.splice(index, 1);
1541
+ }
1542
+ }
1543
+ flushSharedPublications() {
1544
+ if (this.emittingSharedPublications)
1545
+ return;
1546
+ this.emittingSharedPublications = true;
1547
+ try {
1548
+ let publication;
1549
+ while ((publication = this.pendingSharedPublications.shift())) {
1550
+ this.sharedEvidenceNotificationDepth += 1;
1551
+ let acknowledged = false;
1552
+ try {
1553
+ const handoff = this.onSharedPublication?.(publication);
1554
+ if (this.onSharedPublication !== undefined && handoff !== false) {
1555
+ this.publicationAcknowledgements.get(publication)?.();
1556
+ acknowledged = true;
1557
+ this.removeUnacknowledgedSharedPublication(publication);
1558
+ }
1559
+ else if (!this.unacknowledgedSharedPublications.includes(publication)) {
1560
+ this.unacknowledgedSharedPublications.push(publication);
1561
+ }
1562
+ }
1563
+ finally {
1564
+ if (acknowledged) {
1565
+ this.publicationAcknowledgements.delete(publication);
1566
+ }
1567
+ this.sharedEvidenceNotificationDepth -= 1;
1568
+ }
1569
+ }
1570
+ }
1571
+ finally {
1572
+ this.emittingSharedPublications = false;
1573
+ }
1574
+ }
1575
+ emitCompensationSharedDelivery({ entry, record }, eventName, payload, compensationIndex, batchId) {
1576
+ if (this.transactionOrigin() === 'remote')
1577
+ return;
1578
+ const shared = entry.shared;
1579
+ const evidence = record.evidence;
1580
+ if (!shared || !evidence)
1581
+ return;
1582
+ const forwardDelivery = record.delivery;
1583
+ const deliveryId = forwardDelivery?.compensationDeliveryIds?.[compensationIndex] ??
1584
+ this.compensationDeliveryId(entry, record, compensationIndex);
1585
+ return deepFreezeValue({
1586
+ deliveryId,
1587
+ artifactId: this.currentArtifactId,
1588
+ batchId,
1589
+ transactionId: this.currentTransactionId,
1590
+ origin: 'rollback-compensation',
1591
+ kind: 'compensation',
1592
+ channel: shared.name,
1593
+ eventName,
1594
+ payload,
1595
+ recordId: evidence.recordId,
1596
+ record: evidence,
1597
+ sharedDelivery: entry.options.sharedDelivery,
1598
+ compensatesDeliveryId: this.forwardDeliveryId(entry, record)
1599
+ });
1600
+ }
1601
+ createFactoryOwnedBuiltInInverse(event) {
1602
+ const payload = event.payload;
1603
+ if (!payload || typeof payload !== 'object') {
1604
+ throw new Error(`Transaction event ${event.type} has no invertible payload`);
1605
+ }
1606
+ if (event.type === EventTypes.MOVE_ELEMENTS &&
1607
+ 'moves' in payload &&
1608
+ Array.isArray(payload.moves)) {
1609
+ const movePayload = payload;
1610
+ return [
1611
+ {
1612
+ ...event,
1613
+ payload: {
1614
+ ...movePayload,
1615
+ moves: movePayload.moves.map((move) => ({
1616
+ ...move,
1617
+ before: move.after,
1618
+ after: move.before
1619
+ }))
1620
+ }
1621
+ }
1622
+ ];
1623
+ }
1624
+ if ('changes' in payload && Array.isArray(payload.changes)) {
1625
+ const inverseChanges = [...payload.changes]
1626
+ .reverse()
1627
+ .map((change, index) => {
1628
+ if (!change ||
1629
+ typeof change !== 'object' ||
1630
+ !('before' in change) ||
1631
+ !('after' in change)) {
1632
+ throw new Error(`Transaction event ${event.type} has an invalid change at index ${index}`);
1633
+ }
1634
+ return {
1635
+ ...change,
1636
+ before: change.after,
1637
+ after: change.before
1638
+ };
1639
+ });
1640
+ return [
1641
+ {
1642
+ ...event,
1643
+ payload: {
1644
+ ...payload,
1645
+ changes: inverseChanges
1646
+ }
1647
+ }
1648
+ ];
1649
+ }
1650
+ let inverseType = event.type;
1651
+ const inversePayload = { ...payload };
1652
+ if ('undoType' in payload && payload.undoType !== undefined) {
1653
+ inverseType = payload.undoType;
1654
+ inversePayload.undoType = event.type;
1655
+ if ('eventName' in payload) {
1656
+ inversePayload.eventName = inverseType;
1657
+ }
1658
+ }
1659
+ if ('undoAction' in payload && payload.undoAction !== undefined) {
1660
+ inversePayload.action = payload.undoAction;
1661
+ inversePayload.undoAction = payload.action;
1662
+ }
1663
+ if ('after' in payload) {
1664
+ inversePayload.before = payload.after;
1665
+ inversePayload.after = payload.before;
1666
+ }
1667
+ return [
1668
+ {
1669
+ ...event,
1670
+ type: inverseType,
1671
+ payload: inversePayload
1672
+ }
1673
+ ];
1674
+ }
1675
+ createReplayEvents(event, direction, provenance = 'detached') {
1676
+ if (direction === 'inverse') {
1677
+ const customInverter = this.inverters.get(event.type);
1678
+ if (customInverter) {
1679
+ const result = customInverter(cloneEvent(event));
1680
+ const replayEvents = Array.isArray(result) ? result : [result];
1681
+ if (replayEvents.length === 0) {
1682
+ throw new Error(`Transaction inverter ${event.type} produced no replay event`);
1683
+ }
1684
+ return replayEvents.map((item, index) => {
1685
+ if (!isReplayEvent(item)) {
1686
+ throw new Error(`Transaction inverter ${event.type} produced an invalid replay event at index ${index}`);
1687
+ }
1688
+ return cloneEvent(item);
1689
+ });
1690
+ }
1691
+ }
1692
+ if (direction === 'inverse' && provenance === 'factory-owned-journal') {
1693
+ return this.createFactoryOwnedBuiltInInverse(event);
1694
+ }
1695
+ const replayEvent = cloneEvent(event);
1696
+ const payload = replayEvent.payload;
1697
+ if (direction === 'inverse' &&
1698
+ replayEvent.type === EventTypes.MOVE_ELEMENTS &&
1699
+ payload &&
1700
+ typeof payload === 'object' &&
1701
+ 'moves' in payload &&
1702
+ Array.isArray(payload.moves)) {
1703
+ const movePayload = payload;
1704
+ return [
1705
+ {
1706
+ type: replayEvent.type,
1707
+ payload: {
1708
+ ...movePayload,
1709
+ moves: movePayload.moves.map((move) => ({
1710
+ elementId: move.elementId,
1711
+ before: { ...move.after },
1712
+ after: { ...move.before }
1713
+ }))
1714
+ }
1715
+ }
1716
+ ];
1717
+ }
1718
+ if (direction === 'inverse' &&
1719
+ payload &&
1720
+ typeof payload === 'object' &&
1721
+ 'changes' in payload) {
1722
+ const changes = payload.changes;
1723
+ if (Array.isArray(changes)) {
1724
+ const { changes: _changes, ...basePayload } = payload;
1725
+ const inverseChanges = [...changes].reverse().map((change, index) => {
1726
+ if (!change ||
1727
+ typeof change !== 'object' ||
1728
+ !('before' in change) ||
1729
+ !('after' in change)) {
1730
+ throw new Error(`Transaction event ${event.type} has an invalid change at index ${index}`);
1731
+ }
1732
+ return {
1733
+ ...change,
1734
+ before: change.after,
1735
+ after: change.before
1736
+ };
1737
+ });
1738
+ return [
1739
+ {
1740
+ type: replayEvent.type,
1741
+ payload: {
1742
+ ...basePayload,
1743
+ changes: inverseChanges
1744
+ }
1745
+ }
1746
+ ];
1747
+ }
1748
+ }
1749
+ if (direction === 'forward') {
1750
+ return [replayEvent];
1751
+ }
1752
+ if (!payload || typeof payload !== 'object') {
1753
+ throw new Error(`Transaction event ${event.type} has no invertible payload`);
1754
+ }
1755
+ if ('undoType' in payload && payload.undoType !== undefined) {
1756
+ const originalType = replayEvent.type;
1757
+ replayEvent.type = payload.undoType;
1758
+ payload.undoType = originalType;
1759
+ if ('eventName' in payload) {
1760
+ ;
1761
+ payload.eventName = replayEvent.type;
1762
+ }
1763
+ }
1764
+ if ('undoAction' in payload && payload.undoAction !== undefined) {
1765
+ const originalAction = payload.action;
1766
+ payload.action = payload.undoAction;
1767
+ payload.undoAction = originalAction;
1768
+ }
1769
+ if ('after' in payload) {
1770
+ const originalBefore = payload.before;
1771
+ const originalAfter = payload.after;
1772
+ payload.before = originalAfter;
1773
+ payload.after = originalBefore;
1774
+ }
1775
+ return [replayEvent];
1776
+ }
1777
+ applyForwardEvent(event, apply) {
1778
+ return apply(cloneEvent(event)) !== false;
1779
+ }
1780
+ applyReplayEvent(event, mode) {
1781
+ const previousApplyingReplayEvent = this.applyingReplayEvent;
1782
+ this.applyingReplayEvent = true;
1783
+ try {
1784
+ return runInTransactionReplayMode(mode, () => {
1785
+ const result = this.onReplayEvent?.(event, mode);
1786
+ const handled = typeof result === 'object' ? result.handled : result === true;
1787
+ const applied = typeof result === 'object' ? result.applied : result === true;
1788
+ if (handled) {
1789
+ if (applied) {
1790
+ acknowledgeTransactionReplayApplied();
1791
+ }
1792
+ publishEventToObservers(event);
1793
+ }
1794
+ else {
1795
+ publishEvent(event);
1796
+ }
1797
+ return isTransactionReplayApplied();
1798
+ });
1799
+ }
1800
+ finally {
1801
+ this.applyingReplayEvent = previousApplyingReplayEvent;
1802
+ }
1803
+ }
1804
+ applyReplayEventBatch(events, mode) {
1805
+ const previousApplyingReplayEvent = this.applyingReplayEvent;
1806
+ this.applyingReplayEvent = true;
1807
+ try {
1808
+ return runInTransactionReplayMode(mode, () => {
1809
+ applyEventBatchToSynchronousOwners(events);
1810
+ publishEventsToObservers(events);
1811
+ return isTransactionReplayApplied();
1812
+ });
1813
+ }
1814
+ finally {
1815
+ this.applyingReplayEvent = previousApplyingReplayEvent;
1816
+ }
1817
+ }
1818
+ replayStepSourceSliceId(step) {
1819
+ if (!step.shared || 'suppress' in step.shared)
1820
+ return;
1821
+ const sliceIds = new Set();
1822
+ step.shared.records.forEach(({ readinessKey }) => {
1823
+ const states = this.historyReplaySharedState?.batchStatesByReadinessKey.get(readinessKey) ?? [];
1824
+ states.forEach(({ batch }) => sliceIds.add(batch.sliceId));
1825
+ });
1826
+ return sliceIds.size === 1 ? [...sliceIds][0] : undefined;
1827
+ }
1828
+ *replaySteps(events, direction, mode, maxItemsPerSlice, restorationBatches, sharedReplay, preparedReplayEvents) {
1829
+ const failures = [];
1830
+ const pendingSliceWorkItemKeys = new Set();
1831
+ let hasPendingSlicePublication = false;
1832
+ const entries = events.map((event, index) => ({
1833
+ event,
1834
+ shared: sharedReplay?.[index],
1835
+ preparedReplayEvents: preparedReplayEvents?.[index]
1836
+ }));
1837
+ const orderedEntries = direction === 'inverse' ? entries.reverse() : entries;
1838
+ const preparedSteps = [];
1839
+ for (const { event, shared: sharedOutputs, preparedReplayEvents } of orderedEntries) {
1840
+ let replayEvents;
1841
+ try {
1842
+ replayEvents = preparedReplayEvents
1843
+ ? preparedReplayEvents.map(cloneEvent)
1844
+ : this.createReplayEvents(event, direction);
1845
+ }
1846
+ catch (error) {
1847
+ failures.push(error);
1848
+ continue;
1849
+ }
1850
+ for (let replayOutputIndex = 0; replayOutputIndex < replayEvents.length; replayOutputIndex += 1) {
1851
+ const replayEvent = replayEvents[replayOutputIndex];
1852
+ if (!replayEvent)
1853
+ continue;
1854
+ const shared = sharedOutputs?.[replayOutputIndex];
1855
+ let restorationEvents;
1856
+ const mustValidateReplayOutput = restorationBatches !== undefined ||
1857
+ (direction === 'inverse' && this.inverters.has(event.type));
1858
+ const replayPayload = replayEvent
1859
+ .payload;
1860
+ if (mustValidateReplayOutput &&
1861
+ !this.hasInverseContract(replayEvent.type, replayPayload)) {
1862
+ failures.push(new Error(`Replay output ${replayEvent.type} requires an inverse contract`));
1863
+ continue;
1864
+ }
1865
+ if (restorationBatches || this.inverters.has(replayEvent.type)) {
1866
+ try {
1867
+ const inverseOutputEvents = this.createReplayEvents(replayEvent, 'inverse').map(cloneEvent);
1868
+ if (inverseOutputEvents.length === 0) {
1869
+ throw new Error(`Replay output ${replayEvent.type} produced no restoration event`);
1870
+ }
1871
+ if (restorationBatches) {
1872
+ restorationEvents = inverseOutputEvents;
1873
+ }
1874
+ }
1875
+ catch (error) {
1876
+ failures.push(error);
1877
+ continue;
1878
+ }
1879
+ }
1880
+ preparedSteps.push({
1881
+ replayEvent,
1882
+ restorationEvents,
1883
+ shared
1884
+ });
1885
+ }
1886
+ }
1887
+ for (let stepIndex = 0; stepIndex < preparedSteps.length; stepIndex += 1) {
1888
+ const firstStep = preparedSteps[stepIndex];
1889
+ if (!firstStep)
1890
+ continue;
1891
+ const firstEventType = firstStep.replayEvent.type;
1892
+ const firstSourceSliceId = this.replayStepSourceSliceId(firstStep);
1893
+ const mayUseOwnerBatch = hasSynchronousEventBatchHandler(firstEventType) &&
1894
+ (this.canReplayEventBatch?.(firstEventType) ??
1895
+ this.onReplayEvent === undefined);
1896
+ const ownerBatch = [firstStep];
1897
+ if (mayUseOwnerBatch) {
1898
+ while (ownerBatch.length < MAX_CANONICAL_REPLAY_OWNER_BATCH_ITEMS) {
1899
+ const candidate = preparedSteps[stepIndex + ownerBatch.length];
1900
+ if (!candidate ||
1901
+ candidate.replayEvent.type !== firstEventType ||
1902
+ this.replayStepSourceSliceId(candidate) !== firstSourceSliceId) {
1903
+ break;
1904
+ }
1905
+ ownerBatch.push(candidate);
1906
+ }
1907
+ }
1908
+ const appliedSteps = mayUseOwnerBatch && ownerBatch.length > 1 ? ownerBatch : [firstStep];
1909
+ const journalStart = this.journal.length;
1910
+ const previousRetainingHistoryReplaySharedEvidence = this.retainingHistoryReplaySharedEvidence;
1911
+ const isRetainedHistoryReplay = this.historyReplaySharedState?.ownsReplayEvidence === true;
1912
+ this.retainingHistoryReplaySharedEvidence = isRetainedHistoryReplay;
1913
+ try {
1914
+ const applied = appliedSteps.length > 1
1915
+ ? this.applyReplayEventBatch(appliedSteps.map(({ replayEvent }) => replayEvent), mode)
1916
+ : this.applyReplayEvent(firstStep.replayEvent, mode);
1917
+ const recordedEntries = this.journal.slice(journalStart);
1918
+ if (isRetainedHistoryReplay) {
1919
+ this.suppressHistoryReplayOwnerSharedEntries(recordedEntries);
1920
+ }
1921
+ if (applied) {
1922
+ appliedSteps.forEach(({ restorationEvents }) => {
1923
+ if (restorationEvents) {
1924
+ restorationBatches?.push(restorationEvents);
1925
+ }
1926
+ });
1927
+ if (isRetainedHistoryReplay) {
1928
+ appliedSteps.forEach(({ shared }) => {
1929
+ if (shared && !('suppress' in shared)) {
1930
+ this.markHistoryReplaySharedReady(shared);
1931
+ }
1932
+ });
1933
+ let settlement = this.flushNextReadyHistoryReplaySlice();
1934
+ while (settlement !== 'none') {
1935
+ hasPendingSlicePublication = true;
1936
+ settlement.workItemKeys.forEach((workItemKey) => pendingSliceWorkItemKeys.add(workItemKey));
1937
+ if (settlement.explicitBoundary ||
1938
+ pendingSliceWorkItemKeys.size >= maxItemsPerSlice) {
1939
+ hasPendingSlicePublication = false;
1940
+ pendingSliceWorkItemKeys.clear();
1941
+ yield;
1942
+ }
1943
+ settlement = this.flushNextReadyHistoryReplaySlice();
1944
+ }
1945
+ }
1946
+ }
1947
+ }
1948
+ catch (error) {
1949
+ if (isRetainedHistoryReplay) {
1950
+ this.suppressHistoryReplayOwnerSharedEntries(this.journal.slice(journalStart));
1951
+ }
1952
+ if (wasTransactionReplayApplied(error)) {
1953
+ appliedSteps.forEach(({ restorationEvents }) => {
1954
+ if (restorationEvents) {
1955
+ restorationBatches?.push(restorationEvents);
1956
+ }
1957
+ });
1958
+ }
1959
+ failures.push(error);
1960
+ }
1961
+ finally {
1962
+ this.retainingHistoryReplaySharedEvidence =
1963
+ previousRetainingHistoryReplaySharedEvidence;
1964
+ }
1965
+ stepIndex += appliedSteps.length - 1;
1966
+ }
1967
+ if (hasPendingSlicePublication) {
1968
+ yield;
1969
+ }
1970
+ return failures;
1971
+ }
1972
+ replay(events, direction, mode, restorationBatches, sharedReplay, preparedReplayEvents) {
1973
+ const steps = this.replaySteps(events, direction, mode, Number.MAX_SAFE_INTEGER, restorationBatches, sharedReplay, preparedReplayEvents);
1974
+ let step = steps.next();
1975
+ while (!step.done) {
1976
+ step = steps.next();
1977
+ }
1978
+ return step.value;
1979
+ }
1980
+ async replayProgressively(events, direction, mode, yieldAfterSlice, maxItemsPerSlice, restorationBatches, sharedReplay, preparedReplayEvents) {
1981
+ const steps = this.replaySteps(events, direction, mode, maxItemsPerSlice, restorationBatches, sharedReplay, preparedReplayEvents);
1982
+ let step = steps.next();
1983
+ try {
1984
+ while (!step.done) {
1985
+ await yieldAfterSlice();
1986
+ step = steps.next();
1987
+ }
1988
+ return step.value;
1989
+ }
1990
+ catch (error) {
1991
+ steps.return([]);
1992
+ throw error;
1993
+ }
1994
+ }
1995
+ restoreNestedReplay() {
1996
+ const failures = [];
1997
+ [...this.nestedReplayRestorationBatches]
1998
+ .reverse()
1999
+ .forEach((restorationEvents) => {
2000
+ restorationEvents.forEach((event) => {
2001
+ try {
2002
+ this.applyReplayEvent(cloneEvent(event), 'rollback');
2003
+ }
2004
+ catch (error) {
2005
+ failures.push(error);
2006
+ }
2007
+ });
2008
+ });
2009
+ return failures;
2010
+ }
2011
+ rollbackJournal(source) {
2012
+ const failures = [];
2013
+ const rollbackableEntries = this.journal.filter((entry) => entry.options.rollbackable &&
2014
+ (source === undefined || entry.source === source));
2015
+ const preparedEntries = rollbackableEntries.filter((entry) => {
2016
+ try {
2017
+ this.prepareEntryInverses(entry);
2018
+ return true;
2019
+ }
2020
+ catch (error) {
2021
+ failures.push(error);
2022
+ return false;
2023
+ }
2024
+ });
2025
+ return [
2026
+ ...failures,
2027
+ ...this.replay(preparedEntries.map(({ event }) => event), 'inverse', 'rollback', undefined, undefined, preparedEntries.map((entry) => entry.inverseEvents))
2028
+ ];
2029
+ }
2030
+ compensateDeliveredHistoryReplayBatches() {
2031
+ const sharedState = this.historyReplaySharedState;
2032
+ if (!sharedState)
2033
+ return [];
2034
+ const failures = [];
2035
+ const acknowledgedCompensationBatches = [];
2036
+ [...sharedState.batchStates]
2037
+ .reverse()
2038
+ .filter(({ delivered }) => delivered)
2039
+ .forEach((state) => {
2040
+ const forwardBatch = state.batch;
2041
+ try {
2042
+ const batchId = forwardBatch.compensationBatchId ??
2043
+ `${forwardBatch.batchId}:compensation`;
2044
+ const inverseRecords = [...forwardBatch.deliveries]
2045
+ .reverse()
2046
+ .flatMap((forwardDelivery) => forwardDelivery.record.inverseEvents.map((inverseEvent, inverseIndex) => ({
2047
+ forwardDelivery,
2048
+ inverseEvent,
2049
+ inverseIndex,
2050
+ payload: inverseEvent.payload
2051
+ })));
2052
+ const deliveries = deepFreezeValue(inverseRecords.map(({ forwardDelivery, inverseEvent, inverseIndex, payload }) => deepFreezeValue({
2053
+ deliveryId: forwardDelivery.compensationDeliveryIds?.[inverseIndex] ??
2054
+ `${forwardDelivery.deliveryId}:compensation:${inverseIndex}`,
2055
+ artifactId: this.currentArtifactId,
2056
+ batchId,
2057
+ transactionId: this.currentTransactionId,
2058
+ origin: 'rollback-compensation',
2059
+ kind: 'compensation',
2060
+ channel: forwardBatch.channel,
2061
+ eventName: inverseEvent.type,
2062
+ payload,
2063
+ recordId: forwardDelivery.recordId,
2064
+ record: forwardDelivery.record,
2065
+ sharedDelivery: forwardBatch.sharedDelivery,
2066
+ compensatesDeliveryId: forwardDelivery.deliveryId
2067
+ })));
2068
+ const compensationBatch = deepFreezeValue({
2069
+ batchId,
2070
+ sliceId: `${forwardBatch.sliceId}:compensation`,
2071
+ artifactId: this.currentArtifactId,
2072
+ transactionId: this.currentTransactionId,
2073
+ origin: 'rollback-compensation',
2074
+ kind: 'compensation',
2075
+ channel: forwardBatch.channel,
2076
+ sharedDelivery: forwardBatch.sharedDelivery,
2077
+ deliveries,
2078
+ records: deepFreezeValue(inverseRecords.map(({ forwardDelivery }) => forwardDelivery.record)),
2079
+ changes: deepFreezeValue(deliveries.map((delivery) => delivery.payload)),
2080
+ compensatesBatchId: forwardBatch.batchId
2081
+ });
2082
+ this.sharedEvidenceNotificationDepth += 1;
2083
+ try {
2084
+ const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, compensationBatch.channel, compensationBatch.changes);
2085
+ if (!delivered) {
2086
+ throw new Error(`Failed to compensate shared channel ${compensationBatch.channel}`);
2087
+ }
2088
+ this.onSharedDeliveryBatch?.(compensationBatch);
2089
+ }
2090
+ finally {
2091
+ this.sharedEvidenceNotificationDepth -= 1;
2092
+ }
2093
+ if (state.acknowledgedPublicationId &&
2094
+ state.compensationPublicationId) {
2095
+ acknowledgedCompensationBatches.push({
2096
+ batch: compensationBatch,
2097
+ publicationId: state.compensationPublicationId,
2098
+ compensatesPublicationId: state.acknowledgedPublicationId
2099
+ });
2100
+ }
2101
+ }
2102
+ catch (error) {
2103
+ failures.push(error);
2104
+ }
2105
+ });
2106
+ this.queueAcknowledgedCompensationPublications(acknowledgedCompensationBatches);
2107
+ this.flushSharedPublications();
2108
+ return failures;
2109
+ }
2110
+ compensateImmediateSharedChanges() {
2111
+ const failures = [
2112
+ ...this.compensateDeliveredHistoryReplayBatches()
2113
+ ];
2114
+ const acknowledgedCompensationBatches = [];
2115
+ const inversePreparedEntries = new Set();
2116
+ const groupedRecords = new Map();
2117
+ [...this.journal].reverse().forEach((entry) => {
2118
+ ;
2119
+ [...(entry.shared?.records ?? [])].reverse().forEach((record) => {
2120
+ const forwardBatch = record.batch;
2121
+ if (!entry.options.rollbackable || !record.delivered || !forwardBatch) {
2122
+ return;
2123
+ }
2124
+ const group = groupedRecords.get(forwardBatch.batchId);
2125
+ if (group) {
2126
+ group.records.push({ entry, record });
2127
+ }
2128
+ else {
2129
+ groupedRecords.set(forwardBatch.batchId, {
2130
+ forwardBatch,
2131
+ records: [{ entry, record }]
2132
+ });
2133
+ }
2134
+ });
2135
+ });
2136
+ groupedRecords.forEach(({ forwardBatch, records }) => {
2137
+ try {
2138
+ const inverseRecords = records.flatMap((recordRef) => {
2139
+ const { entry, record } = recordRef;
2140
+ if (!inversePreparedEntries.has(entry)) {
2141
+ inversePreparedEntries.add(entry);
2142
+ this.prepareEntryInverses(entry);
2143
+ }
2144
+ const inverseEvents = record.inverseEvents ?? [];
2145
+ return inverseEvents.map((inverseEvent, compensationIndex) => ({
2146
+ recordRef,
2147
+ inverseEvent,
2148
+ compensationIndex,
2149
+ payload: inverseEvent.payload
2150
+ }));
2151
+ });
2152
+ const inverseChanges = deepFreezeValue(inverseRecords.map(({ payload }) => payload));
2153
+ const isRemote = this.transactionOrigin() === 'remote';
2154
+ const batchId = forwardBatch.compensationBatchId ??
2155
+ `${forwardBatch.batchId}:compensation`;
2156
+ const deliveries = deepFreezeValue(isRemote
2157
+ ? []
2158
+ : inverseRecords.flatMap(({ recordRef, inverseEvent, compensationIndex, payload }) => {
2159
+ const delivery = this.emitCompensationSharedDelivery(recordRef, inverseEvent.type, payload, compensationIndex, batchId);
2160
+ return delivery ? [delivery] : [];
2161
+ }));
2162
+ const compensationBatch = deepFreezeValue({
2163
+ batchId,
2164
+ sliceId: `${forwardBatch.sliceId}:compensation`,
2165
+ artifactId: this.currentArtifactId,
2166
+ transactionId: this.currentTransactionId,
2167
+ origin: 'rollback-compensation',
2168
+ kind: 'compensation',
2169
+ channel: forwardBatch.channel,
2170
+ sharedDelivery: forwardBatch.sharedDelivery,
2171
+ deliveries,
2172
+ records: deepFreezeValue(records.flatMap(({ record }) => record.evidence ? [record.evidence] : [])),
2173
+ changes: isRemote
2174
+ ? inverseChanges
2175
+ : deepFreezeValue(deliveries.map((delivery) => delivery.payload)),
2176
+ compensatesBatchId: forwardBatch.batchId
2177
+ });
2178
+ this.sharedEvidenceNotificationDepth += 1;
2179
+ try {
2180
+ const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, compensationBatch.channel, compensationBatch.changes);
2181
+ if (!delivered) {
2182
+ throw new Error(`Failed to compensate shared channel ${compensationBatch.channel}`);
2183
+ }
2184
+ if (!isRemote) {
2185
+ this.onSharedDeliveryBatch?.(compensationBatch);
2186
+ }
2187
+ }
2188
+ finally {
2189
+ this.sharedEvidenceNotificationDepth -= 1;
2190
+ }
2191
+ const acknowledgedRecord = records.find(({ record }) => record.acknowledgedPublicationId !== undefined &&
2192
+ record.compensationPublicationId !== undefined)?.record;
2193
+ if (acknowledgedRecord?.acknowledgedPublicationId &&
2194
+ acknowledgedRecord.compensationPublicationId) {
2195
+ acknowledgedCompensationBatches.push({
2196
+ batch: compensationBatch,
2197
+ publicationId: acknowledgedRecord.compensationPublicationId,
2198
+ compensatesPublicationId: acknowledgedRecord.acknowledgedPublicationId
2199
+ });
2200
+ }
2201
+ }
2202
+ catch (error) {
2203
+ failures.push(error);
2204
+ }
2205
+ });
2206
+ this.queueAcknowledgedCompensationPublications(acknowledgedCompensationBatches);
2207
+ this.flushSharedPublications();
2208
+ return failures;
2209
+ }
2210
+ transactionOrigin() {
2211
+ if (this.isInUndo()) {
2212
+ return 'undo';
2213
+ }
2214
+ if (this.isInRedo()) {
2215
+ return 'redo';
2216
+ }
2217
+ return this.activeOrigin;
2218
+ }
2219
+ createStatusPayload(status, failure, error) {
2220
+ return {
2221
+ transactionId: this.currentTransactionId,
2222
+ origin: this.transactionOrigin(),
2223
+ status,
2224
+ ...this.validationContext(),
2225
+ ...(failure ? { failure } : {}),
2226
+ ...(error !== undefined ? { error } : {}),
2227
+ timestamp: Date.now()
2228
+ };
2229
+ }
2230
+ queueStatus(payload) {
2231
+ this.pendingTransactionStatuses.push(payload);
2232
+ }
2233
+ flushStatuses() {
2234
+ if (this.emittingTransactionStatuses)
2235
+ return;
2236
+ this.emittingTransactionStatuses = true;
2237
+ try {
2238
+ let payload;
2239
+ while ((payload = this.pendingTransactionStatuses.shift())) {
2240
+ this.onStatus?.(payload);
2241
+ }
2242
+ }
2243
+ finally {
2244
+ this.emittingTransactionStatuses = false;
2245
+ }
2246
+ }
2247
+ emitStatus(status, failure, error) {
2248
+ this.queueStatus(this.createStatusPayload(status, failure, error));
2249
+ this.flushStatuses();
2250
+ }
2251
+ emitCommitCapture(payload) {
2252
+ if (!['action', 'undo', 'redo'].includes(payload.origin)) {
2253
+ return;
2254
+ }
2255
+ try {
2256
+ this.onCommitCapture?.(payload);
2257
+ }
2258
+ catch {
2259
+ // Persistence capture observers cannot alter canonical settlement.
2260
+ }
2261
+ }
2262
+ emitReplayCommitted(events) {
2263
+ const payload = {
2264
+ transactionId: this.currentTransactionId,
2265
+ origin: this.transactionOrigin(),
2266
+ status: 'committed',
2267
+ changeCount: events.length,
2268
+ undoableChangeCount: events.length,
2269
+ rollbackableChangeCount: events.length,
2270
+ nonRollbackableChangeCount: 0,
2271
+ timestamp: Date.now()
2272
+ };
2273
+ this.emitCommitCapture(payload);
2274
+ this.onStatus?.(payload);
2275
+ }
2276
+ commitNestedReplayHistory(history) {
2277
+ if (this.inUndo) {
2278
+ if (this.undoStack[this.undoStack.length - 1] !== history) {
2279
+ throw new Error('Nested undo source history changed before commit');
2280
+ }
2281
+ this.undoStack.pop();
2282
+ this.redoStack.push(history);
2283
+ return;
2284
+ }
2285
+ if (this.inRedo) {
2286
+ if (this.redoStack[this.redoStack.length - 1] !== history) {
2287
+ throw new Error('Nested redo source history changed before commit');
2288
+ }
2289
+ this.redoStack.pop();
2290
+ this.undoStack.push(history);
2291
+ }
2292
+ }
2293
+ ensureReplayTransactionId() {
2294
+ if (this.isTransacting > 0) {
2295
+ return;
2296
+ }
2297
+ this.transactionId += 1;
2298
+ this.currentTransactionId = this.transactionId;
2299
+ }
2300
+ settleRollback(failure, precedingFailures = []) {
2301
+ this.discardPendingImmediatePublication();
2302
+ if (this.nestedReplaySourceEvents) {
2303
+ this.restoringNestedReplay = true;
2304
+ let failures;
2305
+ try {
2306
+ failures = [
2307
+ ...this.rollbackJournal('action'),
2308
+ ...this.restoreNestedReplay()
2309
+ ];
2310
+ }
2311
+ finally {
2312
+ this.restoringNestedReplay = false;
2313
+ }
2314
+ const rollbackFailures = [
2315
+ ...precedingFailures,
2316
+ ...failures,
2317
+ ...this.compensateImmediateSharedChanges()
2318
+ ];
2319
+ if (rollbackFailures.length > 0) {
2320
+ const rollbackError = new TransactionRollbackError(rollbackFailures);
2321
+ this.emitStatus('rollback-failed', failure, rollbackError);
2322
+ throw rollbackError;
2323
+ }
2324
+ this.emitStatus('rolled-back', failure);
2325
+ return;
2326
+ }
2327
+ if (this.journal.length === 0) {
2328
+ this.emitStatus('discarded', failure);
2329
+ return;
2330
+ }
2331
+ const failures = [
2332
+ ...precedingFailures,
2333
+ ...this.rollbackJournal(),
2334
+ ...this.compensateImmediateSharedChanges()
2335
+ ];
2336
+ if (failures.length > 0) {
2337
+ const rollbackError = new TransactionRollbackError(failures);
2338
+ this.emitStatus('rollback-failed', failure, rollbackError);
2339
+ throw rollbackError;
2340
+ }
2341
+ this.emitStatus('rolled-back', failure);
2342
+ }
2343
+ validationContext() {
2344
+ const undoableEntries = this.preparedActionHistoryEntries ?? this.journal;
2345
+ const undoableChangeCount = undoableEntries.filter(({ options }) => options.undoable).length;
2346
+ const rollbackableChangeCount = this.journal.filter(({ options }) => options.rollbackable).length;
2347
+ return {
2348
+ changeCount: this.journal.length,
2349
+ undoableChangeCount,
2350
+ rollbackableChangeCount,
2351
+ nonRollbackableChangeCount: this.journal.length - rollbackableChangeCount
2352
+ };
2353
+ }
2354
+ validateRequestedCommit() {
2355
+ const context = this.validationContext();
2356
+ for (const [name, validator] of this.validators) {
2357
+ let result;
2358
+ try {
2359
+ result = validator(context);
2360
+ }
2361
+ catch (error) {
2362
+ throw new TransactionValidationError(name, 'validator-threw', `Transaction validator ${name} threw an error`, error);
2363
+ }
2364
+ if (result &&
2365
+ typeof result === 'object' &&
2366
+ 'then' in result &&
2367
+ typeof result.then === 'function') {
2368
+ void Promise.resolve(result).catch(() => undefined);
2369
+ throw new TransactionValidationError(name, 'async-validator', `Transaction validator ${name} must be synchronous`);
2370
+ }
2371
+ if (result && result.valid === false) {
2372
+ throw new TransactionValidationError(name, result.code, result.message);
2373
+ }
2374
+ }
2375
+ }
2376
+ prepareHistoryTransition(history) {
2377
+ if (this.nestedReplaySourceHistory && this.nestedReplaySourceEvents) {
2378
+ const sourceHistory = this.nestedReplaySourceHistory;
2379
+ const events = this.nestedReplaySourceEvents;
2380
+ this.commitNestedReplayHistory(sourceHistory);
2381
+ return {
2382
+ complete: () => this.emitReplayCommitted(events),
2383
+ rollback: () => {
2384
+ if (this.inUndo) {
2385
+ if (this.redoStack[this.redoStack.length - 1] !== sourceHistory) {
2386
+ throw new Error('Undo target history changed before rollback');
2387
+ }
2388
+ this.redoStack.pop();
2389
+ this.undoStack.push(sourceHistory);
2390
+ return;
2391
+ }
2392
+ if (this.inRedo) {
2393
+ if (this.undoStack[this.undoStack.length - 1] !== sourceHistory) {
2394
+ throw new Error('Redo target history changed before rollback');
2395
+ }
2396
+ this.undoStack.pop();
2397
+ this.redoStack.push(sourceHistory);
2398
+ }
2399
+ }
2400
+ };
2401
+ }
2402
+ if (this.isInUndo() || this.isInRedo()) {
2403
+ return null;
2404
+ }
2405
+ if (!history) {
2406
+ throw new Error('Committed transaction journal is required for local history');
2407
+ }
2408
+ const committedChanges = this.historyChanges(history);
2409
+ if (committedChanges.length === 0) {
2410
+ return null;
2411
+ }
2412
+ const previousRedoStack = this.redoStack;
2413
+ this.undoStack.push(history);
2414
+ this.redoStack = [];
2415
+ return {
2416
+ complete: () => {
2417
+ this.actionId += 1;
2418
+ this.onUserActionCompleted?.({
2419
+ actionId: this.actionId,
2420
+ changeCount: committedChanges.length,
2421
+ timestamp: Date.now()
2422
+ });
2423
+ },
2424
+ rollback: () => {
2425
+ if (this.undoStack[this.undoStack.length - 1] !== history) {
2426
+ throw new Error('Action undo history changed before rollback');
2427
+ }
2428
+ this.undoStack.pop();
2429
+ this.redoStack = previousRedoStack;
2430
+ }
2431
+ };
2432
+ }
2433
+ end(options = {}) {
2434
+ this.assertSharedEvidenceCanonicalControlAllowed();
45
2435
  if (this.isTransacting <= 0) {
46
2436
  return;
47
2437
  }
2438
+ if (options.outcome === 'rollback') {
2439
+ this.rollbackOnly = true;
2440
+ this.rollbackFailure ?? (this.rollbackFailure = options.failure);
2441
+ }
48
2442
  this.isTransacting--;
49
2443
  if (this.isTransacting === 0) {
50
- this.commitUndo();
51
- this.changes = [];
2444
+ this.transactionSettlementDepth += 1;
2445
+ try {
2446
+ if (this.rollbackOnly) {
2447
+ this.settleRollback(this.rollbackFailure);
2448
+ }
2449
+ else {
2450
+ try {
2451
+ if (this.journal.length > 0 &&
2452
+ !this.isInUndo() &&
2453
+ !this.isInRedo()) {
2454
+ this.preparedActionHistoryEntries =
2455
+ this.prepareCommittedActionHistoryEntries();
2456
+ this.validateRequestedCommit();
2457
+ }
2458
+ }
2459
+ catch (error) {
2460
+ this.rollbackFailure = {
2461
+ kind: 'validation-failed',
2462
+ message: error instanceof Error ? error.message : undefined,
2463
+ cause: error
2464
+ };
2465
+ this.settleRollback(this.rollbackFailure);
2466
+ throw error;
2467
+ }
2468
+ if (this.journal.length === 0 &&
2469
+ !this.historyReplaySharedState?.batchStates.length) {
2470
+ if (this.nestedReplaySourceEvents) {
2471
+ this.prepareHistoryTransition()?.complete();
2472
+ }
2473
+ else if (!this.isInUndo() && !this.isInRedo()) {
2474
+ this.emitStatus('discarded');
2475
+ }
2476
+ }
2477
+ else {
2478
+ let historyTransition = null;
2479
+ const sharedPublications = [];
2480
+ try {
2481
+ this.queueUnacknowledgedSharedPublications();
2482
+ this.queuePendingImmediatePublication();
2483
+ this.flushPendingImmediatePublication();
2484
+ this.flushSharedPublications();
2485
+ const transactionEndBatches = this.prepareTransactionEndDeliveryIndex();
2486
+ const transactionEndEntries = this.journal.filter((entry) => entry.options.sharedDelivery === 'transaction-end');
2487
+ const historyDeliverySequence = this.resolveCommittedHistoryDeliverySequence();
2488
+ const history = {
2489
+ entries: this.preparedActionHistoryEntries ?? this.journal,
2490
+ ...(historyDeliverySequence
2491
+ ? {
2492
+ progressiveDeliverySequence: historyDeliverySequence
2493
+ }
2494
+ : {})
2495
+ };
2496
+ historyTransition = this.prepareHistoryTransition(history);
2497
+ measureBrowserDragPhase('factory:flush-shared-channels', () => {
2498
+ if (this.activeDeliverySequence?.mode === 'progressive') {
2499
+ const { slices } = this.activeDeliverySequence;
2500
+ while (this.nextDeliverySliceIndex < slices.length) {
2501
+ const sliceId = slices[this.nextDeliverySliceIndex]?.sliceId;
2502
+ if (!sliceId) {
2503
+ throw new Error('Factory mutation delivery sequence contains an empty progressive slice');
2504
+ }
2505
+ const sliceBatches = this.transactionEndBatchesBySlice.get(sliceId) ?? [];
2506
+ sliceBatches.forEach((batch) => {
2507
+ this.deliverPreparedSharedBatch(batch);
2508
+ });
2509
+ this.queueProgressiveSlicePublication(this.transactionEndRecordsBySlice.get(sliceId) ?? [], slices[this.nextDeliverySliceIndex]?.orderedIds ?? [], this.nextDeliverySliceIndex === slices.length - 1);
2510
+ this.nextDeliverySliceIndex += 1;
2511
+ }
2512
+ return;
2513
+ }
2514
+ transactionEndBatches.forEach((batch) => {
2515
+ this.deliverPreparedSharedBatch(batch);
2516
+ });
2517
+ const publication = this.historyReplaySharedState?.batchStates
2518
+ .length
2519
+ ? this.createHistoryReplaySharedPublication(transactionEndBatches)
2520
+ : this.createSharedPublication(transactionEndEntries);
2521
+ if (publication)
2522
+ sharedPublications.push(publication);
2523
+ });
2524
+ }
2525
+ catch (error) {
2526
+ this.rollbackFailure = toReplayFailure(error);
2527
+ const historyFailures = [];
2528
+ try {
2529
+ historyTransition?.rollback();
2530
+ }
2531
+ catch (historyError) {
2532
+ historyFailures.push(historyError);
2533
+ }
2534
+ this.settleRollback(this.rollbackFailure, historyFailures);
2535
+ throw error;
2536
+ }
2537
+ sharedPublications.forEach((publication) => this.queueSharedPublication(publication));
2538
+ const committedStatus = !this.nestedReplaySourceEvents &&
2539
+ !this.isInUndo() &&
2540
+ !this.isInRedo()
2541
+ ? this.createStatusPayload('committed')
2542
+ : undefined;
2543
+ if (committedStatus) {
2544
+ this.queueStatus(committedStatus);
2545
+ this.emitCommitCapture(committedStatus);
2546
+ }
2547
+ historyTransition?.complete();
2548
+ this.flushSharedPublications();
2549
+ this.flushStatuses();
2550
+ }
2551
+ }
2552
+ }
2553
+ finally {
2554
+ this.discardPendingImmediatePublication();
2555
+ this.unacknowledgedSharedPublications.length = 0;
2556
+ this.publicationAcknowledgements.clear();
2557
+ this.journal = [];
2558
+ this.replaceLatestHistoryStages.clear();
2559
+ this.preparedActionHistoryEntries = null;
2560
+ this.rollbackOnly = false;
2561
+ this.rollbackFailure = undefined;
2562
+ this.activeOrigin = 'action';
2563
+ this.activeDeliverySequence = undefined;
2564
+ this.activeDeliverySliceByOrderedId.clear();
2565
+ this.activeDeliverySliceOrder.clear();
2566
+ this.activeDeliveryBoundaryBySliceId.clear();
2567
+ this.activeDeliveryOrderedIdOrder.clear();
2568
+ this.activeDeliverySequenceValidated = false;
2569
+ this.nextDeliverySliceIndex = 0;
2570
+ this.activeStagedDeliveryController = undefined;
2571
+ this.activeDeliveryHandle = undefined;
2572
+ this.activeDeliveryHandleToken = undefined;
2573
+ this.currentSharedDeliveryBatches = [];
2574
+ this.preparedSharedBatchRecords.clear();
2575
+ this.transactionEndDeliveryBatches = null;
2576
+ this.transactionEndBatchesBySlice.clear();
2577
+ this.transactionEndRecordsBySlice.clear();
2578
+ this.pendingProgressivePublicationRecords.length = 0;
2579
+ this.pendingProgressivePublicationWorkItemKeys.clear();
2580
+ this.pendingHistoryReplayPublicationBatches.length = 0;
2581
+ this.pendingHistoryReplayPublicationWorkItemKeys.clear();
2582
+ this.historyReplaySharedState = undefined;
2583
+ this.retainingHistoryReplaySharedEvidence = false;
2584
+ if (this.nestedReplaySourceEvents) {
2585
+ this.nestedReplaySourceEvents = null;
2586
+ this.nestedReplaySourceHistory = null;
2587
+ this.nestedReplayRestorationBatches = [];
2588
+ this.inUndo = false;
2589
+ this.inRedo = false;
2590
+ }
2591
+ this.transactionSettlementDepth -= 1;
2592
+ if (this.transactionSettlementDepth === 0) {
2593
+ this.flushSharedPublications();
2594
+ this.flushStatuses();
2595
+ }
2596
+ }
2597
+ }
2598
+ }
2599
+ flushPendingSharedChannelChanges() {
2600
+ measureBrowserDragPhase('factory:flush-shared-channels', () => {
2601
+ this.deliverSharedEntries(this.journal.filter((entry) => entry.shared?.records.some((record) => !record.delivered)));
2602
+ });
2603
+ }
2604
+ historyChanges(history) {
2605
+ return history.entries.filter(({ options }) => options.undoable);
2606
+ }
2607
+ deliveredHistoryRecords(history) {
2608
+ return this.historyChanges(history).flatMap((entry) => (entry.shared?.records ?? []).flatMap((record) => record.delivered && record.delivery && record.batch
2609
+ ? [{ entry, record }]
2610
+ : []));
2611
+ }
2612
+ historySourceBatches(records) {
2613
+ const batches = [];
2614
+ const seenBatchIds = new Set();
2615
+ records.forEach(({ record }) => {
2616
+ const batch = record.batch;
2617
+ if (!batch || seenBatchIds.has(batch.batchId))
2618
+ return;
2619
+ seenBatchIds.add(batch.batchId);
2620
+ batches.push(batch);
2621
+ });
2622
+ return batches;
2623
+ }
2624
+ orderHistorySourceBatchesByDeliverySequence(history, batches) {
2625
+ const sequence = history.progressiveDeliverySequence;
2626
+ if (!sequence)
2627
+ return batches;
2628
+ const batchesBySlice = new Map();
2629
+ batches.forEach((batch) => {
2630
+ const sliceBatches = batchesBySlice.get(batch.sliceId) ?? [];
2631
+ sliceBatches.push(batch);
2632
+ batchesBySlice.set(batch.sliceId, sliceBatches);
2633
+ });
2634
+ const orderedBatches = sequence.slices.flatMap(({ sliceId }) => batchesBySlice.get(sliceId) ?? []);
2635
+ const orderedBatchIds = new Set(orderedBatches.map(({ batchId }) => batchId));
2636
+ orderedBatches.push(...batches.filter(({ batchId }) => !orderedBatchIds.has(batchId)));
2637
+ return deepFreezeValue(orderedBatches);
2638
+ }
2639
+ historyReplayReadinessKey(sourceRecordId, outputIndex) {
2640
+ return `${sourceRecordId}:output:${outputIndex}`;
2641
+ }
2642
+ configureHistoryReplayProgressiveSequence(history, direction, deliveredOrderedIds) {
2643
+ const deliverySequence = history.progressiveDeliverySequence;
2644
+ if (this.activeDeliverySequence ||
2645
+ !deliverySequence ||
2646
+ deliveredOrderedIds.size === 0) {
2647
+ return;
2648
+ }
2649
+ const slices = direction === 'forward'
2650
+ ? deliverySequence.slices.flatMap((slice) => {
2651
+ const orderedIds = slice.orderedIds.filter((orderedId) => deliveredOrderedIds.has(orderedId));
2652
+ return orderedIds.length > 0
2653
+ ? [{ sliceId: slice.sliceId, orderedIds }]
2654
+ : [];
2655
+ })
2656
+ : [...deliverySequence.slices].reverse().flatMap((slice) => {
2657
+ const orderedIds = [...slice.orderedIds]
2658
+ .reverse()
2659
+ .filter((orderedId) => deliveredOrderedIds.has(orderedId));
2660
+ return orderedIds.length > 0
2661
+ ? [{ sliceId: `${slice.sliceId}:inverse`, orderedIds }]
2662
+ : [];
2663
+ });
2664
+ const deliveryOrderedIds = new Set(slices.flatMap(({ orderedIds }) => orderedIds));
2665
+ if (deliveryOrderedIds.size !== deliveredOrderedIds.size ||
2666
+ [...deliveredOrderedIds].some((orderedId) => !deliveryOrderedIds.has(orderedId))) {
2667
+ return;
52
2668
  }
2669
+ this.configureActiveDeliverySequence(deepFreezeValue({
2670
+ mode: 'progressive',
2671
+ ...(deliverySequence.batchPublications === undefined
2672
+ ? {}
2673
+ : { batchPublications: deliverySequence.batchPublications }),
2674
+ slices
2675
+ }));
2676
+ }
2677
+ prepareHistoryReplaySharedState(history, direction) {
2678
+ if (this.historyReplaySharedState) {
2679
+ throw new Error('Factory history replay shared state already exists');
2680
+ }
2681
+ const historyChanges = this.historyChanges(history);
2682
+ const deliveredRecords = this.deliveredHistoryRecords(history);
2683
+ const deliveredSourceIds = new Set(deliveredRecords.flatMap(({ record }) => record.delivery ? [record.delivery.deliveryId] : []));
2684
+ const committedSourceBatches = this.orderHistorySourceBatchesByDeliverySequence(history, this.historySourceBatches(deliveredRecords));
2685
+ const sourceBatches = direction === 'forward'
2686
+ ? committedSourceBatches
2687
+ : [...committedSourceBatches].reverse();
2688
+ const batchStates = [];
2689
+ const batchStatesByReadinessKey = new Map();
2690
+ const deliveredOrderedIds = new Set();
2691
+ const historyDeliveryOrderedIds = new Set(history.progressiveDeliverySequence?.slices.flatMap(({ orderedIds }) => orderedIds) ?? []);
2692
+ sourceBatches.forEach((sourceBatch) => {
2693
+ const sourceDeliveries = (direction === 'forward'
2694
+ ? sourceBatch.deliveries
2695
+ : [...sourceBatch.deliveries].reverse()).filter((delivery) => deliveredSourceIds.has(delivery.deliveryId));
2696
+ if (sourceDeliveries.length === 0)
2697
+ return;
2698
+ const batchId = this.nextDeliveryBatchId();
2699
+ let replayRecordOccurrence = 0;
2700
+ const replayRecords = sourceDeliveries.flatMap((sourceDelivery) => {
2701
+ const sourceRecord = sourceDelivery.record;
2702
+ const replayEvents = direction === 'forward'
2703
+ ? [
2704
+ {
2705
+ event: {
2706
+ type: sourceDelivery.eventName,
2707
+ payload: sourceDelivery.payload
2708
+ },
2709
+ outputIndex: 0
2710
+ }
2711
+ ]
2712
+ : sourceRecord.inverseEvents.map((event, outputIndex) => ({
2713
+ event,
2714
+ outputIndex
2715
+ }));
2716
+ return replayEvents.map(({ event, outputIndex }) => {
2717
+ const readinessKey = this.historyReplayReadinessKey(sourceRecord.recordId, outputIndex);
2718
+ const recordIndex = replayRecordOccurrence;
2719
+ replayRecordOccurrence += 1;
2720
+ const recordId = `${this.currentTransactionId}:history:${sourceRecord.recordId}:${outputIndex}`;
2721
+ const deliveryId = `${recordId}:forward`;
2722
+ const orderedIds = direction === 'forward'
2723
+ ? sourceRecord.orderedIds
2724
+ : [...sourceRecord.orderedIds].reverse();
2725
+ orderedIds.forEach((orderedId) => {
2726
+ if (historyDeliveryOrderedIds.has(orderedId)) {
2727
+ deliveredOrderedIds.add(orderedId);
2728
+ }
2729
+ });
2730
+ if (historyDeliveryOrderedIds.has(sourceDelivery.deliveryId)) {
2731
+ deliveredOrderedIds.add(sourceDelivery.deliveryId);
2732
+ }
2733
+ const replaySharedOptions = {
2734
+ undoable: false,
2735
+ rollbackable: true,
2736
+ sharedDelivery: sourceBatch.sharedDelivery
2737
+ };
2738
+ const payload = deepFreezeValue(toSharedChannelPayload(event.payload, replaySharedOptions));
2739
+ const inverseEvents = (direction === 'forward'
2740
+ ? sourceRecord.inverseEvents
2741
+ : this.createReplayEvents(event, 'inverse', 'factory-owned-journal')).map((inverseEvent) => deepFreezeValue({
2742
+ ...inverseEvent,
2743
+ payload: toSharedChannelPayload(inverseEvent.payload, replaySharedOptions)
2744
+ }));
2745
+ const record = deepFreezeValue({
2746
+ recordId,
2747
+ deliveryId,
2748
+ occurrence: recordIndex,
2749
+ orderedIds,
2750
+ payload,
2751
+ inverseEvents: deepFreezeValue(inverseEvents)
2752
+ });
2753
+ return { event, readinessKey, record };
2754
+ });
2755
+ });
2756
+ const deliveries = deepFreezeValue(replayRecords.map(({ event, record }) => deepFreezeValue({
2757
+ deliveryId: record.deliveryId,
2758
+ artifactId: this.currentArtifactId,
2759
+ batchId,
2760
+ transactionId: this.currentTransactionId,
2761
+ origin: this.transactionOrigin(),
2762
+ kind: 'forward',
2763
+ channel: sourceBatch.channel,
2764
+ eventName: event.type,
2765
+ payload: record.payload,
2766
+ recordId: record.recordId,
2767
+ record,
2768
+ sharedDelivery: sourceBatch.sharedDelivery,
2769
+ compensationDeliveryIds: deepFreezeValue(record.inverseEvents.map((_event, inverseIndex) => `${record.deliveryId}:compensation:${inverseIndex}`))
2770
+ })));
2771
+ const batch = deepFreezeValue({
2772
+ batchId,
2773
+ sliceId: direction === 'forward'
2774
+ ? sourceBatch.sliceId
2775
+ : `${sourceBatch.sliceId}:inverse`,
2776
+ artifactId: this.currentArtifactId,
2777
+ transactionId: this.currentTransactionId,
2778
+ origin: this.transactionOrigin(),
2779
+ kind: 'forward',
2780
+ channel: sourceBatch.channel,
2781
+ sharedDelivery: sourceBatch.sharedDelivery,
2782
+ deliveries,
2783
+ records: deepFreezeValue(deliveries.map((delivery) => delivery.record)),
2784
+ changes: deepFreezeValue(deliveries.map((delivery) => delivery.payload)),
2785
+ compensationBatchId: `${batchId}:compensation`
2786
+ });
2787
+ const requiredReadinessKeys = new Set(replayRecords.map(({ readinessKey }) => readinessKey));
2788
+ const state = {
2789
+ batch,
2790
+ requiredReadinessKeys,
2791
+ readyReadinessKeys: new Set(),
2792
+ delivered: false
2793
+ };
2794
+ batchStates.push(state);
2795
+ requiredReadinessKeys.forEach((readinessKey) => {
2796
+ const states = batchStatesByReadinessKey.get(readinessKey) ?? [];
2797
+ states.push(state);
2798
+ batchStatesByReadinessKey.set(readinessKey, states);
2799
+ });
2800
+ });
2801
+ this.configureHistoryReplayProgressiveSequence(history, direction, deliveredOrderedIds);
2802
+ const sharedState = {
2803
+ direction,
2804
+ ownsReplayEvidence: historyChanges.some((change) => change.shared !== undefined),
2805
+ batchStates: Object.freeze([...batchStates]),
2806
+ batchStateById: new Map(batchStates.map((state) => [state.batch.batchId, state])),
2807
+ batchStatesByReadinessKey: new Map([...batchStatesByReadinessKey].map(([readinessKey, states]) => [
2808
+ readinessKey,
2809
+ Object.freeze([...states])
2810
+ ]))
2811
+ };
2812
+ this.historyReplaySharedState = sharedState;
2813
+ this.currentSharedDeliveryBatches.push(...sharedState.batchStates.map(({ batch }) => batch));
53
2814
  }
54
- commitUndo() {
55
- // If changes are coming from Undo or Redo events, they should not push back to list again
56
- if (!this.isInUndo() && !this.isInRedo() && this.changes.length > 0) {
57
- this.undoStack.push(this.changes);
58
- this.changes = [];
59
- this.redoStack = [];
2815
+ flushNextReadyHistoryReplaySlice() {
2816
+ const sharedState = this.historyReplaySharedState;
2817
+ if (!sharedState)
2818
+ return 'none';
2819
+ const firstUndeliveredIndex = sharedState.batchStates.findIndex((state) => !state.delivered);
2820
+ if (firstUndeliveredIndex < 0)
2821
+ return 'none';
2822
+ const firstUndeliveredState = sharedState.batchStates[firstUndeliveredIndex];
2823
+ if (!firstUndeliveredState)
2824
+ return 'none';
2825
+ const isProgressive = this.activeDeliverySequence?.mode === 'progressive';
2826
+ if (!isProgressive &&
2827
+ firstUndeliveredState.batch.sharedDelivery !== 'immediate' &&
2828
+ !sharedState.batchStates
2829
+ .slice(firstUndeliveredIndex + 1)
2830
+ .some((state) => !state.delivered &&
2831
+ state.batch.sharedDelivery === 'immediate' &&
2832
+ state.readyReadinessKeys.size === state.requiredReadinessKeys.size)) {
2833
+ this.flushPendingHistoryReplayPublication();
2834
+ return 'none';
60
2835
  }
2836
+ const sliceId = firstUndeliveredState.batch.sliceId;
2837
+ let sliceEnd = firstUndeliveredIndex;
2838
+ while (sharedState.batchStates[sliceEnd + 1]?.batch.sliceId === sliceId) {
2839
+ sliceEnd += 1;
2840
+ }
2841
+ const states = sharedState.batchStates.slice(firstUndeliveredIndex, sliceEnd + 1);
2842
+ if (states.some((state) => state.readyReadinessKeys.size !== state.requiredReadinessKeys.size)) {
2843
+ return 'none';
2844
+ }
2845
+ const isFormalProgressiveSlice = isProgressive && this.activeDeliveryBoundaryBySliceId.has(sliceId);
2846
+ const activeSlice = isFormalProgressiveSlice
2847
+ ? this.activeDeliverySequence?.slices[this.nextDeliverySliceIndex]
2848
+ : undefined;
2849
+ if (isFormalProgressiveSlice &&
2850
+ (!activeSlice || activeSlice.sliceId !== sliceId)) {
2851
+ throw new Error(`Factory history replay delivery slice must follow sequence order: ${activeSlice?.sliceId ?? 'complete'}`);
2852
+ }
2853
+ const workItemKeys = new Set(this.sharedBatchPublicationWorkItemKeys(states.map(({ batch }) => batch)));
2854
+ const pendingDeliveryMode = this.pendingHistoryReplayPublicationBatches[0]?.sharedDelivery;
2855
+ const currentDeliveryMode = states[0]?.batch.sharedDelivery;
2856
+ if (this.pendingHistoryReplayPublicationBatches.length > 0 &&
2857
+ (pendingDeliveryMode !== currentDeliveryMode ||
2858
+ this.activeDeliverySequence?.batchPublications === false ||
2859
+ this.publicationWindowWouldExceedTarget(this.pendingHistoryReplayPublicationWorkItemKeys, [...workItemKeys]))) {
2860
+ this.flushPendingHistoryReplayPublication();
2861
+ }
2862
+ states.forEach((state) => {
2863
+ if (!this.deliverPreparedSharedBatch(state.batch)) {
2864
+ throw new Error(`Factory history replay batch could not be delivered: ${state.batch.batchId}`);
2865
+ }
2866
+ });
2867
+ this.pendingHistoryReplayPublicationBatches.push(...states.map(({ batch }) => batch));
2868
+ workItemKeys.forEach((workItemKey) => this.pendingHistoryReplayPublicationWorkItemKeys.add(workItemKey));
2869
+ const finalSlice = sharedState.batchStates.every((state) => state.delivered);
2870
+ if (this.shouldFlushPublicationWindow(this.pendingHistoryReplayPublicationWorkItemKeys, finalSlice)) {
2871
+ this.flushPendingHistoryReplayPublication();
2872
+ }
2873
+ if (isFormalProgressiveSlice) {
2874
+ this.nextDeliverySliceIndex += 1;
2875
+ }
2876
+ return {
2877
+ explicitBoundary: isFormalProgressiveSlice,
2878
+ workItemKeys: deepFreezeValue([...workItemKeys])
2879
+ };
2880
+ }
2881
+ flushPendingHistoryReplayPublication() {
2882
+ const batches = this.pendingHistoryReplayPublicationBatches.splice(0);
2883
+ this.pendingHistoryReplayPublicationWorkItemKeys.clear();
2884
+ if (batches.length === 0)
2885
+ return;
2886
+ const publication = this.createHistoryReplaySharedPublication(batches);
2887
+ this.queueSharedPublication(publication);
2888
+ this.flushSharedPublications();
2889
+ }
2890
+ markHistoryReplaySharedReady(sharedReplay) {
2891
+ const sharedState = this.historyReplaySharedState;
2892
+ if (!sharedState)
2893
+ return;
2894
+ sharedReplay.records.forEach(({ readinessKey }) => {
2895
+ const states = sharedState.batchStatesByReadinessKey.get(readinessKey) ?? [];
2896
+ states.forEach((state) => state.readyReadinessKeys.add(readinessKey));
2897
+ });
2898
+ }
2899
+ suppressHistoryReplayOwnerSharedEntries(entries) {
2900
+ entries.forEach((entry) => {
2901
+ entry.options.shared = undefined;
2902
+ entry.shared = undefined;
2903
+ });
2904
+ }
2905
+ historySharedReplay(history, direction) {
2906
+ const historyChanges = this.historyChanges(history);
2907
+ const deliveredRecordsByChange = historyChanges.map((change) => {
2908
+ if (!change.shared)
2909
+ return [];
2910
+ return change.shared.records.filter((record) => record.delivered && record.delivery && record.evidence);
2911
+ });
2912
+ return historyChanges.map((change, changeIndex) => {
2913
+ if (!change.shared)
2914
+ return;
2915
+ const deliveredRecords = deliveredRecordsByChange[changeIndex] ?? [];
2916
+ const outputCount = direction === 'forward' ? 1 : (change.inverseEvents?.length ?? 0);
2917
+ if (deliveredRecords.length === 0) {
2918
+ return deepFreezeValue(Array.from({ length: outputCount }, () => ({ suppress: true })));
2919
+ }
2920
+ const sourceRecords = direction === 'forward'
2921
+ ? deliveredRecords
2922
+ : [...deliveredRecords].reverse();
2923
+ return deepFreezeValue(Array.from({ length: outputCount }, (_, outputIndex) => {
2924
+ const records = sourceRecords.map((record) => ({
2925
+ readinessKey: this.historyReplayReadinessKey(record.evidence?.recordId ?? '', outputIndex),
2926
+ orderedIds: direction === 'forward'
2927
+ ? record.orderedIds
2928
+ : [...record.orderedIds].reverse(),
2929
+ payload: direction === 'forward'
2930
+ ? record.change
2931
+ : (record.inverseEvents?.[outputIndex]).payload
2932
+ }));
2933
+ const orderedIds = [];
2934
+ const seenOrderedIds = new Set();
2935
+ records.forEach((record) => record.orderedIds.forEach((orderedId) => {
2936
+ if (seenOrderedIds.has(orderedId))
2937
+ return;
2938
+ seenOrderedIds.add(orderedId);
2939
+ orderedIds.push(orderedId);
2940
+ }));
2941
+ return {
2942
+ name: change.shared?.name ?? '',
2943
+ sharedDelivery: change.options.sharedDelivery,
2944
+ orderedIds: deepFreezeValue(orderedIds),
2945
+ records: deepFreezeValue(records)
2946
+ };
2947
+ }));
2948
+ });
2949
+ }
2950
+ async replayHistoryProgressively(direction, yieldAfterSlice, options = {}) {
2951
+ if (this.isTransacting > 0 && this.activeOrigin === 'remote') {
2952
+ throw new Error(`Remote transaction cannot consume local ${direction === 'inverse' ? 'undo' : 'redo'} history`);
2953
+ }
2954
+ const sourceStack = direction === 'inverse' ? this.undoStack : this.redoStack;
2955
+ if (!sourceStack.length) {
2956
+ return;
2957
+ }
2958
+ if (this.isTransacting <= 0) {
2959
+ throw new Error(`Progressive ${direction === 'inverse' ? 'Undo' : 'Redo'} requires an active outer transaction`);
2960
+ }
2961
+ if (this.journal.length > 0 || this.nestedReplaySourceEvents) {
2962
+ throw new Error(`${direction === 'inverse' ? 'Undo' : 'Redo'} cannot join a non-empty transaction journal`);
2963
+ }
2964
+ const sourceHistory = sourceStack[sourceStack.length - 1];
2965
+ if (!sourceHistory)
2966
+ return;
2967
+ const maxItemsPerSlice = resolveCooperativeRenderMaxItemsPerSlice(options);
2968
+ const sourceChanges = this.historyChanges(sourceHistory);
2969
+ const lastChanges = sourceChanges.map(({ event }) => event);
2970
+ if (direction === 'inverse') {
2971
+ this.inUndo = true;
2972
+ updateUndoRedoStatus(UNDO.UNDO);
2973
+ }
2974
+ else {
2975
+ this.inRedo = true;
2976
+ updateUndoRedoStatus(UNDO.REDO);
2977
+ }
2978
+ try {
2979
+ this.ensureReplayTransactionId();
2980
+ this.nestedReplaySourceEvents = lastChanges;
2981
+ this.nestedReplaySourceHistory = sourceHistory;
2982
+ this.nestedReplayRestorationBatches = [];
2983
+ this.prepareHistoryReplaySharedState(sourceHistory, direction);
2984
+ const failures = await this.replayProgressively(lastChanges, direction, direction === 'inverse' ? 'undo' : 'redo', yieldAfterSlice, maxItemsPerSlice, this.nestedReplayRestorationBatches, this.historySharedReplay(sourceHistory, direction), direction === 'inverse'
2985
+ ? sourceChanges.map(({ inverseEvents }) => inverseEvents)
2986
+ : undefined);
2987
+ if (failures.length > 0) {
2988
+ throw new TransactionRollbackError(failures);
2989
+ }
2990
+ }
2991
+ catch (error) {
2992
+ this.rollbackOnly = true;
2993
+ this.rollbackFailure ?? (this.rollbackFailure = toReplayFailure(error));
2994
+ throw error;
2995
+ }
2996
+ finally {
2997
+ updateUndoRedoStatus(UNDO.NONE);
2998
+ }
2999
+ }
3000
+ undoProgressively(yieldAfterSlice, options) {
3001
+ return this.replayHistoryProgressively('inverse', yieldAfterSlice, options);
3002
+ }
3003
+ redoProgressively(yieldAfterSlice, options) {
3004
+ return this.replayHistoryProgressively('forward', yieldAfterSlice, options);
61
3005
  }
62
3006
  undo() {
3007
+ if (this.isTransacting > 0 && this.activeOrigin === 'remote') {
3008
+ throw new Error('Remote transaction cannot consume local undo history');
3009
+ }
63
3010
  if (!this.undoStack.length) {
64
3011
  return;
65
3012
  }
66
- startTransaction();
3013
+ const hasOuterBoundary = this.isTransacting > 0;
3014
+ if (hasOuterBoundary &&
3015
+ (this.journal.length > 0 || this.nestedReplaySourceEvents)) {
3016
+ throw new Error('Undo cannot join a non-empty transaction journal');
3017
+ }
3018
+ const sourceHistory = this.undoStack[this.undoStack.length - 1];
3019
+ if (!sourceHistory)
3020
+ return;
3021
+ const sourceChanges = this.historyChanges(sourceHistory);
3022
+ const lastChanges = sourceChanges.map(({ event }) => event);
3023
+ let openedBoundary = false;
67
3024
  this.inUndo = true;
68
3025
  updateUndoRedoStatus(UNDO.UNDO);
69
- const lastChanges = this.undoStack.pop();
70
- for (let i = lastChanges.length - 1; i >= 0; i--) {
71
- const event = lastChanges[i];
72
- const undoEvent = JSON.parse(JSON.stringify(event));
73
- if (undoEvent.payload.undoType !== undefined) {
74
- undoEvent.type = undoEvent.payload.undoType;
3026
+ try {
3027
+ if (!hasOuterBoundary) {
3028
+ startTransaction();
3029
+ openedBoundary = true;
75
3030
  }
76
- if (undoEvent.payload.undoAction !== undefined) {
77
- undoEvent.payload.action = undoEvent.payload.undoAction;
3031
+ this.ensureReplayTransactionId();
3032
+ this.nestedReplaySourceEvents = lastChanges;
3033
+ this.nestedReplaySourceHistory = sourceHistory;
3034
+ this.nestedReplayRestorationBatches = [];
3035
+ this.prepareHistoryReplaySharedState(sourceHistory, 'inverse');
3036
+ const failures = this.replay(lastChanges, 'inverse', 'undo', this.nestedReplayRestorationBatches, this.historySharedReplay(sourceHistory, 'inverse'), sourceChanges.map(({ inverseEvents }) => inverseEvents));
3037
+ if (failures.length > 0) {
3038
+ throw new TransactionRollbackError(failures);
78
3039
  }
79
- if (undoEvent.payload.after !== undefined) {
80
- undoEvent.payload.after = undoEvent.payload.before;
3040
+ if (!hasOuterBoundary) {
3041
+ endTransaction();
3042
+ openedBoundary = false;
3043
+ }
3044
+ }
3045
+ catch (error) {
3046
+ const failure = toReplayFailure(error);
3047
+ if (hasOuterBoundary) {
3048
+ this.rollbackOnly = true;
3049
+ this.rollbackFailure ?? (this.rollbackFailure = failure);
3050
+ }
3051
+ else if (openedBoundary) {
3052
+ endTransaction({ outcome: 'rollback', failure });
3053
+ openedBoundary = false;
3054
+ }
3055
+ throw error;
3056
+ }
3057
+ finally {
3058
+ updateUndoRedoStatus(UNDO.NONE);
3059
+ if (!hasOuterBoundary) {
3060
+ this.journal = [];
3061
+ this.inUndo = false;
81
3062
  }
82
- publishEvent(undoEvent);
83
3063
  }
84
- this.redoStack.push(lastChanges);
85
- endTransaction();
86
- updateUndoRedoStatus(UNDO.NONE);
87
- this.changes = [];
88
- this.inUndo = false;
89
3064
  }
90
3065
  redo() {
3066
+ if (this.isTransacting > 0 && this.activeOrigin === 'remote') {
3067
+ throw new Error('Remote transaction cannot consume local redo history');
3068
+ }
91
3069
  if (!this.redoStack.length) {
92
3070
  return;
93
3071
  }
94
- startTransaction();
3072
+ const hasOuterBoundary = this.isTransacting > 0;
3073
+ if (hasOuterBoundary &&
3074
+ (this.journal.length > 0 || this.nestedReplaySourceEvents)) {
3075
+ throw new Error('Redo cannot join a non-empty transaction journal');
3076
+ }
3077
+ const sourceHistory = this.redoStack[this.redoStack.length - 1];
3078
+ if (!sourceHistory)
3079
+ return;
3080
+ const sourceChanges = this.historyChanges(sourceHistory);
3081
+ const lastChanges = sourceChanges.map(({ event }) => event);
3082
+ let openedBoundary = false;
95
3083
  this.inRedo = true;
96
3084
  updateUndoRedoStatus(UNDO.REDO);
97
- const lastChanges = this.redoStack.pop();
98
- for (const event of lastChanges) {
99
- const redoEvent = JSON.parse(JSON.stringify(event));
100
- publishEvent(redoEvent);
101
- }
102
- this.undoStack.push(lastChanges);
103
- endTransaction();
104
- updateUndoRedoStatus(UNDO.NONE);
105
- this.changes = [];
106
- this.inRedo = false;
3085
+ try {
3086
+ if (!hasOuterBoundary) {
3087
+ startTransaction();
3088
+ openedBoundary = true;
3089
+ }
3090
+ this.ensureReplayTransactionId();
3091
+ this.nestedReplaySourceEvents = lastChanges;
3092
+ this.nestedReplaySourceHistory = sourceHistory;
3093
+ this.nestedReplayRestorationBatches = [];
3094
+ this.prepareHistoryReplaySharedState(sourceHistory, 'forward');
3095
+ const failures = this.replay(lastChanges, 'forward', 'redo', this.nestedReplayRestorationBatches, this.historySharedReplay(sourceHistory, 'forward'));
3096
+ if (failures.length > 0) {
3097
+ throw new TransactionRollbackError(failures);
3098
+ }
3099
+ if (!hasOuterBoundary) {
3100
+ endTransaction();
3101
+ openedBoundary = false;
3102
+ }
3103
+ }
3104
+ catch (error) {
3105
+ const failure = toReplayFailure(error);
3106
+ if (hasOuterBoundary) {
3107
+ this.rollbackOnly = true;
3108
+ this.rollbackFailure ?? (this.rollbackFailure = failure);
3109
+ }
3110
+ else if (openedBoundary) {
3111
+ endTransaction({ outcome: 'rollback', failure });
3112
+ openedBoundary = false;
3113
+ }
3114
+ throw error;
3115
+ }
3116
+ finally {
3117
+ updateUndoRedoStatus(UNDO.NONE);
3118
+ if (!hasOuterBoundary) {
3119
+ this.journal = [];
3120
+ this.inRedo = false;
3121
+ }
3122
+ }
107
3123
  }
108
3124
  isInUndo() {
109
3125
  return this.inUndo;
110
3126
  }
3127
+ getUndoHistoryDepth() {
3128
+ return this.undoStack.length;
3129
+ }
111
3130
  isInRedo() {
112
3131
  return this.inRedo;
113
3132
  }
3133
+ dispose() {
3134
+ this.discardPendingImmediatePublication();
3135
+ this.pendingSharedPublications.length = 0;
3136
+ this.unacknowledgedSharedPublications.length = 0;
3137
+ this.publicationAcknowledgements.clear();
3138
+ this.transactionSettlementDepth = 0;
3139
+ this.publicationSequence = 0;
3140
+ this.journal = [];
3141
+ this.undoStack = [];
3142
+ this.redoStack = [];
3143
+ this.isTransacting = 0;
3144
+ this.inUndo = false;
3145
+ this.inRedo = false;
3146
+ this.applyingReplayEvent = false;
3147
+ this.restoringNestedReplay = false;
3148
+ this.nestedReplaySourceEvents = null;
3149
+ this.nestedReplaySourceHistory = null;
3150
+ this.nestedReplayRestorationBatches = [];
3151
+ this.actionId = 0;
3152
+ this.transactionId = 0;
3153
+ this.currentTransactionId = 0;
3154
+ this.currentArtifactId = '';
3155
+ this.activeOrigin = 'action';
3156
+ this.deliveryBatchSequence = 0;
3157
+ this.currentSharedDeliveryBatches = [];
3158
+ this.preparedSharedBatchRecords.clear();
3159
+ this.transactionEndDeliveryBatches = null;
3160
+ this.transactionEndBatchesBySlice.clear();
3161
+ this.transactionEndRecordsBySlice.clear();
3162
+ this.pendingProgressivePublicationRecords.length = 0;
3163
+ this.pendingProgressivePublicationWorkItemKeys.clear();
3164
+ this.pendingHistoryReplayPublicationBatches.length = 0;
3165
+ this.pendingHistoryReplayPublicationWorkItemKeys.clear();
3166
+ this.historyReplaySharedState = undefined;
3167
+ this.retainingHistoryReplaySharedEvidence = false;
3168
+ this.activeDeliverySequence = undefined;
3169
+ this.activeDeliverySliceByOrderedId.clear();
3170
+ this.activeDeliverySliceOrder.clear();
3171
+ this.activeDeliveryBoundaryBySliceId.clear();
3172
+ this.activeDeliveryOrderedIdOrder.clear();
3173
+ this.activeDeliverySequenceValidated = false;
3174
+ this.nextDeliverySliceIndex = 0;
3175
+ this.activeStagedDeliveryController = undefined;
3176
+ this.activeDeliveryHandle = undefined;
3177
+ this.activeDeliveryHandleToken = undefined;
3178
+ this.sharedEvidenceNotificationDepth = 0;
3179
+ this.rollbackOnly = false;
3180
+ this.rollbackFailure = undefined;
3181
+ }
3182
+ reset() {
3183
+ this.dispose();
3184
+ }
114
3185
  }
115
3186
  export default DataTransact;
116
3187
  //# sourceMappingURL=data-transact.js.map