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