pending-task-kit 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,660 @@
1
+ // src/store.ts
2
+ import { create } from "zustand";
3
+ import { createJSONStorage, persist } from "zustand/middleware";
4
+ var DEFAULT_TTL_MS = 24 * 60 * 60 * 1e3;
5
+ var DEFAULT_STORAGE_KEY = "pending-tasks";
6
+ function isPendingTaskShape(value) {
7
+ if (!value || typeof value !== "object") return false;
8
+ const t = value;
9
+ return typeof t.id === "string" && typeof t.type === "string" && typeof t.startedAt === "number" && (typeof t.taskId === "number" || typeof t.taskId === "string");
10
+ }
11
+ function parseTasksFromStorageValue(value) {
12
+ if (!value) return [];
13
+ try {
14
+ const parsed = JSON.parse(value);
15
+ const tasks = parsed?.state?.tasks;
16
+ if (!Array.isArray(tasks)) return [];
17
+ return tasks.filter(isPendingTaskShape);
18
+ } catch {
19
+ return [];
20
+ }
21
+ }
22
+ function readPersistedTasks(storageKey) {
23
+ if (typeof localStorage === "undefined") return [];
24
+ return parseTasksFromStorageValue(localStorage.getItem(storageKey));
25
+ }
26
+ function createPendingTaskStore(options = {}) {
27
+ const storageKey = options.storageKey ?? DEFAULT_STORAGE_KEY;
28
+ const readPersisted = () => readPersistedTasks(storageKey);
29
+ const writeTasks = (tasks) => {
30
+ try {
31
+ useStore.setState({ tasks });
32
+ useStore.hasUnpersistedWrites = false;
33
+ } catch {
34
+ useStore.hasUnpersistedWrites = true;
35
+ }
36
+ };
37
+ const useStore = create()(
38
+ persist(
39
+ (_set, get) => {
40
+ const base = () => useStore.hasUnpersistedWrites ? get().tasks : readPersisted();
41
+ return {
42
+ tasks: [],
43
+ addTask: (task) => {
44
+ const next = base().filter((t) => t.id !== task.id);
45
+ next.push(task);
46
+ writeTasks(next);
47
+ },
48
+ removeTask: (id) => {
49
+ writeTasks(base().filter((t) => t.id !== id));
50
+ },
51
+ updateTask: (id, patch) => {
52
+ writeTasks(base().map((t) => t.id === id ? { ...t, ...patch } : t));
53
+ },
54
+ pruneTasksBy: (predicate) => {
55
+ writeTasks(base().filter(predicate));
56
+ },
57
+ clearAllTasks: () => writeTasks([])
58
+ };
59
+ },
60
+ {
61
+ name: storageKey,
62
+ storage: createJSONStorage(() => localStorage),
63
+ partialize: (state) => ({ tasks: state.tasks })
64
+ }
65
+ )
66
+ );
67
+ useStore.storageKey = storageKey;
68
+ useStore.hasUnpersistedWrites = false;
69
+ useStore.writeTasks = writeTasks;
70
+ return useStore;
71
+ }
72
+
73
+ // src/registry.ts
74
+ function createPendingTaskRegistryBinding(store, registry) {
75
+ function addTask(task) {
76
+ const handler = registry[task.type];
77
+ const ttlMs = handler?.ttlMs;
78
+ const withTtl = ttlMs === void 0 ? task : { ...task, ttlMs };
79
+ store.getState().addTask(withTtl);
80
+ }
81
+ function addTaskIfMissing(task) {
82
+ const existsInMemory = store.getState().tasks.some((t) => t.id === task.id);
83
+ const existsPersisted = !store.hasUnpersistedWrites && readPersistedTasks(store.storageKey).some((t) => t.id === task.id);
84
+ if (!existsInMemory && !existsPersisted) {
85
+ addTask(task);
86
+ }
87
+ }
88
+ return { addTask, addTaskIfMissing };
89
+ }
90
+
91
+ // src/safe-storage.ts
92
+ function safeGetItem(key) {
93
+ try {
94
+ if (typeof localStorage === "undefined") return null;
95
+ return localStorage.getItem(key);
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+ function safeSetItem(key, value) {
101
+ try {
102
+ if (typeof localStorage === "undefined") return false;
103
+ localStorage.setItem(key, value);
104
+ return true;
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+ function safeRemoveItem(key) {
110
+ try {
111
+ if (typeof localStorage === "undefined") return;
112
+ localStorage.removeItem(key);
113
+ } catch {
114
+ }
115
+ }
116
+
117
+ // src/poll-lease.ts
118
+ function readLease(storageKey) {
119
+ const raw = safeGetItem(storageKey);
120
+ if (!raw) return null;
121
+ try {
122
+ const parsed = JSON.parse(raw);
123
+ if (typeof parsed.ownerId !== "string" || typeof parsed.expiresAt !== "number" || typeof parsed.fence !== "number") {
124
+ return null;
125
+ }
126
+ return parsed;
127
+ } catch {
128
+ return null;
129
+ }
130
+ }
131
+ function writeLease(storageKey, lease) {
132
+ safeSetItem(storageKey, JSON.stringify(lease));
133
+ }
134
+ function createPollLeaseClaimer(storageKey, ttlMs) {
135
+ if (ttlMs <= 0 && typeof console !== "undefined") {
136
+ console.warn(`pending-task-kit: pollLeaseTtlMs must be positive, got ${ttlMs}`);
137
+ }
138
+ return {
139
+ claim(ownerId) {
140
+ const current = readLease(storageKey);
141
+ const now = Date.now();
142
+ if (current && current.ownerId !== ownerId && current.expiresAt > now) {
143
+ return { leader: false };
144
+ }
145
+ const isRenewal = current !== null && current.ownerId === ownerId && current.expiresAt > now;
146
+ const fence = isRenewal ? current.fence : (current?.fence ?? 0) + 1;
147
+ writeLease(storageKey, { ownerId, fence, expiresAt: now + ttlMs });
148
+ return { leader: true, fence };
149
+ },
150
+ release(ownerId) {
151
+ const current = readLease(storageKey);
152
+ if (current?.ownerId === ownerId) {
153
+ writeLease(storageKey, { ownerId, fence: current.fence, expiresAt: 0 });
154
+ }
155
+ }
156
+ };
157
+ }
158
+ function generatePollOwnerId() {
159
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
160
+ return crypto.randomUUID();
161
+ }
162
+ return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
163
+ }
164
+
165
+ // src/result-relay.ts
166
+ var RESULT_STATUSES = [
167
+ "success",
168
+ "failure",
169
+ "error",
170
+ "expired"
171
+ ];
172
+ function isResultStatus(value) {
173
+ return typeof value === "string" && RESULT_STATUSES.includes(value);
174
+ }
175
+ function writeResultRelay(storageKey, detail) {
176
+ try {
177
+ const serialized = JSON.stringify(detail);
178
+ safeSetItem(storageKey, serialized);
179
+ } catch {
180
+ }
181
+ }
182
+ function parseResultRelay(value) {
183
+ if (!value) return null;
184
+ try {
185
+ const parsed = JSON.parse(value);
186
+ if (!isPendingTaskShape(parsed.task) || !isResultStatus(parsed.status)) {
187
+ return null;
188
+ }
189
+ return parsed;
190
+ } catch {
191
+ return null;
192
+ }
193
+ }
194
+ function clearResultRelay(storageKey) {
195
+ safeRemoveItem(storageKey);
196
+ }
197
+
198
+ // src/tab-lock.ts
199
+ async function withTabLock(name, operation) {
200
+ const locks = typeof navigator !== "undefined" ? navigator.locks : void 0;
201
+ if (!locks) {
202
+ return operation();
203
+ }
204
+ return locks.request(name, async () => operation());
205
+ }
206
+
207
+ // src/engine.ts
208
+ var DEFAULT_POLL_TICK_MS = 2e3;
209
+ var DEFAULT_POLL_INTERVAL_MS = 1e4;
210
+ var DEFAULT_MAX_FAILURE_COUNT = 5;
211
+ var DEFAULT_RESULT_EVENT = "pending-task-result";
212
+ var DEFAULT_POLL_LEASE_TTL_MULTIPLIER = 4;
213
+ function describeError(error) {
214
+ if (error instanceof Error) return error.message;
215
+ return typeof error === "string" ? error : "Unknown error";
216
+ }
217
+ var PendingTaskPoller = class {
218
+ constructor(options) {
219
+ this.isChecking = false;
220
+ this.pendingForce = false;
221
+ this.stopped = false;
222
+ /** Task ids that already got their one `finalCheckOnExpiry` attempt, so a repeatedly-failing
223
+ * final check doesn't get retried every tick. Reset on process restart — worst case that
224
+ * costs one extra check, never an infinite retry loop.
225
+ *
226
+ * Every id added here (only when a task is expired, right before its final `check()`) is
227
+ * removed again before the *same* tick's iteration moves past that task — either by
228
+ * `finalize()`'s first line, or by one of the leadership-loss/`onCheckError`-intercept
229
+ * branches that bail out without ever reaching `finalize()`. Nothing here is meant to
230
+ * survive past the tick that added it. */
231
+ this.finalCheckAttempted = /* @__PURE__ */ new Set();
232
+ const storageKey = options.storageKey ?? options.store.storageKey ?? DEFAULT_STORAGE_KEY;
233
+ const pollTickMs = options.pollTickMs ?? DEFAULT_POLL_TICK_MS;
234
+ this.options = {
235
+ store: options.store,
236
+ registry: options.registry,
237
+ pollTickMs,
238
+ defaultPollIntervalMs: options.defaultPollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,
239
+ defaultTtlMs: options.defaultTtlMs ?? DEFAULT_TTL_MS,
240
+ maxFailureCount: options.maxFailureCount ?? DEFAULT_MAX_FAILURE_COUNT,
241
+ dispatchDomEvent: options.dispatchDomEvent ?? typeof window !== "undefined",
242
+ eventName: options.eventName ?? DEFAULT_RESULT_EVENT,
243
+ storageKey,
244
+ crossTabPollLeaderElection: options.crossTabPollLeaderElection ?? true,
245
+ pollLeaseKey: options.pollLeaseKey ?? `${storageKey}-poll-leader`,
246
+ pollLeaseTtlMs: options.pollLeaseTtlMs ?? pollTickMs * DEFAULT_POLL_LEASE_TTL_MULTIPLIER,
247
+ resultRelayKey: options.resultRelayKey ?? `${storageKey}-result-relay`,
248
+ onResult: options.onResult,
249
+ onCheckError: options.onCheckError,
250
+ claimResultOnce: options.claimResultOnce,
251
+ acceptRelayedResult: options.acceptRelayedResult
252
+ };
253
+ this.ownerId = generatePollOwnerId();
254
+ this.pollLease = createPollLeaseClaimer(this.options.pollLeaseKey, this.options.pollLeaseTtlMs);
255
+ }
256
+ start() {
257
+ this.stopped = false;
258
+ if (this.intervalId !== void 0) return;
259
+ this.intervalId = setInterval(() => {
260
+ this.runTickSafely(false);
261
+ }, this.options.pollTickMs);
262
+ if (typeof window !== "undefined") {
263
+ this.storageListener = (event) => {
264
+ if (event.key === null) {
265
+ this.options.store.writeTasks([]);
266
+ return;
267
+ }
268
+ if (event.key === this.options.storageKey) {
269
+ this.options.store.writeTasks(parseTasksFromStorageValue(event.newValue));
270
+ return;
271
+ }
272
+ if (this.options.crossTabPollLeaderElection && event.key === this.options.resultRelayKey) {
273
+ const detail = parseResultRelay(event.newValue);
274
+ if (!detail) return;
275
+ let accepted;
276
+ try {
277
+ accepted = this.options.acceptRelayedResult?.(detail) ?? true;
278
+ } catch (error) {
279
+ queueMicrotask(() => {
280
+ throw error;
281
+ });
282
+ return;
283
+ }
284
+ if (accepted) void this.dispatchRelayedResult(detail);
285
+ }
286
+ };
287
+ window.addEventListener("storage", this.storageListener);
288
+ }
289
+ this.runTickSafely(false);
290
+ }
291
+ stop() {
292
+ this.stopped = true;
293
+ this.pendingForce = false;
294
+ if (this.intervalId !== void 0) {
295
+ clearInterval(this.intervalId);
296
+ this.intervalId = void 0;
297
+ }
298
+ if (this.storageListener && typeof window !== "undefined") {
299
+ window.removeEventListener("storage", this.storageListener);
300
+ this.storageListener = void 0;
301
+ }
302
+ if (this.options.crossTabPollLeaderElection) {
303
+ void this.releaseLeadership().catch(() => void 0);
304
+ }
305
+ }
306
+ /** Re-check every tracked task right now, bypassing each task's poll interval (e.g. on tab focus). */
307
+ forceCheckAll() {
308
+ this.runTickSafely(true);
309
+ }
310
+ claimLeadership() {
311
+ return withTabLock(this.options.pollLeaseKey, () => this.pollLease.claim(this.ownerId));
312
+ }
313
+ /**
314
+ * Re-confirms that poll leadership is still this tab's — and still the *same continuous
315
+ * tenure* as when `fence` was captured, not just "is nobody else currently holding it" (a
316
+ * no-op returning `fence` unchanged when `crossTabPollLeaderElection` is off). Clears `task`'s
317
+ * `finalCheckAttempted` bookkeeping and returns `false` if not — the caller should stop
318
+ * treating this tick's remaining due tasks as network-eligible (though it may still process
319
+ * ones that need no leadership) rather than act on a possibly-stale outcome.
320
+ *
321
+ * A fence mismatch (rather than just an owner-id mismatch) is needed to catch leadership
322
+ * having churned through another tab and back to this one while a slow `handler.check()` was
323
+ * in flight: this tab's lease can expire mid-check, another tab claims it and fully resolves
324
+ * the same task, and that tab's own lease can *also* expire before this tab's stale response
325
+ * comes back — at which point this tab's next claim legitimately succeeds under its own
326
+ * stable owner id (nothing currently holds the lease), even though leadership genuinely
327
+ * changed hands in between. See `PollLeaseClaimResult`.
328
+ */
329
+ async reconfirmLeadership(task, expired, fence) {
330
+ if (!this.options.crossTabPollLeaderElection) return fence;
331
+ if (this.stopped) {
332
+ if (expired) this.finalCheckAttempted.delete(task.id);
333
+ return false;
334
+ }
335
+ let result;
336
+ try {
337
+ result = await this.claimLeadership();
338
+ } catch (error) {
339
+ if (expired) this.finalCheckAttempted.delete(task.id);
340
+ throw error;
341
+ }
342
+ if (result.leader && result.fence === fence) return result.fence;
343
+ if (expired) this.finalCheckAttempted.delete(task.id);
344
+ return false;
345
+ }
346
+ releaseLeadership() {
347
+ return withTabLock(this.options.pollLeaseKey, () => {
348
+ this.pollLease.release(this.ownerId);
349
+ });
350
+ }
351
+ /** Fires `runTick`, but instead of leaving its promise `void`-called (which would turn an
352
+ * exception thrown by a consumer callback — `onResult`, `onCheckError`, or a `dispatchEvent`
353
+ * listener — into a silent unhandled rejection), re-throws it as an uncaught exception on a
354
+ * fresh microtask. `runTick`'s own `finally` has already flushed the batch and reset
355
+ * `isChecking` by the time this ever runs, so a broken consumer callback can't take the
356
+ * poller down — it just becomes visible the way any other uncaught error in the host
357
+ * environment would be, instead of vanishing. */
358
+ runTickSafely(force) {
359
+ this.runTick(force).catch((error) => {
360
+ queueMicrotask(() => {
361
+ throw error;
362
+ });
363
+ });
364
+ }
365
+ /** Reads the freshest snapshot of `task` from the store, in case another tab wrote to it
366
+ * while this tab's `handler.check()` was in flight — narrows, but doesn't eliminate, the
367
+ * window where a concurrent cross-tab write to the same task could be clobbered.
368
+ *
369
+ * Indexes `store.getState().tasks` into a Map keyed by id rather than doing a linear find
370
+ * each call — this is called once per pending/failing task per tick, so a plain find would
371
+ * make a tick O(n²). The cache keys off the `tasks` array reference, which zustand only
372
+ * replaces on an actual write, so it's rebuilt only when the store has genuinely changed. */
373
+ getLatestTask(task) {
374
+ const tasks = this.options.store.getState().tasks;
375
+ if (this.latestTasksCache?.tasks !== tasks) {
376
+ this.latestTasksCache = { tasks, byId: new Map(tasks.map((t) => [t.id, t])) };
377
+ }
378
+ return this.latestTasksCache.byId.get(task.id) ?? task;
379
+ }
380
+ /** Applies a whole tick's worth of per-task updates/removals (`patch: null` means "remove")
381
+ * in a single read-modify-write, instead of one persisted-storage round trip per task.
382
+ * Reads the freshest persisted list right before writing (same "never resurrect a task
383
+ * another tab already removed" guarantee `PendingTaskStore`'s own mutators give) — unless
384
+ * the store's `hasUnpersistedWrites` is set (a write on *any* path for this store, including
385
+ * this store's own direct mutators, failed and hasn't yet been followed by a success), in
386
+ * which case persisted storage is stale relative to this tab's memory, so this flush builds
387
+ * on `store.getState().tasks` instead. Writes through `writeTasks`, which swallows a
388
+ * throwing write and updates that same shared flag — see the comment in `store.ts`. */
389
+ flushBatch(batch) {
390
+ if (batch.size === 0) return;
391
+ const base = this.options.store.hasUnpersistedWrites ? this.options.store.getState().tasks : readPersistedTasks(this.options.storageKey);
392
+ const next = [];
393
+ for (const t of base) {
394
+ if (!batch.has(t.id)) {
395
+ next.push(t);
396
+ continue;
397
+ }
398
+ const patch = batch.get(t.id);
399
+ if (patch !== null) next.push({ ...t, ...patch });
400
+ }
401
+ this.options.store.writeTasks(next);
402
+ }
403
+ async finalize(task, detail, handler, batch) {
404
+ this.finalCheckAttempted.delete(task.id);
405
+ batch.set(task.id, null);
406
+ if (detail.status === "expired") return;
407
+ const silent = detail.status === "success" ? handler?.silentOnSuccess : handler?.silentOnFailure;
408
+ if (silent) return;
409
+ let claimed;
410
+ try {
411
+ claimed = this.options.claimResultOnce ? await this.options.claimResultOnce(task) : true;
412
+ } catch {
413
+ return;
414
+ }
415
+ if (!claimed) return;
416
+ const fullDetail = { task, ...detail };
417
+ if (this.options.crossTabPollLeaderElection) {
418
+ writeResultRelay(this.options.resultRelayKey, fullDetail);
419
+ }
420
+ this.options.onResult?.(fullDetail);
421
+ if (this.options.dispatchDomEvent && typeof window !== "undefined") {
422
+ window.dispatchEvent(new CustomEvent(this.options.eventName, { detail: fullDetail }));
423
+ }
424
+ }
425
+ /**
426
+ * Handles a result relayed from another tab's leader — mirrors finalize()'s own
427
+ * `claimResultOnce` gate and dispatch, so a `claimResultOnce` composed for "one notification
428
+ * system-wide" (see its doc comment's "keep both if you want both properties") applies
429
+ * uniformly whether this tab detected the result itself or only learned about it via the
430
+ * relay, not just to the narrower direct-detection race `claimResultOnce` guarded before this
431
+ * relay existed.
432
+ *
433
+ * Fired-and-forgotten (`void`-called) from the "storage" listener rather than awaited, so it
434
+ * has no `this.stopped` check of its own: `stop()` removes the listener (no *new* relayed
435
+ * result starts one of these after that), but one already in flight when `stop()` is called
436
+ * (e.g. awaiting a slow `claimResultOnce`) still runs to completion — the same tolerance
437
+ * `runTick`'s own doc comment describes for an in-flight tick.
438
+ */
439
+ async dispatchRelayedResult(detail) {
440
+ let claimed;
441
+ try {
442
+ claimed = this.options.claimResultOnce ? await this.options.claimResultOnce(detail.task) : true;
443
+ } catch {
444
+ return;
445
+ }
446
+ if (!claimed) return;
447
+ try {
448
+ this.options.onResult?.(detail);
449
+ if (this.options.dispatchDomEvent && typeof window !== "undefined") {
450
+ window.dispatchEvent(new CustomEvent(this.options.eventName, { detail }));
451
+ }
452
+ } catch (error) {
453
+ queueMicrotask(() => {
454
+ throw error;
455
+ });
456
+ }
457
+ }
458
+ async runTick(force) {
459
+ if (this.stopped) return;
460
+ if (this.isChecking) {
461
+ this.pendingForce = this.pendingForce || force;
462
+ return;
463
+ }
464
+ const tasks = this.options.store.getState().tasks;
465
+ if (tasks.length === 0) return;
466
+ this.isChecking = true;
467
+ const batch = /* @__PURE__ */ new Map();
468
+ try {
469
+ const now = Date.now();
470
+ let fence;
471
+ let leadershipLost = false;
472
+ for (const task of tasks) {
473
+ const handler = this.options.registry[task.type];
474
+ const ttlMs = task.ttlMs ?? this.options.defaultTtlMs;
475
+ const expired = now - task.startedAt >= ttlMs;
476
+ if (!handler) {
477
+ if (expired) {
478
+ await this.finalize(task, { status: "expired" }, handler, batch);
479
+ }
480
+ continue;
481
+ }
482
+ const interval = handler.pollIntervalMs ?? this.options.defaultPollIntervalMs;
483
+ const lastChecked = task.lastCheckedAt ?? task.startedAt;
484
+ const due = force || now - lastChecked >= interval;
485
+ const finalAttemptDone = this.finalCheckAttempted.has(task.id);
486
+ if (expired && (!handler.finalCheckOnExpiry || finalAttemptDone)) {
487
+ await this.finalize(task, { status: "expired" }, handler, batch);
488
+ continue;
489
+ }
490
+ if (!due && !expired) continue;
491
+ if (expired) {
492
+ this.finalCheckAttempted.add(task.id);
493
+ }
494
+ if (this.options.crossTabPollLeaderElection) {
495
+ if (leadershipLost || this.stopped) {
496
+ leadershipLost = true;
497
+ if (expired) this.finalCheckAttempted.delete(task.id);
498
+ continue;
499
+ }
500
+ if (fence === void 0) {
501
+ let claimed;
502
+ try {
503
+ claimed = await this.claimLeadership();
504
+ } catch (error) {
505
+ if (expired) this.finalCheckAttempted.delete(task.id);
506
+ throw error;
507
+ }
508
+ if (!claimed.leader) {
509
+ leadershipLost = true;
510
+ if (expired) this.finalCheckAttempted.delete(task.id);
511
+ continue;
512
+ }
513
+ fence = claimed.fence;
514
+ }
515
+ }
516
+ let result;
517
+ try {
518
+ result = await handler.check(task);
519
+ } catch (error) {
520
+ const reconfirmedOnError = await this.reconfirmLeadership(task, expired, fence);
521
+ if (reconfirmedOnError === false) {
522
+ leadershipLost = true;
523
+ fence = void 0;
524
+ continue;
525
+ }
526
+ fence = reconfirmedOnError;
527
+ let intercepted;
528
+ try {
529
+ intercepted = this.options.onCheckError?.(error, task);
530
+ } catch (onCheckErrorError) {
531
+ queueMicrotask(() => {
532
+ throw onCheckErrorError;
533
+ });
534
+ intercepted = false;
535
+ }
536
+ if (intercepted) {
537
+ batch.set(task.id, { lastCheckedAt: now });
538
+ this.finalCheckAttempted.delete(task.id);
539
+ break;
540
+ }
541
+ if (expired) {
542
+ await this.finalize(task, { status: "expired" }, handler, batch);
543
+ continue;
544
+ }
545
+ const latest = this.getLatestTask(task);
546
+ const failureCount = (latest.failureCount ?? 0) + 1;
547
+ if (failureCount >= this.options.maxFailureCount) {
548
+ await this.finalize(task, { status: "error", data: describeError(error) }, handler, batch);
549
+ } else {
550
+ batch.set(task.id, { lastCheckedAt: now, failureCount });
551
+ }
552
+ continue;
553
+ }
554
+ const reconfirmedOnSuccess = await this.reconfirmLeadership(task, expired, fence);
555
+ if (reconfirmedOnSuccess === false) {
556
+ leadershipLost = true;
557
+ fence = void 0;
558
+ continue;
559
+ }
560
+ fence = reconfirmedOnSuccess;
561
+ if (result.status === "pending") {
562
+ const latest = this.getLatestTask(task);
563
+ batch.set(task.id, {
564
+ lastCheckedAt: now,
565
+ failureCount: 0,
566
+ metadata: { ...latest.metadata, ...result.progress }
567
+ });
568
+ if (expired) {
569
+ await this.finalize(task, { status: "expired" }, handler, batch);
570
+ }
571
+ continue;
572
+ }
573
+ await this.finalize(task, { status: result.status, data: result.data }, handler, batch);
574
+ }
575
+ } finally {
576
+ this.flushBatch(batch);
577
+ this.isChecking = false;
578
+ if (this.pendingForce && !this.stopped) {
579
+ this.pendingForce = false;
580
+ this.runTickSafely(true);
581
+ }
582
+ }
583
+ }
584
+ };
585
+
586
+ // src/ttl-dedupe-cache.ts
587
+ function createTtlDedupeCache(storageKey, ttlMs) {
588
+ const read = () => {
589
+ const raw = safeGetItem(storageKey);
590
+ if (!raw) return {};
591
+ try {
592
+ const parsed = JSON.parse(raw);
593
+ return parsed && typeof parsed === "object" ? parsed : {};
594
+ } catch {
595
+ return {};
596
+ }
597
+ };
598
+ const write = (state) => {
599
+ safeSetItem(storageKey, JSON.stringify(Object.fromEntries(state)));
600
+ };
601
+ const prune = (state, now) => {
602
+ const next = /* @__PURE__ */ new Map();
603
+ for (const [id, entry] of Object.entries(state)) {
604
+ if (now - entry.claimedAt < ttlMs) {
605
+ next.set(id, entry);
606
+ }
607
+ }
608
+ return next;
609
+ };
610
+ return {
611
+ /** Returns true the first time `id` is claimed within the TTL window, false on any repeat. */
612
+ claim(id) {
613
+ const now = Date.now();
614
+ const state = prune(read(), now);
615
+ if (state.has(id)) {
616
+ write(state);
617
+ return false;
618
+ }
619
+ state.set(id, { claimedAt: now });
620
+ write(state);
621
+ return true;
622
+ },
623
+ /** Wipes every claim this cache holds — e.g. on explicit user logout, if `id`s (or
624
+ * whatever metadata a caller's own claim wrapper attaches alongside them) can carry PII.
625
+ * Unlike `claim`, this doesn't need TTL pruning first: it removes the whole entry
626
+ * regardless of age.
627
+ *
628
+ * Best-effort, not atomic with a concurrent `claim()` in another tab: like every other
629
+ * primitive in this package, this is a plain, unlocked read-modify-write (`claim` reads,
630
+ * then this removes), so a `claim()` in another tab that read its state just before this
631
+ * call's removal lands can write that stale state back afterwards, resurrecting the very
632
+ * claim this call meant to wipe. Compose your own `withTabLock` around both calls if a
633
+ * logout-time clear must be atomic with respect to a claim that could race it. */
634
+ clear() {
635
+ safeRemoveItem(storageKey);
636
+ }
637
+ };
638
+ }
639
+ export {
640
+ DEFAULT_MAX_FAILURE_COUNT,
641
+ DEFAULT_POLL_INTERVAL_MS,
642
+ DEFAULT_POLL_LEASE_TTL_MULTIPLIER,
643
+ DEFAULT_POLL_TICK_MS,
644
+ DEFAULT_RESULT_EVENT,
645
+ DEFAULT_STORAGE_KEY,
646
+ DEFAULT_TTL_MS,
647
+ PendingTaskPoller,
648
+ clearResultRelay,
649
+ createPendingTaskRegistryBinding,
650
+ createPendingTaskStore,
651
+ createPollLeaseClaimer,
652
+ createTtlDedupeCache,
653
+ generatePollOwnerId,
654
+ isPendingTaskShape,
655
+ parseResultRelay,
656
+ parseTasksFromStorageValue,
657
+ withTabLock,
658
+ writeResultRelay
659
+ };
660
+ //# sourceMappingURL=index.js.map