UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

80 lines (79 loc) • 2.35 kB
"use strict"; Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); const errorMessage = require("../error-message.cjs"); const cleanupNow = () => globalThis.performance?.now() ?? Date.now(); const _CleanupQueue = class _CleanupQueue { constructor() { this.tasks = /* @__PURE__ */ new Map(); this.timeoutId = null; this.dm = false; } static getInstance() { return _CleanupQueue.fY ??= new _CleanupQueue(); } /** * Queues a cleanup task and defers timeout selection to a microtask so * multiple synchronous registrations can share one root timer. */ schedule(key, gcTime, callback) { const executeAt = cleanupNow() + gcTime; this.tasks.set(key, { executeAt, callback }); if (!this.dm) { this.dm = true; Promise.resolve().then(() => { this.dm = false; this.fa(); }); } } cancel(key) { this.tasks.delete(key); if (this.tasks.size === 0 && this.timeoutId !== null) { clearTimeout(this.timeoutId); this.timeoutId = null; } } /** * Keeps only one active timeout: whichever task is due next. */ fa() { if (this.timeoutId !== null) { clearTimeout(this.timeoutId); this.timeoutId = null; } if (this.tasks.size === 0) { return; } let earliestTime = Infinity; for (const task of this.tasks.values()) { if (task.executeAt < earliestTime) { earliestTime = task.executeAt; } } const delay = Math.max(0, earliestTime - cleanupNow()); this.timeoutId = setTimeout(() => { this.timeoutId = null; const now = cleanupNow(); for (const [key, task] of this.tasks.entries()) { if (now >= task.executeAt) { this.tasks.delete(key); try { task.callback(); } catch (error) { console.error( errorMessage.devBuild() && process.env.NODE_ENV !== `production` ? "Error in CleanupQueue task:" : errorMessage.codedMessage(214), error ); } } } this.fa(); }, delay); if (typeof this.timeoutId === `object`) this.timeoutId.unref(); } }; _CleanupQueue.fY = null; let CleanupQueue = _CleanupQueue; exports.CleanupQueue = CleanupQueue; exports.cleanupNow = cleanupNow; //# sourceMappingURL=cleanup-queue.cjs.map