@cldmv/holdmytask 2.1.2 → 3.0.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/README.md CHANGED
@@ -16,17 +16,19 @@ Use it with callbacks or promises, from ESM or CommonJS, with full TypeScript de
16
16
 
17
17
  ## ✨ What's New
18
18
 
19
- ### Latest: v2.1.2 (November 2026)
19
+ ### Latest: v3.0.0 (November 2026)
20
20
 
21
- - **Tooling release, no library changes** — the vitest config now uses `devCondition()` from `@cldmv/configs`, so tests really run against `src/` through the `holdmytask-dev` export condition, and the type scripts are renamed to the fleet names `types:check` and `types:build` ([#99](https://github.com/CLDMV/holdmytask/pull/99), [#101](https://github.com/CLDMV/holdmytask/pull/101)).
22
- - [View full v2.1.2 Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.1.2.md)
21
+ - **`require()` returns the module object** — the CommonJS entry is now the generic CLDMV shim, so `require("@cldmv/holdmytask")` gives the same exports as `import` (`HoldMyTask`, the aliases, `default` and the `create*` factories) instead of the class itself. Use `const { HoldMyTask } = require("@cldmv/holdmytask")`; ESM `import` is unchanged ([#116](https://github.com/CLDMV/holdmytask/pull/116)).
22
+ - **One file per module in `dist/`** — the build no longer bundles with tsup; `dist/` mirrors `src/` with each file minified in place, and the entry points and exports are unchanged ([#119](https://github.com/CLDMV/holdmytask/pull/119)).
23
+ - **Tooling** — superseded CI runs are cancelled, `npm test` also runs the suite against the build, and the CLDMV dev tools are bumped ([#117](https://github.com/CLDMV/holdmytask/pull/117), [#103](https://github.com/CLDMV/holdmytask/pull/103), [#120](https://github.com/CLDMV/holdmytask/pull/120)).
24
+ - [View full v3.0.0 Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v3/v3.0.0.md)
23
25
 
24
26
  ### Recent Releases
25
27
 
28
+ - **v2.1.2** (November 2026) — Tooling release: vitest config uses `devCondition()`, type scripts renamed to `types:check` and `types:build` ([Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.1.2.md))
26
29
  - **v2.1.1** (November 2026) — `engines.node` is the runtime floor again (`>=18.12.0`); the 22.22.0 toolchain floor moves to `devEngines` ([Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.1.1.md))
27
- - **v2.1.0** (November 2026) — Built with tsup from `src/` into `dist/`, `@cldmv/holdmytask/main` becomes a deprecated alias of the root, and `engines.node` went to `>=22.22.0` ([Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.1.0.md))
30
+ - **v2.1.0** (November 2026) — Built from `src/` into `dist/`, `@cldmv/holdmytask/main` becomes a deprecated alias of the root, and `engines.node` went to `>=22.22.0` ([Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.1.0.md))
28
31
  - **v2.0.6** (October 2026) — Development dependency updates only (`eslint`, `globals`, `@cldmv/vitest-runner`, `@types/node`); the published package is unchanged ([Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.0.6.md))
29
- - **v2.0.5** (October 2026) — Task-level `postDelay` / `startDelay` honored, failing callback tasks no longer crash the process, and header tooling on fix-headers 2.2.0 ([Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.0.5.md))
30
32
 
31
33
  📚 **For complete version history and detailed release notes, see the [docs/changelog/](https://github.com/CLDMV/holdmytask/tree/master/docs/changelog/) folder.**
32
34
 
@@ -131,8 +133,8 @@ import * as HoldMyTaskLib from "@cldmv/holdmytask";
131
133
  // Uses optimized distribution files
132
134
 
133
135
  // CommonJS (Node.js ^20.19.0 || >=22.13.0)
134
- const HoldMyTask = require("@cldmv/holdmytask"); // the class itself
135
- const { HoldMyTask: Named } = require("@cldmv/holdmytask"); // or by name
136
+ const { HoldMyTask } = require("@cldmv/holdmytask"); // require() returns the module object, same names as import
137
+ const holdmytask = require("@cldmv/holdmytask"); // holdmytask.HoldMyTask, holdmytask.createQueue(), holdmytask.default
136
138
  ```
137
139
 
138
140
  ### Common Queue System Aliases
@@ -1938,9 +1940,12 @@ setInterval(() => {
1938
1940
  ## 🧪 Testing & Development
1939
1941
 
1940
1942
  ```bash
1941
- # Run tests (vitest suite + CommonJS entry tests)
1943
+ # Run tests (vitest suite on src/, CommonJS entry tests, and the suite again on the build)
1942
1944
  npm test
1943
1945
 
1946
+ # Build, then run the vitest suite against dist/
1947
+ npm run test:dist
1948
+
1944
1949
  # Run tests with coverage
1945
1950
  npm run coverage
1946
1951
 
@@ -0,0 +1,13 @@
1
+ var v=Object.defineProperty;var g=(T,e)=>v(T,"name",{value:e,configurable:!0});import{EventEmitter as w}from"events";import{MinHeap as b}from"./utils.mjs";class k extends w{static{g(this,"HoldMyTask")}static _transformDelayProperties(e,t=null){if(!e||typeof e!="object")return e;const s={...e};return"start"in e&&!("startDelay"in e)&&(s.startDelay=e.start,t&&setImmediate(()=>t.emit("warning",{type:"deprecation",message:"Property 'start' is deprecated. Use 'startDelay' instead.",deprecated:"start",replacement:"startDelay"}))),delete s.start,"delay"in e&&!("postDelay"in e)&&(s.postDelay=e.delay,t&&setImmediate(()=>t.emit("warning",{type:"deprecation",message:"Property 'delay' is deprecated. Use 'postDelay' instead.",deprecated:"delay",replacement:"postDelay"}))),delete s.delay,s}_normalizeTaskDelayOptions(e){if(!("delay"in e)&&!("start"in e))return e;const t={...e},s=[{deprecated:"start",replacement:"startDelay"},{deprecated:"delay",replacement:"postDelay"}];for(const{deprecated:i,replacement:r}of s)i in e&&(r in e||(t[r]=e[i],this._warnTaskOptionDeprecated(i,r)),delete t[i]);return t}_warnTaskOptionDeprecated(e,t){this._warnedTaskOptions.has(e)||(this._warnedTaskOptions.add(e),setImmediate(()=>this.emit("warning",{type:"deprecation",message:`Task option '${e}' is deprecated. Use '${t}' instead.`,deprecated:e,replacement:t})))}constructor(e={}){if(super(),e.sync!==!1)this._initializeSync(e);else return this._initializeAsync(e)}_resolvePriorityKey(e,t){if(/^-?\d+$/.test(e))return Number(e);const s=parseInt(e),i=isNaN(s)?null:s,r=i===null?`Priority key '${e}' in '${t}' is not an integer and was ignored. Priority keys must be integers.`:`Priority key '${e}' in '${t}' is not an integer; it was applied to priority ${i}. Priority keys must be integers.`;return setImmediate(()=>this.emit("warning",{type:"invalid-priority",message:r,option:t,key:e,priority:i})),i}_initializeSync(e){this._syncMode=!0,this._initializeCommon(e)}async _initializeAsync(e){return this._syncMode=!1,new Promise(t=>{setImmediate(()=>{this._initializeCommon(e),t(this)})})}_initializeCommon(e){const t={...e};delete t.sync,delete t.async;const s={windowDuration:t.coalescingWindowDuration??200,maxDelay:t.coalescingMaxDelay??1e3,multipleCallbacks:t.coalescingMultipleCallbacks??!1,resolveAllPromises:t.coalescingResolveAllPromises??!0};[{old:"coalescingWindowDuration",new:"coalescing.defaults.windowDuration"},{old:"coalescingMaxDelay",new:"coalescing.defaults.maxDelay"},{old:"coalescingMultipleCallbacks",new:"coalescing.defaults.multipleCallbacks"},{old:"coalescingResolveAllPromises",new:"coalescing.defaults.resolveAllPromises"}].forEach(({old:d,new:l})=>{t[d]!==void 0&&setImmediate(()=>this.emit("warning",{type:"deprecation",message:`Option '${d}' is deprecated. Use '${l}' instead.`,deprecated:d,replacement:l}))});const r=t.coalescing||{},n=k._transformDelayProperties({...s,...r.defaults},this),a={};if(r.keys&&typeof r.keys=="object")for(const[d,l]of Object.entries(r.keys))l!=null&&(a[d]=k._transformDelayProperties(l,this));const o={};if(t.priorities&&typeof t.priorities=="object")for(const[d,l]of Object.entries(t.priorities)){if(l==null)continue;const c=this._resolvePriorityKey(d,"priorities");c!==null&&(o[c]=k._transformDelayProperties(l,this))}if(t.delays&&typeof t.delays=="object"){setImmediate(()=>this.emit("warning",{type:"deprecation",message:"Option 'delays' is deprecated. Use 'priorities' instead with { [priority]: { postDelay: value, startDelay: 0 } } format.",deprecated:"delays",replacement:"priorities"}));for(const[d,l]of Object.entries(t.delays)){if(l==null)continue;const c=this._resolvePriorityKey(d,"delays");c!==null&&(o[c]={postDelay:l,startDelay:0,...o[c]||{}})}}const h={...t};delete h.priorities,delete h.delays,delete h.coalescing;let y=h.maxQueue;y===-1&&(y=1/0),delete h.maxQueue,this.options={concurrency:1,tick:25,autoStart:!0,defaultPriority:0,maxQueue:y!==void 0?y:1/0,priorities:o,smartScheduling:!0,healingInterval:5e3,coalescing:{defaults:n,keys:a},coalescingWindowDuration:s.windowDuration,coalescingMaxDelay:s.maxDelay,coalescingMultipleCallbacks:s.multipleCallbacks,coalescingResolveAllPromises:s.resolveAllPromises,...h},this.pendingHeap=new b((d,l)=>d.readyAt-l.readyAt),this.readyHeap=new b((d,l)=>d.priority!==l.priority?l.priority-d.priority:d.readyAt!==l.readyAt?d.readyAt-l.readyAt:d.enqueueSeq-l.enqueueSeq),this.running=new Set,this.runningByPriority=new Map,this.tasks=new Map,this.nextId=1,this.enqueueSeq=1,this.isActive=!1,this.destroyed=!1,this.lastCompletedPriority=null,this.nextAvailableTime=0,this.schedulerTimeout=null,this.healingInterval=null,this.lastSchedulerRun=0,this.intervalId=null,this.coalescingGroups=new Map,this.coalescingRepresentatives=new Map,this.nextGroupId=1,this._warnedTaskOptions=new Set,this.options.autoStart&&this.resume()}static async _create(e={}){return new k({...e,sync:!1})}enqueue(e,t,s={}){if(this.destroyed){const u=new Error("Queue is destroyed");return setImmediate(()=>this.emit("error",{error:u,task:e,options:t})),Promise.reject(u)}if(this.tasks.size>=this.options.maxQueue){const u=new Error("Queue is full");return setImmediate(()=>this.emit("error",{error:u,task:e,options:t})),Promise.reject(u)}let i=null,r=s;typeof t=="function"?i=t:t&&typeof t=="object"&&(r={...t,...s}),r=this._normalizeTaskDelayOptions(r);const n=r.id?String(r.id):String(this.nextId++);if(r.id&&this.tasks.has(n)){const u=new Error(`Task with ID '${n}' already exists`);return setImmediate(()=>this.emit("error",{error:u,task:e,options:r})),Promise.reject(u)}const a=this.now();if(r.coalescingKey)return this._handleCoalescingTask(n,e,i,r,a);const o=r.priority??this.options.defaultPriority,y=this.getPriorityConfig(o,r).startDelay??0,d=r.timestamp??(y?a+y:a);let l=null;r.expire!==void 0&&(r.expire===-1?l=null:r.expire>a?l=r.expire:l=a+r.expire);const c={id:n,task:e,callback:i,priority:o,readyAt:d,expireAt:l,enqueueSeq:this.enqueueSeq++,status:"pending",signal:r.signal,timeout:r.timeout,delay:r.postDelay,bypassDelay:r.bypassDelay||r.postDelay===-1,metadata:r.metadata};this.tasks.set(n,c),this.pendingHeap.push(c),r.signal?.aborted?this.cancel(n,"Task was aborted"):r.signal&&r.signal.addEventListener("abort",()=>{this.cancel(n,"Task was aborted")}),this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this._scheduleNextTick());const m=this.tasks,f={id:n,cancel:g(u=>this.cancel(n,u),"cancel"),status:g(()=>m.get(n)?.status??"canceled","status"),get startedAt(){return m.get(n)?.startedAt},get finishedAt(){return m.get(n)?.finishedAt},get result(){return m.get(n)?.result},get error(){return m.get(n)?.error},get metadata(){return m.get(n)?.metadata},get coalescingInfo(){return null}};if(!i){const u=new Promise((p,A)=>{c.resolve=p,c.reject=A});return c.promise=u,Object.defineProperty(u,"id",{value:n,enumerable:!0}),Object.defineProperty(u,"cancel",{value:g(p=>this.cancel(n,p),"value"),enumerable:!0}),Object.defineProperty(u,"status",{value:g(()=>{const p=this.tasks.get(n);return p?p.status:u._status??"canceled"},"value"),enumerable:!0}),Object.defineProperty(u,"startedAt",{get:g(()=>{const p=this.tasks.get(n);return p?p.startedAt:u._startedAt},"get"),enumerable:!0}),Object.defineProperty(u,"finishedAt",{get:g(()=>{const p=this.tasks.get(n);return p?p.finishedAt:u._finishedAt},"get"),enumerable:!0}),Object.defineProperty(u,"result",{get:g(()=>{const p=this.tasks.get(n);return p?p.result:u._result},"get"),enumerable:!0}),Object.defineProperty(u,"error",{get:g(()=>{const p=this.tasks.get(n);return p?p.error:u._error},"get"),enumerable:!0}),Object.defineProperty(u,"metadata",{get:g(()=>{const p=this.tasks.get(n);return p?p.metadata:void 0},"get"),enumerable:!0}),Object.defineProperty(u,"coalescingInfo",{get:g(()=>null,"get"),enumerable:!0}),u}return f}_handleCoalescingTask(e,t,s,i,r){const{coalescingKey:n}=i,a=this.getCoalescingConfig(n,i),o=i.priority??this.options.defaultPriority,h=this.getPriorityConfig(o,i),y=i.startDelay??a.startDelay??h.startDelay??0,d=i.timestamp??(y?r+y:r),l=r+a.windowDuration,c=r+a.maxDelay,m=i.postDelay??a.postDelay??h.postDelay,f={id:e,task:t,callback:s,priority:o,readyAt:d,status:"coalescing",signal:i.signal,timeout:i.timeout,delay:m,bypassDelay:i.bypassDelay||i.postDelay===-1,metadata:i.metadata,coalescingKey:n,enqueueSeq:this.enqueueSeq++};if(i.signal?.aborted){if(f.status="canceled",s)try{s(new Error("Task was aborted"),null)}catch(p){this.emit("error",{...f,error:p,callbackError:!0})}return this._createTaskHandle(f,s)}i.signal?.addEventListener("abort",()=>{this._cancelCoalescingTask(e,n,"Task was aborted")});const u=this._findCompatibleCoalescingGroup(n,r);return u?this._addToCoalescingGroup(u,f,l,c):this._createCoalescingGroup(n,f,l,c,a.multipleCallbacks,a.resolveAllPromises),this._createTaskHandle(f,s)}_findCompatibleCoalescingGroup(e,t){const s=this.coalescingGroups.get(e);if(!s)return null;for(const i of s)if(t<=i.windowEnd&&t<=i.mustRunBy)return i;return null}_createCoalescingGroup(e,t,s,i,r,n){const a=String(this.nextId++),o=String(this.nextGroupId++),h={id:a,task:this._createCoalescingRepresentativeTask(e,o),callback:null,priority:t.priority,readyAt:t.readyAt,expireAt:null,enqueueSeq:this.enqueueSeq++,status:"pending",signal:null,timeout:t.timeout,delay:t.delay||0,bypassDelay:t.bypassDelay||!1,metadata:{coalescingKey:e,groupId:o,representative:!0},isCoalescingRepresentative:!0},y={coalescingKey:e,groupId:o,tasks:new Map([[t.id,t]]),representativeId:a,windowEnd:s,mustRunBy:i,multipleCallbacks:r,resolveAllPromises:n,latestTask:t,originalTask:t.task};return this.coalescingGroups.has(e)||this.coalescingGroups.set(e,[]),this.coalescingGroups.get(e).push(y),this.coalescingRepresentatives.set(a,{coalescingKey:e,groupId:o}),this.tasks.set(a,h),this.pendingHeap.push(h),this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this._scheduleNextTick()),y}_addToCoalescingGroup(e,t,s,i){e.tasks.set(t.id,t),e.mustRunBy=Math.min(e.mustRunBy,i),e.latestTask=t,e.originalTask=t.task;const r=this.tasks.get(e.representativeId);r&&(r.readyAt=t.readyAt,r.priority=t.priority,r.timeout=t.timeout,r.delay=t.delay||r.delay,r.bypassDelay=t.bypassDelay||r.bypassDelay,this._rebuildHeaps(),this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this._scheduleNextTick()))}_createCoalescingRepresentativeTask(e,t){return async s=>{const r=this.coalescingGroups.get(e)?.find(n=>n.groupId===t);if(!r)throw new Error(`Coalescing group ${e}:${t} not found`);try{const n=await r.originalTask(s);return this._resolveCoalescingGroup(r,null,n),n}catch(n){throw this._resolveCoalescingGroup(r,n,null),n}finally{this._cleanupCoalescingGroup(e,t)}}}_resolveCoalescingGroup(e,t,s){if(e.multipleCallbacks){for(const i of e.tasks.values())if(i.status!=="canceled")if(i.status=t?"error":"completed",i.finishedAt=this.now(),t?i.error=t:i.result=s,i.callback)try{t?i.callback(t,null):i.callback(null,s)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.resolve&&(t?i.reject(t):i.resolve(s));for(const i of e.tasks.values())i.status==="canceled"&&i.reject&&i.reject(new Error("Task was canceled"))}else{for(const i of e.tasks.values())if(i.status!=="canceled")if(i===e.latestTask)if(i.status=t?"error":"completed",i.finishedAt=this.now(),t?i.error=t:i.result=s,i.callback)try{t?i.callback(t,null):i.callback(null,s)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.resolve&&(t?i.reject(t):i.resolve(s));else if(e.resolveAllPromises)if(i.status=t?"error":"coalesced",i.finishedAt=this.now(),t?i.error=t:i.result=s,i.callback)try{t?i.callback(t,null):i.callback(null,s)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.resolve&&(t?i.reject(t):i.resolve(s));else if(i.status="coalesced",i.finishedAt=this.now(),i.callback)try{i.callback(new Error("Task was coalesced with a newer task"),null)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.reject&&i.reject(new Error("Task was coalesced with a newer task"));for(const i of e.tasks.values())i.status==="canceled"&&i.reject&&i.reject(new Error("Task was canceled"))}}_cancelCoalescingTask(e,t,s){const i=this.coalescingGroups.get(t)||[];for(const r of i){const n=r.tasks.get(e);if(n){if(n.status="canceled",n.finishedAt=this.now(),n.callback)try{n.callback(new Error(s),null)}catch(a){this.emit("error",{...n,error:a,callbackError:!0})}else n.reject&&n.reject(new Error(s));if(r.tasks.delete(e),r.tasks.size===0)this.tasks.get(r.representativeId)&&this.cancel(r.representativeId,"All coalesced tasks canceled"),this._cleanupCoalescingGroup(t,r.groupId);else{const a=Array.from(r.tasks.values());r.latestTask=a[a.length-1],r.originalTask=r.latestTask.task}return}}}_cleanupCoalescingGroup(e,t){const s=this.coalescingGroups.get(e);if(!s)return;const i=s.findIndex(r=>r.groupId===t);if(i>=0){const r=s[i];s.splice(i,1),this.coalescingRepresentatives.delete(r.representativeId),s.length===0&&this.coalescingGroups.delete(e)}}_rebuildHeaps(){const e=[...this.pendingHeap.heap];this.pendingHeap=new b((s,i)=>s.readyAt-i.readyAt);for(const s of e)this.pendingHeap.push(s);const t=[...this.readyHeap.heap];this.readyHeap=new b((s,i)=>s.priority!==i.priority?i.priority-s.priority:s.readyAt!==i.readyAt?s.readyAt-i.readyAt:s.enqueueSeq-i.enqueueSeq);for(const s of t)this.readyHeap.push(s)}_createTaskHandle(e,t){const s={id:e.id,cancel:g(i=>{e.coalescingKey?this._cancelCoalescingTask(e.id,e.coalescingKey,i||"Task canceled"):this.cancel(e.id,i||"Task canceled")},"cancel"),status:g(()=>e.status,"status"),get startedAt(){return e.startedAt},get finishedAt(){return e.finishedAt},get result(){return e.result},get error(){return e.error},get metadata(){if(e.coalescingKey){const i=this.findCoalescingGroupByTaskId(e.id);return i?i.task.metadata:e.metadata}return e.metadata},get coalescingInfo(){if(!e.coalescingKey)return null;const i=this.findCoalescingGroupByTaskId(e.id);return i?{coalescingKey:i.coalescingKey,groupId:i.groupId,representativeId:i.representativeId,taskCount:i.groupTasks.length,allTaskMetadata:i.groupTasks.map(r=>({id:r.id,metadata:r.metadata}))}:null}};if(!t){const i=new Promise((r,n)=>{e.resolve=r,e.reject=n});return e.promise=i,Object.defineProperty(i,"id",{value:e.id,enumerable:!0}),Object.defineProperty(i,"cancel",{value:s.cancel,enumerable:!0}),Object.defineProperty(i,"status",{value:s.status,enumerable:!0}),Object.defineProperty(i,"startedAt",{get:g(()=>i._startedAt!==void 0?i._startedAt:e.startedAt,"get"),enumerable:!0}),Object.defineProperty(i,"finishedAt",{get:g(()=>i._finishedAt!==void 0?i._finishedAt:e.finishedAt,"get"),enumerable:!0}),Object.defineProperty(i,"result",{get:g(()=>i._result!==void 0?i._result:e.result,"get"),enumerable:!0}),Object.defineProperty(i,"error",{get:g(()=>i._error!==void 0?i._error:e.error,"get"),enumerable:!0}),Object.defineProperty(i,"metadata",{get:g(()=>{if(e.coalescingKey){const r=this.findCoalescingGroupByTaskId(e.id);return r?r.task.metadata:e.metadata}return e.metadata},"get"),enumerable:!0}),Object.defineProperty(i,"coalescingInfo",{get:g(()=>{if(!e.coalescingKey)return null;const r=this.findCoalescingGroupByTaskId(e.id);return r?{coalescingKey:r.coalescingKey,groupId:r.groupId,representativeId:r.representativeId,taskCount:r.groupTasks.length,allTaskMetadata:r.groupTasks.map(n=>({id:n.id,metadata:n.metadata}))}:null},"get"),enumerable:!0}),i}return s}cancel(e,t){const s=this.tasks.get(e);return!s||s.status!=="pending"?!1:(s.status="canceled",s.finishedAt=this.now(),this.tasks.delete(e),this.emit("cancel",s,t),!s.callback&&s.reject&&s.reject(new Error(t||"Task canceled")),!0)}cancelTask(e,t){return this.cancel(e,t)}pause(){this.isActive=!1,this.options.smartScheduling?this.clearSchedulerTimers():this.clearTimers()}resume(){this.destroyed||(this.isActive=!0,this.options.smartScheduling?(this.startHealingInterval(),this.pendingHeap.size()>0||this.readyHeap.size()>0?this.runScheduler():this.scheduleSmartTimeout()):((this.pendingHeap.size()>0||this.readyHeap.size()>0)&&this.schedulerTick(),this._scheduleNextTick()))}clear(){const e=[];for(;this.pendingHeap.size()>0;){const t=this.pendingHeap.pop();t&&t.status==="pending"&&e.push(t)}for(const t of e)t.status="canceled",this.emit("cancel",t);for(const[t,s]of this.coalescingGroups)for(const i of s)for(const r of i.tasks.values())if(r.status="canceled",r.callback)try{r.callback(new Error("Queue cleared"),null)}catch(n){this.emit("error",{...r,error:n,callbackError:!0})}else r.reject&&r.reject(new Error("Queue cleared"));this.pendingHeap=new b((t,s)=>t.readyAt-s.readyAt),this.readyHeap=new b((t,s)=>t.priority!==s.priority?s.priority-t.priority:t.readyAt!==s.readyAt?t.readyAt-s.readyAt:t.enqueueSeq-s.enqueueSeq),this.tasks.clear(),this.coalescingGroups.clear(),this.coalescingRepresentatives.clear(),this.isActive&&this.options.smartScheduling&&this.scheduleSmartTimeout()}size(){return this.tasks.size}length(){return this.tasks.size}inflight(){return this.running.size}getCoalescingGroup(e,t=null){const s=this.coalescingGroups.get(e);if(!s||s.length===0)return null;if(t===null)return s.map(r=>({coalescingKey:r.coalescingKey,groupId:r.groupId,representativeId:r.representativeId,windowEnd:r.windowEnd,mustRunBy:r.mustRunBy,taskCount:r.tasks.size,tasks:Array.from(r.tasks.entries()).map(([n,a])=>({id:n,metadata:a.metadata,status:a.status,priority:a.priority,readyAt:a.readyAt,coalescingKey:a.coalescingKey}))}));const i=s.find(r=>r.groupId===t);return i?{coalescingKey:i.coalescingKey,groupId:i.groupId,representativeId:i.representativeId,windowEnd:i.windowEnd,mustRunBy:i.mustRunBy,taskCount:i.tasks.size,tasks:Array.from(i.tasks.entries()).map(([r,n])=>({id:r,metadata:n.metadata,status:n.status,priority:n.priority,readyAt:n.readyAt,coalescingKey:n.coalescingKey}))}:null}getCoalescingGroupMetadata(e,t=null){const s=this.coalescingGroups.get(e);if(!s||s.length===0)return[];const i=t?s.filter(n=>n.groupId===t):s,r=[];for(const n of i)for(const[a,o]of n.tasks)r.push({taskId:a,groupId:n.groupId,metadata:o.metadata});return r}getCoalescingGroupsSummary(){const e={};for(const[t,s]of this.coalescingGroups){const i=s.reduce((r,n)=>r+n.tasks.size,0);e[t]={groupCount:s.length,totalTasks:i}}return e}findCoalescingGroupByTaskId(e){for(const[t,s]of this.coalescingGroups)for(const i of s){const r=i.tasks.get(e);if(r)return{coalescingKey:t,groupId:i.groupId,representativeId:i.representativeId,windowEnd:i.windowEnd,mustRunBy:i.mustRunBy,task:{id:e,metadata:r.metadata,status:r.status,priority:r.priority,readyAt:r.readyAt},groupTasks:Array.from(i.tasks.entries()).map(([n,a])=>({id:n,metadata:a.metadata,status:a.status}))}}return null}destroy(){this.destroyed=!0,this.pause(),this.clear(),this.emit("drain")}now(){return this.options.now?.()??Date.now()}_scheduleNextTick(){if(!this.isActive||this.destroyed)return;this.clearTimers();const e=this.now();let t=1/0;const s=this.pendingHeap.peek();if(s&&(t=s.readyAt),this.nextAvailableTime>e&&(t=Math.min(t,this.nextAvailableTime)),t===1/0&&this.readyHeap.size()>0&&(t=e),t<=e+this.options.tick)this.intervalId=setInterval(()=>this.schedulerTick(),this.options.tick);else{const i=Math.min(t-e,2147483647);this.timeoutId=setTimeout(()=>this.schedulerTick(),i)}}schedulerTick(){const e=this.now();let t=this.pendingHeap.peek();for(;t&&t.readyAt<=e;){const n=this.pendingHeap.pop();n&&n.status==="pending"&&(n.expireAt&&e>=n.expireAt?this._expireTask(n):(n.status="ready",this.readyHeap.push(n))),t=this.pendingHeap.peek()}let s=!1;const i=this.now(),r=i<this.nextAvailableTime;for(;this.readyHeap.size()>0;){const n=this.readyHeap.peek();if(!n)break;if(n.expireAt&&i>=n.expireAt){this.readyHeap.pop(),this._expireTask(n);continue}const a=this._canStartTask(n),o=n.bypassDelay||!r;if(a&&o)this.readyHeap.pop(),this._startTask(n);else if(a){const y=this.readyHeap.heap.slice();let d=!1;for(let l=0;l<y.length;l++){const c=y[l];if(c.expireAt&&i>=c.expireAt){const m=y.filter(f=>f.id!==c.id);this.readyHeap.heap=[];for(const f of m)this.readyHeap.push(f);this._expireTask(c),y.splice(l,1),l--;continue}if(c.bypassDelay){d=!0;const m=y.filter(f=>f.id!==c.id);this.readyHeap.heap=[];for(const f of m)this.readyHeap.push(f);this._startTask(c);break}}if(!d){s=!0;break}}else{const y=this.readyHeap.heap.slice();let d=!1;for(let l=0;l<y.length;l++){const c=y[l];if(c.expireAt&&i>=c.expireAt){const u=y.filter(p=>p.id!==c.id);this.readyHeap.heap=[];for(const p of u)this.readyHeap.push(p);this._expireTask(c),y.splice(l,1),l--;continue}const m=this._canStartTask(c),f=c.bypassDelay||!r;if(m&&f){d=!0;const u=y.filter(p=>p.id!==c.id);this.readyHeap.heap=[];for(const p of u)this.readyHeap.push(p);this._startTask(c);break}}if(!d){s=!0;break}}}!this.options.smartScheduling&&(this.pendingHeap.size()>0||this.readyHeap.size()>0||s)&&this._scheduleNextTick()}_canStartTask(e){if(this.running.size>=this.options.concurrency)return!1;const t=this.options.priorities[e.priority];return!(t&&typeof t.concurrency=="number"&&(this.runningByPriority.get(e.priority)||0)>=t.concurrency)}_expireTask(e){if(e.status==="expired"||e.status==="canceled"||e.status==="completed")return;e.status="expired",this.tasks.delete(e.id),this.running.delete(e);const t=new Error(`Task expired after waiting ${this.now()-(e.readyAt||this.now())}ms in queue`);if(t.type="expire",t.taskId=e.id,e.callback){try{e.callback(t,null)}catch(s){this.emit("error",{error:s,task:e})}this._emitTaskError({error:t,task:e})}else e.reject&&e.reject(t)}_emitTaskError(e){this.listenerCount("error")>0&&this.emit("error",e)}async _startTask(e){if(e.status!=="ready")return;if(!e.callback&&e.signal?.aborted){e.reject(new Error("Task was aborted"));return}e.status="running",e.startedAt=this.now(),this.running.add(e);const t=this.runningByPriority.get(e.priority)||0;this.runningByPriority.set(e.priority,t+1),this.emit("start",e);const s=new AbortController;let i;try{let r;e.timeout&&(r=new Promise((o,h)=>{i=setTimeout(()=>{s.abort(),h(new Error(`Task timed out after ${e.timeout}ms`))},e.timeout)}));const n=e.task(s.signal),a=e.timeout?await Promise.race([n,r]):await n;if(e.result=a,e.status="completed",e.finishedAt=this.now(),i&&clearTimeout(i),this.emit("success",e),e.promise&&(e.promise._result=e.result,e.promise._error=e.error,e.promise._startedAt=e.startedAt,e.promise._finishedAt=e.finishedAt,e.promise._status=e.status),e.callback)try{e.callback(null,a)}catch(o){this.emit("error",{...e,error:o,callbackError:!0})}else e.resolve&&e.resolve(a)}catch(r){if(e.error=r,e.status=r.message.includes("timed out")?"timeout":s.signal.aborted||r.name==="AbortError"?"canceled":"error",e.finishedAt=this.now(),e.callback&&this._emitTaskError(e),e.promise&&(e.promise._result=e.result,e.promise._error=e.error,e.promise._startedAt=e.startedAt,e.promise._finishedAt=e.finishedAt,e.promise._status=e.status),e.callback)try{const n=e.status==="timeout"?{type:"timeout",message:r.message}:s.signal.aborted||r.name==="AbortError"?{type:"canceled",message:"Task was aborted"}:{type:"error",error:r};e.callback(n,null)}catch(n){this.emit("error",{...e,error:n,callbackError:!0})}else e.reject&&e.reject(r)}finally{i&&clearTimeout(i),this.running.delete(e);const r=this.runningByPriority.get(e.priority)||0;r>0&&this.runningByPriority.set(e.priority,r-1),this.tasks.delete(e.id);const n=e.priority,a=e.delay,o=this.options.priorities[n]?.postDelay??0,h=a!==void 0?a:o;h>0?(this.lastCompletedPriority=n,this.nextAvailableTime=this.now()+h):(this.lastCompletedPriority=null,this.nextAvailableTime=0),setImmediate(()=>{this.running.size===0&&this.pendingHeap.size()===0&&this.readyHeap.size()===0?this.emit("drain"):this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this.schedulerTick())})}}clearTimers(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0),this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0)}scheduleSmartTimeout(){if(!this.isActive||this.destroyed)return;this.clearSchedulerTimers();const e=this.now();let t=1/0,s=!1;if(this.readyHeap.size()>0&&this.running.size<this.options.concurrency)if(!(e<this.nextAvailableTime))s=!0;else{const n=this.readyHeap.heap.slice();for(const a of n)if(a.bypassDelay&&(!a.expireAt||e<a.expireAt)){s=!0;break}s||(t=Math.min(t,this.nextAvailableTime))}const i=this.pendingHeap.peek();if(i&&(t=Math.min(t,i.readyAt)),s||t<=e+1){setImmediate(()=>this.runScheduler());return}if(t<1/0){const r=Math.min(t-e,2147483647);this.schedulerTimeout=setTimeout(()=>{this.runScheduler()},r)}}runScheduler(){!this.isActive||this.destroyed||(this.lastSchedulerRun=this.now(),this.schedulerTick(),this.scheduleSmartTimeout())}startHealingInterval(){this.healingInterval&&clearInterval(this.healingInterval),this.healingInterval=setInterval(()=>{if(!this.isActive||this.destroyed)return;const e=this.now(),t=this.pendingHeap.size()>0||this.readyHeap.size()>0,s=e-this.lastSchedulerRun;t&&s>this.options.healingInterval&&!this.schedulerTimeout&&(console.warn(`HoldMyTask: Healing scheduler - ${s}ms since last run`),this.runScheduler())},this.options.healingInterval)}clearSchedulerTimers(){this.schedulerTimeout&&(clearTimeout(this.schedulerTimeout),this.schedulerTimeout=null),this.healingInterval&&(clearInterval(this.healingInterval),this.healingInterval=null)}configureCoalescingKey(e,t){if(typeof e!="string"){const n=new Error("coalescingKey must be a string");setImmediate(()=>this.emit("error",{error:n,method:"configureCoalescingKey",coalescingKey:e,config:t}));return}if(typeof t!="object"||t===null){const n=new Error("config must be an object");setImmediate(()=>this.emit("error",{error:n,method:"configureCoalescingKey",coalescingKey:e,config:t}));return}const s=["windowDuration","maxDelay","delay","start","postDelay","startDelay","multipleCallbacks","resolveAllPromises"],i=Object.keys(t).filter(n=>!s.includes(n));if(i.length>0){const n=new Error(`Invalid config keys: ${i.join(", ")}. Valid keys: ${s.join(", ")}`);setImmediate(()=>this.emit("error",{error:n,method:"configureCoalescingKey",coalescingKey:e,config:t,invalidKeys:i}));return}const r=k._transformDelayProperties(t,this);this.options.coalescing.keys[e]={...this.options.coalescing.keys[e],...r}}getCoalescingConfig(e,t={}){const s=this.options.coalescing.keys&&this.options.coalescing.keys[e]||{},i=this.options.coalescing.defaults,r=this.getPriorityConfig(t.priority??this.options.defaultPriority),n=t.postDelay??t.delay??s.postDelay??r.postDelay??i.postDelay,a=t.startDelay??t.start??s.startDelay??r.startDelay??i.startDelay;return{windowDuration:t.coalescingWindowDuration??s.windowDuration??i.windowDuration,maxDelay:t.coalescingMaxDelay??s.maxDelay??i.maxDelay,postDelay:n,startDelay:a,delay:n,start:a,multipleCallbacks:t.coalescingMultipleCallbacks??s.multipleCallbacks??i.multipleCallbacks,resolveAllPromises:t.coalescingResolveAllPromises??s.resolveAllPromises??i.resolveAllPromises}}getCoalescingConfigurations(){const e={};for(const t of Object.keys(this.options.coalescing.keys))e[t]=this.getCoalescingConfig(t);return e}configurePriority(e,t){if(typeof e!="number"){const n=new Error("priority must be a number");setImmediate(()=>this.emit("error",{error:n,method:"configurePriority",priority:e,config:t}));return}if(typeof t!="object"||t===null){const n=new Error("config must be an object");setImmediate(()=>this.emit("error",{error:n,method:"configurePriority",priority:e,config:t}));return}const s=["delay","start","postDelay","startDelay"],i=Object.keys(t).filter(n=>!s.includes(n));if(i.length>0){const n=new Error(`Invalid config keys: ${i.join(", ")}. Valid keys: ${s.join(", ")}`);setImmediate(()=>this.emit("error",{error:n,method:"configurePriority",priority:e,config:t,invalidKeys:i}));return}const r=k._transformDelayProperties(t,this);this.options.priorities[e]={...this.options.priorities[e],...r}}getPriorityConfig(e,t={}){const s=this.options.priorities[e]||{},i=t.postDelay??t.delay??s.postDelay,r=t.startDelay??t.start??s.startDelay;return{postDelay:i,startDelay:r,delay:i,start:r}}getPriorityConfigurations(){const e={};for(const t of Object.keys(this.options.priorities))e[t]=this.getPriorityConfig(parseInt(t));return e}shutdown(){return this.destroy()}schedule(e,t,s={}){return this.enqueue(e,t,s)}add(e,t,s={}){return this.enqueue(e,t,s)}get(e){return this.tasks.get(String(e))||null}has(e){return this.tasks.has(String(e))}getTask(e){return this.get(e)}hasTask(e){return this.has(e)}inspect(){const e=this.now(),t=[...this.pendingHeap.heap].map(o=>({id:o.id,priority:o.priority,readyAt:o.readyAt,readyIn:o.readyAt-e,coalescingKey:o.coalescingKey,metadata:o.metadata,status:"pending"})),s=[...this.readyHeap.heap].map(o=>({id:o.id,priority:o.priority,coalescingKey:o.coalescingKey,metadata:o.metadata,status:"ready"})),i=Array.from(this.running).map(o=>({id:o.id,priority:o.priority,coalescingKey:o.coalescingKey,metadata:o.metadata,startedAt:o.startedAt,runningFor:e-o.startedAt,status:"running"})),r=this.inspectTimers(),n={isActive:this.isActive,isPaused:!this.isActive,smartScheduling:this.options.smartScheduling,concurrency:this.options.concurrency,currentConcurrency:this.running.size,tick:this.options.tick,nextActiveDelay:this.nextAvailableTime>e?this.nextAvailableTime-e:null,priorityConcurrency:{}};for(const[o,h]of this.runningByPriority.entries())if(h>0){const y=this.options.priorities[o];n.priorityConcurrency[o]={running:h,limit:y?.concurrency||this.options.concurrency,available:(y?.concurrency||this.options.concurrency)-h}}for(const[o,h]of Object.entries(this.options.priorities))h.concurrency&&!n.priorityConcurrency[o]&&(n.priorityConcurrency[o]={running:0,limit:h.concurrency,available:h.concurrency});const a={};for(const[o,h]of this.coalescingGroups.entries())a[o]={groupCount:h.size,totalTasks:Array.from(h.values()).reduce((y,d)=>y+d.tasks.size,0),groups:Array.from(h.entries()).map(([y,d])=>({groupId:y,taskCount:d.tasks.size,representativeId:d.representativeId,tasks:Array.from(d.tasks.entries()).map(([l,c])=>({id:c.id,metadata:c.metadata}))}))};return{timestamp:e,scheduler:n,timers:r,queues:{pending:{count:t.length,tasks:t},ready:{count:s.length,tasks:s},running:{count:i.length,tasks:i}},totals:{totalTasks:t.length+s.length+i.length,pendingTasks:t.length,readyTasks:s.length,runningTasks:i.length},coalescing:a,delays:{activeDelays:this.nextAvailableTime>e?1:0,delayDetails:this.nextAvailableTime>e?[{priority:this.lastCompletedPriority,expiresAt:this.nextAvailableTime,expiresIn:this.nextAvailableTime-e}]:[]}}}inspectTimers(){const e=this.now();return{schedulerInterval:{id:this.schedulerInterval,active:this.schedulerInterval!==null,type:"interval"},schedulerTimeout:{id:this.schedulerTimeout,active:this.schedulerTimeout!==null,type:"timeout"},nextScheduledRun:this.nextScheduledRun,nextRunIn:this.nextScheduledRun?this.nextScheduledRun-e:null,smartScheduling:this.options.smartScheduling,tickInterval:this.options.tick}}inspectTasks(){const e=this.now(),t={pending:[],ready:[],running:[],byPriority:{},byCoalescingKey:{},total:0};return[...this.pendingHeap.heap].forEach(s=>{const i={id:s.id,priority:s.priority,readyAt:s.readyAt,readyIn:s.readyAt-e,coalescingKey:s.coalescingKey,metadata:s.metadata};t.pending.push(i),t.total++,t.byPriority[s.priority]||(t.byPriority[s.priority]={pending:0,ready:0,running:0}),t.byPriority[s.priority].pending++,s.coalescingKey&&(t.byCoalescingKey[s.coalescingKey]||(t.byCoalescingKey[s.coalescingKey]={pending:0,ready:0,running:0}),t.byCoalescingKey[s.coalescingKey].pending++)}),[...this.readyHeap.heap].forEach(s=>{const i={id:s.id,priority:s.priority,coalescingKey:s.coalescingKey,metadata:s.metadata};t.ready.push(i),t.total++,t.byPriority[s.priority]||(t.byPriority[s.priority]={pending:0,ready:0,running:0}),t.byPriority[s.priority].ready++,s.coalescingKey&&(t.byCoalescingKey[s.coalescingKey]||(t.byCoalescingKey[s.coalescingKey]={pending:0,ready:0,running:0}),t.byCoalescingKey[s.coalescingKey].ready++)}),Array.from(this.running).forEach(s=>{const i={id:s.id,priority:s.priority,coalescingKey:s.coalescingKey,metadata:s.metadata,startedAt:s.startedAt,runningFor:e-s.startedAt};t.running.push(i),t.total++,t.byPriority[s.priority]||(t.byPriority[s.priority]={pending:0,ready:0,running:0}),t.byPriority[s.priority].running++,s.coalescingKey&&(t.byCoalescingKey[s.coalescingKey]||(t.byCoalescingKey[s.coalescingKey]={pending:0,ready:0,running:0}),t.byCoalescingKey[s.coalescingKey].running++)}),t}inspectScheduler(){const e=this.now();let t=1/0,s=null;if(this.pendingHeap.size()>0){const n=this.pendingHeap.peek();n&&n.readyAt<t&&(t=n.readyAt,s={id:n.id,priority:n.priority,readyAt:n.readyAt,source:"pending"})}if(this.readyHeap.size()>0){const n=this.readyHeap.peek();n&&(t=e,s={id:n.id,priority:n.priority,source:"ready"})}let i=null;this.nextAvailableTime>e&&(i={priority:this.lastCompletedPriority,expiresAt:this.nextAvailableTime});const r={};for(const[n,a]of this.runningByPriority.entries())if(a>0){const o=this.options.priorities[n];r[n]={running:a,limit:o?.concurrency||this.options.concurrency,available:(o?.concurrency||this.options.concurrency)-a}}for(const[n,a]of Object.entries(this.options.priorities))a.concurrency&&!r[n]&&(r[n]={running:0,limit:a.concurrency,available:a.concurrency});return{timestamp:e,isActive:this.isActive,smartScheduling:this.options.smartScheduling,concurrency:this.options.concurrency,currentConcurrency:this.running.size,availableSlots:this.options.concurrency-this.running.size,priorityConcurrency:r,timers:{schedulerInterval:this.schedulerInterval,schedulerTimeout:this.schedulerTimeout,nextScheduledRun:this.nextScheduledRun,nextRunIn:this.nextScheduledRun?this.nextScheduledRun-e:null},nextTask:s?{...s,readyIn:t-e,canRunNow:t<=e&&this.running.size<this.options.concurrency}:null,delays:{hasActiveDelays:this.nextAvailableTime>e,count:this.nextAvailableTime>e?1:0,nextExpiry:i?{...i,expiresIn:i.expiresAt-e}:null},queueCounts:{pending:this.pendingHeap.size(),ready:this.readyHeap.size(),running:this.running.size,total:this.pendingHeap.size()+this.readyHeap.size()+this.running.size}}}debugLog(e=!1){const t=this.inspect();console.log(`
2
+ === HoldMyTask Debug Information ===`),console.log(`Timestamp: ${new Date(t.timestamp).toISOString()}`),console.log(`Status: ${t.scheduler.isActive?"ACTIVE":"PAUSED"}`),console.log(`Smart Scheduling: ${t.scheduler.smartScheduling?"ON":"OFF"}`),console.log(`Concurrency: ${t.scheduler.currentConcurrency}/${t.scheduler.concurrency}`),console.log(`
3
+ --- Queue State ---`),console.log(`Total Tasks: ${t.totals.totalTasks}`),console.log(` Pending: ${t.totals.pendingTasks}`),console.log(` Ready: ${t.totals.readyTasks}`),console.log(` Running: ${t.totals.runningTasks}`),Object.keys(t.scheduler.priorityConcurrency).length>0&&(console.log(`
4
+ --- Priority Concurrency ---`),Object.entries(t.scheduler.priorityConcurrency).forEach(([s,i])=>{console.log(` Priority ${s}: ${i.running}/${i.limit} (${i.available} available)`)})),console.log(`
5
+ --- Timer State ---`),console.log(`Interval: ${t.timers.schedulerInterval.active?`Active (${t.timers.schedulerInterval.id})`:"None"}`),console.log(`Timeout: ${t.timers.schedulerTimeout.active?`Active (${t.timers.schedulerTimeout.id})`:"None"}`),t.timers.nextRunIn!==null&&console.log(`Next Run: ${t.timers.nextRunIn}ms`),t.delays.activeDelays>0&&(console.log(`
6
+ --- Active Delays ---`),t.delays.delayDetails.forEach(s=>{console.log(` Priority ${s.priority}: expires in ${s.expiresIn}ms`)})),Object.keys(t.coalescing).length>0&&(console.log(`
7
+ --- Coalescing Groups ---`),Object.entries(t.coalescing).forEach(([s,i])=>{console.log(` ${s}: ${i.groupCount} groups, ${i.totalTasks} tasks`)})),e&&(console.log(`
8
+ --- Detailed Task Information ---`),t.queues.pending.count>0&&(console.log(`
9
+ Pending Tasks:`),t.queues.pending.tasks.forEach(s=>{console.log(` ${s.id}: priority ${s.priority}, ready in ${s.readyIn}ms`)})),t.queues.ready.count>0&&(console.log(`
10
+ Ready Tasks:`),t.queues.ready.tasks.forEach(s=>{console.log(` ${s.id}: priority ${s.priority}`)})),t.queues.running.count>0&&(console.log(`
11
+ Running Tasks:`),t.queues.running.tasks.forEach(s=>{console.log(` ${s.id}: priority ${s.priority}, running for ${s.runningFor}ms`)}))),console.log(`=====================================
12
+ `)}}export{k as HoldMyTask};
13
+ //# sourceMappingURL=hold-my-task.mjs.map
package/dist/index.cjs CHANGED
@@ -1,37 +1,30 @@
1
1
  /**
2
2
  *
3
3
  * @Project: @cldmv/holdmytask
4
- * @Filename: /src/index.cjs
4
+ * @Filename: src/index.cjs
5
5
  * @Date: 2025-11-08T14:04:10-08:00 (1762639450)
6
6
  * @Author: Nate Corcoran <CLDMV>
7
7
  * @Email: <Shinrai@users.noreply.github.com>
8
8
  * -----
9
9
  * @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
10
- * @Last modified time: 2026-11-01T16:28:46-08:00 (1793579326)
10
+ * @Last modified time: 2026-11-28T10:01:58-08:00 (1795888918)
11
11
  * -----
12
12
  * @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
13
13
  *
14
14
  */
15
15
 
16
16
  /**
17
- * CommonJS entry point for holdmytask
17
+ * @fileoverview CommonJS entry point: the generic CLDMV drop-in shim
18
+ * (CLDMV/.github docs/conventions/package-layout.md).
18
19
  *
19
- * A thin, synchronous wrapper around the ESM entry: it loads ./index.mjs through Node's
20
- * require(esm) and maps it to the historical CommonJS shape (the HoldMyTask class as
21
- * module.exports, plus the class aliases as properties), instead of bundling a second
22
- * copy of the library.
23
- *
24
- * It sits next to the ESM entry under the same name, so require("./index.mjs") resolves
25
- * to src/index.mjs from source and to dist/index.mjs once built. tsup's onSuccess copies
26
- * it verbatim into dist/ (tsup.config.mjs); it never passes through esbuild.
27
- *
28
- * @module holdmytask
20
+ * It returns what `import` gives. holdmytask exports several distinct values (the HoldMyTask
21
+ * class and the create* factories), so `require("@cldmv/holdmytask")` is the module object
22
+ * ({ default, HoldMyTask, createQueue, ... }), not the class. tsup's onSuccess copies this
23
+ * file verbatim into dist/, where `./index.mjs` resolves to the built entry.
24
+ * @module holdmytask/cjs-entry
29
25
  */
30
26
  "use strict";
31
27
 
32
- // index.cjs is a thin wrapper: it loads index.mjs through Node's synchronous require(esm).
33
- // Node.js versions without require(esm) would fail with a bare ERR_REQUIRE_ESM, so fail
34
- // early with a message that says what to do instead.
35
28
  if (!process.features?.require_module) {
36
29
  const error = new Error(
37
30
  `@cldmv/holdmytask: require() needs Node.js ^20.19.0 or >=22.13.0 (this is ${process.version}). On older Node.js, load the package with import() instead.`
@@ -40,16 +33,12 @@ if (!process.features?.require_module) {
40
33
  throw error;
41
34
  }
42
35
 
43
- const { HoldMyTask } = require("./index.mjs");
44
-
45
- // Export main class
46
- module.exports = HoldMyTask; // Default export
47
- module.exports.HoldMyTask = HoldMyTask;
48
-
49
- // Common queue system aliases
50
- module.exports.queue = HoldMyTask;
51
- module.exports.Queue = HoldMyTask;
52
- module.exports.TaskManager = HoldMyTask;
53
- module.exports.TaskQueue = HoldMyTask;
54
- module.exports.QueueManager = HoldMyTask;
55
- module.exports.TaskProcessor = HoldMyTask;
36
+ // Same exports as `import`. One distinct exported value (aliases of it count once) comes back as that value,
37
+ // so require(x)(...) works; anything else comes back as the module object ({ default, ...named }).
38
+ const esm = require("./index.mjs");
39
+ const values = new Set(
40
+ Object.keys(esm)
41
+ .filter((key) => key !== "__esModule")
42
+ .map((key) => esm[key])
43
+ );
44
+ module.exports = values.size === 1 ? values.values().next().value : esm;
package/dist/index.mjs CHANGED
@@ -1,13 +1,2 @@
1
- var v=Object.defineProperty;var g=(m,e)=>v(m,"name",{value:e,configurable:!0});import{EventEmitter as w}from"events";var b=class{static{g(this,"MinHeap")}constructor(e){this.heap=[],this.compare=e}push(e){this.heap.push(e),this.bubbleUp(this.heap.length-1)}pop(){if(this.heap.length===0)return;let e=this.heap[0],t=this.heap.pop();return this.heap.length>0&&(this.heap[0]=t,this.sinkDown(0)),e}peek(){return this.heap[0]}size(){return this.heap.length}bubbleUp(e){for(;e>0;){let t=Math.floor((e-1)/2);if(this.compare(this.heap[e],this.heap[t])>=0)break;[this.heap[e],this.heap[t]]=[this.heap[t],this.heap[e]],e=t}}sinkDown(e){let t=this.heap.length;for(;;){let s=2*e+1,i=2*e+2,r=e;if(s<t&&this.compare(this.heap[s],this.heap[r])<0&&(r=s),i<t&&this.compare(this.heap[i],this.heap[r])<0&&(r=i),r===e)break;[this.heap[e],this.heap[r]]=[this.heap[r],this.heap[e]],e=r}}};var T=class m extends w{static{g(this,"HoldMyTask")}static _transformDelayProperties(e,t=null){if(!e||typeof e!="object")return e;let s={...e};return"start"in e&&!("startDelay"in e)&&(s.startDelay=e.start,t&&setImmediate(()=>t.emit("warning",{type:"deprecation",message:"Property 'start' is deprecated. Use 'startDelay' instead.",deprecated:"start",replacement:"startDelay"}))),delete s.start,"delay"in e&&!("postDelay"in e)&&(s.postDelay=e.delay,t&&setImmediate(()=>t.emit("warning",{type:"deprecation",message:"Property 'delay' is deprecated. Use 'postDelay' instead.",deprecated:"delay",replacement:"postDelay"}))),delete s.delay,s}_normalizeTaskDelayOptions(e){if(!("delay"in e)&&!("start"in e))return e;let t={...e},s=[{deprecated:"start",replacement:"startDelay"},{deprecated:"delay",replacement:"postDelay"}];for(let{deprecated:i,replacement:r}of s)i in e&&(r in e||(t[r]=e[i],this._warnTaskOptionDeprecated(i,r)),delete t[i]);return t}_warnTaskOptionDeprecated(e,t){this._warnedTaskOptions.has(e)||(this._warnedTaskOptions.add(e),setImmediate(()=>this.emit("warning",{type:"deprecation",message:`Task option '${e}' is deprecated. Use '${t}' instead.`,deprecated:e,replacement:t})))}constructor(e={}){if(super(),e.sync!==!1)this._initializeSync(e);else return this._initializeAsync(e)}_resolvePriorityKey(e,t){if(/^-?\d+$/.test(e))return Number(e);let s=parseInt(e),i=isNaN(s)?null:s,r=i===null?`Priority key '${e}' in '${t}' is not an integer and was ignored. Priority keys must be integers.`:`Priority key '${e}' in '${t}' is not an integer; it was applied to priority ${i}. Priority keys must be integers.`;return setImmediate(()=>this.emit("warning",{type:"invalid-priority",message:r,option:t,key:e,priority:i})),i}_initializeSync(e){this._syncMode=!0,this._initializeCommon(e)}async _initializeAsync(e){return this._syncMode=!1,new Promise(t=>{setImmediate(()=>{this._initializeCommon(e),t(this)})})}_initializeCommon(e){let t={...e};delete t.sync,delete t.async;let s={windowDuration:t.coalescingWindowDuration??200,maxDelay:t.coalescingMaxDelay??1e3,multipleCallbacks:t.coalescingMultipleCallbacks??!1,resolveAllPromises:t.coalescingResolveAllPromises??!0};[{old:"coalescingWindowDuration",new:"coalescing.defaults.windowDuration"},{old:"coalescingMaxDelay",new:"coalescing.defaults.maxDelay"},{old:"coalescingMultipleCallbacks",new:"coalescing.defaults.multipleCallbacks"},{old:"coalescingResolveAllPromises",new:"coalescing.defaults.resolveAllPromises"}].forEach(({old:d,new:l})=>{t[d]!==void 0&&setImmediate(()=>this.emit("warning",{type:"deprecation",message:`Option '${d}' is deprecated. Use '${l}' instead.`,deprecated:d,replacement:l}))});let r=t.coalescing||{},n=m._transformDelayProperties({...s,...r.defaults},this),a={};if(r.keys&&typeof r.keys=="object")for(let[d,l]of Object.entries(r.keys))l!=null&&(a[d]=m._transformDelayProperties(l,this));let o={};if(t.priorities&&typeof t.priorities=="object")for(let[d,l]of Object.entries(t.priorities)){if(l==null)continue;let c=this._resolvePriorityKey(d,"priorities");c!==null&&(o[c]=m._transformDelayProperties(l,this))}if(t.delays&&typeof t.delays=="object"){setImmediate(()=>this.emit("warning",{type:"deprecation",message:"Option 'delays' is deprecated. Use 'priorities' instead with { [priority]: { postDelay: value, startDelay: 0 } } format.",deprecated:"delays",replacement:"priorities"}));for(let[d,l]of Object.entries(t.delays)){if(l==null)continue;let c=this._resolvePriorityKey(d,"delays");c!==null&&(o[c]={postDelay:l,startDelay:0,...o[c]||{}})}}let p={...t};delete p.priorities,delete p.delays,delete p.coalescing;let h=p.maxQueue;h===-1&&(h=1/0),delete p.maxQueue,this.options={concurrency:1,tick:25,autoStart:!0,defaultPriority:0,maxQueue:h!==void 0?h:1/0,priorities:o,smartScheduling:!0,healingInterval:5e3,coalescing:{defaults:n,keys:a},coalescingWindowDuration:s.windowDuration,coalescingMaxDelay:s.maxDelay,coalescingMultipleCallbacks:s.multipleCallbacks,coalescingResolveAllPromises:s.resolveAllPromises,...p},this.pendingHeap=new b((d,l)=>d.readyAt-l.readyAt),this.readyHeap=new b((d,l)=>d.priority!==l.priority?l.priority-d.priority:d.readyAt!==l.readyAt?d.readyAt-l.readyAt:d.enqueueSeq-l.enqueueSeq),this.running=new Set,this.runningByPriority=new Map,this.tasks=new Map,this.nextId=1,this.enqueueSeq=1,this.isActive=!1,this.destroyed=!1,this.lastCompletedPriority=null,this.nextAvailableTime=0,this.schedulerTimeout=null,this.healingInterval=null,this.lastSchedulerRun=0,this.intervalId=null,this.coalescingGroups=new Map,this.coalescingRepresentatives=new Map,this.nextGroupId=1,this._warnedTaskOptions=new Set,this.options.autoStart&&this.resume()}static async _create(e={}){return new m({...e,sync:!1})}enqueue(e,t,s={}){if(this.destroyed){let u=new Error("Queue is destroyed");return setImmediate(()=>this.emit("error",{error:u,task:e,options:t})),Promise.reject(u)}if(this.tasks.size>=this.options.maxQueue){let u=new Error("Queue is full");return setImmediate(()=>this.emit("error",{error:u,task:e,options:t})),Promise.reject(u)}let i=null,r=s;typeof t=="function"?i=t:t&&typeof t=="object"&&(r={...t,...s}),r=this._normalizeTaskDelayOptions(r);let n=r.id?String(r.id):String(this.nextId++);if(r.id&&this.tasks.has(n)){let u=new Error(`Task with ID '${n}' already exists`);return setImmediate(()=>this.emit("error",{error:u,task:e,options:r})),Promise.reject(u)}let a=this.now();if(r.coalescingKey)return this._handleCoalescingTask(n,e,i,r,a);let o=r.priority??this.options.defaultPriority,h=this.getPriorityConfig(o,r).startDelay??0,d=r.timestamp??(h?a+h:a),l=null;r.expire!==void 0&&(r.expire===-1?l=null:r.expire>a?l=r.expire:l=a+r.expire);let c={id:n,task:e,callback:i,priority:o,readyAt:d,expireAt:l,enqueueSeq:this.enqueueSeq++,status:"pending",signal:r.signal,timeout:r.timeout,delay:r.postDelay,bypassDelay:r.bypassDelay||r.postDelay===-1,metadata:r.metadata};this.tasks.set(n,c),this.pendingHeap.push(c),r.signal?.aborted?this.cancel(n,"Task was aborted"):r.signal&&r.signal.addEventListener("abort",()=>{this.cancel(n,"Task was aborted")}),this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this._scheduleNextTick());let k=this.tasks,f={id:n,cancel:g(u=>this.cancel(n,u),"cancel"),status:g(()=>k.get(n)?.status??"canceled","status"),get startedAt(){return k.get(n)?.startedAt},get finishedAt(){return k.get(n)?.finishedAt},get result(){return k.get(n)?.result},get error(){return k.get(n)?.error},get metadata(){return k.get(n)?.metadata},get coalescingInfo(){return null}};if(!i){let u=new Promise((y,A)=>{c.resolve=y,c.reject=A});return c.promise=u,Object.defineProperty(u,"id",{value:n,enumerable:!0}),Object.defineProperty(u,"cancel",{value:g(y=>this.cancel(n,y),"value"),enumerable:!0}),Object.defineProperty(u,"status",{value:g(()=>{let y=this.tasks.get(n);return y?y.status:u._status??"canceled"},"value"),enumerable:!0}),Object.defineProperty(u,"startedAt",{get:g(()=>{let y=this.tasks.get(n);return y?y.startedAt:u._startedAt},"get"),enumerable:!0}),Object.defineProperty(u,"finishedAt",{get:g(()=>{let y=this.tasks.get(n);return y?y.finishedAt:u._finishedAt},"get"),enumerable:!0}),Object.defineProperty(u,"result",{get:g(()=>{let y=this.tasks.get(n);return y?y.result:u._result},"get"),enumerable:!0}),Object.defineProperty(u,"error",{get:g(()=>{let y=this.tasks.get(n);return y?y.error:u._error},"get"),enumerable:!0}),Object.defineProperty(u,"metadata",{get:g(()=>{let y=this.tasks.get(n);return y?y.metadata:void 0},"get"),enumerable:!0}),Object.defineProperty(u,"coalescingInfo",{get:g(()=>null,"get"),enumerable:!0}),u}return f}_handleCoalescingTask(e,t,s,i,r){let{coalescingKey:n}=i,a=this.getCoalescingConfig(n,i),o=i.priority??this.options.defaultPriority,p=this.getPriorityConfig(o,i),h=i.startDelay??a.startDelay??p.startDelay??0,d=i.timestamp??(h?r+h:r),l=r+a.windowDuration,c=r+a.maxDelay,k=i.postDelay??a.postDelay??p.postDelay,f={id:e,task:t,callback:s,priority:o,readyAt:d,status:"coalescing",signal:i.signal,timeout:i.timeout,delay:k,bypassDelay:i.bypassDelay||i.postDelay===-1,metadata:i.metadata,coalescingKey:n,enqueueSeq:this.enqueueSeq++};if(i.signal?.aborted){if(f.status="canceled",s)try{s(new Error("Task was aborted"),null)}catch(y){this.emit("error",{...f,error:y,callbackError:!0})}return this._createTaskHandle(f,s)}i.signal?.addEventListener("abort",()=>{this._cancelCoalescingTask(e,n,"Task was aborted")});let u=this._findCompatibleCoalescingGroup(n,r);return u?this._addToCoalescingGroup(u,f,l,c):this._createCoalescingGroup(n,f,l,c,a.multipleCallbacks,a.resolveAllPromises),this._createTaskHandle(f,s)}_findCompatibleCoalescingGroup(e,t){let s=this.coalescingGroups.get(e);if(!s)return null;for(let i of s)if(t<=i.windowEnd&&t<=i.mustRunBy)return i;return null}_createCoalescingGroup(e,t,s,i,r,n){let a=String(this.nextId++),o=String(this.nextGroupId++),p={id:a,task:this._createCoalescingRepresentativeTask(e,o),callback:null,priority:t.priority,readyAt:t.readyAt,expireAt:null,enqueueSeq:this.enqueueSeq++,status:"pending",signal:null,timeout:t.timeout,delay:t.delay||0,bypassDelay:t.bypassDelay||!1,metadata:{coalescingKey:e,groupId:o,representative:!0},isCoalescingRepresentative:!0},h={coalescingKey:e,groupId:o,tasks:new Map([[t.id,t]]),representativeId:a,windowEnd:s,mustRunBy:i,multipleCallbacks:r,resolveAllPromises:n,latestTask:t,originalTask:t.task};return this.coalescingGroups.has(e)||this.coalescingGroups.set(e,[]),this.coalescingGroups.get(e).push(h),this.coalescingRepresentatives.set(a,{coalescingKey:e,groupId:o}),this.tasks.set(a,p),this.pendingHeap.push(p),this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this._scheduleNextTick()),h}_addToCoalescingGroup(e,t,s,i){e.tasks.set(t.id,t),e.mustRunBy=Math.min(e.mustRunBy,i),e.latestTask=t,e.originalTask=t.task;let r=this.tasks.get(e.representativeId);r&&(r.readyAt=t.readyAt,r.priority=t.priority,r.timeout=t.timeout,r.delay=t.delay||r.delay,r.bypassDelay=t.bypassDelay||r.bypassDelay,this._rebuildHeaps(),this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this._scheduleNextTick()))}_createCoalescingRepresentativeTask(e,t){return async s=>{let r=this.coalescingGroups.get(e)?.find(n=>n.groupId===t);if(!r)throw new Error(`Coalescing group ${e}:${t} not found`);try{let n=await r.originalTask(s);return this._resolveCoalescingGroup(r,null,n),n}catch(n){throw this._resolveCoalescingGroup(r,n,null),n}finally{this._cleanupCoalescingGroup(e,t)}}}_resolveCoalescingGroup(e,t,s){if(e.multipleCallbacks){for(let i of e.tasks.values())if(i.status!=="canceled")if(i.status=t?"error":"completed",i.finishedAt=this.now(),t?i.error=t:i.result=s,i.callback)try{t?i.callback(t,null):i.callback(null,s)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.resolve&&(t?i.reject(t):i.resolve(s));for(let i of e.tasks.values())i.status==="canceled"&&i.reject&&i.reject(new Error("Task was canceled"))}else{for(let i of e.tasks.values())if(i.status!=="canceled")if(i===e.latestTask)if(i.status=t?"error":"completed",i.finishedAt=this.now(),t?i.error=t:i.result=s,i.callback)try{t?i.callback(t,null):i.callback(null,s)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.resolve&&(t?i.reject(t):i.resolve(s));else if(e.resolveAllPromises)if(i.status=t?"error":"coalesced",i.finishedAt=this.now(),t?i.error=t:i.result=s,i.callback)try{t?i.callback(t,null):i.callback(null,s)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.resolve&&(t?i.reject(t):i.resolve(s));else if(i.status="coalesced",i.finishedAt=this.now(),i.callback)try{i.callback(new Error("Task was coalesced with a newer task"),null)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.reject&&i.reject(new Error("Task was coalesced with a newer task"));for(let i of e.tasks.values())i.status==="canceled"&&i.reject&&i.reject(new Error("Task was canceled"))}}_cancelCoalescingTask(e,t,s){let i=this.coalescingGroups.get(t)||[];for(let r of i){let n=r.tasks.get(e);if(n){if(n.status="canceled",n.finishedAt=this.now(),n.callback)try{n.callback(new Error(s),null)}catch(a){this.emit("error",{...n,error:a,callbackError:!0})}else n.reject&&n.reject(new Error(s));if(r.tasks.delete(e),r.tasks.size===0)this.tasks.get(r.representativeId)&&this.cancel(r.representativeId,"All coalesced tasks canceled"),this._cleanupCoalescingGroup(t,r.groupId);else{let a=Array.from(r.tasks.values());r.latestTask=a[a.length-1],r.originalTask=r.latestTask.task}return}}}_cleanupCoalescingGroup(e,t){let s=this.coalescingGroups.get(e);if(!s)return;let i=s.findIndex(r=>r.groupId===t);if(i>=0){let r=s[i];s.splice(i,1),this.coalescingRepresentatives.delete(r.representativeId),s.length===0&&this.coalescingGroups.delete(e)}}_rebuildHeaps(){let e=[...this.pendingHeap.heap];this.pendingHeap=new b((s,i)=>s.readyAt-i.readyAt);for(let s of e)this.pendingHeap.push(s);let t=[...this.readyHeap.heap];this.readyHeap=new b((s,i)=>s.priority!==i.priority?i.priority-s.priority:s.readyAt!==i.readyAt?s.readyAt-i.readyAt:s.enqueueSeq-i.enqueueSeq);for(let s of t)this.readyHeap.push(s)}_createTaskHandle(e,t){let s={id:e.id,cancel:g(i=>{e.coalescingKey?this._cancelCoalescingTask(e.id,e.coalescingKey,i||"Task canceled"):this.cancel(e.id,i||"Task canceled")},"cancel"),status:g(()=>e.status,"status"),get startedAt(){return e.startedAt},get finishedAt(){return e.finishedAt},get result(){return e.result},get error(){return e.error},get metadata(){if(e.coalescingKey){let i=this.findCoalescingGroupByTaskId(e.id);return i?i.task.metadata:e.metadata}return e.metadata},get coalescingInfo(){if(!e.coalescingKey)return null;let i=this.findCoalescingGroupByTaskId(e.id);return i?{coalescingKey:i.coalescingKey,groupId:i.groupId,representativeId:i.representativeId,taskCount:i.groupTasks.length,allTaskMetadata:i.groupTasks.map(r=>({id:r.id,metadata:r.metadata}))}:null}};if(!t){let i=new Promise((r,n)=>{e.resolve=r,e.reject=n});return e.promise=i,Object.defineProperty(i,"id",{value:e.id,enumerable:!0}),Object.defineProperty(i,"cancel",{value:s.cancel,enumerable:!0}),Object.defineProperty(i,"status",{value:s.status,enumerable:!0}),Object.defineProperty(i,"startedAt",{get:g(()=>i._startedAt!==void 0?i._startedAt:e.startedAt,"get"),enumerable:!0}),Object.defineProperty(i,"finishedAt",{get:g(()=>i._finishedAt!==void 0?i._finishedAt:e.finishedAt,"get"),enumerable:!0}),Object.defineProperty(i,"result",{get:g(()=>i._result!==void 0?i._result:e.result,"get"),enumerable:!0}),Object.defineProperty(i,"error",{get:g(()=>i._error!==void 0?i._error:e.error,"get"),enumerable:!0}),Object.defineProperty(i,"metadata",{get:g(()=>{if(e.coalescingKey){let r=this.findCoalescingGroupByTaskId(e.id);return r?r.task.metadata:e.metadata}return e.metadata},"get"),enumerable:!0}),Object.defineProperty(i,"coalescingInfo",{get:g(()=>{if(!e.coalescingKey)return null;let r=this.findCoalescingGroupByTaskId(e.id);return r?{coalescingKey:r.coalescingKey,groupId:r.groupId,representativeId:r.representativeId,taskCount:r.groupTasks.length,allTaskMetadata:r.groupTasks.map(n=>({id:n.id,metadata:n.metadata}))}:null},"get"),enumerable:!0}),i}return s}cancel(e,t){let s=this.tasks.get(e);return!s||s.status!=="pending"?!1:(s.status="canceled",s.finishedAt=this.now(),this.tasks.delete(e),this.emit("cancel",s,t),!s.callback&&s.reject&&s.reject(new Error(t||"Task canceled")),!0)}cancelTask(e,t){return this.cancel(e,t)}pause(){this.isActive=!1,this.options.smartScheduling?this.clearSchedulerTimers():this.clearTimers()}resume(){this.destroyed||(this.isActive=!0,this.options.smartScheduling?(this.startHealingInterval(),this.pendingHeap.size()>0||this.readyHeap.size()>0?this.runScheduler():this.scheduleSmartTimeout()):((this.pendingHeap.size()>0||this.readyHeap.size()>0)&&this.schedulerTick(),this._scheduleNextTick()))}clear(){let e=[];for(;this.pendingHeap.size()>0;){let t=this.pendingHeap.pop();t&&t.status==="pending"&&e.push(t)}for(let t of e)t.status="canceled",this.emit("cancel",t);for(let[t,s]of this.coalescingGroups)for(let i of s)for(let r of i.tasks.values())if(r.status="canceled",r.callback)try{r.callback(new Error("Queue cleared"),null)}catch(n){this.emit("error",{...r,error:n,callbackError:!0})}else r.reject&&r.reject(new Error("Queue cleared"));this.pendingHeap=new b((t,s)=>t.readyAt-s.readyAt),this.readyHeap=new b((t,s)=>t.priority!==s.priority?s.priority-t.priority:t.readyAt!==s.readyAt?t.readyAt-s.readyAt:t.enqueueSeq-s.enqueueSeq),this.tasks.clear(),this.coalescingGroups.clear(),this.coalescingRepresentatives.clear(),this.isActive&&this.options.smartScheduling&&this.scheduleSmartTimeout()}size(){return this.tasks.size}length(){return this.tasks.size}inflight(){return this.running.size}getCoalescingGroup(e,t=null){let s=this.coalescingGroups.get(e);if(!s||s.length===0)return null;if(t===null)return s.map(r=>({coalescingKey:r.coalescingKey,groupId:r.groupId,representativeId:r.representativeId,windowEnd:r.windowEnd,mustRunBy:r.mustRunBy,taskCount:r.tasks.size,tasks:Array.from(r.tasks.entries()).map(([n,a])=>({id:n,metadata:a.metadata,status:a.status,priority:a.priority,readyAt:a.readyAt,coalescingKey:a.coalescingKey}))}));let i=s.find(r=>r.groupId===t);return i?{coalescingKey:i.coalescingKey,groupId:i.groupId,representativeId:i.representativeId,windowEnd:i.windowEnd,mustRunBy:i.mustRunBy,taskCount:i.tasks.size,tasks:Array.from(i.tasks.entries()).map(([r,n])=>({id:r,metadata:n.metadata,status:n.status,priority:n.priority,readyAt:n.readyAt,coalescingKey:n.coalescingKey}))}:null}getCoalescingGroupMetadata(e,t=null){let s=this.coalescingGroups.get(e);if(!s||s.length===0)return[];let i=t?s.filter(n=>n.groupId===t):s,r=[];for(let n of i)for(let[a,o]of n.tasks)r.push({taskId:a,groupId:n.groupId,metadata:o.metadata});return r}getCoalescingGroupsSummary(){let e={};for(let[t,s]of this.coalescingGroups){let i=s.reduce((r,n)=>r+n.tasks.size,0);e[t]={groupCount:s.length,totalTasks:i}}return e}findCoalescingGroupByTaskId(e){for(let[t,s]of this.coalescingGroups)for(let i of s){let r=i.tasks.get(e);if(r)return{coalescingKey:t,groupId:i.groupId,representativeId:i.representativeId,windowEnd:i.windowEnd,mustRunBy:i.mustRunBy,task:{id:e,metadata:r.metadata,status:r.status,priority:r.priority,readyAt:r.readyAt},groupTasks:Array.from(i.tasks.entries()).map(([n,a])=>({id:n,metadata:a.metadata,status:a.status}))}}return null}destroy(){this.destroyed=!0,this.pause(),this.clear(),this.emit("drain")}now(){return this.options.now?.()??Date.now()}_scheduleNextTick(){if(!this.isActive||this.destroyed)return;this.clearTimers();let e=this.now(),t=1/0,s=this.pendingHeap.peek();if(s&&(t=s.readyAt),this.nextAvailableTime>e&&(t=Math.min(t,this.nextAvailableTime)),t===1/0&&this.readyHeap.size()>0&&(t=e),t<=e+this.options.tick)this.intervalId=setInterval(()=>this.schedulerTick(),this.options.tick);else{let i=Math.min(t-e,2147483647);this.timeoutId=setTimeout(()=>this.schedulerTick(),i)}}schedulerTick(){let e=this.now(),t=this.pendingHeap.peek();for(;t&&t.readyAt<=e;){let n=this.pendingHeap.pop();n&&n.status==="pending"&&(n.expireAt&&e>=n.expireAt?this._expireTask(n):(n.status="ready",this.readyHeap.push(n))),t=this.pendingHeap.peek()}let s=!1,i=this.now(),r=i<this.nextAvailableTime;for(;this.readyHeap.size()>0;){let n=this.readyHeap.peek();if(!n)break;if(n.expireAt&&i>=n.expireAt){this.readyHeap.pop(),this._expireTask(n);continue}let a=this._canStartTask(n),o=n.bypassDelay||!r;if(a&&o)this.readyHeap.pop(),this._startTask(n);else if(a){let h=this.readyHeap.heap.slice(),d=!1;for(let l=0;l<h.length;l++){let c=h[l];if(c.expireAt&&i>=c.expireAt){let k=h.filter(f=>f.id!==c.id);this.readyHeap.heap=[];for(let f of k)this.readyHeap.push(f);this._expireTask(c),h.splice(l,1),l--;continue}if(c.bypassDelay){d=!0;let k=h.filter(f=>f.id!==c.id);this.readyHeap.heap=[];for(let f of k)this.readyHeap.push(f);this._startTask(c);break}}if(!d){s=!0;break}}else{let h=this.readyHeap.heap.slice(),d=!1;for(let l=0;l<h.length;l++){let c=h[l];if(c.expireAt&&i>=c.expireAt){let u=h.filter(y=>y.id!==c.id);this.readyHeap.heap=[];for(let y of u)this.readyHeap.push(y);this._expireTask(c),h.splice(l,1),l--;continue}let k=this._canStartTask(c),f=c.bypassDelay||!r;if(k&&f){d=!0;let u=h.filter(y=>y.id!==c.id);this.readyHeap.heap=[];for(let y of u)this.readyHeap.push(y);this._startTask(c);break}}if(!d){s=!0;break}}}!this.options.smartScheduling&&(this.pendingHeap.size()>0||this.readyHeap.size()>0||s)&&this._scheduleNextTick()}_canStartTask(e){if(this.running.size>=this.options.concurrency)return!1;let t=this.options.priorities[e.priority];return!(t&&typeof t.concurrency=="number"&&(this.runningByPriority.get(e.priority)||0)>=t.concurrency)}_expireTask(e){if(e.status==="expired"||e.status==="canceled"||e.status==="completed")return;e.status="expired",this.tasks.delete(e.id),this.running.delete(e);let t=new Error(`Task expired after waiting ${this.now()-(e.readyAt||this.now())}ms in queue`);if(t.type="expire",t.taskId=e.id,e.callback){try{e.callback(t,null)}catch(s){this.emit("error",{error:s,task:e})}this._emitTaskError({error:t,task:e})}else e.reject&&e.reject(t)}_emitTaskError(e){this.listenerCount("error")>0&&this.emit("error",e)}async _startTask(e){if(e.status!=="ready")return;if(!e.callback&&e.signal?.aborted){e.reject(new Error("Task was aborted"));return}e.status="running",e.startedAt=this.now(),this.running.add(e);let t=this.runningByPriority.get(e.priority)||0;this.runningByPriority.set(e.priority,t+1),this.emit("start",e);let s=new AbortController,i;try{let r;e.timeout&&(r=new Promise((o,p)=>{i=setTimeout(()=>{s.abort(),p(new Error(`Task timed out after ${e.timeout}ms`))},e.timeout)}));let n=e.task(s.signal),a=e.timeout?await Promise.race([n,r]):await n;if(e.result=a,e.status="completed",e.finishedAt=this.now(),i&&clearTimeout(i),this.emit("success",e),e.promise&&(e.promise._result=e.result,e.promise._error=e.error,e.promise._startedAt=e.startedAt,e.promise._finishedAt=e.finishedAt,e.promise._status=e.status),e.callback)try{e.callback(null,a)}catch(o){this.emit("error",{...e,error:o,callbackError:!0})}else e.resolve&&e.resolve(a)}catch(r){if(e.error=r,e.status=r.message.includes("timed out")?"timeout":s.signal.aborted||r.name==="AbortError"?"canceled":"error",e.finishedAt=this.now(),e.callback&&this._emitTaskError(e),e.promise&&(e.promise._result=e.result,e.promise._error=e.error,e.promise._startedAt=e.startedAt,e.promise._finishedAt=e.finishedAt,e.promise._status=e.status),e.callback)try{let n=e.status==="timeout"?{type:"timeout",message:r.message}:s.signal.aborted||r.name==="AbortError"?{type:"canceled",message:"Task was aborted"}:{type:"error",error:r};e.callback(n,null)}catch(n){this.emit("error",{...e,error:n,callbackError:!0})}else e.reject&&e.reject(r)}finally{i&&clearTimeout(i),this.running.delete(e);let r=this.runningByPriority.get(e.priority)||0;r>0&&this.runningByPriority.set(e.priority,r-1),this.tasks.delete(e.id);let n=e.priority,a=e.delay,o=this.options.priorities[n]?.postDelay??0,p=a!==void 0?a:o;p>0?(this.lastCompletedPriority=n,this.nextAvailableTime=this.now()+p):(this.lastCompletedPriority=null,this.nextAvailableTime=0),setImmediate(()=>{this.running.size===0&&this.pendingHeap.size()===0&&this.readyHeap.size()===0?this.emit("drain"):this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this.schedulerTick())})}}clearTimers(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0),this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0)}scheduleSmartTimeout(){if(!this.isActive||this.destroyed)return;this.clearSchedulerTimers();let e=this.now(),t=1/0,s=!1;if(this.readyHeap.size()>0&&this.running.size<this.options.concurrency)if(!(e<this.nextAvailableTime))s=!0;else{let n=this.readyHeap.heap.slice();for(let a of n)if(a.bypassDelay&&(!a.expireAt||e<a.expireAt)){s=!0;break}s||(t=Math.min(t,this.nextAvailableTime))}let i=this.pendingHeap.peek();if(i&&(t=Math.min(t,i.readyAt)),s||t<=e+1){setImmediate(()=>this.runScheduler());return}if(t<1/0){let r=Math.min(t-e,2147483647);this.schedulerTimeout=setTimeout(()=>{this.runScheduler()},r)}}runScheduler(){!this.isActive||this.destroyed||(this.lastSchedulerRun=this.now(),this.schedulerTick(),this.scheduleSmartTimeout())}startHealingInterval(){this.healingInterval&&clearInterval(this.healingInterval),this.healingInterval=setInterval(()=>{if(!this.isActive||this.destroyed)return;let e=this.now(),t=this.pendingHeap.size()>0||this.readyHeap.size()>0,s=e-this.lastSchedulerRun;t&&s>this.options.healingInterval&&!this.schedulerTimeout&&(console.warn(`HoldMyTask: Healing scheduler - ${s}ms since last run`),this.runScheduler())},this.options.healingInterval)}clearSchedulerTimers(){this.schedulerTimeout&&(clearTimeout(this.schedulerTimeout),this.schedulerTimeout=null),this.healingInterval&&(clearInterval(this.healingInterval),this.healingInterval=null)}configureCoalescingKey(e,t){if(typeof e!="string"){let n=new Error("coalescingKey must be a string");setImmediate(()=>this.emit("error",{error:n,method:"configureCoalescingKey",coalescingKey:e,config:t}));return}if(typeof t!="object"||t===null){let n=new Error("config must be an object");setImmediate(()=>this.emit("error",{error:n,method:"configureCoalescingKey",coalescingKey:e,config:t}));return}let s=["windowDuration","maxDelay","delay","start","postDelay","startDelay","multipleCallbacks","resolveAllPromises"],i=Object.keys(t).filter(n=>!s.includes(n));if(i.length>0){let n=new Error(`Invalid config keys: ${i.join(", ")}. Valid keys: ${s.join(", ")}`);setImmediate(()=>this.emit("error",{error:n,method:"configureCoalescingKey",coalescingKey:e,config:t,invalidKeys:i}));return}let r=m._transformDelayProperties(t,this);this.options.coalescing.keys[e]={...this.options.coalescing.keys[e],...r}}getCoalescingConfig(e,t={}){let s=this.options.coalescing.keys&&this.options.coalescing.keys[e]||{},i=this.options.coalescing.defaults,r=this.getPriorityConfig(t.priority??this.options.defaultPriority),n=t.postDelay??t.delay??s.postDelay??r.postDelay??i.postDelay,a=t.startDelay??t.start??s.startDelay??r.startDelay??i.startDelay;return{windowDuration:t.coalescingWindowDuration??s.windowDuration??i.windowDuration,maxDelay:t.coalescingMaxDelay??s.maxDelay??i.maxDelay,postDelay:n,startDelay:a,delay:n,start:a,multipleCallbacks:t.coalescingMultipleCallbacks??s.multipleCallbacks??i.multipleCallbacks,resolveAllPromises:t.coalescingResolveAllPromises??s.resolveAllPromises??i.resolveAllPromises}}getCoalescingConfigurations(){let e={};for(let t of Object.keys(this.options.coalescing.keys))e[t]=this.getCoalescingConfig(t);return e}configurePriority(e,t){if(typeof e!="number"){let n=new Error("priority must be a number");setImmediate(()=>this.emit("error",{error:n,method:"configurePriority",priority:e,config:t}));return}if(typeof t!="object"||t===null){let n=new Error("config must be an object");setImmediate(()=>this.emit("error",{error:n,method:"configurePriority",priority:e,config:t}));return}let s=["delay","start","postDelay","startDelay"],i=Object.keys(t).filter(n=>!s.includes(n));if(i.length>0){let n=new Error(`Invalid config keys: ${i.join(", ")}. Valid keys: ${s.join(", ")}`);setImmediate(()=>this.emit("error",{error:n,method:"configurePriority",priority:e,config:t,invalidKeys:i}));return}let r=m._transformDelayProperties(t,this);this.options.priorities[e]={...this.options.priorities[e],...r}}getPriorityConfig(e,t={}){let s=this.options.priorities[e]||{},i=t.postDelay??t.delay??s.postDelay,r=t.startDelay??t.start??s.startDelay;return{postDelay:i,startDelay:r,delay:i,start:r}}getPriorityConfigurations(){let e={};for(let t of Object.keys(this.options.priorities))e[t]=this.getPriorityConfig(parseInt(t));return e}shutdown(){return this.destroy()}schedule(e,t,s={}){return this.enqueue(e,t,s)}add(e,t,s={}){return this.enqueue(e,t,s)}get(e){return this.tasks.get(String(e))||null}has(e){return this.tasks.has(String(e))}getTask(e){return this.get(e)}hasTask(e){return this.has(e)}inspect(){let e=this.now(),t=[...this.pendingHeap.heap].map(o=>({id:o.id,priority:o.priority,readyAt:o.readyAt,readyIn:o.readyAt-e,coalescingKey:o.coalescingKey,metadata:o.metadata,status:"pending"})),s=[...this.readyHeap.heap].map(o=>({id:o.id,priority:o.priority,coalescingKey:o.coalescingKey,metadata:o.metadata,status:"ready"})),i=Array.from(this.running).map(o=>({id:o.id,priority:o.priority,coalescingKey:o.coalescingKey,metadata:o.metadata,startedAt:o.startedAt,runningFor:e-o.startedAt,status:"running"})),r=this.inspectTimers(),n={isActive:this.isActive,isPaused:!this.isActive,smartScheduling:this.options.smartScheduling,concurrency:this.options.concurrency,currentConcurrency:this.running.size,tick:this.options.tick,nextActiveDelay:this.nextAvailableTime>e?this.nextAvailableTime-e:null,priorityConcurrency:{}};for(let[o,p]of this.runningByPriority.entries())if(p>0){let h=this.options.priorities[o];n.priorityConcurrency[o]={running:p,limit:h?.concurrency||this.options.concurrency,available:(h?.concurrency||this.options.concurrency)-p}}for(let[o,p]of Object.entries(this.options.priorities))p.concurrency&&!n.priorityConcurrency[o]&&(n.priorityConcurrency[o]={running:0,limit:p.concurrency,available:p.concurrency});let a={};for(let[o,p]of this.coalescingGroups.entries())a[o]={groupCount:p.size,totalTasks:Array.from(p.values()).reduce((h,d)=>h+d.tasks.size,0),groups:Array.from(p.entries()).map(([h,d])=>({groupId:h,taskCount:d.tasks.size,representativeId:d.representativeId,tasks:Array.from(d.tasks.entries()).map(([l,c])=>({id:c.id,metadata:c.metadata}))}))};return{timestamp:e,scheduler:n,timers:r,queues:{pending:{count:t.length,tasks:t},ready:{count:s.length,tasks:s},running:{count:i.length,tasks:i}},totals:{totalTasks:t.length+s.length+i.length,pendingTasks:t.length,readyTasks:s.length,runningTasks:i.length},coalescing:a,delays:{activeDelays:this.nextAvailableTime>e?1:0,delayDetails:this.nextAvailableTime>e?[{priority:this.lastCompletedPriority,expiresAt:this.nextAvailableTime,expiresIn:this.nextAvailableTime-e}]:[]}}}inspectTimers(){let e=this.now();return{schedulerInterval:{id:this.schedulerInterval,active:this.schedulerInterval!==null,type:"interval"},schedulerTimeout:{id:this.schedulerTimeout,active:this.schedulerTimeout!==null,type:"timeout"},nextScheduledRun:this.nextScheduledRun,nextRunIn:this.nextScheduledRun?this.nextScheduledRun-e:null,smartScheduling:this.options.smartScheduling,tickInterval:this.options.tick}}inspectTasks(){let e=this.now(),t={pending:[],ready:[],running:[],byPriority:{},byCoalescingKey:{},total:0};return[...this.pendingHeap.heap].forEach(s=>{let i={id:s.id,priority:s.priority,readyAt:s.readyAt,readyIn:s.readyAt-e,coalescingKey:s.coalescingKey,metadata:s.metadata};t.pending.push(i),t.total++,t.byPriority[s.priority]||(t.byPriority[s.priority]={pending:0,ready:0,running:0}),t.byPriority[s.priority].pending++,s.coalescingKey&&(t.byCoalescingKey[s.coalescingKey]||(t.byCoalescingKey[s.coalescingKey]={pending:0,ready:0,running:0}),t.byCoalescingKey[s.coalescingKey].pending++)}),[...this.readyHeap.heap].forEach(s=>{let i={id:s.id,priority:s.priority,coalescingKey:s.coalescingKey,metadata:s.metadata};t.ready.push(i),t.total++,t.byPriority[s.priority]||(t.byPriority[s.priority]={pending:0,ready:0,running:0}),t.byPriority[s.priority].ready++,s.coalescingKey&&(t.byCoalescingKey[s.coalescingKey]||(t.byCoalescingKey[s.coalescingKey]={pending:0,ready:0,running:0}),t.byCoalescingKey[s.coalescingKey].ready++)}),Array.from(this.running).forEach(s=>{let i={id:s.id,priority:s.priority,coalescingKey:s.coalescingKey,metadata:s.metadata,startedAt:s.startedAt,runningFor:e-s.startedAt};t.running.push(i),t.total++,t.byPriority[s.priority]||(t.byPriority[s.priority]={pending:0,ready:0,running:0}),t.byPriority[s.priority].running++,s.coalescingKey&&(t.byCoalescingKey[s.coalescingKey]||(t.byCoalescingKey[s.coalescingKey]={pending:0,ready:0,running:0}),t.byCoalescingKey[s.coalescingKey].running++)}),t}inspectScheduler(){let e=this.now(),t=1/0,s=null;if(this.pendingHeap.size()>0){let n=this.pendingHeap.peek();n&&n.readyAt<t&&(t=n.readyAt,s={id:n.id,priority:n.priority,readyAt:n.readyAt,source:"pending"})}if(this.readyHeap.size()>0){let n=this.readyHeap.peek();n&&(t=e,s={id:n.id,priority:n.priority,source:"ready"})}let i=null;this.nextAvailableTime>e&&(i={priority:this.lastCompletedPriority,expiresAt:this.nextAvailableTime});let r={};for(let[n,a]of this.runningByPriority.entries())if(a>0){let o=this.options.priorities[n];r[n]={running:a,limit:o?.concurrency||this.options.concurrency,available:(o?.concurrency||this.options.concurrency)-a}}for(let[n,a]of Object.entries(this.options.priorities))a.concurrency&&!r[n]&&(r[n]={running:0,limit:a.concurrency,available:a.concurrency});return{timestamp:e,isActive:this.isActive,smartScheduling:this.options.smartScheduling,concurrency:this.options.concurrency,currentConcurrency:this.running.size,availableSlots:this.options.concurrency-this.running.size,priorityConcurrency:r,timers:{schedulerInterval:this.schedulerInterval,schedulerTimeout:this.schedulerTimeout,nextScheduledRun:this.nextScheduledRun,nextRunIn:this.nextScheduledRun?this.nextScheduledRun-e:null},nextTask:s?{...s,readyIn:t-e,canRunNow:t<=e&&this.running.size<this.options.concurrency}:null,delays:{hasActiveDelays:this.nextAvailableTime>e,count:this.nextAvailableTime>e?1:0,nextExpiry:i?{...i,expiresIn:i.expiresAt-e}:null},queueCounts:{pending:this.pendingHeap.size(),ready:this.readyHeap.size(),running:this.running.size,total:this.pendingHeap.size()+this.readyHeap.size()+this.running.size}}}debugLog(e=!1){let t=this.inspect();console.log(`
2
- === HoldMyTask Debug Information ===`),console.log(`Timestamp: ${new Date(t.timestamp).toISOString()}`),console.log(`Status: ${t.scheduler.isActive?"ACTIVE":"PAUSED"}`),console.log(`Smart Scheduling: ${t.scheduler.smartScheduling?"ON":"OFF"}`),console.log(`Concurrency: ${t.scheduler.currentConcurrency}/${t.scheduler.concurrency}`),console.log(`
3
- --- Queue State ---`),console.log(`Total Tasks: ${t.totals.totalTasks}`),console.log(` Pending: ${t.totals.pendingTasks}`),console.log(` Ready: ${t.totals.readyTasks}`),console.log(` Running: ${t.totals.runningTasks}`),Object.keys(t.scheduler.priorityConcurrency).length>0&&(console.log(`
4
- --- Priority Concurrency ---`),Object.entries(t.scheduler.priorityConcurrency).forEach(([s,i])=>{console.log(` Priority ${s}: ${i.running}/${i.limit} (${i.available} available)`)})),console.log(`
5
- --- Timer State ---`),console.log(`Interval: ${t.timers.schedulerInterval.active?`Active (${t.timers.schedulerInterval.id})`:"None"}`),console.log(`Timeout: ${t.timers.schedulerTimeout.active?`Active (${t.timers.schedulerTimeout.id})`:"None"}`),t.timers.nextRunIn!==null&&console.log(`Next Run: ${t.timers.nextRunIn}ms`),t.delays.activeDelays>0&&(console.log(`
6
- --- Active Delays ---`),t.delays.delayDetails.forEach(s=>{console.log(` Priority ${s.priority}: expires in ${s.expiresIn}ms`)})),Object.keys(t.coalescing).length>0&&(console.log(`
7
- --- Coalescing Groups ---`),Object.entries(t.coalescing).forEach(([s,i])=>{console.log(` ${s}: ${i.groupCount} groups, ${i.totalTasks} tasks`)})),e&&(console.log(`
8
- --- Detailed Task Information ---`),t.queues.pending.count>0&&(console.log(`
9
- Pending Tasks:`),t.queues.pending.tasks.forEach(s=>{console.log(` ${s.id}: priority ${s.priority}, ready in ${s.readyIn}ms`)})),t.queues.ready.count>0&&(console.log(`
10
- Ready Tasks:`),t.queues.ready.tasks.forEach(s=>{console.log(` ${s.id}: priority ${s.priority}`)})),t.queues.running.count>0&&(console.log(`
11
- Running Tasks:`),t.queues.running.tasks.forEach(s=>{console.log(` ${s.id}: priority ${s.priority}, running for ${s.runningFor}ms`)}))),console.log(`=====================================
12
- `)}};async function E(m={}){return new T(m)}g(E,"createHoldMyTask");async function j(m={}){return new T(m)}g(j,"createQueue");async function K(m={}){return new T(m)}g(K,"createTaskManager");async function z(m={}){return new T(m)}g(z,"createTaskProcessor");export{T as HoldMyTask,T as Queue,T as QueueManager,T as TaskManager,T as TaskProcessor,T as TaskQueue,E as createHoldMyTask,j as createQueue,K as createTaskManager,z as createTaskProcessor,T as default,T as queue};
13
- //# sourceMappingURL=index.mjs.map
1
+ var n=Object.defineProperty;var a=(r,t)=>n(r,"name",{value:t,configurable:!0});import{HoldMyTask as e}from"./hold-my-task.mjs";async function u(r={}){return new e(r)}a(u,"createHoldMyTask");async function c(r={}){return new e(r)}a(c,"createQueue");async function p(r={}){return new e(r)}a(p,"createTaskManager");async function x(r={}){return new e(r)}a(x,"createTaskProcessor");export{e as HoldMyTask,e as Queue,e as QueueManager,e as TaskManager,e as TaskProcessor,e as TaskQueue,u as createHoldMyTask,c as createQueue,p as createTaskManager,x as createTaskProcessor,e as default,e as queue};
2
+ //# sourceMappingURL=index.mjs.map
package/dist/main.mjs CHANGED
@@ -1,2 +1,2 @@
1
- export*from"./index.mjs";import{default as r}from"./index.mjs";var e='"@cldmv/holdmytask/main" is deprecated; import "@cldmv/holdmytask" instead.';typeof process<"u"&&typeof process.emitWarning=="function"?process.emitWarning(e,{type:"DeprecationWarning",code:"CLDMV_HOLDMYTASK_MAIN"}):console.warn(`DeprecationWarning: ${e}`);export{r as default};
2
- //# sourceMappingURL=main.mjs.map
1
+ const e='"@cldmv/holdmytask/main" is deprecated; import "@cldmv/holdmytask" instead.';typeof process<"u"&&typeof process.emitWarning=="function"?process.emitWarning(e,{type:"DeprecationWarning",code:"CLDMV_HOLDMYTASK_MAIN"}):console.warn(`DeprecationWarning: ${e}`);export*from"./index.mjs";import{default as r}from"./index.mjs";export{r as default};
2
+ //# sourceMappingURL=main.mjs.map
package/dist/utils.mjs ADDED
@@ -0,0 +1,2 @@
1
+ var r=Object.defineProperty;var i=(a,h)=>r(a,"name",{value:h,configurable:!0});class o{static{i(this,"MinHeap")}constructor(h){this.heap=[],this.compare=h}push(h){this.heap.push(h),this.bubbleUp(this.heap.length-1)}pop(){if(this.heap.length===0)return;const h=this.heap[0],t=this.heap.pop();return this.heap.length>0&&(this.heap[0]=t,this.sinkDown(0)),h}peek(){return this.heap[0]}size(){return this.heap.length}bubbleUp(h){for(;h>0;){const t=Math.floor((h-1)/2);if(this.compare(this.heap[h],this.heap[t])>=0)break;[this.heap[h],this.heap[t]]=[this.heap[t],this.heap[h]],h=t}}sinkDown(h){const t=this.heap.length;for(;;){let s=2*h+1,p=2*h+2,e=h;if(s<t&&this.compare(this.heap[s],this.heap[e])<0&&(e=s),p<t&&this.compare(this.heap[p],this.heap[e])<0&&(e=p),e===h)break;[this.heap[h],this.heap[e]]=[this.heap[e],this.heap[h]],h=e}}}export{o as MinHeap};
2
+ //# sourceMappingURL=utils.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cldmv/holdmytask",
3
- "version": "2.1.2",
3
+ "version": "3.0.0",
4
4
  "description": "A tiny task queue that waits until your task is ready",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.mjs",
@@ -36,17 +36,18 @@
36
36
  }
37
37
  },
38
38
  "scripts": {
39
- "test": "node tests/run-vitest.mjs && npm run test:cjs",
39
+ "test": "node tests/run-vitest.mjs && npm run test:cjs && npm run test:dist",
40
40
  "test:cjs": "npm run build && node --conditions=holdmytask-dev --test tests/cjs/entry.test.cjs",
41
+ "test:dist": "npm run build && node tests/run-vitest.mjs --mode=dist",
41
42
  "test:watch": "vitest --config .configs/vitest.config.mjs",
42
43
  "types:check": "tsc --noEmit --project .configs/tsconfig.dts.jsonc",
43
44
  "coverage": "node tests/run-vitest.mjs --coverage-quiet && npm run test:cjs",
44
- "ci:coverage": "npm run coverage",
45
+ "ci:coverage": "npm run coverage && npm run test:dist",
45
46
  "lint": "eslint --config .configs/eslint.config.mjs .",
46
47
  "lint:fix": "eslint --config .configs/eslint.config.mjs . --fix",
47
48
  "format": "prettier --config .configs/.prettierrc --write .",
48
49
  "format:check": "prettier --config .configs/.prettierrc --check .",
49
- "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsup",
50
+ "build": "node scripts/build.mjs",
50
51
  "types:build": "tsc --project .configs/tsconfig.dts.jsonc",
51
52
  "build:ci": "npm run lint && npm run format:check && npm run types:build && npm run types:check && npm run build",
52
53
  "prepack": "npm run build",
@@ -97,22 +98,22 @@
97
98
  "minimatch": "^11.0.3"
98
99
  },
99
100
  "devDependencies": {
100
- "@cldmv/configs": "^1.4.0",
101
- "@cldmv/fix-headers": "^2.2.4",
102
- "@cldmv/vitest-runner": "^1.5.6",
101
+ "@cldmv/configs": "^1.5.0",
102
+ "@cldmv/fix-headers": "^2.6.1",
103
+ "@cldmv/vitest-runner": "^1.11.4",
103
104
  "@eslint/css": "^2.0.1",
104
105
  "@eslint/js": "^10.0.1",
105
106
  "@eslint/json": "^2.1.1",
106
107
  "@eslint/markdown": "^8.0.3",
107
- "@html-eslint/eslint-plugin": "^0.67.0",
108
- "@html-eslint/parser": "^0.67.0",
108
+ "@html-eslint/eslint-plugin": "^0.69.0",
109
+ "@html-eslint/parser": "^0.69.0",
109
110
  "@types/node": "^26.6.6",
110
111
  "@vitest/coverage-v8": "^5.0.5",
111
112
  "@vitest/ui": "^5.0.5",
113
+ "esbuild": "^0.28.2",
112
114
  "eslint": "^10.14.0",
113
115
  "globals": "^17.14.0",
114
116
  "prettier": "^3.9.10",
115
- "tsup": "^9.0.0",
116
117
  "typescript": "^6.0.3",
117
118
  "vitest": "^5.0.5"
118
119
  },
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  *
3
3
  * @Project: @cldmv/holdmytask
4
- * @Filename: /src/utils.mjs
4
+ * @Filename: src/utils.mjs
5
5
  * @Date: 2025-11-08T17:43:09-08:00 (1762652589)
6
6
  * @Author: Nate Corcoran <CLDMV>
7
7
  * @Email: <Shinrai@users.noreply.github.com>
8
8
  * -----
9
9
  * @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
10
- * @Last modified time: 2026-10-02T12:20:29-07:00 (1790968829)
10
+ * @Last modified time: 2026-11-28T10:01:59-08:00 (1795888919)
11
11
  * -----
12
12
  * @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
13
13
  *