@lunora/scheduler 1.0.0-alpha.7 → 1.0.0-alpha.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +4 -3
  2. package/dist/index.d.mts +870 -411
  3. package/dist/index.d.ts +870 -411
  4. package/dist/index.mjs +1 -8
  5. package/dist/packem_shared/CRON_SCHEDULE_KINDS-xyFk800s.mjs +1 -0
  6. package/dist/packem_shared/MAX_RETRY_ATTEMPTS-CoEnaemn.mjs +1 -0
  7. package/dist/packem_shared/assertScheduleDelay-BgA4K1WB.mjs +1 -0
  8. package/dist/packem_shared/assertScheduleInstant-BzESPqyw.mjs +1 -0
  9. package/dist/packem_shared/assertValidCronExpression-DnBtukpq.mjs +1 -0
  10. package/dist/packem_shared/base64-BFBvYeZM.mjs +1 -0
  11. package/dist/packem_shared/createCronTrigger-DSuDZtqj.mjs +1 -0
  12. package/dist/packem_shared/createQueueConsumer-DWWfGYKN.mjs +1 -0
  13. package/dist/packem_shared/createScheduler-BW6wVD57.mjs +1 -0
  14. package/dist/packem_shared/createSchedulerHost-CO6BlgVY.mjs +1 -0
  15. package/dist/packem_shared/createWorkpool-CQs6z3Y0.mjs +1 -0
  16. package/dist/packem_shared/do-client-XQayNStI.mjs +1 -0
  17. package/dist/packem_shared/isWorkflowReference-CT3tdefh.mjs +1 -0
  18. package/dist/packem_shared/resolveScheduleId-DgysKSrN.mjs +1 -0
  19. package/dist/packem_shared/wire-codec-TIVAE0Ds.mjs +1 -0
  20. package/package.json +4 -3
  21. package/dist/packem_shared/CRON_SCHEDULE_KINDS-BMVeCHOu.mjs +0 -130
  22. package/dist/packem_shared/SchedulerDO-DVeJrNbs.mjs +0 -675
  23. package/dist/packem_shared/assertValidCronExpression-B9m75qU0.mjs +0 -24
  24. package/dist/packem_shared/createCronTrigger-Dh4VLxD9.mjs +0 -28
  25. package/dist/packem_shared/createQueueConsumer-Cy-Mp-El.mjs +0 -61
  26. package/dist/packem_shared/createScheduler-CcD09oIm.mjs +0 -70
  27. package/dist/packem_shared/createWorkpool-C28trhTA.mjs +0 -63
  28. package/dist/packem_shared/isWorkflowReference-C9mQkMXt.mjs +0 -3
  29. package/dist/packem_shared/jurisdiction-CR2zC3Et.mjs +0 -13
package/dist/index.mjs CHANGED
@@ -1,8 +1 @@
1
- export { default as createScheduler } from './packem_shared/createScheduler-CcD09oIm.mjs';
2
- export { default as createWorkpool } from './packem_shared/createWorkpool-C28trhTA.mjs';
3
- export { createCronTrigger } from './packem_shared/createCronTrigger-Dh4VLxD9.mjs';
4
- export { CRON_SCHEDULE_KINDS, compileCronSchedule, cronJobs } from './packem_shared/CRON_SCHEDULE_KINDS-BMVeCHOu.mjs';
5
- export { createQueueConsumer, createQueueWorkpool, httpDispatcher } from './packem_shared/createQueueConsumer-Cy-Mp-El.mjs';
6
- export { SchedulerDO } from './packem_shared/SchedulerDO-DVeJrNbs.mjs';
7
- export { isWorkflowReference } from './packem_shared/isWorkflowReference-C9mQkMXt.mjs';
8
- export { assertValidCronExpression, isValidCronExpression } from './packem_shared/assertValidCronExpression-B9m75qU0.mjs';
1
+ import{default as o}from"./packem_shared/createScheduler-BW6wVD57.mjs";import{default as a}from"./packem_shared/createWorkpool-CQs6z3Y0.mjs";import{createCronTrigger as f}from"./packem_shared/createCronTrigger-DSuDZtqj.mjs";import{CRON_SCHEDULE_KINDS as p,compileCronSchedule as c,cronJobs as d}from"./packem_shared/CRON_SCHEDULE_KINDS-xyFk800s.mjs";import{createQueueConsumer as m,createQueueWorkpool as n,httpDispatcher as x}from"./packem_shared/createQueueConsumer-DWWfGYKN.mjs";import{default as i}from"./packem_shared/resolveScheduleId-DgysKSrN.mjs";import{MAX_RETRY_ATTEMPTS as E,RETRY_BASE_DELAY_MS as C,SchedulerDO as _}from"./packem_shared/MAX_RETRY_ATTEMPTS-CoEnaemn.mjs";import{createSchedulerHost as R}from"./packem_shared/createSchedulerHost-CO6BlgVY.mjs";import{isWorkflowReference as A}from"./packem_shared/isWorkflowReference-CT3tdefh.mjs";import{assertValidCronExpression as g,isValidCronExpression as k,warnIfSecondsLeading as L}from"./packem_shared/assertValidCronExpression-DnBtukpq.mjs";import{default as W}from"./packem_shared/assertScheduleDelay-BgA4K1WB.mjs";import{default as w}from"./packem_shared/assertScheduleInstant-BzESPqyw.mjs";export{p as CRON_SCHEDULE_KINDS,E as MAX_RETRY_ATTEMPTS,C as RETRY_BASE_DELAY_MS,_ as SchedulerDO,W as assertScheduleDelay,w as assertScheduleInstant,g as assertValidCronExpression,c as compileCronSchedule,f as createCronTrigger,m as createQueueConsumer,n as createQueueWorkpool,o as createScheduler,R as createSchedulerHost,a as createWorkpool,d as cronJobs,x as httpDispatcher,k as isValidCronExpression,A as isWorkflowReference,i as resolveScheduleId,L as warnIfSecondsLeading};
@@ -0,0 +1 @@
1
+ import{LunoraError as l}from"@lunora/errors";import{isWorkflowReference as m}from"./isWorkflowReference-CT3tdefh.mjs";import{assertValidCronExpression as f}from"./assertValidCronExpression-DnBtukpq.mjs";const w={friday:5,monday:1,saturday:6,sunday:0,thursday:4,tuesday:2,wednesday:3},T=24,h=" For a daily or longer schedule use crons.daily(name, { hourUTC, minuteUTC }, …), crons.weekly(name, { dayOfWeek, hourUTC, minuteUTC }, …) or crons.monthly(name, { day, hourUTC, minuteUTC }, …).",a=(e,o,r,i)=>{if(!Number.isInteger(e)||e<r||e>i)throw new l("INTERNAL",`@lunora/scheduler: cronJobs ${o} must be an integer in [${r.toFixed(0)}, ${i.toFixed(0)}], got ${String(e)}`);return e.toFixed(0)},y=(e,o,r)=>{const i=a(e,o,1,r-1);if(r%e!==0)throw new l("INTERNAL",`@lunora/scheduler: ${o} must evenly divide ${r.toFixed(0)} for a fixed "every ${e.toFixed(0)}" interval — cron "*/${e.toFixed(0)}" means "at values divisible by ${e.toFixed(0)}", which wraps unevenly; pick a divisor of ${r.toFixed(0)}`);return i},$=(e,o)=>{const r=["seconds","minutes","hours"].filter(s=>e[s]!==void 0);if(r.length!==1){const s=Object.entries(e).filter(([,t])=>t!==void 0).map(([t])=>t);throw new l("INTERNAL",`@lunora/scheduler: interval schedule must specify exactly one of { seconds, minutes, hours }, got { ${s.join(", ")} }.${h}`)}const i=r[0],n=e[i];if(i==="hours"&&n>=T)throw new l("INTERNAL",`@lunora/scheduler: interval.hours is capped at 23, got ${String(n)} — an interval repeats WITHIN a day rather than spanning one.${h}`);if(i==="seconds")throw new l("INTERNAL",`@lunora/scheduler: cron job${o?` "${o}"`:""} uses interval.seconds (${String(n)}) — Cloudflare Cron Triggers have a one-minute floor and cannot run sub-minute schedules; \`wrangler deploy\` would reject the resulting 6-field cron expression. Use ctx.scheduler.runAfter/runAt (optionally via a workpool for bounded concurrency) for sub-minute recurrence, or crons.interval(name, { minutes: 1 }, …) for the fastest cron-native cadence.`);return i==="minutes"?`*/${y(n,"interval.minutes",60)} * * * *`:`0 */${y(n,"interval.hours",24)} * * *`},p=e=>`${a(e.minuteUTC,"hourly.minuteUTC",0,59)} * * * *`,C=e=>{const o=a(e.minuteUTC,"daily.minuteUTC",0,59),r=a(e.hourUTC,"daily.hourUTC",0,23);return`${o} ${r} * * *`},N=e=>{const o=w[e.dayOfWeek];if(o===void 0)throw new l("INTERNAL",`@lunora/scheduler: weekly schedule has invalid dayOfWeek "${e.dayOfWeek}"`);const r=a(e.minuteUTC,"weekly.minuteUTC",0,59),i=a(e.hourUTC,"weekly.hourUTC",0,23);return`${r} ${i} * * ${o.toFixed(0)}`},U=e=>{const o=a(e.day,"monthly.day",1,31),r=a(e.minuteUTC,"monthly.minuteUTC",0,59),i=a(e.hourUTC,"monthly.hourUTC",0,23);return`${r} ${i} ${o} * *`},b=new Set(["daily","hourly","interval","monthly","weekly"]),c=(e,o,r)=>{switch(e){case"daily":return C(o);case"hourly":return p(o);case"interval":return $(o,r);case"monthly":return U(o);case"weekly":return N(o);default:throw new l("INTERNAL",`@lunora/scheduler: unknown cron schedule kind "${String(e)}"`)}},k=()=>{const e=[],o=new Set,r=(n,s,t,u)=>{if(typeof n!="string"||n.trim()==="")throw new l("INTERNAL","@lunora/scheduler: cron job name must be a non-empty string");if(o.has(n))throw new l("INTERNAL",`@lunora/scheduler: duplicate cron job name "${n}" — names must be unique within one cronJobs()`);let d;if(m(t))d={workflow:typeof t.name=="string"?t.name:""};else if(t&&typeof t.__lunoraRef=="string")d={functionPath:t.__lunoraRef};else throw new l("INTERNAL",`@lunora/scheduler: cron job "${n}" requires a function reference (e.g. internal.email.digest) or a workflow reference`);f(s,`cron expression for job "${n}"`),o.add(n),e.push({args:u??{},cron:s,name:n,...d})},i={cron(n,s,t,u){return r(n,s,t,u),i},daily(n,s,t,u){return r(n,c("daily",s),t,u),i},hourly(n,s,t,u){return r(n,c("hourly",s),t,u),i},interval(n,s,t,u){return r(n,c("interval",s,n),t,u),i},jobs:()=>[...e],monthly(n,s,t,u){return r(n,c("monthly",s),t,u),i},weekly(n,s,t,u){return r(n,c("weekly",s),t,u),i}};return i};export{b as CRON_SCHEDULE_KINDS,c as compileCronSchedule,k as cronJobs};
@@ -0,0 +1 @@
1
+ import{t as b}from"./base64-BFBvYeZM.mjs";import P from"./resolveScheduleId-DgysKSrN.mjs";const I=(u,t=200,e)=>{const s=new Headers({"content-type":"application/json"});for(const[a,n]of Object.entries({}))s.set(a,n);return Response.json(u,{headers:s,status:t})},F="lunora-ping",x="lunora-pong",r="id:",f="retry:",g="dead:",y="pool:",m=100,R=5,A=3e4,N=1e3,E=999999999999999,$=15,v=u=>String(u).padStart($,"0"),w=u=>Number.isInteger(u)&&u>0&&u<=E;class i{static indexKey(t,e){return`t:${v(t)}:${e}`}static json(t,e=200){return I(t,e)}static error(t,e,s){return i.json({error:{code:e,message:s}},t)}static resolveRetry(t){const e=t.retry,s=typeof e?.maxAttempts=="number"&&Number.isInteger(e.maxAttempts)&&e.maxAttempts>0?e.maxAttempts:R,a=typeof e?.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0?e.baseMs:A,n=e?.backoff==="linear"?"linear":"exponential",o=typeof e?.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0?e.maxMs:void 0;return{backoff:n,baseMs:a,maxAttempts:s,maxMs:o}}static normalizeConcurrency(t,e){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:e}static normalizeRetry(t){if(typeof t!="object"||t===null)return;const e=t,s={};return typeof e.maxAttempts=="number"&&Number.isInteger(e.maxAttempts)&&e.maxAttempts>0&&(s.maxAttempts=e.maxAttempts),typeof e.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0&&(s.baseMs=e.baseMs),(e.backoff==="exponential"||e.backoff==="linear")&&(s.backoff=e.backoff),typeof e.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0&&(s.maxMs=e.maxMs),Object.keys(s).length===0?void 0:s}static releaseSlot(t,e){if(t.inFlightIds===void 0)return{...t,inFlight:Math.max(0,t.inFlight-1)};const s=t.inFlightIds.filter(a=>a!==e);return{...t,inFlight:s.length,inFlightIds:s}}static releaseFirstSlot(t){if(t.inFlightIds===void 0)return{...t,inFlight:Math.max(0,t.inFlight-1)};const e=t.inFlightIds.slice(0,Math.max(0,t.inFlightIds.length-1));return{...t,inFlight:e.length,inFlightIds:e}}static resolveScheduleTarget(t){const e=typeof t?.functionPath=="string"&&t.functionPath.length>0?t.functionPath:void 0,s=typeof t?.workflow=="string"&&t.workflow.length>0?t.workflow:void 0;if(!(e===void 0&&s===void 0))return{functionPath:e,workflow:s}}state;env;reindexed=!1;constructor(t,e){this.state=t,this.env=e,this.armWebSocketKeepalive()}async fetch(t){await this.reindexOrphanedRecords();const e=new URL(t.url);if(e.pathname==="/ws"&&t.headers.get("Upgrade")==="websocket")return this.handleWebSocketUpgrade();switch(`${t.method} ${e.pathname}`){case"GET /dead":return this.handleDeadList(e);case"GET /get":return this.handleGet(e);case"GET /list":return this.handleList(e);case"GET /pool":return this.handlePoolStatus(e);case"GET /status":return this.handleStatus();case"POST /cancel":return this.handleCancel(t);case"POST /complete":return this.handleComplete(t);case"POST /dead/cancel":return this.handleDeadCancel(t);case"POST /dead/retry":return this.handleDeadRetry(t);case"POST /schedule":return this.handleSchedule(t)}return I({error:{code:"NOT_FOUND"}},404)}async alarm(){await this.reindexOrphanedRecords();const t=Date.now(),e=[],s=await this.state.storage.list({end:`t:${v(t)}:~`,limit:100,prefix:"t:"});for(const[a,n]of s.entries()){const o=Number.parseInt(a.slice(2,a.indexOf(":",2)),10);if(Number.isFinite(o)&&o<=t){const c=await this.state.storage.get(`${r}${n}`);c?e.push(c):await this.state.storage.delete(a)}}try{for(const a of e)await this.drainRecordGuarded(a)}finally{await this.rescheduleAlarm()}e.length>0&&await this.broadcastChange()}async dispatch(t){const e=typeof this.env.LUNORA_ORIGIN_URL=="string"&&this.env.LUNORA_ORIGIN_URL.length>0?this.env.LUNORA_ORIGIN_URL:void 0;if(!e)return!1;const s=JSON.stringify({args:t.args,functionPath:t.functionPath,id:t.id,instanceName:t.instanceName,pool:t.pool,scheduledFor:t.scheduledFor,shardKey:t.shardKey,workflow:t.workflow});try{const a={"content-type":"application/json"},n=await this.signDispatch(s);return n!==void 0?a["x-lunora-scheduler-signature"]=n:typeof this.env.LUNORA_ADMIN_TOKEN=="string"&&this.env.LUNORA_ADMIN_TOKEN.length>0&&(a.authorization=`Bearer ${this.env.LUNORA_ADMIN_TOKEN}`),(await fetch(`${e}/_lunora/scheduler/dispatch`,{body:s,headers:a,method:"POST"})).ok}catch{return!1}}armWebSocketKeepalive(){const t=this.state.setWebSocketAutoResponse;typeof t!="function"||typeof WebSocketRequestResponsePair>"u"||t.call(this.state,new WebSocketRequestResponsePair(F,x))}async drainRecordGuarded(t){try{await this.state.storage.delete(i.indexKey(t.scheduledFor,t.id)),await this.drainRecord(t)}catch{try{if(await this.state.storage.get(`${g}${t.id}`)!==void 0){await this.state.storage.delete([`${f}${t.id}`,`${r}${t.id}`]);return}await this.state.storage.put(i.indexKey(t.scheduledFor,t.id),t.id)}catch{}}}async drainRecord(t){if(!await this.reservePoolSlot(t))return!1;const s=await this.dispatch(t);if(!s&&t.pool!==void 0){const a=await this.loadPool(t.pool),n=i.releaseSlot(a,t.id);await this.savePool(t.pool,n)}if(s){try{await this.state.storage.delete([`${r}${t.id}`,`${f}${t.id}`])}catch{}return!0}return await this.recordRetry(t),!1}async reservePoolSlot(t){if(t.pool===void 0)return!0;const e=await this.loadPool(t.pool);if(e.inFlight>=e.maxConcurrency)return await this.requeuePooled(t),!1;const s=e.inFlightIds??[];return s.includes(t.id)||s.push(t.id),e.inFlightIds=s,e.inFlight=s.length,await this.savePool(t.pool,e),!0}async handleWebSocketUpgrade(){if(this.state.acceptWebSocket===void 0)return i.error(501,"WS_UNSUPPORTED","WebSocket subscriptions are not supported in this runtime");const t=new WebSocketPair,e=t[0],s=t[1];this.state.acceptWebSocket(s);const a=await this.listPage(r,m);return s.send(JSON.stringify({records:a.records,truncated:a.truncated,type:"jobs"})),new Response(null,{status:101,webSocket:e})}async broadcastChange(){const t=this.state.getWebSockets?.();if(t===void 0||t.length===0)return;const{records:e,truncated:s}=await this.listPage(r,m),a=JSON.stringify({records:e,truncated:s,type:"jobs"});for(const n of t)try{n.send(a)}catch{}}async listPage(t,e,s){const a=await this.state.storage.list({limit:e+1,prefix:t,...s===void 0?{}:{startAfter:s}}),n=[...a.keys()],o=[...a.values()],c=o.length>e;return c?{cursor:n[e-1],records:o.slice(0,e),truncated:c}:{records:o,truncated:c}}async forEachPage(t,e,s=m){let a;for(;;){const n=await this.state.storage.list(a===void 0?{limit:s,prefix:t}:{limit:s,prefix:t,startAfter:a});if(n.size===0)break;for(const[c,h]of n.entries())e(h,c);if(a=[...n.keys()].at(-1),n.size<s)break}}async signDispatch(t){const e=typeof this.env.LUNORA_SCHEDULER_SECRET=="string"?this.env.LUNORA_SCHEDULER_SECRET:void 0;if(!e||e.length===0)return;const s=new TextEncoder,a=await crypto.subtle.importKey("raw",s.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",a,s.encode(t));return b(new Uint8Array(n))}async recordRetry(t){const e=(t.attempts??0)+1,{backoff:s,baseMs:a,maxAttempts:n,maxMs:o}=i.resolveRetry(t),c=s==="linear"?a*e:a*2**(e-1),h=o===void 0?c:Math.min(c,o),l=Math.round(Date.now()+h);if(e>n){await this.parkDead(t,e,`after ${String(e)} attempts`);return}if(!w(l)){await this.parkDead(t,e,`at attempt ${String(e)}: the retry backoff exceeded the largest schedulable time`);return}const d={...t,attempts:e,scheduledFor:l};await this.state.storage.put(`${f}${t.id}`,d),await this.state.storage.put(`${r}${t.id}`,d),await this.state.storage.put(i.indexKey(l,t.id),t.id)}async parkDead(t,e,s){await this.state.storage.put(`${g}${t.id}`,{...t,attempts:e}),await this.state.storage.delete([`${f}${t.id}`,`${r}${t.id}`]),console.warn(`@lunora/scheduler: job "${t.id}" (${t.functionPath??t.workflow??"unknown"}) parked in dead-letter ${s}`)}async loadPool(t,e){const s=await this.state.storage.get(`${y}${t}`);return s!==void 0?Array.isArray(s.inFlightIds)?{inFlight:s.inFlightIds.length,inFlightIds:[...s.inFlightIds],maxConcurrency:s.maxConcurrency}:{inFlight:Math.max(0,s.inFlight),maxConcurrency:s.maxConcurrency}:{inFlight:0,inFlightIds:[],maxConcurrency:i.normalizeConcurrency(e,1)}}async savePool(t,e){await this.state.storage.put(`${y}${t}`,e)}async requeuePooled(t){const e=Date.now()+N,s={...t,scheduledFor:e};await this.state.storage.put(`${r}${t.id}`,s),await this.state.storage.put(i.indexKey(e,t.id),t.id)}async handleComplete(t){const e=await t.json().catch(()=>{}),s=typeof e?.pool=="string"&&e.pool.length>0?e.pool:void 0,a=typeof e?.id=="string"&&e.id.length>0?e.id:void 0;if(s===void 0)return i.error(400,"INVALID_INPUT","pool is required");const n=await this.loadPool(s),o=a===void 0?i.releaseFirstSlot(n):i.releaseSlot(n,a);return await this.savePool(s,o),await this.armAlarmIfEarlier(Date.now()),i.json({inFlight:o.inFlight})}async handlePoolStatus(t){const e=t.searchParams.get("name");if(e===null||e.length===0)return i.error(400,"INVALID_INPUT","name is required");const s=await this.loadPool(e);let a=0;return await this.forEachPage(r,n=>{n.pool===e&&(a+=1)}),i.json({inFlight:s.inFlight,maxConcurrency:s.maxConcurrency,queued:a})}async handleStatus(){const t=new Map;await this.forEachPage(r,o=>{o.pool!==void 0&&t.set(o.pool,(t.get(o.pool)??0)+1)});const e=[];let s=0,a=0;await this.forEachPage(y,(o,c)=>{const h=c.slice(y.length),l=Math.max(0,o.inFlight),d=t.get(h)??0;e.push({inFlight:l,maxConcurrency:o.maxConcurrency,name:h,queued:d}),s+=d,a+=l});const n={backlog:s,inFlight:a,pools:e};return i.json(n)}async persistPoolCap(t,e){const s=await this.loadPool(t,e);await this.savePool(t,{inFlight:s.inFlight,...s.inFlightIds===void 0?{}:{inFlightIds:s.inFlightIds},maxConcurrency:i.normalizeConcurrency(e,s.maxConcurrency)})}async idConflict(t){if(await this.state.storage.get(`${r}${t}`)!==void 0)return i.error(409,"DUPLICATE_SCHEDULE_ID",`a job with id "${t}" is already scheduled — cancel it first, or schedule under a different id`);if(await this.state.storage.get(`${g}${t}`)!==void 0)return i.error(409,"DUPLICATE_SCHEDULE_ID",`id "${t}" is held by a dead-letter record — retry or cancel it (POST /dead/retry, POST /dead/cancel) first, or schedule under a different id`)}async resolveId(t){let e;try{e=P(t)}catch(s){return i.error(400,"INVALID_SCHEDULE_ID",s instanceof Error?s.message:"invalid `id`")}return t===void 0?e:await this.idConflict(e)??e}async handleSchedule(t){const e=await t.json().catch(()=>{}),s=i.resolveScheduleTarget(e);if(!e||s===void 0)return i.error(400,"INVALID_INPUT","functionPath or workflow is required");const{functionPath:a,workflow:n}=s;if(typeof e.scheduledFor!="number"||!w(e.scheduledFor))return i.error(400,"INVALID_INPUT","scheduledFor must be a positive integer epoch-millisecond number no greater than 999999999999999");if(typeof this.env.LUNORA_ORIGIN_URL!="string"||this.env.LUNORA_ORIGIN_URL.length===0)return i.error(500,"ORIGIN_NOT_CONFIGURED","LUNORA_ORIGIN_URL env binding must be set on the SchedulerDO");const o=typeof e.pool=="string"&&e.pool.length>0?e.pool:void 0,c=typeof e.instanceName=="string"&&e.instanceName.length>0?e.instanceName:void 0,h=i.normalizeRetry(e.retry),l=await this.resolveId(e.id);if(l instanceof Response)return l;const d=l,p={args:e.args??{},enqueuedAt:Date.now(),id:d,...a===void 0?{}:{functionPath:a},...c===void 0?{}:{instanceName:c},...o===void 0?{}:{pool:o},...h===void 0?{}:{retry:h},scheduledFor:e.scheduledFor,shardKey:e.shardKey,...n===void 0?{}:{workflow:n}};return o!==void 0&&await this.persistPoolCap(o,e.maxConcurrency),await this.state.storage.put(`${r}${d}`,p),await this.state.storage.put(i.indexKey(p.scheduledFor,d),d),await this.armAlarmIfEarlier(p.scheduledFor),await this.broadcastChange(),i.json({id:d,scheduledFor:p.scheduledFor})}async handleCancel(t){const e=await t.json().catch(()=>{});if(!e?.id)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${r}${e.id}`);return s?(await this.removeRecord(s),await this.rescheduleAlarm(),await this.broadcastChange(),i.json({cancelled:!0})):i.json({cancelled:!1})}async handleList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(r,m,t.searchParams.get("cursor")??void 0);return i.json({cursor:e,records:s,truncated:a})}async handleDeadList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(g,m,t.searchParams.get("cursor")??void 0);return i.json({cursor:e,records:s,truncated:a})}async handleDeadRetry(t){const e=await t.json().catch(()=>{});if(typeof e?.id!="string"||e.id.length===0)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${g}${e.id}`);if(s===void 0)return i.json({retried:!1});const a=Date.now(),n={...s,attempts:0,scheduledFor:a};return await this.state.storage.put(`${r}${s.id}`,n),await this.state.storage.put(i.indexKey(a,s.id),s.id),await this.state.storage.delete(`${g}${s.id}`),await this.armAlarmIfEarlier(a),await this.broadcastChange(),i.json({id:s.id,retried:!0,scheduledFor:a})}async handleDeadCancel(t){const e=await t.json().catch(()=>{});if(typeof e?.id!="string"||e.id.length===0)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.delete(`${g}${e.id}`);return i.json({removed:!!s})}async handleGet(t){const e=t.searchParams.get("id");if(e===null||e.length===0)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${r}${e}`);return i.json(s===void 0?{}:{record:s})}async removeRecord(t){await this.state.storage.delete([`${r}${t.id}`,i.indexKey(t.scheduledFor,t.id),`${f}${t.id}`])}async armAlarmIfEarlier(t){const e=await this.state.storage.getAlarm();(e===null||t<e)&&await this.state.storage.setAlarm(t)}async reindexOrphanedRecords(){if(this.reindexed)return;this.reindexed=!0;const t=new Set;await this.forEachPage("t:",s=>{t.add(s)});const e=[];await this.forEachPage(r,s=>{!t.has(s.id)&&w(s.scheduledFor)&&e.push(s)});for(const s of e)await this.state.storage.put(i.indexKey(s.scheduledFor,s.id),s.id),await this.armAlarmIfEarlier(s.scheduledFor)}async rescheduleAlarm(){const e=(await this.state.storage.list({limit:1,prefix:"t:"})).entries().next();if(e.done){await this.state.storage.deleteAlarm();return}const[s]=e.value,a=Number.parseInt(s.slice(2,s.indexOf(":",2)),10);Number.isFinite(a)&&await this.state.storage.setAlarm(a)}}export{R as MAX_RETRY_ATTEMPTS,A as RETRY_BASE_DELAY_MS,i as SchedulerDO};
@@ -0,0 +1 @@
1
+ import{LunoraError as n}from"@lunora/errors";const o=(e,r,t="delayMs")=>{if(!Number.isFinite(e)||e<0)throw new n("INVALID_INPUT",`${r}: \`${t}\` must be a non-negative finite number`)};export{o as default};
@@ -0,0 +1 @@
1
+ import r from"./assertScheduleDelay-BgA4K1WB.mjs";const l=(t,s,a)=>{const e=t-s;r(Number.isFinite(e)&&e<0?0:e,a,"date")};export{l as default};
@@ -0,0 +1 @@
1
+ import{LunoraError as n}from"@lunora/errors";import{CronExpressionParser as o}from"cron-parser";const s=r=>{if(typeof r!="string"||r.trim()==="")return!1;try{return o.parse(r.trim()),!0}catch{return!1}},t=/\s+/u,i=(r,e)=>{r.trim().split(t).length===6&&console.warn(`@lunora/scheduler: ${e} "${r}" is a 6-field (seconds-leading) cron expression — Cloudflare Cron Triggers only support the standard 5-field form and will reject this at \`wrangler deploy\`. Drop the seconds field, or use ctx.scheduler.runAfter/runAt for sub-minute work.`)},d=(r,e="cron expression")=>{if(!s(r))throw new n("INTERNAL",`@lunora/scheduler: invalid ${e} "${r}" — expected a standard 5- or 6-field cron expression (e.g. "0 * * * *")`);i(r,e)};export{d as assertValidCronExpression,s as isValidCronExpression,i as warnIfSecondsLeading};
@@ -0,0 +1 @@
1
+ const h=t=>{let r="";for(let a=0;a<t.length;a+=32768)r+=String.fromCharCode(...t.subarray(a,a+32768));return btoa(r)},l=t=>{const r=atob(t),n=new Uint8Array(r.length);for(let a=0;a<r.length;a+=1)n[a]=r.codePointAt(a)??0;return n},c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",i=t=>{let r="",n=0;const a=t.length-2;for(;n<a;n+=3){const o=t[n]<<16|t[n+1]<<8|t[n+2];r+=c.charAt(o>>18&63)+c.charAt(o>>12&63)+c.charAt(o>>6&63)+c.charAt(o&63)}const e=t.length-n;if(e===1){const o=t[n]<<16;r+=c.charAt(o>>18&63)+c.charAt(o>>12&63)}else if(e===2){const o=t[n]<<16|t[n+1]<<8;r+=c.charAt(o>>18&63)+c.charAt(o>>12&63)+c.charAt(o>>6&63)}return r};export{h as a,l as f,i as t};
@@ -0,0 +1 @@
1
+ import{LunoraError as n}from"@lunora/errors";import{assertValidCronExpression as s}from"./assertValidCronExpression-DnBtukpq.mjs";const u=r=>{if(!r.schedule||!r.fn)throw new n("INTERNAL","@lunora/scheduler: createCronTrigger() requires `schedule` and `fn`");s(r.schedule);const e=JSON.stringify({triggers:{crons:[r.schedule]}},void 0,2);return{crons:[r.schedule],dispatcher:{args:r.args??{},functionPath:r.fn.__lunoraRef},wranglerJsonc:e}};export{u as createCronTrigger};
@@ -0,0 +1 @@
1
+ import{LunoraError as l}from"@lunora/errors";import{a as x}from"./wire-codec-TIVAE0Ds.mjs";const j=(e,t,o)=>{if(t===void 0)return{dispose:()=>{},signal:e};const a=new AbortController,r=setTimeout(()=>{a.abort(o())},t);return{dispose:()=>{clearTimeout(r)},signal:a.signal}},M=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},B=e=>{const t=atob(e),o=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)o[a]=t.codePointAt(a)??0;return o},y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",$=e=>{let t="",o=0;const a=e.length-2;for(;o<a;o+=3){const n=e[o]<<16|e[o+1]<<8|e[o+2];t+=y.charAt(n>>18&63)+y.charAt(n>>12&63)+y.charAt(n>>6&63)+y.charAt(n&63)}const r=e.length-o;if(r===1){const n=e[o]<<16;t+=y.charAt(n>>18&63)+y.charAt(n>>12&63)}else if(r===2){const n=e[o]<<16|e[o+1]<<8;t+=y.charAt(n>>18&63)+y.charAt(n>>12&63)+y.charAt(n>>6&63)}return t};new TextDecoder;const L=new TextEncoder,E="=",D=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},k=e=>$(L.encode(JSON.stringify(e))),K=e=>!e.startsWith(E)&&D(e)?e:`${E}${$(L.encode(e))}`,J="$lunora.wire$",N=64,I=1024,O="__proto__",T={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},R={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},i=(e,t=0)=>{if(t>N)throw new RangeError(`wire-codec: value nesting exceeds the ${N}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===J)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>i(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>I||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${I} digits)`);return BigInt(r)}case"date":{const r=i(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[i(n[0],t+1),i(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>i(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(R,r)?R[r]:void 0)??Error,c=new s(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const u=i(e[4],t+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(u))d===O?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:u[d],writable:!0}):c[d]=u[d];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:i(e[5],t+1),writable:!0}),c}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=B(r);if(M(n)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const c=Object.hasOwn(T,s)?T[s]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>i(r,t+1))}return e.map(r=>i(r,t+1))}const o=e,a={};for(const r of Object.keys(o)){const n=i(o[r],t+1);r===O?Object.defineProperty(a,r,{configurable:!0,enumerable:!0,value:n,writable:!0}):a[r]=n}return a},q="/_lunora/scheduler/dispatch",C=3e4,Q=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},W=Symbol("lunoraDispatchFailure"),F=Symbol("lunoraDispatchMessageId"),S=(e,t)=>(t!==void 0&&Object.defineProperty(e,F,{value:t}),e),G=(e,t)=>(Object.defineProperty(e,W,{value:!0}),S(e,t)),z=(e,t,o,a)=>{try{const r=JSON.parse(o)?.error;if(typeof r=="object"&&r!==null&&typeof r.code=="string"){const{code:n,data:s,message:c}=r;return G(new l(n,typeof c=="string"?c:void 0,{data:s,status:t}),a)}}catch{}return S(new l("INTERNAL",`${e}: function dispatch failed (${String(t)}): ${o}`,{status:t}),a)},H=(e,t,o)=>new l("INTERNAL",`${e}: function dispatch to "${t}" timed out after ${String(o)}ms`,{status:503}),V=e=>{const{label:t}=e,o=globalThis.fetch,a=e.fetchImpl??(typeof o=="function"?o.bind(globalThis):void 0);return async(r,n,s={})=>{if(typeof a!="function")throw new TypeError(`${t}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const c=()=>n??{},u=e.env.LUNORA_ORIGIN_URL;if(typeof u!="string"||u.length===0)throw new l("INTERNAL",`${t}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const d=e.env.LUNORA_ADMIN_TOKEN;if(typeof d!="string"||d.length===0)throw new l("INTERNAL",`${t}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const U=`${Q(u)}${q}`,m={authorization:`Bearer ${d}`,"content-type":"application/json"};e.traceparent!==void 0&&e.traceparent.length>0&&(m.traceparent=e.traceparent),e.identity?.userId!==void 0&&(m["x-lunora-userid"]=K(e.identity.userId)),e.identity?.claims!==void 0&&(m["x-lunora-identity"]=k(e.identity.claims));const g=s.timeoutMs??C,A=j(void 0,g,()=>new DOMException(`dispatch timed out after ${String(g)}ms`,"TimeoutError")),b=h=>{throw h instanceof Error&&h.name==="TimeoutError"?H(t,r.__lunoraRef,g):h};let f;try{try{f=await a(U,{body:JSON.stringify({args:c(),functionPath:r.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:m,method:"POST",signal:A.signal})}catch(w){return b(w)}if(!f.ok){let w;try{w=await f.text()}catch(P){return b(P)}throw z(t,f.status,w,s.messageId)}let h;try{h=await f.text()}catch(w){return b(w)}if(h.length===0)return;let p;try{p=JSON.parse(h)}catch{throw new l("INTERNAL",`${t}: function dispatch returned a non-JSON body (${String(f.status)}): ${h}`,{status:f.status})}if(p===null||typeof p!="object"||Array.isArray(p)||!("result"in p))throw new l("INTERNAL",`${t}: function dispatch returned a JSON body that is not a { result } envelope (${String(f.status)}): ${h}`,{status:f.status});return i(p.result)}finally{A.dispose()}}},_=100,X=3e5,v=e=>e===void 0?void 0:x(e),te=e=>{if(!e.queue)throw new l("INTERNAL","@lunora/scheduler: `queue` (a Cloudflare Queue binding) is required");return{enqueue:async(a,r,n={})=>{const s={args:v(r),functionPath:a.__lunoraRef,shardKey:n.shardKey},c=n.delaySeconds===void 0?void 0:{delaySeconds:n.delaySeconds};await e.queue.send(s,c)},enqueueBatch:async(a,r)=>{if(a.length>_)throw new l("VALIDATION_ERROR",`@lunora/scheduler: enqueueBatch exceeds ${String(_)} (got ${String(a.length)}) — split across calls`);const n=a.map(s=>({body:{args:v(s.args),functionPath:s.ref.__lunoraRef,shardKey:s.shardKey}}));await e.queue.sendBatch(n,r)}}},Y=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string",re=e=>async t=>{await Promise.all(t.messages.map(async o=>{try{if(!Y(o.body))throw new l("INTERNAL","@lunora/scheduler: queue message body is not a QueueJob (missing functionPath)");await e.dispatch(o.body,o.id),o.ack()}catch{o.retry()}}))},ne=e=>{const t=V({env:{LUNORA_ADMIN_TOKEN:e.adminToken,LUNORA_ORIGIN_URL:e.originUrl},fetchImpl:e.fetchImpl,label:"@lunora/scheduler"}),o=e.timeoutMs??X;return async(a,r)=>{await t({__lunoraRef:a.functionPath},a.args,{dedupId:r,messageId:r,shardKey:a.shardKey,timeoutMs:o})}};export{re as createQueueConsumer,te as createQueueWorkpool,ne as httpDispatcher};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{e as w,d as A}from"./wire-codec-TIVAE0Ds.mjs";import{a as p,c as d,g as f}from"./do-client-XQayNStI.mjs";import{isWorkflowReference as y}from"./isWorkflowReference-CT3tdefh.mjs";import R from"./assertScheduleDelay-BgA4K1WB.mjs";import b from"./assertScheduleInstant-BzESPqyw.mjs";const v=async e=>{const o=[];let a;for(;;){const c=await e(a);if(o.push(...Array.isArray(c.records)?c.records:[]),c.truncated!==!0||typeof c.cursor!="string"||c.cursor.length===0)return o;if(c.cursor===a)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");a=c.cursor}},x=e=>typeof e=="string"?e:(y(e)?e.binding:e.__lunoraRef)??"<unknown>",h=e=>({...e,args:A(e.args)}),K=e=>{p(e);const o=async(n,r,s,t={})=>{const l=n instanceof Date?n.getTime():n;b(l,Date.now(),"ctx.scheduler.runAt");const i={args:w("ctx.scheduler.runAt",x(r),s),id:t.id,instanceName:e.instanceName??"default",maxConcurrency:t.pool===void 0?void 0:t.maxConcurrency,pool:t.pool,retry:t.retry,scheduledFor:l,shardKey:t.shardKey};if(y(r)){if(typeof r.binding!="string"||r.binding.length===0)throw new g("INTERNAL","@lunora/scheduler: workflow/agent schedule target is missing its `binding` — pass the generated `workflows.<name>` / `agents.<name>` reference");return(await d(e,"/schedule",{...i,workflow:r.binding})).id}const m=typeof r=="string"?r:r.__lunoraRef;return(await d(e,"/schedule",{...i,functionPath:m})).id},a=async(n,r,s,t={})=>(R(n,"ctx.scheduler.runAfter"),o(Date.now()+n,r,s,t)),c=async n=>d(e,"/cancel",{id:n}),u=async n=>(await v(async s=>f(e,s===void 0?n:`${n}?cursor=${encodeURIComponent(s)}`))).map(s=>h(s));return{cancel:c,dead:async()=>u("/dead"),deadRetry:async n=>{const{retried:r}=await d(e,"/dead/retry",{id:n});return r===!0},get:async n=>{const r=await f(e,`/get?id=${encodeURIComponent(n)}`);return r.record===void 0?null:h(r.record)},list:async()=>u("/list"),runAfter:a,runAt:o}};export{K as default};
@@ -0,0 +1 @@
1
+ import u from"./createScheduler-BW6wVD57.mjs";const i=t=>t?.at!==void 0?typeof t.at=="number"?t.at:t.at.getTime():Date.now()+(t?.delayMs??0),m=t=>{const r=u({instanceName:t.instanceName,jurisdiction:t.jurisdiction,namespace:t.namespace}),n=e=>({attempts:e.attempts??0,functionPath:e.functionPath??e.workflow??"",id:e.id,scheduledFor:e.scheduledFor});return{cancel:async e=>{const{cancelled:a}=await r.cancel(e);return a},deadLetter:{list:async()=>(await r.dead()).map(a=>n(a)),requeue:async e=>r.deadRetry(e)},list:async()=>(await r.list()).map(a=>n(a)),schedule:async(e,a,c)=>{const d=r.runAt,s=i(c);return{id:await d(s,e,a,{retry:c?.retry,shardKey:c?.shardKey}),scheduledFor:s}}}};export{m as createSchedulerHost};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{e as l}from"./wire-codec-TIVAE0Ds.mjs";import{a as o,g as m,c as u}from"./do-client-XQayNStI.mjs";import y from"./assertScheduleDelay-BgA4K1WB.mjs";const N=e=>{if(o(e),!Number.isInteger(e.maxConcurrency)||e.maxConcurrency<=0)throw new s("INTERNAL","@lunora/scheduler: `maxConcurrency` must be a positive integer");const a=typeof e.name=="string"&&e.name.length>0?e.name:"default";return{cancel:async r=>u(e,"/cancel",{id:r}),enqueue:async(r,t,n={})=>{const c=n.delayMs??0;return y(c,"workpool.enqueue"),u(e,"/schedule",{args:l("workpool.enqueue",r.__lunoraRef,t),functionPath:r.__lunoraRef,instanceName:e.instanceName??"default",maxConcurrency:e.maxConcurrency,pool:a,retry:n.retry,scheduledFor:Date.now()+c,shardKey:n.shardKey})},name:a,status:async()=>m(e,`/pool?name=${encodeURIComponent(a)}`)}};export{N as default};
@@ -0,0 +1 @@
1
+ import{LunoraError as o}from"@lunora/errors";const c=(e,r)=>{if(r===void 0)return e;if(typeof e.jurisdiction!="function")throw new TypeError(`@lunora/scheduler: Durable Object namespace does not support jurisdiction("${r}") — update @cloudflare/workers-types or remove the jurisdiction option`);return e.jurisdiction(r)},d=e=>{if(!e.namespace)throw new o("INTERNAL","@lunora/scheduler: `namespace` (SchedulerDO binding) is required")},i=e=>{const r=c(e.namespace,e.jurisdiction);return r.get(r.idFromName(e.instanceName??"default"))},u=(e,r,n)=>{let s,t;try{({code:s,message:t}=JSON.parse(n).error??{})}catch{}throw typeof s=="string"&&s.length>0?new o(s,typeof t=="string"&&t.length>0?t:`@lunora/scheduler: SchedulerDO ${e} failed`,{status:r}):new o("INTERNAL",`@lunora/scheduler: SchedulerDO ${e} failed (${String(r)}): ${n}`)},a=async(e,r,n)=>{const t=await i(e).fetch(`https://scheduler.internal${r}`,n);return t.ok||u(r,t.status,await t.text()),await t.json()},h=async(e,r,n)=>a(e,r,{body:JSON.stringify(n),headers:{"content-type":"application/json"},method:"POST"}),p=async(e,r)=>a(e,r,{method:"GET"});export{d as a,h as c,p as g};
@@ -0,0 +1 @@
1
+ const e=o=>typeof o=="object"&&o!==null&&o.isLunoraWorkflow===!0;export{e as isWorkflowReference};
@@ -0,0 +1 @@
1
+ import{LunoraError as o}from"@lunora/errors";import{t as r}from"./base64-BFBvYeZM.mjs";const a=/^\w[\w-]{0,63}$/u,n=/^-/u,i=t=>{if(t===void 0)return r(crypto.getRandomValues(new Uint8Array(12))).replace(n,"_");if(typeof t!="string"||!a.test(t))throw new o("INVALID_SCHEDULE_ID","@lunora/scheduler: `id` must be 1-64 characters of [A-Za-z0-9_-] and must not start with `-`; omit it to have one minted",{status:400});return t};export{i as default};
@@ -0,0 +1 @@
1
+ import{a as d,f as E}from"./base64-BFBvYeZM.mjs";const o="$lunora.wire$",w=64,p=1024,g="__proto__",l={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},A={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype},u=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const b=typeof e;if(b==="bigint")return[o,"bigint",e.toString()];if(b==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(b!=="object")return e;if(e instanceof Date)return[o,"date",u(e.getTime(),n+1)];if(e instanceof Error){const r=e,t={};for(const i of Object.keys(r)){if(r[i]===void 0)continue;const y=u(r[i],n+1);i===g?Object.defineProperty(t,i,{configurable:!0,enumerable:!0,value:y,writable:!0}):t[i]=y}const s=[o,"error",String(r.name),String(r.message),t];return r.cause!==void 0&&s.push(u(r.cause,n+1)),s}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,t])=>[u(r,n+1),u(t,n+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>u(r,n+1))];if(e instanceof ArrayBuffer)return[o,"bytes",d(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,t=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return t==="Uint8Array"?[o,"bytes",d(s)]:[o,"bytes",d(s),t]}if(Array.isArray(e)){const r=e.map(t=>u(t,n+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const c=e,a={};for(const r of Object.keys(c)){const t=c[r];if(t===void 0)continue;const s=u(t,n+1);r===g?Object.defineProperty(a,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):a[r]=s}return a},f=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>p||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${p} digits)`);return BigInt(r)}case"date":{const r=f(e[2],n+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(t[0],n+1),f(t[1],n+1)]}))}case"set":return new Set(e[2].map(r=>f(r,n+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],t=e[3];if(typeof r!="string"||typeof t!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(A,r)?A[r]:void 0)??Error,i=new s(t);i.name!==r&&Object.defineProperty(i,"name",{configurable:!0,value:r,writable:!0});const y=f(e[4],n+1);if(y===null||typeof y!="object"||Array.isArray(y))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(y))m===g?Object.defineProperty(i,m,{configurable:!0,enumerable:!0,value:y[m],writable:!0}):i[m]=y[m];return e.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(e[5],n+1),writable:!0}),i}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=E(r);if(d(t)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const i=Object.hasOwn(l,s)?l[s]:void 0;return i?new i(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,n+1))}return e.map(a=>f(a,n+1))}const b=e,c={};for(const a of Object.keys(b)){const r=f(b[a],n+1);a===g?Object.defineProperty(c,a,{configurable:!0,enumerable:!0,value:r,writable:!0}):c[a]=r}return c},T=(e,n,b)=>{try{return u(b)}catch(c){throw new TypeError(`${e}: cannot encode args for '${n}' — ${c instanceof Error?c.message:String(c)}`,c instanceof Error?{cause:c}:void 0)}};export{u as a,f as d,T as e};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/scheduler",
3
- "version": "1.0.0-alpha.7",
3
+ "version": "1.0.0-alpha.71",
4
4
  "description": "Scheduling for Lunora: runAfter / runAt and Cron Triggers via SchedulerDO",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,8 +46,9 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/errors": "1.0.0-alpha.3",
50
- "cron-parser": "5.6.1"
49
+ "@lunora/errors": "1.0.0-alpha.36",
50
+ "@lunora/platform": "1.0.0-alpha.30",
51
+ "cron-parser": "5.10.0"
51
52
  },
52
53
  "engines": {
53
54
  "node": "^22.15.0 || >=24.11.0"
@@ -1,130 +0,0 @@
1
- import { LunoraError } from '@lunora/errors';
2
- import { isWorkflowReference } from './isWorkflowReference-C9mQkMXt.mjs';
3
- import { assertValidCronExpression } from './assertValidCronExpression-B9m75qU0.mjs';
4
-
5
- const WEEKDAY_INDEX = {
6
- friday: 5,
7
- monday: 1,
8
- saturday: 6,
9
- sunday: 0,
10
- thursday: 4,
11
- tuesday: 2,
12
- wednesday: 3
13
- };
14
- const field = (value, label, min, max) => {
15
- if (!Number.isInteger(value) || value < min || value > max) {
16
- throw new LunoraError(
17
- "INTERNAL",
18
- `@lunora/scheduler: cronJobs ${label} must be an integer in [${min.toFixed(0)}, ${max.toFixed(0)}], got ${String(value)}`
19
- );
20
- }
21
- return value.toFixed(0);
22
- };
23
- const compileInterval = (schedule) => {
24
- const units = ["seconds", "minutes", "hours"].filter((unit2) => schedule[unit2] !== void 0);
25
- if (units.length !== 1) {
26
- throw new LunoraError("INTERNAL", `@lunora/scheduler: interval schedule must specify exactly one of { seconds, minutes, hours }`);
27
- }
28
- const unit = units[0];
29
- const value = schedule[unit];
30
- if (unit === "seconds") {
31
- return `*/${field(value, "interval.seconds", 1, 59)} * * * * *`;
32
- }
33
- if (unit === "minutes") {
34
- return `*/${field(value, "interval.minutes", 1, 59)} * * * *`;
35
- }
36
- return `0 */${field(value, "interval.hours", 1, 23)} * * *`;
37
- };
38
- const compileDaily = (schedule) => {
39
- const minute = field(schedule.minuteUTC, "daily.minuteUTC", 0, 59);
40
- const hour = field(schedule.hourUTC, "daily.hourUTC", 0, 23);
41
- return `${minute} ${hour} * * *`;
42
- };
43
- const compileWeekly = (schedule) => {
44
- const index = WEEKDAY_INDEX[schedule.dayOfWeek];
45
- if (index === void 0) {
46
- throw new LunoraError("INTERNAL", `@lunora/scheduler: weekly schedule has invalid dayOfWeek "${schedule.dayOfWeek}"`);
47
- }
48
- const minute = field(schedule.minuteUTC, "weekly.minuteUTC", 0, 59);
49
- const hour = field(schedule.hourUTC, "weekly.hourUTC", 0, 23);
50
- return `${minute} ${hour} * * ${index.toFixed(0)}`;
51
- };
52
- const compileMonthly = (schedule) => {
53
- const day = field(schedule.day, "monthly.day", 1, 31);
54
- const minute = field(schedule.minuteUTC, "monthly.minuteUTC", 0, 59);
55
- const hour = field(schedule.hourUTC, "monthly.hourUTC", 0, 23);
56
- return `${minute} ${hour} ${day} * *`;
57
- };
58
- const CRON_SCHEDULE_KINDS = /* @__PURE__ */ new Set(["daily", "interval", "monthly", "weekly"]);
59
- const compileCronSchedule = (kind, schedule) => {
60
- switch (kind) {
61
- case "daily": {
62
- return compileDaily(schedule);
63
- }
64
- case "interval": {
65
- return compileInterval(schedule);
66
- }
67
- case "monthly": {
68
- return compileMonthly(schedule);
69
- }
70
- case "weekly": {
71
- return compileWeekly(schedule);
72
- }
73
- default: {
74
- throw new LunoraError("INTERNAL", `@lunora/scheduler: unknown cron schedule kind "${String(kind)}"`);
75
- }
76
- }
77
- };
78
- const cronJobs = () => {
79
- const jobs = [];
80
- const seen = /* @__PURE__ */ new Set();
81
- const register = (name, cron, target, args) => {
82
- if (typeof name !== "string" || name.trim() === "") {
83
- throw new LunoraError("INTERNAL", `@lunora/scheduler: cron job name must be a non-empty string`);
84
- }
85
- if (seen.has(name)) {
86
- throw new LunoraError("INTERNAL", `@lunora/scheduler: duplicate cron job name "${name}" — names must be unique within one cronJobs()`);
87
- }
88
- if (isWorkflowReference(target)) {
89
- assertValidCronExpression(cron, `cron expression for job "${name}"`);
90
- seen.add(name);
91
- jobs.push({ args: args ?? {}, cron, name, workflow: typeof target.name === "string" ? target.name : "" });
92
- return;
93
- }
94
- if (!target || typeof target.__lunoraRef !== "string") {
95
- throw new LunoraError(
96
- "INTERNAL",
97
- `@lunora/scheduler: cron job "${name}" requires a function reference (e.g. internal.email.digest) or a workflow reference`
98
- );
99
- }
100
- assertValidCronExpression(cron, `cron expression for job "${name}"`);
101
- seen.add(name);
102
- jobs.push({ args: args ?? {}, cron, functionPath: target.__lunoraRef, name });
103
- };
104
- const builder = {
105
- cron(name, cronExpr, function_, args) {
106
- register(name, cronExpr, function_, args);
107
- return builder;
108
- },
109
- daily(name, schedule, function_, args) {
110
- register(name, compileCronSchedule("daily", schedule), function_, args);
111
- return builder;
112
- },
113
- interval(name, schedule, function_, args) {
114
- register(name, compileCronSchedule("interval", schedule), function_, args);
115
- return builder;
116
- },
117
- jobs: () => [...jobs],
118
- monthly(name, schedule, function_, args) {
119
- register(name, compileCronSchedule("monthly", schedule), function_, args);
120
- return builder;
121
- },
122
- weekly(name, schedule, function_, args) {
123
- register(name, compileCronSchedule("weekly", schedule), function_, args);
124
- return builder;
125
- }
126
- };
127
- return builder;
128
- };
129
-
130
- export { CRON_SCHEDULE_KINDS, compileCronSchedule, cronJobs };