@vrtmrz/livesync-commonlib 0.6.0 → 0.7.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.
Files changed (83) hide show
  1. package/README.md +29 -19
  2. package/dist/common/models/shared.definition.d.ts +10 -1
  3. package/dist/common/models/shared.definition.js +4 -3
  4. package/dist/events/coreEvents.d.ts +3 -0
  5. package/dist/events/coreEvents.js +2 -0
  6. package/dist/managers/EntryManager/EntryManager.d.ts +1 -1
  7. package/dist/managers/EntryManager/EntryManager.js +2 -2
  8. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +1 -1
  9. package/dist/managers/EntryManager/EntryManagerImpls.js +4 -4
  10. package/dist/managers/StorageEventManager/admission.d.ts +1 -0
  11. package/dist/managers/StorageEventManager/admission.js +5 -1
  12. package/dist/managers/StorageEventManager.d.ts +2 -0
  13. package/dist/managers/StorageEventManager.js +1 -0
  14. package/dist/pouchdb/LiveSyncLocalDB.d.ts +1 -1
  15. package/dist/pouchdb/LiveSyncLocalDB.js +2 -2
  16. package/dist/pouchdb/encryption.policy.js +2 -1
  17. package/dist/replication/LiveSyncAbstractReplicator.d.ts +7 -0
  18. package/dist/replication/LiveSyncAbstractReplicator.js +5 -2
  19. package/dist/replication/ReplicatorInstance.d.ts +3 -0
  20. package/dist/replication/ReplicatorProvider.d.ts +23 -2
  21. package/dist/replication/ReplicatorProvider.js +10 -0
  22. package/dist/replication/SyncParamsHandler.js +26 -25
  23. package/dist/replication/UnsupportedEncryptedDocumentFormatError.d.ts +13 -0
  24. package/dist/replication/UnsupportedEncryptedDocumentFormatError.js +28 -0
  25. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +17 -3
  26. package/dist/replication/couchdb/LiveSyncReplicator.js +265 -132
  27. package/dist/replication/index.d.ts +5 -2
  28. package/dist/replication/index.js +8 -0
  29. package/dist/replication/remoteTransportFailure.d.ts +24 -0
  30. package/dist/replication/remoteTransportFailure.js +80 -0
  31. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +1 -1
  32. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +2 -2
  33. package/dist/replication/trystero/TrysteroRpcRoom.d.ts +14 -0
  34. package/dist/replication/trystero/TrysteroRpcRoom.js +168 -0
  35. package/dist/replication/trystero/rpcCompat.d.ts +1 -0
  36. package/dist/replication/trystero/rpcCompat.js +15 -0
  37. package/dist/rpc/RpcRoom.d.ts +1 -0
  38. package/dist/rpc/RpcRoom.js +21 -9
  39. package/dist/rpc/RpcSession.d.ts +8 -13
  40. package/dist/rpc/RpcSession.js +14 -35
  41. package/dist/rpc/commonlibRpcRoom.d.ts +1 -0
  42. package/dist/rpc/commonlibRpcRoom.js +4 -0
  43. package/dist/rpc/errors.d.ts +9 -3
  44. package/dist/rpc/errors.js +13 -16
  45. package/dist/rpc/index.d.ts +10 -1
  46. package/dist/rpc/index.js +2 -1
  47. package/dist/rpc/pouchdb/RpcPouchDBProxy.d.ts +1 -1
  48. package/dist/rpc/pouchdb/RpcPouchDBServer.d.ts +1 -1
  49. package/dist/serviceFeatures/targetFilter.d.ts +3 -1
  50. package/dist/serviceFeatures/targetFilter.js +2 -2
  51. package/dist/services/base/IService.d.ts +9 -6
  52. package/dist/services/base/ReadinessEvaluator.d.ts +7 -6
  53. package/dist/services/base/ReadinessEvaluator.js +4 -2
  54. package/dist/services/base/RemoteConnection.d.ts +4 -0
  55. package/dist/services/base/RemoteService.d.ts +5 -3
  56. package/dist/services/base/RemoteService.js +85 -33
  57. package/dist/services/base/ReplicationService.d.ts +11 -2
  58. package/dist/services/base/ReplicationService.js +18 -7
  59. package/dist/services/base/ReplicationService.readiness.d.ts +14 -4
  60. package/dist/services/base/ReplicationService.readiness.js +29 -2
  61. package/dist/services/base/ReplicationService.typedReplication.d.ts +5 -2
  62. package/dist/services/base/ReplicationService.typedReplication.js +67 -6
  63. package/dist/services/base/ReplicationStaticsOwner.d.ts +18 -0
  64. package/dist/services/base/ReplicationStaticsOwner.js +33 -0
  65. package/dist/services/base/ReplicatorService.d.ts +2 -10
  66. package/dist/services/base/ReplicatorService.js +6 -3
  67. package/dist/services/base/VaultService.d.ts +1 -0
  68. package/dist/string_and_binary/chunks.d.ts +1 -1
  69. package/dist/string_and_binary/chunks.js +63 -50
  70. package/dist/worker/bg.worker.js +3 -1
  71. package/dist/worker/bg.worker.splitting.d.ts +1 -0
  72. package/dist/worker/bg.worker.splitting.js +42 -6
  73. package/dist/worker/bgWorker.d.ts +4 -0
  74. package/dist/worker/bgWorker.js +87 -57
  75. package/dist/worker/bgWorker.splitting.d.ts +2 -3
  76. package/dist/worker/bgWorker.splitting.js +48 -52
  77. package/dist/worker/universalTypes.d.ts +13 -1
  78. package/docs/development.md +69 -32
  79. package/docs/offline-scanner.md +14 -6
  80. package/docs/p2p-transport-lifecycle.md +2 -3
  81. package/docs/releasing.md +6 -5
  82. package/docs/storage-events-and-reflection.md +10 -3
  83. package/package.json +3 -2
@@ -1,6 +1,9 @@
1
+ import { promiseWithResolvers } from "octagonal-wheels/promises";
2
+ import { LOG_LEVEL_VERBOSE, Logger } from "../../common/logger.js";
1
3
  import {
2
4
  CAPABILITY_SUPPORT_KINDS,
3
5
  NO_INTERACTION,
6
+ REPLICATION_CANCELLED,
4
7
  REPLICATION_PROGRESS_PRESENTATIONS,
5
8
  isActiveReplicatorContextBoundToSetting,
6
9
  replicationBlocked,
@@ -13,6 +16,8 @@ class TypedReplicationCoordinator {
13
16
  }
14
17
  dependencies;
15
18
  oneShotInProgress = false;
19
+ continuousStopGeneration = 0;
20
+ cancelReadinessWaits = /* @__PURE__ */ new Set();
16
21
  /**
17
22
  * Execute a user-initiated finite role with the request's interaction authority.
18
23
  *
@@ -84,21 +89,72 @@ class TypedReplicationCoordinator {
84
89
  * recovery handler.
85
90
  */
86
91
  async startContinuous(request) {
92
+ const generation = this.continuousStopGeneration;
93
+ const isCancelled = () => generation !== this.continuousStopGeneration;
94
+ const observer = request.onStartSettled;
95
+ if (!observer) return await this.admitContinuous(request, isCancelled);
96
+ const settlement = promiseWithResolvers();
97
+ void settlement.promise.then(observer).catch((error) => Logger(error, LOG_LEVEL_VERBOSE));
98
+ try {
99
+ const admitted = await this.admitContinuous(
100
+ { ...request, onStartSettled: settlement.resolve },
101
+ isCancelled
102
+ );
103
+ if (admitted.status !== "completed") {
104
+ settlement.resolve({ status: admitted.status === "cancelled" ? "cancelled" : "failed" });
105
+ }
106
+ return admitted;
107
+ } catch (error) {
108
+ settlement.resolve({ status: "failed" });
109
+ throw error;
110
+ }
111
+ }
112
+ async admitContinuous(request, isCancelled) {
87
113
  if (request.interaction.kind !== NO_INTERACTION.kind) {
88
114
  return replicationBlocked("interaction-required");
89
115
  }
90
116
  const context = await this.acquireContext();
117
+ if (isCancelled()) {
118
+ return REPLICATION_CANCELLED;
119
+ }
91
120
  if ("status" in context) return context;
92
121
  const capability = context.provider.continuous;
93
122
  if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {
94
123
  return replicationBlocked(capability.reason);
95
124
  }
96
- const ready = await this.acquireReadyContext(false, context);
97
- if ("status" in ready) return ready;
125
+ const cancellation = promiseWithResolvers();
126
+ const cancel = () => cancellation.resolve(false);
127
+ this.cancelReadinessWaits.add(cancel);
128
+ let readiness;
129
+ try {
130
+ readiness = await Promise.race([
131
+ this.dependencies.checkReadiness(false, context.provider.readiness),
132
+ cancellation.promise
133
+ ]);
134
+ } catch (error) {
135
+ if (isCancelled()) {
136
+ return REPLICATION_CANCELLED;
137
+ }
138
+ throw error;
139
+ } finally {
140
+ this.cancelReadinessWaits.delete(cancel);
141
+ }
142
+ if (isCancelled()) {
143
+ return REPLICATION_CANCELLED;
144
+ }
145
+ if (readiness !== true) {
146
+ request.onStartSettled?.(
147
+ readiness === false ? { status: "failed" } : { status: "failed", networkFailure: readiness }
148
+ );
149
+ return replicationBlocked("not-ready");
150
+ }
98
151
  const setting = Object.freeze(asCopy(this.dependencies.currentSettings()));
99
152
  const admitted = await this.dependencies.replicatorService.runWithActiveReplicatorContext(
100
153
  async (activeContext) => {
101
- if (activeContext !== ready || !isActiveReplicatorContextBoundToSetting(activeContext, setting)) {
154
+ if (isCancelled()) {
155
+ return REPLICATION_CANCELLED;
156
+ }
157
+ if (activeContext !== context || !isActiveReplicatorContextBoundToSetting(activeContext, setting)) {
102
158
  return replicationBlocked("not-ready");
103
159
  }
104
160
  try {
@@ -118,6 +174,11 @@ class TypedReplicationCoordinator {
118
174
  * not a request to begin new remote work.
119
175
  */
120
176
  async stopActiveTransfer() {
177
+ this.continuousStopGeneration++;
178
+ for (const cancel of this.cancelReadinessWaits) {
179
+ cancel();
180
+ }
181
+ this.cancelReadinessWaits.clear();
121
182
  const context = await this.acquireContext();
122
183
  if ("status" in context) return context;
123
184
  const capability = context.provider.stopActiveTransfer;
@@ -162,10 +223,10 @@ class TypedReplicationCoordinator {
162
223
  if (context) return context;
163
224
  return this.dependencies.replicatorService.hasActiveReplicator() ? replicationBlocked("provider-not-composed") : replicationBlocked("no-active-replicator");
164
225
  }
165
- async acquireReadyContext(showMessage, contextOverride) {
166
- const context = contextOverride ?? await this.acquireContext();
226
+ async acquireReadyContext(showMessage) {
227
+ const context = await this.acquireContext();
167
228
  if ("status" in context) return context;
168
- if (!await this.dependencies.checkReadiness(showMessage, context.provider.readiness)) {
229
+ if (await this.dependencies.checkReadiness(showMessage, context.provider.readiness) !== true) {
169
230
  return replicationBlocked("not-ready");
170
231
  }
171
232
  return context;
@@ -0,0 +1,18 @@
1
+ import { type ReactiveValue } from "octagonal-wheels/dataobject/reactive";
2
+ import { type PublishedReplicationStatics, type ReplicationStatics } from "../../common/models/shared.definition.js";
3
+ /** A reactive source which accepts raw statistics and returns published values. */
4
+ export interface ReplicationStaticsSource {
5
+ get value(): PublishedReplicationStatics;
6
+ set value(value: ReplicationStatics);
7
+ onChanged: ReactiveValue<PublishedReplicationStatics>["onChanged"];
8
+ offChanged: ReactiveValue<PublishedReplicationStatics>["offChanged"];
9
+ }
10
+ /** Own the publication timestamp and initial state for replication statistics. */
11
+ export declare class ReplicationStaticsOwner {
12
+ private readonly state;
13
+ private readonly view;
14
+ readonly source: ReplicationStaticsSource;
15
+ constructor();
16
+ reset(): void;
17
+ private publish;
18
+ }
@@ -0,0 +1,33 @@
1
+ import { reactive, reactiveSource } from "octagonal-wheels/dataobject/reactive";
2
+ import {
3
+ DEFAULT_REPLICATION_STATICS
4
+ } from "../../common/models/shared.definition.js";
5
+ class ReplicationStaticsOwner {
6
+ state = reactiveSource(
7
+ Object.freeze({ ...DEFAULT_REPLICATION_STATICS })
8
+ );
9
+ view = reactive(() => this.state.value);
10
+ source;
11
+ constructor() {
12
+ const owner = this;
13
+ this.source = {
14
+ get value() {
15
+ return owner.state.value;
16
+ },
17
+ set value(value) {
18
+ owner.publish(value);
19
+ },
20
+ onChanged: (handler) => owner.view.onChanged(handler),
21
+ offChanged: (handler) => owner.view.offChanged(handler)
22
+ };
23
+ }
24
+ reset() {
25
+ this.state.value = Object.freeze({ ...DEFAULT_REPLICATION_STATICS });
26
+ }
27
+ publish(value) {
28
+ this.state.value = Object.freeze({ ...value, statsUpdatedAt: Date.now() });
29
+ }
30
+ }
31
+ export {
32
+ ReplicationStaticsOwner
33
+ };
@@ -28,9 +28,11 @@ export interface ReplicatorServiceDependencies {
28
28
  * readiness and replication dispatch.
29
29
  */
30
30
  export declare abstract class ReplicatorService<T extends ServiceContext = ServiceContext> extends ServiceBase<T> implements IReplicatorService {
31
+ #private;
31
32
  protected dependencies: ReplicatorServiceDependencies;
32
33
  readonly boundedRemoteActivityCount: import("octagonal-wheels/dataobject/reactive_v2").ReactiveSource<number>;
33
34
  readonly finiteReplicationActivityCount: import("octagonal-wheels/dataobject/reactive_v2").ReactiveSource<number>;
35
+ get replicationStatics(): import("./ReplicationStaticsOwner.js").ReplicationStaticsSource;
34
36
  _log: (msg: unknown, level?: import("octagonal-wheels/common/logger").LOG_LEVEL, key?: string) => void;
35
37
  private settingService;
36
38
  private databaseEventService;
@@ -117,14 +119,4 @@ export declare abstract class ReplicatorService<T extends ServiceContext = Servi
117
119
  * `ActiveReplicatorContext` before using a Replicator.
118
120
  */
119
121
  hasActiveReplicator(): boolean;
120
- replicationStatics: import("octagonal-wheels/dataobject/reactive_v2").ReactiveSource<{
121
- sent: number;
122
- arrived: number;
123
- maxPullSeq: number;
124
- maxPushSeq: number;
125
- lastSyncPullSeq: number;
126
- lastSyncPushSeq: number;
127
- syncStatus: import("../../common/types.js").DatabaseConnectingStatus;
128
- couchDB?: import("../../common/models/shared.definition.js").CouchDBReplicationProgress;
129
- }>;
130
122
  }
@@ -4,7 +4,7 @@ import { createInstanceLogFunction } from "../lib/logUtils.js";
4
4
  import { UnresolvedErrorManager } from "./UnresolvedErrorManager.js";
5
5
  import { yieldMicrotask } from "octagonal-wheels/promises";
6
6
  import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "../../common/logger.js";
7
- import { DEFAULT_REPLICATION_STATICS } from "../../common/models/shared.definition.js";
7
+ import { ReplicationStaticsOwner } from "./ReplicationStaticsOwner.js";
8
8
  import { reactiveSource } from "octagonal-wheels/dataobject/reactive";
9
9
  import {
10
10
  runWithOptionalActivity
@@ -39,6 +39,10 @@ class ReplicatorService extends ServiceBase {
39
39
  dependencies;
40
40
  boundedRemoteActivityCount = reactiveSource(0);
41
41
  finiteReplicationActivityCount = reactiveSource(0);
42
+ #replicationStaticsOwner = new ReplicationStaticsOwner();
43
+ get replicationStatics() {
44
+ return this.#replicationStaticsOwner.source;
45
+ }
42
46
  _log = createInstanceLogFunction("ReplicatorService");
43
47
  settingService;
44
48
  databaseEventService;
@@ -217,7 +221,7 @@ class ReplicatorService extends ServiceBase {
217
221
  this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);
218
222
  return false;
219
223
  }
220
- this.replicationStatics.value = { ...DEFAULT_REPLICATION_STATICS };
224
+ this.#replicationStaticsOwner.reset();
221
225
  await yieldMicrotask();
222
226
  try {
223
227
  if (!await newReplicator.initializeDatabaseForReplication()) {
@@ -364,7 +368,6 @@ class ReplicatorService extends ServiceBase {
364
368
  hasActiveReplicator() {
365
369
  return this._activeReplicatorState.current !== void 0;
366
370
  }
367
- replicationStatics = reactiveSource({ ...DEFAULT_REPLICATION_STATICS });
368
371
  }
369
372
  export {
370
373
  ReplicatorService
@@ -39,6 +39,7 @@ export declare abstract class VaultService<T extends ServiceContext = ServiceCon
39
39
  */
40
40
  readonly isTargetFile: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(file: string | import("../../common/types.js").UXFileInfoStub, options?: {
41
41
  skipCaseCollisionCheck?: boolean;
42
+ internalFileEvent?: boolean;
42
43
  }) => Promise<boolean>>;
43
44
  /**
44
45
  * Check if a file is a target file for some extra feature
@@ -6,5 +6,5 @@ export declare function collectGenAll(strGen: AsyncGenerator<string, unknown, un
6
6
  export declare function concatGeneratedAll(strGen: AsyncGenerator<string, unknown, unknown> | Generator<string>): Promise<string>;
7
7
  export declare function splitPieces2V2(dataSrc: Blob, pieceSize: number, plainSplit: boolean, minimumChunkSize: number, filename?: string, useSegmenter?: boolean): Promise<(() => Generator<string>) | (() => AsyncGenerator<string>)>;
8
8
  export declare function splitPieces2(dataSrc: Blob, pieceSize: number, plainSplit: boolean, minimumChunkSize: number, filename?: string, useSegmenter?: boolean): Promise<(() => Generator<string>) | (() => AsyncGenerator<string>)>;
9
- export declare function splitPiecesRabinKarp(dataSrc: Blob, absoluteMaxPieceSize: number, doPlainSplit: boolean, minimumChunkSize: number, _filename?: string, _useSegmenter?: boolean): Promise<() => AsyncGenerator<string, void, unknown>>;
9
+ export declare function splitPiecesRabinKarp(dataSrc: Blob, absoluteMaxPieceSize: number, doPlainSplit: boolean, minimumChunkSize: number, _filename?: string, _useSegmenter?: boolean, signal?: AbortSignal): Promise<() => AsyncGenerator<string, void, unknown>>;
10
10
  export declare function splitPiecesRabinKarpOld(dataSrc: Blob, absoluteMaxPieceSize: number, doPlainSplit: boolean, minimumChunkSize: number, _filename?: string, _useSegmenter?: boolean): Promise<() => AsyncGenerator<string, void, unknown>>;
@@ -1,6 +1,8 @@
1
1
  function isTextBlob(blob) {
2
2
  return blob.type === "text/plain";
3
3
  }
4
+ import { iterateBlobBlocks } from "octagonal-wheels/binary/blob";
5
+ import { concatUInt8Array } from "octagonal-wheels/binary/typedArray";
4
6
  import { LOG_LEVEL_VERBOSE, Logger } from "../common/logger.js";
5
7
  import { arrayBufferToBase64Single, readString } from "./convert.js";
6
8
  import { wrapByDefault } from "../common/utils.js";
@@ -384,7 +386,7 @@ async function splitPieces2(dataSrc, pieceSize, plainSplit, minimumChunkSize, fi
384
386
  } while (i < size);
385
387
  };
386
388
  }
387
- async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit, minimumChunkSize, _filename, _useSegmenter) {
389
+ async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit, minimumChunkSize, _filename, _useSegmenter, signal) {
388
390
  let plainSplit = doPlainSplit || isTextBlob(dataSrc);
389
391
  const dataSize = dataSrc.size;
390
392
  let chunkUnitPlain = 64;
@@ -417,66 +419,77 @@ async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit,
417
419
  const windowSize = 48;
418
420
  const hashModulus = avgChunkSize;
419
421
  const boundaryPattern = 1;
420
- const PRIME = 31;
421
- let P_pow_w = 1;
422
+ const prime = 31;
423
+ let outgoingByteWeight = 1;
422
424
  for (let i = 0; i < windowSize - 1; i++) {
423
- P_pow_w = Math.imul(P_pow_w, PRIME);
425
+ outgoingByteWeight = Math.imul(outgoingByteWeight, prime);
424
426
  }
425
- const buffer = new Uint8Array(await dataSrc.arrayBuffer());
426
- let pos = 0;
427
- let hash = 0;
428
- let start = 0;
429
427
  const isText = isTextBlob(dataSrc);
430
- const length = buffer.length;
431
- return async function* piecesBlob() {
432
- while (pos < length) {
433
- const byte = buffer[pos];
434
- if (pos >= windowSize) {
435
- const oldByte = buffer[pos - windowSize];
436
- const oldByteTerm = Math.imul(oldByte, P_pow_w);
437
- hash = hash - oldByteTerm | 0;
438
- hash = Math.imul(hash, PRIME);
439
- hash = hash + byte | 0;
440
- } else {
441
- hash = Math.imul(hash, PRIME);
442
- hash = hash + byte | 0;
443
- }
444
- const currentChunkSize = pos - start + 1;
445
- let isBoundaryCandidate = false;
446
- if (currentChunkSize >= minChunkSize) {
447
- if ((hash >>> 0) % hashModulus === boundaryPattern) {
448
- isBoundaryCandidate = true;
449
- }
428
+ const readBlockBytes = 1024 * 1024;
429
+ async function* readChunks() {
430
+ if (dataSize === 0 || signal?.aborted) {
431
+ return;
432
+ }
433
+ const previousWindow = new Uint8Array(windowSize);
434
+ const pendingParts = [];
435
+ let remainingBytes = dataSize;
436
+ let hash = 0;
437
+ let chunkSize = 0;
438
+ function isBoundaryCandidate() {
439
+ return chunkSize >= maxChunkSize || chunkSize >= minChunkSize && (hash >>> 0) % hashModulus === boundaryPattern;
440
+ }
441
+ function finishChunk(lastPart) {
442
+ if (pendingParts.length === 0) {
443
+ return lastPart;
450
444
  }
451
- if (currentChunkSize >= maxChunkSize) {
452
- isBoundaryCandidate = true;
445
+ if (lastPart.length > 0) {
446
+ pendingParts.push(lastPart);
453
447
  }
454
- if (isBoundaryCandidate) {
455
- let isSafeBoundary = true;
456
- if (isText) {
457
- if (pos + 1 < length && (buffer[pos + 1] & 192) === 128) {
458
- isSafeBoundary = false;
459
- }
448
+ const bytes = pendingParts.length === 1 ? pendingParts[0] : concatUInt8Array(pendingParts);
449
+ pendingParts.length = 0;
450
+ return bytes;
451
+ }
452
+ const blocks = dataSize > readBlockBytes ? iterateBlobBlocks(dataSrc, readBlockBytes) : void 0;
453
+ try {
454
+ while (remainingBytes > 0 && !signal?.aborted) {
455
+ const block = blocks ? (await blocks.next()).value : new Uint8Array(await dataSrc.arrayBuffer());
456
+ if (!block || signal?.aborted) {
457
+ return;
460
458
  }
461
- if (isSafeBoundary) {
462
- if (isText) {
463
- yield Promise.resolve(readString(buffer.subarray(start, pos + 1)));
464
- } else {
465
- yield await arrayBufferToBase64Single(buffer.subarray(start, pos + 1));
459
+ let chunkStart = 0;
460
+ for (let index = 0; index < block.length; index++) {
461
+ const byte = block[index];
462
+ if (isBoundaryCandidate() && (!isText || (byte & 192) !== 128)) {
463
+ const chunk = finishChunk(block.subarray(chunkStart, index));
464
+ chunkStart = index;
465
+ chunkSize = 0;
466
+ yield isText ? readString(chunk) : await arrayBufferToBase64Single(chunk);
466
467
  }
467
- start = pos + 1;
468
+ const oldByte = index < windowSize ? previousWindow[index] : block[index - windowSize];
469
+ hash = Math.imul(hash - Math.imul(oldByte, outgoingByteWeight), prime) + byte | 0;
470
+ chunkSize++;
471
+ }
472
+ remainingBytes -= block.length;
473
+ const lastPart = block.subarray(chunkStart);
474
+ if (remainingBytes === 0 || !isText && isBoundaryCandidate()) {
475
+ const chunk = finishChunk(lastPart);
476
+ chunkSize = 0;
477
+ yield isText ? readString(chunk) : await arrayBufferToBase64Single(chunk);
478
+ } else {
479
+ pendingParts.push(lastPart);
480
+ }
481
+ if (remainingBytes > 0) {
482
+ previousWindow.set(block.subarray(block.length - windowSize));
468
483
  }
469
484
  }
470
- pos++;
471
- }
472
- if (start < length) {
473
- if (isText) {
474
- yield Promise.resolve(readString(buffer.subarray(start, length)));
475
- } else {
476
- yield await arrayBufferToBase64Single(buffer.subarray(start, length));
485
+ } finally {
486
+ if (blocks) {
487
+ await blocks.return();
477
488
  }
478
489
  }
479
- };
490
+ }
491
+ const chunks = readChunks();
492
+ return () => chunks;
480
493
  }
481
494
  async function splitPiecesRabinKarpOld(dataSrc, absoluteMaxPieceSize, doPlainSplit, minimumChunkSize, _filename, _useSegmenter) {
482
495
  const plainSplit = doPlainSplit || isTextBlob(dataSrc);
@@ -1,9 +1,11 @@
1
- import { processSplit } from "./bg.worker.splitting.js";
1
+ import { cancelSplit, processSplit } from "./bg.worker.splitting.js";
2
2
  import { processEncryption } from "./bg.worker.encryption.js";
3
3
  self.onmessage = (e) => {
4
4
  const data = e.data.data;
5
5
  if (data.type === "split") {
6
6
  return processSplit(data);
7
+ } else if (data.type === "cancelSplit") {
8
+ cancelSplit(data.key);
7
9
  } else if (data.type === "encrypt" || data.type === "decrypt") {
8
10
  return processEncryption(data);
9
11
  } else if (data.type === "encryptHKDF" || data.type === "decryptHKDF") {
@@ -1,4 +1,5 @@
1
1
  import type { SplitArguments } from "./universalTypes.js";
2
+ export declare function cancelSplit(key: number): void;
2
3
  /**
3
4
  * Processes the splitting of data into chunks.
4
5
  * @param data The data to be split.
@@ -15,6 +15,18 @@ function getMainThreadPostBack(key) {
15
15
  }
16
16
  };
17
17
  }
18
+ const activeSplits = /* @__PURE__ */ new Map();
19
+ function cancelSplit(key) {
20
+ activeSplits.get(key)?.abort();
21
+ }
22
+ function readErrorField(error, field) {
23
+ try {
24
+ const value = error?.[field];
25
+ return typeof value === "string" ? value : void 0;
26
+ } catch {
27
+ return void 0;
28
+ }
29
+ }
18
30
  async function processSplit(data) {
19
31
  const key = data.key;
20
32
  const dataSrc = data.dataSrc;
@@ -23,14 +35,38 @@ async function processSplit(data) {
23
35
  const minimumChunkSize = data.minimumChunkSize;
24
36
  const filename = data.filename;
25
37
  const useSegmenter = data.useSegmenter;
26
- const func = data.splitVersion == 3 ? splitPiecesRabinKarp : data.splitVersion == 2 ? splitPieces2V2 : splitPieces2;
27
- const gen = await func(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter);
28
- const emit = getMainThreadPostBack(key);
29
- for await (const v of gen()) {
30
- emit(v);
38
+ const controller = new AbortController();
39
+ const signal = controller.signal;
40
+ activeSplits.set(key, controller);
41
+ try {
42
+ const splitLegacy = data.splitVersion === 2 ? splitPieces2V2 : splitPieces2;
43
+ const gen = data.splitVersion === 3 ? await splitPiecesRabinKarp(
44
+ dataSrc,
45
+ pieceSize,
46
+ plainSplit,
47
+ minimumChunkSize,
48
+ filename,
49
+ useSegmenter,
50
+ signal
51
+ ) : await splitLegacy(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter);
52
+ const emit = getMainThreadPostBack(key);
53
+ for await (const v of gen()) {
54
+ if (signal.aborted) {
55
+ break;
56
+ }
57
+ emit(v);
58
+ }
59
+ emit(END_OF_DATA);
60
+ } catch (error) {
61
+ const name = readErrorField(error, "name") ?? "Error";
62
+ const message = typeof error === "string" ? error : readErrorField(error, "message") ?? "Background splitting failed";
63
+ const stack = readErrorField(error, "stack");
64
+ self.postMessage({ key, error: { name, message, stack } });
65
+ } finally {
66
+ activeSplits.delete(key);
31
67
  }
32
- emit(END_OF_DATA);
33
68
  }
34
69
  export {
70
+ cancelSplit,
35
71
  processSplit
36
72
  };
@@ -5,6 +5,8 @@ export type WorkerInstance = {
5
5
  processing: number;
6
6
  /** Keys of tasks currently dispatched to this worker instance. */
7
7
  taskKeys: Set<number>;
8
+ /** Cancelled splits awaiting their terminal response. */
9
+ cancelledSplitKeys: Set<number>;
8
10
  };
9
11
  export declare function splitPieces2Worker(dataSrc: Blob, pieceSize: number, plainSplit: boolean, minimumChunkSize: number, filename?: string, useSegmenter?: boolean): () => AsyncGenerator<string, void, unknown>;
10
12
  export declare function splitPieces2WorkerV2(dataSrc: Blob, pieceSize: number, plainSplit: boolean, minimumChunkSize: number, filename?: string, useSegmenter?: boolean): () => AsyncGenerator<string, void, unknown>;
@@ -18,6 +20,8 @@ export declare const tasks: Map<number, ProcessItem>;
18
20
  * Remove a completed (or aborted) task from both the tasks map and its worker's taskKeys set.
19
21
  */
20
22
  export declare function removeTask(key: number): void;
23
+ /** Worker-side cancellation takes effect asynchronously when the worker receives the `cancelSplit` message. */
24
+ export declare function cancelSplitTask(key: number): void;
21
25
  export declare function initialiseWorkerModule(events: LiveSyncEventHub): void;
22
26
  export declare function startWorker(data: Omit<EncryptHKDFArguments, "key">): EncryptHKDFProcessItem;
23
27
  export declare function startWorker(data: Omit<EncryptArguments, "key">): EncryptProcessItem;