@asyra/factory 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
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';
1
+ import { UNDO, measureBrowserDragPhase, MutationRecoveryError } from '@asyra/utils';
2
+ import { acknowledgeTransactionReplayApplied, applyEventBatchToSynchronousOwners, EventTypes, endTransaction, hasSynchronousEventBatchHandler, isDetachedTransactionValue, isTransactionReplayApplied, getTransactionReplayRestorationEvents, getFailedTransactionReplayRestorationEvents, publishEvent, publishEventsToObservers, publishEventToObservers, resolveCooperativeRenderMaxItemsPerSlice, runInTransactionReplayMode, startTransaction, userActionCompleted, wasTransactionReplayApplied, updateUndoRedoStatus } from '@asyra/reactive-events';
3
3
  import { pushFactoryOwnedBatchToSharedChannel, SharedDataChannelRegistry } from './shared-data-channel.js';
4
4
  import { TransactionRollbackError, TransactionValidationError } from './transaction.js';
5
5
  import { FactoryMutationBatchAcceptanceError } from './mutation-batch.js';
@@ -12,6 +12,7 @@ const BUILT_IN_INVERTIBLE_EVENT_TYPES = new Set([
12
12
  EventTypes.MOVE_ELEMENTS,
13
13
  EventTypes.CHANGE_SUBTREE,
14
14
  EventTypes.UPDATE_ELEMENT_DATA,
15
+ EventTypes.UPDATE_ELEMENT_PROPERTY_BINDINGS,
15
16
  EventTypes.ADD_PROPERTY,
16
17
  EventTypes.REMOVE_PROPERTY,
17
18
  EventTypes.UPDATE_PROPERTY,
@@ -26,8 +27,9 @@ const LOCAL_ONLY_COMPUTED_EVENT_TYPES = new Set([
26
27
  const MAX_CANONICAL_REPLAY_OWNER_BATCH_ITEMS = 32;
27
28
  const DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS = 512;
28
29
  const toDefinedMutationOptions = (options) => {
29
- if (!options)
30
+ if (!options) {
30
31
  return;
32
+ }
31
33
  const definedOptions = {};
32
34
  if (options.undoable !== undefined) {
33
35
  definedOptions.undoable = options.undoable;
@@ -41,8 +43,9 @@ const toDefinedMutationOptions = (options) => {
41
43
  if (options.sharedDelivery !== undefined) {
42
44
  definedOptions.sharedDelivery = options.sharedDelivery;
43
45
  }
44
- if (Object.keys(definedOptions).length === 0)
46
+ if (Object.keys(definedOptions).length === 0) {
45
47
  return;
48
+ }
46
49
  return definedOptions;
47
50
  };
48
51
  const toSharedChannelPayload = (payload, options) => {
@@ -97,11 +100,13 @@ const freezeReplayEvents = (events, trustedOwnerValues) => {
97
100
  if (payload && typeof payload === 'object') {
98
101
  ;
99
102
  ['changes', 'moves'].forEach((key) => {
100
- if (!(key in payload))
103
+ if (!(key in payload)) {
101
104
  return;
105
+ }
102
106
  const values = payload[key];
103
- if (!Array.isArray(values))
107
+ if (!Array.isArray(values)) {
104
108
  return;
109
+ }
105
110
  values.forEach((value) => {
106
111
  if (value && typeof value === 'object') {
107
112
  freezeTrustedValue(value);
@@ -131,16 +136,18 @@ const isPlainRecord = (value) => {
131
136
  return prototype === Object.prototype || prototype === null;
132
137
  };
133
138
  const areHistoryValuesEqual = (left, right) => {
134
- if (Object.is(left, right))
139
+ if (Object.is(left, right)) {
135
140
  return true;
141
+ }
136
142
  if (Array.isArray(left) || Array.isArray(right)) {
137
143
  return (Array.isArray(left) &&
138
144
  Array.isArray(right) &&
139
145
  left.length === right.length &&
140
146
  left.every((value, index) => areHistoryValuesEqual(value, right[index])));
141
147
  }
142
- if (!isPlainRecord(left) || !isPlainRecord(right))
148
+ if (!isPlainRecord(left) || !isPlainRecord(right)) {
143
149
  return false;
150
+ }
144
151
  const leftRecord = left;
145
152
  const rightRecord = right;
146
153
  const leftKeys = Reflect.ownKeys(leftRecord);
@@ -159,6 +166,8 @@ class DataTransact {
159
166
  this.journal = [];
160
167
  this.replaceLatestHistoryStages = new Map();
161
168
  this.preparedActionHistoryEntries = null;
169
+ this.historyGroups = new WeakMap();
170
+ this.notifyingHistoryGroup = false;
162
171
  this.undoStack = [];
163
172
  this.redoStack = [];
164
173
  this.isTransacting = 0;
@@ -183,6 +192,7 @@ class DataTransact {
183
192
  this.pendingImmediatePublicationEntries = [];
184
193
  this.pendingImmediatePublicationRecords = [];
185
194
  this.pendingImmediatePublicationWorkItemKeys = new Set();
195
+ this.nextImmediateDeliveryJournalIndex = 0;
186
196
  this.immediatePublicationToken = 0;
187
197
  this.scheduledImmediatePublicationToken = null;
188
198
  this.publicationSequence = 0;
@@ -220,6 +230,143 @@ class DataTransact {
220
230
  this.onSharedDeliveryBatch = callbacks?.onSharedDeliveryBatch;
221
231
  this.onSharedPublication = callbacks?.onSharedPublication;
222
232
  }
233
+ isTransactionBoundaryIdle() {
234
+ return (this.isTransacting === 0 &&
235
+ this.transactionSettlementDepth === 0 &&
236
+ !this.inUndo &&
237
+ !this.inRedo &&
238
+ !this.enrollingHistoryGroup &&
239
+ !this.notifyingHistoryGroup);
240
+ }
241
+ assertHistoryGroupBoundaryIdle() {
242
+ if (!this.isTransactionBoundaryIdle()) {
243
+ throw new Error('History group lifecycle requires an idle transaction owner');
244
+ }
245
+ this.assertSharedEvidenceCanonicalControlAllowed();
246
+ }
247
+ requireHistoryGroup(handle, open = true) {
248
+ const group = this.historyGroups.get(handle);
249
+ if (!group || (open && group.status.state !== 'open')) {
250
+ throw new Error('History group handle is foreign, closed or retired');
251
+ }
252
+ return group;
253
+ }
254
+ startHistoryGroup(options = {}) {
255
+ this.assertHistoryGroupBoundaryIdle();
256
+ const threshold = options.warningChangeCount;
257
+ if (threshold !== undefined &&
258
+ (!Number.isSafeInteger(threshold) || threshold <= 0)) {
259
+ throw new Error('History group warningChangeCount must be a positive safe integer');
260
+ }
261
+ const handle = Object.freeze({});
262
+ this.historyGroups.set(handle, {
263
+ members: [],
264
+ options: { ...options },
265
+ status: Object.freeze({
266
+ state: 'open',
267
+ memberCount: 0,
268
+ changeCount: 0,
269
+ warningReached: false
270
+ })
271
+ });
272
+ return handle;
273
+ }
274
+ getHistoryGroupStatus(handle) {
275
+ return this.requireHistoryGroup(handle, false).status;
276
+ }
277
+ notifyHistoryGroup(group) {
278
+ this.notifyingHistoryGroup = true;
279
+ try {
280
+ group.options.onChange?.(group.status);
281
+ }
282
+ catch {
283
+ // Advisory observers cannot change a committed outcome.
284
+ }
285
+ finally {
286
+ this.notifyingHistoryGroup = false;
287
+ }
288
+ }
289
+ withHistoryGroup(handle, runMember) {
290
+ this.assertHistoryGroupBoundaryIdle();
291
+ const group = this.requireHistoryGroup(handle);
292
+ const before = group.status;
293
+ this.enrollingHistoryGroup = group;
294
+ try {
295
+ return runMember();
296
+ }
297
+ finally {
298
+ this.enrollingHistoryGroup = undefined;
299
+ if (group.status !== before) {
300
+ this.notifyHistoryGroup(group);
301
+ }
302
+ }
303
+ }
304
+ createGroupedHistory(members) {
305
+ const sourceBatches = [];
306
+ const sourceSliceIds = new Map();
307
+ const slices = [];
308
+ members.forEach((member, memberIndex) => {
309
+ const batches = this.orderHistorySourceBatchesByDeliverySequence(member, this.historySourceBatches(this.deliveredHistoryRecords(member)));
310
+ const memberSlices = new Map();
311
+ let atomicSliceId;
312
+ batches.forEach((batch) => {
313
+ const sourceSliceId = `${memberIndex}:${batch.sliceId}`;
314
+ const isAtomicMemberBatch = !member.progressiveDeliverySequence &&
315
+ batch.sharedDelivery === 'transaction-end';
316
+ if (isAtomicMemberBatch) {
317
+ atomicSliceId ?? (atomicSliceId = sourceSliceId);
318
+ }
319
+ else {
320
+ atomicSliceId = undefined;
321
+ }
322
+ const sliceId = atomicSliceId ?? sourceSliceId;
323
+ sourceSliceIds.set(batch.batchId, sliceId);
324
+ const ids = memberSlices.get(sliceId) ?? [];
325
+ ids.push(...batch.deliveries.map(({ deliveryId }) => deliveryId));
326
+ memberSlices.set(sliceId, ids);
327
+ sourceBatches.push(batch);
328
+ });
329
+ memberSlices.forEach((orderedIds, sliceId) => slices.push({ sliceId, orderedIds }));
330
+ });
331
+ return {
332
+ // Reuse immutable owner evidence. Only the index of references is joined.
333
+ entries: members.flatMap((member) => member.entries),
334
+ sourceBatches: Object.freeze(sourceBatches),
335
+ sourceSliceIds,
336
+ ...(slices.length > 0
337
+ ? {
338
+ progressiveDeliverySequence: deepFreezeValue({
339
+ mode: 'progressive',
340
+ ...(members.some((member) => member.progressiveDeliverySequence?.batchPublications ===
341
+ false)
342
+ ? { batchPublications: false }
343
+ : {}),
344
+ slices
345
+ })
346
+ }
347
+ : {})
348
+ };
349
+ }
350
+ endHistoryGroup(handle) {
351
+ this.assertHistoryGroupBoundaryIdle();
352
+ const group = this.requireHistoryGroup(handle);
353
+ const history = this.createGroupedHistory(group.members);
354
+ group.members = [];
355
+ group.status = Object.freeze({ ...group.status, state: 'closed' });
356
+ if (group.status.memberCount > 0) {
357
+ this.undoStack.push(history);
358
+ this.redoStack = [];
359
+ this.actionId += 1;
360
+ this.onUserActionCompleted?.({
361
+ actionId: this.actionId,
362
+ changeCount: group.status.changeCount,
363
+ timestamp: Date.now()
364
+ });
365
+ }
366
+ this.notifyHistoryGroup(group);
367
+ group.options = {};
368
+ return group.status;
369
+ }
223
370
  start(origin) {
224
371
  if (this.sharedEvidenceNotificationDepth > 0) {
225
372
  throw new Error('Factory shared evidence observers cannot start a canonical transaction');
@@ -235,6 +382,7 @@ class DataTransact {
235
382
  }
236
383
  this.activeOrigin = origin ?? 'action';
237
384
  this.journal = [];
385
+ this.nextImmediateDeliveryJournalIndex = 0;
238
386
  this.replaceLatestHistoryStages.clear();
239
387
  this.preparedActionHistoryEntries = null;
240
388
  this.pendingImmediatePublicationEntries.length = 0;
@@ -399,12 +547,30 @@ class DataTransact {
399
547
  recordedEntries.some((entry) => entry.source === 'action')) {
400
548
  throw new Error('Nested undo or redo cannot accept a new action mutation');
401
549
  }
402
- const immediateEntries = this.applyingReplayEvent && this.retainingHistoryReplaySharedEvidence
403
- ? []
404
- : recordedEntries.filter((entry) => entry.shared && entry.options.sharedDelivery === 'immediate');
405
- this.deliverSharedEntries(immediateEntries, immediateEntries.length > 0
406
- ? `${this.currentArtifactId}:owner-batch:${journalStart}`
407
- : undefined);
550
+ let lastImmediateEntry;
551
+ for (const entry of recordedEntries) {
552
+ if (entry.shared && entry.options.sharedDelivery === 'immediate') {
553
+ lastImmediateEntry = entry;
554
+ }
555
+ }
556
+ const immediateEntries = [];
557
+ if (lastImmediateEntry &&
558
+ !(this.applyingReplayEvent && this.retainingHistoryReplaySharedEvidence)) {
559
+ // Immediate delivery is an ordered journal frontier, not a priority lane.
560
+ // Earlier deferred writes may be prerequisites of this completed mutation.
561
+ for (let index = this.nextImmediateDeliveryJournalIndex; index <= lastImmediateEntry.index; index += 1) {
562
+ const entry = this.journal[index];
563
+ if (!entry?.shared) {
564
+ continue;
565
+ }
566
+ if (entry.shared.records.some((record) => !record.delivered)) {
567
+ entry.options.sharedDelivery = 'immediate';
568
+ immediateEntries.push(entry);
569
+ }
570
+ }
571
+ this.nextImmediateDeliveryJournalIndex = lastImmediateEntry.index + 1;
572
+ }
573
+ this.deliverSharedEntries(immediateEntries);
408
574
  this.queueImmediatePublicationEntries(immediateEntries.filter((entry) => entry.shared?.records.some((record) => record.delivered)));
409
575
  return recordedEntries.length > 0 ? deliveryHandle : null;
410
576
  }
@@ -419,14 +585,17 @@ class DataTransact {
419
585
  }
420
586
  stageReplaceLatestHistory(events, journalIndexes) {
421
587
  const firstEvent = events[0];
422
- if (!firstEvent)
588
+ if (!firstEvent) {
423
589
  return;
590
+ }
424
591
  const history = firstEvent.options?.history;
425
592
  const candidate = firstEvent.historyCandidate;
426
- if (!history && !candidate)
593
+ if (!history && !candidate) {
427
594
  return;
428
- if (history?.mode !== 'replace-latest' || !candidate)
595
+ }
596
+ if (history?.mode !== 'replace-latest' || !candidate) {
429
597
  return;
598
+ }
430
599
  let stage = this.replaceLatestHistoryStages.get(history.key);
431
600
  if (!stage) {
432
601
  stage = {
@@ -473,8 +642,9 @@ class DataTransact {
473
642
  evidence.sharedRecords.length === 0) {
474
643
  throw new Error(`Factory mutation delivery evidence ${eventIndex} requires at least one shared record`);
475
644
  }
476
- if (!evidence.sharedRecords)
645
+ if (!evidence.sharedRecords) {
477
646
  return;
647
+ }
478
648
  const firstOccurrences = [];
479
649
  const seenOccurrences = new Set();
480
650
  evidence.sharedRecords.forEach((record, recordIndex) => {
@@ -606,8 +776,9 @@ class DataTransact {
606
776
  const firstEvent = stage.firstEventsByKey.get(eventKey);
607
777
  const latestEvent = stage.latestEventsByKey.get(eventKey);
608
778
  const payload = this.mergeReplaceLatestHistoryPayload(firstEvent.payload, latestEvent.payload);
609
- if (!payload)
779
+ if (!payload) {
610
780
  return;
781
+ }
611
782
  const { history: _history, ...options } = latestEvent.options ?? {};
612
783
  entries.push(this.createJournalEntry({
613
784
  type: latestEvent.type,
@@ -621,8 +792,9 @@ class DataTransact {
621
792
  }
622
793
  prepareReplaceLatestHistorySourceBatches(entries) {
623
794
  const sharedEntries = entries.filter((entry) => entry.shared);
624
- if (sharedEntries.length === 0)
795
+ if (sharedEntries.length === 0) {
625
796
  return;
797
+ }
626
798
  const unsupportedEntry = sharedEntries.find((entry) => entry.options.sharedDelivery !== 'immediate');
627
799
  if (unsupportedEntry) {
628
800
  throw new Error('Factory replace-latest shared History requires immediate delivery');
@@ -654,8 +826,9 @@ class DataTransact {
654
826
  entries.push(entry);
655
827
  return;
656
828
  }
657
- if (emittedKeys.has(history.key))
829
+ if (emittedKeys.has(history.key)) {
658
830
  return;
831
+ }
659
832
  emittedKeys.add(history.key);
660
833
  const materialized = this.materializeReplaceLatestHistoryStage(stage, nextSyntheticIndex);
661
834
  nextSyntheticIndex += materialized.length;
@@ -749,11 +922,13 @@ class DataTransact {
749
922
  return;
750
923
  }
751
924
  const sharedInverseEvents = entry.shared?.inverseEvents;
752
- if (sharedInverseEvents?.length !== 1)
925
+ if (sharedInverseEvents?.length !== 1) {
753
926
  return;
927
+ }
754
928
  const inverseEvent = sharedInverseEvents[0];
755
- if (!inverseEvent)
929
+ if (!inverseEvent) {
756
930
  return;
931
+ }
757
932
  const inversePayload = inverseEvent.payload;
758
933
  const recordPayload = record.change;
759
934
  let projectedCollection;
@@ -801,8 +976,9 @@ class DataTransact {
801
976
  })
802
977
  };
803
978
  }
804
- if (!projectedCollection)
979
+ if (!projectedCollection) {
805
980
  return;
981
+ }
806
982
  return freezeReplayEvents([
807
983
  {
808
984
  ...inverseEvent,
@@ -833,11 +1009,13 @@ class DataTransact {
833
1009
  }
834
1010
  createForwardSharedDelivery({ entry, record }, batchId) {
835
1011
  const shared = entry.shared;
836
- if (!shared)
1012
+ if (!shared) {
837
1013
  return;
1014
+ }
838
1015
  const evidence = record.evidence;
839
- if (!evidence)
1016
+ if (!evidence) {
840
1017
  return;
1018
+ }
841
1019
  return deepFreezeValue({
842
1020
  deliveryId: evidence.deliveryId,
843
1021
  artifactId: this.currentArtifactId,
@@ -959,13 +1137,15 @@ class DataTransact {
959
1137
  return this.activeDeliverySequence.slices.flatMap(({ sliceId }) => recordsBySlice.get(sliceId) ?? []);
960
1138
  }
961
1139
  deliverySliceIdForRecord({ entry, record }) {
962
- if (entry.options.sharedDelivery === 'immediate')
963
- return;
1140
+ if (entry.options.sharedDelivery === 'immediate') {
1141
+ return `${this.currentArtifactId}:immediate:${this.immediatePublicationToken}`;
1142
+ }
964
1143
  if (this.activeDeliverySequence?.mode === 'atomic') {
965
1144
  return this.activeDeliverySequence.slices[0]?.sliceId;
966
1145
  }
967
- if (this.activeDeliverySequence?.mode !== 'progressive')
1146
+ if (this.activeDeliverySequence?.mode !== 'progressive') {
968
1147
  return;
1148
+ }
969
1149
  if (record.orderedIds.length === 0) {
970
1150
  throw new Error(`Factory mutation shared record ${this.sharedRecordId(entry, record)} is not assigned to a progressive delivery slice`);
971
1151
  }
@@ -982,17 +1162,17 @@ class DataTransact {
982
1162
  }
983
1163
  return [...sliceIds][0];
984
1164
  }
985
- prepareSharedDeliveryBatches(entries, orderedRecords, deliverySliceIdOverride) {
1165
+ prepareSharedDeliveryBatches(entries, orderedRecords) {
986
1166
  const records = orderedRecords ?? this.sharedRecordRefs(entries);
987
1167
  const preparedBatches = [];
988
1168
  const seenBatchIds = new Set();
989
1169
  const deliverySliceIds = new Map();
990
1170
  records.forEach((recordRef) => {
991
1171
  const sliceId = recordRef.record.batch?.sliceId ??
992
- deliverySliceIdOverride ??
993
1172
  this.deliverySliceIdForRecord(recordRef);
994
- if (!sliceId)
1173
+ if (!sliceId) {
995
1174
  return;
1175
+ }
996
1176
  if (this.activeDeliverySequence &&
997
1177
  recordRef.entry.options.sharedDelivery !== 'immediate' &&
998
1178
  !this.activeDeliverySliceOrder.has(sliceId)) {
@@ -1068,8 +1248,9 @@ class DataTransact {
1068
1248
  deliverPreparedSharedBatch(batch) {
1069
1249
  const historyReplayState = this.historyReplaySharedState?.batchStateById.get(batch.batchId);
1070
1250
  if (historyReplayState) {
1071
- if (historyReplayState.delivered)
1251
+ if (historyReplayState.delivered) {
1072
1252
  return true;
1253
+ }
1073
1254
  if (historyReplayState.readyReadinessKeys.size !==
1074
1255
  historyReplayState.requiredReadinessKeys.size) {
1075
1256
  return false;
@@ -1077,8 +1258,9 @@ class DataTransact {
1077
1258
  this.sharedEvidenceNotificationDepth += 1;
1078
1259
  try {
1079
1260
  const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, batch.channel, batch.changes);
1080
- if (!delivered)
1261
+ if (!delivered) {
1081
1262
  return false;
1263
+ }
1082
1264
  historyReplayState.delivered = true;
1083
1265
  if (this.transactionOrigin() !== 'remote') {
1084
1266
  this.onSharedDeliveryBatch?.(batch);
@@ -1090,13 +1272,15 @@ class DataTransact {
1090
1272
  }
1091
1273
  }
1092
1274
  const records = (this.preparedSharedBatchRecords.get(batch.batchId) ?? []).filter(({ record }) => !record.delivered);
1093
- if (records.length === 0)
1275
+ if (records.length === 0) {
1094
1276
  return true;
1277
+ }
1095
1278
  this.sharedEvidenceNotificationDepth += 1;
1096
1279
  try {
1097
1280
  const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, batch.channel, batch.changes);
1098
- if (!delivered)
1281
+ if (!delivered) {
1099
1282
  return false;
1283
+ }
1100
1284
  records.forEach(({ record }) => {
1101
1285
  record.delivered = true;
1102
1286
  });
@@ -1109,8 +1293,8 @@ class DataTransact {
1109
1293
  this.sharedEvidenceNotificationDepth -= 1;
1110
1294
  }
1111
1295
  }
1112
- deliverSharedEntries(entries, deliverySliceIdOverride) {
1113
- this.prepareSharedDeliveryBatches(entries, undefined, deliverySliceIdOverride).forEach((batch) => this.deliverPreparedSharedBatch(batch));
1296
+ deliverSharedEntries(entries) {
1297
+ this.prepareSharedDeliveryBatches(entries).forEach((batch) => this.deliverPreparedSharedBatch(batch));
1114
1298
  }
1115
1299
  prepareTransactionEndDeliveryIndex() {
1116
1300
  if (this.transactionEndDeliveryBatches) {
@@ -1186,12 +1370,14 @@ class DataTransact {
1186
1370
  : [`delivery:${deliveryId}`]));
1187
1371
  }
1188
1372
  publicationWindowWouldExceedTarget(pendingWorkItemKeys, currentWorkItemKeys, maxItemsPerPublication = DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS) {
1189
- if (pendingWorkItemKeys.size === 0)
1373
+ if (pendingWorkItemKeys.size === 0) {
1190
1374
  return false;
1375
+ }
1191
1376
  let distinctCount = pendingWorkItemKeys.size;
1192
1377
  for (const workItemKey of currentWorkItemKeys) {
1193
- if (!pendingWorkItemKeys.has(workItemKey))
1378
+ if (!pendingWorkItemKeys.has(workItemKey)) {
1194
1379
  distinctCount += 1;
1380
+ }
1195
1381
  }
1196
1382
  return distinctCount > maxItemsPerPublication;
1197
1383
  }
@@ -1203,8 +1389,9 @@ class DataTransact {
1203
1389
  flushPendingProgressivePublication() {
1204
1390
  const records = this.pendingProgressivePublicationRecords.splice(0);
1205
1391
  this.pendingProgressivePublicationWorkItemKeys.clear();
1206
- if (records.length === 0)
1392
+ if (records.length === 0) {
1207
1393
  return;
1394
+ }
1208
1395
  this.queueSharedPublication(this.createSharedPublicationFromRecords(records));
1209
1396
  this.flushSharedPublications();
1210
1397
  }
@@ -1250,16 +1437,18 @@ class DataTransact {
1250
1437
  }
1251
1438
  }
1252
1439
  nextPublicationId() {
1440
+ this.publicationNamespace ?? (this.publicationNamespace = Array.from(globalThis.crypto.getRandomValues(new Uint32Array(4)), (value) => value.toString(16).padStart(8, '0')).join(''));
1253
1441
  this.publicationSequence += 1;
1254
- return `${this.currentTransactionId}:publication:${this.publicationSequence}`;
1442
+ return `${this.publicationNamespace}:${this.currentTransactionId}:publication:${this.publicationSequence}`;
1255
1443
  }
1256
1444
  createSharedPublication(entries, origin = this.transactionOrigin()) {
1257
1445
  return this.createSharedPublicationFromRecords(this.sharedRecordRefs(entries), origin);
1258
1446
  }
1259
1447
  createSharedPublicationFromRecords(records, origin = this.transactionOrigin()) {
1260
1448
  return measureBrowserDragPhase('factory:create-shared-publication', () => {
1261
- if (this.transactionOrigin() === 'remote' || origin === 'remote')
1449
+ if (this.transactionOrigin() === 'remote' || origin === 'remote') {
1262
1450
  return;
1451
+ }
1263
1452
  const publishableRecords = records.filter(({ record }) => {
1264
1453
  if (!record.delivered || record.publicationId !== undefined) {
1265
1454
  return false;
@@ -1270,16 +1459,19 @@ class DataTransact {
1270
1459
  const seenBatchIds = new Set();
1271
1460
  publishableRecords.forEach(({ record }) => {
1272
1461
  const batch = record.batch;
1273
- if (!batch || seenBatchIds.has(batch.batchId))
1462
+ if (!batch || seenBatchIds.has(batch.batchId)) {
1274
1463
  return;
1464
+ }
1275
1465
  seenBatchIds.add(batch.batchId);
1276
1466
  batches.push(batch);
1277
1467
  });
1278
- if (batches.length === 0)
1468
+ if (batches.length === 0) {
1279
1469
  return;
1470
+ }
1280
1471
  const publication = this.createSharedPublicationFromBatches(batches, origin);
1281
- if (!publication)
1472
+ if (!publication) {
1282
1473
  return;
1474
+ }
1283
1475
  publishableRecords.forEach(({ record }) => {
1284
1476
  record.publicationId = publication.publicationId;
1285
1477
  record.compensationPublicationId = `${publication.publicationId}:compensation`;
@@ -1349,19 +1541,22 @@ class DataTransact {
1349
1541
  }
1350
1542
  createHistoryReplaySharedPublication(batches) {
1351
1543
  const state = this.historyReplaySharedState;
1352
- if (!state)
1544
+ if (!state) {
1353
1545
  return;
1546
+ }
1354
1547
  const publishableBatches = batches.filter((batch) => {
1355
1548
  const batchState = state.batchStateById.get(batch.batchId);
1356
1549
  return (batchState?.delivered === true && batchState.publicationId === undefined);
1357
1550
  });
1358
1551
  const publication = this.createSharedPublicationFromBatches(publishableBatches, this.transactionOrigin());
1359
- if (!publication)
1552
+ if (!publication) {
1360
1553
  return;
1554
+ }
1361
1555
  publishableBatches.forEach((batch) => {
1362
1556
  const batchState = state.batchStateById.get(batch.batchId);
1363
- if (!batchState)
1557
+ if (!batchState) {
1364
1558
  return;
1559
+ }
1365
1560
  batchState.publicationId = publication.publicationId;
1366
1561
  batchState.compensationPublicationId = `${publication.publicationId}:compensation`;
1367
1562
  });
@@ -1401,14 +1596,16 @@ class DataTransact {
1401
1596
  this.activeDeliverySequence.slices.length > 0 &&
1402
1597
  options.includeActiveSequence !== false &&
1403
1598
  (batches.length === 0 || activeSequenceBatches.length > 0)) {
1404
- if (batches.length === 0)
1599
+ if (batches.length === 0) {
1405
1600
  return this.activeDeliverySequence;
1601
+ }
1406
1602
  return measureBrowserDragPhase('factory:select-delivery-sequence-boundaries', () => {
1407
1603
  const seenSliceIds = new Set();
1408
1604
  const slices = [];
1409
1605
  activeSequenceBatches.forEach((batch) => {
1410
- if (seenSliceIds.has(batch.sliceId))
1606
+ if (seenSliceIds.has(batch.sliceId)) {
1411
1607
  return;
1608
+ }
1412
1609
  const boundary = this.activeDeliveryBoundaryBySliceId.get(batch.sliceId);
1413
1610
  if (!boundary) {
1414
1611
  throw new Error(`Factory mutation delivery slice is unknown: ${batch.sliceId}`);
@@ -1429,8 +1626,9 @@ class DataTransact {
1429
1626
  if (options.orderedIdsFromRecords) {
1430
1627
  const seenOrderedIds = seenSliceOrderedIds.get(batch.sliceId) ?? new Set();
1431
1628
  batch.records.forEach((record) => [...record.orderedIds].reverse().forEach((orderedId) => {
1432
- if (seenOrderedIds.has(orderedId))
1629
+ if (seenOrderedIds.has(orderedId)) {
1433
1630
  return;
1631
+ }
1434
1632
  seenOrderedIds.add(orderedId);
1435
1633
  orderedIds.push(orderedId);
1436
1634
  }));
@@ -1456,16 +1654,18 @@ class DataTransact {
1456
1654
  if (this.activeDeliverySequence?.mode === 'progressive') {
1457
1655
  return this.activeDeliverySequence;
1458
1656
  }
1459
- if (this.activeDeliverySequence?.batchPublications !== false)
1657
+ if (this.activeDeliverySequence?.batchPublications !== false) {
1460
1658
  return;
1659
+ }
1461
1660
  const deliveryIdsBySlice = new Map();
1462
1661
  this.currentSharedDeliveryBatches.forEach((batch) => {
1463
1662
  const deliveryIds = deliveryIdsBySlice.get(batch.sliceId) ?? [];
1464
1663
  deliveryIds.push(...batch.deliveries.map((delivery) => delivery.deliveryId));
1465
1664
  deliveryIdsBySlice.set(batch.sliceId, deliveryIds);
1466
1665
  });
1467
- if (deliveryIdsBySlice.size === 0)
1666
+ if (deliveryIdsBySlice.size === 0) {
1468
1667
  return;
1668
+ }
1469
1669
  return deepFreezeValue({
1470
1670
  mode: 'progressive',
1471
1671
  batchPublications: false,
@@ -1476,19 +1676,22 @@ class DataTransact {
1476
1676
  });
1477
1677
  }
1478
1678
  queueImmediatePublicationEntries(entries) {
1479
- if (entries.length === 0)
1679
+ if (entries.length === 0) {
1480
1680
  return;
1681
+ }
1481
1682
  this.pendingImmediatePublicationEntries.push(...entries);
1482
1683
  const token = this.immediatePublicationToken;
1483
- if (this.scheduledImmediatePublicationToken === token)
1684
+ if (this.scheduledImmediatePublicationToken === token) {
1484
1685
  return;
1686
+ }
1485
1687
  this.scheduledImmediatePublicationToken = token;
1486
1688
  queueMicrotask(() => {
1487
1689
  if (this.scheduledImmediatePublicationToken === token) {
1488
1690
  this.scheduledImmediatePublicationToken = null;
1489
1691
  }
1490
- if (token !== this.immediatePublicationToken)
1692
+ if (token !== this.immediatePublicationToken) {
1491
1693
  return;
1694
+ }
1492
1695
  this.queuePendingImmediatePublication();
1493
1696
  this.flushSharedPublications();
1494
1697
  });
@@ -1497,8 +1700,9 @@ class DataTransact {
1497
1700
  this.scheduledImmediatePublicationToken = null;
1498
1701
  this.immediatePublicationToken += 1;
1499
1702
  const entries = this.pendingImmediatePublicationEntries.splice(0);
1500
- if (entries.length === 0)
1703
+ if (entries.length === 0) {
1501
1704
  return;
1705
+ }
1502
1706
  const records = this.sharedRecordRefs(entries).filter(({ record }) => record.delivered && record.publicationId === undefined);
1503
1707
  const workItemKeys = this.sharedRecordPublicationWorkItemKeys(records);
1504
1708
  if (records.length > 0 &&
@@ -1518,8 +1722,9 @@ class DataTransact {
1518
1722
  flushPendingImmediatePublication() {
1519
1723
  const records = this.pendingImmediatePublicationRecords.splice(0);
1520
1724
  this.pendingImmediatePublicationWorkItemKeys.clear();
1521
- if (records.length === 0)
1725
+ if (records.length === 0) {
1522
1726
  return;
1727
+ }
1523
1728
  this.queueSharedPublication(this.createSharedPublicationFromRecords(records));
1524
1729
  this.flushSharedPublications();
1525
1730
  }
@@ -1531,8 +1736,9 @@ class DataTransact {
1531
1736
  this.pendingImmediatePublicationWorkItemKeys.clear();
1532
1737
  }
1533
1738
  queueSharedPublication(publication) {
1534
- if (!publication)
1739
+ if (!publication) {
1535
1740
  return;
1741
+ }
1536
1742
  this.pendingSharedPublications.push(publication);
1537
1743
  }
1538
1744
  queueUnacknowledgedSharedPublications() {
@@ -1549,8 +1755,9 @@ class DataTransact {
1549
1755
  }
1550
1756
  }
1551
1757
  flushSharedPublications() {
1552
- if (this.emittingSharedPublications)
1758
+ if (this.emittingSharedPublications) {
1553
1759
  return;
1760
+ }
1554
1761
  this.emittingSharedPublications = true;
1555
1762
  try {
1556
1763
  let publication;
@@ -1581,12 +1788,14 @@ class DataTransact {
1581
1788
  }
1582
1789
  }
1583
1790
  emitCompensationSharedDelivery({ entry, record }, eventName, payload, compensationIndex, batchId) {
1584
- if (this.transactionOrigin() === 'remote')
1791
+ if (this.transactionOrigin() === 'remote') {
1585
1792
  return;
1793
+ }
1586
1794
  const shared = entry.shared;
1587
1795
  const evidence = record.evidence;
1588
- if (!shared || !evidence)
1796
+ if (!shared || !evidence) {
1589
1797
  return;
1798
+ }
1590
1799
  const forwardDelivery = record.delivery;
1591
1800
  const deliveryId = forwardDelivery?.compensationDeliveryIds?.[compensationIndex] ??
1592
1801
  this.compensationDeliveryId(entry, record, compensationIndex);
@@ -1802,7 +2011,10 @@ class DataTransact {
1802
2011
  else {
1803
2012
  publishEvent(event);
1804
2013
  }
1805
- return isTransactionReplayApplied();
2014
+ return {
2015
+ applied: isTransactionReplayApplied(),
2016
+ restorationEvents: getTransactionReplayRestorationEvents()
2017
+ };
1806
2018
  });
1807
2019
  }
1808
2020
  finally {
@@ -1816,7 +2028,10 @@ class DataTransact {
1816
2028
  return runInTransactionReplayMode(mode, () => {
1817
2029
  applyEventBatchToSynchronousOwners(events);
1818
2030
  publishEventsToObservers(events);
1819
- return isTransactionReplayApplied();
2031
+ return {
2032
+ applied: isTransactionReplayApplied(),
2033
+ restorationEvents: getTransactionReplayRestorationEvents()
2034
+ };
1820
2035
  });
1821
2036
  }
1822
2037
  finally {
@@ -1824,8 +2039,9 @@ class DataTransact {
1824
2039
  }
1825
2040
  }
1826
2041
  replayStepSourceSliceId(step) {
1827
- if (!step.shared || 'suppress' in step.shared)
2042
+ if (!step.shared || 'suppress' in step.shared) {
1828
2043
  return;
2044
+ }
1829
2045
  const sliceIds = new Set();
1830
2046
  step.shared.records.forEach(({ readinessKey }) => {
1831
2047
  const states = this.historyReplaySharedState?.batchStatesByReadinessKey.get(readinessKey) ?? [];
@@ -1857,8 +2073,9 @@ class DataTransact {
1857
2073
  }
1858
2074
  for (let replayOutputIndex = 0; replayOutputIndex < replayEvents.length; replayOutputIndex += 1) {
1859
2075
  const replayEvent = replayEvents[replayOutputIndex];
1860
- if (!replayEvent)
2076
+ if (!replayEvent) {
1861
2077
  continue;
2078
+ }
1862
2079
  const shared = sharedOutputs?.[replayOutputIndex];
1863
2080
  let restorationEvents;
1864
2081
  const mustValidateReplayOutput = restorationBatches !== undefined ||
@@ -1894,8 +2111,9 @@ class DataTransact {
1894
2111
  }
1895
2112
  for (let stepIndex = 0; stepIndex < preparedSteps.length; stepIndex += 1) {
1896
2113
  const firstStep = preparedSteps[stepIndex];
1897
- if (!firstStep)
2114
+ if (!firstStep) {
1898
2115
  continue;
2116
+ }
1899
2117
  const firstEventType = firstStep.replayEvent.type;
1900
2118
  const firstSourceSliceId = this.replayStepSourceSliceId(firstStep);
1901
2119
  const mayUseOwnerBatch = hasSynchronousEventBatchHandler(firstEventType) &&
@@ -1918,38 +2136,53 @@ class DataTransact {
1918
2136
  const previousRetainingHistoryReplaySharedEvidence = this.retainingHistoryReplaySharedEvidence;
1919
2137
  const isRetainedHistoryReplay = this.historyReplaySharedState?.ownsReplayEvidence === true;
1920
2138
  this.retainingHistoryReplaySharedEvidence = isRetainedHistoryReplay;
2139
+ let restorationRecorded = false;
2140
+ const retainRestoration = (events) => {
2141
+ if (restorationRecorded) {
2142
+ return;
2143
+ }
2144
+ restorationRecorded = true;
2145
+ if (events) {
2146
+ restorationBatches?.push([...events]);
2147
+ }
2148
+ else {
2149
+ appliedSteps.forEach(({ restorationEvents }) => {
2150
+ if (restorationEvents) {
2151
+ restorationBatches?.push(restorationEvents);
2152
+ }
2153
+ });
2154
+ }
2155
+ };
1921
2156
  try {
1922
- const applied = appliedSteps.length > 1
2157
+ const result = appliedSteps.length > 1
1923
2158
  ? this.applyReplayEventBatch(appliedSteps.map(({ replayEvent }) => replayEvent), mode)
1924
2159
  : this.applyReplayEvent(firstStep.replayEvent, mode);
1925
2160
  const recordedEntries = this.journal.slice(journalStart);
1926
2161
  if (isRetainedHistoryReplay) {
1927
2162
  this.suppressHistoryReplayOwnerSharedEntries(recordedEntries);
1928
2163
  }
1929
- if (applied) {
1930
- appliedSteps.forEach(({ restorationEvents }) => {
1931
- if (restorationEvents) {
1932
- restorationBatches?.push(restorationEvents);
2164
+ if (result.applied) {
2165
+ retainRestoration(result.restorationEvents);
2166
+ }
2167
+ // Successful replay settles retained shared evidence even when the local
2168
+ // owner already has the requested value. Only actual mutation needs rollback.
2169
+ if (isRetainedHistoryReplay) {
2170
+ appliedSteps.forEach(({ shared }) => {
2171
+ if (shared && !('suppress' in shared)) {
2172
+ this.markHistoryReplaySharedReady(shared);
1933
2173
  }
1934
2174
  });
1935
- if (isRetainedHistoryReplay) {
1936
- appliedSteps.forEach(({ shared }) => {
1937
- if (shared && !('suppress' in shared)) {
1938
- this.markHistoryReplaySharedReady(shared);
1939
- }
1940
- });
1941
- let settlement = this.flushNextReadyHistoryReplaySlice();
1942
- while (settlement !== 'none') {
1943
- hasPendingSlicePublication = true;
1944
- settlement.workItemKeys.forEach((workItemKey) => pendingSliceWorkItemKeys.add(workItemKey));
1945
- if (settlement.explicitBoundary ||
1946
- pendingSliceWorkItemKeys.size >= maxItemsPerSlice) {
1947
- hasPendingSlicePublication = false;
1948
- pendingSliceWorkItemKeys.clear();
1949
- yield;
1950
- }
1951
- settlement = this.flushNextReadyHistoryReplaySlice();
2175
+ let settlement = this.flushNextReadyHistoryReplaySlice();
2176
+ while (settlement !== 'none') {
2177
+ hasPendingSlicePublication = true;
2178
+ settlement.workItemKeys.forEach((workItemKey) => pendingSliceWorkItemKeys.add(workItemKey));
2179
+ if (settlement.explicitBoundary ||
2180
+ pendingSliceWorkItemKeys.size >= maxItemsPerSlice) {
2181
+ hasPendingSlicePublication = false;
2182
+ pendingSliceWorkItemKeys.clear();
2183
+ yield;
1952
2184
  }
2185
+ settlement = this.flushNextReadyHistoryReplaySlice();
1953
2186
  }
1954
2187
  }
1955
2188
  }
@@ -1958,11 +2191,7 @@ class DataTransact {
1958
2191
  this.suppressHistoryReplayOwnerSharedEntries(this.journal.slice(journalStart));
1959
2192
  }
1960
2193
  if (wasTransactionReplayApplied(error)) {
1961
- appliedSteps.forEach(({ restorationEvents }) => {
1962
- if (restorationEvents) {
1963
- restorationBatches?.push(restorationEvents);
1964
- }
1965
- });
2194
+ retainRestoration(getFailedTransactionReplayRestorationEvents(error));
1966
2195
  }
1967
2196
  failures.push(error);
1968
2197
  }
@@ -2037,8 +2266,9 @@ class DataTransact {
2037
2266
  }
2038
2267
  compensateDeliveredHistoryReplayBatches() {
2039
2268
  const sharedState = this.historyReplaySharedState;
2040
- if (!sharedState)
2269
+ if (!sharedState) {
2041
2270
  return [];
2271
+ }
2042
2272
  const failures = [];
2043
2273
  const acknowledgedCompensationBatches = [];
2044
2274
  [...sharedState.batchStates]
@@ -2239,8 +2469,9 @@ class DataTransact {
2239
2469
  this.pendingTransactionStatuses.push(payload);
2240
2470
  }
2241
2471
  flushStatuses() {
2242
- if (this.emittingTransactionStatuses)
2472
+ if (this.emittingTransactionStatuses) {
2243
2473
  return;
2474
+ }
2244
2475
  this.emittingTransactionStatuses = true;
2245
2476
  try {
2246
2477
  let payload;
@@ -2307,6 +2538,9 @@ class DataTransact {
2307
2538
  }
2308
2539
  settleRollback(failure, precedingFailures = []) {
2309
2540
  this.discardPendingImmediatePublication();
2541
+ if (failure?.cause instanceof MutationRecoveryError) {
2542
+ precedingFailures = [...precedingFailures, failure.cause];
2543
+ }
2310
2544
  if (this.nestedReplaySourceEvents) {
2311
2545
  this.restoringNestedReplay = true;
2312
2546
  let failures;
@@ -2333,6 +2567,11 @@ class DataTransact {
2333
2567
  return;
2334
2568
  }
2335
2569
  if (this.journal.length === 0) {
2570
+ if (precedingFailures.length) {
2571
+ const rollbackError = new TransactionRollbackError(precedingFailures);
2572
+ this.emitStatus('rollback-failed', failure, rollbackError);
2573
+ throw rollbackError;
2574
+ }
2336
2575
  this.emitStatus('discarded', failure);
2337
2576
  return;
2338
2577
  }
@@ -2418,6 +2657,26 @@ class DataTransact {
2418
2657
  return null;
2419
2658
  }
2420
2659
  const previousRedoStack = this.redoStack;
2660
+ const group = this.enrollingHistoryGroup;
2661
+ if (group) {
2662
+ this.redoStack = [];
2663
+ return {
2664
+ complete: () => {
2665
+ group.members.push(history);
2666
+ const changeCount = group.status.changeCount + committedChanges.length;
2667
+ group.status = Object.freeze({
2668
+ state: 'open',
2669
+ memberCount: group.status.memberCount + 1,
2670
+ changeCount,
2671
+ warningReached: group.options.warningChangeCount !== undefined &&
2672
+ changeCount >= group.options.warningChangeCount
2673
+ });
2674
+ },
2675
+ rollback: () => {
2676
+ this.redoStack = previousRedoStack;
2677
+ }
2678
+ };
2679
+ }
2421
2680
  this.undoStack.push(history);
2422
2681
  this.redoStack = [];
2423
2682
  return {
@@ -2526,8 +2785,9 @@ class DataTransact {
2526
2785
  .length
2527
2786
  ? this.createHistoryReplaySharedPublication(transactionEndBatches)
2528
2787
  : this.createSharedPublication(transactionEndEntries);
2529
- if (publication)
2788
+ if (publication) {
2530
2789
  sharedPublications.push(publication);
2790
+ }
2531
2791
  });
2532
2792
  }
2533
2793
  catch (error) {
@@ -2563,6 +2823,7 @@ class DataTransact {
2563
2823
  this.unacknowledgedSharedPublications.length = 0;
2564
2824
  this.publicationAcknowledgements.clear();
2565
2825
  this.journal = [];
2826
+ this.nextImmediateDeliveryJournalIndex = 0;
2566
2827
  this.replaceLatestHistoryStages.clear();
2567
2828
  this.preparedActionHistoryEntries = null;
2568
2829
  this.rollbackOnly = false;
@@ -2622,17 +2883,22 @@ class DataTransact {
2622
2883
  const seenBatchIds = new Set();
2623
2884
  records.forEach(({ record }) => {
2624
2885
  const batch = record.batch;
2625
- if (!batch || seenBatchIds.has(batch.batchId))
2886
+ if (!batch || seenBatchIds.has(batch.batchId)) {
2626
2887
  return;
2888
+ }
2627
2889
  seenBatchIds.add(batch.batchId);
2628
2890
  batches.push(batch);
2629
2891
  });
2630
2892
  return batches;
2631
2893
  }
2632
2894
  orderHistorySourceBatchesByDeliverySequence(history, batches) {
2895
+ if (history.sourceBatches) {
2896
+ return history.sourceBatches;
2897
+ }
2633
2898
  const sequence = history.progressiveDeliverySequence;
2634
- if (!sequence)
2899
+ if (!sequence) {
2635
2900
  return batches;
2901
+ }
2636
2902
  const batchesBySlice = new Map();
2637
2903
  batches.forEach((batch) => {
2638
2904
  const sliceBatches = batchesBySlice.get(batch.sliceId) ?? [];
@@ -2701,8 +2967,9 @@ class DataTransact {
2701
2967
  const sourceDeliveries = (direction === 'forward'
2702
2968
  ? sourceBatch.deliveries
2703
2969
  : [...sourceBatch.deliveries].reverse()).filter((delivery) => deliveredSourceIds.has(delivery.deliveryId));
2704
- if (sourceDeliveries.length === 0)
2970
+ if (sourceDeliveries.length === 0) {
2705
2971
  return;
2972
+ }
2706
2973
  const batchId = this.nextDeliveryBatchId();
2707
2974
  let replayRecordOccurrence = 0;
2708
2975
  const replayRecords = sourceDeliveries.flatMap((sourceDelivery) => {
@@ -2776,11 +3043,10 @@ class DataTransact {
2776
3043
  sharedDelivery: sourceBatch.sharedDelivery,
2777
3044
  compensationDeliveryIds: deepFreezeValue(record.inverseEvents.map((_event, inverseIndex) => `${record.deliveryId}:compensation:${inverseIndex}`))
2778
3045
  })));
3046
+ const sourceSliceId = history.sourceSliceIds?.get(sourceBatch.batchId) ?? sourceBatch.sliceId;
2779
3047
  const batch = deepFreezeValue({
2780
3048
  batchId,
2781
- sliceId: direction === 'forward'
2782
- ? sourceBatch.sliceId
2783
- : `${sourceBatch.sliceId}:inverse`,
3049
+ sliceId: direction === 'forward' ? sourceSliceId : `${sourceSliceId}:inverse`,
2784
3050
  artifactId: this.currentArtifactId,
2785
3051
  transactionId: this.currentTransactionId,
2786
3052
  origin: this.transactionOrigin(),
@@ -2822,14 +3088,17 @@ class DataTransact {
2822
3088
  }
2823
3089
  flushNextReadyHistoryReplaySlice() {
2824
3090
  const sharedState = this.historyReplaySharedState;
2825
- if (!sharedState)
3091
+ if (!sharedState) {
2826
3092
  return 'none';
3093
+ }
2827
3094
  const firstUndeliveredIndex = sharedState.batchStates.findIndex((state) => !state.delivered);
2828
- if (firstUndeliveredIndex < 0)
3095
+ if (firstUndeliveredIndex < 0) {
2829
3096
  return 'none';
3097
+ }
2830
3098
  const firstUndeliveredState = sharedState.batchStates[firstUndeliveredIndex];
2831
- if (!firstUndeliveredState)
3099
+ if (!firstUndeliveredState) {
2832
3100
  return 'none';
3101
+ }
2833
3102
  const isProgressive = this.activeDeliverySequence?.mode === 'progressive';
2834
3103
  if (!isProgressive &&
2835
3104
  firstUndeliveredState.batch.sharedDelivery !== 'immediate' &&
@@ -2889,16 +3158,18 @@ class DataTransact {
2889
3158
  flushPendingHistoryReplayPublication() {
2890
3159
  const batches = this.pendingHistoryReplayPublicationBatches.splice(0);
2891
3160
  this.pendingHistoryReplayPublicationWorkItemKeys.clear();
2892
- if (batches.length === 0)
3161
+ if (batches.length === 0) {
2893
3162
  return;
3163
+ }
2894
3164
  const publication = this.createHistoryReplaySharedPublication(batches);
2895
3165
  this.queueSharedPublication(publication);
2896
3166
  this.flushSharedPublications();
2897
3167
  }
2898
3168
  markHistoryReplaySharedReady(sharedReplay) {
2899
3169
  const sharedState = this.historyReplaySharedState;
2900
- if (!sharedState)
3170
+ if (!sharedState) {
2901
3171
  return;
3172
+ }
2902
3173
  sharedReplay.records.forEach(({ readinessKey }) => {
2903
3174
  const states = sharedState.batchStatesByReadinessKey.get(readinessKey) ?? [];
2904
3175
  states.forEach((state) => state.readyReadinessKeys.add(readinessKey));
@@ -2913,13 +3184,15 @@ class DataTransact {
2913
3184
  historySharedReplay(history, direction) {
2914
3185
  const historyChanges = this.historyChanges(history);
2915
3186
  const deliveredRecordsByChange = historyChanges.map((change) => {
2916
- if (!change.shared)
3187
+ if (!change.shared) {
2917
3188
  return [];
3189
+ }
2918
3190
  return change.shared.records.filter((record) => record.delivered && record.delivery && record.evidence);
2919
3191
  });
2920
3192
  return historyChanges.map((change, changeIndex) => {
2921
- if (!change.shared)
3193
+ if (!change.shared) {
2922
3194
  return;
3195
+ }
2923
3196
  const deliveredRecords = deliveredRecordsByChange[changeIndex] ?? [];
2924
3197
  const outputCount = direction === 'forward' ? 1 : (change.inverseEvents?.length ?? 0);
2925
3198
  if (deliveredRecords.length === 0) {
@@ -2941,8 +3214,9 @@ class DataTransact {
2941
3214
  const orderedIds = [];
2942
3215
  const seenOrderedIds = new Set();
2943
3216
  records.forEach((record) => record.orderedIds.forEach((orderedId) => {
2944
- if (seenOrderedIds.has(orderedId))
3217
+ if (seenOrderedIds.has(orderedId)) {
2945
3218
  return;
3219
+ }
2946
3220
  seenOrderedIds.add(orderedId);
2947
3221
  orderedIds.push(orderedId);
2948
3222
  }));
@@ -2970,8 +3244,9 @@ class DataTransact {
2970
3244
  throw new Error(`${direction === 'inverse' ? 'Undo' : 'Redo'} cannot join a non-empty transaction journal`);
2971
3245
  }
2972
3246
  const sourceHistory = sourceStack[sourceStack.length - 1];
2973
- if (!sourceHistory)
3247
+ if (!sourceHistory) {
2974
3248
  return;
3249
+ }
2975
3250
  const maxItemsPerSlice = resolveCooperativeRenderMaxItemsPerSlice(options);
2976
3251
  const sourceChanges = this.historyChanges(sourceHistory);
2977
3252
  const lastChanges = sourceChanges.map(({ event }) => event);
@@ -3012,6 +3287,9 @@ class DataTransact {
3012
3287
  return this.replayHistoryProgressively('forward', yieldAfterSlice, options);
3013
3288
  }
3014
3289
  undo() {
3290
+ if (this.enrollingHistoryGroup) {
3291
+ throw new Error('Cannot replay history inside a group member');
3292
+ }
3015
3293
  if (this.isTransacting > 0 && this.activeOrigin === 'remote') {
3016
3294
  throw new Error('Remote transaction cannot consume local undo history');
3017
3295
  }
@@ -3024,8 +3302,9 @@ class DataTransact {
3024
3302
  throw new Error('Undo cannot join a non-empty transaction journal');
3025
3303
  }
3026
3304
  const sourceHistory = this.undoStack[this.undoStack.length - 1];
3027
- if (!sourceHistory)
3305
+ if (!sourceHistory) {
3028
3306
  return;
3307
+ }
3029
3308
  const sourceChanges = this.historyChanges(sourceHistory);
3030
3309
  const lastChanges = sourceChanges.map(({ event }) => event);
3031
3310
  let openedBoundary = false;
@@ -3066,11 +3345,15 @@ class DataTransact {
3066
3345
  updateUndoRedoStatus(UNDO.NONE);
3067
3346
  if (!hasOuterBoundary) {
3068
3347
  this.journal = [];
3348
+ this.nextImmediateDeliveryJournalIndex = 0;
3069
3349
  this.inUndo = false;
3070
3350
  }
3071
3351
  }
3072
3352
  }
3073
3353
  redo() {
3354
+ if (this.enrollingHistoryGroup) {
3355
+ throw new Error('Cannot replay history inside a group member');
3356
+ }
3074
3357
  if (this.isTransacting > 0 && this.activeOrigin === 'remote') {
3075
3358
  throw new Error('Remote transaction cannot consume local redo history');
3076
3359
  }
@@ -3083,8 +3366,9 @@ class DataTransact {
3083
3366
  throw new Error('Redo cannot join a non-empty transaction journal');
3084
3367
  }
3085
3368
  const sourceHistory = this.redoStack[this.redoStack.length - 1];
3086
- if (!sourceHistory)
3369
+ if (!sourceHistory) {
3087
3370
  return;
3371
+ }
3088
3372
  const sourceChanges = this.historyChanges(sourceHistory);
3089
3373
  const lastChanges = sourceChanges.map(({ event }) => event);
3090
3374
  let openedBoundary = false;
@@ -3125,6 +3409,7 @@ class DataTransact {
3125
3409
  updateUndoRedoStatus(UNDO.NONE);
3126
3410
  if (!hasOuterBoundary) {
3127
3411
  this.journal = [];
3412
+ this.nextImmediateDeliveryJournalIndex = 0;
3128
3413
  this.inRedo = false;
3129
3414
  }
3130
3415
  }
@@ -3138,7 +3423,29 @@ class DataTransact {
3138
3423
  isInRedo() {
3139
3424
  return this.inRedo;
3140
3425
  }
3426
+ /** Full lifecycle reset; ordinary dispose/reset keep their legacy scope. */
3427
+ resetRuntime() {
3428
+ if (this.isTransacting !== 0 ||
3429
+ this.inUndo ||
3430
+ this.inRedo ||
3431
+ this.transactionSettlementDepth !== 0 ||
3432
+ this.emittingSharedPublications ||
3433
+ this.emittingTransactionStatuses ||
3434
+ this.sharedEvidenceNotificationDepth !== 0 ||
3435
+ this.applyingReplayEvent ||
3436
+ this.restoringNestedReplay) {
3437
+ throw new Error('Factory runtime cannot reset during active transaction or delivery settlement');
3438
+ }
3439
+ this.dispose();
3440
+ this.replaceLatestHistoryStages.clear();
3441
+ this.preparedActionHistoryEntries = null;
3442
+ this.pendingTransactionStatuses.length = 0;
3443
+ this.inverters.clear();
3444
+ this.validators.clear();
3445
+ }
3141
3446
  dispose() {
3447
+ this.historyGroups = new WeakMap();
3448
+ this.enrollingHistoryGroup = undefined;
3142
3449
  this.discardPendingImmediatePublication();
3143
3450
  this.pendingSharedPublications.length = 0;
3144
3451
  this.unacknowledgedSharedPublications.length = 0;
@@ -3146,6 +3453,7 @@ class DataTransact {
3146
3453
  this.transactionSettlementDepth = 0;
3147
3454
  this.publicationSequence = 0;
3148
3455
  this.journal = [];
3456
+ this.nextImmediateDeliveryJournalIndex = 0;
3149
3457
  this.undoStack = [];
3150
3458
  this.redoStack = [];
3151
3459
  this.isTransacting = 0;